TExcelTAD
Home › Game Physics & Animation › Mini Project: 2D Physics Sandbox

Mini Project: 2D Physics Sandbox

In this project you will build a small but complete 2D physics engine: circles that roll, bounce, pile up, fall asleep and hang from chains, on a level made of static line segments. The core is written in C++ and grows in three steps; the last step is the same engine ported to JavaScript on a canvas, where you can drop balls, throw them and switch solver features on and off.

It uses nearly every section of the course:

Step What it adds Lessons it uses
1. World and walls bodies, fixed step, semi-implicit Euler, circle vs segment Integrators, Fixed Timestep, Closest Point Queries
2. A real solver circle vs circle, rotation, sequential impulses, restitution, friction, positional correction Impulses, Friction, Positional Correction, Rotation
3. The complete engine uniform-grid broad phase, sleeping, distance joints, a determinism hash Uniform Grid, Stacking and Sleeping, Distance Constraints, Determinism
4. The playable sandbox the same engine in JavaScript with a canvas, mouse dragging and debug drawing everything above

Note: Circles keep the narrow phase short, so the project can focus on the solver. Adding boxes means adding the SAT for oriented boxes test and contact clipping; it is the first "extend it" idea at the end.

Step 1: The world and its walls

A World owns the bodies and the static level. Each step integrates gravity into velocity, velocity into position (semi-implicit Euler), then finds each ball's closest point on every segment. If that point is closer than the radius, the ball is pushed out along the normal and the normal part of its velocity is reflected with restitution.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>
#include <algorithm>

struct Vec2 { double x = 0, y = 0; };
Vec2 operator+(Vec2 a, Vec2 b) { return {a.x + b.x, a.y + b.y}; }
Vec2 operator-(Vec2 a, Vec2 b) { return {a.x - b.x, a.y - b.y}; }
Vec2 operator*(Vec2 v, double s) { return {v.x * s, v.y * s}; }
double dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; }
double length(Vec2 v) { return std::sqrt(dot(v, v)); }
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }

struct Body { Vec2 p, v; double radius = 0.5, invMass = 1, restitution = 0.3; };
struct Segment { Vec2 a, b; };

struct World {
    std::vector<Body> bodies;
    std::vector<Segment> segments;
    Vec2 gravity{0, -9.81};

    void step(double dt) {
        for (auto& b : bodies) b.v = b.v + gravity * dt;          // forces -> velocity
        for (auto& b : bodies) b.p = b.p + b.v * dt;              // velocity -> position
        for (auto& b : bodies)                                     // detect + respond
            for (auto& s : segments) {
                Vec2 ab = s.b - s.a;
                double t = std::clamp(dot(b.p - s.a, ab) / dot(ab, ab), 0.0, 1.0);
                Vec2 closest = s.a + ab * t, d = b.p - closest;
                double dist = length(d);
                if (dist >= b.radius || dist == 0) continue;
                Vec2 n = d * (1 / dist);                           // from the wall toward the ball
                b.p = b.p + n * (b.radius - dist);                 // push out
                double vn = dot(b.v, n);
                if (vn < 0) b.v = b.v - n * ((1 + b.restitution) * vn);   // reflect the normal part
            }
    }
};

int main() {
    std::cout << std::fixed << std::setprecision(3);
    World w;
    w.segments = {{{-10, 0}, {10, 0}}, {{-9, 6}, {-3, 3}}};      // ground and a ramp
    w.bodies.push_back({{-7, 8}, {0, 0}});
    for (int s = 1; s <= 180; s++) {
        w.step(1.0 / 60);
        if (s % 20 == 0) {
            const Body& b = w.bodies[0];
            std::cout << "t=" << s / 60.0 << "  p=(" << z0(b.p.x) << ", " << z0(b.p.y) << ")  v=(" << z0(b.v.x) << ", " << z0(b.v.y) << ")\n";
        }
    }
}
t=0.333  p=(-7.000, 7.428)  v=(0.000, -3.270)
t=0.667  p=(-7.000, 5.765)  v=(0.000, -6.540)
t=1.000  p=(-5.921, 5.172)  v=(3.571, -2.668)
t=1.333  p=(-4.445, 4.281)  v=(5.247, -2.586)
t=1.667  p=(-2.478, 3.283)  v=(6.359, -3.632)
t=2.000  p=(-0.358, 1.500)  v=(6.359, -6.902)
t=2.333  p=(1.762, 0.780)  v=(6.359, 0.501)
t=2.667  p=(3.881, 0.516)  v=(6.359, 0.406)
t=3.000  p=(6.001, 0.500)  v=(6.359, 0.038)

The ball falls, lands on the ramp at about 0.7 s, rolls off its end, bounces on the ground and then slides forever at 6.4 m/s: there is no friction yet, and with a single ball there is nothing else to hit. The response is also as simple as it can be: it fixes one contact at a time and can't handle a ball resting on another ball, or two contacts that fight each other. Step 2 replaces it with a proper solver.

Step 2: Sequential impulses with friction

Now bodies have angular velocity and an inertia (a disc: ½·m·r²), and the response becomes the solver from the Collision Response section:

  1. Detect all contacts first (ball–ball and ball–segment), each with a normal pointing from body A to body B, a contact point and a depth.
  2. Compute a restitution target per contact from the approach speed before solving (and skip bouncing for slow contacts, so resting balls don't buzz).
  3. Iterate over all contacts several times. Each pass applies a normal impulse (with the accumulated impulse clamped to stay non-negative) and a friction impulse (clamped to μ · jn, the Coulomb limit).
  4. Integrate positions, then push overlapping pairs apart by 60% of the depth beyond a small slop.

To see what the iterations buy, the program drops 15 balls into a bucket and runs the same scene with 1, 4 and 10 iterations:

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>
#include <algorithm>

struct Vec2 { double x = 0, y = 0; };
Vec2 operator+(Vec2 a, Vec2 b) { return {a.x + b.x, a.y + b.y}; }
Vec2 operator-(Vec2 a, Vec2 b) { return {a.x - b.x, a.y - b.y}; }
Vec2 operator*(Vec2 v, double s) { return {v.x * s, v.y * s}; }
double dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; }
double cross(Vec2 a, Vec2 b) { return a.x * b.y - a.y * b.x; }
Vec2 cross(double w, Vec2 r) { return {-w * r.y, w * r.x}; }
double length(Vec2 v) { return std::sqrt(dot(v, v)); }

