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
@@ -1,5 +1,5 @@
1
1
  // Level module: load a hand-built scene (glTF/GLB from Blender, or THREE objects assembled in code) and make it playable:
2
- // - ground: walkable meshes become ground height (provides engine.surface/slope/groundType; mutually exclusive with the terrain module)
2
+ // - ground: walkable meshes become ground height (provides engine.surface/slope/groundType; holds the exclusive 'ground' slot, as terrain does: installing both is refused at use())
3
3
  // - collision: meshes named col_* (or userData.collider) become walls the character cannot cross; col_ meshes themselves are hidden
4
4
  // - markers: objects named spawn, spawn_*, npc_*, trigger_*, marker_* (usually Blender empties) have their positions recorded
5
5
  //
@@ -40,10 +40,12 @@
40
40
  // markers { name: { name, position, quaternion, scale, userData, object } } (world space; position is a Vector3, object is the original)
41
41
  // spawn spawn position (spawn, else the first spawn_*, else the origin)
42
42
  // marker(name) / markersWith(prefix) get one / get a group (e.g. markersWith('npc_'))
43
- // ready whether loading is done (boolean)
43
+ // ready the level's state is committed and nothing is loading (boolean). After unload() it is true with no level, since nothing is loading: root says whether a level stands
44
+ // playable every module and required nearby build settled after the commit too (boolean)
44
45
  // heightfield heightfield data (for debugging)
45
46
  // staticTrimeshes() walkable-mesh triangles (world space), for building Rapier static colliders
46
- // load(path/asset name or THREE object) switch level (unload current, load new, emit level:loaded when done); returns a Promise
47
+ // load(path/asset name or THREE object) switch level: the new one is built first and replaces the old one only on success; a failure keeps the old level
48
+ // and rejects. Returns a Promise
47
49
  // unload() unload (also removes everything registered via track)
48
50
  // track(handle) register things that belong to the current level and need no keeping (handles with remove(): trigger zones...); auto-removed on level switch /
49
51
  // unload.
@@ -53,30 +55,35 @@
53
55
  // cameraOcclusion).
54
56
  // Save: the current level (path or asset name) goes into the save; on load, switch back first and wait for it before loading the rest (save key level comes
55
57
  // first, load returns a Promise);
56
- // scenes built in code (scene) cannot be saved, loading does not switch level -- to support cross-level loading, register the builder in the assets manifest
57
- // and use level({ url: name }).
58
- // Event: level:loaded { root, markers, spawn }
58
+ // a scene built in code has no file a stored save could name: it saves a token only this page can read back ({ scene: n }), so a rollback and a new game return to it; a token from another page
59
+ // stays on the level that stands. To load across pages, register the builder in the assets manifest and use level({ url: name }).
60
+ // Events: level:loading { source }, then level:failed { source, error } or level:loaded { root, markers, spawn } (state committed), then level:playable { root }.
61
+ // level:unloaded { source } says a level left: on unload(), and on a switch just before the new one commits. What was built from the level goes on it
59
62
  // Picture: the level module draws nothing itself, the scene looks entirely like your model, so it does not read the style.
60
63
  import * as THREE from 'three';
61
64
  import { readParams, keysSchema } from '../../core/base/params.js';
62
65
  import { levelNodes } from './nodes.js';
63
66
  import { worldTrimeshes } from './geometry.js';
64
- import { loadLevel, finishLoad, processScene } from './load.js';
67
+ import { follows } from '../../core/base/follows.js';
68
+ import { loadLevel, dropLoad, dropAsks, finishLoad, readScene, adoptScene, addColliders, levelSection } from './load.js';
65
69
  import { warnOnce } from '../../core/base/validate.js';
66
70
  import { coded } from '../../core/base/errorHints.js';
71
+ import { checkSaveFile } from '../../core/base/saveValues.js';
72
+ import { whenTurnFree } from '../../core/saves/stateReplace.js';
67
73
 
68
74
  const STRINGS = {
69
75
  'zh-CN': { 'module.level': '关卡', 'level.loadFailed': '关卡加载失败:{url}', 'level.noScene': '关卡模块需要 url 或 scene 参数' },
70
76
  en: { 'module.level': 'level', 'level.loadFailed': 'Failed to load level: {url}', 'level.noScene': 'The level module needs a url or scene option' },
71
77
  };
72
78
 
73
- const LEVEL_PARAMS = keysSchema(['url', 'scene', 'walkable', 'colliders', 'cellSize', 'outside', 'waterLevel', 'colliderPad', 'colliderHeight', 'sharpEdge', 'hideMarkers', 'addToScene']);
79
+ const LEVEL_PARAMS = keysSchema(['url', 'scene', 'walkable', 'colliders', 'cellSize', 'outside', 'waterLevel', 'colliderPad', 'colliderHeight', 'sharpEdge', 'hideMarkers', 'addToScene', 'part']);
74
80
 
75
81
  /** The object behind engine.level; st is the module's state (level() below). load and unload go through api, so a wrapped one (engine.wrap) is the one that runs */
