threedog 0.7.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (593) hide show
  1. package/CHANGELOG.md +411 -1
  2. package/README.md +8 -11
  3. package/core/{Animator.js → assets/Animator.js} +30 -18
  4. package/core/{Assets.js → assets/Assets.js} +131 -56
  5. package/core/{Baked.js → assets/Baked.js} +4 -4
  6. package/core/assets/assetEntry.js +302 -0
  7. package/core/{assetHot.js → assets/assetHot.js} +9 -7
  8. package/core/{assetLoad.js → assets/assetLoad.js} +55 -16
  9. package/core/assets/assetLod.js +113 -0
  10. package/core/{assetManifest.js → assets/assetManifest.js} +19 -11
  11. package/core/{assetReport.js → assets/assetReport.js} +7 -14
  12. package/core/{namedModel.js → assets/namedModel.js} +17 -13
  13. package/core/{Audio.js → audio/Audio.js} +47 -25
  14. package/core/{audioRules.js → audio/audioRules.js} +8 -5
  15. package/core/{audioVoice.js → audio/audioVoice.js} +17 -30
  16. package/core/{Events.js → base/Events.js} +3 -3
  17. package/core/{I18n.js → base/I18n.js} +15 -12
  18. package/core/{Random.js → base/Random.js} +7 -4
  19. package/core/{Vars.js → base/Vars.js} +14 -4
  20. package/core/{easing.js → base/easing.js} +1 -1
  21. package/core/{errorCodes.js → base/errorCodes.js} +151 -125
  22. package/core/{errorHints.js → base/errorHints.js} +17 -10
  23. package/core/{errors.js → base/errors.js} +12 -10
  24. package/core/{events.generated.js → base/events.generated.js} +11 -0
  25. package/core/base/follows.js +26 -0
  26. package/core/base/math.js +66 -0
  27. package/core/{params.js → base/params.js} +5 -6
  28. package/core/base/saveValues.js +81 -0
  29. package/core/base/sections.js +97 -0
  30. package/core/base/spelling.js +32 -0
  31. package/core/base/util.js +32 -0
  32. package/core/{validate.js → base/validate.js} +34 -34
  33. package/core/{Engine.js → engine/Engine.js} +137 -91
  34. package/core/{Loading.js → engine/Loading.js} +34 -5
  35. package/core/{copies.js → engine/copies.js} +4 -4
  36. package/core/{headlessLoad.js → engine/headlessLoad.js} +32 -15
  37. package/core/{lifecycle.js → engine/lifecycle.js} +41 -34
  38. package/core/{loop.js → engine/loop.js} +88 -49
  39. package/core/engine/moduleSlots.js +176 -0
  40. package/core/{moduleTypes.js → engine/moduleTypes.js} +26 -14
  41. package/core/engine/modules.js +503 -0
  42. package/core/{page.js → engine/page.js} +59 -29
  43. package/core/{plugins.js → engine/plugins.js} +21 -12
  44. package/core/{services.js → engine/services.js} +50 -40
  45. package/core/{startup.js → engine/startup.js} +66 -54
  46. package/core/{Input.js → input/Input.js} +67 -39
  47. package/core/{inputContext.js → input/inputContext.js} +14 -5
  48. package/core/input/inputKeyboard.js +39 -0
  49. package/core/{inputPad.js → input/inputPad.js} +24 -3
  50. package/core/{inputPointer.js → input/inputPointer.js} +11 -3
  51. package/core/input/inputSeat.js +66 -0
  52. package/core/{inputTouch.js → input/inputTouch.js} +24 -7
  53. package/core/{Budget.js → inspect/Budget.js} +21 -20
  54. package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +43 -18
  55. package/core/{Describe.js → inspect/Describe.js} +34 -26
  56. package/core/{Inspect.js → inspect/Inspect.js} +39 -10
  57. package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
  58. package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
  59. package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
  60. package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
  61. package/core/{UrlState.js → inspect/UrlState.js} +60 -24
  62. package/core/{catalog.js → inspect/catalog.js} +15 -8
  63. package/core/{checks.js → inspect/checks.js} +7 -5
  64. package/core/{debugView.js → inspect/debugView.js} +4 -4
  65. package/core/{describeRender.js → inspect/describeRender.js} +24 -22
  66. package/core/{describeText.js → inspect/describeText.js} +17 -8
  67. package/core/inspect/geometryWatch.js +38 -0
  68. package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
  69. package/core/inspect/metadata.generated.js +4140 -0
  70. package/core/{pictureWriters.js → inspect/pictureWriters.js} +130 -47
  71. package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
  72. package/core/inspect/toolDoor.js +21 -0
  73. package/core/inspect/valueHistory.js +35 -0
  74. package/core/{Ops.js → ops/Ops.js} +44 -14
  75. package/core/{control.js → ops/control.js} +57 -31
  76. package/core/ops/holds.js +140 -0
  77. package/core/{opsAtomic.js → ops/opsAtomic.js} +18 -5
  78. package/core/{opsCheck.js → ops/opsCheck.js} +11 -10
  79. package/core/{opsFail.js → ops/opsFail.js} +5 -7
  80. package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
  81. package/core/{opsRun.js → ops/opsRun.js} +9 -6
  82. package/core/{owned.js → ops/owned.js} +33 -19
  83. package/core/{sharedPoint.js → ops/sharedPoint.js} +13 -16
  84. package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
  85. package/core/{stacks.js → ops/stacks.js} +34 -15
  86. package/core/{wrap.js → ops/wrap.js} +8 -6
  87. package/core/{SaveStore.js → saves/SaveStore.js} +53 -27
  88. package/core/{Saves.js → saves/Saves.js} +171 -54
  89. package/core/saves/saveApply.js +312 -0
  90. package/core/{saveFiles.js → saves/saveFiles.js} +45 -38
  91. package/core/{saveVersions.js → saves/saveVersions.js} +24 -23
  92. package/core/saves/session.js +231 -0
  93. package/core/saves/stateReplace.js +184 -0
  94. package/core/{Rays.js → scene/Rays.js} +44 -30
  95. package/core/{Views.js → scene/Views.js} +16 -8
  96. package/core/{adaptive.js → scene/adaptive.js} +19 -9
  97. package/core/{canvasBox.js → scene/canvasBox.js} +4 -3
  98. package/core/scene/compositeGround.js +72 -0
  99. package/core/scene/floor.js +17 -0
  100. package/core/{gameLights.js → scene/gameLights.js} +17 -7
  101. package/core/{grayMap.js → scene/grayMap.js} +8 -2
  102. package/core/{grid.js → scene/grid.js} +6 -4
  103. package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
  104. package/core/scene/ground.contract.js +14 -0
  105. package/core/scene/ground.js +139 -0
  106. package/core/{movement.js → scene/movement.js} +3 -3
  107. package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
  108. package/core/scene/pixel.js +154 -0
  109. package/core/scene/pixelRatio.js +167 -0
  110. package/core/{sceneDelta.js → scene/sceneDelta.js} +5 -5
  111. package/core/{sceneMethods.js → scene/sceneMethods.js} +43 -15
  112. package/core/scene/stepPoses.js +60 -0
  113. package/core/{targeting.js → scene/targeting.js} +4 -5
  114. package/core/{thingExplain.js → scene/thingExplain.js} +7 -6
  115. package/core/{thingOps.js → scene/thingOps.js} +25 -16
  116. package/core/{things.js → scene/things.js} +18 -5
  117. package/core/{threePatches.js → scene/threePatches.js} +1 -1
  118. package/core/{tier.js → scene/tier.js} +10 -0
  119. package/core/scene/view.js +161 -0
  120. package/core/{Batching.js → stream/Batching.js} +85 -28
  121. package/core/{Stream.js → stream/Stream.js} +80 -38
  122. package/core/{batchGroups.js → stream/batchGroups.js} +11 -9
  123. package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
  124. package/core/{scatter.js → stream/scatter.js} +7 -4
  125. package/core/{streamSources.js → stream/streamSources.js} +14 -8
  126. package/core/{Commits.js → threads/Commits.js} +17 -11
  127. package/core/{Jobs.js → threads/Jobs.js} +25 -13
  128. package/core/{Threads.js → threads/Threads.js} +21 -18
  129. package/core/{threadPure.js → threads/threadPure.js} +7 -5
  130. package/core/{threadServe.js → threads/threadServe.js} +3 -3
  131. package/core/{Clock.js → time/Clock.js} +20 -11
  132. package/core/{dayTime.js → time/dayTime.js} +5 -1
  133. package/core/{skip.js → time/skip.js} +28 -21
  134. package/core/{time.js → time/time.js} +32 -20
  135. package/core/{uiClock.js → time/uiClock.js} +4 -4
  136. package/docs/AI.md +92 -72
  137. package/docs/API.md +33 -28
  138. package/docs/CODEMAP.md +121 -200
  139. package/docs/COMMANDS.md +77 -70
  140. package/docs/CONVENTIONS.md +167 -24
  141. package/docs/MIGRATING-0.8.md +171 -0
  142. package/docs/MIGRATING-1.0.md +101 -0
  143. package/docs/THREE.md +140 -38
  144. package/docs/api/assets.md +12 -13
  145. package/docs/api/audio.md +6 -5
  146. package/docs/api/budget.md +4 -4
  147. package/docs/api/calendar.md +10 -11
  148. package/docs/api/cameraRig.md +32 -29
  149. package/docs/api/characters.md +35 -24
  150. package/docs/api/clock.md +1 -1
  151. package/docs/api/collider3d.md +9 -0
  152. package/docs/api/collision.md +12 -9
  153. package/docs/api/content.md +18 -17
  154. package/docs/api/dialogue.md +5 -4
  155. package/docs/api/engine.md +58 -54
  156. package/docs/api/events.md +17 -6
  157. package/docs/api/flow.md +1 -1
  158. package/docs/api/grids.md +1 -1
  159. package/docs/api/ground.md +6 -7
  160. package/docs/api/hud.md +2 -2
  161. package/docs/api/i18n.md +6 -6
  162. package/docs/api/input.md +9 -8
  163. package/docs/api/interactions.md +5 -5
  164. package/docs/api/inventory.md +10 -10
  165. package/docs/api/jobs.md +5 -5
  166. package/docs/api/level.md +10 -9
  167. package/docs/api/lightPool.md +1 -6
  168. package/docs/api/music.md +3 -3
  169. package/docs/api/nav.md +14 -12
  170. package/docs/api/openWorld.md +1 -1
  171. package/docs/api/particles.md +10 -7
  172. package/docs/api/photo.md +4 -2
  173. package/docs/api/pickups.md +3 -3
  174. package/docs/api/post.md +21 -5
  175. package/docs/api/quests.md +7 -5
  176. package/docs/api/rays.md +7 -7
  177. package/docs/api/rigid.md +29 -19
  178. package/docs/api/saves.md +13 -11
  179. package/docs/api/settings.md +9 -8
  180. package/docs/api/sky.md +8 -7
  181. package/docs/api/stream.md +8 -9
  182. package/docs/api/swarm.md +34 -0
  183. package/docs/api/terrain.md +6 -8
  184. package/docs/api/terrainDraw.md +2 -2
  185. package/docs/api/timeline.md +4 -4
  186. package/docs/api/tools.md +27 -22
  187. package/docs/api/triggers.md +2 -0
  188. package/docs/api/vars.md +1 -1
  189. package/docs/api/vegetation.md +4 -3
  190. package/docs/api/vegetationDraw.md +2 -2
  191. package/docs/api/water.md +7 -3
  192. package/docs/api/weather.md +27 -12
  193. package/docs/api/weatherDraw.md +4 -4
  194. package/docs/api/world.md +6 -6
  195. package/docs/recipes/01-new-game.md +28 -43
  196. package/docs/recipes/02-npc.md +21 -23
  197. package/docs/recipes/03-items-pickups.md +37 -53
  198. package/docs/recipes/04-quests.md +5 -4
  199. package/docs/recipes/05-props-bake.md +34 -44
  200. package/docs/recipes/06-clock-events.md +31 -22
  201. package/docs/recipes/07-flow-scenes-pause.md +30 -32
  202. package/docs/recipes/08-weather-sky.md +91 -37
  203. package/docs/recipes/09-materials-lights-models.md +25 -39
  204. package/docs/recipes/10-blender-level.md +22 -11
  205. package/docs/recipes/11-vehicles.md +44 -24
  206. package/docs/recipes/12-navmesh.md +60 -15
  207. package/docs/recipes/13-animation.md +70 -22
  208. package/docs/recipes/14-custom-module.md +33 -20
  209. package/docs/recipes/15-perf.md +51 -28
  210. package/docs/recipes/16-dev-bridge.md +39 -58
  211. package/docs/recipes/18-world.md +49 -28
  212. package/docs/recipes/19-shooting-picking.md +7 -4
  213. package/docs/recipes/20-content-actions-save.md +55 -40
  214. package/docs/recipes/21-camera.md +47 -25
  215. package/docs/recipes/22-shop-gold.md +21 -16
  216. package/docs/recipes/23-ops.md +28 -24
  217. package/docs/recipes/26-ui-parts.md +25 -14
  218. package/docs/recipes/27-net.md +3 -5
  219. package/docs/recipes/28-terrain.md +119 -23
  220. package/docs/recipes/29-grid.md +3 -3
  221. package/docs/recipes/30-templates.md +63 -30
  222. package/docs/recipes/31-audio.md +7 -7
  223. package/docs/recipes/32-action-game.md +21 -11
  224. package/docs/recipes/33-stream-sources.md +6 -3
  225. package/docs/recipes/34-environment-lighting.md +72 -25
  226. package/docs/recipes/35-picture-from-reference.md +20 -23
  227. package/docs/recipes/36-ground-plants.md +106 -0
  228. package/docs/recipes/40-scene.md +18 -21
  229. package/docs/recipes/43-shader-patches-surfaces.md +27 -48
  230. package/docs/recipes/44-water-weather-hooks.md +56 -50
  231. package/docs/recipes/45-cascaded-shadows.md +41 -20
  232. package/docs/recipes/46-blender-art-route.md +9 -10
  233. package/docs/recipes/49-game-module-contract.md +7 -6
  234. package/docs/recipes/50-own-renderer.md +3 -2
  235. package/docs/recipes/51-capability-catalog.md +14 -8
  236. package/docs/recipes/52-around-the-picture.md +56 -100
  237. package/docs/recipes/53-ground-up-close.md +61 -24
  238. package/docs/recipes/55-mods-time-wrap.md +17 -20
  239. package/docs/recipes/56-webgpu-tsl.md +28 -15
  240. package/docs/recipes/57-control.md +39 -12
  241. package/docs/recipes/58-input.md +15 -2
  242. package/docs/recipes/59-depth-post-effects.md +1 -1
  243. package/docs/recipes/60-judge-the-picture.md +30 -25
  244. package/docs/recipes/62-picture-code.md +129 -39
  245. package/docs/recipes/63-third-person-start.md +19 -5
  246. package/docs/recipes/64-particles.md +54 -5
  247. package/docs/recipes/65-swarm.md +140 -0
  248. package/docs/recipes/66-common-tasks.md +313 -0
  249. package/examples/action/.threedog/content-index.json +1 -1
  250. package/examples/action/GAMEMAP.md +5 -5
  251. package/examples/perf-island/.threedog/content-index.json +1 -0
  252. package/examples/{sheepisland → perf-island}/GAMEMAP.md +15 -14
  253. package/examples/{sheepisland → perf-island}/assets.js +1 -1
  254. package/examples/{sheepisland → perf-island}/main.js +8 -8
  255. package/examples/{sheepisland → perf-island}/models.js +1 -1
  256. package/examples/{sheepisland → perf-island}/params.js +1 -1
  257. package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
  258. package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
  259. package/examples/{sheepisland → perf-island}/views.js +1 -1
  260. package/examples/plain-picture/GAMEMAP.md +4 -1
  261. package/examples/rc2d/GAMEMAP.md +4 -3
  262. package/examples/rc2d/main.js +1 -3
  263. package/examples/rc2d/rc2d.js +1 -1
  264. package/examples/styletest/.threedog/content-index.json +1 -1
  265. package/examples/styletest/GAMEMAP.md +6 -5
  266. package/examples/techniques/contact-shadows/contactShadows.js +1 -1
  267. package/examples/techniques/contact-shadows/main.js +1 -1
  268. package/examples/techniques/interior-light/main.js +1 -1
  269. package/examples/techniques/modular-building/README.md +7 -6
  270. package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
  271. package/examples/techniques/procedural-animation/README.md +1 -1
  272. package/examples/webgpu-tsl/GAMEMAP.md +2 -1
  273. package/examples/world/.threedog/content-index.json +1 -1
  274. package/examples/world/GAMEMAP.md +9 -7
  275. package/examples/world/main.js +3 -3
  276. package/examples/world/picture/sky.js +1 -1
  277. package/index.d.ts +16 -12
  278. package/index.js +53 -32
  279. package/llms.txt +11 -14
  280. package/modules/ambience/Ambience.js +16 -11
  281. package/modules/calendar/Calendar.js +19 -19
  282. package/modules/calendar/index.js +18 -16
  283. package/modules/calendar/schedule.js +11 -6
  284. package/modules/calendar/seasons.js +7 -7
  285. package/modules/camera/FirstPersonCamera.js +5 -5
  286. package/modules/camera/FixedCamera.js +43 -30
  287. package/modules/camera/FollowCamera.js +24 -15
  288. package/modules/camera/RtsCamera.js +12 -11
  289. package/modules/camera/common.js +72 -37
  290. package/modules/camera/contract.js +1 -0
  291. package/modules/camera/pixelSnap.js +62 -0
  292. package/modules/characters/Character.js +166 -70
  293. package/modules/characters/NPC.js +84 -44
  294. package/modules/characters/assetModel.js +16 -12
  295. package/modules/characters/astar.js +48 -27
  296. package/modules/characters/behaviors.js +4 -5
  297. package/modules/characters/character.contract.js +21 -0
  298. package/modules/characters/contract.js +17 -3
  299. package/modules/characters/index.js +240 -226
  300. package/modules/characters/moveHelpers.js +88 -12
  301. package/modules/characters/mover.contract.js +14 -0
  302. package/modules/characters/movers/common.js +22 -18
  303. package/modules/characters/movers/manual.js +1 -1
  304. package/modules/characters/movers/rapier.js +18 -10
  305. package/modules/characters/movers/simple.js +26 -13
  306. package/modules/characters/movers/support.js +24 -13
  307. package/modules/characters/npcAvoid.js +19 -16
  308. package/modules/characters/npcSim.js +88 -32
  309. package/modules/characters/npcView.js +19 -11
  310. package/modules/characters/pathAsync.js +81 -29
  311. package/modules/characters/pathJob.js +38 -21
  312. package/modules/characters/pathWorker.js +1 -1
  313. package/modules/characters/player.js +120 -0
  314. package/modules/characters/playerStrings.js +2 -2
  315. package/modules/characters/proceduralRig.js +2 -2
  316. package/modules/characters/seat.js +56 -0
  317. package/modules/characters/useModel.js +3 -3
  318. package/modules/characters/vehicle.contract.js +8 -5
  319. package/modules/characters/walkTo.js +40 -33
  320. package/modules/collision/Collision.js +69 -45
  321. package/modules/collision/contract.js +15 -0
  322. package/modules/collision/grid.js +6 -1
  323. package/modules/content/explain.js +2 -3
  324. package/modules/content/fields.js +24 -3
  325. package/modules/content/ids.js +5 -3
  326. package/modules/content/index.js +132 -114
  327. package/modules/content/loader.js +117 -140
  328. package/modules/content/markers.js +25 -0
  329. package/modules/content/models.js +54 -17
  330. package/modules/content/packs.js +5 -4
  331. package/modules/content/parts.js +2 -2
  332. package/modules/content/places.js +36 -0
  333. package/modules/content/props.js +22 -17
  334. package/modules/content/rules.js +47 -61
  335. package/modules/content/stages.js +7 -7
  336. package/modules/content/templates.js +80 -49
  337. package/modules/content/words.js +47 -0
  338. package/modules/debug/DebugPanel.js +14 -45
  339. package/modules/flow/contract.js +2 -1
  340. package/modules/flow/index.js +30 -16
  341. package/modules/gameplay/Container.js +17 -13
  342. package/modules/gameplay/Containers.js +23 -6
  343. package/modules/gameplay/Dialogue.js +93 -34
  344. package/modules/gameplay/Interactions.js +93 -51
  345. package/modules/gameplay/Inventory.js +64 -22
  346. package/modules/gameplay/Quests.js +146 -30
  347. package/modules/gameplay/boxOps.js +8 -1
  348. package/modules/gameplay/dialogueBubbles.js +16 -12
  349. package/modules/gameplay/inventoryOps.js +11 -8
  350. package/modules/gameplay/pickups.js +63 -37
  351. package/modules/gameplay/questLog.js +4 -2
  352. package/modules/gameplay/questSave.js +9 -4
  353. package/modules/gameplay/quests.contract.js +1 -1
  354. package/modules/grid/Grid.js +2 -2
  355. package/modules/grid/Layer.js +12 -8
  356. package/modules/grid/index.js +28 -23
  357. package/modules/grid/ops.js +43 -46
  358. package/modules/grid/preview.js +7 -7
  359. package/modules/grid/tiles.js +6 -6
  360. package/modules/hlod/index.js +42 -57
  361. package/modules/hud/index.js +22 -14
  362. package/modules/hud/parts.js +8 -8
  363. package/modules/level/contract.js +16 -0
  364. package/modules/level/heightfield.js +29 -31
  365. package/modules/level/index.js +113 -161
  366. package/modules/level/load.js +196 -0
  367. package/modules/level/meshes.js +65 -0
  368. package/modules/level/nodes.js +40 -23
  369. package/modules/lights/index.js +33 -183
  370. package/modules/lights/slots.js +93 -0
  371. package/modules/lights/sources.js +90 -0
  372. package/modules/music/Music.js +34 -28
  373. package/modules/music/rules.js +1 -1
  374. package/modules/nav/contract.js +16 -0
  375. package/modules/nav/index.js +180 -49
  376. package/modules/nav/navPath.js +45 -10
  377. package/modules/net/Client.js +7 -7
  378. package/modules/net/Host.js +7 -7
  379. package/modules/net/Net.js +1 -1
  380. package/modules/net/index.js +6 -5
  381. package/modules/net/sync.js +2 -2
  382. package/modules/net/transports.js +2 -2
  383. package/modules/particles/Particles.js +95 -29
  384. package/modules/particles/effect.js +86 -32
  385. package/modules/particles/shaders.js +19 -1
  386. package/modules/photo/Photo.js +23 -23
  387. package/modules/rigid/RigidBodies.js +255 -89
  388. package/modules/rigid/Vehicles.js +17 -8
  389. package/modules/rigid/collider3d.contract.js +26 -0
  390. package/modules/rigid/ragdoll.js +298 -0
  391. package/modules/rigid/ragdollBones.js +209 -0
  392. package/modules/rigid/refresh.js +10 -0
  393. package/modules/rigid/sync.js +51 -20
  394. package/modules/settings/Settings.js +177 -61
  395. package/modules/settings/apply.js +20 -13
  396. package/modules/settings/sections.js +19 -14
  397. package/modules/settings/strings.js +2 -2
  398. package/modules/settings/view.js +3 -3
  399. package/modules/sky/Sky.js +29 -22
  400. package/modules/sky/clouds.js +7 -7
  401. package/modules/sky/dome.js +33 -20
  402. package/modules/sky/domeLayers.js +9 -9
  403. package/modules/sky/environment.js +6 -6
  404. package/modules/sky/frame.js +19 -10
  405. package/modules/sky/season.js +7 -1
  406. package/modules/sky/shader.js +24 -25
  407. package/modules/sky/skyModule.js +17 -28
  408. package/modules/sky/tint.js +1 -1
  409. package/modules/swarm/Swarm.js +356 -0
  410. package/modules/swarm/draw.js +68 -0
  411. package/modules/swarm/grid.js +63 -0
  412. package/modules/terrain/ChunkManager.js +71 -59
  413. package/modules/terrain/chunkQueries.js +7 -24
  414. package/modules/terrain/chunkWorker.js +1 -1
  415. package/modules/terrain/draw.js +14 -11
  416. package/modules/terrain/index.js +42 -42
  417. package/modules/terrain/terrainColorMap.js +6 -3
  418. package/modules/terrain/terrainDefaults.js +2 -1
  419. package/modules/terrain/terrainEdit.js +45 -29
  420. package/modules/terrain/terrainGen.js +19 -12
  421. package/modules/terrain/terrainIsland.js +2 -2
  422. package/modules/terrain/terrainMesh.js +7 -6
  423. package/modules/terrain/terrainShape.js +8 -10
  424. package/modules/terrain/terrainShapeMain.js +3 -3
  425. package/modules/timeline/Timeline.js +83 -43
  426. package/modules/timeline/Tween.js +25 -19
  427. package/modules/timeline/shots.js +24 -17
  428. package/modules/triggers/index.js +95 -28
  429. package/modules/vegetation/Vegetation.js +34 -26
  430. package/modules/vegetation/densityMap.js +4 -7
  431. package/modules/vegetation/draw.js +39 -18
  432. package/modules/vegetation/groundChunks.js +21 -38
  433. package/modules/vegetation/index.js +37 -12
  434. package/modules/vegetation/modelGeometry.js +3 -6
  435. package/modules/vegetation/nearFade.js +1 -1
  436. package/modules/water/Water.js +20 -16
  437. package/modules/water/surface.js +3 -3
  438. package/modules/weather/Weather.js +52 -40
  439. package/modules/weather/particles.js +8 -8
  440. package/modules/weather/weatherDraw.js +28 -23
  441. package/modules/world/World.js +28 -15
  442. package/modules/world/explain.js +1 -1
  443. package/modules/world/index.js +30 -17
  444. package/modules/world/persist.js +90 -27
  445. package/modules/world/pos.js +5 -5
  446. package/modules/world/records.js +37 -11
  447. package/modules/world/sim.js +78 -27
  448. package/modules/world/simFar.js +2 -2
  449. package/modules/world/state.js +43 -11
  450. package/modules/world/thingSource.js +20 -5
  451. package/modules/world/views.js +27 -14
  452. package/package.json +48 -7
  453. package/presets.js +1 -3
  454. package/render/PostFX.js +83 -53
  455. package/render/backend.js +31 -33
  456. package/render/cascades.js +17 -12
  457. package/render/cascades.tsl.js +5 -8
  458. package/render/daylight.js +20 -3
  459. package/render/detail.js +8 -7
  460. package/render/effects.js +28 -25
  461. package/render/fuse.js +3 -3
  462. package/render/fx/cloudShadow.tsl.js +3 -3
  463. package/render/fx/detail.tsl.js +1 -1
  464. package/render/fx/index.js +5 -10
  465. package/render/fx/library.tsl.js +11 -0
  466. package/render/fx/lighting.tsl.js +2 -1
  467. package/render/fx/nodeErrors.tsl.js +2 -2
  468. package/render/fx/objectOrigin.tsl.js +1 -2
  469. package/render/fx/particles.tsl.js +8 -6
  470. package/render/fx/patchNodes.tsl.js +5 -15
  471. package/render/fx/postWebGPU.tsl.js +30 -26
  472. package/render/fx/sky.tsl.js +15 -17
  473. package/render/fx/uniforms.tsl.js +4 -4
  474. package/render/fx/wind.tsl.js +1 -1
  475. package/render/fxNumbers.js +3 -0
  476. package/render/layers.js +2 -2
  477. package/render/lighting.js +5 -3
  478. package/render/lightmap.js +41 -21
  479. package/render/lights.js +6 -6
  480. package/render/lit.js +24 -0
  481. package/render/materials.js +8 -7
  482. package/render/mergeCommon.js +22 -0
  483. package/render/modeling.js +2 -2
  484. package/render/occlusion.js +62 -15
  485. package/render/ownFrame.js +4 -4
  486. package/render/patches.js +15 -15
  487. package/render/postWebGL.js +15 -12
  488. package/render/probes.js +41 -19
  489. package/render/recordSweep.js +117 -0
  490. package/render/shaderErrors.js +10 -9
  491. package/render/shadowCache.tsl.js +107 -0
  492. package/render/shadowTypes.js +9 -0
  493. package/{core → render}/shadows.js +59 -13
  494. package/render/slots.js +7 -7
  495. package/render/terms.js +22 -24
  496. package/render/uniformDecl.js +1 -1
  497. package/types/core.d.ts +336 -202
  498. package/types/gameplay.d.ts +254 -130
  499. package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
  500. package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
  501. package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
  502. package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +8 -16
  503. package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
  504. package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
  505. package/types/generated/core/{Input.d.ts → input/Input.d.ts} +28 -10
  506. package/types/generated/core/input/inputSeat.d.ts +26 -0
  507. package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
  508. package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +17 -3
  509. package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +6 -4
  510. package/types/generated/core/{control.d.ts → ops/control.d.ts} +14 -10
  511. package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +62 -18
  512. package/types/generated/core/{session.d.ts → saves/session.d.ts} +3 -2
  513. package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
  514. package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +2 -2
  515. package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
  516. package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +22 -18
  517. package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
  518. package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
  519. package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
  520. package/types/generated/modules/calendar/Calendar.d.ts +10 -11
  521. package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
  522. package/types/generated/modules/grid/Grid.d.ts +1 -0
  523. package/types/generated/modules/grid/Layer.d.ts +1 -1
  524. package/types/generated/modules/grid/index.d.ts +3 -3
  525. package/types/generated/modules/music/Music.d.ts +7 -5
  526. package/types/generated/modules/particles/Particles.d.ts +5 -4
  527. package/types/generated/modules/sky/Sky.d.ts +21 -10
  528. package/types/generated/modules/swarm/Swarm.d.ts +80 -0
  529. package/types/generated/modules/timeline/Timeline.d.ts +7 -5
  530. package/types/generated/modules/water/Water.d.ts +1 -0
  531. package/types/generated/modules/weather/Weather.d.ts +14 -16
  532. package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
  533. package/types/generated/modules/world/World.d.ts +11 -7
  534. package/types/generated/render/PostFX.d.ts +21 -23
  535. package/types/generated/render/materials.d.ts +1 -0
  536. package/types/generated/render/occlusion.d.ts +9 -0
  537. package/types/generated/render/patches.d.ts +1 -0
  538. package/types/generated/ui/Focus.d.ts +1 -0
  539. package/types/generated/ui/UI.d.ts +1 -0
  540. package/types/nav.d.ts +47 -15
  541. package/types/physics.d.ts +150 -73
  542. package/types/pixel.d.ts +75 -0
  543. package/types/tsl.d.ts +37 -4
  544. package/types/world.d.ts +48 -75
  545. package/ui/Focus.js +10 -9
  546. package/ui/Parts.js +13 -5
  547. package/ui/UI.js +7 -7
  548. package/ui/defaults.js +3 -2
  549. package/ui/theme.js +7 -5
  550. package/core/assetEntry.js +0 -109
  551. package/core/engineCamera.js +0 -32
  552. package/core/ground.js +0 -104
  553. package/core/holds.js +0 -134
  554. package/core/math.js +0 -48
  555. package/core/moduleSlots.js +0 -100
  556. package/core/modules.js +0 -314
  557. package/core/saveApply.js +0 -210
  558. package/core/saveValues.js +0 -46
  559. package/core/session.js +0 -174
  560. package/core/shadowTypes.js +0 -16
  561. package/core/util.js +0 -17
  562. package/core/view.js +0 -43
  563. package/docs/MIGRATING-0.3.md +0 -248
  564. package/docs/MIGRATING-0.4.md +0 -320
  565. package/docs/MIGRATING-0.5.md +0 -68
  566. package/docs/MIGRATING-0.6.md +0 -126
  567. package/docs/PERF.md +0 -245
  568. package/docs/recipes/36-sky-ground-plants.md +0 -158
  569. package/docs/recipes/37-terrain-hooks.md +0 -115
  570. package/docs/recipes/38-environment-hooks.md +0 -67
  571. package/docs/recipes/42-terrain-shape.md +0 -64
  572. package/docs/recipes/47-island-snow-backdrop.md +0 -43
  573. package/docs/recipes/54-three-idioms.md +0 -88
  574. package/examples/plain-picture/FINDINGS.md +0 -53
  575. package/examples/sheepisland/.threedog/content-index.json +0 -1
  576. package/modules/camera/projection.js +0 -21
  577. /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
  578. /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
  579. /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
  580. /package/core/{actor.js → ops/actor.js} +0 -0
  581. /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
  582. /package/core/{saveIds.js → saves/saveIds.js} +0 -0
  583. /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
  584. /package/core/{cells.js → stream/cells.js} +0 -0
  585. /package/core/{streamCells.js → stream/streamCells.js} +0 -0
  586. /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
  587. /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
  588. /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
  589. /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
  590. /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
  591. /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
  592. /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
  593. /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