struct Body { Vec2 p, v; double w = 0, radius = 0.5, invMass = 1, invI = 1, restitution = 0.2, friction = 0.6; };
struct Segment { Vec2 a, b; };
struct Contact { int a, b; Vec2 n, point; double depth, bounce = 0, jn = 0, jt = 0; };   // b < 0: segment

struct World {
    std::vector<Body> bodies;
    std::vector<Segment> segments;
    Vec2 gravity{0, -9.81};
    int iterations = 10;
    double maxDepth = 0;

    void addCircle(Vec2 p, double r) {
        double m = 3.141592653589793 * r * r;                 // density 1
        Body b; b.p = p; b.radius = r; b.invMass = 1 / m; b.invI = 1 / (0.5 * m * r * r);
        bodies.push_back(b);
    }

    void step(double dt) {
        for (auto& b : bodies) b.v = b.v + gravity * dt;
        std::vector<Contact> contacts = findContacts();
        maxDepth = 0;
        for (auto& c : contacts) {
            maxDepth = std::max(maxDepth, c.depth);
            double vn = dot(relVel(c), c.n);
            c.bounce = vn < -1.0 ? -vn * bodies[c.a].restitution : 0;
        }
        for (int it = 0; it < iterations; it++)
            for (auto& c : contacts) solve(c);
        for (auto& b : bodies) b.p = b.p + b.v * dt;
        for (auto& c : contacts) correct(c);
    }

    std::vector<Contact> findContacts() {
        std::vector<Contact> out;
        for (int i = 0; i < int(bodies.size()); i++)                       // brute force, for now
            for (int j = i + 1; j < int(bodies.size()); j++) {
                Vec2 d = bodies[j].p - bodies[i].p;
                double dist = length(d), r = bodies[i].radius + bodies[j].radius;
                if (dist >= r || dist == 0) continue;
                Vec2 n = d * (1 / dist);
                out.push_back({i, j, n, bodies[i].p + n * (bodies[i].radius - (r - dist) / 2), r - dist});
            }
        for (int i = 0; i < int(bodies.size()); i++)
            for (int s = 0; s < int(segments.size()); s++) {
                Vec2 a = segments[s].a, ab = segments[s].b - a;
                double t = std::clamp(dot(bodies[i].p - a, ab) / dot(ab, ab), 0.0, 1.0);
                Vec2 closest = a + ab * t, d = closest - bodies[i].p;
                double dist = length(d);
                if (dist >= bodies[i].radius || dist == 0) continue;
                out.push_back({i, -1 - s, d * (1 / dist), closest, bodies[i].radius - dist});
            }
        return out;
    }

    double invM(int i) const { return i < 0 ? 0 : bodies[i].invMass; }
    double invI(int i) const { return i < 0 ? 0 : bodies[i].invI; }
    Vec2 pointVel(int i, Vec2 pt) const { return i < 0 ? Vec2{} : bodies[i].v + cross(bodies[i].w, pt - bodies[i].p); }
    Vec2 relVel(const Contact& c) const { return pointVel(c.b, c.point) - pointVel(c.a, c.point); }
    void impulse(int i, Vec2 P, Vec2 pt) {
        if (i < 0) return;
        bodies[i].v = bodies[i].v + P * bodies[i].invMass;
        bodies[i].w += cross(pt - bodies[i].p, P) * bodies[i].invI;
    }

    void solve(Contact& c) {
        Vec2 rA = c.point - bodies[c.a].p, rB = c.b < 0 ? Vec2{} : c.point - bodies[c.b].p;
        double rnA = cross(rA, c.n), rnB = cross(rB, c.n);
        double kn = invM(c.a) + invM(c.b) + invI(c.a) * rnA * rnA + invI(c.b) * rnB * rnB;
        double dj = (-dot(relVel(c), c.n) + c.bounce) / kn;
        double old = c.jn;
        c.jn = std::max(old + dj, 0.0);                        // accumulated impulse never pulls
        dj = c.jn - old;
        impulse(c.a, c.n * -dj, c.point);
        impulse(c.b, c.n * dj, c.point);

        Vec2 t{-c.n.y, c.n.x};
        double rtA = cross(rA, t), rtB = cross(rB, t);
        double kt = invM(c.a) + invM(c.b) + invI(c.a) * rtA * rtA + invI(c.b) * rtB * rtB;
        double mu = c.b < 0 ? bodies[c.a].friction : std::sqrt(bodies[c.a].friction * bodies[c.b].friction);
        double oldT = c.jt;
        c.jt = std::clamp(oldT - dot(relVel(c), t) / kt, -mu * c.jn, mu * c.jn);   // Coulomb limit
        double djt = c.jt - oldT;
        impulse(c.a, t * -djt, c.point);
        impulse(c.b, t * djt, c.point);
    }

    void correct(const Contact& c) {
        double mA = invM(c.a), mB = invM(c.b);
        double push = std::max(c.depth - 0.005, 0.0) * 0.6 / (mA + mB);
        bodies[c.a].p = bodies[c.a].p - c.n * (push * mA);
        if (c.b >= 0) bodies[c.b].p = bodies[c.b].p + c.n * (push * mB);
    }
};