76
82
  function levelApi(st) {
77
83
  const api = {
78
84
  root: null, markers: {}, spawn: new THREE.Vector3(), heightfield: null,
79
85
  get ready() { return st.done; },
86
+ get playable() { return st.done && st.playable; },
80
87
  /** Register things belonging to the current level ({ remove() } handles); auto-removed on level switch / unload; returns the same handle */
81
88
  track(h) { if (h) st.removers.push(h); return h; },
82
89
  marker: name => api.markers[name] || null,
@@ -89,55 +96,103 @@ function levelApi(st) {
89
96
  },
90
97
  /** Unload the level: remove from scene, delete colliders, ground reverts to the outside height */
91
98
  unload() {
92
- for (const h of st.removers.splice(0)) h.remove();
99
+ const source = api.root ? st.current : undefined; // undefined: no level stood here, nobody needs telling
100
+ for (const h of [...st.removers.splice(0), ...st.walls.splice(0)]) h.remove();
93
101
  if (api.root && st.o.addToScene) st.e.remove(api.root); // full removal (geometries and materials shared by assets are not disposed)
94
- st.walkMeshes.length = 0; st.hf = api.heightfield = null; st.pendingColliders = null; st.trimeshCache = null; api.markers = {}; api.root = null; st.current = null; st.version++; st.loadGen++;
95
- st.done = true; // nothing is loading now: a file still on its way is dropped, and no finishLoad would ever come for it (load sets it back)
102
+ st.walkMeshes.length = 0; st.hf = api.heightfield = null; st.colliders = null; st.wallsIn.reset(); st.trimeshCache = null; api.markers = {}; api.root = null; st.current = null; st.version++; dropAsks(st); st.playable = false;
103
+ st.done = true; st.playable = false; // nothing is loading now: a file still on its way is dropped, and no finishLoad would ever come for it (load sets it back)
104
+ if (source !== undefined) {
105
+ // a level that left takes its zone and spawn with it: the next scene's nodes must not be placed in a zone that is gone
106
+ api.spawn = new THREE.Vector3();
107
+ if (st.e.world) st.e.world.zone = null;
108
+ st.e.events.emit('level:unloaded', { source });
109
+ }
96
110
  },
97
- /** Switch level: unload the current one, load a new one (glTF path/asset name, or THREE object), emit level:loaded when done */
98
- async load(urlOrScene) { return loadLevel(st, urlOrScene, false); },
111
+ /** Switch level (glTF path/asset name, or THREE object): the new one is built first, a failure keeps the old one and rejects (load.js). During a save load it waits for the load to end, so the level a load answered true for is the one that stands */
112
+ async load(urlOrScene, { turn } = {}) { return whenTurnFree(st.e, () => loadLevel(st, urlOrScene, false), turn); },
99
113
  };
100
114
  return api;
101
115
  }
102
116
 
117
+ const OPENING = '(opening scene)'; // no file or asset can be named this
118
+
119
+ /** What the save holds for a level built in code. Weak: a token in a stored save must not keep every level this page ever built in memory */
120
+ function sceneToken(st, root) {
121
+ const ids = st.sceneIds, id = ids.get(root) ?? ids.set(root, st.scenes.push(new WeakRef(root)) - 1).get(root);
122
+ return { scene: id };
123
+ }
124
+
103
125
  export function level(opts = {}) {
104
126
  readParams('level', LEVEL_PARAMS, opts);
105
127
  const { url = null, scene = null, walkable = null, colliders = 'named', cellSize = 0.5, outside = 0, waterLevel = -Infinity,
106
- colliderPad = 0, colliderHeight = 0, sharpEdge = 0.6, hideMarkers = true, addToScene = true } = opts;
128
+ colliderPad = 0, colliderHeight = 0, sharpEdge = 0.6, hideMarkers = true, addToScene = true, part = false } = opts;
107
129
  const st = {
108
- e: null, hf: null, done: false, version: 0, trimeshCache: null, pendingColliders: null,
130
+ e: null, hf: null, playable: false,
131
+ _done: false, idle: [], // done: nothing is loading. idle: who waits for that (init); a setter, because a load ends in many ways: committed, failed, cancelled, overtaken, unloaded
132
+ get done() { return this._done; },
133
+ set done(v) { this._done = v; if (v) for (const go of this.idle.splice(0)) go(); },
134
+ version: 0, trimeshCache: null,
135
+ colliders: null, walls: [], wallsIn: follows(() => st.e.collision), // the level's collision meshes, the handles of their boxes, the module those boxes are in (load.js addColliders)
109
136
  o: { walkable, colliders, cellSize, outside, colliderPad, colliderHeight, sharpEdge, hideMarkers, addToScene },
110
- loadGen: 0, // +1 per load / unload: a file that arrives after a newer load or unload started is dropped, not processed on top of it
137
+ asks: [], // the loads under way, newest last: only the newest may commit, so a file that arrives after a newer load, a save or an unload is dropped
111
138
  current: typeof url === 'string' && !scene ? url : null, // current level path/asset name (for saving)
112
139
  walkMeshes: [], removers: [],
140
+ scenes: [], sceneIds: new WeakMap(), // levels built in code, by token (sceneToken)
113
141
  nodeSet: null, // level nodes that become world records (nodes.js), created at install
142
+ taken: [], // record nodes of the adopted scene, placed by finishLoad
114
143
  };
115
144
  const api = st.api = levelApi(st);
145
+ st.section = levelSection(st);
116
146
 
