@woosh/meep-engine 2.147.0 → 2.148.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 (44) hide show
  1. package/package.json +1 -1
  2. package/src/core/math/spline/spline3_hermite_intersection_spline3_hermite.d.ts +4 -4
  3. package/src/core/math/spline/spline3_hermite_intersection_spline3_hermite.d.ts.map +1 -1
  4. package/src/core/math/spline/spline3_hermite_intersection_spline3_hermite.js +48 -52
  5. package/src/core/math/spline/spline3_hermite_intersection_spline3_hermite_2d.d.ts +23 -21
  6. package/src/core/math/spline/spline3_hermite_intersection_spline3_hermite_2d.d.ts.map +1 -1
  7. package/src/core/math/spline/spline3_hermite_intersection_spline3_hermite_2d.js +41 -406
  8. package/src/core/math/spline/spline3_hermite_intersection_spline3_hermite_nd.d.ts +5 -4
  9. package/src/core/math/spline/spline3_hermite_intersection_spline3_hermite_nd.d.ts.map +1 -1
  10. package/src/core/math/spline/spline3_hermite_intersection_spline3_hermite_nd.js +400 -395
  11. package/src/engine/physics/body/SolverBodyState.d.ts +142 -0
  12. package/src/engine/physics/body/SolverBodyState.d.ts.map +1 -0
  13. package/src/engine/physics/body/SolverBodyState.js +251 -0
  14. package/src/engine/physics/broadphase/generate_pairs.d.ts +2 -1
  15. package/src/engine/physics/broadphase/generate_pairs.d.ts.map +1 -1
  16. package/src/engine/physics/broadphase/generate_pairs.js +5 -3
  17. package/src/engine/physics/constraint/solve_constraints.d.ts.map +1 -1
  18. package/src/engine/physics/constraint/solve_constraints.js +691 -673
  19. package/src/engine/physics/ecs/PhysicsSystem.d.ts +21 -18
  20. package/src/engine/physics/ecs/PhysicsSystem.d.ts.map +1 -1
  21. package/src/engine/physics/ecs/PhysicsSystem.js +223 -91
  22. package/src/engine/physics/inertia/world_inverse_inertia.d.ts +23 -0
  23. package/src/engine/physics/inertia/world_inverse_inertia.d.ts.map +1 -1
  24. package/src/engine/physics/inertia/world_inverse_inertia.js +116 -77
  25. package/src/engine/physics/integration/integrate_position.d.ts +11 -1
  26. package/src/engine/physics/integration/integrate_position.d.ts.map +1 -1
  27. package/src/engine/physics/integration/integrate_position.js +97 -79
  28. package/src/engine/physics/integration/integrate_velocity.d.ts +12 -3
  29. package/src/engine/physics/integration/integrate_velocity.d.ts.map +1 -1
  30. package/src/engine/physics/integration/integrate_velocity.js +201 -160
  31. package/src/engine/physics/narrowphase/box_box_manifold.d.ts.map +1 -1
  32. package/src/engine/physics/narrowphase/box_box_manifold.js +750 -665
  33. package/src/engine/physics/narrowphase/box_triangle_contact.d.ts.map +1 -1
  34. package/src/engine/physics/narrowphase/box_triangle_contact.js +4 -34
  35. package/src/engine/physics/narrowphase/clip_against_axis_uv.d.ts +16 -0
  36. package/src/engine/physics/narrowphase/clip_against_axis_uv.d.ts.map +1 -0
  37. package/src/engine/physics/narrowphase/clip_against_axis_uv.js +49 -0
  38. package/src/engine/physics/narrowphase/narrowphase_step.d.ts.map +1 -1
  39. package/src/engine/physics/narrowphase/narrowphase_step.js +24 -3
  40. package/src/engine/physics/queries/raycast.d.ts.map +1 -1
  41. package/src/engine/physics/queries/raycast.js +7 -4
  42. package/src/engine/physics/solver/solve_contacts.d.ts +2 -2
  43. package/src/engine/physics/solver/solve_contacts.d.ts.map +1 -1
  44. package/src/engine/physics/solver/solve_contacts.js +1341 -1173