int main() {
    std::cout << std::fixed << std::setprecision(3);
    for (int iters : {1, 4, 10}) {
        World w;
        w.iterations = iters;
        w.segments = {{{-2, 0}, {2, 0}}, {{-2, 0}, {-2, 10}}, {{2, 0}, {2, 10}}};   // a bucket 4 m wide
        for (int k = 0; k < 15; k++) w.addCircle({-1.5 + (k % 4) * 1.0 + (k / 4 % 2) * 0.2, 1 + k / 4 * 1.1}, 0.45);
        double worst = 0;
        for (int s = 1; s <= 300; s++) { w.step(1.0 / 60); if (s > 120) worst = std::max(worst, w.maxDepth); }
        double ke = 0, top = 0;
        for (auto& b : w.bodies) { ke += 0.5 * dot(b.v, b.v) / b.invMass; top = std::max(top, b.p.y + b.radius); }
        std::cout << std::setw(2) << iters << " iterations: pile height " << top << " m, worst overlap " << worst * 100
                  << " cm, kinetic energy " << ke << " J\n";
    }
}
 1 iterations: pile height 2.676 m, worst overlap 19.970 cm, kinetic energy 1.449 J
 4 iterations: pile height 3.174 m, worst overlap 3.714 cm, kinetic energy 0.085 J
10 iterations: pile height 3.249 m, worst overlap 2.649 cm, kinetic energy 0.007 J

With one iteration the pile is squashed: balls sink deep into each other (a worst overlap of about 20 cm on 45 cm balls), the pile is half a meter lower, and it keeps jiggling. Four iterations already hold the pile up; ten make it nearly still. This is the trade-off every engine exposes as solver iterations (Box2D's sub-steps, Unity's defaultSolverIterations, Jolt's velocity and position steps).

Step 3: The complete engine

The last C++ step adds the three things a sandbox with many bodies needs:

  • A uniform-grid broad phase. The cell size is the largest diameter, every body is inserted into the cells its bounding box touches, and only bodies sharing a cell are tested. A std::map and a std::set keep the pair order deterministic.
  • Sleeping. A body whose kinetic energy stays below a threshold for half a second goes to sleep: it is skipped by integration and acts like a static body in contacts. A moving body that hits a sleeper wakes it.
  • Distance joints. A chain is a row of small balls joined by rigid rods, solved inside the same iteration loop as the contacts, then corrected in position like the distance constraints lesson.

At the end it prints an FNV-1a hash of every position, the cheapest possible determinism check: run it twice, or on two machines, and compare one number.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <cstdint>
#include <cstring>

// ---------- math ----------
struct Vec2 { double x = 0, y = 0; };
Vec2 operator+(Vec2 a, Vec2 b) { return {a.x + b.x, a.y + b.y}; }
Vec2 operator-(Vec2 a, Vec2 b) { return {a.x - b.x, a.y - b.y}; }
Vec2 operator*(Vec2 v, double s) { return {v.x * s, v.y * s}; }
double dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; }
double cross(Vec2 a, Vec2 b) { return a.x * b.y - a.y * b.x; }
Vec2 cross(double w, Vec2 r) { return {-w * r.y, w * r.x}; }      // w x r
double length(Vec2 v) { return std::sqrt(dot(v, v)); }
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }

// ---------- data ----------
struct Body {
    Vec2 p, v;
    double angle = 0, w = 0, radius = 0.5, invMass = 1, invI = 1;
    double restitution = 0.2, friction = 0.6;
    bool asleep = false;
    double sleepTimer = 0;
};
struct Segment { Vec2 a, b; };
struct Contact { int a, b; Vec2 n, point; double depth, bounce = 0, jn = 0, jt = 0; };
struct Joint { int a, b; double length; };

struct Stats { int pairTests = 0, contacts = 0, awake = 0; };

class World {
public:
    std::vector<Body> bodies;
    std::vector<Segment> segments;
    std::vector<Joint> joints;
    Vec2 gravity{0, -9.81};
    int iterations = 10;
    bool sleeping = true;
    Stats stats;

    int addCircle(Vec2 p, double r, double density = 1) {
        Body b; b.p = p; b.radius = r;
        if (density > 0) {
            double m = density * 3.141592653589793 * r * r;
            b.invMass = 1 / m; b.invI = 1 / (0.5 * m * r * r);
        } else { b.invMass = 0; b.invI = 0; }
        bodies.push_back(b);
        return int(bodies.size()) - 1;
    }

    void step(double dt) {
        // 1. integrate forces (sleeping and static bodies don't move)
        for (auto& b : bodies)
            if (b.invMass > 0 && !b.asleep) b.v = b.v + gravity * dt;

        // 2. collision detection: broad phase grid + narrow phase
        std::vector<Contact> contacts;
        findContacts(contacts);
        stats.contacts = int(contacts.size());

        // wake sleepers touched by moving bodies; otherwise a sleeper acts as static this step
        for (auto& c : contacts) {
            if (c.b < 0) continue;
            Body& A = bodies[c.a]; Body& B = bodies[c.b];
            if (A.asleep != B.asleep) {
                Body& mover = A.asleep ? B : A;
                if (dot(mover.v, mover.v) > 0.05) { A.asleep = B.asleep = false; A.sleepTimer = B.sleepTimer = 0; }
            }
        }
        for (auto& c : contacts) {
            Vec2 vr = relVel(c);
            double vn = dot(vr, c.n);
            c.bounce = vn < -1.0 ? -vn * mixRest(c) : 0;          // no bounce for slow contacts
        }

        // 3. sequential impulses
        for (int it = 0; it < iterations; it++) {
            for (auto& c : contacts) solveContact(c);
            for (auto& j : joints) solveJoint(j);
        }

        // 4. integrate velocities
        for (auto& b : bodies)
            if (b.invMass > 0 && !b.asleep) { b.p = b.p + b.v * dt; b.angle += b.w * dt; }

        // 5. positional correction (contacts with the depth found before the move, then joints)
        for (auto& c : contacts) correctContact(c);
        for (int it = 0; it < 4; it++) for (auto& j : joints) correctJoint(j);

        // 6. sleeping
        stats.awake = 0;
        for (auto& b : bodies) {
            if (b.invMass == 0) continue;
            double e = dot(b.v, b.v) + b.w * b.w * b.radius * b.radius;
            if (sleeping && e < 0.01) b.sleepTimer += dt; else b.sleepTimer = 0;
            if (b.sleepTimer > 0.5) { b.asleep = true; b.v = {}; b.w = 0; }
            if (!b.asleep) stats.awake++;
        }
    }

private:
    double invM(int i) const { return i < 0 || bodies[i].asleep ? 0 : bodies[i].invMass; }
    double invI(int i) const { return i < 0 || bodies[i].asleep ? 0 : bodies[i].invI; }
    double mixRest(const Contact& c) const { return c.b < 0 ? bodies[c.a].restitution : std::max(bodies[c.a].restitution, bodies[c.b].restitution); }
    double mixFric(const Contact& c) const { return c.b < 0 ? bodies[c.a].friction : std::sqrt(bodies[c.a].friction * bodies[c.b].friction); }

