# Physics Engine Review: meep vs. Jolt

A deep technical comparison of the meep in-house rigid-body engine
(`H:/git/moh/app/src/mir-engine/meep/src/engine/physics/`) against
**Jolt Physics** (https://github.com/jrouwe/JoltPhysics).

This review respects PLAN.md's documented out-of-scope decisions (pure JS,
no SIMD, no SAB, no multi-threaded solver, action-log netcode). Citations
on our side use `path:line` relative to the package root; Jolt citations
use file + class/function name.

---

## 1. Overall Architecture

### Pipeline shape

| Stage | meep | Jolt |
|---|---|---|
| Integrate velocity (gravity, forces) | `PhysicsSystem.fixedUpdate` stage 1 | `JobApplyGravity` |
| Broadphase refit | Stage 2 — per-leaf `node_move_aabb` with velocity-padded fat AABB | `BroadPhaseQuadTree::UpdatePrepare` + `UpdateFinalize` (background tree rebuild w/ atomic swap) |
| Pair generation | Stage 3 — `generate_pairs.js`, awake-list driven, leaf query into both BVHs | `JobFindCollisions` over active bodies |
| Wake propagation | Stage 4 — explicit `__wake_pairs` | implicit via island building / `BodyManager::ActivateBodies` |
| Narrowphase | Stage 5 — `narrowphase_step.js` per body-pair | `CollisionDispatch::sCollideShapeVsShape` table dispatch |
| Island build | Stage 6 — `IslandBuilder.build()` | `IslandBuilder::Build()` + `LargeIslandSplitter` |
| Solver | Stage 7 — `solve_contacts.js`, 10 velocity iterations, Baumgarte folded in | `SolveVelocityConstraints` (10×) + **separate** `SolvePositionConstraints` (2×) |
| Position integration | Stage 8 — `integrate_position.js` | `JobIntegrateVelocity` |
| Sleep test | Stage 9 — `__sleep_test`, per-island atomic | `Body::UpdateSleepStateInternal`, per-body sleep-point displacement, island-level dispatch |
| Event diff / advance | Stage 10–11 — `diff_manifolds`, `manifolds.advance_frame()` | `ContactConstraintManager::FinalizeContactCacheAndCallContactPointRemovedCallbacks` |

The single most consequential structural divergence is **stage 7**: we
fold position correction (Baumgarte) into the same velocity iterations
that handle restitution + friction. Jolt runs a **second outer pass**
(`SolvePositionConstraints`, default `mNumPositionSteps = 2`) that
operates as split-impulse — see §3 "Split impulse".

### Data layout — body pool

Both engines mirror the same conceptual model:

| Aspect | meep `BodyStorage` | Jolt `BodyManager` |
|---|---|---|
| ID encoding | 24-bit index ǁ 8-bit generation (`body/BodyStorage.js:11-19`) | 23-bit index ǁ 8-bit sequence ǁ 1 reserved bit (`Body/BodyID.h`, `cMaxBodyIndex = 0x7fffff`, `cSequenceNumberShift = 23`) |
| Slot reuse policy | Min-heap of free indices for deterministic reuse (`body/BodyStorage.js:154-176`) | First-free; sequence number bumped on destroy |
| Active list | Dense `Uint32Array __awake_list` + reverse map `__awake_pos` (`body/BodyStorage.js:101-103`) | `BodyID * mActiveBodies[cBodyTypeCount]` + `atomic<uint32> mNumActiveBodies[cBodyTypeCount]` |
| Body storage | SoA — `__entities`, `__generations`, `__kinds`, `__flags` as parallel typed arrays (`body/BodyStorage.js:92-95`) | AoS — `Array<Body *>` of pointers; bodies allocated individually on heap |
| Iteration | `for (let i = 0; i < awake_count; i++) { const idx = awake_at(i); ... }` (`generate_pairs.js:50-51`) | `BodyID *ab = GetActiveBodiesUnsafe(EBodyType::RigidBody); for (uint32 i = 0; i < n; ++i) ...` |

**Where we diverge in our favour:** SoA in `BodyStorage` is structurally
better-suited to streaming reads of cold flags / kinds / generations
than Jolt's pointer-chase. The price: per-body mutable state
(`linearVelocity`, `angularVelocity`, accumulators) still lives on
`RigidBody` objects, so the SoA wins are concentrated at the body-identity
side (allocate, wake, sleep, generation check), not the hot solver path.
Jolt's pointer-chase is mitigated by `Body` being contiguous-allocated
in chunks via a fixed-block pool.

**Where Jolt diverges:** the 1 reserved bit in `BodyID` is for the
broadphase to mark sleeping bodies in-tree without touching the body
object. We don't need it because sleeping bodies are evicted from the
awake list, and the manifold cache decides whether a slot deserves a
solver visit independently.

### Broadphase

| | meep | Jolt |
|---|---|---|
| Tree type | Two BVH2 (binary) | `BroadPhaseQuadTree` (4-ary), one per object layer |
| Layer model | One static + one dynamic BVH | Multiple `BroadPhaseLayer` → multiple quad trees; `ObjectLayerPairFilter` for per-pair allow/deny |
| Refit on motion | Velocity-padded fat AABB (`broadphase/compute_fat_world_aabb.js:14-18`: `FAT_LINEAR = 0.05 m`, `FAT_VELOCITY_MULTIPLIER = 2 × |v| × dt`) | Bounding boxes only widen; no velocity pad; full tree rebuild in background each step |
| Update strategy | In-place `node_move_aabb`; tree mutated immediately | Double-buffered atomic tree swap ("one-way tree swap" per Jolt GDC 2022) |
| Query | Per-leaf `bvh_query_user_data_overlaps_aabb` against both trees | `CastAABoxNoLock` etc. via collector pattern |

The two-tree split is sound — both engines exploit it to skip
static-vs-static. Where Jolt goes further: `BroadPhaseLayer` is a
**multi-tree partition** (typically static, dynamic, kinematic,
debris) with a `ObjectVsBroadPhaseLayerFilter` short-circuiting whole
trees that can't possibly collide. Our layer/mask check happens
later, in the pair filter callback. Cost: every static body is paid
for at broadphase query time even if no dynamic could ever collide
with it.

### Solver architecture

