threedog 0.8.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (372) hide show
  1. package/CHANGELOG.md +219 -4
  2. package/README.md +6 -6
  3. package/core/assets/Animator.js +2 -0
  4. package/core/assets/Assets.js +44 -13
  5. package/core/assets/assetEntry.js +87 -22
  6. package/core/assets/assetHot.js +2 -1
  7. package/core/assets/assetReport.js +1 -2
  8. package/core/audio/Audio.js +24 -5
  9. package/core/base/I18n.js +6 -3
  10. package/core/base/Random.js +3 -1
  11. package/core/base/Vars.js +14 -4
  12. package/core/base/errorCodes.js +54 -16
  13. package/core/base/errorHints.js +12 -1
  14. package/core/base/errors.js +6 -4
  15. package/core/base/events.generated.js +10 -0
  16. package/core/base/follows.js +26 -0
  17. package/core/base/math.js +15 -8
  18. package/core/base/params.js +2 -2
  19. package/core/{saves → base}/saveValues.js +24 -6
  20. package/core/base/sections.js +97 -0
  21. package/core/base/spelling.js +32 -0
  22. package/core/base/validate.js +8 -29
  23. package/core/engine/Engine.js +61 -18
  24. package/core/engine/Loading.js +30 -3
  25. package/core/engine/copies.js +1 -1
  26. package/core/engine/headlessLoad.js +30 -13
  27. package/core/engine/lifecycle.js +30 -25
  28. package/core/engine/loop.js +22 -4
  29. package/core/engine/moduleSlots.js +91 -15
  30. package/core/engine/moduleTypes.js +13 -0
  31. package/core/engine/modules.js +248 -62
  32. package/core/engine/page.js +25 -8
  33. package/core/engine/plugins.js +15 -3
  34. package/core/engine/services.js +3 -0
  35. package/core/engine/startup.js +46 -36
  36. package/core/input/Input.js +39 -19
  37. package/core/input/inputKeyboard.js +39 -0
  38. package/core/input/inputPad.js +23 -2
  39. package/core/input/inputPointer.js +3 -1
  40. package/core/input/inputSeat.js +66 -0
  41. package/core/input/inputTouch.js +23 -6
  42. package/core/inspect/DebugOverrides.js +13 -2
  43. package/core/inspect/Describe.js +10 -6
  44. package/core/inspect/Inspect.js +31 -4
  45. package/core/inspect/UrlState.js +14 -10
  46. package/core/inspect/catalog.js +12 -5
  47. package/core/inspect/describeRender.js +3 -2
  48. package/core/inspect/describeText.js +6 -2
  49. package/core/inspect/metadata.generated.js +4140 -0
  50. package/core/inspect/pictureWriters.js +117 -33
  51. package/core/inspect/toolDoor.js +21 -0
  52. package/core/inspect/valueHistory.js +35 -0
  53. package/core/ops/Ops.js +32 -7
  54. package/core/ops/control.js +48 -23
  55. package/core/ops/holds.js +4 -3
  56. package/core/ops/opsAtomic.js +18 -6
  57. package/core/ops/opsCheck.js +7 -5
  58. package/core/ops/opsFail.js +5 -7
  59. package/core/ops/opsRun.js +2 -2
  60. package/core/ops/owned.js +20 -3
  61. package/core/ops/sharedPoint.js +7 -10
  62. package/core/ops/stacks.js +22 -1
  63. package/core/saves/SaveStore.js +52 -26
  64. package/core/saves/Saves.js +122 -27
  65. package/core/saves/saveApply.js +159 -61
  66. package/core/saves/saveFiles.js +30 -25
  67. package/core/saves/saveVersions.js +20 -6
  68. package/core/saves/session.js +76 -33
  69. package/core/saves/stateReplace.js +184 -0
  70. package/core/scene/Rays.js +21 -5
  71. package/core/scene/Views.js +6 -6
  72. package/core/scene/adaptive.js +13 -10
  73. package/core/scene/canvasBox.js +2 -0
  74. package/core/scene/compositeGround.js +72 -0
  75. package/core/scene/floor.js +17 -0
  76. package/core/scene/grid.js +2 -0
  77. package/core/scene/ground.contract.js +14 -0
  78. package/core/scene/ground.js +52 -17
  79. package/core/scene/pixel.js +154 -0
  80. package/core/scene/pixelRatio.js +167 -0
  81. package/core/scene/sceneDelta.js +3 -3
  82. package/core/scene/sceneMethods.js +11 -6
  83. package/core/scene/stepPoses.js +6 -1
  84. package/core/scene/thingExplain.js +1 -1
  85. package/core/scene/thingOps.js +22 -14
  86. package/core/scene/things.js +1 -1
  87. package/core/scene/tier.js +10 -0
  88. package/core/scene/view.js +126 -9
  89. package/core/stream/Batching.js +0 -1
  90. package/core/stream/Stream.js +24 -12
  91. package/core/stream/batchGroups.js +1 -0
  92. package/core/stream/scatter.js +5 -2
  93. package/core/stream/streamSources.js +2 -1
  94. package/core/threads/Commits.js +12 -7
  95. package/core/threads/Jobs.js +15 -5
  96. package/core/threads/Threads.js +5 -2
  97. package/core/time/Clock.js +3 -1
  98. package/core/time/skip.js +10 -4
  99. package/core/time/time.js +16 -10
  100. package/docs/AI.md +89 -72
  101. package/docs/API.md +18 -14
  102. package/docs/CODEMAP.md +68 -40
  103. package/docs/COMMANDS.md +22 -23
  104. package/docs/CONVENTIONS.md +120 -17
  105. package/docs/MIGRATING-0.8.md +2 -0
  106. package/docs/MIGRATING-1.0.md +101 -0
  107. package/docs/THREE.md +65 -12
  108. package/docs/api/cameraRig.md +3 -0
  109. package/docs/api/characters.md +13 -7
  110. package/docs/api/collider3d.md +9 -0
  111. package/docs/api/content.md +16 -15
  112. package/docs/api/dialogue.md +2 -1
  113. package/docs/api/engine.md +18 -16
  114. package/docs/api/events.md +14 -4
  115. package/docs/api/ground.md +2 -2
  116. package/docs/api/i18n.md +1 -1
  117. package/docs/api/input.md +2 -1
  118. package/docs/api/interactions.md +1 -1
  119. package/docs/api/inventory.md +1 -1
  120. package/docs/api/level.md +3 -2
  121. package/docs/api/nav.md +4 -2
  122. package/docs/api/particles.md +8 -5
  123. package/docs/api/pickups.md +1 -1
  124. package/docs/api/post.md +3 -4
  125. package/docs/api/quests.md +4 -2
  126. package/docs/api/rays.md +2 -0
  127. package/docs/api/rigid.md +3 -2
  128. package/docs/api/saves.md +8 -7
  129. package/docs/api/stream.md +4 -5
  130. package/docs/api/terrain.md +3 -4
  131. package/docs/api/terrainDraw.md +1 -1
  132. package/docs/api/timeline.md +2 -2
  133. package/docs/api/tools.md +3 -1
  134. package/docs/api/triggers.md +2 -0
  135. package/docs/api/vegetationDraw.md +1 -1
  136. package/docs/api/water.md +6 -2
  137. package/docs/api/weather.md +19 -4
  138. package/docs/api/weatherDraw.md +1 -1
  139. package/docs/api/world.md +1 -1
  140. package/docs/recipes/01-new-game.md +3 -3
  141. package/docs/recipes/02-npc.md +3 -4
  142. package/docs/recipes/03-items-pickups.md +11 -11
  143. package/docs/recipes/04-quests.md +2 -0
  144. package/docs/recipes/05-props-bake.md +9 -9
  145. package/docs/recipes/06-clock-events.md +6 -6
  146. package/docs/recipes/07-flow-scenes-pause.md +18 -15
  147. package/docs/recipes/08-weather-sky.md +5 -5
  148. package/docs/recipes/09-materials-lights-models.md +3 -3
  149. package/docs/recipes/10-blender-level.md +16 -4
  150. package/docs/recipes/11-vehicles.md +18 -6
  151. package/docs/recipes/12-navmesh.md +52 -8
  152. package/docs/recipes/13-animation.md +34 -8
  153. package/docs/recipes/14-custom-module.md +20 -8
  154. package/docs/recipes/15-perf.md +4 -4
  155. package/docs/recipes/16-dev-bridge.md +9 -8
  156. package/docs/recipes/18-world.md +13 -5
  157. package/docs/recipes/19-shooting-picking.md +3 -2
  158. package/docs/recipes/20-content-actions-save.md +26 -6
  159. package/docs/recipes/21-camera.md +17 -23
  160. package/docs/recipes/22-shop-gold.md +21 -12
  161. package/docs/recipes/23-ops.md +19 -15
  162. package/docs/recipes/26-ui-parts.md +3 -2
  163. package/docs/recipes/27-net.md +3 -3
  164. package/docs/recipes/28-terrain.md +3 -3
  165. package/docs/recipes/29-grid.md +1 -1
  166. package/docs/recipes/30-templates.md +10 -13
  167. package/docs/recipes/31-audio.md +2 -2
  168. package/docs/recipes/32-action-game.md +6 -5
  169. package/docs/recipes/33-stream-sources.md +4 -1
  170. package/docs/recipes/34-environment-lighting.md +7 -8
  171. package/docs/recipes/35-picture-from-reference.md +13 -9
  172. package/docs/recipes/36-ground-plants.md +3 -2
  173. package/docs/recipes/40-scene.md +11 -10
  174. package/docs/recipes/43-shader-patches-surfaces.md +7 -7
  175. package/docs/recipes/44-water-weather-hooks.md +9 -8
  176. package/docs/recipes/45-cascaded-shadows.md +3 -4
  177. package/docs/recipes/46-blender-art-route.md +3 -3
  178. package/docs/recipes/49-game-module-contract.md +2 -1
  179. package/docs/recipes/50-own-renderer.md +1 -0
  180. package/docs/recipes/51-capability-catalog.md +14 -8
  181. package/docs/recipes/52-around-the-picture.md +4 -4
  182. package/docs/recipes/55-mods-time-wrap.md +5 -4
  183. package/docs/recipes/56-webgpu-tsl.md +12 -1
  184. package/docs/recipes/57-control.md +30 -10
  185. package/docs/recipes/58-input.md +13 -0
  186. package/docs/recipes/60-judge-the-picture.md +1 -1
  187. package/docs/recipes/62-picture-code.md +106 -48
  188. package/docs/recipes/63-third-person-start.md +2 -1
  189. package/docs/recipes/64-particles.md +53 -4
  190. package/docs/recipes/65-swarm.md +2 -2
  191. package/docs/recipes/66-common-tasks.md +313 -0
  192. package/examples/action/.threedog/content-index.json +1 -1
  193. package/examples/action/GAMEMAP.md +3 -3
  194. package/examples/perf-island/.threedog/content-index.json +1 -1
  195. package/examples/perf-island/GAMEMAP.md +3 -3
  196. package/examples/perf-island/main.js +2 -2
  197. package/examples/plain-picture/GAMEMAP.md +3 -1
  198. package/examples/rc2d/GAMEMAP.md +1 -1
  199. package/examples/rc2d/rc2d.js +1 -1
  200. package/examples/styletest/.threedog/content-index.json +1 -1
  201. package/examples/styletest/GAMEMAP.md +3 -3
  202. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  203. package/examples/world/.threedog/content-index.json +1 -1
  204. package/examples/world/GAMEMAP.md +5 -4
  205. package/examples/world/main.js +3 -3
  206. package/index.d.ts +8 -5
  207. package/index.js +22 -1
  208. package/llms.txt +2 -1
  209. package/modules/ambience/Ambience.js +5 -3
  210. package/modules/calendar/index.js +7 -5
  211. package/modules/camera/FirstPersonCamera.js +3 -3
  212. package/modules/camera/FixedCamera.js +34 -20
  213. package/modules/camera/FollowCamera.js +20 -11
  214. package/modules/camera/RtsCamera.js +1 -0
  215. package/modules/camera/common.js +33 -22
  216. package/modules/camera/pixelSnap.js +62 -0
  217. package/modules/characters/Character.js +136 -43
  218. package/modules/characters/NPC.js +60 -28
  219. package/modules/characters/assetModel.js +2 -2
  220. package/modules/characters/astar.js +47 -28
  221. package/modules/characters/character.contract.js +21 -0
  222. package/modules/characters/contract.js +17 -3
  223. package/modules/characters/index.js +94 -34
  224. package/modules/characters/moveHelpers.js +80 -15
  225. package/modules/characters/mover.contract.js +14 -0
  226. package/modules/characters/movers/common.js +6 -4
  227. package/modules/characters/movers/rapier.js +12 -5
  228. package/modules/characters/movers/simple.js +25 -12
  229. package/modules/characters/movers/support.js +18 -7
  230. package/modules/characters/npcAvoid.js +15 -12
  231. package/modules/characters/npcSim.js +75 -25
  232. package/modules/characters/npcView.js +13 -6
  233. package/modules/characters/pathAsync.js +74 -24
  234. package/modules/characters/pathJob.js +38 -21
  235. package/modules/characters/player.js +59 -47
  236. package/modules/characters/seat.js +56 -0
  237. package/modules/characters/vehicle.contract.js +8 -5
  238. package/modules/characters/walkTo.js +31 -18
  239. package/modules/collision/Collision.js +44 -26
  240. package/modules/collision/contract.js +2 -2
  241. package/modules/collision/grid.js +6 -1
  242. package/modules/content/explain.js +1 -1
  243. package/modules/content/fields.js +3 -3
  244. package/modules/content/ids.js +3 -1
  245. package/modules/content/index.js +83 -27
  246. package/modules/content/loader.js +110 -130
  247. package/modules/content/markers.js +1 -1
  248. package/modules/content/models.js +48 -14
  249. package/modules/content/packs.js +2 -1
  250. package/modules/content/places.js +5 -4
  251. package/modules/content/props.js +8 -6
  252. package/modules/content/rules.js +29 -47
  253. package/modules/content/templates.js +66 -35
  254. package/modules/content/words.js +19 -6
  255. package/modules/debug/DebugPanel.js +4 -2
  256. package/modules/flow/contract.js +1 -0
  257. package/modules/flow/index.js +24 -14
  258. package/modules/gameplay/Container.js +5 -2
  259. package/modules/gameplay/Containers.js +9 -1
  260. package/modules/gameplay/Dialogue.js +82 -25
  261. package/modules/gameplay/Interactions.js +61 -32
  262. package/modules/gameplay/Inventory.js +56 -13
  263. package/modules/gameplay/Quests.js +133 -24
  264. package/modules/gameplay/boxOps.js +7 -0
  265. package/modules/gameplay/dialogueBubbles.js +14 -9
  266. package/modules/gameplay/inventoryOps.js +11 -7
  267. package/modules/gameplay/pickups.js +43 -16
  268. package/modules/gameplay/questLog.js +4 -2
  269. package/modules/gameplay/questSave.js +6 -1
  270. package/modules/gameplay/quests.contract.js +1 -1
  271. package/modules/grid/Grid.js +1 -1
  272. package/modules/grid/Layer.js +8 -4
  273. package/modules/grid/index.js +21 -15
  274. package/modules/grid/ops.js +43 -46
  275. package/modules/grid/tiles.js +1 -1
  276. package/modules/hlod/index.js +6 -3
  277. package/modules/hud/index.js +6 -4
  278. package/modules/hud/parts.js +4 -4
  279. package/modules/level/contract.js +2 -2
  280. package/modules/level/heightfield.js +17 -21
  281. package/modules/level/index.js +83 -26
  282. package/modules/level/load.js +165 -48
  283. package/modules/level/nodes.js +34 -16
  284. package/modules/lights/index.js +6 -3
  285. package/modules/lights/sources.js +3 -1
  286. package/modules/music/Music.js +4 -2
  287. package/modules/nav/contract.js +7 -5
  288. package/modules/nav/index.js +174 -44
  289. package/modules/nav/navPath.js +45 -10
  290. package/modules/net/index.js +1 -1
  291. package/modules/particles/Particles.js +85 -22
  292. package/modules/particles/effect.js +80 -28
  293. package/modules/particles/shaders.js +17 -0
  294. package/modules/photo/Photo.js +12 -10
  295. package/modules/rigid/RigidBodies.js +200 -57
  296. package/modules/rigid/Vehicles.js +15 -5
  297. package/modules/rigid/collider3d.contract.js +26 -0
  298. package/modules/rigid/ragdoll.js +55 -44
  299. package/modules/rigid/ragdollBones.js +83 -33
  300. package/modules/rigid/refresh.js +10 -0
  301. package/modules/rigid/sync.js +46 -15
  302. package/modules/settings/Settings.js +84 -37
  303. package/modules/settings/apply.js +15 -8
  304. package/modules/settings/sections.js +7 -4
  305. package/modules/settings/strings.js +2 -2
  306. package/modules/sky/skyModule.js +3 -1
  307. package/modules/swarm/Swarm.js +16 -6
  308. package/modules/terrain/ChunkManager.js +10 -16
  309. package/modules/terrain/index.js +17 -11
  310. package/modules/terrain/terrainEdit.js +13 -2
  311. package/modules/terrain/terrainGen.js +5 -3
  312. package/modules/terrain/terrainShape.js +1 -1
  313. package/modules/timeline/Timeline.js +58 -26
  314. package/modules/timeline/Tween.js +19 -13
  315. package/modules/timeline/shots.js +19 -10
  316. package/modules/triggers/index.js +87 -20
  317. package/modules/vegetation/Vegetation.js +4 -3
  318. package/modules/vegetation/draw.js +16 -0
  319. package/modules/vegetation/groundChunks.js +10 -7
  320. package/modules/vegetation/index.js +30 -7
  321. package/modules/water/Water.js +6 -2
  322. package/modules/weather/Weather.js +16 -15
  323. package/modules/weather/weatherDraw.js +7 -6
  324. package/modules/world/World.js +20 -7
  325. package/modules/world/explain.js +1 -1
  326. package/modules/world/index.js +13 -6
  327. package/modules/world/persist.js +23 -8
  328. package/modules/world/pos.js +4 -4
  329. package/modules/world/records.js +13 -7
  330. package/modules/world/sim.js +74 -23
  331. package/modules/world/simFar.js +2 -2
  332. package/modules/world/state.js +31 -6
  333. package/modules/world/thingSource.js +16 -3
  334. package/modules/world/views.js +19 -8
  335. package/package.json +7 -1
  336. package/render/PostFX.js +47 -29
  337. package/render/backend.js +5 -1
  338. package/render/fx/particles.tsl.js +8 -6
  339. package/render/fx/postWebGPU.tsl.js +3 -3
  340. package/render/layers.js +1 -1
  341. package/render/lightmap.js +23 -3
  342. package/render/occlusion.js +43 -12
  343. package/render/patches.js +2 -2
  344. package/render/postWebGL.js +4 -3
  345. package/render/probes.js +25 -0
  346. package/render/shadows.js +2 -2
  347. package/types/core.d.ts +142 -55
  348. package/types/gameplay.d.ts +92 -40
  349. package/types/generated/core/base/I18n.d.ts +2 -2
  350. package/types/generated/core/input/Input.d.ts +16 -2
  351. package/types/generated/core/input/inputSeat.d.ts +26 -0
  352. package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
  353. package/types/generated/core/ops/Ops.d.ts +2 -1
  354. package/types/generated/core/ops/control.d.ts +12 -2
  355. package/types/generated/core/saves/Saves.d.ts +26 -6
  356. package/types/generated/core/saves/session.d.ts +1 -1
  357. package/types/generated/core/scene/Views.d.ts +1 -1
  358. package/types/generated/core/stream/Stream.d.ts +6 -4
  359. package/types/generated/modules/grid/Grid.d.ts +1 -0
  360. package/types/generated/modules/particles/Particles.d.ts +4 -3
  361. package/types/generated/modules/timeline/Timeline.d.ts +5 -4
  362. package/types/generated/modules/weather/Weather.d.ts +1 -7
  363. package/types/generated/modules/world/World.d.ts +6 -4
  364. package/types/generated/render/PostFX.d.ts +6 -14
  365. package/types/nav.d.ts +36 -4
  366. package/types/physics.d.ts +55 -7
  367. package/types/pixel.d.ts +75 -0
  368. package/types/world.d.ts +14 -8
  369. package/ui/Parts.js +9 -2
  370. package/ui/theme.js +2 -2
  371. package/core/scene/engineCamera.js +0 -32
  372. package/modules/camera/projection.js +0 -21