    Vec2 pointVel(int i, Vec2 point) const {
        if (i < 0) return {};
        const Body& b = bodies[i];
        return b.v + cross(b.w, point - b.p);
    }
    Vec2 relVel(const Contact& c) const { return pointVel(c.b, c.point) - pointVel(c.a, c.point); }

    void applyImpulse(int i, Vec2 P, Vec2 point) {
        if (i < 0 || bodies[i].asleep) return;
        Body& b = bodies[i];
        b.v = b.v + P * b.invMass;
        b.w += cross(point - b.p, P) * b.invI;
    }

    void findContacts(std::vector<Contact>& out) {
        // uniform grid: cell = largest diameter; std::map keeps the order deterministic
        double cell = 0;
        for (auto& b : bodies) cell = std::max(cell, 2 * b.radius);
        std::map<std::pair<int, int>, std::vector<int>> grid;
        for (int i = 0; i < int(bodies.size()); i++) {
            const Body& b = bodies[i];
            int x0 = int(std::floor((b.p.x - b.radius) / cell)), x1 = int(std::floor((b.p.x + b.radius) / cell));
            int y0 = int(std::floor((b.p.y - b.radius) / cell)), y1 = int(std::floor((b.p.y + b.radius) / cell));
            for (int x = x0; x <= x1; x++) for (int y = y0; y <= y1; y++) grid[{x, y}].push_back(i);
        }
        std::set<std::pair<int, int>> pairs;
        for (auto& [key, list] : grid)
            for (size_t i = 0; i < list.size(); i++)
                for (size_t j = i + 1; j < list.size(); j++) pairs.insert({std::min(list[i], list[j]), std::max(list[i], list[j])});
        stats.pairTests = int(pairs.size());

        for (auto [i, j] : pairs) {
            Body& A = bodies[i]; Body& B = bodies[j];
            if (A.invMass == 0 && B.invMass == 0) continue;
            if (A.asleep && B.asleep) continue;
            Vec2 d = B.p - A.p;
            double dist = length(d), r = A.radius + B.radius;
            if (dist >= r || dist == 0) continue;
            Vec2 n = d * (1 / dist);
            out.push_back({i, j, n, A.p + n * (A.radius - (r - dist) / 2), r - dist});
        }
        // static segments: tested against every awake body (a real engine keeps them in a static tree)
        for (int i = 0; i < int(bodies.size()); i++) {
            Body& A = bodies[i];
            if (A.invMass == 0 || A.asleep) continue;
            for (int s = 0; s < int(segments.size()); s++) {
                Vec2 a = segments[s].a, ab = segments[s].b - a;
                double t = std::clamp(dot(A.p - a, ab) / dot(ab, ab), 0.0, 1.0);
                Vec2 closest = a + ab * t, d = closest - A.p;
                double dist = length(d);
                if (dist >= A.radius || dist == 0) continue;
                out.push_back({i, -1 - s, d * (1 / dist), closest, A.radius - dist});
            }
        }
    }

    void solveContact(Contact& c) {
        Vec2 rA = c.point - bodies[c.a].p;
        Vec2 rB = c.b < 0 ? Vec2{} : c.point - bodies[c.b].p;
        double mA = invM(c.a), mB = invM(c.b), iA = invI(c.a), iB = invI(c.b);
        // normal impulse, clamped so the accumulated impulse only pushes
        double rnA = cross(rA, c.n), rnB = cross(rB, c.n);
        double kn = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
        if (kn == 0) return;
        double vn = dot(relVel(c), c.n);
        double dj = (-vn + c.bounce) / kn;
        double old = c.jn;
        c.jn = std::max(old + dj, 0.0);
        dj = c.jn - old;
        applyImpulse(c.a, c.n * -dj, c.point);
        applyImpulse(c.b, c.n * dj, c.point);
        // friction impulse, clamped to the Coulomb limit mu * jn
        Vec2 t{-c.n.y, c.n.x};
        double rtA = cross(rA, t), rtB = cross(rB, t);
        double kt = mA + mB + iA * rtA * rtA + iB * rtB * rtB;
        double vt = dot(relVel(c), t);
        double djt = -vt / kt, maxF = mixFric(c) * c.jn;
        double oldT = c.jt;
        c.jt = std::clamp(oldT + djt, -maxF, maxF);
        djt = c.jt - oldT;
        applyImpulse(c.a, t * -djt, c.point);
        applyImpulse(c.b, t * djt, c.point);
    }

