@driftengine/physics 4.8.2 → 4.8.4

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.
package/dist/exact.js ADDED
@@ -0,0 +1,331 @@
1
+ /**
2
+ * Transcendentals that give the same bits on every JavaScript engine.
3
+ *
4
+ * **Not more accurate than `Math`, and that is not what they are for.** These are within a couple
5
+ * of units in the last place of correctly rounded, which is about what a platform `sin` gives you.
6
+ * What they are is *reproducible*: ECMAScript declines to specify `sin`, `cos`, `exp`, `acos` and
7
+ * eighteen more, so two engines may differ by an ulp, and an ulp is enough to make two peers running
8
+ * the same simulation disagree — first invisibly, then completely.
9
+ *
10
+ * **In physics rather than core since 4.8.4**: a skinned cloth's damping needs `exp` and its bending
11
+ * `acos`, the simulation set may not call the platform's, and physics imports no other package. Core
12
+ * re-exports physics wholesale, so `exactExp` from `@driftengine/core` is the same function.
13
+ *
14
+ * `scripts/determinism.mjs` is the gate that refuses the unspecified ones inside the simulation set
15
+ * and names the twenty-two. Its header carries the other half of the argument: `+ - * /` are IEEE
16
+ * 754 operations by specification, JavaScript permits no fused-multiply-add contraction, and
17
+ * `Math.sqrt` is required correctly rounded and is *not* on that list. **So everything below uses
18
+ * only those five operations**, which is the whole design: reproducibility by construction rather
19
+ * than by hoping two engines chose the same algorithm.
20
+ *
21
+ * ---
22
+ *
23
+ * ## What is here, and what is deliberately not
24
+ *
25
+ * `exactSin`, `exactCos`, `exactExp`, `exactAcos` and `exactLog`. Five, because five is what the
26
+ * engine and its first consumer actually reach for: the terrain binding's slope angle needs `acos`,
27
+ * a lockstep fixture rotating anything needs `sin` and `cos`, exponential decay needs `exp`, and a
28
+ * detector's box prior is a logit of the patch grid, which needs `log`.
29
+ *
30
+ * **`atan2` is absent.** It is the obvious fifth and nothing here needs one: `shape.ts` sorts by a
31
+ * comparison key computed from two in-plane axes rather than by an angle, and `joints.ts` compares
32
+ * a quaternion component against a half-angle's sine. *Reversed by* a site that genuinely needs a
33
+ * signed angle from two components, at which point it arrives with its own golden vectors.
34
+ *
35
+ * ## Nothing in core imports these
36
+ *
37
+ * Deliberately. `core-only` is the one size figure in this repository that every consumer pays, and
38
+ * a module reachable from `createRenderer` is in it whether anybody calls it or not. These are
39
+ * reached by the script bindings and by consumers who ask for them, so tree-shaking keeps them out
40
+ * of a bundle that does not, which is measured rather than assumed.
41
+ *
42
+ * ## The coefficients
43
+ *
44
+ * The polynomial and rational coefficients are fdlibm's, which is the ancestor of most platform
45
+ * libms and is public domain. They are written as literals: **a literal is the same number on
46
+ * every engine, which is the only property being bought.** Their provenance matters less than their
47
+ * fixity — a coefficient somebody re-derived to one more digit is a different function, and
48
+ * `exact.test.ts`'s golden bit patterns are what would catch that.
49
+ */
50
+ /*
51
+ * π/2 in four pieces, most significant first, so a large multiple of it can be removed without
52
+ * losing the small remainder in the subtraction.
53
+ *
54
+ * **Two pieces are not enough and the measurement says so**: at an angle of 740 radians a two-part
55
+ * reduction leaves `sin` and `cos` 18.5 ulps out, because `k * PIO2_1` needs more than 53 bits once
56
+ * `k` grows. Three brings it under two ulps for the cost of two multiplies.
57
+ *
58
+ * **`PIO2_TAIL` and `PIO2_TAIL_LO` are one number in two halves, not two successive corrections.**
59
+ * fdlibm carries a fourth constant, `pio2_1t`, which is the tail for its *single*-iteration path;
60
+ * `pio2_2` is the same tail rounded differently, with `pio2_2t` as its own tail, and the two paths
61
+ * are alternatives. Refining the first with the second is not more accurate, it is wrong: it
62
+ * subtracts the tail twice and took `sin` to 2.2e11 ulps out, which is how this comment came to be
63
+ * here.
64
+ */
65
+ const PIO2_1 = 1.5707963267341256;
66
+ const PIO2_TAIL = 6.077100506303966e-11;
67
+ const PIO2_TAIL_LO = 2.0222662487959506e-21;
68
+ const TWO_OVER_PI = 0.6366197723675814;
69
+ const HALF_PI = 1.5707963267948966;
70
+ const PI = 3.141592653589793;
71
+ /* fdlibm's `__kernel_sin` coefficients. */
72
+ const S1 = -1.6666666666666632e-1;
73
+ const S2 = 8.33333333332249e-3;
74
+ const S3 = -1.984126982985795e-4;
75
+ const S4 = 2.7557313707070068e-6;
76
+ const S5 = -2.5050760253406863e-8;
77
+ const S6 = 1.5896909952115501e-10;
78
+ /* fdlibm's `__kernel_cos` coefficients. */
79
+ const C1 = 4.1666666666666602e-2;
80
+ const C2 = -1.388888888887411e-3;
81
+ const C3 = 2.480158728947673e-5;
82
+ const C4 = -2.7557314351390663e-7;
83
+ const C5 = 2.0875723212981748e-9;
84
+ const C6 = -1.1359647557788195e-11;
85
+ /* fdlibm's `asin` rational, numerator then denominator. */
86
+ const P0 = 1.6666666666666666e-1;
87
+ const P1 = -3.2556581862240092e-1;
88
+ const P2 = 2.0121253213486293e-1;
89
+ const P3 = -4.0055534500679411e-2;
90
+ const P4 = 7.9153499428981453e-4;
91
+ const P5 = 3.4793310759602117e-5;
92
+ const Q1 = -2.4033949117344142;
93
+ const Q2 = 2.0209457602335057;
94
+ const Q3 = -6.8828397160545329e-1;
95
+ const Q4 = 7.7038150555901935e-2;
96
+ /** ln 2, split for the same reason π/2 is. */
97
+ const LN2_HI = 0.6931471803691238;
98
+ const LN2_LO = 1.9082149292705877e-10;
99
+ const ONE_OVER_LN2 = 1.4426950408889634;
100
+ /** 2^(2^i), for i = 0 to 9. Every one is exact, so a product of them is exact. */
101
+ const POW2 = [
102
+ 2, 4, 16, 256, 65536, 4294967296, 1.8446744073709552e19, 3.402823669209385e38,
103
+ 1.157920892373162e77, 1.3407807929942597e154,
104
+ ];
105
+ /**
106
+ * Two to an integer power, by binary decomposition of the exponent.
107
+ *
108
+ * Multiplication by a power of two is exact in IEEE 754, so this is exact wherever it does not
109
+ * overflow — which is what makes it a legitimate substitute for the `Math.pow` a range reduction
110
+ * would otherwise reach for.
111
+ *
112
+ * A large negative exponent lands on zero instead of a subnormal, because the reciprocal is taken
113
+ * after the product overflows. That is `exp` underflowing to zero, which is where it was going.
114
+ */
115
+ function pow2(exponent) {
116
+ let remaining = exponent < 0 ? -exponent : exponent;
117
+ let result = 1;
118
+ let index = 0;
119
+ while (remaining > 0 && index < POW2.length) {
120
+ if ((remaining & 1) === 1)
121
+ result *= POW2[index];
122
+ remaining >>= 1;
123
+ index += 1;
124
+ }
125
+ return exponent < 0 ? 1 / result : result;
126
+ }
127
+ /** sin on [-π/4, π/4]. */
128
+ function sinKernel(x) {
129
+ const z = x * x;
130
+ const poly = S1 + z * (S2 + z * (S3 + z * (S4 + z * (S5 + z * S6))));
131
+ return x + x * z * poly;
132
+ }
133
+ /** cos on [-π/4, π/4]. */
134
+ function cosKernel(x) {
135
+ const z = x * x;
136
+ const poly = C1 + z * (C2 + z * (C3 + z * (C4 + z * (C5 + z * C6))));
137
+ return 1 - 0.5 * z + z * z * poly;
138
+ }
139
+ /**
140
+ * Fold an angle into [-π/4, π/4] and say which quadrant it came from.
141
+ *
142
+ * Cody-Waite: the multiple of π/2 is removed in pieces, so the subtraction that produces a small
143
+ * remainder from two large numbers does not lose the bits it is supposed to keep. One-piece
144
+ * reduction is accurate to about 1e-8 at an angle of a thousand radians, which for a simulation
145
+ * that accumulates rotation is the difference between an object facing forward and facing sideways
146
+ * after a few minutes.
147
+ */
148
+ function reduce(x) {
149
+ const k = Math.round(x * TWO_OVER_PI);
150
+ /* The leading piece, whose product with `k` is exact for every `k` a simulation reaches. */
151
+ const head = x - k * PIO2_1;
152
+ /*
153
+ * The tail, in two halves. `head - tail` loses the bits below its own last place, and
154
+ * `PIO2_TAIL_LO - (head - r - tail)` is exactly those bits recovered — the same
155
+ * subtract-and-recover fdlibm uses on its two-iteration path.
156
+ */
157
+ const tail = k * PIO2_TAIL;
158
+ let r = head - tail;
159
+ const lost = k * PIO2_TAIL_LO - (head - r - tail);
160
+ r = r - lost;
161
+ return { r, quadrant: ((k % 4) + 4) % 4 };
162
+ }
163
+ /** `Math.sin`, reproducibly. NaN in, NaN out; an infinity answers NaN, as `Math.sin` does. */
164
+ export function exactSin(x) {
165
+ if (!Number.isFinite(x))
166
+ return Number.NaN;
167
+ const { r, quadrant } = reduce(x);
168
+ switch (quadrant) {
169
+ case 0:
170
+ return sinKernel(r);
171
+ case 1:
172
+ return cosKernel(r);
173
+ case 2:
174
+ return -sinKernel(r);
175
+ default:
176
+ return -cosKernel(r);
177
+ }
178
+ }
179
+ /** `Math.cos`, reproducibly. */
180
+ export function exactCos(x) {
181
+ if (!Number.isFinite(x))
182
+ return Number.NaN;
183
+ const { r, quadrant } = reduce(x);
184
+ switch (quadrant) {
185
+ case 0:
186
+ return cosKernel(r);
187
+ case 1:
188
+ return -sinKernel(r);
189
+ case 2:
190
+ return -cosKernel(r);
191
+ default:
192
+ return sinKernel(r);
193
+ }
194
+ }
195
+ /**
196
+ * `Math.exp`, reproducibly.
197
+ *
198
+ * Reduce by a multiple of ln 2 into [-ln2/2, ln2/2], sum the Taylor series there, and scale by a
199
+ * power of two. **A degree-14 series and not a shorter minimax**, because on that interval the
200
+ * fifteenth term is about 4e-20 — below the precision of a double — so the series is exact to the
201
+ * representation and there is nothing a fitted polynomial would buy.
202
+ */
203
+ export function exactExp(x) {
204
+ if (Number.isNaN(x))
205
+ return Number.NaN;
206
+ if (x === Number.POSITIVE_INFINITY)
207
+ return Number.POSITIVE_INFINITY;
208
+ if (x === Number.NEGATIVE_INFINITY)
209
+ return 0;
210
+ if (x > 709.782712893384)
211
+ return Number.POSITIVE_INFINITY;
212
+ if (x < -745.1332191019411)
213
+ return 0;
214
+ const k = Math.round(x * ONE_OVER_LN2);
215
+ const r = x - k * LN2_HI - k * LN2_LO;
216
+ /* Horner over 1/n!, highest term first. */
217
+ let sum = 1 / 87178291200; // 1/14!
218
+ sum = 1 / 6227020800 + r * sum; // 1/13!
219
+ sum = 1 / 479001600 + r * sum; // 1/12!
220
+ sum = 1 / 39916800 + r * sum; // 1/11!
221
+ sum = 1 / 3628800 + r * sum; // 1/10!
222
+ sum = 1 / 362880 + r * sum; // 1/9!
223
+ sum = 1 / 40320 + r * sum; // 1/8!
224
+ sum = 1 / 5040 + r * sum; // 1/7!
225
+ sum = 1 / 720 + r * sum; // 1/6!
226
+ sum = 1 / 120 + r * sum; // 1/5!
227
+ sum = 1 / 24 + r * sum; // 1/4!
228
+ sum = 1 / 6 + r * sum; // 1/3!
229
+ sum = 0.5 + r * sum;
230
+ sum = 1 + r * sum;
231
+ sum = 1 + r * sum;
232
+ return sum * pow2(k);
233
+ }
234
+ /* fdlibm's `log` polynomial in s², for log(1 + f) around f = 0 by way of s = f / (2 + f). */
235
+ const LG1 = 6.66666666666673513e-1;
236
+ const LG2 = 3.999999999940941908e-1;
237
+ const LG3 = 2.857142874366239149e-1;
238
+ const LG4 = 2.222219843214978396e-1;
239
+ const LG5 = 1.818357216161805012e-1;
240
+ const LG6 = 1.531383769920937332e-1;
241
+ const LG7 = 1.479819860511658591e-1;
242
+ const TWO54 = 1.8014398509481984e16;
243
+ const SMALLEST_NORMAL = 2.2250738585072014e-308;
244
+ /* A double's two words, for reading and setting an exponent; one view, reused. */
245
+ const words = new DataView(new ArrayBuffer(8));
246
+ /**
247
+ * `Math.log`, reproducibly: fdlibm's algorithm, which is also V8's.
248
+ *
249
+ * Take the power of two out as `k` and leave a significand in [√2/2, √2), so that `f = m - 1` is
250
+ * small either side of zero; then log(1 + f) = f - f²/2 + s·(f²/2 + R(s²)) with s = f/(2 + f), and
251
+ * `k·ln 2` added back in two parts so the large part loses nothing. The exponent is read and the
252
+ * significand rescaled through the double's own words — integer operations, not transcendentals.
253
+ */
254
+ export function exactLog(x) {
255
+ if (Number.isNaN(x) || x < 0)
256
+ return Number.NaN;
257
+ if (x === 0)
258
+ return Number.NEGATIVE_INFINITY;
259
+ if (x === Number.POSITIVE_INFINITY)
260
+ return x;
261
+ let k = 0;
262
+ let value = x;
263
+ if (value < SMALLEST_NORMAL) {
264
+ k = -54;
265
+ value *= TWO54;
266
+ }
267
+ words.setFloat64(0, value);
268
+ let hx = words.getUint32(0);
269
+ k += (hx >>> 20) - 1023;
270
+ hx &= 0x000fffff;
271
+ /* Keep the significand at or above √2/2: past √2, halve it and count one more power of two. */
272
+ const i = (hx + 0x95f64) & 0x100000;
273
+ words.setUint32(0, hx | (i ^ 0x3ff00000));
274
+ k += i >>> 20;
275
+ const f = words.getFloat64(0) - 1;
276
+ if ((0x000fffff & (2 + hx)) < 3) {
277
+ /* |f| < 2^-20: two terms of the series are the whole answer. */
278
+ if (f === 0)
279
+ return k === 0 ? 0 : k * LN2_HI + k * LN2_LO;
280
+ const r = f * f * (0.5 - 0.3333333333333333 * f);
281
+ return k === 0 ? f - r : k * LN2_HI - (r - k * LN2_LO - f);
282
+ }
283
+ const s = f / (2 + f);
284
+ const z = s * s;
285
+ const w = z * z;
286
+ const t1 = w * (LG2 + w * (LG4 + w * LG6));
287
+ const t2 = z * (LG1 + w * (LG3 + w * (LG5 + w * LG7)));
288
+ const r = t2 + t1;
289
+ /* Far enough from one that f²/2 is worth carrying apart from f. */
290
+ if (((hx - 0x6147a) | (0x6b851 - hx)) > 0) {
291
+ const half = 0.5 * f * f;
292
+ return k === 0
293
+ ? f - (half - s * (half + r))
294
+ : k * LN2_HI - (half - (s * (half + r) + k * LN2_LO) - f);
295
+ }
296
+ return k === 0 ? f - s * (f - r) : k * LN2_HI - (s * (f - r) - k * LN2_LO - f);
297
+ }
298
+ /** fdlibm's `asin` rational on `z = x²`, valid where `z` is small. */
299
+ function asinRational(z) {
300
+ const numerator = z * (P0 + z * (P1 + z * (P2 + z * (P3 + z * (P4 + z * P5)))));
301
+ const denominator = 1 + z * (Q1 + z * (Q2 + z * (Q3 + z * Q4)));
302
+ return numerator / denominator;
303
+ }
304
+ /**
305
+ * `Math.acos`, reproducibly. Outside [-1, 1] this answers NaN, as `Math.acos` does.
306
+ *
307
+ * Three branches rather than one, and the split at ±0.5 is the reason it is accurate near the ends:
308
+ * `acos` has infinite derivative at ±1, so a polynomial in `x` loses its footing there. Substituting
309
+ * `s = sqrt((1 ∓ x)/2)` moves the awkward point to zero, where a polynomial is comfortable — which
310
+ * is also why `sqrt` being exactly rounded matters here rather than being a convenience.
311
+ */
312
+ export function exactAcos(x) {
313
+ if (Number.isNaN(x) || x > 1 || x < -1)
314
+ return Number.NaN;
315
+ if (x === 1)
316
+ return 0;
317
+ if (x === -1)
318
+ return PI;
319
+ if (x >= 0.5) {
320
+ const z = (1 - x) / 2;
321
+ const s = Math.sqrt(z);
322
+ return 2 * (s + s * asinRational(z));
323
+ }
324
+ if (x <= -0.5) {
325
+ const z = (1 + x) / 2;
326
+ const s = Math.sqrt(z);
327
+ return PI - 2 * (s + s * asinRational(z));
328
+ }
329
+ const z = x * x;
330
+ return HALF_PI - (x + x * asinRational(z));
331
+ }
package/dist/index.d.ts CHANGED
@@ -58,6 +58,15 @@ export type { EscapeResult, EscapeVeto, StallEscapeOptions, StallInput } from '.
58
58
  export { ESCAPE_EASED, ESCAPE_IDLE, ESCAPE_PUSHED, ESCAPE_SEALED, StallEscape, } from './stallEscape.ts';