@@ -1,673 +1,691 @@
1
- import { BodyKind } from "../ecs/BodyKind.js";
2
- import { SleepState } from "../ecs/SleepState.js";
3
- import { JOINT_WORLD } from "../ecs/Joint.js";
4
- import { DofMode } from "./DofMode.js";
5
- import { world_inverse_inertia_apply } from "../inertia/world_inverse_inertia.js";
6
- import { v3_quat3_apply } from "../../../core/geom/vec3/v3_quat3_apply.js";
7
- import { quat3_to_matrix3 } from "../../../core/geom/3d/quaternion/quat3_to_matrix3.js";
8
- import { quat3_multiply } from "../../../core/geom/3d/quaternion/quat3_multiply.js";
9
-
10
- /**
11
- * # 6-DOF constraint (joint) solver
12
- *
13
- * Runs alongside the contact solver inside the same TGS substep loop: each
14
- * substep the joints are warm-started and their velocity rows solved, sharing
15
- * the contact solver's per-substep / warm-start / SPOOK-bias model so the two
16
- * constraint families converge together (a body touched by both a contact and
17
- * a joint sees a single coupled Gauss-Seidel sweep across the substep loop).
18
- *
19
- * A joint is a configurable 6-DOF constraint ({@link Joint}); each relative
20
- * degree of freedom is independently locked / free / limited / springy /
21
- * motorised. This module implements **LOCKED** and **LIMITED** DOFs (linear
22
- * and angular). LOCKED + FREE express the ball-socket, hinge, weld, and
23
- * prismatic joints; LIMITED adds slider end-stops and joint range-of-motion.
24
- * Springs and motors slot into the same per-DOF row model as they land.
25
- *
26
- * ## One row model, parameterised by mode
27
- *
28
- * Every DOF resolves to the same scalar velocity row, contact-shaped: for a
29
- * unit axis `d` and lever arms `rA = anchorA − comA`, `rB = anchorB − comB`,
30
- * `K = invMA + invMB + (rA×d)·Iw_A·(rA×d) + (rB×d)·Iw_B·(rB×d)` (linear)
31
- * `K = d·Iw_A·d + d·Iw_B·d` (angular)
32
- * `vrel = (vA + ωA×rA vB ωB×rB) · d` (linear, A−B)
33
- * `vrel = (ωB ωA) · d` (angular, B−A)
34
- * = clamp(λ_acc (1/K)·(vrel + bias)) λ_acc`,
35
- * applied as `±λ·d`. The **mode** picks only two row parameters:
36
- * - LOCKED → `bias = β/h · error`, impulse clamp `(−∞, +∞)` (bilateral).
37
- * - LIMITED row active only when the DOF position is at/beyond a bound;
38
- * `bias = β/h · (position bound)`, impulse clamp one-sided
39
- * (`[0, +∞)` at the lower stop, `(−∞, 0]` at the upper). The clamp makes
40
- * it a unilateral push-out-of-violation constraint, exactly like a contact
41
- * normal the limit can only resist crossing the stop, never pull the DOF
42
- * back into range.
43
- * The warm-start and the iteration loop are mode-agnostic; they read the
44
- * per-DOF `(active, effMass, bias, clampLo, clampHi)` filled by the mode-aware
45
- * setup. Geometry (anchors / lever arms / position error) is recomputed from
46
- * the current pose every substep, so the joint tracks the bodies as they move.
47
- *
48
- * The "position" along a DOF is `C · axis` for linear (signed anchor offset in
49
- * metres) and `e · axis` for angular, where `e = 2·sign(qD.wqD.xyz` is the
50
- * small-angle rotation vector of the relative rotation `qD = conj(qA)⊗qB`,
51
- * expressed in frame-A-local coordinates (so error component `k` pairs with
52
- * frame axis `k`). The angular position is therefore a first-order (small
53
- * angle) measure: accurate for the modest ranges of slider/hinge end-stops,
54
- * but it under-reports large angles (`2·sin(θ/2)` vs `θ`). Accurate wide-cone
55
- * range-of-motion (ragdoll shoulders) needs the swing-twist decomposition,
56
- * tracked as the follow-up; angular LIMITED here is the moderate-range cut.
57
- * The decomposition itself is already implemented reuse
58
- * `Quaternion.computeSwingAndTwist(axis, swing, twist)` /
59
- * `computeTwistAngle(axis)` (`core/geom/Quaternion.js`) on the relative
60
- * rotation `qD` rather than writing a new one.
61
- *
62
- * @author Alex Goldring
63
- * @copyright Company Named Limited (c) 2026
64
- */
65
-
66
- /**
67
- * Maximum SPOOK position-correction bias for a joint row, m/s — belt-and-braces
68
- * against a wildly-violated constraint (e.g. a freshly-teleported body)
69
- * yanking the solve. Equality joints sit near zero error at steady state, so
70
- * this only clamps transients.
71
- * @type {number}
72
- */
73
- const MAX_JOINT_BIAS = 4;
74
-
75
- /**
76
- * Baumgarte / SPOOK position-correction gain `β`. The per-substep gain is
77
- * / dt_sub`; with `β = 0.2` this matches the contact solver's position
78
- * stiffness. Joints are bilateral equality constraints, so this only nudges
79
- * residual position error toward zero (no clamp interplay to destabilise).
80
- * @type {number}
81
- */
82
- const JOINT_BAUMGARTE = 0.2;
83
-
84
- const scratch_inertia = new Float64Array(3);
85
- const scratch_anchor = new Float64Array(3);
86
- /** Frame-A world basis (rows = A's frame axes in world), from quat3_to_matrix3. */
87
- const scratch_frame_a = new Float64Array(9);
88
- /** Scratch quaternion for frame composition / relative rotation. */
89
- const scratch_q = new Float64Array(4);
90
- /** Angular position error `e` per frame axis (frame-A-local small-angle vector). */
91
- const scratch_ang_err = new Float64Array(3);
92
-
93
- // Per-DOF row parameters, filled per joint by the mode-aware setup and consumed
94
- // by the mode-agnostic warm-start + iteration. Indexed 0..2 (the three frame
95
- // axes); the linear set drives imp[0..2], the angular set drives imp[3..5].
96
- const lin_active = new Uint8Array(3);
97
- const lin_eff = new Float64Array(3);
98
- const lin_bias = new Float64Array(3);
99
- const lin_clo = new Float64Array(3);
100
- const lin_chi = new Float64Array(3);
101
- const lin_gamma = new Float64Array(3);
102
- const ang_active = new Uint8Array(3);
103
- const ang_eff = new Float64Array(3);
104
- const ang_bias = new Float64Array(3);
105
- const ang_clo = new Float64Array(3);
106
- const ang_chi = new Float64Array(3);
107
- const ang_gamma = new Float64Array(3);
108
-
109
- /**
110
- * Angular effective-mass contribution of one body about a unit world axis:
111
- * `a · Iw⁻¹ · a`. Zero for non-dynamic / rotation-locked bodies.
112
- * @returns {number}
113
- */
114
- function angular_axis_effective_mass(rb, transform, ax, ay, az) {
115
- if (rb.kind !== BodyKind.Dynamic) return 0;
116
- const ii = rb.inverseInertiaLocal;
117
- if (ii.x === 0 && ii.y === 0 && ii.z === 0) return 0;
118
- world_inverse_inertia_apply(scratch_inertia, 0, ii, transform.rotation, ax, ay, az);
119
- return ax * scratch_inertia[0] + ay * scratch_inertia[1] + az * scratch_inertia[2];
120
- }
121
-
122
- /**
123
- * Apply a pure angular impulse `sign·λ·axis`: Δω = Iw⁻¹·(sign·λ·axis).
124
- * @param {RigidBody} rb @param {Transform} transform
125
- * @param {number} ax @param {number} ay @param {number} az
126
- * @param {number} lambda @param {number} sign
127
- */
128
- function apply_angular_impulse(rb, transform, ax, ay, az, lambda, sign) {
129
- if (rb.kind !== BodyKind.Dynamic) return;
130
- const ii = rb.inverseInertiaLocal;
131
- if (ii.x === 0 && ii.y === 0 && ii.z === 0) return;
132
- const L = sign * lambda;
133
- world_inverse_inertia_apply(scratch_inertia, 0, ii, transform.rotation, ax * L, ay * L, az * L);
134
- const av = rb.angularVelocity;
135
- av[0] += scratch_inertia[0];
136
- av[1] += scratch_inertia[1];
137
- av[2] += scratch_inertia[2];
138
- }
139
-
140
- /**
141
- * Effective-mass denominator contribution of one body along a unit axis:
142
- * `invM + (r×d)·Iw⁻¹·(r×d)`. Static / kinematic bodies (invM === 0) contribute
143
- * nothing.
144
- *
145
- * @param {RigidBody} rb
146
- * @param {Transform} transform
147
- * @param {number} invM
148
- * @param {number} rx @param {number} ry @param {number} rz
149
- * @param {number} dx @param {number} dy @param {number} dz
150
- * @returns {number}
151
- */
152
- function axis_effective_mass(rb, transform, invM, rx, ry, rz, dx, dy, dz) {
153
- if (invM === 0) return 0;
154
- let k = invM;
155
- const ii = rb.inverseInertiaLocal;
156
- if (ii.x !== 0 || ii.y !== 0 || ii.z !== 0) {
157
- const cx = ry * dz - rz * dy;
158
- const cy = rz * dx - rx * dz;
159
- const cz = rx * dy - ry * dx;
160
- world_inverse_inertia_apply(scratch_inertia, 0, ii, transform.rotation, cx, cy, cz);
161
- k += cx * scratch_inertia[0] + cy * scratch_inertia[1] + cz * scratch_inertia[2];
162
- }
163
- return k;
164
- }
165
-
166
- /**
167
- * Apply impulse `P` at body-relative offset `r`: Δv = P·invM, Δω = Iw⁻¹·(r×P).
168
- * Direct typed-array writes (bypass Vector3#set observers dead weight here).
169
- *
170
- * @param {RigidBody} rb @param {Transform} transform @param {number} invM
171
- * @param {number} rx @param {number} ry @param {number} rz
172
- * @param {number} Px @param {number} Py @param {number} Pz
173
- * @param {number} sign +1 / −1
174
- */
175
- function apply_impulse(rb, transform, invM, rx, ry, rz, Px, Py, Pz, sign) {
176
- if (invM === 0) return;
177
- const sPx = sign * Px, sPy = sign * Py, sPz = sign * Pz;
178
- const lv = rb.linearVelocity;
179
- lv[0] += sPx * invM; lv[1] += sPy * invM; lv[2] += sPz * invM;
180
-
181
- const tx = ry * sPz - rz * sPy;
182
- const ty = rz * sPx - rx * sPz;
183
- const tz = rx * sPy - ry * sPx;
184
- world_inverse_inertia_apply(scratch_inertia, 0, rb.inverseInertiaLocal, transform.rotation, tx, ty, tz);
185
- const av = rb.angularVelocity;
186
- av[0] += scratch_inertia[0]; av[1] += scratch_inertia[1]; av[2] += scratch_inertia[2];
187
- }
188
-
189
- /**
190
- * @param {RigidBody} rb
191
- * @returns {number}
192
- */
193
- function inv_mass_of(rb) {
194
- if (rb.kind !== BodyKind.Dynamic) return 0;
195
- return rb.mass > 0 ? 1 / rb.mass : 0;
196
- }
197
-
198
- /**
199
- * Clamp the SPOOK position bias to ±{@link MAX_JOINT_BIAS}.
200
- * @param {number} b @returns {number}
201
- */
202
- function clamp_bias(b) {
203
- if (b > MAX_JOINT_BIAS) return MAX_JOINT_BIAS;
204
- if (b < -MAX_JOINT_BIAS) return -MAX_JOINT_BIAS;
205
- return b;
206
- }
207
-
208
- /**
209
- * Swing-twist decomposition of the relative rotation `qD = conj(qA)⊗qB`, giving
210
- * the per-frame-axis angular positions used by wide-cone angular DOFs.
211
- *
212
- * Decomposes `qD = swing ⊗ twist`, with **twist** the rotation about frame
213
- * axis X (the bone / twist axis) and **swing** the residual tilt (a rotation
214
- * about an axis in the YZ plane that carries X to its new direction). Writes,
215
- * into `out`:
216
- * - `out[0]` = signed twist angle about X, in `(−π, π]` — *exact*, so a twist
217
- * limit engages at the true angle, not the `2·sin(θ/2)` small-angle proxy;
218
- * - `out[1]`, `out[2]` = the swing angle distributed over Y and Z
219
- * (`φ·axis`, φ the true swing angle), so independent Y/Z swing limits form
220
- * an accurate (box-shaped) cone that holds at large tilt.
221
- * Reduces continuously to the small-angle vector near identity. Pure scratch /
222
- * locals no allocation, suitable for the per-substep hot loop. (The Quaternion
223
- * class has an object-based `computeSwingAndTwist`; this is the inlined,
224
- * allocation-free form — see the bench that justifies it.)
225
- *
226
- * @param {number} dx @param {number} dy @param {number} dz @param {number} dw qD
227
- * @param {Float64Array} out length-3 destination (frame-axis positions)
228
- */
229
- export function swing_twist_error(dx, dy, dz, dw, out) {
230
- // Shortest arc: work with the hemisphere where dw ≥ 0.
231
- if (dw < 0) { dx = -dx; dy = -dy; dz = -dz; dw = -dw; }
232
-
233
- const nxt = Math.sqrt(dx * dx + dw * dw); // |twist| (before normalising)
234
- let sy, sz, sw;
235
- if (nxt < 1e-12) {
236
- // dw 0 and dx ≈ 0: a ~180° pure swing twist is undefined, take 0.
237
- out[0] = 0;
238
- // Swing is qD itself; distribute its angle over Y/Z below.
239
- sy = dy; sz = dz; sw = dw;
240
- } else {
241
- out[0] = 2 * Math.atan2(dx, dw); // exact signed twist about X
242
- const tx = dx / nxt, tw = dw / nxt; // normalised twist (tx,0,0,tw)
243
- // swing = qD ⊗ conj(twist); its X component is identically 0.
244
- sy = dy * tw - dz * tx;
245
- sz = dy * tx + dz * tw;
246
- sw = dw * tw + dx * tx;
247
- }
248
-
249
- if (sw < 0) { sy = -sy; sz = -sz; sw = -sw; }
250
- const syz = Math.sqrt(sy * sy + sz * sz);
251
- if (syz < 1e-9) {
252
- // Near-zero swing: small-angle vector (continuous with φ·axis as φ→0).
253
- out[1] = 2 * sy;
254
- out[2] = 2 * sz;
255
- } else {
256
- const phi = 2 * Math.atan2(syz, sw); // exact swing angle in [0, π]
257
- const s = phi / syz;
258
- out[1] = sy * s;
259
- out[2] = sz * s;
260
- }
261
- }
262
-
263
- /**
264
- * Fill the row parameters for one DOF given its mode, signed position and
265
- * signed velocity.
266
- *
267
- * Writes `active / eff / bias / clampLo / clampHi` at index `k` of the supplied
268
- * arrays and, for LIMITED, resets the warm-start impulse when the active bound
269
- * flipped (a stale opposite-side impulse must not warm-start).
270
- *
271
- * ## LIMITED is a speculative (β = 1) one-sided velocity constraint
272
- *
273
- * Rather than waiting for the DOF to cross a stop and then pushing back with a
274
- * Baumgarte bias which injects real velocity and makes the stop *bounce* when
275
- * nothing else loads the joint — the limit row is always live and uses the full
276
- * `(position bound)/h` as its bias. With the impulse clamped to one side this
277
- * removes exactly the approach velocity that would overshoot, so the DOF
278
- * **lands on the bound** with zero relative velocity (an inelastic stop, no
279
- * penetration to recover, no rebound). When the DOF is far from the bound the
280
- * large same-signed bias drives the clamp to zero, so the row is a no-op — it
281
- * self-gates on approach. At a stop held by a sustained load (gravity on a
282
- * slider) the per-substep load and the per-substep warm-start cancel, so the
283
- * DOF rests exactly on the bound, mirroring a resting contact.
284
- *
285
- * Only the *push-out* side of the bias is clamped (to {@link MAX_JOINT_BIAS}),
286
- * so a body teleported deep past a stop is eased out rather than yanked; the
287
- * gating side is left unbounded.
288
- *
289
- * The active bound is the violated one, else within range — the one the DOF
290
- * is moving toward (`vel` sign). LOCKED is unchanged: a bilateral row with a
291
- * `β/h` Baumgarte bias and no clamp.
292
- *
293
- * ## MOTOR drives the relative velocity toward a target
294
- *
295
- * A motor is a velocity row biased to the target (`bias = −target`, so the
296
- * solve drives the relative velocity to the target) with the impulse clamped to
297
- * `±maxForce·h` a force-limited servo. With an unbounded force budget it is a
298
- * perfect velocity drive; with a finite one it pulls toward the target as hard
299
- * as it can (a weak motor cannot overcome a heavier load). The target follows
300
- * the row's sign convention: linear is A−B along the frame axis, angular is
301
- * B−A about it.
302
- *
303
- * ## SPRING is a SPOOK soft (compliant) constraint
304
- *
305
- * A spring drives the DOF position toward zero with stiffness `k` (N/m or
306
- * N·m/rad) and damping `c`, as a *regularised* row rather than a hard one. The
307
- * implicit-Euler soft constraint (Catto, "Soft Constraints") gives, per substep
308
- * `h`, with `denom = c + h·k`:
309
- * = 1 / (h·denom)` the compliance / regularisation (inverse mass),
310
- * `bias = (k/denom)·C` the restoring velocity, and a softened effective
311
- * `effMass = 1/(K + γ)` mass so the row solves
312
- * `λ = −effMass·(vrel + bias + γ·λ_accum)`.
313
- * The `γ·λ_accum` term is what makes it compliant (the constraint yields in
314
- * proportion to the force it carries), so a spring under load settles at a
315
- * deflection rather than snapping rigid. Stiffness-only (`c = 0`) oscillates
316
- * undamped; damping-only (`k = 0`) is a pure damper; both zero is inert. The
317
- * row is bilateral (no clamp). This is the suspension / bungee / soft-return
318
- * element, and the soft basis for cone-twist later. The angular position uses
319
- * the same small-angle measure as LIMITED (good for modest ranges).
320
- *
321
- * @param {Joint} joint the joint (per-DOF config + warm-start impulse read here)
322
- * @param {number} dofIndex DOF 0..5 (selects mode / limits / motor / imp slot)
323
- * @param {number} k axis index 0..2 (output-array slot for this DOF group)
324
- * @param {number} keff raw effective-mass denominator `K` (0 no row); the
325
- * row's effective mass is `1/K`, or `1/(K+γ)` softened for a spring.
326
- * @param {number} pos signed DOF position (`C·axis` linear / `e·axis` angular)
327
- * @param {number} vel signed DOF velocity along the same axis (selects the
328
- * approached bound for an in-range LIMITED DOF)
329
- * @param {number} spook_locked Baumgarte gain / dt_sub` (LOCKED)
330
- * @param {number} spook_spec speculative gain `1 / dt_sub` (LIMITED)
331
- * @param {number} dt_sub substep size (MOTOR impulse cap = `maxForce·dt_sub`;
332
- * SPRING compliance derives from it)
333
- * @param {Uint8Array} active @param {Float64Array} effOut
334
- * @param {Float64Array} biasOut @param {Float64Array} cloOut @param {Float64Array} chiOut
335
- * @param {Float64Array} gammaOut per-row regularisation (0 for non-spring rows)
336
- */
337
- function fill_row(joint, dofIndex, k, keff, pos, vel, spook_locked, spook_spec, dt_sub,
338
- active, effOut, biasOut, cloOut, chiOut, gammaOut) {
339
- const mode = joint.dofMode[dofIndex];
340
- const imp = joint.dofImpulse;
341
-
342
- if (mode === DofMode.LOCKED) {
343
- if (keff === 0) { active[k] = 0; return; }
344
- effOut[k] = 1 / keff;
345
- biasOut[k] = clamp_bias(spook_locked * pos);
346
- cloOut[k] = -Infinity;
347
- chiOut[k] = Infinity;
348
- gammaOut[k] = 0;
349
- active[k] = 1;
350
- return;
351
- }
352
- if (mode === DofMode.LIMITED) {
353
- if (keff === 0) { imp[dofIndex] = 0; active[k] = 0; return; }
354
- const lower = joint.dofLowerLimit[dofIndex];
355
- const upper = joint.dofUpperLimit[dofIndex];
356
- // Select the bound: the violated one, else the one being approached.
357
- let bound, lower_side;
358
- if (pos <= lower) { bound = lower; lower_side = true; }
359
- else if (pos >= upper) { bound = upper; lower_side = false; }
360
- else { lower_side = vel <= 0; bound = lower_side ? lower : upper; }
361
-
362
- let b = spook_spec * (pos - bound);
363
- if (lower_side) {
364
- // Lower stop: impulse pushes the DOF up (+), clamp [0, +∞). The
365
- // push-out side of the bias is the negative one — bound it.
366
- cloOut[k] = 0; chiOut[k] = Infinity;
367
- if (imp[dofIndex] < 0) imp[dofIndex] = 0; // drop stale upper-side impulse
368
- if (b < -MAX_JOINT_BIAS) b = -MAX_JOINT_BIAS;
369
- } else {
370
- // Upper stop: impulse pushes the DOF down (−), clamp (−∞, 0]. The
371
- // push-out side of the bias is the positive one bound it.
372
- cloOut[k] = -Infinity; chiOut[k] = 0;
373
- if (imp[dofIndex] > 0) imp[dofIndex] = 0; // drop stale lower-side impulse
374
- if (b > MAX_JOINT_BIAS) b = MAX_JOINT_BIAS;
375
- }
376
- effOut[k] = 1 / keff;
377
- biasOut[k] = b;
378
- gammaOut[k] = 0;
379
- active[k] = 1;
380
- return;
381
- }
382
- if (mode === DofMode.MOTOR) {
383
- if (keff === 0) { imp[dofIndex] = 0; active[k] = 0; return; }
384
- const maxImpulse = joint.dofMotorMaxForce[dofIndex] * dt_sub;
385
- if (maxImpulse <= 0) { imp[dofIndex] = 0; active[k] = 0; return; }
386
- effOut[k] = 1 / keff;
387
- // Drive the relative velocity to the target: λ = −eff·(vrel − target).
388
- biasOut[k] = -joint.dofMotorTargetVelocity[dofIndex];
389
- cloOut[k] = -maxImpulse;
390
- chiOut[k] = maxImpulse;
391
- gammaOut[k] = 0;
392
- active[k] = 1;
393
- return;
394
- }
395
- if (mode === DofMode.SPRING) {
396
- if (keff === 0) { imp[dofIndex] = 0; active[k] = 0; return; }
397
- const ks = joint.dofStiffness[dofIndex];
398
- const cs = joint.dofDamping[dofIndex];
399
- const denom = cs + dt_sub * ks;
400
- if (denom <= 0) { imp[dofIndex] = 0; active[k] = 0; return; } // inert (no k, no c)
401
- const gamma = 1 / (dt_sub * denom);
402
- effOut[k] = 1 / (keff + gamma);
403
- biasOut[k] = (ks / denom) * pos; // restoring velocity toward pos = 0
404
- cloOut[k] = -Infinity;
405
- chiOut[k] = Infinity;
406
- gammaOut[k] = gamma;
407
- active[k] = 1;
408
- return;
409
- }
410
- // FREE: no row this substep.
411
- imp[dofIndex] = 0;
412
- active[k] = 0;
413
- }
414
-
415
- /**
416
- * Solve every joint for one substep: recompute geometry at the current poses,
417
- * derive each DOF's row parameters from its mode, replay the per-substep
418
- * warm-start, and run `iters` velocity iterations.
419
- *
420
- * Called once per substep from `PhysicsSystem.fixedUpdate`, after the contact
421
- * solve so the two share the substep / warm-start cadence.
422
- *
423
- * @param {Joint[]} joints live joints (sparse array; holes skipped)
424
- * @param {PhysicsSystem} system reads `__bodies` / `__transforms` / index map
425
- * @param {number} dt_sub substep size in seconds (the SPOOK gain is derived
426
- * from it, matching the contact solver's per-substep position stiffness)
427
- * @param {number} iters velocity iterations
428
- */
429
- export function solve_joints(joints, system, dt_sub, iters) {
430
- const n = joints.length;
431
- if (n === 0 || dt_sub <= 0) return;
432
-
433
- const spook_locked = JOINT_BAUMGARTE / dt_sub;
434
- const spook_spec = 1 / dt_sub;
435
-
436
- const storage = system.storage;
437
-
438
- for (let ji = 0; ji < n; ji++) {
439
- const joint = joints[ji];
440
- if (joint === undefined || joint === null) continue;
441
-
442
- // Generation-checked validity: if A's body was unlinked (and its slot
443
- // possibly reused by a different body), the stored packed id no longer
444
- // validates skip the stale joint rather than attach to the wrong body.
445
- if (!storage.is_valid(joint._bodyIdA)) continue;
446
- const idxA = system.__index_of(joint._bodyIdA);
447
- const rbA = system.__bodies[idxA];
448
- if (rbA === undefined) continue;
449
- const trA = system.__transforms[idxA];
450
-
451
- const to_world = joint._bodyIdB === JOINT_WORLD;
452
- let rbB = null, trB = null, idxB = -1;
453
- if (!to_world) {
454
- if (!storage.is_valid(joint._bodyIdB)) continue;
455
- idxB = system.__index_of(joint._bodyIdB);
456
- rbB = system.__bodies[idxB];
457
- if (rbB === undefined) continue;
458
- trB = system.__transforms[idxB];
459
- }
460
-
461
- // Skip while a participating dynamic body sleeps its velocity must
462
- // stay zero until woken. (Island-aware joint sleep is a follow-up; for
463
- // now jointed bodies that should stay coupled use DisableSleep.)
464
- if (rbA.sleepState === SleepState.Sleeping) continue;
465
- if (!to_world && rbB.sleepState === SleepState.Sleeping) continue;
466
-
467
- // Both bodies static/kinematic → nothing to solve.
468
- const invMA = inv_mass_of(rbA);
469
- const invMB = to_world ? 0 : inv_mass_of(rbB);
470
- if (invMA === 0 && invMB === 0) continue;
471
-
472
- const mode = joint.dofMode;
473
- const linConstrained = mode[0] !== DofMode.FREE || mode[1] !== DofMode.FREE || mode[2] !== DofMode.FREE;
474
- const angConstrained = mode[3] !== DofMode.FREE || mode[4] !== DofMode.FREE || mode[5] !== DofMode.FREE;
475
- if (!linConstrained && !angConstrained) continue;
476
-
477
- // World anchor A and its lever arm rA = R_A · localAnchorA.
478
- const la = joint.localAnchorA;
479
- v3_quat3_apply(scratch_anchor, 0, la.x, la.y, la.z,
480
- trA.rotation[0], trA.rotation[1], trA.rotation[2], trA.rotation[3]);
481
- const rAx = scratch_anchor[0], rAy = scratch_anchor[1], rAz = scratch_anchor[2];
482
- const anchorAx = trA.position.x + rAx;
483
- const anchorAy = trA.position.y + rAy;
484
- const anchorAz = trA.position.z + rAz;
485
-
486
- // World anchor B + lever arm rB. For a world anchor, localAnchorB is a
487
- // fixed world point and there is no body B lever.
488
- let rBx = 0, rBy = 0, rBz = 0;
489
- let anchorBx, anchorBy, anchorBz;
490
- const lb = joint.localAnchorB;
491
- if (to_world) {
492
- anchorBx = lb.x; anchorBy = lb.y; anchorBz = lb.z;
493
- } else {
494
- v3_quat3_apply(scratch_anchor, 0, lb.x, lb.y, lb.z,
495
- trB.rotation[0], trB.rotation[1], trB.rotation[2], trB.rotation[3]);
496
- rBx = scratch_anchor[0]; rBy = scratch_anchor[1]; rBz = scratch_anchor[2];
497
- anchorBx = trB.position.x + rBx;
498
- anchorBy = trB.position.y + rBy;
499
- anchorBz = trB.position.z + rBz;
500
- }
501
-
502
- // Position error C = anchorA anchorB (its projection on a frame axis
503
- // is the signed DOF offset; locked axes drive it to zero, limited axes
504
- // bound it).
505
- const Cx = anchorAx - anchorBx;
506
- const Cy = anchorAy - anchorBy;
507
- const Cz = anchorAz - anchorBz;
508
-
509
- const imp = joint.dofImpulse;
510
- const lvA = rbA.linearVelocity, avA = rbA.angularVelocity;
511
- const lvB = to_world ? null : rbB.linearVelocity;
512
- const avB = to_world ? null : rbB.angularVelocity;
513
-
514
- // === Frame A world axes — shared by the linear AND angular rows ===
515
- // Every DOF is expressed in the joint's frame on body A. Frame A =
516
- // body-A rotation ⊗ localBasisA; the rows of its matrix are the frame
517
- // axes in world (see quat3_to_matrix3).
518
- const lba = joint.localBasisA;
519
- quat3_multiply(scratch_q, 0, trA.rotation[0], trA.rotation[1], trA.rotation[2], trA.rotation[3], lba[0], lba[1], lba[2], lba[3]);
520
- const qAx = scratch_q[0], qAy = scratch_q[1], qAz = scratch_q[2], qAw = scratch_q[3];
521
- quat3_to_matrix3(scratch_frame_a, 0, qAx, qAy, qAz, qAw);
522
- const fa = scratch_frame_a;
523
-
524
- // --- Linear DOF row setup (frame axes). Position along axis k is
525
- // `C · axis_k`; convention is A−B (impulse +to A / −to B). ---
526
- if (linConstrained) {
527
- for (let k = 0; k < 3; k++) {
528
- lin_active[k] = 0;
529
- const m = mode[k];
530
- if (m === DofMode.FREE) { imp[k] = 0; continue; }
531
- const ax = fa[3 * k], ay = fa[3 * k + 1], az = fa[3 * k + 2];
532
- const keff = axis_effective_mass(rbA, trA, invMA, rAx, rAy, rAz, ax, ay, az)
533
- + (to_world ? 0 : axis_effective_mass(rbB, trB, invMB, rBx, rBy, rBz, ax, ay, az));
534
- const pos = Cx * ax + Cy * ay + Cz * az;
535
- // Relative anchor velocity along the axis (A−B), for LIMITED
536
- // bound selection. Cheap; only the projection is used.
537
- let vel = 0;
538
- if (m === DofMode.LIMITED) {
539
- const rvx = (lvA[0] + avA[1] * rAz - avA[2] * rAy) - (to_world ? 0 : (lvB[0] + avB[1] * rBz - avB[2] * rBy));
540
- const rvy = (lvA[1] + avA[2] * rAx - avA[0] * rAz) - (to_world ? 0 : (lvB[1] + avB[2] * rBx - avB[0] * rBz));
541
- const rvz = (lvA[2] + avA[0] * rAy - avA[1] * rAx) - (to_world ? 0 : (lvB[2] + avB[0] * rBy - avB[1] * rBx));
542
- vel = rvx * ax + rvy * ay + rvz * az;
543
- }
544
- fill_row(joint, k, k, keff, pos, vel, spook_locked, spook_spec, dt_sub,
545
- lin_active, lin_eff, lin_bias, lin_clo, lin_chi, lin_gamma);
546
- }
547
- } else {
548
- lin_active[0] = lin_active[1] = lin_active[2] = 0;
549
- }
550
-
551
- // --- Angular DOF row setup (frame axes). Position along axis k is the
552
- // k-th component of the frame-local small-angle error vector `e`;
553
- // convention is B−A (impulse +to B /to A). ---
554
- if (angConstrained) {
555
- // Frame B world rotation (identity for a world anchor → locks A's
556
- // frame to world axes).
557
- let qBx = 0, qBy = 0, qBz = 0, qBw = 1;
558
- if (!to_world) {
559
- const lbb = joint.localBasisB;
560
- quat3_multiply(scratch_q, 0, trB.rotation[0], trB.rotation[1], trB.rotation[2], trB.rotation[3], lbb[0], lbb[1], lbb[2], lbb[3]);
561
- qBx = scratch_q[0]; qBy = scratch_q[1]; qBz = scratch_q[2]; qBw = scratch_q[3];
562
- }
563
- // qD = conj(qA) qB → the per-axis angular position in frame-A
564
- // coords. Two measures: the cheap small-angle rotation vector
565
- // (default — exact at the origin, fine for welds / hinges / modest
566
- // limits) or, when the joint opts into `swingTwist`, the swing-twist
567
- // decomposition (X = twist, Y/Z = swing) with *exact* angles, for
568
- // wide cone-twist range-of-motion (ragdoll shoulders) where the
569
- // small-angle measure under-reports.
570
- quat3_multiply(scratch_q, 0, -qAx, -qAy, -qAz, qAw, qBx, qBy, qBz, qBw);
571
- if (joint.swingTwist) {
572
- swing_twist_error(scratch_q[0], scratch_q[1], scratch_q[2], scratch_q[3], scratch_ang_err);
573
- } else {
574
- const es = scratch_q[3] < 0 ? -2 : 2;
575
- scratch_ang_err[0] = es * scratch_q[0];
576
- scratch_ang_err[1] = es * scratch_q[1];
577
- scratch_ang_err[2] = es * scratch_q[2];
578
- }
579
-
580
- for (let k = 0; k < 3; k++) {
581
- ang_active[k] = 0;
582
- const m = mode[3 + k];
583
- if (m === DofMode.FREE) { imp[3 + k] = 0; continue; }
584
- const ax = fa[3 * k], ay = fa[3 * k + 1], az = fa[3 * k + 2];
585
- const keff = angular_axis_effective_mass(rbA, trA, ax, ay, az)
586
- + (to_world ? 0 : angular_axis_effective_mass(rbB, trB, ax, ay, az));
587
- const pos = scratch_ang_err[k];
588
- // Relative angular velocity about the axis (B−A), for LIMITED
589
- // bound selection.
590
- let vel = 0;
591
- if (m === DofMode.LIMITED) {
592
- vel = -(avA[0] * ax + avA[1] * ay + avA[2] * az);
593
- if (!to_world) vel += avB[0] * ax + avB[1] * ay + avB[2] * az;
594
- }
595
- fill_row(joint, 3 + k, k, keff, pos, vel, spook_locked, spook_spec, dt_sub,
596
- ang_active, ang_eff, ang_bias, ang_clo, ang_chi, ang_gamma);
597
- }
598
- } else {
599
- ang_active[0] = ang_active[1] = ang_active[2] = 0;
600
- }
601
-
602
- if (!lin_active[0] && !lin_active[1] && !lin_active[2]
603
- && !ang_active[0] && !ang_active[1] && !ang_active[2]) continue;
604
-
605
- // --- Per-substep warm-start (frame axes): linear impulse `Σ imp[k]·aₖ`
606
- // applied at the anchors, angular impulse imp[3+k]·aₖ` about the
607
- // frame axes (+to B / −to A). ---
608
- {
609
- let Px = 0, Py = 0, Pz = 0;
610
- for (let k = 0; k < 3; k++) {
611
- if (!lin_active[k]) continue;
612
- const w = imp[k];
613
- Px += w * fa[3 * k]; Py += w * fa[3 * k + 1]; Pz += w * fa[3 * k + 2];
614
- }
615
- if (Px !== 0 || Py !== 0 || Pz !== 0) {
616
- apply_impulse(rbA, trA, invMA, rAx, rAy, rAz, Px, Py, Pz, +1);
617
- if (!to_world) apply_impulse(rbB, trB, invMB, rBx, rBy, rBz, Px, Py, Pz, -1);
618
- }
619
- let Lx = 0, Ly = 0, Lz = 0;
620
- for (let k = 0; k < 3; k++) {
621
- if (!ang_active[k]) continue;
622
- const w = imp[3 + k];
623
- Lx += w * fa[3 * k]; Ly += w * fa[3 * k + 1]; Lz += w * fa[3 * k + 2];
624
- }
625
- if (Lx !== 0 || Ly !== 0 || Lz !== 0) {
626
- if (!to_world) apply_angular_impulse(rbB, trB, Lx, Ly, Lz, 1, +1);
627
- apply_angular_impulse(rbA, trA, Lx, Ly, Lz, 1, -1);
628
- }
629
- }
630
-
631
- for (let it = 0; it < iters; it++) {
632
- // Linear rows (frame axes). The relative anchor velocity is
633
- // recomputed before each row so successive rows see the prior
634
- // impulses (Gauss-Seidel coupling).
635
- for (let k = 0; k < 3; k++) {
636
- if (!lin_active[k]) continue;
637
- const ax = fa[3 * k], ay = fa[3 * k + 1], az = fa[3 * k + 2];
638
- const rvx = (lvA[0] + avA[1] * rAz - avA[2] * rAy) - (to_world ? 0 : (lvB[0] + avB[1] * rBz - avB[2] * rBy));
639
- const rvy = (lvA[1] + avA[2] * rAx - avA[0] * rAz) - (to_world ? 0 : (lvB[1] + avB[2] * rBx - avB[0] * rBz));
640
- const rvz = (lvA[2] + avA[0] * rAy - avA[1] * rAx) - (to_world ? 0 : (lvB[2] + avB[0] * rBy - avB[1] * rBx));
641
- const vrel = rvx * ax + rvy * ay + rvz * az;
642
- const old = imp[k];
643
- // `+ γ·old` regularises a spring row = 0 otherwise exact).
644
- let nv = old - lin_eff[k] * (vrel + lin_bias[k] + lin_gamma[k] * old);
645
- if (nv < lin_clo[k]) nv = lin_clo[k]; else if (nv > lin_chi[k]) nv = lin_chi[k];
646
- imp[k] = nv;
647
- const d = nv - old;
648
- if (d !== 0) {
649
- apply_impulse(rbA, trA, invMA, rAx, rAy, rAz, d * ax, d * ay, d * az, +1);
650
- if (!to_world) apply_impulse(rbB, trB, invMB, rBx, rBy, rBz, d * ax, d * ay, d * az, -1);
651
- }
652
- }
653
-
654
- // Angular rows (frame axes): drive ωB−ωA about each axis toward the
655
- // bias target, clamped per the row's bound.
656
- for (let k = 0; k < 3; k++) {
657
- if (!ang_active[k]) continue;
658
- const ax = fa[3 * k], ay = fa[3 * k + 1], az = fa[3 * k + 2];
659
- let wrel = -(avA[0] * ax + avA[1] * ay + avA[2] * az);
660
- if (!to_world) wrel += avB[0] * ax + avB[1] * ay + avB[2] * az;
661
- const old = imp[3 + k];
662
- let nv = old - ang_eff[k] * (wrel + ang_bias[k] + ang_gamma[k] * old);
663
- if (nv < ang_clo[k]) nv = ang_clo[k]; else if (nv > ang_chi[k]) nv = ang_chi[k];
664
- imp[3 + k] = nv;
665
- const d = nv - old;
666
- if (d !== 0) {
667
- if (!to_world) apply_angular_impulse(rbB, trB, ax, ay, az, d, +1);
668
- apply_angular_impulse(rbA, trA, ax, ay, az, d, -1);
669
- }
670
- }
671
- }
672
- }
673
- }
1
+ import { quat3_multiply } from "../../../core/geom/3d/quaternion/quat3_multiply.js";
2
+ import { quat3_to_matrix3 } from "../../../core/geom/3d/quaternion/quat3_to_matrix3.js";
3
+ import { v3_quat3_apply } from "../../../core/geom/vec3/v3_quat3_apply.js";
4
+ import { body_id_index } from "../body/BodyStorage.js";
5
+ import {
6
+ SBS_AV_X,
7
+ SBS_AV_Y,
8
+ SBS_AV_Z,
9
+ SBS_INV_I_X,
10
+ SBS_INV_I_Y,
11
+ SBS_INV_I_Z,
12
+ SBS_INV_MASS,
13
+ SBS_LV_X,
14
+ SBS_LV_Y,
15
+ SBS_LV_Z,
16
+ SBS_QW,
17
+ SBS_QX,
18
+ SBS_QY,
19
+ SBS_QZ,
20
+ SBS_STRIDE,
21
+ } from "../body/SolverBodyState.js";
22
+ import { JOINT_WORLD } from "../ecs/Joint.js";
23
+ import { SleepState } from "../ecs/SleepState.js";
24
+ import { world_inverse_inertia_apply_raw } from "../inertia/world_inverse_inertia.js";
25
+ import { DofMode } from "./DofMode.js";
26
+
27
+ /**
28
+ * # 6-DOF constraint (joint) solver
29
+ *
30
+ * Runs alongside the contact solver inside the same TGS substep loop: each
31
+ * substep the joints are warm-started and their velocity rows solved, sharing
32
+ * the contact solver's per-substep / warm-start / SPOOK-bias model so the two
33
+ * constraint families converge together (a body touched by both a contact and
34
+ * a joint sees a single coupled Gauss-Seidel sweep across the substep loop).
35
+ *
36
+ * A joint is a configurable 6-DOF constraint ({@link Joint}); each relative
37
+ * degree of freedom is independently locked / free / limited / springy /
38
+ * motorised. This module implements **LOCKED** and **LIMITED** DOFs (linear
39
+ * and angular). LOCKED + FREE express the ball-socket, hinge, weld, and
40
+ * prismatic joints; LIMITED adds slider end-stops and joint range-of-motion.
41
+ * Springs and motors slot into the same per-DOF row model as they land.
42
+ *
43
+ * ## One row model, parameterised by mode
44
+ *
45
+ * Every DOF resolves to the same scalar velocity row, contact-shaped: for a
46
+ * unit axis `d` and lever arms `rA = anchorA comA`, `rB = anchorB − comB`,
47
+ * `K = invMA + invMB + (rA×d)·Iw_A·(rA×d) + (rB×d)·Iw_B·(rB×d)` (linear)
48
+ * `K = d·Iw_A·d + d·Iw_B·d` (angular)
49
+ * `vrel = (vA + ωA×rA vB ωB×rB) · d` (linear, A−B)
50
+ * `vrel = (ωB ωA) · d` (angular, B−A)
51
+ * = clamp(λ_acc (1/K)·(vrel + bias)) λ_acc`,
52
+ * applied as `±λ·d`. The **mode** picks only two row parameters:
53
+ * - LOCKED → `bias = β/h · error`, impulse clamp `(−∞, +∞)` (bilateral).
54
+ * - LIMITED row active only when the DOF position is at/beyond a bound;
55
+ * `bias = β/h · (position − bound)`, impulse clamp one-sided
56
+ * (`[0, +∞)` at the lower stop, `(−∞, 0]` at the upper). The clamp makes
57
+ * it a unilateral push-out-of-violation constraint, exactly like a contact
58
+ * normal the limit can only resist crossing the stop, never pull the DOF
59
+ * back into range.
60
+ * The warm-start and the iteration loop are mode-agnostic; they read the
61
+ * per-DOF `(active, effMass, bias, clampLo, clampHi)` filled by the mode-aware
62
+ * setup. Geometry (anchors / lever arms / position error) is recomputed from
63
+ * the current pose every substep, so the joint tracks the bodies as they move.
64
+ *
65
+ * The "position" along a DOF is `C · axis` for linear (signed anchor offset in
66
+ * metres) and `e · axis` for angular, where `e = 2·sign(qD.w)·qD.xyz` is the
67
+ * small-angle rotation vector of the relative rotation `qD = conj(qA)⊗qB`,
68
+ * expressed in frame-A-local coordinates (so error component `k` pairs with
69
+ * frame axis `k`). The angular position is therefore a first-order (small
70
+ * angle) measure: accurate for the modest ranges of slider/hinge end-stops,
71
+ * but it under-reports large angles (`2·sin(θ/2)` vs `θ`). Accurate wide-cone
72
+ * range-of-motion (ragdoll shoulders) needs the swing-twist decomposition,
73
+ * tracked as the follow-up; angular LIMITED here is the moderate-range cut.
74
+ * The decomposition itself is already implemented — reuse
75
+ * `Quaternion.computeSwingAndTwist(axis, swing, twist)` /
76
+ * `computeTwistAngle(axis)` (`core/geom/Quaternion.js`) on the relative
77
+ * rotation `qD` rather than writing a new one.
78
+ *
79
+ * @author Alex Goldring
80
+ * @copyright Company Named Limited (c) 2026
81
+ */
82
+
83
+ /**
84
+ * Maximum SPOOK position-correction bias for a joint row, m/s — belt-and-braces
85
+ * against a wildly-violated constraint (e.g. a freshly-teleported body)
86
+ * yanking the solve. Equality joints sit near zero error at steady state, so
87
+ * this only clamps transients.
88
+ * @type {number}
89
+ */
90
+ const MAX_JOINT_BIAS = 4;
91
+
92
+ /**
93
+ * Baumgarte / SPOOK position-correction gain `β`. The per-substep gain is
94
+ * / dt_sub`; with = 0.2` this matches the contact solver's position
95
+ * stiffness. Joints are bilateral equality constraints, so this only nudges
96
+ * residual position error toward zero (no clamp interplay to destabilise).
97
+ * @type {number}
98
+ */
99
+ const JOINT_BAUMGARTE = 0.2;
100
+
101
+ const scratch_inertia = new Float64Array(3);
102
+ const scratch_anchor = new Float64Array(3);
103
+ /** Frame-A world basis (rows = A's frame axes in world), from quat3_to_matrix3. */
104
+ const scratch_frame_a = new Float64Array(9);
105
+ /** Scratch quaternion for frame composition / relative rotation. */
106
+ const scratch_q = new Float64Array(4);
107
+ /** Angular position error `e` per frame axis (frame-A-local small-angle vector). */
108
+ const scratch_ang_err = new Float64Array(3);
109
+
110
+ // Per-DOF row parameters, filled per joint by the mode-aware setup and consumed
111
+ // by the mode-agnostic warm-start + iteration. Indexed 0..2 (the three frame
112
+ // axes); the linear set drives imp[0..2], the angular set drives imp[3..5].
113
+ const lin_active = new Uint8Array(3);
114
+ const lin_eff = new Float64Array(3);
115
+ const lin_bias = new Float64Array(3);
116
+ const lin_clo = new Float64Array(3);
117
+ const lin_chi = new Float64Array(3);
118
+ const lin_gamma = new Float64Array(3);
119
+ const ang_active = new Uint8Array(3);
120
+ const ang_eff = new Float64Array(3);
121
+ const ang_bias = new Float64Array(3);
122
+ const ang_clo = new Float64Array(3);
123
+ const ang_chi = new Float64Array(3);
124
+ const ang_gamma = new Float64Array(3);
125
+
126
+ /**
127
+ * Angular effective-mass contribution of one body about a unit world axis:
128
+ * `a · Iw⁻¹ · a`. Zero for non-dynamic / rotation-locked bodies (whose
129
+ * {@link SolverBodyState} inverse-inertia diagonal is zero).
130
+ * @param {Float64Array} ss solver-body-state data array
131
+ * @param {number} base `body_index * SBS_STRIDE`
132
+ * @returns {number}
133
+ */
134
+ function angular_axis_effective_mass(ss, base, ax, ay, az) {
135
+ const iix = ss[base + SBS_INV_I_X], iiy = ss[base + SBS_INV_I_Y], iiz = ss[base + SBS_INV_I_Z];
136
+ if (iix === 0 && iiy === 0 && iiz === 0) return 0;
137
+ world_inverse_inertia_apply_raw(scratch_inertia, 0, iix, iiy, iiz,
138
+ ss[base + SBS_QX], ss[base + SBS_QY], ss[base + SBS_QZ], ss[base + SBS_QW], ax, ay, az);
139
+ return ax * scratch_inertia[0] + ay * scratch_inertia[1] + az * scratch_inertia[2];
140
+ }
141
+
142
+ /**
143
+ * Apply a pure angular impulse `sign·λ·axis`: Δω = Iw⁻¹·(sign·λ·axis).
144
+ * @param {Float64Array} ss solver-body-state data array
145
+ * @param {number} base `body_index * SBS_STRIDE`
146
+ * @param {number} ax @param {number} ay @param {number} az
147
+ * @param {number} lambda @param {number} sign
148
+ */
149
+ function apply_angular_impulse(ss, base, ax, ay, az, lambda, sign) {
150
+ const iix = ss[base + SBS_INV_I_X], iiy = ss[base + SBS_INV_I_Y], iiz = ss[base + SBS_INV_I_Z];
151
+ if (iix === 0 && iiy === 0 && iiz === 0) return;
152
+ const L = sign * lambda;
153
+ world_inverse_inertia_apply_raw(scratch_inertia, 0, iix, iiy, iiz,
154
+ ss[base + SBS_QX], ss[base + SBS_QY], ss[base + SBS_QZ], ss[base + SBS_QW], ax * L, ay * L, az * L);
155
+ ss[base + SBS_AV_X] += scratch_inertia[0];
156
+ ss[base + SBS_AV_Y] += scratch_inertia[1];
157
+ ss[base + SBS_AV_Z] += scratch_inertia[2];
158
+ }
159
+
160
+ /**
161
+ * Effective-mass denominator contribution of one body along a unit axis:
162
+ * `invM + (r×d)·Iw⁻¹·(r×d)`. Static / kinematic bodies (invM === 0) contribute
163
+ * nothing.
164
+ *
165
+ * @param {Float64Array} ss solver-body-state data array
166
+ * @param {number} base `body_index * SBS_STRIDE`
167
+ * @param {number} invM
168
+ * @param {number} rx @param {number} ry @param {number} rz
169
+ * @param {number} dx @param {number} dy @param {number} dz
170
+ * @returns {number}
171
+ */
172
+ function axis_effective_mass(ss, base, invM, rx, ry, rz, dx, dy, dz) {
173
+ if (invM === 0) return 0;
174
+ let k = invM;
175
+ const iix = ss[base + SBS_INV_I_X], iiy = ss[base + SBS_INV_I_Y], iiz = ss[base + SBS_INV_I_Z];
176
+ if (iix !== 0 || iiy !== 0 || iiz !== 0) {
177
+ const cx = ry * dz - rz * dy;
178
+ const cy = rz * dx - rx * dz;
179
+ const cz = rx * dy - ry * dx;
180
+ world_inverse_inertia_apply_raw(scratch_inertia, 0, iix, iiy, iiz,
181
+ ss[base + SBS_QX], ss[base + SBS_QY], ss[base + SBS_QZ], ss[base + SBS_QW], cx, cy, cz);
182
+ k += cx * scratch_inertia[0] + cy * scratch_inertia[1] + cz * scratch_inertia[2];
183
+ }
184
+ return k;
185
+ }
186
+
187
+ /**
188
+ * Apply impulse `P` at body-relative offset `r`: Δv = P·invM, Δω = Iw⁻¹·(r×P).
189
+ * Reads / writes the body's {@link SolverBodyState} span.
190
+ *
191
+ * @param {Float64Array} ss solver-body-state data array
192
+ * @param {number} base `body_index * SBS_STRIDE`
193
+ * @param {number} invM
194
+ * @param {number} rx @param {number} ry @param {number} rz
195
+ * @param {number} Px @param {number} Py @param {number} Pz
196
+ * @param {number} sign +1 / −1
197
+ */
198
+ function apply_impulse(ss, base, invM, rx, ry, rz, Px, Py, Pz, sign) {
199
+ if (invM === 0) return;
200
+ const sPx = sign * Px, sPy = sign * Py, sPz = sign * Pz;
201
+ ss[base + SBS_LV_X] += sPx * invM;
202
+ ss[base + SBS_LV_Y] += sPy * invM;
203
+ ss[base + SBS_LV_Z] += sPz * invM;
204
+
205
+ const tx = ry * sPz - rz * sPy;
206
+ const ty = rz * sPx - rx * sPz;
207
+ const tz = rx * sPy - ry * sPx;
208
+ world_inverse_inertia_apply_raw(scratch_inertia, 0,
209
+ ss[base + SBS_INV_I_X], ss[base + SBS_INV_I_Y], ss[base + SBS_INV_I_Z],
210
+ ss[base + SBS_QX], ss[base + SBS_QY], ss[base + SBS_QZ], ss[base + SBS_QW], tx, ty, tz);
211
+ ss[base + SBS_AV_X] += scratch_inertia[0];
212
+ ss[base + SBS_AV_Y] += scratch_inertia[1];
213
+ ss[base + SBS_AV_Z] += scratch_inertia[2];
214
+ }
215
+
216
+ /**
217
+ * Clamp the SPOOK position bias to ±{@link MAX_JOINT_BIAS}.
218
+ * @param {number} b @returns {number}
219
+ */
220
+ function clamp_bias(b) {
221
+ if (b > MAX_JOINT_BIAS) return MAX_JOINT_BIAS;
222
+ if (b < -MAX_JOINT_BIAS) return -MAX_JOINT_BIAS;
223
+ return b;
224
+ }
225
+
226
+ /**
227
+ * Swing-twist decomposition of the relative rotation `qD = conj(qA)⊗qB`, giving
228
+ * the per-frame-axis angular positions used by wide-cone angular DOFs.
229
+ *
230
+ * Decomposes `qD = swing ⊗ twist`, with **twist** the rotation about frame
231
+ * axis X (the bone / twist axis) and **swing** the residual tilt (a rotation
232
+ * about an axis in the YZ plane that carries X to its new direction). Writes,
233
+ * into `out`:
234
+ * - `out[0]` = signed twist angle about X, in `(−π, π]` — *exact*, so a twist
235
+ * limit engages at the true angle, not the `2·sin(θ/2)` small-angle proxy;
236
+ * - `out[1]`, `out[2]` = the swing angle distributed over Y and Z
237
+ * (`φ·axis`, φ the true swing angle), so independent Y/Z swing limits form
238
+ * an accurate (box-shaped) cone that holds at large tilt.
239
+ * Reduces continuously to the small-angle vector near identity. Pure scratch /
240
+ * locals — no allocation, suitable for the per-substep hot loop. (The Quaternion
241
+ * class has an object-based `computeSwingAndTwist`; this is the inlined,
242
+ * allocation-free form see the bench that justifies it.)
243
+ *
244
+ * @param {number} dx @param {number} dy @param {number} dz @param {number} dw qD
245
+ * @param {Float64Array} out length-3 destination (frame-axis positions)
246
+ */
247
+ export function swing_twist_error(dx, dy, dz, dw, out) {
248
+ // Shortest arc: work with the hemisphere where dw ≥ 0.
249
+ if (dw < 0) { dx = -dx; dy = -dy; dz = -dz; dw = -dw; }
250
+
251
+ const nxt = Math.sqrt(dx * dx + dw * dw); // |twist| (before normalising)
252
+ let sy, sz, sw;
253
+ if (nxt < 1e-12) {
254
+ // dw 0 and dx ≈ 0: a ~180° pure swing — twist is undefined, take 0.
255
+ out[0] = 0;
256
+ // Swing is qD itself; distribute its angle over Y/Z below.
257
+ sy = dy; sz = dz; sw = dw;
258
+ } else {
259
+ out[0] = 2 * Math.atan2(dx, dw); // exact signed twist about X
260
+ const tx = dx / nxt, tw = dw / nxt; // normalised twist (tx,0,0,tw)
261
+ // swing = qD ⊗ conj(twist); its X component is identically 0.
262
+ sy = dy * tw - dz * tx;
263
+ sz = dy * tx + dz * tw;
264
+ sw = dw * tw + dx * tx;
265
+ }
266
+
267
+ if (sw < 0) { sy = -sy; sz = -sz; sw = -sw; }
268
+ const syz = Math.sqrt(sy * sy + sz * sz);
269
+ if (syz < 1e-9) {
270
+ // Near-zero swing: small-angle vector (continuous with φ·axis as φ→0).
271
+ out[1] = 2 * sy;
272
+ out[2] = 2 * sz;
273
+ } else {
274
+ const phi = 2 * Math.atan2(syz, sw); // exact swing angle in [0, π]
275
+ const s = phi / syz;
276
+ out[1] = sy * s;
277
+ out[2] = sz * s;
278
+ }
279
+ }
280
+
281
+ /**
282
+ * Fill the row parameters for one DOF given its mode, signed position and
283
+ * signed velocity.
284
+ *
285
+ * Writes `active / eff / bias / clampLo / clampHi` at index `k` of the supplied
286
+ * arrays and, for LIMITED, resets the warm-start impulse when the active bound
287
+ * flipped (a stale opposite-side impulse must not warm-start).
288
+ *
289
+ * ## LIMITED is a speculative = 1) one-sided velocity constraint
290
+ *
291
+ * Rather than waiting for the DOF to cross a stop and then pushing back with a
292
+ * Baumgarte bias — which injects real velocity and makes the stop *bounce* when
293
+ * nothing else loads the joint the limit row is always live and uses the full
294
+ * `(position − bound)/h` as its bias. With the impulse clamped to one side this
295
+ * removes exactly the approach velocity that would overshoot, so the DOF
296
+ * **lands on the bound** with zero relative velocity (an inelastic stop, no
297
+ * penetration to recover, no rebound). When the DOF is far from the bound the
298
+ * large same-signed bias drives the clamp to zero, so the row is a no-op — it
299
+ * self-gates on approach. At a stop held by a sustained load (gravity on a
300
+ * slider) the per-substep load and the per-substep warm-start cancel, so the
301
+ * DOF rests exactly on the bound, mirroring a resting contact.
302
+ *
303
+ * Only the *push-out* side of the bias is clamped (to {@link MAX_JOINT_BIAS}),
304
+ * so a body teleported deep past a stop is eased out rather than yanked; the
305
+ * gating side is left unbounded.
306
+ *
307
+ * The active bound is the violated one, else — within range — the one the DOF
308
+ * is moving toward (`vel` sign). LOCKED is unchanged: a bilateral row with a
309
+ * `β/h` Baumgarte bias and no clamp.
310
+ *
311
+ * ## MOTOR drives the relative velocity toward a target
312
+ *
313
+ * A motor is a velocity row biased to the target (`bias = −target`, so the
314
+ * solve drives the relative velocity to the target) with the impulse clamped to
315
+ * `±maxForce·h` a force-limited servo. With an unbounded force budget it is a
316
+ * perfect velocity drive; with a finite one it pulls toward the target as hard
317
+ * as it can (a weak motor cannot overcome a heavier load). The target follows
318
+ * the row's sign convention: linear is A−B along the frame axis, angular is
319
+ * B−A about it.
320
+ *
321
+ * ## SPRING is a SPOOK soft (compliant) constraint
322
+ *
323
+ * A spring drives the DOF position toward zero with stiffness `k` (N/m or
324
+ * N·m/rad) and damping `c`, as a *regularised* row rather than a hard one. The
325
+ * implicit-Euler soft constraint (Catto, "Soft Constraints") gives, per substep
326
+ * `h`, with `denom = c + h·k`:
327
+ * = 1 / (h·denom)` the compliance / regularisation (inverse mass),
328
+ * `bias = (k/denom)·C` the restoring velocity, and a softened effective
329
+ * `effMass = 1/(K + γ)` mass so the row solves
330
+ * = −effMass·(vrel + bias + γ·λ_accum)`.
331
+ * The `γ·λ_accum` term is what makes it compliant (the constraint yields in
332
+ * proportion to the force it carries), so a spring under load settles at a
333
+ * deflection rather than snapping rigid. Stiffness-only (`c = 0`) oscillates
334
+ * undamped; damping-only (`k = 0`) is a pure damper; both zero is inert. The
335
+ * row is bilateral (no clamp). This is the suspension / bungee / soft-return
336
+ * element, and the soft basis for cone-twist later. The angular position uses
337
+ * the same small-angle measure as LIMITED (good for modest ranges).
338
+ *
339
+ * @param {Joint} joint the joint (per-DOF config + warm-start impulse read here)
340
+ * @param {number} dofIndex DOF 0..5 (selects mode / limits / motor / imp slot)
341
+ * @param {number} k axis index 0..2 (output-array slot for this DOF group)
342
+ * @param {number} keff raw effective-mass denominator `K` (0 no row); the
343
+ * row's effective mass is `1/K`, or `1/(K+γ)` softened for a spring.
344
+ * @param {number} pos signed DOF position (`C·axis` linear / `e·axis` angular)
345
+ * @param {number} vel signed DOF velocity along the same axis (selects the
346
+ * approached bound for an in-range LIMITED DOF)
347
+ * @param {number} spook_locked Baumgarte gain `β / dt_sub` (LOCKED)
348
+ * @param {number} spook_spec speculative gain `1 / dt_sub` (LIMITED)
349
+ * @param {number} dt_sub substep size (MOTOR impulse cap = `maxForce·dt_sub`;
350
+ * SPRING compliance derives from it)
351
+ * @param {Uint8Array} active @param {Float64Array} effOut
352
+ * @param {Float64Array} biasOut @param {Float64Array} cloOut @param {Float64Array} chiOut
353
+ * @param {Float64Array} gammaOut per-row regularisation (0 for non-spring rows)
354
+ */
355
+ function fill_row(joint, dofIndex, k, keff, pos, vel, spook_locked, spook_spec, dt_sub,
356
+ active, effOut, biasOut, cloOut, chiOut, gammaOut) {
357
+ const mode = joint.dofMode[dofIndex];
358
+ const imp = joint.dofImpulse;
359
+
360
+ if (mode === DofMode.LOCKED) {
361
+ if (keff === 0) { active[k] = 0; return; }
362
+ effOut[k] = 1 / keff;
363
+ biasOut[k] = clamp_bias(spook_locked * pos);
364
+ cloOut[k] = -Infinity;
365
+ chiOut[k] = Infinity;
366
+ gammaOut[k] = 0;
367
+ active[k] = 1;
368
+ return;
369
+ }
370
+ if (mode === DofMode.LIMITED) {
371
+ if (keff === 0) { imp[dofIndex] = 0; active[k] = 0; return; }
372
+ const lower = joint.dofLowerLimit[dofIndex];
373
+ const upper = joint.dofUpperLimit[dofIndex];
374
+ // Select the bound: the violated one, else the one being approached.
375
+ let bound, lower_side;
376
+ if (pos <= lower) { bound = lower; lower_side = true; }
377
+ else if (pos >= upper) { bound = upper; lower_side = false; }
378
+ else { lower_side = vel <= 0; bound = lower_side ? lower : upper; }
379
+
380
+ let b = spook_spec * (pos - bound);
381
+ if (lower_side) {
382
+ // Lower stop: impulse pushes the DOF up (+), clamp [0, +∞). The
383
+ // push-out side of the bias is the negative one bound it.
384
+ cloOut[k] = 0; chiOut[k] = Infinity;
385
+ if (imp[dofIndex] < 0) imp[dofIndex] = 0; // drop stale upper-side impulse
386
+ if (b < -MAX_JOINT_BIAS) b = -MAX_JOINT_BIAS;
387
+ } else {
388
+ // Upper stop: impulse pushes the DOF down (−), clamp (−∞, 0]. The
389
+ // push-out side of the bias is the positive one — bound it.
390
+ cloOut[k] = -Infinity; chiOut[k] = 0;
391
+ if (imp[dofIndex] > 0) imp[dofIndex] = 0; // drop stale lower-side impulse
392
+ if (b > MAX_JOINT_BIAS) b = MAX_JOINT_BIAS;
393
+ }
394
+ effOut[k] = 1 / keff;
395
+ biasOut[k] = b;
396
+ gammaOut[k] = 0;
397
+ active[k] = 1;
398
+ return;
399
+ }
400
+ if (mode === DofMode.MOTOR) {
401
+ if (keff === 0) { imp[dofIndex] = 0; active[k] = 0; return; }
402
+ const maxImpulse = joint.dofMotorMaxForce[dofIndex] * dt_sub;
403
+ if (maxImpulse <= 0) { imp[dofIndex] = 0; active[k] = 0; return; }
404
+ effOut[k] = 1 / keff;
405
+ // Drive the relative velocity to the target: λ = −eff·(vrel − target).
406
+ biasOut[k] = -joint.dofMotorTargetVelocity[dofIndex];
407
+ cloOut[k] = -maxImpulse;
408
+ chiOut[k] = maxImpulse;
409
+ gammaOut[k] = 0;
410
+ active[k] = 1;
411
+ return;
412
+ }
413
+ if (mode === DofMode.SPRING) {
414
+ if (keff === 0) { imp[dofIndex] = 0; active[k] = 0; return; }
415
+ const ks = joint.dofStiffness[dofIndex];
416
+ const cs = joint.dofDamping[dofIndex];
417
+ const denom = cs + dt_sub * ks;
418
+ if (denom <= 0) { imp[dofIndex] = 0; active[k] = 0; return; } // inert (no k, no c)
419
+ const gamma = 1 / (dt_sub * denom);
420
+ effOut[k] = 1 / (keff + gamma);
421
+ biasOut[k] = (ks / denom) * pos; // restoring velocity toward pos = 0
422
+ cloOut[k] = -Infinity;
423
+ chiOut[k] = Infinity;
424
+ gammaOut[k] = gamma;
425
+ active[k] = 1;
426
+ return;
427
+ }
428
+ // FREE: no row this substep.
429
+ imp[dofIndex] = 0;
430
+ active[k] = 0;
431
+ }
432
+
433
+ /**
434
+ * Solve every joint for one substep: recompute geometry at the current poses,
435
+ * derive each DOF's row parameters from its mode, replay the per-substep
436
+ * warm-start, and run `iters` velocity iterations.
437
+ *
438
+ * Called once per substep from `PhysicsSystem.fixedUpdate`, after the contact
439
+ * solve so the two share the substep / warm-start cadence.
440
+ *
441
+ * @param {Joint[]} joints live joints (sparse array; holes skipped)
442
+ * @param {PhysicsSystem} system reads `__bodies` / `__transforms` / index map
443
+ * @param {number} dt_sub substep size in seconds (the SPOOK gain is derived
444
+ * from it, matching the contact solver's per-substep position stiffness)
445
+ * @param {number} iters velocity iterations
446
+ */
447
+ export function solve_joints(joints, system, dt_sub, iters) {
448
+ const n = joints.length;
449
+ if (n === 0 || dt_sub <= 0) return;
450
+
451
+ const spook_locked = JOINT_BAUMGARTE / dt_sub;
452
+ const spook_spec = 1 / dt_sub;
453
+
454
+ const storage = system.storage;
455
+ const ss = system.__solver_state.data;
456
+
457
+ for (let ji = 0; ji < n; ji++) {
458
+ const joint = joints[ji];
459
+ if (joint === undefined || joint === null) continue;
460
+
461
+ // Generation-checked validity: if A's body was unlinked (and its slot
462
+ // possibly reused by a different body), the stored packed id no longer
463
+ // validates skip the stale joint rather than attach to the wrong body.
464
+ if (!storage.is_valid(joint._bodyIdA)) continue;
465
+ const idxA = body_id_index(joint._bodyIdA);
466
+ const baseA = idxA * SBS_STRIDE;
467
+ const rbA = system.__bodies[idxA];
468
+ if (rbA === undefined) continue;
469
+ const trA = system.__transforms[idxA];
470
+
471
+ const to_world = joint._bodyIdB === JOINT_WORLD;
472
+ let rbB = null, trB = null, idxB = -1, baseB = -1;
473
+ if (!to_world) {
474
+ if (!storage.is_valid(joint._bodyIdB)) continue;
475
+ idxB = body_id_index(joint._bodyIdB);
476
+ baseB = idxB * SBS_STRIDE;
477
+ rbB = system.__bodies[idxB];
478
+ if (rbB === undefined) continue;
479
+ trB = system.__transforms[idxB];
480
+ }
481
+
482
+ // Skip while a participating dynamic body sleeps — its velocity must
483
+ // stay zero until woken. (Island-aware joint sleep is a follow-up; for
484
+ // now jointed bodies that should stay coupled use DisableSleep.)
485
+ if (rbA.sleepState === SleepState.Sleeping) continue;
486
+ if (!to_world && rbB.sleepState === SleepState.Sleeping) continue;
487
+
488
+ // Both bodies static/kinematic nothing to solve.
489
+ const invMA = ss[baseA + SBS_INV_MASS];
490
+ const invMB = to_world ? 0 : ss[baseB + SBS_INV_MASS];
491
+ if (invMA === 0 && invMB === 0) continue;
492
+
493
+ const mode = joint.dofMode;
494
+ const linConstrained = mode[0] !== DofMode.FREE || mode[1] !== DofMode.FREE || mode[2] !== DofMode.FREE;
495
+ const angConstrained = mode[3] !== DofMode.FREE || mode[4] !== DofMode.FREE || mode[5] !== DofMode.FREE;
496
+ if (!linConstrained && !angConstrained) continue;
497
+
498
+ // World anchor A and its lever arm rA = R_A · localAnchorA.
499
+ const la = joint.localAnchorA;
500
+ v3_quat3_apply(scratch_anchor, 0, la.x, la.y, la.z,
501
+ trA.rotation[0], trA.rotation[1], trA.rotation[2], trA.rotation[3]);
502
+ const rAx = scratch_anchor[0], rAy = scratch_anchor[1], rAz = scratch_anchor[2];
503
+ const anchorAx = trA.position.x + rAx;
504
+ const anchorAy = trA.position.y + rAy;
505
+ const anchorAz = trA.position.z + rAz;
506
+
507
+ // World anchor B + lever arm rB. For a world anchor, localAnchorB is a
508
+ // fixed world point and there is no body B lever.
509
+ let rBx = 0, rBy = 0, rBz = 0;
510
+ let anchorBx, anchorBy, anchorBz;
511
+ const lb = joint.localAnchorB;
512
+ if (to_world) {
513
+ anchorBx = lb.x; anchorBy = lb.y; anchorBz = lb.z;
514
+ } else {
515
+ v3_quat3_apply(scratch_anchor, 0, lb.x, lb.y, lb.z,
516
+ trB.rotation[0], trB.rotation[1], trB.rotation[2], trB.rotation[3]);
517
+ rBx = scratch_anchor[0]; rBy = scratch_anchor[1]; rBz = scratch_anchor[2];
518
+ anchorBx = trB.position.x + rBx;
519
+ anchorBy = trB.position.y + rBy;
520
+ anchorBz = trB.position.z + rBz;
521
+ }
522
+
523
+ // Position error C = anchorA − anchorB (its projection on a frame axis
524
+ // is the signed DOF offset; locked axes drive it to zero, limited axes
525
+ // bound it).
526
+ const Cx = anchorAx - anchorBx;
527
+ const Cy = anchorAy - anchorBy;
528
+ const Cz = anchorAz - anchorBz;
529
+
530
+ const imp = joint.dofImpulse;
531
+
532
+ // === Frame A world axes shared by the linear AND angular rows ===
533
+ // Every DOF is expressed in the joint's frame on body A. Frame A =
534
+ // body-A rotation localBasisA; the rows of its matrix are the frame
535
+ // axes in world (see quat3_to_matrix3).
536
+ const lba = joint.localBasisA;
537
+ quat3_multiply(scratch_q, 0, trA.rotation[0], trA.rotation[1], trA.rotation[2], trA.rotation[3], lba[0], lba[1], lba[2], lba[3]);
538
+ const qAx = scratch_q[0], qAy = scratch_q[1], qAz = scratch_q[2], qAw = scratch_q[3];
539
+ quat3_to_matrix3(scratch_frame_a, 0, qAx, qAy, qAz, qAw);
540
+ const fa = scratch_frame_a;
541
+
542
+ // --- Linear DOF row setup (frame axes). Position along axis k is
543
+ // `C · axis_k`; convention is A−B (impulse +to A / −to B). ---
544
+ if (linConstrained) {
545
+ for (let k = 0; k < 3; k++) {
546
+ lin_active[k] = 0;
547
+ const m = mode[k];
548
+ if (m === DofMode.FREE) { imp[k] = 0; continue; }
549
+ const ax = fa[3 * k], ay = fa[3 * k + 1], az = fa[3 * k + 2];
550
+ const keff = axis_effective_mass(ss, baseA, invMA, rAx, rAy, rAz, ax, ay, az)
551
+ + (to_world ? 0 : axis_effective_mass(ss, baseB, invMB, rBx, rBy, rBz, ax, ay, az));
552
+ const pos = Cx * ax + Cy * ay + Cz * az;
553
+ // Relative anchor velocity along the axis (AB), for LIMITED
554
+ // bound selection. Cheap; only the projection is used.
555
+ let vel = 0;
556
+ if (m === DofMode.LIMITED) {
557
+ const rvx = (ss[baseA + SBS_LV_X] + ss[baseA + SBS_AV_Y] * rAz - ss[baseA + SBS_AV_Z] * rAy) - (to_world ? 0 : (ss[baseB + SBS_LV_X] + ss[baseB + SBS_AV_Y] * rBz - ss[baseB + SBS_AV_Z] * rBy));
558
+ const rvy = (ss[baseA + SBS_LV_Y] + ss[baseA + SBS_AV_Z] * rAx - ss[baseA + SBS_AV_X] * rAz) - (to_world ? 0 : (ss[baseB + SBS_LV_Y] + ss[baseB + SBS_AV_Z] * rBx - ss[baseB + SBS_AV_X] * rBz));
559
+ const rvz = (ss[baseA + SBS_LV_Z] + ss[baseA + SBS_AV_X] * rAy - ss[baseA + SBS_AV_Y] * rAx) - (to_world ? 0 : (ss[baseB + SBS_LV_Z] + ss[baseB + SBS_AV_X] * rBy - ss[baseB + SBS_AV_Y] * rBx));
560
+ vel = rvx * ax + rvy * ay + rvz * az;
561
+ }
562
+ fill_row(joint, k, k, keff, pos, vel, spook_locked, spook_spec, dt_sub,
563
+ lin_active, lin_eff, lin_bias, lin_clo, lin_chi, lin_gamma);
564
+ }
565
+ } else {
566
+ lin_active[0] = lin_active[1] = lin_active[2] = 0;
567
+ }
568
+
569
+ // --- Angular DOF row setup (frame axes). Position along axis k is the
570
+ // k-th component of the frame-local small-angle error vector `e`;
571
+ // convention is B−A (impulse +to B / −to A). ---
572
+ if (angConstrained) {
573
+ // Frame B world rotation (identity for a world anchor → locks A's
574
+ // frame to world axes).
575
+ let qBx = 0, qBy = 0, qBz = 0, qBw = 1;
576
+ if (!to_world) {
577
+ const lbb = joint.localBasisB;
578
+ quat3_multiply(scratch_q, 0, trB.rotation[0], trB.rotation[1], trB.rotation[2], trB.rotation[3], lbb[0], lbb[1], lbb[2], lbb[3]);
579
+ qBx = scratch_q[0]; qBy = scratch_q[1]; qBz = scratch_q[2]; qBw = scratch_q[3];
580
+ }
581
+ // qD = conj(qA) ⊗ qB → the per-axis angular position in frame-A
582
+ // coords. Two measures: the cheap small-angle rotation vector
583
+ // (default exact at the origin, fine for welds / hinges / modest
584
+ // limits) or, when the joint opts into `swingTwist`, the swing-twist
585
+ // decomposition (X = twist, Y/Z = swing) with *exact* angles, for
586
+ // wide cone-twist range-of-motion (ragdoll shoulders) where the
587
+ // small-angle measure under-reports.
588
+ quat3_multiply(scratch_q, 0, -qAx, -qAy, -qAz, qAw, qBx, qBy, qBz, qBw);
589
+ if (joint.swingTwist) {
590
+ swing_twist_error(scratch_q[0], scratch_q[1], scratch_q[2], scratch_q[3], scratch_ang_err);
591
+ } else {
592
+ const es = scratch_q[3] < 0 ? -2 : 2;
593
+ scratch_ang_err[0] = es * scratch_q[0];
594
+ scratch_ang_err[1] = es * scratch_q[1];
595
+ scratch_ang_err[2] = es * scratch_q[2];
596
+ }
597
+
598
+ for (let k = 0; k < 3; k++) {
599
+ ang_active[k] = 0;
600
+ const m = mode[3 + k];
601
+ if (m === DofMode.FREE) { imp[3 + k] = 0; continue; }
602
+ const ax = fa[3 * k], ay = fa[3 * k + 1], az = fa[3 * k + 2];
603
+ const keff = angular_axis_effective_mass(ss, baseA, ax, ay, az)
604
+ + (to_world ? 0 : angular_axis_effective_mass(ss, baseB, ax, ay, az));
605
+ const pos = scratch_ang_err[k];
606
+ // Relative angular velocity about the axis (B−A), for LIMITED
607
+ // bound selection.
608
+ let vel = 0;
609
+ if (m === DofMode.LIMITED) {
610
+ vel = -(ss[baseA + SBS_AV_X] * ax + ss[baseA + SBS_AV_Y] * ay + ss[baseA + SBS_AV_Z] * az);
611
+ if (!to_world) vel += ss[baseB + SBS_AV_X] * ax + ss[baseB + SBS_AV_Y] * ay + ss[baseB + SBS_AV_Z] * az;
612
+ }
613
+ fill_row(joint, 3 + k, k, keff, pos, vel, spook_locked, spook_spec, dt_sub,
614
+ ang_active, ang_eff, ang_bias, ang_clo, ang_chi, ang_gamma);
615
+ }
616
+ } else {
617
+ ang_active[0] = ang_active[1] = ang_active[2] = 0;
618
+ }
619
+
620
+ if (!lin_active[0] && !lin_active[1] && !lin_active[2]
621
+ && !ang_active[0] && !ang_active[1] && !ang_active[2]) continue;
622
+
623
+ // --- Per-substep warm-start (frame axes): linear impulse imp[k]·aₖ`
624
+ // applied at the anchors, angular impulse `Σ imp[3+k]·aₖ` about the
625
+ // frame axes (+to B / −to A). ---
626
+ {
627
+ let Px = 0, Py = 0, Pz = 0;
628
+ for (let k = 0; k < 3; k++) {
629
+ if (!lin_active[k]) continue;
630
+ const w = imp[k];
631
+ Px += w * fa[3 * k]; Py += w * fa[3 * k + 1]; Pz += w * fa[3 * k + 2];
632
+ }
633
+ if (Px !== 0 || Py !== 0 || Pz !== 0) {
634
+ apply_impulse(ss, baseA, invMA, rAx, rAy, rAz, Px, Py, Pz, +1);
635
+ if (!to_world) apply_impulse(ss, baseB, invMB, rBx, rBy, rBz, Px, Py, Pz, -1);
636
+ }
637
+ let Lx = 0, Ly = 0, Lz = 0;
638
+ for (let k = 0; k < 3; k++) {
639
+ if (!ang_active[k]) continue;
640
+ const w = imp[3 + k];
641
+ Lx += w * fa[3 * k]; Ly += w * fa[3 * k + 1]; Lz += w * fa[3 * k + 2];
642
+ }
643
+ if (Lx !== 0 || Ly !== 0 || Lz !== 0) {
644
+ if (!to_world) apply_angular_impulse(ss, baseB, Lx, Ly, Lz, 1, +1);
645
+ apply_angular_impulse(ss, baseA, Lx, Ly, Lz, 1, -1);
646
+ }
647
+ }
648
+
649
+ for (let it = 0; it < iters; it++) {
650
+ // Linear rows (frame axes). The relative anchor velocity is
651
+ // recomputed before each row so successive rows see the prior
652
+ // impulses (Gauss-Seidel coupling).
653
+ for (let k = 0; k < 3; k++) {
654
+ if (!lin_active[k]) continue;
655
+ const ax = fa[3 * k], ay = fa[3 * k + 1], az = fa[3 * k + 2];
656
+ const rvx = (ss[baseA + SBS_LV_X] + ss[baseA + SBS_AV_Y] * rAz - ss[baseA + SBS_AV_Z] * rAy) - (to_world ? 0 : (ss[baseB + SBS_LV_X] + ss[baseB + SBS_AV_Y] * rBz - ss[baseB + SBS_AV_Z] * rBy));
657
+ const rvy = (ss[baseA + SBS_LV_Y] + ss[baseA + SBS_AV_Z] * rAx - ss[baseA + SBS_AV_X] * rAz) - (to_world ? 0 : (ss[baseB + SBS_LV_Y] + ss[baseB + SBS_AV_Z] * rBx - ss[baseB + SBS_AV_X] * rBz));
658
+ const rvz = (ss[baseA + SBS_LV_Z] + ss[baseA + SBS_AV_X] * rAy - ss[baseA + SBS_AV_Y] * rAx) - (to_world ? 0 : (ss[baseB + SBS_LV_Z] + ss[baseB + SBS_AV_X] * rBy - ss[baseB + SBS_AV_Y] * rBx));
659
+ const vrel = rvx * ax + rvy * ay + rvz * az;
660
+ const old = imp[k];
661
+ // `+ γ·old` regularises a spring row (γ = 0 otherwise → exact).
662
+ let nv = old - lin_eff[k] * (vrel + lin_bias[k] + lin_gamma[k] * old);
663
+ if (nv < lin_clo[k]) nv = lin_clo[k]; else if (nv > lin_chi[k]) nv = lin_chi[k];
664
+ imp[k] = nv;
665
+ const d = nv - old;
666
+ if (d !== 0) {
667
+ apply_impulse(ss, baseA, invMA, rAx, rAy, rAz, d * ax, d * ay, d * az, +1);
668
+ if (!to_world) apply_impulse(ss, baseB, invMB, rBx, rBy, rBz, d * ax, d * ay, d * az, -1);
669
+ }
670
+ }
671
+
672
+ // Angular rows (frame axes): drive ωB−ωA about each axis toward the
673
+ // bias target, clamped per the row's bound.
674
+ for (let k = 0; k < 3; k++) {
675
+ if (!ang_active[k]) continue;
676
+ const ax = fa[3 * k], ay = fa[3 * k + 1], az = fa[3 * k + 2];
677
+ let wrel = -(ss[baseA + SBS_AV_X] * ax + ss[baseA + SBS_AV_Y] * ay + ss[baseA + SBS_AV_Z] * az);
678
+ if (!to_world) wrel += ss[baseB + SBS_AV_X] * ax + ss[baseB + SBS_AV_Y] * ay + ss[baseB + SBS_AV_Z] * az;
679
+ const old = imp[3 + k];
680
+ let nv = old - ang_eff[k] * (wrel + ang_bias[k] + ang_gamma[k] * old);
681
+ if (nv < ang_clo[k]) nv = ang_clo[k]; else if (nv > ang_chi[k]) nv = ang_chi[k];
682
+ imp[3 + k] = nv;
683
+ const d = nv - old;
684
+ if (d !== 0) {
685
+ if (!to_world) apply_angular_impulse(ss, baseB, ax, ay, az, d, +1);
686
+ apply_angular_impulse(ss, baseA, ax, ay, az, d, -1);
687
+ }
688
+ }
689
+ }
690
+ }
691
+ }