threedog 0.8.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 (372) hide show
  1. package/CHANGELOG.md +219 -4
  2. package/README.md +6 -6
  3. package/core/assets/Animator.js +2 -0
  4. package/core/assets/Assets.js +44 -13
  5. package/core/assets/assetEntry.js +87 -22
  6. package/core/assets/assetHot.js +2 -1
  7. package/core/assets/assetReport.js +1 -2
  8. package/core/audio/Audio.js +24 -5
  9. package/core/base/I18n.js +6 -3
  10. package/core/base/Random.js +3 -1
  11. package/core/base/Vars.js +14 -4
  12. package/core/base/errorCodes.js +54 -16
  13. package/core/base/errorHints.js +12 -1
  14. package/core/base/errors.js +6 -4
  15. package/core/base/events.generated.js +10 -0
  16. package/core/base/follows.js +26 -0
  17. package/core/base/math.js +15 -8
  18. package/core/base/params.js +2 -2
  19. package/core/{saves → base}/saveValues.js +24 -6
  20. package/core/base/sections.js +97 -0
  21. package/core/base/spelling.js +32 -0
  22. package/core/base/validate.js +8 -29
  23. package/core/engine/Engine.js +61 -18
  24. package/core/engine/Loading.js +30 -3
  25. package/core/engine/copies.js +1 -1
  26. package/core/engine/headlessLoad.js +30 -13
  27. package/core/engine/lifecycle.js +30 -25
  28. package/core/engine/loop.js +22 -4
  29. package/core/engine/moduleSlots.js +91 -15
  30. package/core/engine/moduleTypes.js +13 -0
  31. package/core/engine/modules.js +248 -62
  32. package/core/engine/page.js +25 -8
  33. package/core/engine/plugins.js +15 -3
  34. package/core/engine/services.js +3 -0
  35. package/core/engine/startup.js +46 -36
  36. package/core/input/Input.js +39 -19
  37. package/core/input/inputKeyboard.js +39 -0
  38. package/core/input/inputPad.js +23 -2
  39. package/core/input/inputPointer.js +3 -1
  40. package/core/input/inputSeat.js +66 -0
  41. package/core/input/inputTouch.js +23 -6
  42. package/core/inspect/DebugOverrides.js +13 -2
  43. package/core/inspect/Describe.js +10 -6
  44. package/core/inspect/Inspect.js +31 -4
  45. package/core/inspect/UrlState.js +14 -10
  46. package/core/inspect/catalog.js +12 -5
  47. package/core/inspect/describeRender.js +3 -2
  48. package/core/inspect/describeText.js +6 -2
  49. package/core/inspect/metadata.generated.js +4140 -0
  50. package/core/inspect/pictureWriters.js +117 -33
  51. package/core/inspect/toolDoor.js +21 -0
  52. package/core/inspect/valueHistory.js +35 -0
  53. package/core/ops/Ops.js +32 -7
  54. package/core/ops/control.js +48 -23
  55. package/core/ops/holds.js +4 -3
  56. package/core/ops/opsAtomic.js +18 -6
  57. package/core/ops/opsCheck.js +7 -5
  58. package/core/ops/opsFail.js +5 -7
  59. package/core/ops/opsRun.js +2 -2
  60. package/core/ops/owned.js +20 -3
  61. package/core/ops/sharedPoint.js +7 -10
  62. package/core/ops/stacks.js +22 -1
  63. package/core/saves/SaveStore.js +52 -26
  64. package/core/saves/Saves.js +122 -27
  65. package/core/saves/saveApply.js +159 -61
  66. package/core/saves/saveFiles.js +30 -25
  67. package/core/saves/saveVersions.js +20 -6
  68. package/core/saves/session.js +76 -33
  69. package/core/saves/stateReplace.js +184 -0
  70. package/core/scene/Rays.js +21 -5
  71. package/core/scene/Views.js +6 -6
  72. package/core/scene/adaptive.js +13 -10
  73. package/core/scene/canvasBox.js +2 -0
  74. package/core/scene/compositeGround.js +72 -0
  75. package/core/scene/floor.js +17 -0
  76. package/core/scene/grid.js +2 -0
  77. package/core/scene/ground.contract.js +14 -0
  78. package/core/scene/ground.js +52 -17
  79. package/core/scene/pixel.js +154 -0
  80. package/core/scene/pixelRatio.js +167 -0
  81. package/core/scene/sceneDelta.js +3 -3
  82. package/core/scene/sceneMethods.js +11 -6
  83. package/core/scene/stepPoses.js +6 -1
  84. package/core/scene/thingExplain.js +1 -1
  85. package/core/scene/thingOps.js +22 -14
  86. package/core/scene/things.js +1 -1
  87. package/core/scene/tier.js +10 -0
  88. package/core/scene/view.js +126 -9
  89. package/core/stream/Batching.js +0 -1
  90. package/core/stream/Stream.js +24 -12
  91. package/core/stream/batchGroups.js +1 -0
  92. package/core/stream/scatter.js +5 -2
  93. package/core/stream/streamSources.js +2 -1
  94. package/core/threads/Commits.js +12 -7
  95. package/core/threads/Jobs.js +15 -5
  96. package/core/threads/Threads.js +5 -2
  97. package/core/time/Clock.js +3 -1
  98. package/core/time/skip.js +10 -4
  99. package/core/time/time.js +16 -10
  100. package/docs/AI.md +89 -72
  101. package/docs/API.md +18 -14
  102. package/docs/CODEMAP.md +68 -40
  103. package/docs/COMMANDS.md +22 -23
  104. package/docs/CONVENTIONS.md +120 -17
  105. package/docs/MIGRATING-0.8.md +2 -0
  106. package/docs/MIGRATING-1.0.md +101 -0
  107. package/docs/THREE.md +65 -12
  108. package/docs/api/cameraRig.md +3 -0
  109. package/docs/api/characters.md +13 -7
  110. package/docs/api/collider3d.md +9 -0
  111. package/docs/api/content.md +16 -15
  112. package/docs/api/dialogue.md +2 -1
  113. package/docs/api/engine.md +18 -16
  114. package/docs/api/events.md +14 -4
  115. package/docs/api/ground.md +2 -2
  116. package/docs/api/i18n.md +1 -1
  117. package/docs/api/input.md +2 -1
  118. package/docs/api/interactions.md +1 -1
  119. package/docs/api/inventory.md +1 -1
  120. package/docs/api/level.md +3 -2
  121. package/docs/api/nav.md +4 -2
  122. package/docs/api/particles.md +8 -5
  123. package/docs/api/pickups.md +1 -1
  124. package/docs/api/post.md +3 -4
  125. package/docs/api/quests.md +4 -2
  126. package/docs/api/rays.md +2 -0
  127. package/docs/api/rigid.md +3 -2
  128. package/docs/api/saves.md +8 -7
  129. package/docs/api/stream.md +4 -5
  130. package/docs/api/terrain.md +3 -4
  131. package/docs/api/terrainDraw.md +1 -1
  132. package/docs/api/timeline.md +2 -2
  133. package/docs/api/tools.md +3 -1
  134. package/docs/api/triggers.md +2 -0
  135. package/docs/api/vegetationDraw.md +1 -1
  136. package/docs/api/water.md +6 -2
  137. package/docs/api/weather.md +19 -4
  138. package/docs/api/weatherDraw.md +1 -1
  139. package/docs/api/world.md +1 -1
  140. package/docs/recipes/01-new-game.md +3 -3
  141. package/docs/recipes/02-npc.md +3 -4
  142. package/docs/recipes/03-items-pickups.md +11 -11
  143. package/docs/recipes/04-quests.md +2 -0
  144. package/docs/recipes/05-props-bake.md +9 -9
  145. package/docs/recipes/06-clock-events.md +6 -6
  146. package/docs/recipes/07-flow-scenes-pause.md +18 -15
  147. package/docs/recipes/08-weather-sky.md +5 -5
  148. package/docs/recipes/09-materials-lights-models.md +3 -3
  149. package/docs/recipes/10-blender-level.md +16 -4
  150. package/docs/recipes/11-vehicles.md +18 -6
  151. package/docs/recipes/12-navmesh.md +52 -8
  152. package/docs/recipes/13-animation.md +34 -8
  153. package/docs/recipes/14-custom-module.md +20 -8
  154. package/docs/recipes/15-perf.md +4 -4
  155. package/docs/recipes/16-dev-bridge.md +9 -8
  156. package/docs/recipes/18-world.md +13 -5
  157. package/docs/recipes/19-shooting-picking.md +3 -2
  158. package/docs/recipes/20-content-actions-save.md +26 -6
  159. package/docs/recipes/21-camera.md +17 -23
  160. package/docs/recipes/22-shop-gold.md +21 -12
  161. package/docs/recipes/23-ops.md +19 -15
  162. package/docs/recipes/26-ui-parts.md +3 -2
  163. package/docs/recipes/27-net.md +3 -3
  164. package/docs/recipes/28-terrain.md +3 -3
  165. package/docs/recipes/29-grid.md +1 -1
  166. package/docs/recipes/30-templates.md +10 -13
  167. package/docs/recipes/31-audio.md +2 -2
  168. package/docs/recipes/32-action-game.md +6 -5
  169. package/docs/recipes/33-stream-sources.md +4 -1
  170. package/docs/recipes/34-environment-lighting.md +7 -8
  171. package/docs/recipes/35-picture-from-reference.md +13 -9
  172. package/docs/recipes/36-ground-plants.md +3 -2
  173. package/docs/recipes/40-scene.md +11 -10
  174. package/docs/recipes/43-shader-patches-surfaces.md +7 -7
  175. package/docs/recipes/44-water-weather-hooks.md +9 -8
  176. package/docs/recipes/45-cascaded-shadows.md +3 -4
  177. package/docs/recipes/46-blender-art-route.md +3 -3
  178. package/docs/recipes/49-game-module-contract.md +2 -1
  179. package/docs/recipes/50-own-renderer.md +1 -0
  180. package/docs/recipes/51-capability-catalog.md +14 -8
  181. package/docs/recipes/52-around-the-picture.md +4 -4
  182. package/docs/recipes/55-mods-time-wrap.md +5 -4
  183. package/docs/recipes/56-webgpu-tsl.md +12 -1
  184. package/docs/recipes/57-control.md +30 -10
  185. package/docs/recipes/58-input.md +13 -0
  186. package/docs/recipes/60-judge-the-picture.md +1 -1
  187. package/docs/recipes/62-picture-code.md +106 -48
  188. package/docs/recipes/63-third-person-start.md +2 -1
  189. package/docs/recipes/64-particles.md +53 -4
  190. package/docs/recipes/65-swarm.md +2 -2
  191. package/docs/recipes/66-common-tasks.md +313 -0
  192. package/examples/action/.threedog/content-index.json +1 -1
  193. package/examples/action/GAMEMAP.md +3 -3
  194. package/examples/perf-island/.threedog/content-index.json +1 -1
  195. package/examples/perf-island/GAMEMAP.md +3 -3
  196. package/examples/perf-island/main.js +2 -2
  197. package/examples/plain-picture/GAMEMAP.md +3 -1
  198. package/examples/rc2d/GAMEMAP.md +1 -1
  199. package/examples/rc2d/rc2d.js +1 -1
  200. package/examples/styletest/.threedog/content-index.json +1 -1
  201. package/examples/styletest/GAMEMAP.md +3 -3
  202. package/examples/webgpu-tsl/GAMEMAP.md +1 -1
  203. package/examples/world/.threedog/content-index.json +1 -1
  204. package/examples/world/GAMEMAP.md +5 -4
  205. package/examples/world/main.js +3 -3
  206. package/index.d.ts +8 -5
  207. package/index.js +22 -1
  208. package/llms.txt +2 -1
  209. package/modules/ambience/Ambience.js +5 -3
  210. package/modules/calendar/index.js +7 -5
  211. package/modules/camera/FirstPersonCamera.js +3 -3
  212. package/modules/camera/FixedCamera.js +34 -20
  213. package/modules/camera/FollowCamera.js +20 -11
  214. package/modules/camera/RtsCamera.js +1 -0
  215. package/modules/camera/common.js +33 -22
  216. package/modules/camera/pixelSnap.js +62 -0
  217. package/modules/characters/Character.js +136 -43
  218. package/modules/characters/NPC.js +60 -28
  219. package/modules/characters/assetModel.js +2 -2
  220. package/modules/characters/astar.js +47 -28
  221. package/modules/characters/character.contract.js +21 -0
  222. package/modules/characters/contract.js +17 -3
  223. package/modules/characters/index.js +94 -34
  224. package/modules/characters/moveHelpers.js +80 -15
  225. package/modules/characters/mover.contract.js +14 -0
  226. package/modules/characters/movers/common.js +6 -4
  227. package/modules/characters/movers/rapier.js +12 -5
  228. package/modules/characters/movers/simple.js +25 -12
  229. package/modules/characters/movers/support.js +18 -7
  230. package/modules/characters/npcAvoid.js +15 -12
  231. package/modules/characters/npcSim.js +75 -25
  232. package/modules/characters/npcView.js +13 -6
  233. package/modules/characters/pathAsync.js +74 -24
  234. package/modules/characters/pathJob.js +38 -21
  235. package/modules/characters/player.js +59 -47
  236. package/modules/characters/seat.js +56 -0
  237. package/modules/characters/vehicle.contract.js +8 -5
  238. package/modules/characters/walkTo.js +31 -18
  239. package/modules/collision/Collision.js +44 -26
  240. package/modules/collision/contract.js +2 -2
  241. package/modules/collision/grid.js +6 -1
  242. package/modules/content/explain.js +1 -1
  243. package/modules/content/fields.js +3 -3
  244. package/modules/content/ids.js +3 -1
  245. package/modules/content/index.js +83 -27
  246. package/modules/content/loader.js +110 -130
  247. package/modules/content/markers.js +1 -1
  248. package/modules/content/models.js +48 -14
  249. package/modules/content/packs.js +2 -1
  250. package/modules/content/places.js +5 -4
  251. package/modules/content/props.js +8 -6
  252. package/modules/content/rules.js +29 -47
  253. package/modules/content/templates.js +66 -35
  254. package/modules/content/words.js +19 -6
  255. package/modules/debug/DebugPanel.js +4 -2
  256. package/modules/flow/contract.js +1 -0
  257. package/modules/flow/index.js +24 -14
  258. package/modules/gameplay/Container.js +5 -2
  259. package/modules/gameplay/Containers.js +9 -1
  260. package/modules/gameplay/Dialogue.js +82 -25
  261. package/modules/gameplay/Interactions.js +61 -32
  262. package/modules/gameplay/Inventory.js +56 -13
  263. package/modules/gameplay/Quests.js +133 -24
  264. package/modules/gameplay/boxOps.js +7 -0
  265. package/modules/gameplay/dialogueBubbles.js +14 -9
  266. package/modules/gameplay/inventoryOps.js +11 -7
  267. package/modules/gameplay/pickups.js +43 -16
  268. package/modules/gameplay/questLog.js +4 -2
  269. package/modules/gameplay/questSave.js +6 -1
  270. package/modules/gameplay/quests.contract.js +1 -1
  271. package/modules/grid/Grid.js +1 -1
  272. package/modules/grid/Layer.js +8 -4
  273. package/modules/grid/index.js +21 -15
  274. package/modules/grid/ops.js +43 -46
  275. package/modules/grid/tiles.js +1 -1
  276. package/modules/hlod/index.js +6 -3
  277. package/modules/hud/index.js +6 -4
  278. package/modules/hud/parts.js +4 -4
  279. package/modules/level/contract.js +2 -2
  280. package/modules/level/heightfield.js +17 -21
  281. package/modules/level/index.js +83 -26
  282. package/modules/level/load.js +165 -48
  283. package/modules/level/nodes.js +34 -16
  284. package/modules/lights/index.js +6 -3
  285. package/modules/lights/sources.js +3 -1
  286. package/modules/music/Music.js +4 -2
  287. package/modules/nav/contract.js +7 -5
  288. package/modules/nav/index.js +174 -44
  289. package/modules/nav/navPath.js +45 -10
  290. package/modules/net/index.js +1 -1
  291. package/modules/particles/Particles.js +85 -22
  292. package/modules/particles/effect.js +80 -28
  293. package/modules/particles/shaders.js +17 -0
  294. package/modules/photo/Photo.js +12 -10
  295. package/modules/rigid/RigidBodies.js +200 -57
  296. package/modules/rigid/Vehicles.js +15 -5
  297. package/modules/rigid/collider3d.contract.js +26 -0
  298. package/modules/rigid/ragdoll.js +55 -44
  299. package/modules/rigid/ragdollBones.js +83 -33
  300. package/modules/rigid/refresh.js +10 -0
  301. package/modules/rigid/sync.js +46 -15
  302. package/modules/settings/Settings.js +84 -37
  303. package/modules/settings/apply.js +15 -8
  304. package/modules/settings/sections.js +7 -4
  305. package/modules/settings/strings.js +2 -2
  306. package/modules/sky/skyModule.js +3 -1
  307. package/modules/swarm/Swarm.js +16 -6
  308. package/modules/terrain/ChunkManager.js +10 -16
  309. package/modules/terrain/index.js +17 -11
  310. package/modules/terrain/terrainEdit.js +13 -2
  311. package/modules/terrain/terrainGen.js +5 -3
  312. package/modules/terrain/terrainShape.js +1 -1
  313. package/modules/timeline/Timeline.js +58 -26
  314. package/modules/timeline/Tween.js +19 -13
  315. package/modules/timeline/shots.js +19 -10
  316. package/modules/triggers/index.js +87 -20
  317. package/modules/vegetation/Vegetation.js +4 -3
  318. package/modules/vegetation/draw.js +16 -0
  319. package/modules/vegetation/groundChunks.js +10 -7
  320. package/modules/vegetation/index.js +30 -7
  321. package/modules/water/Water.js +6 -2
  322. package/modules/weather/Weather.js +16 -15
  323. package/modules/weather/weatherDraw.js +7 -6
  324. package/modules/world/World.js +20 -7
  325. package/modules/world/explain.js +1 -1
  326. package/modules/world/index.js +13 -6
  327. package/modules/world/persist.js +23 -8
  328. package/modules/world/pos.js +4 -4
  329. package/modules/world/records.js +13 -7
  330. package/modules/world/sim.js +74 -23
  331. package/modules/world/simFar.js +2 -2
  332. package/modules/world/state.js +31 -6
  333. package/modules/world/thingSource.js +16 -3
  334. package/modules/world/views.js +19 -8
  335. package/package.json +7 -1
  336. package/render/PostFX.js +47 -29
  337. package/render/backend.js +5 -1
  338. package/render/fx/particles.tsl.js +8 -6
  339. package/render/fx/postWebGPU.tsl.js +3 -3
  340. package/render/layers.js +1 -1
  341. package/render/lightmap.js +23 -3
  342. package/render/occlusion.js +43 -12
  343. package/render/patches.js +2 -2
  344. package/render/postWebGL.js +4 -3
  345. package/render/probes.js +25 -0
  346. package/render/shadows.js +2 -2
  347. package/types/core.d.ts +142 -55
  348. package/types/gameplay.d.ts +92 -40
  349. package/types/generated/core/base/I18n.d.ts +2 -2
  350. package/types/generated/core/input/Input.d.ts +16 -2
  351. package/types/generated/core/input/inputSeat.d.ts +26 -0
  352. package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
  353. package/types/generated/core/ops/Ops.d.ts +2 -1
  354. package/types/generated/core/ops/control.d.ts +12 -2
  355. package/types/generated/core/saves/Saves.d.ts +26 -6
  356. package/types/generated/core/saves/session.d.ts +1 -1
  357. package/types/generated/core/scene/Views.d.ts +1 -1
  358. package/types/generated/core/stream/Stream.d.ts +6 -4
  359. package/types/generated/modules/grid/Grid.d.ts +1 -0
  360. package/types/generated/modules/particles/Particles.d.ts +4 -3
  361. package/types/generated/modules/timeline/Timeline.d.ts +5 -4
  362. package/types/generated/modules/weather/Weather.d.ts +1 -7
  363. package/types/generated/modules/world/World.d.ts +6 -4
  364. package/types/generated/render/PostFX.d.ts +6 -14
  365. package/types/nav.d.ts +36 -4
  366. package/types/physics.d.ts +55 -7
  367. package/types/pixel.d.ts +75 -0
  368. package/types/world.d.ts +14 -8
  369. package/ui/Parts.js +9 -2
  370. package/ui/theme.js +2 -2
  371. package/core/scene/engineCamera.js +0 -32
  372. package/modules/camera/projection.js +0 -21
