Skip to content

michael@malura:~$ developer // data hoarder // nerd // homelab enjoyer

Boids: Flocking

A flock of birds that turns together looks choreographed. Anyone who wants to rebuild that first thinks of a leader that everyone follows, or of paths laid out in advance. In 1986 Craig Reynolds showed that neither is needed: every bird keeps three simple rules and only looks at its neighbors. The flock does not exist as a data structure anywhere. How a wish turns into a steering force is in Steering Behaviors, this builds on it.

In the demo 600 birds fly through a world that starts over at its edges. The three sliders weigh separation, alignment and cohesion. The mouse is a predator: birds near it turn orange and flee. At the bottom right you switch the neighbor search between grid and brute force, the card at the top left shows how many distance tests a step needs and how long it takes. "Show grid" draws the cells the orange bird looks at. Reynolds explains the idea with pictures on his boids page, the code here is mine.

Who counts as a neighbor

A bird sees every other bird closer than 50 px. For each neighbor it adds up three things: its velocity, the vector to it and, if it is closer than 14 px, a push away from it:

inline void accumulate(Sums& s, const Bird& me, const Bird& other, const World& w, const Params& p) {
    const Vec2 d{wrapDelta(me.pos.x, other.pos.x, w.width), wrapDelta(me.pos.y, other.pos.y, w.height)};
    const float distSq = lengthSq(d);
    if (!(distSq < p.perception * p.perception)) return;
    s.vel += other.vel;
    s.offset += d;
    ++s.count;
    // Two birds on the very same spot have no direction to part in; their different velocities part them soon enough.
    if (distSq < p.separationRadius * p.separationRadius && distSq > 1e-12F) {
        s.away -= d * (1.0F / distSq);
        ++s.crowd;
    }
}

The push is the direction away from the neighbor times 1/distance, so a very close one pushes harder. The < is strict, a bird exactly on the radius does not count. Two birds on the same spot have no direction, they part through their different velocities.

The distances come from wrapDelta, because the world is a torus:

inline float wrapDelta(float from, float to, float size) {
    float d = to - from;
    const float half = size * 0.5F;
    if (d > half) d -= size;
    else if (d < -half) d += size;
    return d;
}

For a bird at x = 1 a neighbor at x = 959 is two pixels away, not 958. Without that every flock would tear apart at the edge.

From sums to forces

Each rule turns its sum into a wish and steers with desired velocity minus velocity, limited to maxForce:

inline Vec2 steerToward(Vec2 desired, Vec2 vel, float maxForce) {
    if (lengthSq(desired) == 0.0F) return {};
    return limited(desired - vel, maxForce);
}
inline Vec2 flockSteering(const Bird& me, const Sums& s, const Params& p) {
    Vec2 total;
    if (s.crowd > 0) {
        total += steerToward(normalized(s.away) * p.maxSpeed, me.vel, p.maxForce) * p.separation;
    }
    if (s.count > 0) {
        total += steerToward(normalized(s.vel) * p.maxSpeed, me.vel, p.maxForce) * p.alignment;
        // Towards the center of the neighbors, fading out inside half the perception so a bird in the middle of
        // its group does not jitter around a center that is almost on top of it.
        const Vec2 center = s.offset * (1.0F / static_cast<float>(s.count));
        const float dist = length(center);
        const float fade = std::min(1.0F, dist / (p.perception * 0.5F));
        total += steerToward(normalized(center) * p.maxSpeed, me.vel, p.maxForce) * (p.cohesion * fade);
    }
    return total;
}

Separation wants away from the sum of the pushes, alignment wants the averaged heading of the neighbors at full speed, cohesion wants the center of the neighbors. The factors at the end of each line are the sliders. I fade cohesion out inside half the perception (fade), otherwise a bird in the middle of its group jitters around a center that is almost on top of it.

All accelerations are computed from the state before the step and applied afterwards, otherwise the result would depend on the order of the birds. After that the speed is clamped to 70 to 130 px/s so that no bird stands still in the air.

What comes out