@@ -1,14 +1,17 @@
1
1
  // Runtime checks: when an option or name is misspelled, print the fix to the console ("did you mean `xxx`?").
2
2
  // Type checking (npm run types) catches mistakes while you write code; this catches the same kind at runtime, which also works for code without type checking.
3
3
  //
4
- // readParams('npcs.add()', NPC_PARAMS, opts) // options: an unknown key throws in dev (core/params.js)
4
+ // readParams('npcs.add()', NPC_PARAMS, opts) // options: an unknown key throws in dev (core/base/params.js)
5
5
  // checkOptions('inventory.define()', def, KEYS, { loose: true }) // extensible data: warns once on a near-miss key
6
6
  // warnMissing('action', 'jupm', ['jump', 'run']) // 'action "jupm" does not exist, did you mean `jump`? (available: jump, run)'
7
- // Properties the engine writes every frame (sky lights, camera ...) are core/owned.js defineOwned: the engine yields to a direct write and warns once
7
+ // Properties the engine writes every frame (sky lights, camera ...) are core/ops/owned.js defineOwned: the engine yields to a direct write and warns once
8
8
  //
9
9
  // On by default; createEngine({ validate: false }) turns it all off (for release builds). Each message warns only once.
10
10
 
11
11
  import { hintText, coded, codedError } from './errorHints.js';