@@ -1,11 +1,12 @@
1
1
  // Ragdoll: one dynamic rigid body per part of a skinned character, joined by joints; every fixed step the result is written back to the plain three.js bones.
2
2
  // const rd = engine.rigid.ragdoll(player, { impulse: [0, 2, -8], position: hitPoint });
3
3
  // rd.remove(); // back to animation
4
+ // engine.mod('ragdoll.graph', { owner: 'game', id: 'wolf', set: { body: { bone: 'Spine' }, tail: { bone: 'Tail1', parent: 'body' } } }); // not a human: any graph of parts
4
5
  //
5
6
  // Why it is done this way:
6
7
  // - Bodies do not use the bone's orientation but "one shared frame for the whole body in bind pose": bodyQ = boneWorldQ * inv(restQ). That way the frames on both sides of every joint coincide in bind pose,
7
8
  // so the limit zero is the bind pose, whatever pose the animation was in at the start. Using bone orientation directly gives every joint an error the moment it is created and it blows apart on the first step.
8
- // - Only hips writes a position, other bones write rotation only: child bones keep their local offsets, so bone length cannot change and the mesh cannot stretch (the forum post this was modelled on fails right here).
9
+ // - Only the root part writes a position, other bones write rotation only: child bones keep their local offsets, so bone length cannot change and the mesh cannot stretch (the forum post this was modelled on fails right here).
9
10
  // - Parts go through rigid's _add: buoyancy, freezing while terrain is not ready, engine.raycast and world rebuild all come for free; no second copy.
