Game of Life

glint · Examples · Tutorials · Gallery

Conway's Life on a quarter-resolution feedback buffer. Left-drag draws cells, right-click reseeds.

Game of Life: a GLSL shader

An example in glint, a free live shader editor in the browser: the GLSL code floats over the running picture and recompiles as you type.

The code

2 passes, drawn in this order each frame, in GLSL.

Life: fragment shader

#version 300 es
precision highp float;

uniform sampler2D feedback;
uniform sampler2D noise;
uniform vec2 resolution;
uniform vec2 mouse;
uniform vec3 mouseButtons;
uniform int frame;
uniform float density;

in vec2 v_texcoord;
out vec4 fragColor;

float alive(ivec2 p) {
    ivec2 s = textureSize(feedback, 0);
    return step(0.5, texelFetch(feedback, (p + s) % s, 0).r);
}

void main() {
    ivec2 p = ivec2(gl_FragCoord.xy);
    // Random soup on the first frame, or while the right button is held.
    if (frame < 2 || mouseButtons.z > 0.5) {
        float n = texture(noise, (gl_FragCoord.xy + float(frame)) / 256.0).r;
        fragColor = vec4(step(1.0 - density, n), 0.0, 0.0, 1.0);
        return;
    }
    float n = 0.0;
    for (int y = -1; y <= 1; y++)
        for (int x = -1; x <= 1; x++)
            if (x != 0 || y != 0) n += alive(p + ivec2(x, y));
    float me = alive(p);
    float next = (me > 0.5 && (n == 2.0 || n == 3.0)) || (me < 0.5 && n == 3.0) ? 1.0 : 0.0;
    if (mouseButtons.x > 0.5 && length(gl_FragCoord.xy - mouse * resolution) < 3.0) next = 1.0;
    // g keeps a fading trail of where life has been.
    float trail = max(texelFetch(feedback, p, 0).g * 0.96, next);
    fragColor = vec4(next, trail, 0.0, 1.0);
}

Display: fragment shader

#version 300 es
precision highp float;

uniform sampler2D prevPass;
uniform float time;

in vec2 v_texcoord;
out vec4 fragColor;

void main() {
    ivec2 size = textureSize(prevPass, 0);
    vec2 cell = v_texcoord * vec2(size);
    vec2 s = texelFetch(prevPass, ivec2(cell), 0).rg;
    vec3 trail = (0.5 + 0.5 * cos(time * 0.3 + v_texcoord.xyx * 3.0 + vec3(0, 2, 4))) * s.g * 0.5;
    vec3 col = mix(trail, vec3(1.0), s.r);
    // Faint grid lines between cells.
    vec2 f = fract(cell);
    col *= 0.85 + 0.15 * step(0.08, min(f.x, f.y));
    fragColor = vec4(col, 1.0);
}

More Starters examples

Plasma · Tunnel · Mandelbrot & Julia · Reaction–diffusion · Instanced cubes · Wireframe waves · Bloom · Terrain flyover