| | meep | Jolt |
|---|---|---|
| Solver type | PGS (Projected Gauss-Seidel) with sequential impulse + warm-start | PGS with warm-start, **two-pass** velocity + position |
| Velocity iterations | 10 (`solver/solve_contacts.js:33`) | 10 (`mNumVelocitySteps`) |
| Position iterations | 0 (folded into velocity loop via Baumgarte bias) | 2 (`mNumPositionSteps`) — separate `SolvePositionConstraints` pass |
| Sub-stepping (TGS) | No (PLAN.md documents failed attempt) | No — but `inCollisionSteps` parameter to `Update()` is a coarser collision-detection sub-step, not constraint substepping |
| Baumgarte | β = 0.2 inside velocity solve, capped at `MAX_BAUMGARTE_BIAS = 3 m/s` (`solver/solve_contacts.js:62`) | β = 0.2 in `SolvePositionConstraint`, applied as pseudo-velocity to positions then discarded |
| Restitution | Velocity bias inside velocity iterations, suppressed below 1 m/s (`solver/solve_contacts.js:69`) | One-shot velocity bias, `mMinVelocityForRestitution = 1.0` |
| Penetration slop | 0.005 m (`solver/solve_contacts.js:48`) | 0.02 m (`mPenetrationSlop`) |
| Friction | Coulomb disk-clamp in 2-D tangent plane (`friction_cone.js`) | Two scalar friction constraints (t1, t2) coupled via a single friction limit `μ * j_n` |

Jolt is **not** TGS-based — PLAN.md is correct to consider TGS deferred
work, but the way to do it well is what Jolt **does have**:
split-impulse, where positions get a separate solver pass driven by a
pseudo-velocity, decoupled from `mLinearVelocity`/`mAngularVelocity`.
This is the missing primitive on the path to TGS. Details in §3.

### Sleep system

| | meep | Jolt |
|---|---|---|
| Granularity | Per-island atomic (`PhysicsSystem.js:942-1006`) | Per-body decision aggregated to per-island |
| Test signal | `max(|v|² + |ω|²)` across island, accumulated dt below threshold (`PhysicsSystem.js:967-995`) | Sphere-fit accumulated displacement of 3 body-frame "sleep points" (`Body::UpdateSleepStateInternal` — measures actual movement across bbox corners, captures pure rotation too) |
| Wake propagation | Explicit walk over `sleep_group_next` chain in `__wake_body` (`PhysicsSystem.js:707-735`) — circular doubly-linked list |  Activation listener pattern + bodies in same island activate together implicitly through `ActivateBodies` |
| Sleep timer field | `RigidBody.sleep_timer` (per body) | `MotionProperties::AccumulateSleepTime` |

**Notable divergence:** Jolt's sleep signal is **point displacement**
across the body's bounding-box corners, not velocity². This is
materially more robust on pure-rotation cases: a thin rod spinning
about its long axis has tiny linear velocity but nonzero `|ω|`; our
test catches that (we include `+ av·av`), but Jolt's catches the case
where rotation alone moves a corner — even if neither `|v|` nor `|ω|`
alone is large. Practically, our test is a close approximation; the
question is whether the failure modes Jolt's resolves (spinning
elongated bodies that we'd sleep too early) actually arise in
gameplay. For most game scenarios the equivalence is good enough.

### Threading model

Jolt is fundamentally a job-system engine — `JobApplyGravity`,
`JobFindCollisions`, `JobBuildIslandsFromConstraints`,
`JobSolveVelocityConstraints` × N, `JobSolvePositionConstraints` × N
are all parallel jobs, and `LargeIslandSplitter` exists specifically
to subdivide big islands so multiple workers can solve a single island
in parallel. PLAN.md explicitly excludes worker-based solving until
`SharedArrayBuffer` is universally usable; this is a deliberate
tradeoff and not a gap.

What is **not** a deliberate tradeoff: even single-threaded, the
inability to parallelise within a tall stack means the largest pile
in a scene is the latency floor for the whole frame. The island data
layout we have (sorted CSR, deterministic by min root) is **ready** to
support split-island workers later — that's an underlying
architectural good.

---

## 2. Specific Algorithms and Tradeoffs

### Body storage / ID stability

| Aspect | meep | Jolt |
|---|---|---|
| Index bits | 24 → 16M live bodies | 23 → 8M live bodies |
| Generation/sequence bits | 8 (wraps mod 256) | 8 (wraps mod 256) |
| Generation bump on free | `body/BodyStorage.js:200` — `(generations[i] + 1) & 0xFF` | `BodyManager::GetNextSequenceNumber` |
| Reuse policy | **Min-heap** of free indices (`body/BodyStorage.js:405-426`) | First-free / lowest-index-wins via simple iteration |

The min-heap is genuinely interesting — Jolt doesn't formalise this.
Determinism for `BodyID` reuse in Jolt depends on call order; ours
depends only on the allocation/free sequence, which is the right
property for action-log replication.

### Broadphase

| Aspect | meep | Jolt |
|---|---|---|
| File | `broadphase/generate_pairs.js`, `broadphase/compute_fat_world_aabb.js` | `BroadPhase/BroadPhaseQuadTree.cpp`, `BroadPhase/QuadTree.cpp` |
| Tree arity | Binary BVH | 4-ary quad tree (better SIMD-pack on Jolt; for us 2-ary is fine) |
| Update model | Mutate-in-place | Background rebuild + atomic swap |
| Fat AABB philosophy | Pad at insert/refit time; cheap O(1) test against fattened envelope on each move | No pad; tree-widen + periodic full rebuild |

Tradeoff summary: our model is simpler and lower-latency per body
move. Jolt's model is friendlier to multithreaded readers (queries
can run against the stable side of the swap while writers update the
other side). Pure-JS, single-threaded, our model wins on simplicity
and zero-allocation refit cost.

### Narrowphase pair dispatch

| | meep | Jolt |
|---|---|---|
| Dispatch shape | Cascading `if (isSphereA && isBoxB) ...` branches inside `dispatch_pair` (`narrowphase/narrowphase_step.js:192-353`) | 2-D function-pointer table `sCollideShape[NumSubShapeTypes][NumSubShapeTypes]` (`Collision/CollisionDispatch.cpp`) |
| Symmetry handling | Explicit `(isSphereA && isBoxB) || (isBoxA && isSphereB)` blocks with swap on each handler | `sReversedCollideShape` wraps the registered direction's handler with a `ReversedCollector` swap |
| Adding new shape pair | Modify the cascade in `narrowphase_step.js` + write a new module like `sphere_box_contact.js` | Register a function pointer for the pair on each side (or one + reversed) at init |
| Concave dispatch | Inline branch on `shape.is_convex === false` (`narrowphase/narrowphase_step.js:368-501`) | `CollideShape` for `MeshShape` / `HeightFieldShape` calls into `CollideConvexVsTriangles` per filtered triangle from the shape's internal BVH |

