threedog 0.7.0 → 0.8.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 (544) hide show
  1. package/CHANGELOG.md +196 -1
  2. package/README.md +6 -9
  3. package/core/{Animator.js → assets/Animator.js} +28 -18
  4. package/core/{Assets.js → assets/Assets.js} +98 -54
  5. package/core/{Baked.js → assets/Baked.js} +4 -4
  6. package/core/assets/assetEntry.js +237 -0
  7. package/core/{assetHot.js → assets/assetHot.js} +7 -6
  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} +6 -12
  12. package/core/{namedModel.js → assets/namedModel.js} +17 -13
  13. package/core/{Audio.js → audio/Audio.js} +26 -23
  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} +10 -10
  18. package/core/{Random.js → base/Random.js} +5 -4
  19. package/core/{easing.js → base/easing.js} +1 -1
  20. package/core/{errorCodes.js → base/errorCodes.js} +98 -110
  21. package/core/{errorHints.js → base/errorHints.js} +5 -9
  22. package/core/{errors.js → base/errors.js} +6 -6
  23. package/core/{events.generated.js → base/events.generated.js} +1 -0
  24. package/core/{math.js → base/math.js} +15 -4
  25. package/core/{params.js → base/params.js} +3 -4
  26. package/core/base/util.js +32 -0
  27. package/core/{validate.js → base/validate.js} +28 -7
  28. package/core/{Engine.js → engine/Engine.js} +80 -77
  29. package/core/{Loading.js → engine/Loading.js} +4 -2
  30. package/core/{copies.js → engine/copies.js} +4 -4
  31. package/core/{headlessLoad.js → engine/headlessLoad.js} +4 -4
  32. package/core/{lifecycle.js → engine/lifecycle.js} +14 -12
  33. package/core/{loop.js → engine/loop.js} +68 -47
  34. package/core/{moduleSlots.js → engine/moduleSlots.js} +6 -6
  35. package/core/{moduleTypes.js → engine/moduleTypes.js} +13 -14
  36. package/core/{modules.js → engine/modules.js} +14 -11
  37. package/core/{page.js → engine/page.js} +36 -23
  38. package/core/{plugins.js → engine/plugins.js} +6 -9
  39. package/core/{services.js → engine/services.js} +47 -40
  40. package/core/{startup.js → engine/startup.js} +26 -24
  41. package/core/{Input.js → input/Input.js} +30 -22
  42. package/core/{inputContext.js → input/inputContext.js} +14 -5
  43. package/core/{inputPad.js → input/inputPad.js} +1 -1
  44. package/core/{inputPointer.js → input/inputPointer.js} +8 -2
  45. package/core/{inputTouch.js → input/inputTouch.js} +1 -1
  46. package/core/{Budget.js → inspect/Budget.js} +21 -20
  47. package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +30 -16
  48. package/core/{Describe.js → inspect/Describe.js} +26 -22
  49. package/core/{Inspect.js → inspect/Inspect.js} +9 -7
  50. package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
  51. package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
  52. package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
  53. package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
  54. package/core/{UrlState.js → inspect/UrlState.js} +52 -20
  55. package/core/{catalog.js → inspect/catalog.js} +3 -3
  56. package/core/{checks.js → inspect/checks.js} +7 -5
  57. package/core/{debugView.js → inspect/debugView.js} +4 -4
  58. package/core/{describeRender.js → inspect/describeRender.js} +21 -20
  59. package/core/{describeText.js → inspect/describeText.js} +11 -6
  60. package/core/inspect/geometryWatch.js +38 -0
  61. package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
  62. package/core/{pictureWriters.js → inspect/pictureWriters.js} +15 -16
  63. package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
  64. package/core/{Ops.js → ops/Ops.js} +16 -11
  65. package/core/{control.js → ops/control.js} +13 -12
  66. package/core/ops/holds.js +139 -0
  67. package/core/{opsAtomic.js → ops/opsAtomic.js} +2 -1
  68. package/core/{opsCheck.js → ops/opsCheck.js} +4 -5
  69. package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
  70. package/core/{opsRun.js → ops/opsRun.js} +7 -4
  71. package/core/{owned.js → ops/owned.js} +14 -17
  72. package/core/{sharedPoint.js → ops/sharedPoint.js} +8 -8
  73. package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
  74. package/core/{stacks.js → ops/stacks.js} +12 -14
  75. package/core/{wrap.js → ops/wrap.js} +8 -6
  76. package/core/{SaveStore.js → saves/SaveStore.js} +1 -1
  77. package/core/{Saves.js → saves/Saves.js} +58 -36
  78. package/core/{saveApply.js → saves/saveApply.js} +13 -9
  79. package/core/{saveFiles.js → saves/saveFiles.js} +17 -15
  80. package/core/{saveValues.js → saves/saveValues.js} +20 -3
  81. package/core/{saveVersions.js → saves/saveVersions.js} +4 -17
  82. package/core/{session.js → saves/session.js} +31 -17
  83. package/core/{Rays.js → scene/Rays.js} +23 -25
  84. package/core/{Views.js → scene/Views.js} +14 -6
  85. package/core/{adaptive.js → scene/adaptive.js} +15 -8
  86. package/core/{canvasBox.js → scene/canvasBox.js} +2 -3
  87. package/core/{engineCamera.js → scene/engineCamera.js} +1 -1
  88. package/core/{gameLights.js → scene/gameLights.js} +17 -7
  89. package/core/{grayMap.js → scene/grayMap.js} +8 -2
  90. package/core/{grid.js → scene/grid.js} +4 -4
  91. package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
  92. package/core/{ground.js → scene/ground.js} +9 -9
  93. package/core/{movement.js → scene/movement.js} +3 -3
  94. package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
  95. package/core/{sceneDelta.js → scene/sceneDelta.js} +2 -2
  96. package/core/{sceneMethods.js → scene/sceneMethods.js} +36 -13
  97. package/core/scene/stepPoses.js +55 -0
  98. package/core/{targeting.js → scene/targeting.js} +4 -5
  99. package/core/{thingExplain.js → scene/thingExplain.js} +6 -5
  100. package/core/{thingOps.js → scene/thingOps.js} +4 -3
  101. package/core/{things.js → scene/things.js} +18 -5
  102. package/core/{threePatches.js → scene/threePatches.js} +1 -1
  103. package/core/{view.js → scene/view.js} +17 -16
  104. package/core/{Batching.js → stream/Batching.js} +85 -27
  105. package/core/{Stream.js → stream/Stream.js} +60 -30
  106. package/core/{batchGroups.js → stream/batchGroups.js} +10 -9
  107. package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
  108. package/core/{scatter.js → stream/scatter.js} +2 -2
  109. package/core/{streamSources.js → stream/streamSources.js} +12 -7
  110. package/core/{Commits.js → threads/Commits.js} +6 -5
  111. package/core/{Jobs.js → threads/Jobs.js} +12 -10
  112. package/core/{Threads.js → threads/Threads.js} +16 -16
  113. package/core/{threadPure.js → threads/threadPure.js} +7 -5
  114. package/core/{threadServe.js → threads/threadServe.js} +3 -3
  115. package/core/{Clock.js → time/Clock.js} +17 -10
  116. package/core/{dayTime.js → time/dayTime.js} +5 -1
  117. package/core/{skip.js → time/skip.js} +18 -17
  118. package/core/{time.js → time/time.js} +18 -12
  119. package/core/{uiClock.js → time/uiClock.js} +4 -4
  120. package/docs/AI.md +22 -19
  121. package/docs/API.md +24 -23
  122. package/docs/CODEMAP.md +76 -183
  123. package/docs/COMMANDS.md +66 -58
  124. package/docs/CONVENTIONS.md +54 -14
  125. package/docs/MIGRATING-0.8.md +169 -0
  126. package/docs/THREE.md +78 -29
  127. package/docs/api/assets.md +12 -13
  128. package/docs/api/audio.md +6 -5
  129. package/docs/api/budget.md +4 -4
  130. package/docs/api/calendar.md +10 -11
  131. package/docs/api/cameraRig.md +29 -29
  132. package/docs/api/characters.md +23 -18
  133. package/docs/api/clock.md +1 -1
  134. package/docs/api/collision.md +12 -9
  135. package/docs/api/content.md +6 -6
  136. package/docs/api/dialogue.md +3 -3
  137. package/docs/api/engine.md +45 -43
  138. package/docs/api/events.md +3 -2
  139. package/docs/api/flow.md +1 -1
  140. package/docs/api/grids.md +1 -1
  141. package/docs/api/ground.md +4 -5
  142. package/docs/api/hud.md +2 -2
  143. package/docs/api/i18n.md +6 -6
  144. package/docs/api/input.md +7 -7
  145. package/docs/api/interactions.md +4 -4
  146. package/docs/api/inventory.md +9 -9
  147. package/docs/api/jobs.md +5 -5
  148. package/docs/api/level.md +7 -7
  149. package/docs/api/lightPool.md +1 -6
  150. package/docs/api/music.md +3 -3
  151. package/docs/api/nav.md +10 -10
  152. package/docs/api/openWorld.md +1 -1
  153. package/docs/api/particles.md +2 -2
  154. package/docs/api/photo.md +4 -2
  155. package/docs/api/pickups.md +2 -2
  156. package/docs/api/post.md +20 -3
  157. package/docs/api/quests.md +3 -3
  158. package/docs/api/rays.md +5 -7
  159. package/docs/api/rigid.md +27 -18
  160. package/docs/api/saves.md +8 -7
  161. package/docs/api/settings.md +9 -8
  162. package/docs/api/sky.md +8 -7
  163. package/docs/api/stream.md +7 -7
  164. package/docs/api/swarm.md +34 -0
  165. package/docs/api/terrain.md +7 -8
  166. package/docs/api/terrainDraw.md +1 -1
  167. package/docs/api/timeline.md +2 -2
  168. package/docs/api/tools.md +25 -22
  169. package/docs/api/vars.md +1 -1
  170. package/docs/api/vegetation.md +4 -3
  171. package/docs/api/vegetationDraw.md +1 -1
  172. package/docs/api/water.md +1 -1
  173. package/docs/api/weather.md +9 -9
  174. package/docs/api/weatherDraw.md +3 -3
  175. package/docs/api/world.md +5 -5
  176. package/docs/recipes/01-new-game.md +25 -40
  177. package/docs/recipes/02-npc.md +19 -20
  178. package/docs/recipes/03-items-pickups.md +27 -43
  179. package/docs/recipes/04-quests.md +3 -4
  180. package/docs/recipes/05-props-bake.md +29 -39
  181. package/docs/recipes/06-clock-events.md +27 -18
  182. package/docs/recipes/07-flow-scenes-pause.md +12 -17
  183. package/docs/recipes/08-weather-sky.md +88 -34
  184. package/docs/recipes/09-materials-lights-models.md +22 -36
  185. package/docs/recipes/10-blender-level.md +6 -7
  186. package/docs/recipes/11-vehicles.md +30 -22
  187. package/docs/recipes/12-navmesh.md +9 -8
  188. package/docs/recipes/13-animation.md +39 -17
  189. package/docs/recipes/14-custom-module.md +14 -13
  190. package/docs/recipes/15-perf.md +49 -26
  191. package/docs/recipes/16-dev-bridge.md +32 -52
  192. package/docs/recipes/18-world.md +36 -23
  193. package/docs/recipes/19-shooting-picking.md +4 -2
  194. package/docs/recipes/20-content-actions-save.md +30 -35
  195. package/docs/recipes/21-camera.md +33 -5
  196. package/docs/recipes/22-shop-gold.md +0 -4
  197. package/docs/recipes/23-ops.md +10 -10
  198. package/docs/recipes/26-ui-parts.md +22 -12
  199. package/docs/recipes/27-net.md +0 -2
  200. package/docs/recipes/28-terrain.md +117 -21
  201. package/docs/recipes/29-grid.md +2 -2
  202. package/docs/recipes/30-templates.md +55 -19
  203. package/docs/recipes/31-audio.md +5 -5
  204. package/docs/recipes/32-action-game.md +15 -6
  205. package/docs/recipes/33-stream-sources.md +2 -2
  206. package/docs/recipes/34-environment-lighting.md +67 -19
  207. package/docs/recipes/35-picture-from-reference.md +10 -17
  208. package/docs/recipes/36-ground-plants.md +105 -0
  209. package/docs/recipes/40-scene.md +7 -11
  210. package/docs/recipes/43-shader-patches-surfaces.md +20 -41
  211. package/docs/recipes/44-water-weather-hooks.md +48 -43
  212. package/docs/recipes/45-cascaded-shadows.md +39 -17
  213. package/docs/recipes/46-blender-art-route.md +7 -8
  214. package/docs/recipes/49-game-module-contract.md +5 -5
  215. package/docs/recipes/50-own-renderer.md +2 -2
  216. package/docs/recipes/52-around-the-picture.md +54 -98
  217. package/docs/recipes/53-ground-up-close.md +61 -24
  218. package/docs/recipes/55-mods-time-wrap.md +12 -16
  219. package/docs/recipes/56-webgpu-tsl.md +16 -14
  220. package/docs/recipes/57-control.md +9 -2
  221. package/docs/recipes/58-input.md +2 -2
  222. package/docs/recipes/59-depth-post-effects.md +1 -1
  223. package/docs/recipes/60-judge-the-picture.md +29 -24
  224. package/docs/recipes/62-picture-code.md +49 -17
  225. package/docs/recipes/63-third-person-start.md +17 -4
  226. package/docs/recipes/64-particles.md +1 -1
  227. package/docs/recipes/65-swarm.md +140 -0
  228. package/examples/action/.threedog/content-index.json +1 -1
  229. package/examples/action/GAMEMAP.md +2 -2
  230. package/examples/{sheepisland → perf-island}/.threedog/content-index.json +1 -1
  231. package/examples/{sheepisland → perf-island}/GAMEMAP.md +12 -11
  232. package/examples/{sheepisland → perf-island}/assets.js +1 -1
  233. package/examples/{sheepisland → perf-island}/main.js +8 -8
  234. package/examples/{sheepisland → perf-island}/models.js +1 -1
  235. package/examples/{sheepisland → perf-island}/params.js +1 -1
  236. package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
  237. package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
  238. package/examples/{sheepisland → perf-island}/views.js +1 -1
  239. package/examples/plain-picture/GAMEMAP.md +1 -0
  240. package/examples/rc2d/GAMEMAP.md +3 -2
  241. package/examples/rc2d/main.js +1 -3
  242. package/examples/styletest/.threedog/content-index.json +1 -1
  243. package/examples/styletest/GAMEMAP.md +3 -2
  244. package/examples/techniques/contact-shadows/contactShadows.js +1 -1
  245. package/examples/techniques/contact-shadows/main.js +1 -1
  246. package/examples/techniques/interior-light/main.js +1 -1
  247. package/examples/techniques/modular-building/README.md +7 -6
  248. package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
  249. package/examples/techniques/procedural-animation/README.md +1 -1
  250. package/examples/webgpu-tsl/GAMEMAP.md +1 -0
  251. package/examples/world/.threedog/content-index.json +1 -1
  252. package/examples/world/GAMEMAP.md +4 -3
  253. package/examples/world/picture/sky.js +1 -1
  254. package/index.d.ts +8 -7
  255. package/index.js +31 -31
  256. package/llms.txt +9 -13
  257. package/modules/ambience/Ambience.js +11 -8
  258. package/modules/calendar/Calendar.js +19 -19
  259. package/modules/calendar/index.js +13 -13
  260. package/modules/calendar/schedule.js +11 -6
  261. package/modules/calendar/seasons.js +7 -7
  262. package/modules/camera/FirstPersonCamera.js +2 -2
  263. package/modules/camera/FixedCamera.js +14 -15
  264. package/modules/camera/FollowCamera.js +4 -4
  265. package/modules/camera/RtsCamera.js +11 -11
  266. package/modules/camera/common.js +48 -24
  267. package/modules/camera/contract.js +1 -0
  268. package/modules/camera/projection.js +2 -2
  269. package/modules/characters/Character.js +33 -30
  270. package/modules/characters/NPC.js +27 -19
  271. package/modules/characters/assetModel.js +14 -10
  272. package/modules/characters/astar.js +7 -5
  273. package/modules/characters/behaviors.js +4 -5
  274. package/modules/characters/contract.js +2 -2
  275. package/modules/characters/index.js +168 -214
  276. package/modules/characters/moveHelpers.js +14 -3
  277. package/modules/characters/movers/common.js +16 -14
  278. package/modules/characters/movers/manual.js +1 -1
  279. package/modules/characters/movers/rapier.js +7 -6
  280. package/modules/characters/movers/simple.js +3 -3
  281. package/modules/characters/movers/support.js +8 -8
  282. package/modules/characters/npcAvoid.js +4 -4
  283. package/modules/characters/npcSim.js +23 -17
  284. package/modules/characters/npcView.js +6 -5
  285. package/modules/characters/pathAsync.js +12 -10
  286. package/modules/characters/pathWorker.js +1 -1
  287. package/modules/characters/player.js +108 -0
  288. package/modules/characters/playerStrings.js +2 -2
  289. package/modules/characters/proceduralRig.js +2 -2
  290. package/modules/characters/useModel.js +3 -3
  291. package/modules/characters/walkTo.js +11 -17
  292. package/modules/collision/Collision.js +26 -20
  293. package/modules/collision/contract.js +15 -0
  294. package/modules/content/explain.js +1 -2
  295. package/modules/content/fields.js +24 -3
  296. package/modules/content/ids.js +2 -2
  297. package/modules/content/index.js +61 -99
  298. package/modules/content/loader.js +14 -17
  299. package/modules/content/markers.js +25 -0
  300. package/modules/content/models.js +10 -7
  301. package/modules/content/packs.js +3 -3
  302. package/modules/content/parts.js +2 -2
  303. package/modules/content/places.js +35 -0
  304. package/modules/content/props.js +17 -14
  305. package/modules/content/rules.js +25 -21
  306. package/modules/content/stages.js +7 -7
  307. package/modules/content/templates.js +20 -20
  308. package/modules/content/words.js +34 -0
  309. package/modules/debug/DebugPanel.js +10 -43
  310. package/modules/flow/contract.js +1 -1
  311. package/modules/flow/index.js +11 -7
  312. package/modules/gameplay/Container.js +12 -11
  313. package/modules/gameplay/Containers.js +14 -5
  314. package/modules/gameplay/Dialogue.js +13 -11
  315. package/modules/gameplay/Interactions.js +37 -24
  316. package/modules/gameplay/Inventory.js +8 -9
  317. package/modules/gameplay/Quests.js +16 -9
  318. package/modules/gameplay/boxOps.js +1 -1
  319. package/modules/gameplay/dialogueBubbles.js +3 -4
  320. package/modules/gameplay/inventoryOps.js +0 -1
  321. package/modules/gameplay/pickups.js +22 -23
  322. package/modules/gameplay/questSave.js +3 -3
  323. package/modules/grid/Grid.js +1 -1
  324. package/modules/grid/Layer.js +4 -4
  325. package/modules/grid/index.js +7 -8
  326. package/modules/grid/preview.js +7 -7
  327. package/modules/grid/tiles.js +6 -6
  328. package/modules/hlod/index.js +37 -55
  329. package/modules/hud/index.js +17 -11
  330. package/modules/hud/parts.js +4 -4
  331. package/modules/level/contract.js +16 -0
  332. package/modules/level/heightfield.js +12 -10
  333. package/modules/level/index.js +47 -152
  334. package/modules/level/load.js +79 -0
  335. package/modules/level/meshes.js +65 -0
  336. package/modules/level/nodes.js +6 -7
  337. package/modules/lights/index.js +28 -181
  338. package/modules/lights/slots.js +93 -0
  339. package/modules/lights/sources.js +88 -0
  340. package/modules/music/Music.js +30 -26
  341. package/modules/music/rules.js +1 -1
  342. package/modules/nav/contract.js +14 -0
  343. package/modules/nav/index.js +11 -10
  344. package/modules/net/Client.js +7 -7
  345. package/modules/net/Host.js +7 -7
  346. package/modules/net/Net.js +1 -1
  347. package/modules/net/index.js +5 -4
  348. package/modules/net/sync.js +2 -2
  349. package/modules/net/transports.js +2 -2
  350. package/modules/particles/Particles.js +11 -8
  351. package/modules/particles/effect.js +7 -5
  352. package/modules/particles/shaders.js +2 -1
  353. package/modules/photo/Photo.js +15 -17
  354. package/modules/rigid/RigidBodies.js +66 -43
  355. package/modules/rigid/Vehicles.js +2 -3
  356. package/modules/rigid/ragdoll.js +287 -0
  357. package/modules/rigid/ragdollBones.js +159 -0
  358. package/modules/rigid/sync.js +6 -6
  359. package/modules/settings/Settings.js +108 -39
  360. package/modules/settings/apply.js +6 -6
  361. package/modules/settings/sections.js +16 -14
  362. package/modules/settings/view.js +3 -3
  363. package/modules/sky/Sky.js +29 -22
  364. package/modules/sky/clouds.js +7 -7
  365. package/modules/sky/dome.js +33 -20
  366. package/modules/sky/domeLayers.js +9 -9
  367. package/modules/sky/environment.js +6 -6
  368. package/modules/sky/frame.js +19 -10
  369. package/modules/sky/season.js +7 -1
  370. package/modules/sky/shader.js +24 -25
  371. package/modules/sky/skyModule.js +14 -27
  372. package/modules/sky/tint.js +1 -1
  373. package/modules/swarm/Swarm.js +346 -0
  374. package/modules/swarm/draw.js +68 -0
  375. package/modules/swarm/grid.js +63 -0
  376. package/modules/terrain/ChunkManager.js +70 -52
  377. package/modules/terrain/chunkQueries.js +7 -24
  378. package/modules/terrain/chunkWorker.js +1 -1
  379. package/modules/terrain/draw.js +14 -11
  380. package/modules/terrain/index.js +28 -34
  381. package/modules/terrain/terrainColorMap.js +6 -3
  382. package/modules/terrain/terrainDefaults.js +2 -1
  383. package/modules/terrain/terrainEdit.js +32 -27
  384. package/modules/terrain/terrainGen.js +17 -12
  385. package/modules/terrain/terrainIsland.js +2 -2
  386. package/modules/terrain/terrainMesh.js +7 -6
  387. package/modules/terrain/terrainShape.js +8 -10
  388. package/modules/terrain/terrainShapeMain.js +3 -3
  389. package/modules/timeline/Timeline.js +27 -19
  390. package/modules/timeline/Tween.js +6 -6
  391. package/modules/timeline/shots.js +5 -7
  392. package/modules/triggers/index.js +9 -9
  393. package/modules/vegetation/Vegetation.js +30 -23
  394. package/modules/vegetation/densityMap.js +4 -7
  395. package/modules/vegetation/draw.js +23 -18
  396. package/modules/vegetation/groundChunks.js +11 -31
  397. package/modules/vegetation/index.js +8 -6
  398. package/modules/vegetation/modelGeometry.js +3 -6
  399. package/modules/vegetation/nearFade.js +1 -1
  400. package/modules/water/Water.js +16 -16
  401. package/modules/water/surface.js +3 -3
  402. package/modules/weather/Weather.js +41 -30
  403. package/modules/weather/particles.js +8 -8
  404. package/modules/weather/weatherDraw.js +22 -18
  405. package/modules/world/World.js +8 -8
  406. package/modules/world/explain.js +1 -1
  407. package/modules/world/index.js +18 -12
  408. package/modules/world/persist.js +73 -25
  409. package/modules/world/pos.js +4 -4
  410. package/modules/world/records.js +28 -8
  411. package/modules/world/sim.js +4 -4
  412. package/modules/world/state.js +12 -5
  413. package/modules/world/thingSource.js +4 -2
  414. package/modules/world/views.js +11 -9
  415. package/package.json +42 -7
  416. package/presets.js +1 -3
  417. package/render/PostFX.js +39 -27
  418. package/render/backend.js +26 -32
  419. package/render/cascades.js +17 -12
  420. package/render/cascades.tsl.js +5 -8
  421. package/render/daylight.js +20 -3
  422. package/render/detail.js +8 -7
  423. package/render/effects.js +28 -25
  424. package/render/fuse.js +3 -3
  425. package/render/fx/cloudShadow.tsl.js +3 -3
  426. package/render/fx/detail.tsl.js +1 -1
  427. package/render/fx/index.js +5 -10
  428. package/render/fx/library.tsl.js +11 -0
  429. package/render/fx/lighting.tsl.js +2 -1
  430. package/render/fx/nodeErrors.tsl.js +2 -2
  431. package/render/fx/objectOrigin.tsl.js +1 -2
  432. package/render/fx/patchNodes.tsl.js +5 -15
  433. package/render/fx/postWebGPU.tsl.js +27 -23
  434. package/render/fx/sky.tsl.js +15 -17
  435. package/render/fx/uniforms.tsl.js +4 -4
  436. package/render/fx/wind.tsl.js +1 -1
  437. package/render/fxNumbers.js +3 -0
  438. package/render/layers.js +1 -1
  439. package/render/lighting.js +5 -3
  440. package/render/lightmap.js +20 -20
  441. package/render/lights.js +6 -6
  442. package/render/lit.js +24 -0
  443. package/render/materials.js +8 -7
  444. package/render/mergeCommon.js +22 -0
  445. package/render/modeling.js +2 -2
  446. package/render/occlusion.js +20 -4
  447. package/render/ownFrame.js +4 -4
  448. package/render/patches.js +13 -13
  449. package/render/postWebGL.js +12 -10
  450. package/render/probes.js +16 -19
  451. package/render/recordSweep.js +117 -0
  452. package/render/shaderErrors.js +10 -9
  453. package/render/shadowCache.tsl.js +107 -0
  454. package/render/shadowTypes.js +9 -0
  455. package/{core → render}/shadows.js +57 -11
  456. package/render/slots.js +7 -7
  457. package/render/terms.js +22 -24
  458. package/render/uniformDecl.js +1 -1
  459. package/types/core.d.ts +200 -153
  460. package/types/gameplay.d.ts +163 -91
  461. package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
  462. package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
  463. package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
  464. package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +7 -15
  465. package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
  466. package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
  467. package/types/generated/core/{Input.d.ts → input/Input.d.ts} +12 -8
  468. package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
  469. package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +2 -2
  470. package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +4 -3
  471. package/types/generated/core/{control.d.ts → ops/control.d.ts} +4 -10
  472. package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +37 -13
  473. package/types/generated/core/{session.d.ts → saves/session.d.ts} +2 -1
  474. package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
  475. package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +1 -1
  476. package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
  477. package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +18 -16
  478. package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
  479. package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
  480. package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
  481. package/types/generated/modules/calendar/Calendar.d.ts +10 -11
  482. package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
  483. package/types/generated/modules/grid/Layer.d.ts +1 -1
  484. package/types/generated/modules/grid/index.d.ts +3 -3
  485. package/types/generated/modules/music/Music.d.ts +7 -5
  486. package/types/generated/modules/particles/Particles.d.ts +1 -1
  487. package/types/generated/modules/sky/Sky.d.ts +21 -10
  488. package/types/generated/modules/swarm/Swarm.d.ts +80 -0
  489. package/types/generated/modules/timeline/Timeline.d.ts +2 -1
  490. package/types/generated/modules/water/Water.d.ts +1 -0
  491. package/types/generated/modules/weather/Weather.d.ts +16 -12
  492. package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
  493. package/types/generated/modules/world/World.d.ts +5 -3
  494. package/types/generated/render/PostFX.d.ts +17 -11
  495. package/types/generated/render/materials.d.ts +1 -0
  496. package/types/generated/render/occlusion.d.ts +9 -0
  497. package/types/generated/render/patches.d.ts +1 -0
  498. package/types/generated/ui/Focus.d.ts +1 -0
  499. package/types/generated/ui/UI.d.ts +1 -0
  500. package/types/nav.d.ts +11 -11
  501. package/types/physics.d.ts +99 -70
  502. package/types/tsl.d.ts +37 -4
  503. package/types/world.d.ts +38 -71
  504. package/ui/Focus.js +10 -9
  505. package/ui/Parts.js +4 -3
  506. package/ui/UI.js +7 -7
  507. package/ui/defaults.js +3 -2
  508. package/ui/theme.js +5 -3
  509. package/core/assetEntry.js +0 -109
  510. package/core/holds.js +0 -134
  511. package/core/shadowTypes.js +0 -16
  512. package/core/util.js +0 -17
  513. package/docs/MIGRATING-0.3.md +0 -248
  514. package/docs/MIGRATING-0.4.md +0 -320
  515. package/docs/MIGRATING-0.5.md +0 -68
  516. package/docs/MIGRATING-0.6.md +0 -126
  517. package/docs/PERF.md +0 -245
  518. package/docs/recipes/36-sky-ground-plants.md +0 -158
  519. package/docs/recipes/37-terrain-hooks.md +0 -115
  520. package/docs/recipes/38-environment-hooks.md +0 -67
  521. package/docs/recipes/42-terrain-shape.md +0 -64
  522. package/docs/recipes/47-island-snow-backdrop.md +0 -43
  523. package/docs/recipes/54-three-idioms.md +0 -88
  524. package/examples/plain-picture/FINDINGS.md +0 -53
  525. /package/core/{Vars.js → base/Vars.js} +0 -0
  526. /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
  527. /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
  528. /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
  529. /package/core/{actor.js → ops/actor.js} +0 -0
  530. /package/core/{opsFail.js → ops/opsFail.js} +0 -0
  531. /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
  532. /package/core/{saveIds.js → saves/saveIds.js} +0 -0
  533. /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
  534. /package/core/{tier.js → scene/tier.js} +0 -0
  535. /package/core/{cells.js → stream/cells.js} +0 -0
  536. /package/core/{streamCells.js → stream/streamCells.js} +0 -0
  537. /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
  538. /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
  539. /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
  540. /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
  541. /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
  542. /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
  543. /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
  544. /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
