threedog 0.2.0 → 0.5.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 (596) hide show
  1. package/CHANGELOG.md +290 -0
  2. package/README.md +9 -8
  3. package/core/Animator.js +15 -12
  4. package/core/Assets.js +83 -16
  5. package/core/Audio.js +45 -38
  6. package/core/Baked.js +32 -8
  7. package/core/Batching.js +102 -15
  8. package/core/Budget.js +39 -18
  9. package/core/Clock.js +40 -80
  10. package/core/DebugOverrides.js +45 -10
  11. package/core/Describe.js +104 -43
  12. package/core/Engine.js +190 -57
  13. package/core/Events.js +4 -1
  14. package/core/I18n.js +25 -13
  15. package/core/Input.js +168 -79
  16. package/core/Inspect.js +2 -2
  17. package/core/InspectMaterials.js +85 -0
  18. package/core/InspectPerf.js +61 -0
  19. package/core/InspectScene.js +13 -2
  20. package/core/Loading.js +2 -1
  21. package/core/Ops.js +50 -9
  22. package/core/Random.js +9 -2
  23. package/core/Rays.js +5 -5
  24. package/core/SaveStore.js +41 -9
  25. package/core/Saves.js +71 -15
  26. package/core/Stream.js +14 -10
  27. package/core/Threads.js +26 -7
  28. package/core/UrlState.js +25 -9
  29. package/core/Views.js +9 -6
  30. package/core/actor.js +1 -1
  31. package/core/adaptive.js +93 -0
  32. package/core/assetEntry.js +22 -5
  33. package/core/assetHot.js +176 -0
  34. package/core/assetLoad.js +38 -11
  35. package/core/assetManifest.js +48 -9
  36. package/core/assetReport.js +1 -1
  37. package/core/audioRules.js +13 -11
  38. package/core/audioVoice.js +69 -42
  39. package/core/canvasBox.js +1 -2
  40. package/core/catalog.js +5 -2
  41. package/core/cells.js +62 -0
  42. package/core/checks.js +10 -8
  43. package/core/chunkStream.js +87 -0
  44. package/core/control.js +149 -0
  45. package/core/copies.js +32 -0
  46. package/core/dayTime.js +12 -6
  47. package/core/debugView.js +82 -15
  48. package/core/describeRender.js +43 -17
  49. package/core/describeText.js +41 -21
  50. package/core/engineCamera.js +32 -0
  51. package/core/errorCodes.js +438 -19
  52. package/core/errorHints.js +37 -141
  53. package/core/errors.js +31 -8
  54. package/core/events.generated.js +12 -7
  55. package/core/gameLights.js +62 -0
  56. package/core/grayMap.js +20 -0
  57. package/core/grid.js +128 -0
  58. package/core/gridLoad.js +20 -0
  59. package/core/ground.js +6 -4
  60. package/core/headlessLoad.js +55 -0
  61. package/core/holds.js +78 -50
  62. package/core/inputContext.js +11 -7
  63. package/core/inputDefaults.js +24 -21
  64. package/core/inputPad.js +1 -1
  65. package/core/inputPointer.js +1 -1
  66. package/core/inputTouch.js +2 -2
  67. package/core/lifecycle.js +48 -12
  68. package/core/lightWatch.js +6 -4
  69. package/core/look/coreParts.js +137 -30
  70. package/core/look/part.js +175 -95
  71. package/core/look/points.js +255 -0
  72. package/core/look/report.js +34 -17
  73. package/core/look/shadowPart.js +63 -0
  74. package/core/look/state.js +45 -0
  75. package/core/look/write.js +12 -28
  76. package/core/loop.js +101 -37
  77. package/core/math.js +11 -3
  78. package/core/moduleSlots.js +75 -0
  79. package/core/moduleTypes.js +73 -0
  80. package/core/modules.js +145 -27
  81. package/core/movement.js +2 -2
  82. package/core/namedModel.js +70 -0
  83. package/core/opsCheck.js +3 -3
  84. package/core/opsFail.js +15 -6
  85. package/core/opsGuard.js +4 -4
  86. package/core/opsRun.js +4 -3
  87. package/core/owned.js +168 -0
  88. package/core/page.js +2 -1
  89. package/core/params.js +30 -8
  90. package/core/plugins.js +277 -0
  91. package/core/saveApply.js +99 -17
  92. package/core/saveFiles.js +8 -6
  93. package/core/saveValues.js +46 -0
  94. package/core/saveVersions.js +20 -3
  95. package/core/scatter.js +48 -19
  96. package/core/sceneDelta.js +203 -0
  97. package/core/sceneMethods.js +35 -30
  98. package/core/screenToGround.js +1 -1
  99. package/core/services.js +27 -11
  100. package/core/session.js +28 -25
  101. package/core/shaderCost.js +78 -0
  102. package/core/shadowTypes.js +2 -1
  103. package/core/sharedPoint.js +317 -0
  104. package/core/skip.js +36 -28
  105. package/core/stackFrames.js +34 -0
  106. package/core/stacks.js +166 -0
  107. package/core/startup.js +153 -11
  108. package/core/streamSources.js +0 -11
  109. package/core/styleParts.js +65 -47
  110. package/core/targeting.js +1 -1
  111. package/core/textureBytes.js +20 -0
  112. package/core/thingExplain.js +2 -2
  113. package/core/thingOps.js +29 -6
  114. package/core/things.js +21 -11
  115. package/core/threadPure.js +7 -3
  116. package/core/threePatches.js +47 -0
  117. package/core/tier.js +21 -10
  118. package/core/time.js +236 -0
  119. package/core/uiClock.js +25 -0
  120. package/core/util.js +7 -1
  121. package/core/validate.js +65 -86
  122. package/core/wrap.js +106 -0
  123. package/docs/AI.md +89 -97
  124. package/docs/API.md +32 -28
  125. package/docs/CODEMAP.md +224 -149
  126. package/docs/COMMANDS.md +57 -34
  127. package/docs/CONVENTIONS.md +92 -30
  128. package/docs/MIGRATING-0.3.md +248 -0
  129. package/docs/MIGRATING-0.4.md +228 -0
  130. package/docs/MIGRATING-0.5.md +68 -0
  131. package/docs/PERF.md +35 -7
  132. package/docs/THREE.md +79 -27
  133. package/docs/api/ambience.md +0 -1
  134. package/docs/api/assets.md +12 -9
  135. package/docs/api/audio.md +10 -14
  136. package/docs/api/calendar.md +41 -0
  137. package/docs/api/cameraRig.md +16 -5
  138. package/docs/api/characters.md +41 -25
  139. package/docs/api/clock.md +6 -5
  140. package/docs/api/collision.md +9 -6
  141. package/docs/api/content.md +6 -4
  142. package/docs/api/dialogue.md +9 -9
  143. package/docs/api/engine.md +65 -62
  144. package/docs/api/events.md +19 -14
  145. package/docs/api/grids.md +3 -3
  146. package/docs/api/ground.md +1 -1
  147. package/docs/api/hud.md +2 -2
  148. package/docs/api/i18n.md +1 -1
  149. package/docs/api/input.md +11 -6
  150. package/docs/api/interactions.md +7 -5
  151. package/docs/api/inventory.md +17 -16
  152. package/docs/api/level.md +0 -1
  153. package/docs/api/lightPool.md +3 -1
  154. package/docs/api/music.md +1 -1
  155. package/docs/api/nav.md +3 -0
  156. package/docs/api/openWorld.md +2 -1
  157. package/docs/api/particles.md +2 -2
  158. package/docs/api/photo.md +0 -2
  159. package/docs/api/pickups.md +15 -0
  160. package/docs/api/post.md +5 -4
  161. package/docs/api/quests.md +2 -3
  162. package/docs/api/rigid.md +16 -14
  163. package/docs/api/saves.md +6 -4
  164. package/docs/api/settings.md +2 -3
  165. package/docs/api/sky.md +11 -44
  166. package/docs/api/stream.md +1 -1
  167. package/docs/api/style.md +31 -29
  168. package/docs/api/terrain.md +9 -6
  169. package/docs/api/terrainLook.md +10 -0
  170. package/docs/api/timeline.md +3 -4
  171. package/docs/api/tools.md +30 -13
  172. package/docs/api/triggers.md +5 -10
  173. package/docs/api/vegetation.md +12 -8
  174. package/docs/api/vegetationLook.md +10 -0
  175. package/docs/api/water.md +4 -20
  176. package/docs/api/weather.md +5 -15
  177. package/docs/api/weatherLook.md +10 -0
  178. package/docs/api/world.md +2 -1
  179. package/docs/recipes/01-new-game.md +71 -59
  180. package/docs/recipes/02-npc.md +46 -29
  181. package/docs/recipes/03-items-pickups.md +38 -24
  182. package/docs/recipes/04-quests.md +34 -27
  183. package/docs/recipes/05-props-bake.md +154 -18
  184. package/docs/recipes/06-clock-events.md +100 -52
  185. package/docs/recipes/07-flow-scenes-pause.md +41 -10
  186. package/docs/recipes/08-weather-sky.md +146 -37
  187. package/docs/recipes/09-style.md +218 -0
  188. package/docs/recipes/10-blender-level.md +14 -2
  189. package/docs/recipes/11-vehicles.md +64 -7
  190. package/docs/recipes/13-animation.md +34 -10
  191. package/docs/recipes/14-custom-module.md +65 -34
  192. package/docs/recipes/15-perf.md +35 -6
  193. package/docs/recipes/16-dev-bridge.md +65 -41
  194. package/docs/recipes/18-world.md +21 -8
  195. package/docs/recipes/19-shooting-picking.md +12 -11
  196. package/docs/recipes/20-content-actions-save.md +63 -25
  197. package/docs/recipes/21-camera.md +49 -16
  198. package/docs/recipes/22-shop-gold.md +18 -18
  199. package/docs/recipes/23-ops.md +17 -11
  200. package/docs/recipes/26-ui-parts.md +61 -12
  201. package/docs/recipes/27-net.md +12 -6
  202. package/docs/recipes/28-terrain.md +35 -2
  203. package/docs/recipes/29-grid.md +71 -33
  204. package/docs/recipes/30-templates.md +64 -12
  205. package/docs/recipes/31-audio.md +20 -12
  206. package/docs/recipes/32-action-game.md +35 -2
  207. package/docs/recipes/34-environment-lighting.md +27 -4
  208. package/docs/recipes/35-style-from-reference.md +115 -51
  209. package/docs/recipes/36-sky-ground-plant-looks.md +37 -35
  210. package/docs/recipes/37-terrain-look-hooks.md +37 -15
  211. package/docs/recipes/38-environment-look-hooks.md +64 -48
  212. package/docs/recipes/40-scene.md +16 -13
  213. package/docs/recipes/41-thing-registry.md +11 -7
  214. package/docs/recipes/42-terrain-shape.md +3 -3
  215. package/docs/recipes/43-shader-patches-surface-looks.md +171 -74
  216. package/docs/recipes/44-water-weather-look-hooks.md +30 -21
  217. package/docs/recipes/45-cascaded-shadows.md +17 -8
  218. package/docs/recipes/46-blender-art-route.md +4 -4
  219. package/docs/recipes/47-island-snow-backdrop.md +11 -10
  220. package/docs/recipes/48-make-material.md +11 -6
  221. package/docs/recipes/49-game-module-contract.md +46 -33
  222. package/docs/recipes/50-own-renderer.md +2 -2
  223. package/docs/recipes/51-capability-catalog.md +4 -4
  224. package/docs/recipes/52-look.md +228 -54
  225. package/docs/recipes/53-ground-up-close.md +58 -0
  226. package/docs/recipes/54-three-idioms.md +88 -0
  227. package/docs/recipes/55-mods-time-wrap.md +112 -0
  228. package/docs/recipes/56-webgpu-tsl.md +260 -0
  229. package/docs/recipes/57-control.md +65 -0
  230. package/docs/recipes/58-input.md +57 -0
  231. package/docs/recipes/59-depth-post-effects.md +83 -0
  232. package/docs/recipes/60-judge-the-picture.md +55 -0
  233. package/examples/action/.threedog/content-index.json +1 -0
  234. package/examples/action/GAMEMAP.md +17 -13
  235. package/examples/action/assets.js +8 -0
  236. package/examples/action/content/actions.js +1 -1
  237. package/examples/action/content/audio.js +5 -5
  238. package/examples/action/look.js +1 -1
  239. package/examples/action/main.js +10 -13
  240. package/examples/action/models.js +24 -23
  241. package/examples/pullable.json +111 -0
  242. package/examples/rc2d/.threedog/content-index.json +1 -0
  243. package/examples/rc2d/GAMEMAP.md +83 -0
  244. package/examples/rc2d/README.md +52 -0
  245. package/examples/rc2d/main.js +63 -0
  246. package/examples/rc2d/rc2d.js +197 -0
  247. package/examples/rc2d/shaders.js +144 -0
  248. package/examples/sheepisland/.threedog/content-index.json +1 -0
  249. package/examples/sheepisland/GAMEMAP.md +13 -11
  250. package/examples/sheepisland/assets.js +5 -0
  251. package/examples/sheepisland/main.js +17 -12
  252. package/examples/sheepisland/style/index.js +6 -6
  253. package/examples/styletest/.threedog/content-index.json +1 -0
  254. package/examples/styletest/GAMEMAP.md +15 -16
  255. package/examples/styletest/assets.js +6 -0
  256. package/examples/styletest/content/npcs.js +1 -1
  257. package/examples/styletest/content/templates.js +1 -1
  258. package/examples/styletest/content/vegetation.js +1 -1
  259. package/examples/styletest/look.js +1 -1
  260. package/examples/styletest/main.js +18 -17
  261. package/examples/styletest/models.js +1 -1
  262. package/examples/styletest/params.js +3 -3
  263. package/examples/techniques/contact-shadows/README.md +92 -0
  264. package/examples/techniques/contact-shadows/contactShadows.js +51 -0
  265. package/examples/techniques/contact-shadows/main.js +53 -0
  266. package/examples/techniques/day-night-grade/README.md +86 -0
  267. package/examples/techniques/day-night-grade/dayNightGrade.js +76 -0
  268. package/examples/techniques/day-night-grade/main.js +51 -0
  269. package/examples/techniques/interior-light/README.md +103 -0
  270. package/examples/techniques/interior-light/interiorLight.js +45 -0
  271. package/examples/techniques/interior-light/main.js +124 -0
  272. package/examples/techniques/modular-building/README.md +125 -0
  273. package/examples/techniques/modular-building/kit.js +426 -0
  274. package/examples/techniques/modular-building/main.js +47 -0
  275. package/examples/techniques/night-lights/README.md +94 -0
  276. package/examples/techniques/night-lights/main.js +70 -0
  277. package/examples/techniques/night-lights/nightLights.js +91 -0
  278. package/examples/techniques/outlines-and-rim/README.md +59 -0
  279. package/examples/techniques/outlines-and-rim/main.js +84 -0
  280. package/examples/techniques/outlines-and-rim/outlines.js +64 -0
  281. package/examples/techniques/procedural-animation/README.md +77 -0
  282. package/examples/techniques/procedural-animation/creature.js +44 -0
  283. package/examples/techniques/procedural-animation/main.js +45 -0
  284. package/examples/techniques/procedural-animation/proceduralAnim.js +118 -0
  285. package/examples/techniques/procedural-surface/README.md +67 -0
  286. package/examples/techniques/procedural-surface/main.js +103 -0
  287. package/examples/techniques/procedural-surface/surface.js +120 -0
  288. package/examples/techniques/stylized-shading/README.md +75 -0
  289. package/examples/techniques/stylized-shading/main.js +93 -0
  290. package/examples/techniques/stylized-shading/shading.js +131 -0
  291. package/examples/techniques/sun-and-key-light/README.md +135 -0
  292. package/examples/techniques/sun-and-key-light/keyLight.js +53 -0
  293. package/examples/techniques/sun-and-key-light/main.js +95 -0
  294. package/examples/techniques/wet-road/README.md +99 -0
  295. package/examples/techniques/wet-road/main.js +68 -0
  296. package/examples/techniques/wet-road/wetRoad.js +209 -0
  297. package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
  298. package/examples/webgpu-tsl/GAMEMAP.md +84 -0
  299. package/examples/webgpu-tsl/README.md +42 -0
  300. package/examples/webgpu-tsl/main.js +21 -0
  301. package/examples/webgpu-tsl/tslScene.js +75 -0
  302. package/examples/world/.threedog/content-index.json +1 -0
  303. package/examples/world/GAMEMAP.md +22 -15
  304. package/examples/world/art/humanoid.js +42 -0
  305. package/examples/world/art/index.js +11 -0
  306. package/examples/world/art/models.js +58 -0
  307. package/examples/world/art/shapes.js +9 -0
  308. package/examples/world/assets.js +6 -0
  309. package/examples/world/content/audio.js +5 -5
  310. package/examples/world/content/npcs.js +2 -2
  311. package/examples/world/content/props.js +1 -1
  312. package/examples/world/content/rules.js +1 -1
  313. package/examples/world/content/templates.js +1 -1
  314. package/examples/world/content/vegetation.js +1 -1
  315. package/examples/world/main.js +17 -13
  316. package/examples/world/style/index.js +61 -0
  317. package/examples/world/style/plugins/10-bloom.js +5 -0
  318. package/index.d.ts +50 -45
  319. package/index.js +27 -22
  320. package/llms.txt +20 -12
  321. package/modules/ambience/Ambience.js +34 -23
  322. package/modules/calendar/Calendar.js +163 -0
  323. package/modules/calendar/contract.js +21 -0
  324. package/modules/calendar/index.js +81 -0
  325. package/modules/{sky → calendar}/schedule.js +17 -16
  326. package/modules/calendar/seasons.js +55 -0
  327. package/modules/camera/FirstPersonCamera.js +6 -15
  328. package/modules/camera/FixedCamera.js +33 -15
  329. package/modules/camera/FollowCamera.js +90 -16
  330. package/modules/camera/RtsCamera.js +18 -17
  331. package/modules/camera/common.js +70 -19
  332. package/modules/camera/contract.js +17 -0
  333. package/modules/camera/projection.js +11 -24
  334. package/modules/characters/Character.js +196 -59
  335. package/modules/characters/NPC.js +87 -36
  336. package/modules/characters/assetModel.js +27 -8
  337. package/modules/characters/behaviors.js +2 -1
  338. package/modules/characters/contract.js +13 -0
  339. package/modules/characters/footsteps.js +1 -1
  340. package/modules/characters/index.js +87 -49
  341. package/modules/characters/moveHelpers.js +4 -5
  342. package/modules/characters/movers/common.js +97 -19
  343. package/modules/characters/movers/manual.js +20 -0
  344. package/modules/characters/movers/rapier.js +19 -16
  345. package/modules/characters/movers/simple.js +14 -11
  346. package/modules/characters/movers/support.js +172 -0
  347. package/modules/characters/npcAvoid.js +47 -42
  348. package/modules/characters/npcSim.js +12 -8
  349. package/modules/characters/npcView.js +44 -16
  350. package/modules/characters/pathAsync.js +7 -3
  351. package/modules/characters/playerStrings.js +4 -3
  352. package/modules/characters/proceduralRig.js +46 -10
  353. package/modules/characters/useModel.js +1 -1
  354. package/modules/characters/vehicle.contract.js +21 -0
  355. package/modules/characters/walkTo.js +21 -7
  356. package/modules/collision/Collision.js +65 -25
  357. package/modules/collision/grid.js +8 -6
  358. package/modules/content/explain.js +2 -2
  359. package/modules/content/fields.js +102 -0
  360. package/modules/content/ids.js +8 -6
  361. package/modules/content/index.js +97 -28
  362. package/modules/content/loader.js +45 -33
  363. package/modules/content/models.js +11 -40
  364. package/modules/content/packs.js +6 -5
  365. package/modules/content/parts.js +41 -0
  366. package/modules/content/props.js +16 -9
  367. package/modules/content/rules.js +58 -0
  368. package/modules/content/stages.js +80 -0
  369. package/modules/content/templates.js +121 -30
  370. package/modules/debug/DebugPanel.js +24 -17
  371. package/modules/flow/contract.js +16 -0
  372. package/modules/flow/index.js +21 -15
  373. package/modules/gameplay/Container.js +41 -32
  374. package/modules/gameplay/Containers.js +30 -15
  375. package/modules/gameplay/Dialogue.js +113 -55
  376. package/modules/gameplay/Interactions.js +193 -67
  377. package/modules/gameplay/Inventory.js +69 -73
  378. package/modules/gameplay/Quests.js +75 -39
  379. package/modules/gameplay/boxOps.js +3 -3
  380. package/modules/gameplay/dialogue.contract.js +21 -0
  381. package/modules/gameplay/dialogueBox.js +4 -2
  382. package/modules/gameplay/dialogueBubbles.js +116 -0
  383. package/modules/gameplay/interactionPrompt.js +4 -1
  384. package/modules/gameplay/interactions.contract.js +16 -0
  385. package/modules/gameplay/inventory.contract.js +23 -0
  386. package/modules/gameplay/inventoryOps.js +18 -16
  387. package/modules/gameplay/pickups.js +268 -85
  388. package/modules/gameplay/questLog.js +4 -4
  389. package/modules/gameplay/quests.contract.js +17 -0
  390. package/modules/grid/Grid.js +92 -50
  391. package/modules/grid/Layer.js +14 -13
  392. package/modules/grid/index.js +60 -36
  393. package/modules/grid/ops.js +20 -18
  394. package/modules/grid/preview.js +15 -16
  395. package/modules/grid/strings.js +12 -0
  396. package/modules/grid/tiles.js +6 -5
  397. package/modules/hlod/index.js +51 -19
  398. package/modules/hud/index.js +35 -20
  399. package/modules/hud/parts.js +20 -7
  400. package/modules/level/heightfield.js +3 -1
  401. package/modules/level/index.js +45 -20
  402. package/modules/level/nodes.js +4 -3
  403. package/modules/lights/index.js +42 -18
  404. package/modules/music/Music.js +38 -21
  405. package/modules/music/rules.js +1 -1
  406. package/modules/nav/index.js +48 -42
  407. package/modules/net/Client.js +13 -6
  408. package/modules/net/Host.js +19 -5
  409. package/modules/net/Net.js +2 -1
  410. package/modules/net/index.js +13 -8
  411. package/modules/net/sync.js +9 -8
  412. package/modules/net/transports.js +77 -27
  413. package/modules/particles/Particles.js +23 -14
  414. package/modules/particles/contract.js +17 -0
  415. package/modules/particles/effect.js +39 -11
  416. package/modules/photo/Photo.js +53 -36
  417. package/modules/rigid/RigidBodies.js +194 -32
  418. package/modules/rigid/Vehicles.js +18 -15
  419. package/modules/rigid/sync.js +62 -17
  420. package/modules/settings/Settings.js +57 -52
  421. package/modules/settings/apply.js +38 -3
  422. package/modules/settings/sections.js +5 -3
  423. package/modules/settings/strings.js +3 -2
  424. package/modules/settings/view.js +5 -3
  425. package/modules/sky/Sky.js +88 -176
  426. package/modules/sky/cascades.js +86 -25
  427. package/modules/sky/cascades.tsl.js +82 -0
  428. package/modules/sky/clouds.js +34 -19
  429. package/modules/sky/domeLayers.js +30 -15
  430. package/modules/sky/environment.js +83 -13
  431. package/modules/sky/fog.js +140 -95
  432. package/modules/sky/frame.js +112 -44
  433. package/modules/sky/look.js +22 -19
  434. package/modules/sky/lookFog.js +48 -52
  435. package/modules/sky/lookShadow.js +53 -41
  436. package/modules/sky/lookSky.js +82 -21
  437. package/modules/sky/season.js +21 -0
  438. package/modules/sky/shader.js +41 -19
  439. package/modules/sky/shadow.js +44 -20
  440. package/modules/sky/skyModule.js +45 -33
  441. package/modules/sky/tint.js +61 -0
  442. package/modules/terrain/ChunkManager.js +175 -108
  443. package/modules/terrain/chunkJob.js +1 -1
  444. package/modules/terrain/chunkQueries.js +6 -4
  445. package/modules/terrain/index.js +105 -50
  446. package/modules/terrain/look.js +83 -0
  447. package/modules/terrain/lookGround.js +21 -16
  448. package/modules/terrain/terrainDefaults.js +1 -1
  449. package/modules/terrain/terrainEdit.js +18 -20
  450. package/modules/terrain/terrainGen.js +5 -3
  451. package/modules/terrain/terrainIsland.js +5 -4
  452. package/modules/terrain/terrainShape.js +12 -12
  453. package/modules/terrain/terrainShapeMain.js +8 -7
  454. package/modules/terrain/terrainTexture.js +21 -19
  455. package/modules/timeline/Timeline.js +95 -43
  456. package/modules/timeline/Tween.js +18 -10
  457. package/modules/timeline/letterbox.js +2 -2
  458. package/modules/timeline/shots.js +5 -1
  459. package/modules/triggers/index.js +107 -76
  460. package/modules/vegetation/Vegetation.js +190 -102
  461. package/modules/vegetation/densityMap.js +62 -0
  462. package/modules/vegetation/groundChunks.js +52 -58
  463. package/modules/vegetation/index.js +31 -10
  464. package/modules/vegetation/look.js +119 -0
  465. package/modules/vegetation/lookWind.js +71 -10
  466. package/modules/vegetation/modelGeometry.js +3 -2
  467. package/modules/vegetation/nearFade.js +45 -0
  468. package/modules/water/Water.js +65 -27
  469. package/modules/water/look.js +29 -18
  470. package/modules/water/surface.js +64 -25
  471. package/modules/water/surfaceDefaults.js +3 -0
  472. package/modules/weather/Weather.js +62 -104
  473. package/modules/weather/look.js +1 -2
  474. package/modules/weather/particles.js +24 -9
  475. package/modules/weather/strings.js +2 -2
  476. package/modules/weather/weatherLook.js +135 -0
  477. package/modules/world/World.js +24 -7
  478. package/modules/world/explain.js +1 -1
  479. package/modules/world/index.js +18 -4
  480. package/modules/world/persist.js +62 -2
  481. package/modules/world/pos.js +3 -2
  482. package/modules/world/records.js +8 -6
  483. package/modules/world/sim.js +60 -20
  484. package/modules/world/simFar.js +4 -3
  485. package/modules/world/state.js +3 -2
  486. package/modules/world/thingSource.js +1 -1
  487. package/modules/world/views.js +7 -5
  488. package/package.json +8 -3
  489. package/presets.js +41 -27
  490. package/render/PostFX.js +145 -120
  491. package/render/backend.js +440 -0
  492. package/render/detail.js +150 -45
  493. package/render/effects.js +130 -38
  494. package/render/engineUniforms.js +10 -1
  495. package/render/fuse.js +5 -4
  496. package/render/fx/cloudShadow.tsl.js +16 -0
  497. package/render/fx/detail.tsl.js +66 -0
  498. package/render/fx/index.js +26 -0
  499. package/render/fx/lighting.tsl.js +28 -0
  500. package/render/fx/nodeErrors.tsl.js +68 -0
  501. package/render/fx/noise.tsl.js +12 -0
  502. package/render/fx/objectOrigin.tsl.js +42 -0
  503. package/render/fx/particles.tsl.js +139 -0
  504. package/render/fx/patchNodes.tsl.js +403 -0
  505. package/render/fx/postWebGPU.tsl.js +158 -0
  506. package/render/fx/season.tsl.js +13 -0
  507. package/render/fx/sky.tsl.js +260 -0
  508. package/render/fx/uniforms.tsl.js +67 -0
  509. package/render/fx/water.tsl.js +53 -0
  510. package/render/fx/wind.tsl.js +22 -0
  511. package/render/fxNumbers.js +36 -0
  512. package/render/hotGlsl.js +24 -0
  513. package/render/lighting.js +66 -14
  514. package/render/lights.js +223 -4
  515. package/render/lookGlow.js +139 -0
  516. package/render/lookSurface.js +99 -36
  517. package/render/materials.js +71 -52
  518. package/render/modeling.js +73 -0
  519. package/render/ownFrame.js +76 -0
  520. package/render/patches.js +311 -34
  521. package/render/postLook.js +124 -46
  522. package/render/postWebGL.js +197 -0
  523. package/render/probes.js +231 -0
  524. package/render/shaderErrors.js +154 -0
  525. package/render/slots.js +165 -0
  526. package/render/surface.js +53 -17
  527. package/render/terms.js +211 -0
  528. package/render/uniformDecl.js +3 -2
  529. package/types/common.d.ts +2 -2
  530. package/types/core.d.ts +620 -244
  531. package/types/gameplay.d.ts +494 -318
  532. package/types/generated/core/Audio.d.ts +26 -42
  533. package/types/generated/core/Batching.d.ts +6 -2
  534. package/types/generated/core/Budget.d.ts +2 -8
  535. package/types/generated/core/DebugOverrides.d.ts +44 -3
  536. package/types/generated/core/I18n.d.ts +2 -2
  537. package/types/generated/core/Input.d.ts +102 -31
  538. package/types/generated/core/Ops.d.ts +31 -0
  539. package/types/generated/core/Random.d.ts +2 -2
  540. package/types/generated/core/Saves.d.ts +10 -2
  541. package/types/generated/core/Stream.d.ts +1 -1
  542. package/types/generated/core/Threads.d.ts +4 -1
  543. package/types/generated/core/Views.d.ts +0 -1
  544. package/types/generated/core/audioVoice.d.ts +17 -9
  545. package/types/generated/core/control.d.ts +55 -0
  546. package/types/generated/core/session.d.ts +2 -1
  547. package/types/generated/modules/ambience/Ambience.d.ts +0 -9
  548. package/types/generated/modules/calendar/Calendar.d.ts +84 -0
  549. package/types/generated/modules/calendar/index.d.ts +10 -0
  550. package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
  551. package/types/generated/modules/grid/Grid.d.ts +61 -25
  552. package/types/generated/modules/grid/Layer.d.ts +5 -5
  553. package/types/generated/modules/grid/index.d.ts +29 -17
  554. package/types/generated/modules/music/Music.d.ts +5 -3
  555. package/types/generated/modules/net/index.d.ts +3 -3
  556. package/types/generated/modules/net/transports.d.ts +12 -3
  557. package/types/generated/modules/particles/Particles.d.ts +1 -1
  558. package/types/generated/modules/sky/Sky.d.ts +12 -104
  559. package/types/generated/modules/sky/skyModule.d.ts +1 -1
  560. package/types/generated/modules/timeline/Timeline.d.ts +8 -6
  561. package/types/generated/modules/weather/Weather.d.ts +17 -18
  562. package/types/generated/modules/weather/weatherLook.d.ts +12 -0
  563. package/types/generated/modules/world/World.d.ts +18 -3
  564. package/types/generated/render/PostFX.d.ts +67 -30
  565. package/types/generated/render/materials.d.ts +26 -20
  566. package/types/generated/render/modeling.d.ts +30 -0
  567. package/types/generated/render/patches.d.ts +16 -2
  568. package/types/generated/ui/UI.d.ts +6 -3
  569. package/types/nav.d.ts +6 -0
  570. package/types/physics.d.ts +137 -44
  571. package/types/style.d.ts +125 -92
  572. package/types/tsl.d.ts +86 -0
  573. package/types/world.d.ts +164 -110
  574. package/ui/Focus.js +25 -14
  575. package/ui/LoadingScreen.js +1 -1
  576. package/ui/Parts.js +27 -11
  577. package/ui/UI.js +20 -10
  578. package/ui/cursor.js +115 -0
  579. package/ui/defaults.js +15 -11
  580. package/ui/theme.js +9 -6
  581. package/ui/touchPart.js +1 -1
  582. package/core/claims.js +0 -51
  583. package/core/look/layers.js +0 -136
  584. package/core/renamed.js +0 -21
  585. package/docs/api/entities.md +0 -61
  586. package/docs/recipes/09-style-pack.md +0 -234
  587. package/examples/styletest/overrides.js +0 -33
  588. package/examples/styletest/panel.js +0 -135
  589. package/modules/entities/Entities.js +0 -243
  590. package/modules/entities/build.js +0 -25
  591. package/modules/entities/index.js +0 -4
  592. package/modules/sky/calendar.js +0 -80
  593. package/modules/sky/layers.js +0 -69
  594. package/modules/terrain/chunkLevels.js +0 -40
  595. package/modules/terrain/mountTerrain.js +0 -32
  596. package/modules/world/cells.js +0 -42