    void correctContact(const Contact& c) {
        const double slop = 0.005, percent = 0.6;
        double mA = invM(c.a), mB = invM(c.b);
        if (mA + mB == 0) return;
        double push = std::max(c.depth - slop, 0.0) * percent / (mA + mB);
        if (mA > 0) bodies[c.a].p = bodies[c.a].p - c.n * (push * mA);
        if (mB > 0) bodies[c.b].p = bodies[c.b].p + c.n * (push * mB);
    }

    void solveJoint(const Joint& j) {
        Body& A = bodies[j.a]; Body& B = bodies[j.b];
        double mA = invM(j.a), mB = invM(j.b);
        if (mA + mB == 0) return;
        Vec2 d = B.p - A.p;
        double len = length(d);
        if (len == 0) return;
        Vec2 u = d * (1 / len);
        double vrel = dot(B.v - A.v, u);
        double lambda = -vrel / (mA + mB);               // rigid rod: remove all stretching velocity
        A.v = A.v - u * (lambda * mA);
        B.v = B.v + u * (lambda * mB);
    }

    void correctJoint(const Joint& j) {
        Body& A = bodies[j.a]; Body& B = bodies[j.b];
        double mA = invM(j.a), mB = invM(j.b);
        if (mA + mB == 0) return;
        Vec2 d = B.p - A.p;
        double len = length(d);
        if (len == 0) return;
        Vec2 u = d * (1 / len);
        double err = len - j.length;
        A.p = A.p + u * (err * mA / (mA + mB));
        B.p = B.p - u * (err * mB / (mA + mB));
    }
};

uint64_t stateHash(const World& w) {
    uint64_t h = 1469598103934665603ull;                 // FNV-1a over the raw bytes of every position
    for (auto& b : w.bodies) {
        unsigned char bytes[16];
        std::memcpy(bytes, &b.p.x, 8); std::memcpy(bytes + 8, &b.p.y, 8);
        for (unsigned char c : bytes) { h ^= c; h *= 1099511628211ull; }
    }
    return h;
}

double kinetic(const World& w) {
    double e = 0;
    for (auto& b : w.bodies)
        if (b.invMass > 0) e += 0.5 * dot(b.v, b.v) / b.invMass + 0.5 * b.w * b.w / b.invI;
    return e;
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    World world;
    world.segments = {{{-10, 0}, {10, 0}}, {{-10, 0}, {-10, 10}}, {{10, 0}, {10, 10}}, {{-9, 6}, {-3, 3}}};
    // a 4 x 3 block of balls above the ramp
    for (int row = 0; row < 3; row++)
        for (int col = 0; col < 4; col++)
            world.addCircle({-8 + col * 1.1 + row * 0.3, 8 + row * 1.1}, 0.5);
    // a hanging chain: a static anchor plus 6 links
    int prev = world.addCircle({5, 9}, 0.1, 0);
    for (int k = 1; k <= 6; k++) {
        int link = world.addCircle({5 + 0.6 * k, 9}, 0.15);
        world.joints.push_back({prev, link, 0.6});
        prev = link;
    }
    int n = int(world.bodies.size());
    const double dt = 1.0 / 60.0;
    for (int s = 1; s <= 600; s++) {
        world.step(dt);
        if (s % 60 == 0)
            std::cout << "t=" << std::setw(2) << s / 60 << " s  awake " << std::setw(2) << world.stats.awake
                      << "  contacts " << std::setw(2) << world.stats.contacts << "  pair tests " << std::setw(2) << world.stats.pairTests
                      << " (brute force " << n * (n - 1) / 2 << ")  kinetic " << kinetic(world) << " J\n";
    }
    std::cout << "chain end: (" << z0(world.bodies.back().p.x) << ", " << z0(world.bodies.back().p.y) << ")\n";
    std::cout << "state hash: " << std::hex << stateHash(world) << "\n";
}
t= 1 s  awake 18  contacts 10  pair tests 34 (brute force 171)  kinetic 75.108 J
t= 2 s  awake 18  contacts  4  pair tests 24 (brute force 171)  kinetic 242.196 J
t= 3 s  awake 18  contacts 12  pair tests 18 (brute force 171)  kinetic 107.249 J
t= 4 s  awake 18  contacts 15  pair tests 19 (brute force 171)  kinetic 11.862 J
t= 5 s  awake 17  contacts 17  pair tests 22 (brute force 171)  kinetic 1.823 J
t= 6 s  awake 15  contacts 16  pair tests 18 (brute force 171)  kinetic 3.039 J
t= 7 s  awake 14  contacts 15  pair tests 20 (brute force 171)  kinetic 0.073 J
t= 8 s  awake  6  contacts  0  pair tests 19 (brute force 171)  kinetic 2.755 J
t= 9 s  awake  6  contacts  0  pair tests 21 (brute force 171)  kinetic 0.328 J
t=10 s  awake  6  contacts  0  pair tests 20 (brute force 171)  kinetic 1.424 J
chain end: (6.711, 5.873)
state hash: 164ad09e69875b42

Read the table from top to bottom:

  • pair tests stay around 20 per step instead of the 171 a brute-force loop would test, and that ratio improves as the world grows.
  • awake drops from 18 to 6 as the balls settle and fall asleep; the six chain links never sleep because the chain keeps swinging.
  • contacts drop to 0 once every ball sleeps, because pairs of sleeping or static bodies aren't tested at all. That is where sleeping saves most of its time.
  • kinetic energy rises while the balls fall, drops as friction and inelastic contacts take it out, and what remains at the end is the swinging chain.

Tip: Change world.iterations to 2, or set world.sleeping = false, and run again. The state hash changes, which is exactly what a determinism test should tell you: any change to the solver gives a new "golden" value.

Step 4: The playable sandbox