Both engines specialise primitive pair handlers (sphere-sphere,
sphere-box, capsule-capsule, capsule-sphere, capsule-box, box-box for
us; equivalent for Jolt). The structural difference is the dispatch
table — Jolt is genuinely cleaner here. See §4 "Simplicity & uniformity".

### GJK / EPA

| | meep `gjk/gjk.js` | Jolt `Geometry/GJKClosestPoint.h` |
|---|---|---|
| Reference | Kevin Moran's `GJK.h` (cited at file top) | Gino van den Bergen "Fast and Robust GJK" |
| Simplex update | Edge-based Voronoi check using cross products (`gjk/gjk.js:163-265`) — explicit cases for triangle and tetrahedron | Christer Ericson-style sub-simplex closest-point with bitset of surviving vertices (`uint32 set`) |
| Iteration cap | 64 (`gjk/gjk.js:4`) | None visible — terminates on tolerance only |
| Separating-axis cache between calls | **No** — initial dir always `(1, 0, 0)` (`gjk/gjk.js:42`) | **Yes** — `ioV` parameter carries the last separating axis in/out, providing frame coherence |
| Tolerance | Exact zero on degenerate case + 64-iter cap; no relative tolerance | `inTolerance` parameter, default `cDefaultCollisionTolerance = 1e-4` |
| Convergence criteria | Iteration cap + dir-becomes-zero | `v_len_sq <= tolerance_sq`, `v_len_sq <= FLT_EPSILON * GetMaxYLengthSq()`, `prev_v_len_sq - v_len_sq <= FLT_EPSILON * prev_v_len_sq` |

**The missing separating-axis cache is a real opportunity.** See §3
for the detailed comparison.

| EPA | meep `gjk/expanding_polytope_algorithm.js` | Jolt `Geometry/EPAPenetrationDepth.h` |
|---|---|---|
| Initial polytope | 4-vertex tetrahedron from GJK final simplex (`expanding_polytope_algorithm.js:103-106`) | Variable — 1/2/3/4-point start; manufactures extra supports if simplex incomplete |
| Closest-face search | Linear scan over `num_faces` every iteration (`expanding_polytope_algorithm.js:118-126`) | Priority queue (`PeekClosestTriangleInQueue`, `PopClosestTriangleFromQueue`) |
| Tolerance | Absolute `EPA_TOLERANCE = 0.0001` (`expanding_polytope_algorithm.js:10`) | Relative: `dist_sq - t->mClosestLenSq < t->mClosestLenSq * inTolerance` |
| Max faces / edges | `EPA_MAX_NUM_FACES = 64`, `EPA_MAX_NUM_LOOSE_EDGES = 32` (hard cap, returns degenerate result) (`expanding_polytope_algorithm.js:11-12`) | `EPAConvexHullBuilder` with `cMaxPoints` |
| Behaviour at cap | Returns closest-face approximation (`expanding_polytope_algorithm.js:329-346`) | Same; also detects "hull defects" and bails |

### Solver

Covered in §1 architecturally. Key per-algorithm tradeoffs:

| | meep | Jolt |
|---|---|---|
| Lambda accumulation pattern | Clamp `sum = j_n + λ; new_j_n = max(sum, 0); delta = new_j_n - j_n` (`solver/solve_contacts.js:530-535`) | Same: `Clamp(mTotalLambda + lambda, inMinLambda, inMaxLambda)`, apply delta |
| Tangent basis | Least-aligned world axis trick (`solver/solve_contacts.js:115-143`) | `Vec3::sGetNormalizedPerpendicular(inWorldSpaceAxis)` similar |
| Friction coupling | Disk clamp in (t1, t2) plane via `friction_cone_clamp` | Effectively same — friction limit `μ * j_n` applied to combined `(t1, t2)` magnitude |
| Friction combine | Geometric mean `sqrt(μA * μB)` (`solver/solve_contacts.js:161-163`) | Configurable; default is the same |
| Restitution combine | `max(eA, eB)` (`solver/solve_contacts.js:171-174`) | Configurable; default is `max` or via `ContactListener::OnContactAdded` |

### Manifold caching

| | meep `contact/ManifoldStore.js` | Jolt `ContactConstraintManager.h/cpp` |
|---|---|---|
| Max contacts per slot | 4 (`MAX_CONTACTS_PER_MANIFOLD`) | 4 (`MaxContactPoints`) |
| Per-contact data | 13 doubles: 2× world point, 3 normal, depth, 3 accumulated impulses (`contact/ManifoldStore.js:30`) | `CachedContactPoint` = 36 bytes: 2× `Float3` local position, 1 float non-pen impulse, 2 floats friction impulse (Jolt stores **local** positions, recomputed each frame) |
| Persistence key | Canonical `(idA, idB)` via `PairUint32Map` (Robin Hood + Fibonacci hash) | `BodyPairMap::KeyValue` with `Body *` pair |
| Cross-frame matching | Slot persists; new contact set overwrites in-place by index | Local-position-matching: `ccp->mPosition1.IsClose(p1_ls, mContactPointPreserveLambdaMaxDistSq)` — impulses transferred to matching points only |
| Eviction | Touched-flag grace counter (2 frames untouched → release) (`contact/ManifoldStore.js:344-373`) | Body-pair grace via `mBodyPairCacheMaxDeltaPositionSq` |

**Important divergence:** Jolt stores contact points in **local** body
space and matches **points** across frames; we store **world** space
and inherit warm-start by **index** in the manifold. Index-based
matching is faster but breaks when contact-point identity drifts (e.g.
a box sliding across another box — contact index 0 may be a different
geometric corner this frame than last). Real-world impact: warm-start
quality degrades on sliding contacts. For a quasi-static stack
(corners stay put across frames) the two are equivalent. The bench's
4-cube stack working cleanly is consistent with this.

### Sleep semantics

Covered in §1. Worth restating: Jolt's per-body sleep test is
**movement of body-frame sleep points** integrated over a window. Our
test is `max(|v|² + |ω|²)` over an island. Both have an island-atomic
sleep / wake structure. Ours has the explicit `sleep_group_next`
linked list for instant wake propagation — that's a genuine engineering
investment for the "100-block tower base-knock" scenario described in
PLAN.md. Jolt achieves equivalent semantics by re-running island
detection each frame (cheap because the broadphase tree is already
maintained).