package/types/core.d.ts CHANGED
@@ -1,18 +1,19 @@
1
1
  // Engine core: the Engine class, events, input, i18n, saves, assets, audio, the ground interface, module definitions.
2
2
  import type { Object3D, Vector3, Vector2, Color, Texture, BufferGeometry, Handle, PositionLike, Vec3Like, ColorLike, Material } from './common';
3
- import type { Style, StyleInput } from './style';
3
+ import type { Style, StyleInput, MaterialSpec } from './style';
4
4
  import type {
5
- Terrain, Vegetation, Sky, Weather, Water, WaterBody, WaterBodyOptions, VegetationRemoveEvent, Hlod, LightPool, Budget, BudgetLimits, BudgetReport,
5
+ Terrain, TerrainLook, Vegetation, VegetationLook, Sky, Calendar, Weather, WeatherLook, Water, WaterBody, WaterBodyOptions, VegetationRemoveEvent, Hlod, LightPool, Budget, BudgetLimits, BudgetReport,
6
6
  } from './world';
7
7
  import type { World } from './generated/modules/world/World';
8
8
  import type { Net } from './generated/modules/net/Net';
9
9
  import type { PostEffect } from './generated/render/PostFX';
10
10
  import type { Grids } from './generated/modules/grid/index';
11
- import type { Collision, RigidBodies, CameraRig, CameraKind, CameraShotEvent, Animator, AnimatorOptions, Vehicle } from './physics';
11
+ import type { Collision, RigidBodies, CameraRig, CameraKind, CameraShotEvent, Animator, AnimatorOptions, Vehicle, Rideable } from './physics';
12
12
  import type { Nav } from './nav';
13
13
  import type { Stream } from './generated/core/Stream';
14
14
  import type { Batching } from './generated/core/Batching';
15
15
  import type { Rays } from './generated/core/Rays';
16
+ import type { Control } from './generated/core/control';
16
17
  import type { I18n } from './generated/core/I18n';
17
18
  import type { Audio } from './generated/core/Audio';
18
19
  import type { Input } from './generated/core/Input';
@@ -29,9 +30,9 @@ import type { Jobs } from './generated/core/Jobs';
29
30
  import type { Random } from './generated/core/Random';
30
31
  import type { PostFX } from './generated/render/PostFX';
31
32
  import type {
32
- Timeline, Level, LevelLoadedEvent, Triggers, TriggerEvent, Entities, Entity, EntityStateEvent, EntityStageEvent,
33
+ Timeline, Level, LevelLoadedEvent, Triggers, TriggerEvent, TemplateStageEvent,
33
34
  Particles, Settings, Music, MusicChangeEvent, CharactersApi, NPCManager, Character,
34
- Interactions, Dialogue, Inventory, ItemEvent, ItemUseEvent, ContainerEvent, PickupEvent, Quests, Photo, PhotoShot, Ambience, DebugPanel,
35
+ Interactions, Dialogue, Inventory, ItemEvent, ItemUseEvent, PickupEvent, Pickups, PickupsOptions, Quests, Photo, PhotoShot, Ambience, DebugPanel,
35
36
  Clock, Vars, Content, Flow, Hud,
36
37
  } from './gameplay';
37
38
 
@@ -47,6 +48,12 @@ declare global {
47
48
  * interface GameEvents { 'fighter:hit': [{ attacker: string; victim: string; damage: number }] }
48
49
  */
49
50
  interface GameEvents {}
51
+ /**
52
+ * Vite's import.meta.glob, the documented way a style lists its plugins folder (style.plugins: import.meta.glob('./plugins/*.js', { eager: true }))
53
+ * and engine.plugins.add takes one. Declared here because a game's tsconfig has no vite/client types ("types": []), so the documented line
54
+ * failed the type check of a fresh game; with vite/client too, the two declarations merge as overloads.
55
+ */
56
+ interface ImportMeta { glob(pattern: string | string[], options?: { eager?: boolean; import?: string; query?: string | Record<string, string> }): Record<string, any>; }
50
57
  }
51
58
  /**
52
59
  * Events the engine and modules emit, and the arguments callbacks receive (written as an array: what each argument is).
@@ -83,10 +90,12 @@ export interface EventMap extends GameEvents {
83
90
  'water:add': [body: WaterBody];
84
91
  /** A water body was removed */
85
92
  'water:remove': [body: WaterBody];
86
- /** A new day (the argument is the day number, starting at 1; needs the sky module) */
93
+ /** A new day (the argument is the day number, starting at 1; needs the calendar module) */
87
94
  'day:start': [day: number];
88
95
  /** Season changed (the argument is the season name, e.g. 'autumn') */
89
96
  'season:change': [season: string];
97
+ /** A mod with `for` ran out (engine.mod(target, { owner, for })): target is the quantity's name, id the record for per-record ones */
98
+ 'mod:end': [{ target: string; owner: string; id: string | null }];
90
99
  /** engine.skip jumped game time forward (seconds = game seconds skipped); timers and world catch-up already ran */
91
100
  'time:skip': [{ seconds: number }];
92
101
  /** Lightning strike (weather module) */
