threedog 1.1.0 → 1.2.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 (363) hide show
  1. package/CHANGELOG.md +879 -798
  2. package/README.md +1 -1
  3. package/core/assets/Animator.js +41 -3
  4. package/core/assets/Assets.js +100 -24
  5. package/core/assets/assetEntry.js +73 -20
  6. package/core/assets/assetHot.js +68 -16
  7. package/core/assets/assetLoad.js +6 -6
  8. package/core/assets/assetLod.js +9 -2
  9. package/core/assets/assetManifest.js +12 -2
  10. package/core/assets/assetPart.js +54 -0
  11. package/core/assets/ik.js +271 -0
  12. package/core/assets/modelNeeds.js +37 -0
  13. package/core/assets/namedModel.js +102 -29
  14. package/core/assets/nodeVisibility.js +15 -0
  15. package/core/audio/Audio.js +36 -4
  16. package/core/audio/audioReverb.js +99 -0
  17. package/core/audio/audioRules.js +1 -1
  18. package/core/audio/audioVoice.js +1 -1
  19. package/core/base/Events.js +14 -4
  20. package/core/base/Random.js +1 -1
  21. package/core/base/Vars.js +1 -1
  22. package/core/base/docRef.js +51 -0
  23. package/core/base/errorCodes.js +178 -126
  24. package/core/base/errorHints.js +9 -7
  25. package/core/base/errors.js +25 -10
  26. package/core/base/events.generated.js +2 -0
  27. package/core/base/freeParts.js +76 -0
  28. package/core/base/math.js +28 -0
  29. package/core/base/sections.js +5 -5
  30. package/core/base/validate.js +31 -3
  31. package/core/engine/Engine.js +16 -6
  32. package/core/engine/Loading.js +5 -3
  33. package/core/engine/copies.js +1 -1
  34. package/core/engine/headlessLoad.js +4 -1
  35. package/core/engine/lifecycle.js +32 -16
  36. package/core/engine/loop.js +71 -27
  37. package/core/engine/moduleSlots.js +2 -2
  38. package/core/engine/moduleTypes.js +3 -3
  39. package/core/engine/modules.js +65 -39
  40. package/core/engine/page.js +6 -3
  41. package/core/engine/services.js +6 -5
  42. package/core/engine/startup.js +5 -5
  43. package/core/input/Input.js +28 -14
  44. package/core/input/inputContext.js +28 -16
  45. package/core/input/inputKeyboard.js +31 -3
  46. package/core/input/inputPad.js +4 -0
  47. package/core/input/inputPointer.js +2 -1
  48. package/core/input/inputSeat.js +1 -1
  49. package/core/inspect/Budget.js +109 -19
  50. package/core/inspect/DebugOverrides.js +28 -4
  51. package/core/inspect/Describe.js +17 -9
  52. package/core/inspect/Inspect.js +4 -2
  53. package/core/inspect/InspectMaterials.js +3 -1
  54. package/core/inspect/InspectPerf.js +19 -9
  55. package/core/inspect/InspectScene.js +32 -7
  56. package/core/inspect/MaterialInfo.js +19 -2
  57. package/core/inspect/UrlState.js +46 -27
  58. package/core/inspect/catalog.js +28 -9
  59. package/core/inspect/debugView.js +2 -1
  60. package/core/inspect/describeRender.js +25 -13
  61. package/core/inspect/describeText.js +14 -6
  62. package/core/inspect/lightWatch.js +1 -1
  63. package/core/inspect/metadata.generated.js +35 -17
  64. package/core/inspect/pictureChecks.js +148 -0
  65. package/core/inspect/pictureMenu.js +84 -0
  66. package/core/inspect/pictureWriters.js +26 -6
  67. package/core/inspect/textureBytes.js +12 -2
  68. package/core/inspect/toolDoor.js +2 -4
  69. package/core/ops/Ops.js +11 -4
  70. package/core/ops/holds.js +27 -10
  71. package/core/ops/opsAtomic.js +15 -7
  72. package/core/ops/opsGuard.js +2 -2
  73. package/core/ops/opsRun.js +8 -7
  74. package/core/ops/sharedPoint.js +72 -21
  75. package/core/ops/stacks.js +56 -16
  76. package/core/saves/SaveStore.js +9 -3
  77. package/core/saves/Saves.js +32 -23
  78. package/core/saves/saveApply.js +96 -44
  79. package/core/saves/saveIds.js +1 -1
  80. package/core/saves/saveVersions.js +7 -5
  81. package/core/saves/session.js +17 -8
  82. package/core/saves/stateReplace.js +34 -15
  83. package/core/scene/Rays.js +52 -10
  84. package/core/scene/Views.js +13 -7
  85. package/core/scene/adaptive.js +144 -21
  86. package/core/scene/drawOnly.js +17 -0
  87. package/core/scene/gameLights.js +44 -3
  88. package/core/scene/sceneMethods.js +13 -11
  89. package/core/scene/stepPoses.js +11 -3
  90. package/core/scene/targeting.js +5 -3
  91. package/core/scene/thingOps.js +1 -1
  92. package/core/scene/tier.js +15 -0
  93. package/core/stream/Batching.js +30 -7
  94. package/core/stream/Stream.js +26 -7
  95. package/core/stream/batchGroups.js +2 -2
  96. package/core/stream/chunkStream.js +7 -5
  97. package/core/stream/prepare.js +77 -0
  98. package/core/time/skip.js +3 -1
  99. package/core/time/time.js +4 -2
  100. package/docs/AI.md +82 -83
  101. package/docs/API.md +16 -16
  102. package/docs/CODEMAP.md +16 -11
  103. package/docs/COMMANDS.md +139 -142
  104. package/docs/CONVENTIONS.md +37 -49
  105. package/docs/MIGRATING-0.8.md +2 -2
  106. package/docs/MIGRATING-1.0.md +2 -2
  107. package/docs/THREE.md +28 -35
  108. package/docs/api/assets.md +3 -1
  109. package/docs/api/audio.md +4 -2
  110. package/docs/api/budget.md +5 -0
  111. package/docs/api/characters.md +10 -8
  112. package/docs/api/collision.md +6 -4
  113. package/docs/api/engine.md +16 -16
  114. package/docs/api/events.md +3 -2
  115. package/docs/api/ground.md +6 -5
  116. package/docs/api/hud.md +4 -2
  117. package/docs/api/input.md +5 -5
  118. package/docs/api/particles.md +2 -1
  119. package/docs/api/photo.md +3 -0
  120. package/docs/api/post.md +7 -4
  121. package/docs/api/quests.md +2 -2
  122. package/docs/api/rays.md +1 -2
  123. package/docs/api/saves.md +7 -7
  124. package/docs/api/settings.md +2 -2
  125. package/docs/api/tools.md +3 -1
  126. package/docs/api/vars.md +1 -1
  127. package/docs/api/vegetation.md +4 -2
  128. package/docs/api/world.md +1 -1
  129. package/docs/recipes/01-new-game.md +16 -17
  130. package/docs/recipes/02-npc.md +22 -18
  131. package/docs/recipes/03-items-pickups.md +37 -35
  132. package/docs/recipes/04-quests.md +15 -10
  133. package/docs/recipes/05-props-bake.md +101 -95
  134. package/docs/recipes/06-clock-events.md +28 -28
  135. package/docs/recipes/07-flow-scenes-pause.md +29 -26
  136. package/docs/recipes/08-weather-sky.md +52 -64
  137. package/docs/recipes/09-materials-lights-models.md +26 -17
  138. package/docs/recipes/10-blender-level.md +15 -10
  139. package/docs/recipes/11-vehicles.md +12 -7
  140. package/docs/recipes/12-navmesh.md +44 -26
  141. package/docs/recipes/13-animation.md +56 -45
  142. package/docs/recipes/14-custom-module.md +21 -18
  143. package/docs/recipes/15-perf.md +61 -55
  144. package/docs/recipes/16-dev-bridge.md +23 -33
  145. package/docs/recipes/18-world.md +36 -42
  146. package/docs/recipes/19-shooting-picking.md +20 -15
  147. package/docs/recipes/20-content-actions-save.md +48 -56
  148. package/docs/recipes/21-camera.md +45 -54
  149. package/docs/recipes/22-shop-gold.md +12 -7
  150. package/docs/recipes/23-ops.md +25 -23
  151. package/docs/recipes/26-ui-parts.md +67 -47
  152. package/docs/recipes/27-net.md +12 -7
  153. package/docs/recipes/28-terrain.md +24 -21
  154. package/docs/recipes/29-grid.md +32 -27
  155. package/docs/recipes/30-templates.md +21 -20
  156. package/docs/recipes/31-audio.md +39 -22
  157. package/docs/recipes/32-action-game.md +19 -14
  158. package/docs/recipes/33-stream-sources.md +15 -11
  159. package/docs/recipes/34-environment-lighting.md +126 -70
  160. package/docs/recipes/35-picture-from-reference.md +8 -8
  161. package/docs/recipes/36-ground-plants.md +27 -21
  162. package/docs/recipes/40-scene.md +19 -28
  163. package/docs/recipes/43-shader-patches-surfaces.md +15 -12
  164. package/docs/recipes/44-water-weather-hooks.md +34 -31
  165. package/docs/recipes/45-cascaded-shadows.md +35 -26
  166. package/docs/recipes/46-blender-art-route.md +6 -1
  167. package/docs/recipes/49-game-module-contract.md +13 -8
  168. package/docs/recipes/50-own-renderer.md +6 -2
  169. package/docs/recipes/51-capability-catalog.md +15 -8
  170. package/docs/recipes/52-around-the-picture.md +34 -32
  171. package/docs/recipes/53-ground-up-close.md +6 -1
  172. package/docs/recipes/55-mods-time-wrap.md +27 -19
  173. package/docs/recipes/56-webgpu-tsl.md +74 -43
  174. package/docs/recipes/57-control.md +18 -13
  175. package/docs/recipes/58-input.md +26 -16
  176. package/docs/recipes/59-depth-post-effects.md +8 -3
  177. package/docs/recipes/60-judge-the-picture.md +9 -8
  178. package/docs/recipes/61-deploy.md +5 -0
  179. package/docs/recipes/62-picture-code.md +70 -79
  180. package/docs/recipes/63-third-person-start.md +47 -45
  181. package/docs/recipes/64-particles.md +22 -10
  182. package/docs/recipes/65-swarm.md +18 -13
  183. package/docs/recipes/66-common-tasks.md +38 -35
  184. package/examples/action/GAMEMAP.md +2 -3
  185. package/examples/action/main.js +3 -3
  186. package/examples/action/picture/lights.js +3 -1
  187. package/examples/perf-island/GAMEMAP.md +3 -3
  188. package/examples/perf-island/picture/lights.js +2 -1
  189. package/examples/plain-picture/GAMEMAP.md +1 -1
  190. package/examples/rc2d/GAMEMAP.md +1 -1
  191. package/examples/styletest/GAMEMAP.md +2 -2
  192. package/examples/styletest/main.js +1 -1
  193. package/examples/techniques/interior-light/README.md +3 -3
  194. package/examples/techniques/interior-light/interiorLight.js +2 -4
  195. package/examples/techniques/interior-light/picture/lights.js +2 -1
  196. package/examples/techniques/modular-building/picture/lights.js +3 -1
  197. package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
  198. package/examples/techniques/procedural-animation/README.md +1 -1
  199. package/examples/techniques/procedural-animation/main.js +1 -1
  200. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  201. package/examples/world/GAMEMAP.md +2 -3
  202. package/examples/world/art/humanoid.js +1 -1
  203. package/examples/world/main.js +6 -3
  204. package/index.d.ts +2 -2
  205. package/llms.txt +101 -0
  206. package/modules/ambience/Ambience.js +21 -5
  207. package/modules/calendar/index.js +9 -5
  208. package/modules/calendar/schedule.js +23 -8
  209. package/modules/camera/FirstPersonCamera.js +3 -1
  210. package/modules/camera/FollowCamera.js +10 -5
  211. package/modules/camera/RtsCamera.js +4 -3
  212. package/modules/camera/common.js +70 -8
  213. package/modules/camera/contract.js +1 -1
  214. package/modules/characters/Character.js +16 -10
  215. package/modules/characters/NPC.js +31 -19
  216. package/modules/characters/assetModel.js +14 -9
  217. package/modules/characters/astar.js +6 -1
  218. package/modules/characters/contract.js +2 -2
  219. package/modules/characters/index.js +34 -22
  220. package/modules/characters/movers/manual.js +1 -1
  221. package/modules/characters/movers/rapier.js +17 -2
  222. package/modules/characters/movers/simple.js +1 -1
  223. package/modules/characters/movers/support.js +16 -7
  224. package/modules/characters/npcAvoid.js +2 -2
  225. package/modules/characters/npcSim.js +3 -2
  226. package/modules/characters/pathAsync.js +24 -8
  227. package/modules/characters/pathJob.js +1 -1
  228. package/modules/characters/player.js +10 -9
  229. package/modules/characters/playerStrings.js +5 -5
  230. package/modules/characters/proceduralRig.js +5 -5
  231. package/modules/characters/useModel.js +6 -0
  232. package/modules/characters/walkTo.js +1 -1
  233. package/modules/collision/Collision.js +29 -18
  234. package/modules/collision/grid.js +22 -4
  235. package/modules/content/index.js +3 -1
  236. package/modules/content/loader.js +1 -1
  237. package/modules/content/models.js +82 -33
  238. package/modules/content/props.js +2 -1
  239. package/modules/content/rules.js +11 -5
  240. package/modules/content/templates.js +3 -3
  241. package/modules/content/words.js +2 -2
  242. package/modules/debug/DebugPanel.js +9 -9
  243. package/modules/flow/index.js +9 -6
  244. package/modules/gameplay/Dialogue.js +34 -20
  245. package/modules/gameplay/Interactions.js +19 -15
  246. package/modules/gameplay/Inventory.js +9 -4
  247. package/modules/gameplay/Quests.js +12 -10
  248. package/modules/gameplay/pickups.js +23 -11
  249. package/modules/grid/index.js +1 -1
  250. package/modules/grid/preview.js +2 -2
  251. package/modules/grid/tiles.js +1 -1
  252. package/modules/hlod/index.js +4 -1
  253. package/modules/hud/index.js +47 -10
  254. package/modules/hud/parts.js +28 -9
  255. package/modules/level/geometry.js +8 -3
  256. package/modules/level/index.js +10 -5
  257. package/modules/level/load.js +4 -2
  258. package/modules/lights/sources.js +1 -1
  259. package/modules/music/Music.js +22 -4
  260. package/modules/nav/index.js +20 -10
  261. package/modules/particles/Particles.js +31 -14
  262. package/modules/particles/effect.js +20 -5
  263. package/modules/particles/lit.js +72 -0
  264. package/modules/photo/Photo.js +72 -28
  265. package/modules/photo/pathTrace.js +106 -0
  266. package/modules/rigid/RigidBodies.js +23 -14
  267. package/modules/rigid/Vehicles.js +3 -13
  268. package/modules/rigid/sync.js +2 -1
  269. package/modules/settings/Settings.js +52 -20
  270. package/modules/settings/apply.js +23 -9
  271. package/modules/settings/sections.js +39 -6
  272. package/modules/settings/strings.js +2 -0
  273. package/modules/settings/view.js +19 -3
  274. package/modules/sky/dome.js +15 -3
  275. package/modules/sky/environment.js +28 -12
  276. package/modules/sky/fog.js +1 -1
  277. package/modules/sky/frame.js +6 -1
  278. package/modules/sky/shader.js +4 -3
  279. package/modules/sky/skyModule.js +8 -4
  280. package/modules/swarm/Swarm.js +1 -1
  281. package/modules/terrain/ChunkManager.js +61 -15
  282. package/modules/terrain/chunkJob.js +2 -2
  283. package/modules/terrain/index.js +20 -5
  284. package/modules/terrain/terrainEdit.js +8 -4
  285. package/modules/terrain/terrainTexture.js +4 -2
  286. package/modules/timeline/Timeline.js +4 -3
  287. package/modules/timeline/Tween.js +3 -0
  288. package/modules/timeline/letterbox.js +1 -0
  289. package/modules/triggers/index.js +36 -17
  290. package/modules/vegetation/Vegetation.js +81 -19
  291. package/modules/vegetation/densityMap.js +13 -8
  292. package/modules/vegetation/draw.js +147 -24
  293. package/modules/vegetation/groundChunks.js +20 -5
  294. package/modules/vegetation/index.js +3 -3
  295. package/modules/vegetation/modelGeometry.js +9 -4
  296. package/modules/water/Water.js +11 -8
  297. package/modules/weather/Weather.js +7 -2
  298. package/modules/weather/shaders.js +25 -5
  299. package/modules/weather/weatherDraw.js +20 -6
  300. package/modules/world/World.js +2 -1
  301. package/modules/world/index.js +2 -2
  302. package/modules/world/persist.js +6 -2
  303. package/modules/world/views.js +15 -2
  304. package/package.json +4 -1
  305. package/presets.js +5 -5
  306. package/render/PostFX.js +84 -41
  307. package/render/backend.js +137 -16
  308. package/render/cascades.js +3 -1
  309. package/render/cascades.tsl.js +2 -0
  310. package/render/daylight.js +7 -1
  311. package/render/detail.js +7 -4
  312. package/render/effects.js +27 -8
  313. package/render/fogLook.js +24 -0
  314. package/render/fuse.js +5 -2
  315. package/render/fx/detail.tsl.js +9 -7
  316. package/render/fx/index.js +7 -2
  317. package/render/fx/library.tsl.js +1 -0
  318. package/render/fx/lightShaft.tsl.js +114 -0
  319. package/render/fx/noise.tsl.js +25 -8
  320. package/render/fx/objectOrigin.tsl.js +39 -10
  321. package/render/fx/particles.tsl.js +23 -6
  322. package/render/fx/patchNodes.tsl.js +17 -12
  323. package/render/fx/pcss.tsl.js +51 -0
  324. package/render/fx/postWebGPU.tsl.js +89 -29
  325. package/render/fx/sky.tsl.js +3 -9
  326. package/render/fxNumbers.js +10 -4
  327. package/render/impostor.tsl.js +107 -0
  328. package/render/lighting.js +33 -1
  329. package/render/lightmap.js +42 -28
  330. package/render/lights.js +19 -3
  331. package/render/materials.js +6 -4
  332. package/render/mergeCommon.js +4 -1
  333. package/render/occlusion.js +14 -4
  334. package/render/patches.js +79 -41
  335. package/render/postRuns.js +32 -0
  336. package/render/postWebGL.js +97 -10
  337. package/render/probes.js +10 -14
  338. package/render/shaderErrors.js +2 -1
  339. package/render/shadowCache.tsl.js +33 -5
  340. package/render/shadows.js +42 -16
  341. package/render/slots.js +8 -5
  342. package/render/vertexInputs.js +52 -0
  343. package/types/core.d.ts +114 -46
  344. package/types/gameplay.d.ts +56 -23
  345. package/types/generated/core/audio/Audio.d.ts +27 -1
  346. package/types/generated/core/base/Random.d.ts +1 -1
  347. package/types/generated/core/input/Input.d.ts +6 -8
  348. package/types/generated/core/input/inputSeat.d.ts +1 -1
  349. package/types/generated/core/inspect/Budget.d.ts +26 -0
  350. package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
  351. package/types/generated/core/saves/Saves.d.ts +10 -7
  352. package/types/generated/core/saves/session.d.ts +8 -2
  353. package/types/generated/core/scene/Rays.d.ts +1 -3
  354. package/types/generated/modules/particles/Particles.d.ts +1 -1
  355. package/types/generated/modules/world/World.d.ts +2 -1
  356. package/types/generated/render/PostFX.d.ts +35 -9
  357. package/types/physics.d.ts +796 -764
  358. package/types/pixel.d.ts +1 -1
  359. package/types/tsl.d.ts +62 -1
  360. package/types/world.d.ts +12 -3
  361. package/ui/Focus.js +7 -5
  362. package/ui/Parts.js +1 -1
  363. package/ui/touchPart.js +6 -3