59
59
  export type { ClothOptions } from './cloth.ts';
60
60
  export { ClothBody, makeClothGrid } from './cloth.ts';
61
+ export { SkinnedCloth } from './skinnedCloth.ts';
62
+ export { ClothControl } from './clothControl.ts';
63
+ export type { ClothDevice } from './clothControl.ts';
64
+ export type { ClothTargets } from './clothTargets.ts';
65
+ export { validateClothSetup } from './skinnedClothSetup.ts';
66
+ export { exactAcos, exactCos, exactExp, exactLog, exactSin } from './exact.ts';
67
+ export { batchesOf, colourConstraints } from './clothBatches.ts';
68
+ export type { ClothBatches } from './clothBatches.ts';
69
+ export type { BendingConstraints, ClothCollider, ClothLimits, DistanceConstraints, ResolvedClothParameters, SkinnedClothParameters, SkinnedClothSetup, TetherConstraints, } from './skinnedClothSetup.ts';
61
70
  export type { Collider, ColliderBytes, ColliderGroup } from './colliderSet.ts';
62
71
  export { ColliderSet, boxCollider, colliderFromShape } from './colliderSet.ts';
63
72
  export { fingerprintBodies, fingerprintColliders } from './fingerprint.ts';
package/dist/index.js CHANGED
@@ -23,6 +23,25 @@ export { accelerateAlong } from './groundMotor.js';
23
23
  export { applyBuoyancy, createBuoyancy } from './buoyancy.js';
