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
@@ -64,6 +64,7 @@ export class IdCheck {
64
64
  * Why in content and not a save version: renaming is an authoring change; the save format stays the same and an unrenamed save still loads. @internal
65
65
  * @param {any} e
66
66
  * @param {Record<string, string | null>} map
67
+ * @returns {void | (() => void)} what puts the goods back, when the inventory gives it (a failed load; the world has its own undo point)
67
68
  */
68
69
  export function applyRenames(e, map) {
69
70
  for (const [a, b] of Object.entries(map || {})) {
@@ -71,8 +72,9 @@ export function applyRenames(e, map) {
71
72
  if (typeof b === 'string' && b.includes('#')) throw codedError('content-id', fmt(RENAME_STRINGS.badTarget, { a, b }));
72
73
  }
73
74
  const stuck = e.world?.renameIds(map) ?? [];
74
- e.inventory?.renameIds(map);
75
+ const goods = e.inventory?.renameIds(map);
75
76
  if (DEV && stuck.length) warnOnce(fmt(RENAME_STRINGS.stuck, { list: stuck.join(', ') }));
77
+ return goods;
76
78
  }
77
79
 
78
80
  /** Index id of a pickup without a written id (the loader's id, and what `threedog content ids` writes) @param {any} p @param {number} i @internal */
@@ -21,32 +21,42 @@
21
21
  import { contentExplain } from './explain.js';
22
22
  import { reportError } from '../../core/base/errors.js';
23
23
  import { CONDITIONS, EFFECTS } from './rules.js';
24
- import { missingText } from '../../core/base/validate.js';
25
- import { loadContent, BUILTIN_TESTS, BUILTIN_RUNS } from './loader.js';
26
- import { templateOf, spawnTemplate, placeTemplate } from './templates.js';
24
+ import { missingText, warnOnce } from '../../core/base/validate.js';
25
+ import { loadContent, checkRefs, BUILTIN_TESTS, BUILTIN_RUNS } from './loader.js';
26
+ import { sectionsOf } from '../../core/base/sections.js';
27
+ import { addProps, needWorld } from './props.js';
28
+ import { templateOf, spawnTemplate, placeTemplate, defineTemplates } from './templates.js';
29
+ import { refit } from './models.js';
27
30
  import { packsOf } from './packs.js';
28
31
  import { IdCheck } from './ids.js';
29
32
  import { fieldsOf } from './fields.js';
30
- import { addPlaces, placeOf, offsetFrom, whereOf } from './places.js';
33
+ import { placesOf, placeOf, offsetFrom, whereOf } from './places.js';
31
34
  import { testWords, runWords } from './words.js';
32
35
  import { setMark, marksPart } from './markers.js';
33
- import { codedError } from '../../core/base/errorHints.js';
36
+ import { codedError, coded } from '../../core/base/errorHints.js';
34
37
 
35
38
  /** The state the module's files share: loader.js and templates.js fill it on each content.load, st.e is set at install */
36
39
  function contentState() {
40
+ // the words of a section (startQuest) are its owner's: sections.effects, looked up per run because modules come and go
41
+ const own = new Map(Object.entries(EFFECTS).map(([k, d]) => [k, { ...d, run: BUILTIN_RUNS[k] }]));
42
+ const moduleWords = () => new Map([...sectionsOf(st.e).values()].flatMap(s => Object.entries(s.effects ?? {})));
37
43
  const st = {
38
44
  e: null, places: {},
39
45
  pending: new Set(), // model promises the module waits for (ready)
40
- triggers: {}, subs: null, startOn: new Map(), ops: new Set(), kinds: {},
46
+ queue: null, // the last load still waiting to commit: the next one stands on it (loader.js)
47
+ ops: new Set(), kinds: {},
48
+ packs: new Set(), // every pack loaded, latest last: what a module put back after a failed replaces gets again (replay)
49
+ gaveWay: new WeakMap(), // pack -> names of its sections that gave way to a newer load: the replay leaves them out
50
+ sectionIds: {}, refs: [], // ids each loaded section holds; ids sections name elsewhere, not checked yet (checkRefs)
41
51
  marks: new Map(), // marker id -> [position, label]: what the marker effect shows (the content save part)
42
- templates: new Map(), templateViews: new Set(), // template name -> frozen definition; names whose presenter is registered
43
- templateSims: new Set(), // names whose world.simulate (stages / update) is registered
52
+ templates: new Map(), templateViews: new Map(), // template name -> frozen definition; name -> its presenter's handle
53
+ templateSims: new Map(), // name -> the handle of its world.simulate (stages / update)
44
54
  templateSrc: new Map(), // dev: template name -> 'content/templates.js:12'
45
55
  templateFields: new Map(), // template name -> parsed state fields (fields.js), for placement checks and content.fields()
46
56
  levelPlace: name => !!name && !(name in st.places) && !!st.e.level?.marker(name),
47
57
  wait: p => { st.pending.add(p); p.catch(err => reportError(st.e, err, 'content model', { soft: true })).finally(() => st.pending.delete(p)); },
48
58
  conds: new Map(Object.entries(CONDITIONS).map(([k, d]) => [k, { ...d, test: BUILTIN_TESTS[k] }])),
49
- effects: new Map(Object.entries(EFFECTS).map(([k, d]) => [k, { ...d, run: BUILTIN_RUNS[k] }])),
59
+ effects: { get: k => moduleWords().get(k) ?? own.get(k), keys: () => [...own.keys(), ...moduleWords().keys()] },
50
60
  };
51
61
  return st;
52
62
  }
@@ -69,17 +79,39 @@ function contentApi(st) {
69
79
  * Models are asset names (engine.assets.manifest / an asset pack), never paths. Places: a pack's own places file, then the places option on top (a place
70
80
  * computed at startup: { places: { home } }); a place is a position, plus rot (radians about Y), and a place file's text entry waits for the option.
71
81
  * Loading again with a place moved or turned moves what stands there, models and collision too, unless play moved that record (world.add).
72
- * @example engine.content.load([baseContent, forestDlc], { places: { home: { x: 0, z: 0 } } })
82
+ * Answers for this load, once its transaction ended: resolves when it committed, rejects when it failed, after the old level and registrations are back
83
+ * (err.notRestored lists what could not be). A load nobody awaits is reported all the same. Bad data throws on the line, and with nothing to wait for the pack is live on the
84
+ * next line. Models keep arriving after it: engine.content.ready says when they did.
85
+ * Inside a save part's load(data, turn) or a module's afterLoad(engine, turn), pass { turn }: without it the load waits for that replacement to end.
86
+ * @example await engine.content.load([baseContent, forestDlc], { places: { home: { x: 0, z: 0 } } })
73
87
  * @param {any} data
74
- * @param {{ places?: Record<string, any> }} [opts]
88
+ * @param {{ places?: Record<string, any>, turn?: object }} [opts]
89
+ * @returns {Promise<void>}
75
90
  */
76
- load(data, { places: given = {} } = {}) {
91
+ load(data, { places: given = {}, turn } = {}) {
77
92
  const packs = packsOf(data), ids = new IdCheck(); // one IdCheck for the whole call: an id used in two packs' props / pickups is an error too
78
- addPlaces(st.places, packs, given);
79
- st.e.ops.allow(() => { for (const p of packs) loadContent(st.e, api, p, st, ids); }); // loading data is setup, not a gameplay action (ops guard)
80
- ids.done();
81
- st.checkOps?.();
82
- return api;
93
+ const places = placesOf(packs, given);
94
+ const run = st.e.ops.allow(() => loadContent(st.e, api, packs, st, ids, places, turn, st.checkOps)); // loading data is setup, not a gameplay action (ops guard)
95
+ const finish = () => { ids.done(); for (const p of packs) { st.packs.delete(p); st.packs.add(p); } if (st.e.ready) checkRefs(st); };
96
+ if (!run) { finish(); return Promise.resolve(); }
97
+ const done = run.then(finish);
98
+ st.wait(done); // told once, here, whoever listens to done
99
+ return done;
100
+ },
101
+ /**
102
+ * @internal modules a replaces installed fresh, or a failed one put back ('module:restored'): their sections get every pack again, one load each as they came. A fresh install has
103
+ * none of it. A section's format is its holder's, so a newcomer may refuse what was written for the old one: no line of the game asked for this load, so it is told, not thrown
104
+ */
105
+ _replay(mods) {
106
+ const names = new Set(mods.flatMap(m => Object.entries(m.content ?? {}).filter(([, s]) => !s.once).map(([n]) => n)));
107
+ for (const p of st.packs) {
108
+ const part = Object.fromEntries(Object.entries(p).filter(([k]) => names.has(k) && !st.gaveWay.get(p)?.has(k))), ids = new IdCheck(), keys = Object.keys(part);
109
+ try {
110
+ const run = keys.length ? st.e.ops.allow(() => loadContent(st.e, api, [part], st, ids)) : null;
111
+ if (run) st.wait(run);
112
+ ids.done();
113
+ } catch (err) { warnOnce(coded('content-misuse', `content: ${mods.map(m => m.name).join(', ')} refused ${keys.join(', ')} of pack ${p.name ?? '(no name)'}, written for the module it replaced, so that part stays out: ${err.message}`)); }
114
+ }
83
115
  },
84
116
  /** Register a condition word: condition('timeAfter', { ref: 'clock', desc, test: (e, value) => ... }) */
85
117
  condition(name, def) { st.conds.set(name, def); return api; },
@@ -93,7 +125,8 @@ function contentApi(st) {
93
125
  test(c, { actor = st.e.ops.actor } = {}) { return testWords(st.e, api, st.conds, c, actor); },
94
126
  /**
95
127
  * Run an effect (object, array or function fn(e, { actor })). actor: whose bag { give } / { take } change (default: the running op's actor, else
96
- * engine.actor), so a reward lands in the bag of whoever earned it.
128
+ * engine.actor), so a reward lands in the bag of whoever earned it. Every word runs; answers { ok: true }, or a failure with facts.failed [{ word, code, facts }]
129
+ * (content:failed fires too): give in a full bag answers 'full' with facts.left, the items that did not fit. A function's own return value is the answer.
97
130
  * @param {any} a
98
131
  * @param {{ actor?: string }} [opts]
99
132
  */
@@ -120,6 +153,7 @@ function contentApi(st) {
120
153
  /**
121
154
  * @internal A level-model node with the custom property template: an authored instance with id `<level>/<node>` (level module).
122
155
  * entry is a props-style entry ({ template, id, x, z, floor, rot, scale, state fields }); origin = { level, node }
156
+ * @internal
123
157
  */
124
158
  placeNode(entry, zone, origin) { placeTemplate(st.e, api, st, entry, 0, zone, null, origin); },
125
159
  /**
@@ -129,7 +163,7 @@ function contentApi(st) {
129
163
  * ('props', 'props.template', 'props.grid', 'pickups', 'views'), a game kind with fields (content/rules.js kinds), or a world record id
130
164
  * (answers for the shape that record came from).
131
165
  * @example engine.content.fields('crop').stage // { type: 'int', optional: true, default: 0, min: 0, max: 4 }
132
- * @example engine.content.fields('props').rot // { type: 'number', optional: true, desc: 'facing around the vertical axis, radians' }
166
+ * @example engine.content.fields('props').rot // { label: 'Facing', type: 'number|position', optional: true, desc: 'facing around the vertical axis, radians; or [x, y, z] radians to tilt it ...' }
133
167
  * @param {string} name
134
168
  * @returns {Record<string, { type: string, optional?: boolean, default?: any, min?: number, max?: number, values?: any[], desc?: string }>}
135
169
  */
@@ -152,27 +186,47 @@ function contentApi(st) {
152
186
  /** @internal The floor a position notation stands on (its own floor, else its marker's height); undefined = top layer */
153
187
  _floorOf(p) { return p.floor ?? (p.place ? api.place(p.place)?.y : undefined); },
154
188
  /** @internal The facing of an entry: its own rot on top of its place's; undefined = neither is written, so the record stays without rot */
155
- _facingOf(p) { const r = p.place ? api.place(p.place)?.rot : undefined; return r === undefined ? p.rot : r + (p.rot ?? 0); },
189
+ _facingOf(p) {
190
+ const r = p.place ? api.place(p.place)?.rot : undefined;
191
+ if (r === undefined) return p.rot;
192
+ return Array.isArray(p.rot) ? [p.rot[0], p.rot[1] + r, p.rot[2]] : r + (p.rot ?? 0); // a place turns about Y, so it adds to the y part
193
+ },
156
194
  };
157
195
  return api;
158
196
  }
159
197
 
160
- /** content may name ops that main.js defines after load: check once everything is set up, and again for loads after that */
198
+ /** content may name ops that main.js defines after load: check once everything is set up, and inside the transaction of every load after that */
161
199
  function checkOps(e, st) {
162
200
  for (const name of st.ops) if (!e.ops.defs.has(name)) throw codedError('unknown-name', `content: ${missingText('op', name, [...e.ops.defs.keys()])} (used in { op } / { can })`);
163
201
  }
164
202
 
203
+ /** A section the loader itself reads before the others run (rules and renames change how they load). Declared so its name and sentence have one home */
204
+ const readEarly = desc => ({ desc, commit() {} });
205
+
165
206
  export function content() {
166
207
  const st = contentState(), api = contentApi(st);
167
208
  return {
168
- name: 'content', type: 'rules', label: 'Content',
209
+ name: 'content', skipKind: 'none', type: 'rules', label: 'Content',
210
+ content: {
211
+ templates: { desc: 'reusable objects (name -> model, collide, interact, container, sound, animate, state defaults, physics body); shared read-only definitions', commit(d) { needWorld(st.e); defineTemplates(st.e, api, st, d); } },
212
+ props: { desc: 'props (list: model, position, facing, collision; or { template, x, z } = an instance of a template; or { id, grid, item, cell } = a grid item), streamed in on demand', live: true, commit(d, c) { if (d.length) addProps(st.e, api, d, st, c.zone, c.ids); } },
213
+ actions: readEarly('own key actions of the game (action name -> default key, label)'),
214
+ places: readEarly('place names (name -> { x, z, y?, rot? }; rot turns everything placed there about Y; coordinates may be computed at runtime in main.js)'),
215
+ audio: readEarly('sounds by asset name, ambience and music rules as data, footsteps (sounds, ambience, music: { tracks, rules }, footsteps)'),
216
+ views: readEarly('named fixed camera views (name -> { position: [x, y, z], target?: [x, y, z], fov? }); engine.views.show(name), ?view=name, npm run shot -- -w game --view name'),
217
+ renames: readEarly("renamed or deleted authored ids (old id -> new id, or null = deleted on purpose): the player's saved changes follow the new id"),
218
+ rules: readEarly('condition words and data kinds added by the game ({ conditions, kinds }); actions are ops, not effect words'),
219
+ },
169
220
  optional: ['level', 'calendar', 'inventory', 'pickups', 'quests', 'particles', 'hud', 'vegetation', 'dialogue', 'triggers', 'collision', 'world', 'interactions', 'grids', 'rigid'],
170
221
  install(engine, ctx) { engine.i18n.add({ 'zh-CN': { 'module.content': '内容' }, en: { 'module.content': 'content' } });
171
222
  const e = st.e = engine;
172
- st.track = ctx.track; // loader.js subscribes on the first content.load: those listeners belong to the module too
173
- engine.explainWith(contentExplain);
174
- e.saves.register('content', marksPart(api, st));
175
- ctx.track(e.events.on('engine:ready', () => checkOps(e, st)));
223
+ st.track = ctx.track; // templates.js subscribes on content.load: those listeners belong to the module too
224
+ ctx.things.explainWith(contentExplain);
225
+ ctx.saves.register('content', { ...marksPart(api, st), atomic: true });
226
+ for (const holder of ['collision', 'collider3d']) ctx.feeds(holder, () => refit(e));
227
+ ctx.track(e.events.on('engine:ready', () => { checkOps(e, st); checkRefs(st); }));
228
+ ctx.track(e.events.on('module:restored', ({ modules }) => api._replay(modules)));
229
+ ctx.track({ remove: () => { for (const m of api.markers.values()) m.remove(); api.markers.clear(); } }); // the marks stay in st.marks and the save part; only what is on screen goes
176
230
  st.checkOps = () => { if (e.ready) checkOps(e, st); };
177
231
  return api;
178
232
  },
@@ -187,7 +241,9 @@ export function content() {
187
241
  return p;
188
242
  },
189
243
  describe() {
190
- return { props: st.e.world ? st.e.world.query({ kind: 'prop' }).length : 0, templates: [...st.templates.keys()], markers: api.markers.size };
244
+ return { props: st.e.world ? st.e.world.query({ kind: 'prop' }).length : 0, templates: [...st.templates.keys()], markers: api.markers.size, sections: [...sectionsOf(st.e).keys()] };
191
245
  },
192
246
  };
193
247
  }
248
+
249
+ export const handRolled = 'none: game data in plain objects is the normal way to start, not a bypass';
@@ -4,16 +4,18 @@
4
4
  // a world coordinate.
5
5
  // Optional floor (reference height on multi-layer ground) and y (meters above that ground): see content.where.
6
6
  import { toast } from '../../ui/UI.js';
7
- import { vegetationModel } from '../../core/assets/namedModel.js';
8
- import { addProps, needWorld } from './props.js';
9
- import { defineTemplates } from './templates.js';
10
7
  import { srcOf, applyRenames, pickupId } from './ids.js';
11
8
  import { DEV, warnOnce } from '../../core/base/validate.js';
12
- import { readParams, keysSchema } from '../../core/base/params.js';
13
9
  import { NO_GAME_EFFECTS, contentFiles, kindProblems, unknownContent } from './rules.js';
10
+ import { sectionHomes } from '../../core/inspect/metadata.generated.js';
11
+ import { sectionsOf, runSections, keepTable } from '../../core/base/sections.js';
12
+ import { whenTurnFree, whileRestoring, liveTurn } from '../../core/saves/stateReplace.js';
14
13
  import { codedError, coded } from '../../core/base/errorHints.js';
15
- import { reportError } from '../../core/base/errors.js';
14
+ import { failure } from '../../core/ops/opsFail.js';
16
15
 
16
+ // data order, not ownership: a place or template must exist before what stands on it. A section not listed runs after these. Rules, actions, audio, views and renames run before all of them (loadSteps)
17
+ const ORDER = ['level', 'vegetation', 'items', 'startItems', 'containers', 'pickups', 'npcs', 'dialogues', 'quests', 'triggers', 'grids', 'templates', 'props'];
18
+ const isEmpty = d => d == null || (typeof d === 'object' && Object.keys(d).length === 0);
17
19
  const each = (o, fn) => Object.entries(o || {}).forEach(([k, v]) => fn(k, v));
18
20
  const all = (o, fn) => Object.entries(o || {}).every(([k, n]) => fn(k, n));
19
21
 
@@ -24,9 +26,9 @@ const all = (o, fn) => Object.entries(o || {}).every(([k, n]) => fn(k, n));
24
26
  const inv = (e, word, ctx) => e.inventory?.of(ctx?.actor ?? e.ops.actor) ?? (() => { throw codedError('content-misuse', `content word { ${word} } needs the inventory module: add inventory() to engine.use(...), `
25
27
  + 'or track the thing with a flag / counter ({ setFlag } / { bump }) or a game condition word instead'); })();
26
28
 
27
- /** Execution part of the engine's built-in words (descriptions are in rules.js) */
29
+ /** Execution part of the engine's built-in words (descriptions are in rules.js). A run answers by returning a failure ({ ok: false, code, facts }); runWords hands it up */
28
30
  export const BUILTIN_TESTS = {
29
- can: (e, v) => e.ops.can(v[0], v[1] ?? {}).ok,
31
+ can: (e, v, raw, ctx) => e.ops.can(v[0], v[1] ?? {}, { actor: ctx?.actor }).ok,
30
32
  flag: (e, v) => !!e.vars.flag(v),
31
33
  notFlag: (e, v) => !e.vars.flag(v),
32
34
  has: (e, v, raw, ctx) => all(v, (id, n) => inv(e, 'has', ctx).has(id, n)),
@@ -34,11 +36,19 @@ export const BUILTIN_TESTS = {
34
36
  counter: (e, v) => all(v, (k, n) => e.vars.counter(k) >= n),
35
37
  };
36
38
  export const BUILTIN_RUNS = {
37
- op: (e, v) => { e.ops.run(v[0], v[1] ?? {}); }, setFlag: (e, v) => e.vars.setFlag(v),
38
- give: (e, v, raw, ctx) => each(v, (id, n) => inv(e, 'give', ctx).add(id, n)),
39
- take: (e, v, raw, ctx) => each(v, (id, n) => inv(e, 'take', ctx).remove(id, n)),
39
+ op: (e, v, raw, ctx) => e.ops.run(v[0], v[1] ?? {}, { actor: ctx?.actor }),
40
+ setFlag: (e, v) => e.vars.setFlag(v),
41
+ // add keeps what fits and calls that ok, so the rest is this word's to report; facts.left is exactly what { give } could still pay later
42
+ give(e, v, raw, ctx) {
43
+ const left = {};
44
+ each(v, (id, n) => { const r = inv(e, 'give', ctx).add(id, n), got = r.ok ? r.added : 0; if (got < n) left[id] = n - got; });
45
+ return Object.keys(left).length ? failure({ code: 'full', facts: { left } }) : undefined;
46
+ },
47
+ take(e, v, raw, ctx) {
48
+ const short = Object.entries(v).filter(([id, n]) => !inv(e, 'take', ctx).remove(id, n)).map(([id]) => id);
49
+ return short.length ? failure({ code: 'notEnough', facts: { short } }) : undefined;
50
+ },
40
51
  bump: (e, v) => e.vars.bump(v),
41
- startQuest: (e, v) => e.quests.start(v),
42
52
  toast: (e, v) => toast(e, v),
43
53
  particles: (e, v) => e.particles.emit(v.name, v.at, { count: v.count }),
44
54
  marker: (e, v, raw) => e.content._mark(markerId(raw), v, raw.label), // the same marker again replaces the old one
@@ -47,148 +57,118 @@ export const BUILTIN_RUNS = {
47
57
  const markerId = raw => raw.id ?? (typeof raw === 'string' ? raw : raw.place ?? `${raw.x},${raw.z}`);
48
58
 
49
59
  /**
50
- * Load one content pack. c is the merged object of content/index.js (or one pack of a list); api is engine.content; ids is the IdCheck shared by every pack of
51
- * this load call (ids.js); st is the content module's load state (shared across repeated load calls):
52
- * { triggers: merged trigger table, subs: listener handles, startOn: quest id -> listener handle, levelPlace(name) }
53
- * Order: vocabulary -> key actions -> vegetation -> items -> containers -> pickups -> NPCs -> dialogues -> quests -> trigger zones -> templates -> props.
60
+ * Load content packs as one transaction (core/base/sections.js): every pack is checked and prepared before any commits, and whatever fails after that takes every commit
61
+ * back, so a refused load changed nothing. packs are the merged objects of content/index.js; api is engine.content; ids is the IdCheck of this load call (ids.js); st is
62
+ * the content module's load state (shared across repeated load calls): { kinds, ops, sectionIds, refs, levelPlace(name), wait(promise) }; places are this load's new places;
63
+ * turn says it belongs to the state replacement running now (stateReplace.js). checkOps refuses op names nothing defines; a replay passes none, its pack was checked when it came.
64
+ * Returns the Promise of the transaction, or nothing when it ended on this tick.
65
+ * Order per pack: vocabulary -> key actions, audio, views (core services) -> renames -> the modules' sections in ORDER -> any other section -> game kinds. Packs commit in
66
+ * load order, so a later pack stands on an earlier one; with a level file to wait for the whole load commits after it, on the new level's markers. A load waits for the one
67
+ * before it (st.queue) and goes down with it: a level that failed leaves nothing to stand on. A load with its turn does neither: the load before it may be waiting for that very
68
+ * replacement to end, and what a load() brings in is part of the state it builds, not of the line outside. content's isReady waits for all of it.
69
+ * What a section's data means belongs to the module that owns it: replacing the quests module replaces the quests format.
54
70
  * Pickups, props and NPCs are initial world data: the save records only changes and removals, independent of load order (rules at the top of world/persist.js).
55
71
  * Positions that use level markers (not in places) belong to the current level: pickup, prop and NPC data carry a zone (= current level name,
56
72
  * engine.world.zone),
57
73
  * a level change only tears down models and they are rebuilt on return, with taken / moved / removed state intact; trigger zones are not data and are removed
58
74
  * on level change (level.track).
59
75
  */
60
- export function loadContent(e, api, c, st, ids) {
76
+ export function loadContent(e, api, packs, st, ids, places = {}, turn, checkOps) {
61
77
  const { where } = api;
62
78
  const origin = (id, list, key) => { if (DEV) e.world?.setOrigin(id, { definedAt: srcOf(list, key) }); };
63
79
  const onLevel = (...ps) => ps.some(p => p && typeof p === 'object' ? st.levelPlace(p.place) : st.levelPlace(p));
64
80
  const bind = (h, ...ps) => { if (h && onLevel(...ps)) e.level?.track(h); return h; };
65
81
  const zoneOf = (...ps) => onLevel(...ps) ? e.world?.zone ?? null : null;
82
+ const sections = sectionsOf(e), kinds = { ...st.kinds };
83
+ const list = [{ s: {
84
+ undo: () => keepLoad(e, st),
85
+ // the first commit of the load, so a refusal leaves the rest uncommitted: a game kind's load has no undo. Not in validate: a load waiting for a file may meet an op defined meanwhile
86
+ commit() { Object.assign(st.places, places); for (const p of packs) collectOps(p, st.ops); checkOps?.(); },
87
+ } }];
88
+ for (const pack of packs) list.push(...loadSteps(e, api, pack, st), ...packSections(e, pack, st, sections, kinds));
89
+ // track: these listeners run content words, so they go with the content module
90
+ const inTurn = liveTurn(e, turn), after = inTurn ? null : st.queue, c = { engine: e, content: api, where, bind, zone: zoneOf, ids, origin, pickupId, track: st.track, after };
91
+ // a commit writes state, so it lands between replacements, never inside one: a pack that waited on a file through a load commits on the state that load left
92
+ const commits = fn => { const r = e.ops.allow(fn); if (r) whileRestoring(e, r); return r; }; // only a failure whose undo has to wait gives a result
93
+ const run = runSections(list, c, { after, around: fn => whenTurnFree(e, () => commits(fn), turn) });
94
+ if (!run || inTurn) return run;
95
+ const tail = st.queue = run.finally(() => { if (st.queue === tail) st.queue = null; });
96
+ return tail;
97
+ }
66
98
 
67
- each(c.rules?.conditions, (name, d) => api.condition(name, d));
68
- if (c.rules?.effects) throw codedError('content-misuse', NO_GAME_EFFECTS);
69
- // game kinds stay registered across loads, so a later content.load({ recipes }) without rules still finds them
70
- const bad = kindProblems(c.rules);
71
- if (bad.length) throw codedError('content-misuse', 'content/rules.js: ' + bad.join('; '));
72
- Object.assign(st.kinds, c.rules?.kinds);
73
- const known = contentFiles({ kinds: st.kinds });
74
- for (const k of Object.keys(c)) if (k !== 'name' && !known[k]) throw codedError('unknown-option', 'content.load: ' + unknownContent(k, { kinds: st.kinds }));
75
- collectOps(c, st.ops);
76
-
77
- if (c.renames) applyRenames(e, c.renames); // first: saved state under an old id must reach the new id before anything is placed under it
99
+ /** The undo of a whole load: the world, which several sections write, and the tables content itself fills */
100
+ function keepLoad(e, st) {
101
+ const world = e.world?.undoPoint();
102
+ const tables = [st.conds, st.ops, st.templates, st.templateFields, st.templateSrc].map(keepTable);
103
+ const { templateViews, templateSims } = st, was = { kinds: { ...st.kinds }, places: { ...st.places }, sectionIds: structuredClone(st.sectionIds), refs: st.refs.length };
104
+ const views = new Set(templateViews.keys()), sims = new Set(templateSims.keys());
105
+ return () => {
106
+ world?.();
107
+ for (const fn of tables) fn();
108
+ st.kinds = was.kinds; st.places = was.places; st.sectionIds = was.sectionIds; st.refs.length = was.refs;
109
+ for (const [map, had] of [[templateViews, views], [templateSims, sims]]) for (const [name, h] of map) if (!had.has(name)) { h.remove(); map.delete(name); }
110
+ };
111
+ }
78
112
 
113
+ /** What a pack registers with the core services and the vocabulary its sections read, as steps of the transaction */
114
+ function loadSteps(e, api, c, st) {
115
+ const steps = [];
116
+ // game kinds stay registered across loads, so a later content.load({ recipes }) without rules still finds them
117
+ if (c.rules) steps.push({ commit() { each(c.rules.conditions, (name, d) => api.condition(name, d)); Object.assign(st.kinds, c.rules.kinds); } });
79
118
  // a pack's actions are the game's own (owner 'game'): loading the pack again replaces them, it is not a second binder
80
- each(c.actions, (name, a) => e.input.action(name, { label: a.label, keys: a.keys, ...(a.context ? { context: a.context } : {}) }));
81
-
119
+ if (c.actions) steps.push({ undo: () => e.input.keepActions(Object.keys(c.actions)), commit: () => each(c.actions, (name, a) => e.input.action(name, { label: a.label, keys: a.keys, ...(a.context ? { context: a.context } : {}) })) });
82
120
  // audio: sounds / footsteps by name into engine.audio.config, rules to ambience() / music() (core/audio/audioRules.js). A pack loaded again
83
121
  // replaces its own rules (hot reload): a named pack by its name, an unnamed one by the data object itself, so loading the same object
84
122
  // twice never stacks its rules (a fresh key per load did); two different unnamed objects both keep theirs
85
- if (c.audio) e.audio.contentPack(c.name ? 'pack:' + c.name : c, c.name ? `pack "${c.name}"` : 'pack (no name)', c.audio);
86
-
123
+ const key = c.name ? 'pack:' + c.name : c;
124
+ if (c.audio) steps.push({ undo: () => e.audio.keepPack(key), commit: () => e.audio.contentPack(key, c.name ? `pack "${c.name}"` : 'pack (no name)', c.audio) });
87
125
  // views: named fixed camera views (core/scene/Views.js); defining a name again replaces it, so a hot reload just works
88
- each(c.views, (name, v) => e.views.define(name, v));
89
-
90
- // vegetation: model names resolve through vegetationModel (core/assets/namedModel.js, the same resolver vegetation.define uses for a name); register all
91
- // kinds at the same moment once all models are ready
92
- // (each registration rebuilds terrain chunks; registering one by one would rebuild several times at start). content's isReady waits for them
93
- const veg = [];
94
- each(c.vegetation, (name, { model: m, lod, ...rest }) => {
95
- veg.push(Promise.all([vegetationModel(e, m), lod && vegetationModel(e, lod)])
96
- .then(([main, low]) => [name, { ...rest, ...main, ...(low && { lodGeometry: low.model ?? low.geometry }) }])
97
- .catch(err => { reportError(e, err, `content vegetation ${name}: model generation`, { soft: true }); return null; })); // one failure does not affect the others
98
- });
99
- if (veg.length) st.wait(Promise.all(veg).then(list => { for (const v of list) if (v) e.vegetation.define(v[0], v[1]); }));
100
-
101
- each(c.items, (id, d) => e.inventory.define(id, d));
102
- each(c.startItems, (id, n) => e.inventory.add(id, n, { silent: true }));
103
- // containers: starting goods are placed only the first time (if the save already has the container, the save wins; no refill after it was emptied and
104
- // reloaded)
105
- each(c.containers, (id, d) => { ids.claim(id, `containers.${id}`); e.inventory.container(id, { capacity: d.capacity, items: d.items }); });
106
- // pickups: data goes into world (kind 'pickup'). id: the written id if given, else `pickup:<item>:<index in the pickups array>` (stable for the same content;
107
- // when inserting in the middle, give existing entries an id)
108
- if (c.pickups?.length && !e.pickups) throw codedError('module-needs', 'content pickups lie on the ground as pickups: add pickups() to engine.use(...) after world() (and inventory() for item pickups)');
109
- c.pickups?.forEach((p, i) => {
110
- const id = pickupId(p, i);
111
- if (p.id != null) ids.claim(id, `pickups[${i}] (${p.item})`); else ids.unnamed(id, `pickups[${i}] (${p.item})`); // taken / respawning is state
112
- e.pickups.spawn(where(p), { give: p.item, id, count: p.count, data: p.data, radius: p.radius, auto: p.auto, respawnSeconds: p.respawn, initial: true, zone: zoneOf(p) });
113
- origin(id, c.pickups, i);
114
- });
115
-
116
- each(c.npcs, (id, n) => { // the key in content is the NPC's stable id (used by saves and quest targets)
117
- const plan = n.schedule ?? [];
118
- ids.claim(id, `npcs.${id}`);
119
- // every documented npcs.add option can be written in content (arriveDistance, interact, speed...); the same option table checks the spelling.
120
- // The content form owns start / schedule (clock strings, places) and the id (the key), so those are translated below and not passed as written
121
- readParams(`content npcs.${id}`, keysSchema([...e.npcs.optionKeys.filter(k => !['id', 'position', 'zone', 'initial'].includes(k)), 'start']), n);
122
- const { start: _s, schedule: _p, ...rest } = n;
123
- e.npcs.add({ ...rest, id, schedule: plan.map(s => ({ at: s.at, position: where(s) })), position: where(n.start || plan[0]), zone: zoneOf(n.start, ...plan), initial: true });
124
- origin(id, c.npcs, id);
125
- });
126
+ if (c.views) steps.push({ undo: () => keepTable(e.views.map), commit: () => each(c.views, (name, v) => e.views.define(name, v)) });
127
+ // saved state under an old id must reach the new id before anything is placed under it. The world goes back with keepLoad
128
+ let goods = null;
129
+ if (c.renames) steps.push({ undo: () => () => goods?.(), commit() { goods = applyRenames(e, c.renames); } });
130
+ return steps.map(s => ({ s }));
131
+ }
126
132
 
127
- // dialogue: a line can be several variants [{ if: condition, text }, ..., { text }]; the first whose condition holds is used.
128
- // When none holds (no unconditional last variant) the line is empty and a warning names it: throwing inside the dialogue's op would leave
129
- // the conversation stuck on that node.
130
- const variants = (where, list) => () => {
131
- const hit = list.find(v => api.test(v.if));
132
- if (!hit) warnOnce(coded('content-misuse', `content ${where}: no variant's "if" holds and there is no variant without "if", so the line is empty. ` +
133
- 'End the list with a plain { text } as the fallback'), where);
134
- return hit?.text ?? '';
133
+ /** The sections of one pack, in ORDER. Every check that needs no commit runs here, before anything of the load commits. Game kinds are sections too, after the modules' */
134
+ function packSections(e, pack, st, modules, kinds) {
135
+ if (pack.rules?.effects) throw codedError('content-misuse', NO_GAME_EFFECTS);
136
+ const bad = kindProblems(pack.rules);
137
+ if (bad.length) throw codedError('content-misuse', 'content/rules.js: ' + bad.join('; '));
138
+ Object.assign(kinds, pack.rules?.kinds);
139
+ const known = { ...contentFiles({ kinds }), ...Object.fromEntries(modules) };
140
+ for (const k of Object.keys(pack)) if (k !== 'name' && !known[k]) throw codedError('unknown-option', 'content.load: ' + unknownContent(k, { kinds }));
141
+ const sections = new Map(modules);
142
+ for (const [name, k] of Object.entries(kinds)) {
143
+ if (sections.has(name)) throw codedError('content-misuse', `content kind "${name}" is also a section of module ${sections.get(name).owner}: keep one`);
144
+ sections.set(name, { owner: 'game', commit: (data, c) => k.load?.(e, data, c.content) });
145
+ }
146
+ const rank = n => { const i = ORDER.indexOf(n); return i < 0 ? ORDER.length : i; };
147
+ for (const name of Object.keys(pack)) {
148
+ const home = sectionHomes[name];
149
+ if (home && !sections.has(name) && !isEmpty(pack[name])) throw codedError('module-needs', `content ${name}: no installed module reads this section. Add ${home} to engine.use(...), or a module with content: { ${name}: { commit } }`);
150
+ }
151
+ const done = (name, s) => r => {
152
+ if (typeof r?.then === 'function') st.wait(r);
153
+ st.gaveWay.get(pack)?.delete(name);
154
+ note(st, name, s, pack[name]);
135
155
  };
136
- each(c.dialogues, (id, d) => {
137
- const nodes = {};
138
- each(d.nodes, (nid, n) => {
139
- nodes[nid] = {
140
- ...n, speaker: n.speaker ?? d.speaker,
141
- text: Array.isArray(n.text) ? variants(`dialogues.${id}.nodes.${nid}.text`, n.text) : n.text,
142
- do: n.do && (() => api.run(n.do)),
143
- choices: n.choices?.map(ch => ({ ...ch, if: ch.if && (() => api.test(ch.if)), do: ch.do && (() => api.run(ch.do)) })),
144
- };
145
- });
146
- e.dialogue.define(id, nodes);
147
- });
156
+ const gaveWay = name => () => { if (!st.gaveWay.has(pack)) st.gaveWay.set(pack, new Set()); st.gaveWay.get(pack).add(name); };
157
+ return [...sections].filter(([name]) => pack[name] != null).sort(([a], [b]) => rank(a) - rank(b)).map(([name, s]) => ({ s, data: pack[name], done: done(name, s), gaveWay: gaveWay(name) }));
158
+ }
148
159
 
149
- // quests: a step target can be a place, { place, x, z }, { x, z }, { npc: 'id' } (follows the NPC) or { nearest: itemId } (the nearest pickup)
150
- // { npc } reads the position by id each frame: follow the model if there is one, else (far away, other level) use the data position
151
- const target = t => t == null ? undefined : t.npc ? () => e.npcs?.get(t.npc)?.position : t.nearest ? t : where(typeof t === 'string' ? { place: t } : t);
152
- // a step may be parallel goals { text?, all: [{ text, done, target, optional }] }; fail / onFail are a condition and an effect like done / reward
153
- const goal = s => ({ ...(s.id != null && { id: s.id }), text: s.text, done: () => api.test(s.done), target: target(s.target), ...(s.optional && { optional: true }) }); // id: stable for saves
154
- each(c.quests, (id, q) => {
155
- e.quests.define(id, {
156
- title: q.title, desc: q.desc,
157
- steps: q.steps.map(s => s.all ? { ...(s.id != null && { id: s.id }), text: s.text, all: s.all.map(goal) } : goal(s)),
158
- reward: q.reward && (() => api.run(q.reward)),
159
- ...(q.fail && { fail: () => api.test(q.fail) }), ...(q.onFail && { onFail: () => api.run(q.onFail) }),
160
- });
161
- st.startOn.get(id)?.remove(); // loading the same quest again: replace the old listener instead of attaching twice
162
- if (q.startOn) st.startOn.set(id, st.track(e.events.on(q.startOn, () => e.quests.start(id))));
163
- });
160
+ /** What the reference check (checkRefs) needs from a section just loaded */
161
+ function note(st, name, s, data) {
162
+ const ids = st.sectionIds[name] ??= new Set();
163
+ for (const k of Array.isArray(data) ? data.map(x => x?.id) : Object.keys(data)) if (k != null) ids.add(k);
164
+ st.refs.push(...s.references?.(data) ?? []);
165
+ }
164
166
 
165
- // trigger zones: fromLevel = the level's trigger_<tag> marker; otherwise placed by position. Enter/exit effects look up the merged table, and the listener is
166
- // attached only once
167
- if (c.triggers) {
168
- Object.assign(st.triggers, c.triggers);
169
- if (Object.values(c.triggers).some(t => t.fromLevel)) e.triggers.fromMarkers();
170
- each(c.triggers, (tag, t) => {
171
- if (!t.fromLevel) bind(e.triggers.add({ ...t, tag, position: where(t.position), onEnter: null, onExit: null }), t.position);
172
- });
173
- st.subs ??= [
174
- // the effects act for whoever crossed the zone (a { give } lands in that actor's bag); a zone emptied by removal has no id: engine.actor
175
- st.track(e.events.on('trigger:enter', ({ tag, id }) => api.run(st.triggers[tag]?.onEnter, { actor: id ?? e.actor }))),
176
- st.track(e.events.on('trigger:exit', ({ tag, id }) => api.run(st.triggers[tag]?.onExit, { actor: id ?? e.actor }))),
177
- ];
167
+ /** Ids a section names in a section that was loaded and does not have them. Only when that section was loaded: a game may define its items in code */
168
+ export function checkRefs(st) {
169
+ for (const { section, id, at } of st.refs.splice(0)) {
170
+ if (st.sectionIds[section] && !st.sectionIds[section].has(id)) warnOnce(coded('content-misuse', `content ${at}: ${section} has no "${id}"`), `${at}:${id}`);
178
171
  }
179
-
180
- // grids (layout rules, not saved) before props: a props entry with grid places an item on one; a repeated load keeps the grid that exists
181
- each(c.grids, (name, g) => {
182
- if (!e.grids) throw codedError('content-misuse', `content grids: install grids() to use grid "${name}"`);
183
- if (!e.grids.get(name)) e.grids.add(name, g);
184
- });
185
- // templates before props: a props entry with template places an instance of it
186
- if (c.templates) { needWorld(e); defineTemplates(e, api, st, c.templates); }
187
- // props: data goes into world (kind 'prop'); models and collision are built nearby and torn down when far by present in props.js
188
- if (c.props?.length) addProps(e, api, c.props, st, zoneOf, ids);
189
-
190
- // game kinds last: their data may name the items, NPCs and places loaded above
191
- each(st.kinds, (name, k) => { if (c[name] !== undefined) k.load?.(e, c[name], api); });
192
172
  }
193
173
 
194
174
  /** Op names that content data refers to ({ op: [...] } / { can: [...] } anywhere), checked against engine.ops once the game is ready */
@@ -1,6 +1,6 @@
1
1
  // What the marker / clearMarker effects show: playthrough state, kept in the 'content' save part, so a load shows the save's markers and a new game none of the old
2
2
  // ones. st.marks holds id -> [position, label]; api.markers holds the hud markers on screen now.
3
- import { refuseSave } from '../../core/saves/saveValues.js';
3
+ import { refuseSave } from '../../core/base/saveValues.js';
4
4
 
5
5
  /** content._mark: set (v = position) or clear (v = null) marker id */
6
6
  export function setMark(e, api, st, id, v, label) {