@@ -3,6 +3,7 @@
3
3
  export default {
4
4
  name: 'flow',
5
5
  api: ['define', 'go', 'transition'],
6
+ fields: ['state'], // the settings menu reads what to go back to
6
7
  ops: [],
7
8
  events: ['flow:change', 'flow:transition'],
8
9
  saves: {},
@@ -11,7 +11,8 @@
11
11
  import { warnMissing } from '../../core/base/validate.js';
12
12
  import { readParams, keysSchema } from '../../core/base/params.js';
13
13
  import { fadeScreen } from '../../ui/UI.js';
14
- import { unsettled } from '../../core/engine/headlessLoad.js';
14
+ import { whenSettled } from '../../core/engine/headlessLoad.js';
15
+ import { stateTurn } from '../../core/saves/stateReplace.js';
15
16
  /** @import { ModuleDef } from '../../types/core' */
16
17
  /** @import { Flow, FlowOptions } from '../../types/gameplay' */
17
18
 
@@ -26,16 +27,13 @@ const FLOW_PARAMS = keysSchema(['start']);
26
27
  */
27
28
  export function flow(opts = {}) {
28
29
  readParams('flow', FLOW_PARAMS, opts);
29
- let e = null, chain = Promise.resolve(), held = null, frozen = null;
30
+ let e = null, sig = null, chain = Promise.resolve(), held = null, frozen = null;
30
31
  const states = new Map([['playing', {}], ['paused', { freeze: true, lockInput: true }]]);
31
32
  // turn freeze / input lock on or off for one state
32
33
  const hold = (def, on) => {
33
34
  if (def.freeze) { if (on) frozen ??= e.freeze('flow'); else { frozen?.remove(); frozen = null; } }
34
35
  if (def.lockInput) { if (on) held ??= e.input.push('flow'); else { held?.remove(); held = null; } }
35
36
  };
36
- // wait until the modules and the required nearby builds are ready (checked per engine frame, so step() advances it too)
37
- const settled = () => !unsettled(e).length;
38
- const waitReady = () => settled() ? Promise.resolve() : new Promise(res => { const h = e.onFrame(() => { if (settled()) { h.remove(); res(); } }); });
39
37
 
40
38
  const api = {
41
39
  /** Current state name */
@@ -58,27 +56,36 @@ export function flow(opts = {}) {
58
56
  to.enter?.(e, from);
59
57
  e.events.emit('flow:change', { from, to: name });
60
58
  },
61
- /** Scene transition: lock input → fade out → fade music → (autosave: 'auto' saves slot 'auto') → fn() → wait for modules ready → fade in → unlock. Repeated calls are queued */
59
+ /** Scene transition: lock input → fade out → fade music → (autosave: 'auto' saves slot 'auto') → fn() → wait for modules ready → fade in → unlock. Repeated calls are queued.
60
+ * A new game or load that goes through before the fade out ends drops the transition, one still in line included, as if it was never asked: fn was written for the state that is gone.
61
+ * One that fails gives the state back, so the transition goes on, like stream.teleport: it waits for the end of a load under way, unless it was asked inside that load, which cannot wait for itself */
62
62
  transition(fn, o = {}) {
63
63
  readParams('flow.transition()', keysSchema(['fade', 'lockInput', 'music', 'autosave']), o);
64
- const { fade = 0.5, lockInput = true, music = 'fade', autosave = false } = o;
64
+ const { fade = 0.5, lockInput = true, music = 'fade', autosave = false } = o, generation = e.saves.generation;
65
+ const replaced = () => e.saves.generation !== generation, waits = !e.saves.replacing;
66
+ const gone = async () => { if (!replaced()) return false; if (waits) await e.saves.settled(); return replaced(); };
65
67
  const run = async () => {
68
+ if (await gone()) return;
66
69
  api.transitioning = true;
67
70
  e.events.emit('flow:transition', { phase: 'start' });
68
71
  const lock = lockInput ? e.input.push('transition') : null;
69
- let shown = false;
72
+ let shown = false, turn = null;
70
73
  try {
71
74
  await fadeScreen(e, 1, { seconds: fade });
75
+ if (sig?.aborted || await gone()) return; // unloaded, or the state replaced, during the fade: no scene swap for what is gone (the finally gives the screen and input back)
72
76
  const m = music === 'fade' ? e.music : null, prev = m?.current;
73
77
  m?.stop({ fade });
74
78
  if (autosave === 'auto') e.saves.save('auto');
79
+ turn = stateTurn(e); // from here until the far door stands, the world is between two states
75
80
  await e.ops.allow(async () => { await fn?.(); }); // the scene swap is loading: the ops guard lets its writes through
76
- await waitReady();
77
- if (m && prev && !m.current && !m.ruled) m.play(prev); // no track rule: resume the previous track after the switch
81
+ await whenSettled(e);
82
+ if (sig?.aborted) return;
83
+ if (m && prev && !m.current && !m.ruled && !replaced()) m.play(prev); // no track rule: resume the previous track after the switch. A new game or load has its own music, however fn started it; a level load nobody awaited is still this playthrough
78
84
  await fadeScreen(e, 0, { seconds: fade });
79
85
  shown = true;
80
86
  } finally {
81
87
  if (!shown) fadeScreen(e, 0, { seconds: 0 }); // fn threw: don't leave the screen black, fade back in at once (the error still propagates to the caller)
88
+ turn?.remove();
82
89
  lock?.remove();
83
90
  api.transitioning = false;
84
91
  e.events.emit('flow:transition', { phase: 'end' });
@@ -88,17 +95,18 @@ export function flow(opts = {}) {
88
95
  },
89
96
  };
90
97
  return {
91
- name: 'flow', type: 'rules', provides: ['flow'], params: FLOW_PARAMS, options: opts, label: 'Game flow', optional: ['music'],
98
+ name: 'flow', skipKind: 'none', type: 'rules', provides: ['flow'], params: FLOW_PARAMS, options: opts, label: 'Game flow', optional: ['music'],
92
99
  install(engine, ctx) { engine.i18n.add({ 'zh-CN': { 'module.flow': '游戏流程' }, en: { 'module.flow': 'game flow' } });
93
- e = engine;
100
+ e = engine; sig = ctx.signal;
94
101
  // initial state (title screen etc.): entered once the world is ready, so the game can define it after use()
95
102
  if (opts.start && opts.start !== 'playing') ctx.track(e.events.once('engine:ready', () => api.go(opts.start)));
96
103
  // a playthrough ends (engine.session): back to the start state, so its enter() runs again; a new one starts in 'playing'
97
104
  // a failed replacement keeps the old playthrough: back to the state it was in
98
105
  let before = null;
99
- ctx.track(e.events.on('session:end', () => { before = api.state; api.go(opts.start ?? 'playing'); }));
106
+ // the state goes after every session:end listener: the start state may start things (a title track) that another listener of the same event ends (music stops there), and install order must not decide which won
107
+ ctx.track(e.events.on('session:end', () => { before = api.state; queueMicrotask(() => { if (!sig.aborted) api.go(opts.start ?? 'playing'); }); }));
100
108
  ctx.track(e.events.on('session:start', () => api.go('playing')));
101
- ctx.track(e.events.on('session:failed', () => { if (before) api.go(before); }));
109
+ ctx.track(e.events.on('session:failed', ({ kind }) => { if (before && kind !== 'quick') api.go(before); })); // a quick load ended nothing here
102
110
  return api;
103
111
  },
104
112
  // unloaded (unuse, replaces) in a state that stops the game: nothing else would ever end its freeze or input lock
@@ -109,3 +117,5 @@ export function flow(opts = {}) {
109
117
  describe() { return { state: api.state, transitioning: api.transitioning }; },
110
118
  };
111
119
  }
120
+
121
+ export const handRolled = 'none: a scene change is a few ordinary calls in any order';
@@ -9,7 +9,7 @@
9
9
  import { fmt, DEV } from '../../core/base/validate.js';
10
10
  import { readParams, keysSchema } from '../../core/base/params.js';
11
11
  import { failure } from '../../core/ops/opsFail.js';
12
- import { sig, freeze, canTrade, acceptsFrom, putIn, loadEntries } from './boxOps.js';
12
+ import { sig, freeze, checkCount, canTrade, acceptsFrom, putIn, loadEntries } from './boxOps.js';
13
13
  import { codedError } from '../../core/base/errorHints.js';
14
14
 
15
15
  // Developer messages (warned once in DEV): add doesn't throw when full, which an AI would hardly notice
@@ -79,6 +79,7 @@ export class Container {
79
79
  DEV && this.inv.engine.ops.guard(this._local ? 'inventory.add' : 'container.add');
80
80
  readParams(`add('${id}')`, keysSchema(['data', 'silent']), opts);
81
81
  if (isKey(id)) throw codedError('container', fmt(STRINGS.keyToAdd, { key: id }));
82
+ checkCount(`add('${id}')`, 'n', n);
82
83
  this.inv._known(id);
83
84
  const before = this.count(id), key = this._put(id, n, copyData('add', id, opts?.data), null, !!opts?.silent);
84
85
  return key === false ? failure({ code: 'full', facts: { id, n } }) : { ok: true, key, added: this.count(id) - before };
@@ -94,6 +95,7 @@ export class Container {
94
95
  */
95
96
  remove(x, n = 1) {
96
97
  DEV && this.inv.engine.ops.guard(this._local ? 'inventory.remove' : 'container.remove');
98
+ checkCount(`remove('${x}')`, 'n', n);
97
99
  if (!this.has(x, n)) return false;
98
100
  let rest = n;
99
101
  for (const e of this._of(x)) { const k = Math.min(rest, e.count); this._take(e, k); if (!(rest -= k)) break; }
@@ -117,7 +119,7 @@ export class Container {
117
119
  DEV && this.inv.engine.ops.guard(this._local ? 'inventory.trade' : 'container.trade');
118
120
  readParams(`trade('${take}', '${give}')`, keysSchema(['takeN', 'giveN', 'data', 'silent']), opts);
119
121
  const { takeN = 1, giveN = 1 } = opts;
120
- if (!(takeN > 0) || !(giveN > 0)) throw codedError('container', `trade('${take}', '${give}'): takeN and giveN must be positive numbers, got takeN ${takeN}, giveN ${giveN}. Example: bag.trade('rusty_key', 'gold_key', { takeN: 1, giveN: 1 })`);
122
+ checkCount(`trade('${take}', '${give}')`, 'takeN', takeN); checkCount(`trade('${take}', '${give}')`, 'giveN', giveN);
121
123
  if (isKey(give)) throw codedError('container', fmt(STRINGS.keyToAdd, { key: give }));
122
124
  this.inv._known(give);
123
125
  const data = copyData('trade', give, opts.data), why = this._canTrade(take, give, takeN, giveN, data);
@@ -150,6 +152,7 @@ export class Container {
150
152
  DEV && this.inv.engine.ops.guard(this._local ? 'inventory.setData' : 'container.setData');
151
153
  const e = this._find(key);
152
154
  if (!e) throw codedError('container', fmt(STRINGS.noKey, { fn: 'setData', key, box: this.id, keys: this._keys() }));
155
+ if (n !== undefined) checkCount(`setData('${key}')`, 'n', n);
153
156
  const d = copyData('setData', e.id, data), k = Math.min(n ?? e.count, e.count), at = this._entries.indexOf(e);
154
157
  const keep = k === e.count && e.data !== undefined ? e.key : null; // a whole entry keeps its key, so references held by the game stay valid
155
158
  e.count -= k;
@@ -1,8 +1,12 @@
1
1
  // Container table: implementation of inventory.container() / transfer() and the containers save part.
2
+ import { keepTable } from '../../core/base/sections.js';
2
3
  import { DEV, warnOnce } from '../../core/base/validate.js';
3
4
  import { readParams, keysSchema } from '../../core/base/params.js';
4
5
  import { Container } from './Container.js';
6
+ import { checkCount } from './boxOps.js';
5
7
  import { codedError } from '../../core/base/errorHints.js';
8
+ import { isPlainObject } from '../../core/base/util.js';
9
+ import { refuseSave } from '../../core/base/saveValues.js';
6
10
 
7
11
  /** Container table: implementation of inventory.container() / transfer(); bag is the home bag 'player' (saved as its own part, never removed). @internal */
8
12
  export class Containers {
@@ -12,8 +16,10 @@ export class Containers {
12
16
  * content/renames.js: a container saved under an old authored id moves to the new id (null = drop it). Remembered, so a save loaded later
13
17
  * is renamed the same way. Skipped when the new id already holds goods of its own (they cannot merge; the old one stays an orphan).
14
18
  * @param {Record<string, string | null>} [map] new entries; without it, applies the remembered ones
19
+ * @returns {() => void} what puts the containers and the remembered names back
15
20
  */
16
21
  rename(map) {
22
+ const back = [this.map, this.renames].map(keepTable), ids = [...this.map.values()].map(c => [c, c.id]);
17
23
  for (const [a, b] of Object.entries(map || {})) this.renames.set(a, b);
18
24
  for (const [a, b] of this.renames) {
19
25
  const c = this.map.get(a);
@@ -21,6 +27,7 @@ export class Containers {
21
27
  this.map.delete(a);
22
28
  if (b != null) { c.id = b; this.map.set(b, c); }
23
29
  }
30
+ return () => { for (const fn of back) fn(); for (const [c, id] of ids) c.id = id; };
24
31
  }
25
32
 
26
33
  get(id, opts) {
@@ -54,7 +61,7 @@ export class Containers {
54
61
  transfer(from, to, x, n = 1) {
55
62
  DEV && this.inv.engine.ops.guard('inventory.transfer');
56
63
  const a = this.find(from, 'from'), b = this.find(to, 'to');
57
- if (!(n > 0)) throw codedError('container', `inventory.transfer: count must be a positive number, got ${n}`);
64
+ checkCount('inventory.transfer', 'count', n);
58
65
  if (a === b) return 0;
59
66
  let moved = 0;
60
67
  for (const e of a._of(x)) { // each entry keeps its data; its key only when the whole entry moves (as setData does)
@@ -101,6 +108,7 @@ export class Containers {
101
108
  * save loads the same on a fresh page and after an hour of play (review 0.4 modules-a B6)
102
109
  */
103
110
  load(d) {
111
+ if (d != null && !(isPlainObject(d) && Object.entries(d).every(([id, list]) => id && Array.isArray(list)))) refuseSave('containers', 'the part', 'must be { container id: [{ id, count }] }', d);
104
112
  if (d && this.renames.size) d = Object.fromEntries(Object.entries(d).flatMap(([id, v]) => { // content/renames.js first (null = dropped)
105
113
  const b = this.renames.has(id) ? this.renames.get(id) : id;
106
114
  return b == null || (b !== id && b in d) ? (b == null ? [] : [[id, v]]) : [[b, v]];
@@ -19,11 +19,13 @@
19
19
  // The speaker defaults to the script name; set speaker: '另一个人' on a node to switch speakers.
20
20
  // Advancing and picking a choice are the ops dialogue.advance and dialogue.choose { index } (recipes/23-ops.md): keys, the cursor, clicks, the dev bridge and
21
21
  // tests all run them, so a choice's do (which may change gameplay state) always runs inside a logged op.
22
+ import { keepTable } from '../../core/base/sections.js';
22
23
  import { uiFocus } from '../../ui/UI.js';
23
24
  import { warnMissing, warnOnce, fmt } from '../../core/base/validate.js';
25
+ import { reportError } from '../../core/base/errors.js';
24
26
  import { readParams, keysSchema } from '../../core/base/params.js';
25
27
  import { dialogueBox } from './dialogueBox.js';
26
- import { codedError } from '../../core/base/errorHints.js';
28
+ import { codedError, coded } from '../../core/base/errorHints.js';
27
29
  import { Bubbles, bubblePart } from './dialogueBubbles.js';
28
30
  // 'data' is the one slot for game-specific fields: other unknown keys stay typos (a misspelled next would silently end the dialogue)
29
31
  const NODE_KEYS = ['text', 'next', 'choices', 'do', 'speaker', 'data'], CHOICE_KEYS = ['text', 'next', 'if', 'do', 'data'];
@@ -39,8 +41,11 @@ const SAY_KEYS = ['speaker', 'node', 'channel', 'at', 'seconds', 'queue', 'onCan
39
41
  const readLine = (fn, keys, o) => readParams(`dialogue.${fn}`, keysSchema(keys), o ?? {});
40
42
 
41
43
  export class Dialogue {
42
- constructor(engine, { charsPerSecond = 40, advanceActions = ['confirm'], holdSeconds = 2 } = {}) {
44
+ constructor(engine, { charsPerSecond = 40, advanceActions = ['confirm'], holdSeconds = 2, bubbleChoice = 'end' } = {}) {
43
45
  this.engine = engine;
46
+ // a bubble script reaching a node with choices: 'end' (warn, the script ends there) or 'ask' (the line stays with its choices until dialogue.choose { index, run })
47
+ if (bubbleChoice !== 'end' && bubbleChoice !== 'ask') throw codedError('module-params', `dialogue({ bubbleChoice }): 'end' (default) or 'ask'; got ${JSON.stringify(bubbleChoice)}`);
48
+ this.bubbleChoice = bubbleChoice; /** @internal run id -> { opts, pick(i) } for bubble lines waiting for a choice */ this._asks = new Map(); this._askSeq = 0;
44
49
  this.scripts = new Map();
45
50
  this.state = { get flags() { return engine.vars.flags; } }; // story flags = engine.vars.flags (autosaved)
46
51
  this.charsPerSecond = charsPerSecond;
@@ -90,18 +95,28 @@ export class Dialogue {
90
95
  _playBubbles(name, nodeId, onEnd, { at = null, seconds, queue } = {}) {
91
96
  const nodes = this.scripts.get(name);
92
97
  let stopped = false, cur = null;
98
+ let asking = 0;
99
+ const actor = this.engine.ops.actor; // who it opened for, as on the main channel (_by)
93
100
  const finish = () => { if (!stopped) { stopped = true; onEnd?.(); } };
94
101
  const step = id => {
95
102
  const node = id && id !== 'end' && nodes[id];
96
103
  if (!node || stopped) { finish(); return; }
97
- if (node.choices?.length) { warnOnce(fmt(STR.bubbleChoices, { name, id })); finish(); return; }
104
+ const opts = node.choices?.length && this.bubbleChoice === 'ask' ? node.choices.filter(c => !c.if || c.if(this.state, this.engine)) : null;
105
+ if (node.choices?.length && !opts) { warnOnce(fmt(STR.bubbleChoices, { name, id })); finish(); return; }
98
106
  const text = typeof node.text === 'function' ? node.text(this.state, this.engine) : node.text;
99
- node.do?.(this.state, this.engine);
100
- cur = this._bubbles.say(at, text, { speaker: node.speaker || (name.startsWith('__say_') ? '' : name), seconds, queue });
107
+ if (!this._do(node)) { finish(); return; }
108
+ const speaker = node.speaker || (name.startsWith('__say_') ? '' : name);
109
+ if (opts?.length) { // 'ask': the line stays up with its choices until one is picked (dialogue.choose { index, run })
110
+ const run = asking = ++this._askSeq, label = c => typeof c.text === 'function' ? c.text(this.state, this.engine) : c.text;
111
+ cur = this._bubbles.say(at, text, { speaker, seconds: Infinity, queue, run, choices: opts.map(label) });
112
+ this._asks.set(run, { opts, actor, pick: i => { const c = opts[i]; this._asks.delete(run); asking = 0; cur.remove(); step(this._do(c) ? c.next || 'end' : 'end'); } });
113
+ return;
114
+ }
115
+ cur = this._bubbles.say(at, text, { speaker, seconds, queue });
101
116
  cur.then(() => step(node.next || 'end'));
102
117
  };
103
118
  step(nodeId);
104
- return { remove: () => { stopped || cur?.remove(); finish(); } };
119
+ return { remove: () => { this._asks.delete(asking); stopped || cur?.remove(); finish(); } };
105
120
  }
106
121
 
107
122
  /**
@@ -115,9 +130,9 @@ export class Dialogue {
115
130
  // wrong name: warn with the fix and still call onEnd (so an NPC waiting on it and the say() Promise don't hang)
116
131
  if (!nodes) { warnMissing('dialogue', speaker, [...this.scripts.keys()].filter(k => !k.startsWith('__say_'))); onEnd?.(); return; }
117
132
  if (channel === 'bubble') { this._playBubbles(speaker, nodeId, onEnd, { at }); return; }
118
- if (this.active) this.end(); // end a running dialogue normally first (runs its onEnd so NPCs don't hang)
133
+ while (this.active) this.end(); // end a running dialogue normally first (runs its onEnd so NPCs don't hang); an onEnd may open the next one, which ends too
119
134
  // join the UI focus stack (Esc swallowed unless onCancel; the choice cursor lives on this entry) and lock game input with an opaque context
120
- this.active = { speaker, nodes, onEnd, focus: uiFocus(this.engine).push('dialogue', { cancel: onCancel }), ctx: this.engine.input.push('dialog', { owner: 'dialogue' }) };
135
+ this.active = { speaker, nodes, onEnd, actor: this.engine.ops.actor, focus: uiFocus(this.engine).push('dialogue', { cancel: onCancel }), ctx: this.engine.input.push('dialog', { owner: 'dialogue' }), duringLoad: this.engine.saves.replacing };
121
136
  this.part = this.engine.ui.get('dialogue');
122
137
  this.part?.show();
123
138
  this.engine.events.emit('dialogue:start', speaker);
@@ -133,9 +148,9 @@ export class Dialogue {
133
148
  a?.onEnd?.();
134
149
  if (a) this.engine.events.emit('dialogue:end', a.speaker);
135
150
  }
136
- /** @internal session:end: close the dialogue without its onEnd (that callback belongs to the old playthrough: an NPC's busy flag, a say() Promise); drop bubbles */
151
+ /** @internal session:end or a load: close the dialogue without its onEnd (that callback belongs to the old playthrough: an NPC's busy flag, a say() Promise); drop bubbles */
137
152
  _cancel() {
138
- this._bubbles.clear();
153
+ this._bubbles.clear(); this._asks.clear();
139
154
  const a = this.active;
140
155
  if (!a) return;
141
156
  a.onEnd = null;
@@ -143,6 +158,11 @@ export class Dialogue {
143
158
  this.end();
144
159
  }
145
160
 
161
+ /** @internal A node's or choice's do. One that throws ends the conversation, as a throwing step ends a cutscene: a line nobody can finish would keep the keys and a say() waiting */
162
+ _do(x) {
163
+ try { x.do?.(this.state, this.engine); return true; } catch (err) { reportError(this.engine, err, 'dialogue do', { soft: true }); return false; }
164
+ }
165
+
146
166
  _show(id) {
147
167
  const a = this.active;
148
168
  if (!a) return; // a dialogue:start listener ended it
@@ -152,7 +172,7 @@ export class Dialogue {
152
172
  a.node = node; a.id = id;
153
173
  a.focus.setNav(null); // no choices while the new line types
154
174
  const text = typeof node.text === 'function' ? node.text(this.state, this.engine) : node.text;
155
- node.do?.(this.state, this.engine); // read the line before running effects, so it doesn't see flags just changed
175
+ if (!this._do(node)) { this.end(); return; } // read the line before running effects, so it doesn't see flags just changed
156
176
  if (this.active !== a) return; // do ended the dialogue or started another
157
177
  a.who = node.speaker || a.speaker;
158
178
  this.full = String(text ?? ''); this.shown = 0; this.typing = true; this._opts = null;
@@ -172,13 +192,15 @@ export class Dialogue {
172
192
  // key: the first bound key only ('1', not '1/Numpad1'), so a rebound choice key shows its new name
173
193
  this._choices = opts.map((c, i) => ({ text: label(c), key: i < 9 ? e.input.label('choice' + (i + 1)).split('/')[0] || null : null, data: c.data ?? {} }));
174
194
  // the choice cursor: the menu keys / d-pad / stick move it, confirm picks (the same op as a click or a number key); the part draws view.selected
175
- if (this._opts) a.focus.setNav({ count: () => this._choices.length, moved: () => this._draw(), confirm: i => e.ops.run('dialogue.choose', { index: i }, { source: 'player' }) });
195
+ if (this._opts) a.focus.setNav({ count: () => this._choices.length, moved: () => this._draw(), confirm: i => e.ops.run('dialogue.choose', { index: i }, this._by) });
176
196
  this._draw();
177
197
  }
178
198
 
199
+ /** @internal who presses on in this conversation: the actor it was opened for (a seat, an NPC's op), so what its choices give does not land on the local player */
200
+ get _by() { return { source: 'player', actor: this.active?.actor }; }
179
201
  /** @internal hand the current line to the UI part: plain data plus advance() / choose(i), which run the ops */
180
202
  _draw() {
181
- const a = this.active, e = this.engine, P = { source: 'player' };
203
+ const a = this.active, e = this.engine, P = this._by;
182
204
  const hint = !this.typing && !this._opts ? e.t('dialogue.continue', { key: e.input.label(this.advanceActions[0]) }) : '';
183
205
  this.part?.update({
184
206
  script: a.speaker, node: a.id, speaker: a.who, text: this.full.slice(0, Math.floor(this.shown)), full: this.full, typing: this.typing,
@@ -203,7 +225,7 @@ export class Dialogue {
203
225
  if (this.typing) this._finishTyping(); // mid-typing: finish the sentence (choices appear) before picking
204
226
  if (!this._opts?.[i]) return;
205
227
  const c = this._opts[i], a = this.active;
206
- c.do?.(this.state, this.engine);
228
+ if (!this._do(c)) { this.end(); return; }
207
229
  if (this.active === a) this._show(c.next || 'end'); // do ended the dialogue or started another: its next belongs to the old one
208
230
  }
209
231
 
@@ -221,7 +243,7 @@ export class Dialogue {
221
243
  }
222
244
  // just opened this frame (the press that opened it does not advance), or the choice cursor already used confirm this frame
223
245
  if (a.focus.fresh || a.focus.consumed) return;
224
- const input = this.engine.input, P = { source: 'player' };
246
+ const input = this.engine.input, P = this._by;
225
247
  if (this.advanceActions.some(x => input.pressedRaw(x))) ops.run('dialogue.advance', {}, P);
226
248
  for (let i = 1; i <= 9; i++) if (input.pressedRaw('choice' + i) && this.active && this._visible()[i - 1]) ops.run('dialogue.choose', { index: i - 1 }, P);
227
249
  }
@@ -232,14 +254,44 @@ const STRINGS = {
232
254
  en: { 'module.dialogue': 'dialogue', 'dialogue.continue': '{key} to continue ▸', 'dialogue.choice': 'Choose option' },
233
255
  };
234
256
 
235
- const DIALOGUE_PARAMS = keysSchema(['charsPerSecond', 'advanceActions', 'holdSeconds']);
257
+ const DIALOGUE_PARAMS = keysSchema(['charsPerSecond', 'advanceActions', 'holdSeconds', 'bubbleChoice']);
258
+
259
+ /**
260
+ * The dialogues section of content data. A line can be several variants [{ if: condition, text }, ..., { text }]; the first whose condition holds is used.
261
+ * When none holds the line is empty and a warning names it: throwing inside the dialogue's op would leave the conversation stuck on that node.
262
+ */
263
+ const variants = (content, at, list) => () => {
264
+ const hit = list.find(v => content.test(v.if));
265
+ if (!hit) warnOnce(coded('content-misuse', `content ${at}: no variant's "if" holds and there is no variant without "if", so the line is empty. ` +
266
+ 'End the list with a plain { text } as the fallback'), at);
267
+ return hit?.text ?? '';
268
+ };
269
+ const DIALOGUE_CONTENT = {
270
+ desc: 'dialogues (id -> speaker, nodes)',
271
+ undo: (d, { engine: e }) => keepTable(e.dialogue.scripts),
272
+ commit(d, { engine: e, content }) {
273
+ for (const [id, def] of Object.entries(d)) {
274
+ const nodes = {};
275
+ for (const [nid, n] of Object.entries(def.nodes ?? {})) {
276
+ nodes[nid] = {
277
+ ...n, speaker: n.speaker ?? def.speaker,
278
+ text: Array.isArray(n.text) ? variants(content, `dialogues.${id}.nodes.${nid}.text`, n.text) : n.text,
279
+ do: n.do && (() => content.run(n.do)),
280
+ choices: n.choices?.map(ch => ({ ...ch, if: ch.if && (() => content.test(ch.if)), do: ch.do && (() => content.run(ch.do)) })),
281
+ };
282
+ }
283
+ e.dialogue.define(id, nodes);
284
+ }
285
+ },
286
+ };
236
287
 
237
288
  /** Dialogue module. Installs engine.dialogue; story flags engine.dialogue.state.flags are engine.vars.flags. Declares the UI parts 'dialogue' and 'dialogue.bubble'. */
238
289
  export function dialogue(opts = {}) {
239
290
  readParams('dialogue', DIALOGUE_PARAMS, opts);
240
291
  let d = null;
241
292
  return {
242
- name: 'dialogue', type: 'rules', provides: ['dialogue'], params: DIALOGUE_PARAMS, options: opts, label: 'Dialogue', stage: 'gameplay', after: ['interactions'],
293
+ content: { dialogues: DIALOGUE_CONTENT },
294
+ name: 'dialogue', skipKind: 'none', type: 'rules', provides: ['dialogue'], params: DIALOGUE_PARAMS, options: opts, label: 'Dialogue', stage: 'gameplay', after: ['interactions'],
243
295
  install(e, ctx) {
244
296
  e.i18n.add(STRINGS);
245
297
  d = new Dialogue(e, opts);
@@ -247,25 +299,28 @@ export function dialogue(opts = {}) {
247
299
  // (basic menu keys + confirm) and clicks pick choices without them. Context 'dialog', so 1-9 stay free for hotbars outside a conversation
248
300
  for (let i = 1; i <= 9; i++) ctx.input.action('choice' + i, { context: 'dialog', label: 'dialogue.choice', optional: true });
249
301
  ctx.track(e.events.on('session:end', () => d._cancel())); // an open dialogue belongs to the playthrough that opened it
250
- e.ui.define('dialogue', dialogueBox);
251
- e.ui.define('dialogue.bubble', bubblePart, { multi: true });
252
- e.ops.define('dialogue.advance', {
302
+ ctx.ui.define('dialogue', dialogueBox);
303
+ ctx.ui.define('dialogue.bubble', bubblePart, { multi: true });
304
+ ctx.ops.define('dialogue.advance', {
253
305
  desc: 'Finish typing the line, or go on to the next one',
254
306
  net: 'local', // in co-op each player reads their own dialogue box; ops it runs (give, start a quest) still go to the host
255
307
  can: () => d.active ? true : 'noDialogue',
256
308
  run: () => { d._advance(); },
257
309
  offers: () => d.active && !d._opts ? [{}] : [],
258
310
  });
259
- e.ops.define('dialogue.choose', {
260
- desc: 'Pick a visible dialogue choice (0-based)', args: { index: 'int' },
311
+ ctx.ops.define('dialogue.choose', {
312
+ desc: 'Pick a visible dialogue choice (0-based); run: the bubble line asking (dialogue.bubbles() run), none = the main conversation', args: { index: 'int', run: 'int?' },
261
313
  net: 'local',
262
- can: (e, { index }) => !d.active ? 'noDialogue' : d._visible()[index] ? true : 'noChoice',
263
- run: (e, { index }) => { d._choose(index); },
264
- offers: () => d.active ? d._visible().map((c, index) => ({ index })) : [],
314
+ can: (e, { index, run }) => run != null ? (d._asks.get(run)?.opts[index] ? true : 'noChoice') : !d.active ? 'noDialogue' : d._visible()[index] ? true : 'noChoice',
315
+ run: (e, { index, run }) => { if (run != null) d._asks.get(run)?.pick(index); else d._choose(index); },
316
+ offers: () => [...(d.active ? d._visible().map((c, index) => ({ index })) : []), ...[...d._asks].flatMap(([run, a]) => a.opts.map((c, index) => ({ index, run })))],
265
317
  });
266
318
  return d;
267
319
  },
268
320
  frame(dt) { d.frame(dt); },
321
+ // unloaded mid-conversation: the input context and focus entry are the conversation's, not tracked, and a say() Promise gets its end. Not on engine.dispose: waits stay pending there
322
+ dispose(e) { if (!e.disposed) { d._bubbles.clear(); d._asks.clear(); d.end(); } },
323
+ afterLoad() { if (!d.active?.duringLoad) d._cancel(); }, // a line open at a load belongs to the state thrown away; one a load opened stays
269
324
  describe(e, ctx) {
270
325
  const a = d.active, bubbles = d.bubbles();
271
326
  if (!a && !bubbles.length) return;
@@ -277,3 +332,5 @@ export function dialogue(opts = {}) {
277
332
  },
278
333
  };
279
334
  }
335
+
336
+ export const handRolled = [{ kind: 'dialogue', seen: 'a dialogue box of its own', use: 'engine.dialogue.define(speaker, nodes) and the dialogue part: typing on game time, choices, input lock (recipe 02, recipe 26)', quiet: /\b(engine|e|eng|ctx)\.dialogue\b|\bdialogue\(\s*[{)]/, code: /\b(createElement|innerHTML|className|classList|getElementById|querySelector|\.id)\b/, raw: /(?:createElement|innerHTML|className|classList|getElementById|querySelector|\.id\b)[^,;{}]*(?:dialog(?:ue)?|speech|subtitle|textbox|conversation)|(?:dialog(?:ue)?|speech|subtitle|textbox|conversation)[^,;{}]*(?:createElement|innerHTML|className|classList|getElementById|querySelector|\.id\b)/i }];