threedog 0.8.0 → 1.0.1

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 +223 -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
@@ -8,25 +8,68 @@
8
8
  // const ball = engine.rigid.addBall(mesh, { radius: 0.4, restitution: 0.6 });
9
9
  // engine.rigid.impulse(ball, [0, 3, 5]); // kick (impulse vector: Vector3 / [x, y, z] / { x, y, z })
10
10
  // Returns an entry (handle) { body, collider, mesh (= object, position written by physics), remove() }: remove only deletes the body; the model is yours
11
- // (shadow settings are untouched too)
11
+ // (shadow settings are untouched too). The other way round a body follows its model: engine.remove of the model, or of a parent such as a level's root, takes the body too
12
12
  // const car = engine.rigid.addWheeled(carMesh, { wheels: [...] }); // vehicle, see Vehicles.js; engine.player.enter(car) to board; car.remove()
13
13
  // Ray: once installed, engine.raycast(origin, direction, { targets: 'all' }) also hits rigid bodies (hit carries entry, kind: 'rigid'); no separate entry
14
14
  // point.
15
15
  //
16
16
  // Rapier is downloaded on demand at start() (about 1.5MB); games without physics never load it.
17
+ import { FALL_Y } from '../../core/scene/ground.js';
17
18
  import * as THREE from 'three';
18
19
  import { vec3, xzOf } from '../../core/base/math.js';
19
20
 
20
21
  import { readParams, keysSchema } from '../../core/base/params.js';
21
22
  import { cellsChanged } from '../../core/stream/streamCells.js';
22
23
  import { createVehicle, VEHICLE_KEYS, STRINGS } from './Vehicles.js';
23
- import { syncTerrain, syncTrees, treesChanged, syncGroundTrees, syncStatics, syncLevel, recordLocks, carryBody, carryCollider } from './sync.js';
24
+ import { syncTerrain, syncTrees, treesChanged, syncGroundTrees, syncStatics, restandStatics, syncLevel, syncFloor, dropChunks, wantsFloor, recordLocks, carryBody, carryCollider } from './sync.js';
25
+ import { refreshQueries } from './refresh.js';
24
26
  import { Ragdolls } from './ragdoll.js';
25
27
  import { codedError, coded } from '../../core/base/errorHints.js';
26
- import { refuseSave, saveNumberOk, SAVE_MAX } from '../../core/saves/saveValues.js';
28
+ import { refuseSave, saveNumberOk, SAVE_MAX } from '../../core/base/saveValues.js';
27
29
  import { warnOnce, DEV } from '../../core/base/validate.js';
30
+ import { follows } from '../../core/base/follows.js';
28
31
  // Params of addBox / addBall / addHull
32
+ // A body lives in world space, a mesh's position in its parent's: register the world pose and write the pose back through the parent. A parent whose scale differs
33
+ // between axes would shear the rotation (and no body can follow it), so that is refused by name instead of drifting.
34
+ const _p = new THREE.Vector3(), _q = new THREE.Quaternion(), _s = new THREE.Vector3(), _pq = new THREE.Quaternion();
35
+ function worldPose(mesh, who) {
36
+ const P = mesh.parent;
37
+ if (P) {
38
+ P.updateWorldMatrix(true, false); P.matrixWorld.decompose(_p, _pq, _s);
39
+ if (Math.abs(_s.x - _s.y) > 1e-4 || Math.abs(_s.x - _s.z) > 1e-4)
40
+ throw codedError('rigid-misuse', `${who}: '${mesh.name || mesh.type}' sits under '${P.name || P.type}' whose world scale (${_s.x.toFixed(3)}, ${_s.y.toFixed(3)}, ${_s.z.toFixed(3)}) differs between axes; a body cannot follow a sheared parent. Make the parent's scale equal on all axes, or give the body a mesh outside it`);
41
+ }
42
+ mesh.updateWorldMatrix(true, false); mesh.matrixWorld.decompose(_p, _q, _s);
43
+ return { p: _p, q: _q };
44
+ }
45
+ function setLocalPose(mesh, t, r) {
46
+ const P = mesh.parent;
47
+ if (!P || P.matrixWorld.equals(_I)) { mesh.position.set(t.x, t.y, t.z); mesh.quaternion.set(r.x, r.y, r.z, r.w); return; }
48
+ P.matrixWorld.decompose(_p, _pq, _s);
49
+ mesh.position.copy(P.worldToLocal(_p.set(t.x, t.y, t.z)));
50
+ mesh.quaternion.copy(_pq.invert().multiply(_q.set(r.x, r.y, r.z, r.w)));
51
+ }
52
+ const _I = new THREE.Matrix4(), _eu = new THREE.Euler(), _box = new THREE.Box3(), _part = new THREE.Box3(), _inv = new THREE.Matrix4(), _rel = new THREE.Matrix4();
53
+ /**
54
+ * The size a body gets from its model, as [x, y, z]: measured in the mesh's own axes, since the body takes its rotation, and at its world scale, parents included.
55
+ * The box around it in the world grew with the turn, so a turned crate got a larger body turned on top of that
56
+ */
57
+ function ownSize(mesh) {
58
+ mesh.updateWorldMatrix(true, true);
59
+ mesh.matrixWorld.decompose(_p, _q, _s);
60
+ _inv.copy(mesh.matrixWorld).invert(); _box.makeEmpty();
61
+ mesh.traverse(o => {
62
+ const g = o.geometry; if (!g) return;
63
+ if (!g.boundingBox) g.computeBoundingBox();
64
+ _box.union(_part.copy(g.boundingBox).applyMatrix4(_rel.multiplyMatrices(_inv, o.matrixWorld)));
65
+ });
66
+ return _box.getSize(_p).multiply(_s).toArray();
67
+ }
68
+ const NO_TURN = { x: 0, y: 0, z: 0, w: 1 };
69
+
29
70
  const PHYSICS = { physics: true }; // stream source filter (shared, not rebuilt every step)
71
+ /** A body this far down over the ground fell through it: the rule 'fall' is asked. Deep enough that no walkable level reaches it by accident; a level below it sets the rule to false */
72
+ const SOLID_PARAMS = keysSchema(['position', 'size', 'radius', 'rotation', 'friction']);
30
73
  const BODY_KEYS = ['id', 'mass', 'friction', 'restitution', 'damping', 'angularDamping', 'fixed'];
31
74
 