24
24
  export { ESCAPE_EASED, ESCAPE_IDLE, ESCAPE_PUSHED, ESCAPE_SEALED, StallEscape, } from './stallEscape.js';
25
25
  export { ClothBody, makeClothGrid } from './cloth.js';
26
+ /*
27
+ * Cloth anchored to a skeleton rather than a world: a garment. The CPU solver is the reference and
28
+ * runs under WebGL2 and in Node; `@driftengine/core` runs the same kernels on WebGPU.
29
+ */
30
+ export { SkinnedCloth } from './skinnedCloth.js';
31
+ /*
32
+ * The schedule both solvers share — poses, whole steps, resets and the blend — and the device
33
+ * interface the GPU solver implements, with what it reads: the targets' matrices and colliders,
34
+ * and the set-up checked and batched exactly as the CPU solver checks and batches it.
35
+ */
36
+ export { ClothControl } from './clothControl.js';
37
+ export { validateClothSetup } from './skinnedClothSetup.js';
38
+ /*
39
+ * Transcendentals that give the same bits on every engine. Here rather than in core since 4.8.4,
40
+ * because the simulation needs them and this package imports nothing; core re-exports them with
41
+ * the rest of physics.
42
+ */
43
+ export { exactAcos, exactCos, exactExp, exactLog, exactSin } from './exact.js';
44
+ export { batchesOf, colourConstraints } from './clothBatches.js';
26
45
  export { ColliderSet, boxCollider, colliderFromShape } from './colliderSet.js';