117
147
  return {
118
- name: 'level', type: 'world', provides: ['level'], params: LEVEL_PARAMS, options: opts, label: 'Level', stage: 'ground', after: ['terrain'], optional: ['world', 'content', 'collision'],
119
- install(engine) {
148
+ name: 'level', skipKind: 'none', type: 'world', provides: part ? ['level'] : ['level', 'ground'], params: LEVEL_PARAMS, options: opts, label: 'Level', stage: 'ground', optional: ['world', 'content', 'collision'],
149
+ content: { level: st.section },
150
+ install(engine, ctx) {
151
+ ctx.feeds('collision', () => addColliders(st));
120
152
  const e = st.e = engine;
121
- st.nodeSet = levelNodes(e, () => api.root, () => st.current);
153
+ st.nodeSet = levelNodes(e, ctx, () => api.root, () => st.current);
122
154
  e.i18n.add(STRINGS);
123
155
  // ground API: before the heightfield is built, return the outside height
124
- e.setGround({
156
+ const ground = {
125
157
  height: (x, z, refY) => st.hf ? st.hf.height(x, z, refY) : outside,
126
- slope: (x, z) => st.hf ? st.hf.slope(x, z) : 0,
127
- type: (x, z) => st.hf ? st.hf.type(x, z) : 'default',
158
+ slope: (x, z, refY) => st.hf ? st.hf.slope(x, z, refY) : 0,
159
+ type: (x, z, refY) => st.hf ? st.hf.type(x, z, refY) : 'default',
128
160
  waterLevel,
129
161
  staticTrimeshes: () => api.staticTrimeshes(),
130
162
  staticVersion: () => st.version, // +1 on level change; the physics module rebuilds static colliders on it
131
- });
132
- if (scene) processScene(st, scene);
163
+ };
164
+ if (part) api.ground = ground; else ctx.ground.provide(ground); // part: compositeGround holds the slot and reads level.ground
165
+ // the level is the module's: scene, walls, rays and level.track handles leave with it (unuse, replaces, a failed init). Before the part: handles go newest first, so the
166
+ // part still reads the level as it leaves
167
+ ctx.track({ remove: () => api.unload() });
133
168
  // on load, switch back to the saved level (code-built scenes have no name, record null, no switch)
134
169
  // load returns a Promise: the save system waits for the new level (old level's trigger zones are already removed by unload) before reading player
135
170
  // position etc.
136
- e.saves.register('level', { first: true, save: () => st.current, load: d => { if (typeof d === 'string' && d !== st.current) return api.load(d); } });
171
+ // a save that names this level, or none, stays here: a load on its way would land on top of what the save put back
172
+ // The level a holder stood on comes back through the same part when a module takes over the key (Saves.register): a swap keeps the game where it was, and a pack's older
173
+ // level must not take it back (the section's once). A newcomer that says where to open keeps that promise; the same definition put back after a failed swap has none to make
174
+ // the opening scene has no name either, so it saves as OPENING: a new game goes back to it, and a save from before this mark takes it from the new-game state
175
+ const opens = !st.installed && (scene || url);
176
+ let installing = st.installed = true;
177
+ st.kept = false;
178
+ ctx.saves.register('level', { notAtomic: 'its load fetches and builds a level: not plain data, and not something a failed op can wait for', first: true, save: () => st.current ?? (!api.root ? null : api.root === scene ? OPENING : sceneToken(st, api.root)), load: (d, turn) => {
179
+ if (installing) { if (opens || typeof d !== 'string' || d === OPENING) return; st.kept = true; }
180
+ else if (d === OPENING) return api.root === scene ? dropLoad(st) : api.load(scene, { turn });
181
+ else if (d?.scene != null) { const root = st.scenes[d.scene]?.deref(); return !root || root === api.root ? dropLoad(st) : api.load(root, { turn }); }
182
+ else if (typeof d !== 'string' || d === st.current) return dropLoad(st);
183
+ checkSaveFile(e.assets, 'level', 'the level file', d);
184
+ return api.load(d, { turn });
185
+ } });
186
+ installing = false;
187
+ if (scene) adoptScene(st, readScene(st, scene));
137
188
  return api;
138
189
  },
139
190
  critical: true, // the level file is the game's world: a failed load stops start() with the reason
140
191
  async init(engine) {
192
+ // the options say where to open; what the game asked for before init (a pack's level, level.load) comes first and stays, and the url file is not fetched. Asking here
193
+ // would be the newer load and overtake it. If that load ends with no level (refused, failed), the options are the level after all
194
+ if (st.asks.length) await new Promise(res => st.idle.push(res));
195
+ if (api.root && api.root !== scene) return;
141
196
  if (scene) return finishLoad(st);
142
197
  if (url) return loadLevel(st, url, true);
143
198
  warnOnce(coded('level-node', engine.t('level.noScene')));
@@ -147,8 +202,10 @@ export function level(opts = {}) {
147
202
  // which level is up and what it gave: a wrong path shows as file set but markers 0 / walk 0, a code-built scene as file null
148
203
  describe() {
149
204
  const s = api.spawn, r = v => Math.round(v * 10) / 10;
150
- return { file: st.current, ready: st.done, markers: Object.keys(api.markers).length, walkMeshes: st.walkMeshes.length, removers: st.removers.length,
205
+ return { file: st.current, ready: st.done, playable: api.playable, markers: Object.keys(api.markers).length, walkMeshes: st.walkMeshes.length, removers: st.removers.length + st.walls.length,
151
206
  spawn: { x: r(s.x), y: r(s.y), z: r(s.z) } };
152
207
  },
153
208
  };
154
209
  }
210
+
211
+ export const handRolled = 'none: loading a map by hand is one model load that looks like any other';
@@ -1,79 +1,196 @@
1
- // Loading a level: st is the module's state (index.js), and the steps run in this order: loadLevel -> processScene -> finishLoad.
1
+ // Loading a level is the module's content section (core/base/sections.js): prepare builds the new level beside the old one, commit swaps it in.
2
+ // st is the module's state (index.js). Nothing live changes before commit, so a level that cannot load leaves the old one playable:
3
+ // a save transaction rolls back around it, and the error reaches whoever asked.
4
+ // The moments: level:loading (asked for), then level:failed, or level:loaded (state committed: ground, markers, records) and later
5
+ // level:playable (every module and required nearby build settled). A load overtaken by a newer one, a save or an unload ends silently: the newest stands and reports. Only the level gives way: the rest of its pack goes in, on the level that won.
2
6
  import * as THREE from 'three';
3
7
  import { buildHeightfield } from './heightfield.js';
4
8
  import { colliderBoxes } from './geometry.js';
5
9
  import { sortNodes, groundTypeOf, readMarkers, chainHas, chainValue, COL_RE } from './meshes.js';
6
10
  import { toast } from '../../ui/UI.js';
7
- import { reportError } from '../../core/base/errors.js';
11
+ import { runSections, DROPPED } from '../../core/base/sections.js';
12
+ import { whenSettled } from '../../core/engine/headlessLoad.js';
13
+ import { codedError, coded } from '../../core/base/errorHints.js';
14
+ import { warnOnce } from '../../core/base/validate.js';
8
15
 
9
- /** hard: the first load from init() (the module is critical, so a missing level file must stop start() instead of opening an empty world);
10
- * a switch while playing or a save load stays soft (reported + toast) so the running game is not torn down by one bad path */
11
- export async function loadLevel(st, urlOrScene, hard) {
16
+ const isScene = v => !!v?.isObject3D;
17
+ const nameOf = source => typeof source === 'string' ? source : null; // code-built scenes have no name: saves record null, no zoning
18
+
19
+ /** The level section: a file or asset name, or a THREE object, becomes the level; plain { markers } data is the tools' file for a code-built level and loads nothing */
20
+ export const levelSection = st => ({
21
+ desc: 'level markers (spawn point, NPCs, trigger zones) of a code-built level: for the tools (content checks, GAMEMAP); load() reads no markers from it. A file or asset name here switches level, as engine.level.load does',
22
+ validate(data) {
23
+ if (typeof data === 'string' || isScene(data) || (data && typeof data === 'object' && !Array.isArray(data))) return;
24
+ throw codedError('content-misuse', `level: expected a file or asset name, a THREE object, or { markers }, got ${JSON.stringify(data)}`);
25
+ },
26
+ prepare: (data, c) => typeof data === 'string' || isScene(data) ? prepareLevel(st, data, c) : null,
27
+ // an overtaken load's pack goes in on the level that won, so it waits to see which. Not for a pack queued behind this one: that one waits for this
28
+ waitFor: p => p && !isNewest(st, p) && st.asks.length && !st.asks.at(-1).behind ? new Promise(res => st.idle.push(res)) : undefined,
29
+ commit: (p, c) => p ? commitLevel(st, p, c) : undefined,
30
+ cancel: p => { if (p) letGo(st, p.ask ?? p); },
31
+ undo: p => p ? backToLevel(st) : undefined,
32
+ get once() { return st.kept; }, // the level came back through the save part: the pack's is older than where the game stood
33
+ });
34
+
35
+ /**
36
+ * The undo of a level swap: the old root left the scene and its memory may be gone, so the old level loads again, by the same road as any level (a failure there is told
37
+ * as a level failure, and reaches whoever asked for the pack: sections.js). Records of its nodes are still in the world. A pack with no level before it ends with no level
38
+ */
39
+ function backToLevel(st) {
40
+ const { e, api } = st, root = api.root, source = st.current ?? root, zone = e.world?.zone;
41
+ return () => {
42
+ if (api.root === root) return;
43
+ api.unload();
44
+ if (e.world) e.world.zone = zone;
45
+ if (source) return loadLevel(st, source, false);
46
+ };
47
+ }
48
+
49
+ /** hard: the first load from init() stops start() on its own (the module is critical), so no toast over the loading screen.
50
+ * async: a scene with nothing to wait for commits on this tick, and any failure still arrives as a rejection */
51
+ export async function loadLevel(st, source, hard) {
52
+ await runSections([{ s: st.section, data: source }], { hard });
53
+ }
54
+
55
+ /** The load is over: a failure is told once, here, and passed on. It ends every load before it too: they were already overtaken */
56
+ function failLevel(st, source, err, { hard }) {
57
+ const { e } = st;
58
+ dropAsks(st); st.done = true; // nothing is loading any more
59
+ if (!st.api.root) st.current = null; // a first load that failed: the save must not name a level that never loaded
60
+ e.events.emit('level:failed', { source: nameOf(source), error: err });
61
+ if (!hard) toast(e, e.t('level.loadFailed', { url: nameOf(source) ?? 'scene' }), { kind: 'error' });
62
+ throw err;
63
+ }
64
+
65
+ /** Is this load the last one asked for? Only that one may commit */
66
+ const isNewest = (st, ask) => st.asks.at(-1) === ask && !st.e.disposed;
67
+
68
+ /** A load that goes no further. e.remove releases a file, so assets.trim can free it; a code-built scene stays the caller's, whole */
69
+ function letGo(st, ask) {
70
+ const i = st.asks.indexOf(ask), { root, source, taken = [] } = ask;
71
+ if (i >= 0) st.asks.splice(i, 1);
72
+ ask.leave.abort(); // a file still on its way: this load stops waiting for it, and with no other waiter the download ends
73
+ if (!st.asks.length) st.done = true;
74
+ if (!root) return;
75
+ ask.root = null;
76
+ if (typeof source === 'string') st.e.remove(root); else st.nodeSet.giveBack(taken);
77
+ }
78
+
79
+ /** A save that stays on this level: what is on its way would land on top of it. The first load is the level itself, so it goes on */
80
+ export function dropLoad(st) { if (st.api.root) { dropAsks(st); st.done = true; } }
81
+
82
+ /** No load under way counts any more: each stops waiting for its file (its prepare then ends as an overtaken load does) */
83
+ export function dropAsks(st) { for (const ask of st.asks.splice(0)) ask.leave.abort(); }
84
+
85
+ /** Everything that can fail, away from the live game. Returns what commitLevel needs, or for a file a Promise of it */
86
+ function prepareLevel(st, source, c) {
87
+ const { e } = st, ask = { source, behind: !!c.after, leave: new AbortController() }; // grows into the prepared level; behind: a content load queued after an earlier one; leave: stop waiting for the file
88
+ st.asks.push(ask);
89
+ st.done = false;
90
+ e.events.emit('level:loading', { source: nameOf(source) });
91
+ const build = root => {
92
+ Object.assign(ask, readScene(st, root));
93
+ st.nodeSet.check(ask.taken, nameOf(source), root);
94
+ return ask;
95
+ };
96
+ const fail = err => {
97
+ const newest = isNewest(st, ask);
98
+ letGo(st, ask);
99
+ return newest ? failLevel(st, source, err, c) : ask;
100
+ };
101
+ if (isScene(source)) { ask.root = source; try { return build(source); } catch (err) { return fail(err); } }
102
+ return Object.assign(new Promise(res => res(e.assets.wholeModel(source, ask.leave.signal))).then(root => {
103
+ ask.root = root;
104
+ // a newer load / unload / save came while this file loaded (two doors in a row, a save loaded mid-switch): that one owns the level now
105
+ if (!isNewest(st, ask)) { letGo(st, ask); return ask; }
106
+ return build(root);
107
+ }).catch(fail), { ask }); // cancel may come while the file is on its way
108
+ }
109
+
110
+ /** The swap, or giving way to a newer load: the newest level wins, the pack's other sections do not depend on that. Prepare checked what it can, so a throw here is a bug: told like any failure */
111
+ function commitLevel(st, p, c) {
12
112
  const { e, api } = st;
13
- api.unload(); st.done = false;
14
- e.commits.invalidate(); // background results requested for the old level must not land on the new one
15
- // world-data zone = level name: other levels' NPCs etc. only lose models, data stays and is rebuilt on return (code-built scenes have no name, record
16
- // null, no zoning)
17
- if (e.world) e.world.zone = typeof urlOrScene === 'string' ? urlOrScene : null;
18
- if (typeof urlOrScene === 'string') {
19
- st.current = urlOrScene; // set before processScene(): level nodes read it as their zone
20
- const gen = st.loadGen;
21
- try {
22
- const scene = await e.assets.model(urlOrScene);
23
- // a newer load / unload started while this file loaded (two doors in a row, a save loaded mid-switch): that one owns the level now;
24
- // processing this one too would put both levels in the scene under the newer level's name
25
- if (gen !== st.loadGen || e.disposed) { e.remove(scene); return; } // e.remove releases the copy (assets.trim can free the file)
26
- processScene(st, scene);
27
- } catch (err) {
28
- if (gen !== st.loadGen || e.disposed) return; // superseded: the newer load reports its own outcome
29
- st.current = null; // the save must not name a level that never loaded
30
- if (hard) throw err;
31
- reportError(e, err, `level.load('${urlOrScene}')`, { soft: true }); toast(e, e.t('level.loadFailed', { url: urlOrScene }), { kind: 'error' });
32
- }
33
- } else processScene(st, urlOrScene);
34
- finishLoad(st);
113
+ if (!isNewest(st, p)) { letGo(st, p); return DROPPED; }
114
+ try {
115
+ api.unload();
116
+ st.done = false;
117
+ e.commits.invalidate(); // background results requested for the old level must not land on the new one
118
+ // world-data zone = level name: other levels' NPCs etc. only lose models, data stays and is rebuilt on return
119
+ if (e.world) e.world.zone = nameOf(p.source);
120
+ st.current = nameOf(p.source); // before the records are placed: level nodes read it as their zone
121
+ adoptScene(st, p);
122
+ finishLoad(st);
123
+ } catch (err) { failLevel(st, p.source, err, c); }
35
124
  }
36
125
 
37
126
  export function finishLoad(st) {
38
127
  const { e, api } = st;
39
128
  addColliders(st); // if the collision module is installed after level, add colliders here
40
129
  // nodes tagged template / id become world records (loading is setup, not a gameplay action) before anyone (hlod...) sees level:loaded
41
- e.ops.allow(st.nodeSet.place);
130
+ e.ops.allow(() => st.nodeSet.place(st.taken.splice(0)));
42
131
  st.done = true;
43
132
  e.assets.trim(); // old level's models have no copies in use: return GPU memory
44
133
  e.events.emit('level:loaded', { root: api.root, markers: api.markers, spawn: api.spawn });
134
+ // playable comes later than committed: nav, nearby models and physics start building on level:loaded. This level leaving ends the wait, a load that may not come to anything does not
135
+ const version = st.version;
136
+ st.playable = false;
137
+ whenSettled(e, () => version === st.version).then(ok => {
138
+ if (!ok) return;
139
+ st.playable = true;
140
+ e.events.emit('level:playable', { root: api.root });
141
+ }, err => warnOnce(coded('module-not-ready', `level:playable did not come: ${err.message}`)));
45
142
  }
46
143
 
47
- /** Process a scene: classify meshes, build the heightfield, record markers. Colliders wait for the collision module (may not be installed at install time) */
48
- export function processScene(st, root) {
49
- const { e, api, o } = st;
50
- api.root = root;
144
+ /** Read a scene without touching the game: classify meshes, build the heightfield, read markers */
145
+ export function readScene(st, root) {
146
+ const { e, o } = st;
51
147
  root.userData.budgetTag ??= 'level';
52
- if (o.addToScene && !root.parent) e.add(root, { owner: 'level' });
53
148
  root.updateMatrixWorld(true);
54
- st.nodeSet.take(root); // record nodes leave the level root first: no ground, collision or ray registration for them, and hlod never bakes them
149
+ const taken = st.nodeSet.take(root); // record nodes leave the level root first: no ground, collision or ray registration for them, and hlod never bakes them
55
150
  const { meshes, cols, markerObjs, walk, walkSet } = sortNodes(root, o);
56
- st.walkMeshes.push(...walk);
57
- // heightfield
58
151
  const t0 = performance.now(); // measure
59
- st.hf = api.heightfield = buildHeightfield(walk, { cellSize: o.cellSize, outside: o.outside, typeOf: groundTypeOf(root), sharpEdge: o.sharpEdge, stepUp: e.movement.stepHeight, layerGap: e.movement.height });
60
- api.buildMs = performance.now() - t0; // measure: heightfield build time (shown in the debug panel)
61
- const markers = api.markers = readMarkers(markerObjs, o.hideMarkers);
152
+ const hf = buildHeightfield(walk, { cellSize: o.cellSize, outside: o.outside, typeOf: groundTypeOf(root), sharpEdge: o.sharpEdge, stepUp: e.movement.stepHeight, layerGap: e.movement.height });
153
+ const buildMs = performance.now() - t0; // measure: heightfield build time (shown in the debug panel)
154
+ const markers = readMarkers(markerObjs, o.hideMarkers);
62
155
  const sp = markers.spawn || Object.values(markers).find(m => /^spawn_/i.test(m.name));
63
- api.spawn = sp ? sp.position.clone() : new THREE.Vector3(0, st.hf.height(0, 0), 0);
64
- st.pendingColliders = o.colliders === false ? cols.filter(m => COL_RE.test(m.name) || chainValue(m, root, 'collider')) : cols;
65
156
  // rays: all meshes; collision meshes and shown non-walkable meshes also occlude the camera, unless a node says userData.occluder = false (a glass roof, a thin railing).
66
157
  // col_ meshes are hidden by design and still block; any other hidden mesh is not on screen, so the arm has nothing to avoid
67
158
  const blocks = m => chainValue(m, root, 'occluder') !== false, shownHere = m => !chainHas(m, root, p => !p.visible);
68
- st.removers.push(e.rays.addStatic(root), e.rays.addStatic([...cols.filter(blocks), ...meshes.filter(m => !walkSet.has(m) && shownHere(m) && blocks(m))], { occluder: true }));
159
+ return {
160
+ root, taken, walk, hf, buildMs, markers,
161
+ spawn: sp ? sp.position.clone() : new THREE.Vector3(0, hf.height(0, 0), 0),
162
+ colliders: o.colliders === false ? cols.filter(m => COL_RE.test(m.name) || chainValue(m, root, 'collider')) : cols,
163
+ occluders: [...cols.filter(blocks), ...meshes.filter(m => !walkSet.has(m) && shownHere(m) && blocks(m))],
164
+ };
165
+ }
166
+
167
+ /** A read scene becomes the level. Colliders wait for the collision module (may not be installed at install time) */
168
+ export function adoptScene(st, p) {
169
+ const { e, api, o } = st;
170
+ api.root = p.root;
171
+ if (o.addToScene && !p.root.parent) e.add(p.root, { owner: 'level' });
172
+ st.taken = p.taken;
173
+ st.walkMeshes.push(...p.walk);
174
+ st.hf = api.heightfield = p.hf; api.buildMs = p.buildMs;
175
+ api.markers = p.markers; api.spawn = p.spawn;
176
+ st.colliders = p.colliders;
177
+ st.removers.push(e.rays.addStatic(p.root), e.rays.addStatic(p.occluders, { occluder: true }));
69
178
  st.trimeshCache = null; st.version++;
70
179
  addColliders(st);
71
180
  }
72
181
 
73
- /** Turn collision meshes into rotated boxes in the collision module (best-fit box by the mesh's world orientation) */
74
- function addColliders(st) {
75
- const ph = st.e.collision;
76
- if (!ph || !st.pendingColliders) return;
77
- for (const b of colliderBoxes(st.pendingColliders, { colliderHeight: st.o.colliderHeight, colliderPad: st.o.colliderPad })) st.removers.push(ph.addBox(b.at, b.opts));
78
- st.pendingColliders = null;
182
+ /**
183
+ * Turn collision meshes into rotated boxes in the collision module (best-fit box by the mesh's world orientation). A level load and a change of collision module ask (ctx.feeds):
184
+ * it acts only when the module holding them is not the one installed now, so one that came late, came back or replaced the old one gets the walls, and the old handles, gone
185
+ * with their module, are dropped. All or none: a module that refuses a box keeps none of them, and its use() fails on that error
186
+ */
187
+ export function addColliders(st) {
188
+ if (!st.colliders) return;
189
+ st.wallsIn.sync(() => {
190
+ const ph = st.e.collision, fresh = [];
191
+ if (ph) try {
192
+ for (const b of colliderBoxes(st.colliders, { colliderHeight: st.o.colliderHeight, colliderPad: st.o.colliderPad })) fresh.push(ph.addBox(b.at, b.opts));
193
+ } catch (err) { for (const h of fresh) h.remove?.(); throw err; }
194
+ st.walls.length = 0; st.walls.push(...fresh);
195
+ });
79
196
  }
@@ -1,5 +1,5 @@
1
1
  // Level nodes that become world records: nodes tagged with the custom property template or id (Blender -> glTF extras -> userData) leave the level root
2
- // and are placed as authored records `<level>/<node>` once the level is processed. Created per level module by levelNodes(e, getRoot, getCurrent).
2
+ // and are placed as authored records `<level>/<node>` once the level is processed. Created per level module by levelNodes(e, ctx, getRoot, getCurrent).
3
3
  import * as THREE from 'three';
4
4
  import { warnOnce, fmt } from '../../core/base/validate.js';
5
5
  import { codedError } from '../../core/base/errorHints.js';
@@ -13,16 +13,17 @@ const STRINGS_DEV = {
13
13
 
14
14
  export const MARKER_RE = /^(spawn|spawn_.*|npc_.*|trigger_.*|marker_.*)$/i;
15
15
 
16
- /** @param {any} e engine @param {() => any} getRoot current level root @param {() => string | null} getCurrent current level path / name */
17
- export function levelNodes(e, getRoot, getCurrent) {
18
- const taken = [], nodes = new Map(); // record nodes waiting to be placed; record id -> node object (levelNode records)
16
+ /** @param {any} e engine @param {any} ctx the level module's ctx @param {() => any} getRoot current level root @param {() => string | null} getCurrent current level path / name */
17
+ export function levelNodes(e, ctx, getRoot, getCurrent) {
18
+ const nodes = new Map(); // record id -> node object (levelNode records)
19
+ const homes = new WeakMap(); // taken node -> the parent it left
19
20
  let presented = null;
20
21
  /**
21
22
  * Nodes tagged with the custom property template or id (Blender custom property -> glTF extras -> userData): taken out of the level root, world transform
22
- * kept
23
+ * kept. Returns them: the level being prepared holds its own list, the live one is untouched
23
24
  */
24
25
  function take(root) {
25
- taken.length = 0;
26
+ const taken = [];
26
27
  const walk = o => {
27
28
  for (const c of [...o.children]) {
28
29
  if ((c.userData?.template == null && c.userData?.id == null) || MARKER_RE.test(c.name)) { walk(c); continue; }
@@ -31,26 +32,43 @@ export function levelNodes(e, getRoot, getCurrent) {
31
32
  if (!e.world) { warnOnce(STRINGS_DEV.noWorld); continue; }
32
33
  const p = new THREE.Vector3(), q = new THREE.Quaternion(), s = new THREE.Vector3();
33
34
  c.matrixWorld.decompose(p, q, s);
35
+ homes.set(c, c.parent);
34
36
  c.removeFromParent(); c.position.copy(p); c.quaternion.copy(q); c.scale.copy(s);
35
37
  c.userData.hlod = false; // its model comes and goes with the record: never part of a merged far proxy
36
38
  taken.push(c);
37
39
  }
38
40
  };
39
41
  walk(root);
42
+ return taken;
40
43
  }
44
+ /** Undo take, for a code-built scene that will not become the level: it is the caller's, and may be loaded again */
45
+ const giveBack = taken => { for (const o of taken) homes.get(o).attach(o); };
41
46
  /** The name in node ids `<level>/<node>`: the level file name without folders and extension; a code-built scene uses its root name */
42
- const levelName = () => {
43
- const current = getCurrent();
44
- if (!current) return getRoot()?.name || 'level';
47
+ const levelName = (current, root) => {
48
+ if (!current) return root?.name || 'level';
45
49
  const f = String(current), base = f.slice(Math.max(f.lastIndexOf('/'), f.lastIndexOf('\\')) + 1), dot = base.lastIndexOf('.');
46
50
  return dot > 0 ? base.slice(0, dot) : base;
47
51
  };
48
52
  const OWN = ['template', 'id', 'name', 'hlod']; // userData keys that are not record fields (three's glTF loader keeps the node name in userData.name)
53
+ /** What place would refuse, asked before the commit so a level that cannot place its records never replaces the old one */
54
+ function check(taken, current, root) {
55
+ const level = levelName(current, root);
56
+ for (const o of taken) {
57
+ const id = `${level}/${o.name}`, tpl = o.userData.template;
58
+ if (tpl != null) {
59
+ if (!e.content) throw codedError('level-node', fmt(STRINGS_DEV.noContent, { id }));
60
+ e.content.template(tpl); // throws, naming the templates there are
61
+ } else {
62
+ const kind = e.world.get(id)?.kind;
63
+ if (kind && kind !== 'levelNode') throw codedError('level-node', fmt(STRINGS_DEV.clash, { id, kind }));
64
+ }
65
+ }
66
+ }
49
67
  /** Taken nodes -> authored world records, id `<level>/<node>`: a template instance (custom property template) or the node itself (custom property id) */
50
- function place() {
68
+ function place(taken) {
51
69
  if (!taken.length) return; // also without world(): take left the nodes in the level
52
- const level = levelName(), zone = e.world.zone;
53
- for (const o of taken.splice(0)) {
70
+ const level = levelName(getCurrent(), getRoot()), zone = e.world.zone;
71
+ for (const o of taken) {
54
72
  const id = `${level}/${o.name}`, ud = o.userData, node = o.name, { x, y, z } = o.position;
55
73
  const fields = Object.fromEntries(Object.entries(ud).filter(([k, v]) => !OWN.includes(k) && (v == null || typeof v !== 'object' || Array.isArray(v) || v.constructor === Object)));
56
74
  if (ud.template != null) {
@@ -70,15 +88,15 @@ export function levelNodes(e, getRoot, getCurrent) {
70
88
  /** How a level node record looks: the node itself (detached while far or on another level, rebuilt from the same object) */
71
89
  function presentNodes() {
72
90
  if (presented) return;
73
- presented = e.world.present('levelNode', {
91
+ presented = ctx.track(e.world.present('levelNode', {
74
92
  build(rec) {
75
93
  const o = nodes.get(rec.id);
76
94
  if (!o) throw codedError('level-node', fmt(STRINGS_DEV.notLoaded, { id: rec.id }));
77
95
  o.userData.unstatic = e.rays.addStatic(o);
78
96
  return o;
79
97
  },
80
- dispose(rec, o) { o.userData.unstatic?.remove(); e.detach(o); },
81
- });
98
+ dispose(rec, o) { o.userData.unstatic?.remove(); o.removeFromParent(); },
99
+ }));
82
100
  }
83
- return { take, place };
101
+ return { take, giveBack, check, place };
84
102
  }
@@ -23,7 +23,7 @@ import { warnOnce, fmt } from '../../core/base/validate.js';
23
23
  import { readParams, keysSchema } from '../../core/base/params.js';
24
24
  import { coded } from '../../core/base/errorHints.js';
25
25
  import { daylightOf } from '../../render/daylight.js';
26
- import { addSource } from './sources.js';
26
+ import { addSource, restoreGlow } from './sources.js';
27
27
  import { makeGroup, assign, update } from './slots.js';
28
28
  /** @import { ModuleDef } from '../../types/core' */
29
29
  /** @import { LightPool, LightPoolOptions } from '../../types/world' */
@@ -71,7 +71,7 @@ export function lightPool(opts = {}) {
71
71
  };
72
72
 
73
73
  return {
74
- name: 'lightPool', type: 'picture', params: LIGHT_POOL_PARAMS, options: opts, label: 'Light pool', stage: 'late',
74
+ name: 'lightPool', skipKind: 'none', type: 'picture', params: LIGHT_POOL_PARAMS, options: opts, label: 'Light pool', stage: 'late',
75
75
  install(engine) { engine.i18n.add({ 'zh-CN': { 'module.lightPool': '光源池' }, en: { 'module.lightPool': 'light pool' } });
76
76
  const e = pool.e = engine;
77
77
  const k = Math.max(0, Math.min(shadows, point));
@@ -93,10 +93,13 @@ export function lightPool(opts = {}) {
93
93
  if ((pool.timer += dt) >= every) { pool.timer = 0; assign(pool); }
94
94
  update(pool, dt);
95
95
  },
96
- dispose() { offCut?.remove(); for (const L of api.lights) { L.removeFromParent(); L.target?.removeFromParent(); L.dispose(); } },
96
+ // newest first: sources sharing one material each saved the value they found, so the oldest restore comes last and leaves the true original (M12)
97
+ dispose() { offCut?.remove(); for (let i = pool.sources.length - 1; i >= 0; i--) restoreGlow(pool.sources[i]); for (const L of api.lights) { L.removeFromParent(); L.target?.removeFromParent(); L.dispose(); } },
97
98
  describe() {
98
99
  const u = api.stats;
99
100
  return { lights: api.lights.length, lit: u.lit, sources: u.sources, shadows: Math.max(0, Math.min(shadows, point)) };
100
101
  },
101
102
  };
102
103
  }
104
+
105
+ export const handRolled = 'none: lights in the scene are plain three.js, used on purpose';
@@ -27,6 +27,8 @@ function glowOf(g) {
27
27
  // 1 for a source that ignores the time of day, else the night factor (0 by day, 1 at night) for its dusk
28
28
  const nightK = (pool, src) => src.dusk === null ? 1 : nightOf(pool.daylight, src.dusk);
29
29
  export const litOf = (pool, src) => src.intensity * nightK(pool, src);
30
+ /** Put a source's stand-in back as it was added */
31
+ export function restoreGlow(src) { const g = src.glow; if (g) { g.m[g.key] = g.base; g.k = -1; } }
30
32
  export function setGlow(pool, src, k) {
31
33
  const g = src.glow;
32
34
  if (!g) return;
@@ -66,7 +68,7 @@ function handleOf(pool, src) {
66
68
  src.removed = true;
67
69
  const i = pool.sources.indexOf(src); if (i >= 0) pool.sources.splice(i, 1);
68
70
  if (src.slot) src.slot.want = 0;
69
- if (src.glow) { src.glow.m[src.glow.key] = src.glow.base; src.glow.k = -1; }
71
+ restoreGlow(src);
70
72
  pool.timer = Infinity;
71
73
  },
72
74
  };
@@ -300,11 +300,11 @@ export function music(opts = {}) {
300
300
  readParams('music', MUSIC_PARAMS, opts);
301
301
  let m = null;
302
302
  return {
303
- name: 'music', type: 'picture', params: MUSIC_PARAMS, options: opts, label: 'Music', optional: ['dialogue'], stage: 'audio',
303
+ name: 'music', skipKind: 'none', type: 'picture', params: MUSIC_PARAMS, options: opts, label: 'Music', optional: ['dialogue'], stage: 'audio',
304
304
  install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.music': '音乐' }, en: { 'module.music': 'music' } });
305
305
  m = new Music(e, opts, ctx.track);
306
306
  ctx.track(e.events.on('session:end', () => m.stop({ fade: 0 }))); // a playthrough ends: its music stops at once
307
- e.saves.register('music', { save: () => ({ override: m._override ?? null, intensity: m.intensity }), load: d => m._load(d) });
307
+ ctx.saves.register('music', { notAtomic: 'sound, which an atomic op leaves alone: side effects go in after', save: () => ({ override: m._override ?? null, intensity: m.intensity }), load: d => m._load(d) });
308
308
  return m;
309
309
  },
310
310
  frame(dt) { m.frame(dt); },
@@ -313,3 +313,5 @@ export function music(opts = {}) {
313
313
  describe() { return { ...m.state, ready: m.ready, ruled: m.ruled, ducked: !!m._duck, tracks: m.tracks.size }; },
314
314
  };
315
315
  }
316
+
317
+ export const handRolled = 'none: a song by hand is the audio hint already';