playground

Grain, a falling-sand sandbox

Paint sand, water, fire, acid, gas, oil, wood and stone, drop spawners that keep pouring, and watch them interact. Click inside the sandbox and the keyboard shortcuts work too: 1–9 for elements, Space to pause, V to show chunks.

6
Frame rate
–
Particles
–
Chunks awake
–
Spawners
0

Pick an element and draw. Try fire on the plank, or acid on the sand pile.

1–9 elements, S spawner mode, [ ] brush size, Space pause, N step, V chunks, X clear. Right-click erases.

A grid of cells with simple rules

The world is a cellular automaton: a grid where every cell holds one element, and each step every cell follows a few local rules. Sand tries to fall straight down, then diagonally. Water does the same but also spreads sideways. Heavier elements sink through lighter ones, which is why sand settles under water and oil floats on top of it. Fire burns down on its own and spreads to wood, oil and gas. Acid eats what it touches and is diluted by water.

Only the parts that move

Most of a sandbox is still. A settled sand pile doesn't need to be looked at sixty times a second, so the grid is split into 16×16 chunks. Any cell that changes wakes its chunk for the next step, and its neighbour too when the cell sits on an edge. A step only visits chunks that were woken, and the rest sleep and cost nothing.

export function step() {
  emit();
  tick = (tick + 1) & 255;
  const t = act; act = nxt; nxt = t; nxt.fill(0);
  for (let cy = CH - 1; cy >= 0; cy--) {
    // skip whole rows of sleeping chunks, then
    // sweep the awake ones bottom-up
  }
}

Two details keep it honest. Rows are swept from the bottom up, and each row alternates left-to-right and right-to-left so liquids don't drift to one side. Every cell also records the tick it last moved on, so a grain that falls into a row that hasn't been visited yet isn't moved a second time in the same step.

Turn on Show chunks in the panel to see it. Pour some water and the highlighted squares follow the flow, then go out one by one as it settles.

The source

Plain JavaScript and a canvas with no dependencies: about five hundred lines across the element tables, the engine and the UI. Read it at github.com/swayam5342/grain.