@@ -10,12 +10,13 @@
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 } from './namedModel.js';
14
- import { clone as skeletonClone } from 'three/addons/utils/SkeletonUtils.js';
13
+ import { protoSlots, protoOf, dropProto, cachedModel } from './namedModel.js';
15
14
  import { list } from '../base/util.js';
16
15
  import { reportError } from '../base/errors.js';
17
16
  import { codedError } from '../base/errorHints.js';
18
- import { note } from '../base/validate.js';
17
+ import { note, warnOnce } from '../base/validate.js';
18
+ import { freeRetired } from './assetEntry.js';
19
+ import { partsOf, cloneModel } from '../base/freeParts.js';
19
20
 
20
21
  // a failed rebuild is reported (soft: the old copies stay on screen) and the swap goes on with the other names
21
22
  const failWith = e => (err, what) => reportError(e, err, `asset hot swap: ${what}`, { soft: true });
@@ -60,11 +61,13 @@ async function swapModels(e, changed, why = 'edit') {
60
61
  if (type === 'model' && neu) pair(old.value.scene, neu.scene, name);
61
62
  }
62
63
  // 2. cached builds (what content, pickups and vegetation got): drop them, build every name + params asked for so far again
63
- const oldCached = new Map();
64
+ const oldCached = new Map(), builds = [];
64
65
  for (const [k, ent] of [...a.entries]) {
65
66
  const n = k.startsWith('cached:') ? k.slice(7, k.indexOf(':', 7)) : null;
66
67
  if (n == null || !names.has(n)) continue;
67
68
  if (ent.value) oldCached.set(unhashed(k), ent.value);
69
+ // retired, not just dropped: the load is pinned (Assets.cached), so it waits in a._retired where dispose reaches it, and is freed below once nothing draws it
70
+ const load = ent.load; a._retire(ent); if (load?.settled) builds.push(load);
68
71
  a.entries.delete(k);
69
72
  }