Here is the same engine, line for line, in JavaScript, with a fixed 60 Hz step, a step cap against the spiral of death, and a canvas renderer. The spoke on each ball shows its rotation (watch friction spin the balls as they roll down the ramps).

  • Click empty space to drop a ball; drag a ball to throw it.
  • + Rope adds another chain.
  • Sleeping toggles sleeping; sleeping balls turn grey.
  • Debug draws the broad-phase grid and the contact normals.
  • Iterations cycles 10 → 1 → 4: with one iteration, watch the pile sag and the rope stretch.
html · try it yourself
<style>
  html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; color: #fff; font: 12px system-ui, sans-serif; }
  canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; touch-action: none; cursor: crosshair; }
  .ui { position: absolute; left: 6px; top: 6px; display: flex; gap: 4px; flex-wrap: wrap; }
  button { font: inherit; padding: 2px 6px; }
</style>
<canvas width="480" height="270"></canvas>
<div class="ui">
  <button id="reset">Reset</button><button id="rope">+ Rope</button>
  <button id="sleep">Sleeping: on</button><button id="debug">Debug: off</button>
  <button id="iters">Iterations: 10</button>
</div>
<script>
// ---------- a 2D physics sandbox: circles, static segments, distance joints ----------
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const SCALE = 20, W = cv.width, H = cv.height;           // 20 px per meter; world x -12..12, y 0..13
const toScreen = (p) => [(p.x + 12) * SCALE, H - 8 - p.y * SCALE];
const toWorld = (sx, sy) => ({ x: sx / SCALE - 12, y: (H - 8 - sy) / SCALE });

const add = (a, b) => ({ x: a.x + b.x, y: a.y + b.y });
const sub = (a, b) => ({ x: a.x - b.x, y: a.y - b.y });
const mul = (v, s) => ({ x: v.x * s, y: v.y * s });
const dot = (a, b) => a.x * b.x + a.y * b.y;
const cross = (a, b) => a.x * b.y - a.y * b.x;
const crossW = (w, r) => ({ x: -w * r.y, y: w * r.x });
const len = (v) => Math.hypot(v.x, v.y);

let bodies, segments, joints, contacts = [];
let iterations = 10, sleeping = true, debug = false, grab = null;
const stats = { pairs: 0, awake: 0 };

function addCircle(p, r, density = 1) {
  const m = density * Math.PI * r * r;
  bodies.push({ p, v: { x: 0, y: 0 }, angle: 0, w: 0, r, invMass: density ? 1 / m : 0, invI: density ? 1 / (0.5 * m * r * r) : 0,
    restitution: 0.2, friction: 0.6, asleep: false, sleepTimer: 0, hue: (bodies.length * 47) % 360 });
  return bodies.length - 1;
}
function addRope(x, y, links) {
  let prev = addCircle({ x, y }, 0.12, 0);
  for (let k = 1; k <= links; k++) {
    const link = addCircle({ x: x + 0.5 * k, y }, 0.15);
    joints.push({ a: prev, b: link, length: 0.5 });
    prev = link;
  }
}
function reset() {
  bodies = []; joints = [];
  segments = [[{ x: -12, y: 0 }, { x: 12, y: 0 }], [{ x: -12, y: 0 }, { x: -12, y: 14 }], [{ x: 12, y: 0 }, { x: 12, y: 14 }],
    [{ x: -11, y: 7 }, { x: -4, y: 3.5 }], [{ x: 1, y: 4 }, { x: 6, y: 5.5 }]];
  for (let row = 0; row < 3; row++)
    for (let col = 0; col < 5; col++) addCircle({ x: -10 + col * 1.1 + row * 0.3, y: 9 + row * 1.1 }, 0.5);
  addRope(7, 11, 7);
}

const invM = (i) => (i < 0 || bodies[i].asleep ? 0 : bodies[i].invMass);
const invI = (i) => (i < 0 || bodies[i].asleep ? 0 : bodies[i].invI);
const pointVel = (i, pt) => (i < 0 ? { x: 0, y: 0 } : add(bodies[i].v, crossW(bodies[i].w, sub(pt, bodies[i].p))));
const relVel = (c) => sub(pointVel(c.b, c.point), pointVel(c.a, c.point));
function impulse(i, P, pt) {
  if (i < 0 || bodies[i].asleep) return;
  const b = bodies[i];
  b.v = add(b.v, mul(P, b.invMass));
  b.w += cross(sub(pt, b.p), P) * b.invI;
}
function wake(b) { b.asleep = false; b.sleepTimer = 0; }

function findContacts() {
  const out = [];
  let cell = 0;
  for (const b of bodies) cell = Math.max(cell, 2 * b.r);
  const grid = new Map();
  bodies.forEach((b, i) => {
    for (let x = Math.floor((b.p.x - b.r) / cell); x <= Math.floor((b.p.x + b.r) / cell); x++)
      for (let y = Math.floor((b.p.y - b.r) / cell); y <= Math.floor((b.p.y + b.r) / cell); y++) {
        const key = x * 100003 + y;
        if (!grid.has(key)) grid.set(key, []);
        grid.get(key).push(i);
      }
  });
  const seen = new Set();
  for (const list of grid.values())
    for (let i = 0; i < list.length; i++)
      for (let j = i + 1; j < list.length; j++) {
        const a = Math.min(list[i], list[j]), b = Math.max(list[i], list[j]);
        const key = a * 65536 + b;
        if (seen.has(key)) continue;
        seen.add(key);
        const A = bodies[a], B = bodies[b];
        if ((A.invMass === 0 && B.invMass === 0) || (A.asleep && B.asleep)) continue;
        const d = sub(B.p, A.p), dist = len(d), r = A.r + B.r;
        if (dist >= r || dist === 0) continue;
        const n = mul(d, 1 / dist);
        out.push({ a, b, n, point: add(A.p, mul(n, A.r - (r - dist) / 2)), depth: r - dist, jn: 0, jt: 0, bounce: 0 });
      }
  stats.pairs = seen.size;
  bodies.forEach((A, i) => {
    if (A.invMass === 0 || A.asleep) return;
    segments.forEach(([a, b], s) => {
      const ab = sub(b, a);
      const t = Math.min(1, Math.max(0, dot(sub(A.p, a), ab) / dot(ab, ab)));
      const closest = add(a, mul(ab, t)), d = sub(closest, A.p), dist = len(d);
      if (dist >= A.r || dist === 0) return;
      out.push({ a: i, b: -1 - s, n: mul(d, 1 / dist), point: closest, depth: A.r - dist, jn: 0, jt: 0, bounce: 0 });
    });
  });
  return out;
}