@@ -4,7 +4,7 @@
4
4
  // 3. Cache and reuse: one file downloads once; models return independent copies (geometry and materials shared), so you can place many.
5
5
  // 4. Release: models count usage per copy; release(name) frees only when the last copy is removed, trim() frees every model with no copy in use (see their docs
6
6
  // below).
7
- // 5. Compression: Draco / Meshopt models and .ktx2 textures load as-is; the decoder downloads on first use (npm run assets produces compressed files in public/optimized/).
7
+ // 5. Compression: Draco / Meshopt models and .ktx2 textures load as-is; the decoder downloads on first use (npm run assets -- optimize produces compressed files in public/optimized/).
8
8
  // 6. Made in code: a model / texture / sound may be a function in the manifest instead of a file, used by name exactly like a file (content, model(),
9
9
  // pickups, vegetation, audio.sounds). Models are built on demand and cached automatically (baked file -> dev cache -> build, the internal cached()).
10
10
  // 7. Observable: every load is a task in engine.loading. A registered file that fails falls back (gray placeholder / silence / the entry's fallback)
@@ -24,20 +24,21 @@
24
24
  // engine.assets.manifest({ name: 'forest', base: '/packs/forest/', models: { oak: 'oak.glb' } }); // -> /packs/forest/oak.glb
