threedog 2.2.2 → 2.3.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 (194) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +4 -4
  3. package/core/assets/Animator.js +66 -12
  4. package/core/assets/ik.js +144 -18
  5. package/core/assets/maskLayer.js +377 -0
  6. package/core/assets/rootMotion.js +148 -0
  7. package/core/audio/Audio.js +100 -4
  8. package/core/base/errorCodes.js +6 -369
  9. package/core/base/errorCodesModules.js +378 -0
  10. package/core/engine/Engine.js +8 -5
  11. package/core/engine/Loading.js +8 -4
  12. package/core/engine/copies.js +1 -1
  13. package/core/engine/headlessLoad.js +15 -4
  14. package/core/engine/lifecycle.js +1 -0
  15. package/core/engine/loop.js +22 -3
  16. package/core/engine/moduleSlots.js +3 -7
  17. package/core/engine/modules.js +30 -58
  18. package/core/engine/startup.js +3 -3
  19. package/core/input/Input.js +7 -3
  20. package/core/input/inputContext.js +3 -2
  21. package/core/input/inputSeat.js +1 -1
  22. package/core/inspect/DebugOverrides.js +1 -1
  23. package/core/inspect/Describe.js +7 -2
  24. package/core/inspect/describeRender.js +4 -1
  25. package/core/inspect/describeText.js +2 -2
  26. package/core/inspect/metadata.generated.js +371 -74
  27. package/core/inspect/pictureMenu.js +2 -0
  28. package/core/inspect/pictureWriters.js +4 -3
  29. package/core/ops/Ops.js +9 -3
  30. package/core/ops/actor.js +10 -0
  31. package/core/ops/control.js +17 -6
  32. package/core/ops/holds.js +1 -1
  33. package/core/ops/opsAtomic.js +6 -1
  34. package/core/ops/opsGuard.js +2 -2
  35. package/core/ops/owned.js +37 -11
  36. package/core/ops/sharedPoint.js +5 -1
  37. package/core/ops/stacks.js +30 -7
  38. package/core/saves/Saves.js +0 -2
  39. package/core/saves/saveApply.js +7 -7
  40. package/core/saves/session.js +6 -3
  41. package/core/saves/stateReplace.js +71 -41
  42. package/core/scene/Rays.js +74 -26
  43. package/core/scene/gameLights.js +19 -11
  44. package/core/scene/sceneDelta.js +8 -4
  45. package/core/stream/chunkStream.js +21 -0
  46. package/core/stream/dirtyWatch.js +37 -0
  47. package/core/time/skip.js +9 -6
  48. package/core/time/time.js +72 -18
  49. package/docs/AI.md +22 -21
  50. package/docs/API.md +5 -4
  51. package/docs/CODEMAP.md +16 -10
  52. package/docs/COMMANDS.md +5 -5
  53. package/docs/CONVENTIONS.md +9 -25
  54. package/docs/api/ambience.md +1 -0
  55. package/docs/api/assets.md +10 -3
  56. package/docs/api/audio.md +5 -3
  57. package/docs/api/decals.md +16 -0
  58. package/docs/api/engine.md +1 -0
  59. package/docs/api/tools.md +3 -1
  60. package/docs/api/water.md +3 -0
  61. package/docs/recipes/09-materials-lights-models.md +15 -1
  62. package/docs/recipes/13-animation.md +51 -10
  63. package/docs/recipes/16-dev-bridge.md +1 -1
  64. package/docs/recipes/31-audio.md +15 -9
  65. package/docs/recipes/34-environment-lighting.md +11 -1
  66. package/docs/recipes/44-water-weather-hooks.md +1 -0
  67. package/examples/action/.threedog/content-index.json +1 -0
  68. package/examples/perf-island/.threedog/content-index.json +1 -0
  69. package/examples/plain-picture/.threedog/content-index.json +1 -0
  70. package/examples/rc2d/.threedog/content-index.json +1 -0
  71. package/examples/styletest/.threedog/content-index.json +1 -0
  72. package/examples/techniques/outlines-and-rim/main.js +1 -1
  73. package/examples/techniques/procedural-surface/main.js +1 -1
  74. package/examples/techniques/stylized-shading/main.js +1 -1
  75. package/examples/webgpu-tsl/.threedog/content-index.json +1 -0
  76. package/examples/world/.threedog/content-index.json +1 -0
  77. package/index.d.ts +6 -2
  78. package/index.js +3 -2
  79. package/llms.txt +11 -10
  80. package/modules/ambience/Ambience.js +97 -15
  81. package/modules/camera/common.js +18 -12
  82. package/modules/characters/Character.js +30 -3
  83. package/modules/characters/NPC.js +2 -5
  84. package/modules/characters/astar.js +45 -14
  85. package/modules/characters/movers/rapier.js +53 -41
  86. package/modules/characters/movers/simple.js +37 -24
  87. package/modules/characters/npcView.js +2 -2
  88. package/modules/characters/pathAsync.js +3 -3
  89. package/modules/collision/contract.js +2 -2
  90. package/modules/content/index.js +3 -0
  91. package/modules/content/models.js +11 -4
  92. package/modules/content/templates.js +11 -11
  93. package/modules/debug/DebugPanel.js +1 -0
  94. package/modules/decals/Decals.js +393 -0
  95. package/modules/decals/index.js +1 -0
  96. package/modules/gameplay/Container.js +2 -0
  97. package/modules/gameplay/Containers.js +17 -3
  98. package/modules/gameplay/Dialogue.js +1 -1
  99. package/modules/gameplay/Interactions.js +7 -6
  100. package/modules/gameplay/Inventory.js +5 -1
  101. package/modules/gameplay/Quests.js +4 -3
  102. package/modules/gameplay/inventoryOps.js +2 -2
  103. package/modules/gameplay/pickups.js +32 -12
  104. package/modules/gameplay/questSave.js +2 -2
  105. package/modules/grid/index.js +8 -2
  106. package/modules/hud/index.js +1 -1
  107. package/modules/level/heightfield.js +1 -0
  108. package/modules/level/index.js +3 -2
  109. package/modules/level/nodes.js +2 -1
  110. package/modules/lights/index.js +27 -4
  111. package/modules/lights/slots.js +33 -16
  112. package/modules/nav/contract.js +4 -4
  113. package/modules/nav/index.js +6 -2
  114. package/modules/net/Client.js +24 -11
  115. package/modules/net/Host.js +73 -20
  116. package/modules/net/index.js +33 -21
  117. package/modules/net/sync.js +38 -8
  118. package/modules/net/transports.js +7 -3
  119. package/modules/particles/Particles.js +11 -4
  120. package/modules/particles/contract.js +6 -6
  121. package/modules/particles/effect.js +0 -1
  122. package/modules/rigid/RigidBodies.js +69 -57
  123. package/modules/rigid/Vehicles.js +8 -7
  124. package/modules/rigid/ragdoll.js +4 -6
  125. package/modules/rigid/rapierCompat.js +90 -0
  126. package/modules/rigid/sync.js +2 -5
  127. package/modules/settings/Settings.js +10 -4
  128. package/modules/sky/Sky.js +10 -2
  129. package/modules/sky/environment.js +29 -13
  130. package/modules/sky/frame.js +2 -2
  131. package/modules/sky/shader.js +5 -2
  132. package/modules/sky/skyModule.js +2 -2
  133. package/modules/swarm/Swarm.js +3 -2
  134. package/modules/swarm/grid.js +12 -7
  135. package/modules/terrain/ChunkManager.js +16 -26
  136. package/modules/triggers/index.js +5 -6
  137. package/modules/vegetation/draw.js +62 -26
  138. package/modules/vegetation/groundChunks.js +8 -22
  139. package/modules/water/Water.js +152 -24
  140. package/modules/water/surface.js +43 -20
  141. package/modules/weather/weatherDraw.js +4 -1
  142. package/modules/world/World.js +21 -2
  143. package/modules/world/index.js +5 -0
  144. package/modules/world/persist.js +1 -0
  145. package/modules/world/records.js +3 -1
  146. package/modules/world/sim.js +3 -2
  147. package/modules/world/simFar.js +4 -2
  148. package/modules/world/state.js +7 -1
  149. package/package.json +2 -2
  150. package/presets.js +30 -0
  151. package/render/PostFX.js +24 -17
  152. package/render/backend.js +72 -31
  153. package/render/cascades.js +25 -14
  154. package/render/cascades.tsl.js +32 -21
  155. package/render/fogLook.js +2 -1
  156. package/render/fx/library.tsl.js +1 -1
  157. package/render/fx/particles.tsl.js +4 -18
  158. package/render/fx/pcss.tsl.js +2 -2
  159. package/render/fx/postWebGPU.tsl.js +47 -25
  160. package/render/fx/sky.tsl.js +6 -18
  161. package/render/fx/uniforms.tsl.js +16 -0
  162. package/render/fx/water.tsl.js +24 -5
  163. package/render/fxNumbers.js +2 -0
  164. package/render/impostor.tsl.js +10 -6
  165. package/render/lights.js +6 -6
  166. package/render/occlusion.js +17 -6
  167. package/render/patches.js +40 -28
  168. package/render/postWebGL.js +6 -4
  169. package/render/reflectionProbes.js +302 -0
  170. package/render/shaderErrors.js +18 -8
  171. package/render/shadowCache.tsl.js +10 -5
  172. package/render/shadows.js +70 -49
  173. package/render/threeCompat.js +166 -0
  174. package/types/core.d.ts +33 -3
  175. package/types/gameplay.d.ts +80 -0
  176. package/types/generated/core/audio/Audio.d.ts +18 -1
  177. package/types/generated/core/ops/Ops.d.ts +2 -1
  178. package/types/generated/core/ops/control.d.ts +7 -3
  179. package/types/generated/core/saves/session.d.ts +4 -1
  180. package/types/generated/modules/ambience/Ambience.d.ts +6 -0
  181. package/types/generated/modules/debug/DebugPanel.d.ts +1 -0
  182. package/types/generated/modules/grid/index.d.ts +27 -3
  183. package/types/generated/modules/net/index.d.ts +8 -3
  184. package/types/generated/modules/sky/Sky.d.ts +1 -0
  185. package/types/generated/modules/water/Water.d.ts +15 -0
  186. package/types/generated/modules/world/index.d.ts +5 -0
  187. package/types/generated/render/patches.d.ts +5 -0
  188. package/types/physics.d.ts +66 -9
  189. package/types/tsl.d.ts +2 -0
  190. package/types/world.d.ts +2 -0
  191. package/ui/Parts.js +3 -2
  192. package/docs/MIGRATING-0.7.md +0 -39
  193. package/docs/MIGRATING-0.8.md +0 -171
  194. package/modules/rigid/refresh.js +0 -10
