ECS Physics Engine
A 3D rigid body physics engine built from scratch on my own archetype-based ECS. It has a dynamic AABB tree broadphase, box-box collision using SAT with full contact manifolds, an iterative impulse solver for stable stacking, and tearable cloth.
- Duration
- 2 months
- Platform
- PC
- Module Grade
- 100%

This is a 3D rigid body physics engine I built from scratch in C++ for a second-year university module, together with the archetype-based Entity Component System (ECS) it runs on. It’s rendered with my own DirectX 11 framework. It covers the full physics pipeline: integration, a dynamic bounding volume tree for the broadphase, a narrowphase that builds contact manifolds, and an iterative impulse solver with friction. On top of that are mass-spring cloth, heightmap terrain collision, and ImGui menus for modifying the simulation.
- 5 collider types, from points to oriented boxes
- 10 velocity solver iterations per step
- 5 position solver iterations per step
- 60 simulation steps a second
The ECS
Instead of objects with virtual Update() methods, everything in the engine is an entity (just an ID) with plain-data components such as Transform, Particle, RigidBody and Collider, and logic lives in systems that iterate over a select few of those components.
Storage is archetype-based. Every distinct combination of components (defined by a bitset signature) gets its own archetype, which stores each component type in a tightly packed, type-erased column. When a system asks for every entity with a Particle and a Transform, the engine finds the archetypes whose signature contains both and walks their columns in order. Each component type sits contiguously in memory, which optimises for cache lookup speed in the CPU.
scene.ForEach<Particle, Transform>([dt, frameDamping](Entity entity, Particle* particle, Transform* transform)
{
if (particle->inverseMass <= 0.0f) return; // static bodies have infinite mass
Vector3 newAcceleration = particle->force * particle->inverseMass + Vector3::Down * 9.8f;
// velocity Verlet integration
transform->position += particle->linearVelocity * dt + particle->lastLinearAcceleration * 0.5f * dt * dt;
particle->linearVelocity += (particle->lastLinearAcceleration + newAcceleration) * 0.5f * dt;
particle->linearVelocity *= frameDamping;
particle->lastLinearAcceleration = newAcceleration;
particle->force = Vector3::Zero;
});
Adding or removing a component moves the entity to a different archetype by copying its data across. Removal uses swap-and-pop, so columns never have gaps.
The simulation step
Physics runs on a fixed 60 Hz timestep with an accumulator, so the simulation is not affected by frame rate. However the number of steps that can happen in a single frame is capped to avoid simulation explosion. Each step runs four systems in order:
- Integrator: applies gravity and forces with velocity Verlet, and integrates angular velocity into the orientation quaternion. Each body’s inverse inertia tensor is rotated into world space every step, so tumbling boxes respond correctly to off-centre hits.
- Collider update: syncs each collider’s shape to its transform.
- Broadphase: updates each body’s bounds in the AABB tree.
- Narrowphase and solver: confirms real contacts, builds manifolds, and resolves them.
Broadphase: dynamic AABB tree
Checking every pair of bodies is O(n²), so the broadphase uses a dynamic bounding volume hierarchy, based on Erin Catto’s GDC 2019 talk on the Box2D tree.
- Fat AABBs. Each leaf stores its real box plus an enlarged box 30% bigger. While a body stays inside its enlarged box, only the parent boxes are refitted. It’s only removed and re-inserted when it moves outside. Most frames, most bodies don’t need re-inserting.
- Surface area cost. When a leaf is inserted, the tree uses branch and bound to find the sibling that adds the least total surface area. Subtrees whose lower-bound cost can’t beat the best so far are skipped completely.
- Static nodes. The floor, walls and terrain are flagged as static. They’re never updated, and pairs where both bodies are static are never generated.
// cost of making current the new sibling is: the new box, plus how much every ancestor grows
costCache[current.index] = AABB::Union(leafBox, currentNode.box).GetArea() - currentNode.box.GetArea() + parentCost;
// the best any descendant could possibly do
float subTreeLowerBoundCost = leafBoxArea + costCache[current.index];
if (subTreeLowerBoundCost < bestCost)
{
// only then is it worth exploring the children
}
The same tree handles ray casts for mouse picking, so clicking an object only tests the boxes along the ray.

