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
@@ -14,13 +14,15 @@
14
14
  // shape 'sphere' | 'box' (can rotate) | 'cylinder' (vertical, default)
15
15
  // position center { x, y, z } / Vector3 / Object3D / [x, y, z]. For box and cylinder, y is the bottom height; if y is omitted, the ground height there is used
16
16
  // radius sphere/cylinder radius (default 1.5); size [width, height, depth] (box, default [2,2,2]); height cylinder height (default 3)
17
+ // volume your own region instead of shape: { contains({x,y,z}) -> boolean, bounds?: { min, max } } (the same plain volume addWaterBody takes); bounds
18
+ // (Box3-like) lets the zone be indexed and drawn by the debug view, without it the zone is checked every step
17
19
  // rotation box rotation around the Y axis in radians (default 0)
18
20
  // onEnter(t, who, id) / onExit(t, who, id) / onStay(dt, t, who, id) callbacks; who is the position that entered, id the world record id of who it is
19
21
  // (engine.actor for the default who, the id for an id in a custom who, object.userData.id for an Object3D, null for a bare position)
20
22
  // once fire on the first enter only (default false; exit follows at once); t.used is true afterwards, and a new playthrough (engine.session) re-arms it
21
23
  // enabled false pauses detection (handle.enabled can be changed any time)
22
24
  // tag name carried in events, for shared handling
23
- // who what can trigger: default is engine.actor (engine.actorPosition(): the player, or what engine.actor names; engine.focus without a player); or an
25
+ // who what can trigger: default is engine.actor and every seat's actor (engine.actorPosition(): the player, or what engine.actor names; engine.focus without a player); or an
24
26
  // actor id, a Vector3 / Object3D, or a function returning an array of those () => [e.actor, ...peerIds] (several actors)
25
27
  // (a zone with a function / object `who` is checked every step; zones with the default `who` cost nothing while the actor is far away)
26
28
  // cooldown seconds after leaving during which enter will not fire again (stops edge jitter from re-triggering), default 0
@@ -40,6 +42,7 @@ import { engineOwned } from '../../core/scene/things.js';
40
42
  import * as THREE from 'three';
41
43
  import { readParams, keysSchema } from '../../core/base/params.js';
42
44
  import { Cells } from '../../core/stream/cells.js';
45
+ import { codedError } from '../../core/base/errorHints.js';
43
46
  import { placeY } from '../../core/scene/ground.js';
44
47
 
45
48
  // Zones are indexed (core/stream/cells.js, the shared xz index) by the cells their bounding box covers, so a step looks at the zones near the actor instead of every
@@ -48,7 +51,7 @@ const CELL = 16, MAX_CELLS = 64, PAD = 0.01; // PAD: contains() is inclusive,
48
51
  const DEBUG_GRAY = 0x9a9a9a;
49
52
  const bySeqDesc = (a, b) => b._seq - a._seq; // the order zones have always run in: newest first
50
53
 
51
- const ADD_KEYS = ['shape', 'position', 'radius', 'size', 'height', 'rotation', 'onEnter', 'onExit', 'onStay', 'once', 'enabled', 'tag', 'who', 'cooldown', 'userData'];
54
+ const ADD_KEYS = ['shape', 'position', 'radius', 'size', 'height', 'rotation', 'onEnter', 'onExit', 'onStay', 'once', 'enabled', 'tag', 'who', 'cooldown', 'userData', 'occupancy', 'volume'];
52
55
 