### Islands

| | meep `island/IslandBuilder.js` + `union_find.js` | Jolt `IslandBuilder.cpp` |
|---|---|---|
| Build algorithm | Union-find over awake bodies + touched non-sensor manifolds; path halving + union by min-index (`core/collection/union-find/union_find.js:45-76`) | Union-find via `BodyLink::mLinkedTo` atomic; linked-to-lowest-index |
| Output | CSR-style: `body_data` + `body_offsets`, `contact_data` + `contact_offsets`; both sorted ascending within islands | CSR-style: `BodyID *mBodyIslands` + `mBodyIslandEnds`, similar for constraints |
| Anchors | Static/Kinematic bodies are anchors only — do not merge islands (`island/IslandBuilder.js:172`) | Same |
| Determinism | Union by min-index + sort guarantees stable output across runs (PLAN.md determinism contract) | Atomic union may have ordering races in MT mode |
| Multi-threaded split | No (out of scope) | `LargeIslandSplitter` divides islands >128 constraints into ≤32 parallel groups by body-disjoint sets |

### CCD

| | meep | Jolt |
|---|---|---|
| Default | Speculative margin via velocity-padded fat AABB | Discrete |
| Optional | None | `EMotionQuality::LinearCast` per body — linear shape sweep, "time steals" body to first impact |
| Threshold to activate | N/A | `mLinearCastThreshold = 0.75` (fraction of inner radius/step) |
| Max penetration on cast hit | N/A | `mLinearCastMaxPenetration = 0.25` |

PLAN.md documents the falling-tower reproducer (180/1000 bodies tunnel
through a 1cm floor) and proposes a per-body linear shape-cast as the
fix. That maps almost identically to Jolt's `LinearCast` motion
quality. Worth scoping the same opt-in field on `RigidBodyFlags` if
the gameplay budget needs it.

### Concave / triangle mesh

| | meep | Jolt |
|---|---|---|
| Mesh shape | `MeshShape3D` — face index list + `Vector3` vertex buffer; `is_convex = false` | `MeshShape` — compressed BVH of triangles, leaf triangles with materials + active-edge flags |
| Heightmap | `HeightMapShape3D` — Catmull-Rom sampled grid (`narrowphase/decomposition/heightmap_enumerate_triangles.js`) | `HeightFieldShape` |
| Enumeration | Linear O(N) scan with per-tri AABB overlap (`mesh_enumerate_triangles`) — no internal BVH on `MeshShape3D` | Internal compressed BVH on `MeshShape`, descended for the query AABB |
| Per-triangle narrowphase | GJK + EPA every triangle (`narrowphase/narrowphase_step.js:476-481`) — hits `Triangle3D`'s degenerate face-normal support | Specialised: `CollideSphereVsTriangles` uses `ClosestPoint::GetClosestPointOnTriangle` (closed-form). Other primitives go through `CollideConvexVsTriangles` which is GJK+EPA but with **active-edge fix-normal** to suppress ghost contacts at internal edges |
| Active-edge handling | None | `EActiveEdgeMode::CollideOnlyWithActive`, `mActiveEdgeCosThresholdAngle` (~5°), `ActiveEdges::FixNormal` rewrites the contact normal to the triangle face normal when GJK lands on an inactive edge |

This is the largest correctness gap and PLAN.md correctly flags it as
the biggest accuracy opportunity. See §3 for the deep dive.

### Queries (raycast / shape-cast / overlap)

| | meep | Jolt |
|---|---|---|
| Raycast | `queries/raycast.js` — single nearest hit across both BVHs | `NarrowPhaseQuery::CastRay` + `RayCastCollector` callback pattern |
| Shape cast | `queries/shape_cast.js` — broadphase swept AABB, per-candidate AABB-slab narrowing, coarse step, GJK bisection, MPR for normal recovery (`shape_cast.js`) | `NarrowPhaseQuery::CastShape` — dispatch table `sCastShape[NumSubShapeTypes][NumSubShapeTypes]`, specialised per shape-pair |
| Overlap | `queries/overlap_shape.js` — broadphase + GJK overlap, fills Uint32Array of body ids | `NarrowPhaseQuery::CollideShape` — collector-based |
| Filter model | Single callback `pair_filter(idA, idB)` + optional `filter?` per query | Four-stage: `BroadPhaseLayerFilter`, `ObjectLayerFilter`, `BodyFilter` (`ShouldCollide` + `ShouldCollideLocked`), `ShapeFilter` |

The collector pattern in Jolt is the cleanest extension point: a
caller asks "give me all hits and let me decide" or "give me the
closest" or "stop after the first" by choosing a collector
implementation. We expose nearest-only for raycast. Worth noting
this as a Section 4 simplicity tension: our API is narrower but
forces a separate query function per use case, vs. one query × N
collectors.

---

## 3. In-depth comparison — correctness and improvement opportunities

This section picks 8 algorithmic touchpoints, reads both engines'
actual code, and identifies bugs / divergences / opportunities.

### 3.1 GJK separating-axis cache (frame coherence)

**Files:** `gjk/gjk.js`, Jolt's `Geometry/GJKClosestPoint.h`.

Jolt's `Intersects` signature:
```cpp
template <typename A, typename B>
bool Intersects(const A &inA, const B &inB, float inTolerance, Vec3 &ioV)
```

The `ioV` is the **in/out** separating axis. The caller passes in the
last known direction (typically cached on the contact pair), GJK refines
it, and writes the result back. Two consequences:

1. **First-iteration quality:** with a good `ioV` from last frame, GJK
   often converges in 1–2 iterations because the seed direction is
   already close to the true closest-point direction.
2. **Early miss:** if `ioV` from last frame still gives a negative dot
   on the very first support point, the call returns `false` after **one**
   support evaluation.

Our `gjk/gjk.js:42` starts every call with the constant `(1, 0, 0)`:

```js
minkowski_support(
    simplex, 6,
    shape_a, shape_b,
    1, 0, 0
);
```

For a single physics step the broadphase already pruned non-overlapping
pairs, so most GJK calls happen on pairs that already are or have just
been overlapping — and most of those will overlap again next frame.
We do nothing with that information. The `ManifoldStore` already has a
slot per pair; it's the natural place to cache the last separating axis.

**Concrete improvement:** add 3 doubles (`axis_x/y/z`) to the manifold
slot's per-slot data, write the EPA-output normal there at end of
narrowphase, and seed GJK's initial direction with it next frame.
Cost: 24 bytes/slot. Benefit: ~5–10× iteration-count reduction on
established contacts (Jolt's documented experience and standard GJK
practice).

