Patterns from two chemicals
Reaction-diffusion In a reaction-diffusion system, substances spread out (diffusion) and change into each other (reaction). Alan Turing showed in 1952 that this can form stable patterns like spots and stripes from an almost uniform start. Similar patterns appear on animal coats and shells. Wikipedia
Gray-Scott model Two chemicals live on a grid. Chemical U is added at the feed rate. Chemical V eats U (U + 2V → 3V) and is removed at the rate feed + kill. U spreads faster than V. Only the two numbers feed and kill decide if you get spots, worms, coral or a maze. Karl Sims
GPU ping-pong The grid is a float texture with U in the red and V in the green channel. One fragment shader computes one step for every cell at once. It reads the old texture and writes a second one. Then both textures swap roles. Wikipedia
Original work
- Peter Gray, Stephen K. Scott (1984): Autocatalytic reactions in the isothermal, continuous stirred tank reactor
- John E. Pearson (1993): Complex Patterns in a Simple System
How it works
The grid is 512 × 512 cells. Every frame runs the chosen number of steps. Each step is one full-screen pass of a fragment shader.
- Start: U = 1 and V = 0 everywhere, with random small blocks in the middle area where U = 0.5 and V = 0.25. Reset draws this start again.
- Diffusion: the Laplacian of a cell is the weighted sum of its 3×3 neighbors minus the cell itself. The weights are 0.2 for the four side neighbors and 0.05 for the four corners.
- Reaction: dU = Du · lapU − U·V² + feed · (1 − U) and dV = Dv · lapV + U·V² − (feed + kill) · V. Both values are clamped to 0..1.
- Painting: while you press the canvas, V is raised to at least 0.5 near the pointer. This starts new growth wherever you paint.
- Display: the color comes from V only, from dark blue to light cyan. The two textures swap after each step, so no cell reads a value that was already updated in the same step.
Source code:gray-scott.shader.tsgray-scott-simulation.ts
Note Simplifications in this demo:
- Explicit Euler with time step 1. The diffusion sliders stop at 1 to keep the steps stable.
- The grid wraps around at the edges (a torus), so patterns that leave on one side come back on the other.
- If the GPU has no float32 render textures, float16 is used. The patterns are coarser then.
Press and hold the mouse or a finger on the canvas to paint chemical V. New growth starts under the pointer.