53
56
  const STRINGS = {
54
57
  'zh-CN': { 'module.triggers': '触发区', 'triggers.debug': '显示触发区' },
@@ -79,13 +82,18 @@ export class Triggers {
79
82
  add(opts = {}) {
80
83
  readParams('triggers.add()', keysSchema(ADD_KEYS), opts);
81
84
  const { shape = 'cylinder', position: at = {}, radius = 1.5, size = [2, 2, 2], height = 3, rotation = 0, onEnter = null, onExit = null, onStay = null,
82
- once = false, enabled = true, tag = '', who = null, cooldown = 0, userData = {} } = opts;
85
+ once = false, enabled = true, tag = '', who = null, cooldown = 0, userData = {}, occupancy = 'zone', volume = null } = opts;
86
+ if (volume && typeof volume.contains !== 'function') throw codedError('module-params', 'triggers.add({ volume }): needs volume.contains({ x, y, z }) -> boolean and optionally bounds { min, max }');
87
+ if (occupancy !== 'zone' && occupancy !== 'each') throw codedError('module-params', `triggers.add({ occupancy }): 'zone' (default: one enter when the first actor arrives, one exit when the last leaves) or 'each' (an enter and an exit per actor); got ${JSON.stringify(occupancy)}`);
88
+ if (!(radius >= 0 && Number.isFinite(radius))) throw codedError('module-params', `triggers.add({ radius }): must be a finite number >= 0, got ${radius}`); // NaN never matched and sat in the cell index
83
89
  const position = at.isObject3D ? at.position : Array.isArray(at) ? { x: at[0], y: at[1], z: at[2] } : at;
84
90
  const e = this.engine, x = position.x ?? 0, z = position.z ?? 0;
85
- const y = position.y ?? placeY(e, 'triggers.add()', x, z);
91
+ const y = position.y ?? (volume ? 0 : placeY(e, 'triggers.add()', x, z)); // a volume carries its own place
92
+ // a volume with bounds is indexed and drawn as its bounding box (the shape of a box with rotation 0); contains() stays the volume's own
93
+ const bb = volume?.bounds, box = bb ? { x: (bb.min.x + bb.max.x) / 2, y: bb.min.y, z: (bb.min.z + bb.max.z) / 2, size: [bb.max.x - bb.min.x, bb.max.y - bb.min.y, bb.max.z - bb.min.z] } : null;
86
94
  const t = {
87
- shape, x, y, z, radius, hx: size[0] / 2, hy: size[1] / 2, hz: size[2] / 2, sy: size[1], height, rotation,
88
- c: Math.cos(rotation), s: Math.sin(rotation), onEnter, onExit, onStay, once, enabled, tag, who, cooldown, userData,
95
+ shape: volume ? 'volume' : shape, volume, x: box?.x ?? x, y: box?.y ?? y, z: box?.z ?? z, radius, hx: (box?.size ?? size)[0] / 2, hy: (box?.size ?? size)[1] / 2, hz: (box?.size ?? size)[2] / 2, sy: (box?.size ?? size)[1], height, rotation,
96
+ c: Math.cos(rotation), s: Math.sin(rotation), onEnter, onExit, onStay, once, enabled, tag, who, cooldown, userData, occupancy, _in: null,
89
97
  inside: false, used: false, _cool: 0, _mesh: null, _gone: false,
90
98
  remove: () => this._remove(t),
91
99
  contains: p => this._contains(t, p),
@@ -97,21 +105,23 @@ export class Triggers {
97
105
  }
98
106
 
99
107
  _remove(t) { // remove only through the handle t.remove(); zones still occupied send exit first (so music areas and content onExit can clean up)
100
- const i = this._list.indexOf(t); if (i < 0) return;
101
- if (t.inside) this._exit(t, null);
102
- this._list.splice(i, 1); this._unregister(t); this._busy.delete(t);
108
+ if (t._gone) return;
109
+ // leave the books first: onExit may call t.remove() again or add / remove other zones, so no index taken before the callback is used after it (M08)
103
110
  t._gone = true;
111
+ const i = this._list.indexOf(t); if (i >= 0) this._list.splice(i, 1);
112
+ this._unregister(t); this._busy.delete(t);
113
+ if (t.inside) this._exit(t, null);
104
114
  if (t._mesh) { t._mesh.parent?.remove(t._mesh); t._mesh.geometry.dispose(); t._mesh = null; }
105
115
  }
106
116
  _register(t) {
107
- if (t.who) { this._global.push(t); return; }
108
- const ex = (t.shape === 'box' ? t.hx * Math.abs(t.c) + t.hz * Math.abs(t.s) : t.radius) + PAD;
109
- const ez = (t.shape === 'box' ? t.hx * Math.abs(t.s) + t.hz * Math.abs(t.c) : t.radius) + PAD;
117
+ if (t.who || (t.volume && !t.volume.bounds)) { this._global.push(t); return; }
118
+ const ex = (t.shape === 'box' || t.volume ? t.hx * Math.abs(t.c) + t.hz * Math.abs(t.s) : t.radius) + PAD;
119
+ const ez = (t.shape === 'box' || t.volume ? t.hx * Math.abs(t.s) + t.hz * Math.abs(t.c) : t.radius) + PAD;
110
120
  t._span = this._cells.cover(t, t.x - ex, t.z - ez, t.x + ex, t.z + ez, MAX_CELLS);
111
121
  if (!t._span) this._global.push(t);
112
122
  }
113
123
  _unregister(t) {
114
- if (t._span) this._cells.uncover(t); else this._global.splice(this._global.indexOf(t), 1);
124
+ if (t._span) this._cells.uncover(t); else { const i = this._global.indexOf(t); if (i >= 0) this._global.splice(i, 1); }
115
125
  }
116
126
  /** All trigger zones (a new array) */
117
127
  list() { return [...this._list]; }
@@ -147,6 +157,7 @@ export class Triggers {
147
157
  }
148
158
 
149
159
  _contains(t, p) {
160
+ if (t.volume) return !!t.volume.contains(p);
150
161
  const dx = p.x - t.x, dy = p.y - t.y, dz = p.z - t.z;
151
162
  if (t.shape === 'sphere') return dx * dx + dy * dy + dz * dz <= t.radius * t.radius;
152
163
  if (t.shape === 'box') {
@@ -160,7 +171,8 @@ export class Triggers {
160
171
  _defaultWho() {
161
172
  const e = this.engine;
162
173
  this._one[0] = e.actorPosition(); // engine.actor: the player by default, or the vehicle / squad member the game handed control to
163
- this._ids.length = 1; this._ids[0] = e.actor;
174
+ this._one.length = this._ids.length = 1; this._ids[0] = e.actor;
175
+ for (const s of e.input.seats) if (s.actor && s.actor !== e.actor) { this._one.push(e.actorPosition(s.actor)); this._ids.push(s.actor); } // every local player, as interactions and pickups
164
176
  return this._one;
165
177
  }
166
178
 
@@ -201,6 +213,7 @@ export class Triggers {
201
213
  else { ps.push(x); ids.push(null); }
202
214
  }
203
215
  }
216
+ if (t.occupancy === 'each') return this._visitEach(t, dt, ps, ids);
204
217
  let hit = null, id = null;
205
218
  if (ps) for (let k = 0; k < ps.length; k++) { const p = ps[k]; if (p && this._contains(t, p)) { hit = p; id = ids[k] ?? null; break; } }
206
219
  if (hit && !t.inside) {
@@ -212,6 +225,27 @@ export class Triggers {
212
225
  } else if (!hit && t.inside) this._exit(t, null);
213
226
  else if (hit && t.inside) t.onStay?.(dt, t, hit, id);
214
227
  }
228
+ /** @internal occupancy 'each': every actor in the zone enters, stays and exits on its own; t.inside is true while anyone is in. Cooldown runs from when the zone empties */
229
+ _visitEach(t, dt, ps, ids) {
230
+ const e = this.engine, inn = t._in ??= new Map(), now = new Map();
231
+ if (ps) for (let k = 0; k < ps.length; k++) { const p = ps[k]; if (p && this._contains(t, p)) now.set(ids[k] ?? p, { p, id: ids[k] ?? null }); }
232
+ for (const [key, o] of inn) if (!now.has(key)) { inn.delete(key); this._left(t, null, o.id); if (t._gone) return; }
233
+ if (t.inside && !inn.size) { t.inside = false; t._cool = t.cooldown; }
234
+ for (const [key, o] of now) {
235
+ if (inn.has(key)) { t.onStay?.(dt, t, o.p, o.id); if (t._gone) return; continue; }
236
+ if (t._cool > 0 && !inn.size) return;
237
+ inn.set(key, o); t.inside = true;
238
+ t.onEnter?.(t, o.p, o.id);
239
+ e.events.emit('trigger:enter', { tag: t.tag, trigger: t, who: o.p, id: o.id });
240
+ if (t._gone) return;
241
+ if (t.once) { t.used = true; this._exit(t, null); return; }
242
+ }
243
+ }
244
+ /** @internal one actor left: the callback and the event */
245
+ _left(t, who, id) {
246
+ t.onExit?.(t, who, id);
247
+ this.engine.events.emit('trigger:exit', { tag: t.tag, trigger: t, who, id });
248
+ }
215
249
  /** @internal each zone's save key: tag (or '(shape)') plus its order among zones with that label, so code that adds the same zones gets the same keys */
216
250
  _keys() {
217
251
  const n = new Map();
@@ -235,10 +269,10 @@ export class Triggers {
235
269
  }
236
270
  _exit(t, who) {
237
271
  // id: who was inside (remembered at enter), so an exit says who left even though the position that left is gone
238
- const id = t._id ?? null;
272
+ const id = t._id ?? null, all = t._in ? [...t._in.values()] : null;
239
273
  t.inside = false; t._cool = t.cooldown; t._id = null;
240
- t.onExit?.(t, who, id);
241
- this.engine.events.emit('trigger:exit', { tag: t.tag, trigger: t, who, id });
274
+ if (all) { t._in.clear(); for (const o of all) this._left(t, who, o.id); return; } // occupancy 'each': everyone leaves
275
+ this._left(t, who, id);
242
276
  }
243
277
 
244
278
  // ---------- debug view 'triggers' ----------
@@ -260,9 +294,10 @@ export class Triggers {
260
294
  };
261
295
  }
262
296
  _addDebugMesh(t) {
297
+ if (t.volume && !t.volume.bounds) return; // nothing to draw without bounds
263
298
  let geo;
264
299
  if (t.shape === 'sphere') geo = new THREE.SphereGeometry(t.radius, 12, 8);
265
- else if (t.shape === 'box') geo = new THREE.BoxGeometry(t.hx * 2, t.sy, t.hz * 2).translate(0, t.sy / 2, 0);
300
+ else if (t.shape === 'box' || t.volume) geo = new THREE.BoxGeometry(t.hx * 2, t.sy, t.hz * 2).translate(0, t.sy / 2, 0);
266
301
  else geo = new THREE.CylinderGeometry(t.radius, t.radius, t.height, 16, 1, true).translate(0, t.height / 2, 0);
267
302
  const lines = new THREE.LineSegments(new THREE.WireframeGeometry(geo), this._mat);
268
303
  geo.dispose();
@@ -278,17 +313,47 @@ const TRIGGER_PARAMS = {
278
313
  debugOpacity: { type: 'number', default: 0.8, desc: "line opacity of the debug view 'triggers'" },
279
314
  };
280
315
 
316
+ /**
317
+ * The triggers section of content data: fromLevel = the level's trigger_<tag> marker, otherwise placed by position. Enter / exit effects look up the merged table,
318
+ * and the listener is attached only once. They act for whoever crossed the zone (a { give } lands in that actor's bag); a zone emptied by removal has no id: engine.actor
319
+ */
320
+ function triggerContent() {
321
+ const table = {};
322
+ let subs = null;
323
+ return {
324
+ desc: 'trigger zones (tag -> position / from level, enter/exit effects)',
325
+ undo(d, { engine: e }) {
326
+ const had = new Set(e.triggers._list), was = { ...table };
327
+ return () => {
328
+ for (const t of [...e.triggers._list]) if (!had.has(t)) t.remove();
329
+ for (const tag of Object.keys(table)) delete table[tag];
330
+ Object.assign(table, was);
331
+ };
332
+ },
333
+ commit(d, { engine: e, content, where, bind, track }) {
334
+ Object.assign(table, d);
335
+ if (Object.values(d).some(t => t.fromLevel)) e.triggers.fromMarkers();
336
+ for (const [tag, t] of Object.entries(d)) if (!t.fromLevel) bind(e.triggers.add({ ...t, tag, position: where(t.position), onEnter: null, onExit: null }), t.position);
337
+ subs ??= [
338
+ track(e.events.on('trigger:enter', ({ tag, id }) => content.run(table[tag]?.onEnter, { actor: id ?? e.actor }))),
339
+ track(e.events.on('trigger:exit', ({ tag, id }) => content.run(table[tag]?.onExit, { actor: id ?? e.actor }))),
340
+ ];
341
+ },
342
+ };
343
+ }
344
+
281
345
  /** Trigger zone module. Provides engine.triggers once installed. Optional dependency: level (used by fromMarkers) */
282
346
  export function triggers(opts = {}) {
283
347
  const o = readParams('triggers', TRIGGER_PARAMS, opts);
284
348
  let tr = null;
285
349
  return {
286
- name: 'triggers', type: 'rules', label: 'Triggers', params: TRIGGER_PARAMS, options: o, noSkip: 'zone enter/exit is re-evaluated on the next fixed step', optional: ['level'], stage: 'gameplay', after: ['interactions'],
350
+ content: { triggers: triggerContent() },
351
+ name: 'triggers', skipKind: 'none', type: 'rules', label: 'Triggers', params: TRIGGER_PARAMS, options: o, noSkip: 'zone enter/exit is re-evaluated on the next fixed step', optional: ['level'], stage: 'gameplay', after: ['interactions'],
287
352
  install(e, ctx) {
288
353
  tr = new Triggers(e, o, ctx.track);
289
354
  // audio rule condition { zone: 'cave' | ['cave', 'mine'] }: some trigger zone with that tag is occupied
290
355
  ctx.track(e.audio.condition('zone', v => [].concat(v).some(tag => tr.byTag(tag).some(t => t.inside))));
291
- e.saves.register('triggers', { save: () => tr._save(), load: d => tr._load(d) });
356
+ ctx.saves.register('triggers', { notAtomic: 'bodies crossing a zone change it in the step, and its load fires exits', save: () => tr._save(), load: d => tr._load(d) });
292
357
  return tr;
293
358
  },
294
359
  fixed(dt) { tr.update(dt); },
@@ -301,3 +366,5 @@ export function triggers(opts = {}) {
301
366
  },
302
367
  };
303
368
  }
369
+
370
+ export const handRolled = 'none: a zone check by hand is the same maths as any distance or box test';
@@ -52,13 +52,14 @@ function slotOf(r, id) {
52
52
  const REMOVE_KEYS = ['regrowSeconds'];
53
53
 
54
54
  export class Vegetation {
55
- constructor(engine, opts = {}) {
55
+ constructor(engine, opts = {}, ctx) {
56
56
  this.engine = engine; this.species = new Map();
57
57
  // where it grows: on terrain chunks when the terrain module is installed (placed in its workers), else on vegetation's own chunks over
58
58
  // whatever provides the ground (a level, a code-built ground, flat). Both hosts keep chunks of one shape, so everything below is shared
59
59
  if (engine.terrain && Object.keys(opts).length) throw codedError('vegetation-option', `vegetation({ ${Object.keys(opts).join(', ')} }): with terrain() installed vegetation grows on the terrain chunks, and density / view distance are terrain options (terrain({ density, viewChunks })). The vegetation() options are for ground without terrain (a level, a code-built ground)`);
60
60
  /** @internal the draw parts drawing the plants (view()) */ this.views = new Set();
61
61
  /** @internal the chunk table vegetation lives in: engine.terrain, or its own GroundChunks */
62
+ /** @internal what its chunks live on: terrain, or its own ground chunks. The settings menu sizes the view through it */
62
63
  this.host = engine.terrain ?? new GroundChunks(engine, this, opts);
63
64
  // on terrain: this is the terrain's planter (it calls mount / unmount / drop / ring; terrain never reads engine.vegetation); a chunk's
64
65
  // visibility comes from the terrain data part, so a game that replaces the terrain drawing keeps its trees
@@ -72,8 +73,8 @@ export class Vegetation {
72
73
  this._initDone = false; // set when init has waited for _pending: an image of a species added later is not awaited, so its error is caught where it is added
73
74
  // dev asset hot swap (core/assets/assetHot.js): a species made from a swapped model is added again with the new geometry / materials. Why here and
74
75
  // not in the generic scene walk: a species' materials are patched copies (wind, season) and its geometry may be merged from a model
75
- engine.assets.onSwap?.(s => this._swapped(s));
76
- engine.saves.register('vegetation', {
76
+ ctx.track(engine.assets.onSwap(s => this._swapped(s)));
77
+ ctx.saves.register('vegetation', { notAtomic: 'its load redraws the instances it hides: not plain data a rollback restores by itself',
77
78
  save: () => {
78
79
  const removed = {};
79
80
  for (const [ck, m] of this._removed) { for (const [id, until] of m) removed[`veg:${ck}:${id}`] = until; }
@@ -18,12 +18,27 @@ import { EFFECTS, hashText } from '../../render/effects.js';
18
18
  import { codedError } from '../../core/base/errorHints.js';
19
19
  import { isWebGPU } from '../../render/backend.js';
20
20
  import { nearFadePatch } from './nearFade.js';
21
+ import { scatterAttempts } from '../../core/stream/scatter.js';
21
22
 
22
23
  const COLOR = 'vegetationColor'; // the patch name of vegetation.color() on every species' material
23
24
  // The wind patch in engine.vegetation.patches has one amplitude: a shared material cannot carry each species' own (those are define()'s wind option)
24
25
  const SHARED_SWAY = 0.05;
25
26
  const code = v => (typeof v === 'string' ? { glsl: v } : v);
26
27
 
28
+ /**
29
+ * How many instances of a placement to draw at a density. A plant with a collider is placed in full at every quality, so collision and felled ids stay the same world, and low
30
+ * quality thins only its drawing. Why a count and not a filter: ids rise in placement order, so the plants a density keeps are the front of the list, the same ones it kept when
31
+ * it thinned placement, and the instances behind just are not drawn. A blocker that is not drawn still blocks. rule.positions are the game's own and never thin.
32
+ * @internal
33
+ */
34
+ export function drawnPlants(rule, r, density) {
35
+ if (!rule?.collider || rule.positions) return r.n;
36
+ const keep = scatterAttempts(rule, density);
37
+ let n = r.n;
38
+ while (n > 0 && r.ids[n - 1] >= keep) n--;
39
+ return n;
40
+ }
41
+
27
42
  export class VegetationDraw {
28
43
  /** @param {any} e @param {any} v the vegetation data part (engine.vegetation) */
29
44
  constructor(e, v) {
@@ -148,6 +163,7 @@ export class VegetationDraw {
148
163
  a.set(r.m);
149
164
  if (hid) for (const i of hid) if (i < r.n) a.fill(0, i * 16, i * 16 + 16);
150
165
  im.instanceMatrix.needsUpdate = true;
166
+ im.count = drawnPlants(sp.rule, r, this.v.host.density);
151
167
  if (c.ring != null) this._level(im, sp, k, c.ring);
152
168
  }
153
169
 
@@ -7,6 +7,7 @@
7
7
  // Collision circles take effect at the tick engine.commits sets (lag by ring, built on the spot if still pending): machine speed never
8
8
  // changes whether the player bumps into a tree, the same contract as terrain chunks.
9
9
  // The ground changing (setGround, a level loaded or switched: ground.staticVersion) rebuilds every chunk.
10
+ import { follows } from '../../core/base/follows.js';
10
11
  import * as THREE from 'three';
11
12
  import { makePlacer, makeNoise } from '../../core/stream/scatter.js';
12
13
  import { ChunkStream, bookCollision, collidersNear, ringsReady } from '../../core/stream/chunkStream.js';
@@ -18,12 +19,12 @@ export class GroundChunks {
18
19
  constructor(engine, veg, opts = {}) {
19
20
  const { chunkSize, viewChunks, density, seed, area = null } = { ...GROUND_DEFAULTS, ...opts };
20
21
  this.engine = engine; this.veg = veg;
21
- this.chunkSize = chunkSize; this.viewChunks = viewChunks; this.density = density; this.area = area; this.seed = seed;
22
+ this.chunkSize = chunkSize; this._viewChunks = viewChunks; this._density = density; this.area = area; this.seed = seed;
22
23
  this.chunks = new Map();
23
24
  this.applyBudgetMs = 3; // max ms per frame spent placing and uploading chunks once playing (loading builds ring 1 at once)
24
25
  this.gen = 0;
25
26
  this.stats = { loaded: 0, visible: 0, instances: 0, queued: 0 };
26
- this._want = []; this._ground = null; this._groundVer = undefined;
27
+ this._want = []; this._ground = follows(() => engine.ground, G => G.staticVersion?.());
27
28
  // which chunks the sources need, ring, culling: the same helper as the terrain chunks (core/stream/chunkStream.js), so both rings mean the same
28
29
  this._stream = new ChunkStream(this, { show: (c, v) => this.veg._emit('show', c, v), level: (c, ring) => this._setLevel(c, ring),
29
30
  count: (c, ring) => { let n = 0; for (const k in c.plants) { const sp = this.veg.get(k); if (sp && ring <= sp.maxRing) n += c.plants[k].n; } return n; },
@@ -49,7 +50,8 @@ export class GroundChunks {
49
50
  /** @internal vegetation / settings plumbing */
50
51
  refreshLevels() { for (const c of this.chunks.values()) c.level = -1; }
51
52
  /** Rings of chunks drawn around each stream source (the settings page's view distance); the next update loads / releases chunks to match */
52
- setViewChunks(n) { this.viewChunks = n; this.refreshLevels(); }
53
+ get viewChunks() { return this._viewChunks; }
54
+ set viewChunks(n) { this._viewChunks = n; this.refreshLevels(); }
53
55
  /** Drop every chunk; they are placed again around the stream sources (call it after changing the ground behind the same provider) */
54
56
  rebuild() {
55
57
  this._stream.drop();
@@ -59,8 +61,9 @@ export class GroundChunks {
59
61
  * Vegetation density multiplier: the loaded chunks are placed again in place, each species replacing its own plants and collision circles,
60
62
  * so trees never go missing in between (dropping the chunks left them without collision until rebuilt)
61
63
  */
62
- setDensity(d) {
63
- this.density = d;
64
+ get density() { return this._density; }
65
+ set density(d) {
66
+ this._density = d;
64
67
  for (const c of this.chunks.values()) if (c.state === 'ready') for (const sp of this.veg.list()) if (!sp.nearOnly || c.plants[sp.name]) this._grow(c, sp);
65
68
  }
66
69
 
@@ -77,8 +80,8 @@ export class GroundChunks {
77
80
 
78
81
  /** @internal module frame hook: follow the ground, queue / release chunks around the sources, build within budget, LOD and culling */
79
82
  update(sources, camera) {
80
- const e = this.engine, G = e.ground, ver = G.staticVersion?.();
81
- if (G !== this._ground || ver !== this._groundVer) { this._ground = G; this._groundVer = ver; this.rebuild(); }
83
+ const e = this.engine;
84
+ this._ground.sync(() => this.rebuild());
82
85
  this._stream.follow(sources, this.chunkSize, this.viewChunks); // queue what a source needs, release what is far from all
83
86
  const t0 = performance.now(), loading = !e.ready; // measure: placement budget
84
87
  while (this._want.length) {
@@ -2,6 +2,8 @@
2
2
  // felled trees; Vegetation.js) and 'vegetationDraw' (instanced meshes, wind, fade, LOD; draw.js, slot 'vegetation-draw').
3
3
  // Why two: collision, paths and felling read only the data, so engine.use(myPlants, { replaces: 'vegetation-draw' }) swaps every pixel
4
4
  // of the plants and keeps all of play.
5
+ import { vegetationModel } from '../../core/assets/namedModel.js';
6
+ import { reportError } from '../../core/base/errors.js';
5
7
  import { readParams, keysSchema } from '../../core/base/params.js';
6
8
  import { Vegetation } from './Vegetation.js';
7
9
  import { VegetationDraw } from './draw.js';
@@ -10,6 +12,23 @@ import { codedError } from '../../core/base/errorHints.js';
10
12
 
11
13
  const OPTS = ['chunkSize', 'viewChunks', 'density', 'area', 'seed'];
12
14
  const VEG_PARAMS = keysSchema(OPTS, GROUND_DEFAULTS); // defaults of the own-chunks mode (without terrain)
15
+ /**
16
+ * The vegetation section of content data: model names resolve through vegetationModel, the same resolver vegetation.define uses for a name. All kinds register at
17
+ * the same moment once all models are ready, since each registration rebuilds terrain chunks. One model that fails does not stop the others.
18
+ * The models are made in commit, not prepare: nothing stands on vegetation, so the rest of a pack does not wait for them
19
+ */
20
+ const VEGETATION_CONTENT = {
21
+ desc: 'vegetation (name -> model, growth rule)',
22
+ // taken back while its models were still generating. On what this load prepared, not on the table: the same table loaded again is a new load
23
+ prepare: table => ({ table, undone: false }),
24
+ undo: load => () => { load.undone = true; },
25
+ commit: (load, { engine: e }) => Promise.all(Object.entries(load.table).map(([name, { model: m, lod, ...rest }]) =>
26
+ Promise.all([vegetationModel(e, m), lod && vegetationModel(e, lod)])
27
+ .then(([main, low]) => [name, { ...rest, ...main, ...(low && { lodGeometry: low.model ?? low.geometry }) }])
28
+ .catch(err => { reportError(e, err, `content vegetation ${name}: model generation`, { soft: true }); return null; })))
29
+ .then(list => { if (!load.undone) for (const v of list) if (v) e.vegetation.define(v[0], v[1]); }),
30
+ };
31
+
13
32
  /**
14
33
  * Vegetation module. Provides engine.vegetation.define(name, {...}) once installed.
15
34
  * With terrain() installed first it grows on the terrain chunks and takes no options (density and view distance are terrain options).
@@ -30,16 +49,16 @@ const VEG_PARAMS = keysSchema(OPTS, GROUND_DEFAULTS); // defaults of the own-c
30
49
  */
31
50
  export function vegetation(opts = {}) {
32
51
  readParams('vegetation', VEG_PARAMS, opts);
33
- let v = null, own = null, cols = null, ready = null, drawPart = null;
34
- const data = { name: 'vegetation', type: 'world', provides: ['vegetation'], label: 'Vegetation', params: VEG_PARAMS, options: opts, stage: 'ground', after: ['terrain', 'level'], optional: ['terrain', 'level'],
52
+ let v = null, own = null, drawPart = null;
53
+ const data = { content: { vegetation: VEGETATION_CONTENT }, name: 'vegetation', skipKind: 'approx', type: 'world', provides: ['vegetation'], label: 'Vegetation', params: VEG_PARAMS, options: opts, stage: 'ground', after: ['terrain', 'level'], optional: ['terrain', 'level', 'settings'],
35
54
  install(e, ctx) {
36
55
  e.i18n.add({ 'zh-CN': { 'module.vegetation': '植被' }, en: { 'module.vegetation': 'vegetation' } });
37
- v = new Vegetation(e, opts);
56
+ v = new Vegetation(e, opts, ctx);
38
57
  ctx.track(e.events.on('settings:shadows', () => v.host.refreshLevels())); // whichever chunks it grows on: each level pass rereads the shadow switch
39
58
  if (v.host !== e.terrain) {
40
59
  own = v.host;
41
- cols = e.addGroundColliders((x, z, range, fn) => own.forEachCollider(x, z, range, fn)); // collision and path planning see the trees
42
- ready = e.stream.addReadyCheck('vegetation', s => own.readyAt(s));
60
+ ctx.ground.addColliders((x, z, range, fn) => own.forEachCollider(x, z, range, fn)); // collision and path planning see the trees
61
+ ctx.stream.addReadyCheck('vegetation', s => own.readyAt(s));
43
62
  }
44
63
  return v;
45
64
  },
@@ -48,15 +67,17 @@ export function vegetation(opts = {}) {
48
67
  critical: true,
49
68
  async init(e) {
50
69
  if (own && e.terrain) throw codedError('module-requires', 'vegetation() was installed before terrain(): put terrain() first, vegetation then grows on its chunks');
70
+ // over a level or a code-built ground these chunks are the only ones: their rows are this module's to offer (on terrain, the terrain's)
71
+ if (own) e.settings?.define('viewChunks', own.viewChunks, n => { if (own.viewChunks !== n) own.viewChunks = n; }).define('density', own.density, n => { if (own.density !== n) own.density = n; });
51
72
  await v.whenLoaded(); // densityMap.url images of species added before start
52
73
  },
53
74
  frame(dt, e) { own?.update(e.stream.sources(), e.camera); },
54
75
  fixed(dt) { v.tick(dt); }, skip(dt, e, done) { if (done) v.tick(1); },
55
76
  describe(e, ctx) { if (own) ctx.out.perf.vegetation = { loaded: own.stats.loaded, visible: own.stats.visible, queued: own.stats.queued }; },
56
- dispose(e) { own?.dispose(); cols?.remove(); ready?.remove(); v?._view?.remove(); v?._planter?.remove(); } };
77
+ dispose(e) { own?.dispose(); v?._view?.remove(); v?._planter?.remove(); } };
57
78
  const lookModule = {
58
79
  // the same vegetation({...}) call (its options are the data part's; the draw part reads the species' define() options)
59
- name: 'vegetationDraw', type: 'picture', label: 'Vegetation drawing', params: VEG_PARAMS, options: opts, requires: ['vegetation'], provides: ['vegetation-draw'], stage: 'effects',
80
+ name: 'vegetationDraw', skipKind: 'none', type: 'picture', label: 'Vegetation drawing', params: VEG_PARAMS, options: opts, requires: ['vegetation'], provides: ['vegetation-draw'], stage: 'effects',
60
81
  install(e) { e.i18n.add({ 'zh-CN': { 'module.vegetationDraw': '植被外观' }, en: { 'module.vegetationDraw': 'vegetation drawing' } }); drawPart = new VegetationDraw(e, v); return drawPart; },
61
82
  frame() { drawPart.updateFade(); },
62
83
  describe() { return { chunks: drawPart?.meshes.size ?? 0 }; },
@@ -64,3 +85,5 @@ export function vegetation(opts = {}) {
64
85
  };
65
86
  return [data, lookModule];
66
87
  }
88
+
89
+ export const handRolled = 'none: plants of its own are plain three.js, used on purpose';
@@ -86,7 +86,7 @@ export class Water {
86
86
  }
87
87
 
88
88
  /** One water mesh out of the scene. The material is shared by all water, so not engine.remove (which would dispose it); the ray registration goes too @internal */
89
- _drop(m) { const e = this.engine; e.detach(m); e.rays.forget(m); this._uv.delete(m); m.geometry.dispose(); }
89
+ _drop(m) { const e = this.engine; m.removeFromParent(); e.rays.forget(m); this._uv.delete(m); m.geometry.dispose(); }
90
90
  /** The module goes: its meshes and what it made leave with it; a game's material stays the game's @internal */
91
91
  dispose() {
92
92
  for (const m of [this.sea, ...this.bodies.values()]) if (m) this._drop(m);
@@ -142,6 +142,7 @@ export class Water {
142
142
  if ((name ?? null) !== n.name) {
143
143
  n.name = name ?? null;
144
144
  const t = name ? placeholderTexture('normal') : null;
145
+ this.normalTexture?.dispose(); // the one this replaces: the engine made it, so it frees it (its asset callback ignores it from now on)
145
146
  this.normalTexture = own.normalMap = t;
146
147
  own.needsUpdate = true;
147
148
  if (t) {
@@ -191,6 +192,7 @@ export class Water {
191
192
  }
192
193
  /** @internal */
193
194
  _addBody(b) {
195
+ if (b.query) return; // the game's own water (addWaterBody({ query })): it draws the mesh
194
196
  const seg = Math.max(4, Math.round((b.radius ? b.radius * 2 : Math.max(b.hw, b.hd) * 2) / this.cell));
195
197
  const geo = b.radius ? new THREE.CircleGeometry(b.radius, Math.max(16, seg * 2)).rotateX(-Math.PI / 2) : new THREE.PlaneGeometry(b.hw * 2, b.hd * 2, seg, seg).rotateX(-Math.PI / 2);
196
198
  const m = new THREE.Mesh(geo, this._material);
@@ -235,7 +237,7 @@ export class Water {
235
237
  export function water(opts = {}) {
236
238
  readParams('water', WATER_PARAMS, opts);
237
239
  let w = null;
238
- return { name: 'water', type: 'picture', label: 'Water', params: WATER_PARAMS, options: opts, stage: 'environment', after: ['sky'], optional: ['sky'], install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.water': '水面' }, en: { 'module.water': 'water' } }); w = new Water(e, opts, ctx.track); return w; }, frame(dt, e) { w.update(e.focus, dt); }, dispose() { w.dispose(); },
240
+ return { name: 'water', skipKind: 'none', type: 'picture', label: 'Water', params: WATER_PARAMS, options: opts, stage: 'environment', optional: ['sky'], install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.water': '水面' }, en: { 'module.water': 'water' } }); w = new Water(e, opts, ctx.track); return w; }, frame(dt, e) { w.update(e.focus, dt); }, dispose() { w.dispose(); },
239
241
  // "is there water where I think": the global sea (its level and plane size; null = none, e.g. no water level) and each separate body
240
242
  describe() {
241
243
  const r = v => Math.round(v * 10) / 10, s = w.sea;
@@ -243,3 +245,5 @@ export function water(opts = {}) {
243
245
  return { sea: s ? { level: r(s.position.y + 0.2), size: w.st.size } : null, bodies };
244
246
  } };
245
247
  }
248
+
249
+ export const handRolled = 'none: water of its own is plain three.js, used on purpose';
@@ -8,7 +8,7 @@
8
8
  // so a game can swap the picture without touching the weather a save restores.
9
9
  //
10
10
  // engine.weather.set('rain', { seconds: 20 }) // turn to rain over 20 seconds
11
- // engine.weather.setAuto(true) // change weather at random (uses engine.random, so step/tests are reproducible and saved)
11
+ // engine.weather.auto = true // change weather at random (uses engine.random, so step/tests are reproducible and saved)
12
12
  // Weather display names live in the string table as weather.<name> (describe and the debug panel use them); a game that adds a new weather adds its name with
13
13
  // i18n.add.
14
14
  import * as THREE from 'three';
@@ -18,6 +18,8 @@ import { STRINGS, ERR } from './strings.js';
18
18
  import { codedError } from '../../core/base/errorHints.js';
19
19
  import { STEP } from '../../core/time/time.js';
20
20
  import { weatherDrawModule } from './weatherDraw.js';
21
+ import { isPlainObject } from '../../core/base/util.js';
22
+ import { saveNumberOk, saveValues, SAVE_MAX_SECONDS } from '../../core/base/saveValues.js';
21
23
  /** @import { ModuleDef } from '../../types/core' */
22
24
  /** @import { WeatherName, WeatherPreset, WeatherOptions, WeatherParticles, WeatherParticleSystem } from '../../types/world' */
23
25
 
@@ -117,17 +119,11 @@ export class Weather {
117
119
  }
118
120
 
119
121
  /**
120
- * Automatic weather on/off. Writing it takes effect like setAuto.
122
+ * Automatic weather on/off.
121
123
  * @type {boolean}
122
124
  */
123
125
  get auto() { return this._auto; }
124
126
  set auto(on) { this._auto = on; if (on) this.autoTimer = 0; }
125
- /**
126
- * Automatic weather on/off
127
- * @param {boolean} on
128
- * @returns {void}
129
- */
130
- setAuto(on) { this.auto = on; }
131
127
 
132
128
  /**
133
129
  * Switch weather. seconds: transition seconds, default 15; 0 switches at once (current is the new weather before the next step, so a
@@ -145,7 +141,7 @@ export class Weather {
145
141
  if (!p) { warnMissing('weather', name, Object.keys(this.types)); return; }
146
142
  const from = this.name;
147
143
  if (!(seconds >= 0 && Number.isFinite(seconds))) throw codedError('weather-option', `weather.set('${name}', { seconds }) takes seconds >= 0 (0 = at once); got ${seconds}`);
148
- this.name = name; this.from = { ...this.current }; this.to = { ...p }; this.t = 0; this.dur = seconds;
144
+ this.name = name; this.from = { ...this.current }; this.to = { ...p }; this.t = 0; this.dur = Math.max(seconds, 0.01); // the least a load accepts: a blend divides by it, and the save must read the same after a load
149
145
  // seconds 0: land now, not on the next fixed step (a shot or test right after the call saw the old weather, or 1/3 of a short blend)
150
146
  if (seconds === 0) { this.t = 1; for (const key in this.to) this.current[key] = this.to[key]; }
151
147
  // once per change of name (the blend then runs over `seconds`); setting the same weather again is not a change
@@ -200,23 +196,26 @@ export function weather(opts = {}) {
200
196
  readParams('weather', WEATHER_PARAMS, opts);
201
197
  let w = null;
202
198
  const state = {
203
- name: 'weather', type: 'world', provides: ['weather'], label: 'Weather', params: WEATHER_PARAMS, options: opts, stage: 'environment', before: ['sky'],
204
- install(e) {
199
+ name: 'weather', skipKind: 'step', type: 'world', provides: ['weather'], label: 'Weather', params: WEATHER_PARAMS, options: opts, stage: 'environment', before: ['sky'],
200
+ install(e, ctx) {
205
201
  e.i18n.add(STRINGS);
206
202
  w = new Weather(e, opts);
207
203
  if (opts.auto) w.auto = true;
208
204
  // the transition is saved too (current / from / to / t / dur): a save made 30% into sun -> rain loads 30% in, not as full rain, and fires no
209
205
  // weather:change (nothing changed for the player). A damaged part, or a weather the game no longer has, loads as a finished switch to that name
210
- e.saves.register('weather', {
206
+ ctx.saves.register('weather', { notAtomic: 'moves on its own timers like the calendar: an op that sets it means it to stay',
211
207
  save: () => ({ name: w.name, auto: w.auto, autoTimer: w.autoTimer, nextBolt: w.nextBolt, current: { ...w.current }, from: { ...w.from }, to: { ...w.to }, t: w.t, dur: w.dur }),
212
208
  load: d => {
213
209
  if (!d) return;
214
- if (Number.isFinite(d.t) && d.current && d.from && d.to && w.types[d.name]) {
210
+ const s = saveValues('weather'), most = { min: 0, max: SAVE_MAX_SECONDS };
211
+ const fields = v => isPlainObject(v) && Object.values(v).every(saveNumberOk); // every blended field is a finite number: one NaN would spread to the sky, fog and sound
212
+ if (Number.isFinite(d.t) && fields(d.current) && fields(d.from) && fields(d.to) && w.types[d.name]) {
215
213
  // over the type's own fields: a save older than a field the table has now would blend it from undefined (NaN)
216
214
  const full = v => ({ ...w.types[d.name], ...v });
217
- w.name = d.name; w.current = full(d.current); w.from = full(d.from); w.to = full(d.to); w.t = d.t; w.dur = Math.max(0.01, d.dur ?? 1);
215
+ w.name = d.name; w.current = full(d.current); w.from = full(d.from); w.to = full(d.to); w.t = s.num(d.t, 't', { min: 0, max: 1, fallback: 1 }); w.dur = s.num(d.dur ?? 1, 'dur', { ...most, min: 0.01, fallback: 1 });
218
216
  } else w.set(d.name, { seconds: 0 });
219
- w.auto = d.auto; w.autoTimer = d.autoTimer ?? 0; w.nextBolt = d.nextBolt ?? w.lightningFirst;
217
+ w.auto = d.auto === true; w.autoTimer = s.num(d.autoTimer ?? 0, 'autoTimer', { ...most, fallback: 0 }); w.nextBolt = s.num(d.nextBolt ?? w.lightningFirst, 'nextBolt', { ...most, fallback: w.lightningFirst });
218
+ s.done();
220
219
  } });
221
220
  return w;
222
221
  },
@@ -244,3 +243,5 @@ export function weather(opts = {}) {
244
243
  };
245
244
  return [state, weatherDrawModule(Object.fromEntries(['particles', 'area', 'rain', 'snow'].filter(k => opts[k] !== undefined).map(k => [k, opts[k]])))];
246
245
  }
246
+
247
+ export const handRolled = 'none: weather by hand is plain values with no one shape';
@@ -22,13 +22,12 @@ export class WeatherDraw {
22
22
  */
23
23
  constructor(engine, { particles, area = 40, rain = {}, snow = {} } = {}) {
24
24
  /** @internal */ this.engine = engine;
25
- /** @internal the state half: read only */ this.state = engine.weather;
26
25
  /** Sky flash now, 1 at a strike (the weather:lightning event) fading to 0 @type {number} */
27
26
  this.flash = 0;
28
27
  // the weather's entries on the shared sky points: taken once through ctx.mod (owned by this module, gone with it) and rewritten every frame with
29
28
  // handle.change (core/ops/sharedPoint.js), so a frame adds no entry and no cleanup handle. ctx is set by the module's install
30
29
  /** @internal */ this._ctx = null; /** @internal */ this._h = {};
31
- /** @internal */ this._tint = { color: this.state.overcastColor, amount: 0, horizon: 0 };
30
+ /** @internal */ this._tint = { color: null, amount: 0, horizon: 0 };
32
31
  /** Default particle count per system: weather({ particles }), else 6000 (3000 on low-tier devices) @type {number} */
33
32
  this.particles = particles ?? (engine.tier === 'low' ? 3000 : 6000);
34
33
  /** @internal */ this.area = area;
@@ -49,6 +48,8 @@ export class WeatherDraw {
49
48
 
50
49
  /** @internal the weather table (state half) */
51
50
  get types() { return this.state.types; }
51
+ /** @internal the state half, read only and read live: a replaced weather module must not leave the picture on the old one */
52
+ get state() { return this.engine.weather; }
52
53
  /** @internal does any type have this field above 0 */
53
54
  _used(field) { return Object.values(this.types).some(v => v[field] > 0); }
54
55
 
@@ -98,6 +99,7 @@ export class WeatherDraw {
98
99
  */
99
100
  apply(camera, dt = 0) {
100
101
  const c = this.state.current, e = this.engine, T = this._tint;
102
+ T.color = this.state.overcastColor;
101
103
  const t = e.time.now('real');
102
104
  this.flash = Math.max(0, this.flash - dt * 3);
103
105
  T.amount = c.grey; T.horizon = c.grey * 0.8; this._put('sky.tint', 'value', T);
@@ -124,14 +126,13 @@ export function weatherDrawModule(opts) {
124
126
  readParams('weather (drawing half)', DRAW_PARAMS, opts);
125
127
  let L = null;
126
128
  return {
127
- name: 'weatherDraw', type: 'picture', provides: ['weatherDraw'], label: 'Weather drawing', params: DRAW_PARAMS, options: opts, requires: ['weather'], optional: ['sky'], stage: 'environment', before: ['sky'], after: ['weather'],
129
+ name: 'weatherDraw', skipKind: 'none', type: 'picture', provides: ['weatherDraw'], label: 'Weather drawing', params: DRAW_PARAMS, options: opts, requires: ['weather'], optional: ['sky'], stage: 'environment', before: ['sky'], after: ['weather'],
128
130
  install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.weatherDraw': '天气外观' }, en: { 'module.weatherDraw': 'weather drawing' } });
129
131
  L = new WeatherDraw(e, opts);
130
132
  L._ctx = ctx; // the weather's entries on the shared points go with this module (ctx.mod)
131
133
  ctx.track(onRendererSwap(e, () => L._rendererSwapped()));
132
- const w = e.weather;
133
- ctx.track(e.audio.condition('weather', v => [].concat(v).includes(w.name))); // audio rule condition { weather: 'rain' | ['rain', 'storm'] }
134
- for (const k of ['rain', 'snow', 'wind']) ctx.track(e.audio.measure(k, () => w.current[k])); // data rules: { rain: { lt: 0.2 } }, volume add: { rain: 0.22 }
134
+ ctx.track(e.audio.condition('weather', v => [].concat(v).includes(e.weather.name))); // audio rule condition { weather: 'rain' | ['rain', 'storm'] }
135
+ for (const k of ['rain', 'snow', 'wind']) ctx.track(e.audio.measure(k, () => e.weather.current[k])); // data rules: { rain: { lt: 0.2 } }, volume add: { rain: 0.22 }
135
136
  builtInSounds(e.assets, { thunder: (audio, p, out) => { const dur = p.duration ?? 3.5, delay = 0.4 + Math.random() * 1.5; // presentation: thunder delay
136
137
  audio.noiseBurst({ type: 'lowpass', freq: p.freq ?? 140, vol: p.volume ?? 0.9, dur, rate: 0.4 * p.pitch, delay, out }); return delay + dur; } },
137
138
  { bus: 'ambience' }); // sound asset 'thunder', silent until audio.sounds names it