@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,665 +1,750 @@
1
- import { line3_closest_points_segment_segment } from "../../../core/geom/3d/line/line3_closest_points_segment_segment.js";
2
- import { quat3_to_matrix3 } from "../../../core/geom/3d/quaternion/quat3_to_matrix3.js";
3
-
4
- /**
5
- * Multi-point manifold construction for two oriented bounding boxes.
6
- *
7
- * Algorithm:
8
- * 1. SAT over the canonical 15 axes (3 face normals of A, 3 of B, 9 edge-pair
9
- * crosses) to find the smallest-overlap axis and remember whether it came
10
- * from a face normal of A, a face normal of B, or an edge-pair cross.
11
- * 2. Face axis identify a reference face (on the box that owned the axis)
12
- * and an incident face (on the opposite box, the face whose outward
13
- * normal is most antiparallel to the contact normal). Project the four
14
- * incident corners into the reference face's 2-D coordinate frame and
15
- * clip the resulting quad against the reference face rectangle via
16
- * Sutherland-Hodgman. Each surviving vertex with positive penetration
17
- * becomes a contact point.
18
- * 3. Edge-cross axis a single contact at the body-centre midpoint
19
- * (v1 fallback; closest-edge-points refinement is a follow-up).
20
- * 4. If more than {@link MAX_CONTACTS} survive, reduce by picking the
21
- * deepest first, then three more that maximise the perimeter of the
22
- * resulting quad.
23
- *
24
- * Contact convention (matches the manifold cache): the normal points from
25
- * box B toward box A; positive depth means penetration.
26
- *
27
- * Output layout:
28
- * out[0..2] : world normal
29
- * out[3] : contact count (0 .. {@link MAX_CONTACTS})
30
- * out[4 + k*7 + 0..2] : world contact on A's surface
31
- * out[4 + k*7 + 3..5] : world contact on B's surface
32
- * out[4 + k*7 + 6] : penetration depth (positive)
33
- *
34
- * @author Alex Goldring
35
- * @copyright Company Named Limited (c) 2026
36
- */
37
-
38
- const MAX_CONTACTS = 4;
39
- const CONTACT_STRIDE = 7;
40
- const PARALLEL_EPS_SQR = 1e-8;
41
-
42
- /**
43
- * Reference-axis tie-break deadband. SAT picks the minimum-overlap axis, but
44
- * for aligned boxes two axes (A's face normal and B's face normal along the
45
- * contact direction) have *equal* overlap, so floating-point noise from a
46
- * sub-degree wobble flips which one wins frame to frame. That flips the
47
- * reference/incident assignment, which reorders the contact points, which
48
- * flips the solver's Gauss-Seidel sweep order injecting an alternating
49
- * bias that makes symmetric stacks creep and never sleep.
50
- *
51
- * The deadband makes a later axis replace the current best only if it
52
- * reduces the overlap by more than `best · TIE_REL + TIE_ABS`. Axes are
53
- * tested A-faces, then B-faces, then edge-crosses, so ties resolve to the
54
- * earlier axis (A's face, then a face over an edge) a stable, consistent
55
- * choice. Genuine minima (overlap smaller by more than the band) still win,
56
- * so SAT correctness for non-aligned boxes is unchanged; only the
57
- * noise-driven flip on near-perfect alignment is suppressed. Box2D's
58
- * `b2CollidePolygons` uses the same relative+absolute hysteresis.
59
- * @type {number}
60
- */
61
- const TIE_REL = 0.02;
62
- const TIE_ABS = 1e-5;
63
-
64
- /**
65
- * Length of `out` required by {@link box_box_manifold}.
66
- * @type {number}
67
- */
68
- export const BOX_BOX_OUT_LENGTH = 4 + MAX_CONTACTS * CONTACT_STRIDE;
69
-
70
- // --- shared scratch storage -------------------------------------------------
71
-
72
- const scratch_axes_a = new Float64Array(9);
73
- const scratch_axes_b = new Float64Array(9);
74
-
75
- // 4 incident face corners in world space.
76
- const incident_world = new Float64Array(12);
77
- // Clipped polygon — worst case 8 vertices (quad clipped by 4 planes).
78
- const clip_in = new Float64Array(8 * 3);
79
- const clip_out = new Float64Array(8 * 3);
80
- // 2-D projection of incident corners onto reference-face uv plane.
81
- const incident_uv = new Float64Array(8 * 2);
82
- const clipped_uv_in = new Float64Array(8 * 2);
83
- const clipped_uv_out = new Float64Array(8 * 2);
84
-
85
- // Surviving 3-D contact points along with their (signed) depth.
86
- // Stride 4 per candidate: x, y, z, depth.
87
- const candidates = new Float64Array(8 * 4);
88
-
89
- // Output of line3_closest_points_segment_segment for the edge-cross
90
- // SAT-winner path: (s, t) parameters along the two edges.
91
- const scratch_edge_st = new Float64Array(2);
92
-
93
- // --- helpers ---------------------------------------------------------------
94
-
95
- function projected_half_extent(axes, off, hx, hy, hz, lx, ly, lz) {
96
- const px = lx * axes[off] + ly * axes[off + 1] + lz * axes[off + 2];
97
- const py = lx * axes[off + 3] + ly * axes[off + 4] + lz * axes[off + 5];
98
- const pz = lx * axes[off + 6] + ly * axes[off + 7] + lz * axes[off + 8];
99
- return (px < 0 ? -px : px) * hx
100
- + (py < 0 ? -py : py) * hy
101
- + (pz < 0 ? -pz : pz) * hz;
102
- }
103
-
104
- /**
105
- * Sutherland-Hodgman clip of `points_in_uv` (point_count vertices, stride 2)
106
- * against the half-plane `coord_idx bound` (or `coord_idx ≥ bound` when
107
- * `keep_below` is false). Result is written to `points_out_uv`, returns the
108
- * vertex count.
109
- *
110
- * @param {Float64Array} points_in
111
- * @param {number} point_count
112
- * @param {Float64Array} points_out
113
- * @param {number} coord_idx 0 = u, 1 = v
114
- * @param {number} bound
115
- * @param {boolean} keep_below true to keep points with coord ≤ bound
116
- * @returns {number} surviving vertex count
117
- */
118
- function clip_against_axis(points_in, point_count, points_out, coord_idx, bound, keep_below) {
119
- let out_count = 0;
120
- for (let i = 0; i < point_count; i++) {
121
- const j = (i + 1) % point_count;
122
- const ax = points_in[i * 2], ay = points_in[i * 2 + 1];
123
- const bx = points_in[j * 2], by = points_in[j * 2 + 1];
124
- const av = coord_idx === 0 ? ax : ay;
125
- const bv = coord_idx === 0 ? bx : by;
126
- const a_inside = keep_below ? (av <= bound) : (av >= bound);
127
- const b_inside = keep_below ? (bv <= bound) : (bv >= bound);
128
-
129
- if (a_inside) {
130
- // emit a
131
- points_out[out_count * 2] = ax;
132
- points_out[out_count * 2 + 1] = ay;
133
- out_count++;
134
- }
135
- if (a_inside !== b_inside) {
136
- // emit intersection on the bounding line
137
- // Parameterise: p(t) = a + t * (b - a); solve coord(p(t)) = bound.
138
- const denom = bv - av;
139
- const t = denom !== 0 ? (bound - av) / denom : 0;
140
- points_out[out_count * 2] = ax + (bx - ax) * t;
141
- points_out[out_count * 2 + 1] = ay + (by - ay) * t;
142
- out_count++;
143
- }
144
- }
145
- return out_count;
146
- }
147
-
148
- // --- main -------------------------------------------------------------------
149
-
150
- /**
151
- *
152
- * @param {number[]|Float64Array} out length >= BOX_BOX_OUT_LENGTH
153
- * @param {number} ax centre x of A
154
- * @param {number} ay
155
- * @param {number} az
156
- * @param {number} aqx A rotation quaternion x
157
- * @param {number} aqy
158
- * @param {number} aqz
159
- * @param {number} aqw
160
- * @param {number} ahx A half-extent x in body frame
161
- * @param {number} ahy
162
- * @param {number} ahz
163
- * @param {number} bx centre x of B
164
- * @param {number} by
165
- * @param {number} bz
166
- * @param {number} bqx
167
- * @param {number} bqy
168
- * @param {number} bqz
169
- * @param {number} bqw
170
- * @param {number} bhx
171
- * @param {number} bhy
172
- * @param {number} bhz
173
- * @returns {boolean} true if overlap
174
- */
175
- export function box_box_manifold(
176
- out,
177
- ax, ay, az, aqx, aqy, aqz, aqw, ahx, ahy, ahz,
178
- bx, by, bz, bqx, bqy, bqz, bqw, bhx, bhy, bhz
179
- ) {
180
- quat3_to_matrix3(scratch_axes_a, 0, aqx, aqy, aqz, aqw);
181
- quat3_to_matrix3(scratch_axes_b, 0, bqx, bqy, bqz, bqw);
182
-
183
- const ta = scratch_axes_a;
184
- const tb = scratch_axes_b;
185
-
186
- const dx = bx - ax;
187
- const dy = by - ay;
188
- const dz = bz - az;
189
-
190
- // SAT track winning axis + source.
191
- // source: 0..2 = A face normal, 3..5 = B face normal, 6..14 = edge cross.
192
- let best_overlap = Infinity;
193
- let best_nx = 0, best_ny = 0, best_nz = 0;
194
- let best_source = -1;
195
-
196
- function test_axis(lx, ly, lz, source) {
197
- const len_sqr = lx * lx + ly * ly + lz * lz;
198
- if (len_sqr < PARALLEL_EPS_SQR) return false;
199
- const inv_len = 1 / Math.sqrt(len_sqr);
200
- const ux = lx * inv_len, uy = ly * inv_len, uz = lz * inv_len;
201
- const rA = projected_half_extent(ta, 0, ahx, ahy, ahz, ux, uy, uz);
202
- const rB = projected_half_extent(tb, 0, bhx, bhy, bhz, ux, uy, uz);
203
- const proj = dx * ux + dy * uy + dz * uz;
204
- const dist = proj < 0 ? -proj : proj;
205
- const overlap = (rA + rB) - dist;
206
- if (overlap < 0) return true;
207
- // Deadband: the first axis always wins; a later axis replaces it only
208
- // if it reduces the overlap past the hysteresis band. This biases ties
209
- // toward earlier-tested axes (A faces > B faces > edges) so aligned
210
- // boxes pick a stable reference instead of flip-flopping on noise.
211
- if (best_source === -1 || overlap < best_overlap - (best_overlap * TIE_REL + TIE_ABS)) {
212
- best_overlap = overlap;
213
- const sign = proj > 0 ? -1 : 1; // normal points B→A
214
- best_nx = ux * sign;
215
- best_ny = uy * sign;
216
- best_nz = uz * sign;
217
- best_source = source;
218
- }
219
- return false;
220
- }
221
-
222
- if (test_axis(ta[0], ta[1], ta[2], 0)) return false;
223
- if (test_axis(ta[3], ta[4], ta[5], 1)) return false;
224
- if (test_axis(ta[6], ta[7], ta[8], 2)) return false;
225
- if (test_axis(tb[0], tb[1], tb[2], 3)) return false;
226
- if (test_axis(tb[3], tb[4], tb[5], 4)) return false;
227
- if (test_axis(tb[6], tb[7], tb[8], 5)) return false;
228
-
229
- for (let i = 0; i < 3; i++) {
230
- const aix = ta[i * 3], aiy = ta[i * 3 + 1], aiz = ta[i * 3 + 2];
231
- for (let j = 0; j < 3; j++) {
232
- const bjx = tb[j * 3], bjy = tb[j * 3 + 1], bjz = tb[j * 3 + 2];
233
- const cx = aiy * bjz - aiz * bjy;
234
- const cy = aiz * bjx - aix * bjz;
235
- const cz = aix * bjy - aiy * bjx;
236
- if (test_axis(cx, cy, cz, 6 + i * 3 + j)) return false;
237
- }
238
- }
239
-
240
- // We have a contact. Output the normal.
241
- const nx = best_nx, ny = best_ny, nz = best_nz;
242
- out[0] = nx; out[1] = ny; out[2] = nz;
243
-
244
- // ---- Edge-cross axis: closest-pair on the two involved edges ----
245
- //
246
- // When SAT identifies an edge-edge separating axis (source 6..14 =
247
- // 6 + i*3 + j, where `i` is box A's local edge-axis index and
248
- // `j` is box B's), the contact happens where one specific edge of
249
- // A crosses (or is closest to) one specific edge of B. The earlier
250
- // body-centre-midpoint fallback was sufficient for "we know they
251
- // collide" but produced lever arms that confused the solver — for
252
- // skewed-box stacks this led to slow drift.
253
- //
254
- // Procedure:
255
- // 1. Decode (i, j) from `best_source`.
256
- // 2. Among box A's 4 parallel edges along axis i, pick the one
257
- // whose corner is most in the −n direction (closest to B).
258
- // 3. Same for box B with +n direction.
259
- // 4. `line3_closest_points_segment_segment` returns (s, t)
260
- // parameters; reconstruct the world contact on each edge.
261
- if (best_source >= 6) {
262
- const ax_src = best_source - 6;
263
- const i_a = (ax_src / 3) | 0;
264
- const j_b = ax_src - i_a * 3;
265
-
266
- // Edge directions in world.
267
- const edge_a_dx = ta[i_a * 3];
268
- const edge_a_dy = ta[i_a * 3 + 1];
269
- const edge_a_dz = ta[i_a * 3 + 2];
270
- const edge_b_dx = tb[j_b * 3];
271
- const edge_b_dy = tb[j_b * 3 + 1];
272
- const edge_b_dz = tb[j_b * 3 + 2];
273
-
274
- // Edge half-extents (along the chosen axis).
275
- const edge_a_half = i_a === 0 ? ahx : (i_a === 1 ? ahy : ahz);
276
- const edge_b_half = j_b === 0 ? bhx : (j_b === 1 ? bhy : bhz);
277
-
278
- // Perpendicular axes (the other two) and their half-extents.
279
- let u_a_idx, v_a_idx;
280
- if (i_a === 0) { u_a_idx = 1; v_a_idx = 2; }
281
- else if (i_a === 1) { u_a_idx = 2; v_a_idx = 0; }
282
- else { u_a_idx = 0; v_a_idx = 1; }
283
- const u_a_x = ta[u_a_idx * 3], u_a_y = ta[u_a_idx * 3 + 1], u_a_z = ta[u_a_idx * 3 + 2];
284
- const v_a_x = ta[v_a_idx * 3], v_a_y = ta[v_a_idx * 3 + 1], v_a_z = ta[v_a_idx * 3 + 2];
285
- const half_u_a = u_a_idx === 0 ? ahx : (u_a_idx === 1 ? ahy : ahz);
286
- const half_v_a = v_a_idx === 0 ? ahx : (v_a_idx === 1 ? ahy : ahz);
287
-
288
- let u_b_idx, v_b_idx;
289
- if (j_b === 0) { u_b_idx = 1; v_b_idx = 2; }
290
- else if (j_b === 1) { u_b_idx = 2; v_b_idx = 0; }
291
- else { u_b_idx = 0; v_b_idx = 1; }
292
- const u_b_x = tb[u_b_idx * 3], u_b_y = tb[u_b_idx * 3 + 1], u_b_z = tb[u_b_idx * 3 + 2];
293
- const v_b_x = tb[v_b_idx * 3], v_b_y = tb[v_b_idx * 3 + 1], v_b_z = tb[v_b_idx * 3 + 2];
294
- const half_u_b = u_b_idx === 0 ? bhx : (u_b_idx === 1 ? bhy : bhz);
295
- const half_v_b = v_b_idx === 0 ? bhx : (v_b_idx === 1 ? bhy : bhz);
296
-
297
- // The contact normal `n` (= best_n) points B → A. From A's
298
- // perspective B is in the −n direction; pick the A-corner most
299
- // in that direction. From B's perspective A is in +n; pick the
300
- // B-corner most in +n.
301
- const minus_n_dot_u_a = -(nx * u_a_x + ny * u_a_y + nz * u_a_z);
302
- const minus_n_dot_v_a = -(nx * v_a_x + ny * v_a_y + nz * v_a_z);
303
- const u_sign_a = minus_n_dot_u_a >= 0 ? 1 : -1;
304
- const v_sign_a = minus_n_dot_v_a >= 0 ? 1 : -1;
305
-
306
- const plus_n_dot_u_b = nx * u_b_x + ny * u_b_y + nz * u_b_z;
307
- const plus_n_dot_v_b = nx * v_b_x + ny * v_b_y + nz * v_b_z;
308
- const u_sign_b = plus_n_dot_u_b >= 0 ? 1 : -1;
309
- const v_sign_b = plus_n_dot_v_b >= 0 ? 1 : -1;
310
-
311
- // Box-A edge centre = A_centre + u_sign_a * half_u_a * u_a
312
- // + v_sign_a * half_v_a * v_a.
313
- const corner_a_cx = ax + u_a_x * u_sign_a * half_u_a + v_a_x * v_sign_a * half_v_a;
314
- const corner_a_cy = ay + u_a_y * u_sign_a * half_u_a + v_a_y * v_sign_a * half_v_a;
315
- const corner_a_cz = az + u_a_z * u_sign_a * half_u_a + v_a_z * v_sign_a * half_v_a;
316
- const edge_a_p1_x = corner_a_cx - edge_a_dx * edge_a_half;
317
- const edge_a_p1_y = corner_a_cy - edge_a_dy * edge_a_half;
318
- const edge_a_p1_z = corner_a_cz - edge_a_dz * edge_a_half;
319
- const edge_a_p2_x = corner_a_cx + edge_a_dx * edge_a_half;
320
- const edge_a_p2_y = corner_a_cy + edge_a_dy * edge_a_half;
321
- const edge_a_p2_z = corner_a_cz + edge_a_dz * edge_a_half;
322
-
323
- const corner_b_cx = bx + u_b_x * u_sign_b * half_u_b + v_b_x * v_sign_b * half_v_b;
324
- const corner_b_cy = by + u_b_y * u_sign_b * half_u_b + v_b_y * v_sign_b * half_v_b;
325
- const corner_b_cz = bz + u_b_z * u_sign_b * half_u_b + v_b_z * v_sign_b * half_v_b;
326
- const edge_b_p1_x = corner_b_cx - edge_b_dx * edge_b_half;
327
- const edge_b_p1_y = corner_b_cy - edge_b_dy * edge_b_half;
328
- const edge_b_p1_z = corner_b_cz - edge_b_dz * edge_b_half;
329
- const edge_b_p2_x = corner_b_cx + edge_b_dx * edge_b_half;
330
- const edge_b_p2_y = corner_b_cy + edge_b_dy * edge_b_half;
331
- const edge_b_p2_z = corner_b_cz + edge_b_dz * edge_b_half;
332
-
333
- line3_closest_points_segment_segment(
334
- scratch_edge_st,
335
- edge_a_p1_x, edge_a_p1_y, edge_a_p1_z, edge_a_p2_x, edge_a_p2_y, edge_a_p2_z,
336
- edge_b_p1_x, edge_b_p1_y, edge_b_p1_z, edge_b_p2_x, edge_b_p2_y, edge_b_p2_z
337
- );
338
- const s = scratch_edge_st[0];
339
- const t = scratch_edge_st[1];
340
- const contact_a_x = edge_a_p1_x + s * (edge_a_p2_x - edge_a_p1_x);
341
- const contact_a_y = edge_a_p1_y + s * (edge_a_p2_y - edge_a_p1_y);
342
- const contact_a_z = edge_a_p1_z + s * (edge_a_p2_z - edge_a_p1_z);
343
- const contact_b_x = edge_b_p1_x + t * (edge_b_p2_x - edge_b_p1_x);
344
- const contact_b_y = edge_b_p1_y + t * (edge_b_p2_y - edge_b_p1_y);
345
- const contact_b_z = edge_b_p1_z + t * (edge_b_p2_z - edge_b_p1_z);
346
-
347
- out[3] = 1;
348
- out[4] = contact_a_x; out[5] = contact_a_y; out[6] = contact_a_z;
349
- out[7] = contact_b_x; out[8] = contact_b_y; out[9] = contact_b_z;
350
- out[10] = best_overlap;
351
- return true;
352
- }
353
-
354
- // ---- Face axis: face clipping ----
355
- // Determine reference and incident.
356
- const ref_is_A = best_source < 3;
357
- // Reference axis index in the owning box (0..2).
358
- const ref_axis_idx = ref_is_A ? best_source : best_source - 3;
359
-
360
- // Reference box pose.
361
- const ref_axes = ref_is_A ? ta : tb;
362
- const inc_axes = ref_is_A ? tb : ta;
363
- const ref_h_x = ref_is_A ? ahx : bhx;
364
- const ref_h_y = ref_is_A ? ahy : bhy;
365
- const ref_h_z = ref_is_A ? ahz : bhz;
366
- const inc_h_x = ref_is_A ? bhx : ahx;
367
- const inc_h_y = ref_is_A ? bhy : ahy;
368
- const inc_h_z = ref_is_A ? bhz : ahz;
369
- const ref_cx = ref_is_A ? ax : bx;
370
- const ref_cy = ref_is_A ? ay : by;
371
- const ref_cz = ref_is_A ? az : bz;
372
- const inc_cx = ref_is_A ? bx : ax;
373
- const inc_cy = ref_is_A ? by : ay;
374
- const inc_cz = ref_is_A ? bz : az;
375
-
376
- // Reference face outward normal in world: the face of the ref box facing
377
- // the incident box. The contact normal points B→A; the ref face's
378
- // outward normal must point toward the incident box (= -n if ref is A,
379
- // = +n if ref is B).
380
- const ref_out_nx = ref_is_A ? -nx : nx;
381
- const ref_out_ny = ref_is_A ? -ny : ny;
382
- const ref_out_nz = ref_is_A ? -nz : nz;
383
-
384
- // Ref face's three axis-in-world directions: the axis-direction matching
385
- // ref_axis_idx is the OUTWARD normal; the other two are the face tangents.
386
- // Sign of the reference-face axis aligned with ref_out:
387
- const ref_axis_world_x = ref_axes[ref_axis_idx * 3];
388
- const ref_axis_world_y = ref_axes[ref_axis_idx * 3 + 1];
389
- const ref_axis_world_z = ref_axes[ref_axis_idx * 3 + 2];
390
- const ref_axis_dot = ref_axis_world_x * ref_out_nx
391
- + ref_axis_world_y * ref_out_ny
392
- + ref_axis_world_z * ref_out_nz;
393
- const ref_axis_sign = ref_axis_dot >= 0 ? 1 : -1;
394
-
395
- // Face plane: passes through `ref_cx + ref_axis * ref_axis_sign * ref_h_<axis>`,
396
- // with outward normal = `ref_axis_world * ref_axis_sign`.
397
- const ref_h_along_axis = ref_axis_idx === 0 ? ref_h_x : (ref_axis_idx === 1 ? ref_h_y : ref_h_z);
398
- const ref_face_origin_x = ref_cx + ref_axis_world_x * ref_axis_sign * ref_h_along_axis;
399
- const ref_face_origin_y = ref_cy + ref_axis_world_y * ref_axis_sign * ref_h_along_axis;
400
- const ref_face_origin_z = ref_cz + ref_axis_world_z * ref_axis_sign * ref_h_along_axis;
401
-
402
- // Reference face's two tangent axes (u, v) in world, with the corresponding half-extents.
403
- let u_axis_idx, v_axis_idx;
404
- if (ref_axis_idx === 0) { u_axis_idx = 1; v_axis_idx = 2; }
405
- else if (ref_axis_idx === 1) { u_axis_idx = 2; v_axis_idx = 0; }
406
- else { u_axis_idx = 0; v_axis_idx = 1; }
407
-
408
- const ux = ref_axes[u_axis_idx * 3], uy = ref_axes[u_axis_idx * 3 + 1], uz = ref_axes[u_axis_idx * 3 + 2];
409
- const vx = ref_axes[v_axis_idx * 3], vy = ref_axes[v_axis_idx * 3 + 1], vz = ref_axes[v_axis_idx * 3 + 2];
410
- const half_u = u_axis_idx === 0 ? ref_h_x : (u_axis_idx === 1 ? ref_h_y : ref_h_z);
411
- const half_v = v_axis_idx === 0 ? ref_h_x : (v_axis_idx === 1 ? ref_h_y : ref_h_z);
412
-
413
- // ---- Pick incident face on the OTHER box ----
414
- // Its outward normal should be MOST antiparallel to the ref face outward normal
415
- // (i.e., the face of the incident box that is "looking back" at the ref face).
416
- let inc_axis_idx = 0, inc_axis_sign = 1;
417
- let max_anti = -Infinity;
418
- for (let i = 0; i < 3; i++) {
419
- const iax = inc_axes[i * 3], iay = inc_axes[i * 3 + 1], iaz = inc_axes[i * 3 + 2];
420
- const d_pos = iax * ref_out_nx + iay * ref_out_ny + iaz * ref_out_nz;
421
- // We want dot -1, so most negative dot is the most anti-parallel
422
- if (-d_pos > max_anti) { max_anti = -d_pos; inc_axis_idx = i; inc_axis_sign = -1; }
423
- if ( d_pos > max_anti) { max_anti = d_pos; inc_axis_idx = i; inc_axis_sign = 1; }
424
- }
425
- // Now the incident face outward normal must be antiparallel to ref_out_n.
426
- // We chose inc_axis_sign as the sign of dot(inc_axis_dir, ref_out_n). The
427
- // incident face's outward direction is the OPPOSITE sign (facing back at ref).
428
- const inc_outward_sign = -inc_axis_sign;
429
-
430
- const inc_h_along_axis = inc_axis_idx === 0 ? inc_h_x : (inc_axis_idx === 1 ? inc_h_y : inc_h_z);
431
- // Incident face centre in world.
432
- const inc_face_cx = inc_cx + inc_axes[inc_axis_idx * 3] * inc_outward_sign * inc_h_along_axis;
433
- const inc_face_cy = inc_cy + inc_axes[inc_axis_idx * 3 + 1] * inc_outward_sign * inc_h_along_axis;
434
- const inc_face_cz = inc_cz + inc_axes[inc_axis_idx * 3 + 2] * inc_outward_sign * inc_h_along_axis;
435
-
436
- // Incident face's two tangent axes in world, with their half-extents.
437
- let i_u_idx, i_v_idx;
438
- if (inc_axis_idx === 0) { i_u_idx = 1; i_v_idx = 2; }
439
- else if (inc_axis_idx === 1) { i_u_idx = 2; i_v_idx = 0; }
440
- else { i_u_idx = 0; i_v_idx = 1; }
441
- const iux = inc_axes[i_u_idx * 3], iuy = inc_axes[i_u_idx * 3 + 1], iuz = inc_axes[i_u_idx * 3 + 2];
442
- const ivx = inc_axes[i_v_idx * 3], ivy = inc_axes[i_v_idx * 3 + 1], ivz = inc_axes[i_v_idx * 3 + 2];
443
- const i_half_u = i_u_idx === 0 ? inc_h_x : (i_u_idx === 1 ? inc_h_y : inc_h_z);
444
- const i_half_v = i_v_idx === 0 ? inc_h_x : (i_v_idx === 1 ? inc_h_y : inc_h_z);
445
-
446
- // Build incident face's 4 world corners (ordered CCW around the face).
447
- const signs_u = [ 1, 1, -1, -1];
448
- const signs_v = [-1, 1, 1, -1];
449
- for (let i = 0; i < 4; i++) {
450
- const su = signs_u[i] * i_half_u;
451
- const sv = signs_v[i] * i_half_v;
452
- incident_world[i * 3] = inc_face_cx + iux * su + ivx * sv;
453
- incident_world[i * 3 + 1] = inc_face_cy + iuy * su + ivy * sv;
454
- incident_world[i * 3 + 2] = inc_face_cz + iuz * su + ivz * sv;
455
- }
456
-
457
- // Project incident corners into ref-face uv coordinates.
458
- // For each corner C: uv = ((C - ref_face_origin) · u_axis, ... · v_axis).
459
- for (let i = 0; i < 4; i++) {
460
- const ex = incident_world[i * 3] - ref_face_origin_x;
461
- const ey = incident_world[i * 3 + 1] - ref_face_origin_y;
462
- const ez = incident_world[i * 3 + 2] - ref_face_origin_z;
463
- incident_uv[i * 2] = ex * ux + ey * uy + ez * uz;
464
- incident_uv[i * 2 + 1] = ex * vx + ey * vy + ez * vz;
465
- }
466
-
467
- // Sutherland-Hodgman clip against the rectangle |u|<=half_u, |v|<=half_v.
468
- // Apply 4 successive single-axis clips.
469
- let n = 4;
470
- // Copy into clipped_uv_in first.
471
- for (let i = 0; i < n * 2; i++) clipped_uv_in[i] = incident_uv[i];
472
-
473
- n = clip_against_axis(clipped_uv_in, n, clipped_uv_out, 0, half_u, true);
474
- if (n === 0) return out_empty(out);
475
- n = clip_against_axis(clipped_uv_out, n, clipped_uv_in, 0, -half_u, false);
476
- if (n === 0) return out_empty(out);
477
- n = clip_against_axis(clipped_uv_in, n, clipped_uv_out, 1, half_v, true);
478
- if (n === 0) return out_empty(out);
479
- n = clip_against_axis(clipped_uv_out, n, clipped_uv_in, 1, -half_v, false);
480
- if (n === 0) return out_empty(out);
481
-
482
- // Each surviving uv-point is on the ref face rectangle. We need to:
483
- // 1. Map uv back to world → that's the contact point on the *incident* face
484
- // (still on the inc face plane at that uv).
485
- // 2. Compute depth = penetration along contact normal n (B→A).
486
- // 3. The contact on the *reference* face is the projection of the inc-face
487
- // point onto the reference plane along the contact normal.
488
-
489
- // To re-derive the world position from a uv coord: we need to keep both the
490
- // uv coord and the corresponding world point. But we just clipped uv-only,
491
- // so the world position is the projection back. The depth resolves it:
492
- //
493
- // ref plane: normal = ref_outward, origin at ref_face_origin
494
- // incident point world = ref_face_origin + u*u_axis + v*v_axis + (signed projection along ref_out)
495
- //
496
- // The component along ref_out for the original incident corner is what we lost
497
- // by going to uv. We recompute it from the original incident face plane (which
498
- // is at a fixed offset from ref): the inc corner's signed distance from the ref
499
- // plane is `(corner - ref_face_origin) · ref_out_n`.
500
- //
501
- // After clipping in uv, we can't directly recover that distance without
502
- // re-projecting onto the inc face plane. We do that here.
503
-
504
- const ref_out_x = ref_axis_world_x * ref_axis_sign;
505
- const ref_out_y = ref_axis_world_y * ref_axis_sign;
506
- const ref_out_z = ref_axis_world_z * ref_axis_sign;
507
-
508
- // Inc face plane (in world): point inc_face_c, normal inc_outward
509
- // = inc_axes[inc_axis_idx*3..+2] * inc_outward_sign.
510
- const inc_out_x = inc_axes[inc_axis_idx * 3] * inc_outward_sign;
511
- const inc_out_y = inc_axes[inc_axis_idx * 3 + 1] * inc_outward_sign;
512
- const inc_out_z = inc_axes[inc_axis_idx * 3 + 2] * inc_outward_sign;
513
-
514
- // For a clipped uv point P_uv, the corresponding world point P_world on the
515
- // incident face plane satisfies:
516
- // P_world = ref_face_origin + u*u_axis + v*v_axis + t * ref_out for some t
517
- // (P_world - inc_face_c) · inc_out = 0
518
- // Substitute and solve for t. Let:
519
- // X = ref_face_origin + u*u_axis + v*v_axis (a point on the line)
520
- // t such that (X + t*ref_out - inc_face_c) · inc_out = 0
521
- // t * (ref_out · inc_out) = (inc_face_c - X) · inc_out
522
- const ref_dot_inc = ref_out_x * inc_out_x + ref_out_y * inc_out_y + ref_out_z * inc_out_z;
523
- // Faces are nearly parallel → ref_dot_inc ≈ -1 (anti-parallel). Robust.
524
-
525
- // Build candidates: for each clipped uv point.
526
- let cand_count = 0;
527
- const clipped_uv = clipped_uv_in;
528
- for (let i = 0; i < n; i++) {
529
- const u = clipped_uv[i * 2];
530
- const v = clipped_uv[i * 2 + 1];
531
-
532
- const x_x = ref_face_origin_x + u * ux + v * vx;
533
- const x_y = ref_face_origin_y + u * uy + v * vy;
534
- const x_z = ref_face_origin_z + u * uz + v * vz;
535
-
536
- let world_inc_x, world_inc_y, world_inc_z;
537
- if (ref_dot_inc !== 0) {
538
- const num_x = inc_face_cx - x_x;
539
- const num_y = inc_face_cy - x_y;
540
- const num_z = inc_face_cz - x_z;
541
- const t = (num_x * inc_out_x + num_y * inc_out_y + num_z * inc_out_z) / ref_dot_inc;
542
- world_inc_x = x_x + ref_out_x * t;
543
- world_inc_y = x_y + ref_out_y * t;
544
- world_inc_z = x_z + ref_out_z * t;
545
- } else {
546
- // Faces orthogonal degenerate, fall back to uv point on ref plane.
547
- world_inc_x = x_x; world_inc_y = x_y; world_inc_z = x_z;
548
- }
549
-
550
- // Penetration: signed distance of inc-face contact from the ref plane,
551
- // measured into the ref box (= along -ref_out). Positive means penetrating.
552
- const sep_x = world_inc_x - ref_face_origin_x;
553
- const sep_y = world_inc_y - ref_face_origin_y;
554
- const sep_z = world_inc_z - ref_face_origin_z;
555
- const sep_along_ref_out = sep_x * ref_out_x + sep_y * ref_out_y + sep_z * ref_out_z;
556
- const depth = -sep_along_ref_out;
557
- if (depth < 0) continue;
558
-
559
- candidates[cand_count * 4] = world_inc_x;
560
- candidates[cand_count * 4 + 1] = world_inc_y;
561
- candidates[cand_count * 4 + 2] = world_inc_z;
562
- candidates[cand_count * 4 + 3] = depth;
563
- cand_count++;
564
- }
565
-
566
- if (cand_count === 0) return out_empty(out);
567
-
568
- // ---- Reduce to ≤ MAX_CONTACTS by best-deepest + perimeter ----
569
- const kept = reduce_contacts(cand_count);
570
-
571
- // ---- Emit: contact-on-incident is the candidate's world point;
572
- // contact-on-reference is the same point projected onto the ref plane.
573
- out[3] = kept;
574
- for (let k = 0; k < kept; k++) {
575
- const px = candidates[k * 4];
576
- const py = candidates[k * 4 + 1];
577
- const pz = candidates[k * 4 + 2];
578
- const depth = candidates[k * 4 + 3];
579
-
580
- // ref-side contact = project onto ref plane along ref_out.
581
- const dist_to_plane = (px - ref_face_origin_x) * ref_out_x
582
- + (py - ref_face_origin_y) * ref_out_y
583
- + (pz - ref_face_origin_z) * ref_out_z;
584
- const rpx = px - ref_out_x * dist_to_plane;
585
- const rpy = py - ref_out_y * dist_to_plane;
586
- const rpz = pz - ref_out_z * dist_to_plane;
587
-
588
- let wax, way, waz, wbx_, wby_, wbz_;
589
- if (ref_is_A) {
590
- wax = rpx; way = rpy; waz = rpz;
591
- wbx_ = px; wby_ = py; wbz_ = pz;
592
- } else {
593
- wax = px; way = py; waz = pz;
594
- wbx_ = rpx; wby_ = rpy; wbz_ = rpz;
595
- }
596
-
597
- const base = 4 + k * CONTACT_STRIDE;
598
- out[base] = wax; out[base + 1] = way; out[base + 2] = waz;
599
- out[base + 3] = wbx_; out[base + 4] = wby_; out[base + 5] = wbz_;
600
- out[base + 6] = depth;
601
- }
602
- return true;
603
- }
604
-
605
- function out_empty(out) {
606
- out[3] = 0;
607
- return true; // overlap exists per SAT, just no clipped manifold
608
- }
609
-
610
- /**
611
- * In-place reduction of `candidates` to at most {@link MAX_CONTACTS}:
612
- * 1. Sort by depth descending; deepest stays at index 0.
613
- * 2. From the remaining, greedily pick the points that maximise the spread
614
- * (sum of squared distances to already-kept points). This approximates
615
- * the maximum-area heuristic without needing the actual area.
616
- *
617
- * @param {number} n input count
618
- * @returns {number} kept count (min(n, MAX_CONTACTS))
619
- */
620
- function reduce_contacts(n) {
621
- if (n <= MAX_CONTACTS) return n;
622
-
623
- // Find deepest, swap into slot 0.
624
- let deepest_idx = 0;
625
- let deepest_val = candidates[3];
626
- for (let i = 1; i < n; i++) {
627
- if (candidates[i * 4 + 3] > deepest_val) {
628
- deepest_val = candidates[i * 4 + 3];
629
- deepest_idx = i;
630
- }
631
- }
632
- if (deepest_idx !== 0) swap_candidate(0, deepest_idx);
633
-
634
- // Greedy: for slot k in 1..MAX_CONTACTS-1, pick the remaining candidate
635
- // whose min-distance-sq-to-already-kept-set is largest.
636
- for (let k = 1; k < MAX_CONTACTS; k++) {
637
- let best_score = -1;
638
- let best_i = -1;
639
- for (let i = k; i < n; i++) {
640
- let min_d2 = Infinity;
641
- for (let j = 0; j < k; j++) {
642
- const dx = candidates[i * 4] - candidates[j * 4];
643
- const dy = candidates[i * 4 + 1] - candidates[j * 4 + 1];
644
- const dz = candidates[i * 4 + 2] - candidates[j * 4 + 2];
645
- const d2 = dx * dx + dy * dy + dz * dz;
646
- if (d2 < min_d2) min_d2 = d2;
647
- }
648
- if (min_d2 > best_score) { best_score = min_d2; best_i = i; }
649
- }
650
- if (best_i !== k) swap_candidate(k, best_i);
651
- }
652
- return MAX_CONTACTS;
653
- }
654
-
655
- function swap_candidate(a, b) {
656
- const ax = candidates[a * 4], ay = candidates[a * 4 + 1], az = candidates[a * 4 + 2], ad = candidates[a * 4 + 3];
657
- candidates[a * 4] = candidates[b * 4];
658
- candidates[a * 4 + 1] = candidates[b * 4 + 1];
659
- candidates[a * 4 + 2] = candidates[b * 4 + 2];
660
- candidates[a * 4 + 3] = candidates[b * 4 + 3];
661
- candidates[b * 4] = ax;
662
- candidates[b * 4 + 1] = ay;
663
- candidates[b * 4 + 2] = az;
664
- candidates[b * 4 + 3] = ad;
665
- }
1
+ import {
2
+ line3_closest_points_segment_segment
3
+ } from "../../../core/geom/3d/line/line3_closest_points_segment_segment.js";
4
+ import { quat3_to_matrix3 } from "../../../core/geom/3d/quaternion/quat3_to_matrix3.js";
5
+ import { clip_against_axis_uv } from "./clip_against_axis_uv.js";
6
+
7
+ /**
8
+ * Multi-point manifold construction for two oriented bounding boxes.
9
+ *
10
+ * Algorithm:
11
+ * 1. SAT over the canonical 15 axes (3 face normals of A, 3 of B, 9 edge-pair
12
+ * crosses) to find the smallest-overlap axis and remember whether it came
13
+ * from a face normal of A, a face normal of B, or an edge-pair cross.
14
+ * 2. Face axis identify a reference face (on the box that owned the axis)
15
+ * and an incident face (on the opposite box, the face whose outward
16
+ * normal is most antiparallel to the contact normal). Project the four
17
+ * incident corners into the reference face's 2-D coordinate frame and
18
+ * clip the resulting quad against the reference face rectangle via
19
+ * Sutherland-Hodgman. Each surviving vertex with positive penetration
20
+ * becomes a contact point.
21
+ * 3. Edge-cross axis a single contact at the body-centre midpoint
22
+ * (v1 fallback; closest-edge-points refinement is a follow-up).
23
+ * 4. If more than {@link MAX_CONTACTS} survive, reduce by picking the
24
+ * deepest first, then three more that maximise the perimeter of the
25
+ * resulting quad.
26
+ *
27
+ * Contact convention (matches the manifold cache): the normal points from
28
+ * box B toward box A; positive depth means penetration.
29
+ *
30
+ * Output layout:
31
+ * out[0..2] : world normal
32
+ * out[3] : contact count (0 .. {@link MAX_CONTACTS})
33
+ * out[4 + k*7 + 0..2] : world contact on A's surface
34
+ * out[4 + k*7 + 3..5] : world contact on B's surface
35
+ * out[4 + k*7 + 6] : penetration depth (positive)
36
+ *
37
+ * @author Alex Goldring
38
+ * @copyright Company Named Limited (c) 2026
39
+ */
40
+
41
+ const MAX_CONTACTS = 4;
42
+ const CONTACT_STRIDE = 7;
43
+ const PARALLEL_EPS_SQR = 1e-8;
44
+
45
+ /**
46
+ * Reference-axis tie-break deadband. SAT picks the minimum-overlap axis, but
47
+ * for aligned boxes two axes (A's face normal and B's face normal along the
48
+ * contact direction) have *equal* overlap, so floating-point noise from a
49
+ * sub-degree wobble flips which one wins frame to frame. That flips the
50
+ * reference/incident assignment, which reorders the contact points, which
51
+ * flips the solver's Gauss-Seidel sweep order injecting an alternating
52
+ * bias that makes symmetric stacks creep and never sleep.
53
+ *
54
+ * The deadband makes a later axis replace the current best only if it
55
+ * reduces the overlap by more than `best · TIE_REL + TIE_ABS`. Axes are
56
+ * tested A-faces, then B-faces, then edge-crosses, so ties resolve to the
57
+ * earlier axis (A's face, then a face over an edge) — a stable, consistent
58
+ * choice. Genuine minima (overlap smaller by more than the band) still win,
59
+ * so SAT correctness for non-aligned boxes is unchanged; only the
60
+ * noise-driven flip on near-perfect alignment is suppressed. Box2D's
61
+ * `b2CollidePolygons` uses the same relative+absolute hysteresis.
62
+ * @type {number}
63
+ */
64
+ const TIE_REL = 0.02;
65
+ const TIE_ABS = 1e-5;
66
+
67
+ /**
68
+ * Length of `out` required by {@link box_box_manifold}.
69
+ * @type {number}
70
+ */
71
+ export const BOX_BOX_OUT_LENGTH = 4 + MAX_CONTACTS * CONTACT_STRIDE;
72
+
73
+ // --- shared scratch storage -------------------------------------------------
74
+
75
+ const scratch_axes_a = new Float64Array(9);
76
+ const scratch_axes_b = new Float64Array(9);
77
+
78
+ // 4 incident face corners in world space.
79
+ const incident_world = new Float64Array(12);
80
+
81
+ // 2-D projection of incident corners onto reference-face uv plane.
82
+ const incident_uv = new Float64Array(8 * 2);
83
+ const clipped_uv_in = new Float64Array(8 * 2);
84
+ const clipped_uv_out = new Float64Array(8 * 2);
85
+
86
+ // Surviving 3-D contact points along with their (signed) depth.
87
+ // Stride 4 per candidate: x, y, z, depth.
88
+ const candidates = new Float64Array(8 * 4);
89
+
90
+ // Output of line3_closest_points_segment_segment for the edge-cross
91
+ // SAT-winner path: (s, t) parameters along the two edges.
92
+ const scratch_edge_st = new Float64Array(2);
93
+
94
+ // --- helpers ---------------------------------------------------------------
95
+
96
+ function projected_half_extent(
97
+ axes, off,
98
+ hx, hy, hz,
99
+ lx, ly, lz
100
+ ) {
101
+
102
+ const px = lx * axes[off] + ly * axes[off + 1] + lz * axes[off + 2];
103
+ const py = lx * axes[off + 3] + ly * axes[off + 4] + lz * axes[off + 5];
104
+ const pz = lx * axes[off + 6] + ly * axes[off + 7] + lz * axes[off + 8];
105
+
106
+ return (px < 0 ? -px : px) * hx
107
+ + (py < 0 ? -py : py) * hy
108
+ + (pz < 0 ? -pz : pz) * hz;
109
+ }
110
+
111
+ // --- main -------------------------------------------------------------------
112
+
113
+ /**
114
+ *
115
+ * @param {number[]|Float64Array} out length >= BOX_BOX_OUT_LENGTH
116
+ * @param {number} ax centre x of A
117
+ * @param {number} ay
118
+ * @param {number} az
119
+ * @param {number} aqx A rotation quaternion x
120
+ * @param {number} aqy
121
+ * @param {number} aqz
122
+ * @param {number} aqw
123
+ * @param {number} ahx A half-extent x in body frame
124
+ * @param {number} ahy
125
+ * @param {number} ahz
126
+ * @param {number} bx centre x of B
127
+ * @param {number} by
128
+ * @param {number} bz
129
+ * @param {number} bqx
130
+ * @param {number} bqy
131
+ * @param {number} bqz
132
+ * @param {number} bqw
133
+ * @param {number} bhx
134
+ * @param {number} bhy
135
+ * @param {number} bhz
136
+ * @returns {boolean} true if overlap
137
+ */
138
+ export function box_box_manifold(
139
+ out,
140
+ ax, ay, az, aqx, aqy, aqz, aqw, ahx, ahy, ahz,
141
+ bx, by, bz, bqx, bqy, bqz, bqw, bhx, bhy, bhz
142
+ ) {
143
+ quat3_to_matrix3(scratch_axes_a, 0, aqx, aqy, aqz, aqw);
144
+ quat3_to_matrix3(scratch_axes_b, 0, bqx, bqy, bqz, bqw);
145
+
146
+ const ta = scratch_axes_a;
147
+ const tb = scratch_axes_b;
148
+
149
+ const dx = bx - ax;
150
+ const dy = by - ay;
151
+ const dz = bz - az;
152
+
153
+ // SAT track winning axis + source.
154
+ // source: 0..2 = A face normal, 3..5 = B face normal, 6..14 = edge cross.
155
+ let best_overlap = Infinity;
156
+ let best_nx = 0, best_ny = 0, best_nz = 0;
157
+ let best_source = -1;
158
+
159
+ function test_axis(lx, ly, lz, source) {
160
+ const len_sqr = lx * lx + ly * ly + lz * lz;
161
+
162
+ if (len_sqr < PARALLEL_EPS_SQR){
163
+ return false;
164
+ }
165
+
166
+ const inv_len = 1 / Math.sqrt(len_sqr);
167
+
168
+ const ux = lx * inv_len;
169
+ const uy = ly * inv_len;
170
+ const uz = lz * inv_len;
171
+
172
+ const rA = projected_half_extent(ta, 0, ahx, ahy, ahz, ux, uy, uz);
173
+ const rB = projected_half_extent(tb, 0, bhx, bhy, bhz, ux, uy, uz);
174
+
175
+ const proj = dx * ux + dy * uy + dz * uz;
176
+ const dist = proj < 0 ? -proj : proj;
177
+ const overlap = (rA + rB) - dist;
178
+
179
+ if (overlap < 0){
180
+ return true;
181
+ }
182
+
183
+ // Deadband: the first axis always wins; a later axis replaces it only
184
+ // if it reduces the overlap past the hysteresis band. This biases ties
185
+ // toward earlier-tested axes (A faces > B faces > edges) so aligned
186
+ // boxes pick a stable reference instead of flip-flopping on noise.
187
+ if (best_source === -1 || overlap < best_overlap - (best_overlap * TIE_REL + TIE_ABS)) {
188
+ best_overlap = overlap;
189
+ const sign = proj > 0 ? -1 : 1; // normal points B→A
190
+ best_nx = ux * sign;
191
+ best_ny = uy * sign;
192
+ best_nz = uz * sign;
193
+ best_source = source;
194
+ }
195
+ return false;
196
+ }
197
+
198
+ if (test_axis(ta[0], ta[1], ta[2], 0)) return false;
199
+ if (test_axis(ta[3], ta[4], ta[5], 1)) return false;
200
+ if (test_axis(ta[6], ta[7], ta[8], 2)) return false;
201
+ if (test_axis(tb[0], tb[1], tb[2], 3)) return false;
202
+ if (test_axis(tb[3], tb[4], tb[5], 4)) return false;
203
+ if (test_axis(tb[6], tb[7], tb[8], 5)) return false;
204
+
205
+ for (let i = 0; i < 3; i++) {
206
+ const i3 = i * 3;
207
+ const aix = ta[i3], aiy = ta[i3 + 1], aiz = ta[i3 + 2];
208
+
209
+ for (let j = 0; j < 3; j++) {
210
+ const j3 = j * 3;
211
+ const bjx = tb[j3], bjy = tb[j3 + 1], bjz = tb[j3 + 2];
212
+
213
+ const cx = aiy * bjz - aiz * bjy;
214
+ const cy = aiz * bjx - aix * bjz;
215
+ const cz = aix * bjy - aiy * bjx;
216
+
217
+ if (test_axis(cx, cy, cz, 6 + i3 + j)) return false;
218
+ }
219
+ }
220
+
221
+ // We have a contact. Output the normal.
222
+ const nx = best_nx, ny = best_ny, nz = best_nz;
223
+ out[0] = nx;
224
+ out[1] = ny;
225
+ out[2] = nz;
226
+
227
+ // ---- Edge-cross axis: closest-pair on the two involved edges ----
228
+ //
229
+ // When SAT identifies an edge-edge separating axis (source 6..14 =
230
+ // 6 + i*3 + j, where `i` is box A's local edge-axis index and
231
+ // `j` is box B's), the contact happens where one specific edge of
232
+ // A crosses (or is closest to) one specific edge of B. The earlier
233
+ // body-centre-midpoint fallback was sufficient for "we know they
234
+ // collide" but produced lever arms that confused the solver — for
235
+ // skewed-box stacks this led to slow drift.
236
+ //
237
+ // Procedure:
238
+ // 1. Decode (i, j) from `best_source`.
239
+ // 2. Among box A's 4 parallel edges along axis i, pick the one
240
+ // whose corner is most in the −n direction (closest to B).
241
+ // 3. Same for box B with +n direction.
242
+ // 4. `line3_closest_points_segment_segment` returns (s, t)
243
+ // parameters; reconstruct the world contact on each edge.
244
+ if (best_source >= 6) {
245
+ const ax_src = best_source - 6;
246
+ const i_a = (ax_src / 3) | 0;
247
+ const j_b = ax_src - i_a * 3;
248
+
249
+ // Edge directions in world.
250
+ const edge_a_dx = ta[i_a * 3];
251
+ const edge_a_dy = ta[i_a * 3 + 1];
252
+ const edge_a_dz = ta[i_a * 3 + 2];
253
+ const edge_b_dx = tb[j_b * 3];
254
+ const edge_b_dy = tb[j_b * 3 + 1];
255
+ const edge_b_dz = tb[j_b * 3 + 2];
256
+
257
+ // Edge half-extents (along the chosen axis).
258
+ const edge_a_half = i_a === 0 ? ahx : (i_a === 1 ? ahy : ahz);
259
+ const edge_b_half = j_b === 0 ? bhx : (j_b === 1 ? bhy : bhz);
260
+
261
+ // Perpendicular axes (the other two) and their half-extents.
262
+ let u_a_idx, v_a_idx;
263
+ if (i_a === 0) {
264
+ u_a_idx = 1;
265
+ v_a_idx = 2;
266
+ } else if (i_a === 1) {
267
+ u_a_idx = 2;
268
+ v_a_idx = 0;
269
+ } else {
270
+ u_a_idx = 0;
271
+ v_a_idx = 1;
272
+ }
273
+ const u_a_x = ta[u_a_idx * 3], u_a_y = ta[u_a_idx * 3 + 1], u_a_z = ta[u_a_idx * 3 + 2];
274
+ const v_a_x = ta[v_a_idx * 3], v_a_y = ta[v_a_idx * 3 + 1], v_a_z = ta[v_a_idx * 3 + 2];
275
+ const half_u_a = u_a_idx === 0 ? ahx : (u_a_idx === 1 ? ahy : ahz);
276
+ const half_v_a = v_a_idx === 0 ? ahx : (v_a_idx === 1 ? ahy : ahz);
277
+
278
+ let u_b_idx, v_b_idx;
279
+ if (j_b === 0) {
280
+ u_b_idx = 1;
281
+ v_b_idx = 2;
282
+ } else if (j_b === 1) {
283
+ u_b_idx = 2;
284
+ v_b_idx = 0;
285
+ } else {
286
+ u_b_idx = 0;
287
+ v_b_idx = 1;
288
+ }
289
+ const u_b_x = tb[u_b_idx * 3], u_b_y = tb[u_b_idx * 3 + 1], u_b_z = tb[u_b_idx * 3 + 2];
290
+ const v_b_x = tb[v_b_idx * 3], v_b_y = tb[v_b_idx * 3 + 1], v_b_z = tb[v_b_idx * 3 + 2];
291
+ const half_u_b = u_b_idx === 0 ? bhx : (u_b_idx === 1 ? bhy : bhz);
292
+ const half_v_b = v_b_idx === 0 ? bhx : (v_b_idx === 1 ? bhy : bhz);
293
+
294
+ // The contact normal `n` (= best_n) points B A. From A's
295
+ // perspective B is in the −n direction; pick the A-corner most
296
+ // in that direction. From B's perspective A is in +n; pick the
297
+ // B-corner most in +n.
298
+ const minus_n_dot_u_a = -(nx * u_a_x + ny * u_a_y + nz * u_a_z);
299
+ const minus_n_dot_v_a = -(nx * v_a_x + ny * v_a_y + nz * v_a_z);
300
+ const u_sign_a = minus_n_dot_u_a >= 0 ? 1 : -1;
301
+ const v_sign_a = minus_n_dot_v_a >= 0 ? 1 : -1;
302
+
303
+ const plus_n_dot_u_b = nx * u_b_x + ny * u_b_y + nz * u_b_z;
304
+ const plus_n_dot_v_b = nx * v_b_x + ny * v_b_y + nz * v_b_z;
305
+ const u_sign_b = plus_n_dot_u_b >= 0 ? 1 : -1;
306
+ const v_sign_b = plus_n_dot_v_b >= 0 ? 1 : -1;
307
+
308
+ // Box-A edge centre = A_centre + u_sign_a * half_u_a * u_a
309
+ // + v_sign_a * half_v_a * v_a.
310
+ const corner_a_cx = ax + u_a_x * u_sign_a * half_u_a + v_a_x * v_sign_a * half_v_a;
311
+ const corner_a_cy = ay + u_a_y * u_sign_a * half_u_a + v_a_y * v_sign_a * half_v_a;
312
+ const corner_a_cz = az + u_a_z * u_sign_a * half_u_a + v_a_z * v_sign_a * half_v_a;
313
+ const edge_a_p1_x = corner_a_cx - edge_a_dx * edge_a_half;
314
+ const edge_a_p1_y = corner_a_cy - edge_a_dy * edge_a_half;
315
+ const edge_a_p1_z = corner_a_cz - edge_a_dz * edge_a_half;
316
+ const edge_a_p2_x = corner_a_cx + edge_a_dx * edge_a_half;
317
+ const edge_a_p2_y = corner_a_cy + edge_a_dy * edge_a_half;
318
+ const edge_a_p2_z = corner_a_cz + edge_a_dz * edge_a_half;
319
+
320
+ const corner_b_cx = bx + u_b_x * u_sign_b * half_u_b + v_b_x * v_sign_b * half_v_b;
321
+ const corner_b_cy = by + u_b_y * u_sign_b * half_u_b + v_b_y * v_sign_b * half_v_b;
322
+ const corner_b_cz = bz + u_b_z * u_sign_b * half_u_b + v_b_z * v_sign_b * half_v_b;
323
+ const edge_b_p1_x = corner_b_cx - edge_b_dx * edge_b_half;
324
+ const edge_b_p1_y = corner_b_cy - edge_b_dy * edge_b_half;
325
+ const edge_b_p1_z = corner_b_cz - edge_b_dz * edge_b_half;
326
+ const edge_b_p2_x = corner_b_cx + edge_b_dx * edge_b_half;
327
+ const edge_b_p2_y = corner_b_cy + edge_b_dy * edge_b_half;
328
+ const edge_b_p2_z = corner_b_cz + edge_b_dz * edge_b_half;
329
+
330
+ line3_closest_points_segment_segment(
331
+ scratch_edge_st,
332
+ edge_a_p1_x, edge_a_p1_y, edge_a_p1_z, edge_a_p2_x, edge_a_p2_y, edge_a_p2_z,
333
+ edge_b_p1_x, edge_b_p1_y, edge_b_p1_z, edge_b_p2_x, edge_b_p2_y, edge_b_p2_z
334
+ );
335
+
336
+ const s = scratch_edge_st[0];
337
+ const t = scratch_edge_st[1];
338
+
339
+ const contact_a_x = edge_a_p1_x + s * (edge_a_p2_x - edge_a_p1_x);
340
+ const contact_a_y = edge_a_p1_y + s * (edge_a_p2_y - edge_a_p1_y);
341
+ const contact_a_z = edge_a_p1_z + s * (edge_a_p2_z - edge_a_p1_z);
342
+
343
+ const contact_b_x = edge_b_p1_x + t * (edge_b_p2_x - edge_b_p1_x);
344
+ const contact_b_y = edge_b_p1_y + t * (edge_b_p2_y - edge_b_p1_y);
345
+ const contact_b_z = edge_b_p1_z + t * (edge_b_p2_z - edge_b_p1_z);
346
+
347
+ out[3] = 1;
348
+ out[4] = contact_a_x;
349
+ out[5] = contact_a_y;
350
+ out[6] = contact_a_z;
351
+ out[7] = contact_b_x;
352
+ out[8] = contact_b_y;
353
+ out[9] = contact_b_z;
354
+ out[10] = best_overlap;
355
+
356
+ return true;
357
+ }
358
+
359
+ // ---- Face axis: face clipping ----
360
+ // Determine reference and incident.
361
+ const ref_is_A = best_source < 3;
362
+ // Reference axis index in the owning box (0..2).
363
+ const ref_axis_idx = ref_is_A ? best_source : best_source - 3;
364
+
365
+ // Reference box pose.
366
+ const ref_axes = ref_is_A ? ta : tb;
367
+ const inc_axes = ref_is_A ? tb : ta;
368
+ const ref_h_x = ref_is_A ? ahx : bhx;
369
+ const ref_h_y = ref_is_A ? ahy : bhy;
370
+ const ref_h_z = ref_is_A ? ahz : bhz;
371
+ const inc_h_x = ref_is_A ? bhx : ahx;
372
+ const inc_h_y = ref_is_A ? bhy : ahy;
373
+ const inc_h_z = ref_is_A ? bhz : ahz;
374
+ const ref_cx = ref_is_A ? ax : bx;
375
+ const ref_cy = ref_is_A ? ay : by;
376
+ const ref_cz = ref_is_A ? az : bz;
377
+ const inc_cx = ref_is_A ? bx : ax;
378
+ const inc_cy = ref_is_A ? by : ay;
379
+ const inc_cz = ref_is_A ? bz : az;
380
+
381
+ // Reference face outward normal in world: the face of the ref box facing
382
+ // the incident box. The contact normal points B→A; the ref face's
383
+ // outward normal must point toward the incident box (= -n if ref is A,
384
+ // = +n if ref is B).
385
+ const ref_out_nx = ref_is_A ? -nx : nx;
386
+ const ref_out_ny = ref_is_A ? -ny : ny;
387
+ const ref_out_nz = ref_is_A ? -nz : nz;
388
+
389
+ // Ref face's three axis-in-world directions: the axis-direction matching
390
+ // ref_axis_idx is the OUTWARD normal; the other two are the face tangents.
391
+ // Sign of the reference-face axis aligned with ref_out:
392
+ const ref_axis_world_x = ref_axes[ref_axis_idx * 3];
393
+ const ref_axis_world_y = ref_axes[ref_axis_idx * 3 + 1];
394
+ const ref_axis_world_z = ref_axes[ref_axis_idx * 3 + 2];
395
+ const ref_axis_dot = ref_axis_world_x * ref_out_nx
396
+ + ref_axis_world_y * ref_out_ny
397
+ + ref_axis_world_z * ref_out_nz;
398
+ const ref_axis_sign = ref_axis_dot >= 0 ? 1 : -1;
399
+
400
+ // Face plane: passes through `ref_cx + ref_axis * ref_axis_sign * ref_h_<axis>`,
401
+ // with outward normal = `ref_axis_world * ref_axis_sign`.
402
+ const ref_h_along_axis = ref_axis_idx === 0 ? ref_h_x : (ref_axis_idx === 1 ? ref_h_y : ref_h_z);
403
+ const ref_face_origin_x = ref_cx + ref_axis_world_x * ref_axis_sign * ref_h_along_axis;
404
+ const ref_face_origin_y = ref_cy + ref_axis_world_y * ref_axis_sign * ref_h_along_axis;
405
+ const ref_face_origin_z = ref_cz + ref_axis_world_z * ref_axis_sign * ref_h_along_axis;
406
+
407
+ // Reference face's two tangent axes (u, v) in world, with the corresponding half-extents.
408
+ let u_axis_idx, v_axis_idx;
409
+ if (ref_axis_idx === 0) {
410
+ u_axis_idx = 1;
411
+ v_axis_idx = 2;
412
+ } else if (ref_axis_idx === 1) {
413
+ u_axis_idx = 2;
414
+ v_axis_idx = 0;
415
+ } else {
416
+ u_axis_idx = 0;
417
+ v_axis_idx = 1;
418
+ }
419
+
420
+ const ux = ref_axes[u_axis_idx * 3], uy = ref_axes[u_axis_idx * 3 + 1], uz = ref_axes[u_axis_idx * 3 + 2];
421
+ const vx = ref_axes[v_axis_idx * 3], vy = ref_axes[v_axis_idx * 3 + 1], vz = ref_axes[v_axis_idx * 3 + 2];
422
+ const half_u = u_axis_idx === 0 ? ref_h_x : (u_axis_idx === 1 ? ref_h_y : ref_h_z);
423
+ const half_v = v_axis_idx === 0 ? ref_h_x : (v_axis_idx === 1 ? ref_h_y : ref_h_z);
424
+
425
+ // ---- Pick incident face on the OTHER box ----
426
+ // Its outward normal should be MOST antiparallel to the ref face outward normal
427
+ // (i.e., the face of the incident box that is "looking back" at the ref face).
428
+ let inc_axis_idx = 0, inc_axis_sign = 1;
429
+ let max_anti = -Infinity;
430
+ for (let i = 0; i < 3; i++) {
431
+ const iax = inc_axes[i * 3], iay = inc_axes[i * 3 + 1], iaz = inc_axes[i * 3 + 2];
432
+ const d_pos = iax * ref_out_nx + iay * ref_out_ny + iaz * ref_out_nz;
433
+ // We want dot -1, so most negative dot is the most anti-parallel
434
+ if (-d_pos > max_anti) {
435
+ max_anti = -d_pos;
436
+ inc_axis_idx = i;
437
+ inc_axis_sign = -1;
438
+ }
439
+ if (d_pos > max_anti) {
440
+ max_anti = d_pos;
441
+ inc_axis_idx = i;
442
+ inc_axis_sign = 1;
443
+ }
444
+ }
445
+ // Now the incident face outward normal must be antiparallel to ref_out_n.
446
+ // We chose inc_axis_sign as the sign of dot(inc_axis_dir, ref_out_n). The
447
+ // incident face's outward direction is the OPPOSITE sign (facing back at ref).
448
+ const inc_outward_sign = -inc_axis_sign;
449
+
450
+ const inc_h_along_axis = inc_axis_idx === 0 ? inc_h_x : (inc_axis_idx === 1 ? inc_h_y : inc_h_z);
451
+ // Incident face centre in world.
452
+ const inc_face_cx = inc_cx + inc_axes[inc_axis_idx * 3] * inc_outward_sign * inc_h_along_axis;
453
+ const inc_face_cy = inc_cy + inc_axes[inc_axis_idx * 3 + 1] * inc_outward_sign * inc_h_along_axis;
454
+ const inc_face_cz = inc_cz + inc_axes[inc_axis_idx * 3 + 2] * inc_outward_sign * inc_h_along_axis;
455
+
456
+ // Incident face's two tangent axes in world, with their half-extents.
457
+ let i_u_idx, i_v_idx;
458
+ if (inc_axis_idx === 0) {
459
+ i_u_idx = 1;
460
+ i_v_idx = 2;
461
+ } else if (inc_axis_idx === 1) {
462
+ i_u_idx = 2;
463
+ i_v_idx = 0;
464
+ } else {
465
+ i_u_idx = 0;
466
+ i_v_idx = 1;
467
+ }
468
+ const iux = inc_axes[i_u_idx * 3], iuy = inc_axes[i_u_idx * 3 + 1], iuz = inc_axes[i_u_idx * 3 + 2];
469
+ const ivx = inc_axes[i_v_idx * 3], ivy = inc_axes[i_v_idx * 3 + 1], ivz = inc_axes[i_v_idx * 3 + 2];
470
+ const i_half_u = i_u_idx === 0 ? inc_h_x : (i_u_idx === 1 ? inc_h_y : inc_h_z);
471
+ const i_half_v = i_v_idx === 0 ? inc_h_x : (i_v_idx === 1 ? inc_h_y : inc_h_z);
472
+
473
+ // Build incident face's 4 world corners (ordered CCW around the face).
474
+ const signs_u = [1, 1, -1, -1];
475
+ const signs_v = [-1, 1, 1, -1];
476
+ for (let i = 0; i < 4; i++) {
477
+ const su = signs_u[i] * i_half_u;
478
+ const sv = signs_v[i] * i_half_v;
479
+ incident_world[i * 3] = inc_face_cx + iux * su + ivx * sv;
480
+ incident_world[i * 3 + 1] = inc_face_cy + iuy * su + ivy * sv;
481
+ incident_world[i * 3 + 2] = inc_face_cz + iuz * su + ivz * sv;
482
+ }
483
+
484
+ // Project incident corners into ref-face uv coordinates.
485
+ // For each corner C: uv = ((C - ref_face_origin) · u_axis, ... · v_axis).
486
+ for (let i = 0; i < 4; i++) {
487
+ const ex = incident_world[i * 3] - ref_face_origin_x;
488
+ const ey = incident_world[i * 3 + 1] - ref_face_origin_y;
489
+ const ez = incident_world[i * 3 + 2] - ref_face_origin_z;
490
+ incident_uv[i * 2] = ex * ux + ey * uy + ez * uz;
491
+ incident_uv[i * 2 + 1] = ex * vx + ey * vy + ez * vz;
492
+ }
493
+
494
+ // Sutherland-Hodgman clip against the rectangle |u|<=half_u, |v|<=half_v.
495
+ // Apply 4 successive single-axis clips.
496
+ let n = 4;
497
+ // Copy into clipped_uv_in first.
498
+ for (let i = 0; i < n * 2; i++) {
499
+ clipped_uv_in[i] = incident_uv[i];
500
+ }
501
+
502
+ n = clip_against_axis_uv(clipped_uv_in, n, clipped_uv_out, 0, half_u, true);
503
+
504
+ if (n === 0) {
505
+ return out_empty(out);
506
+ }
507
+
508
+ n = clip_against_axis_uv(clipped_uv_out, n, clipped_uv_in, 0, -half_u, false);
509
+
510
+ if (n === 0) {
511
+ return out_empty(out);
512
+ }
513
+
514
+ n = clip_against_axis_uv(clipped_uv_in, n, clipped_uv_out, 1, half_v, true);
515
+
516
+ if (n === 0) {
517
+ return out_empty(out);
518
+ }
519
+
520
+ n = clip_against_axis_uv(clipped_uv_out, n, clipped_uv_in, 1, -half_v, false);
521
+
522
+ if (n === 0) {
523
+ return out_empty(out);
524
+ }
525
+
526
+ // Each surviving uv-point is on the ref face rectangle. We need to:
527
+ // 1. Map uv back to world → that's the contact point on the *incident* face
528
+ // (still on the inc face plane at that uv).
529
+ // 2. Compute depth = penetration along contact normal n (B→A).
530
+ // 3. The contact on the *reference* face is the projection of the inc-face
531
+ // point onto the reference plane along the contact normal.
532
+
533
+ // To re-derive the world position from a uv coord: we need to keep both the
534
+ // uv coord and the corresponding world point. But we just clipped uv-only,
535
+ // so the world position is the projection back. The depth resolves it:
536
+ //
537
+ // ref plane: normal = ref_outward, origin at ref_face_origin
538
+ // incident point world = ref_face_origin + u*u_axis + v*v_axis + (signed projection along ref_out)
539
+ //
540
+ // The component along ref_out for the original incident corner is what we lost
541
+ // by going to uv. We recompute it from the original incident face plane (which
542
+ // is at a fixed offset from ref): the inc corner's signed distance from the ref
543
+ // plane is `(corner - ref_face_origin) · ref_out_n`.
544
+ //
545
+ // After clipping in uv, we can't directly recover that distance without
546
+ // re-projecting onto the inc face plane. We do that here.
547
+
548
+ const ref_out_x = ref_axis_world_x * ref_axis_sign;
549
+ const ref_out_y = ref_axis_world_y * ref_axis_sign;
550
+ const ref_out_z = ref_axis_world_z * ref_axis_sign;
551
+
552
+ // Inc face plane (in world): point inc_face_c, normal inc_outward
553
+ // = inc_axes[inc_axis_idx*3..+2] * inc_outward_sign.
554
+ const inc_out_x = inc_axes[inc_axis_idx * 3] * inc_outward_sign;
555
+ const inc_out_y = inc_axes[inc_axis_idx * 3 + 1] * inc_outward_sign;
556
+ const inc_out_z = inc_axes[inc_axis_idx * 3 + 2] * inc_outward_sign;
557
+
558
+ // For a clipped uv point P_uv, the corresponding world point P_world on the
559
+ // incident face plane satisfies:
560
+ // P_world = ref_face_origin + u*u_axis + v*v_axis + t * ref_out for some t
561
+ // (P_world - inc_face_c) · inc_out = 0
562
+ // Substitute and solve for t. Let:
563
+ // X = ref_face_origin + u*u_axis + v*v_axis (a point on the line)
564
+ // t such that (X + t*ref_out - inc_face_c) · inc_out = 0
565
+ // t * (ref_out · inc_out) = (inc_face_c - X) · inc_out
566
+ const ref_dot_inc = ref_out_x * inc_out_x + ref_out_y * inc_out_y + ref_out_z * inc_out_z;
567
+ // Faces are nearly parallel → ref_dot_inc ≈ -1 (anti-parallel). Robust.
568
+
569
+ // Build candidates: for each clipped uv point.
570
+ let cand_count = 0;
571
+ const clipped_uv = clipped_uv_in;
572
+ for (let i = 0; i < n; i++) {
573
+ const u = clipped_uv[i * 2];
574
+ const v = clipped_uv[i * 2 + 1];
575
+
576
+ const x_x = ref_face_origin_x + u * ux + v * vx;
577
+ const x_y = ref_face_origin_y + u * uy + v * vy;
578
+ const x_z = ref_face_origin_z + u * uz + v * vz;
579
+
580
+ let world_inc_x, world_inc_y, world_inc_z;
581
+ if (ref_dot_inc !== 0) {
582
+ const num_x = inc_face_cx - x_x;
583
+ const num_y = inc_face_cy - x_y;
584
+ const num_z = inc_face_cz - x_z;
585
+ const t = (num_x * inc_out_x + num_y * inc_out_y + num_z * inc_out_z) / ref_dot_inc;
586
+ world_inc_x = x_x + ref_out_x * t;
587
+ world_inc_y = x_y + ref_out_y * t;
588
+ world_inc_z = x_z + ref_out_z * t;
589
+ } else {
590
+ // Faces orthogonal degenerate, fall back to uv point on ref plane.
591
+ world_inc_x = x_x;
592
+ world_inc_y = x_y;
593
+ world_inc_z = x_z;
594
+ }
595
+
596
+ // Penetration: signed distance of inc-face contact from the ref plane,
597
+ // measured into the ref box (= along -ref_out). Positive means penetrating.
598
+ const sep_x = world_inc_x - ref_face_origin_x;
599
+ const sep_y = world_inc_y - ref_face_origin_y;
600
+ const sep_z = world_inc_z - ref_face_origin_z;
601
+ const sep_along_ref_out = sep_x * ref_out_x + sep_y * ref_out_y + sep_z * ref_out_z;
602
+ const depth = -sep_along_ref_out;
603
+ if (depth < 0) continue;
604
+
605
+ candidates[cand_count * 4] = world_inc_x;
606
+ candidates[cand_count * 4 + 1] = world_inc_y;
607
+ candidates[cand_count * 4 + 2] = world_inc_z;
608
+ candidates[cand_count * 4 + 3] = depth;
609
+ cand_count++;
610
+ }
611
+
612
+ if (cand_count === 0) {
613
+ return out_empty(out);
614
+ }
615
+
616
+ // ---- Reduce to ≤ MAX_CONTACTS by best-deepest + perimeter ----
617
+ const kept = reduce_contacts(cand_count);
618
+
619
+ // ---- Emit: contact-on-incident is the candidate's world point;
620
+ // contact-on-reference is the same point projected onto the ref plane.
621
+ out[3] = kept;
622
+ for (let k = 0; k < kept; k++) {
623
+ const px = candidates[k * 4];
624
+ const py = candidates[k * 4 + 1];
625
+ const pz = candidates[k * 4 + 2];
626
+ const depth = candidates[k * 4 + 3];
627
+
628
+ // ref-side contact = project onto ref plane along ref_out.
629
+ const dist_to_plane = (px - ref_face_origin_x) * ref_out_x
630
+ + (py - ref_face_origin_y) * ref_out_y
631
+ + (pz - ref_face_origin_z) * ref_out_z;
632
+ const rpx = px - ref_out_x * dist_to_plane;
633
+ const rpy = py - ref_out_y * dist_to_plane;
634
+ const rpz = pz - ref_out_z * dist_to_plane;
635
+
636
+ let wax, way, waz, wbx_, wby_, wbz_;
637
+ if (ref_is_A) {
638
+ wax = rpx;
639
+ way = rpy;
640
+ waz = rpz;
641
+ wbx_ = px;
642
+ wby_ = py;
643
+ wbz_ = pz;
644
+ } else {
645
+ wax = px;
646
+ way = py;
647
+ waz = pz;
648
+ wbx_ = rpx;
649
+ wby_ = rpy;
650
+ wbz_ = rpz;
651
+ }
652
+
653
+ const base = 4 + k * CONTACT_STRIDE;
654
+ out[base] = wax;
655
+ out[base + 1] = way;
656
+ out[base + 2] = waz;
657
+ out[base + 3] = wbx_;
658
+ out[base + 4] = wby_;
659
+ out[base + 5] = wbz_;
660
+ out[base + 6] = depth;
661
+ }
662
+
663
+ return true;
664
+ }
665
+
666
+ function out_empty(out) {
667
+ out[3] = 0;
668
+ return true; // overlap exists per SAT, just no clipped manifold
669
+ }
670
+
671
+ /**
672
+ * In-place reduction of `candidates` to at most {@link MAX_CONTACTS}:
673
+ * 1. Sort by depth descending; deepest stays at index 0.
674
+ * 2. From the remaining, greedily pick the points that maximise the spread
675
+ * (sum of squared distances to already-kept points). This approximates
676
+ * the maximum-area heuristic without needing the actual area.
677
+ *
678
+ * @param {number} n input count
679
+ * @returns {number} kept count (min(n, MAX_CONTACTS))
680
+ */
681
+ function reduce_contacts(n) {
682
+ if (n <= MAX_CONTACTS) return n;
683
+
684
+ // Find deepest, swap into slot 0.
685
+ let deepest_idx = 0;
686
+ let deepest_val = candidates[3];
687
+ for (let i = 1; i < n; i++) {
688
+
689
+ if (candidates[i * 4 + 3] > deepest_val) {
690
+ deepest_val = candidates[i * 4 + 3];
691
+ deepest_idx = i;
692
+ }
693
+
694
+ }
695
+
696
+ if (deepest_idx !== 0) {
697
+ swap_candidate(0, deepest_idx);
698
+ }
699
+
700
+ // Greedy: for slot k in 1..MAX_CONTACTS-1, pick the remaining candidate
701
+ // whose min-distance-sq-to-already-kept-set is largest.
702
+ for (let k = 1; k < MAX_CONTACTS; k++) {
703
+
704
+ let best_score = -1;
705
+ let best_i = -1;
706
+
707
+ for (let i = k; i < n; i++) {
708
+ let min_d2 = Infinity;
709
+
710
+ for (let j = 0; j < k; j++) {
711
+ const dx = candidates[i * 4] - candidates[j * 4];
712
+ const dy = candidates[i * 4 + 1] - candidates[j * 4 + 1];
713
+ const dz = candidates[i * 4 + 2] - candidates[j * 4 + 2];
714
+ const d2 = dx * dx + dy * dy + dz * dz;
715
+ if (d2 < min_d2) min_d2 = d2;
716
+ }
717
+
718
+ if (min_d2 > best_score) {
719
+ best_score = min_d2;
720
+ best_i = i;
721
+ }
722
+
723
+ }
724
+
725
+ if (best_i !== k) {
726
+ swap_candidate(k, best_i);
727
+ }
728
+ }
729
+ return MAX_CONTACTS;
730
+ }
731
+
732
+ function swap_candidate(a, b) {
733
+ const a4 = a * 4;
734
+ const b4 = b * 4;
735
+
736
+ const ax = candidates[a4];
737
+ const ay = candidates[a4 + 1];
738
+ const az = candidates[a4 + 2];
739
+ const ad = candidates[a4 + 3];
740
+
741
+ candidates[a4] = candidates[b4];
742
+ candidates[a4 + 1] = candidates[b4 + 1];
743
+ candidates[a4 + 2] = candidates[b4 + 2];
744
+ candidates[a4 + 3] = candidates[b4 + 3];
745
+
746
+ candidates[b4] = ax;
747
+ candidates[b4 + 1] = ay;
748
+ candidates[b4 + 2] = az;
749
+ candidates[b4 + 3] = ad;
750
+ }