# Game of Life

> Conway's Game of Life on 17,000 cells, run entirely on the graphics card by two textures taking turns.

Example `game-of-life`, running at https://nacatamalon.com/en/examples/game-of-life. The whole catalogue: https://nacatamalon.com/llms/examples.md.

**Drag the mouse** to draw living cells, **space** pauses and **R** scatters a new colony. The recently dead leave a fading glow.

Every cell is a pixel, and every generation happens on the graphics card. A picture cannot be drawn from itself, so there are two `createSpriteTexture`s taking turns: one is drawn from the other through a material with the rules, and the other copies it back.

The CPU never touches a cell.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import * as Settings from './settings';
import { World } from './scenes/demo';

const game = createGame('#app', {
    width: Settings.WIDTH,
    height: Settings.HEIGHT,
    background: '#02030a'
});

// Declare Scenes
game({
    World
});
```

`components/colony.ts`:

```ts
import * as Settings from '../settings';
import { createMaterial, createSprite, createSpriteTexture, useGame, useKeyboard, usePointer, useUpdate, type TSprite } from 'nacatamalon';
import { SHOW, SHOW_GLSL, STEP, STEP_GLSL } from '../shaders/rules';

export const Colony = () => {
    const game = useGame();
    const keys = useKeyboard();
    const pointer = usePointer();
    const W = game.getWidth();
    const H = game.getHeight();

    // A picture cannot be drawn from itself, so there are two and they take turns: NEXT is drawn
    // from LAST through the rules, and LAST is then a plain copy of NEXT, ready for the next turn.
    // In each cell, red is alive or dead and green is a glow that lingers after a cell has died.
    const rules = {
        texel: [1 / Settings.CELLS_X, 1 / Settings.CELLS_Y],
        run: 0,
        seed: 1,
        now: 0,
        brush: [-1, -1],
        drawing: 0
    };

    const step = createMaterial({
        name: 'life-step',
        fragment: STEP,
        fragmentGlsl: STEP_GLSL,
        uniforms: rules
    });

    const stepped: TSprite[] = [];

    const whole = {
        width: Settings.CELLS_X,
        height: Settings.CELLS_Y,
        transform: {
            x: Settings.CELLS_X / 2,
            y: Settings.CELLS_Y / 2
        },
        smooth: false
    };

    const next = createSpriteTexture({
        width: Settings.CELLS_X,
        height: Settings.CELLS_Y,
        background: '#00000000'
    }, () => {
        stepped.push(createSprite({
            ...whole,
            material: step
        }));
    });

    const last = createSpriteTexture({
        width: Settings.CELLS_X,
        height: Settings.CELLS_Y,
        background: '#00000000'
    }, () => {
        createSprite({
            ...whole,
            texture: next
        });
    });

    // Only now does LAST exist to be read from.
    stepped[0].texture = last;

    // What you see: the cells, blown up three times and coloured.
    createSprite({
        texture: next,
        material: createMaterial({
            name: 'life-show',
            fragment: SHOW,
            fragmentGlsl: SHOW_GLSL
        }),
        width: W,
        height: H,
        transform: {
            x: W / 2,
            y: H / 2
        },
        smooth: false,
    });

    let down = false;

    const aim = (x: number, y: number) => {
        rules.brush[0] = x / W;
        rules.brush[1] = y / H;
    };

    pointer.onDown((info) => {
        down = true;
        aim(info.screenX, info.screenY);
    });
    pointer.onMove((info) => aim(info.screenX, info.screenY));
    pointer.onUp(() => {
        down = false;
    });

    let paused = false;
    let clock = 0;
    let frames = 0;

    useUpdate((delta) => {
        rules.now += delta;
        frames++;

        if (keys.justPressed(' ')) {
            paused = !paused;
        }

        if (keys.justPressed('r')) {
            frames = 0;
        }

        // R scatters a new colony. The shader also initializes a transparent feedback pixel, so
        // startup does not depend on how many CPU frames its GPU pipeline takes to compile.
        rules.seed = frames < 3 ? 1 : 0;

        // A generation only when its time comes; in between, NEXT is drawn as LAST was.
        clock += delta;
        rules.run = 0;

        if (!paused && clock >= 1 / Settings.GENERATIONS_PER_SECOND) {
            clock = 0;
            rules.run = 1;
        }

        rules.drawing = down ? 1 : 0;
    });
};
```

`scenes/demo.ts`:

```ts
import { createScene, useSpawn } from 'nacatamalon';

import { Colony } from '../components/colony';

export const World = () => {
    useSpawn(Colony)();

    return createScene();
};
```

`settings.ts`:

```ts
export const WIDTH = 480;
export const HEIGHT = 320;
export const CELLS_X = 160;
export const CELLS_Y = 106;
export const GENERATIONS_PER_SECOND = 20;
```

`shaders/rules.ts`:

```ts
import * as Settings from '../settings';

// One generation, per cell: count the eight neighbours (the world wraps round at its edges), and
// apply Conway's rules. A living cell with two or three neighbours lives on; a dead one with exactly
// three is born; everything else dies or stays dead.