12
+ import { isOptions } from './util.js';
13
+ import { closest } from './spelling.js';
14
+ export { closest };
12
15
 
13
16
  const STRINGS = {
14
17
  unknownKey: '{where}: unknown option "{key}", {hint}',
@@ -42,12 +45,38 @@ const enabled = () => live === 0 || quiet < live;
42
45
  // @ts-ignore Vite's import.meta.env (undefined outside Vite)
43
46
  const ENV = import.meta.env;
44
47
  export const DEV = !!(ENV?.DEV || ENV?.THREEDOG_TEST);
48
+ /** Positions and speeds beyond this are damage, not a big world: float32 models are already centimetres off at 1e5 and useless far before 1e7 @internal */
49
+ export const SAVE_MAX = 1e7;
50
+ /** A number the running game can take. Past SAVE_MAX the ground loops around it never end, or a step later a position goes out of range @internal */
51
+ export const saveNumberOk = v => Number.isFinite(v) && Math.abs(v) <= SAVE_MAX;
52
+ /** Whether a position can be written: [x, y, z], or { x, z } with y left out or a number, each one a save can hold (a save with a bigger one never loads). The one answer; thing.set asks it in can, world's putPos before it writes @param {any} p @returns {boolean} @internal */
53
+ export const goodPos = p => Array.isArray(p) ? p.length === 3 && p.every(saveNumberOk) : saveNumberOk(p?.x) && saveNumberOk(p?.z) && (p.y === undefined || saveNumberOk(p.y));
45
54
  /** The Vite dev server itself (npm run dev, not the test bundle): only it serves /__threedog endpoints and the dev bridge. The other spelling of "dev", named so nothing reads import.meta.env.DEV on its own. */
46
55
  export const DEV_SERVER = !!ENV?.DEV;
47
56
  /** Vite's base URL ('/' outside Vite) */
48
57
  export const BASE_URL = ENV?.BASE_URL ?? '/';
49
58
  const warned = new Set();
50
59
 
60
+ /**
61
+ * The one check behind every `.material = m` setter a module hands out.
62
+ * @param {string} code the module's error code
63
+ * @param {string} what what is being set, e.g. 'engine.water.material'
64
+ * @param {any} m the value
65
+ * @param {string} [next] what to write instead, appended to the message
66
+ * @internal
67
+ */
68
+ export function needMaterial(code, what, m, next = '') { if (!m?.isMaterial) throw codedError(code, `${what} takes a three.js Material, got ${m}${next}`); }
69
+ /**
70
+ * A shader part written for one renderer only, on the other one: the error that names the missing form.
71
+ * @param {string} code the module's error code
72
+ * @param {string} what the part, e.g. 'wind'
73
+ * @param {boolean} gpu true on WebGPURenderer (the glsl form cannot run), false on WebGLRenderer (the tsl form cannot run)
74
+ * @internal
75
+ */
76
+ export const oneForm = (code, what, gpu) => codedError(code, gpu
77
+ ? `${what} has only a glsl form, which WebGPURenderer cannot draw: give tsl too ({ glsl, tsl })`
78
+ : `${what} has only a tsl form, which WebGLRenderer cannot draw: give glsl too ({ glsl, tsl })`);
79
+
51
80
  /**
52
81
  * Count one engine's createEngine({ validate }) for the page-wide warnings; returns the release for dispose().
53
82
  * @param {boolean | undefined} on
@@ -83,33 +112,6 @@ export function note(msg, key) {
83
112
  console.info('[threedog] ' + msg);
84
113
  }
85
114
 
86
- /** Edit distance (case-insensitive; swapping two adjacent letters counts as 1, e.g. jupm -> jump) */
87
- function distance(a, b) {
88
- a = a.toLowerCase(); b = b.toLowerCase();
89
- const d = Array.from({ length: a.length + 1 }, (_, i) => [i]);
90
- for (let j = 1; j <= b.length; j++) d[0][j] = j;
91
- for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) {
92
- d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
93
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
94
- }
95
- return d[a.length][b.length];
96
- }
97
-
98
- /**
99
- * The entry of list closest to name; null if too far. Without maxDist the limit scales with length (longer names tolerate more errors).
100
- * Too far by spelling, a name of 4+ letters that is part of exactly one entry still matches ('forward' -> 'moveForward'): AIs often drop a prefix.
101
- */
102
- export function closest(name, list, maxDist) {
103
- name = String(name);
104
- const limit = maxDist ?? (name.length <= 4 ? 1 : name.length <= 8 ? 2 : 3);
105
- let best = null, bd = Infinity;
106
- for (const c of list) { if (c === name) continue; const d = distance(name, String(c)); if (d < bd) { bd = d; best = c; } }
107
- if (bd <= limit) return best;
108
- if (maxDist != null || name.length < 4) return null;
109
- const low = name.toLowerCase(), part = [...list].filter(c => String(c).toLowerCase().includes(low));
110
- return part.length === 1 ? part[0] : null;
111
- }
112
-
113
115
  const listText = list => { const a = [...list]; return a.length ? a.slice(0, 15).join(', ') + (a.length > 15 ? fmt(STRINGS.more, { n: a.length }) : '') : STRINGS.none; };