Visualising the tree
The debug view draws the box of every leaf node in the tree, so you can watch how the bounding box wraps around each object.
Narrowphase: contact manifolds
Each possible collision pair from the broadphase goes through a dispatch table indexed by the two collider types (point, sphere, AABB, OBB and terrain triangle), so adding a new shape pair just means registering one handler.
The most involved handler is OBB against OBB:
- Separating Axis Theorem across all 15 candidate axes: three face normals from each box, plus the nine cross products of their edges. If any axis separates the boxes, they aren’t touching. Otherwise, the axis with the smallest overlap gives the collision normal and penetration depth.
- Reference and incident faces. The face most aligned with the normal becomes the reference face. The face on the other box that points most directly against it becomes the incident face. This identification is needed for the next step.
- Clipping. The incident face is clipped against the four side planes of the reference face. The remaining points below the reference face become the contact points, up to four of them.
Getting a full set of contact points, rather than one, is what makes boxes rest flat and stack instead of rocking on a single corner.

Contact points
The debug view draws every contact point the narrowphase produces. A box resting flat shows four points, one for each corner of the clipped face.
Collision response
Contacts are resolved with sequential impulses: ten passes over every contact, each applying a normal impulse (with restitution) and then a friction impulse along the sliding direction. Angular terms are also included so that hits off the centre of mass result in the body spinning.
float impulseForce = Vector3::Dot(contactVelocity, info.manifold.normal);
if (impulseForce > 0.0f) continue; // already separating
Vector3 inertiaA = Vector3::Cross(invInertiaA * Vector3::Cross(relativeA, normal), relativeA);
Vector3 inertiaB = Vector3::Cross(invInertiaB * Vector3::Cross(relativeB, normal), relativeB);
float angularEffect = Vector3::Dot(inertiaA + inertiaB, normal);
float j = (-(1.0f + restitution) * impulseForce) / (totalInverseMass + angularEffect);
Because each contact is solved individually, there is the chance of new collision being created. Repeating the passes lets the impulses settle across the whole pile, which is what makes stacking stable. After the velocity passes, five position correction passes push overlapping bodies apart by a fraction of their penetration. A small tolerance lets resting contacts sit still instead of jittering.


Cloth
The same solver also simulates mass-spring cloth. A grid of point masses is connected by three kinds of springs:
- Structural springs to direct neighbours, which hold the sheet together
- Shear springs across the diagonals, which stop it collapsing sideways
- Bending springs to every second neighbour, which resist folding
Each spring is an ECS entity of its own. If one is stretched past five times its rest length, it is destroyed, so the cloth can tear.
Terrain

Heightmap terrain
Terrain is built from a heightmap. As well as the render mesh, each triangle becomes a static half-space collider in the AABB tree, so bodies roll down slopes and settle in valleys.
Debug tools
Everything can be inspected and changed live through ImGui:
- Entity editor: select any body to see and edit its component’s values such as transform, mass and velocities, or delete it.
- Click modes: Select picks an entity, Push applies an impulse at the exact point you clicked (so off-centre clicks spin things), and Drag pulls a body towards the mouse.
- Spawning: fire spheres or boxes from the camera, or set off a radial explosion impulse.
- Visualisation: toggle contact points and the AABB tree.
Looking back
- Warm starting. Each step’s solver starts from zero. Remembering contact impulses between frames and clamping the accumulated impulse, as Box2D does, would make tall stacks settle much faster and more reliably.
- Static friction. Friction currently uses one dynamic coefficient. Clamping the friction impulse to a friction cone, with separate static and dynamic coefficients, would stop objects creeping slowly down slopes.
- Solver data layout. The solver looks up components through the ECS for every contact on every pass. Gathering the bodies into a flat array before solving would likely suit the cache-friendly approach of ECS better.
- Archetype graph. Finding the destination archetype when a component is added or removed uses a hash map lookup each time. Caching edges between archetypes would make those moves cheaper.
UML class diagram