@@ -22,7 +22,7 @@ import { readParams, keysSchema } from '../../core/base/params.js';
22
22
  import { cellsChanged } from '../../core/stream/streamCells.js';
23
23
  import { createVehicle, VEHICLE_KEYS, STRINGS } from './Vehicles.js';
24
24
  import { syncTerrain, syncTrees, treesChanged, syncGroundTrees, syncStatics, restandStatics, syncLevel, syncFloor, dropChunks, wantsFloor, recordLocks, carryBody, carryCollider, carryWorld } from './sync.js';
25
- import { refreshQueries } from './refresh.js';
25
+ import { loadRapier, warmRapier, refreshQueries, readShapeCastHit } from './rapierCompat.js';
26
26
  import { Ragdolls } from './ragdoll.js';
27
27
  import { codedError, coded } from '../../core/base/errorHints.js';
28
28
  import { refuseSave, saveNumberOk, SAVE_MAX } from '../../core/base/saveValues.js';
@@ -42,14 +42,33 @@ function worldPose(mesh, who) {
42
42
  mesh.updateWorldMatrix(true, false); mesh.matrixWorld.decompose(_p, _q, _s);
43
43
  return { p: _p, q: _q };
44
44
  }
45
- function setLocalPose(mesh, t, r) {
45
+ function setLocalPose(mesh, t, r, scene = null, sceneIdentity = false) {
46
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; }
47
+ if (!P || (sceneIdentity && P === scene) || 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
48
  P.matrixWorld.decompose(_p, _pq, _s);
49
49
  mesh.position.copy(P.worldToLocal(_p.set(t.x, t.y, t.z)));
50
50
  mesh.quaternion.copy(_pq.invert().multiply(_q.set(r.x, r.y, r.z, r.w)));
51
51
  }
52
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
+ const _v3 = { x: 0, y: 0, z: 0 }, _imp = { x: 0, y: 0, z: 0 }, _zero = { x: 0, y: 0, z: 0 };
54
+ const CHUNK_OFF = 524288, CHUNK_MUL = 1048576;
55
+ const inPackRange = (cx, cz) => cx >= -CHUNK_OFF && cx < CHUNK_OFF && cz >= -CHUNK_OFF && cz < CHUNK_OFF;
56
+ const packChunk = (cx, cz) => (cx + CHUNK_OFF) * CHUNK_MUL + (cz + CHUNK_OFF);
57
+ const parseChunkKey = k => {
58
+ if (typeof k !== 'string') return null;
59
+ const i = k.indexOf(',');
60
+ if (i <= 0) return null;
61
+ const cx = Number(k.slice(0, i)), cz = Number(k.slice(i + 1));
62
+ return inPackRange(cx, cz) ? packChunk(cx, cz) : null;
63
+ };
64
+ class TerrainMap extends Map {
65
+ constructor() { super(); this._byInt = new Map(); }
66
+ set(k, v) { const p = parseChunkKey(k); if (p !== null) this._byInt.set(p, v); return super.set(k, v); }
67
+ delete(k) { const p = parseChunkKey(k); if (p !== null) this._byInt.delete(p); return super.delete(k); }
68
+ clear() { this._byInt.clear(); return super.clear(); }
69
+ getAt(cx, cz) { return inPackRange(cx, cz) ? this._byInt.get(packChunk(cx, cz)) : this.get(cx + ',' + cz); }
70
+ hasAt(cx, cz) { return inPackRange(cx, cz) ? this._byInt.has(packChunk(cx, cz)) : this.has(cx + ',' + cz); }
71
+ }
53
72
  /**
54
73
  * 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
74
  * The box around it in the world grew with the turn, so a turned crate got a larger body turned on top of that.
@@ -76,36 +95,6 @@ const PHYSICS = { physics: true }; // stream source filter (shared, not rebuil
76
95
  const SOLID_PARAMS = keysSchema(['position', 'size', 'radius', 'rotation', 'friction']);
77
96
  const BODY_KEYS = ['id', 'mass', 'friction', 'restitution', 'damping', 'angularDamping', 'fixed'];
78
97
 
79
- /**
80
- * Run Rapier's step and character-controller code once in a throwaway world, while start() still loads. Why: the browser compiles a WASM
81
- * function on its first call, and the game world's first step paid that for the whole step path: ~120 ms with 77 colliders on a real GPU
82
- * machine (built page), the whole "draw" part of the first frame (docs/testing/field/2026-11-03-perf.md). Here it runs while start() waits
83
- * for the GPU to compile shaders, when the page's thread is idle anyway (a setTimeout instead landed in WebGPU's nearby-build wait and made
84
- * it 150 ms longer). The game's world is untouched (no game time passes, same results).
85
- * Once per page: the compiled code belongs to the one WASM instance.
86
- */
87
- const WARMED = new WeakSet();
88
- function warmRapier(R) {
89
- if (WARMED.has(R)) return;
90
- WARMED.add(R);
91
- const w = new R.World({ x: 0, y: -9.81, z: 0 });
92
- try {
93
- w.createCollider(R.ColliderDesc.cuboid(5, 0.5, 5));
94
- w.createCollider(R.ColliderDesc.trimesh(new Float32Array([-5, 1, -5, 5, 1, -5, 0, 1, 5]), new Uint32Array([0, 1, 2])));
95
- for (const [i, c] of [R.ColliderDesc.ball(0.5), R.ColliderDesc.cuboid(0.4, 0.4, 0.4), R.ColliderDesc.cylinder(0.4, 0.3), R.ColliderDesc.capsule(0.3, 0.2)].entries())
96
- w.createCollider(c, w.createRigidBody(R.RigidBodyDesc.dynamic().setTranslation(i - 1.5, 1.2, 0)));
97
- const kin = w.createRigidBody(R.RigidBodyDesc.kinematicPositionBased().setTranslation(2, 1.5, 2));
98
- const me = w.createCollider(R.ColliderDesc.capsule(0.5, 0.3), kin);
99
- const cc = w.createCharacterController(0.01);
100
- for (let i = 0; i < 3; i++) {
101
- cc.computeColliderMovement(me, { x: 0.1, y: -0.1, z: 0 });
102
- kin.setNextKinematicTranslation({ x: 2 + i * 0.1, y: 1.5, z: 2 });
103
- w.step();
104
- }
105
- w.removeCharacterController(cc);
106
- } finally { w.free(); }
107
- }
108
-
109
98
  export class RigidBodies {
110
99
  /** terrainRing = chunk rings around each physics stream source that get terrain collision; buoyancyForce = buoyancy strength (1 = exactly floats); waterDrag = drag in water;
111
100
  * floatLine / floatDepth: buoyancy starts when the body center is below floatLine meters above the surface and peaks floatDepth meters deeper;
@@ -127,7 +116,8 @@ export class RigidBodies {
127
116
  this.bodies = []; // { body, mesh, enabled }
128
117
  /** @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;
129
118
  /** @internal a session:end asked for a rebuild that world:load / afterLoad has not run yet (one rebuild per new game or load) */ this._freshDue = false;
130
- this.terrain = new Map(); // chunk key -> { colliders: [] }
119
+ this.terrain = new TerrainMap(); // chunk key -> { colliders: [] }, indexed by packed 20-bit int for O(1) zero-alloc step lookup
120
+ /** @internal reused Rapier Ray for _raycast */ this._ray = null;
131
121
  this.trees = new Map(); // chunk key -> { token, colliders }: trunk cylinders of the chunks near the player / bodies (see sync.js)
132
122
  this._anchors = []; this._treeMemo = [];
133
123
  this.groundTrees = new Map(); // 'x,z,r' -> cylinder collider: circles from ground.forEachCollider when the ground has no chunked collision
@@ -145,7 +135,7 @@ export class RigidBodies {
145
135
  * @internal Import and instantiate Rapier once. Started at install: the import plus WASM compile took 0.8-1.1 s on a cold start and used to
146
136
  * begin only when start() reached this module's init, with every later init waiting behind it; begun at install it overlaps the world build
147
137
  */
148
- _wasm() { return (this._rapier ??= import('@dimforge/rapier3d-compat').then(async mod => { const R = mod.default ?? mod; await R.init(); return R; })); }
138
+ _wasm() { return (this._rapier ??= loadRapier()); }
149
139
 
150
140
  /** @internal module hook */
151
141
  async init(signal) {
@@ -183,7 +173,7 @@ export class RigidBodies {
183
173
  /** @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 */
184
174
  _upkeep() { if (syncStatics(this) | syncLevel(this) | syncFloor(this) | dropChunks(this)) this._behind = true; }
185
175
  /**
186
- * @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
176
+ * @internal Every query starts here, and answers whether physics can be asked. Rapier has no call that refreshes its query structures alone (rapierCompat.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
187
177
  * moves, and it runs only when something changed, so a ray pays three compares.
188
178
  */
189
179
  _current() {
@@ -209,7 +199,13 @@ export class RigidBodies {
209
199
  this._freshDue = false;
210
200
  if (!this.ready) return;
211
201
  if (this.vehicles.length) {
212
- for (const b of this.bodies) { const y = b.body; y.setLinvel({ x: 0, y: 0, z: 0 }, false); y.setAngvel({ x: 0, y: 0, z: 0 }, false); y.resetForces(false); y.resetTorques(false); if (y.isDynamic()) y.sleep(); }
202
+ for (const b of this.bodies) {
203
+ const y = b.body;
204
+ y.setLinvel({ x: 0, y: 0, z: 0 }, false); y.setAngvel({ x: 0, y: 0, z: 0 }, false); y.resetForces(false); y.resetTorques(false);
205
+ if (b.wet) { y.setLinearDamping(b.damping); y.setAngularDamping(b.angularDamping); }
206
+ b.wet = false; b._void = false; b._fell = false;
207
+ if (y.isDynamic()) y.sleep();
208
+ }
213
209
  return;
214
210
  }
215
211
  const old = this.world, R = this.rapier, hadJoints = old.impulseJoints.len();
@@ -344,10 +340,10 @@ export class RigidBodies {
344
340
  return this._chunkReady(x, z);
345
341
  }
346
342
  /** @internal */
347
- _chunkReady(x, z) { const CH = this.engine.ground.chunkSize ?? 64; return !!this.terrain.get(Math.floor(x / CH) + ',' + Math.floor(z / CH))?.ready; }
343
+ _chunkReady(x, z) { const CH = this.engine.ground.chunkSize ?? 64; return !!this.terrain.getAt(Math.floor(x / CH), Math.floor(z / CH))?.ready; }
348
344
  /** @internal A moving body left the terrain colliders. Told once in dev; not told: a body at rest left behind (normal), a chunk still waiting for its collider (it has a terrain entry, or chunks are pending) */
349
345
  _tellFrozen(b, t, CH) {
350
- if (this._srcPending || !b.body.isDynamic() || b.body.isSleeping() || this.terrain.has(Math.floor(t.x / CH) + ',' + Math.floor(t.z / CH))) return;
346
+ if (this._srcPending || !b.body.isDynamic() || b.body.isSleeping() || this.terrain.hasAt(Math.floor(t.x / CH), Math.floor(t.z / CH))) return;
351
347
  warnOnce(coded('rigid-misuse', `rigid: body '${b.id ?? (b.mesh.name || 'unnamed')}' froze at x ${t.x.toFixed(0)}, z ${t.z.toFixed(0)} (entry.enabled is false): it left rigid({ terrainRing: ${this.terrainRing} }), the ${CH} m chunks around the player that have terrain colliders, and would fall through the ground. It stays frozen until the player comes near. A body that must keep moving out there needs a larger terrainRing (recipe 11 section 3)`), 'rigid-frozen');
352
348
  }
353
349
  /** Delete the body (called by entry.remove()); the model stays */
@@ -358,12 +354,13 @@ export class RigidBodies {
358
354
  entry._pose.remove();
359
355
  }
360
356
  /** Push: impulse vector v (Vector3 / [x, y, z] / { x, y, z }) */
361
- impulse(entry, v) { const { x, y, z } = vec3(v); entry.body.wakeUp(); entry.body.applyImpulse({ x, y, z }, true); }
357
+ impulse(entry, v) { const { x, y, z } = vec3(v); _v3.x = x; _v3.y = y; _v3.z = z; entry.body.wakeUp(); entry.body.applyImpulse(_v3, true); }
362
358
  /** Teleport to position (velocity zeroed) */
363
359
  setPosition(entry, position) {
364
360
  const { x, y, z } = vec3(position);
365
361
  entry._x = x; entry._z = z;
366
- entry.body.setTranslation({ x, y, z }, true); entry.body.setLinvel({ x: 0, y: 0, z: 0 }, true); this._behind = true;
362
+ _v3.x = x; _v3.y = y; _v3.z = z;
363
+ entry.body.setTranslation(_v3, true); entry.body.setLinvel(_zero, true); this._behind = true;
367
364
  }
368
365
 
369
366
  // ---------- The collider3d contract (collider3d.contract.js): engine.collider3d is this object ----------
@@ -406,8 +403,8 @@ export class RigidBodies {
406
403
  d.divideScalar(len);
407
404
  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);
408
405
  if (!hit) return null;
409
- const n = hit.normal1; // world space on World.castShape (the tilted-box test fails first if an upgrade changes that)
410
- return { point: a.addScaledVector(d, hit.time_of_impact), normal: new THREE.Vector3(n.x, n.y, n.z), distance: hit.time_of_impact };
406
+ const { timeOfImpact, normal: n } = readShapeCastHit(hit);
407
+ return { point: a.addScaledVector(d, timeOfImpact), normal: new THREE.Vector3(n.x, n.y, n.z), distance: timeOfImpact };
411
408
  }
412
409
 
413
410
  /** Ray (provider for engine.rays, called by engine.raycast when targets: 'all'): hits dynamic bodies only, returns RayHit (with entry, kind: 'rigid') */
@@ -417,7 +414,10 @@ export class RigidBodies {
417
414
  if (!byHandle) { byHandle = this._byHandle = new Map(); for (const b of this.bodies) byHandle.set(b.body.handle, b); }
418
415
  const max = Number.isFinite(far) ? far : 1e6;
419
416
  const only = c => byHandle.has(c.parent()?.handle);
420
- const hit = this.world.castRayAndGetNormal(new this.rapier.Ray(origin, dir), max, true, undefined, undefined, undefined, this.playerBody, only);
417
+ let ray = this._ray;
418
+ if (!ray) ray = this._ray = new this.rapier.Ray({ x: origin.x, y: origin.y, z: origin.z }, { x: dir.x, y: dir.y, z: dir.z });
419
+ else { ray.origin.x = origin.x; ray.origin.y = origin.y; ray.origin.z = origin.z; ray.dir.x = dir.x; ray.dir.y = dir.y; ray.dir.z = dir.z; }
420
+ const hit = this.world.castRayAndGetNormal(ray, max, true, undefined, undefined, undefined, this.playerBody, only);
421
421
  if (!hit) return null;
422
422
  const entry = byHandle.get(hit.collider.parent()?.handle);
423
423
  if (!entry) return null;
@@ -444,7 +444,7 @@ export class RigidBodies {
444
444
  // a body past float precision (x = -1e308) sends the ground loops around it spinning and the page never comes back: damage, refused like a damaged world record (world/persist.js)
445
445
  for (const [id, s] of Object.entries(d ?? {}))
446
446
  if (!Array.isArray(s) || s.length !== 14 || !s.every(v => typeof v === 'boolean' || saveNumberOk(v))) refuseSave('rigid', `body '${id}'`, `must be a list of 14 numbers within ±${SAVE_MAX}`, s);
447
- this._saved = new Map(Object.entries(d ?? {})); this._ragdolls?.load();
447
+ this._saved = new Map(Object.entries(d ?? {}));
448
448
  }
449
449
  /** @internal afterLoad: hand the loaded state to the bodies that exist (vehicles, bodies the game keeps across a load) */
450
450
  _claimSaved() {
@@ -496,37 +496,48 @@ export class RigidBodies {
496
496
  }
497
497
  // player capsule follows the player (the rapier mover computes collision and writes the position itself); turned off while driving to avoid colliding with
498
498
  // the car
499
- if (e.player) this.playerBody.setNextKinematicTranslation({ x: focus.x, y: focus.y, z: focus.z });
499
+ if (e.player) { _v3.x = focus.x; _v3.y = focus.y; _v3.z = focus.z; this.playerBody.setNextKinematicTranslation(_v3); }
500
500
  // no player, no capsule: with no player nothing moves it, and it would sit as an invisible solid body at the origin
501
501
  const onFoot = !!e.player && !e.player.vehicle && !this._ragdolls?.holds(e.player);
502
502
  if (this.playerCollider.isEnabled() !== onFoot) this.playerCollider.setEnabled(onFoot);
503
503
  if (worldDt > 0) for (const v of this.vehicles) if (v.enabled) v._update(worldDt);
504
504
 
505
505
  // freeze bodies without terrain collision under them (unfrozen they would fall through)
506
+ const waterCheck = worldDt > 0 && this.buoyancy;
506
507
  for (const b of this.bodies) {
508
+ if (b.enabled && b.body.isSleeping() && !b.wet) {
509
+ if (chunked && !this._chunkReady(b._x, b._z)) {
510
+ if (DEV) this._tellFrozen(b, b.body.translation(), CH);
511
+ b.body.setEnabled(false); b.enabled = false;
512
+ }
513
+ continue;
514
+ }
507
515
  const t = b.body.translation();
508
516
  b._x = t.x; b._z = t.z;
509
517
  const ok = !chunked || this._chunkReady(t.x, t.z);
510
518
  if (ok !== b.enabled) { if (DEV && !ok) this._tellFrozen(b, t, CH); b.body.setEnabled(ok); b.enabled = ok; }
511
519
  // buoyancy: the submerged part gets an upward force, and water adds drag
512
- 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
513
- if (ok && this.buoyancy && t.y < water + this.floatLine && b.body.isDynamic()) {
514
- const depth = Math.min(1, (water + this.floatLine - t.y) / this.floatDepth);
515
- const m = b.body.mass();
516
- 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
517
- b.body.setLinearDamping(this.waterDrag); b.body.setAngularDamping(this.waterDrag);
518
- b.wet = true;
519
- } else if (b.wet) {
520
- b.body.setLinearDamping(b.damping); b.body.setAngularDamping(b.angularDamping); b.wet = false;
520
+ if (waterCheck) {
521
+ const water = e.waterAt(t.x, t.z, t.y); // at its own height: a game's water body may be a pool upstairs or a falling column
522
+ if (ok && t.y < water + this.floatLine && b.body.isDynamic()) {
523
+ const depth = Math.min(1, (water + this.floatLine - t.y) / this.floatDepth);
524
+ const m = b.body.mass();
525
+ _imp.x = 0; _imp.y = -this.gravity * m * (this.buoyancyForce * depth) * worldDt; _imp.z = 0;
526
+ b.body.applyImpulse(_imp, 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
527
+ if (!b.wet) { b.body.setLinearDamping(this.waterDrag); b.body.setAngularDamping(this.waterDrag); b.wet = true; }
528
+ } else if (b.wet) {
529
+ b.body.setLinearDamping(b.damping); b.body.setAngularDamping(b.angularDamping); b.wet = false;
530
+ }
521
531
  }
522
532
  }
523
533
 
524
534
  if (worldDt > 0) { this.world.timestep = worldDt; this.world.step(); this._behind = false; }
525
535
 
536
+ const scene = e.scene, sceneIdentity = scene.matrixWorld.equals(_I);
526
537
  for (const b of this.bodies) {
527
538
  if (!b.enabled || b.body.isSleeping() || b.ragdoll) continue; // ragdoll parts are drawn by ragdoll.js, through the bones
528
539
  const t = b.body.translation(), r = b.body.rotation();
529
- setLocalPose(b.mesh, t, r);
540
+ setLocalPose(b.mesh, t, r, scene, sceneIdentity);
530
541
  this._fallen(b, t);
531
542
  // fell off terrain({ shape }): one terrain:void per fall, the game decides what next
532
543
  const under = t.y < e.ground.voidY();
@@ -586,6 +597,7 @@ export function rigid(opts = {}) {
586
597
  r._wasm().catch(() => {}); // start loading now (see _wasm); a failure surfaces in init, which awaits the same promise
587
598
  ctx.budget.metric('rigidBodies', () => r.bodies.length);
588
599
  ctx.stream.addReadyCheck('rigid', s => !s.physics || r.ready && r.readyAt(s)); // a physics stream source waits for the collider under it
600
+ ctx.feeds('interactions', () => { for (const v of r.vehicles) v._offerSeat?.(); });
589
601
  ctx.track(e.rays.addProvider((o, d, far) => r._raycast(o, d, far))); // engine.raycast(..., { targets: 'all' }) includes rigid bodies
590
602
  // 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.
591
603
  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
@@ -598,7 +610,7 @@ export function rigid(opts = {}) {
598
610
  // it, afterLoad (newGame / load / quit all apply a save) runs it. Rebuilding in both steps built the world twice per new game.
599
611
  sessionEnd() { r._freshDue = true; },
600
612
  worldLoad() { r._fresh(); },
601
- 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)
613
+ afterLoad() { if (r._freshDue) r._fresh(); r._ragdolls?.load(); r._claimSaved(); }, // after every part loaded and _fresh rebuilt the world (world:load is emitted inside the world part's load)
602
614
  async init(e, ctx) { await r.init(ctx.signal); ctx.whileCompiling(() => warmRapier(r.rapier)); },
603
615
  counts() { return r.bodies.length; }, // engine.counts().rigid
604
616
  // bodies by type and what they are doing: sleeping = at rest (normal), frozen = disabled because no terrain collider is under them yet (they wait, not fall)
@@ -10,6 +10,7 @@
10
10
  import * as THREE from 'three';
11
11
  import { vec3 } from '../../core/base/math.js';
12
12
  import { ownBox } from './RigidBodies.js';
13
+ import { setVehicleAxes } from './rapierCompat.js';
13
14
 
14
15
  export const VEHICLE_KEYS = ['id', 'wheels', 'mass', 'engineForce', 'brakeForce', 'maxSteer', 'suspension', 'seats', 'hideDriver', 'camera', 'size', 'friction', 'exitOffset'];
15
16
  export const STRINGS = { 'zh-CN': { 'vehicle.enter': '上车', 'vehicle.exit': '下车' }, en: { 'vehicle.enter': 'Get in', 'vehicle.exit': 'Get out' } };
@@ -24,7 +25,7 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
24
25
  const s = size ? new THREE.Vector3().fromArray(size) : box.getSize(new THREE.Vector3()), c = size ? new THREE.Vector3() : box.getCenter(new THREE.Vector3());
25
26
  const entry = rigid._add(mesh, R.ColliderDesc.cuboid(s.x / 2, s.y / 2, s.z / 2).setTranslation(c.x, c.y, c.z), { id, mass, friction: 0.5, damping: 0.1, angularDamping: 0.5 });
26
27
  const ctl = w.createVehicleController(entry.body);
27
- ctl.indexUpAxis = 1; ctl.setIndexForwardAxis = 2; // up = Y, forward = Z
28
+ setVehicleAxes(ctl, 1, 2); // up = Y, forward = Z
28
29
  const { rest = 0.3, stiffness = 30, damping = 4 } = suspension;
29
30
  wheels.forEach((wh, i) => {
30
31
  const at = vec3(wh.position);
@@ -39,7 +40,7 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
39
40
  const drives = wheels.filter(x => x.drive).length || wheels.length;
40
41
  // seat 0 drives, the rest ride; without seats one driver seat at the chassis center
41
42
  const seatAt = seats?.length ? seats.map(p => vec3(p)) : [new THREE.Vector3(c.x, c.y, c.z)];
42
- let throttle = 0, steerIn = 0, brake = 0, useFrom;
43
+ let throttle = 0, steerIn = 0, brake = 0;
43
44
 
44
45
  const v = Object.assign(entry, {
45
46
  controller: ctl, wheels, driver: null, camera, hideDriver, seats: seatAt.length, passengers: [],
@@ -55,7 +56,6 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
55
56
  },
56
57
  /** Every fixed step: write controls to the wheels and advance the vehicle controller (called before the physics step) */
57
58
  _update(dt) {
58
- if (useFrom !== e.interactions) offerSeat();
59
59
  wheels.forEach((wh, i) => {
60
60
  ctl.setWheelEngineForce(i, wh.drive || drives === wheels.length ? throttle * engineForce / drives : 0);
61
61
  ctl.setWheelSteering(i, wh.steer ? -steerIn * maxSteer : 0);
@@ -81,18 +81,19 @@ export function createVehicle(rigid, mesh, { wheels, mass = 800, engineForce = 8
81
81
  return l.x * fwd.x + l.y * fwd.y + l.z * fwd.z;
82
82
  } });
83
83
  // With the interactions module installed: press the interact key near the car to get in, and again while driving to get out
84
+ const riderOf = actor => (actor ? e.control.characterOf(actor) : null) ?? e.player;
84
85
  const offerSeat = () => {
85
86
  v._use?.remove(); v._use = null;
86
- useFrom = e.interactions; // the use lives in that module: another one starts empty, so _update offers the seat again
87
87
  if (!e.interactions) return;
88
88
  v._use = e.interactions.add(mesh, {
89
89
  id: v.id,
90
- label: () => e.t(e.player?.vehicle === v ? 'vehicle.exit' : 'vehicle.enter'), radius: Math.max(3, s.z / 2 + 1.5),
90
+ label: (_, ctx) => e.t(riderOf(ctx?.actor)?.vehicle === v ? 'vehicle.exit' : 'vehicle.enter'), radius: Math.max(3, s.z / 2 + 1.5),
91
91
  // in it: get out; else get in while a seat is free (driver first, then passenger seats)
92
- enabled: () => !!e.player && (e.player.vehicle === v || !v.driver || v.passengers.length < v.seats - 1),
93
- onUse: () => e.player.vehicle === v ? e.player.exit() : e.player.enter(v),
92
+ enabled: (_, ctx) => { const r = riderOf(ctx?.actor); return !!r && (r.vehicle === v || !v.driver || v.passengers.length < v.seats - 1); },
93
+ onUse: (_, ctx) => { const r = riderOf(ctx?.actor); if (r) return r.vehicle === v ? r.exit() : r.enter(v); },
94
94
  });
95
95
  };
96
+ v._offerSeat = offerSeat;
96
97
  offerSeat();
97
98
  v._seatBook = e.characters?.addVehicle(v); // after the use: a rider seated here finds a finished vehicle
98
99
  return v;
@@ -8,7 +8,7 @@
8
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.
9
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).
10
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.
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
+ // - Not saved: once a load commits (afterLoad: new game, load and saves.load all run it) every ragdoll ends and a normal character comes back; a refused load rolls back without afterLoad, so the ragdoll keeps lying there.
12
12
  // On a world rebuild without a load, rigid carries the bodies over and this rebuilds the joints on rigid:rebuilt.
13
13
  // - Self-collision is off: capsules of neighbouring parts overlap at the start and would push each other away; the limits keep the pose.
14
14
  // shortcut: one collision group, so ragdolls do not collide with each other either; to pile bodies up, give each ragdoll its own group bit.
@@ -17,6 +17,7 @@ import { vec3 } from '../../core/base/math.js';
17
17
  import { readParams, keysSchema } from '../../core/base/params.js';
18
18
  import { codedError } from '../../core/base/errorHints.js';
19
19
  import { humanoidGraph, shapeParts } from './ragdollBones.js';
20
+ import { configureSphericalJoint } from './rapierCompat.js';
20
21
 
21
22
  const KEYS = keysSchema(['impulse', 'position', 'bones', 'limits', 'mass']);
22
23
  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
@@ -138,7 +139,7 @@ export class Ragdolls {
138
139
  return [[lim.twist, f.x], [lim.side, f.y], [lim.bend, f.z]].map(([[lo, hi], c]) => { const x = ang(c); return [Math.min(lo, x - 0.02), Math.max(hi, x + 0.02)]; });
139
140
  }
140
141
 
141
- /** Build the joints; runs again after a world rebuild. Rapier's JS layer only exposes setLimits for single-axis joints; the three-axis limits and damping of a spherical joint (actually type Generic) go through the rawSet below it (the ragdoll test fails first when the version is upgraded) */
142
+ /** Build the joints; runs again after a world rebuild. Three-axis limits and damping go through rapierCompat.configureSphericalJoint */
142
143
  _joints(rd) {
143
144
  const { r } = this, R = r.rapier, w = r.world, zero = { x: 0, y: 0, z: 0 };
144
145
  rd.joints = [];
@@ -147,10 +148,7 @@ export class Ragdolls {
147
148
  const j = w.createImpulseJoint(R.JointData.spherical(p.anchor, zero), p.parent.entry.body, p.entry.body, true);
148
149
  const F = p.shape.frame, f = { x: F.x, y: F.y, z: F.z, w: F.w };
149
150
  j.setLocalFrame1(p.anchor, f); j.setLocalFrame2(zero, f);
150
- [R.JointAxis.AngX, R.JointAxis.AngY, R.JointAxis.AngZ].forEach((axis, i) => {
151
- j.rawSet.jointSetLimits(j.handle, axis, p.range[i][0], p.range[i][1]);
152
- j.rawSet.jointConfigureMotorVelocity(j.handle, axis, 0, FRICTION);
153
- });
151
+ configureSphericalJoint(R, j, p.range, FRICTION);
154
152
  rd.joints.push(j);
155
153
  }
156
154
  }
@@ -0,0 +1,90 @@
1
+ // Rapier 0.21 compatibility layer: isolates WASM loading, first-step JIT warm-up, and query-pipeline refresh quirks in one place.
2
+ // Upgrading @dimforge/rapier3d-compat should only require adjusting this file.
3
+
4
+ const WARMED = new WeakSet();
5
+
6
+ /** @internal Load and initialize @dimforge/rapier3d-compat */
7
+ export function loadRapier() {
8
+ return import('@dimforge/rapier3d-compat').then(async mod => {
9
+ const R = mod.default ?? mod;
10
+ await R.init();
11
+ return R;
12
+ });
13
+ }
14
+
15
+ /**
16
+ * @internal Run Rapier's step and character-controller code once in a throwaway world while start() still loads,
17
+ * paying WASM JIT compilation off the first-frame critical path. Once per WASM instance.
18
+ */
19
+ export function warmRapier(R) {
20
+ if (WARMED.has(R)) return;
21
+ WARMED.add(R);
22
+ const w = new R.World({ x: 0, y: -9.81, z: 0 });
23
+ try {
24
+ w.createCollider(R.ColliderDesc.cuboid(5, 0.5, 5));
25
+ w.createCollider(R.ColliderDesc.trimesh(new Float32Array([-5, 1, -5, 5, 1, -5, 0, 1, 5]), new Uint32Array([0, 1, 2])));
26
+ for (const [i, c] of [R.ColliderDesc.ball(0.5), R.ColliderDesc.cuboid(0.4, 0.4, 0.4), R.ColliderDesc.cylinder(0.4, 0.3), R.ColliderDesc.capsule(0.3, 0.2)].entries())
27
+ w.createCollider(c, w.createRigidBody(R.RigidBodyDesc.dynamic().setTranslation(i - 1.5, 1.2, 0)));
28
+ const kin = w.createRigidBody(R.RigidBodyDesc.kinematicPositionBased().setTranslation(2, 1.5, 2));
29
+ const me = w.createCollider(R.ColliderDesc.capsule(0.5, 0.3), kin);
30
+ const cc = w.createCharacterController(0.01);
31
+ for (let i = 0; i < 3; i++) {
32
+ cc.computeColliderMovement(me, { x: 0.1, y: -0.1, z: 0 });
33
+ kin.setNextKinematicTranslation({ x: 2 + i * 0.1, y: 1.5, z: 2 });
34
+ w.step();
35
+ }
36
+ w.removeCharacterController(cc);
37
+ } finally { w.free(); }
38
+ }
39
+
40
+ /**
41
+ * @internal Rapier 0.21 keeps its query structures in the broad phase, and only a step rebuilds them:
42
+ * World has no updateSceneQueries / query pipeline, and propagateModifiedBodyPositionsToColliders does not update the broad phase.
43
+ * Two zero-timestep steps catch up moved colliders without advancing simulation.
44
+ */
45
+ export function refreshQueries(world) {
46
+ const dt = world.timestep;
47
+ world.timestep = 0;
48
+ try { world.step(); world.step(); } finally { world.timestep = dt; }
49
+ }
50
+
51
+ /**
52
+ * @internal Rapier 0.21 exposes `indexUpAxis` as a getter+setter, `indexForwardAxis` as a getter-only property,
53
+ * and `setIndexForwardAxis` as a setter-only property (not a method). Isolating this here prevents future typos or upgrade breakage.
54
+ */
55
+ export function setVehicleAxes(ctl, up = 1, forward = 2) {
56
+ ctl.indexUpAxis = up;
57
+ if ('setIndexForwardAxis' in ctl) ctl.setIndexForwardAxis = forward;
58
+ else ctl.indexForwardAxis = forward;
59
+ }
60
+
61
+ /**
62
+ * @internal Rapier 0.21's JS layer only exposes setLimits for single-axis joints; three-axis angular limits and damping on a spherical (Generic) joint go through rawSet.
63
+ */
64
+ export function configureSphericalJoint(R, joint, ranges, friction) {
65
+ const axes = [R.JointAxis.AngX, R.JointAxis.AngY, R.JointAxis.AngZ];
66
+ for (let i = 0; i < 3; i++) {
67
+ joint.rawSet.jointSetLimits(joint.handle, axes[i], ranges[i][0], ranges[i][1]);
68
+ joint.rawSet.jointConfigureMotorVelocity(joint.handle, axes[i], 0, friction);
69
+ }
70
+ }
71
+
72
+ /**
73
+ * @internal Rapier 0.21 exposes `contact_natural_frequency` as a setter without a getter: recover it from `contact_erp`
74
+ * (erp = a*f / (a*f + c), a = 2*pi*dt) by probing a known frequency on the new world so no Rapier constant is copied.
75
+ */
76
+ export function copyContactFrequency(oldParams, newParams) {
77
+ const proto = Object.getPrototypeOf(oldParams), d = k => Object.getOwnPropertyDescriptor(proto, k);
78
+ if (!d('contact_natural_frequency')?.set || !d('contact_erp')?.get) return;
79
+ const a0 = 2 * Math.PI * oldParams.dt, a1 = 2 * Math.PI * newParams.dt, f1 = 30;
80
+ newParams.contact_natural_frequency = f1;
81
+ const e0 = oldParams.contact_erp, e1 = newParams.contact_erp, c = a1 * f1 * (1 - e1) / e1;
82
+ if (e0 > 0 && e0 < 1) newParams.contact_natural_frequency = c * e0 / ((1 - e0) * a0);
83
+ }
84
+
85
+ /**
86
+ * @internal Rapier 0.21's World.castShape returns snake_case `time_of_impact` and world-space `normal1` (unlike castRayAndGetNormal's `timeOfImpact` / `normal`).
87
+ */
88
+ export function readShapeCastHit(hit) {
89
+ return { timeOfImpact: hit.time_of_impact ?? hit.timeOfImpact, normal: hit.normal1 ?? hit.normal };
90
+ }
@@ -1,6 +1,7 @@
1
1
  // Colliders the rigid module keeps in sync with what the game draws: terrain chunks (trimesh + trunk cylinders), trunks on a level or code-built ground, the
2
2
  // collision module's houses / pillars, and a level's static ground. Each function takes the RigidBodies instance as `r` and is called from its step().
3
3
  import * as THREE from 'three';
4
+ import { copyContactFrequency } from './rapierCompat.js';
4
5
 
5
6
  // Chunks around physics stream sources ([cx, cz, rings] each): terrain uses triangle-mesh colliders (identical to what is drawn), vegetation uses cylinders.
6
7
  // Data comes from the ground API ground.chunkCollision
@@ -231,11 +232,7 @@ export function carryBody(entry, o, n) {
231
232
  export function carryWorld(o, n) {
232
233
  const proto = Object.getPrototypeOf(o), d = k => Object.getOwnPropertyDescriptor(proto, k);
233
234
  for (const k of Object.getOwnPropertyNames(proto)) if (k !== 'dt' && d(k).set && d(k).get && o[k] !== n[k]) n[k] = o[k];
234
- if (!d('contact_natural_frequency')?.set || !d('contact_erp')?.get) return;
235
- const a0 = 2 * Math.PI * o.dt, a1 = 2 * Math.PI * n.dt, f1 = 30;
236
- n.contact_natural_frequency = f1;
237
- const e0 = o.contact_erp, e1 = n.contact_erp, c = a1 * f1 * (1 - e1) / e1;
238
- if (e0 > 0 && e0 < 1) n.contact_natural_frequency = c * e0 / ((1 - e0) * a0);
235
+ copyContactFrequency(o, n);
239
236
  }
240
237
 
241
238
  /** @internal Copy game-set collider state from the old collider onto the one rebuilt from the entry's desc */
@@ -65,7 +65,7 @@ const DEFINE_KEYS = keysSchema(['apply', 'limits', 'menu', 'label', 'options', '
65
65
  * @param {any} sections @returns {Set<string>}
66
66
  */
67
67
  function omittedRows(sections) {
68
- const entry = Array.isArray(sections) ? sections.find(s => typeof s === 'object') : null;
68
+ const entry = Array.isArray(sections) ? sections.find(s => s && typeof s === 'object') : null;
69
69
  if (!entry) return new Set();
70
70
  readParams('settings sections', keysSchema(['id', 'omit']), entry);
71
71
  const rows = ['quality', 'adaptive', ...Object.keys(PRESETS.low)], bad = (entry.omit ?? []).filter(k => !rows.includes(k));
@@ -163,7 +163,7 @@ export class Settings extends SettingsView {
163
163
  */
164
164
  get _omit() { return pixelSizeOn(this.engine) ? new Set([...this._leftOut, 'pixelRatio', 'adaptive']) : this._leftOut; }
165
165
  get values() { return { ...this._values, pixelRatio: +this.engine.renderer.getPixelRatio().toFixed(2) }; }
166
- get(key) { return this.values[key]; }
166
+ get(key) { return key === 'pixelRatio' ? +this.engine.renderer.getPixelRatio().toFixed(2) : this._values[key]; }
167
167
  /** @internal Someone answers for this key: a built-in row, a defined one, or a bus's slider @param {string} key */
168
168
  _hasRow(key) { return key in this._defaults || this.custom.has(key) || (key.startsWith('vol.') && key.slice(4) in this.engine.audio.levels); }
169
169
  /**
@@ -178,7 +178,7 @@ export class Settings extends SettingsView {
178
178
  }
179
179
  this._values[key] = value; this._changed[key] = value;
180
180
  if (apply) this._apply(key, value);
181
- if (key in (this.presets.low || {})) this._values.quality = this._matchPreset();
181
+ if (this._presetKeys().has(key)) this._values.quality = this._matchPreset();
182
182
  if (save) this.save();
183
183
  this.win.refresh();
184
184
  }
@@ -271,7 +271,7 @@ export class Settings extends SettingsView {
271
271
  reset(key) {
272
272
  const def = k => this.custom.has(k) ? this.custom.get(k).def : this._defaults[k];
273
273
  // 'quality' is no value of its own (it is the name of the preset the graphics values match): resetting it resets the graphics values the presets set
274
- const keys = key === undefined ? Object.keys(this._values).filter(k => k !== 'quality' && !this._omit.has(k)) : key === 'quality' ? Object.keys(this._presetValues('low')) : [key];
274
+ const keys = key === undefined ? Object.keys(this._values).filter(k => k !== 'quality' && !this._omit.has(k)) : key === 'quality' ? [...this._presetKeys()].filter(k => !this._omit.has(k) && k in this._values) : [key];
275
275
  if (key === undefined || key === 'quality') delete this._changed.quality;
276
276
  const preset = this._presetValues(this._changed.quality); // a row a kept preset sets must stay stored, or the preset takes it back on the next launch
277
277
  for (const k of keys) {
@@ -343,6 +343,12 @@ export class Settings extends SettingsView {
343
343
  for (const [bus, level] of Object.entries(e.audio.levels)) v['vol.' + bus] = level; // one slider per bus, the game's own buses too
344
344
  return v;
345
345
  }
346
+ /** @internal Union of keys touched by any graphics preset */
347
+ _presetKeys() {
348
+ const keys = new Set();
349
+ for (const p of Object.values(this.presets)) if (p && typeof p === 'object') for (const k in p) keys.add(k);
350
+ return keys;
351
+ }
346
352
  /** A preset's values in this game on this device: each share made a value. A share of a row nobody offered is left out. Nothing for 'custom' or no preset @param {string} [name] */
347
353
  _presetValues(name) {
348
354
  const out = {};
@@ -27,6 +27,14 @@ const DIM_PARAMS = {
27
27
  tint: { type: 'bool', default: true, desc: 'a sky.tint color (weather grey, a cave tint) dims with the sky\'s own light, so a grey rain tint stays dark at night' },
28
28
  stars: { type: 'bool', default: true, desc: 'stars fade with the weather\'s cloud cover (uWeatherCloud), not only behind drawn clouds' },
29
29
  };
30
+ /** @internal Detach and dispose a sky dome mesh (handles single or array materials) */
31
+ export function disposeDome(dome) {
32
+ if (!dome) return;
33
+ dome.removeFromParent();
34
+ dome.geometry?.dispose();
35
+ [dome.material].flat().forEach(m => m?.dispose());
36
+ }
37
+
30
38
  /** @import { Object3D, Vector3 } from '../../types/common' */
31
39
  /** engine.sky */
32
40
  export class Sky {
@@ -73,8 +81,8 @@ export class Sky {
73
81
  const old = this.dome, at = old.parent, vis = old.visible;
74
82
  this.dome = makeDome(this.uniforms, st, domeParts, engine);
75
83
  this.dome.visible = vis;
76
- at?.remove(old); at?.add(this.dome);
77
- old.geometry?.dispose(); [old.material].flat().forEach(m => m?.dispose());
84
+ disposeDome(old);
85
+ at?.add(engineOwned('sky', this.dome));
78
86
  this._entries?.reapply();
79
87
  this._envSwap();
80
88
  });
@@ -16,20 +16,35 @@ import { isWebGPU, webgpuPart } from '../../render/backend.js';
16
16
  const DEFAULT_INTERVAL = 1; // seconds between rebuilds (only when the sky actually changed)
17
17
  const LOW_TIER_SLOWER = 4; // by default a low-tier device rebuilds this many times less often (an interval the game gives stands): the cube cannot be made smaller (256 px is PMREMGenerator's floor)
18
18
 
19
+ const _H = new Int32Array(2);
20
+ function hashInt(v) {
21
+ const n = v | 0;
22
+ _H[0] = Math.imul(_H[0] ^ n, 0x01000193);
23
+ _H[1] = Math.imul(_H[1] ^ (n + 0x9e3779b9), 0x85ebca6b);
24
+ }
25
+ function hashStr(s) {
26
+ hashInt(s.length);
27
+ for (let i = 0; i < s.length; i++) hashInt(s.charCodeAt(i));
28
+ }
29
+
19
30
  // Everything that decides how the procedural sky looks right now: when it stays put the environment is not rebuilt. It walks the dome's own uniforms
20
31
  // (sun, moon, cloud colour / cover / speed and a game's layer uniforms are all in there, so a new one needs no edit here) and the dome material's
21
32
  // shader revision (a changed clouds() / layer() hook). uTime is left out: it moves every frame, and cloud drift alone is not worth a rebuild
22
33
  function skyKey(sky) {
23
- const f = x => Math.round(x * 400), m = sky.dome.material, parts = [m.uuid, m.version];
24
- for (const [k, u] of Object.entries(sky.uniforms)) {
34
+ const m = sky.dome.material, U = sky.uniforms;
35
+ _H[0] = 0x811c9dc5 | 0; _H[1] = 0x9e3779b9 | 0;
36
+ hashStr(m.uuid); hashInt(m.version);
37
+ for (const k in U) {
25
38
  if (k === 'uTime') continue;
26
- const v = u.value;
27
- if (typeof v === 'number') parts.push(f(v));
28
- else if (v?.isColor) parts.push(f(v.r), f(v.g), f(v.b));
29
- else if (v?.isVector2 || v?.isVector3 || v?.isVector4) parts.push(...v.toArray().map(f));
30
- else if (v?.isTexture) parts.push(v.uuid);
39
+ const v = U[k].value;
40
+ if (typeof v === 'number') hashInt(Math.round(v * 400));
41
+ else if (v?.isColor) { hashInt(Math.round(v.r * 400)); hashInt(Math.round(v.g * 400)); hashInt(Math.round(v.b * 400)); }
42
+ else if (v?.isVector2) { hashInt(Math.round(v.x * 400)); hashInt(Math.round(v.y * 400)); }
43
+ else if (v?.isVector3) { hashInt(Math.round(v.x * 400)); hashInt(Math.round(v.y * 400)); hashInt(Math.round(v.z * 400)); }
44
+ else if (v?.isVector4) { hashInt(Math.round(v.x * 400)); hashInt(Math.round(v.y * 400)); hashInt(Math.round(v.z * 400)); hashInt(Math.round(v.w * 400)); }
45
+ else if (v?.isTexture) { hashStr(v.uuid); hashInt(v.version); }
31
46
  }
32
- return parts.join(',');
47
+ return (_H[0] >>> 0) * 0x200000 + (_H[1] >>> 11);
33
48
  }
34
49
 
35
50
  export const environmentMethods = {
@@ -62,11 +77,12 @@ export const environmentMethods = {
62
77
  if (!this._oEnv.on) return; // the game wrote scene.environment: nothing is rebuilt while the sky has yielded (frame.js watchOwned)
63
78
  if (!e.deferred && e.since < e.interval) return;
64
79
  e.since = 0; e.deferred = false;
65
- if (skyKey(this) !== e.key) this._envBuild();
80
+ const key = skyKey(this);
81
+ if (key !== e.key) this._envBuild(key);
66
82
  },
67
83
 
68
84
  // Render the dome alone into a cube and prefilter it (PMREM). The dome mesh follows the camera, so a copy sharing its material is rendered
69
- _envBuild() {
85
+ _envBuild(key = skyKey(this)) {
70
86
  const e = this._env, r = this.engine.renderer;
71
87
  // WebGPURenderer needs three/webgpu's PMREMGenerator (registered by threedog/tsl)
72
88
  this._pmrem ??= new (isWebGPU(r) ? webgpuPart('classes', 'engine.sky.environment').PMREMGenerator : THREE.PMREMGenerator)(r);
@@ -84,13 +100,13 @@ export const environmentMethods = {
84
100
  // a map the game wrote there is the game's: the owned check (frame.js) has yielded, and the sky writes it no more
85
101
  if (e.into && this._oEnv.on) { e.into.environment = next.texture; this._oEnv.mark(); }
86
102
  if (old !== next) old?.dispose(); e.target = next;
87
- e.builds++; e.key = skyKey(this);
103
+ e.builds++; e.key = key;
88
104
  },
89
105
 
90
106
  // Renderer swap (fallback 'webgl'): the generator and the map belong to the old renderer, so the next frame builds them again on the new one
91
107
  _envSwap() {
92
- this._pmrem = null; this._envScene = null;
93
- if (this._env) { this._env.key = null; this._env.deferred = true; }
108
+ this._pmrem?.dispose(); this._pmrem = null; this._envScene = null;
109
+ if (this._env) { this._env.target?.dispose(); this._env.target = null; this._env.key = null; this._env.deferred = true; }
94
110
  },
95
111
 
96
112
  // handle.remove() and module dispose: what the engine wrote comes off, the GPU memory is released