32
75
  /**
@@ -63,9 +106,10 @@ export class RigidBodies {
63
106
  /** terrainRing = chunk rings around each physics stream source that get terrain collision; buoyancyForce = buoyancy strength (1 = exactly floats); waterDrag = drag in water;
64
107
  * floatLine / floatDepth: buoyancy starts when the body center is below floatLine meters above the surface and peaks floatDepth meters deeper;
65
108
  * treeColliderHeight = trunk collision cylinder height; treeRadius = trunks get cylinders only in chunks within this many meters of the player or a non-fixed body;
66
- * playerCapsule { halfHeight, radius } = player capsule size (default derived from engine.movement radius / height) */
109
+ * playerCapsule { halfHeight, radius } = player capsule size (default derived from engine.movement radius / height);
110
+ * fallbackFloor = the flat plane at y = 0 when the ground has no collision of its own (default true; false for a game with only its own bodies and solids) */
67
111
  constructor(engine, { gravity = -9.81, terrainRing = 1, buoyancy = true, buoyancyForce = 1.6, waterDrag = 2.5, floatLine = 0.3, floatDepth = 0.8,
68
- treeColliderHeight = 6, treeRadius = 16, playerCapsule } = {}) {
112
+ treeColliderHeight = 6, treeRadius = 16, playerCapsule, fallbackFloor = true } = {}) {
69
113
  const mv = engine.movement; // default capsule uses the shared character radius / height: total height = 2 * halfHeight + 2 * radius
70
114
  playerCapsule ??= { halfHeight: Math.max(0.05, (mv.height - 2 * mv.radius) / 2), radius: mv.radius };
71
115
  this.engine = engine;
@@ -73,6 +117,7 @@ export class RigidBodies {
73
117
  this.terrainRing = terrainRing;
74
118
  this.buoyancy = buoyancy; this.buoyancyForce = buoyancyForce; this.waterDrag = waterDrag; this.playerCapsule = playerCapsule;
75
119
  this.floatLine = floatLine; this.floatDepth = floatDepth; this.treeColliderHeight = treeColliderHeight; this.treeRadius = treeRadius;
120
+ this.fallbackFloor = fallbackFloor;
76
121
  this.rapier = null; this.world = null;
77
122
  this.bodies = []; // { body, mesh, enabled }
78
123
  /** @internal body handle -> entry for rays, rebuilt only after bodies changed (null): a ray cast every frame (aim, a camera probe) built a new Map each time */ this._byHandle = null;
@@ -81,7 +126,10 @@ export class RigidBodies {
81
126
  this.trees = new Map(); // chunk key -> { token, colliders }: trunk cylinders of the chunks near the player / bodies (see sync.js)
82
127
  this._anchors = []; this._treeMemo = [];
83
128
  this.groundTrees = new Map(); // 'x,z,r' -> cylinder collider: circles from ground.forEachCollider when the ground has no chunked collision
84
- /** @internal houses / pillars of the collision module as colliders (engine.collision.mirror, built on the first step: sync.js syncStatics) */ this._statics = null;
129
+ /** @internal houses / pillars of the collision module as colliders (engine.collision.mirror, built on the first step: sync.js syncStatics) */ this._statics = null; /** @internal mirror data -> collider, for those standing on the ground */ this._onGround = new Map();
130
+ /** @internal the sources of the copies above, checked on every read (_current) */ this._collision = follows(() => engine.collision); this._level = follows(() => engine.ground.staticTrimeshes ?? null, () => engine.ground.staticVersion?.() ?? 0); this._standOn = follows(() => engine.ground, G => G.staticVersion?.() ?? 0); this._floor = follows(() => wantsFloor(this));
131
+ /** @internal the world changed since Rapier last built its query structures, which it does only in a step */ this._behind = false;
132
+ /** @internal fixed solids of the collider3d contract: what they are, so every new world (init, _fresh) builds them; a collider only lives as long as its world */ this._solids = new Set();
85
133
  this.vehicles = [];
86
134
  /** @internal numbers vehicles added without an id */ this._vehicleSeq = 0;
87
135
  /** @internal id -> saved physics state of a body not built yet (the save part 'rigid'; claimed when a body with that id is added) */ this._saved = new Map();
@@ -104,16 +152,26 @@ export class RigidBodies {
104
152
  /** @internal A fresh Rapier world with the player capsule (and the flat plane without chunked ground): what init builds, and what _fresh rebuilds */
105
153
  _newWorld() {
106
154
  const R = this.rapier;
107
- /** @internal bumps with every world: a character mover holding a controller of an older world builds a new one (movers/rapier.js) */
108
- this.gen = (this.gen ?? 0) + 1;
109
155
  this.world = new R.World({ x: 0, y: this.gravity, z: 0 });
110
156
  // Player capsule (kinematic: the character controller decides position; physics only pushes other things away)
111
157
  this.playerBody = this.world.createRigidBody(R.RigidBodyDesc.kinematicPositionBased());
112
158
  const pc = this.playerCapsule;
113
159
  this.playerCollider = this.world.createCollider(R.ColliderDesc.capsule(pc.halfHeight, pc.radius).setTranslation(0, pc.halfHeight + pc.radius, 0), this.playerBody);
114
- // When the ground provides no chunked collision (no terrain module): use an infinite flat plane (y = 0)
115
- const G = this.engine.ground;
116
- if (!G.chunkCollision && !G.staticTrimeshes) this.world.createCollider(R.ColliderDesc.cuboid(5000, 0.5, 5000).setTranslation(0, -0.5, 0));
160
+ this._floorCollider = null; this._floor.reset(); syncFloor(this); // a new world has none. Here, so colliders keep the order a fresh page builds them in
161
+ for (const s of this._solids) this._buildSolid(s);
162
+ }
163
+
164
+ /** @internal Copies of what others own are current, as any read needs them. Every step runs it; a frozen engine runs no step, and queries still ask */
165
+ _upkeep() { if (syncStatics(this) | syncLevel(this) | syncFloor(this) | dropChunks(this)) this._behind = true; }
166
+ /**
167
+ * @internal Every query starts here, and answers whether physics can be asked. Rapier has no call that refreshes its query structures alone (refresh.js), so a step of no time does, twice (one leaves a moved body or a reused collider slot out, measured in `refresh while frozen`): nothing
168
+ * moves, and it runs only when something changed, so a ray pays three compares.
169
+ */
170
+ _current() {
171
+ if (!this.ready) return false;
172
+ this._upkeep();
173
+ if (this._behind) { refreshQueries(this.world); this._behind = false; }
174
+ return true;
117
175
  }
118
176
 
119
177
  /**
@@ -125,7 +183,7 @@ export class RigidBodies {
125
183
  * body or collider itself (gravityScale, axis locks, ccd, dominance, sensor, groups, enabled) is carried onto the rebuilt one (carryBody / carryCollider in sync.js). Joints are not carried: Rapier has no getters for a joint's
126
184
  * whole description (rope length, motor settings), and copying one would mean patching Rapier. The game re-creates its own joints on rigid:rebuilt,
127
185
  * emitted once the bodies are back (the coordination point); a dev warning names a game whose joints vanished with no re-creation. Movers'
128
- * character controllers are freed with the old world (World.free frees them; movers/rapier.js sees the new gen and builds new ones).
186
+ * character controllers are freed with the old world (World.free frees them; movers/rapier.js sees another world object and builds new ones).
129
187
  * Vehicles hold a controller built for one world: with a vehicle present only the bodies are stopped and put to sleep (no rebuild).
130
188
  */
131
189
  _fresh() {
@@ -137,8 +195,8 @@ export class RigidBodies {
137
195
  }
138
196
  const old = this.world, R = this.rapier, hadJoints = old.impulseJoints.len();
139
197
  this._newWorld();
140
- this.terrain.clear(); this.trees.clear(); this.groundTrees.clear(); this._statics?.clear();
141
- this._levelVersion = undefined; this._levelColliders = [];
198
+ this.terrain.clear(); this.trees.clear(); this.groundTrees.clear(); this._statics?.clear(); this._onGround.clear();
199
+ this._level.reset(); this._levelColliders = [];
142
200
  this._srcMemo = null; this._srcPending = false; this._syncT = 0; this._anchors = []; this._treeMemo = [];
143
201
  for (const b of this.bodies) {
144
202
  const t = b.body.translation(), q = b.body.rotation();
@@ -150,7 +208,7 @@ export class RigidBodies {
150
208
  // what the game wrote on the Rapier body / collider (gravityScale, locks, ccd, sensor, groups, enabled...) is its own and survives the rebuild
151
209
  carryBody(b, ob, b.body); carryCollider(oc, b.collider);
152
210
  // b.enabled stays: it is the engine's own freeze flag (no ground under it), which the step loop compares with; a game's setEnabled(false) was carried
153
- b.wet = false; b._void = false;
211
+ b.wet = false; b._void = false; b._fell = false;
154
212
  }
155
213
  old.free(); this._byHandle = null; // every body has a new handle
156
214
  // the old world's joints (every one is the game's: the engine makes none) went with it. The game re-creates them here, between the rebuilt bodies
@@ -174,7 +232,7 @@ export class RigidBodies {
174
232
  _add(mesh, desc, { id, mass = 1, friction = 0.7, restitution = 0.1, damping = 0.05, angularDamping = 0.1, fixed = false } = {}) {
175
233
  // id names the body in the save part 'rigid': two live bodies with one id would load into each other
176
234
  if (id != null && this.bodies.some(b => b.id === id)) throw codedError('rigid-misuse', `rigid: id '${id}' is already used by another body or vehicle; ids name the body in saves, pick a unique one (e.g. the world record id)`);
177
- const R = this.rapier, p = mesh.position, q = mesh.quaternion;
235
+ const R = this.rapier, { p, q } = worldPose(mesh, 'rigid');
178
236
  const bd = (fixed ? R.RigidBodyDesc.fixed() : R.RigidBodyDesc.dynamic())
179
237
  .setTranslation(p.x, p.y, p.z).setRotation({ x: q.x, y: q.y, z: q.z, w: q.w })
180
238
  .setLinearDamping(damping).setAngularDamping(angularDamping).setCanSleep(true);
@@ -185,25 +243,26 @@ export class RigidBodies {
185
243
  const entry = { id, body, collider, mesh, object: mesh, enabled: true, volume: 0, damping, angularDamping, fixed, _x: p.x, _z: p.z, _desc: desc }; // _x / _z: where sync.js looks for trunks to give it
186
244
  entry.remove = () => this._remove(entry);
187
245
  recordLocks(entry, body);
188
- this.bodies.push(entry); this._byHandle = null;
189
- this.engine._poses.add(mesh);
246
+ this.bodies.push(entry); this._byHandle = null; this._behind = true;
247
+ // a write to the record of this model lands here (world/views.js placed); with rigid gone first at dispose the model is on its own
248
+ // entry.place: a template's copy says what a written place means for it (content/templates.js)
249
+ this.engine._poses.add(mesh, at => { if (this.world) this.setPosition(entry, entry.place?.(at) ?? at); }, () => entry.remove());
190
250
  // a loaded save holds this body's state (it is built after the load, e.g. by a world presenter): it continues from there, not from the record's pose
191
- const s = id != null && this._saved.get(id);
192
- if (s) { this._saved.delete(id); putState(entry, s); }
251
+ this._claim(entry);
193
252
  return entry;
194
253
  }
195
254
  /** Box. When size is omitted it is computed from the model bounding box */
196
255
  addBox(mesh, o = {}) {
197
256
  readParams('rigid.addBox()', keysSchema([...BODY_KEYS, 'size']), o);
198
257
  if (!this._ready('addBox')) return null;
199
- const s = o.size || new THREE.Box3().setFromObject(mesh).getSize(new THREE.Vector3()).toArray();
258
+ const s = o.size || ownSize(mesh);
200
259
  return this._add(mesh, this.rapier.ColliderDesc.cuboid(s[0] / 2, s[1] / 2, s[2] / 2), o);
201
260
  }
202
261
  /** Ball */
203
262
  addBall(mesh, o = {}) {
204
263
  readParams('rigid.addBall()', keysSchema([...BODY_KEYS, 'radius']), o);
205
264
  if (!this._ready('addBall')) return null;
206
- const r = o.radius ?? new THREE.Box3().setFromObject(mesh).getSize(new THREE.Vector3()).x / 2;
265
+ const r = o.radius ?? ownSize(mesh)[0] / 2;
207
266
  return this._add(mesh, this.rapier.ColliderDesc.ball(r), o);
208
267
  }
209
268
  /** Convex hull: auto-wrapped around the model shape (irregular objects such as rocks, barrels) */
@@ -212,8 +271,10 @@ export class RigidBodies {
212
271
  if (!this._ready('addHull')) return null;
213
272
  const g = mesh.geometry, pts = new Float32Array(g.attributes.position.array.length);
214
273
  const v = new THREE.Vector3();
274
+ mesh.updateWorldMatrix(true, false); mesh.matrixWorld.decompose(_p, _q, _s); // the world scale: a parent's counts as much as the mesh's own
275
+ const scale = _s.clone();
215
276
  for (let i = 0; i < g.attributes.position.count; i++) {
216
- v.fromBufferAttribute(g.attributes.position, i).multiply(mesh.scale); pts.set([v.x, v.y, v.z], i * 3);
277
+ v.fromBufferAttribute(g.attributes.position, i).multiply(scale); pts.set([v.x, v.y, v.z], i * 3);
217
278
  }
218
279
  return this._add(mesh, this.rapier.ColliderDesc.convexHull(pts), o);
219
280
  }
@@ -236,8 +297,8 @@ export class RigidBodies {
236
297
  /** Remove a vehicle (the occupant exits first): called by vehicle.remove() */
237
298
  _removeVehicle(v) {
238
299
  if (!this.vehicles.includes(v)) return;
239
- for (const p of [...v.passengers]) p.exit();
240
- v.driver?.exit(); v._use?.remove();
300
+ for (const p of [...v.passengers]) p.exit({ force: true });
301
+ v.driver?.exit({ force: true }); v._use?.remove(); v.gone = true; v._seatBook?.remove();
241
302
  this.vehicles = this.vehicles.filter(x => x !== v);
242
303
  this.world.removeVehicleController(v.controller);
243
304
  this._remove(v);
@@ -245,8 +306,9 @@ export class RigidBodies {
245
306
  /**
246
307
  * Turn a skinned character limp, one call; rd.remove() returns it to animation. Its mover, animation, capsule and camera yield until then. @experimental
247
308
  * @param {any} who a Character, an NPC handle, a character id or a skinned Object3D
248
- * @param {{ impulse?: any, position?: any, bones?: Record<string, any>, limits?: Record<string, any>, mass?: number }} [o] impulse: a push (kg*m/s) on the part nearest position, else on hips; bones: part -> bone name or bone, over the auto-detection; limits: part or kind ('lowerLeg') -> { bend, side, twist } as [min, max] radians from the bind pose; mass: whole body, default 70 kg
249
- * @example const rd = engine.rigid.ragdoll(player, { impulse: [0, 200, -300], position: hit.point }); engine.clock.after(4, () => rd.remove());
309
+ * The rule 'ragdoll.graph' says which parts it has: 'humanoid' (default), a graph { part: { bone, parent, limits, mass } }, or false for none (returns null).
310
+ * @param {{ impulse?: any, position?: any, bones?: Record<string, any>, limits?: Record<string, any>, mass?: number }} [o] impulse: a push (kg*m/s) on the part nearest position, else on the root part; bones: humanoid part -> bone name or bone, over the auto-detection; limits: part or kind ('lowerLeg') -> { bend, side, twist } as [min, max] radians from the bind pose; mass: whole body, default the graph's (humanoid 70 kg)
311
+ * @example const rd = engine.rigid.ragdoll(player, { impulse: [0, 200, -300], position: hit.point }); engine.clock.after(4, () => rd.remove(), { channel: 'real' });
250
312
  */
251
313
  ragdoll(who, o) {
252
314
  if (!this._ready('ragdoll')) return null;
@@ -268,7 +330,8 @@ export class RigidBodies {
268
330
  /** Delete the body (called by entry.remove()); the model stays */
269
331
  _remove(entry) {
270
332
  const i = this.bodies.indexOf(entry); if (i < 0) return;
271
- this.world.removeRigidBody(entry.body); this.bodies.splice(i, 1); this._byHandle = null;
333
+ this.world?.removeRigidBody(entry.body); // no world: rigid left first at dispose and freed its bodies with it
334
+ this.bodies.splice(i, 1); this._byHandle = null; this._behind = true;
272
335
  this.engine._poses.remove(entry.mesh);
273
336
  }
274
337
  /** Push: impulse vector v (Vector3 / [x, y, z] / { x, y, z }) */
@@ -277,12 +340,56 @@ export class RigidBodies {
277
340
  setPosition(entry, position) {
278
341
  const { x, y, z } = vec3(position);
279
342
  entry._x = x; entry._z = z;
280
- entry.body.setTranslation({ x, y, z }, true); entry.body.setLinvel({ x: 0, y: 0, z: 0 }, true);
343
+ entry.body.setTranslation({ x, y, z }, true); entry.body.setLinvel({ x: 0, y: 0, z: 0 }, true); this._behind = true;
344
+ }
345
+
346
+ // ---------- The collider3d contract (collider3d.contract.js): engine.collider3d is this object ----------
347
+ /**
348
+ * A fixed solid turned any way: size [x, y, z] for a box or radius for a ball, rotation [x, y, z] radians or a quaternion. Returns { remove() }. Callable before start();
349
+ * newGame and a load keep it. Bodies and the rapier mover hit it; engine.collision does not know it, so a simple-mover walker walks through.
350
+ * @example const ramp = engine.collider3d.addSolid({ position: [0, 2, 0], size: [8, 0.5, 3], rotation: [0, 0, 0.4] });
351
+ */
352
+ addSolid(o) {
353
+ readParams('collider3d.addSolid()', SOLID_PARAMS, o);
354
+ if ((o.size == null) === (o.radius == null)) throw codedError('rigid-misuse', `collider3d.addSolid(): give exactly one of size ([x, y, z], a box) or radius (a ball)`);
355
+ const s = { o, collider: null, remove: () => { if (this._solids.delete(s) && this.world && s.collider) { this.world.removeCollider(s.collider, false); this._behind = true; } } };
356
+ this._solids.add(s);
357
+ if (this.world) this._buildSolid(s);
358
+ return s;
359
+ }
360
+ /** @internal */
361
+ _buildSolid(s) {
362
+ const R = this.rapier, { position, size, radius, rotation, friction = 0.9 } = s.o, p = vec3(position);
363
+ const q = Array.isArray(rotation) ? _q.setFromEuler(_eu.fromArray(rotation)) : rotation ? _q.set(rotation.x, rotation.y, rotation.z, rotation.w) : _q.identity();
364
+ const desc = size ? R.ColliderDesc.cuboid(size[0] / 2, size[1] / 2, size[2] / 2) : R.ColliderDesc.ball(radius);
365
+ s.collider = this.world.createCollider(desc.setTranslation(p.x, p.y, p.z).setRotation({ x: q.x, y: q.y, z: q.z, w: q.w }).setFriction(friction));
366
+ this._behind = true;
367
+ }
368
+ /** Is a ball here inside something solid (false before physics is ready). Sees the world as it stands now, also while frozen; skips the player's capsule */
369
+ overlap(position, radius = 0.01) {
370
+ if (!this._current()) return false;
371
+ const R = this.rapier, { x, y, z } = vec3(position);
372
+ return !!this.world.intersectionWithShape({ x, y, z }, NO_TURN, new R.Ball(radius), R.QueryFilterFlags.EXCLUDE_SENSORS, undefined, undefined, this.playerBody);
373
+ }
374
+ /**
375
+ * Move a ball from there to there: null when clear, else the first hit { point, normal, distance }: point is the ball's center at the hit, normal the world direction out of what it hit.
376
+ * A ball that starts touching or inside a solid and moves out of it is clear: a flyer taking off from the ground must not be held by the ground it stands on.
377
+ * @example const hit = engine.collider3d.sweep(drone.position, next, 0.4); if (hit) drone.position.copy(hit.point);
378
+ */
379
+ sweep(from, to, radius = 0.01) {
380
+ if (!this._current()) return null;
381
+ const R = this.rapier, a = vec3(from), d = vec3(to).sub(a), len = d.length();
382
+ if (!len) return null;
383
+ d.divideScalar(len);
384
+ const hit = this.world.castShape({ x: a.x, y: a.y, z: a.z }, NO_TURN, { x: d.x, y: d.y, z: d.z }, new R.Ball(radius), 0, len, false, R.QueryFilterFlags.EXCLUDE_SENSORS, undefined, undefined, this.playerBody);
385
+ if (!hit) return null;
386
+ const n = hit.normal1; // world space on World.castShape (the tilted-box test fails first if an upgrade changes that)
387
+ return { point: a.addScaledVector(d, hit.time_of_impact), normal: new THREE.Vector3(n.x, n.y, n.z), distance: hit.time_of_impact };
281
388
  }
282
389
 
283
390
  /** Ray (provider for engine.rays, called by engine.raycast when targets: 'all'): hits dynamic bodies only, returns RayHit (with entry, kind: 'rigid') */
284
391
  _raycast(origin, dir, far) {
285
- if (!this.ready || !this.bodies.length) return null;
392
+ if (!this._current() || !this.bodies.length) return null;
286
393
  let byHandle = this._byHandle;
287
394
  if (!byHandle) { byHandle = this._byHandle = new Map(); for (const b of this.bodies) byHandle.set(b.body.handle, b); }
288
395
  const max = Number.isFinite(far) ? far : 1e6;
@@ -299,12 +406,14 @@ export class RigidBodies {
299
406
  // ---------- Save part 'rigid' ----------
300
407
  /**
301
408
  * @internal What a save keeps of each body with an id (addBox / addBall / addHull({ id }), vehicles always): pose, velocities, asleep. Without it a
302
- * load put a toppling crate back upright and at rest wherever its record was, so the game after the load was not the game that was saved. Bodies
303
- * not built yet keep their loaded state (it is still the saved game). Not kept: Rapier's contact / warm-start caches (docs/recipes/11-vehicles.md, section 3).
409
+ * load put a toppling crate back upright and at rest wherever its record was, so the game after the load was not the game that was saved. A template
410
+ * body carries its record id, and atRest (content/templates.js): while it stands where content put it, content is its state and it stays out of the save.
411
+ * Bodies not built yet keep their loaded state (it is still the saved game). Not kept: Rapier's contact / warm-start caches (docs/recipes/11-vehicles.md, section 3).
304
412
  */
305
413
  _saveState() {
306
- const out = Object.fromEntries(this._saved);
307
- for (const b of this.bodies) if (b.id != null) out[b.id] = stateOf(b.body);
414
+ const out = {};
415
+ for (const [id, s] of this._saved) if (!this._outrun(id, s)) out[id] = s;
416
+ for (const b of this.bodies) if (b.id != null && !b.atRest) out[b.id] = stateOf(b.body);
308
417
  return out;
309
418
  }
310
419
  /** @internal Load: bodies here now take their state in afterLoad (after _fresh rebuilt them); the rest when they are added */
@@ -316,7 +425,24 @@ export class RigidBodies {
316
425
  }
317
426
  /** @internal afterLoad: hand the loaded state to the bodies that exist (vehicles, bodies the game keeps across a load) */
318
427
  _claimSaved() {
319
- for (const b of this.bodies) { const s = b.id != null && this._saved.get(b.id); if (s) { this._saved.delete(b.id); putState(b, s); } }
428
+ for (const b of this.bodies) this._claim(b);
429
+ }
430
+ /** @internal A body takes its loaded state, the one way in */
431
+ _claim(entry) {
432
+ if (entry.id == null) return;
433
+ const s = this.stateFor(entry.id);
434
+ this._saved.delete(entry.id);
435
+ if (s) putState(entry, s);
436
+ }
437
+ /** @internal The loaded state a body built now with this id takes, or null. Asked before the build too: a copy about to take a state is not where content put it (content/templates.js addBody) */
438
+ stateFor(id) {
439
+ const s = this._saved.get(id);
440
+ return s && !this._outrun(id, s) ? s : null;
441
+ }
442
+ /** @internal The world record of a body not built yet was moved after this state was saved (no body was there to take the write): the newer write wins, as in views.pull */
443
+ _outrun(id, s) {
444
+ const W = this.engine.world, rec = W?.records.get(id), p = rec?.position;
445
+ return !!p && W.presents(rec.kind) && Math.max(Math.abs(p.x - s[0]), Math.abs(p.y - s[1]), Math.abs(p.z - s[2])) > 1e-3; // presented: a record that only shares its id with a game's body follows nothing
320
446
  }
321
447
 
322
448
  // ---------- Every fixed step ----------
@@ -340,8 +466,7 @@ export class RigidBodies {
340
466
  if (chunked) { pending = syncTerrain(this, src); pending = syncTrees(this, focus, CH) || pending; } else syncGroundTrees(this, src, CH);
341
467
  this._srcPending = pending; this._syncT = 0; // pending: chunks still waiting for their turn, sync again next step
342
468
  }
343
- syncStatics(this);
344
- syncLevel(this);
469
+ this._upkeep();
345
470
  if (this._jointsGone) { // dev only (set in _fresh): the old world had the game's joints and nothing re-created one since the rebuild
346
471
  if (!this.world.impulseJoints.len()) warnOnce(coded('rigid-misuse', `rigid: ${this._jointsGone} joint(s) were freed with the old physics world by newGame / load and none was re-created. The engine rebuilds the world and does not copy joints: re-create them in a rigid:rebuilt listener ({ world }), between entry.body of the rebuilt bodies (recipes/11-vehicles.md, Joints)`));
347
472
  this._jointsGone = 0;
@@ -361,27 +486,25 @@ export class RigidBodies {
361
486
  const ok = !chunked || this._chunkReady(t.x, t.z);
362
487
  if (ok !== b.enabled) { if (DEV && !ok) this._tellFrozen(b, t, CH); b.body.setEnabled(ok); b.enabled = ok; }
363
488
  // buoyancy: the submerged part gets an upward force, and water adds drag
364
- const water = this.buoyancy ? e.waterAt(t.x, t.z) : -Infinity;
489
+ const water = this.buoyancy ? e.waterAt(t.x, t.z, t.y) : -Infinity; // at its own height: a game's water body may be a pool upstairs or a falling column
365
490
  if (ok && this.buoyancy && t.y < water + this.floatLine && b.body.isDynamic()) {
366
491
  const depth = Math.min(1, (water + this.floatLine - t.y) / this.floatDepth);
367
492
  const m = b.body.mass();
368
- b.body.resetForces(true);
369
- b.body.addForce({ x: 0, y: -this.gravity * m * (this.buoyancyForce * depth), z: 0 }, true);
493
+ b.body.applyImpulse({ x: 0, y: -this.gravity * m * (this.buoyancyForce * depth) * worldDt, z: 0 }, true); // an impulse, not addForce: Rapier keeps forces until reset, and a reset would wipe the game's own thrust / wind on the same body
370
494
  b.body.setLinearDamping(this.waterDrag); b.body.setAngularDamping(this.waterDrag);
371
495
  b.wet = true;
372
496
  } else if (b.wet) {
373
- b.body.resetForces(true); b.body.setLinearDamping(b.damping); b.body.setAngularDamping(b.angularDamping); b.wet = false;
497
+ b.body.setLinearDamping(b.damping); b.body.setAngularDamping(b.angularDamping); b.wet = false;
374
498
  }
375
499
  }
376
500
 
377
- if (worldDt > 0) { this.world.timestep = worldDt; this.world.step(); }
501
+ if (worldDt > 0) { this.world.timestep = worldDt; this.world.step(); this._behind = false; }
378
502
 
379
503
  for (const b of this.bodies) {
380
504
  if (!b.enabled || b.body.isSleeping() || b.ragdoll) continue; // ragdoll parts are drawn by ragdoll.js, through the bones
381
505
  const t = b.body.translation(), r = b.body.rotation();
382
- b.mesh.position.set(t.x, t.y, t.z);
383
- b.mesh.quaternion.set(r.x, r.y, r.z, r.w);
384
- if (t.y < -200 && e.ground.has(t.x, t.z)) this.setPosition(b, [t.x, e.surface(t.x, t.z) + 2, t.z]); // fell through the ground
506
+ setLocalPose(b.mesh, t, r);
507
+ this._fallen(b, t);
385
508
  // fell off terrain({ shape }): one terrain:void per fall, the game decides what next
386
509
  const under = t.y < e.ground.voidY();
387
510
  if (under && !b._void) e.events.emit('terrain:void', { who: b, position: { x: t.x, y: t.y, z: t.z } });
@@ -391,6 +514,18 @@ export class RigidBodies {
391
514
  this._ragdolls?.sync();
392
515
  }
393
516
 
517
+ /**
518
+ * @internal Fell through the ground: the rule 'fall' decides (nothing happens until the game sets one; 'rescue' is the built-in), asked once per fall so a game's function sees one event, not one per step; b._fell stays set
519
+ * while a body it left down there is still down. Only over ground: out past the map edge there is nothing to put it back on.
520
+ */
521
+ _fallen(b, t) {
522
+ const e = this.engine, out = t.y < FALL_Y && e.ground.has(t.x, t.z);
523
+ if (!out) { b._fell = false; return; }
524
+ if (b._fell) return;
525
+ b._fell = this._fall.decide(b.id, { kind: 'body', who: b, position: { x: t.x, y: t.y, z: t.z } }) !== 'rescue';
526
+ if (!b._fell) this.setPosition(b, [t.x, e.surface(t.x, t.z, t.y) + 2, t.z]); // from below every floor the height picks the lowest: the one it went through, not a deck or a mountain over a cave
527
+ }
528
+
394
529
  get stats() {
395
530
  const active = this.bodies.filter(b => b.enabled && !b.body.isSleeping()).length;
396
531
  return { bodies: this.bodies.length, active, colliders: this.world ? this.world.colliders.len() : 0 };
@@ -404,35 +539,40 @@ function stateOf(b) {
404
539
  }
405
540
  function putState(entry, s) {
406
541
  const b = entry.body, m = entry.mesh;
542
+ entry.atRest = false;
543
+ // sleep first: Rapier's sleep() clears speed, and a body falls asleep with the speed it last had, which it moves off with when woken
544
+ if (s[13]) b.sleep(); else b.wakeUp();
407
545
  b.setTranslation({ x: s[0], y: s[1], z: s[2] }, false); b.setRotation({ x: s[3], y: s[4], z: s[5], w: s[6] }, false);
408
546
  b.setLinvel({ x: s[7], y: s[8], z: s[9] }, false); b.setAngvel({ x: s[10], y: s[11], z: s[12] }, false);
409
- if (s[13]) b.sleep(); else b.wakeUp();
410
- m.position.set(s[0], s[1], s[2]); m.quaternion.set(s[3], s[4], s[5], s[6]);
547
+ setLocalPose(m, { x: s[0], y: s[1], z: s[2] }, { x: s[3], y: s[4], z: s[5], w: s[6] });
411
548
  entry._x = s[0]; entry._z = s[2];
412
549
  }
413
550
 
414
- const RIGID_PARAMS = keysSchema(['gravity', 'terrainRing', 'buoyancy', 'buoyancyForce', 'waterDrag', 'floatLine', 'floatDepth', 'treeColliderHeight', 'treeRadius', 'playerCapsule']);
551
+ const RIGID_PARAMS = keysSchema(['gravity', 'terrainRing', 'buoyancy', 'buoyancyForce', 'waterDrag', 'floatLine', 'floatDepth', 'treeColliderHeight', 'treeRadius', 'playerCapsule', 'fallbackFloor']);
415
552
 
416
553
  /** Real physics module (Rapier). Installs as engine.rigid. Requires collision() to be installed first */
417
554
  export function rigid(opts = {}) {
418
555
  readParams('rigid', RIGID_PARAMS, opts);
419
556
  let r = null;
420
557
  return {
421
- name: 'rigid', type: 'world', provides: ['rigid'], params: RIGID_PARAMS, options: opts, label: 'Physics', noSkip: 'bodies rest while time jumps (stepping seconds of physics would only scatter them)', optional: ['interactions', 'cameraRig'], requires: ['collision'],
558
+ name: 'rigid', skipKind: 'none', type: 'world', provides: ['rigid', 'collider3d'], params: RIGID_PARAMS, options: opts, label: 'Physics', noSkip: 'bodies rest while time jumps (stepping seconds of physics would only scatter them)', optional: ['interactions', 'cameraRig', 'characters'], requires: ['collision'],
422
559
  install(e, ctx) {
423
560
  e.i18n.add(STRINGS); e.i18n.add({ 'zh-CN': { 'module.rigid': '物理引擎' }, en: { 'module.rigid': 'physics' } }); r = new RigidBodies(e, opts);
561
+ r._fall = ctx.rule('fall', false, ['rescue']); // shared with characters: one rule for everything that falls out of the world; no rescue unless the game chose it
562
+ r._graph = ctx.rule('ragdoll.graph', 'humanoid');
424
563
  r._wasm().catch(() => {}); // start loading now (see _wasm); a failure surfaces in init, which awaits the same promise
425
- e.budget.metric('rigidBodies', () => r.bodies.length);
426
- e.stream.addReadyCheck('rigid', s => !s.physics || r.ready && r.readyAt(s)); // a physics stream source waits for the collider under it
427
- e.rays.addProvider((o, d, far) => r._raycast(o, d, far)); // engine.raycast(..., { targets: 'all' }) includes rigid bodies
564
+ ctx.budget.metric('rigidBodies', () => r.bodies.length);
565
+ ctx.stream.addReadyCheck('rigid', s => !s.physics || r.ready && r.readyAt(s)); // a physics stream source waits for the collider under it
566
+ ctx.track(e.rays.addProvider((o, d, far) => r._raycast(o, d, far))); // engine.raycast(..., { targets: 'all' }) includes rigid bodies
428
567
  // a new playthrough / a load is a fresh page for physics too (_fresh), rebuilt once per load: session:end only marks it due. With the world
429
568
  // module the rebuild runs on world:load, after the load removed the records' bodies, so the rebuilt world gets them back in view order; without
430
569
  // it, afterLoad (newGame / load / quit all apply a save) runs it. Rebuilding on both events built the world twice per new game.
431
- // A refused load (session:failed) leaves the game as it was, physics included.
570
+ // A refused load (session:failed) leaves the game as it was, physics included: no afterLoad runs after a rollback, so the state its rigid part read back is claimed here.
571
+ ctx.track(e.events.on('ground:change', b => { r._srcPending = true; restandStatics(r, b); })); // dug or raised ground: colliders follow on the next step, not at the half-second check a body could fall through
432
572
  ctx.track(e.events.on('session:end', () => { r._freshDue = true; }));
433
- ctx.track(e.events.on('session:failed', () => { r._freshDue = false; }));
573
+ ctx.track(e.events.on('session:failed', () => { r._freshDue = false; r._claimSaved(); }));
434
574
  ctx.track(e.events.on('world:load', () => r._fresh()));
435
- e.saves.register('rigid', { save: () => r._saveState(), load: d => r._loadState(d) });
575
+ ctx.saves.register('rigid', { notAtomic: 'the physics world is stepped, not written: a load cannot rewind what the bodies did', save: () => r._saveState(), load: d => r._loadState(d) });
436
576
  return r;
437
577
  },
438
578
  afterLoad() { if (r._freshDue) r._fresh(); r._claimSaved(); }, // after every part loaded and _fresh rebuilt the world (world:load is emitted inside the world part's load)
@@ -442,9 +582,12 @@ export function rigid(opts = {}) {
442
582
  describe() {
443
583
  const B = r.bodies, n = f => B.filter(f).length;
444
584
  return { ready: r.ready, bodies: B.length, dynamic: n(b => !b.fixed), fixed: n(b => b.fixed), sleeping: n(b => b.enabled && b.body.isSleeping()),
445
- frozen: n(b => !b.enabled), vehicles: r.vehicles.length, colliders: r.world ? r.world.colliders.len() : 0, ...(r._ragdolls?.live.size && { ragdolls: r._ragdolls.live.size }) };
585
+ frozen: n(b => !b.enabled), vehicles: r.vehicles.length, colliders: r.world ? r.world.colliders.len() : 0, ...(r._ragdolls?.live.size && { ragdolls: r._ragdolls.live.size }), ...(r._solids.size && { solids: r._solids.size }) };
446
586
  },
447
587
  fixed(dt) { r.step(dt); },
448
- dispose() { r._ragdolls?.dispose(); r.world?.free(); r.world = null; },
588
+ // a vehicle lives in this world: its riders get out while the seat and the exit can still be read, or they would read a freed solver every step
589
+ dispose() { for (const v of [...r.vehicles]) r._removeVehicle(v); r._ragdolls?.dispose(); r.world?.free(); r.world = null; },
449
590
  };
450
591
  }
592
+
593
+ export const handRolled = [{ kind: 'physics', seen: 'a physics library of its own', use: 'rigid(): bodies, joints and vehicles on the engine step, shared with collision and saves (recipe 11)', quiet: /\b(engine|e|eng|ctx)\.rigid\b|\brigid\(\s*[{)]/, raw: /\bfrom\s+['"](?:cannon-es|cannon|ammo\.js|@dimforge\/rapier3d(?:-compat)?|oimo|matter-js)['"]/ }];
@@ -49,7 +49,7 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
49
49
  const drives = wheels.filter(x => x.drive).length || wheels.length;
50
50
  // seat 0 drives, the rest ride; without seats one driver seat at the chassis center
51
51
  const seatAt = seats?.length ? seats.map(p => vec3(p)) : [new THREE.Vector3(c.x, c.y, c.z)];
52
- let throttle = 0, steerIn = 0, brake = 0;
52
+ let throttle = 0, steerIn = 0, brake = 0, useFrom;
53
53
 
54
54
  const v = Object.assign(entry, {
55
55
  controller: ctl, wheels, driver: null, camera, hideDriver, seats: seatAt.length, passengers: [],
@@ -57,10 +57,15 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
57
57
  drive(t, st, b = 0) { throttle = t; steerIn = st; brake = b; if (t || b) entry.body.wakeUp(); },
58
58
  /** World position of a seat (0 = driver) */
59
59
  seatPosition(seat = 0) { return mesh.localToWorld((seatAt[seat] ?? seatAt[0]).clone()); },
60
- /** Exit position of a seat: exitOffset meters outside the door on that seat's side (default 0.8) */
61
- exitPosition(seat = 0) { const a = seatAt[seat] ?? seatAt[0]; return mesh.localToWorld(new THREE.Vector3(c.x + (a.x >= c.x ? 1 : -1) * (s.x / 2 + exitOffset), c.y, a.z)); },
60
+ /** Exit n of a seat, null past the last: exitOffset meters (default 0.8) outside its own door, the other door, behind, in front */
61
+ exitPosition(seat = 0, n = 0) {
62
+ const a = seatAt[seat] ?? seatAt[0], x = (a.x >= c.x ? 1 : -1) * (s.x / 2 + exitOffset), z = s.z / 2 + exitOffset;
63
+ const at = [[c.x + x, a.z], [c.x - x, a.z], [c.x, c.z - z], [c.x, c.z + z]][n];
64
+ return at ? mesh.localToWorld(new THREE.Vector3(at[0], c.y, at[1])) : null;
65
+ },
62
66
  /** Every fixed step: write controls to the wheels and advance the vehicle controller (called before the physics step) */
63
67
  _update(dt) {
68
+ if (useFrom !== e.interactions) offerSeat();
64
69
  wheels.forEach((wh, i) => {
65
70
  ctl.setWheelEngineForce(i, wh.drive || drives === wheels.length ? throttle * engineForce / drives : 0);
66
71
  ctl.setWheelSteering(i, wh.steer ? -steerIn * maxSteer : 0);
@@ -86,7 +91,10 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
86
91
  return l.x * fwd.x + l.y * fwd.y + l.z * fwd.z;
87
92
  } });
88
93
  // With the interactions module installed: press the interact key near the car to get in, and again while driving to get out
89
- if (e.interactions) {
94
+ const offerSeat = () => {
95
+ v._use?.remove(); v._use = null;
96
+ useFrom = e.interactions; // the use lives in that module: another one starts empty, so _update offers the seat again
97
+ if (!e.interactions) return;
90
98
  v._use = e.interactions.add(mesh, {
91
99
  id: v.id,
92
100
  label: () => e.t(e.player?.vehicle === v ? 'vehicle.exit' : 'vehicle.enter'), radius: Math.max(3, s.z / 2 + 1.5),
@@ -94,6 +102,8 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
94
102
  enabled: () => !!e.player && (e.player.vehicle === v || !v.driver || v.passengers.length < v.seats - 1),
95
103
  onUse: () => e.player.vehicle === v ? e.player.exit() : e.player.enter(v),
96
104
  });
97
- }
105
+ };
106
+ offerSeat();
107
+ v._seatBook = e.characters?.addVehicle(v); // after the use: a rider seated here finds a finished vehicle
98
108
  return v;
99
109
  }
@@ -0,0 +1,26 @@
1
+ // What a three-axis collision provider must give (an object contract, shared check @threedog/tools/contract). engine.collision answers on the ground plane, with a height;
2
+ // a tilted solid, a floating island or a flying character needs all three axes. rigid is the first holder (provides: ['collider3d'], so engine.collider3d is it);
3
+ // a game's own voxel grid or BVH that passes this contract takes the slot with engine.use(mine(), { replaces: 'collider3d' }), and nothing else needs to know.
4
+ // addSolid({ position, size | radius, rotation?, friction? }) a fixed solid, turned any way: size = [x, y, z] box, radius = ball; rotation = [x, y, z] radians or a quaternion.
5
+ // Returns { remove() }. Works before start() (rigid builds it with the world), and outlives newGame and a load
6
+ // overlap(position, radius?) is a ball here inside something solid? true / false
7
+ // sweep(from, to, radius?) move a ball from there to there: null when clear, else the first hit { point, normal, distance }; point is the ball's center at the
8
+ // hit, normal the world direction out of what it hit. What a flying mover or a path source steps with
9
+ // Starting in contact and moving out is clear. Sweep from the middle of a body, not its feet: a center exactly on a mesh surface has no side, and that reads as a hit at 0
10
+ // All three see every collider of the holder and skip the player's own capsule. Not here: walking (engine.collision), volumetric paths (rule characters.path).
11
+ export default {
12
+ name: 'collider3d',
13
+ kind: 'object',
14
+ api: ['addSolid', 'overlap', 'sweep'],
15
+ // Who may write where a dynamic body is (design.md section 9). The solver holds it, so the record and the model follow the body and not the other way round
16
+ position: {
17
+ authority: 'solver',
18
+ writers: {
19
+ step: 'the solver, on a fixed step; the record follows through world views',
20
+ setPosition: 'rigid.setPosition or body.setTranslation: a placement, by anyone; it reaches the record on the next fixed step, so a read while frozen is one step late',
21
+ vehicle: 'a seat rides its body: it reads the body and never writes it',
22
+ load: 'a save puts it back',
23
+ },
24
+ },
25
+ calls: [['addSolid', { position: [0, 0, 0], size: [1, 1, 1], rotation: [0, 0, 1] }], ['addSolid', { position: [0, 5, 0], radius: 1 }], ['overlap', [0, 0, 0], 0.5], ['sweep', [0, 9, 0], [0, -9, 0], 0.5]],
26
+ };