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
package/README.md CHANGED
@@ -3,13 +3,13 @@
3
3
  A web 3D game engine on three.js 0.187: **core** (rendering, main loop, input, audio, saving, UI) -> **modules** (terrain, sky and weather, physics, characters, dialogue, inventory, quests... installed on demand); all art is the game's own (`picture/` folder, `assets.js`).
4
4
 
5
5
  ## Install
6
- This README describes threedog 0.7.0 (older releases on npm do not match it; upgrade steps are in `docs/MIGRATING-0.7.md`). To work on the engine itself, clone the [repository](https://github.com/penstic123-code/ThreeDog.js-Game-Engine), run `npm install`, then `npm run new-game -- my-game`. A game in its own folder:
6
+ This README describes threedog 0.9.0 (older releases do not match it; from 0.9.0 read `docs/MIGRATING-1.0.md`, from 0.8.0 `CHANGELOG.md`, from 0.7.0 first `docs/MIGRATING-0.8.md`). To work on the engine itself, clone the [repository](https://github.com/penstic123-code/Threedog.js-Game-Engine), run `npm install`, then `npm run new-game -- my-game`. A game in its own folder:
7
7
  ```sh
8
- npm install threedog@0.7 three@~0.187.0
9
- npm install @threedog/terrain-noise@0.7 # optional: the noise terrain generator terrainPreset() (without one the ground is flat)
10
- npm install -D vite @threedog/tools@0.7 # optional: the vite preset and the threedog command line
8
+ npm install threedog@0.9 three@~0.187.0
9
+ npm install @threedog/terrain-noise@0.9 # optional: the noise terrain generator terrainPreset() (without one the ground is flat)
10
+ npm install -D vite @threedog/tools@0.9 # optional: the vite preset and the threedog command line
11
11
  ```
12
- Then let it set up the folder: `node node_modules/@threedog/tools/bin/threedog.mjs init` (flags: `--open-world` for generated ground, sky, follow camera and a player; the default is a blank scene with a camera and a gray starter picture in `picture/`) writes index.html, main.js, vite.config.js, content/, CLAUDE.md and `.mcp.json` (Claude Code then starts the threedog MCP server by itself), never overwriting a file you have.
12
+ Then let it set up the folder: `npx threedog init` (flags: `--open-world` for generated ground, sky, follow camera and a player; the default is a blank scene with a camera and a gray starter picture in `picture/`) writes index.html, main.js, vite.config.js, content/, CLAUDE.md and `.mcp.json` (Claude Code then starts the threedog MCP server by itself), never overwriting a file you have. Finish with `npm install` (for what the new files need) and `npm run dev`.
13
13
  `three` is a peer dependency: your game and the engine share one copy. Types for three come with the engine (`@types/three`, same version), so `// @ts-check` JS and TypeScript both see real three.js types.
14
14
 
15
15
  ## Minimal usage
@@ -31,17 +31,14 @@ The picture is the game's own: plain three.js in its `picture/` folder (what `th
31
31
  - The engine ships no art (visuals only; the noise terrain generator `terrainPreset()` is `@threedog/terrain-noise`); without picture code everything is a neutral gray placeholder.
32
32
  - `threedog/tsl`: the WebGPU route; import it before `createEngine({ renderer: 'webgpu' })`. Also TSL helpers for materials and lighting.
33
33
  - `threedog/layers`: `RESERVED_LAYERS`, the three.js layers the engine keeps (a game's own are 1 to 25).
34
+ - `threedog/pixel`: `pixelGrid`, `pixelSprite`, `spriteFrame` (art pixel math on an orthographic camera, and an upright sprite; recipe 62 section 4b).
34
35
  - `threedog/grid`: `sampleGrid`, `gridFromPixels`, `decodePng` (2D fields; no three.js, works in workers and tests).
35
36
  - `threedog/worker`: `serve(handler)`, the worker side of `engine.threads` lanes.
36
- - `threedog/error-hints`: the developer error hint table (used by `@threedog/tools`).
37
37
 
38
- Nothing else is a public path; files under `core/`, `modules/` etc. may move between versions.
38
+ Nothing else is a public path: `threedog/error-hints`, `threedog/metadata` and `threedog/spelling` are there for `@threedog/tools`, not for game code; files under `core/`, `modules/` etc. may move between versions.
39
39
 
40
40
  ## Changes to three.js
41
- The engine changes three.js in a few places, because three.js has no per-object hook for what it needs. `describe().threePatches` lists every one at run time, `threePatches.off(id)` turns off the ones that can be turned off, and `docs/THREE.md` says what each does to your code. Importing the engine does these page-wide:
42
- - `Object3D.prototype.add` / `remove` are wrapped once, so `scene.add` is adopted like `engine.add`.
43
- - `Mesh.prototype.customDepthMaterial` and `customDistanceMaterial` become accessors: when nothing was assigned, a mesh whose material has engine vertex patches (wind sway) returns a matching depth material, so its shadow moves with it. Assigning a value still wins; assigning `undefined` restores the default.
44
- - `THREE.ShaderChunk` gains `threedog_*` entries (new names, none of three's replaced).
41
+ The engine changes three.js in a few places, because three.js has no per-object hook for what it needs. `describe().threePatches` lists every one at run time, `threePatches.off(id)` turns off the ones that can be turned off, and `docs/THREE.md` is the full list, with what each does to your code.
45
42
 
46
43
  Raycasting is not a global change: a mesh registered as static gets its own bounds tree and its own `raycast`; `Mesh.prototype.raycast` is untouched.
47
44
 
@@ -16,8 +16,9 @@
16
16
  // Rule: animation is presentation; gameplay timing must not read it. The mixer advances per frame (dropped frames, step's frameEvery or a disposed model all skew it),
17
17
  // so hit windows, stun and cooldowns count in fixed steps, and sync(state, t) is how that gameplay time reaches the pose: the clip never runs ahead or ends by itself.
18
18
  import * as THREE from 'three';
19
- import { warnOnce, warnMissing, missingText } from './validate.js';
20
- import { readParams, keysSchema, isOptions } from './params.js';
19
+ import { warnOnce, warnMissing, missingText } from '../base/validate.js';
20
+ import { readParams, keysSchema } from '../base/params.js';
21
+ import { isOptions } from '../base/util.js';
21
22
  const GO_KEYS = ['fade'];
22
23
 
23
24
  // Config keys: a typo (loops: false, state: {...}) would silently play the wrong thing, so both levels are checked like any other options
@@ -26,7 +27,7 @@ const STATE_KEYS = ['clip', 'blend', 'param', 'sync', 'loop', 'then', 'lock', 't
26
27
 
27
28
  /**
28
29
  * Find a clip by exact name, else by the part after the last '|' ('Idle' finds 'CharacterArmature|Idle').
29
- * @example findClip(model.userData.animations, 'Sword_Slash')
30
+ * @example findClip(model.animations, 'Sword_Slash')
30
31
  */
31
32
  export function findClip(clips, name) {
32
33
  return THREE.AnimationClip.findByName(clips, name) ?? clips.find(c => c.name.slice(c.name.lastIndexOf('|') + 1) === name) ?? null;
@@ -34,6 +35,8 @@ export function findClip(clips, name) {
34
35
  const short = n => n.slice(n.lastIndexOf('|') + 1);
35
36
  const r3 = v => Math.round(v * 1000) / 1000;
36
37
 
38
+ const ONE = Object.freeze([1]); // the blend split of a plain state
39
+
37
40
  export class Animator {
38
41
  /** mappedIn (from Assets.animate): { label, states } when part of the mapping came from the manifest, so fix texts point at the data, not at code */
39
42
  constructor(engine, root, config = {}, mappedIn = null) {
@@ -48,7 +51,7 @@ export class Animator {
48
51
  this.transitions = transitions;
49
52
  this.params = { speed: 0, ...params };
50
53
  this.mixer = new THREE.AnimationMixer(root);
51
- this.clips = root.userData.animations || [];
54
+ this.clips = root.animations;
52
55
  this.actions = new Map(); // clip name (as written in the state) -> three.js AnimationAction
53
56
  this.state = null;
54
57
  this._layers = []; // states being shown: { name, def, w, target, rate, actions: [{ a, clip }], driven }
@@ -61,7 +64,7 @@ export class Animator {
61
64
  if (this.hasClips) {
62
65
  this._check();
63
66
  this.mixer.addEventListener('finished', ev => this._finished(ev.action));
64
- this._hook = engine.onFrame(dt => this.update(dt));
67
+ this._hook = engine._onAnimate(dt => this.update(engine.still ? 0 : dt));
65
68
  }
66
69
  }
67
70
  /** Dev check at build time: the same problems check() returns, minus the game's action list (the Animator does not know it). */
@@ -134,14 +137,15 @@ export class Animator {
134
137
  if (!def) { warnMissing('animState', state, Object.keys(this.states)); return null; }
135
138
  const actions = (def.blend ? def.blend.map(b => b.clip) : [def.clip]).map(clip => ({ a: this._action(clip), clip }));
136
139
  if (actions.some(x => !x.a)) return null; // missing clip: already reported by _check
137
- const f = this._fadeFor(this.state, state, fade), rate = f > 0 ? 1 / f : Infinity;
140
+ const f = this._fadeFor(this.state, state, fade), rate = f > 0 ? 1 / f : 1e9; // not Infinity: 0 * Infinity (dt 0 behind a full still) is NaN
138
141
  for (const l of this._layers) { l.target = 0; l.rate = rate; }
139
142
  let layer = this._layers.find(l => l.name === state);
140
143
  if (!layer) {
141
144
  layer = { name: state, def, w: this._layers.some(l => l.w > 0) ? 0 : 1, actions }; // the first state shows immediately
142
145
  this._layers.push(layer);
143
146
  for (const { a } of actions) {
144
- a.reset().setEffectiveWeight(0);
147
+ // a clip another layer is playing keeps its time (states may share a clip); a fresh one starts over, at the speed a blend may have left on it
148
+ if (!this._held1(a, layer)) a.reset().setEffectiveTimeScale(1).setEffectiveWeight(0);
145
149
  if (def.loop === false) { a.setLoop(THREE.LoopOnce, 1); a.clampWhenFinished = true; } else a.setLoop(THREE.LoopRepeat, Infinity);
146
150
  a.play();
147
151
  }
@@ -161,8 +165,9 @@ export class Animator {
161
165
  }
162
166
  const a = this.go(name, opts);
163
167
  if (a && this.state === name) {
164
- this._layers.find(l => l.name === name).once = true; // not interrupted by the character's per-frame go() until it ends
165
- if (!this.states[name].then) this._return = prev;
168
+ // only a clip that ends can hold the state until it ends: a looping state would lock the animator for good
169
+ if (this.states[name].loop === false) this._layers.find(l => l.name === name).once = true; // not interrupted by the character's per-frame go() until it ends
170
+ if (!this.states[name].then && prev !== name) this._return = prev; // a repeat press of the same action keeps the state to go back to
166
171
  }
167
172
  return a;
168
173
  }
@@ -222,10 +227,12 @@ export class Animator {
222
227
 
223
228
  /** @internal Per frame: advance fades, split blend-tree weights by parameter, sync stride, then advance the mixer (the engine calls it). */
224
229
  update(dt) {
230
+ if (this._held) { this.afterPose?.(dt); return; } // physics owns the bones (a ragdoll): the mixer writes nothing, attachments still follow the pose
225
231
  let j = 0; // fade, stop faded-out layers and compact in place (no arrays per frame)
226
232
  for (const l of this._layers) {
227
- l.w = l.target > l.w ? Math.min(1, l.w + dt * l.rate) : Math.max(0, l.w - dt * l.rate);
228
- if (l.w === 0 && l.target === 0) { for (const { a } of l.actions) a.setEffectiveWeight(0).stop(); continue; }
233
+ if (l.w < l.target) l.w = Math.min(l.target, l.w + dt * l.rate);
234
+ else if (l.w > l.target) l.w = Math.max(l.target, l.w - dt * l.rate);
235
+ if (l.w === 0 && l.target === 0) { for (const { a } of l.actions) if (!this._held1(a, l)) a.setEffectiveWeight(0).stop(); continue; }
229
236
  this._layers[j++] = l;
230
237
  }
231
238
  this._layers.length = j;
@@ -233,18 +240,21 @@ export class Animator {
233
240
  this.mixer.update(dt);
234
241
  this.afterPose?.(dt); // Character.onPose callbacks (the pose is final here)
235
242
  }
243
+ /** @internal is action a also held by a live layer other than l? (states may share a clip, and three keeps one action per clip) */
244
+ _held1(a, l) { return this._layers.some(o => o !== l && !(o.w === 0 && o.target === 0) && o.actions.some(x => x.a === a)); }
236
245
  _weights() {
237
246
  let total = 0;
238
- for (const l of this._layers) total += l.w;
247
+ for (const l of this._layers) { total += l.w; for (const x of l.actions) x.a.setEffectiveWeight(0); }
239
248
  for (const l of this._layers) {
240
- const lw = total > 0 ? l.w / total : 0, bw = l.def.blend ? this._blend(l.def) : [1];
249
+ const lw = total > 0 ? l.w / total : 0, bw = l.def.blend ? this._blend(l.def) : ONE;
241
250
  let dur = 0;
242
- l.actions.forEach((x, i) => { dur += bw[i] * x.a.getClip().duration; });
243
- l.actions.forEach((x, i) => {
244
- x.a.setEffectiveWeight(lw * bw[i]);
251
+ for (let i = 0; i < l.actions.length; i++) dur += bw[i] * l.actions[i].a.getClip().duration;
252
+ for (let i = 0; i < l.actions.length; i++) {
253
+ const { a } = l.actions[i];
254
+ a.setEffectiveWeight(a.weight + lw * bw[i]); // added: two layers on one clip each give their share
245
255
  // blended actions share one beat (walk and run footfalls land together)
246
- if (l.def.blend && l.def.sync !== false && dur > 0) x.a.setEffectiveTimeScale(x.a.getClip().duration / dur);
247
- });
256
+ if (l.def.blend && l.def.sync !== false && dur > 0) a.setEffectiveTimeScale(a.getClip().duration / dur);
257
+ }
248
258
  }
249
259
  }
250
260
  /** Blend-tree weights: a parameter between two `at` values splits proportionally across the two neighbours. */
@@ -269,3 +279,5 @@ export class Animator {
269
279
  /** Call when no longer needed to stop per-frame updates. */
270
280
  dispose() { this._hook?.remove(); this.mixer.stopAllAction(); }
271
281
  }
282
+
283
+ export const handRolled = [{ kind: 'animation', seen: 'an AnimationMixer of its own', use: 'engine.assets.animate(model, { states }): states, crossfades, sync with game time and pause (recipe 13)', quiet: /\bassets\.animate\b/, code: /\bnew\s+(?:THREE\.)?AnimationMixer\s*\(|\bmixer\.update\s*\(/i }];
@@ -2,9 +2,9 @@
2
2
  // 1. Asset manifest: register every model, texture and sound under a name; code uses names only, so swapping a file means editing the manifest.
3
3
  // 2. Preload: load everything marked preload once at startup; the loading screen shows progress.
4
4
  // 3. Cache and reuse: one file downloads once; models return independent copies (geometry and materials shared), so you can place many.
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
5
+ // 4. Release: one count of leases, and a model copy is one (assetEntry.js takeLease); release(name) frees only when the last lease ends, 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,24 +24,26 @@
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 { waitLoad, freeEntry, retireEntry, takeLease, 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",
44
45
  notLoaded: 'assets.modelNow(\'{name}\') is null: nothing has loaded that model yet (a code-built model is built, or read from the bake cache, on its first load too). Use `engine.assets.modelNow(\'{name}\') ?? await engine.assets.model(\'{name}\')`, or mark it preload: true in the manifest and await engine.assets.preload()',
46
+ noLease: 'assets.lease(\'{name}\'): nothing is registered or loaded under that name, so there is no data to hold. Fix: register it in an asset pack, or load it first with assets.model / assets.texture',
45
47
  noFont: 'assets.font(\'{name}\'): no font named {name}{known}. Register the file in an asset pack: engine.assets.manifest({ fonts: { {name}: \'/fonts/{name}.woff2\' } })',
46
48
  sameName: 'model \'{name}\': the same name was used with two different generator functions, so the cache would mix them (keyed by name + params). Use a different name per model; if the result depends on outer variables, put them in params',
47
49
  };
@@ -51,19 +53,22 @@ const srcHash = s => { let h = 0; for (let i = 0; i < s.length; i++) h = (Math.i
51
53
  export class Assets {
52
54
  constructor(engine) {
53
55
  this.engine = engine;
54
- this.entries = new Map(); // name -> { type, url, opts, promise, value }
56
+ this.entries = new Map(); // name -> { type, url, opts, promise, value, load, users } (who owns the data: top of assetEntry.js)
55
57
  this.gltf = new GLTFLoader();
56
58
  this.gltf.setMeshoptDecoder(MeshoptDecoder);
57
59
  this.draco = null; // DRACOLoader / KTX2Loader:created on the first compressed data
58
60
  this.ktx2 = null;
59
61
  this.tex = new THREE.TextureLoader();
60
62
  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)
63
+ this._instances = new WeakMap(); // model copy root -> { e: the entry it was asked for by, load: the load that owns its data }
64
+ this._retired = new Set(); // old loads no entry points at, kept for the copies or geometry still using them
65
+ this._disposed = false;
62
66
  this._animators = new WeakMap(); // model root -> Animator from animate(): engine.remove disposes it with the model
63
67
  this.cacheMinMs = 20; // builds faster than this are not cached (reading the file would be slower)
64
68
  /**
65
69
  * 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.
70
+ * 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,
71
+ * and a model's old build is freed with its last copy.
67
72
  * @example engine.assets.palette = { leaf: 0xd98a3a, bark: 0x6b4a30 };
68
73
  * @type {Record<string, any>}
69
74
  */
@@ -74,18 +79,18 @@ export class Assets {
74
79
  /**
75
80
  * 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
81
  * 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
82
+ * core/base/params.js format ({ height: { type: 'number', min: 1, max: 6, default: 3 }, color: { type: 'color', default: 0x557733 } }): the generator is
78
83
  * 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
84
  * Per entry: critical: true = start() stops if it fails (otherwise it falls back and the game continues); fallback: 'otherName' replaces the gray
80
85
  * placeholder.
81
86
  * 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).
87
+ * 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
88
+ * 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
89
  * @example engine.assets.manifest({ name: 'level-1', models: { hero: { url: '/models/hero.glb', critical: true }, bush: { url: '/models/bush.glb', fallback:
85
90
  * 'rock' } } });
86
91
  * @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]
92
+ * @example import packs from '../assets.js'; engine.assets.manifest(packs); // a list: the game's assets.js, which `npm run check` reads too
93
+ * @param {import('../../types/core').AssetManifest | import('../../types/core').AssetManifest[]} [pack]
89
94
  */
90
95
  manifest(pack = {}) { return registerManifest(this, pack); }
91
96
 
@@ -120,7 +125,7 @@ export class Assets {
120
125
  */
121
126
  setParams(name, values) { return setParams(this.engine, name, values); }
122
127
  /** @internal a module rebuilds its own copies after a hot swap (vegetation): fn({ names, geometry, material }) -> { name: copies } */
123
- onSwap(fn) { (this._swapHooks ||= []).push(fn); }
128
+ onSwap(fn) { (this._swapHooks ||= new Set()).add(fn); return { remove: () => this._swapHooks.delete(fn) }; }
124
129
 
125
130
  _resolve(nameOrUrl, type) {
126
131
  let e = this.entries.get(nameOrUrl);
@@ -134,7 +139,25 @@ export class Assets {
134
139
  /** @internal A generated model or texture built from a palette that has since been written */
135
140
  _stale(e) { return !!e.promise && !!e.opts.build && e.type !== 'sound' && e.palette !== this._paletteKey; }
136
141
  /** @internal Load an entry as a task in engine.loading (assetEntry.js) */
137
- _fetch(e) { return fetchEntry(this, e); }
142
+ _fetch(e) { return this._with(e, v => v); }
143
+ /**
144
+ * @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
145
+ * continuations, and one of them may have released the entry since the load finished; handing out that value is a freed model
146
+ */
147
+ async _with(e, use, wait) {
148
+ for (;;) {
149
+ const v = await waitLoad(this, e, wait);
150
+ if (wait?.whole && e.fellBack) throw e.fellBack;
151
+ if (v === e.load?.value) return use(v, e.load);
152
+ }
153
+ }
154
+ /** @internal A model copy for a caller that cannot stand on a stand-in and may stop waiting: a failed file rejects whatever the manifest falls back to, and an aborted signal leaves the load (assetEntry.js) */
155
+ wholeModel(nameOrUrl, signal) {
156
+ const e = this._resolve(nameOrUrl, 'model');
157
+ return this._with(e, () => this._copy(e), { whole: true, signal });
158
+ }
159
+ /** @internal The entry moves on from its current load (assetEntry.js) */
160
+ _retire(e) { retireEntry(this, e); }
138
161
 
139
162
  /**
140
163
  * 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 +187,18 @@ export class Assets {
164
187
 
165
188
  /** Get a model copy (name or path); skinned characters clone correctly. static: true registers it with engine.rays (builds ray acceleration) */
166
189
  async model(nameOrUrl, opts = {}) {
167
- const e = this._resolve(nameOrUrl, 'model'), gltf = await this._fetch(e);
168
- return this._copy(e, gltf, opts);
190
+ const e = this._resolve(nameOrUrl, 'model');
191
+ return this._with(e, () => this._copy(e, opts));
192
+ }
193
+ /**
194
+ * 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
195
+ * 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.
196
+ * @example const tower = await engine.assets.lod('tower', { distances: [40, 120] }); engine.add(tower); tower.levels[1].object;
197
+ * @experimental
198
+ */
199
+ async lod(nameOrUrl, opts = {}) {
200
+ const { distances, hysteresis, ...copy } = opts;
201
+ return wrapLod(this, nameOrUrl, await this.model(nameOrUrl, copy), { distances, hysteresis });
169
202
  }
170
203
  /**
171
204
  * 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 +207,66 @@ export class Assets {
174
207
  */
175
208
  modelNow(nameOrUrl, opts = {}) {
176
209
  const e = this.entries.get(nameOrUrl);
177
- if (e?.type === 'model' && e.value && !this._stale(e)) return this._copy(e, e.value, opts);
210
+ if (e?.type === 'model' && e.load?.value && !this._stale(e)) return this._copy(e, opts);
178
211
  // 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
212
  // 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
213
  if (DEV && e?.type === 'model' && !e.promise) warnOnce(coded('asset-not-loaded', fmt(STRINGS.notLoaded, { name: nameOrUrl })));
181
214
  return null;
182
215
  }
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);
216
+ /**
217
+ * @internal For modules that hand out what they load, as content does for its models. Hold an asset's data until the handle's remove(): release and trim wait for the last lease, and so does a build replaced by a hot swap or a palette write. For a texture, sound or
218
+ * shared material a game keeps past its own scene. Model copies hold one each already, so nobody has to lease what they took from model(). A lease says "do not free this",
219
+ * it frees nothing by itself: the data stays cached until release or trim. Counts are in describe().assets.
220
+ * @example const lease = ctx.track(await engine.assets.lease('rock')); // in a module: ends with it
221
+ * @param {string} name a registered name, or a path already loaded
222
+ * @returns {Promise<{ name: string, remove(): void }>}
223
+ */
224
+ async lease(name) {
225
+ const e = this.entries.get(name);
226
+ if (!e) throw codedError('unknown-name', fmt(STRINGS.noLease, { name }));
227
+ return this._with(e, () => this._lease(e, name));
228
+ }
229
+ /** @internal the one place a lease is taken, and where describe().assets starts to report (only a game that holds something pays for the line) */
230
+ _lease(e, name) {
231
+ if (!this._reported) { this._reported = true; this.engine.describe?.add?.('assets', () => this._holders()); }
232
+ return takeLease(this, e, name);
233
+ }
234
+ /** @internal describe().assets: leases per name (a model copy is one) and the names whose release waits for them; both empty again means every lease came back */
235
+ _holders() {
236
+ const held = [...this.entries].filter(([, e]) => e.users > 0);
237
+ return { leases: Object.fromEntries(held.map(([k, e]) => [k, e.users])), waiting: held.filter(([, e]) => e.releasePending).map(([k]) => k) };
238
+ }
239
+ /** @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 */
240
+ _copy(e, { castShadow, receiveShadow, static: isStatic = false } = {}) {
241
+ const load = e.load, gltf = load.value, root = skeletonClone(gltf.scene);
242
+ this._instances.set(root, { e, load, lease: this._lease(e) });
187
243
  // the call, then the manifest entry; else a generator's own flags; else cast + receive (shadowDefaults, the same rule content props use)
188
244
  shadowDefaults(root, { castShadow: castShadow ?? e.opts.castShadow, receiveShadow: receiveShadow ?? e.opts.receiveShadow });
189
- root.userData.animations = gltf.animations;
245
+ 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
246
+ 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
247
  if (isStatic) this.engine.rays.addStatic(root);
191
248
  return root;
192
249
  }
193
250
  /**
194
251
  * Import report of a loaded model: materials, textures with their colorSpace, normal maps, clips, nodes, template / id nodes and col_ colliders,
195
252
  * 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)
253
+ * no clip) and for wrong color spaces. Pass a name (the loaded template) or a copy from model() (what the game shows).
197
254
  * @example console.table(engine.assets.report('hero').issues);
198
255
  * @param {string | any} nameOrRoot
199
256
  */
200
257
  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;
258
+ const root = typeof nameOrRoot === 'string' ? null : nameOrRoot, copy = root && this._instances.get(root);
259
+ const e = root ? copy?.e : this.entries.get(nameOrRoot), gltf = (root ? copy?.load : e?.load)?.value;
203
260
  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
261
  return reportGltf(gltf, e, root ?? gltf.scene, this.engine.renderer);
205
262
  }
206
- /** assets.report as text for the console / describe */
207
- reportText(nameOrRoot) { return reportText(this.report(nameOrRoot)); }
208
263
  /** Get the geometry of the first mesh in a model (for vegetation and bulk placement) */
209
264
  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;
265
+ return this._with(this._resolve(nameOrUrl, 'model'), (gltf, load) => {
266
+ load.pinned = true; // the geometry was handed out and we cannot know who still uses it: trim does not free it
267
+ let g = null; gltf.scene.traverse(o => { if (!g && o.isMesh) g = o.geometry; });
268
+ return g;
269
+ });
214
270
  }
215
271
  /**
216
272
  * Get a texture (name or path; .ktx2 works too). Color textures default to sRGB; pass { color: false } for normal/roughness maps.
@@ -225,7 +281,7 @@ export class Assets {
225
281
  if (!diff.length) return this._fetch(base);
226
282
  const key = nameOrUrl + '#' + JSON.stringify(Object.fromEntries(diff.sort().map(k => [k, opts[k]])));
227
283
  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 });
284
+ 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
285
  return this._fetch(v);
230
286
  }
231
287
 
@@ -244,7 +300,7 @@ export class Assets {
244
300
  */
245
301
  useTexture(nameOrUrl, use, { where = 'assets.useTexture', instead = 'the stand-in stays', opts } = {}) {
246
302
  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; });
303
+ err => { warnOnce(coded('asset-load', fmt(STRINGS.textureFailed, { where, name: nameOrUrl, msg: err?.message ?? String(err), instead }))); return false; });
248
304
  }
249
305
 
250
306
  /**
@@ -259,38 +315,52 @@ export class Assets {
259
315
  gridFromImage(nameOrUrl, opts = {}) { return loadGrid(this.entries.get(nameOrUrl)?.url ?? nameOrUrl, opts); }
260
316
 
261
317
  /**
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)
318
+ * Release an asset and return its memory (reloaded on next use). A texture is released together with all its opts variants.
319
+ * A sound (name or path) plays on where it is playing; its memory goes when it ends.
320
+ * 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).
321
+ * 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.
322
+ * 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).
323
+ * A model whose geometry was handed out (assets.geometry, a generator's prototype) stays: nothing can know who still draws it, as with trim.
264
324
  */
265
325
  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);
326
+ for (const [k, v] of this.entries) if (v.variantOf === name) {
327
+ 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
328
+ this.release(k);
329
+ if (!waited) this.entries.delete(k);
330
+ }
331
+ const e = this.entries.get(name); if (e && !e.load?.pinned) freeEntry(this, e);
268
332
  }
269
- /** Release every model with no copy in use (call after a level change; level calls it). Returns the names released */
333
+ /** 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
334
  trim() {
271
335
  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); }
336
+ for (const [k, e] of this.entries) if (e.type === 'model' ? e.value && !e.users && !e.load.pinned && !e.opts.preload : longSound(e) && !e.users) { freeEntry(this, e); freed.push(k); }
273
337
  return freed;
274
338
  }
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; }
339
+ /**
340
+ * 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
341
+ * 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
342
+ */
343
+ _users(name) { return this.entries.get(name)?.users ?? 0; }
277
344
  /** 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
345
  forget(obj) {
279
346
  obj.traverse(o => {
280
347
  const anim = this._animators.get(o); if (anim) { this._animators.delete(o); anim.dispose(); }
281
- const e = this._instances.get(o); if (!e) return;
348
+ const copy = this._instances.get(o); if (!copy) return;
282
349
  this._instances.delete(o);
283
- if (--e.users <= 0 && e.releasePending) freeEntry(e);
350
+ copy.lease.remove();
284
351
  });
285
352
  }
286
- /** Release all loaded assets and decoders (engine.dispose calls it) */
353
+ /**
354
+ * 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
355
+ * model() / texture() / font() call, stays pending for good: it never resumes against a disposed engine and never rejects during teardown
356
+ */
287
357
  dispose() {
288
- for (const e of this.entries.values()) { e.users = 0; freeEntry(e); }
358
+ disposeEntries(this);
289
359
  this.draco?.dispose(); this.ktx2?.dispose();
290
360
  }
291
361
 
292
362
  /**
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.
363
+ * @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
364
  * Code-generated model (build returns an Object3D or BufferGeometry): built once per name + params, returns a copy (geometry returns the same instance).
295
365
  * 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
366
  * Cache key = name + generator source + params: outer variables build uses (colors, sizes, seeds in the closure...) must go in params,
@@ -304,9 +374,12 @@ export class Assets {
304
374
  else this._cachedSrc.set(name, src);
305
375
  const key = 'cached:' + name + ':' + JSON.stringify(params ?? null) + ':' + this._paletteKey + ':' + srcHash(src);
306
376
  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);
377
+ // 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
378
+ // 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
379
+ return this._with(e, (g, load) => {
380
+ load.pinned = true;
381
+ return g.geometry ?? skeletonClone(g.scene);
382
+ });
310
383
  }
311
384
  /** Current usage: number of geometries and textures in GPU memory */
312
385
  get memory() { return memory(this.engine.renderer); }
@@ -318,17 +391,19 @@ export class Assets {
318
391
  * engine.assets.animate(await engine.assets.model('hero')).go('attack');
319
392
  */
320
393
  animate(root, config = {}) {
321
- const m = this.mapping(root), src = this._instances.get(root);
394
+ const m = this.mapping(root), src = this._instances.get(root)?.e;
322
395
  const cfg = m ? { ...m, ...config, states: { ...m.states, ...config.states }, transitions: { ...m.transitions, ...config.transitions } } : config;
323
396
  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
397
  this._animators.get(root)?.dispose(); // one animator per model: a new one replaces the old
325
398
  this._animators.set(root, a);
326
399
  return a;
327
400
  }
401
+ /** @internal the Animator animate() made for a model, or null (a ragdoll holds it while the model is limp) */
402
+ animatorOf(root) { return this._animators.get(root) ?? null; }
328
403
  /**
329
404
  * A model copy's manifest animation mapping ({ states, transitions, fade }), or null. Characters read it so default clip names never shadow it.
330
405
  * @example engine.assets.mapping(model)?.states.attack // { clip: 'Slash', loop: false }
331
406
  * @param {import('three').Object3D} root @returns {{ states?: object, transitions?: object, fade?: number } | null}
332
407
  */
333
- mapping(root) { return this._instances.get(root)?.opts.animation ?? null; }
408
+ mapping(root) { return this._instances.get(root)?.e.opts.animation ?? null; }
334
409
  }
@@ -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)) {