This is a particularly high-value change because EPA's hot loop is
the dominant cost on non-trivial shapes — fewer GJK iterations means
fewer simplex updates, but more importantly, **better seed for EPA**
when GJK terminates with `intersecting = true`. EPA's iteration count
is also sensitive to where the initial polytope starts.

### 3.2 Split-impulse architecture (blocker for TGS)

**Files:** `solver/solve_contacts.js:441-450`, Jolt's
`ContactConstraintManager.cpp`, `ConstraintPart/AxisConstraintPart.h`.

PLAN.md is right: this is the architectural blocker. Worth walking
through Jolt's setup so the shape of the change is concrete.

Jolt's `SolvePositionConstraints` runs **after** the velocity loop:

```cpp
// pseudo-code, paraphrased from AxisConstraintPart::SolvePositionConstraint
separation = max(Vec3(p2 - p1).Dot(ws_normal) + inSettings.mPenetrationSlop,
                 -inSettings.mMaxPenetrationDistance);
lambda = -mEffectiveMass * inBaumgarte * separation;
// "Directly integrate velocity change for one time step,
//  then integrate position, and discard the velocity change."
// — comment from Jolt
```

The key sentence is the comment Jolt's author embedded. Position
correction uses a **pseudo-velocity** computed from the geometric
separation, applies it to positions for one frame, and discards.
The body's real `mLinearVelocity` / `mAngularVelocity` are
**untouched** by position correction.

Compare ours at `solver/solve_contacts.js:441-450`:

```js
if (depth > PENETRATION_SLOP) {
    bias = -BAUMGARTE_BETA / dt * (depth - PENETRATION_SLOP);
    ...
    if (bias < -MAX_BAUMGARTE_BIAS) bias = -MAX_BAUMGARTE_BIAS;
}
// Restitution
if (vn_pre < -RESTITUTION_VELOCITY_THRESHOLD) {
    bias += restitution_combined * vn_pre;
}
pre[pre_off + 15] = bias;
```

We bake position correction into `bias_n` which is then used inside
the velocity solve at lines 530-535:

```js
const lambda_n = -m_eff_n * (vn + bias_n);
const sum_n = j_n_accum + lambda_n;
const new_j_n = sum_n > 0 ? sum_n : 0;
```

Now consider TGS substeps: with this design, substep 0's `j_n` cancels
the inbound vn. Substep 1 sees `vn ≈ 0` separating, the `sum > 0`
clamp shrinks `j_n` (the restitution × warm-start interaction PLAN.md
documents). Restitution and Baumgarte are both inside the same
clamp-against-zero pipeline that's fundamentally about non-penetration
impulse direction.

**The split-impulse work has three sub-pieces** (none of which is on
the velocity hot path, so they cost a comparable amount per tick):

1. **Per-body pseudo-velocity buffers.** Add `pos_lv[3]`, `pos_av[3]`
   parallel to `linearVelocity`, `angularVelocity`. Zero at start of
   position pass.
2. **Position-only constraint computation.** Walks the same contact
   list, computes separation from current world contact points
   (re-evaluate from `r_a + p_a`, `r_b + p_b` to capture the latest
   pose), applies the Baumgarte impulse into `pos_lv`/`pos_av`.
3. **Position integration uses `lv + pos_lv`.** The pseudo-velocity
   is consumed in `integrate_position`. After integration, pseudo
   velocity is zeroed for next step.

Then in stage 7's velocity pass, **drop the `depth > PENETRATION_SLOP`
Baumgarte bias entirely**. Restitution stays as one-shot velocity bias
at pre-step (the iterative-clamping issue PLAN.md describes goes away
once position correction is no longer competing for the same
accumulator).

Once split-impulse is in place, TGS substepping becomes "apply forces
once at `dt`, then loop K substeps of {build pre-step at `sub_dt`,
solve velocity once at `sub_dt`, integrate position with `sub_dt`,
solve position once}". The three PLAN.md-documented issues disappear:

- Restitution × warm-start: restitution is one-shot at sub-step 0
  only, applied as direct velocity delta to `lv` not as a bias.
- Baumgarte K× stronger: position pass uses `sub_dt`-scaled Baumgarte
  inside its own loop, but it operates on `pos_lv` only, so it doesn't
  multiply across substeps.
- Force accumulator timing: forces applied once at `dt` before substeps
  begin, then accumulators zeroed.

This is a major piece of work but PLAN.md correctly classifies it as
deferred. Flagging it as the architectural inflection point.

### 3.3 Triangle-vs-primitive — Jolt's closest-point-on-triangle

**Files:** Jolt's `CollideSphereVsTriangles.cpp` (closed-form),
`CollideConvexVsTriangles.cpp` (GJK+EPA+active-edge), our
`narrowphase/narrowphase_step.js:443-585`,
`narrowphase/compute_penetration.js`.

Jolt's sphere-vs-triangle (paraphrased):

```cpp
uint closest_feature;
Vec3 point2 = ClosestPoint::GetClosestPointOnTriangle(v0, v1, v2, closest_feature);
float distance = (sphere_center - point2).Length();
if (distance > sphere_radius + max_separation_distance) return;
float penetration_depth = sphere_radius - distance;
// Voronoi region encoded in closest_feature (0..7 bitmask)
//   0b111 = interior (face) → normal is triangle face normal
//   0b001, 0b010, 0b100 = edge → normal is along (centre − closest_edge_point)
// Active-edge handling adjusts normal if it points along an inactive edge.
```

This bypasses GJK entirely. Tooling for the same is already in our
codebase — `core/geom/3d/triangle/` has triangle-normal computation;
the missing piece is the Voronoi closest-point routine. Even a
straightforward Ericson Real-Time Collision Detection §5.1.5
implementation removes the entire `Triangle3D` degenerate-support
problem.

Direct sphere-vs-triangle is the highest-leverage missing primitive:
- Unblocks `narrowphase_concave.spec.js` skipped tests immediately.
- Fixes the "ball drops on heightmap, decelerates 70% then sinks over
  50 steps" failure documented in PLAN.md (PLAN.md:228-241).
- Is needed regardless of whether we ever do box-vs-triangle or
  capsule-vs-triangle, because spheres-on-mesh is the single most
  common gameplay primitive (character feet, projectiles, pickup
  hitboxes).

