Creative Coding From Zero · Episode 14
Wave Function Collapse
Wave Function Collapse is Episode 14 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 grid where every cell could be anything — a pure cloud of possibility, every tile overlaid on every cell at once. Then play a patient game: find the cell that's least uncertain, collapse it to a single tile, and let that decision ripple outward, quietly deleting the options it just made impossible from its neighbors, and their neighbors, until the whole board is consistent again. Repeat. One cell at a time, a coherent little world condenses out of static. That's Wave Function Collapse, and it's the algorithm behind Townscaper, Bad North, Caves of Qud, and a thousand procedural-generation experiments.
The demo below is the whole thing, running live and never stopping. A hand-made tileset of a few cells, a table of which edges are allowed to touch, and a loop of observe and propagate. Watch the entropy drain out of the grid as it solves itself; when it finishes it pauses for a beat to admire the result, then wipes clean and does it all again with a fresh seed. No images, no training data, no neural anything — just constraints, a queue, and a seeded coin flip. Pick a tileset, drag the grid size, and watch possibility become a map.
What you're looking at
Every square in the grid is a cell, and at the start every cell holds the full set of tiles — it is in superposition, undecided. In the early stages we draw that uncertainty literally: a cell with many options is rendered dim and muddy (all its possible tiles blended together), a cell with few options is brighter and sharper, and a fully collapsed cell — exactly one tile left — is drawn crisply. The number of options a cell has left is its entropy. The algorithm always attacks the lowest-entropy cell first, because that's where it has the least freedom and therefore the most information.
Use the stage dropdown to walk through the six phases of the idea, the
tileset picker to swap between three hand-made rule sets, and the
grid slider to change the board size. Turn auto off and click
once to single-step the solver and watch one observe-and-propagate cycle in
isolation. regenerate rolls a new seed and starts over; the same seed always
produces the exact same map. In stages 5 and 6 the solver runs to completion and then
restarts forever, so the demo is always generating something.
Stage 1 — The tiles and their adjacency rules
WFC comes in two flavors. The overlapping model learns its rules by scanning a sample bitmap for every NxN patch — powerful, but fiddly. We're building the simple tiled model: a small set of hand-drawn tiles plus an explicit table of which tile may sit next to which. That table is the entire "intelligence" of the generator. Get the tiles and edges right and coherent worlds fall out for free.
The trick that makes the rules tiny is edge sockets. Each tile
describes its four sides — up, right, down, left — with a label. Two tiles may be
neighbors if and only if their touching edges carry the same label. A pipe tile
whose right edge is labelled "pipe" can only sit to the left of a tile whose
left edge is also "pipe". Edges labelled "none" (bare
background) only meet other "none" edges. This stage shows the tileset and,
for the hovered tile, highlights which tiles are legal on each side.
Here is the pipes tileset — a blank cell, four "stub" pieces, two straights, four elbows. Notice how few rules we actually write: just a socket string per edge.
Stage 2 — Superposition: every cell is every tile at once
Before any decision, each cell's state is the full set of tile indices. We store that
as a plain array of booleans (a bitmask would be faster, but booleans read clearly):
cell.options[t] is true while tile t is still
possible. A freshly reset grid has every option true everywhere — maximum
entropy, maximum fog. This stage renders that fog: cells are dark and ambiguous because
they're showing the average of everything they could still become. There's nothing to
look at yet, and that's the point. The whole job of the algorithm is to turn this
uniform haze into a specific picture, decision by decision.
Stage 3 — Observe: collapse the least-uncertain cell
An observation picks one cell and forces it down to a single tile.
Which cell? The one with the lowest entropy — the fewest remaining options
(ties broken randomly so the output doesn't streak). Collapsing a low-entropy cell is the
safest move: it has the least room to cause a contradiction later. Once chosen, we pick
one of its surviving tiles by a weighted random draw (some tiles can be
rarer than others) and set every other option in that cell to false. One
cell just went from a maybe to a definitely. This stage flashes the chosen cell so you
can see exactly which one the heuristic picked and what it became.
Stage 4 — Propagate: ripple the constraint outward
A collapse is a promise, and promises have consequences. If this cell is now definitely a horizontal pipe, then the cell to its right cannot be anything whose left edge fails to match — so we delete those now-impossible options from the neighbor. But removing options from the neighbor might in turn make some of its neighbor's options impossible. The constraint has to travel until nothing changes.
We do that with a worklist (a queue/stack of "this cell changed, go check its neighbors"). Pop a cell, look at each of its four neighbors, and for every option still alive in the neighbor ask: does at least one of my remaining tiles permit it? If not, kill that option and push the neighbor back on the worklist. Drain the list and the grid is arc-consistent again. This stage animates the ripple as a spreading highlight so you can watch one collapse send a shockwave across the board.
Stage 5 — The full observe/propagate loop
Put the two halves together and you have the whole algorithm:
- If every cell is collapsed, we're done — show it, pause, restart.
- Observe: find the min-entropy cell, collapse it by weighted choice.
- Propagate: drain the worklist until the grid is consistent.
- If propagation emptied some cell to zero options, that's a contradiction — restart with a new seed.
- Loop.
This stage runs that loop at the speed you set, a few observations per
frame, so you can watch the map condense in real time and then regenerate. It is
genuinely mesmerizing to watch the entropy field drain.
Stage 6 — Styled tilesets, generating live
Nothing about the solver knows what a "pipe" is. Swap the tile artwork and the
adjacency labels and the same engine paints a circuit board or a coast-and-grass terrain
map instead. This stage cycles a fully-styled tileset to completion and immediately
restarts, so it's perpetually generating a new coherent world. Switch the
tileset control to see all three. The lesson: WFC is a tiny constraint
engine, and all the personality lives in your tiles and rules.
How the code works
(a) The tileset and adjacency rules
A tile is its four edge sockets, a weight, and a draw function. Two tiles are compatible across a direction when the socket on one side equals the socket on the opposite side of the neighbor. We precompute that into a boolean lookup so the hot loop never does string compares.
// A tile knows its four edge sockets [up, right, down, left], a weight, a painter.
const tiles = [
{ edges: ['n','n','n','n'], weight: 1.4, draw: drawEmpty }, // blank
{ edges: ['n','p','n','p'], weight: 1.0, draw: drawHoriz }, // ─
{ edges: ['p','n','p','n'], weight: 1.0, draw: drawVert }, // │
{ edges: ['n','p','p','n'], weight: 0.8, draw: drawElbowRD }, // ┌
// ...elbows, tees...
];
// Opposite edge index: up↔down, right↔left. dir 0=up 1=right 2=down 3=left.
const OPP = [2, 3, 0, 1];
// compatible[a][dir][b] === true ⇔ tile b may sit on the `dir` side of tile a.
function buildCompat(tiles) {
const T = tiles.length, C = [];
for (let a = 0; a < T; a++) {
C[a] = [[],[],[],[]];
for (let dir = 0; dir < 4; dir++)
for (let b = 0; b < T; b++)
// my edge on `dir` must equal b's edge on the opposite side
C[a][dir][b] = tiles[a].edges[dir] === tiles[b].edges[OPP[dir]];
}
return C;
}
Note the symmetry baked in by OPP: defining "my right
socket is p" automatically governs both "what may be on my right" and "what I
may be on the left of." If you ever write the rules by hand instead of deriving them from
sockets, you must add both directions yourself or the grid tears.
(b) Entropy and observe
Entropy here is just the count of remaining options (a true Shannon version would weight by tile probabilities; the count is the standard fast approximation). Scan for the minimum among the not-yet-collapsed cells, break ties with the seeded RNG, then collapse by weighted choice.
// Find the uncollapsed cell with the fewest options (random tie-break).
function lowestEntropyCell() {
let best = -1, bestN = Infinity;
for (let i = 0; i < cells.length; i++) {
const n = cells[i].count; // # of options still true
if (n <= 1) continue; // already collapsed (or contradiction)
// tiny noise so equal-entropy cells don't collapse in scan order
const e = n + rnd() * 0.5;
if (e < bestN) { bestN = e; best = i; }
}
return best; // -1 ⇒ fully collapsed
}
// Collapse one cell to a single tile, chosen by weight.
function observe(i) {
const opt = cells[i].options;
let total = 0;
for (let t = 0; t < tiles.length; t++) if (opt[t]) total += tiles[t].weight;
let r = rnd() * total, chosen = -1;
for (let t = 0; t < tiles.length; t++) {
if (!opt[t]) continue;
r -= tiles[t].weight;
if (r <= 0) { chosen = t; break; }
}
for (let t = 0; t < tiles.length; t++) opt[t] = (t === chosen);
cells[i].count = 1;
return chosen;
}
(c) Propagation — a worklist until stable
After a collapse we seed a stack with that cell and drain it. For each popped cell we visit its four neighbors; an option in the neighbor survives only if some option still alive in the current cell is compatible with it. Remove any that can't be supported, and if the neighbor changed, push it so its own neighbors get re-checked. This transitivity is the whole reason a queue is required — one removal can cascade across the entire board.
// Re-establish consistency outward from a set of seed cells.
function propagate(seeds) {
const stack = seeds.slice();
while (stack.length) {
const ci = stack.pop();
const cx = ci % cols, cy = (ci / cols) | 0;
for (let dir = 0; dir < 4; dir++) {
const nx = cx + DX[dir], ny = cy + DY[dir];
if (nx < 0 || ny < 0 || nx >= cols || ny >= rows) continue;
const ni = ny * cols + nx;
const nOpt = cells[ni].options;
let changed = false;
for (let b = 0; b < tiles.length; b++) { // each neighbor option b
if (!nOpt[b]) continue;
let ok = false;
for (let a = 0; a < tiles.length; a++) // any of my options a?
if (cells[ci].options[a] && compat[a][dir][b]) { ok = true; break; }
if (!ok) { nOpt[b] = false; cells[ni].count--; changed = true; }
}
if (changed) {
if (cells[ni].count === 0) contradiction = true; // 0 options ⇒ stuck
stack.push(ni);
}
}
}
}
(d) The step loop and contradiction handling
One step is observe + propagate. The driver runs several steps per frame (scaled by the speed slider), watches for a contradiction or completion, and on either restarts — completion after a short pause to admire the map, contradiction immediately with a new seed. This restart-on-zero is the simplest recovery; the pitfalls section discusses backtracking as the stronger alternative.
function step() {
const i = lowestEntropyCell();
if (i === -1) { done = true; return; } // nothing left to collapse
observe(i);
propagate([i]);
if (contradiction) restart(nextSeed()); // 0-option cell appeared
}
// in the animation loop:
function frame() {
if (done) {
if (++holdFrames > 45) restart(nextSeed()); // admire, then regenerate
} else {
const budget = stepsPerFrame; // from the speed slider
for (let s = 0; s < budget && !done && !contradiction; s++) step();
}
render();
requestAnimationFrame(frame);
}
Common pitfalls
- Contradictions (a cell with zero options). Propagation can paint the grid into a corner where some cell has nothing left. The simplest fix — used here — is to restart with a new seed. The robust fix is backtracking: snapshot the grid before each observe and roll back to the last good state on a contradiction. Most hobby implementations just restart; well-designed tilesets contradict rarely.
- Picking the wrong cell. The min-entropy heuristic matters. Always collapse the cell with the fewest remaining options — it's the most constrained, so it's least likely to cause a contradiction. Collapsing a high-entropy cell first tends to wreck the board. And break ties randomly (the tiny noise term), or the output streaks in whatever order you scan.
- Propagation must be transitive. Removing an option from a neighbor can make options impossible in its neighbor, and so on. You must use a worklist and keep going until nothing changes in a full pass. A single sweep over the grid is not enough — the constraint travels arbitrarily far.
- Adjacency symmetry. Compatibility is directional but must be consistent: if A may sit to the right of B, then B must be allowed to the left of A. Deriving rules from matching edge sockets gives you this for free; hand-written rule tables routinely forget the reverse direction and produce seams and impossible joints.
- Performance. The grid is O(cells × tiles²) per full propagation in
the worst case, and a naive scan for min-entropy is O(cells) per observe. Keep the grid
capped, keep the tileset small, animate a handful of steps per frame instead of solving
the whole board in one blocking loop, and cache the
counton each cell so you never recount. A bitmask of options and a priority queue keyed by entropy are the usual next optimizations.
Exercises
- Weighted tiles. Give the empty/background tile a much higher
weightand the elbow tiles a much lower one. Watch the maps get sparser and curvier. Then try the opposite. Weighted choice inobserve()is the only knob — no rule changes needed — and it's how you author "this biome is mostly grass with occasional trees." - Pin a constraint. Before the loop starts, force the entire border of the grid to the empty/background tile (collapse those cells and propagate once), so every generated map is framed by blank space and pipes never run off the edge. This "pre-collapsing" is exactly how you'd seed a fixed entrance, a river that must reach an exit, or a building footprint.
- A bigger tileset. Add a new socket type — say a
'wire'edge in the circuit set, distinct from'p'— plus a few tiles that bridgewire↔pipeonly through a special connector tile. More socket types means richer structure but more chances for contradictions; tune weights until it solves reliably. This is how real tiled WFC sets scale from toys to game-ready content.
What's next
Episode 15 — Differential growth. We leave the grid behind for a free-floating chain of points that repels itself, attracts its neighbors, and inserts new points where it gets stretched — the rule behind coral, brain folds, and those hypnotic squiggly-line plots. WFC condenses order out of constraints; differential growth grows complexity out of a single line and a few local forces. Same spirit — simple local rules, surprising global form — different mechanism entirely.
Want to push WFC further? It pairs naturally with the rest of the series: drive tile weights from a noise field (Episode on noise) so biomes drift across the map, or move the per-cell rendering to a fragment shader in the shaders series once your grids get large. The constraint solver stays exactly the same; only the paint changes.