Creative Coding From Zero · Episode 15
Differential Growth
Differential Growth is Episode 15 of Creative Coding From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
Start with a single closed line — a circle of points. Tell every point two things: stay close to your two neighbors, and push away from anyone else who gets too near. Then, wherever the line stretches thin, slip a new point into the gap. That's it. Those three rules, run sixty times a second, make a line that grows until it runs out of room and folds in on itself — into the looping, crowded, brain-coral curves you can't stop staring at.
This is differential growth, and it's the algorithm behind fingerprints, the wrinkles of a brain, the folds of an intestine, and the ruffled edge of a kale leaf. Nature uses it whenever a boundary grows faster than the space it lives in. We're going to build it from scratch in raw canvas 2D — and the hard part isn't the biology, it's the performance: as the line multiplies into thousands of points, naive neighbor-checking dies. The fix is a spatial-hash grid, and it's the star of this episode. Watch the demo below grow live, then reseed it — every seed buckles into a different organism.
What you're looking at
One continuous line, drawn as a closed loop. It begins as a tidy little ring of a
few dozen points. Every frame, three forces act on each point: a repulsion
that shoves apart points that have drifted too close, an attraction
that pulls each point back toward the midpoint of its two path-neighbors (keeping the
line connected and evenly spaced), and a growth step that inserts a
fresh point into any edge that has been stretched too long. Repulsion makes the line
want to spread out; the fixed neighbor-spacing means it can only spread by getting
longer; and a longer line in a bounded space has no choice but to fold. The
badge tracks the live node count; the line stops growing when it hits the
max nodes cap. Step the stage dropdown from 1 to 6 to peel
the system apart one rule at a time.
Stage 1 — The polyline
Before any forces, we just need the thing that grows: an ordered list of points,
each linked to the next, with the last linked back to the first. A closed
polyline. We seed it as a small circle so it starts as a clean ring.
In this stage nothing moves except a gentle breathing wobble — it's here only so you
can see the raw material. A point isn't special; it's just an x and a
y with two implicit neighbors, the one before it and the one after it in
the array. Everything else in this episode is a rule about how that little bundle
relates to its neighbors and to its surroundings.
Stage 2 — Repulsion
Now switch on the first force. Each point looks at every nearby point — not every point, just the close ones — and gets pushed directly away from it, harder the closer it is. On its own, repulsion blows the ring apart like a dandelion: with no counter-force, the points just fly outward forever. That's expected and even useful to watch, because it shows you exactly what repulsion wants to do. The whole rest of the system is about harnessing that outward pressure instead of letting it escape. The radius slider sets how far a point can "feel" its neighbors — the single most important knob for the final look.
Stage 3 — Attraction
Add the leash. Every point is pulled toward the average position of its two path-neighbors, which does two jobs at once: it keeps the line connected (no point can wander off) and it keeps the spacing even (bunched points spread, stretched ones contract). With attraction and repulsion both on but growth still off, the ring relaxes into a smooth, taut, evenly-spaced circle and just sits there, quivering — a perfect equilibrium. It's beautiful and completely stuck. A fixed number of points can only ever make a fixed amount of line. To get folds, the line has to be allowed to grow.
Stage 4 — Growth
Here's the magic ingredient. Each frame we scan the edges between consecutive points, and wherever an edge has been stretched past a threshold length, we insert a new point at its midpoint. The line gets longer — but it lives in the same bounded box, and its neighbor-spacing is fixed, so the only way to fit more length into the same space is to bend. Watch the ring start to wave at its edges, then ripple, then wrinkle. The growth-rate slider controls how many insertions we allow per frame: slow growth gives graceful, well-resolved folds; fast growth buckles violently into chaos. This tension between growth and space is the entire phenomenon.
Stage 5 — The fold emerges
Nothing new is switched on here — this is stages 2, 3, and 4 running together, tuned and left alone to do their thing. Repulsion keeps the line from ever crossing itself; attraction keeps it smooth and evenly spaced; growth keeps feeding it more length. The result is mesmerizing: the line crowds against itself, folds back, folds again, and fills the space with meandering, non-self-intersecting curves — the unmistakable texture of brain coral, of a fingerprint, of a gut. Let it run. It will keep discovering new folds until it hits the node cap, and it never folds the same way twice from a different seed.
Stage 6 — Styled blob
Same simulation, dressed for the gallery. We color the line by each node's age — the order it was born in — using a cosine palette, so the original ring and the freshly-grown folds read as different bands of color, like growth rings in wood. We draw it as a filled, smooth closed shape with a luminous stroke on top, and a soft glow underneath. Pick a palette, let it grow into a dense organic blob, and hit save PNG when it looks frame-worthy. Every seed is a different creature; this is the stage built to be screenshotted.
How the code works
The data model is deliberately tiny. A node is { x, y, age }, and the
whole organism is just an array of them, in path order. Index i's
neighbors are i-1 and i+1, wrapping around because the loop
is closed. Everything below operates on that one array.
(a) Repulsion via a spatial-hash grid
The obvious way to push points apart is a double loop: for every point, check every other point. That's O(N²), and with a few thousand growing nodes it's instant death — millions of distance checks per frame. The fix is a spatial hash: chop the canvas into square cells the size of the repulsion radius, drop each point into its cell, and then to find a point's neighbors only look in its own cell plus the eight around it. Points further than one cell away are physically incapable of being within the radius, so we never even test them. Cost drops to roughly O(N).
// One flat grid, rebuilt each frame. cell = repulsion radius.
function buildGrid(nodes, cell) {
const grid = new Map(); // "cx,cy" -> array of node indices
const inv = 1 / cell;
for (let i = 0; i < nodes.length; i++) {
const cx = Math.floor(nodes[i].x * inv);
const cy = Math.floor(nodes[i].y * inv);
const key = cx + ',' + cy;
let bucket = grid.get(key);
if (!bucket) grid.set(key, bucket = []);
bucket.push(i);
}
return grid;
}
// Push each node away from neighbors within `radius` — only nearby cells.
function repel(nodes, grid, radius, force) {
const inv = 1 / radius, r2 = radius * radius;
for (let i = 0; i < nodes.length; i++) {
const a = nodes[i];
const cx = Math.floor(a.x * inv), cy = Math.floor(a.y * inv);
let dx = 0, dy = 0;
for (let ox = -1; ox <= 1; ox++) // this cell + 8 neighbors
for (let oy = -1; oy <= 1; oy++) {
const bucket = grid.get((cx+ox) + ',' + (cy+oy));
if (!bucket) continue;
for (const j of bucket) {
if (j === i) continue;
const b = nodes[j];
const ex = a.x - b.x, ey = a.y - b.y;
const d2 = ex*ex + ey*ey;
if (d2 > r2 || d2 === 0) continue;
const d = Math.sqrt(d2);
const w = (1 - d / radius) / d; // stronger when closer
dx += ex * w; dy += ey * w;
}
}
a.fx += dx * force; a.fy += dy * force; // accumulate, apply later
}
}
The grid is rebuilt from scratch every frame — that sounds wasteful, but it's a single linear pass and far cheaper than keeping it incrementally correct as thousands of points move. The key insight is that the cell size equals the search radius, which guarantees any point within range lives in one of the nine cells we check.
(b) Path attraction — a spring with a rest length
Repulsion alone is anarchy. Attraction is the constitution: it keeps each node tied
to its neighbors at a sensible distance. The naive version — pull each node toward the
midpoint of its neighbors — has a fatal flaw: it relentlessly shortens edges
toward zero, and an edge that can never get long can never be split, so the line can
never grow. Instead we treat every edge as a spring with a rest length:
if an edge is longer than rest we pull its endpoints together, if shorter
we push them apart. Edges settle near the rest length but are free to stretch
past it when repulsion crowds them — and that stretch is what triggers growth.
// Each edge wants to be `rest` long. Signed force: pull if too long, push if short.
function attract(nodes, force, rest) {
const n = nodes.length;
for (let i = 0; i < n; i++) {
const a = nodes[i];
const next = nodes[(i + 1) % n]; // wrap: closed loop
const dx = next.x - a.x, dy = next.y - a.y;
const d = Math.hypot(dx, dy) || 1e-6;
const diff = (d - rest) / d * 0.5 * force; // + too long, − too short
a.fx += dx * diff; a.fy += dy * diff; // move both endpoints
next.fx -= dx * diff; next.fy -= dy * diff;
}
}
Tuning the balance between this spring force and the repulsion force is
the whole art. Make repulsion too weak and the springs win — the line settles into a
taut circle and stops growing. Make it too strong and the line frays into noisy
spaghetti. The demo's defaults put repulsion slightly ahead, so the boundary keeps
inflating and the line keeps having to fold to fit. Crucially, the rest
length is smaller than the split threshold, leaving a band where edges can
stretch, get split, and grow.
(c) Node insertion on long edges
Growth is what separates this from an ordinary particle relaxation. We walk the
edges and, wherever consecutive nodes have drifted further apart than
maxEdge, we splice a new node in between them. Critically, we only add to
long edges — adding everywhere would double the count every frame and
instantly explode. Inserting midpoints on stretched edges is what lets the line gain
length exactly where it's under tension, which is exactly where folds want to form.
// Insert a midpoint into any edge longer than maxEdge — but cap per frame.
function grow(nodes, maxEdge, budget, maxNodes) {
for (let i = 0; i < nodes.length && budget > 0; i++) {
if (nodes.length >= maxNodes) break; // perf cap
const a = nodes[i];
const b = nodes[(i + 1) % nodes.length];
const dx = b.x - a.x, dy = b.y - a.y;
if (dx*dx + dy*dy > maxEdge * maxEdge) {
const mid = { x: (a.x+b.x)*0.5, y: (a.y+b.y)*0.5,
age: ++birthCounter, fx: 0, fy: 0 };
nodes.splice(i + 1, 0, mid); // drop it into the path
i++; // skip the node we just made
budget--; // spend from the frame budget
}
}
}
The budget is the growth-rate slider: it caps how many insertions we
allow per frame so the line resolves smoothly instead of detonating. Each new node
records the birthCounter at the moment it was created — that's the
age we color by in Stage 6, and it's why the folds read like tree rings.
(d) The growth loop + rendering
Now we stitch it together. Each frame: build the grid, accumulate repulsion and
attraction forces into every node, integrate (move each node by its accumulated force,
clamped so nothing teleports), then grow. Finally we draw the whole path as one closed
stroke. Because this is canvas 2D, "render the path" is genuinely just
moveTo + a run of lineTo back to the start.
const desired = repulsionRadius * 0.20; // rest edge length
const split = repulsionRadius * 0.30; // subdivide above this
function step() {
for (const p of nodes) { p.fx = 0; p.fy = 0; } // reset accumulators
const grid = buildGrid(nodes, repulsionRadius);
if (REPEL_ON) repel(nodes, grid, repulsionRadius, 0.55);
if (ATTRACT_ON) attract(nodes, 0.55, desired);
for (const p of nodes) { // integrate, clamp step
const m = Math.hypot(p.fx, p.fy);
const s = m > MAXSTEP ? MAXSTEP / m : 1;
p.x += p.fx * s; p.y += p.fy * s;
}
if (GROW_ON) grow(nodes, split, budget, maxNodes);
}
function draw() {
ctx.clearRect(0, 0, W, H);
ctx.beginPath();
ctx.moveTo(nodes[0].x, nodes[0].y);
for (let i = 1; i < nodes.length; i++) ctx.lineTo(nodes[i].x, nodes[i].y);
ctx.closePath(); // it's a loop
ctx.stroke();
}
Notice that three lengths are all tied to the one repulsion radius: the
rest edge length (radius * 0.20), the split threshold
(radius * 0.30), and the push range (radius itself). Because
the radius is several times the rest length, each node feels many non-neighbors
at once — that crowding pressure is what keeps inflating the boundary and stretching
edges past the split threshold, frame after frame. Slide the radius and you rescale the
whole organism at once: small radius packs in fine, dense folds; large radius makes
bigger, chunkier loops. That single coupling is why one slider so dramatically reshapes
the result.
Common pitfalls
- O(N²) repulsion. The number-one trap. A naive all-pairs loop is fine at 100 nodes and a slideshow at 3,000. The spatial-hash grid isn't an optimization you add later — it's the thing that makes differential growth possible at all. If your fps collapses as the line grows, this is why.
- Inserting everywhere. If you subdivide every edge each frame instead of only the stretched ones, the node count doubles per frame and you're at the cap (and a frozen tab) in seconds. Only long edges earn a new node, and even then, cap insertions per frame with a budget.
- Self-intersection. If the line crosses itself, the organic look is ruined. Properly-tuned repulsion prevents crossings for free — neighboring strands push apart before they can touch. If you see crossings, your repulsion radius is too small relative to your edge length, or the repulsion force is too weak.
- Growth rate too high. Add length faster than the relaxation can smooth it and the line buckles into noisy chaos instead of clean coral. Slow, patient growth almost always looks better. When in doubt, turn the rate down.
- No node cap. Differential growth wants to grow forever. Without a
hard
maxNodesceiling, an unattended tab will climb to tens of thousands of nodes and crawl. Cap it, and stop inserting once you hit the cap. - Unclamped steps. When two points start nearly coincident, the repulsion force spikes and a point can teleport across the canvas. Clamp each node's per-frame movement to a maximum so a force spike nudges instead of launches.
Exercises
- Grow toward a target shape. Add a weak attraction toward the nearest point on a target outline (a star, a letter, a heart). The line will grow, fold, and gradually fill that silhouette with coral texture — text or logos rendered as living, wrinkled line. Sample the target as a set of points and pull each node toward its closest one with a small force.
- Multiple growing lines. Seed two or three separate loops that share one spatial-hash grid, so they repel each other as well as themselves. Watch them compete for space and pack together like neighboring organisms — the grid already makes cross-line repulsion almost free.
- Vary growth by a noise field. Copy
makeNoisefrom the authoring brief and let the local fbm value modulate the per-edge growth threshold (or the repulsion radius). Some regions grow lush and densely folded, others stay smooth — biological-looking variation across a single organism. Try animating the noise so the growth pattern drifts over time.
What's next
Episode 16 — the Season 2 systems finale. We've spent this season on systems that organize themselves: flow fields, particle swarms, reaction patterns, and now a growing boundary. The finale ties the thread together — composing several of these systems into one piece, where the output of one feeds the next, and the whole thing stays alive and reproducible from a single seed. Differential growth makes a perfect ingredient: imagine a flow field steering the growth, or a swarm seeding where new folds appear. Bring this episode's coral with you.
Cross-links worth chasing: push the per-node forces onto the GPU with a shaders compute pass to grow lines with hundreds of thousands of nodes; lift the loop into 3D in three.js to grow folded surfaces instead of folded lines; or drive the growth rate with audio so the organism breathes in time with music.