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
@@ -33,19 +33,24 @@ import { makeWindow, injectUICSS, uiFocus } from '../../ui/UI.js';
33
33
  import { BUILTIN_SECTIONS } from './sections.js';
34
34
  import { STRINGS, CSS } from './strings.js';
35
35
  import { SettingsView } from './view.js';
36
- import { applySetting, allowed, checkLimits } from './apply.js';
36
+ import { applySetting, allowed, checkLimits, releaseLimits, releaseRow } from './apply.js';
37
37
  import { readParams, keysSchema } from '../../core/base/params.js';
38
- import { codedError } from '../../core/base/errorHints.js';
38
+ import { codedError, coded } from '../../core/base/errorHints.js';
39
39
  import { warnOnce } from '../../core/base/validate.js';
40
+ import { pixelSizeOn } from '../../core/scene/pixelRatio.js';
41
+ import { trackForModule } from '../../core/engine/moduleTypes.js';
40
42
 
41
- // Graphics presets. Values are performance tiers, not art; a game can override with settings({ presets: { low: {...} } })
42
- // pixelRatio here is a share (0 to 1) of the ratio the engine picked for this device. A fixed number is wrong on one screen or the other: 1 is an upscaled
43
- // picture on a 2x screen (core/scene/tier.js), 1.5 is wasted work on a 1x one
43
+ // Graphics presets. Values are performance steps, not art; a game can override with settings({ presets: { low: {...} } })
44
+ // A preset never states a look. A switch is a permission (true lets the game's choice through), and pixelRatio, viewChunks and density are shares (0 to 1) of what this device and
45
+ // this game start with, so the top preset lets everything through and no preset raises anything. A fixed number is wrong on one game or the other: 5 chunks cuts a game built for 8,
46
+ // and a ratio of 1 is an upscaled picture on a 2x screen (core/scene/tier.js). tier: what engine.tier reads under this preset; null leaves it to the device
44
47
  const PRESETS = {
45
- low: { pixelRatio: 0.75, shadows: false, antialias: false, bloom: false, ao: false, viewChunks: 3, density: 0.5 },
46
- medium: { pixelRatio: 1, shadows: true, antialias: true, bloom: false, ao: false, viewChunks: 4, density: 0.75 },
47
- high: { pixelRatio: 1, shadows: true, antialias: true, bloom: true, ao: false, viewChunks: 5, density: 1 },
48
+ low: { pixelRatio: 0.75, shadows: false, antialias: false, bloom: false, ao: false, viewChunks: 0.6, density: 0.5, tier: 'low' },
49
+ medium: { pixelRatio: 1, shadows: true, antialias: true, bloom: false, ao: false, viewChunks: 0.8, density: 0.75, tier: null },
50
+ high: { pixelRatio: 1, shadows: true, antialias: true, bloom: true, ao: true, viewChunks: 1, density: 1, tier: 'high' },
48
51
  };
52
+ // Preset rows that are shares, and how each share lands on its whole
53
+ const SHARES = { pixelRatio: n => +n.toFixed(2), viewChunks: n => Math.max(1, Math.round(n)), density: n => +n.toFixed(2) };
49
54
  // Settings keys that switch a post effect of the same name; a key whose effect the game did not add is hidden and ignored
50
55
  const POST_KEYS = ['bloom', 'ao'];
51
56
 
