executing-plans
executing-plans
Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available
physics-engineExpert physics engine internals - collision detection (broad/narrow phase), rigid body dynamics, constraint solvers, integration, character controllers, and scene queries.
Independent GitHub snapshot · Automated classification · Original documentation governs
A physics engine simulates rigid bodies through three pipelines every tick: collision detection (find contacts), collision resolution (apply impulses/constraints), and integration (advance positions/velocities). This guide gives a lead engineer's view of how real engines (PhysX, Jolt, Bullet, Box2D) work underneath.
1. For each body: apply forces -> linear/angular velocity (accelerate)
2. Broad-phase: generate candidate pairs of AABB-overlapping bodies
3. Narrow-phase: exact contact detection -> contact manifold (points, normals, penetration)
4. Constraint solver: iterate contacts + joints to correct penetration & velocities
5. Integration: x += v * dt; Rot += omega * dt (per body)
6. Sleep/wake: mark bodies nearly at rest for deactivation
skills/game/game-engine/patterns/SKILL.md → game-loop section).Goal: reject distant pairs cheaply; output pairs of possibly-intersecting AABBs.
class DbvhNode {
AABB box;
DbvhNode* parent;
DbvhNode* children[2]; // internal
int32_t bodyIndex; // leaf: body id
int32_t height;
};
// update: if (invalidated) reinsert; else refit bbox walking up the tree
Given a pair, compute contact geometry: point(s), normal, penetration depth.
| Shape | Query cost | Notes |
|---|---|---|
| Sphere | O(1) | cheap, common for ragdolls/CCD |
| Box (AABB/OBB) | O(1) | standard |
| Capsule | O(1) | characters (built from 2 spheres + cylinder) |
| Triangle mesh (static) | O(log N) via BVH | world geometry |
| Convex hull | O(log N) via facing/support | player phys |
| Heightfield | O(log N) | terrains |
For convex vs convex: if a separating axis exists, no collision. Project both shapes onto each candidate axis (edge + face normals); if separated → done; else find minimum overlap axis → contact plane.
Result of narrow-phase: a contact manifold:
struct ContactPoint { Vec3 localA, localB, normal, position; float penetration; };
struct Manifold {
ContactPoint points[4]; // up to 4 (box-box), reduced for others
Vec3 normal; // shared frame
Body* a, * b;
};
Simplify: reduce to 1-1 points for spheres, up to 4 for box/box. Give the solver a small set of contact points, NOT the full polygon intersection.
| Method | Approach | Used by |
|---|---|---|
| Impulse-based (constraint solver) | Compute change in velocity per contact to satisfy non-penetration | PhysX, Jolt, Bullet, Box2D |
| Position-based dynamics (PBD/XPBD) | Direct position correction, stable for cloth/soft | many UE chaos modes / Unreal cloth |
| Penalty force | spring force pushing apart | simple engines; unstable at large dt |
For each contact: relative velocity at contact point
v_rel = (v_b + w_b x r_b) - (v_a + w_a x r_a)
vn = dot(v_rel, n) // approach velocity along normal
// bias: penetration restitution (bounce)
e = restitution(a,b)
j = -(1 + e) * vn / (invMass_a + invMass_b + r cross terms)
v_a -= j * invMass_a * n ; v_b += j * invMass_b * n
// + angular impulse terms
Iterate all contacts several times (4-20 iterations) to converge a global solution — each contact affects others.
Apply two orthogonal tangent impulses:
t = v_rel - dot(v_rel,n)*n (tangent direction)
jt = clamp(-v_rel_t * 1/(totalInvMass...), -mu*jn, mu*jn)
Use mu = Coulomb coefficient (static/dynamic blend).
| Method | Stability | Cost | Use |
|---|---|---|---|
| Explicit Euler | unstable (energy gains) | 1x | never in production |
| Semi-implicit Euler | stable, standard | 1x | default rigid-body |
| Verlet | good energy | ~1.3x | cloth, particles |
| RK4 | high accuracy | 4x | precise simulation/ragdolls |
Semi-implicit (symplectic):
v += a * dt
x += v * dt // velocity updated BEFORE position
struct RigidBody {
Vec3 position;
Quat rotation;
Vec3 linearVelocity, angularVelocity;
float invMass, invI[3]; // inverse inertia tensor (diagonal local space)
Vec3 force, torque; // accumulated this tick
bool sleeping;
};
Integrate rotation: apply angular velocity about local axes via quaternion derivative and normalize.
High-speed small objects tunnel through thin walls at large dt. Solutions:
sweep a test then narrow-phase at midpoint.Rule: CCD only for fast bodies vs static world (never CCD-vs-dynamic — expensive/nonsensical).
Constraint form: C = 0 (position) → Cdot = J * v = 0 (velocity). Solve with the same sequential impulse pattern using Jacobian J.
// generalized velocity constraint solve
lambda = -(J v + bias) / (J M^-1 J^T)
v = v + M^-1 J^T lambda
sleeping.PhysX/Jolt expose character controllers that are NOT rigid-body player physics:
move_and_slide-style: attempt move; slide along obstacles (collide-and-slide).Implement yourself (matching forced checkpoints), or use engine built-in (Godot CharacterBody3D, Unreal CharacterMovementComponent, Unity CharacterController).
// raycast against static + dynamic
Hit hit;
physics.rayCast(origin, dir, maxDist, out hit);
// overlap test
physics.overlapSphere(pos, radius, filter, out bodies[]);
Rules:
QueryFilterCallback and broad-phase fast paths.sqrt in solver hot paths where precision differs (or order-preserve).| Symptom | Fix |
|---|---|
| Jittery stack of boxes | warm-starting missing; iterations too low (>=8) |
| Tunneling bullets | CCD or substeps for fast bodies |
| Ragdoll explodes | solver iterations low; joints wrong axes; dt too big |
| Character sinks in floor | max step vs penetration resolution mismatch; reproject |
| Spinning car on apex | angular damping missing; inertia too low |
| Non-deterministic replays | map iteration + warm-start order |
| Sleeping bodies never wake | wake threshold too high |
| Engine | Strengths | Weaknesses |
|---|---|---|
| PhysX (Unity) | proven, fast, great docs; Unity built-in | closed-source dev; Unity's API hides internals |
| Jolt (Godot option, Hotline Miami dev) | open source, high-perf, deterministic, excellent for immersion | smaller ecosystem |
| Bullet | open source, cross-platform, legacy w/ known bugs | older code, less friendly API |
| Box2D | best 2D solver; tiny, fast | 2D only |
| Unity DOTS Physics | ECS-native, burst-friendly | complex, newer |
skills/game/game-engine/patterns/SKILL.md — engine patterns (game loop, fixed timestep)skills/game/game-engine/patterns/references/spatial-partitioning.md — broad-phase data structuresskills/game/game-engine/ecs-pattern/SKILL.md — ECS storage relevant to physics hotspotsskills/game/game-engine/ecs-pattern/references/ecs-netcode.md — deterministic sim across the wireskills/game/multiplayer-netcode/SKILL.md — server-authoritative simulation