25
25
  // await engine.assets.preload(p => console.log(p)); // p: 0-1 (code-generated models are built ahead only if marked preload)
26
26
  // const house = await engine.assets.model('house'); // get by name
27
- import { reportGltf, reportText } from './assetReport.js';
27
+ import { reportGltf } from './assetReport.js';
28
28
  import * as THREE from 'three';
29
29
  import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
30
30
  import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
31
31
  import { clone as skeletonClone } from 'three/addons/utils/SkeletonUtils.js';
32
- import { warnMissing, warnOnce, fmt, DEV } from './validate.js';
33
- import { codedError, coded } from './errorHints.js';
32
+ import { warnMissing, warnOnce, fmt, DEV } from '../base/validate.js';
33
+ import { codedError, coded } from '../base/errorHints.js';
34
34
  import { Animator } from './Animator.js';
35
- import { fetchEntry, freeEntry, preloadEntries, shadowDefaults } from './assetEntry.js';
35
+ import { fetchEntry, freeEntry, retireEntry, dropCopy, disposeEntries, preloadEntries, shadowDefaults, longSound } from './assetEntry.js';
36
36
  import { registerManifest, paramValues } from './assetManifest.js';
37
37
  import { setParams } from './assetHot.js';
38
- import { schemaInfo } from './params.js';
39
- import { loadGrid } from './gridLoad.js';
40
- import { memory } from '../render/backend.js';
38
+ import { wrapLod } from './assetLod.js';
39
+ import { schemaInfo } from '../base/params.js';
40
+ import { loadGrid } from '../scene/gridLoad.js';
41
+ import { memory } from '../../render/backend.js';
41
42
 