@@ -79,17 +84,19 @@ export class Settings extends SettingsView {
79
84
  /** @internal the module's ctx.track: listeners the settings and its sections add leave with the module */ this._track = track;
80
85
  this.engine = engine;
81
86
  this.action = action;
82
- /** @internal */ this._omit = omittedRows(sections);
87
+ /** @internal */ this._leftOut = omittedRows(sections);
83
88
  this.presets = { ...PRESETS };
84
89
  for (const k in presets) {
85
- // loud, because a game's old fixed ratio (2) would otherwise multiply the device's own
90
+ // loud, because a game's old fixed number (a ratio of 2, 5 chunks) would otherwise multiply the device's or the game's own
91
+ for (const row of ['viewChunks', 'density']) if (presets[k][row] > 1) throw codedError('module-params', `settings({ presets: { ${k}: { ${row}: ${presets[k][row]} } } }): a preset's ${row} is a share from 0 to 1 of the game's own value`);
86
92
  if (presets[k].pixelRatio > 1) throw codedError('module-params', `settings({ presets: { ${k}: { pixelRatio: ${presets[k].pixelRatio} } } }): a preset's pixelRatio is a share from 0 to 1 of the ratio the engine picked for this device. For a fixed ratio call engine.setPixelRatio`);
87
93
  this.presets[k] = { ...(this.presets[k] || {}), ...presets[k] };
88
94
  }
89
95
  this.storageKey = storageKey || engine.saves.storageKey('settings');
90
96
  this.sections = new Map();
91
97
  this.custom = new Map(); // game's custom settings: key -> { def, apply }
92
- this.capturing = null; // action name waiting for a key press
98
+ /** @internal keys set before start() with no row yet: init() reports the ones no row came for */ this._early = new Set();
99
+ /** @internal the action waiting for a key press, and its focus entry: the menu cursor rests above it, or Space and Enter would press a control instead of being bound */ this._capturing = null;
93
100
  this.current = null; // current tab
94
101
  this.freezeWorld = freezeWorld;
95
102
 
@@ -137,11 +144,25 @@ export class Settings extends SettingsView {
137
144
 
138
145
  // ---------- reading and writing settings ----------
139
146
  /** Every setting's value, read only. The render scale comes from the renderer: adaptive resolution and the game move it, and a stored copy was a second answer to describe().render.scale */
147
+ /**
148
+ * @internal Rows out of play now: the game's, and under pixelSize the two that would change the ratio, so no preset, stored value or slider reaches it
149
+ * while it is on, and they come back with setPixelSize(null).
150
+ */
151
+ get _omit() { return pixelSizeOn(this.engine) ? new Set([...this._leftOut, 'pixelRatio', 'adaptive']) : this._leftOut; }
140
152
  get values() { return { ...this._values, pixelRatio: +this.engine.renderer.getPixelRatio().toFixed(2) }; }
141
153
  get(key) { return this.values[key]; }
142
- /** Change a setting: applies at once and saves. Changing a graphics setting turns the preset into "custom" */
154
+ /** @internal Someone answers for this key: a built-in row, a defined one, or a bus's slider @param {string} key */
155
+ _hasRow(key) { return key in this._defaults || this.custom.has(key) || (key.startsWith('vol.') && key.slice(4) in this.engine.audio.levels); }
156
+ /**
157
+ * Change a setting: applies at once and saves. Changing a graphics setting turns the preset into "custom". A key no row owns throws: storing it would read back a value nothing
158
+ * applied. Before start() a module's row may still come, so an unknown key waits and init() reports it.
159
+ */
143
160
  set(key, value, { save = true } = {}) {
144
161
  if (key === 'quality') return this.preset(value);
162
+ if (!this._hasRow(key)) {
163
+ if (this._ready) throw codedError('settings-row', `settings.set('${key}'): no setting has this key. Known: ${Object.keys(this._values).join(', ')}. Add the row with settings.define('${key}', ...) or the tab that has it (settings({ sections }))`);
164
+ this._early.add(key);
165
+ }
145
166
  this._values[key] = value; this._changed[key] = value;
146
167
  this._apply(key, value);
147
168
  if (key in (this.presets.low || {})) this._values.quality = this._matchPreset();
@@ -161,6 +182,7 @@ export class Settings extends SettingsView {
161
182
  * A game's custom setting: default value + apply function (called at once with the saved value), or { apply, limits }. limits names the shared
162
183
  * value(s) the row restricts on the settings layer, the same way the built-in shadows row does: off holds the value off (a cutscene or the
163
184
  * scene cannot turn it back on), on allows what the scene chose; a number row from 0 to 1 is a factor on a number value.
185
+ * A row a module defines from its install, init or a hook leaves with that module and gives its limits back; the player's choice waits for its return.
164
186
  * @param {string} key @param {any} def
165
187
  * @param {((value: any, engine: any) => void) | { apply?: (value: any, engine: any) => void, limits?: string | string[] }} [apply]
166
188
  * @example engine.settings.define('volfog', true, { limits: 'post.volfog.enabled' }); // after engine.post.add(volFog)
@@ -169,21 +191,43 @@ export class Settings extends SettingsView {
169
191
  const o = typeof apply === 'function' || apply == null ? { apply } : apply;
170
192
  const limits = o.limits == null ? null : [].concat(o.limits);
171
193
  if (limits) checkLimits(this, key, def, limits);
172
- this.custom.set(key, { def, apply: o.apply, limits });
173
- if (!(key in this._values)) this._values[key] = def;
194
+ const row = { def, apply: o.apply, limits };
195
+ this.custom.set(key, row);
196
+ const picked = this._picked(); // a preset's share of this row is only known now that the row says what it is a share of
197
+ if (key in picked) this._values[key] = picked[key];
198
+ else if (!(key in this._values)) this._values[key] = def;
174
199
  this._apply(key, this._values[key]);
200
+ if (this._ready) this._values.quality = this._matchPreset();
201
+ this._leavesWithModule(() => {
202
+ if (this.custom.get(key) !== row) return; // the name was defined again: that row is someone else's
203
+ this.custom.delete(key);
204
+ if (limits) releaseRow(this.engine, limits);
205
+ if (!(key in this._changed)) delete this._values[key];
206
+ });
175
207
  return this;
176
208
  }
209
+ /**
210
+ * @internal A row or tab made while a module runs leaves with that module (trackForModule); one the game made, or an async callback, stays
211
+ */
212
+ _leavesWithModule(drop) { trackForModule(this.engine, { remove: () => { drop(); this.win?.refresh(); } }); }
177
213
  /** Add a tab */
178
214
  addSection(id, def) {
179
215
  if (def === undefined) { this._builtin(id); this.win.refresh(); return this; }
180
216
  const { title, render, bind, when, order = 100 } = def;
181
- this.sections.set(id, { title: typeof title === 'function' ? title : () => title, render, bind, when, order });
217
+ const section = { title: typeof title === 'function' ? title : () => title, render, bind, when, order };
218
+ this.sections.set(id, section);
219
+ this._leavesWithModule(() => { if (this.sections.get(id) === section) this.sections.delete(id); });
182
220
  this.win.refresh();
183
221
  return this;
184
222
  }
185
223
 
186
224
  get isOpen() { return this.win.open; }
225
+ /** Action name waiting for a key press, or null @type {string | null} */
226
+ get capturing() { return this._capturing?.action ?? null; }
227
+ set capturing(action) {
228
+ this._capturing?.hold.remove();
229
+ this._capturing = action ? { action, hold: this.focus.push('settings-key', { cancel: () => this._cancel() }) } : null;
230
+ }
187
231
  open() { if (!this.win.open) this.win.toggle(true); }
188
232
  close() { this.capturing = null; if (this.win.open) this.win.toggle(false); }
189
233
  toggle(on = !this.win.open) { on ? this.open() : this.close(); }
@@ -252,26 +296,24 @@ export class Settings extends SettingsView {
252
296
  }
253
297
 
254
298
  // ---------- applying ----------
255
- /**
256
- * @internal The chunk table that "view distance" and "vegetation density" drive: the terrain's, or vegetation's own over a level / code-built ground; null
257
- * without either
258
- */
259
- chunkHost() { return this.engine.terrain ?? this.engine.vegetation?.host ?? null; }
260
299
  _currentValues() {
261
- const e = this.engine, v = { pixelRatio: +e.adaptive.base.toFixed(2), shadows: allowed(e, 'shadows.enabled') };
262
- v.antialias = e.post.antialias;
263
- for (const k of POST_KEYS) if (e.post.get(k)) v[k] = allowed(e, `post.${k}.enabled`);
300
+ const e = this.engine, v = { pixelRatio: +e.adaptive.base.toFixed(2), shadows: allowed(e, 'shadows.enabled'), tier: null };
301
+ v.antialias = e.post.authoredAA; // the default, not what this launch runs with: a choice stored for this launch is the player's, and reset() must get past it
302
+ for (const k of POST_KEYS) v[k] = allowed(e, `post.${k}.enabled`); // a permission, known before the effect exists: this runs at install, the game adds its effects after
264
303
  v.adaptive = !!e.adaptive.on;
265
- const H = this.chunkHost();
266
- if (H) { v.viewChunks = H.viewChunks; v.density = H.density; }
267
304
  for (const [bus, level] of Object.entries(e.audio.levels)) v['vol.' + bus] = level; // one slider per bus, the game's own buses too
268
305
  return v;
269
306
  }
270
- /** A preset's values on this device: its pixelRatio share made a ratio. Nothing for 'custom' or no preset @param {string} [name] */
307
+ /** A preset's values in this game on this device: each share made a value. A share of a row nobody offered is left out. Nothing for 'custom' or no preset @param {string} [name] */
271
308
  _presetValues(name) {
272
- if (!this.presets[name]) return {};
273
- const p = Object.fromEntries(Object.entries(this.presets[name]).filter(([k]) => !this._omit.has(k)));
274
- return 'pixelRatio' in p ? { ...p, pixelRatio: +(p.pixelRatio * this.engine.adaptive.base).toFixed(2) } : p;
309
+ const out = {};
310
+ for (const [k, v] of Object.entries(this.presets[name] ?? {})) {
311
+ if (this._omit.has(k)) continue;
312
+ if (!(k in SHARES)) { out[k] = v; continue; }
313
+ const whole = k === 'pixelRatio' ? this.engine.adaptive.base : this.custom.get(k)?.def;
314
+ if (whole != null) out[k] = SHARES[k](v * whole);
315
+ }
316
+ return out;
275
317
  }
276
318
  /** What the player chose: the preset, then the rows moved after it */
277
319
  _picked() {
@@ -284,8 +326,7 @@ export class Settings extends SettingsView {
284
326
  const v = this._values, e = this.engine;
285
327
  for (const name of Object.keys(this.presets)) {
286
328
  const ok = Object.entries(this._presetValues(name)).every(([k, val]) => {
287
- if ((k === 'viewChunks' || k === 'density') && !this.chunkHost()) return true;
288
- if (POST_KEYS.includes(k) && !e.post.get(k)) return true;
329
+ if (k === 'tier' || (POST_KEYS.includes(k) && !e.post.get(k))) return true; // nothing the menu shows: no reason to call the picture custom
289
330
  return v[k] === val;
290
331
  });
291
332
  if (ok) return name;
@@ -296,13 +337,10 @@ export class Settings extends SettingsView {
296
337
 
297
338
  // ---------- module hooks ----------
298
339
  init() {
299
- // At start() every module is installed: terrain settings and key bindings can only be applied fully now
340
+ // At start() every module is installed, and the modules before this one have offered their rows (the view distance and density rows are the ground's)
300
341
  this._ready = true;
301
342
  const picked = this._picked(), e = this.engine;
302
- for (const k of ['viewChunks', 'density']) {
303
- const H = this.chunkHost(); if (!H) continue;
304
- if (k in picked) this._apply(k, this._values[k] = picked[k]); else this._values[k] = H[k];
305
- }
343
+ for (const k of this._early) if (!this._hasRow(k)) warnOnce(coded('settings-row', `settings.set('${k}') before start: no row came for this key, so nothing applied it`));
306
344
  // start() may have learned the real device on the WebGPU route and written its default ratio over the player's
307
345
  this._defaults.pixelRatio = +e.adaptive.base.toFixed(2);
308
346
  this._values.pixelRatio = picked.pixelRatio ?? this._defaults.pixelRatio;
@@ -312,6 +350,8 @@ export class Settings extends SettingsView {
312
350
  frame() {
313
351
  const inp = this.engine.input;
314
352
  if (this.capturing) {
353
+ if (!this.win.open) { this.capturing = null; return; } // closed by its close button: a focus entry left here would hold the back key
354
+ if (this._capturing.hold.fresh) return; // the confirm press that opened it is not the new key
315
355
  const code = [...inp.justPressed][0];
316
356
  // The back key is routed to _cancel by the UI focus stack (cancels rebinding); nothing to do here
317
357
  if (code && !inp.keysOf('cancel').includes(code)) { const a = this.capturing; this.capturing = null; this.rebind(a, code); }
@@ -357,7 +397,7 @@ export function settings(opts = {}) {
357
397
  readParams('settings', SETTINGS_PARAMS, opts);
358
398
  let s = null;
359
399
  return {
360
- name: 'settings', type: 'ui', params: SETTINGS_PARAMS, options: opts, label: 'Settings', optional: ['terrain', 'vegetation', 'flow', 'cameraRig'], stage: 'effects',
400
+ name: 'settings', skipKind: 'none', type: 'ui', params: SETTINGS_PARAMS, options: opts, label: 'Settings', optional: ['flow', 'cameraRig'], stage: 'effects',
361
401
  install(e, ctx) {
362
402
  s = new Settings(e, opts, ctx.track);
363
403
  ctx.track(e.ui.titleItem('settings', { label: x => x.t('title.settings'), run: () => s.open() })); // the title screen's Settings button
@@ -365,7 +405,14 @@ export function settings(opts = {}) {
365
405
  },
366
406
  init() { s.init(); },
367
407
  frame() { s.frame(); },
408
+ // the tracked ui:close listener went first, so what an open menu holds is given back here
409
+ dispose() { s.capturing = null; s._pause(false); releaseLimits(s); },
368
410
  // the values the player chose (quality preset, volumes, ...) explain a picture or a sound level; open / tab / capturing say the menu holds the input
369
411
  describe() { return { open: s.isOpen, tab: s.current, capturing: s.capturing, values: { ...s.values } }; },
370
412
  };
371
413
  }
414
+
415
+ export const handRolled = [
416
+ { kind: 'pause', seen: 'a pause or Esc handler of its own', use: 'settings({ freezeWorld: true }): Esc stops every system and opens the menu (recipe 63); engine.freeze(why) for a pause with no menu', quiet: /\bsettings\(|\bengine\.(freeze|flow|settings)\b|\buiFocus\(/, code: /\b(?:let|var)\s+(?:is|game)?paused\s*=/i, orRaw: /(?:\.key|\.code)\s*===?\s*['"]Escape['"]/, tags: false },
417
+ { kind: 'settings', seen: 'a settings menu of its own', use: 'the settings module: volume, keys, quality and language in one menu that remembers itself; settings.define adds your own (recipe 26)', quiet: /\bsettings\(|\bengine\.settings\b/, code: /\b(createElement|innerHTML|className|classList|getElementById|querySelector|\.id)\b/, raw: /(?:createElement|innerHTML|className|classList|getElementById|querySelector|\.id\b)[^,;{}]*(?:settings|options-?(?:menu|panel|screen)|pause-?menu)|(?:settings|options|pause)-?(?:menu|panel|screen)[^,;{}]*(?:createElement|innerHTML|className|classList|getElementById|querySelector|\.id\b)/i },
418
+ ];
@@ -1,7 +1,7 @@
1
1
  import { reportError } from '../../core/base/errors.js';
2
2
  import { codedError } from '../../core/base/errorHints.js';
3
- // Apply one setting to the engine (helper of Settings.js): the built-in keys (pixel ratio, shadows, post effects, view distance, density, audio buses) and
4
- // the game's own settings (define). `s` is the Settings instance.
3
+ // Apply one setting to the engine (helper of Settings.js): the built-in keys (pixel ratio, shadows, post effects, quality tier, audio buses) and the rows of modules and of
4
+ // the game (define). `s` is the Settings instance.
5
5
 
6
6
  /** The shared values each built-in row limits. A game's own row names its values with define(key, def, { limits }); both go through limit() */
7
7
  const BUILTIN_LIMITS = { shadows: ['shadows.enabled'], bloom: ['post.bloom.enabled'], ao: ['post.ao.enabled'] };
@@ -14,11 +14,19 @@ const BUILTIN_LIMITS = { shadows: ['shadows.enabled'], bloom: ['post.bloom.enabl
14
14
  * @param {any} e @param {string} name the shared point ('shadows.enabled') @param {boolean | number} val
15
15
  */
16
16
  function limit(e, name, val) {
17
- if (!e.stacks.has(name)) return; // a game without this effect has nothing to switch
18
- const p = e.stacks.get(name);
19
- if (val === true || val === 1) p.release('settings');
17
+ const allow = val === true || val === 1;
18
+ // an effect not added yet (settings install before the game's boot code) has no point: the limit waits on one made now, and add() starts under it. Allowing has nothing to lift
19
+ if (!e.stacks.has(name) && (allow || !name.startsWith('post.'))) return;
20
+ const p = e.stacks.has(name) ? e.stacks.get(name) : e.post.switchPoint(name);
21
+ if (allow) p.release('settings');
20
22
  else p.take({ owner: 'settings', layer: 'settings', ...(p.kind === 'number' ? { mul: val === false ? 0 : val } : { set: val }) });
21
23
  }
24
+ /** @internal a row leaves: no control is left to lift its limits, so it gives its shared values back @param {any} e @param {string[]} names */
25
+ export function releaseRow(e, names) { for (const n of names) if (e.stacks.has(n)) e.stacks.get(n).release('settings'); }
26
+ /** @internal the module leaves: so does every row */
27
+ export function releaseLimits(s) {
28
+ for (const names of [...Object.values(BUILTIN_LIMITS), ['tier'], ...[...s.custom.values()].map(c => c.limits ?? [])]) releaseRow(s.engine, names);
29
+ }
22
30
  /** @internal the row's value fits the points it limits: a switch row (boolean) limits switches or numbers, a number row (a factor) only numbers */
23
31
  export function checkLimits(s, key, def, names) {
24
32
  const e = s.engine;
@@ -43,10 +51,9 @@ export function applySetting(s, key, val) {
43
51
  if (limits) for (const n of limits) limit(e, n, typeof val === 'number' ? val : !!val);
44
52
  switch (key) {
45
53
  case 'pixelRatio': e.setPixelRatio(val); break;
46
- case 'antialias': e.post.setAntialias(val); break;
54
+ case 'antialias': e.post.nextAntialias(val); break;
55
+ case 'tier': if (val) e.mod('tier', { owner: 'settings', layer: 'settings', set: val }); else e.stacks.get('tier').release('settings'); break;
47
56
  case 'adaptive': if (e.adaptive) { e.adaptive.on = val; if (!val && e.adaptive.max) e.setPixelRatio(e.adaptive.max); } break;
48
- case 'viewChunks': { const H = s.chunkHost(); if (H?.setViewChunks && H.viewChunks !== val) H.setViewChunks(val); break; }
49
- case 'density': { const H = s.chunkHost(); if (H?.setDensity && H.density !== val) H.setDensity(val); break; }
50
57
  default:
51
58
  // a saved slider for a bus this build no longer has is skipped, not an error
52
59
  if (key.startsWith('vol.')) { if (key.slice(4) in e.audio.levels) e.audio.setVolume(key.slice(4), val); }
@@ -8,7 +8,7 @@
8
8
  // data-reset="controls" restore default keys
9
9
  // data-locale="en" switch language
10
10
 
11
- import { setFov } from '../../core/scene/view.js';
11
+ import { setFov, lensFov } from '../../core/scene/view.js';
12
12
 
13
13
  const pct = v => Math.round(v * 100) + '%';
14
14
  /** Value shown beside a slider */
@@ -60,8 +60,11 @@ export const BUILTIN_SECTIONS = {
60
60
  if (e.post.get('bloom')) add('bloom', t('settings.bloom'), toggle('bloom', v.bloom, tools));
61
61
  if (e.post.get('ao')) add('ao', t('settings.ao'), toggle('ao', v.ao, tools));
62
62
  add('adaptive', t('settings.adaptive'), toggle('adaptive', v.adaptive, tools));
63
- if (s.chunkHost()?.setViewChunks) add('viewChunks', t('settings.viewDistance'), range('viewChunks', v.viewChunks, 2, 8, 1, tools));
64
- if (s.chunkHost()?.setDensity) add('density', t('settings.density'), range('density', v.density, 0.25, 1.5, 0.25, tools));
63
+ // the ground's own rows: the slider reaches at least as far as the game's value and the share Low gave it
64
+ const view = s.custom.get('viewChunks');
65
+ if (view) add('viewChunks', t('settings.viewDistance'), range('viewChunks', v.viewChunks, Math.min(2, v.viewChunks), Math.max(8, view.def), 1, tools));
66
+ if (s.custom.has('density')) add('density', t('settings.density'), range('density', v.density, 0.25, 1.5, 0.25, tools));
67
+ if (v.antialias !== e.post.antialias) h += `<p class="threedog-set-note">${esc(t('settings.nextStart'))}</p>`; // MSAA is fixed with the canvas: say why the picture did not change
65
68
  return h;
66
69
  },
67
70
  },
@@ -146,7 +149,7 @@ export const OPTIONAL_SECTIONS = {
146
149
  const e = s.engine, rig = () => e.cameraRig;
147
150
  s.define('camera.sensitivity', rig()?.sensitivity ?? 1, v => { if (rig() && 'sensitivity' in rig()) rig().sensitivity = v; });
148
151
  s.define('camera.invertY', rig()?.invertY ?? false, v => { if (rig() && 'invertY' in rig()) rig().invertY = v; });
149
- s.define('camera.fov', e.camera.fov, v => setFov(e, v)); // the player's slider: yields to a fov the game took (engine.autoView.manual('fov'))
152
+ s.define('camera.fov', lensFov(e) ?? 50, v => setFov(e, v)); // the player's slider: yields to a fov the game took (engine.autoView.manual('fov'))
150
153
  // a new rig starts from its own defaults (and setCamera resets the fov): put the player's choices back on it
151
154
  s._track(e.events.on('camera:change', () => { for (const k of ['camera.sensitivity', 'camera.invertY', 'camera.fov']) s.custom.get(k)?.apply(s.values[k], e); }));
152
155
  },
@@ -6,7 +6,7 @@ export const STRINGS = {
6
6
  'settings.title': '设置', 'settings.action': '菜单', 'title.settings': '设置', 'module.settings': '设置',
7
7
  'settings.graphics': '画质', 'settings.audio': '声音', 'settings.controls': '按键', 'settings.language': '语言',
8
8
  'settings.quality': '画质预设', 'settings.quality.low': '低', 'settings.quality.medium': '中', 'settings.quality.high': '高', 'settings.quality.custom': '自定义',
9
- 'settings.pixelRatio': '渲染精度', 'settings.shadows': '阴影', 'settings.antialias': '抗锯齿', 'settings.bloom': '泛光', 'settings.ao': '环境光遮蔽',
9
+ 'settings.pixelRatio': '渲染精度', 'settings.shadows': '阴影', 'settings.antialias': '抗锯齿', 'settings.nextStart': '抗锯齿的改动下次启动时生效', 'settings.bloom': '泛光', 'settings.ao': '环境光遮蔽',
10
10
  'settings.adaptive': '自动分辨率', 'settings.viewDistance': '视距', 'settings.density': '植被密度',
11
11
  'settings.vol.master': '总音量', 'settings.vol.music': '音乐', 'settings.vol.sfx': '音效', 'settings.vol.ambience': '环境音', 'settings.vol.ui': '界面音',
12
12
  'settings.pressKey': '请按一个键…', 'settings.unbound': '未绑定', 'settings.rebindHint': '点击按键后按下新键,Esc 取消。',
@@ -22,7 +22,7 @@ export const STRINGS = {
22
22
  'settings.title': 'Settings', 'settings.action': 'Menu',
23
23
  'settings.graphics': 'Graphics', 'settings.audio': 'Audio', 'settings.controls': 'Controls', 'settings.language': 'Language',
24
24
  'settings.quality': 'Quality preset', 'settings.quality.low': 'Low', 'settings.quality.medium': 'Medium', 'settings.quality.high': 'High', 'settings.quality.custom': 'Custom',
25
- 'settings.pixelRatio': 'Render scale', 'settings.shadows': 'Shadows', 'settings.antialias': 'Anti-aliasing', 'settings.bloom': 'Bloom', 'settings.ao': 'Ambient occlusion',
25
+ 'settings.pixelRatio': 'Render scale', 'settings.shadows': 'Shadows', 'settings.antialias': 'Anti-aliasing', 'settings.nextStart': 'The anti-aliasing change applies the next time the game starts', 'settings.bloom': 'Bloom', 'settings.ao': 'Ambient occlusion',
26
26
  'settings.adaptive': 'Adaptive resolution', 'settings.viewDistance': 'View distance', 'settings.density': 'Vegetation density',
27
27
  'settings.vol.master': 'Master volume', 'settings.vol.music': 'Music', 'settings.vol.sfx': 'Sound effects', 'settings.vol.ambience': 'Ambience', 'settings.vol.ui': 'Interface',
28
28
  'settings.pressKey': 'Press a key…', 'settings.unbound': 'Unbound', 'settings.rebindHint': 'Click a key, then press the new one. Esc cancels.',
@@ -30,7 +30,7 @@ export function sky(opts = {}) {
30
30
  readParams('sky', SKY_PARAMS, opts);
31
31
  let s = null, own = () => {};
32
32
  return {
33
- name: 'sky', type: 'picture', label: 'Sky', params: SKY_PARAMS, options: opts, stage: 'environment',
33
+ name: 'sky', skipKind: 'none', type: 'picture', label: 'Sky', params: SKY_PARAMS, options: opts, stage: 'environment',
34
34
  // the one sky: a game's own sky module takes over with engine.use(mySky(), { replaces: 'sky' }) (this one unloads with its picture changes)
35
35
  provides: ['sky'],
36
36
  // weather: only its name for the picture context; calendar: the time drawn (without it one fixed time, sky({ time }))
@@ -60,3 +60,5 @@ export function sky(opts = {}) {
60
60
  describe(e, ctx) { if (!e.calendar) Object.assign(ctx.out.time, { timeOfDay: Math.round(s.fixedTime * 1000) / 1000, fixed: true }); },
61
61
  };
62
62
  }
63
+
64
+ export const handRolled = 'none: a sky of its own is plain three.js, used on purpose';
@@ -18,7 +18,7 @@ import * as THREE from 'three';
18
18
  import { codedError, coded } from '../../core/base/errorHints.js';
19
19
  import { DEV, warnOnce, closest } from '../../core/base/validate.js';
20
20
  import { readParams } from '../../core/base/params.js';
21
- import { refuseSave } from '../../core/saves/saveValues.js';
21
+ import { refuseSave } from '../../core/base/saveValues.js';
22
22
  import { SwarmGrid } from './grid.js';
23
23
  import { makeMesh, writeMesh } from './draw.js';
24
24
  /** @import { SwarmData, SwarmOptions, SwarmRowFn } from '../../types/gameplay' */
@@ -31,7 +31,7 @@ const SLOT = 2 ** 20;
31
31
  const FIXED = ['x', 'y', 'z'], COLOR = ['r', 'g', 'b'], NOT_FIELDS = ['id', 'color'];
32
32
  const OPTIONS = {
33
33
  name: { type: 'string', desc: 'unique name: shown in describe(), the key in a save' },
34
- capacity: { type: 'number', min: 1, max: SLOT, desc: 'most objects alive at once; all memory is taken up front' },
34
+ capacity: { type: 'int', min: 1, max: SLOT, desc: 'most objects alive at once; all memory is taken up front' },
35
35
  geometry: { type: 'any', optional: true, desc: 'plain three.js geometry; leave out with material for a swarm that draws nothing' },
36
36
  material: { type: 'any', optional: true, desc: 'plain three.js material; it stays the game\'s to dispose' },
37
37
  fields: { type: 'any', optional: true, desc: 'names of the number columns beside x, y, z' },
@@ -271,6 +271,14 @@ export class Swarm {
271
271
  /** @internal */
272
272
  _load(v) {
273
273
  if (!Array.isArray(v?.id) || !v.cols) refuseSave(`swarm '${this.name}'`, 'the part', 'must be { id, cols }', v);
274
+ // validate the whole part before touching anything: a damaged save must not leave a half-emptied swarm. Handles are serial * SLOT + slot (whole numbers >= SLOT, one per slot)
275
+ const seen = new Set();
276
+ for (const h of v.id) {
277
+ if (!Number.isSafeInteger(h) || h < SLOT || seen.has(h % SLOT)) refuseSave(`swarm '${this.name}'`, 'id', 'must be unique whole-number handles (serial * 2^20 + slot)', h);
278
+ seen.add(h % SLOT);
279
+ }
280
+ for (const k in v.cols) if (Array.isArray(v.cols[k]) && v.cols[k].length !== v.id.length) refuseSave(`swarm '${this.name}'`, `cols.${k}`, `must have one value per id (${v.id.length})`, v.cols[k].length);
281
+ if (v.serial !== undefined && !Number.isSafeInteger(v.serial)) refuseSave(`swarm '${this.name}'`, 'serial', 'must be a whole number', v.serial);
274
282
  this.clear();
275
283
  const at = this._at, d = this.data, ids = v.id;
276
284
  let lost = 0;
@@ -285,7 +293,7 @@ export class Swarm {
285
293
  this._freeN = 0;
286
294
  for (let s = this.capacity - 1; s >= 0; s--) if (at[s] < 0) this._free[this._freeN++] = s;
287
295
  // restored as saved and not as a maximum: loading one save twice must give the same handles (determinism); every saved handle is smaller, so none collide
288
- if (Number.isFinite(v.serial)) this._serial = v.serial;
296
+ if (v.serial !== undefined) this._serial = v.serial;
289
297
  if (lost) warnOnce(coded('swarm-full', `swarm '${this.name}': ${lost} saved objects did not fit capacity ${this.capacity} and were left out`), `swarm-load-${this.name}`);
290
298
  }
291
299
  }
@@ -302,7 +310,7 @@ export function swarm() {
302
310
  /** @type {Swarm[]} */ let list = [];
303
311
  let pending = {}; // a swarm not made yet at load: kept here and filled in when it is made
304
312
  const stats = s => ({ count: s.count, capacity: s.capacity, dropped: s.dropped, ...(s.saved ? { saved: true } : {}) });
305
- return { name: 'swarm', type: 'rules', provides: ['swarm'], label: 'Swarm', stage: 'gameplay',
313
+ return { name: 'swarm', skipKind: 'none', type: 'rules', provides: ['swarm'], label: 'Swarm', stage: 'gameplay',
306
314
  install(e, ctx) {
307
315
  e.i18n.add({ 'zh-CN': { 'module.swarm': '成群对象' }, en: { 'module.swarm': 'swarm' } });
308
316
  const owner = { drop: s => { list = list.filter(o => o !== s); } };
@@ -311,8 +319,8 @@ export function swarm() {
311
319
  // onRender and not frame: step(render: false) skips the matrices, only drawn frames write them
312
320
  ctx.track(e.onRender(() => { for (const s of list) if (s.mesh) writeMesh(s, e.stepBlend); }));
313
321
  // one save part for all swarms: a load or new game also empties swarms not in saves, or last round's bullets stay on the field
314
- e.saves.register('swarm', { version: 1,
315
- save: () => Object.fromEntries(list.filter(s => s.saved).map(s => [s.name, s._save()])),
322
+ ctx.saves.register('swarm', { notAtomic: 'simulated in bulk each step: one copy per atomic run would cost more than the op', version: 1,
323
+ save: () => ({ ...pending, ...Object.fromEntries(list.filter(s => s.saved).map(s => [s.name, s._save()])) }), // pending: swarms of the loaded save not made yet stay in the next save
316
324
  load: d => {
317
325
  pending = { ...d };
318
326
  for (const s of list) {
@@ -344,3 +352,5 @@ export function swarm() {
344
352
  explain: { swarm: (e, name) => { const s = list.find(o => o.name === name); return s ? { ...stats(s), channel: s.channel, fields: s._names, moves: !!s._fn, drawn: !!s.mesh } : { error: `no swarm '${name}'; swarms: ${list.map(o => o.name).join(', ') || 'none'}` }; } },
345
353
  dispose() { for (const s of [...list]) s.dispose(); list = []; } };
346
354
  }
355
+
356
+ export const handRolled = [{ kind: 'pool', seen: 'a pool or list of many shots of its own', use: 'engine.swarm: thousands of shots, crowds and debris in one draw, with reuse and hits (recipe 65)', quiet: /\b(engine|e|eng|ctx)\.swarm\b|\bswarm\(\s*[{)]/, code: /(?:\b(?:const|let|var)\s+|\bthis\.)(?:pool|\w*(?:bullet|projectile|shot|enemy|particle|mesh|object)pool|bullets|projectiles)\s*=\s*(?:\[\s*\]|new Map\b|new Set\b)/i }];
@@ -23,7 +23,7 @@ const NO_VEG = { baseNames: () => [], nearNames: () => [], list: () => [], get:
23
23
  const MAX_TRIES = 3;
24
24
 
25
25
  export class ChunkManager {
26
- constructor(engine, terrainCfg) {
26
+ constructor(engine, terrainCfg, ctx) {
27
27
  this.engine = engine;
28
28
  this.generator = createTerrain(terrainCfg); // main-thread copy: height queries for the character and camera
29
29
  this.chunks = new Map();
@@ -48,7 +48,7 @@ export class ChunkManager {
48
48
  // falls back to it
49
49
  this.lane = engine.threads.lane({ create: () => new Worker(new URL('./chunkWorker.js', import.meta.url), { type: 'module' }), local: chunkHandler });
50
50
  this.lane.broadcast({ type: 'init', terrain: terrainCfg, species: {} }, 'init');
51
- /** @internal edit records (saved with the save) */ this.edits = new TerrainEdits(engine, this);
51
+ /** @internal edit records (saved with the save) */ this.edits = new TerrainEdits(engine, this, ctx);
52
52
  }
53
53
 
54
54
  get chunkSize() { return this.generator.CHUNK; }
@@ -99,6 +99,7 @@ export class ChunkManager {
99
99
  * remove() puts the empty planter back if this one is still set.
100
100
  * @param {object} planter
101
101
  * @returns {{ remove(): void }}
102
+ * @internal
102
103
  */
103
104
  setPlanter(planter) {
104
105
  this.plants = planter;
@@ -175,27 +176,20 @@ export class ChunkManager {
175
176
  return n;
176
177
  }
177
178
 
178
- /**
179
- * View distance (in chunks). Also moves the camera far plane out to it; with terrain({ viewFog: true }) the signal uViewDistance follows too (see viewFogFar;
180
- * the game's fog is its own)
181
- */
182
- setViewChunks(n) {
183
- this._viewChunks = n;
184
- this.engine.viewFar(this._viewMeters() + 150); // chunks in view must not be clipped (unless the game owns camera.far)
185
- }
186
179
  /** @internal the view distance in meters */
187
180
  _viewMeters() { return (this._viewChunks - 0.3) * this.generator.CHUNK; }
188
181
  /** The view distance the signal uViewDistance gets with terrain({ viewFog: true }) (meters), else null; never scene.fog itself */
189
182
  get viewFogFar() { return this.viewFog ? this._viewMeters() : null; }
190
- /** Vegetation density multiplier: plants are placed again on the loaded chunks; the ground and its collision stay, old trees block until the new ones are in */
191
- setDensity(d) { this._density = d; this.vgen++; this._regrow(this.plants.baseNames()); this._regrowNear(this.plants.nearNames()); }
192
183
  // Why setters: a plain write used to change the number and nothing else (no far plane, no new plants), with no error
193
- /** View distance (in chunks); writing it takes effect like setViewChunks */
184
+ /** View distance (in chunks). Writing it moves the camera far plane out too; with terrain({ viewFog: true }) the signal uViewDistance follows (see viewFogFar; the game's fog is its own) */
194
185
  get viewChunks() { return this._viewChunks; }
195
- set viewChunks(n) { this.setViewChunks(n); }
196
- /** Vegetation density multiplier; writing it takes effect like setDensity */
186
+ set viewChunks(n) {
187
+ this._viewChunks = n;
188
+ this.engine.viewFar(this._viewMeters() + 150); // chunks in view must not be clipped (unless the game owns camera.far)
189
+ }
190
+ /** Vegetation density multiplier. Writing it places plants again on the loaded chunks: it thins plants without a collider, blocking plants stand at every density, so collision does not change */
197
191
  get density() { return this._density; }
198
- set density(d) { this.setDensity(d); }
192
+ set density(d) { this._density = d; this.vgen++; this._regrow(this.plants.baseNames()); this._regrowNear(this.plants.nearNames()); }
199
193
  // plants-only jobs for every loaded chunk (the ground and its collision stay; near-only species: _regrowNear). c.regrow counts the ones not yet
200
194
  // mounted: readyAt is false until they are, so a headless page (core/engine/headlessLoad.js) keeps running loading frames and stateApplied
201
195
  // waits for the new plants, as it did when a species dropped the whole terrain
@@ -37,13 +37,15 @@ const NO_HEIGHT = 'terrain(): no height function or height map was given, so the
37
37
  export { createTerrain, DEFAULT_TERRAIN } from './terrainGen.js';
38
38
 
39
39
  const VIEW = { viewChunks: 4, density: 1 };
40
- const TERRAIN_PARAMS = keysSchema(['viewChunks', 'density', 'material', 'effects', 'detail', 'variation', 'viewFog', ...Object.keys(DEFAULT_TERRAIN)], { ...DEFAULT_TERRAIN, ...VIEW, viewFog: false }); // defaults shown in the catalog; createTerrain applies the real ones
40
+ /** The rows this ground offers the settings menu; a preset's share is of the value the game gave it. Writing density places plants again, so an unchanged value stays unwritten */
41
+ const offerGroundRows = (e, T) => e.settings?.define('viewChunks', T.viewChunks, v => { if (T.viewChunks !== v) T.viewChunks = v; }).define('density', T.density, v => { if (T.density !== v) T.density = v; });
42
+ const TERRAIN_PARAMS = keysSchema(['viewChunks', 'density', 'material', 'effects', 'detail', 'variation', 'viewFog', 'part', ...Object.keys(DEFAULT_TERRAIN)], { ...DEFAULT_TERRAIN, ...VIEW, viewFog: false }); // defaults shown in the catalog; createTerrain applies the real ones
41
43
 
42
44
  export function terrain(opts = {}) {
43
45
  readParams('terrain', TERRAIN_PARAMS, opts);
44
46
  checkGround('terrain', opts);
45
47
  // material and detail stay on the main thread (a texture, a function): everything left in cfg is plain data for the workers
46
- const { viewChunks = VIEW.viewChunks, density = VIEW.density, material, effects, detail = null, viewFog = false, ...cfg } = opts;
48
+ const { viewChunks = VIEW.viewChunks, density = VIEW.density, material, effects, detail = null, viewFog = false, part = false, ...cfg } = opts;
47
49
  // effects only says how the game's own material is used: without one it would silently do nothing
48
50
  if (effects !== undefined && (material == null || typeof effects !== 'boolean'))
49
51
  throw codedError('terrain-option', 'terrain({ effects }): goes with your own material, terrain({ material: myMaterial, effects: false }) = drawn as given (no cloud shadow / season / detail patch); got ' + JSON.stringify({ effects, material: material == null ? material : typeof material }));
@@ -54,7 +56,7 @@ export function terrain(opts = {}) {
54
56
  // Why two: collision, paths and vegetation read only the data, so engine.use(myGround, { replaces: 'terrain-draw' }) swaps every pixel of the
55
57
  // ground and keeps all of play. The draw part reads chunk data and never changes it.
56
58
  const data = {
57
- name: 'terrain', type: 'world', provides: ['terrain'], label: 'Terrain', params: TERRAIN_PARAMS, options: opts, noSkip: 'void-fall watch only; nothing accumulates over time', optional: ['vegetation'], stage: 'ground',
59
+ name: 'terrain', skipKind: 'none', type: 'world', provides: part ? ['terrain'] : ['terrain', 'ground'], label: 'Terrain', params: TERRAIN_PARAMS, options: opts, noSkip: 'void-fall watch only; nothing accumulates over time', optional: ['vegetation', 'settings'], stage: 'ground',
58
60
  install(e, ctx) {
59
61
  e.i18n.add({ 'zh-CN': { 'module.terrain': '地形' }, en: { 'module.terrain': 'terrain' } });
60
62
  for (const k in cfg) if (cfg[k] === undefined) delete cfg[k];
@@ -64,12 +66,12 @@ export function terrain(opts = {}) {
64
66
  for (const k of ['height', 'groundType']) if (typeof terrainCfg[k] === 'function') terrainCfg[k] = compilePure(terrainCfg[k], `terrain({ ${k} })`).src;
65
67
  if (!terrainCfg.height && !terrainCfg.heightmap) warnOnce(NO_HEIGHT);
66
68
  sideMat = terrainCfg.shape ? prepareShape(terrainCfg) : null;
67
- w = new ChunkManager(e, terrainCfg);
69
+ w = new ChunkManager(e, terrainCfg, ctx);
68
70
  if (terrainCfg.shape) watchVoid = voidWatcher(e, w);
69
71
  w._density = density; // before anything is placed: nothing to place again yet
70
72
  w.viewFog = viewFog; // opt-in: the view distance goes out as the signal uViewDistance (a game's fog reads it to hide the edge)
71
73
  state.cfg = terrainCfg;
72
- e.setGround({
74
+ const ground = {
73
75
  height: (x, z) => w.generator.surface(x, z),
74
76
  slope: (x, z) => w.generator.slope(x, z),
75
77
  type: (x, z) => w.generator.biomeAt(x, z, w.generator.surface(x, z), w.generator.slope(x, z)), // 'void' outside terrain({ shape })
@@ -81,11 +83,12 @@ export function terrain(opts = {}) {
81
83
  chunkCollision: (cx, cz) => w.chunkCollision(cx, cz),
82
84
  has: (x, z) => w.generator.has(x, z),
83
85
  voidY: () => w.voidY, // the physics module reports its own bodies falling below it (terrain:void)
84
- });
85
- w.setViewChunks(viewChunks);
86
+ };
87
+ if (part) w.ground = ground; else ctx.ground.provide(ground); // part: compositeGround holds the slot and reads terrain.ground
88
+ w.viewChunks = viewChunks;
86
89
  // a source is ready when the ring around it is generated, and for a physics source its collision has taken effect (chunkCollision non-null)
87
- ctx.track(e.stream.addReadyCheck('terrain', s => w.readyAt(s, { rings: 1 }) && (!s.physics || w.readyAt(s, { rings: 1, solid: true }))));
88
- e.budget.metric('chunkApplyMs', () => w.stats.applyMs); // chunk upload ms per frame (the limit comes from the game's budget)
90
+ ctx.stream.addReadyCheck('terrain', s => w.readyAt(s, { rings: 1 }) && (!s.physics || w.readyAt(s, { rings: 1, solid: true })));
91
+ ctx.budget.metric('chunkApplyMs', () => w.stats.applyMs); // chunk upload ms per frame (the limit comes from the game's budget)
89
92
  return w;
90
93
  },
91
94
  frame(dt, e) {
@@ -97,7 +100,8 @@ export function terrain(opts = {}) {
97
100
  describe(e, ctx) { ctx.out.perf.chunks = { loaded: w.stats.loaded ?? 0, visible: w.stats.visible ?? 0, queued: w.stats.queued, failed: w.stats.failed }; },
98
101
  // height map / mask image wait for the image: after it loads, rebuild terrain with the new config (both the main-thread copy and the workers)
99
102
  critical: true, // a missing height map would start the game on flat ground: stop start() with the reason instead
100
- async init() {
103
+ async init(e) {
104
+ offerGroundRows(e, w);
101
105
  const hm = state.cfg.heightmap, mk = state.cfg.shape?.mask;
102
106
  const needH = hm?.url && !hm.data, needM = mk?.url && !mk.data;
103
107
  if (!needH && !needM) return;
@@ -112,7 +116,7 @@ export function terrain(opts = {}) {
112
116
  let drawPart = null;
113
117
  const lookModule = {
114
118
  // the same terrain({...}) call: material / effects are read here, the rest by the data part
115
- name: 'terrainDraw', type: 'picture', label: 'Terrain drawing', params: TERRAIN_PARAMS, options: opts, requires: ['terrain'], provides: ['terrain-draw'], stage: 'effects',
119
+ name: 'terrainDraw', skipKind: 'none', type: 'picture', label: 'Terrain drawing', params: TERRAIN_PARAMS, options: opts, requires: ['terrain'], provides: ['terrain-draw'], stage: 'effects',
116
120
  install(e, ctx) {
117
121
  e.i18n.add({ 'zh-CN': { 'module.terrainDraw': '地形外观' }, en: { 'module.terrainDraw': 'terrain drawing' } });
118
122
  // the colors the workers bake into each chunk: no chunk is generated before the first frame, so this reinit only swaps the config
@@ -143,3 +147,5 @@ function drawConfig(e, cfg) {
143
147
 
144
148
  /** Every species' placement rule (the workers get the full table when the terrain config is replaced) */
145
149
  function speciesRules(w) { const out = {}; for (const sp of w.plants.list()) out[sp.name] = sp.rule; return out; }
150
+
151
+ export const handRolled = 'none: a ground of its own is plain three.js, used on purpose';