I measured the polarization, the length of the mean of all heading vectors. 0 means everyone flies somewhere else, 1 means everyone flies the same way. Measured with 400 birds after ten seconds of simulation (60 steps per second, the same setup is in test.cpp): with all three rules 0.98, without alignment 0.12, with separation only 0.04. At the start, with random headings, the value is below 0.2. Without cohesion it stays at 0.99. So the common direction comes from alignment alone, cohesion keeps the groups together.

My first values (perception 60 px, separation radius 22 px, cohesion 0.9) gave an even grid of birds that all flew the same way. That does not look like a flock. With 50 px, 14 px and cohesion 1.5 clumps form with gaps between them.

The predator

Fleeing uses the same steering formula:

inline Vec2 fleeSteering(const Bird& me, const Predator& pr, const World& w, const Params& p) {
    if (!inFear(me, pr, w, p)) return {};
    const Vec2 d{wrapDelta(me.pos.x, pr.pos.x, w.width), wrapDelta(me.pos.y, pr.pos.y, w.height)};
    const float dist = length(d);
    Vec2 away = dist > 1e-6F ? d * (-1.0F / dist) : normalized(me.vel);
    if (lengthSq(away) == 0.0F) away = {1.0F, 0.0F};  // on top of the predator and standing still: any way will do
    const float strength = 1.0F - dist / p.fearRadius;
    return steerToward(away * p.maxSpeed, me.vel, p.maxForce * p.fearBoost) * strength;
}

It may use four times maxForce, and its strength rises from 0 at the edge of the 90 px to 1 right at the predator, so there is no jump when a bird enters the radius. If the predator sits exactly on the bird there is no direction to flee in, then the heading counts.

The mistake: n squared

The naive neighbor search asks every bird about every other bird:

for (std::size_t j = 0; j < birds_.size(); ++j) {
    if (j == i) continue;
    ++tests;
    accumulate(s, birds_[i], birds_[j], world_, p);
}

With 1000 birds that is 999,000 distance tests per step, with 4000 it is already 15,996,000. With the grid (chip "G") the cells are at least as wide as the perception, so every neighbor sits in the bird's own cell or one of the eight around it:

grid_.forEachCandidate(birds_[i].pos, [&](int j) {
    if (static_cast<std::size_t>(j) == i) return;
    ++tests;
    accumulate(s, birds_[i], birds_[static_cast<std::size_t>(j)], world_, p);
});

The 960 x 370 px world gives 19 x 7 cells at 50 px perception. The grid is rebuilt every step, by counting sort without an allocation per bird, and the time for that is part of the measured step time. Grid::block returns the cell columns (or rows) of the 3x3 block with wrap and leaves out duplicates. If the world had only one or two cells in a direction, the same bird would otherwise be counted several times, there is a test for that.

I measured in the browser (Chromium on my Mac), read off the card in the demo. With 1000 birds: grid 155,196 tests and 1.22 ms per step, brute force 999,000 tests and 2.49 ms. With 2000: 361,216 tests and 1.78 ms against 3,998,000 tests and 9.76 ms. With 4000: 1,381,506 tests and 6.50 ms against 15,996,000 tests and 42.40 ms, and with brute force the demo only runs at 8 instead of 60 frames per second. Per frame there are at most three simulation steps, after that the simulation slows down rather than freezing the page.

If you look closely, the grid also needs about four times the time per doubling (1.78 ms, then 6.50 ms). The world has a fixed size, with more birds the density rises and with it the number of neighbors per bird. The grid divides the work by the number of cells, it does not turn it into n. With evenly spread birds it would be 9 of 133 cells, about 7 percent of all pairs. Measured is 8.6 percent at 4000 birds, because the flocks are denser than average. A spatial hash does better, that gets its own post later.

What's missing

In Reynolds' version the neighborhood has an angle from the heading on top of the distance, my birds see all around. There are no obstacles and no third dimension. The predator does not hunt, it only gets in the way.

The code is in the repo under boids. The project Game Dev Snippets collects all demos of the series.

04.12.2026 updated 06.11.2026
Share X Reddit Hacker News LinkedIn E-Mail
Subscribe to new posts RSS JSON