27
46
  export { fingerprintBodies, fingerprintColliders } from './fingerprint.js';
28
47
  export { combineMassProperties, createMassProperties, shapeMassProperties } from './mass.js';
package/dist/ragdoll.js CHANGED
@@ -82,6 +82,11 @@ export function ragdollFromBones(world, parents, worldMatrices, options = {}) {
82
82
  * the bones meet.
83
83
  */
84
84
  const halfOf = new Float32Array(jointCount);
85
+ /**
86
+ * Each bone's rig offset over its length: 1 for a rig at unit scale, and what turns a length in
87
+ * metres back into the parent's own units where the rig is scaled.
88
+ */
89
+ const restScale = new Float32Array(jointCount).fill(1);
85
90
  let boneCount = 0;
86
91
  let firstBone = -1;
87
92
  /** Half the first bone's length, which is how far its head sits from the body's centre. */
@@ -123,6 +128,10 @@ export function ragdollFromBones(world, parents, worldMatrices, options = {}) {
123
128
  });
124
129
  bodyOf[j] = body;
125
130
  halfOf[j] = length / 2;
131
+ const rx = localRest[j * 3] ?? 0;
132
+ const ry = localRest[j * 3 + 1] ?? 0;
133
+ const rz = localRest[j * 3 + 2] ?? 0;
134
+ restScale[j] = Math.sqrt(rx * rx + ry * ry + rz * rz) / length;
126
135
  // What takes the body's rotation back to each of its two joints', captured at rest. Parents