function solveContact(c) {
  const rA = sub(c.point, bodies[c.a].p), rB = c.b < 0 ? { x: 0, y: 0 } : sub(c.point, bodies[c.b].p);
  const mA = invM(c.a), mB = invM(c.b), iA = invI(c.a), iB = invI(c.b);
  const rnA = cross(rA, c.n), rnB = cross(rB, c.n);
  const kn = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
  if (kn === 0) return;
  const old = c.jn;
  c.jn = Math.max(old + (-dot(relVel(c), c.n) + c.bounce) / kn, 0);
  const dj = c.jn - old;
  impulse(c.a, mul(c.n, -dj), c.point); impulse(c.b, mul(c.n, dj), c.point);
  const t = { x: -c.n.y, y: c.n.x };
  const rtA = cross(rA, t), rtB = cross(rB, t);
  const kt = mA + mB + iA * rtA * rtA + iB * rtB * rtB;
  const mu = c.b < 0 ? bodies[c.a].friction : Math.sqrt(bodies[c.a].friction * bodies[c.b].friction);
  const oldT = c.jt;
  c.jt = Math.min(mu * c.jn, Math.max(-mu * c.jn, oldT - dot(relVel(c), t) / kt));
  const djt = c.jt - oldT;
  impulse(c.a, mul(t, -djt), c.point); impulse(c.b, mul(t, djt), c.point);
}
function solveJoint(j) {
  const A = bodies[j.a], B = bodies[j.b], mA = invM(j.a), mB = invM(j.b);
  if (mA + mB === 0) return;
  const d = sub(B.p, A.p), l = len(d);
  if (!l) return;
  const u = mul(d, 1 / l), lambda = -dot(sub(B.v, A.v), u) / (mA + mB);
  A.v = sub(A.v, mul(u, lambda * mA)); B.v = add(B.v, mul(u, lambda * mB));
}
function correctJoint(j) {
  const A = bodies[j.a], B = bodies[j.b], mA = invM(j.a), mB = invM(j.b);
  if (mA + mB === 0) return;
  const d = sub(B.p, A.p), l = len(d);
  if (!l) return;
  const u = mul(d, 1 / l), err = l - j.length;
  A.p = add(A.p, mul(u, err * mA / (mA + mB))); B.p = sub(B.p, mul(u, err * mB / (mA + mB)));
}

function step(dt) {
  if (grab) {                                            // mouse drag: steer the body's velocity toward the pointer
    const b = bodies[grab.i];
    wake(b);
    b.v = mul(sub(grab.target, b.p), 12);
  }
  for (const b of bodies) if (b.invMass > 0 && !b.asleep) b.v = add(b.v, { x: 0, y: -9.81 * dt });
  contacts = findContacts();
  for (const c of contacts) {
    if (c.b < 0) continue;
    const A = bodies[c.a], B = bodies[c.b];
    if (A.asleep !== B.asleep) { const m = A.asleep ? B : A; if (dot(m.v, m.v) > 0.05) { wake(A); wake(B); } }
  }
  for (const c of contacts) {
    const vn = dot(relVel(c), c.n);
    c.bounce = vn < -1 ? -vn * bodies[c.a].restitution : 0;
  }
  for (let it = 0; it < iterations; it++) { contacts.forEach(solveContact); joints.forEach(solveJoint); }
  for (const b of bodies) if (b.invMass > 0 && !b.asleep) { b.p = add(b.p, mul(b.v, dt)); b.angle += b.w * dt; }
  for (const c of contacts) {
    const mA = invM(c.a), mB = invM(c.b);
    if (mA + mB === 0) continue;
    const push = Math.max(c.depth - 0.005, 0) * 0.6 / (mA + mB);
    if (mA) bodies[c.a].p = sub(bodies[c.a].p, mul(c.n, push * mA));
    if (mB) bodies[c.b].p = add(bodies[c.b].p, mul(c.n, push * mB));
  }
  for (let it = 0; it < 4; it++) joints.forEach(correctJoint);
  stats.awake = 0;
  for (const b of bodies) {
    if (b.invMass === 0) continue;
    const e = dot(b.v, b.v) + b.w * b.w * b.r * b.r;
    if (sleeping && e < 0.01) b.sleepTimer += dt; else b.sleepTimer = 0;
    if (b.sleepTimer > 0.5) { b.asleep = true; b.v = { x: 0, y: 0 }; b.w = 0; }
    if (!sleeping) b.asleep = false;
    if (!b.asleep) stats.awake++;
  }
}