70
73
  for (const n of names) a._cachedSrc?.delete(n); // a new source under the same name is not a name clash
@@ -75,13 +78,15 @@ async function swapModels(e, changed, why = 'edit') {
75
78
  const o = oldCached.get(unhashed(k)), name = k.slice(7, k.indexOf(':', 7));
76
79
  pair(o.geometry ?? o.scene, ent.value.geometry ?? ent.value.scene, name);
77
80
  }
78
- // 3. prototypes (content props / templates, pickups): a new prototype per old one; copies point at it from now on
79
- for (const { api, cache } of protoCaches(e)) for (const [key, p] of [...cache]) {
81
+ // 3. prototypes (content props / templates, pickups): a new prototype per old one, held by the same consumers; copies point at it from now on.
82
+ // The old one's lease goes back once the scene below no longer draws its parts (swapped), so trim and release can free the old file then
83
+ let swapped; const offScene = new Promise(r => { swapped = r; });
84
+ for (const [key, slot] of protoSlots(e)) {
80
85
  const model = JSON.parse(key), name = list(model)[0];
81
86
  if (!names.has(name)) continue;
82
- const old = await p.catch(() => null);
83
- cache.delete(key);
84
- const neu = await protoOf(e, api, model).catch(err => { fail(err, `model "${name}"`); return null; });
87
+ const old = await slot.promise.catch(() => null);
88
+ let next = null; for (const h of dropProto(e, key, offScene)) next = protoOf(e, h, model);
89
+ const neu = await next?.catch(err => { fail(err, `model "${name}"`); return null; });
85
90
  if (!old || !neu) continue;
86
91
  protoNew.set(old, neu);
87
92
  pair(old.obj, neu.obj, name);
@@ -91,17 +96,26 @@ async function swapModels(e, changed, why = 'edit') {
91
96
  const b = e.batching, batched = !!b?.enabled;
92
97
  if (batched) b.enabled = false;
93
98
  const count = n => { copies[n] = (copies[n] || 0) + 1; };
94
- const oldGeo = new Set(geo.keys());
99
+ const oldGeo = new Set(geo.keys()), moved = [];
95
100
  e.scene.traverse(o => {
96
101
  const ud = o.userData;
97
- if (ud?.proto && protoNew.has(ud.proto)) ud.proto = protoNew.get(ud.proto); // content copies: later aligns read the new size
102
+ // a model() copy whose parts do not pair 1:1 (2 parts became 1) is rebuilt whole from the new load, like the prototype copies below: never a mix of old and new parts
103
+ const rec = a._instances.get(o), whole = rec && structure.has(rec.e.name) ? a.entries.get(rec.e.name) : null;
104
+ if (whole?.load?.value) {
105
+ const was = new Set(); rec.load.value?.scene?.traverse(x => { for (const p of partsOf(x)) was.add(p); });
106
+ const known = new Set(); rec.load.value?.scene?.traverse(x => { if (x.name) known.add(x.name); });
107
+ rebuildCopy(a, o, rec.e.name, whole.load.value.scene, whole.load.value.animations, c => {
108
+ let old = false; c.traverse(x => { if (partsOf(x).some(p => was.has(p))) old = true; });
109
+ if (old) c.traverse(x => { if (x.name && !known.has(x.name)) warnOnce(`asset hot swap: the parts of "${rec.e.name}" changed, so its copies were rebuilt; objects you attached inside them ("${x.name}") were dropped. Attach them again in onModel`); });
110
+ return old;
111
+ }, count, fail);
112
+ }
113
+ // content copies: later aligns read the new size, measured once their parts are swapped below
114
+ if (ud?.proto && protoNew.has(ud.proto)) { ud.proto = protoNew.get(ud.proto); moved.push(ud); }
98
115
  // a model whose part count changed: the copy root stays (code holds it), its parts from the old prototype are replaced by the new ones
99
- if (ud?.modelKey && structure.has(list(JSON.parse(ud.modelKey))[0]) && !o.isMesh) {
116
+ if (ud?.modelKey && !whole?.load?.value && structure.has(list(JSON.parse(ud.modelKey))[0]) && !o.isMesh) { // not twice: a model() copy was rebuilt above
100
117
  const neu = [...protoNew.values()].find(p => p.obj.userData.modelKey === ud.modelKey);
101
- if (neu) {
102
- for (const c of [...o.children]) if (meshesOf(c).some(m => oldGeo.has(m.geometry))) o.remove(c);
103
- for (const c of [...skeletonClone(neu.obj).children]) { o.add(c); count(list(JSON.parse(ud.modelKey))[0]); } // a copy: add() takes c out of the live list
104
- }
118
+ if (neu) rebuildCopy(a, o, list(JSON.parse(ud.modelKey))[0], neu.obj, neu.obj.animations, c => meshesOf(c).some(m => oldGeo.has(m.geometry)), count, fail);
105
119
  }
106
120
  });
107
121
  const seenMat = new Set();
@@ -117,12 +131,33 @@ async function swapModels(e, changed, why = 'edit') {
117
131
  for (const k of Object.keys(m)) { const t = tex.get(m[k]); if (t) { m[k] = t.to; m.needsUpdate = true; count(t.name); } }
118
132
  }
119
133
  });
134
+ // Leases follow the data: every copy now draws only the new load (a copy whose parts do not pair 1:1 was rebuilt whole above), so its lease moves with it, at this moment
135
+ const stale = [];
136
+ e.scene.traverse(o => {
137
+ const rec = a._instances.get(o), lease = o.userData.lease;
138
+ const next = rec && names.has(rec.e.name) ? a.entries.get(rec.e.name) : null;
139
+ if (next?.load?.value && next.load !== rec.load) { a._instances.set(o, { ...rec, e: next, load: next.load, lease: a._lease(next, undefined, undefined, rec.lease.by) }); stale.push(rec.lease); }
140
+ const own = lease && names.has(lease.name) ? a.entries.get(lease.name) : null; // content props and pickups lease by name
141
+ if (own?.load?.value) { stale.push(lease); o.userData.lease = a._lease(own, lease.name, undefined, lease.by); }
142
+ });
143
+ // the copy as it stands now (what its setup added stays on it), by the rule content measures every build with: never the bare prototype
144
+ for (const ud of moved) ud.remeasure?.();
145
+ swapped();
146
+ for (const l of stale) l.remove();
120
147
  // 5. module hooks: vegetation rebuilds its species from the new models (its materials are patched copies, not found above)
121
148
  for (const fn of a._swapHooks ?? []) {
122
149
  try { const r = await fn({ names, geometry: geo, material: mat }); for (const [n, k] of Object.entries(r ?? {})) copies[n] = (copies[n] || 0) + k; }
123
150
  catch (err) { fail(err, "a module's own copies"); }
124
151
  }
125
152
  if (batched) b.enabled = true;
153
+ // the old generated builds: what no scene mesh draws any more goes now (a part something still draws, one the swap could not find, waits for dispose)
154
+ if (builds.length) {
155
+ const drawn = new Set(); e.scene.traverse(o => { for (const x of partsOf(o)) drawn.add(x); });
156
+ for (const load of builds) {
157
+ let used = false; load.value?.scene?.traverse(o => { if (partsOf(o).some(x => drawn.has(x))) used = true; });
158
+ if (!used) freeRetired(a, load);
159
+ }
160
+ }
126
161
 
127
162
  const report = {
128
163
  why, names: [...new Set(changed.map(c => c.name))], copies, ms: Math.round(performance.now() - t0), // measure
@@ -133,6 +168,23 @@ async function swapModels(e, changed, why = 'edit') {
133
168
  return report;
134
169
  }
135
170
 
171
+ /**
172
+ * The one rebuild of a copy whose parts changed (model() copies, content props, pickups): the old parts go through dropCopy (leases, cloned bones, instance buffers),
173
+ * the new ones are cloned (cloneModel), and the same steps a first build runs follow: the game's onModel setup (the copy root is the same object) and the static rays.
174
+ * An Animator drives the old skeleton: it is stopped, and unless the setup made a new one the game animates again (one dev warning). Why not rebind: a Character
175
+ * holds that Animator object and its hooks, and hot reload is a dev aid, so the simplest rule that is never wrong wins.
176
+ */
177
+ function rebuildCopy(a, o, name, fresh, clips, isOld, count, fail) {
178
+ const was = a.animatorOf(o);
179
+ if (was) { was.dispose(); a._animators.delete(o); }
180
+ for (const c of [...o.children]) if (isOld(c)) { o.remove(c); a.dropCopy(c); }
181
+ for (const c of [...cloneModel(fresh).children]) { o.add(c); count(name); } // a copy: add() takes c out of the live list
182
+ o.animations = clips;
183
+ try { a._setup?.(o, name); } catch (err) { fail(err, `onModel for "${name}"`); }
184
+ a.restatic(o);
185
+ if (was && !a.animatorOf(o)) warnOnce(`asset hot swap: "${name}" has new parts, so its animation was stopped (it drove the old skeleton). Call assets.animate() on the copy again, or reload the page`);
186
+ }
187
+
136
188
  /** Keep the last swaps for describe().assetSwaps, say it in the console and as a toast (dev aid: the AI and the person both see it) */
137
189
  function remember(e, r) {
138
190
  const a = e.assets;
@@ -3,6 +3,7 @@
3
3
  // (a texture / .bin that 404s), so "the model looks gray" is traceable to one path instead of a bare "failed".
4
4
  import { coded } from '../base/errorHints.js';
5
5
  import * as THREE from 'three';
6
+ import { texturesOf } from '../stream/prepare.js';
6
7
  import { restoreBaked, toGLB, fromGLTF } from './Baked.js';
7
8
  import { warnOnce, DEV_SERVER, BASE_URL, fmt } from '../base/validate.js';
8
9
  import { neutralMaterial } from '../../render/neutral.js';
@@ -88,9 +89,7 @@ export async function loadGltf(assets, url, task) {
88
89
  if (task.signal.aborted) return gltf;
89
90
  await noteFailedTextures(gltf, missing);
90
91
  task.source.animations = gltf.animations.map(a => a.name);
91
- const tex = new Set();
92
- gltf.scene.traverse(o => { for (const m of [].concat(o.material || [])) for (const k in m) if (m[k]?.isTexture) tex.add(m[k]); });
93
- upload(assets, tex, task);
92
+ upload(assets, texturesOf(gltf.scene), task);
94
93
  return gltf;
95
94
  }
96
95
 
@@ -248,7 +247,8 @@ export async function generated(assets, name, build, params, task) {
248
247
  toGLB(v, name).then(buf => fetch(CACHE + info.key + '.glb', { method: 'PUT', body: buf })).catch(err => warnOnce(coded('asset-cache', '[cache] could not store a built model in .threedog/cache (' + err.message + '); it is built again next time')));
249
248
  return wrap(v);
250
249
  }
251
- /** Bake manifest public/models/baked/index.json (empty if missing) */
252
- function bakedIndex(assets) {
253
- return assets._baked ||= fetch(BASE + 'models/baked/index.json').then(r => (r.ok ? r.text() : '{}')).then(t => { try { return JSON.parse(t); } catch { return {}; } }, () => ({}));
250
+ /** Bake manifest public/models/baked/index.json (empty if missing: a 404 means nothing was baked; any other failure or a malformed file is said once) */
251
+ export function bakedIndex(assets) {
252
+ const bad = why => { warnOnce(coded('asset-cache', `[assets] the bake manifest models/baked/index.json could not be used (${why}); baked models are ignored and built again`)); return {}; };
253
+ return assets._baked ||= fetch(BASE + 'models/baked/index.json').then(r => (r.ok ? r.text() : r.status === 404 ? '{}' : bad('HTTP ' + r.status))).then(t => { try { const m = typeof t === 'string' ? JSON.parse(t) : t; return m && typeof m === 'object' && !Array.isArray(m) ? m : bad('the top level is not an object: ' + String(t).slice(0, 20)); } catch (e) { return bad(e.message); } }, e => bad(e.message));
254
254
  }
@@ -78,7 +78,11 @@ function readDistances(d) {
78
78
  * Wrap one copy of a model. scale: what the copy will be scaled by, so default distances follow its size on screen.
79
79
  * @param {any} a the Assets instance @param {string} name @param {THREE.Object3D} full @returns {Promise<THREE.LOD>}
80
80
  */
81
- export async function wrapLod(a, name, full, { distances, hysteresis = HYSTERESIS, scale = 1 } = {}) {
81
+ export async function wrapLod(a, name, full, opts = {}) {
82
+ // `full` is the caller's already (a lease, a clone's bones): a LOD that cannot be made gives it back, so a rejected call leaves nothing counted
83
+ try { return await assemble(a, name, full, opts); } catch (err) { a.dropCopy(full); throw err; }
84
+ }
85
+ async function assemble(a, name, full, { distances, hysteresis = HYSTERESIS, scale = 1 } = {}) {
82
86
  const asked = readDistances(distances), e = a.entries.get(name), lod = new THREE.LOD();
83
87
  lod.name = full.name;
84
88
  Object.assign(lod.userData, { batch: false, ...(full.userData.modelName && { modelName: full.userData.modelName }) });
@@ -92,7 +96,10 @@ export async function wrapLod(a, name, full, { distances, hysteresis = HYSTERESI
92
96
  if (DEV && e?.lodCopies === MANY_COPIES) warnOnce(coded('asset-lod', `assets.lod('${name}'): ${MANY_COPIES} copies, and a LOD object is never batched, so each one is its own draw calls. Check engine.batching is not the better fit: drop lod for this model and compare describe().perf`));
93
97
  const fullMeshes = meshesOf(full);
94
98
  const size = new THREE.Box3().setFromObject(full).getSize(new THREE.Vector3()).length() * scale;
95
- const copies = await Promise.all(urls.map(u => a.model(u)));
99
+ // allSettled: one level failing to load must not strand the others that did (each holds a lease)
100
+ const got = await Promise.allSettled(urls.map(u => a._bare(u, {}, 'lod'))), failed = got.find(r => r.status === 'rejected');
101
+ if (failed) { for (const r of got) if (r.status === 'fulfilled') a.dropCopy(r.value); throw failed.reason; }
102
+ const copies = got.map(r => r.value); // bare: a level is part of the LOD, which is what gets the onModel setup
96
103
  copies.forEach((copy, i) => {
97
104
  const low = meshesOf(copy), at = asked ? asked[i] : size * FIRST_LENGTHS * STEP ** i;
98
105
  // a level built from another version of the model, or more levels than the game gave distances: leave it out rather than draw the wrong material on it
@@ -2,10 +2,12 @@
2
2
  import { fmt, warnOnce, BASE_URL } from '../base/validate.js';
3
3
  import { codedError } from '../base/errorHints.js';
4
4
  import { parseSchema, readParams, keysSchema } from '../base/params.js';
5
+ import { readNeeds } from './modelNeeds.js';
5
6
 
6
7
  const STRINGS = {
7
8
  clash: 'assets.manifest(): "{name}" is already registered as a {was} (manifest "{list}"), and now as a {type}; one name is one asset, ' +
8
9
  'so the second would replace the first. Rename one, e.g. {name}_{type}',
10
+ node: 'assets.manifest() models.{name}: node names one node of a file, so it needs the file as a url and a node name as a string, e.g. { url: \'/models/kit.glb\', node: \'Wall.001\' } (no build)',
9
11
  replaced: 'assets.manifest(): {type} "{name}" from manifest "{was}" is replaced by manifest "{list}" (the later one wins). If both packs mean their own asset, rename one; '
10
12
  + 'if the override is intended (a mod replacing a model), ignore this',
11
13
  };
@@ -13,6 +15,9 @@ const STRINGS = {
13
15
  const MANIFEST_KEYS = ['name', 'base', 'models', 'textures', 'sounds', 'fonts'];
14
16
  /** Keys of one fonts entry: the file, the CSS family it registers (default: the asset name), FontFace descriptors, and the usual asset flags */
15
17
  const FONT_KEYS = ['url', 'family', 'weight', 'style', 'stretch', 'unicodeRange', 'display', 'featureSettings', 'variationSettings', 'critical', 'preload'];
18
+ /** What the 'optimized' pack replaces in an entry: the file (so a generator or Texture it replaces goes too: build is checked before url). Everything else stays the game's */
19
+ const FILE_KEYS = new Set(['url', 'lods', 'node', 'build', 'texture']);
20
+ const without = (o, keys) => Object.fromEntries(Object.entries(o).filter(([k]) => !keys.has(k)));
16
21
 
17
22
  /**
18
23
  * hot: { changed: [] } = a dev hot swap (core/assets/assetHot.js) registering the edited packs again: an entry whose build function (or Texture) and url are unchanged
@@ -33,12 +38,17 @@ export function registerManifest(a, pack, hot = null) {
33
38
  for (const [name, v] of Object.entries(map)) {
34
39
  const o0 = typeof v === 'string' ? { url: v } : typeof v === 'function' ? { build: v } : v?.isTexture && type === 'texture' ? { texture: v } : v;
35
40
  if (type === 'font') readParams(`assets.manifest() fonts.${name}`, keysSchema(FONT_KEYS), o0);
36
- const o = o0.url ? { ...o0, url: resolve(o0.url), ...(o0.lods && { lods: o0.lods.map(resolve) }) } : o0;
41
+ if (type === 'model' && o0.node != null && (typeof o0.url !== 'string' || typeof o0.node !== 'string' || o0.build)) throw codedError('asset-misuse', fmt(STRINGS.node, { name }));
42
+ if (type === 'model' && o0.needs != null) readNeeds(`models.${name}`, o0.needs); // a typo'd key or a non-list fails here, naming the entry
37
43
  const old = a.entries.get(name);
44
+ // the 'optimized' pack (`threedog assets optimize`) swaps the file only: url, lods and a part's node. The game's other options (needs,
45
+ // prepare, params, ...) stay, since that pack is written as JSON and cannot carry them
46
+ const o1 = list === 'optimized' && old?.named && old.type === type ? { ...without(old.opts, FILE_KEYS), ...o0 } : o0;
47
+ const o = o1.url ? { ...o1, url: resolve(o1.url), ...(o1.lods && { lods: o1.lods.map(resolve) }) } : o1;
38
48
  // a model's params is a schema (core/base/params.js format, parsed here so a bad spec fails at registration, naming the field)
39
49
  const schema = type === 'model' && o.params ? parseSchema(`assets.manifest() models.${name}.params`, o.params) : null;
40
50
  if (hot && old?.named && old.type === type) {
41
- if (old.opts.build === o.build && old.opts.texture === o.texture && old.url === (o.url ?? name) && JSON.stringify(old.opts.params ?? null) === JSON.stringify(o.params ?? null)) continue;
51
+ if (old.opts.build === o.build && old.opts.texture === o.texture && old.opts.node === o.node && old.url === (o.url ?? name) && JSON.stringify(old.opts.params ?? null) === JSON.stringify(o.params ?? null)) continue;
42
52
  const was = { ...old }; // the swap pairs the old data with the new
43
53
  a._retire(old);
44
54
  Object.assign(old, { url: o.url ?? name, opts: o, schema });
@@ -0,0 +1,54 @@
1
+ // One node of a multi-part file as its own model (manifest models: { wall: { url: '/models/kit.glb', node: 'Wall.001' } }), helper of assetEntry.js.
2
+ // The file is loaded once, as the entry of its path (what assets.model('/models/kit.glb') reads too), and each part holds a lease on it: the part's
3
+ // geometry and materials are the file's, so freeing a part only gives that lease back, and the file goes when nothing holds it.
4
+ import * as THREE from 'three';
5
+ import { clone as skeletonClone } from 'three/addons/utils/SkeletonUtils.js';
6
+ import { sanitize, closest } from '../base/spelling.js';
7
+ import { fmt } from '../base/validate.js';
8
+ import { LoadError } from './assetLoad.js';
9
+
10
+ const MISSING = 'no node "{node}" in {url}{near}. three renames nodes on load: a dot, colon, slash or bracket is dropped ("Wall.001" is Wall001), a space becomes _, '
11
+ + 'and a second node of the same name gets _1, _2 ("Fence", "Fence_1"); either spelling works here. Nodes in the file: {list}';
12
+ const BONES = 'node "{node}" in {url} holds a skinned mesh whose bones are outside it, so a copy would have no skeleton. Name the node that holds both the mesh and its armature';
13
+
14
+ /**
15
+ * The part of a loaded gltf: the named node in a group of its own, at the origin. Why the world turn and size are kept and only the place is dropped:
16
+ * a kit lays its parts out side by side (the place), while the turn and size are how the part should look, often set on a parent (a Z-up root turned
17
+ * -90 degrees about x, a scaled root). A wrapper group, so content's rot / scale on the copy root add to that turn instead of replacing it.
18
+ * Geometry and materials are shared with the file (SkeletonUtils clone: a skinned part gets its own bones); the file's scene is not changed.
19
+ * @returns {{ scene: THREE.Group, animations: THREE.AnimationClip[] }}
20
+ */
21
+ export function partOf(gltf, node, url) {
22
+ const all = [];
23
+ gltf.scene.traverse(o => { if (o !== gltf.scene && o.name) all.push(o.name); });
24
+ const name = all.includes(node) ? node : sanitize(node);
25
+ const src = all.includes(name) ? gltf.scene.getObjectByName(name) : null;
26
+ if (!src) {
27
+ const near = closest(sanitize(node), all);
28
+ const list = all.slice(0, 20).join(', ') + (all.length > 20 ? `, ... (${all.length})` : '');
29
+ throw new LoadError(fmt(MISSING, { node, url, near: near ? ` (did you mean "${near}"?)` : '', list }), { url });
30
+ }
31
+ const inside = new Set();
32
+ src.traverse(o => inside.add(o));
33
+ src.traverse(o => { if (o.isSkinnedMesh && o.skeleton.bones.some(b => !inside.has(b))) throw new LoadError(fmt(BONES, { node, url }), { url }); });
34
+ src.updateWorldMatrix(true, false);
35
+ const part = skeletonClone(src), p = new THREE.Vector3();
36
+ src.matrixWorld.decompose(p, part.quaternion, part.scale);
37
+ part.position.set(0, 0, 0);
38
+ // a node hidden in the file (KHR_node_visibility, nodeVisibility.js) is still shown when a manifest names it: a kit keeps its spare parts hidden. Hidden nodes inside it stay hidden
39
+ part.visible = true;
40
+ const scene = new THREE.Group();
41
+ scene.name = name;
42
+ scene.add(part);
43
+ // clips that move something inside the part; the rest name nodes this model does not have
44
+ const names = new Set([...inside].map(o => o.name));
45
+ const animations = gltf.animations.filter(c => c.tracks.some(t => names.has(THREE.PropertyBinding.parseTrackName(t.name).nodeName)));
46
+ return { scene, animations };
47
+ }
48
+
49
+ /** The load of a part entry: wait for the file's own entry, take the part and a lease on the file (released by freeValue, assetEntry.js) */
50
+ export function loadPart(a, e, task) {
51
+ task.phase('download');
52
+ const file = a._resolve(e.url, 'model');
53
+ return a._with(file, g => ({ ...partOf(g, e.opts.node, e.url), fileLease: a._lease(file, undefined, undefined, `file part ${e.name}`) }));
54
+ }
@@ -0,0 +1,271 @@
1
+ // Inverse kinematics as the Animator's last layer: bones that aim at a target (a head turning to look) and feet that stand on the ground (stairs, slopes).
2
+ // const look = anim.addAim({ bones: ['Neck', 'Head'], target: engine.player.root, limit: 70 }); look.set({ target: null }); look.remove();
3
+ // const feet = anim.addFeet(); // legs found by name; feet.set({ weight: 0 }) fades it out
4
+ // Why inside the Animator and not a second per-frame hook: a bone's pose has one owner. The order each frame is: put back the pose IK found last frame
5
+ // (a bone no clip keys would otherwise add the IK turn to itself every frame) -> the mixer -> remember this pose -> each IK layer in the order added
6
+ // -> onPose. Weight 0 therefore leaves exactly the animation pose, and remove() puts it back at once.
7
+ // Why only positions and the bind pose, never a bone axis: every rig points its bones another way (+Y along the bone in Blender exports, +X in others),
8
+ // so the head's "forward" is the model's forward read in the head's bind frame, and the legs bend in the plane the animation already bends them in.
9
+ // The ground is the Animator's ground query (engine.surface; a Character hands over its own, platforms included, characters/useModel.js): no second raycast path.
10
+ import * as THREE from 'three';
11
+ import { readParams, keysSchema } from '../base/params.js';
12
+ import { codedError } from '../base/errorHints.js';
13
+ import { missingText } from '../base/validate.js';
14
+
15
+ const AIM_KEYS = ['bones', 'target', 'limit', 'speed', 'weight', 'fade', 'forward'];
16
+ const FEET_KEYS = ['legs', 'hips', 'reach', 'far', 'speed', 'weight', 'fade', 'ground'];
17
+ const UP = new THREE.Vector3(0, 1, 0), Z = new THREE.Vector3(0, 0, 1), DEG = Math.PI / 180, EPS = 1e-6;
18
+ const _a = new THREE.Vector3(), _b = new THREE.Vector3(), _c = new THREE.Vector3(), _t = new THREE.Vector3(), _d = new THREE.Vector3(), _e = new THREE.Vector3();
19
+ const _ax0 = new THREE.Vector3(), _ax1 = new THREE.Vector3(), _p = new THREE.Vector3();
20
+ const _q = new THREE.Quaternion(), _q1 = new THREE.Quaternion(), _q2 = new THREE.Quaternion(), _q3 = new THREE.Quaternion(), _q4 = new THREE.Quaternion();
21
+ const _m = new THREE.Matrix4(), _m2 = new THREE.Matrix4(), _s = new THREE.Vector3();
22
+ const clamp1 = v => Math.max(-1, Math.min(1, v));
23
+ const angle = (u, v) => Math.acos(clamp1(u.dot(v)));
24
+
25
+ /** World rotation of an object from its matrixWorld (the caller keeps it current) */
26
+ function wq(o, out) { o.matrixWorld.decompose(_p, out, _s); return out; }
27
+ /** Give o the world rotation q (its parent's matrixWorld is current) */
28
+ function setWq(o, q) { o.quaternion.copy(o.parent ? wq(o.parent, _q4).invert().multiply(q) : q); }
29
+
30
+ /** A bone (any Object3D) by name; the name as written in Blender ('Foot.L') also finds the glTF one ('FootL', three drops the dots) */
31
+ function boneOf(root, name, where) {
32
+ const b = root.getObjectByName(name) ?? root.getObjectByName(THREE.PropertyBinding.sanitizeNodeName(name));
33
+ if (b) return b;
34
+ const names = []; root.traverse(o => { if (o.isBone) names.push(o.name); });
35
+ throw codedError('engine-misuse', `${where}: ${missingText('bone', name, names)}`);
36
+ }
37
+
38
+ /**
39
+ * The two-bone answer (D. Holden, "Simple Two Joint IK"): world rotations for the upper and the middle joint that put the end c at t.
40
+ * a, b, c: joint positions now; pole: where the middle joint bends when the chain is straight. Writes rUpper (applied to the upper joint, carries
41
+ * everything below it) and rMid (applied to the middle joint in the pose before rUpper). Reaches as close as the bone lengths allow.
42
+ * A chain with a zero-length part (joints on top of each other, a scaled-to-zero leg) has no triangle: both stay identity, never NaN.
43
+ */
44
+ export function twoBone(a, b, c, t, pole, rUpper, rMid) {
45
+ const lab = _d.subVectors(b, a).length(), lcb = _e.subVectors(b, c).length();
46
+ rUpper.identity(); rMid.identity();
47
+ if (lab < 1e-5 || lcb < 1e-5 || _a.subVectors(c, a).lengthSq() < 1e-10 || _t.subVectors(t, a).lengthSq() < 1e-10) return rUpper;
48
+ const lat = Math.max(EPS, Math.min(_t.subVectors(t, a).length(), lab + lcb - 1e-4));
49
+ const ac = _a.subVectors(c, a).normalize(), ab = _d.subVectors(b, a).normalize(), at = _t.subVectors(t, a).normalize();
50
+ const ba = _b.subVectors(a, b).normalize(), bc = _e.subVectors(c, b).normalize();
51
+ const acab0 = angle(ac, ab), babc0 = angle(ba, bc), acat0 = angle(ac, at);
52
+ const acab1 = Math.acos(clamp1((lcb * lcb - lab * lab - lat * lat) / (-2 * lab * lat)));
53
+ const babc1 = Math.acos(clamp1((lat * lat - lab * lab - lcb * lcb) / (-2 * lab * lcb)));
54
+ // the plane the chain bends in now; a straight chain has none, so the pole gives it
55
+ _ax0.crossVectors(ac, ab); if (_ax0.lengthSq() < 1e-8) _ax0.crossVectors(ac, pole);
56
+ if (_ax0.lengthSq() < 1e-8) _ax0.crossVectors(ac, Math.abs(ac.y) > 0.9 ? Z : UP);
57
+ _ax0.normalize();
58
+ rMid.setFromAxisAngle(_ax0, babc1 - babc0);
59
+ _q1.setFromAxisAngle(_ax0, acab1 - acab0);
60
+ _ax1.crossVectors(ac, at);
61
+ // no swing plane: the target lies along the chain (no swing) or straight opposite it (half a turn, about the bend axis, which is across the chain)
62
+ if (_ax1.lengthSq() < 1e-10) _ax1.copy(_ax0); else _ax1.normalize();
63
+ if (acat0 < 1e-6) rUpper.copy(_q1);
64
+ else rUpper.setFromAxisAngle(_ax1, acat0).multiply(_q1); // bend first, then swing the bent chain onto the target
65
+ return rUpper;
66
+ }
67
+
68
+ /** Rotate unit vector v toward unit vector to by at most max radians (in place) */
69
+ function turnToward(v, to, max) {
70
+ const ang = angle(v, to);
71
+ if (ang <= max || ang < EPS) return v.copy(to);
72
+ const axis = _ax1.crossVectors(v, to);
73
+ if (axis.lengthSq() < 1e-10) axis.copy(Math.abs(v.y) > 0.9 ? Z : UP).cross(v); // opposite: any axis across v
74
+ return v.applyQuaternion(_q3.setFromAxisAngle(axis.normalize(), max));
75
+ }
76
+
77
+ /** Where a target is (Object3D, Vector3, [x, y, z] or { x, y, z }) into out; null when there is none */
78
+ function targetAt(tg, out) {
79
+ if (tg == null) return null;
80
+ if (tg.isObject3D) return tg.getWorldPosition(out);
81
+ if (Array.isArray(tg)) return out.set(tg[0], tg[1], tg[2]);
82
+ return out.set(tg.x, tg.y ?? 0, tg.z);
83
+ }
84
+ function checkTarget(where, tg) {
85
+ const ok = tg == null || tg.isObject3D || (Array.isArray(tg) && tg.length === 3 && tg.every(Number.isFinite)) || (Number.isFinite(tg.x) && Number.isFinite(tg.z));
86
+ if (!ok) throw codedError('engine-misuse', `${where}: target is an Object3D, a Vector3, [x, y, z] or null (look ahead again), got ${JSON.stringify(tg) ?? typeof tg}`);
87
+ }
88
+ const nonNeg = (where, k, v) => { if (v !== undefined && !(Number.isFinite(v) && v >= 0)) throw codedError('engine-misuse', `${where}: ${k} is a number >= 0, got ${JSON.stringify(v)}`); };
89
+
90
+ /** The model's forward (+Z of the animated root) in the bone's bind frame: the bind pose is the model standing as built, facing forward */
91
+ function bindForward(root, bone) {
92
+ let mesh = null;
93
+ root.traverse(o => { if (!mesh && o.isSkinnedMesh && o.skeleton.bones.includes(bone)) mesh = o; });
94
+ root.updateWorldMatrix(true, true);
95
+ const fwd = Z.clone().applyQuaternion(wq(root, _q)); // world
96
+ if (!mesh) return fwd.applyQuaternion(wq(bone, _q).invert()); // plain Object3D parts: the pose they have now
97
+ const i = mesh.skeleton.bones.indexOf(bone);
98
+ // bone's bind rotation in mesh space, and the model's forward in mesh space (the mesh does not move against the root)
99
+ // bindMatrix, not bindMatrixInverse: in the default 'attached' mode three refreshes the inverse from the mesh's current matrixWorld every frame
100
+ _m.copy(mesh.skeleton.boneInverses[i]).invert().premultiply(_m2.copy(mesh.bindMatrix).invert()).decompose(_p, _q1, _s);
101
+ fwd.applyQuaternion(wq(mesh, _q2).invert());
102
+ return fwd.applyQuaternion(_q1.invert()).normalize();
103
+ }
104
+
105
+ /** Ease a shown weight toward its goal over fade seconds */
106
+ function fadeWeight(l, goal, dt) {
107
+ const r = l.fade > 0 ? dt / l.fade : 1;
108
+ l.w = l.w < goal ? Math.min(goal, l.w + r) : Math.max(goal, l.w - r);
109
+ }
110
+
111
+ function aimLayer(anim, opts) {
112
+ const where = 'anim.addAim()', o = readParams(where, keysSchema(AIM_KEYS), opts);
113
+ const names = [o.bones].flat().filter(Boolean);
114
+ if (!names.length) throw codedError('engine-misuse', `${where}: bones is the bone that turns ('Head') or a chain from the body out (['Neck', 'Head']), got ${JSON.stringify(o.bones)}`);
115
+ const bones = names.map(n => boneOf(anim.root, n, where)), tip = bones[bones.length - 1];
116
+ if (o.forward !== undefined && !(Array.isArray(o.forward) && o.forward.length === 3 && o.forward.every(Number.isFinite))) throw codedError('engine-misuse', `${where}: forward is the last bone's own axis it looks along, [x, y, z]; leave it out to read it from the bind pose`);
117
+ const l = { kind: 'aim', names, bones, writes: bones, w: 0, target: null, limit: 70, speed: 360, weight: 1, fade: 0.25, cur: null,
118
+ fwd: o.forward ? new THREE.Vector3().fromArray(o.forward).normalize() : bindForward(anim.root, tip) };
119
+ l.set = p => {
120
+ const s = readParams('aim.set()', keysSchema(AIM_KEYS.filter(k => k !== 'bones' && k !== 'forward')), p);
121
+ if (p && 'target' in p) { checkTarget('aim.set()', s.target); l.target = s.target; } // the raw options: set({ weight }) keeps the target
122
+ for (const k of ['limit', 'speed', 'weight', 'fade']) if (s[k] !== undefined) { nonNeg('aim.set()', k, s[k]); l[k] = k === 'weight' ? Math.min(1, s[k]) : s[k]; }
123
+ };
124
+ l.set({ target: o.target, limit: o.limit, speed: o.speed, weight: o.weight, fade: o.fade });
125
+ l.run = dt => {
126
+ const T = targetAt(l.target, _c);
127
+ fadeWeight(l, T ? l.weight : 0, dt);
128
+ const D0 = _a.copy(l.fwd).applyQuaternion(wq(tip, _q)).normalize(); // where the animation points it
129
+ if (l.w <= 0) { l.cur = null; return; }
130
+ l.cur ??= D0.clone();
131
+ // the wanted direction, inside the limit around the animated one; the shown one turns toward it at speed (a lost target keeps it, the weight fades)
132
+ if (T) turnToward(l.cur, turnToward(_b.copy(D0), T.sub(tip.getWorldPosition(_d)).normalize(), l.limit * DEG), l.speed * DEG * dt);
133
+ l.cur.copy(turnToward(_t.copy(D0), l.cur, l.limit * DEG)); // the body turned since: still inside the limit
134
+ const F = turnToward(_d.copy(D0), l.cur, angle(D0, l.cur) * l.w); // the weight blends from the animation
135
+ // spread the turn over the chain: bone i takes 1 / (bones left) of what is left; a direction turns by the same rotation about any pivot
136
+ for (let i = 0; i < bones.length; i++) {
137
+ const b = bones[i], now = _e.copy(l.fwd).applyQuaternion(wq(tip, _q)).normalize();
138
+ _q1.setFromUnitVectors(now, F);
139
+ _q2.identity().slerp(_q1, 1 / (bones.length - i));
140
+ setWq(b, _q2.multiply(wq(b, _q3)));
141
+ b.updateWorldMatrix(false, true);
142
+ }
143
+ };
144
+ return l;
145
+ }
146
+
147
+ /** Left / right from a bone name: Left, Foot_L, L_Foot, FootL (glTF drops the dot of Foot.L) */
148
+ function sideOf(n) {
149
+ if (/left/i.test(n) || /(^|[^a-z])l([^a-z]|$)/i.test(n) || /[a-z]L$/.test(n)) return 'L';
150
+ if (/right/i.test(n) || /(^|[^a-z])r([^a-z]|$)/i.test(n) || /[a-z]R$/.test(n)) return 'R';
151
+ return null;
152
+ }
153
+ const FOOT = /foot/i, NOT_FOOT = /toe|end|ball|ik|target|pole|step/i, KNEE = /lower.?leg|lowleg|shin|calf|knee/i, BODY = /root|hips|pelvis|armature|body/i;
154
+
155
+ /** Each leg as [upper, lower, foot]: given by name, or found (a foot bone per side; its parent and grandparent, or the side's lower leg when the foot hangs elsewhere) */
156
+ function findLegs(root, legs, where) {
157
+ if (legs) {
158
+ if (!Array.isArray(legs) || !legs.length || legs.some(l => !Array.isArray(l) || l.length !== 3)) throw codedError('engine-misuse', `${where}: legs is a list of [upper, lower, foot] bone names, e.g. [['UpperLeg.L', 'LowerLeg.L', 'Foot.L'], ['UpperLeg.R', 'LowerLeg.R', 'Foot.R']]`);
159
+ return legs.map(l => l.map(n => boneOf(root, n, where)));
160
+ }
161
+ const bones = []; root.traverse(o => { if (o.isBone) bones.push(o); });
162
+ const out = [];
163
+ for (const side of ['L', 'R']) {
164
+ const foot = bones.find(b => FOOT.test(b.name) && !NOT_FOOT.test(b.name) && sideOf(b.name) === side);
165
+ if (!foot) continue;
166
+ let lower = foot.parent, upper = lower?.parent;
167
+ if (!lower?.isBone || BODY.test(lower.name) || !upper?.isBone) { lower = bones.find(b => KNEE.test(b.name) && sideOf(b.name) === side); upper = lower?.parent; }
168
+ if (lower && upper?.isBone) out.push([upper, lower, foot]);
169
+ }
170
+ if (out.length < 2) throw codedError('engine-misuse', `${where}: could not tell the legs from the bone names (${bones.map(b => b.name).join(', ') || 'no bones'}); name them: legs: [['<upper leg>', '<lower leg>', '<foot>'], ...]`);
171
+ return out;
172
+ }
173
+
174
+ function feetLayer(anim, opts) {
175
+ const where = 'anim.addFeet()', o = readParams(where, keysSchema(FEET_KEYS), opts);
176
+ const legs = findLegs(anim.root, o.legs, where).map(([upper, lower, foot]) => ({ upper, lower, foot, off: 0, cl: new THREE.Vector3(), fp: new THREE.Vector3(), fq: new THREE.Quaternion() }));
177
+ // the hips lower the whole body when one foot must reach down: the leg tops' common parent unless named
178
+ const hips = o.hips ? boneOf(anim.root, o.hips, where) : legs.every(l => l.upper.parent === legs[0].upper.parent) ? legs[0].upper.parent : null;
179
+ const writes = legs.flatMap(g => [g.upper, g.lower, g.foot]).concat(hips && hips !== anim.root ? [hips] : []);
180
+ const l = { kind: 'feet', names: legs.map(g => g.foot.name), writes, legs, hips: writes.includes(hips) ? hips : null, w: 0, drop: 0,
181
+ reach: 0.5, far: 30, speed: 12, weight: 1, fade: 0.25, ground: o.ground ?? null };
182
+ l.set = p => {
183
+ const s = readParams('feet.set()', keysSchema(FEET_KEYS.filter(k => k !== 'legs' && k !== 'hips')), p);
184
+ for (const k of ['reach', 'far', 'speed', 'weight', 'fade']) if (s[k] !== undefined) { nonNeg('feet.set()', k, s[k]); l[k] = k === 'weight' ? Math.min(1, s[k]) : s[k]; }
185
+ if (s.ground !== undefined) {
186
+ if (typeof s.ground !== 'function') throw codedError('engine-misuse', `${where}: ground is (x, z, y) => height; leave it out to use the model's own ground (engine.surface, a Character's supports)`);
187
+ l.ground = s.ground;
188
+ }
189
+ };
190
+ l.set({ reach: o.reach, far: o.far, speed: o.speed, weight: o.weight, fade: o.fade, ground: o.ground });
191
+ // preallocated: this runs per character per frame (joint positions handed to twoBone must not be its own scratch vectors)
192
+ const pole = new THREE.Vector3(), rU = new THREE.Quaternion(), rM = new THREE.Quaternion(), ja = new THREE.Vector3(), jb = new THREE.Vector3(), jc = new THREE.Vector3(), jt = new THREE.Vector3();
193
+ l.run = dt => {
194
+ const root = anim.root, cam = anim.engine.camera, base = root.getWorldPosition(_b).y;
195
+ // off at once, before any ground query: hidden, far from the camera (nobody sees the feet), or not standing (a Character jumping or swimming);
196
+ // fading over the cached corrections would still bend legs in the air
197
+ if (!root.visible || (cam && cam.position.distanceTo(_b) > l.far) || !anim._standing()) { l.w = 0; l.drop = 0; for (const g of legs) g.off = 0; return; }
198
+ fadeWeight(l, l.weight, dt);
199
+ if (l.w <= 0) { l.drop = 0; for (const g of legs) g.off = 0; return; }
200
+ const ground = l.ground ?? anim._ground, k = dt > 0 ? 1 - Math.exp(-l.speed * dt) : 0;
201
+ let low = 0;
202
+ for (const g of legs) {
203
+ g.foot.getWorldPosition(g.fp); wq(g.foot, g.fq);
204
+ g.cl.copy(g.fp); g.lower.worldToLocal(g.cl); // the ankle rides with the lower leg, also when the foot bone hangs elsewhere
205
+ const off = ground(g.fp.x, g.fp.z, base) - base;
206
+ g.off += ((Number.isFinite(off) && Math.abs(off) <= l.reach ? off : 0) - g.off) * k; // smoothed: an edge under the foot does not pop
207
+ low = Math.min(low, g.off);
208
+ }
209
+ l.drop += (low - l.drop) * k;
210
+ if (l.hips && l.drop < 0) {
211
+ const h = l.hips; h.getWorldPosition(_t); _t.y += l.drop * l.w;
212
+ h.position.copy(h.parent ? h.parent.worldToLocal(_t) : _t); h.updateWorldMatrix(false, true);
213
+ }
214
+ pole.copy(Z).applyQuaternion(wq(root, _q)); // knees bend toward the model's front when a leg is straight
215
+ for (const g of legs) {
216
+ jt.copy(g.fp); jt.y += g.off * l.w;
217
+ twoBone(g.upper.getWorldPosition(ja), g.lower.getWorldPosition(jb), jc.copy(g.cl).applyMatrix4(g.lower.matrixWorld), jt, pole, rU, rM);
218
+ setWq(g.lower, rM.multiply(wq(g.lower, _q))); g.lower.updateWorldMatrix(false, false);
219
+ setWq(g.upper, rU.multiply(wq(g.upper, _q))); g.upper.updateWorldMatrix(false, true);
220
+ // the foot keeps the animation's world rotation and sits on the new ankle
221
+ g.lower.localToWorld(_t.copy(g.cl));
222
+ g.foot.position.copy(g.foot.parent ? g.foot.parent.worldToLocal(_t) : _t); setWq(g.foot, g.fq); g.foot.updateWorldMatrix(false, true);
223
+ }
224
+ };
225
+ return l;
226
+ }
227
+
228
+ /** @internal Add a layer to the Animator: remember the bones it writes (the pose put back every frame), start the frame hook a clip-less model lacks */
229
+ function addLayer(anim, l) {
230
+ anim._ik.push(l);
231
+ for (const b of l.writes) { const s = anim._ikPose.get(b); if (s) s.n++; else anim._ikPose.set(b, { q: b.quaternion.clone(), p: b.position.clone(), n: 1 }); }
232
+ anim._needHook();
233
+ return {
234
+ set(p) { if (anim._ik.includes(l)) l.set(p); return this; }, // a removed or disposed layer: nothing to set
235
+ remove() {
236
+ const i = anim._ik.indexOf(l); if (i < 0) return;
237
+ anim._ik.splice(i, 1);
238
+ // a ragdoll owns the bones now: forget them, write nothing. Otherwise the pose before IK, and the layers left are laid on it again at once,
239
+ // so a bone two layers share keeps the other one's turn (no frame without it)
240
+ if (!anim._held) ikRestore(anim);
241
+ for (const b of l.writes) { const s = anim._ikPose.get(b); if (--s.n <= 0) anim._ikPose.delete(b); }
242
+ if (!anim._held && anim._ik.length) solve(anim, 0);
243
+ if (!anim._ik.length && !anim.hasClips) anim._dropHook(); // a clip-less model needed the frame hook only for IK
244
+ },
245
+ describe() { return { kind: l.kind, bones: l.names, weight: Math.round(l.w * 1000) / 1000 }; },
246
+ };
247
+ }
248
+
249
+ /** @internal anim.addAim / anim.addFeet */
250
+ export const addAim = (anim, opts) => addLayer(anim, aimLayer(anim, opts));
251
+ export const addFeet = (anim, opts) => addLayer(anim, feetLayer(anim, opts));
252
+ /** @internal Before the mixer: the pose before last frame's IK (a bone no clip keys keeps its own pose, not last frame's turn) */
253
+ export function ikRestore(anim) { for (const [b, s] of anim._ikPose) { b.quaternion.copy(s.q); b.position.copy(s.p); } }
254
+ /** @internal After the mixer: remember this pose, then run each layer in the order added */
255
+ export function ikRun(anim, dt) {
256
+ for (const [b, s] of anim._ikPose) { s.q.copy(b.quaternion); s.p.copy(b.position); }
257
+ solve(anim, dt);
258
+ }
259
+ /** Each layer on the current pose; dt 0 recomposes without moving any smoothing on */
260
+ function solve(anim, dt) {
261
+ anim.root.updateWorldMatrix(true, true);
262
+ for (const l of anim._ik) l.run(dt);
263
+ }
264
+ /**
265
+ * @internal The Animator is disposed or replaced: the pose before IK goes back (a bone no clip keys would keep the turn, and the next Animator
266
+ * of this model would start from it), every layer ends and its handle does nothing
267
+ */
268
+ export function ikClear(anim) {
269
+ if (!anim._held) ikRestore(anim);
270
+ anim._ik.length = 0; anim._ikPose.clear();
271
+ }
@@ -0,0 +1,37 @@
1
+ // A model's `needs`: the parts (nodes) and animation clips a game relies on, declared in the manifest entry and checked against the file.
2
+ // models: { hero: { url: '/models/hero.glb', needs: { nodes: ['Hand_R'], clips: ['Idle', 'Run'] } } }
3
+ // One reader for both checkers: `threedog assets check` (static, the glb on disk) and the load (the parsed scene) both hand their names to needsProblems.
4
+ // Why: a re-export that drops a node or a clip passes every build and breaks at runtime, far from the file.
5
+ import { readParams, keysSchema } from '../base/params.js';
6
+ import { codedError } from '../base/errorHints.js';
7
+ import { sanitize, closest } from '../base/spelling.js';
8
+
9
+ const KEYS = ['nodes', 'clips'];
10
+
11
+ /** Registration-time read of a `needs` declaration: unknown keys throw like any option, the lists must be arrays of names. Returns { nodes, clips } */
12
+ export function readNeeds(where, needs) {
13
+ const o = readParams(`assets.manifest() ${where}.needs`, keysSchema(KEYS), needs);
14
+ for (const k of KEYS) if (o[k] != null && (!Array.isArray(o[k]) || o[k].some(n => typeof n !== 'string'))) {
15
+ throw codedError('module-params', `assets.manifest() ${where}.needs.${k} is a list of names, e.g. needs: { ${k}: ['${k === 'nodes' ? 'Hand_R' : 'Idle'}'] }`);
16
+ }
17
+ return { nodes: o.nodes ?? [], clips: o.clips ?? [] };
18
+ }
19
+
20
+ /**
21
+ * What a file lacks of its declaration: [{ kind: 'node' | 'clip', name, near }] (near = the closest name the file has, or null).
22
+ * Node names compare the way the loader spells them (a dot, colon or bracket dropped, a space becomes _: the same rule as the { url, node } entry); clip names compare as written.
23
+ * @param {{ nodes?: string[], clips?: string[] }} needs @param {{ nodes: string[], clips: string[] }} have names present in the file
24
+ * @returns {{ kind: 'node' | 'clip', name: string, near: string | null }[]}
25
+ */
26
+ export function needsProblems(needs, have) {
27
+ const out = [], nodes = new Set(have.nodes.map(sanitize)), clips = new Set(have.clips);
28
+ for (const n of needs.nodes ?? []) if (!nodes.has(sanitize(n))) out.push({ kind: 'node', name: n, near: closest(sanitize(n), [...nodes]) ?? null });
29
+ for (const c of needs.clips ?? []) if (!clips.has(c)) out.push({ kind: 'clip', name: c, near: closest(c, [...clips]) ?? null });
30
+ return out;
31
+ }
32
+
33
+ /** One line for a game or the CLI: model name, what is missing, the closest name that exists */
34
+ export function needsText(model, url, problems) {
35
+ const list = problems.map(p => `${p.kind} "${p.name}"${p.near ? ` (closest in the file: "${p.near}")` : ''}`).join(', ');
36
+ return `model "${model}" (${url}) is missing what its manifest entry needs: ${list}. The file was re-exported without it, or the name changed; restore it in the model, or update needs in the manifest`;
37
+ }