Box-vs-triangle and capsule-vs-triangle are non-trivial: box-vs-triangle
is SAT with the triangle treated as having three edges plus a face
normal (13 candidate axes — 3 face normals of box, 1 triangle face,
9 edge-edge crosses). Capsule-vs-triangle reduces to segment-vs-
triangle closest pair, then sphere-vs-triangle at that closest
segment-point.

Active-edge handling is also missing — `mesh_enumerate_triangles` emits
all triangles regardless of which edges are shared with neighbours.
Adding a precomputed active-edge bitmask to `MeshShape3D.indices`
(3 bits per triangle for the three edges, packed) and a fix-normal
pass like Jolt's would close out the ghost-contact failure mode on
adjacent-triangle seams. The heightmap doesn't need this — the
grid topology means every interior edge is shared with exactly one
neighbour, so the active-edge classification is purely a function of
the height difference (which we can compute on the fly).

### 3.4 Manifold caching — world-space index match vs. local-space point match

**Files:** `contact/ManifoldStore.js:258-291`, `narrowphase_step.js`
candidate reduction (`reduce_candidates`), Jolt's
`ContactConstraintManager.cpp`.

Jolt's match (paraphrased):
```cpp
if (Vec3::sLoadFloat3Unsafe(ccp->mPosition1).IsClose(p1_ls,
        mPhysicsSettings.mContactPointPreserveLambdaMaxDistSq))
{
    wcp.mNonPenetrationConstraint.SetTotalLambda(ccp.mNonPenetrationLambda);
    ...
}
```

For each new contact, Jolt scans the cached `CachedContactPoint`s and
transfers the impulse from any cached point within
`mContactPointPreserveLambdaMaxDistSq` (default ~1mm). Points are
stored in **body-local** space, so a body that rotated 90° between
frames still matches correctly.

Ours at `narrowphase_step.js` writes the candidate buffer into
`manifolds.set_contact(slot, k, ...)` where `k` is the slice index
inside `reduce_candidates`'s output. The warm-start impulses at slot
offset `+10..+12` (`contact/ManifoldStore.js:30`) **are preserved across
calls to `set_contact`** because `set_contact` only writes 10 floats
(positions, normal, depth) and leaves `j_n / j_t1 / j_t2` untouched.
This is good when the reduction picks the same contacts in the same
slice order — and bad when it doesn't.

`reduce_candidates` is deterministic (deepest into slot 0, then
greedy max-min-distance for the next three) — but it's deterministic
*per call*, given a candidate list. If the candidate list mutates in
order across frames (which it does: contacts come from per-collider
cross-product loops whose ordering can shift if compound colliders move
relatively, and the underlying triangle decomposition emits triangles
in spatial order that depends on the query AABB), the warm-start
impulse at slot k might be inherited from a geometrically *different*
contact in last frame's manifold.

**Concrete failure mode:** sliding contact. A box sliding on the
floor has 4 contact points that translate every frame. Frame N's
slot-0 contact (deepest) is at corner X; frame N+1's slot-0 (also
deepest) is at corner Y because the box rotated slightly and a
different corner is now deepest. Slot-0 inherits last frame's `j_n`
from corner X — which was holding up a different part of the box.
The error converges out in 10 velocity iterations, but warm-start
is supposed to **save** iterations, and it stops doing so when the
match is wrong.

**Improvement:** match by world (or better, local) position with a
small tolerance. The 13-float stride could grow to 16 by adding a
`(local_x, local_y, local_z)` triple per contact on body A (and skip
B because we can recompute via the normal). The reduction step
becomes "for each new candidate, find the nearest old contact within
tolerance, transfer its impulse to the new contact". This is
~`O(new × old) ≤ 16` per pair — cheap. Storage cost: 3 doubles ×
4 contacts × #slots = 96 bytes/slot. On 1k active pairs that's 96kB,
trivial.

This is materially more impactful for tall stacks than for static
piles, but it improves rolling/sliding scenarios across the board.

### 3.5 EPA priority queue and termination

**Files:** `gjk/expanding_polytope_algorithm.js:118-127`, Jolt's
`Geometry/EPAPenetrationDepth.h`.

Our closest-face search:
```js
let min_dist = v3_dot_array_array(faces, 0, faces, 3 * 3);
closest_face = 0;
for (let i = 1; i < num_faces; i++) {
    const dist = v3_dot_array_array(faces, i * FACE_ELEMENT_COUNT, faces, i * FACE_ELEMENT_COUNT + 3 * 3);
    if (dist < min_dist) { min_dist = dist; closest_face = i; }
}
```

Linear scan over up to `EPA_MAX_NUM_FACES = 64` faces. Cost per
iteration: 64 dot products. We do up to 64 iterations. Worst case
4096 dot products per EPA invocation.

Jolt maintains a heap-based priority queue keyed by `mClosestLenSq`
of each face. Insert on face creation, pop on access. Each
add/remove is `O(log N)`. With typical EPA convergence ~10
iterations, the savings are ~10 ×64 = 640 dot products → ~10 × log₂(40)
≈ 50 heap ops, an order of magnitude.

This is a JS-friendly improvement (heap on a typed array is
straightforward; we already have a min-heap pattern in `BodyStorage`
and `ManifoldStore` for free lists). The catch: face removal mid-iteration
(the loose-edge step) needs to mark heap entries as deleted lazily.
Jolt's comment notes "removed triangles skipped during iteration"
— same lazy-delete pattern.

**Termination tolerance also wants attention.** Ours is absolute
(`EPA_TOLERANCE = 0.0001`); Jolt's is relative
(`dist_sq - mClosestLenSq < mClosestLenSq * inTolerance`). For a
sphere on a flat surface where the true penetration depth is 0.0001,
our absolute test passes on iteration 1 with garbage normal direction
(`closest_face` is whichever of the 4 initial-tetrahedron faces
happened to land near origin). Jolt's relative test would keep
iterating to refine the direction. This is the geometric source of
PLAN.md's "EPA degenerates on smooth shapes" — not the lack of MPR
fallback, but the **stopping criterion** failing to gate on actual
convergence of the search direction.

### 3.6 Box-box manifold construction (Sutherland-Hodgman)

**Files:** `narrowphase/box_box_manifold.js`, Jolt's
`Geometry/ClipPoly.h`.

Both engines use SAT to find the smallest-overlap axis and
Sutherland-Hodgman to clip the incident face against the reference
face for face-vs-face contact. The implementations are
structurally identical.