function draw() {
  ctx.fillStyle = '#0e1018'; ctx.fillRect(0, 0, W, H);
  if (debug) {
    let cell = 0; for (const b of bodies) cell = Math.max(cell, 2 * b.r);
    ctx.strokeStyle = 'rgba(255,255,255,0.06)';
    for (let x = -12; x <= 12; x += cell) { const [sx] = toScreen({ x, y: 0 }); ctx.beginPath(); ctx.moveTo(sx, 0); ctx.lineTo(sx, H); ctx.stroke(); }
    for (let y = 0; y <= 14; y += cell) { const [, sy] = toScreen({ x: 0, y }); ctx.beginPath(); ctx.moveTo(0, sy); ctx.lineTo(W, sy); ctx.stroke(); }
  }
  ctx.strokeStyle = '#90a4ae'; ctx.lineWidth = 3;
  for (const [a, b] of segments) { ctx.beginPath(); ctx.moveTo(...toScreen(a)); ctx.lineTo(...toScreen(b)); ctx.stroke(); }
  ctx.lineWidth = 2; ctx.strokeStyle = '#bcaaa4';
  for (const j of joints) { ctx.beginPath(); ctx.moveTo(...toScreen(bodies[j.a].p)); ctx.lineTo(...toScreen(bodies[j.b].p)); ctx.stroke(); }
  ctx.lineWidth = 1;
  bodies.forEach((b, i) => {
    const [sx, sy] = toScreen(b.p);
    ctx.fillStyle = b.invMass === 0 ? '#78909c' : b.asleep ? '#455a64' : `hsl(${b.hue},70%,60%)`;
    ctx.beginPath(); ctx.arc(sx, sy, b.r * SCALE, 0, Math.PI * 2); ctx.fill();
    if (b.r > 0.3) {                                      // a spoke shows the rotation
      ctx.strokeStyle = '#0e1018'; ctx.beginPath(); ctx.moveTo(sx, sy);
      ctx.lineTo(sx + Math.cos(b.angle) * b.r * SCALE, sy - Math.sin(b.angle) * b.r * SCALE); ctx.stroke();
    }
    if (grab && grab.i === i) { ctx.strokeStyle = '#fff'; ctx.beginPath(); ctx.moveTo(sx, sy); ctx.lineTo(...toScreen(grab.target)); ctx.stroke(); }
  });
  if (debug) {
    ctx.strokeStyle = '#ff5252';
    for (const c of contacts) {
      const [px, py] = toScreen(c.point);
      ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(px + c.n.x * 10, py - c.n.y * 10); ctx.stroke();
    }
  }
  ctx.fillStyle = '#ccc'; ctx.textAlign = 'right';
  const n = bodies.length;
  ctx.fillText(`bodies ${n}  awake ${stats.awake}  contacts ${contacts.length}  pair tests ${stats.pairs} (brute force ${n * (n - 1) / 2})`, W - 6, 40);
  ctx.fillStyle = '#888';
  ctx.fillText('click empty space: drop a ball   drag a ball: throw it', W - 6, 54);
}

function pointer(e) {
  const r = cv.getBoundingClientRect();
  return toWorld((e.clientX - r.left) * W / r.width, (e.clientY - r.top) * H / r.height);
}
cv.addEventListener('pointerdown', (e) => {
  const p = pointer(e);
  const hit = bodies.findIndex((b) => b.invMass > 0 && len(sub(b.p, p)) < b.r + 0.1);
  if (hit >= 0) { grab = { i: hit, target: p }; cv.setPointerCapture(e.pointerId); }
  else if (bodies.length < 200) addCircle(p, 0.3 + ((bodies.length * 7) % 5) * 0.08);
});
cv.addEventListener('pointermove', (e) => { if (grab) grab.target = pointer(e); });
cv.addEventListener('pointerup', () => { grab = null; });
cv.addEventListener('pointercancel', () => { grab = null; });
const btn = (id, fn) => document.getElementById(id).addEventListener('click', fn);
btn('reset', reset);
btn('rope', () => addRope(-6 + (joints.length % 3) * 3, 12.5, 6));
btn('sleep', (e) => { sleeping = !sleeping; e.target.textContent = `Sleeping: ${sleeping ? 'on' : 'off'}`; });
btn('debug', (e) => { debug = !debug; e.target.textContent = `Debug: ${debug ? 'on' : 'off'}`; });
btn('iters', (e) => { iterations = iterations === 10 ? 1 : iterations === 1 ? 4 : 10; e.target.textContent = `Iterations: ${iterations}`; });

reset();
const STEP = 1 / 60;
let acc = 0, last = performance.now();
requestAnimationFrame(function frame(now) {
  acc += Math.min((now - last) / 1000, 0.1);
  last = now;
  let steps = 0;
  while (acc >= STEP && steps < 4) { step(STEP); acc -= STEP; steps++; }
  if (steps === 4) acc = 0;
  draw();
  requestAnimationFrame(frame);
});
</script>

What you practised

  • A fixed-step loop with semi-implicit Euler and a step cap.
  • Closest-point contact generation for circles and segments.
  • Sequential impulses with accumulated, clamped normal and friction impulses, restitution with a velocity threshold, and positional correction with slop.
  • A deterministic uniform-grid broad phase, sleeping with wake-up on contact, distance joints and a state hash.

Ideas to extend it

  1. Boxes. Add oriented boxes with SAT for the normal and depth, and clip the incident edge against the reference face to get up to two contact points. Two points are what make boxes stack without rocking.
  2. Warm starting. Keep each contact's accumulated jn and jt from the previous step (match contacts by body pair) and apply them before the first iteration. Stacks converge in far fewer iterations.
  3. Continuous collision. Give fast balls a swept test against segments (CCD) and fire one at the ramp at 200 m/s.
  4. Islands. Group touching bodies and put a whole island to sleep at once, so a pile doesn't wake ball by ball.
  5. A character. Add a kinematic capsule driven by collide and slide that can push the balls.

Test yourself

Why does the engine compute each contact's restitution target before the solver iterations, not inside them?

  1. It is faster
  2. The target must come from the approach speed before any impulse; inside the loop the speed has already been changed
  3. Restitution only applies to static contacts
  4. To avoid square roots

In step 3, why does the contact count fall to 0 when all balls are asleep?

  1. The balls fell through the floor
  2. Pairs where both bodies are asleep or static are skipped, so no contacts are generated
  3. The grid is cleared
  4. Friction removed the contacts

What does the state hash at the end of step 3 let you check?

  1. That the simulation is physically correct
  2. That two runs produced bit-identical positions
  3. That no bodies overlap
  4. That the frame rate was constant