10
11
  // - Not saved: as soon as rigid's save part is read in (new game, load and saves.load all go through it) every ragdoll ends and a normal character comes back; a refused load never gets here, so the ragdoll keeps lying there.
11
12
  // On a world rebuild without a load, rigid carries the bodies over and this rebuilds the joints on rigid:rebuilt.
@@ -15,26 +16,15 @@ import * as THREE from 'three';
15
16
  import { vec3 } from '../../core/base/math.js';
16
17
  import { readParams, keysSchema } from '../../core/base/params.js';
17
18
  import { codedError } from '../../core/base/errorHints.js';
18
- import { readBones, shapeParts } from './ragdollBones.js';
19
+ import { humanoidGraph, shapeParts } from './ragdollBones.js';
19
20
 
20
21
  const KEYS = keysSchema(['impulse', 'position', 'bones', 'limits', 'mass']);
21
22
  const GROUP = (0x8000 << 16 | 0x7fff) >>> 0; // the high 16 bits are its own group, the low 16 bits say what it can touch: everything except its own group
22
- const D = Math.PI / 180;
23
- // Default range of motion (radians, relative to bind pose). bend is positive forward (backward for knees), side is sideways, twist is around the bone. This is physical plausibility, not looks
24
- const LIMITS = {
25
- chest: { bend: [-30 * D, 40 * D], side: [-25 * D, 25 * D], twist: [-30 * D, 30 * D] },
26
- head: { bend: [-40 * D, 50 * D], side: [-35 * D, 35 * D], twist: [-60 * D, 60 * D] },
27
- upperArm: { bend: [-60 * D, 120 * D], side: [-100 * D, 100 * D], twist: [-70 * D, 70 * D] },
28
- lowerArm: { bend: [0, 145 * D], side: [-3 * D, 3 * D], twist: [-60 * D, 60 * D] },
29
- upperLeg: { bend: [-25 * D, 110 * D], side: [-45 * D, 45 * D], twist: [-35 * D, 35 * D] },
30
- lowerLeg: { bend: [0, 140 * D], side: [-3 * D, 3 * D], twist: [-5 * D, 5 * D] },
31
- };
32
- const SHARE = { hips: 0.16, chest: 0.3, head: 0.08, upperArm: 0.03, lowerArm: 0.025, upperLeg: 0.11, lowerLeg: 0.07 }; // how the total mass is split
33
23
  const FRICTION = 2; // damping in the joints (1/s): limbs with no muscle still do not whip around like ropes forever