@@ -98,11 +107,18 @@ export interface EventMap extends GameEvents {
98
107
  /** engine.setCamera switched the camera kind; settings that belong to the camera (sensitivity, invert Y, field of view) are re-applied on it */
99
108
  'camera:change': [{ kind: string; previous: string }];
100
109
  /** A character jumped */
101
- 'character:jump': [{ character: Character }];
110
+ 'character:jump': [{ character: Character; air: boolean; index: number }];
111
+ 'character:launch': [{ character: Character; speed: number; owner: string }];
112
+ 'character:fall': [{ character: Character; safe: Vector3 | null; preventDefault(): void }];
102
113
  /** A character's model named by asset finished loading and replaced the placeholder body (same root; anim is now set) */
103
114
  'character:model': [{ character: Character; model: Object3D }];
104
115
  /** A character landed; impact is the landing speed (m/s), the larger the harder the fall */
105
116
  'character:land': [{ character: Character; impact: number }];
117
+ /**
118
+ * A character went into or out of deep water (water option): in true on entering, mode what the water option did there ('swim' | 'block' | 'wade',
119
+ * or what the function returned)
120
+ */
121
+ 'character:water': [{ character: Character; in: boolean; mode: string; depth: number }];
106
122
  /** Dialogue started; the argument is the dialogue script name */
107
123
  'dialogue:start': [speaker: string];
108
124
  /**
@@ -110,18 +126,20 @@ export interface EventMap extends GameEvents {
110
126
  * shots without replacing the UI part
111
127
  */
112
128
  'dialogue:line': [{ script: string; node: string; speaker: string; text: string; data: Record<string, any> }];
129
+ /** A bubble line started showing (the bubble channel: lines over their speakers while play goes on); at is what it is attached to, null = a screen line */
130
+ 'dialogue:bubble': [{ speaker: string; text: string; at: any }];
113
131
  /** Dialogue ended; the argument is the dialogue script name */
114
132
  'dialogue:end': [speaker: string];
115
- /** An item was added to the inventory */
133
+ /** An item was added to a container (any bag or chest: container names it, actor says who did it) */
116
134
  'item:add': [ItemEvent];
117
- /** An item was removed from the inventory */
135
+ /** An item was removed from a container (container names it, actor says who did it) */
118
136
  'item:remove': [ItemEvent];
119
- /** An item was added to a non-player container (chest, corpse...); container is the container id */
120
- 'container:add': [ContainerEvent];
121
- /** An item was removed from a non-player container */
122
- 'container:remove': [ContainerEvent];
123
- /** An item on the ground was picked up */
124
- 'item:pickup': [PickupEvent];
137
+ /** A pickup was taken off the ground (pickup = world id, item = its item id or null for a give function, actor = who took it) */
138
+ 'pickup:take': [PickupEvent];
139
+ /** A hold interaction started (the key went down on it); seconds is its hold */
140
+ 'interaction:hold': [{ id: string; action: string; seconds: number }];
141
+ /** A hold interaction stopped before it completed: 'released' | 'tooFar' | 'disabled' | 'removed' | 'inputLocked' */
142
+ 'interaction:interrupt': [{ id: string; action: string; reason: string; progress: number }];
125
143
  /** An item was used through the inventory.use op (after use ran) */
126
144
  'item:use': [ItemUseEvent];
127
145
  /** A quest started */
@@ -148,18 +166,20 @@ export interface EventMap extends GameEvents {
148
166
  'timeline:start': [{ id: number }];
149
167
  /** A cutscene ended; skipped tells whether it was skipped */
150
168
  'timeline:end': [{ id: number; skipped: boolean }];
151
- /** An entity was spawned */
152
- 'entity:spawn': [Entity];
153
- /** An entity was removed */
154
- 'entity:remove': [Entity];
155
- /** A state value of an entity changed */
156
- 'entity:state': [EntityStateEvent];
157
- /** An entity entered a new growth stage */
158
- 'entity:stage': [EntityStageEvent];
169
+ /** A content template instance entered a new stage by growing (templates with stages) */
170
+ 'template:stage': [TemplateStageEvent];
159
171
  /** The ground's shape or type changed in this world-space box (engine.terrain.edit): cached ground samples (path rasters) inside it are stale */
160
172
  'ground:change': [{ x0: number; z0: number; x1: number; z1: number }];
173
+ /**
174
+ * rigid: newGame / a load rebuilt the physics world (a fresh page for physics) and the engine's bodies are back (entry.body is the rebuilt Rapier
175
+ * body; bodies maps the ids given to addBox / addBall / addHull / addWheeled). The old world's joints were freed with it: re-create the game's
176
+ * joints here (recipes/11-vehicles.md, Joints). Not emitted while a vehicle exists (the world is kept then, joints included)
177
+ */
178
+ 'rigid:rebuilt': [{ world: any; player: any; bodies: Record<string, any> }];
161
179
  /** terrain({ shape }): the player or a moving rigid body dropped below engine.terrain.voidY (once per fall). The engine does not respawn: the game decides */
162
180
  'terrain:void': [{ who: any; position: { x: number; y: number; z: number } }];
181
+ /** A terrain chunk job failed every try (usually the game's height / groundType / placement rule throws there): the chunk stays empty and the error is reported. engine.terrain.retry() sends failed chunks again */
182
+ 'terrain:chunkFailed': [{ cx: number; cz: number; error: any }];
163
183
  /** A vegetation instance was chopped / removed */
164
184
  'vegetation:remove': [VegetationRemoveEvent];
165
185
  /** A vegetation instance was restored */
@@ -194,12 +214,12 @@ export interface EventMap extends GameEvents {
194
214
  'net:result': [{ seq: number; name: string; ok: boolean; code: string | null; value?: any; tick: number }];
195
215
  /** A gameplay error in development / testing; gameplay is frozen (error severity levels, see engine.error) */
196
216
  'engine:error': [EngineError];
197
- /** A presentation module errored and was disabled (the game continues) */
217
+ /** A look or ui module errored and was disabled (the game continues) */
198
218
  'module:disabled': [{ name: string; message: string }];
199
219
  /** A character boarded a vehicle */
200
- 'vehicle:enter': [{ character: Character; vehicle: Vehicle }];
220
+ 'vehicle:enter': [{ character: Character; vehicle: Rideable }];
201
221
  /** A character exited a vehicle */
202
- 'vehicle:exit': [{ character: Character; vehicle: Vehicle }];
222
+ 'vehicle:exit': [{ character: Character; vehicle: Rideable }];
203
223
  /** Game flow state changed */
204
224
  'flow:change': [{ from: string; to: string }];
205
225
  /** Scene transition: phase 'start' begins fading to black, 'end' finishes fading back in */
@@ -208,6 +228,8 @@ export interface EventMap extends GameEvents {
208
228
  'session:end': [];
209
229
  /** A playthrough started from a clean slate: kind 'new' (newGame) or 'load' (session.load, with the slot) */
210
230
  'session:start': [{ kind: 'new' | 'load'; slot?: string }];
231
+ /** newGame / session.load failed (a save part's load() threw) and the game was rolled back: the old playthrough goes on, no session:start */
232
+ 'session:failed': [{ kind: 'new' | 'load'; slot?: string }];
211
233
  /** The page went away: the window lost focus or the tab was hidden (engine.page) */
212
234
  'page:blur': [{ focused: boolean; visible: boolean }];
213
235
  /** The page came back: focused and visible again */
@@ -219,6 +241,10 @@ export interface EventMap extends GameEvents {
219
241
  /** The WebGL context is back: gameplay resumes */
220
242
  'page:contextrestored': [];
221
243
  }
244
+ /** The renderer behind engine.renderer: a WebGLRenderer by default, three's WebGPURenderer on the WebGPU route (createEngine({ renderer: 'webgpu' })).
245
+ * Narrow before using one side's API: `if ('isWebGPURenderer' in r)`, or engine.describe().renderer.backend */
246
+ export type EngineRenderer = import('three').WebGLRenderer | import('three/webgpu').WebGPURenderer;
247
+
222
248
  /** Arguments a callback of the given event receives: known events follow EventMap, other names are not checked */
223
249
  export type EventArgs<K extends string> = K extends keyof EventMap ? EventMap[K] : any[];
224
250
  /** Event name: known events get autocompletion, any string is also allowed */
@@ -229,10 +255,9 @@ export type EventName = keyof EventMap | (string & {});
229
255
  // Input
230
256
  // ======================================================================
231
257
 
232
- /** Mouse / touch pointer. ndcX/ndcY are screen coordinates in -1..1 */
233
258
  /** Per-engine shader uniforms (engine.uniforms): { value } objects shared by every material of that engine */
234
259
  export interface EngineUniforms {
235
- /** Fixed seconds (= engine.elapsed) */
260
+ /** Ambient seconds (= engine.time.now('ambient')): keeps moving while gameplay is frozen; written only by the time source */
236
261
  uTime: { value: number };
237
262
  /** Wind strength multiplier (weather) */
238
263
  uWind: { value: number };
@@ -246,14 +271,27 @@ export interface EngineUniforms {
246
271
  uCloudScale: { value: number };
247
272
  /** Cloud drift per second (style.clouds.speed) */
248
273
  uCloudSpeed: { value: Vector2 };
249
- /** Season tint of foliage (sky calendar) */
274
+ /** Unit vector toward the sun (sky, every frame); share the object in your own sky: mySky.material.uniforms.sunPosition = engine.uniforms.uSunDir */
275
+ uSunDir: { value: Vector3 };
276
+ /** 0 at night .. 1 at noon (sky, the sun it draws) */
277
+ uDaylight: { value: number };
278
+ /** Time of day 0-1 the sky draws (calendar time, or the sky's fixed time) */
279
+ uTimeOfDay: { value: number };
280
+ /** Zenith color the sky draws this frame (keyframes, look.sky top, weather tint, lightning); linear, like every THREE.Color */
281
+ uSkyTop: { value: Color };
282
+ /** Horizon color the sky draws this frame (or the backdrop color); the default fog color ('horizon') is this same color. Read it for a shader that should meet the sky */
283
+ uSkyHorizon: { value: Color };
284
+ /** Season tint of foliage (sky, by the calendar's season) */
250
285
  uFoliageTint: { value: Color };
251
- /** Season tint of the ground (sky calendar) */
286
+ /** Season tint of the ground (sky, by the calendar's season) */
252
287
  uGroundTint: { value: Color };
253
288
  uFoliageMix: { value: number };
254
289
  uGroundMix: { value: number };
290
+ /** Snow / ash cover amount alone, x foliage, y ground, 0-1 (the 'look.ground.cover' point); the tints above already hold it blended in */
291
+ uCover: { value: Vector2 };
255
292
  }
256
293
 
294
+ /** Mouse / touch pointer. ndcX/ndcY are screen coordinates in -1..1 */
257
295
  export interface Pointer {
258
296
  /** Pixels from the canvas's top-left corner (not the window's): the same space as worldToScreen and the UI root */
259
297
  x: number; y: number;
@@ -289,17 +327,26 @@ export type StringTables = Record<string, Record<string, string>>;
289
327
  * later parts wait for it to finish before loading).
290
328
  * first: true providers load first (parts such as the level, where the rest only makes sense after it is loaded) */
291
329
  export interface SaveProvider {
330
+ /** This part's data now: plain data (structuredClone can copy it; no functions, DOM nodes or three objects). It may be the live object the
331
+ * part keeps: the engine copies it for its rollback point before a load, so a load() that writes into that same object can still be undone.
332
+ * Data that cannot be copied makes a load refuse before anything changes (save-part-threw) */
292
333
  save: () => any;
334
+ /** Read data back; may return a Promise (later parts wait). Listener errors of events it emits count as the load throwing, also after an await */
293
335
  load: (data: any) => void | Promise<void>;
294
336
  /** Load before the other parts (such as the level) */
295
337
  first?: boolean;
296
338
  /** Join atomic ops: copied before an atomic op runs, put back if it fails (plain data; afterLoad does not run on rollback) */
297
339
  atomic?: boolean;
340
+ /** Dev only: called once start() finished with this part's data in the new-game state, to warn about what should not be there yet (world: records placed by code) */
341
+ checkNewGame?: (data: any) => void;
298
342
  /** This part's format version, default 1: raise it by 1 when what save() returns changes shape. A save with a newer version is refused */
299
343
  version?: number;
300
344
  /** Upgrade steps: old version -> data => data in the next version's shape, e.g. { 1: d => ({ ...d, beds: [] }) }.
301
345
  * The second argument is the whole save as read ({ parts, versions }, read only), for a step that depends on another part */
302
346
  migrate?: Record<number, (data: any, save: { parts: Record<string, any>, versions: Record<string, number> }) => any>;
347
+ /** This part's data used to be saved under another part's name: { oldPart: data => newData } (newData in this version's shape). An old save without
348
+ * this part but with oldPart loads it here; oldPart is then dropped unless a registered part still owns that name */
349
+ movedFrom?: Record<string, (data: any) => any>;
303
350
  }
304
351
 
305
352
 
@@ -318,8 +365,23 @@ export type AssetEntry = string | ModelBuilder | {
318
365
  url?: string;
319
366
  /** Model: generator function (instead of url) */
320
367
  build?: ModelBuilder;
321
- /** Model: parameters passed to build */
322
- params?: any;
368
+ /**
369
+ * Model: a params schema (core/params.js format plus 'color'), e.g. { height: { type: 'number', min: 1, max: 8, default: 3 } }: build gets one
370
+ * object (defaults < dev panel values < a call's own ['name', { ... }]) and the dev panel shows the fields
371
+ */
372
+ params?: Record<string, string | { type: string; default?: any; min?: number; max?: number; values?: any[]; desc?: string; optional?: boolean }>;
373
+ /**
374
+ * Model generator: false = never stored in the dev cache (.threedog/cache); for materials the GLB round trip cannot keep
375
+ * (own onBeforeCompile, ShaderMaterial uniforms that code keeps a reference to)
376
+ */
377
+ cache?: boolean;
378
+ /**
379
+ * Model: every mesh casts (receives) shadows, or none does. Left out: a generator that set the flag on any mesh keeps its own,
380
+ * otherwise (files, generators that set nothing) all meshes cast and receive
381
+ */
382
+ castShadow?: boolean;
383
+ /** Model: see castShadow */
384
+ receiveShadow?: boolean;
323
385
  /** Bake manifest (bake.js) only: 'file' = the baked file is the source of truth (edited in Blender), npm run bake no longer overwrites it */
324
386
  source?: 'file';
325
387
  /** Preload at startup */
@@ -354,10 +416,17 @@ export interface AssetManifest {
354
416
  base?: string | URL;
355
417
  /** Models (.glb / .gltf, Draco/Meshopt compression also works): name -> path or generator function */
356
418
  models?: Record<string, AssetEntry>;
357
- /** Textures: name -> path */
358
- textures?: Record<string, AssetEntry>;
359
- /** Sounds: name -> path */
360
- sounds?: Record<string, AssetEntry>;
419
+ /**
420
+ * Textures: name -> path, or a texture made in code: a function returning a THREE.Texture (run once, on first use) or the Texture itself.
421
+ * Code textures come back as made (their colorSpace / wrap / repeat are yours) and are never disposed by the engine if passed as a Texture.
422
+ * Example: textures: { brick: () => makeBrickTexture(), sign: mySignTexture }
423
+ */
424
+ textures?: Record<string, AssetEntry | Texture | (() => Texture | Promise<Texture>)>;
425
+ /**
426
+ * Sounds: name -> file path, or a sound made in code: a synth function (SynthFn) or { build: synthFn, params } (params: its defaults). Used by name
427
+ * like a file: audio.sfx(name), audio.sounds rules (src / variants), music and ambience. Example: sounds: { step: '/sfx/step.ogg', ding: dingSynth }
428
+ */
429
+ sounds?: Record<string, AssetEntry | SynthFn | { build: SynthFn; params?: Record<string, any> }>;
361
430
  /** Fonts: name -> file, or { url, family, weight, style, ... } (family defaults to the name). style.ui.fonts lists the names the UI uses */
362
431
  fonts?: Record<string, string | FontAssetEntry>;
363
432
  }
@@ -378,9 +447,13 @@ export interface Assets {
378
447
  * Register an asset manifest or asset pack (can be called several times; a later entry with the same name replaces the earlier one). Its name labels
379
448
  * it in engine.loading, base resolves its relative paths
380
449
  */
381
- manifest(m: AssetManifest): this;
450
+ manifest(m: AssetManifest | AssetManifest[]): this;
382
451
  /** The generator function registered under a model name, null for a file model or an unknown name (content builds [name, ...params] models with it) */
383
452
  builder(name: string): ((...args: any[]) => any) | null;
453
+ /** The params of a generator registered with a params schema: { schema, values (built with now), tuned (from setParams) }, or null */
454
+ paramsOf(name: string): { schema: Record<string, any>; values: Record<string, any>; tuned: Record<string, any> } | null;
455
+ /** Dev tuning: build a generator with these params (replacing its defaults) and swap every live copy in place; the dev panel's models folder calls it */
456
+ setParams(name: string, values: Record<string, any>): Promise<{ why: string; names: string[]; copies: Record<string, number>; ms: number; partsChanged?: string[] }>;
384
457
  /**
385
458
  * Preload (onProgress(0–1, current name)). Code-generated models and fonts are only loaded up front if marked preload. failed includes entries now
386
459
  * showing their fallback
@@ -397,22 +470,27 @@ export interface Assets {
397
470
  */
398
471
  model(nameOrUrl: string, opts?: { castShadow?: boolean; receiveShadow?: boolean; static?: boolean }): Promise<Object3D>;
399
472
  /**
400
- * A model copy right now if it has already loaded, else null (never starts a load, never waits): lets code that rebuilds often skip the frame an await costs
473
+ * A model copy right now if it has already loaded, else null (never starts a load, never waits): lets code that rebuilds often skip the frame an await costs.
474
+ * Code-built models (a build function in the manifest) count too: they are null until one await model(name) or an entry with preload: true ran (dev warns [asset-not-loaded])
401
475
  * @example const m = engine.assets.modelNow('villager') ?? await engine.assets.model('villager');
402
476
  */
403
477
  modelNow(nameOrUrl: string, opts?: { castShadow?: boolean; receiveShadow?: boolean; static?: boolean }): Object3D | null;
404
478
  /** Get the geometry of the first mesh in a model */
405
479
  geometry(nameOrUrl: string): Promise<BufferGeometry>;
480
+ /** An image as grid data for sampleGrid: PNG at 8 or 16 bits (jpg / webp 8). channel 'r' (default) 'g' 'b' 'a' or 0-3; range maps pixels to [min, max] (default [0, 1]) */
481
+ gridFromImage(nameOrUrl: string, opts?: { channel?: 'r' | 'g' | 'b' | 'a' | number; range?: [number, number]; bits?: 8 | 16 }): Promise<{ data: Float32Array; width: number; height: number; bits: number }>;
406
482
  /** Get a texture (.ktx2 compressed textures also work) */
407
483
  texture(nameOrUrl: string, opts?: { color?: boolean; pixelated?: boolean; repeat?: number[] }): Promise<Texture>;
484
+ /** Fetch a texture for something that already shows a stand-in: use(texture) runs when it arrives; a failed load is one load-failed dev warning naming `where` and what shows `instead`, and resolves false (an error inside use() is not swallowed). opts are texture()'s options */
485
+ useTexture(nameOrUrl: string, use: (texture: Texture) => void, o?: { where?: string; instead?: string; opts?: { color?: boolean; pixelated?: boolean; repeat?: number[] } }): Promise<boolean>;
408
486
  /**
409
487
  * Release a resource and return GPU memory. Not released while copies of the model are still in the scene; it is released when the last copy is
410
488
  * removed with engine.remove
411
489
  */
412
490
  release(name: string): void;
413
491
  /**
414
- * Release every model that has no copy in use (called automatically after level changes). Models whose shared geometry was taken by geometry() /
415
- * cached() are not released automatically. Returns the released names
492
+ * Release every model that has no copy in use (called automatically after level changes). Models whose shared geometry was taken by geometry() and
493
+ * code-generated models are not released automatically. Returns the released names
416
494
  */
417
495
  trim(): string[];
418
496
  /** How many copies of this model are in use now (taken with model() and not yet removed with engine.remove) */
@@ -422,13 +500,6 @@ export interface Assets {
422
500
  * under it
423
501
  */
424
502
  forget(obj: Object3D): void;
425
- /**
426
- * Code-generated model: generated only once per name + params, returns a copy (for geometry, the same one).
427
- * Order: files baked by npm run bake (public/models/baked/) -> automatic dev cache (.threedog/cache, invalidated automatically when the generator or
428
- * a file it imports changes) -> compute now.
429
- * When the generator is newer than the baked file during development, it computes now and prints a one-time hint "run npm run bake once it is final"
430
- */
431
- cached<T = any>(name: string, build: (params?: any) => T | Promise<T>, params?: any): Promise<T>;
432
503
  /** Generations faster than this many milliseconds are not written to the automatic cache (reading the file would be slower), default 20 */
433
504
  cacheMinMs: number;
434
505
  /** Geometry and materials shared by model copies (engine.remove does not release them, use release) */
@@ -527,13 +598,15 @@ export type AudioBus = 'master' | 'music' | 'sfx' | 'ambience' | 'ui' | (string
527
598
  /** A playing sound (returned by audio.sfx / audio.play): stop(fade), fade(to, seconds), setPosition(at) */
528
599
  import type { SoundHandle } from './generated/core/audioVoice';
529
600
  export type { SoundHandle };
530
- /** One sounds entry in full form. src: a file or variants (random, no immediate repeat); synth: a registered synth name (default: the entry's own name) */
601
+ /**
602
+ * One sounds rule in full form: how a sound plays, never what it is made of (that is the asset manifest's: a file or a synth function).
603
+ * src: an asset pack sound name or a path, or variants (random, no immediate repeat); default: the asset of the rule's own name
604
+ */
531
605
  export interface SoundDef {
532
606
  src?: string | string[];
533
- synth?: string;
534
- /** Passed to the synth (merged over its registered defaults) */
607
+ /** Passed to a synth source (merged over the manifest entry's params) */
535
608
  params?: Record<string, any>;
536
- /** Bus it plays on (default 'sfx', or the synth's registered bus) */
609
+ /** Bus it plays on (default 'sfx', or the built-in synth's own bus) */
537
610
  bus?: AudioBus;
538
611
  volume?: number;
539
612
  /** Playback rate multiplier (1 = as recorded); synths get it as params.pitch */
@@ -548,7 +621,7 @@ export interface SoundDef {
548
621
  /** 3D falloff for sfx(name, { at }): ref meters at full volume (2), max meters (60), rolloff (1) */
549
622
  distance?: { ref?: number; max?: number; rolloff?: number };
550
623
  }
551
- /** A sounds entry: a file, variants, 'synth' (the synth registered under the same name) or the full form */
624
+ /** A sounds rule: a sound name / path, variants, or the full form */
552
625
  export type SoundSource = string | string[] | SoundDef;
553
626
  /** A measure comparison in a rule's `when`: every given key must hold ({ daylight: { gt: 0.15 } }, { rain: { lt: 0.2 } }) */
554
627
  export interface AudioCompare { gt?: number; gte?: number; lt?: number; lte?: number }
@@ -574,11 +647,14 @@ export interface AmbienceRule {
574
647
  /** Bus (default 'ambience') */
575
648
  bus?: AudioBus;
576
649
  }
577
- /** Synthesized sound: connect to `out` and return the length in seconds, or { stop(time) } for a loop (params.loop is true then) */
650
+ /**
651
+ * Synthesized sound, registered as a sound asset (assets.manifest({ sounds: { ding: fn } }) or { build: fn, params }): connect to `out` and return
652
+ * the length in seconds, or { stop(time) } for a loop (params.loop is true then)
653
+ */
578
654
  export type SynthFn = (audio: Audio, params: Record<string, any>, out: any) => number | void | { stop(time: number): void };
579
655
 
580
656
  /**
581
- * The audio table of a content pack (content.load({ audio })): data only. sounds name asset pack sounds ('synth' for a built-in);
657
+ * The audio table of a content pack (content.load({ audio })): data only. sounds are play rules naming asset pack sounds (files or synths);
582
658
  * ambience and music.rules use condition keys and measures, never functions. Merged with createEngine({ audio }); a name in both is an error
583
659
  */
584
660
  export interface ContentAudio {
@@ -587,9 +663,9 @@ export interface ContentAudio {
587
663
  music?: { tracks?: Record<string, import('./gameplay').MusicTrack>; rules?: import('./gameplay').MusicRule[] };
588
664
  footsteps?: Record<string, string>;
589
665
  }
590
- /** The game's sound config: createEngine({ audio }), read back as engine.audio.config (merged with content packs' ContentAudio). Not part of a style pack */
666
+ /** The game's sound config: createEngine({ audio }), read back as engine.audio.config (merged with content packs' ContentAudio). Not part of a style */
591
667
  export interface AudioConfig {
592
- /** Sound name -> file / variants / 'synth' / SoundDef */
668
+ /** Sound name -> play rule: an asset sound name / path, variants, or SoundDef */
593
669
  sounds?: Record<string, SoundSource>;
594
670
  /** ambience() rule table */
595
671
  ambience?: AmbienceRule[];
@@ -629,6 +705,8 @@ export interface UIPart {
629
705
  /** May return a promise that resolves when a fade-out has finished (engine.ui.settled() waits for it) */
630
706
  hide?(): void | Promise<void>;
631
707
  dispose?(): void;
708
+ /** A modal part's root element: the UI choice cursor (uiFocus nav) moves over the controls inside it, so the part works with a gamepad / keyboard only */
709
+ readonly el?: HTMLElement | null;
632
710
  [key: string]: any;
633
711
  }
634
712
  /** Your own part: called once per single part (loading, toast, title) or once per item (hud.*); options are what the game passed as an object */
@@ -660,7 +738,7 @@ export interface TouchView {
660
738
  press(action: string): void;
661
739
  release(action: string): void;
662
740
  }
663
- /** A title screen button: built-ins 'start' | 'continue' | 'settings', or your own */
741
+ /** A title screen button: built-ins 'start' | 'continue', a module's button by id (engine.ui.titleItem: 'settings'), or your own */
664
742
  export interface UITitleItem {
665
743
  id?: string;
666
744
  label: string | ((engine: Engine) => string);
@@ -685,6 +763,8 @@ export interface UIParts {
685
763
  /** Close a full-screen part, emits ui:close */
686
764
  close(name: string): void;
687
765
  isOpen(name: string): boolean;
766
+ /** Add a title screen button from a module (settings adds 'settings'): shown after continue / start, and nameable by id in the title's items. ctx.track the handle */
767
+ titleItem(id: string, item: { label: string | ((engine: Engine) => string); run(engine: Engine): any }): { remove(): void };
688
768
  /** name -> 'default' | 'custom' | 'off' */
689
769
  describe(): Record<string, string>;
690
770
  /**
@@ -722,7 +802,7 @@ export interface Ground {
722
802
  forEachCollider?(x: number, z: number, range: number, fn: (cx: number, cz: number, r: number) => void): void;
723
803
  /** Optional: chunk edge length (meters) */
724
804
  chunkSize?: number;
725
- /** Optional: how far (meters) the ground is shown around a stream source now; stream entries build within it by default (else fogFar) */
805
+ /** Optional: how far (meters) the ground is shown around a stream source now; stream entries build within it by default (else the fog distance, look.fog far) */
726
806
  viewRange?(): number;
727
807
  /** Optional: collision data of a chunk (used by the physics module) */
728
808
  chunkCollision?(cx: number, cz: number): any;
@@ -738,6 +818,37 @@ export interface Ground {
738
818
  // Module definition
739
819
  // ======================================================================
740
820
 
821
+ /** What a module's install / init receive: the module's name, track(handle) and mod(point, o), both tied to the module's life */
822
+ export interface ModuleCtx {
823
+ readonly name: string;
824
+ /** Keep handle (anything with remove(): events.on, onFixed, onFrame, clock timers, audio.measure...) until the module goes: removed when its use()
825
+ * batch rolls back, its init fails, it is replaced, or on engine.dispose() before its dispose hook. Returns the handle */
826
+ track<H extends { remove(): void }>(handle: H): H;
827
+ /**
828
+ * engine.mod with this module as the owner, tracked: the change goes when the module goes. Passing owner throws (use engine.mod for another name).
829
+ * @example ctx.mod('time.world', { mul: 0.8, layer: 'effect' })
830
+ */
831
+ mod(point: string, opts: Omit<import('./gameplay').ModOptions, 'owner'>): import('./gameplay').ModHandle;
832
+ /**
833
+ * engine.control with this module as the default owner, tracked: every character the module holds is handed back when the module goes.
834
+ * @example const h = ctx.control.take(guard, { layer: 'script', step: (dt, ch) => ({ x: 1, z: 0 }) })
835
+ */
836
+ control: {
837
+ take(who: any, opts?: Omit<Parameters<Control['take']>[1], 'owner'> & { owner?: string }): ReturnType<Control['take']>;
838
+ /** True while owner (default the module) holds the character */
839
+ has(who: any, owner?: string): boolean;
840
+ };
841
+ /**
842
+ * Run fn once while start() waits for the GPU to compile shaders (the page's thread is idle then), for a one-time warm-up that would
843
+ * otherwise land in the first frame: a WASM library's first call compiles its code. After start() it runs at once.
844
+ * @example ctx.whileCompiling(() => { const w = new R.World(g); w.step(); w.free(); })
845
+ */
846
+ whileCompiling(fn: () => void): void;
847
+ }
848
+
849
+ /** What a module may own (ModuleDef.type; core/moduleTypes.js) */
850
+ export type ModuleType = 'world' | 'look' | 'actor' | 'rules' | 'ui' | 'net' | 'tool';
851
+
741
852
  /**
742
853
  * A module (the argument of engine.use). The name is the property name on the engine once installed.
743
854
  * Per-frame hook order follows stage, then before / after within a stage, then install order.
@@ -745,10 +856,24 @@ export interface Ground {
745
856
  export interface ModuleDef<Api = any> {
746
857
  /** Module name; after install, access the object returned by install through engine[name] */
747
858
  name: string;
859
+ /**
860
+ * What the module may own (required; core/moduleTypes.js): 'world' state, records, ops (draws nothing) | 'look' what is seen and heard (changes no
861
+ * game state: no ops, no world record writes) | 'actor' characters | 'rules' game logic | 'ui' panels and menus (binds no keys, no game save part)
862
+ * | 'net' multiplayer | 'tool' a one-shot job. A game module is usually 'rules'. Breaking a rule throws in dev with the fix.
863
+ */
864
+ type: ModuleType;
748
865
  /** Display name (used by the loading screen) */
749
866
  label?: string;
750
- /** Names of other modules this depends on; they must be installed first (an error is thrown if not) */
867
+ /**
868
+ * Capabilities this depends on: slot names another module provides ('inventory', 'world', 'sky'), never a particular module. Missing throws with both
869
+ * fixes: install the engine's part of that name first, or your own module with provides: ['inventory']
870
+ */
751
871
  requires?: string[];
872
+ /**
873
+ * Capabilities this module holds while installed ("only one may hold this": 'sky', 'inventory'); engine.<slot> is its API too, so dependents keep
874
+ * working when a game swaps it: engine.use(mine(), { replaces: 'inventory' }). A second provider throws shared-taken. describe().shared shows the holder.
875
+ */
876
+ provides?: string[];
752
877
  /**
753
878
  * Optional dependencies (modules the code uses as e.xxx?. or guards with if (e.xxx); rule R16 requires listing them all).
754
879
  * An array only registers them; written as { moduleName: 'what is lost when missing' }, start() prints a one-time development hint when one is
@@ -756,34 +881,32 @@ export interface ModuleDef<Api = any> {
756
881
  */
757
882
  optional?: string[] | Record<string, string>;
758
883
  /**
759
- * Hook stages (first -> last): 'control' timeline, camera -> 'world' terrain, level -> 'environment' weather, sky, water -> 'gameplay' interactions,
760
- * dialogue, triggers, entities
761
- * -> 'presentation' particles, settings, objective markers -> 'late' (default) -> 'audio' music. Within a stage use before / after, then install order
884
+ * Hook stages, only the run order (first -> last): 'control' timeline, camera -> 'ground' terrain, level -> 'environment' weather, sky, water
885
+ * -> 'gameplay' interactions, dialogue, triggers -> 'effects' particles, settings, objective markers -> 'late' (default) -> 'audio' music.
886
+ * Within a stage use before / after, then install order. What the module may own and how its errors are handled come from type
762
887
  */
763
- stage?: 'control' | 'world' | 'environment' | 'gameplay' | 'presentation' | 'late' | 'audio';
888
+ stage?: 'control' | 'ground' | 'environment' | 'gameplay' | 'effects' | 'late' | 'audio';
764
889
  /** Hooks run before these modules, inside one stage (ignored if not installed;
765
890
  * use() throws on a cycle, or when the other module's stage already runs earlier) */
766
891
  before?: string[];
767
892
  /** Hooks run after these modules, inside one stage (ignored if not installed;
768
893
  * use() throws on a cycle, or when the other module's stage already runs later) */
769
894
  after?: string[];
770
- /**
771
- * Presentation modules (particles, sound effects, HLOD; gameplay is unaffected without them): when a hook errors only this module is disabled and the
772
- * game continues.
773
- * Without it the module counts as gameplay: during development / testing an error freezes gameplay and is recorded in engine.error (error severity levels)
774
- */
775
- presentation?: boolean;
776
895
  /**
777
896
  * The game cannot run without this module (default false): when its init() fails, engine.start() rejects with the module name and reason instead of
778
- * starting a broken game. Without it a failed init is reported by severity (presentation: disabled and the game carries on; gameplay: error tiers) and
897
+ * starting a broken game. Without it a failed init is reported by severity (type look / ui: disabled and the game carries on; other types: error tiers) and
779
898
  * start() goes on. Only start() reads it; a critical module installed after start() is reported like any other
780
- * @example engine.use({ name: 'saveSlots', critical: true, async init(e) { await loadSlots(); } })
899
+ * @example engine.use({ name: 'saveSlots', type: 'rules', critical: true, async init(e) { await loadSlots(); } })
781
900
  */
782
901
  critical?: boolean;
783
- /** Install: create and return the object the game uses (engine.name) */
784
- install?(e: Engine): Api;
785
- /** Called at startup (download things, wait for assets); may be async */
786
- init?(e: Engine): void | Promise<void>;
902
+ /**
903
+ * Install: create and return the object the game uses (engine.name). Register listeners / timers through ctx.track so they leave with the module
904
+ * (a use() batch that rolls back, a failed init, engine.dispose)
905
+ * @example install(e, ctx) { ctx.track(e.events.on('item:add', onAdd)); return api; }
906
+ */
907
+ install?(e: Engine, ctx: ModuleCtx): Api;
908
+ /** Called at startup (download things, wait for assets); may be async. ctx is the same as install's */
909
+ init?(e: Engine, ctx: ModuleCtx): void | Promise<void>;
787
910
  /** The loading screen waits until this returns true before disappearing (the hook is called isReady; in the engine ready is always a boolean property) */
788
911
  isReady?(e: Engine): boolean;
789
912
  /** After a save loaded: rebuild what the loaded state needs nearby; gameplay waits frozen until the returned Promise resolves */
@@ -795,9 +918,9 @@ export interface ModuleDef<Api = any> {
795
918
  /** After rendering */
796
919
  afterRender?(dt: number, e: Engine): void;
797
920
  /**
798
- * engine.skip moved time without stepping: advance your own time by dt fixed seconds (game seconds = dt x clock.timeScale), no per-step work.
799
- * Called once per skip segment (segments end at timers and sky clock marks); done is true on the last one: do expensive catch-up only then.
800
- * Only for modules that keep time themselves (sky, world); modules that compare against clock.now need nothing
921
+ * engine.skip moved time without stepping: advance your own time by dt fixed seconds (calendar seconds = dt x clock.speed), no per-step work.
922
+ * Called once per skip segment (segments end at timers and calendar clock marks); done is true on the last one: do expensive catch-up only then.
923
+ * Only for modules that keep time themselves (calendar, world); modules that compare against clock.now need nothing
801
924
  */
802
925
  skip?(dt: number, e: Engine, done: boolean): void;
803
926
  /**
@@ -810,7 +933,7 @@ export interface ModuleDef<Api = any> {
810
933
  counts?(e: Engine): number | Record<string, number>;
811
934
  /** Optional: answer engine.explain({ key: value }) for your own keys, e.g. explain: { quest: (e, id) => ({ ok: false, text: 'waits on step 2: ...' }) } */
812
935
  explain?: Record<string, (e: Engine, value: any, query: Record<string, any>) => { ok: boolean; text: string; [k: string]: any }>;
813
- /** Optional: handle the keys of engine.applyState that this module owns (e.g. sky handles time) */
936
+ /** Optional: handle the keys of engine.applyState that this module owns (e.g. calendar handles time and season) */
814
937
  applyState?(e: Engine, params: StateParams): void | Promise<void>;
815
938
  /**
816
939
  * Optional: called on engine.dispose() (in reverse install order). Only clean up what the core cannot: Workers, the physics world, real-time timers,
@@ -830,23 +953,22 @@ export type ModuleInput = ModuleDef | ModuleInput[] | false | null | undefined;
830
953
  export interface EngineOptions {
831
954
  /** Canvas element (required unless renderer is given), e.g. document.getElementById('view') */
832
955
  canvas?: HTMLCanvasElement | HTMLElement;
833
- /** A ready three.js renderer (WebGLRenderer or compatible) to use instead of creating one; canvas then defaults to renderer.domElement. The engine configures
834
- * (pixel ratio, size, tone mapping, shadows) only a renderer it created itself. WebGL is the fully supported path; WebGPU-style renderers may not run shader patches or post effects (recipe 48) */
835
- renderer?: any;
836
- /** Style pack (looks only: materials, sky, lighting, post, UI look), e.g. import lowpoly from '@threedog/style-lowpoly', or a list of parts
837
- * deep-merged left to right: [lowpoly, { sky: { sunSize: 600 } }]. Without one: neutral gray placeholders */
956
+ /** 'webgl' (default): the engine builds a WebGLRenderer. 'webgpu': it builds three's WebGPURenderer (needs import 'threedog/tsl' first) and start() awaits its init().
957
+ * Or a ready three.js renderer (WebGLRenderer or WebGPURenderer) used as is; canvas then defaults to renderer.domElement. The engine configures
958
+ * (pixel ratio, size, tone mapping, shadows) only a renderer it created itself. A WebGPURenderer passed in goes the same way as 'webgpu' (start() inits it if needed) */
959
+ renderer?: 'webgl' | 'webgpu' | EngineRenderer;
960
+ /** WebGPU route only: what start() does when the browser gives no WebGPU. 'webgl2' (default): the same WebGPURenderer on its WebGL2 backend, TSL keeps
961
+ * working; 'webgl': a WebGLRenderer instead (faster, but NodeMaterials cannot draw: start() fails if the scene has one); 'error': start() rejects.
962
+ * Every fallback prints one '[threedog] WebGPU unavailable (...)' line and shows in describe().renderer */
963
+ fallback?: 'webgl2' | 'webgl' | 'error';
964
+ /** Style (looks only: materials, sky, lighting, post, UI look), the game's own style (import style from './style/index.js'), or a list of parts
965
+ * deep-merged left to right: [basePack, { sky: { sunSize: 600 } }]. Without one: neutral gray placeholders */
838
966
  style?: StyleInput;
839
- /** Real-time shadows, default true */
840
- shadows?: boolean;
841
- /** Shadow filter: 'basic' (hard edge) | 'pcf' | 'vsm' (softest, costliest), default 'pcf'. Change later with engine.look.shadow.set({ type }) */
842
- shadowType?: 'basic' | 'pcf' | 'vsm';
843
- /** MSAA anti-aliasing (kept with post effects on), default style.antialias, else on for desktop and off for low-tier devices */
967
+ /** MSAA anti-aliasing (kept with post effects on), default style.antialias, else on for desktop and off for low-tier devices; with a renderer of your own, its own antialias. The start value is the canvas's own MSAA (no post chain while no effect is on) */
844
968
  antialias?: boolean;
845
- /** Turn style post effects on or off by name at startup, e.g. { bloom: false }; default: each effect's own setting (costly ones off on low-tier devices) */
846
- post?: Record<string, boolean>;
847
- /** Render resolution, default min(device pixel ratio, 1.5) */
969
+ /** Render resolution, default min(device pixel ratio, 1.5); the low tier uses at least 0.75 x device pixel ratio (never below 1). describe().render.scale reports it */
848
970
  pixelRatio?: number;
849
- /** Automatically lower resolution when the frame rate is too low, default true */
971
+ /** Automatically lower resolution when the frame rate is too low, default true. Never silent: a dev warning once, and describe().render.scale.autoLowered */
850
972
  adaptiveResolution?: boolean;
851
973
  /** Target frame rate for automatic resolution lowering, default 55 */
852
974
  targetFps?: number;
@@ -861,19 +983,15 @@ export interface EngineOptions {
861
983
  fov?: number;
862
984
  /** Camera near clipping plane (meters), default 0.3 */
863
985
  near?: number;
864
- /** Default fog distance (meters), default 600 */
865
- fogFar?: number;
866
- /** UI language: 'auto' (default) follows the browser (a language starting with zh gives 'zh-CN', anything else 'en'); or force 'zh-CN' | 'en' | your own */
986
+ /** UI language: 'auto' (default) follows the browser (a language starting with zh gives 'zh-CN', anything else 'en'); or force 'zh-CN' | 'en' | your own. Matched by language: 'zh' / 'zh-Hans' give 'zh-CN', 'en-US' gives 'en'; a language with no strings warns once */
867
987
  locale?: string;
868
988
  /** Override / add UI strings: { 'zh-CN': { key: text } } */
869
989
  strings?: StringTables;
870
990
  /**
871
- * Keys per action: changes the neutral defaults (move / confirm / cancel) and binds gameplay actions, e.g. { interact: ['KeyE'], run: ['ShiftLeft'] };
872
- * a module's define() keeps these keys
991
+ * The game's keys per action (keyboard, 'Mouse0', gamepad 'PadA' in one list), owner 'game': replaces the basics (move / confirm / cancel / UI
992
+ * cursor) and binds every other action, e.g. { interact: ['KeyE', 'PadX'], ...presets.bindings.dialogNumbers }. Same as engine.input.bind(map)
873
993
  */
874
- bindings?: Record<string, string[]>;
875
- /** Default gamepad buttons: { jump: 'PadA' } */
876
- padBindings?: Record<string, string>;
994
+ bindings?: Readonly<Record<string, string | readonly string[]>>;
877
995
  /** Save name prefix; must differ when several games share one site, default 'game' */
878
996
  saveKey?: string;
879
997
  /** On-screen joystick: 'auto' (only on touch devices) | true | false */
@@ -913,7 +1031,7 @@ export interface EngineOptions {
913
1031
  pauseOnBlur?: boolean;
914
1032
  /** false: no default lights in the scene at all (engine.lights.sun / hemi still exist, detached, so sky and describe never see undefined); the game adds its own. Default true */
915
1033
  lights?: boolean;
916
- /** Automatic instancing of repeated static models (engine.batching): false turns it off; default { minCount: 8, cell: engine.stream.cellSize } */
1034
+ /** Automatic instancing of repeated static models the engine places (engine.batching; your own meshes opt in with userData.batch = true): false turns it off; default { minCount: 8, cell: engine.stream.cellSize } */
917
1035
  batching?: false | BatchingOptions;
918
1036
  }
919
1037
 
@@ -1054,6 +1172,10 @@ export interface BatchingStats {
1054
1172
  instances: number;
1055
1173
  /** Draw calls saved per pass (instances - batches) */
1056
1174
  saved: number;
1175
+ /** Present while anything is batched: what batching did to the engine's content meshes and how to raycast / opt out / turn it off */
1176
+ note?: string;
1177
+ /** Dev only, while at least minCount identical game-made meshes draw unbatched: the opt-in line (obj.userData.batch = true) */
1178
+ hint?: string;
1057
1179
  }
1058
1180
  /** One entry of engine.batching.batches */
1059
1181
  export interface BatchInfo {
@@ -1125,10 +1247,15 @@ export interface StreamHandle { def: StreamEntryOptions; object: Object3D | null
1125
1247
  * Startup timing (milliseconds): totalMs page open to playable, startMs start() to playable, preloadMs preloading, streamMs the nearby builds required
1126
1248
  * by stream registrations finished, compileMs shader compilation before the first frame,
1127
1249
  * modules is the init / ready time of each module. With a budget on and startupMs (open to playable) / moduleMs (a single module) given, the slowest
1128
- * module is reported in the console when exceeded
1250
+ * module is reported in the console when exceeded.
1251
+ * firstFrameMs: page open to the end of the first frame drawn after the loading screen (null until that frame, and headless); phases add up to it:
1252
+ * script (page open until createEngine), construct (createEngine), setup (game code until start()), init (saves, renderer, module init), preload,
1253
+ * world (scenario parameters, nearby builds), compile (shaders + hidden warm-up frame), draw (ready until the first frame's draw calls were submitted)
1129
1254
  */
1130
1255
  export interface StartupReport {
1131
1256
  totalMs: number; startMs: number; preloadMs: number; streamMs: number | null; compileMs: number; modules: Record<string, { init?: number; ready?: number }>;
1257
+ firstFrameMs: number | null;
1258
+ phases: { script: number; construct: number; setup: number; init: number; preload: number; world: number; compile: number; draw: number | null };
1132
1259
  }
1133
1260
 
1134
1261
  // ======================================================================
@@ -1141,7 +1268,7 @@ export interface StateParams {
1141
1268
  state?: string;
1142
1269
  /** Time of day: 'HH:MM' or 0–1 */
1143
1270
  time?: string | number;
1144
- /** Season name from sky({ seasons }): jumps sky.day to that season's first day (time of day kept) */
1271
+ /** Season name from calendar({ seasons }): jumps calendar.day to that season's first day (time of day kept) */
1145
1272
  season?: string;
1146
1273
  /** Weather name */
1147
1274
  weather?: string;
@@ -1149,24 +1276,20 @@ export interface StateParams {
1149
1276
  pos?: string | PositionLike;
1150
1277
  /** Which save slot to load */
1151
1278
  save?: string;
1152
- /** How many seconds to advance (fixed-step seconds, not multiplied by clock.timeScale) */
1279
+ /** How many seconds to advance (real seconds: fixed-step seconds, no scale) */
1153
1280
  wait?: number;
1154
1281
  /** Opening cutscene: 'skip' skips it | 'keep' plays it as usual */
1155
1282
  cutscene?: 'skip' | 'keep';
1283
+ /** A view declared with engine.views to show after engine:ready (?view=name); ignored when the game declared no views */
1284
+ view?: string;
1285
+ /** Present (?play, any value): leave the title screen the way its Start does (engine.session.newGame(), the title part closes; flow leaves its start state) before wait; nothing when no title is up */
1286
+ play?: string | boolean;
1156
1287
  }
1157
1288
 
1158
1289
  /** A claim on something only its owner releases (pause, freeze, takeCamera, views) */
1159
1290
  export interface OwnerHandle { owner: string; remove(): void }
1160
- /** What pause / freeze return: the claim handle, plus the old chaining calls forwarded to the engine */
1161
- export interface ChainedHandle extends OwnerHandle {
1162
- pause(owner?: string | { owner?: string; kind?: 'test' }, opts?: { kind?: 'test' }): ChainedHandle;
1163
- resume(owner?: string | { owner?: string }): Engine;
1164
- freeze(owner?: string | { owner?: string; kind?: 'title' }, opts?: { kind?: 'title' }): ChainedHandle;
1165
- unfreeze(owner?: string | { owner?: string }): Engine;
1166
- step(seconds: number, opts?: { render?: boolean; frameEvery?: number; describe?: boolean }): GameState | null;
1167
- }
1168
- /** engine.runState: state in one word, by = every pause / freeze owner, blockedBy = opaque input contexts plus 'error' / 'loading' */
1169
- export interface RunState { state: 'loading' | 'title-frozen' | 'test-paused' | 'paused' | 'running'; by: string[]; blockedBy: string[] }
1291
+ /** engine.runState: state in one word, owners = every pause / freeze owner, blockedBy = opaque input contexts plus 'error' / 'loading' */
1292
+ export interface RunState { state: 'loading' | 'title-frozen' | 'test-paused' | 'paused' | 'running'; owners: string[]; blockedBy: string[] }
1170
1293
  /** Camera takeover: when non-null no camera module moves the camera (for cutscenes); see engine.takeCamera */
1171
1294
  export interface CameraOverride {
1172
1295
  /** Who took over (any name) */
@@ -1176,7 +1299,7 @@ export interface CameraOverride {
1176
1299
  [key: string]: any;
1177
1300
  }
1178
1301
  /** State of automatic resolution */
1179
- export interface AdaptiveState { paused: boolean; on: boolean; target: number; min: number; max: number; [key: string]: any }
1302
+ export interface AdaptiveState { paused: boolean; on: boolean; target: number; min: number; max: number; /** true once the render scale was lowered below max (a dev warning was logged) */ lowered?: boolean; [key: string]: any }
1180
1303
 
1181
1304
  // ======================================================================
1182
1305
  // Look parts engine.look.<part> (recipes/52-look.md)
@@ -1184,14 +1307,59 @@ export interface AdaptiveState { paused: boolean; on: boolean; target: number; m
1184
1307
 
1185
1308
  /** Returned by set / patch / replace: remove() takes that owner's layer back off */
1186
1309
  export interface LookHandle { remove(): void }
1187
- /** engine.look.post: a LookPart with add() for one custom pass */
1310
+ /** engine.look.shadow */
1311
+ export interface LookShadowPart extends LookPart<LookShadow> {
1312
+ /**
1313
+ * Let cascaded shadows patch a lit ShaderMaterial of yours (lights: true, built from THREE.ShaderLib); built-in lit materials need nothing. Returns it.
1314
+ * @example engine.look.shadow.include(myShaderMaterial);
1315
+ */
1316
+ include<M extends import('three').Material>(material: M): M;
1317
+ }
1318
+ /** engine.look.post: a LookPart whose add() is the one way to put a post effect in the chain (game code, the plugins folder and style plugins all use it) */
1188
1319
  export interface LookPost extends LookPart {
1189
- /** Add ONE custom post pass (name, create | fuse, slot, order, params) without replacing the chain; remove() takes it out again. Slot, order and depth-order errors throw and add nothing. Change its params with set({ '<name>.<param>': v }) */
1190
- add(effect: PostEffect, opts?: LookOptions): LookHandle;
1320
+ /**
1321
+ * Add one post effect: a plain three.js Pass (WebGL; placed by kind: a pass that renders engine.scene itself replaces the scene render,
1322
+ * FXAA / SMAA / TAA run last, any other after the style's effects in 'hdr'), a node function (input, ctx) => node (WebGPU), or an effect
1323
+ * { name, create, node, fuse, slot, order, params } (both renderers). opts: name (its look.post key: set({ [name]: false })), slot, order
1324
+ * (position in the chain), owner. Slot, order and depth-order errors throw and add nothing. remove() takes it out (a Pass of yours is not disposed)
1325
+ * @example engine.look.post.add(new UnrealBloomPass(size, 0.6, 0.4, 0.85), { name: 'glow' }); engine.look.post.set({ glow: false });
1326
+ */
1327
+ add(x: PostEffect | { render(...args: any[]): any } | ((input: any, ctx: any) => any),
1328
+ opts?: { name?: string; slot?: import('./generated/render/PostFX').PostSlot; order?: number; owner?: string }): { name: string | null; remove(): void };
1191
1329
  }
1192
- /** owner: who writes the layer (non-empty name, default 'game'); roles: only materials.patch, the material roles that get the patch */
1193
- export interface LookOptions { owner?: string; roles?: string[] }
1194
- /** patch(name, spec): a spec instead of plain GLSL. post: fuse snippet (glsl, slot, order, uniforms, values); sky 'layer:<name>': glsl, blend, order, uniforms */
1330
+ /** engine.look.materials: a LookPart whose add() puts a shader patch on some roles, with glow() for emissive that follows daylight */
1331
+ export interface LookMaterials extends LookPart<Record<string, Record<string, any>>> {
1332
+ /**
1333
+ * Add a named ShaderPatch to the materials made for roles (none = all) from now on; the handle's remove() takes it out. (Was materials.patch:
1334
+ * patch only swaps a named hook, and materials have none.)
1335
+ * @example const h = engine.look.materials.add('tint', { slot: 'color', glsl: 'diffuseColor.rgb *= 0.9;' }, { roles: ['wool'] });
1336
+ */
1337
+ add(name: string, patch: import('./generated/render/patches').ShaderPatch | Record<string, any>, opts?: { roles?: string[]; owner?: string }): LookHandle;
1338
+ /**
1339
+ * Materials matching `match` (a material role or material.name such as 'window', one Material, or (material) => boolean) get emissiveIntensity
1340
+ * `night` at night and `day` by day, faded in as daylight (calendar, else sky) drops below `dusk` (default 0.3, a starting value: raise it
1341
+ * for signs that come on early, lower it for things that only glow in full dark; 0 = on only while daylight is 0). Finds models built later (templates, streamed
1342
+ * cells) after each scene change; the emissive color stays the game's. remove() gives each material its own emissiveIntensity back.
1343
+ * describe().look.materials lists each rule and how many materials it found
1344
+ * @example engine.look.materials.glow('window', { night: 2 });
1345
+ */
1346
+ glow(match: string | import('three').Material | ((material: import('three').Material) => boolean), opts: { night: number; day?: number; dusk?: number; owner?: string }): LookHandle;
1347
+ /**
1348
+ * Make every material makeMaterial made that is on a mesh in the scene again from the current layers (type, replace, patches, spec) and put
1349
+ * the new one in its place: the one way a patch / replace / type change reaches materials made before it. Keeps the call's own params, live
1350
+ * keys set by hand and patches added after makeMaterial (wind, cloud shadow); the old material is disposed. engine.plugins.off / on of a
1351
+ * material or patch plugin calls it. kept: made materials the scene does not hold (left as they are).
1352
+ * @example engine.look.materials.rebuild(); // after look.materials.add / replace, for the materials already out
1353
+ */
1354
+ rebuild(): { rebuilt: number; kept: number; ms: number };
1355
+ }
1356
+ /** owner: who writes the layer (non-empty name, default 'game'); roles: only materials.add, the material roles that get the patch */
1357
+ export interface LookOptions {
1358
+ owner?: string; roles?: string[];
1359
+ /** look.ground.replace(myMaterial, { effects: false }): your material as is, no cloud shadow / season / detail patch */
1360
+ effects?: boolean;
1361
+ }
1362
+ /** patch(hook, spec): a spec instead of plain GLSL ({ glsl, tsl, uniforms }); sky 'layer:<name>': glsl, blend, order, uniforms */
1195
1363
  export interface LookPatchSpec {
1196
1364
  glsl?: string | Record<string, any>;
1197
1365
  /** post: 'hdr' | 'ldr' */
@@ -1207,32 +1375,44 @@ export interface LookPatchSpec {
1207
1375
 
1208
1376
  /**
1209
1377
  * One look part. Layers, upper wins: engine default < style < game (per owner, last write wins) < engine.debug.override.
1210
- * A part offers only the verbs that make sense for it; the others throw naming the verb to use.
1378
+ * Every part has the same verbs (docs/plans/2026-11-03-look-api.md); a part offers the ones that make sense for it, the others throw naming
1379
+ * the call to use: set (values), patch (swap a named hook), add (one more named thing), replace (the one three.js thing it draws),
1380
+ * manual (the engine stops writing), value (the one read). A whole module (behaviour, saves) is engine.use(mine(), { replaces: '<slot>' }).
1211
1381
  */
1212
1382
  export interface LookPart<P = Record<string, any>> {
1213
1383
  /** 'look.<part>': the id engine.catalog() and debug.override use */
1214
1384
  readonly id: string;
1215
1385
  /** Shallow-merge into the owner's layer, only the keys given; null drops a key so the layer below shows again. Keys that recompile shaders warn once in dev */
1216
1386
  set(params: { [K in keyof P]?: P[K] | null } & Record<string, any>, opts?: LookOptions): LookHandle;
1217
- /** Swap one named GLSL hook the part registered (names: engine.catalog('look.<part>').hooks); the same name again overrides; patch(name, null) restores the default */
1218
- patch(name: string, glsl: string | LookPatchSpec | null, opts?: LookOptions): LookHandle;
1219
- /** Take the whole part over (Material, texture, object, effect list ...: see the catalog); replace(null) gives it back. materials.replace takes the role first */
1220
- replace(impl: any, opts?: LookOptions): LookHandle;
1221
- replace(role: string, impl: any, opts?: LookOptions): LookHandle;
1222
- /** Drop every game and debug layer of that owner (the style value shows again); returns how many layers were removed, like engine.debug.clear */
1223
- clear(owner: string): number;
1224
- /** The resolved value of a key (what is in use now) */
1387
+ /** Swap one named hook the part declares (names: engine.catalog('look.<part>').hooks); the same name again overrides; patch(hook, null) restores the default */
1388
+ patch(hook: string, code: string | LookPatchSpec | null, opts?: LookOptions): LookHandle;
1389
+ /** Put one more named thing in next to the engine's (look.post.add, look.materials.add); the handle's remove() takes it out. Other parts throw */
1390
+ add(...args: any[]): LookHandle;
1391
+ /** Swap the one three.js thing the part draws (texture, sky object, Material, effect list ...: see the catalog); replace(null) gives it back. materials.replace takes the role first */
1392
+ replace(thing: any, opts?: LookOptions): LookHandle;
1393
+ replace(role: string, thing: any, opts?: LookOptions): LookHandle;
1394
+ /**
1395
+ * Take values the engine writes on its own (every frame or on a timer: the sky's sun, the fog, camera.far ...) for the game: the engine stops
1396
+ * writing them and the three.js object is yours. manual(keys, false) or the handle's remove() gives them back. Keys match by dotted prefix
1397
+ * ('sun' takes sun.intensity and sun.color); none = every one of the part; a key that matches nothing throws with the part's keys.
1398
+ * A direct write without manual() takes the value too (the engine yields and warns once). Which values: describe().owned, recipes/52 "Who writes it".
1399
+ * @example engine.look.lights.manual('sun'); engine.lights.sun.intensity = 3;
1400
+ */
1401
+ manual(keys?: string | string[] | boolean, on?: boolean): LookHandle;
1402
+ /** The value in effect for a key (after every layer): the one read. Who set it and how: engine.describe().look.<part> */
1225
1403
  value(key: string): any;
1226
- /** The value from the highest game / debug layer for the key (undefined when only style or default gives it) */
1227
- top(key: string): any;
1228
1404
  /** The three.js object(s) behind the part (renderer, lights, scene.fog ...); changing it directly works but describe tags it 'three'.
1229
1405
  * look.materials: a function, object('wool') = the last Material made for that role, object() = all of them */
1230
1406
  readonly object: any;
1407
+ /** For module code that defines or drives a part (defineLookPart, recipes/52-look.md "Your own part"); a game never needs it */
1408
+ readonly author: LookPartAuthor;
1409
+ }
1410
+ /** part.author: raw writes, extending keys, drivers and the per-frame tick, for module code. Kept off LookPart so a game's autocomplete shows only the game verbs */
1411
+ export interface LookPartAuthor {
1231
1412
  /** Each verb's call shape, e.g. { set: 'set(params, { owner })', replace: 'replace(role, ...)' } (also in engine.catalog('look.<part>')) */
1232
1413
  readonly signatures: Record<string, string>;
1233
- // ---- for authors of a part made with defineLookPart (recipes/52-look.md) ----
1234
1414
  /** Write raw keys (params, 'hook:<name>', '@replace') for an owner, no normalize; null drops a key */
1235
- write(owner: string, values: Record<string, any>, opts?: { layer?: 'game' | 'debug' }): LookHandle;
1415
+ write(owner: string, values: Record<string, any>, opts?: { layer?: 'style' | 'game' | 'debug' }): LookHandle;
1236
1416
  /** What one owner holds for a key, or undefined */
1237
1417
  ownerValue(owner: string, key: string, opts?: { layer?: 'game' | 'debug' }): any;
1238
1418
  /** Add declared keys to a started part (same fields as defineLookPart params) */
@@ -1243,21 +1423,43 @@ export interface LookPart<P = Record<string, any>> {
1243
1423
  has(key: string): boolean;
1244
1424
  /** [key, value] pairs in effect whose key starts with prefix */
1245
1425
  resolved(prefix?: string): Array<[string, any]>;
1426
+ /** Resolved params as a plain object */
1427
+ values(): Record<string, any>;
1428
+ /** The value from the highest game / debug layer for the key (undefined when only style or default gives it) */
1429
+ top(key: string): any;
1246
1430
  /** Replace the style layer */
1247
1431
  restyle(values: Record<string, any>): void;
1248
1432
  /** Declare keys a style-driven system writes every frame (by = the driver's module name); drive(keys, null) hands them back */
1249
1433
  drive(keys: string[], by: string | null): void;
1250
- /** Unregister the part (its module went away) */
1251
- dispose(): void;
1434
+ /** Who drives key every frame, or null */
1435
+ driven(key: string): string | null;
1436
+ /** The driver's value for a driven key this frame */
1437
+ feed(key: string, value: any): void;
1438
+ /** @internal Once per frame (the sky's frame calls it): function values on number keys are evaluated */
1439
+ tick(ctx: any): void;
1440
+ /** Run fn with the recompute held, so several writes apply once */
1441
+ batch<T>(fn: () => T): T;
1442
+ /** Unregister the part (its module went away); remove, not dispose: it owns no GPU resource */
1443
+ remove(): void;
1252
1444
  }
1253
1445
 
1254
- export interface LookTone { mapping: string; exposure: number | Array<[number, number]> | ((t: number) => number) }
1255
- export interface LookLightSide { color?: ColorLike; intensity?: number }
1256
- export interface LookLights { sun: LookLightSide | 'manual' | false; hemi: LookLightSide | 'manual' | false }
1446
+ /** Exposure only: the tone curve is plain three.js (engine.renderer.toneMapping), written by the engine once at creation (style.toneMapping, else AgX) */
1447
+ export interface LookTone { exposure: number | Array<[number, number]> | ((t: number) => number) }
1448
+ export interface LookLightSide { color?: ColorLike; intensity?: number; /** hemi only */ ground?: ColorLike }
1449
+ /** env: the neutral generated room environment (scene.environment) the no-style baseline uses; 0 = none */
1450
+ export interface LookLights { sun: LookLightSide | 'manual' | false; hemi: LookLightSide | 'manual' | false; env: { intensity?: number; share?: number } }
1257
1451
  /** The map itself is the replace slot: look.env.replace('sky' | Texture | null) */
1258
1452
  export interface LookEnv { intensity: number; rotation: number; interval: number }
1259
1453
  export interface LookFog { kind: string; color: ColorLike | 'horizon'; density: number; near: number; far: number; height: number; falloff: number; enabled: boolean }
1260
- export interface LookSky { clouds: Record<string, any>; backdrop: ColorLike | null }
1454
+ /** Color keys also take ({ time, weather, season, day, state, sky }) => color, evaluated every frame (engine.look.state feeds state) */
1455
+ export type LookColorFn = ColorLike | ((ctx: import('./style').LookContext) => ColorLike) | null;
1456
+ /** The style.sky look keys (types/style.d.ts StyleSky has what each one does) plus the per-frame color overrides top / horizon */
1457
+ export interface LookSky {
1458
+ clouds: Record<string, any>; backdrop: LookColorFn; top: LookColorFn; horizon: LookColorFn;
1459
+ keyframes: import('./style').SkyKeyframe[]; sunSize: number; sunGlow: number; sunBrightness: number; moonSize: number; moonColor: ColorLike;
1460
+ moonBrightness: number; starDensity: number; starScale: number; gradientCurve: number; groundTint: ColorLike; orbitTilt: number; orbitSway: number;
1461
+ dim: { tint?: boolean; stars?: boolean };
1462
+ }
1261
1463
  export interface LookShadow {
1262
1464
  type: 'basic' | 'pcf' | 'vsm'; radius: number; blurSamples: number; bias: number; normalBias: number; mapSize: number; updateEvery: number;
1263
1465
  snap: number | 'texel'; ahead: number; cascades: number; maxFar: number; fade: boolean; lightMargin: number; enabled: boolean;
@@ -1268,36 +1470,53 @@ export interface LookWind { frequency: number; amplitude: number }
1268
1470
  export interface LookGround {
1269
1471
  colors: Record<string, ColorLike>; biomeColors: Record<string, string | string[]>; steep: Array<{ maxNormalY: number; colors: any }>;
1270
1472
  variation: any; detail: any; shading: string;
1473
+ /** Texture shading only: lighting normals 'smooth' (null = smooth) | 'flat' */
1474
+ normals: 'smooth' | 'flat' | null;
1271
1475
  }
1272
1476
  export interface LookSurface { lighting: Record<string, any>; detail: Record<string, any>; ramp: number[]; soften: number }
1273
1477
  export interface LookWater {
1274
1478
  color: ColorLike; opacity: number; depthColor: { shallow?: ColorLike; deep?: ColorLike }; foam: Record<string, any>;
1275
1479
  waveHeight: number; waveScale: number; waveSpeed: number; fresnel: number;
1480
+ /** Normal map asset name or path (null = none; a change rebuilds the material once) */
1481
+ normalMap: string | null; normalScale: number; normalRepeat: number;
1482
+ /** Normal map scroll [x, z] per second */
1483
+ normalSpeed: [number, number]; shininess: number; specular: ColorLike;
1276
1484
  }
1277
1485
 
1278
1486
  /** engine.look: the parts by name. A part exists only when the module that provides it is installed (fog / sky / shadow / env: sky(); ground: terrain(); wind: vegetation(); water; weather) */
1279
1487
  export interface Look {
1280
1488
  tone: LookPart<LookTone>;
1281
1489
  lights: LookPart<LookLights>;
1490
+ /**
1491
+ * The camera and canvas values the engine writes on its own: camera.far, camera.fov, the pixel ratio. No params, shader or replace slot:
1492
+ * manual('far' | 'fov' | 'pixelRatio') takes one for the game (to place the camera itself use engine.takeCamera(owner))
1493
+ * @example engine.look.view.manual('far'); engine.camera.far = 3000; engine.camera.updateProjectionMatrix();
1494
+ */
1495
+ view: LookPart<{}>;
1282
1496
  cloudShadow: LookPart<LookCloudShadow>;
1283
- /** Old name of cloudShadow (recipes/52-look.md, Old names) */
1284
- clouds: LookPart<LookCloudShadow>;
1285
1497
  env: LookPart<LookEnv>;
1286
1498
  fog: LookPart<LookFog>;
1287
1499
  sky: LookPart<LookSky>;
1288
- shadow: LookPart<LookShadow>;
1289
- /** Roles are the keys: set({ wool: { roughness: 0.4 } }), patch(name, spec, { roles }), replace('wool', Material | fn) */
1290
- materials: LookPart<Record<string, Record<string, any>>>;
1500
+ /** set({ enabled, type }) always (the engine's own: shadows on, 'pcf'); a sky adds cascades, follow, extent ...; include(myLitShaderMaterial) opts a ShaderMaterial of yours into cascaded shadows */
1501
+ shadow: LookShadowPart;
1502
+ /** Roles are the keys: set({ wool: { roughness: 0.4 } }), add(name, shaderPatch, { roles }), replace('wool', Material | fn), glow('window', { night: 2 }) */
1503
+ materials: LookMaterials;
1291
1504
  surface: LookPart<LookSurface>;
1292
1505
  ground: LookPart<LookGround>;
1293
1506
  wind: LookPart<LookWind>;
1294
1507
  water: LookPart<LookWater>;
1295
1508
  /** Keys 'rain.speed', 'snow.size', 'lightning.brightness', overcastColor ...; patch('rain.fragment', wholeShaderText) */
1296
1509
  weather: LookPart;
1297
- /** Per effect: set({ bloom: { strength: 0.6 }, vignette: false }); patch(name, { glsl, slot, order, uniforms, values }); add(effect, { owner }); replace([effects]) */
1510
+ /** Per effect: set({ bloom: { strength: 0.6 }, vignette: false }); add(pass | node fn | effect, { name, owner }); replace([effects]) */
1298
1511
  post: LookPost;
1512
+ /**
1513
+ * The game's half of the frame context every function-valued look key reads ({ time, weather, season, day, state, sky }): merge fields
1514
+ * (null drops one) and get the state back; state() only reads it
1515
+ * @example engine.look.fog.set({ color: ({ state }) => state.boss ? '#400' : 'horizon' }); engine.look.state({ boss: true });
1516
+ */
1517
+ state(patch?: Record<string, any> | null): Record<string, any>;
1299
1518
  /** Parts made with defineLookPart */
1300
- [custom: string]: LookPart;
1519
+ [custom: string]: LookPart | ((patch?: Record<string, any> | null) => Record<string, any>);
1301
1520
  }
1302
1521
 
1303
1522
  /**
@@ -1310,11 +1529,11 @@ export declare class Engine {
1310
1529
  // ---------- Core objects ----------
1311
1530
  /** three.js (a game can also import { THREE } from 'threedog' directly) */
1312
1531
  THREE: typeof import('three');
1313
- /** Style pack */
1532
+ /** Style */
1314
1533
  style: Style;
1315
- /** three.js renderer */
1316
- renderer: import('three').WebGLRenderer;
1317
- /** Device tier: 'low' (phones, integrated graphics) | 'high' */
1534
+ /** three.js renderer: WebGLRenderer, or WebGPURenderer on the WebGPU route (EngineRenderer) */
1535
+ renderer: EngineRenderer;
1536
+ /** Device tier: 'low' (phones, integrated graphics) | 'high'. A headless page takes it from ?threedog-tier=low|high (threedog shot / gallery / capture pass high, shot --tier low checks the low tier) */
1318
1537
  tier: 'low' | 'high';
1319
1538
  /** three.js scene */
1320
1539
  scene: import('three').Scene;
@@ -1323,17 +1542,13 @@ export declare class Engine {
1323
1542
  * false`
1324
1543
  */
1325
1544
  lights: { sun: import('three').DirectionalLight; hemi: import('three').HemisphereLight };
1326
- /** three.js perspective camera */
1545
+ /** three.js PerspectiveCamera (class EngineCamera, core/engineCamera.js): a camera rig with projection: 'orthographic' switches it to an orthographic matrix in place (orthoSize; describe().camera.projection says which) */
1327
1546
  camera: import('three').PerspectiveCamera;
1328
1547
  /**
1329
1548
  * Camera focus, updated every frame by the camera module: terrain, models etc. load around it. The center of gameplay simulation is world.anchor (the
1330
1549
  * player by default), which does not follow the camera
1331
1550
  */
1332
1551
  focus: Vector3;
1333
- /** Whether shadows are on */
1334
- shadows: boolean;
1335
- /** Shadow filter in use; change it with look.shadow.set({ type }) */
1336
- shadowType: 'basic' | 'pcf' | 'vsm';
1337
1552
  /** Current ground */
1338
1553
  ground: Ground;
1339
1554
  /**
@@ -1356,9 +1571,15 @@ export declare class Engine {
1356
1571
  * position; null when unknown. @example engine.actor = 'boat_1'; engine.actorPosition()
1357
1572
  */
1358
1573
  actorPosition(id?: string): { x: number; y: number; z: number } | null;
1359
- /** True once start() completes and the loading screen is gone (every "is it ready" in the engine is such a boolean property) */
1360
- ready: boolean;
1361
- /** True after dispose() */
1574
+ /**
1575
+ * Where the engine is in its life: 'constructed' (start() not called) -> 'loading' (start() running: frame hooks only, no fixed step, so no game
1576
+ * time passes and every machine opens at tick 0) -> 'ready' (world built: fixed steps run, engine:ready fires) -> 'running' (start() resolved)
1577
+ * -> 'disposed'. engine.step() during loading runs frame hooks only
1578
+ */
1579
+ readonly phase: 'constructed' | 'loading' | 'ready' | 'running' | 'disposed';
1580
+ /** phase is 'ready' or 'running': the world is built and the loading screen is gone (every "is it ready" in the engine is such a boolean property) */
1581
+ readonly ready: boolean;
1582
+ /** phase is 'disposed' */
1362
1583
  readonly disposed: boolean;
1363
1584
  /** Execution order of module hooks (module names, first -> last), for debugging "who runs before whom" */
1364
1585
  readonly moduleOrder: string[];
@@ -1369,8 +1590,9 @@ export declare class Engine {
1369
1590
  readonly moduleStates: Record<string, 'registered' | 'initializing' | 'running' | 'failed' | 'disposed'>;
1370
1591
  /**
1371
1592
  * What this game can do, read from the existing registrations (modules, ops, save parts, describe, params schemas).
1372
- * No argument: short list; a module id / op name: that entry expanded (null if unknown); { find }: the short list filtered. recipes/51-capability-catalog.md
1373
- * @example engine.catalog('shop').ops[0].failures // ['soldOut', 'noMoney']
1593
+ * No argument: the short list, an ARRAY of { id, kind, label, ops, saves, ... } (read .id, not Object.keys); a module id / op name: that entry
1594
+ * expanded (null if unknown); { find }: the short list filtered. recipes/51-capability-catalog.md
1595
+ * @example engine.catalog().map(s => s.id); engine.catalog('shop').ops[0].failures // ['soldOut', 'noMoney']
1374
1596
  */
1375
1597
  catalog(id?: string | { find?: string }): any;
1376
1598
  /**
@@ -1378,7 +1600,7 @@ export declare class Engine {
1378
1600
  * message }, gameplay is frozen; null when there is no error. A release build does not freeze, it reports once in the console
1379
1601
  */
1380
1602
  readonly error: EngineError | null;
1381
- /** Names of presentation modules disabled after an error (modules with presentation: true) */
1603
+ /** Names of look / ui modules disabled after an error (a module's type decides: look and ui fail soft) */
1382
1604
  readonly disabledModules: Set<string>;
1383
1605
  /**
1384
1606
  * The engine's cancel signal (AbortSignal): for DOM listeners write addEventListener(type, fn, { signal: engine.signal }), removed automatically on
@@ -1387,8 +1609,6 @@ export declare class Engine {
1387
1609
  readonly signal: AbortSignal;
1388
1610
  /** UI root node: UI elements of the engine and modules hang under it (don't attach to document.body directly), the whole tree is removed on dispose() */
1389
1611
  readonly uiRoot: HTMLDivElement;
1390
- /** Base fog distance (meters) */
1391
- fogFar: number;
1392
1612
  /** Installed modules: name -> module definition */
1393
1613
  modules: Map<string, ModuleDef>;
1394
1614
  /** Standalone water bodies (lakes, ponds) */
@@ -1426,7 +1646,7 @@ export declare class Engine {
1426
1646
  cpuMs: number;
1427
1647
  /** cpuMs split by phase (last frame): fixed = input + fixed steps, frame = frame hooks incl. stream / jobs, render = draw submission, afterRender = its hooks */
1428
1648
  cpuPhases: { fixed: number; frame: number; render: number; afterRender: number };
1429
- /** The camera holder in charge (latest engine.takeCamera claim), null when nobody holds it. Assigning { owner } / null is the old alias of takeCamera */
1649
+ /** The camera holder in charge (latest engine.takeCamera claim), null when nobody holds it. Read-only */
1430
1650
  cameraOverride: CameraOverride | null;
1431
1651
  /** Take the camera over (camera modules leave it alone) until remove(); the latest holder is in charge, releasing hands it back to the previous one */
1432
1652
  takeCamera(owner: string | ({ owner: string } & Partial<CameraOverride>), opts?: Partial<CameraOverride>): OwnerHandle;
@@ -1434,12 +1654,51 @@ export declare class Engine {
1434
1654
  readonly runState: RunState;
1435
1655
  /** Draco/KTX2 decoder directory */
1436
1656
  decoders: string;
1437
- /** Game clock: game seconds now, after / every (clock-time / season timers are on engine.sky) */
1657
+ /** Calendar clock: calendar seconds now, after / every, the rate (clock-time / season timers are on engine.calendar) */
1438
1658
  clock: Clock;
1659
+ /**
1660
+ * The one way several systems change a shared quantity: an entry per owner, combined by layer, ended by its handle; nothing remembers an old value.
1661
+ * @example engine.mod('time.enemies', { owner: 'bullet-time', mul: 0.35, for: 2 }) // bullet time on the enemies channel
1662
+ * @example engine.mod('time.player', { owner: 'haste', mul: 1.2, for: 5 }) // haste on the player
1663
+ * @example engine.mod('freeze', { owner: 'pause-menu' }) // pause menu (same as engine.freeze('pause-menu'))
1664
+ */
1665
+ mod(name: string, opts: import('./gameplay').ModOptions): import('./gameplay').ModHandle;
1666
+ /** Every shared quantity by name; define your own with engine.stacks.define(name, { base }) */
1667
+ stacks: import('./gameplay').Stacks;
1668
+ /**
1669
+ * Who decides where each character goes: one holder in charge per character, layers base < script < cutscene < net; a higher one pauses the
1670
+ * lower until it ends. engine.control.take(ch, { owner, layer, step }) / .of(ch). Recipe 57
1671
+ * @example const h = engine.control.take(npc, { owner: 'escort', layer: 'script', step: () => ({ x: 0, z: 1 }) }); ... h.remove();
1672
+ */
1673
+ control: Control;
1674
+ /**
1675
+ * The one way to change what a module's public method does without copying the module: fn(next, ...args) runs instead of it; call next(...args)
1676
+ * for the method (do work before, after, or skip it). Several wrappers compose (the last wrapped runs first); remove() takes one out; listed in
1677
+ * describe().wraps. Private (_) methods throw. The methods a module promises are its contract.js api.
1678
+ * @example engine.wrap(engine.inventory, 'add', (next, id, n = 1, o) => carried() + weightOf(id) * n > 30 ? false : next(id, n, o), { owner: 'weight' })
1679
+ */
1680
+ wrap<T extends object>(target: T, method: string, fn: (next: (...args: any[]) => any, ...args: any[]) => any, opts?: { owner?: string }): Handle;
1681
+ /** Time channels: real seconds, channel seconds (world, player, your own), read speeds with scale(ch, id?) */
1682
+ time: import('./gameplay').Time;
1439
1683
  /** Story flags and counters (autosaved) */
1440
1684
  vars: Vars;
1441
1685
  /** Performance budget (off by default) */
1442
1686
  budget: Budget;
1687
+ /** The plugins folder: files in the game's plugins/ plugged at start by what they export (core/plugins.js); describe().slots lists them */
1688
+ plugins: {
1689
+ /** Plug a folder's modules yourself (the vite preset does it): import.meta.glob('./plugins/*.js', { eager: true }) */
1690
+ add(files: Record<string, any>, o?: { order?: string[]; off?: string[] }): any;
1691
+ /**
1692
+ * Unload: take everything a plugin plugged out again (file name without .js; a style pack's name: all its plugins, its starting values stay).
1693
+ * A material / patch plugin also rebuilds the made materials (look.materials.rebuild) unless { rebuild: false }. To pause a post effect in
1694
+ * its place, look.post.set({ name: false }) is lighter. The result names what was switched, the reach and what stays.
1695
+ */
1696
+ off(name: string, o?: { rebuild?: boolean }): { off: string[]; reach: ('live' | 'new materials only')[]; rebuilt: number | null; note: string };
1697
+ /** Plug a switched-off plugin again (same place in the post chain; material / patch plugins rebuild the made materials) */
1698
+ on(name: string, o?: { rebuild?: boolean }): { on: string[]; reach: ('live' | 'new materials only')[]; rebuilt: number | null; note: string };
1699
+ /** In plug order. reach per slot: 'live', or 'new materials only' (a material / patch); replacedBy: the plugin that holds it out (export const replaces) */
1700
+ list(): { name: string; file: string; on: boolean; slots: string[]; reach: ('live' | 'new materials only')[]; style: string | null; replacedBy: string | null }[];
1701
+ };
1443
1702
  /** Ray registry (what engine.raycast hits) */
1444
1703
  rays: Rays;
1445
1704
  /** Frame-spread job scheduler */
@@ -1455,28 +1714,25 @@ export declare class Engine {
1455
1714
  ops: Ops;
1456
1715
  /** Named fixed camera views for repeatable screenshots: define / show / release (recipes/46-blender-art-route.md) */
1457
1716
  views: Views;
1458
- /** Fixed-step count (the gameplay timeline: does not advance while frozen; commits due times, event history and the operation log use it) */
1717
+ /**
1718
+ * Fixed-step count (= engine.time.tick, the one time counter: does not advance while frozen; commits due times, event history and the operation
1719
+ * log use it). Seconds are views of it: engine.time.now('real' | 'ambient' | 'calendar' | channel)
1720
+ */
1459
1721
  readonly tick: number;
1460
- /** Seeded random numbers (use for gameplay randomness: reproducible and saved with the game) */
1722
+ /** Seeded random numbers, an object (not a function): engine.random.next() in [0, 1), .range(a, b), .int(a, b), .pick(list), .chance(p). Use it for gameplay randomness: reproducible and saved with the game */
1461
1723
  random: Random;
1462
1724
  /**
1463
1725
  * Spatial stream-in and the stream sources (where the world is loaded: terrain, colliders, models, stream entries; built-in player and camera sources,
1464
1726
  * add one for a teleport destination)
1465
1727
  */
1466
1728
  stream: Stream;
1467
- /** Automatic batching: the same static model placed many times in a cell is drawn as one InstancedMesh (createEngine({ batching })) */
1729
+ /** Automatic batching: the same static model the engine placed (world records, stream builds, level files) many times in a cell is drawn as one InstancedMesh; your own meshes only with userData.batch = true (createEngine({ batching })) */
1468
1730
  batching: Batching;
1469
1731
  /** Startup timing report (null until start() completes) */
1470
1732
  startup: StartupReport | null;
1471
- /**
1472
- * Run seconds: unaffected by the sky time scale, does not advance while frozen or paused; for presentation animation (swaying, floating).
1473
- * The other two "times": game seconds engine.clock.now (= fixed-step seconds x clock.timeScale, saved); sky time of day engine.sky.timeOfDay (0–1,
1474
- * one day = dayLength game seconds)
1475
- */
1476
- readonly elapsed: number;
1477
1733
  /**
1478
1734
  * This engine's shader uniforms, read by the built-in effects (wind, clouds, season, water, sky, rain). Share these objects in your
1479
- * own ShaderMaterial or patch instead of making your own uTime. Weather and sky write them; uTime follows engine.elapsed.
1735
+ * own ShaderMaterial or patch instead of making your own uTime. Weather and sky write them; uTime is engine.time.now('ambient').
1480
1736
  * @example
1481
1737
  * new THREE.ShaderMaterial({ uniforms: { uTime: engine.uniforms.uTime }, vertexShader, fragmentShader });
1482
1738
  */
@@ -1485,14 +1741,22 @@ export declare class Engine {
1485
1741
  readonly waterLevel: number;
1486
1742
 
1487
1743
  // ---------- Modules (undefined when not installed) ----------
1488
- /** Procedural terrain (terrain() module) */
1744
+ /** Procedural terrain, data part (terrain() module: chunks, heights, edits, collision) */
1489
1745
  terrain?: Terrain;
1746
+ /** Draws the terrain chunks (terrain()'s look module, slot 'terrain-look'; undefined when a game replaced it) */
1747
+ terrainLook?: TerrainLook;
1490
1748
  /** Vegetation (vegetation() module; grows on terrain or on any ground provider) */
1491
1749
  vegetation?: Vegetation;
1492
- /** Sky, day/night, calendar (sky() module) */
1750
+ /** Draws the plants (vegetation()'s look module, slot 'vegetation-look'; undefined when a game replaced it) */
1751
+ vegetationLook?: VegetationLook;
1752
+ /** Sky dome, sun / moon light and fog drawn from the calendar's time (sky() module) */
1493
1753
  sky?: Sky;
1494
- /** Weather (weather() module, needs sky) */
1754
+ /** Time of day, day, seasons and clock-time timers (calendar() module); NPC schedules, content clock conditions and audio time rules read it */
1755
+ calendar?: Calendar;
1756
+ /** Weather state (weather() module): the table, current values, set / setAuto, save, events */
1495
1757
  weather?: Weather;
1758
+ /** Weather look (installed by weather(), needs sky): rain / snow particle systems, lightning flash, the weather's effect on sun, fog and sky */
1759
+ weatherLook?: WeatherLook;
1496
1760
  /** Water surface (water() module) */
1497
1761
  water?: Water;
1498
1762
  /** World data (world() module): things that must be saved, survive level changes and keep changing while far away; the model is built only when nearby */
@@ -1508,25 +1772,21 @@ export declare class Engine {
1508
1772
  /** Current camera (one of followCamera / firstPersonCamera / fixedCamera / rtsCamera) */
1509
1773
  cameraRig?: CameraRig;
1510
1774
  /**
1511
- * Switch the camera at runtime (only exists with a camera module installed): the target and horizontal heading carry over; the first-person camera
1775
+ * Switch the camera at runtime between kinds, once a camera module is installed (openWorld installs followCamera; with none it throws camera-none
1776
+ * naming the module to install, e.g. engine.use(fixedCamera({ position, lookAt }))): the target and horizontal heading carry over; the first-person camera
1512
1777
  * hides the character body automatically (the shadow stays) and locks / releases the mouse; the camera switched out is kept, with its parameters, for
1513
1778
  * switching back.
1514
1779
  * Passing opts rebuilds this kind of camera with the new parameters. A wrong kind throws and lists the available options.
1515
1780
  * @example engine.onFrame(() => { if (engine.input.pressedRaw('toggleView')) engine.setCamera(engine.cameraRig.kind === 'follow' ? 'firstPerson' :
1516
1781
  * 'follow'); });
1517
1782
  */
1518
- setCamera?(kind: CameraKind, opts?: object): CameraRig;
1783
+ setCamera(kind: CameraKind, opts?: object): CameraRig;
1519
1784
  /** Cutscenes, tweens (timeline() module) */
1520
1785
  timeline?: Timeline;
1521
1786
  /** Hand-built level (level() module) */
1522
1787
  level?: Level;
1523
1788
  /** Trigger zones (triggers() module) */
1524
1789
  triggers?: Triggers;
1525
- /**
1526
- * Entities: single stateful, saved objects such as saplings, campfires and chests; the data is a record of engine.world, the model is built only when
1527
- * nearby (entities() module)
1528
- */
1529
- entities?: Entities;
1530
1790
  /** Particles (particles() module) */
1531
1791
  particles?: Particles;
1532
1792
  /** Settings menu (settings() module) */
@@ -1539,10 +1799,16 @@ export declare class Engine {
1539
1799
  npcs?: NPCManager;
1540
1800
  /** Interaction prompts (interactions() module) */
1541
1801
  interactions?: Interactions;
1542
- /** Dialogue (dialogue() module) */
1802
+ /**
1803
+ * Dialogue (dialogue() module). Ops: `dialogue.advance` (finish typing the line, else go on to the next one) and `dialogue.choose { index }` (pick
1804
+ * visible choice index, 0-based) are the only ways keys, clicks, tests and the dev bridge move a conversation on:
1805
+ * `engine.ops.run('dialogue.choose', { index: 0 })`
1806
+ */
1543
1807
  dialogue?: Dialogue;
1544
1808
  /** Inventory (inventory() module) */
1545
1809
  inventory?: Inventory;
1810
+ /** pickups() */
1811
+ pickups?: Pickups;
1546
1812
  /** Quests (quests() module) */
1547
1813
  quests?: Quests;
1548
1814
  /** Photo mode (photo() module) */
@@ -1565,13 +1831,17 @@ export declare class Engine {
1565
1831
  hud?: Hud;
1566
1832
 
1567
1833
  // ---------- Module system ----------
1568
- /** Install one or more modules (in order; dependencies must be installed first) */
1569
- use(...mods: ModuleInput[]): this;
1834
+ /**
1835
+ * Install one or more modules (in order; dependencies must be installed first). A last argument { replaces: 'slot' } swaps the module that holds
1836
+ * that exclusive slot: it is unloaded first (its handles, changes and dispose) and put back if the new install fails.
1837
+ * @example engine.use(myInventory(), { replaces: 'inventory' })
1838
+ */
1839
+ use(...mods: (ModuleInput | { replaces: string | string[] })[]): this;
1570
1840
  /** Whether a module is installed */
1571
1841
  has(name: string): boolean;
1572
1842
 
1573
- /** Material by role from this engine's style pack: engine.makeMaterial('prop', { color: 0x8a5a36 }) */
1574
- makeMaterial(purpose?: string, params?: { color?: ColorLike, [prop: string]: any }): Material;
1843
+ /** Material by role from this engine's style: engine.makeMaterial('prop', { color: 0x8a5a36 }) */
1844
+ makeMaterial(purpose?: string, params?: MaterialSpec): Material;
1575
1845
 
1576
1846
  // ---------- Ground ----------
1577
1847
  /** Set the ground (called by the terrain and level modules); missing parts fall back to flat ground */
@@ -1630,22 +1900,57 @@ export declare class Engine {
1630
1900
  detach(...objs: Object3D[]): void;
1631
1901
  /**
1632
1902
  * Fixed-step logic (60 times per second, dt in fixed seconds): movement, physics, cooldowns, and gameplay keys (read pressed() here: a per-step
1633
- * snapshot, independent of frame rate). Returns a handle { remove() }
1903
+ * snapshot, independent of frame rate). dt is real seconds (always 1/60) unless { channel } names a time channel: then the channel's scaled dt.
1904
+ * phase 'early' (default) runs before every module fixed hook (the player has not moved yet this step); 'late' after them, before the clock
1905
+ * (hit checks, reading this step's result). Returns a handle { remove() }
1906
+ * @example engine.onFixed(() => checkHits(engine.player.position), { phase: 'late' })
1634
1907
  */
1635
- onFixed(fn: (dt: number) => void): Handle;
1908
+ onFixed(fn: (dt: number) => void, opts?: { channel?: string, phase?: 'early' | 'late' }): Handle;
1636
1909
  /**
1637
1910
  * Once per frame (dt in frame seconds): animation, camera, UI and UI keys (menus read this frame's latest input). Gameplay keys belong in onFixed.
1638
1911
  * Returns a handle { remove() }
1639
1912
  */
1640
1913
  onFrame(fn: (dt: number) => void): Handle;
1914
+ /**
1915
+ * Around the main frame render, after the camera update and batching. when 'before' (default): render into your own render target here
1916
+ * (mirror, minimap, portal, picking); the render target is reset to the screen afterwards. 'after': right after the frame (read pixels).
1917
+ * The main frame render itself stays the engine's (post chain). Returns a handle { remove() }
1918
+ * @example const rt = new THREE.WebGLRenderTarget(256, 256);
1919
+ * engine.onRender(({ renderer, scene }) => { renderer.setRenderTarget(rt); renderer.render(scene, mapCam); });
1920
+ */
1921
+ onRender(fn: (ctx: { renderer: EngineRenderer; scene: import('three').Scene; camera: import('three').Camera; dt: number }) => void, opts?: { when?: 'before' | 'after' }): Handle;
1922
+
1923
+ /**
1924
+ * Draw one picture now, outside the loop, on either renderer. `renderOnce()`: the frame the player sees, onto the canvas through engine.post
1925
+ * (read the canvas in the same task, as photo mode does). `renderOnce(target)`: that frame through engine.post into a render target (the
1926
+ * canvas's pixels). `renderOnce(target, camera)` with another camera: the scene from that camera, without post. On WebGPURenderer each call is a fresh node frame, so two calls in one task give two pictures (a RenderPipeline draws its scene pass once per frame).
1927
+ * @example engine.renderOnce(); const url = engine.renderer.domElement.toDataURL('image/png');
1928
+ * engine.renderOnce(rt, mapCamera); // a minimap / thumbnail into your own render target
1929
+ */
1930
+ renderOnce(target?: import('three').RenderTarget | null, camera?: import('three').Camera): void;
1931
+
1932
+ // ---------- Light probes (render/probes.js) ----------
1933
+ /**
1934
+ * Bake a grid of light probes from the scene as it is now: a cube render at every grid point, turned into spherical harmonics (three's
1935
+ * LightProbeGenerator), then one scene `LightProbe` that follows a point (`follow`, default the camera focus) and takes the light
1936
+ * interpolated there every frame. The probe light adds to whatever ambient light the scene has (hemi, environment): lower those yourself
1937
+ * where the probes take over. A load-time cost, not per frame: 6 renders + a GPU read back per probe, awaited one probe at a time so the page
1938
+ * keeps drawing; ship the result with `toJSON()` + `engine.loadProbes(json)` instead of baking at every start.
1939
+ * Render targets and cube cameras are disposed before it resolves. Adding the probe changes the light setup: bake at start-up, not mid-play.
1940
+ * @example const probes = await engine.bakeProbes({ bounds: { min: [-20, 0, -20], max: [20, 6, 20] }, spacing: 4, include: o => !o.userData.moving });
1941
+ * probes.sample(npc.position, npcProbe); // your own probe for one object
1942
+ */
1943
+ bakeProbes(opts: { bounds: import('three').Box3 | { min: PositionLike; max: PositionLike }; spacing: number; resolution?: number;
1944
+ include?: (o: Object3D) => boolean; height?: number; follow?: ProbeFollow; owner?: string }): Promise<ProbeSet>;
1945
+ /**
1946
+ * A probe set from a file made by `handle.toJSON()` (no baking). A wrong shape is refused with code `probes-data` and nothing is added.
1947
+ * @example const probes = engine.loadProbes(await (await fetch('probes.json')).json());
1948
+ */
1949
+ loadProbes(json: ProbeData, opts?: { follow?: ProbeFollow; owner?: string }): ProbeSet;
1641
1950
 
1642
1951
  // ---------- Settings ----------
1643
1952
  /** Render resolution */
1644
1953
  setPixelRatio(p: number): void;
1645
- /** Shadow toggle */
1646
- setShadows(on: boolean): void;
1647
- /** Fog distance (meters), also adjusts the camera far plane */
1648
- setFogFar(d: number): void;
1649
1954
  /** Exposure per frame from style.exposure / look.tone keyframes or function, null for a plain number; the sky module calls it with engine.sky @readonly */
1650
1955
  exposureDriver: ((sky: any) => number) | null;
1651
1956
 
@@ -1654,15 +1959,10 @@ export declare class Engine {
1654
1959
  raycast(origin: Vec3Like, dir: Vec3Like, opts?: RaycastOptions): RayHit | null;
1655
1960
  /** Shoot a ray through the camera from screen coordinates (-1..1, e.g. input.pointer.ndcX/ndcY) */
1656
1961
  pick(ndcX: number, ndcY: number, opts?: RaycastOptions): RayHit | null;
1657
- /**
1658
- * New runtime instance of a content template (inside an op or fixed step), saved whole; returns the world record (kind = template name). Needs content().
1659
- * e.g. engine.spawn('chest', { x: 10, z: 4 }, { opened: true })
1660
- */
1661
- spawn(name: string, at: any, fields?: { id?: string; rot?: number; scale?: number; y?: number; items?: Record<string, number>; [stateField: string]: any }): import('./generated/modules/world/World').WorldRecord;
1662
1962
  /** Set up a scenario: time of day, weather, player position, load a save, advance time, skip cutscenes; emits state:applied when done */
1663
1963
  applyState(params: StateParams): Promise<void>;
1664
- /** Name a group of scenario parameters, then use applyState({ state: name }) or URL ?state=name */
1665
- defineState(name: string, params: StateParams): this;
1964
+ /** Name a group of scenario parameters, then use applyState({ state: name }) or URL ?state=name. Returns a handle: remove() forgets the name */
1965
+ defineState(name: string, params: StateParams, opts?: { owner?: string }): { owner?: string; remove(): void };
1666
1966
  /**
1667
1967
  * Scenario is ready: start() completed, and the URL parameters / the latest applyState have all been applied. Tests and screenshots wait for it:
1668
1968
  * page.waitForFunction(() => window.engine?.stateApplied)
@@ -1684,26 +1984,22 @@ export declare class Engine {
1684
1984
  * Pause the real-time loop: the picture stops and even rendering stops, only step() advances (for tests and screenshots). Use freeze() for a game menu
1685
1985
  * pause
1686
1986
  */
1687
- pause(owner?: string | { owner?: string; kind?: 'test' }, opts?: { kind?: 'test' }): ChainedHandle;
1688
- /** Resume the real-time loop (only this owner's pause) */
1689
- resume(owner?: string | { owner?: string }): this;
1987
+ pause(owner?: string | { owner?: string; kind?: 'test' }, opts?: { kind?: 'test' }): OwnerHandle; // end it with the handle's remove()
1690
1988
  /** Run fn at the start of the next fixed step (via commits); a Promise of fn's value */
1691
1989
  nextFixed<T>(fn: () => T): Promise<T>;
1692
1990
  /**
1693
- * Gameplay pause (menu, flow's paused): fixed steps are skipped entirely (onFixed, module fixed, the game clock and engine.elapsed all stop), frame
1991
+ * Gameplay pause (menu, flow's paused): fixed steps are skipped entirely (onFixed, module fixed, tick and every time view but ambient stop), frame
1694
1992
  * hooks and rendering continue and the UI works.
1695
1993
  * So gameplay logic (movement, timing, quest checks, cutscene waits) belongs in fixed, or check engine.frozen first in frame. owner is the freezer's
1696
- * name, default 'game'
1994
+ * name, default 'game'. uniforms.uTime (wind, water, clouds) keeps moving while frozen; { ambient: true } stops it too
1697
1995
  */
1698
- freeze(owner?: string | { owner?: string; kind?: 'title' }, opts?: { kind?: 'title' }): ChainedHandle;
1699
- /** Release the freeze of owner (gameplay resumes only when all freezers are released) */
1700
- unfreeze(owner?: string | { owner?: string }): this;
1996
+ freeze(owner?: string | { owner?: string; kind?: 'title'; ambient?: boolean }, opts?: { kind?: 'title'; ambient?: boolean }): OwnerHandle;
1701
1997
  /** Is anyone freezing gameplay? */
1702
1998
  readonly frozen: boolean;
1703
1999
  /**
1704
2000
  * Advance seconds of fixed-step time synchronously; seconds must be a finite number >= 0: 0 advances nothing (no step, no render),
1705
- * negative or non-finite throws (code step-seconds), any positive value runs at least one fixed step (60Hz; when timeScale is not 1,
1706
- * game seconds clock.now and sky time of day run faster or slower than it;
2001
+ * negative or non-finite throws (code step-seconds), any positive value runs at least one fixed step (60Hz; time channels and
2002
+ * the calendar clock.now / sky time of day run at their own speeds;
1707
2003
  * frame hooks run once every frameEvery fixed steps, default 2; describe: false returns null instead of building describe()).
1708
2004
  * jobs ignore real time and finish every frame; results of stream's synchronous build are attached to the scene before returning. When render is true
1709
2005
  * (default) one frame is rendered at the end. Returns the describe() result after advancing
@@ -1713,7 +2009,7 @@ export declare class Engine {
1713
2009
  * Skip game time forward (sleep until morning, wait an hour) without stepping every fixed step.
1714
2010
  * clock.after / every, sky.at / daily / between, day:start and season:change fire in time order as if stepped (each crossing once);
1715
2011
  * world records with far catch up the span in one far(rec, dt). onFixed, module fixed hooks, physics and near simulation do not run;
1716
- * engine.elapsed does not move. Input is locked and gameplay frozen during the skip; emits time:skip.
2012
+ * every time view (tick, real, ambient, channels, calendar) moves as if stepped. Input is locked and gameplay frozen during the skip; emits time:skip.
1717
2013
  * fade 0 (default): the time has moved when skip returns. fade > 0: fade out, jump, save, fade in; the Promise resolves after the fade in (it needs frames).
1718
2014
  * session.newGame / load / quit cancel a running skip: it resolves null.
1719
2015
  * @example await engine.skip({ to: '06:00' })
@@ -1727,7 +2023,7 @@ export declare class Engine {
1727
2023
  * @returns a = after skip, b = after stepping
1728
2024
  * @example const r = await engine.checkSkip(600); if (!r.ok) console.log(r.diffs);
1729
2025
  */
1730
- checkSkip(seconds: number, opts?: { ignore?: string[] }): Promise<{ ok: boolean; diffs: { path: string; a: any; b: any }[] }>;
2026
+ checkSkip(seconds: number, opts?: { ignore?: string[] }): Promise<{ ok: boolean; code?: 'frozen' | 'rate0'; diffs: { path: string; a: any; b: any }[] }>;
1731
2027
  /**
1732
2028
  * Consistency check: save -> load gives the same saved state back (nothing is written to the browser).
1733
2029
  * @example const r = await engine.checkSave(); if (!r.ok) console.log(r.diffs);
@@ -1735,28 +2031,30 @@ export declare class Engine {
1735
2031
  checkSave(opts?: { ignore?: string[] }): Promise<{ ok: boolean; diffs: { path: string; a: any; b: any }[] }>;
1736
2032
  /**
1737
2033
  * Call engine.describe(opts?: { radius?: number }) to get the current game state (a plain object, JSON.stringify-able); radius is how far counts as
1738
- * "nearby" (meters, default 30).
2034
+ * "nearby" (meters, default 30). describe('look') or describe({ only: ['look', 'shared'] }) returns just those top-level sections (the whole object
2035
+ * is tens of KB on a big world); an unknown name comes back in unknownSections next to the list of sections.
1739
2036
  * engine.describe.add(name, fn) registers the game's own state in one line: the return value of fn(engine, ctx) goes into describe().<name>, and the
1740
2037
  * returned handle's remove() cancels it.
1741
2038
  * Small games use add; big games write the system as a module and use the module's describe hook. Example: engine.describe.add('range', () => ({
1742
2039
  * score, targets: targets.length }))
1743
2040
  */
1744
2041
  describe: {
1745
- (opts?: { radius?: number; center?: { x: number; z: number } }): GameState;
2042
+ (opts?: { radius?: number; center?: { x: number; z: number }; only?: string[] }): GameState;
2043
+ (section: string | string[]): Partial<GameState> & { unknownSections?: string[]; sections?: string[] };
1746
2044
  add(name: string, fn: (e: Engine, ctx: DescribeContext) => any): { remove(): void };
1747
2045
  };
1748
2046
  /**
1749
- * The same information as English text, summary first: at most 30 lines (standard lines, the 5 nearest things, one line per module with its key
1750
- * counts), ending with how to expand.
2047
+ * The same information as English text, summary first: at most 30 lines (standard lines, the 5 nearest things, the game's describe.add sections,
2048
+ * one line per module with its key counts, the engine tables such as shared / slots / look as one count line), ending with how to expand.
1751
2049
  * { path: 'world.byKind' } returns one part of describe() as JSON; { full: true } returns everything (all nearby things, every module's full data).
1752
2050
  * @example engine.describeText() engine.describeText({ path: 'quests' }) engine.describeText({ full: true })
1753
2051
  */
1754
2052
  describeText(opts?: { radius?: number; full?: boolean; path?: string }): string;
1755
2053
  /**
1756
2054
  * What is around an actor or a spot, and what that actor can do now (each op offer checked with can, possible first, at most 8; failed ones carry
1757
- * reason and the op's reasons note).
2055
+ * code and the op's reasons note).
1758
2056
  * at: a world record id (that actor), [x, z] / { x, z } (a spot, ops as the player), or nothing (the player). radius default 10 m.
1759
- * @example engine.inspect(); // { actor: 'player', at: { x, z }, near: [...], ops: [{ op: 'shop.buy', args, ok: false, reason: 'noMoney',
2057
+ * @example engine.inspect(); // { actor: 'player', at: { x, z }, near: [...], ops: [{ op: 'shop.buy', args, ok: false, code: 'noMoney',
1760
2058
  * why: 'Not enough gold' }] }
1761
2059
  * @example engine.inspect('enemy_3'); // why is this enemy not attacking: its ops and their reasons
1762
2060
  * @example engine.inspect('chest-home').thing.definedAt // 'content/props.js:14': edit that line to change the level for good
@@ -1765,7 +2063,7 @@ export declare class Engine {
1765
2063
  inspect: {
1766
2064
  (at?: string | { x: number; z: number } | number[], opts?: { radius?: number }): {
1767
2065
  actor: string; at: { x: number; z: number }; near: any[]; thing?: HitThing;
1768
- ops: { op: string; args: any; ok: boolean; reason?: string; why?: string | null }[];
2066
+ ops: { op: string; args: any; ok: boolean; code?: string; why?: string | null; facts?: any; nextActions?: any[] }[];
1769
2067
  };
1770
2068
  /**
1771
2069
  * The mesh exists but is not drawn: use this first. Lists every Mesh / Points / Line / Sprite in the scene (name, type, world position, bounding radius,
@@ -1777,6 +2075,25 @@ export declare class Engine {
1777
2075
  * @example engine.inspect.scene().text
1778
2076
  */
1779
2077
  scene(opts?: { hidden?: boolean; limit?: number }): SceneInspect;
2078
+ /**
2079
+ * Every material in the scene with its textures (slot, size, color space, estimated GPU bytes, how many materials share it), who made it
2080
+ * (engine / game), its shader patches and their slots, and how many meshes share it. issues lists wrong color spaces first (a color map that is not
2081
+ * sRGB renders washed out; a normal / roughness map marked sRGB bends its data). Computed on call. Plain three.js: scene.traverse + texture.colorSpace.
2082
+ * @example engine.inspect.materials().issues // ['material "rock" (mesh "cliff"): normalMap "rock_n" holds data but is marked sRGB ...']
2083
+ */
2084
+ materials(opts?: { limit?: number }): { count: number; textures: number; textureBytes: number; issues: string[]; text: string;
2085
+ materials: { name: string | null; type: string; uuid: string; madeBy: 'engine' | 'game'; role: string | null; sharedBy: number; firstMesh: string | null;
2086
+ patches: { name: string; slots: string[] }[];
2087
+ textures: { slot: string; name: string | null; size: string; colorSpace: string; bytes: number; sharedBy: number; issue?: string }[] }[] };
2088
+ /**
2089
+ * The last frame's cost against budgets, each with the next call when over: draw calls, triangles, shader programs, texture memory (estimate),
2090
+ * JS ms per frame (cpuPhases), compile stalls during play (frames where three.js compiled new programs; startup compile ms), the costliest programs.
2091
+ * Budgets are the game's engine.budget limits, else a reference (desktop 60 fps; not enforced). Plain three.js: renderer.info.
2092
+ * @example engine.inspect.perf().text
2093
+ */
2094
+ perf(opts?: { top?: number }): { drawCalls: number; triangles: number; programs: number; textureMB: number; cpuMs: number; compileMs: number; ok: boolean; text: string;
2095
+ budgets: { name: string; value: number; budget: number; from: 'engine.budget' | 'reference'; ok: boolean; next?: string }[];
2096
+ compiles: { at: number; programs: number; ms: number }[]; [k: string]: any };
1780
2097
  };
1781
2098
  /**
1782
2099
  * Why something is the way it is. { op, args?, actor? }: text says whether it can run now, and if not the reason and the op's note on fixing it
@@ -1789,7 +2106,7 @@ export declare class Engine {
1789
2106
  * thing has the rest).
1790
2107
  */
1791
2108
  explain(q: { op: string; args?: any; actor?: string } | Record<string, any>): {
1792
- ok: boolean; reason?: string | null; text: string; detail?: string; recent?: any[]; events?: string[]; thing?: HitThing;
2109
+ ok: boolean; code?: string | null; text: string; detail?: string; recent?: any[]; events?: string[]; thing?: HitThing;
1793
2110
  };
1794
2111
  /**
1795
2112
  * Module hook timing: pass true to turn on, false to turn off (returns the engine); with no argument returns { moduleName: average milliseconds per
@@ -1800,9 +2117,11 @@ export declare class Engine {
1800
2117
  /**
1801
2118
  * Destroy the engine: stop the main loop, call each module's dispose(e) in reverse install order, then reclaim listeners, timers, audio, UI and GPU
1802
2119
  * memory (scene, assets cache, post-processing, renderer).
1803
- * After that no callbacks fire and step() returns null. Safe to call repeatedly. Don't use it for level changes; use level.track(handle)
2120
+ * After that no callbacks fire and step() returns null. Safe to call repeatedly. Don't use it for level changes; use level.track(handle).
2121
+ * The engine's own renderer gives its WebGL context back (browsers keep about 16 live ones), so that canvas cannot host a new engine; keepContext: true
2122
+ * keeps it. A renderer passed to createEngine({ renderer }) is never released.
1804
2123
  */
1805
- dispose(): void;
2124
+ dispose(opts?: { keepContext?: boolean }): void;
1806
2125
  /**
1807
2126
  * Counts for leak hunting: they should not keep growing after repeatedly entering / leaving levels or opening / closing windows. geometries / textures
1808
2127
  * come from three.js renderer.info.memory (counted only after rendering)
@@ -1810,7 +2129,6 @@ export declare class Engine {
1810
2129
  counts(): EngineCounts;
1811
2130
  }
1812
2131
 
1813
- /** Result of engine.counts() */
1814
2132
  /** engine.error and the engine:error event: where and why, plus a stable code, the fix and the pages to read (from the error or the hint table) */
1815
2133
  export interface EngineError {
1816
2134
  /** Where it happened, e.g. "fixed hook of module quests" or "load() of save part 'inventory'" */
@@ -1821,10 +2139,13 @@ export interface EngineError {
1821
2139
  code: string | null;
1822
2140
  /** What to do about it; null when unknown */
1823
2141
  fix: string | null;
2142
+ /** The first frame of the stack ("at onFixed (main.js:91:12)"): which line threw; null when the error has no stack */
2143
+ at: string | null;
1824
2144
  /** Doc pages to read, relative to the package docs */
1825
2145
  docs: string[];
1826
2146
  }
1827
2147
 
2148
+ /** Result of engine.counts() */
1828
2149
  export interface EngineCounts {
1829
2150
  /** Number of event listeners */
1830
2151
  listeners: number;
@@ -1853,7 +2174,7 @@ export interface EngineCounts {
1853
2174
  /** Only with particles() installed: alive is the number of live particles, emitters the number of attached emitters */
1854
2175
  particles?: { alive: number; emitters: number };
1855
2176
  /** Only with sky() installed: timers is the number of at / between / daily / onSeason timers */
1856
- sky?: { timers: number };
2177
+ calendar?: { timers: number };
1857
2178
  /** Any other module's counts(e) hook result, under the module name */
1858
2179
  [module: string]: any;
1859
2180
  }
@@ -1880,44 +2201,65 @@ export interface GameState {
1880
2201
  ready: boolean;
1881
2202
  /** Gameplay error in development / testing (gameplay is frozen), null when there is none */
1882
2203
  error: EngineError | null;
1883
- /** Presentation modules disabled after an error */
2204
+ /** look / ui modules disabled after an error */
1884
2205
  disabledModules: string[];
1885
2206
  /** Modules that are initializing or failed ({ name: state }); absent when every module with an init is running (engine.moduleStates has all) */
1886
2207
  moduleStates?: Record<string, string>;
1887
2208
  /** What loading is waiting for, what failed, whether it blocks the start (engine.loading.view()) */
1888
2209
  loading: LoadingView;
1889
- /** elapsed is the run seconds (= engine.elapsed); with the sky module there are also clock, day, season, isDay, timeOfDay */
2210
+ /** tick / real / ambient / calendar are the time views (engine.time); with the calendar module there are also clock, day, season, isDay, timeOfDay */
1890
2211
  time: {
1891
- elapsed: number; paused: boolean; frozen: boolean; headless: boolean; clock?: string; day?: number; season?: string; isDay?: boolean;
2212
+ tick: number; real: number; ambient: number; calendar: number; paused: boolean; frozen: boolean; headless: boolean; clock?: string; day?: number; season?: string; isDay?: boolean;
1892
2213
  [key: string]: any;
1893
2214
  };
1894
- /** Player (null when there is no player), position in meters */
1895
- /** ground is the ground type, groundName its display name (i18n key ground.<type>, null if none) */
2215
+ /**
2216
+ * Everyone who holds the engine still (empty parts left out): pause / freeze / camera / debugView [{ owner, at? }], input [{ context, owner, pass }]
2217
+ * (input.push), gates { action: owners } (input.gate). Every other shared value is in `shared`
2218
+ */
2219
+ holds: { pause?: any[]; freeze?: any[]; camera?: any[]; debugView?: any[]; input?: { context: string; owner: string; pass: boolean }[];
2220
+ gates?: Record<string, string[]>; };
2221
+ /**
2222
+ * Every shared value and exclusive slot with entries, one row each ('move.speed[player]' for one record): the value, who decides it, how it
2223
+ * combined, and everyone else who wants it (hidden: a set above hides theirs).
2224
+ * @example engine.describe().shared['fog.far'] // { value: 72, writer: 'cave', layer: 'game', how: 'cave 180 × storm 0.4', also: [{ owner: 'storm', layer: 'effect', op: 'mul', value: 0.4 }] }
2225
+ */
2226
+ shared: Record<string, import('./gameplay').SharedRow>;
2227
+ /**
2228
+ * Player (null when there is no player), position in meters; ground is the ground type, groundName its display name
2229
+ * (i18n key ground.<type>, null if none)
2230
+ */
1896
2231
  player: {
1897
- x: number; y: number; z: number; ground: string; groundName: string | null; inWater: boolean; state: string | null;
1898
- running: boolean; jumping: boolean; [key: string]: any;
2232
+ x: number; y: number; z: number; ground: string; groundName: string | null; inWater: boolean;
2233
+ /** The character module's state name as it gives it ('idle', 'walk', 'run', 'jump'...): compare it yourself (state === 'run') */
2234
+ state: string | null; [key: string]: any;
1899
2235
  } | null;
1900
2236
  /** Camera: type 'follow' | 'first' | 'fixed' | 'rts', override is the takeover owner's name */
1901
- camera: { type: string | null; x: number; y: number; z: number; focus: { x: number; z: number }; override: string | null; [key: string]: any };
2237
+ camera: { type: string | null; /** a camera rig may switch engine.camera (an EngineCamera) to orthographic */ projection: 'perspective' | 'orthographic'; orthoSize?: number; x: number; y: number; z: number; focus: { x: number; z: number }; override: string | null; [key: string]: any };
1902
2238
  /** How far counts as nearby (meters) */
1903
2239
  nearbyRadius: number;
1904
2240
  /** Nearby things, sorted by distance (at most 15) */
1905
2241
  nearby: NearbyThing[];
1906
- /** UI: open windows, whether input is locked, the dialogue in progress */
1907
- /** windows: open windows and full-screen UI parts (e.g. 'title'); parts: each UI part 'default' | 'custom' | 'off' */
2242
+ /**
2243
+ * UI: open windows, whether input is locked, the dialogue in progress. windows: open windows and full-screen UI parts (e.g. 'title');
2244
+ * parts: each UI part 'default' | 'custom' | 'off'
2245
+ */
1908
2246
  ui: {
1909
2247
  windows: string[]; inputLocked: boolean; parts: Record<string, string>; [key: string]: any;
1910
2248
  dialogue: { speaker: string; text: string; choices: string[]; [key: string]: any } | null;
1911
2249
  };
1912
2250
  /** Cutscenes: count is how many are playing, skippable whether they can be skipped */
1913
2251
  cutscene: { count: number; skippable: boolean; [key: string]: any } | null;
1914
- /** Installed module names */
1915
- modules: string[];
2252
+ /** Installed modules in install order: name, type, and the capabilities it provides / requires when it has any */
2253
+ modules: { name: string; type: ModuleType; provides?: string[]; requires?: string[] }[];
2254
+ /** What is plugged in where: plugins/ files, scene.add roots, addPass passes, modules, plain lights (core/plugins.js) */
2255
+ slots: { slot: 'scene' | 'post' | 'material' | 'patch' | 'module' | 'light'; plugged: string; file: string; on: boolean; reach?: 'live' | 'new materials only'; affects: string[] }[];
1916
2256
  /**
1917
2257
  * engine.add / world things by save tier (counts only) and what will not survive a load: unsaved ('obj#3 (main.js:88, made during play by op x)'),
1918
2258
  * conflicts (two systems managing one object), orphans (saved ids no object has); atCapped when dev stopped taking stacks
1919
2259
  */
1920
2260
  scene: { game: number; code: number; session: number; world: number; engine: number; unsaved: string[]; conflicts: string[]; orphans: string[]; atCapped?: boolean };
2261
+ /** Renderer asked for ('webgl' default, 'webgpu') and the backend drawing ('webgl' | 'webgpu' | 'webgl2'; null before start()); reason: why not WebGPU, or null */
2262
+ renderer: { requested: 'webgl' | 'webgpu'; backend: 'webgl' | 'webgpu' | 'webgl2' | null; reason: string | null };
1921
2263
  /** Performance (fps/cpuMs are null while paused) */
1922
2264
  perf: {
1923
2265
  fps: number | null; cpuMs: number | null; drawCalls: number; triangles: number; pixelRatio: number;
@@ -1933,10 +2275,16 @@ export interface GameState {
1933
2275
  /** Number of unfinished frame-spread jobs */
1934
2276
  jobs?: number; [key: string]: any };
1935
2277
  /**
1936
- * Weather module additions: name (label is the display name), rain, snow, fog intensity 0–1, progress is the transition progress 0–1, rainVisible /
1937
- * snowVisible whether raindrops / snowflakes are drawn right now (object names weather-rain / weather-snow)
2278
+ * Weather state: name (label is the display name), rain, snow, fog intensity 0–1, progress is the transition progress 0–1
1938
2279
  */
1939
2280
  weather?: any;
2281
+ /** Weather look: rainVisible / snowVisible whether raindrops / snowflakes are drawn right now (object names weather-rain / weather-snow), flash 0–1 */
2282
+ weatherLook?: { rainVisible: boolean; snowVisible: boolean; flash: number };
2283
+ /**
2284
+ * Every value the engine writes on its own (sun, fog, exposure, camera.far, pixel ratio, camera ...) and who writes it now (writer): 'engine',
2285
+ * 'manual:<who>' (look.<part>.manual / sky({ sun: 'manual' })) or 'three (engine yielded)' (the game wrote it directly). manual = the takeover call
2286
+ */
2287
+ owned?: Record<string, { part: string; key: string; writer: string; manual?: string }>;
1940
2288
  /** Content added by other modules */
1941
2289
  [module: string]: any;
1942
2290
  }
@@ -1954,7 +2302,7 @@ export interface DescribeContext {
1954
2302
 
1955
2303
  /** engine.skip options: pass to or seconds */
1956
2304
  export interface SkipOptions {
1957
- /** Until the sky clock next reads this time ('HH:MM' or 0-1; needs sky). The current time itself means a full day */
2305
+ /** Until the calendar clock next reads this time ('HH:MM' or 0-1; needs calendar). The current time itself means a full day */
1958
2306
  to?: string | number;
1959
2307
  /** Game seconds to skip (> 0) */
1960
2308
  seconds?: number;
@@ -1963,3 +2311,31 @@ export interface SkipOptions {
1963
2311
  /** Save slot written after the jump, before the fade in (true = 'auto') */
1964
2312
  save?: string | boolean;
1965
2313
  }
2314
+
2315
+ /** Where a probe set's scene LightProbe samples the grid each frame; false: no scene probe (read the grid with sample()) */
2316
+ export type ProbeFollow = 'focus' | 'camera' | Object3D | (() => PositionLike) | false;
2317
+ /** A probe file: what ProbeSet.toJSON() returns and engine.loadProbes reads (sh: count x 27 numbers, x fastest, then y, then z) */
2318
+ export interface ProbeData { format: 'threedog-probes'; version: 1; origin: [number, number, number]; step: [number, number, number]; counts: [number, number, number]; height: number | null; sh: number[] }
2319
+ /** A baked or loaded grid of SH light probes (engine.bakeProbes / loadProbes); describe().render.probes lists the live ones */
2320
+ export interface ProbeSet extends Handle {
2321
+ /** number of probes */
2322
+ count: number;
2323
+ /** probes per axis [x, y, z] (y is 1 in height mode) */
2324
+ counts: [number, number, number];
2325
+ /** the actual distance between neighbours per axis (<= spacing, so the grid ends on the bounds) */
2326
+ step: [number, number, number];
2327
+ /** the scene LightProbe the engine writes the sh of every frame (null with follow: false); its intensity is yours. Writing its sh yourself takes it over (look.lights.manual('probes')) */
2328
+ probe: import('three').LightProbe | null;
2329
+ /** bake time in ms (null for a loaded set) */
2330
+ bakeMs: number | null;
2331
+ /** 'bake' | 'file' */
2332
+ source: string;
2333
+ /** the interpolated SH at a position (trilinear; outside the grid the nearest edge), written into target (a SphericalHarmonics3 or a LightProbe's sh) */
2334
+ sample(pos: PositionLike, target?: import('three').SphericalHarmonics3 | import('three').LightProbe): import('three').SphericalHarmonics3;
2335
+ /** world position of probe i */
2336
+ point(i: number, out?: Vector3): Vector3;
2337
+ /** plain data for a file: engine.loadProbes(json) makes the same set */
2338
+ toJSON(): ProbeData;
2339
+ /** takes the scene probe out and stops updating it; sample / toJSON still work */
2340
+ remove(): void;
2341
+ }