// Alpha marks a feedback pixel initialized by this shader. The targets clear transparent, so
// the first successful GPU step seeds itself even if compilation took past the CPU seed frames.
export const STEP = `
fn alive(uv: vec2<f32>, dx: f32, dy: f32) -> f32 {
    return step(0.5, sampleTexture(fract(uv + vec2<f32>(dx, dy) * mu.texel)).r);
}

fn hash(p: vec2<f32>) -> f32 {
    return fract(sin(dot(p, vec2<f32>(12.9898, 78.233))) * 43758.5453);
}

fn effect(color: vec4<f32>, uv: vec2<f32>) -> vec4<f32> {
    let here = sampleTexture(uv);
    let n = alive(uv, -1.0, -1.0) + alive(uv, 0.0, -1.0) + alive(uv, 1.0, -1.0)
          + alive(uv, -1.0, 0.0) + alive(uv, 1.0, 0.0)
          + alive(uv, -1.0, 1.0) + alive(uv, 0.0, 1.0) + alive(uv, 1.0, 1.0);
    let now = step(0.5, here.r);

    var next = now;
    if (mu.run > 0.5) {
        next = select(select(0.0, 1.0, n > 2.5 && n < 3.5), select(0.0, 1.0, n > 1.5 && n < 3.5), now > 0.5);
    }
    if (mu.seed > 0.5 || here.a < 0.5) {
        next = step(0.78, hash(uv * 997.0 + mu.now));
    }
    let cellsAway = (uv - mu.brush) / mu.texel;
    if (mu.drawing > 0.5 && dot(cellsAway, cellsAway) < 6.0) {
        next = 1.0;
    }
    // The glow: full while alive, fading a little each generation once dead.
    let glow = max(next, here.g - 0.04 * mu.run);
    return vec4<f32>(next, glow, 0.0, 1.0);
}
`;

export const STEP_GLSL = `
float alive(vec2 uv, float dx, float dy) {
    return step(0.5, sampleTexture(fract(uv + vec2(dx, dy) * mu.texel)).r);
}

float hash(vec2 p) {
    return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453);
}

vec4 effect(vec4 color, vec2 uv) {
    vec4 here = sampleTexture(uv);
    float n = alive(uv, -1.0, -1.0) + alive(uv, 0.0, -1.0) + alive(uv, 1.0, -1.0)
            + alive(uv, -1.0, 0.0) + alive(uv, 1.0, 0.0)
            + alive(uv, -1.0, 1.0) + alive(uv, 0.0, 1.0) + alive(uv, 1.0, 1.0);
    float now = step(0.5, here.r);

    float next = now;
    if (mu.run > 0.5) {
        next = now > 0.5 ? ((n > 1.5 && n < 3.5) ? 1.0 : 0.0) : ((n > 2.5 && n < 3.5) ? 1.0 : 0.0);
    }
    if (mu.seed > 0.5 || here.a < 0.5) {
        next = step(0.78, hash(uv * 997.0 + mu.now));
    }
    vec2 cellsAway = (uv - mu.brush) / mu.texel;
    if (mu.drawing > 0.5 && dot(cellsAway, cellsAway) < 6.0) {
        next = 1.0;
    }
    float glow = max(next, here.g - 0.04 * mu.run);
    return vec4(next, glow, 0.0, 1.0);
}
`;

// What you see: living cells bright, the glow of the recently dead fading from teal to deep blue,
// and a faint grid between cells, as if on an old monitor.
export const SHOW = `
fn effect(color: vec4<f32>, uv: vec2<f32>) -> vec4<f32> {
    let cell = sampleTexture(uv);
    let glow = cell.g * cell.g;
    var rgb = mix(vec3<f32>(0.01, 0.015, 0.05), vec3<f32>(0.05, 0.45, 0.6), glow);
    rgb = mix(rgb, vec3<f32>(0.75, 1.0, 0.85), cell.r);
    let inCell = fract(uv * vec2<f32>(${Settings.CELLS_X}.0, ${Settings.CELLS_Y}.0));
    let edge = step(0.12, inCell.x) * step(0.12, inCell.y);
    return vec4<f32>(rgb * (0.75 + 0.25 * edge), 1.0);
}
`;

export const SHOW_GLSL = `
vec4 effect(vec4 color, vec2 uv) {
    vec4 cell = sampleTexture(uv);
    float glow = cell.g * cell.g;
    vec3 rgb = mix(vec3(0.01, 0.015, 0.05), vec3(0.05, 0.45, 0.6), glow);
    rgb = mix(rgb, vec3(0.75, 1.0, 0.85), cell.r);
    vec2 inCell = fract(uv * vec2(${Settings.CELLS_X}.0, ${Settings.CELLS_Y}.0));
    float edge = step(0.12, inCell.x) * step(0.12, inCell.y);
    return vec4(rgb * (0.75 + 0.25 * edge), 1.0);
}
`;
```
