← All work
2025C++DirectX 11ECSRigid Body PhysicsDear ImGui

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%
ECS Physics Engine

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.

Spawning bodies and exploding them
  • 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.

IntegratorSystem.cpp
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:

  1. 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.
  2. Collider update: syncs each collider’s shape to its transform.
  3. Broadphase: updates each body’s bounds in the AABB tree.
  4. 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.

AABBTree.cpp: PickBest()
// 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.

Bounding Box Visuals
The AABB tree drawn as wireframe boxes

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:

  1. 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.
  2. 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.
  3. 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 Point Visuals
Contact points from the box-box clipping

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.

NarrowPhaseSystem.cpp (simplified)
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:

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

Terrain Collision
Spheres resting on heightmap 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:

Looking back

UML class diagram

UML Class Diagram
UML diagram of the physics framework and ECS engine
Tanks →Next project