Where we diverge: edge-edge contact. PLAN.md flags this — when the
SAT axis is an edge-pair cross, we emit a **single** midpoint contact
(`narrowphase/box_box_manifold.js:15-16`: "v1 fallback;
closest-edge-points refinement is a follow-up"). Jolt does the
edge-edge closest-pair computation and emits up to 2 contacts
(roughly: an edge-edge skew gives one contact per pair of
ribbons of overlap).

Practical impact: a tilted cube falling corner-onto-flat-cube relies
on the edge-edge path for the first ~5 frames before face-face takes
over. With a single midpoint contact, the impulse can be slightly off
the geometric centre of contact, producing a small tumble. The
existing 16-cube test PLAN.md mentions is run in a short window, so
this likely isn't visible in normal play but is the right next step
for box-stacking polish.

### 3.7 Manifold reduction heuristic

**Files:** `narrowphase/narrowphase_step.js:149-178`, Jolt's
`Collision/ManifoldBetweenTwoFaces.cpp` `PruneContactPoints`.

Ours:
```js
function reduce_candidates(n) {
    // 1. deepest to slot 0
    // 2. for each subsequent slot, pick the remaining candidate whose
    //    minimum distance to the already-kept set is largest
}
```

Jolt's strategy:
1. **First point:** maximises `(distance to CoM)² × (penetration depth)²`
2. **Second point:** furthest from the first
3. **Third and fourth:** opposite sides of the line from points 1–2,
   maximising perpendicular distance.

The CoM-distance weighting in point 1 is the real divergence. It
biases toward contacts with maximum torque-arm leverage — the right
choice for stable rotational support. Our "deepest" choice
sometimes picks an under-the-CoM contact that produces no torque and
leaves the box unable to resist tipping. Practically, you'd see this
in a tall stack where outer contacts that prevent toppling get
displaced from the manifold by deeper contacts near the centre.

The CoM is available (`Transform.position` for the body — adjusted by
`com_offset` if we add one). The cost of folding `dist_to_com` into
the depth weight is trivial.

### 3.8 Active body iteration / SoA layout

**Files:** `body/BodyStorage.js`, `broadphase/generate_pairs.js:50-51`,
Jolt's `BodyManager.cpp`.

Jolt:
```cpp
BodyID *active_bodies = mActiveBodies[EBodyType::RigidBody];
uint32 num_active_bodies = mNumActiveBodies[EBodyType::RigidBody].load(memory_order_relaxed);
for (uint32 i = 0; i < num_active_bodies; ++i) {
    BodyID id = active_bodies[i];
    Body *body = mBodies[id.GetIndex()];
    ...
}
```

The body object lives behind a pointer. Each iteration is:
*read active_bodies[i]* → *index into mBodies* → *pointer chase to Body*.

Ours:
```js
for (let i = 0; i < awake_count; i++) {
    const body_idx = storage.awake_at(i);
    const list = body_collider_lists[body_idx];   // sparse array
    ...
}
```

We do the same pointer chase to `RigidBody` and `Transform`. The
SoA wins of `BodyStorage` apply to **flags**, **kinds**, and
**generations** — but the simulation hot path reads `linearVelocity`,
`angularVelocity`, `inverseInertiaLocal` (on `RigidBody`), and
`position`, `rotation` (on `Transform`). Those are not in
`BodyStorage`.

This is a deliberate architectural choice (ECS shape with components
owning their own state) and the right one given meep's ECS model — but
worth being honest that it doesn't realise the SoA-locality benefit
that Jolt's pure pool design might (if Jolt were SoA, which it
isn't). Both engines have similar effective cache behaviour at the
solver's inner loop.

**No actionable change here** — flagging only because PLAN.md cites
"active list iteration" as a Jolt-derived design, and the win is
more conceptual (dense active list, no scanning all bodies) than
locality (the per-body data is still pointer-chased on both sides).

---

## 4. Simplicity & uniformity

### Where the code is uniform

Both engines have clean per-stage decomposition. Our pipeline
(`PhysicsSystem.fixedUpdate`) is a single linear function with
11 stages clearly commented. Jolt's `Update` is more elaborate
because of the job system — at least 12 distinct job types — but
the conceptual stages map 1:1.

Internal primitives (vec3 ops, AABB transforms, quaternion math)
are factored into `core/geom/` for us, equivalently into `Jolt/Math/`
and `Jolt/Geometry/`. No glaring over- or under-abstraction.

### Where the code is specialised

**Narrowphase dispatch.** Our `dispatch_pair` (`narrowphase/narrowphase_step.js:192-353`)
is a cascade of `if (isSphereA && isBoxB)...`. Jolt has a 2-D table
`sCollideShape[NumSubShapeTypes][NumSubShapeTypes]`. The cascade is
fine while we have ~5 shape types × symmetric handling but it grows
quadratically in lines of code per new pair (sphere/box/capsule today
→ +cylinder +cone +convex-hull on the PLAN backlog → roughly doubles
the cascade body).

**A table-based dispatch is worth considering** once we add the next
2 shapes. The table is `Function[][]` keyed by shape type marker
(we already use `isUnitSphereShape3D`, `isBoxShape3D`, etc. — those
could become small integer codes). Symmetry handled by a single
"reversed" wrapper, as Jolt does. The cost is a level of indirection
per pair; the gain is "to add a new shape pair, you write one new
handler module + register it in two table slots", instead of editing
a 200-line cascade.

**Concave dispatch** is correctly factored out (`narrowphase_step.js:355-585`)
behind `is_convex === false`. The decomposition machinery
(`narrowphase/decomposition/`) is genuinely clean — `Triangle3D` as a
buffer-flyweight is a nice piece of work. The per-triangle GJK+EPA
should be replaced with closed-form primitives (see §3.3), but the
**enumeration / dispatch** structure is the right shape.

### Code reuse

- `world_inverse_inertia_apply` is the central angular-Jacobian routine
  used by the solver, the velocity integrator, and `applyImpulseAt`.
  Good.
- `gjk` is shared between narrowphase, raycast (via shape_cast), and
  the standalone `compute_penetration`. Good.
- `compute_penetration` is callable independently of the system,
  enabling kinematic resolution. Nice abstraction.
- The min-heap pattern appears in `BodyStorage` (free body indices)
  and `ManifoldStore` (free manifold slots) as **duplicated code**. A
  shared `int_min_heap.js` primitive in `core/collection/` could host
  both — same arguments, same algorithm. Low priority but a real
  duplication.

### Ease of extension

| Task | meep | Jolt |
|---|---|---|
| Add a new shape pair | Edit `dispatch_pair` cascade + write a new `xxx_yyy_contact.js` module | Write a handler function + register it in `CollisionDispatch::sInit` |
| Add a new constraint (joint) | Solver loop is set up to iterate `contacts ∪ joints` per PLAN.md, but the constraint pre-step + warm-start interface is not formalised — `solve_contacts.js` is hard-coded to contact-shape constraints | `Constraint` base class with `BuildIslands`, `SetupVelocityConstraint`, `WarmStartVelocityConstraint`, `SolveVelocityConstraint`, `SolvePositionConstraint` — clearly structured for arbitrary constraint types |
| Add a new query collector | Each query is its own function with its own filter pattern | One method per query type × user provides any `CollisionCollector` subclass |
| Add a new motion quality | N/A (only Discrete) | Add to `EMotionQuality`, route through `JobBuildIslandsFromConstraints` switch |

The constraint extension point is genuinely weaker on our side and
matters for the planned joints (distance, hinge, ball-socket,
prismatic per PLAN.md). The work to abstract is roughly:

1. Define a `Constraint` interface with `setup(dt) → pre_step_data`,
   `warm_start(state)`, `solve_velocity(state)`, optionally
   `solve_position(state)` (in the future split-impulse world).
2. Refactor `solve_contacts.js` so the contact path is *one
   implementation* of the interface, sitting next to (eventually)
   `solve_distance.js`, `solve_hinge.js`.
3. The island builder gains a `__constraints` array that gets ordered
   alongside the manifold-slot list.

This isn't strictly urgent (joints are backlog), but the time to do
it cleanly is **before** joints arrive, not after they each have
custom code paths.

### What Jolt has that's worth adopting

1. **`CollisionCollector` pattern for queries.** A `Collector` is a
   tiny interface with `AddHit(result) → bool` (return false to early-out).
   One implementation each for "all hits", "nearest", "any-hit", "first-in-layer".
   Cleaner than our query-per-use-case approach, future-proofs against
   batch queries.

2. **`mContactPointPreserveLambdaMaxDistSq` (local-position-based warm-start).**
   See §3.4.

3. **Active-edge classification on triangle meshes.** See §3.3.

4. **Closed-form sphere-vs-triangle.** See §3.3. (PLAN.md flags this.)

5. **Last-separating-axis cache for GJK on persistent pairs.** See §3.1.

6. **Position iteration as a separate pass (split-impulse architecture).**
   See §3.2 and §3 of PLAN.md TGS backlog.

7. **Manifold reduction weighted by torque-arm from CoM.** See §3.7.

### What Jolt has that would be over-engineering for us

1. **`LargeIslandSplitter`** — exists purely to enable parallel solving
   within an island. PLAN.md's "out of scope without universal SAB" is
   correct.
2. **Multiple `BroadPhaseLayer`s.** Our two-tree split is enough; adding
   a tree per object layer increases broadphase memory linearly in
   layer count and only helps when there's a strict hierarchy of
   "static vs. dynamic vs. kinematic vs. debris". Game content for our
   target doesn't have that diversity.
3. **`MutexArray` for body locking.** Single-threaded.
4. **`ShapeRefC` reference counting.** Our shapes are managed by the
   ECS lifetime; refcounts would be ceremony.
5. **`EMotionQuality::LinearCast` with timestealing.** The simpler
   "swept shape cast → clip movement → integrate at TOI" works in
   single-threaded code without needing the elaborate substep state
   machine Jolt builds for thread coordination.

### Where we could simplify further

- **Heap implementation duplication** (`BodyStorage` / `ManifoldStore`)
  — one shared `core/collection/IntMinHeap.js` (small).
- **PosedShape3D** (`core/geom/3d/shape/PosedShape3D.js`) is fine but only used by
  GJK/EPA paths; the comment-noted concave dispatch builds two of them
  for the inverted convention. A single canonical "shape under pose"
  abstraction used everywhere (broadphase, narrowphase, queries) would
  reduce per-pair branching.
- **`generate_pairs.js`** runs `pair_filter` after the touched-flag
  check. If `pair_filter` is set and the pair is currently rejected,
  the manifold slot is still acquired-then-orphaned. Reordering so
  the filter runs **before** `acquire` would avoid temporarily
  allocating slots for rejected pairs.

---

## Headline takeaways

1. **The single biggest correctness gap is closed-form sphere-vs-triangle**
   (per PLAN.md). Jolt provides the blueprint in
   `CollideSphereVsTriangles.cpp` — `ClosestPoint::GetClosestPointOnTriangle`
   with a 3-bit Voronoi feature id. This unblocks the skipped
   `narrowphase_concave.spec.js` tests and improves the heightmap drop
   case fundamentally.

2. **The biggest stability gap is split-impulse architecture.** Without
   it, TGS is blocked (PLAN.md documents this). Jolt's pattern:
   separate `SolvePositionConstraints` pass operating on a
   pseudo-velocity, integrated for one substep and discarded. This is
   a several-commit solver rewrite but the right one. Restitution
   should be one-shot, not iterative.

3. **GJK separating-axis cache** is a free win — 3 doubles per
   manifold slot, ~5–10× iteration-count reduction on established
   contacts, no architectural change needed.

4. **Manifold warm-start by position match** (Jolt's
   `mContactPointPreserveLambdaMaxDistSq`) closes a quiet correctness
   bug in sliding/rolling contacts where warm-start currently inherits
   impulses by slice index rather than by geometric identity.

5. **EPA priority queue + relative tolerance** addresses the
   "EPA-on-smooth-shapes" failure mode at its source. Current absolute
   tolerance terminates with garbage normal direction on small-depth
   contacts.

6. **Active-edge classification on triangle meshes** suppresses ghost
   contacts at internal seams without needing the full closed-form
   triangle-vs-X family.

7. **Manifold reduction should weight by CoM distance** for torque-arm
   stability. Single-line change once `Transform.position` is
   threaded through.

8. **Constraint interface abstraction** before joints land — solver
   loop is conceptually right, but the data-flow protocol for non-contact
   constraints is informal.

9. **Per-body LinearCast CCD** (Jolt's `EMotionQuality::LinearCast`)
   maps directly to PLAN.md's documented falling-tower reproducer fix.

10. **Threading, multi-tree broadphase layers, refcounted shapes,
    cross-platform determinism** are all Jolt features that are correctly
    out of scope for meep given the design bets in PLAN.md. Do not
    pursue.