34
24
  const CALM_SPEED = 0.09, CALM_SPIN = 4, CALM_STEPS = 45; // speed squared (m²/s²), angular speed squared (rad²/s²), how many steps in a row
35
25
  const HIT_SPEED = 6; // the speed (m/s) the hit part alone can take, see _push
36
26
 
37
- const q1 = new THREE.Quaternion(), q2 = new THREE.Quaternion(), p1 = new THREE.Vector3(), p2 = new THREE.Vector3(), s1 = new THREE.Vector3();
27
+ const q1 = new THREE.Quaternion(), q2 = new THREE.Quaternion(), p1 = new THREE.Vector3(), s1 = new THREE.Vector3(), m1 = new THREE.Matrix4();
38
28
  const toQ = (r, out = q1) => out.set(r.x, r.y, r.z, r.w);
39
29
  const worldOf = (o, p, q) => { o.matrixWorld.decompose(p, q, s1); };
40
30
  const shapes = new WeakMap(); // skeleton -> { key, parts }: the same character falling again and again is not re-measured
@@ -57,7 +47,8 @@ export class Ragdolls {
57
47
  if (ch?.vehicle) throw codedError('rigid-misuse', `rigid.ragdoll(): character '${ch.id}' sits in a vehicle. Fix: character.exit() first`);
58
48
  const mesh = skinOf(root);
59
49
  if (!mesh) throw codedError('rigid-misuse', `rigid.ragdoll(): no SkinnedMesh under ${ch ? `character '${ch.id}'` : `'${root.name || root.type}'`}, so there are no bones to drive. A capsule or a procedural rig cannot go limp; a model given by name loads later: await character.whenReady first`);
60
- const shape = this._shape(mesh, o.bones);
50
+ const shape = this._shape(ch, root, mesh, o.bones);
51
+ if (!shape) return null; // the game's rule says this one does not go limp
61
52
  // Take control first: a remote character throws here, when nothing has been built yet
62
53
  const hold = ch ? this.e.control.take(ch, { owner: 'ragdoll', layer: 'physics', step: () => false }) : null;
63
54
  const rd = this._build(ch, root, mesh, shape, hold, o);
@@ -75,23 +66,29 @@ export class Ragdolls {
75
66
  return { ch, root: ch.root };
76
67
  }
77
68
 
78
- _shape(mesh, bones = {}) {
79
- const key = JSON.stringify(bones, (k, v) => (v?.isObject3D ? v.uuid : v));
69
+ /** The rule 'ragdoll.graph' for this body: 'humanoid', a graph, or false for no ragdoll. Measured once per skeleton and graph */
70
+ _shape(ch, root, mesh, bones = {}) {
71
+ const g = this.r._graph.decide(ch?.id, { character: ch, root, mesh });
72
+ if (g === false) return null;
73
+ const human = g === 'humanoid';
74
+ if (!human && Object.keys(bones).length) throw codedError('rigid-misuse', `rigid.ragdoll({ bones }): bones names the parts of the humanoid graph, and this body's rule 'ragdoll.graph' gives its own. Fix: name the bones in the graph`);
75
+ const key = JSON.stringify(human ? bones : g, (k, v) => (v?.isObject3D ? v.uuid : v));
80
76
  const c = shapes.get(mesh.skeleton);
81
77
  if (c?.key === key) return c.parts;
82
- const parts = shapeParts(mesh, readBones(mesh.skeleton, bones));
78
+ const parts = shapeParts(mesh, human ? humanoidGraph(mesh, bones) : g);
83
79
  shapes.set(mesh.skeleton, { key, parts });
84
80
  return parts;
85
81
  }
86
82
 
87
83
  _build(ch, root, mesh, shape, hold, o) {
88
- const { r } = this, R = r.rapier, mass = o.mass ?? 70;
84
+ const { r } = this, R = r.rapier, skeleton = mesh.skeleton, top = shape[0];
85
+ const massK = o.mass != null ? o.mass / shape.reduce((n, s) => n + s.mass, 0) : 1; // the call's whole-body mass keeps the graph's proportions
89
86
  root.updateWorldMatrix(true, true);
90
87
  const holder = new THREE.Group(); // parent of the placeholder objects: _add does not add to the scene when there is a parent
91
88
  const parts = {}, list = [];
92
89
  // bind space to world scale: when the model is scaled (0.01 is common for Mixamo) colliders must use the real length as it is now
93
- const a = shape.find(s => s.name === 'upperLegL'), b = shape.find(s => s.name === 'lowerLegL');
94
- const k = a.bone.getWorldPosition(p1).distanceTo(b.bone.getWorldPosition(p2)) / a.p.distanceTo(b.p);
90
+ // read from the skinning matrix of the root part: bind to now is pose and scale, and pose does not change its size, whatever the body looks like
91
+ const k = s1.setFromMatrixScale(m1.multiplyMatrices(top.bone.matrixWorld, skeleton.boneInverses[skeleton.bones.indexOf(top.bone)])).x;
95
92
  for (const s of shape) {
96
93
  const proxy = new THREE.Object3D(), bq = new THREE.Quaternion();
97
94
  holder.add(proxy);
@@ -101,18 +98,19 @@ export class Ragdolls {
101
98
  const mid = seg.clone().multiplyScalar(0.5), up = q1.setFromUnitVectors(new THREE.Vector3(0, 1, 0), seg.clone().normalize());
102
99
  const desc = R.ColliderDesc.capsule(Math.max(len / 2 - rad, len * 0.02), rad).setTranslation(mid.x, mid.y, mid.z)
103
100
  .setRotation({ x: up.x, y: up.y, z: up.z, w: up.w }).setCollisionGroups(GROUP);
104
- const entry = r._add(proxy, desc, { mass: mass * SHARE[s.kind], friction: 0.8, restitution: 0, damping: 0.1, angularDamping: 0.8 });
101
+ const entry = r._add(proxy, desc, { mass: s.mass * massK, friction: 0.8, restitution: 0, damping: 0.1, angularDamping: 0.8 });
105
102
  entry.ragdoll = true; entry.object = s.bone; // a ray hit returns the bone: the game needs to know what was hit
106
103
  entry.body.enableCcd(true); // limbs are thin and fast when knocked away; without it they pass through thin ground
107
- const part = { name: s.name, shape: s, entry, mass: mass * SHARE[s.kind], seg: seg.clone(), rad, bone: s.bone, pos0: s.bone.position.clone(), q0: s.bone.quaternion.clone() };
104
+ const part = { name: s.name, shape: s, entry, mass: s.mass * massK, seg: seg.clone(), rad, bone: s.bone, pos0: s.bone.position.clone(), q0: s.bone.quaternion.clone() };
108
105
  list.push(parts[s.name] = part);
109
106
  }
110
107
  const self = this;
111
108
  const rd = {
112
- ch, root, mesh, list, parts: Object.fromEntries(list.map(p => [p.name, p.entry])), hold, joints: [], limits: o.limits ?? {}, anchor: null, rig: null, anim: null, drawn: false, void: false, calm: 0,
109
+ ch, root, mesh, list, parts: Object.fromEntries(list.map(p => [p.name, p.entry])), hold, joints: [], limits: o.limits ?? {}, anchor: null, anim: null, drawn: false, void: false, calm: 0,
113
110
  get active() { return self.live.has(rd); },
114
111
  get settled() { return rd.active && list.every(p => !p.entry.enabled || p.entry.body.isSleeping()); },
115
112
  remove() { self._end(rd); },
113
+ /** @internal character.placeAt: root follows the body, so a placement moves the body */ shift(x, y, z) { self._shift(rd, x, y, z); },
116
114
  };
117
115
  // Joint anchors are computed from the current pose (not the bind pose): in-between bones that are not in the part table (Spine1, clavicle) may not be at their bind position at the start, and this way the error on the first step is zero
118
116
  for (const p of list) {
@@ -130,7 +128,7 @@ export class Ragdolls {
130
128
 
131
129
  /** The three-axis range of this joint. If the starting pose is already past the limit, widen the range to the starting angle: otherwise the solver yanks it back on the first step and it looks like a twitch */
132
130
  _range(p, limits) {
133
- const given = limits[p.name] ?? limits[p.shape.kind], base = LIMITS[p.shape.kind];
131
+ const given = limits[p.name] ?? limits[p.shape.kind], base = p.shape.limits;
134
132
  const lim = { twist: given?.twist ?? base.twist, side: given?.side ?? base.side, bend: given?.bend ?? base.bend };
135
133
  const F = p.shape.frame;
136
134
  // The child's rotation relative to the parent, read in the joint frame: the imaginary x / y / z are the three values Rapier's limits use
@@ -158,7 +156,7 @@ export class Ragdolls {
158
156
  }
159
157
 
160
158
  /**
161
- * The impulse hits the part nearest to position (hips when no position is given). That part only takes HIT_SPEED worth, the rest is shared over the whole body by mass:
159
+ * The impulse hits the part nearest to position (the root part when no position is given). That part only takes HIT_SPEED worth, the rest is shared over the whole body by mass:
162
160
  * in a real body force travels along the skeleton, but the solver cannot pass that much in one step, and the whole hit on a 5 kg head would send it flying and tear the joints apart. Total momentum is unchanged.
163
161
  */
164
162
  _push(rd, { impulse, position }) {
@@ -184,27 +182,27 @@ export class Ragdolls {
184
182
  rd.anim = ch ? ch.anim : e.assets.animatorOf(root);
185
183
  if (rd.anim) rd.anim._held = true;
186
184
  if (ch) {
187
- ch._limp = rd;
188
- ch.velocity.set(0, 0); ch.vy = 0; ch.moveAmount = 0; ch.state = ch._stateMark = 'ragdoll';
189
- // the player capsule is turned off by rigid.step according to _limp; an NPC's capsule belongs to its mover
190
- if (ch !== e.player && ch.mover.collider && ch.mover.gen === this.r.gen) ch.mover.collider.setEnabled(false);
185
+ ch.limp = rd;
186
+ ch.velocity.set(0, 0); ch.vy = 0; ch.moveAmount = 0; ch.state = ch.stateMark = 'ragdoll';
187
+ // the player capsule is turned off by rigid.step according to limp; an NPC's capsule belongs to its mover
188
+ if (ch !== e.player && ch.mover.collider && ch.mover.world === this.r.world) ch.mover.collider.setEnabled(false);
191
189
  }
192
190
  const rig = e.cameraRig;
193
191
  if (rig?.target === root) {
194
- // follow the waist, not the feet: the camera looks at the body, not at the air a person's height above it
195
- rd.rig = rig; rd.anchor = new THREE.Object3D();
192
+ // follow the root part, not the feet: the camera looks at the body, not at the air a person's height above it
193
+ rd.anchor = new THREE.Object3D();
196
194
  this._anchor(rd);
197
195
  rig.follow(rd.anchor, { height: 0 });
198
196
  }
199
197
  }
200
198
 
201
- _anchor(rd) { const t = rd.parts.hips.body.translation(); rd.anchor.position.set(t.x, t.y, t.z); }
199
+ _anchor(rd) { const t = rd.list[0].entry.body.translation(); rd.anchor.position.set(t.x, t.y, t.z); }
202
200
 
203
201
  /** Every fixed step, after the world has stepped (called by RigidBodies.step) */
204
202
  sync() {
205
203
  for (const rd of this.live) {
206
204
  const { ch, root } = rd;
207
- if (ch?._disposed || !root.parent) { this._end(rd, true); continue; } // the character or model was deleted: only clean up the physics
205
+ if (ch?.disposed || !root.parent) { this._end(rd, true); continue; } // the character or model was deleted: only clean up the physics
208
206
  if (rd.settled) { if (rd.drawn) continue; rd.drawn = true; } else { rd.drawn = false; this._calm(rd); } // once asleep, stop writing: saves cost and a bone the game wrote stays
209
207
  this._pose(rd);
210
208
  ch?.syncRecord();
@@ -222,13 +220,13 @@ export class Ragdolls {
222
220
 
223
221
  /** Write the physics result back to the bones. root follows the body (triggers, streaming and saves read it), so the bones are computed after root has moved */
224
222
  _pose(rd) {
225
- const { root, list } = rd, hips = list[0].entry.body.translation();
223
+ const { root, list } = rd, core = list[0].entry.body.translation();
226
224
  let low = Infinity;
227
225
  for (const p of list) { // lowest point of the body: the soles when standing, the ground when lying, no need to ask the terrain
228
226
  const t = p.entry.body.translation(), q = toQ(p.entry.body.rotation());
229
227
  low = Math.min(low, t.y - p.rad, t.y + p1.copy(p.seg).applyQuaternion(q).y - p.rad);
230
228
  }
231
- p1.set(hips.x, low, hips.z);
229
+ p1.set(core.x, low, core.z);
232
230
  if (root.parent) root.parent.worldToLocal(p1);
233
231
  root.position.copy(p1);
234
232
  root.updateWorldMatrix(true, false);
@@ -244,21 +242,32 @@ export class Ragdolls {
244
242
  p.bone.updateMatrixWorld();
245
243
  }
246
244
  if (rd.anchor) this._anchor(rd);
247
- const under = hips.y < this.e.ground.voidY();
248
- if (under && !rd.void) this.e.events.emit('terrain:void', { who: rd.parts.hips, position: { x: hips.x, y: hips.y, z: hips.z } });
245
+ const under = core.y < this.e.ground.voidY();
246
+ if (under && !rd.void) this.e.events.emit('terrain:void', { who: list[0].entry, position: { x: core.x, y: core.y, z: core.z } });
249
247
  rd.void = under;
250
248
  }
251
249
 
252
250
  /** Is this character lying down (rigid.step turns the player capsule off by this) */
253
- holds(ch) { return !!ch._limp; }
251
+ holds(ch) { return !!ch.limp; }
254
252
 
255
253
  /** Load: position belongs to the save, so the character is not put back where the body lies */
256
254
  load() { for (const rd of [...this.live]) this._end(rd, false, false); }
257
255
 
256
+ /** A placement: every part moves by the same offset, so the joints see the pose they had, and at rest, so nothing the fall carried arrives with it. Woken parts settle again */
257
+ _shift(rd, x, y, z) {
258
+ for (const p of rd.list) {
259
+ const b = p.entry.body, t = b.translation();
260
+ this.r.setPosition(p.entry, { x: t.x + x, y: t.y + y, z: t.z + z });
261
+ b.setAngvel({ x: 0, y: 0, z: 0 }, true);
262
+ }
263
+ rd.calm = 0;
264
+ if (rd.anchor) this._anchor(rd);
265
+ }
266
+
258
267
  /** End: tear down the physics and give every slot back to its owner. gone: the character no longer exists, nothing to give back; place: put the character where the body lies */
259
268
  _end(rd, gone = false, place = true) {
260
269
  if (!this.live.delete(rd)) return;
261
- const { ch, list, anim, rig, anchor, hold } = rd;
270
+ const { ch, list, anim, anchor, hold } = rd;
262
271
  for (const j of rd.joints) if (j.isValid()) this.r.world.removeImpulseJoint(j, true);
263
272
  rd.joints = [];
264
273
  for (const p of list) p.entry.remove();
@@ -267,16 +276,18 @@ export class Ragdolls {
267
276
  for (const p of list) { p.bone.position.copy(p.pos0); p.bone.quaternion.copy(p.q0); } // bones no animation clip writes also go back to how they were before falling
268
277
  if (anim) anim._held = false;
269
278
  if (ch) {
270
- ch._limp = null;
271
- if (ch !== this.e.player && ch.mover.collider && ch.mover.gen === this.r.gen) ch.mover.collider.setEnabled(true);
272
- if (ch.state === 'ragdoll') ch.state = ch._stateMark = 'idle';
279
+ ch.limp = null;
280
+ if (ch !== this.e.player && ch.mover.collider && ch.mover.world === this.r.world) ch.mover.collider.setEnabled(true);
281
+ if (ch.state === 'ragdoll') ch.state = ch.stateMark = 'idle';
273
282
  if (place) ch.placeAt(ch.root.position);
274
283
  }
275
284
  // if the game switched the camera away meanwhile, do not take it back
285
+ const rig = this.e.cameraRig; // read now: the rig that started following may have been swapped out (architecture 8.2)
276
286
  if (rig?.target === anchor) rig.follow(rd.root);
277
287
  }
278
288
 
279
- dispose() { this._sub.remove(); this.live.clear(); }
289
+ /** The solver is going (rigid left or was replaced): every limp body gets up while its parts can still be read, or the character stays held by a physics that is gone. A dispose of the whole engine, or of the character, has nobody left to give it to */
290
+ dispose() { this._sub.remove(); for (const rd of [...this.live]) this._end(rd, this.e.disposed || !!rd.ch?.disposed); }
280
291
  }
281
292
 
282
293
  /** The SkinnedMesh with the most bones: clothes and accessories are often small meshes on the same skeleton */
@@ -1,6 +1,8 @@
1
- // Ragdoll skeleton reading: recognise each tool's bone names (Mixamo, Blender, Unreal, Bip01, VRM, Quaternius...) as 11 parts, then measure each segment's real length and thickness.
1
+ // Ragdoll skeleton reading: a graph of parts over a skeleton, each measured for its real length and thickness. The default graph comes from recognising each tool's bone names
2
+ // (Mixamo, Blender, Unreal, Bip01, VRM, Quaternius...) as the 11 parts of a human body; a game's own graph (four legs, a tail) goes through the same measuring.
2
3
  // Why this is apart from ragdoll.js: it only reads, never writes, and never touches Rapier, so it can be tested without physics.
3
4
  import * as THREE from 'three';
5
+ import { vec3 } from '../../core/base/math.js';
4
6
  import { codedError } from '../../core/base/errorHints.js';
5
7
 
6
8
  const PARTS = ['hips', 'chest', 'head', 'upperArmL', 'lowerArmL', 'upperArmR', 'lowerArmR', 'upperLegL', 'lowerLegL', 'upperLegR', 'lowerLegR'];
@@ -12,6 +14,20 @@ const NAMES = {
12
14
  upperLeg: ['thigh', 'upperleg', 'upleg', 'femur', 'leg'], lowerLeg: ['shin', 'calf', 'lowerleg', 'loleg', 'knee', 'tibia', 'leg'],
13
15
  };
14
16
 
17
+ const D = Math.PI / 180;
18
+ // Default range of motion (radians, relative to bind pose). bend is positive forward (backward for knees), side is sideways, twist is around the bone. This is physical plausibility, not looks
19
+ const LIMITS = {
20
+ chest: { bend: [-30 * D, 40 * D], side: [-25 * D, 25 * D], twist: [-30 * D, 30 * D] },
21
+ head: { bend: [-40 * D, 50 * D], side: [-35 * D, 35 * D], twist: [-60 * D, 60 * D] },
22
+ upperArm: { bend: [-60 * D, 120 * D], side: [-100 * D, 100 * D], twist: [-70 * D, 70 * D] },
23
+ lowerArm: { bend: [0, 145 * D], side: [-3 * D, 3 * D], twist: [-60 * D, 60 * D] },
24
+ upperLeg: { bend: [-25 * D, 110 * D], side: [-45 * D, 45 * D], twist: [-35 * D, 35 * D] },
25
+ lowerLeg: { bend: [0, 140 * D], side: [-3 * D, 3 * D], twist: [-5 * D, 5 * D] },
26
+ };
27
+ const SHARE = { hips: 0.16, chest: 0.3, head: 0.08, upperArm: 0.03, lowerArm: 0.025, upperLeg: 0.11, lowerLeg: 0.07 }; // how the total mass is split
28
+ const WHOLE = 70; // kg of a body whose graph or call names none
29
+ const OPEN = { bend: [-45 * D, 45 * D], side: [-45 * D, 45 * D], twist: [-30 * D, 30 * D] }; // a part of a game's graph that gives no limits: loose, but no joint folds through itself
30
+
15
31
  /** Bone name -> { side: 'L' | 'R' | '', word }: LeftForeArm, upperarm_l, Bip01 L Thigh, DEF-forearm.L, UpperArmR (GLTFLoader eats the dot) all split into the same shape */
16
32
  function parse(name) {
17
33
  const words = name.replace(/([a-z0-9])([A-Z])/g, '$1 $2').split(/[^a-zA-Z0-9]+/).map(w => w.toLowerCase().replace(/\d+$/, '')).filter(w => w && !NOISE.has(w));
@@ -68,7 +84,7 @@ export function readBones(skeleton, given = {}) {
68
84
  if (bad.length || missing.length) {
69
85
  const names = skeleton.bones.slice(0, 40).map(b => b.name).join(', ');
70
86
  throw codedError('rigid-misuse', `rigid.ragdoll(): cannot read this skeleton. Missing: ${[...bad, ...missing.filter(p => !bad.some(s => s.startsWith(p + ':')))].join(', ')}. `
71
- + `Bones in it: ${names}${skeleton.bones.length > 40 ? ', ...' : ''}. Fix: name them, e.g. engine.rigid.ragdoll(character, { bones: { ${missing[0] ?? 'hips'}: '<bone name>' } })`);
87
+ + `Bones in it: ${names}${skeleton.bones.length > 40 ? ', ...' : ''}. Fix: name them, e.g. engine.rigid.ragdoll(character, { bones: { ${missing[0] ?? 'hips'}: '<bone name>' } }); a body that is not a human: the rule 'ragdoll.graph', recipe 11`);
72
88
  }
73
89
  if (map.hips === map.chest) throw codedError('rigid-misuse', `rigid.ragdoll(): hips and chest are the same bone ('${map.hips.name}'), so the torso has one part. Fix: pass bones: { hips: '<pelvis bone>', chest: '<upper spine bone>' }`);
74
90
  return map;
@@ -89,40 +105,59 @@ function toSegment(p, a, b) {
89
105
  }
90
106
 
91
107
  /**
92
- * Static shape of each part (all in bind space, in bind-time length units): { name, kind, bone, parent, p, q, end, radius, frame }, parents before children.
93
- * end: the tip of this bone, from the real bone length, not guessed by proportion (a misaligned collider is where mesh deformation comes from). radius: distance from skinned vertices to this bone, so thin and heavy characters both fit.
94
- * frame: joint frame, x along the bone (twist), y toward positive bend, z the hinge axis.
108
+ * The default graph: the 11 parts of a human body, read from the skeleton. Everything that knows a body has legs lives here, so a wolf or a snake is just another graph.
109
+ * Beyond the data any graph has: kind names the limits a game can widen for both sides at once, end is the part a bone points at, forward the way this joint bends.
110
+ * @returns {Record<string, any>}
95
111
  */
96
- export function shapeParts(mesh, map) {
97
- const sk = mesh.skeleton, rest = {};
112
+ export function humanoidGraph(mesh, given) {
113
+ const map = readBones(mesh.skeleton, given), sk = mesh.skeleton, rest = {};
98
114
  for (const n of PARTS) rest[n] = restOf(sk, map[n]);
99
115
  const right = v1.subVectors(rest.upperLegR.p, rest.upperLegL.p).clone().normalize();
100
116
  const up = new THREE.Vector3().subVectors(rest.chest.p, rest.hips.p).normalize();
101
117
  const forward = new THREE.Vector3().crossVectors(up, right).normalize();
102
- const childEnd = bone => { // Hand or foot: the end is the first child bone; with no child, extend along the previous segment's direction (end is corrected from vertices later)
103
- const c = bone.children.find(o => o.isBone && sk.bones.includes(o));
104
- return c ? restOf(sk, c).p : null;
105
- };
106
- const parts = PARTS.map(name => {
107
- const kind = name.replace(/[LR]$/, ''), side = name.slice(-1), r = rest[name];
108
- let end;
109
- if (name === 'hips') end = rest.chest.p;
110
- else if (name === 'chest') end = rest.head.p;
111
- else if (kind === 'upperArm') end = rest['lowerArm' + side].p;
112
- else if (kind === 'upperLeg') end = rest['lowerLeg' + side].p;
113
- else if (name === 'head') end = null;
114
- else end = childEnd(map[name]) ?? new THREE.Vector3().subVectors(r.p, rest[(kind === 'lowerArm' ? 'upperArm' : 'upperLeg') + side].p).add(r.p);
118
+ return Object.fromEntries(PARTS.map(name => {
119
+ const kind = name.replace(/[LR]$/, ''), side = name.slice(-1);
115
120
  let parent = null;
116
121
  for (let o = map[name].parent; o && !parent; o = o.parent) parent = PARTS.find(n => map[n] === o) ?? null;
117
122
  if (name !== 'hips' && !parent) throw codedError('rigid-misuse', `rigid.ragdoll(): bone '${map[name].name}' (${name}) is not under hips ('${map.hips.name}'), so nothing holds it. Fix: pass bones: { hips: '<the bone every body part hangs from>' }`);
118
- return { name, kind, bone: map[name], parent, p: r.p, q: r.q, end, radius: 0, frame: null, d: depth(map[name]) };
123
+ const end = { hips: 'chest', chest: 'head', head: 'top', upperArm: 'lowerArm' + side, upperLeg: 'lowerLeg' + side }[kind];
124
+ // Knees bend backward, other joints forward
125
+ return [name, { bone: map[name], parent, kind, limits: LIMITS[kind], mass: WHOLE * SHARE[kind], end, forward: kind === 'lowerLeg' ? forward.clone().negate() : forward, up }];
126
+ }));
127
+ }
128
+
129
+ /** A graph's bone: a name or the bone itself; one outside the skeleton is refused by name */
130
+ function boneOf(sk, name, b) {
131
+ const bone = b?.isObject3D ? b : sk.bones.find(x => x.name === b);
132
+ if (bone && sk.bones.includes(bone)) return bone;
133
+ throw codedError('rigid-misuse', `ragdoll.graph: part '${name}' names bone '${b?.name ?? b}', which is not in the skeleton. Bones in it: ${sk.bones.slice(0, 40).map(x => x.name).join(', ')}`);
134
+ }
135
+
136
+ /**
137
+ * Static shape of each part of a graph { part: { bone, parent, limits, mass, end, forward, kind, up } } (all in bind space, in bind-time length units):
138
+ * { name, kind, bone, parent, p, q, end, radius, frame, limits, mass }, parents before children, so the one part without a parent comes first.
139
+ * end: the tip of this bone, from the real bone length, not guessed by proportion (a misaligned collider is where mesh deformation comes from). radius: distance from skinned vertices to this bone, so thin and heavy characters both fit.
140
+ * frame: joint frame, x along the bone (twist), y toward positive bend, z the hinge axis.
141
+ */
142
+ export function shapeParts(mesh, graph) {
143
+ const bad = why => codedError('rigid-misuse', `ragdoll.graph: ${why}. A graph is { part: { bone, parent, limits?, mass?, end?, forward? } }, one part without a parent`);
144
+ if (!graph || typeof graph !== 'object') throw bad(`got ${String(graph)}`);
145
+ const sk = mesh.skeleton, names = Object.keys(graph), roots = names.filter(n => !graph[n].parent);
146
+ if (names.length < 2 || roots.length !== 1) throw bad(`${names.length} part(s) with ${roots.length} root(s) (${roots.join(', ')})`);
147
+ const parts = names.map(name => {
148
+ const g = graph[name], bone = boneOf(sk, name, g.bone), r = restOf(sk, bone);
149
+ if (g.parent && !graph[g.parent]) throw bad(`part '${name}' has parent '${g.parent}', which is not a part`);
150
+ if (g.parent && !under(bone, boneOf(sk, g.parent, graph[g.parent].bone))) throw bad(`part '${name}': bone '${bone.name}' is not under the bone of its parent '${g.parent}'`);
151
+ return { name, kind: g.kind, bone, parent: g.parent ?? null, p: r.p, q: r.q, end: null, radius: 0, frame: null, limits: { ...OPEN, ...g.limits }, mass: g.mass ?? WHOLE / names.length, d: depth(bone) };
119
152
  }).sort((a, b) => a.d - b.d);
120
- measure(mesh, parts, up);
153
+ const byName = Object.fromEntries(parts.map(s => [s.name, s]));
154
+ for (const s of parts) if (graph[s.name].end !== 'top') s.end = tipOf(sk, s, parts, byName, graph[s.name].end);
155
+ measure(mesh, parts, graph, byName);
121
156
  for (const s of parts) {
157
+ const g = graph[s.name], F = g.forward ? vec3(g.forward) : new THREE.Vector3(0, 0, 1), up = g.up ? vec3(g.up) : new THREE.Vector3(0, 1, 0);
122
158
  const x = new THREE.Vector3().subVectors(s.end, s.p).normalize();
123
- // Knees bend backward, other joints forward: the y axis is the direction the bone tip moves when bend is positive
124
- const y = forward.clone().multiplyScalar(s.kind === 'lowerLeg' ? -1 : 1).addScaledVector(x, s.kind === 'lowerLeg' ? x.dot(forward) : -x.dot(forward));
125
- if (y.lengthSq() < 1e-4) y.copy(up).addScaledVector(x, -x.dot(up)); // The bone points straight forward (a rare bind pose)
159
+ const y = F.clone().addScaledVector(x, -x.dot(F)); // the y axis is the direction the bone tip moves when bend is positive
160
+ if (y.lengthSq() < 1e-4) y.copy(up).addScaledVector(x, -x.dot(up)); // The bone points straight along forward (a rare bind pose)
126
161
  y.normalize();
127
162
  const z = new THREE.Vector3().crossVectors(x, y);
128
163
  s.frame = new THREE.Quaternion().setFromRotationMatrix(new THREE.Matrix4().makeBasis(x, y, z));
@@ -130,11 +165,23 @@ export function shapeParts(mesh, map) {
130
165
  return parts;
131
166
  }
132
167
 
133
- /** Measure thickness: assign each vertex to the part of its heaviest-weighted bone and take the 60th percentile of the distance to the segment (outliers such as fingers and capes do not count). The head has no next bone, so its top is measured from vertices too */
134
- function measure(mesh, parts, up) {
168
+ /** Where a part ends: the part it names; else the middle of its child parts (the one child when they meet at its own joint); else its first child bone, a hand or a foot; else on along the segment before it */
169
+ function tipOf(sk, s, parts, byName, end) {
170
+ if (end) { if (!byName[end]) throw codedError('rigid-misuse', `ragdoll.graph: part '${s.name}' has end '${end}', which is not a part`); return byName[end].p; }
171
+ const kids = parts.filter(c => c.parent === s.name);
172
+ if (kids.length) {
173
+ const mid = kids.reduce((m, c) => m.add(c.p), new THREE.Vector3()).divideScalar(kids.length);
174
+ return mid.distanceTo(s.p) > 1e-5 ? mid : kids[0].p;
175
+ }
176
+ const c = s.bone.children.find(o => o.isBone && sk.bones.includes(o));
177
+ return c ? restOf(sk, c).p : new THREE.Vector3().subVectors(s.p, byName[s.parent].p).add(s.p);
178
+ }
179
+
180
+ /** Measure thickness: assign each vertex to the part of its heaviest-weighted bone and take the 60th percentile of the distance to the segment (outliers such as fingers and capes do not count). A part with end: 'top' (a head) has no next bone, so its top is measured from vertices too */
181
+ function measure(mesh, parts, graph, byName) {
135
182
  const g = mesh.geometry, pos = g.attributes.position, si = g.attributes.skinIndex, sw = g.attributes.skinWeight, sk = mesh.skeleton;
136
183
  const owner = sk.bones.map(b => { for (let o = b; o; o = o.parent) { const s = parts.find(x => x.bone === o); if (s) return s; } return null; });
137
- const lists = new Map(parts.map(s => [s, []])), head = parts.find(s => s.name === 'head');
184
+ const lists = new Map(parts.map(s => [s, []]));
138
185
  const pts = new Map(parts.map(s => [s, []]));
139
186
  if (pos && si && sw) {
140
187
  for (let i = 0; i < pos.count; i++) {
@@ -144,11 +191,14 @@ function measure(mesh, parts, up) {
144
191
  if (s) pts.get(s).push(new THREE.Vector3().fromBufferAttribute(pos, i).applyMatrix4(mesh.bindMatrix));
145
192
  }
146
193
  }
147
- // Top of the head: the vertex farthest up along the torso; with no vertices, estimate half the neck-to-chest distance
148
- let top = 0;
149
- for (const v of pts.get(head)) top = Math.max(top, v1.subVectors(v, head.p).dot(up));
150
- const chest = parts.find(s => s.name === 'chest');
151
- head.end = head.p.clone().addScaledVector(up, top > 0 ? top : chest.p.distanceTo(head.p) * 0.5);
194
+ // The top: the vertex farthest up; with no vertices, estimate half the distance to the parent
195
+ for (const s of parts) {
196
+ if (graph[s.name].end !== 'top') continue;
197
+ const up = graph[s.name].up ? vec3(graph[s.name].up) : new THREE.Vector3(0, 1, 0);
198
+ let top = 0;
199
+ for (const v of pts.get(s)) top = Math.max(top, v1.subVectors(v, s.p).dot(up));
200
+ s.end = s.p.clone().addScaledVector(up, top > 0 ? top : byName[s.parent].p.distanceTo(s.p) * 0.5);
201
+ }
152
202
  for (const s of parts) {
153
203
  const list = lists.get(s), len = s.p.distanceTo(s.end);
154
204
  for (const v of pts.get(s)) list.push(toSegment(v, s.p, s.end));
@@ -0,0 +1,10 @@
1
+ // Rapier 0.21 keeps its query structures in the broad phase, and only a step rebuilds them: World has no updateSceneQueries and no query pipeline, and
2
+ // propagateModifiedBodyPositionsToColliders moves colliders without touching the broad phase. So a frozen engine refreshes with a step of no time, here and nowhere else.
3
+ // Twice: the first leaves a moved body's collider in the old place, the second catches it up. Tools test `rapier refresh` holds each of these, per Rapier version.
4
+
5
+ /** @internal Rebuild what queries read and nothing else (velocities, positions, sleep and contacts stay); the step length comes back even if Rapier throws */
6
+ export function refreshQueries(world) {
7
+ const dt = world.timestep;
8
+ world.timestep = 0;
9
+ try { world.step(); world.step(); } finally { world.timestep = dt; }
10
+ }
@@ -129,30 +129,61 @@ function dropTerrain(r, key) {
129
129
  if (t) for (const c of t.colliders) r.world.removeCollider(c, false);
130
130
  r.terrain.delete(key);
131
131
  }
132
+ // Chunk copies of a ground source that left: terrain and trunks are copies of the ground too, and nothing else asks for them once chunkCollision is gone. Answers whether any went.
133
+ export function dropChunks(r) {
134
+ if (r.engine.ground.chunkCollision || !(r.terrain.size || r.trees.size)) return false;
135
+ for (const key of [...r.terrain.keys()]) dropTerrain(r, key);
136
+ for (const key of [...r.trees.keys()]) dropTrees(r, key);
137
+ return true;
138
+ }
132
139
  // Houses and pillars from the collision module, as physics colliders: engine.collision.mirror does the add / remove diff (shared with nav), this
133
- // only says how one collider is built and dropped. Built lazily: the mirror lives on the collision module, which rigid requires.
140
+ // only says how one collider is built and dropped. Built lazily: the mirror lives on the collision module, which rigid requires. A mirror knows one module, so another
141
+ // collision module (replaces) drops the old colliders and starts a new mirror. Answers whether a collider changed.
134
142
  const UP = new THREE.Vector3(0, 1, 0), Q = new THREE.Quaternion();
135
143
  export function syncStatics(r) {
136
- r._statics ??= r.engine.collision.mirror({
144
+ r._collision.sync(() => { r._statics?.clear(true); r._statics = null; });
145
+ r._statics ??= r.engine.collision?.mirror({
137
146
  add(type, o) {
138
147
  const R = r.rapier, g = o.y ?? r.engine.surface(o.x, o.z);
139
- if (type !== 'box') return r.world.createCollider(R.ColliderDesc.cylinder(o.h / 2, o.r).setTranslation(o.x, g + o.h / 2, o.z));
140
- Q.setFromAxisAngle(UP, o.rot);
141
- return r.world.createCollider(R.ColliderDesc.cuboid(o.hw, o.h / 2, o.hd).setTranslation(o.x, g + o.h / 2, o.z).setRotation({ x: Q.x, y: Q.y, z: Q.z, w: Q.w }));
148
+ Q.setFromAxisAngle(UP, o.rot ?? 0);
149
+ const shape = type === 'box' ? R.ColliderDesc.cuboid(o.hw, o.h / 2, o.hd).setRotation({ x: Q.x, y: Q.y, z: Q.z, w: Q.w }) : R.ColliderDesc.cylinder(o.h / 2, o.r);
150
+ const c = r.world.createCollider(shape.setTranslation(o.x, g + o.h / 2, o.z));
151
+ if (o.y == null) r._onGround.set(o, c);
152
+ return c;
142
153
  },
143
- remove(col) { r.world.removeCollider(col, false); },
144
- });
145
- r._statics.sync();
154
+ remove(c, o) { r._onGround.delete(o); r.world.removeCollider(c, false); },
155
+ }) ?? null;
156
+ return !!r._statics?.sync();
157
+ }
158
+
159
+ /** The ground moved under a world box: a collider that stands on the ground, one with no y of its own, stands on what is there now. Mirror data keeps no height, so nothing else would tell it. No area: all of them */
160
+ export function restandStatics(r, { x0 = -Infinity, z0 = -Infinity, x1 = Infinity, z1 = Infinity } = {}) {
161
+ for (const [o, c] of r._onGround) if (o.x + o.r >= x0 && o.x - o.r <= x1 && o.z + o.r >= z0 && o.z - o.r <= z1) { c.setTranslation({ x: o.x, y: r.engine.surface(o.x, o.z) + o.h / 2, z: o.z }); r._behind = true; }
146
162
  }
147
163
 
148
- // Ground of a level (hand-built scene): one static triangle mesh, rebuilt when the level changes
164
+ // Ground of a level (hand-built scene): one static triangle mesh, rebuilt when the level changes. The provider's staticTrimeshes names the source
165
+ // (engine.ground itself is a fresh object whenever a collider source joins, and that alone must not rebuild it). A new ground of any kind stands the world boxes on it again:
166
+ // a level at another height sends no ground:change. Answers whether the triangles changed.
149
167
  export function syncLevel(r) {
150
- const G = r.engine.ground; if (!G.staticTrimeshes) return;
151
- const v = G.staticVersion?.() ?? 0; if (v === r._levelVersion) return;
152
- r._levelVersion = v;
153
- for (const c of r._levelColliders || []) r.world.removeCollider(c, false);
154
- const desc = t => r.rapier.ColliderDesc.trimesh(t.positions, t.indices).setFriction(0.9);
155
- r._levelColliders = G.staticTrimeshes().map(t => r.world.createCollider(desc(t)));
168
+ r._standOn.sync(() => restandStatics(r));
169
+ return !!r._level.sync(() => {
170
+ const G = r.engine.ground, old = r._levelColliders || [];
171
+ r._levelColliders = []; // before anything can throw: the retry must not remove these twice
172
+ for (const c of old) r.world.removeCollider(c, false);
173
+ const desc = t => r.rapier.ColliderDesc.trimesh(t.positions, t.indices).setFriction(0.9);
174
+ for (const t of G.staticTrimeshes?.() ?? []) r._levelColliders.push(r.world.createCollider(desc(t)));
175
+ });
176
+ }
177
+
178
+ // A ground with no collision of its own stands on an infinite flat plane at y = 0, unless the game turned it off. One more copy of the ground, so it comes and goes with the ground
179
+ // source: left standing it is an invisible floor over a level installed later. Answers whether it changed.
180
+ export const wantsFloor = r => { const G = r.engine.ground; return r.fallbackFloor && !G.chunkCollision && !G.staticTrimeshes; };
181
+ export function syncFloor(r) {
182
+ return !!r._floor.sync(() => {
183
+ const want = wantsFloor(r);
184
+ if (want && !r._floorCollider) r._floorCollider = r.world.createCollider(r.rapier.ColliderDesc.cuboid(5000, 0.5, 5000).setTranslation(0, -0.5, 0));
185
+ else if (!want && r._floorCollider) { r.world.removeCollider(r._floorCollider, false); r._floorCollider = null; }
186
+ });
156
187
  }
157
188
 
158
189
  // ---------- Game-set body / collider state across RigidBodies._fresh ----------