127
136
  // come before children in a rig, so the start joint's rotation is already read.
128
137
  multiplyConjugate(TMP, restRotation, j * 4, bodyToJoint, j * 4);
@@ -139,15 +148,67 @@ export function ragdollFromBones(world, parents, worldMatrices, options = {}) {
139
148
  firstBoneHalf = length / 2;
140
149
  }
141
150
  }
151
+ /*
152
+ * **A bone too short for a body is transparent.** Each joint resolves to the nearest one at or
153
+ * above it that a body ends at, or to its root: what hangs from a collar sitting on the chest
154
+ * joint hangs from the bone that ends at the chest. A rig puts one joint exactly on another as
155
+ * often as not, and a bone under `minLength` gets no body, so until 4.8.3 the spine above such a
156
+ * collar was jointed to nothing and collided with every bone it met there — compared by index,
157
+ * they shared no end. **What it gives up** is the skipped bone's own length, under `minLength`,
158
+ * which the joints below absorb exactly at rest: see `restAnchor`.
159
+ */
160
+ const attach = new Int32Array(jointCount);
161
+ for (let j = 0; j < jointCount; j++) {
162
+ let a = j;
163
+ while ((bodyOf[a] ?? -1) < 0 && (parents[a] ?? -1) >= 0)
164
+ a = parents[a] ?? -1;
165
+ attach[j] = a;
166
+ }
167
+ /** Where a bone's parent end really hangs: its parent joint, seen through any bone too short. */
168
+ const hangsFrom = (j) => {
169
+ const p = parents[j] ?? -1;
170
+ return p < 0 ? -1 : (attach[p] ?? p);
171
+ };
172
+ /**
173
+ * Bone `j`'s body-frame point at joint `at`'s rest position, into `REST_ANCHOR`. Where `at` is
174
+ * the bone's own parent joint this is its head, `(0, -half, 0)`, exactly as before; through a
175
+ * short bone it is where the two bones meet at rest, so a joint anchored there moves nothing on
176
+ * the first tick.
177
+ */
178
+ const restAnchor = (j, at) => {
179
+ const p = parents[j] ?? -1;
180
+ if (at === p) {
181
+ REST_ANCHOR[0] = 0;
182
+ REST_ANCHOR[1] = -(halfOf[j] ?? 0);
183
+ REST_ANCHOR[2] = 0;
184
+ return;
185
+ }
186
+ const body = bodyOf[j] ?? 0;
187
+ const dx = (worldMatrices[at * 16 + 12] ?? 0) - (world.bodies.posX[body] ?? 0);
188
+ const dy = (worldMatrices[at * 16 + 13] ?? 0) - (world.bodies.posY[body] ?? 0);
189
+ const dz = (worldMatrices[at * 16 + 14] ?? 0) - (world.bodies.posZ[body] ?? 0);
190
+ /* Into the body's frame: turned by the conjugate of its rotation. */
191
+ const ux = -(world.bodies.rotX[body] ?? 0);
192
+ const uy = -(world.bodies.rotY[body] ?? 0);
193
+ const uz = -(world.bodies.rotZ[body] ?? 0);
194
+ const w = world.bodies.rotW[body] ?? 1;
195
+ const cx = uy * dz - uz * dy;
196
+ const cy = uz * dx - ux * dz;
197
+ const cz = ux * dy - uy * dx;
198
+ REST_ANCHOR[0] = dx + 2 * (w * cx + (uy * cz - uz * cy));
199
+ REST_ANCHOR[1] = dy + 2 * (w * cy + (uz * cx - ux * cz));
200
+ REST_ANCHOR[2] = dz + 2 * (w * cz + (ux * cy - uy * cx));
201
+ };
142
202
  // Joint each bone to its parent's bone, at the shared end.