42
43
  const STRINGS = {
43
44
  textureFailed: "{where}: texture '{name}' did not load ({msg}); {instead}. Register it (engine.assets.manifest({ textures: { name: 'file.png' } })) or check its URL",
@@ -51,19 +52,22 @@ const srcHash = s => { let h = 0; for (let i = 0; i < s.length; i++) h = (Math.i
51
52
  export class Assets {
52
53
  constructor(engine) {
53
54
  this.engine = engine;
54
- this.entries = new Map(); // name -> { type, url, opts, promise, value }
55
+ this.entries = new Map(); // name -> { type, url, opts, promise, value, load, users } (who owns the data: top of assetEntry.js)
55
56
  this.gltf = new GLTFLoader();
56
57
  this.gltf.setMeshoptDecoder(MeshoptDecoder);
57
58
  this.draco = null; // DRACOLoader / KTX2Loader:created on the first compressed data
58
59
  this.ktx2 = null;
59
60
  this.tex = new THREE.TextureLoader();
60
61
  this.shared = new WeakSet(); // geometry and materials shared by model copies (engine.remove does not dispose them)
61
- this._instances = new WeakMap(); // model copy root -> asset entry (counts usage)
62
+ this._instances = new WeakMap(); // model copy root -> { e: the entry it was asked for by, load: the load that owns its data }
63
+ this._retired = new Set(); // old loads no entry points at, kept for the copies or geometry still using them
64
+ this._disposed = false;
62
65
  this._animators = new WeakMap(); // model root -> Animator from animate(): engine.remove disposes it with the model
63
66
  this.cacheMinMs = 20; // builds faster than this are not cached (reading the file would be slower)
64
67
  /**
65
68
  * Named colors for what is made in code: a generator written with `function` reads this.palette. Plain data, read or replace it freely:
66
- * it is part of the cache key, so a model or texture asked for after a write is built from the new colors. Copies already placed keep theirs.
69
+ * it is part of the cache key, so a model or texture asked for after a write is built from the new colors. Copies already placed keep theirs,
70
+ * and a model's old build is freed with its last copy.
67
71
  * @example engine.assets.palette = { leaf: 0xd98a3a, bark: 0x6b4a30 };
68
72
  * @type {Record<string, any>}
69
73
  */
@@ -74,18 +78,18 @@ export class Assets {
74
78
  /**
75
79
  * Register an asset manifest or asset pack (may be called repeatedly; a later entry with the same name replaces the earlier one). A model may be a generator
76
80
  * function or { build, params, preload, cache } (cache: false = never stored in the dev cache, recipes/05-props-bake.md §2a). params is a schema in the
77
- * core/params.js format ({ height: { type: 'number', min: 1, max: 6, default: 3 }, color: { type: 'color', default: 0x557733 } }): the generator is
81
+ * core/base/params.js format ({ height: { type: 'number', min: 1, max: 6, default: 3 }, color: { type: 'color', default: 0x557733 } }): the generator is
78
82
  * then called with one object (defaults, then dev panel values, then a call's own `['tree', { height: 4 }]`), and the dev panel shows the fields.
79
83
  * Per entry: critical: true = start() stops if it fails (otherwise it falls back and the game continues); fallback: 'otherName' replaces the gray
80
84
  * placeholder.
81
85
  * name labels the manifest in engine.loading (default 'manifest#1', '#2'...), so a failure says which list it came from.
82
- * base (a pack's folder: '/packs/forest/', a CDN URL, or new URL('./files/', import.meta.url)) resolves the relative paths of this manifest; full URLs stay
83
- * as written, and '/x' is the game's public/ folder under the build's base (BASE_URL in core/validate.js: '/' unless built with --base).
86
+ * base (a pack's folder: '/packs/forest/', a CDN URL, or new URL('../files', import.meta.url)) resolves the relative paths of this manifest; full URLs stay
87
+ * as written, and '/x' is the game's public/ folder under the build's base (BASE_URL in core/base/validate.js: '/' unless built with --base).
84
88
  * @example engine.assets.manifest({ name: 'level-1', models: { hero: { url: '/models/hero.glb', critical: true }, bush: { url: '/models/bush.glb', fallback:
85
89
  * 'rock' } } });
86
90
  * @example import forest from 'my-forest-assets'; engine.assets.manifest(forest); // { name: 'forest', base, models: { oak: 'oak.glb' } }
87
- * @example import packs from './assets.js'; engine.assets.manifest(packs); // a list: the game's assets.js, which `npm run check` reads too
88
- * @param {import('../types/core').AssetManifest | import('../types/core').AssetManifest[]} [pack]
91
+ * @example import packs from '../assets.js'; engine.assets.manifest(packs); // a list: the game's assets.js, which `npm run check` reads too
92
+ * @param {import('../../types/core').AssetManifest | import('../../types/core').AssetManifest[]} [pack]
89
93
  */
90
94
  manifest(pack = {}) { return registerManifest(this, pack); }
91
95
 
@@ -134,7 +138,16 @@ export class Assets {
134
138
  /** @internal A generated model or texture built from a palette that has since been written */
135
139
  _stale(e) { return !!e.promise && !!e.opts.build && e.type !== 'sound' && e.palette !== this._paletteKey; }
136
140
  /** @internal Load an entry as a task in engine.loading (assetEntry.js) */
137
- _fetch(e) { return fetchEntry(this, e); }
141
+ _fetch(e) { return this._with(e, v => v); }
142
+ /**
143
+ * @internal Run use(value, load) on an entry's live data, in the same tick it is checked. Why the loop: code resumed by an await runs after other
144
+ * continuations, and one of them may have released the entry since the load finished; handing out that value is a freed model
145
+ */
146
+ async _with(e, use) {
147
+ for (;;) { const v = await fetchEntry(this, e); if (v === e.load?.value) return use(v, e.load); }
148
+ }
149
+ /** @internal The entry moves on from its current load (assetEntry.js) */
150
+ _retire(e) { retireEntry(this, e); }
138
151
 
139
152
  /**
140
153
  * Preload manifest assets (all by default; onlyMarked=true loads only those marked preload). Code-generated models and fonts are loaded ahead only if marked
@@ -164,8 +177,18 @@ export class Assets {
164
177
 
165
178
  /** Get a model copy (name or path); skinned characters clone correctly. static: true registers it with engine.rays (builds ray acceleration) */
166
179
  async model(nameOrUrl, opts = {}) {
167
- const e = this._resolve(nameOrUrl, 'model'), gltf = await this._fetch(e);
168
- return this._copy(e, gltf, opts);
180
+ const e = this._resolve(nameOrUrl, 'model');
181
+ return this._with(e, () => this._copy(e, opts));
182
+ }
183
+ /**
184
+ * A model copy as a plain THREE.LOD: the full model near, the levels of `threedog assets optimize --lod` far away (assetLod.js). Off unless called: model() never
185
+ * downloads a level. Default distances follow the model's size. Rays, collision and saves keep using the full model; a LOD object is never batched.
186
+ * @example const tower = await engine.assets.lod('tower', { distances: [40, 120] }); engine.add(tower); tower.levels[1].object;
187
+ * @experimental
188
+ */
189
+ async lod(nameOrUrl, opts = {}) {
190
+ const { distances, hysteresis, ...copy } = opts;
191
+ return wrapLod(this, nameOrUrl, await this.model(nameOrUrl, copy), { distances, hysteresis });
169
192
  }
170
193
  /**
171
194
  * A model copy right now if that model has already loaded, else null (never starts a load, never waits). For code that rebuilds often,
@@ -174,43 +197,46 @@ export class Assets {
174
197
  */
175
198
  modelNow(nameOrUrl, opts = {}) {
176
199
  const e = this.entries.get(nameOrUrl);
177
- if (e?.type === 'model' && e.value && !this._stale(e)) return this._copy(e, e.value, opts);
200
+ if (e?.type === 'model' && e.load?.value && !this._stale(e)) return this._copy(e, opts);
178
201
  // Why warn: generated models also need one load() first (dev reads the baked-cache GLB, release reads the baked file), so before any await model() this is null;
179
202
  // in one playtest world.present only called modelNow, the model never showed up and nothing said why. Already loading (promise present) = no warning: that is a normal "not ready yet"
180
203
  if (DEV && e?.type === 'model' && !e.promise) warnOnce(coded('asset-not-loaded', fmt(STRINGS.notLoaded, { name: nameOrUrl })));
181
204
  return null;
182
205
  }
183
- /** @internal one counted copy of a loaded model */
184
- _copy(e, gltf, { castShadow, receiveShadow, static: isStatic = false } = {}) {
185
- const root = skeletonClone(gltf.scene);
186
- e.users = (e.users || 0) + 1; e.releasePending = false; this._instances.set(root, e);
206
+ /** @internal one copy of a loaded model, counted on the load that owns its data, which for a name that fell back belongs to the other entry */
207
+ _copy(e, { castShadow, receiveShadow, static: isStatic = false } = {}) {
208
+ const load = e.load, owner = load.owner, gltf = load.value, root = skeletonClone(gltf.scene);
209
+ load.users++; e.users = (e.users || 0) + 1;
210
+ if (owner !== e) owner.users = (owner.users || 0) + 1;
211
+ e.releasePending = owner.releasePending = false;
212
+ this._instances.set(root, { e, load });
187
213
  // the call, then the manifest entry; else a generator's own flags; else cast + receive (shadowDefaults, the same rule content props use)
188
214
  shadowDefaults(root, { castShadow: castShadow ?? e.opts.castShadow, receiveShadow: receiveShadow ?? e.opts.receiveShadow });
189
- root.userData.animations = gltf.animations;
215
+ root.animations = gltf.animations; // three's own place: .clone() keeps it as clips, where userData goes through JSON and the clips would come back broken
216
+ if (e.named) root.userData.modelName = e.name; // which named model this is; .clone() carries it, the _instances map does not (content capture reads it)
190
217
  if (isStatic) this.engine.rays.addStatic(root);
191
218
  return root;
192
219
  }
193
220
  /**
194
221
  * Import report of a loaded model: materials, textures with their colorSpace, normal maps, clips, nodes, template / id nodes and col_ colliders,
195
222
  * with issues for what the file has but the scene lost (normal map, material replaced by an engine one, clip not loaded, clip mapping that names
196
- * no clip) and for wrong color spaces. Pass a name (the loaded template) or a copy from model() (what the game shows). Text: assets.reportText(name)
223
+ * no clip) and for wrong color spaces. Pass a name (the loaded template) or a copy from model() (what the game shows).
197
224
  * @example console.table(engine.assets.report('hero').issues);
198
225
  * @param {string | any} nameOrRoot
199
226
  */
200
227
  report(nameOrRoot) {
201
- const root = typeof nameOrRoot === 'string' ? null : nameOrRoot, e = root ? this._instances.get(root) : this.entries.get(nameOrRoot);
202
- const gltf = e?.value;
228
+ const root = typeof nameOrRoot === 'string' ? null : nameOrRoot, copy = root && this._instances.get(root);
229
+ const e = root ? copy?.e : this.entries.get(nameOrRoot), gltf = (root ? copy?.load : e?.load)?.value;
203
230
  if (!gltf?.scene) throw codedError('asset-misuse', `assets.report: ${root ? 'that object is not a model copy from assets.model()' : `model "${nameOrRoot}" is not loaded yet (await engine.assets.model(...) first)`}`);
204
231
  return reportGltf(gltf, e, root ?? gltf.scene, this.engine.renderer);
205
232
  }
206
- /** assets.report as text for the console / describe */
207
- reportText(nameOrRoot) { return reportText(this.report(nameOrRoot)); }
208
233
  /** Get the geometry of the first mesh in a model (for vegetation and bulk placement) */
209
234
  async geometry(nameOrUrl) {
210
- const e = this._resolve(nameOrUrl, 'model'), gltf = await this._fetch(e);
211
- e.pinned = true; // the geometry was handed out and we cannot know who still uses it: trim does not free it
212
- let g = null; gltf.scene.traverse(o => { if (!g && o.isMesh) g = o.geometry; });
213
- return g;
235
+ return this._with(this._resolve(nameOrUrl, 'model'), (gltf, load) => {
236
+ load.pinned = true; // the geometry was handed out and we cannot know who still uses it: trim does not free it
237
+ let g = null; gltf.scene.traverse(o => { if (!g && o.isMesh) g = o.geometry; });
238
+ return g;
239
+ });
214
240
  }
215
241
  /**
216
242
  * Get a texture (name or path; .ktx2 works too). Color textures default to sRGB; pass { color: false } for normal/roughness maps.
@@ -225,7 +251,7 @@ export class Assets {
225
251
  if (!diff.length) return this._fetch(base);
226
252
  const key = nameOrUrl + '#' + JSON.stringify(Object.fromEntries(diff.sort().map(k => [k, opts[k]])));
227
253
  let v = this.entries.get(key);
228
- if (!v) this.entries.set(key, v = { type: 'texture', url: base.url, opts: { ...base.opts, ...opts }, promise: null, variantOf: nameOrUrl });
254
+ if (v?.url !== base.url) this.entries.set(key, v = { type: 'texture', url: base.url, opts: { ...base.opts, ...opts }, promise: null, variantOf: nameOrUrl, named: base.named, manifest: base.manifest }); // named: it falls back like its base
229
255
  return this._fetch(v);
230
256
  }
231
257
 
@@ -244,7 +270,7 @@ export class Assets {
244
270
  */
245
271
  useTexture(nameOrUrl, use, { where = 'assets.useTexture', instead = 'the stand-in stays', opts } = {}) {
246
272
  return this.texture(nameOrUrl, opts).then(t => { use(t); return true; },
247
- err => { warnOnce(coded('load-failed', fmt(STRINGS.textureFailed, { where, name: nameOrUrl, msg: err?.message ?? String(err), instead }))); return false; });
273
+ err => { warnOnce(coded('asset-load', fmt(STRINGS.textureFailed, { where, name: nameOrUrl, msg: err?.message ?? String(err), instead }))); return false; });
248
274
  }
249
275
 
250
276
  /**
@@ -259,38 +285,51 @@ export class Assets {
259
285
  gridFromImage(nameOrUrl, opts = {}) { return loadGrid(this.entries.get(nameOrUrl)?.url ?? nameOrUrl, opts); }
260
286
 
261
287
  /**
262
- * Release an asset and return its GPU memory (reloaded on next use). A texture is released together with all its opts variants.
263
- * A model with copies still in the scene is not released yet; it is freed when the last copy is engine.remove'd (copies in use are never broken)
288
+ * Release an asset and return its memory (reloaded on next use). A texture is released together with all its opts variants.
289
+ * A sound (name or path) plays on where it is playing; its memory goes when it ends.
290
+ * A model with copies still in the scene is not released yet; it is freed when the last copy is engine.remove'd (copies in use are never broken).
291
+ * A load still running ends here and its result is thrown away; code awaiting that load is a use, so it gets a fresh load, never the freed data.
292
+ * A name that fell back has no data of its own: release the name it fell back to (describe().assets says what still holds it).
264
293
  */
265
294
  release(name) {
266
- for (const [k, v] of this.entries) if (v.variantOf === name) { this.release(k); this.entries.delete(k); }
267
- const e = this.entries.get(name); if (e) freeEntry(e);
295
+ for (const [k, v] of this.entries) if (v.variantOf === name) {
296
+ const waited = v.load && !v.load.settled; // the fresh load of whoever waits must stay in the table, where the next release can reach it
297
+ this.release(k);
298
+ if (!waited) this.entries.delete(k);
299
+ }
300
+ const e = this.entries.get(name); if (e) freeEntry(this, e);
268
301
  }
269
- /** Release every model with no copy in use (call after a level change; level calls it). Returns the names released */
302
+ /** Release every model with no copy in use and every long decoded sound (music, long loops; short effects stay), unless marked preload (call after a level change; level calls it). A prop or template keeps one copy for good, so its model stays. A sound still playing plays on. Returns the names released */
270
303
  trim() {
271
304
  const freed = [];
272
- for (const [k, e] of this.entries) if (e.type === 'model' && e.value && !e.users && !e.pinned) { freeEntry(e); freed.push(k); }
305
+ for (const [k, e] of this.entries) if (e.type === 'model' ? e.value && !e.users && !e.load.pinned && !e.opts.preload : longSound(e)) { freeEntry(this, e); freed.push(k); }
273
306
  return freed;
274
307
  }
275
- /** How many copies of this model are in use (taken by model() and not yet engine.remove'd) */
276
- users(name) { return this.entries.get(name)?.users ?? 0; }
308
+ /**
309
+ * How many copies of this model are in use (taken by model() and not yet engine.remove'd); these are what keep its data in memory. A model that failed
310
+ * and fell back: _users('shrub') is the copies asked for as 'shrub', and _users('rock') counts those too, since they show rock's data; 0 means it can be freed
311
+ */
312
+ _users(name) { return this.entries.get(name)?.users ?? 0; }
277
313
  /** Called when an object is fully removed (engine.remove calls it): decrements the usage count of model copies beneath it and stops their animators */
278
314
  forget(obj) {
279
315
  obj.traverse(o => {
280
316
  const anim = this._animators.get(o); if (anim) { this._animators.delete(o); anim.dispose(); }
281
- const e = this._instances.get(o); if (!e) return;
317
+ const copy = this._instances.get(o); if (!copy) return;
282
318
  this._instances.delete(o);
283
- if (--e.users <= 0 && e.releasePending) freeEntry(e);
319
+ dropCopy(this, copy);
284
320
  });
285
321
  }
286
- /** Release all loaded assets and decoders (engine.dispose calls it) */
322
+ /**
323
+ * Release all loaded assets and decoders (engine.dispose calls it). A load still running ends and leaves nothing behind. Code awaiting one, and any later
324
+ * model() / texture() / font() call, stays pending for good: it never resumes against a disposed engine and never rejects during teardown
325
+ */
287
326
  dispose() {
288
- for (const e of this.entries.values()) { e.users = 0; freeEntry(e); }
327
+ disposeEntries(this);
289
328
  this.draco?.dispose(); this.ktx2?.dispose();
290
329
  }
291
330
 
292
331
  /**
293
- * @internal Only core/namedModel.js calls this (the one path for "a model made in code, used by name"): games name the model instead.
332
+ * @internal Only core/assets/namedModel.js calls this (the one path for "a model made in code, used by name"): games name the model instead.
294
333
  * Code-generated model (build returns an Object3D or BufferGeometry): built once per name + params, returns a copy (geometry returns the same instance).
295
334
  * A generator written with `function` (not an arrow) can read this.palette = engine.assets.palette (the key includes it, so a new palette rebuilds).
296
335
  * Cache key = name + generator source + params: outer variables build uses (colors, sizes, seeds in the closure...) must go in params,
@@ -304,9 +343,12 @@ export class Assets {
304
343
  else this._cachedSrc.set(name, src);
305
344
  const key = 'cached:' + name + ':' + JSON.stringify(params ?? null) + ':' + this._paletteKey + ':' + srcHash(src);
306
345
  const e = this.entries.get(key) || this.entries.set(key, { type: 'model', url: name, opts: { build, params }, promise: null }).get(key);
307
- const g = await this._fetch(e);
308
- e.pinned = true; // neither copies nor geometry are counted: trim does not free it
309
- return g.geometry ?? skeletonClone(g.scene);
346
+ // Why pinned for good, also after a palette write: what leaves here is a bare geometry or a prototype that content, vegetation and pickups clone on
347
+ // their own, so nothing counts who uses it and a free would break placed props. Counting it needs those three modules to count their copies
348
+ return this._with(e, (g, load) => {
349
+ load.pinned = true;
350
+ return g.geometry ?? skeletonClone(g.scene);
351
+ });
310
352
  }
311
353
  /** Current usage: number of geometries and textures in GPU memory */
312
354
  get memory() { return memory(this.engine.renderer); }
@@ -318,17 +360,19 @@ export class Assets {
318
360
  * engine.assets.animate(await engine.assets.model('hero')).go('attack');
319
361
  */
320
362
  animate(root, config = {}) {
321
- const m = this.mapping(root), src = this._instances.get(root);
363
+ const m = this.mapping(root), src = this._instances.get(root)?.e;
322
364
  const cfg = m ? { ...m, ...config, states: { ...m.states, ...config.states }, transitions: { ...m.transitions, ...config.transitions } } : config;
323
365
  const a = new Animator(this.engine, root, cfg, m && { label: `manifest "${src.manifest}" models.${src.name}.animation`, states: Object.keys(m.states || {}).filter(k => !config.states?.[k]) });
324
366
  this._animators.get(root)?.dispose(); // one animator per model: a new one replaces the old
325
367
  this._animators.set(root, a);
326
368
  return a;
327
369
  }
370
+ /** @internal the Animator animate() made for a model, or null (a ragdoll holds it while the model is limp) */
371
+ animatorOf(root) { return this._animators.get(root) ?? null; }
328
372
  /**
329
373
  * A model copy's manifest animation mapping ({ states, transitions, fade }), or null. Characters read it so default clip names never shadow it.
330
374
  * @example engine.assets.mapping(model)?.states.attack // { clip: 'Slash', loop: false }
331
375
  * @param {import('three').Object3D} root @returns {{ states?: object, transitions?: object, fade?: number } | null}
332
376
  */
333
- mapping(root) { return this._instances.get(root)?.opts.animation ?? null; }
377
+ mapping(root) { return this._instances.get(root)?.e.opts.animation ?? null; }
334
378
  }
@@ -10,9 +10,9 @@
10
10
  // ShaderMaterial texture uniforms and the identity of uniform objects (code holding a uniform reference stops driving the copy). Such a model's
11
11
  // manifest entry takes cache: false, or the material is made at use time.
12
12
  import * as THREE from 'three';
13
- import { neutralMaterial } from '../render/neutral.js';
14
- import { markEngineMade } from '../render/patches.js';
15
- import { warnOnce } from './validate.js';
13
+ import { neutralMaterial } from '../../render/neutral.js';
14
+ import { markEngineMade } from '../../render/patches.js';
15
+ import { warnOnce, fmt } from '../base/validate.js';
16
16
 
17
17
  const TEX_KEYS = ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'aoMap', 'alphaMap', 'bumpMap', 'lightMap', 'specularMap', 'envMap', 'gradientMap', 'displacementMap'];
18
18
  // Slots glTF has no place for (the exporter drops them)
@@ -35,7 +35,7 @@ export async function toGLB(value, name = 'model') {
35
35
  const mats = new Map(), lost = new Set();
36
36
  root.traverse(o => { for (const m of [].concat(o.material ?? [])) for (const k of lostSlots(m)) lost.add(k); });
37
37
  // said before the file is written, once per model and list: the copy read back next run would silently lack them
38
- if (lost.size) warnOnce(LOST.replaceAll('{name}', name).replace('{list}', [...lost].join(', ')).replace('{first}', [...lost][0]));
38
+ if (lost.size) warnOnce(fmt(LOST, { name, list: [...lost].join(', '), first: [...lost][0] }));
39
39
  // Export with glTF's standard material (color, textures, vertex colors); the original type and params go in userData.threedogMat and are rebuilt as-is on read-back
40
40
  const tag = m => {
41
41
  if (!mats.has(m)) {
@@ -0,0 +1,237 @@
1
+ // The life of one engine.assets entry, split from Assets.js (which keeps the public API and the manifest):
2
+ // load: fetchEntry runs the load as a task in engine.loading and, for a registered non-critical file that fails, falls back (gray placeholder / silence / the entry's fallback)
3
+ // free: freeEntry gives the GPU memory back, deferred while model copies are still in the scene; shareModel marks what copies share so engine.remove does not dispose it
4
+ // sounds: freeing one needs no count. A playing voice holds its own buffer, so it plays on and the memory goes when it ends; the next play loads the file again
5
+ // Plain functions that take the Assets instance, so they stay out of the class's public surface.
6
+ //
7
+ // Who owns what. An entry is a name; a load is one attempt at its data, and the load is what owns that data:
8
+ // { owner, type, gameOwned, task, stop, value, users, settled, pinned }, reached as e.load.
9
+ // - One rule for freed, replaced and disposed: whoever ends a load aborts `stop`; a result arriving for an aborted load is freed and never written
10
+ // back. Why a record per load and not a counter on the entry: a palette write, a hot swap and a release all leave a load behind while the
11
+ // name moves on, and only the load knows which copies still hold its data.
12
+ // - Each copy counts on the load its data came from, so a name that fell back to another (e.load is then the other entry's load, e.value stays null)
13
+ // keeps that entry's data alive, and freeing the data sends every name reading it back to a fresh load.
14
+ // - e.users is the count Assets._users reads: copies asked for by this name plus copies that borrow its data. load.users frees an old build.
15
+ //
16
+ // A caller already awaiting a load that was ended:
17
+ // - release, trim, a palette write, a name registered again: the game is alive and asked for this asset, so the wait carries on with a fresh load
18
+ // (release says "reloaded on next use", and a wait is a use). It gets a live value, or the failure of that fresh load. Why not reject: every
19
+ // model() in the game would need a catch for a normal level change, and a rejected promise stays cached in the prototype tables.
20
+ // - assets.dispose: the promise stays pending for good. Why not reject or resolve null: `model(x).then(add)` with no catch would be an unhandled
21
+ // rejection in teardown, and null would be a TypeError in the same place; the code after the await belongs to a disposed engine.
22
+ import { warnOnce, fmt } from '../base/validate.js';
23
+ import { codedError, coded } from '../base/errorHints.js';
24
+ import { loadGltf, loadTexture, loadFont, loadAudio, generated, placeholder } from './assetLoad.js';
25
+ import { failureText } from '../engine/Loading.js';
26
+ import { paramValues } from './assetManifest.js';
27
+
28
+ const STRINGS = {
29
+ failed: 'Asset failed to load: {what}',
30
+ fellBack: '; using {fallback} instead, the game continues (mark it critical: true if the game cannot start without it)',
31
+ cycle: '; its fallbacks loop back on themselves ({chain}). Break the loop: give one of them no fallback, or a fallback that is a different file',
32
+ missingRefs: 'Asset loaded with missing references: {what} (missing {list}); materials show without those files',
33
+ };
34
+
35
+ /** From this many seconds a decoded sound is music or a long loop, worth loading again; shorter ones are effects, played often and small, and stay */
36
+ const LONG_SOUND = 10;
37
+ /** Decoded long sounds kept at once, in bytes: about 6 minutes of stereo at 48 kHz (a decoded minute is 21 MB, whatever the file's size) */
38
+ const SOUND_BUDGET = 128 * 2 ** 20;
39
+ const soundBytes = b => b.length * b.numberOfChannels * 4;
40
+ /** A decoded long sound trim and the budget may free; preload: true keeps it, as it keeps a model */
41
+ export const longSound = e => e.type === 'sound' && e.value?.duration >= LONG_SOUND && !e.opts.preload;
42
+
43
+ /** What a caller holds once the engine is gone: never settles, so nothing runs against a disposed engine (the rule is at the top of this file) */
44
+ const NEVER = new Promise(() => {});
45
+
46
+ /** Mark a model template's geometry and materials as shared (copies share them; engine.remove must not dispose them) */
47
+ function shareModel(a, g) {
48
+ g.scene.traverse(o => { if (o.geometry) a.shared.add(o.geometry); for (const m of [].concat(o.material || [])) a.shared.add(m); });
49
+ return g;
50
+ }
51
+
52
+ /**
53
+ * Shadow flags of a model copy, one rule for files, generators and content props: an explicit castShadow / receiveShadow (the model() call,
54
+ * then the manifest entry) wins; otherwise a generator that set either flag on any of its meshes decided for itself and is kept as built
55
+ * (a decal that must not cast stays that way); otherwise (a file, or a generator that set nothing) every mesh casts and receives.
56
+ * @param {import('three').Object3D} root
57
+ * @param {{ castShadow?: boolean, receiveShadow?: boolean }} [set]
58
+ */
59
+ export function shadowDefaults(root, { castShadow, receiveShadow } = {}) {
60
+ let decided = false;
61
+ root.traverse(o => { if (/** @type {any} */ (o).isMesh && (o.castShadow || o.receiveShadow)) decided = true; });
62
+ const cast = castShadow ?? (decided ? null : true), recv = receiveShadow ?? (decided ? null : true);
63
+ root.traverse(o => { if (/** @type {any} */ (o).isMesh) { if (cast != null) o.castShadow = cast; if (recv != null) o.receiveShadow = recv; } });
64
+ return root;
65
+ }
66
+
67
+ /** Load an entry as a task in engine.loading; a registered, non-critical file that fails resolves to its fallback */
68
+ export function fetchEntry(a, e) {
69
+ if (a._disposed) return NEVER;
70
+ if (a._stale(e)) retireEntry(a, e);
71
+ if (e.promise) return e.promise;
72
+ e.palette = a._paletteKey;
73
+ const L = a.engine.loading, name = e.variantOf ?? e.name ?? e.url;
74
+ const t = L._begin(name, e.type, { critical: e.opts.critical === true, url: e.opts.build || e.opts.texture ? null : e.url, manifest: e.manifest ?? null });
75
+ const load = e.load = { owner: e, type: e.type, gameOwned: !!e.opts.texture, task: t, stop: new AbortController(), value: null, users: 0, settled: false, pinned: false };
76
+ t.signal = load.stop.signal; // the loaders read it between phases, and a download passes it to fetch
77
+ let work;
78
+ if (e.type === 'model') {
79
+ const got = e.opts.build ? (t.phase('build'), new Promise(res => res(generated(a, e.url, e.opts.build, e.schema ? paramValues(e) : e.opts.params, t)))) /* a sync throw takes the failure path below */ : loadGltf(a, e.url, t);
80
+ work = got.then(g => shareModel(a, g));
81
+ } else if (e.type === 'texture') work = loadTexture(a, e, t);
82
+ else if (e.type === 'font') work = loadFont(a, e, t);
83
+ else if (e.type === 'sound' && e.opts.build) work = Promise.resolve(e.opts.build); // a synth function: nothing to download
84
+ else if (e.type === 'sound') work = loadAudio(a, e, t);
85
+ // a._disposed too: an entry a hot swap dropped from the table is not reached by dispose, so its load was never aborted
86
+ const ended = () => load.stop.signal.aborted || a._disposed;
87
+ e.promise = work.then(v => {
88
+ if (ended()) { freeValue(load, v); return fetchEntry(a, e); }
89
+ L._done(t);
90
+ const what = `${e.type} "${name}" <- ${e.url}`;
91
+ if (t.missing.length) warnOnce(coded('asset-missing-ref', fmt(STRINGS.missingRefs, { what, list: t.missing.join(', ') })));
92
+ load.settled = true;
93
+ load.value = e.value = v;
94
+ if (e.type === 'sound') capSounds(a, e);
95
+ return v;
96
+ }, err => (ended() ? fetchEntry(a, e) : failedEntry(a, e, load, err))); // a failure nobody wants any more is not reported
97
+ return e.promise;
98
+ }
99
+
100
+ /** The fallback chain from e if it comes back to a name already on it (e -> ... -> e or into a ring), as names; null if it ends */
101
+ function fallbackCycle(a, e) {
102
+ const chain = [e.name ?? e.url];
103
+ for (let x = e; x?.opts.fallback;) {
104
+ const next = a.entries.get(x.opts.fallback);
105
+ chain.push(x.opts.fallback);
106
+ if (chain.indexOf(x.opts.fallback) < chain.length - 1) return chain;
107
+ x = next;
108
+ }
109
+ return null;
110
+ }
111
+
112
+ /** A load failed: a registered file entry degrades (warn + fallback); anything else is recorded and rethrown to the caller */
113
+ function failedEntry(a, e, load, err) {
114
+ const t = load.task;
115
+ e.promise = null;
116
+ const degrade = e.named && !e.opts.build && !e.opts.critical;
117
+ const fb = degrade ? (e.opts.fallback ?? (e.type === 'sound' ? 'silence' : e.type === 'font' ? 'the system font' : 'gray placeholder')) : null;
118
+ a.engine.loading._fail(t, err, fb);
119
+ const msg = fmt(STRINGS.failed, { what: failureText(t) });
120
+ const loop = degrade && e.opts.fallback ? fallbackCycle(a, e) : null;
121
+ // A -> B -> A: each would wait for the other's fallback forever, so fail once and name the chain (the fix is in the manifest)
122
+ if (loop) { e.load = null; throw codedError('asset-fallback-cycle', msg + fmt(STRINGS.cycle, { chain: loop.join(' -> ') })); }
123
+ if (!degrade) { e.load = null; throw codedError('asset-load', msg); }
124
+ warnOnce(coded('asset-load', msg + fmt(STRINGS.fellBack, { fallback: e.opts.fallback ? `"${fb}"` : fb })));
125
+ if (e.opts.fallback) return (e.promise = borrow(a, e, load, a._resolve(e.opts.fallback, e.type)));
126
+ load.settled = true;
127
+ load.value = e.value = e.type === 'model' ? shareModel(a, placeholder('model')) : placeholder(e.type);
128
+ return (e.promise = Promise.resolve(e.value));
129
+ }
130
+
131
+ /** e falls back to `from`: until `from` answers, e's own failed load stays the token a release ends; then e reads from's load, which owns the data */
132
+ function borrow(a, e, load, from) {
133
+ const ended = () => load.stop.signal.aborted;
134
+ return fetchEntry(a, from).then(v => {
135
+ if (ended()) return fetchEntry(a, e);
136
+ if (from.load?.value !== v) { letGo(e); return fetchEntry(a, e); } // released between its load finishing and this line
137
+ e.load = from.load;
138
+ return v;
139
+ }, err => {
140
+ if (ended()) return fetchEntry(a, e);
141
+ letGo(e); // not kept as a rejected promise: the next use tries again
142
+ throw err;
143
+ });
144
+ }
145
+
146
+ /** This name reads nothing now; its next use loads again */
147
+ function letGo(e) { e.load = e.value = e.promise = null; }
148
+ /** Every name reading this load, the owner and any that fell back to it, lets go of it */
149
+ function letGoAll(a, load) { for (const x of a.entries.values()) if (x.load === load) letGo(x); }
150
+
151
+ /** End a load still running. Its task goes too: nobody is waiting for that attempt, and a loading screen must not stay on it */
152
+ function cancelLoad(a, load) {
153
+ load.stop.abort();
154
+ a.engine.loading._drop(load.task);
155
+ }
156
+
157
+ /** Give back what one load made. A font that never reached document.fonts is a no-op here */
158
+ function freeValue(load, v) {
159
+ if (!v) return;
160
+ if (load.type === 'texture' && !load.gameOwned) v.dispose(); // a Texture the game registered is the game's: never disposed here
161
+ if (load.type === 'font') document.fonts.delete(v); // a released font stops matching its family
162
+ if (load.type === 'model') { // always { scene, ... }: generated() wraps a bare geometry too
163
+ v.scene.traverse(o => {
164
+ if (!o.geometry) return;
165
+ o.geometry.dispose();
166
+ [].concat(o.material).forEach(m => { for (const k in m) if (m[k]?.isTexture) m[k].dispose(); m.dispose(); });
167
+ });
168
+ }
169
+ }
170
+
171
+ /** Free an entry's GPU memory; while model copies are still in use it waits (releasePending) and the last engine.remove frees it. A load in flight ends here */
172
+ export function freeEntry(a, e) {
173
+ const load = e.load;
174
+ if (!load) return;
175
+ if (load.owner !== e) { letGo(e); return; } // fell back: the data is the other entry's, and this name only stops reading it
176
+ if (!load.settled) { letGoAll(a, load); cancelLoad(a, load); return; }
177
+ if (e.users > 0) { e.releasePending = true; return; }
178
+ freeValue(load, load.value);
179
+ letGoAll(a, load);
180
+ e.releasePending = false;
181
+ }
182
+
183
+ /**
184
+ * The name moves on from its current load (a palette write, a new registration, tuned params): an unfinished load ends, and finished data goes as soon as
185
+ * nothing holds it. Only models can be judged: copies are counted and geometry() pins. A texture is handed out uncounted, so a material may still show it: it
186
+ * is left to the game. Loads kept here wait in a._retired for their last copy, and for dispose
187
+ */
188
+ export function retireEntry(a, e) {
189
+ const load = e.load;
190
+ if (!load) return;
191
+ if (load.owner !== e) { letGo(e); return; }
192
+ letGoAll(a, load);
193
+ if (!load.settled) cancelLoad(a, load);
194
+ else if (load.type === 'model') { if (load.users > 0 || load.pinned) a._retired.add(load); else freeValue(load, load.value); }
195
+ }
196
+
197
+ /** One model copy went away (engine.remove): the argument is what Assets._copy recorded */
198
+ export function dropCopy(a, { e, load }) {
199
+ const owner = load.owner;
200
+ load.users--; e.users--;
201
+ if (owner !== e) owner.users--;
202
+ if (load.users <= 0 && !load.pinned && a._retired.delete(load)) freeValue(load, load.value);
203
+ if (owner.users <= 0 && owner.releasePending) freeEntry(a, owner);
204
+ }
205
+
206
+ /** e just loaded: while long sounds are over the budget, the one asked for longest ago goes (never e itself) */
207
+ function capSounds(a, e) {
208
+ const long = [...a.entries.values()].filter(longSound).sort((x, y) => (x.usedAt ?? 0) - (y.usedAt ?? 0));
209
+ let bytes = long.reduce((n, x) => n + soundBytes(x.value), 0);
210
+ for (const x of long) {
211
+ if (bytes <= SOUND_BUDGET) break;
212
+ if (x !== e) { bytes -= soundBytes(x.value); freeEntry(a, x); }
213
+ }
214
+ }
215
+
216
+ /** Everything goes, copies or not, and no load finishing later may bring anything back (engine.dispose) */
217
+ export function disposeEntries(a) {
218
+ a._disposed = true;
219
+ for (const e of a.entries.values()) { e.users = 0; freeEntry(a, e); }
220
+ for (const load of a._retired) freeValue(load, load.value);
221
+ a._retired.clear();
222
+ }
223
+
224
+ /** Load the entries preload() wants and report progress; returns { loaded, failed, ok } (Assets.preload documents it) */
225
+ export async function preloadEntries(a, onProgress, onlyMarked) {
226
+ // generators and fonts only when marked: a font pack may hold many faces, and only those ui.fonts names (or preload: true) are wanted
227
+ const list = [...a.entries.entries()].filter(([, e]) => e.opts.build || e.type === 'font' ? e.opts.preload : !onlyMarked || e.opts.preload);
228
+ let done = 0;
229
+ onProgress?.(list.length ? 0 : 1, '');
230
+ // critical failures are reported by start(); others not already warned about (generated models) are warned here
231
+ await Promise.all(list.map(([name, e]) => fetchEntry(a, e).catch(err => { if (!e.opts.critical) warnOnce(err.message); }).finally(() => {
232
+ done++;
233
+ onProgress?.(done / list.length, name);
234
+ })));
235
+ const failed = list.filter(([name, e]) => a.engine.loading.get(name, e.type)?.phase === 'failed').map(([name]) => name);
236
+ return { loaded: list.length - failed.length, failed, ok: !failed.length };
237
+ }
@@ -10,10 +10,11 @@
10
10
  // Limits (said in the report): a copy's collision box keeps the size it was placed with until the next load; an InstancedMesh or a merged batch
11
11
  // the game built itself from a geometry is not found (only engine paths are).
12
12
  import { registerManifest, paramValues } from './assetManifest.js';
13
- import { protoCaches, protoOf, cachedModel, list } from './namedModel.js';
14
- import { reportError } from './errors.js';
15
- import { codedError } from './errorHints.js';
16
- import { note } from './validate.js';
13
+ import { protoCaches, protoOf, cachedModel } from './namedModel.js';
14
+ import { list } from '../base/util.js';
15
+ import { reportError } from '../base/errors.js';
16
+ import { codedError } from '../base/errorHints.js';
17
+ import { note } from '../base/validate.js';
17
18
 
18
19
  // a failed rebuild is reported (soft: the old copies stay on screen) and the swap goes on with the other names
19
20
  const failWith = e => (err, what) => reportError(e, err, `asset hot swap: ${what}`, { soft: true });
@@ -27,7 +28,7 @@ const LAST = 10; // swaps kept for describe().assetSwaps
27
28
  * with the new ones mesh by mesh; every scene mesh using an old geometry / material gets the new one.
28
29
  * @param {any} e @param {{ name: string, type: string, old: any }[]} changed @param {string} why for the report ('edit', 'params')
29
30
  */
30
- export async function swapModels(e, changed, why = 'edit') {
31
+ async function swapModels(e, changed, why = 'edit') {
31
32
  const t0 = performance.now(), a = e.assets, fail = failWith(e); // measure
32
33
  const names = new Set(changed.filter(c => c.type === 'model').map(c => c.name));
33
34
  const geo = new Map(), mat = new Map(), tex = new Map(), protoNew = new Map(), structure = new Set(), copies = {};
@@ -170,7 +171,7 @@ export async function setParams(e, name, values) {
170
171
  paramValues(ent, values); // a typo or a wrong type throws here, before anything is rebuilt
171
172
  const old = { ...ent };
172
173
  ent.tuned = { ...ent.tuned, ...values };
173
- if (ent.value) { ent.value = null; ent.promise = null; }
174
+ e.assets._retire(ent);
174
175
  return swapModels(e, [{ name, type: 'model', old }], 'params');
175
176
  }
176
177