114
116
 
115
117
  /** Text like 'xxx "name" does not exist, did you mean `yyy`? (available: a, b, c)', shared by errors and warnings. */
@@ -120,7 +122,7 @@ export function missingText(kind, name, list) {
120
122
  /** A name does not exist: warn once */
121
123
  export function warnMissing(kind, name, list) {
122
124
  // may be called every frame: keyed by the name, so the list text is built only the first time
123
- if (!enabled || warned.has(kind + '\0' + name)) return;
125
+ if (!enabled() || warned.has(kind + '\0' + name)) return;
124
126
  warnOnce(coded('unknown-name', missingText(kind, name, list)), kind + '\0' + name);
125
127
  }
126
128
 
@@ -135,17 +137,15 @@ export function unknownOptionText(where, key, known, { soft = false } = {}) {
135
137
  if (!c && soft) return null;
136
138
  return fmt(STRINGS.unknownKey, { where, key, hint: c ? fmt(STRINGS.didYouMean, { name: c }) : fmt(STRINGS.available, { list: known.join(', ') }) });
137
139
  }
138
- /** Is options an object a game passed (not a Three.js object, array or missing)? */
139
- const isOptionsObject = o => !!o && typeof o === 'object' && !Array.isArray(o) && !o.isObject3D && !o.isVector3;
140
140
 
141
141
  /**
142
142
  * Unknown keys in extensible data (item definitions, template instance state, material specs: objects where games add their own fields): warn once.
143
- * Options bags of public calls do not come here: they go through readParams (core/params.js), where an unknown key throws in dev with the
143
+ * Options bags of public calls do not come here: they go through readParams (core/base/params.js), where an unknown key throws in dev with the
144
144
  * did-you-mean and warns once in a release build. Why two kinds: a misspelled option is always a bug and should stop on the spot; extra fields in extensible data may be the game's own, so only near-spellings are hinted (loose).
145
145
  * where is the origin (such as 'inventory.define()'), known are the keys the code reads. loose: report only near-misses.
146
146
  */
147
147
  export function checkOptions(where, opts, known, { loose = false } = {}) {
148
- if (!enabled() || !isOptionsObject(opts)) return;
148
+ if (!enabled() || !isOptions(opts)) return;
149
149
  for (const k of Object.keys(opts)) {
150
150
  const msg = unknownOptionText(where, k, known, { soft: loose });
151
151
  if (!msg) continue;
@@ -5,47 +5,50 @@
5
5
  import * as THREE from 'three';
6
6
  import { Page } from './page.js';
7
7
  import { createServices } from './services.js';
8
- import { Stacks } from './stacks.js';
9
- import { PostFX } from '../render/PostFX.js';
10
- import { Occlusion } from '../render/occlusion.js';
11
- import { createDefaultLights } from '../render/lights.js';
12
- import { registerEngine } from '../render/materials.js';
13
- import { createUniforms } from '../render/effects.js';
14
- import { bindUniforms } from '../render/engineUniforms.js';
15
- import { UIParts } from '../ui/Parts.js';
16
- import { defineCoreParts } from '../ui/defaults.js';
17
- import { applyUITheme } from '../ui/theme.js';
18
- import { trackValidate, warnOnce, DEV } from './validate.js';
19
- import { readParams } from './params.js';
8
+ import { Stacks } from '../ops/stacks.js';
9
+ import { PostFX } from '../../render/PostFX.js';
10
+ import { Occlusion } from '../../render/occlusion.js';
11
+ import { createDefaultLights } from '../../render/lights.js';
12
+ import { registerEngine } from '../../render/materials.js';
13
+ import { createUniforms } from '../../render/effects.js';
14
+ import { bindUniforms } from '../../render/engineUniforms.js';
15
+ import { UIParts } from '../../ui/Parts.js';
16
+ import { defineCoreParts } from '../../ui/defaults.js';
17
+ import { applyUITheme } from '../../ui/theme.js';
18
+ import { trackValidate, warnOnce, DEV } from '../base/validate.js';
19
+ import { readParams } from '../base/params.js';
20
20
  import { loopMethods } from './loop.js';
21
- import { holdMethods } from './holds.js';
21
+ import { holdMethods } from '../ops/holds.js';
22
22
  import { startupMethods } from './startup.js';
23
- import { groundMethods, flatGround } from './ground.js';
24
- import { actorMethods } from './actor.js';
25
- import { forcedTier, defaultPixelRatio } from './tier.js';
26
- import { tier as detectTier, tierBeforeRenderer, ownMsaa, timerContext, isWebGPU, webgpuPart, watchNodePrograms } from '../render/backend.js';
27
- import { dressNodeTwins } from '../render/patches.js';
23
+ import { groundMethods, flatGround } from '../scene/ground.js';
24
+ import { actorMethods } from '../ops/actor.js';
25
+ import { forcedTier, storedMsaa } from '../scene/tier.js';
26
+ import { tier as detectTier, tierBeforeRenderer, ownMsaa, timerContext, isWebGPU, webgpuPart, watchNodePrograms } from '../../render/backend.js';
27
+ import { recordSweep } from '../../render/recordSweep.js';
28
+ import { dressNodeTwins } from '../../render/patches.js';
28
29
  import { lifecycleMethods, clearHooks, checkCanvasUsable } from './lifecycle.js';
29
- import { createAdaptive, GpuTimer } from './adaptive.js';
30
- import { watchRejections } from './errors.js';
31
- import { createMovement } from './movement.js';
30
+ import { createAdaptive, GpuTimer } from '../scene/adaptive.js';
31
+ import { firstRatio, noteDeviceBox, pixelSizeOn } from '../scene/pixelRatio.js';
32
+ import { watchRejections } from '../base/errors.js';
33
+ import { createMovement } from '../scene/movement.js';
32
34
  import { moduleMethods } from './modules.js';
33
- import { skipMethods } from './skip.js';
34
- import { checkMethods } from './checks.js';
35
- import { canvasBox, placeUI, resizeMethods } from './canvasBox.js';
36
- import { sceneMethods } from './sceneMethods.js';
37
- import { EngineCamera } from './engineCamera.js';
38
- import { recordRender } from './describeRender.js';
39
- import { installPictureWriters } from './pictureWriters.js';
35
+ import { skipMethods } from '../time/skip.js';
36
+ import { checkMethods } from '../inspect/checks.js';
37
+ import { toolDoor } from '../inspect/toolDoor.js';
38
+ import { canvasBox, placeUI, resizeMethods } from '../scene/canvasBox.js';
39
+ import { sceneMethods } from '../scene/sceneMethods.js';
40
+ import { movedOwned } from '../ops/owned.js';
41
+ import { recordRender } from '../inspect/describeRender.js';
42
+ import { installPictureWriters } from '../inspect/pictureWriters.js';
40
43
  import { ownHook } from './moduleTypes.js';
41
- import { defineShadows } from './shadows.js';
42
- import { defineTerms } from '../render/terms.js';
43
- import { defineView } from './view.js';
44
- import { nameShaderErrors } from '../render/shaderErrors.js';
45
- import { probeMethods } from '../render/probes.js';
46
- import { lightmapMethods } from '../render/lightmap.js';
44
+ import { defineShadows } from '../../render/shadows.js';
45
+ import { defineTerms } from '../../render/terms.js';
46
+ import { defineView, checkCamera } from '../scene/view.js';
47
+ import { nameShaderErrors } from '../../render/shaderErrors.js';
48
+ import { probeMethods } from '../../render/probes.js';
49
+ import { lightmapMethods } from '../../render/lightmap.js';
47
50
  import { headlessSettled } from './headlessLoad.js';
48
- import { codedError } from './errorHints.js';
51
+ import { coded, codedError } from '../base/errorHints.js';
49
52
  const FALLBACKS = ['webgl2', 'webgl', 'error'];
50
53
  // createEngine() options: the one table for the unknown-key and type check (dev throws with did-you-mean, release warns once), the plain
51
54
  // defaults and engine.catalog('core').params; R6 checks EngineOptions (types/core.d.ts) has exactly these keys. A key with several shapes
@@ -54,7 +57,7 @@ const FALLBACKS = ['webgl2', 'webgl', 'error'];
54
57
  export const ENGINE_PARAMS = {
55
58
  canvas: 'object?', renderer: { type: 'string|object', optional: true, desc: "'webgl' (default), 'webgpu', or a renderer the game built" },
56
59
  fallback: { type: 'string', optional: true, values: FALLBACKS }, antialias: 'bool?',
57
- pixelRatio: 'number?', adaptiveResolution: { type: 'bool', default: true }, targetFps: { type: 'number', default: 55, min: 1 },
60
+ pixelRatio: 'number?', pixelSize: { type: 'int', optional: true, min: 1, desc: 'real screen pixels per art pixel' }, adaptiveResolution: { type: 'bool', default: true }, targetFps: { type: 'number', default: 55, min: 1 },
58
61
  ui: 'object?', audio: 'object?', fov: { type: 'number', default: 55, min: 1, max: 179 }, near: { type: 'number', default: 0.3, min: 0 },
59
62
  locale: { type: 'string', default: 'auto' }, strings: 'object?', bindings: 'object?', saveKey: { type: 'string', default: 'game' },
60
63
  joystick: { type: 'string|bool', default: 'auto' }, headless: 'bool?', validate: { type: 'bool', default: true }, decoders: 'string?',
@@ -62,9 +65,13 @@ export const ENGINE_PARAMS = {
62
65
  pauseOnBlur: { type: 'bool', default: true }, batching: 'bool|object?', lights: { type: 'bool', default: true },
63
66
  };
64
67
 
65
- /** createEngine({ renderer: 'webgpu' }): three's WebGPURenderer from the classes threedog/tsl registered (render/backend.js) @param {any} canvas */
68
+ /**
69
+ * createEngine({ renderer: 'webgpu' }): three's WebGPURenderer from the classes threedog/tsl registered (render/backend.js). No powerPreference on
70
+ * Windows: Chrome ignores it there and warns on every page load (crbug.com/369219127) @param {any} canvas
71
+ */
66
72
  function newWebGPURenderer(canvas, antialias) {
67
- return new (needTsl("'webgpu'").WebGPURenderer)({ canvas, antialias, powerPreference: 'high-performance' });
73
+ const power = navigator.userAgent.includes('Windows') ? {} : { powerPreference: 'high-performance' };
74
+ return new (needTsl("'webgpu'").WebGPURenderer)({ canvas, antialias, ...power });
68
75
  }
69
76
 
70
77
  /**
@@ -80,11 +87,17 @@ function rendererWant(r, rendererIn, fallback) {
80
87
  if (typeof rendererIn === 'string' && rendererIn !== 'webgpu') throw codedError('engine-misuse', `createEngine({ renderer }): a name is 'webgl' (the default) or 'webgpu', or pass a three.js renderer object, got ${JSON.stringify(rendererIn)}`);
81
88
  const gpu = isWebGPU(r);
82
89
  if (gpu) needTsl('yourWebGPURenderer');
83
- if (fallback !== undefined && !gpu) throw codedError('engine-misuse', "createEngine({ fallback }) only applies with renderer: 'webgpu' or your own WebGPURenderer (WebGLRenderer has nothing to fall back from)");
90
+ if (DEV && fallback !== undefined && !gpu) warnOnce(coded('engine-misuse', `createEngine({ fallback: ${JSON.stringify(fallback)} }) does nothing here: it only applies with renderer: 'webgpu' or your own WebGPURenderer (WebGLRenderer has nothing to fall back from)`));
84
91
  return { requested: gpu ? 'webgpu' : 'webgl', fallback: fallback ?? 'webgl2' };
85
92
  }
86
93
 
87
94
 
95
+ /** pixelSize decides the ratio, so an option asking for something else about it is an error that names which to keep */
96
+ function checkPixelSizeOptions(pixelSize, pixelRatio, adaptiveResolution) {
97
+ if (pixelRatio != null) throw codedError('pixel-conflict', `createEngine({ pixelRatio: ${pixelRatio}, pixelSize: ${pixelSize} }): both decide the render resolution. Keep pixelSize for art pixels of one exact size, or pixelRatio for a plain render scale`);
98
+ if (adaptiveResolution === true) throw codedError('pixel-conflict', `createEngine({ adaptiveResolution: true, pixelSize: ${pixelSize} }): adaptive resolution would change the art pixels' size. Keep pixelSize and drop adaptiveResolution`);
99
+ }
100
+
88
101
  // Dev note once when createEngine keeps the engine's placeholder lights; lights: false says the game writes its own picture
89
102
  const NO_PICTURE = 'createEngine(): the placeholder picture is on: a still white sun and hemisphere light with soft shadows, no tone curve, no environment map (see describe().render.defaults), ' +
90
103
  'gray background, ground, capsule characters and box props. Not an error, but the game has no picture yet: making the art is part of building the game. ' +
@@ -101,43 +114,43 @@ export class Engine {
101
114
  /** This engine's dev checks (createEngine({ validate })); another engine on the page does not change it @type {boolean} */
102
115
  this.validate = opts.validate !== false;
103
116
  /** @internal */ this._untrackValidate = trackValidate(opts.validate);
104
- // createEngine({ post }) read as "turn bloom on" when nothing had added a bloom. Said here, because an unknown key would only be ignored
105
- if (opts.post !== undefined) throw codedError('post-effect', 'createEngine({ post }) is gone. The engine ships no effects: add one with engine.post.add(bloom()) ' +
106
- `(@threedog/post-effects), or as a file in the plugins folder; switch it with its handle: engine.post.get('bloom').enabled = false`);
107
- // said before the unknown-option check for the same reason: a picture given here has one place to go, and the generic message does not name it
108
- if (opts.style !== undefined) throw codedError('engine-misuse', "createEngine({ style }) is gone: there is no style table. Write the picture as plain three.js in the game's picture/ code " +
109
- "(scene.background, scene.fog, renderer.toneMapping, engine.<module>.material, engine.uniforms), and the screen UI's colors and CSS with createEngine({ ui }). recipes/62-picture-code.md");
110
117
  const o = readParams('createEngine()', ENGINE_PARAMS, opts);
111
118
  /** @internal createEngine options as read (engine.catalog('core').params shows them with the schema) */ this._createParams = o;
112
- const { canvas: canvasIn, renderer: rendererName, antialias, pixelRatio, adaptiveResolution, targetFps, ui = {}, audio = {},
119
+ const { canvas: canvasIn, renderer: rendererName, antialias, pixelRatio, pixelSize, adaptiveResolution, targetFps, ui = {}, audio = {},
113
120
  fov, near, locale, strings = {}, bindings = {}, saveKey, joystick,
114
121
  headless = new URLSearchParams(location.search).has('threedog-headless'), validate,
115
122
  decoders = null, budget = null, urlState = DEV, seed, movement, threads, pauseOnBlur, batching = {}, lights, fallback } = o;
116
- this.THREE = THREE;
123
+ if (pixelSize != null) checkPixelSizeOptions(pixelSize, pixelRatio, opts.adaptiveResolution);
117
124
  // 'webgl' names the default (a WebGLRenderer the engine builds), so it reads like leaving the option out
118
125
  const rendererIn = rendererName === 'webgl' ? undefined : rendererName;
119
- // 'webgpu' is the same road as a game's own WebGPURenderer: built here, then handed on like one (start() inits it, core/startup.js)
126
+ // 'webgpu' is the same road as a game's own WebGPURenderer: built here, then handed on like one (start() inits it, core/engine/startup.js)
120
127
  const gpuWanted = rendererIn === 'webgpu';
121
128
  const canvas = canvasIn ?? (gpuWanted ? undefined : rendererIn?.domElement);
122
129
  this.movement = createMovement(movement); // character radius / height / slope / step height: the single copy shared by collision, physics and nav
123
130
  if (opts.lights !== false) warnOnce(NO_PICTURE);
124
- // a game-supplied renderer is used as is: the engine configures (pixel ratio, size, tone mapping, shadows) only a renderer it created itself
131
+ // a game-supplied renderer keeps its settings: the engine configures pixel ratio, size, tone mapping and shadows only on a renderer it created itself.
132
+ // One write on every renderer: info.autoReset = false below, because the frame stats count a whole frame, not each render call
125
133
  const owned = !rendererIn || gpuWanted;
126
134
  this._ownsRenderer = owned; // dispose() releases the WebGL context only of a renderer the engine built
127
135
  if (owned) checkCanvasUsable(canvas);
128
- // 'low' | 'high': device tier, decides default quality. A headless tool page names its tier (?threedog-tier, core/tier.js): detection would call
136
+ // 'low' | 'high': device tier, decides default quality. A headless tool page names its tier (?threedog-tier, core/scene/tier.js): detection would call
129
137
  // every headless browser low tier and drop the game's costly post from shots. An engine-built renderer needs it before it exists: MSAA defaults
130
138
  // from the tier and is the canvas's own (antialias, fixed when the context is made), so an effect-free frame skips the post chain
131
139
  const tierFirst = (headless && forcedTier()) || (owned ? tierBeforeRenderer() : null);
132
- const aa = antialias ?? (owned ? tierFirst !== 'low' : null);
140
+ // pixelSize: hard art pixels are the point, so the default is off
141
+ const authoredAA = antialias ?? (owned ? tierFirst !== 'low' && pixelSize == null : null);
142
+ // the player's choice from the last launch comes here because here is the last moment it can reach the canvas; art pixels stay as they are
143
+ const aa = (owned && pixelSize == null ? storedMsaa(saveKey) : null) ?? authoredAA;
133
144
  const r = this.renderer = gpuWanted ? newWebGPURenderer(canvas, aa) : rendererIn ?? new THREE.WebGLRenderer({ canvas, antialias: aa, powerPreference: 'high-performance' });
134
145
  /** @internal what the game asked for and what to do without WebGPU; start() fills describe().renderer from it */
135
146
  this._backendWant = rendererWant(r, rendererIn, fallback);
136
147
  watchNodePrograms(r); // WebGPU: generated code per material, for debug.view('shaderCost') (render/backend.js)
148
+ this._records = recordSweep(r); // WebGPU: meshes that left the scene free their records (render/recordSweep.js)
137
149
  if (isWebGPU(r)) dressNodeTwins(r); // WebGPU: classic materials get their patches as nodes (render/patches.js)
138
150
  nameShaderErrors(r); // compile errors name the patch and slot (render/shaderErrors.js); a game's own handler stays
139
- this.tier = tierFirst || detectTier(r);
140
- if (owned || pixelRatio != null) r.setPixelRatio(pixelRatio ?? defaultPixelRatio(devicePixelRatio || 1, this.tier));
151
+ this._deviceTier = tierFirst || detectTier(r);
152
+ /** @internal real screen pixels per art pixel, null when off (core/scene/pixelRatio.js) @type {number | null} */ this._pixelSize = null;
153
+ if (owned || pixelRatio != null) firstRatio(r, this._deviceTier, pixelRatio);
141
154
  this._autoSize = undefined; // decided once the canvas is in the page (sizeMode): true = no CSS size, the engine sizes it to the window
142
155
  const box = canvasBox(this);
143
156
  if (owned) r.setSize(box.w, box.h, !!this._autoSize);
@@ -145,19 +158,21 @@ export class Engine {
145
158
 
146
159
  this.scene = new THREE.Scene();
147
160
  /** @internal the neutral background a scene starts with: describe().render.defaults, and the reference a sky compares with @type {any} */ this.baseBackground = new THREE.Color(0x8c8c8c);
161
+ /** @internal */ this.baseBackgroundHex = this.baseBackground.getHex();
148
162
  this.scene.background = this.baseBackground;
163
+ this.stacks = new Stacks(this); // shared points: before the lights, whose shadow size reads engine.tier, and the first engine.shadows / engine.post point
149
164
  /** Placeholder lights { sun: DirectionalLight, hemi: HemisphereLight }: neutral and still; createEngine({ lights: false }) leaves them out of the scene @type {{ sun: any, hemi: any }} */
150
165
  this.lights = createDefaultLights(this, { add: lights !== false });
151
166
  // the engine's own renderer gets soft shadows by default; tone curve and environment stay three.js's defaults
152
- this.stacks = new Stacks(this); // shared points: the registry exists before the first engine.shadows / engine.post point
153
- defineShadows(this, { owned }); // engine.shadows: master switch, cascades, box, budget on the lights a game hands in (core/shadows.js)
154
- recordRender(this, { owned }); // baseline for describe().render (after the curve is written): which values the engine set
167
+ defineShadows(this, { owned }); // engine.shadows: master switch, cascades, box, budget on the lights a game hands in (render/shadows.js)
168
+ recordRender(this, { owned }); // baseline for describe().render (after the shadow defaults are written): which values the engine set
155
169
  // Dev server only. A bundled build (npm test, threedog shot, release) is one minified file, so a stack there names assets/index-x.js:1 for every value: a
156
170
  // wrong answer. Written as the literal, not DEV_SERVER: only the literal folds at build time, so the tracker leaves a release bundle altogether
157
171
  // @ts-ignore Vite's import.meta.env (undefined outside Vite)
158
172
  if (import.meta.env?.DEV) installPictureWriters(this);
159
- this.camera = new EngineCamera(fov, box.w / box.h, near, 1500); // a PerspectiveCamera that camera rigs can switch to orthographic (core/engineCamera.js)
160
- this.camera.position.set(0, 10, 20);
173
+ this._camera = new THREE.PerspectiveCamera(fov, box.w / box.h, near, 1500);
174
+ /** @internal { camera, home }: the orthographic camera a rig's projection swapped in, and the camera it stands in for (setProjection, core/scene/view.js) */ this._ortho = null;
175
+ this._camera.position.set(0, 10, 20);
161
176
  this.focus = new THREE.Vector3(); // camera focus (updated by the camera module): the view loads around it; simulation follows world.anchor
162
177
  this.ground = flatGround;
163
178
  this.player = null;
@@ -168,12 +183,13 @@ export class Engine {
168
183
  this.actor = 'player';
169
184
  /**
170
185
  * Where the engine is in its life, the one state every "may this run yet" check reads: 'constructed' (createEngine done, start() not called)
171
- * -> 'loading' (start() running: modules init, assets, the world builds; frame hooks run, fixed steps do not, so no game time passes)
186
+ * -> 'starting' (start() running: modules init; frame hooks run, fixed steps do not, so no game time passes) -> 'loading' (the same, assets and the world build)
172
187
  * -> 'ready' (the world is built: fixed steps run, engine:ready fires, the new-game state is captured) -> 'running' (start() resolved)
173
- * -> 'disposed'. @type {'constructed' | 'loading' | 'ready' | 'running' | 'disposed'}
188
+ * -> 'disposed'. @type {'constructed' | 'starting' | 'loading' | 'ready' | 'running' | 'disposed'}
174
189
  */
175
190
  this.phase = 'constructed';
176
191
  /** @internal module name -> handles its install / init passed to ctx.track (removed with the module: modules.js) */ this._modTracked = new Map();
192
+ /** @internal object -> property -> its one ctx.borrow holder (modules.js) */ this._borrowed = new WeakMap();
177
193
  /** @internal module name -> the token of its current install: ctx and async init check it (modules.js, a stale init must not act on a newcomer) */ this._modInst = new Map();
178
194
  this._abort = new AbortController();
179
195
  // attach DOM listeners to it: addEventListener(type, fn, { signal: engine.signal }); dispose cancels them together
@@ -184,85 +200,116 @@ export class Engine {
184
200
  this.uiRoot.className = 'threedog-root';
185
201
  if (r.domElement.parentElement) r.domElement.after(this.uiRoot); else document.body.appendChild(this.uiRoot);
186
202
  this.headless = headless;
187
- this.paused = headless; // while paused the real-time loop does not advance; only step() does
203
+ this.halted = headless; // while halted the real-time loop does not advance; only step() does
188
204
  this.fps = 0;
189
- this.cpuMs = 0; // main-thread ms of the last real-time frame; cpuPhases splits it (loop.js)
190
- this.cpuPhases = { fixed: 0, frame: 0, render: 0, afterRender: 0 };
191
- this.openWindows = new Set(); // ids of open windows (for describe)
205
+ /** How far the drawn frame is from the last fixed step to the next, 0-1 (real loop); 1 after step(). Holds still while frozen. For drawing fixed-step state smoothly: prev + (now - prev) * stepBlend */
206
+ this.stepBlend = 1;
207
+ /** @internal the picture check is rendering (tools/picture/check.mjs): what it changes and puts back is not the game's */ this._probing = false;
208
+ /** @internal the tools' one way in (rule R68) */ this._tools = toolDoor(this);
209
+ /** @internal */ this._cpuMs = 0; // main-thread ms of the last real-time frame; _cpuPhases splits it (loop.js); read through engine.inspect.perf() and engine.budget
210
+ /** @internal */ this._cpuPhases = { fixed: 0, frame: 0, render: 0, afterRender: 0 };
211
+ this._openWindows = new Set(); // ids of open windows (for describe)
192
212
  this.modules = new Map();
193
213
  this._modState = new Map(); // module name -> registered | initializing | running | failed | disposed (modules.js)
214
+ /** @internal module name -> what it waits for: [{ requires, module, state }], derived from _modState (modules.js) */ this._modBlocked = new Map();
215
+ /** @internal installs (engine._modInst tokens) whose critical block was already reported */ this._modFatal = new WeakSet();
194
216
  this.waterBodies = [];
195
217
  clearHooks(this);
196
218
  this._hookErrors = new Set(); // places that already reported an error (once per place, see errors.js)
197
219
  this.error = null; // gameplay error in dev/test: { where, message, cause?, docs? }; gameplay is frozen (see errors.js)
198
- this.disabledModules = new Set(); // picture / ui modules disabled after they threw
199
220
  /**
200
- * This engine's shader uniforms (uTime, uWind, uCloud, season tints...); share these objects in your own ShaderMaterial or patch @type
201
- * {import('../types/core').EngineUniforms}
221
+ * This engine's shader uniforms (uTime, uWind, uWeatherCloud, season tints...); share these objects in your own ShaderMaterial or patch @type
222
+ * {import('../../types/core').EngineUniforms}
202
223
  */
203
224
  this.uniforms = createUniforms();
204
225
  bindUniforms(r, this.uniforms); // built-in shader effects read this engine's uniforms when compiled by this renderer
205
- defineView(this); // engine.view: manual() for camera.far / fov / pixel ratio / camera pose the engine changes on its own (core/view.js)
206
- defineTerms(this); // engine.terms: the game's own cloud shadow or season tint in place of the engine's (render/terms.js)
226
+ defineView(this); // engine.autoView: manual() for camera.far / fov / pixel ratio / camera pose the engine changes on its own (core/scene/view.js)
227
+ defineTerms(this); // engine.shaderTerms: the game's own cloud shadow or season tint in place of the engine's (render/terms.js)
207
228
  this._materials = registerEngine(this); // applyEffects without an engine option uses the first live engine
208
229
 
209
- createServices(this, { canvas, validate, locale, strings, saveKey, joystick, bindings, audio, decoders, budget, seed, headless, urlState, threads, batching });
230
+ createServices(this, { canvas: r.domElement, validate, locale, strings, saveKey, joystick, bindings, audio, decoders, budget, seed, headless, urlState, threads, batching });
210
231
  this.startup = null; // startup timing report (set once start() finishes)
211
232
  this._readyAt = null; // set at ready until the first frame is drawn (loop.js firstFrame)
212
233
  this._whileCompiling = []; // @internal one-time warm-ups a module queues during loading; start() runs them while the GPU compiles
213
234
  this._prof = null; // module hook timing (profile(true) turns it on)
214
235
  this._afterTick = null; // at startup, checked once at the end of each frame for readiness
215
236
  // a game's own renderer keeps its own MSAA choice by default (used as is, like its pixel ratio)
216
- this.post = new PostFX(this, { antialias: aa ?? ownMsaa(r) });
237
+ this.post = new PostFX(this, { antialias: aa ?? ownMsaa(r), authored: authoredAA ?? ownMsaa(r) });
217
238
  this.occlusion = new Occlusion(this); // off until the game turns it on (render/occlusion.js)
218
239
  this._uiStyle = applyUITheme(this, ui); // theme variables and the game's CSS; removed on dispose
219
240
  this.ui = new UIParts(this, ui); // UI parts: every piece of screen UI is replaceable or off (ui/Parts.js)
220
241
  defineCoreParts(this);
221
242
  this.ui.get('loading')?.show({});
222
- this.adaptive = createAdaptive({ on: adaptiveResolution && !headless, target: targetFps, max: r.getPixelRatio() });
223
- this._gpu = this.adaptive.on ? new GpuTimer(timerContext(r)) : null; // GPU frame time for adaptive resolution where the browser offers the timer query
243
+ const adaptiveOn = adaptiveResolution && !headless;
244
+ this.adaptive = createAdaptive({ on: adaptiveOn, target: targetFps, max: r.getPixelRatio(), held: () => pixelSizeOn(this) });
245
+ this._gpu = adaptiveOn ? new GpuTimer(timerContext(r)) : null; // GPU frame time for adaptive resolution where the browser offers the timer query
224
246
  // follow the canvas's own CSS box, not the window: a canvas in a page section or editor panel renders at its own size.
225
247
  // The window event stays for a canvas outside the page (no box, falls back to the window) and for moves that do not resize the canvas
226
248
  addEventListener('resize', () => this._resize(), { signal: this.signal });
227
249
  this._unhandled = null; watchRejections(this);
228
250
  if (typeof ResizeObserver === 'function') {
229
- const ro = new ResizeObserver(() => this._resize());
230
- ro.observe(r.domElement);
251
+ const ro = new ResizeObserver(([entry]) => { noteDeviceBox(this, entry); this._resize(); });
252
+ try { ro.observe(r.domElement, { box: 'device-pixel-content-box' }); } catch { ro.observe(r.domElement); } // Safari rejects the box name
231
253
  this.signal.addEventListener('abort', () => ro.disconnect());
232
254
  }
233
255
  placeUI(this);
256
+ if (pixelSize != null) this.setPixelSize(pixelSize);
234
257
  this.page = new Page(this, { pauseOnBlur }); // window focus, tab visibility, mouse lock, WebGL context: handled only there
235
258
  this._born.built = performance.now(); // measure
236
259
  }
237
260
 
261
+ /**
262
+ * The camera the engine draws with. Assign a real THREE.PerspectiveCamera or THREE.OrthographicCamera to draw through it: rendering, post, picking, shadows, audio and an
263
+ * installed rig all go on with it. Its aspect follows the canvas unless the game took engine.autoView 'aspect'. Keep the first value to swap back. Any other class is refused.
264
+ * @example const own = engine.camera; engine.camera = new THREE.OrthographicCamera(-16, 16, 9, -9, 0.1, 500); engine.camera = own;
265
+ * @type {import('three').PerspectiveCamera | import('three').OrthographicCamera}
266
+ */
267
+ get camera() { return this._camera; }
268
+ set camera(cam) {
269
+ const old = this._camera;
270
+ if (cam === old) return;
271
+ checkCamera(cam);
272
+ cam.coordinateSystem = old.coordinateSystem; // the renderer's depth range: three sets it at the first draw, and a pick before that needs it too
273
+ cam.updateProjectionMatrix(); cam.updateMatrixWorld();
274
+ this._camera = cam;
275
+ movedOwned(this, new Map([[old, cam], [old.position, cam.position], [old.quaternion, cam.quaternion]]));
276
+ const c = this.renderer.domElement;
277
+ this._oAspect.drive(c.width / c.height); // the buffer, as a resize leaves it: with pixelSize it is not the canvas box
278
+ }
279
+
238
280
  get waterLevel() { return this.ground.waterLevel; }
281
+ /** The one quality value, 'low' | 'high', what everything that scales by quality reads: the device's tier, unless the player's preset says otherwise (shared point 'tier') @type {'low' | 'high'} */
282
+ get tier() { return this.stacks.has('tier') ? this.stacks.get('tier').value() : this._deviceTier; }
283
+ /** The device's tier, the base under a player's preset */
284
+ set tier(t) { this._deviceTier = t; if (this.stacks.has('tier')) this.stacks.get('tier').base = t; }
239
285
  /** True once the world is built (phase 'ready' or 'running'): fixed steps, ops and rendering run from here on @type {boolean} */
240
286
  get ready() { return this.phase === 'ready' || this.phase === 'running'; }
287
+ /** @internal start() is on its way: no game time passes */
288
+ get _inStart() { return this.phase === 'starting' || this.phase === 'loading'; }
289
+ /** @internal the modules at start() have had their init, so one installed now runs its own at once */
290
+ get _initsDone() { return this.phase !== 'constructed' && this.phase !== 'starting'; }
241
291
  /** True after dispose() @type {boolean} */
242
292
  get disposed() { return this.phase === 'disposed'; }
243
293
 
244
294
  // ---------- common ----------
245
295
  /** Get a UI string (i18n) */
246
- t(key, params) { return this.i18n.t(key, params); }
247
- /**
248
- * Fixed steps run (= engine.time.tick, the one time counter, core/time.js). Read-only; starts again from 0 on session.newGame / load / quit.
249
- * Seconds are views of it: engine.time.now('real' | 'ambient' | 'calendar' | channel)
250
- */
251
- get tick() { return this.time.tick; }
296
+ t(key, params) { return this.i18n._t(key, params); }
252
297
  /** Ray cast: the nearest hit or null, see Rays.js */
253
- raycast(origin, dir, opts) { return this.rays.cast(origin, dir, opts); }
298
+ raycast(origin, dir, opts) { return this.rays._ray(origin, dir, opts); }
254
299
  /** Cast a ray from screen coordinates (-1..1) */
255
- pick(ndcX, ndcY, opts) { return this.rays.pick(ndcX, ndcY, opts); }
300
+ pick(ndcX, ndcY, opts) { return this.rays._rayAt(ndcX, ndcY, opts); }
256
301
  /** Set up a scenario: { time, weather, pos, at, save, wait, cutscene, state }, see UrlState.js */
257
302
  applyState(params) { return this._urlState.apply(params); }
258
303
  /**
259
304
  * Scenario ready: start() has finished, the URL parameters / latest applyState are applied, and (headless) a load begun after start has settled
260
- * (tests and screenshots wait for it; core/headlessLoad.js)
305
+ * (tests and screenshots wait for it; core/engine/headlessLoad.js)
261
306
  */
262
307
  get stateApplied() { return this.ready && this._urlState.applied && headlessSettled(this); }
308
+ /** What the URL parameters or the latest applyState could not do: [{ key, value, reason }], e.g. ?weather=typo. Read it after stateApplied @type {{ key: string, value: any, reason: string }[]} */
309
+ get stateRefused() { return this._urlState.refused; }
263
310
  /**
264
311
  * Name a set of scenario parameters, then use applyState({ state: name }) or the URL ?state=name. Returns a handle: remove() forgets the name
265
- * @param {string} name @param {import('../types/core').StateParams} params @param {{ owner?: string }} [opts]
312
+ * @param {string} name @param {import('../../types/core').StateParams} params @param {{ owner?: string }} [opts]
266
313
  * @returns {{ owner?: string, remove(): void }}
267
314
  */
268
315
  defineState(name, params, opts) { return this._urlState.define(name, params, opts); }
@@ -282,10 +329,14 @@ export class Engine {
282
329
  }
283
330
  /** Once per frame: animation, camera, UI. Returns a handle { remove() } */
284
331
  onFrame(fn) { const h = ownHook(this, fn); this._frame.push(h); return { remove: () => { this._frame = this._frame.filter(f => f !== h); } }; }
332
+ /** @internal An animator's per-frame update: runs after the whole onFrame list (loop.js), so what onFrame asked of it shows the same frame. Returns a handle { remove() } */
333
+ _onAnimate(fn) { const h = ownHook(this, fn); this._animate.push(h); return { remove: () => { this._animate = this._animate.filter(f => f !== h); } }; }
334
+
285
335
  /**
286
336
  * Around the main render, after the camera update and batching: fn({ renderer, scene, camera, dt }). when 'before' (default) runs just before the
287
337
  * engine's frame render: render to your own target there (mirror, minimap, portal, picking); the render target is reset afterwards. 'after' runs
288
- * right after it (read pixels, overlays). The main frame render stays the engine's. Returns a handle { remove() }
338
+ * right after it (read pixels, overlays). The main frame render stays the engine's. A hook that throws has what it borrowed put back (target, viewport, scissor,
339
+ * autoClear, scene.overrideMaterial, camera.layers). Returns a handle { remove() }
289
340
  * @param {(ctx: { renderer: any, scene: any, camera: any, dt: number }) => void} fn @param {{ when?: 'before' | 'after' }} [opts]
290
341
  */
291
342
  onRender(fn, { when = 'before' } = {}) {
@@ -314,8 +365,3 @@ export class Engine {
314
365
  // Mix in by property descriptor (Object.assign would evaluate getters on the spot and lose them)
315
366
  for (const part of [loopMethods, holdMethods, startupMethods, groundMethods, actorMethods, moduleMethods, lifecycleMethods, skipMethods, checkMethods, resizeMethods, sceneMethods, probeMethods, lightmapMethods])
316
367
  Object.defineProperties(Engine.prototype, Object.getOwnPropertyDescriptors(part));
317
- // engine.elapsed was a second counter beside engine.time (review 0.4, B): removed. In dev a read throws with the new form instead of giving
318
- // undefined (NaN in every Math.sin(engine.elapsed) animation, silently)
319
- if (DEV) Object.defineProperty(Engine.prototype, 'elapsed', { configurable: true, get() {
320
- throw codedError('renamed-field', "engine.elapsed was removed: read engine.time.now('real') (fixed seconds, no scale) or engine.time.now('ambient') (keeps moving while frozen)");
321
- } });
@@ -19,7 +19,7 @@ class Task {
19
19
  this.source = { manifest, url, version: null, bytes: null, animations: null };
20
20
  }
21
21
  /** @param {string} p queued | download | decode | upload | build | done | failed @param {number} [progress] */
22
- phase(p, progress = 0) { this.state = p; this.progress = progress; }
22
+ phase(p, progress = 0) { this.state = p; this.progress = progress; this.at = performance.now(); } // measure: at, the last sign of life the load limit reads
23
23
  toJSON() {
24
24
  const o = { name: this.name, kind: this.kind, phase: this.state, progress: Math.round(this.progress * 100) / 100, critical: this.critical };
25
25
  if (this.error) o.error = this.error;
@@ -35,7 +35,7 @@ export class Loading {
35
35
  constructor(engine) {
36
36
  this.engine = engine; this.tasks = new Map();
37
37
  this._inits = new Set(); // init() of modules installed after start(), in flight
38
- /** How long start() waits for modules whose isReady stays false before it rejects naming them (ms) @type {number} */
38
+ /** The one limit on every wait for a load (ms): a file that gives no sign of life, a module's init or a settle that does not end fail by name after it @type {number} */
39
39
  this.timeoutMs = 120000;
40
40
  }
41
41
 
@@ -45,13 +45,40 @@ export class Loading {
45
45
  * Resolves when every module installed after start() has finished its init() (also when one failed: its state is then 'failed' in engine.moduleStates and the error went through the error tiers).
46
46
  * engine.use() returns the engine, so await this to know a late module is running.
47
47
  * @returns {Promise<void>}
48
- * @example engine.use(shop()); await engine.loading.settled(); engine.moduleStates.shop // 'running'
48
+ * @example engine.use(shop()); await engine.loading.settled(); engine.explain({ module: 'shop' }).ok // true
49
49
  */
50
50
  async settled() { while (this._inits.size) await Promise.allSettled([...this._inits]); }
51
51
 
52
+ /**
53
+ * @internal The one limit: p, or fail()'s error once lastSign() (the time of the last sign of life, null: stop watching) is older than timeoutMs. It only answers the waiter; p goes on unless fail ends it.
54
+ * @template T
55
+ * @param {Promise<T>} p
56
+ * @param {() => number | null} lastSign
57
+ * @param {() => any} fail
58
+ * @returns {Promise<T>}
59
+ */
60
+ _limit(p, lastSign, fail) {
61
+ let timer;
62
+ const over = new Promise((_, rej) => {
63
+ const look = () => {
64
+ const last = lastSign();
65
+ if (last == null || this.engine.disposed) return;
66
+ const left = this.timeoutMs - (performance.now() - last); // measure
67
+ if (left > 0) timer = setTimeout(look, Math.min(left, 2 ** 31 - 1)); // main-loop: a wall clock, because what it guards may be why no frame runs
68
+ else rej(fail());
69
+ };
70
+ look();
71
+ });
72
+ const end = () => clearTimeout(timer);
73
+ p.then(end, end);
74
+ return Promise.race([p, over]);
75
+ }
76
+
52
77
  /** Start (or restart) a task; engine-internal callers keep the returned task and move its phase */
53
78
  _begin(name, kind, opts) { const t = new Task(name, kind, opts); this.tasks.set(kind + ':' + name, t); return t; } // keyed by kind too: a module and a model may share a name
54
79
  _done(t) { t.phase('done', 1); }
80
+ /** A load ended on purpose (assets.release, dispose): it neither finished nor failed, so the record goes; the next load of that name starts its own */
81
+ _drop(t) { if (this.tasks.get(t.kind + ':' + t.name) === t) this.tasks.delete(t.kind + ':' + t.name); }
55
82
  /** Record a failure: err may carry url / status (LoadError) */
56
83
  _fail(t, err, fallback = null) {
57
84
  t.phase('failed');
@@ -101,13 +128,13 @@ export class Loading {
101
128
  if (!e.stream.ready) out.push(Object.assign(new Task('stream', 'stream', { critical: true }), { state: 'build' }));
102
129
  return out;
103
130
  }
104
- /** The item to name when asked "what are we waiting for": a critical one first, the furthest along last */
131
+ /** The item to name when asked "what are we waiting for": a critical one first, else the oldest */
105
132
  _current(pending) { return pending.find(t => t.critical) ?? pending[0] ?? null; }
106
133
 
107
134
  /**
108
135
  * The summary describe().loading shows. done: nothing pending; ok: nothing failed and no missing references;
109
136
  * blocked: a critical item failed before start() finished; waiting: one English line naming the current item.
110
- * @returns {import('../types/core').LoadingView}
137
+ * @returns {import('../../types/core').LoadingView}
111
138
  */
112
139
  view() {
113
140
  const pending = this._pending(), all = [...this.tasks.values()];
@@ -148,3 +175,5 @@ export function failureText(t) {
148
175
  const where = [err.url && err.url !== s.url ? `missing ${err.url}` : null, s.manifest ? `manifest "${s.manifest}"` : null].filter(Boolean);
149
176
  return `${j.kind} "${j.name}" <- ${s.url ?? j.name}: ${err.message}${where.length ? ` [${where.join(', ')}]` : ''}`;
150
177
  }
178
+
179
+ export const handRolled = [{ kind: 'loading', seen: 'a loading screen of its own', use: 'engine.loading: tracks what is loading, shows progress and has a view you can replace (recipe 07)', quiet: /\bengine\.loading\b/, code: /\b(createElement|innerHTML|className|classList|getElementById|querySelector|\.id)\b/, raw: /(?:createElement|innerHTML|className|classList|getElementById|querySelector|\.id\b)[^,;{}]*(?:loading|loader|load-?bar|progress-?bar)|(?:loading|loader|load-?bar|progress-?bar)[^,;{}]*(?:createElement|innerHTML|className|classList|getElementById|querySelector|\.id\b)/i }];