143
203
  for (let j = 0; j < jointCount; j++) {
144
204
  const body = bodyOf[j] ?? -1;
145
205
  if (body < 0)
146
206
  continue;
147
- const p = parents[j] ?? -1;
207
+ const p = hangsFrom(j);
148
208
  const parentBody = p >= 0 ? (bodyOf[p] ?? -1) : -1;
149
209
  if (parentBody < 0)
150
210
  continue;
211
+ restAnchor(j, p);
151
212
  world.addJoint({
152
213
  type: JOINT_CONE_TWIST,
153
214
  bodyA: parentBody,
@@ -174,7 +235,9 @@ export function ragdollFromBones(world, parents, worldMatrices, options = {}) {
174
235
  * so the first tick still moves nothing.
175
236
  */
176
237
  anchorAY: halfOf[p] ?? 0,
177
- anchorBY: -(halfOf[j] ?? 0),
238
+ anchorBX: REST_ANCHOR[0],
239
+ anchorBY: REST_ANCHOR[1],
240
+ anchorBZ: REST_ANCHOR[2],
178
241
  });
179
242
  }
180
243
  /*
@@ -191,7 +254,7 @@ export function ragdollFromBones(world, parents, worldMatrices, options = {}) {
191
254
  const body = bodyOf[j] ?? -1;
192
255
  if (body < 0)
193
256
  continue;
194
- const p = parents[j] ?? -1;
257
+ const p = hangsFrom(j);
195
258
  if (p < 0 || (bodyOf[p] ?? -1) >= 0)
196
259
  continue;
197
260
  const first = firstUnder[p] ?? -1;
@@ -199,6 +262,11 @@ export function ragdollFromBones(world, parents, worldMatrices, options = {}) {
199
262
  firstUnder[p] = j;
200
263
  continue;
201
264
  }
265
+ restAnchor(first, p);
266
+ const ax = REST_ANCHOR[0];
267
+ const ay = REST_ANCHOR[1];
268
+ const az = REST_ANCHOR[2];
269
+ restAnchor(j, p);
202
270
  world.addJoint({
203
271
  type: JOINT_CONE_TWIST,
204
272
  bodyA: bodyOf[first] ?? 0,
@@ -206,8 +274,12 @@ export function ragdollFromBones(world, parents, worldMatrices, options = {}) {
206
274
  swingCos: limitAt(swingCos, Math.SQRT1_2, j),
207
275
  twistSin: limitAt(twistSin, 0.3826834323650898, j),
208
276
  axisY: 1,
209
- anchorAY: -(halfOf[first] ?? 0),
210
- anchorBY: -(halfOf[j] ?? 0),
277
+ anchorAX: ax,
278
+ anchorAY: ay,
279
+ anchorAZ: az,
280
+ anchorBX: REST_ANCHOR[0],
281
+ anchorBY: REST_ANCHOR[1],
282
+ anchorBZ: REST_ANCHOR[2],
211
283
  });
212
284
  }
213
285
  /*
@@ -230,8 +302,9 @@ export function ragdollFromBones(world, parents, worldMatrices, options = {}) {
230
302
  world.ignorePair(body, other);
231
303
  continue;
232
304
  }
233
- const pj = parents[j] ?? -1;
234
- const pk = parents[k] ?? -1;
305
+ /* Seen through any bone too short for a body, which is where they really meet. */
306
+ const pj = hangsFrom(j);
307
+ const pk = hangsFrom(k);
235
308
  /* Jointed, either way round, or two bones hanging off the same parent joint: siblings share
236
309
  a head the way a parent and child share a point, so they overlap there too. */
237
310
  if (pk === j || pj === k || (pj === pk && pj >= 0))
@@ -284,10 +357,25 @@ export function ragdollFromBones(world, parents, worldMatrices, options = {}) {
284
357
  }
285
358
  if (p < 0)
286
359
  continue;
287
- // Bones are rigid, so translation stays what the rig was built with.
288
- out.translation[j * 3] = localRest[j * 3] ?? 0;
289
- out.translation[j * 3 + 1] = localRest[j * 3 + 1] ?? 0;
290
- out.translation[j * 3 + 2] = localRest[j * 3 + 2] ?? 0;
360
+ /*
361
+ * **Placed along its own bone as the body holds it**, at the rig's length: the body's +y,
362
+ * in the parent's frame. For the first bone under a joint that is the rig's offset exactly,
363
+ * because the joint turns with that body; for a second or third — a thigh beside the spine,
364
+ * a clavicle beside the neck — it is what keeps the branch on its own body. Placed by the
365
+ * rig's offset, every branch but the first was swung by the first one's turn: reported as
366
+ * a foot 0.24 m and an arm 0.17 m from their bodies after a fall. A joint with no bone of
367
+ * its own keeps the rig's offset. **What would make it wrong** is a bone the body
368
+ * stretches, which a rigid capsule cannot.
369
+ */
370
+ const body = bodyOf[j] ?? -1;
371
+ if (body >= 0 && KNOWN[p] === 1) {
372
+ boneInParentFrame(world, body, 2 * (halfOf[j] ?? 0) * (restScale[j] ?? 1), WORLD_ROT, p * 4, out.translation, j * 3);
373
+ }
374
+ else {
375
+ out.translation[j * 3] = localRest[j * 3] ?? 0;
376
+ out.translation[j * 3 + 1] = localRest[j * 3 + 1] ?? 0;
377
+ out.translation[j * 3 + 2] = localRest[j * 3 + 2] ?? 0;
378
+ }
291
379
  out.scale[j * 3] = 1;
292
380
  out.scale[j * 3 + 1] = 1;
293
381
  out.scale[j * 3 + 2] = 1;
@@ -402,6 +490,8 @@ const WORLD_ROT = new Float32Array(256 * 4);
402
490
  /** Whether `writePose` recovered each joint's rotation this call: 1 if a body speaks for it. */
403
491
  const KNOWN = new Uint8Array(256);
404
492
  const START_ROT = new Float32Array(4);
493
+ /** One joint anchor in a body's own frame, filled by `restAnchor` and read at once. */
494
+ const REST_ANCHOR = new Float64Array(3);
405
495
  const PARENT_ROT = new Float32Array(4);
406
496
  const TARGET_ROT = new Float32Array(4);
407
497
  const CURRENT_ROT = new Float32Array(4);
@@ -560,6 +650,31 @@ function multiplyByConjugate(a, b, bAt, out) {
560
650
  out[2] = aw * bz + ax * by - ay * bx + az * bw;
561
651
  out[3] = aw * bw - ax * bx - ay * by - az * bz;
562
652
  }
653
+ /**
654
+ * A body's own +y at `length`, turned by the body and then back by the inverse of a parent's world
655
+ * rotation: the bone as the body holds it, in the parent's frame.
656
+ */
657
+ function boneInParentFrame(world, body, length, parent, parentAt, out, outAt) {
658
+ const bx = world.bodies.rotX[body] ?? 0;
659
+ const by = world.bodies.rotY[body] ?? 0;
660
+ const bz = world.bodies.rotZ[body] ?? 0;
661
+ const bw = world.bodies.rotW[body] ?? 1;
662
+ /* The body's +y in the world, scaled. */
663
+ const vx = 2 * length * (bx * by - bw * bz);
664
+ const vy = length * (1 - 2 * (bx * bx + bz * bz));
665
+ const vz = 2 * length * (by * bz + bw * bx);
666
+ /* Turned by the conjugate of the parent's rotation: v + 2w(u×v) + 2u×(u×v), u = −q.xyz. */
667
+ const ux = -(parent[parentAt] ?? 0);
668
+ const uy = -(parent[parentAt + 1] ?? 0);
669
+ const uz = -(parent[parentAt + 2] ?? 0);
670
+ const w = parent[parentAt + 3] ?? 1;
671
+ const cx = uy * vz - uz * vy;
672
+ const cy = uz * vx - ux * vz;
673
+ const cz = ux * vy - uy * vx;
674
+ out[outAt] = vx + 2 * (w * cx + (uy * cz - uz * cy));
675
+ out[outAt + 1] = vy + 2 * (w * cy + (uz * cx - ux * cz));
676
+ out[outAt + 2] = vz + 2 * (w * cz + (ux * cy - uy * cx));
677
+ }
563
678
  /** `conj(a) · b` into `out`. */
564
679
  function multiplyConjugate(a, b, bAt, out, at) {
565
680
  const ax = -a[0];
@@ -0,0 +1,63 @@
1
+ import type { ResolvedClothParameters, SkinnedClothSetup } from './skinnedClothSetup.ts';
2
+ /**
3
+ * A garment's particles, constraints and solver state, stepped at the set-up's fixed step. Read
4
+ * `positions` after a step, or `interpolate` between the last two for a frame's `alpha`. The
5
+ * schedule — poses, steps, resets, the blend — is `ClothControl`'s; this is its CPU device.
6
+ */
7
+ export declare class SkinnedCloth {
8
+ /** How many particles. */
9
+ readonly count: number;
10
+ /** Where each particle is now, three floats a particle. */
11
+ readonly positions: Float32Array;
12
+ /** Metres a second, three floats a particle. */
13
+ readonly velocities: Float32Array;
14
+ readonly inverseMass: Float32Array;
15
+ /** The parameters with their defaults filled in. */
16
+ readonly parameters: ResolvedClothParameters;
17
+ /** Where each particle was when the last step began, for drawing on `alpha`. */
18
+ private readonly stepStart;
19
+ /** Where each particle was when the current substep began, for its velocity. */
20
+ private readonly substepStart;
21
+ private readonly distance;
22
+ private readonly bending;
23
+ private readonly tethers;
24
+ private readonly control;
25
+ private readonly targets;
26
+ private readonly limits;
27
+ private readonly colliders;
28
+ /** The air the cloth drags toward, metres a second: the set-up's until `setWind` says otherwise. */
29
+ private readonly wind;
30
+ constructor(setup: SkinnedClothSetup);
31
+ /**
32
+ * The air the steps to come drag the cloth toward, world space, metres a second: the frame's
33
+ * sample of the scene's one wind, so a garment moves with the smoke and the grass rather than
34
+ * with a second wind of its own. See `AGENTS.md`, "One wind, sampled once".
35
+ */
36
+ setWind(x: number, y: number, z: number): void;
37
+ /** See `ClothControl.setPose`. */
38
+ setPose(globals: Float32Array, model: Float32Array): void;
39
+ /** See `ClothControl.reset`. */
40
+ reset(): void;
41
+ /** See `ClothControl.advance`. */
42
+ advance(dt: number): number;
43
+ /** How far the time handed to `advance` reaches into the next step, 0 to 1. */
44
+ get alpha(): number;
45
+ /** Each particle between the start and the end of the last step, at `alpha`, into `out`. */
46
+ interpolate(alpha: number, out: Float32Array): void;
47
+ /** One fixed step, all the way to the latest pose: for a caller in the engine's fixed-step loop. */
48
+ step(): void;
49
+ /** Every particle at its latest skinned position, at rest. */
50
+ private rest;
51
+ /**
52
+ * One fixed step, `fraction` of the way from the last pose to the latest: carried by the share of
53
+ * the character's motion it does not keep, its kinematic particles placed, then its substeps —
54
+ * each predicted, constrained, limited and turned into velocities.
55
+ */
56
+ private stepAt;
57
+ /** The limits and the colliders, after the constraints, so a garment pulling into the body loses. */
58
+ private limit;
59
+ /** After a reset, the share of the simulation drawn grows from nothing to all over the blend. */
60
+ private blend;
61
+ /** Every batch of one kind, in colour order. */
62
+ private solve;
63
+ }