Physics engine

From j4flmao/agent-skills · View interactive version

Physics engine is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks about a physics engine, collision detection, broad phase, narrow phase, GJK, EPA, constraint solvers, rigid bodies, CCD, character controllers or Jolt/PhysX internals. Produces rigid-body physics design and solver code. Not for engine-specific physics settings (use unity, unre

How to use this skill

Skill file

Physics Engine Internals — Deep Guide

Purpose

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.

Agent Protocol

Trigger

"physics engine", "collision detection", "broad phase", "narrow phase", "GJK", "EPA", "constraint solver", "rigid body", "character controller", "CCD".

Input Context

Output Artifact

Physics design or code with stability/performance reasoning. No file unless requested.

Response Format

Stage: {broad | narrow | solve | integrate}
Approach: {algorithm}
Code: {snippet}
Stability: {iterations, substeps, tolerances}

1. The Physics Step Pipeline

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

1.1 Determinism vs Performance

2. Broad-Phase Collision Detection

Goal: reject distant pairs cheaply; output pairs of possibly-intersecting AABBs.

2.1 Sweep-and-Prune (SAP)

2.2 Dynamic Bounding Volume Hierarchy (DBVH)

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

2.3 Uniform Grid / Hash Grid

3. Narrow-Phase Collision

Given a pair, compute contact geometry: point(s), normal, penetration depth.

3.1 The Collider Zoo

| 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 |

3.2 SAT (Separating Axis Theorem)

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.

3.3 GJK + EPA

3.4 Contact Manifold

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.

4. Collision Resolution — the Solver

4.1 Impulse-Based vs Penalty

| 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 |

4.2 The Sequential Impulse Solver (per contact)

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.

4.3 Friction

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).

4.4 Solver Order & Warm Starting

5. Integration

5.1 Choosing the integrator

| 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

5.2 Rigid Body State

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.

5.3 CCD (Continuous Collision Detection)

High-speed small objects tunnel through thin walls at large dt. Solutions:

Rule: CCD only for fast bodies vs static world (never CCD-vs-dynamic — expensive/nonsensical).

6. Joints & Constraints

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

7. Sleeping & Activation

8. Character Controllers

PhysX/Jolt expose character controllers that are NOT rigid-body player physics:

Implement yourself (matching forced checkpoints), or use engine built-in (Godot CharacterBody3D, Unreal CharacterMovementComponent, Unity CharacterController).

9. Scene Queries (Raycasts / Overlaps)

// raycast against static + dynamic
Hit hit;
physics.rayCast(origin, dir, maxDist, out hit);
// overlap test
physics.overlapSphere(pos, radius, filter, out bodies[]);

Rules:

10. Determinism & Networking

11. Tuning Cheat-Sheet

| 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 |

12. Engine Comparison (when to choose what)

| Engine | Strengths | Weaknesses |

|--------|-----------|-----------|

| PhysX (NVIDIA, BSD-3 open source) | proven, fast, GPU features; Unity's built-in 3D physics | engine wrappers (Unity) hide most solver controls |

| Jolt (MIT; by Jorrit Rouwe, used in Horizon Forbidden West; Godot's default 3D engine since 4.6) | multithreaded, fast, optional cross-platform determinism build | younger ecosystem than PhysX |

| Bullet | open source (zlib), widely embedded | little active development; older API |

| Box2D (v3: C API, multithreaded, SIMD) | de facto standard 2D solver; small, fast | 2D only |

| Unity Physics / Havok Physics for Unity | ECS-native, Burst-compiled, stateless (Unity Physics) | requires the Entities stack |

13. References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.