# Pond

> A sunny pond with simulated waves: a floating ball with a V-shaped wake, rings that bounce off the shore, lily pads that ride the waves, and caustics on the bottom.

Example `pond`, running at https://nacatamalon.com/en/examples/pond. The whole catalogue: https://nacatamalon.com/llms/examples.md.

A sunny pond with an island. WASD or the arrows move the ball, and space jumps. It floats and bobs on the waves, leaves a V-shaped wake, and splashes when it lands; the rings bounce off the shore and the island, the lily pads rise, fall and tilt on them and drift aside when the ball comes by, and the light the waves focus dances on the bottom. Left alone, the ball drives itself. V, or the button at the top right, shows the water: red its depth, green the height of the waves.

The waves are simulated: the wave equation on a 288×288 grid of 6 cm cells, in plain TypeScript, where only the wet cells move, so the shore and the island reflect them. Every step the heights are painted into a picture with `updatePixelTexture`, and two `mesh3d` materials, written for both cards, read it as a `maps` entry: the water for its ripples, foam and sun glints, and the bottom for where the waves focus the caustics. The ball and the lily pads read the same heights to float.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { Pond } from './scenes/pond';
import { ACTIONS, HEIGHT, SKY, WIDTH } from './settings';

// A sunny pond: a floating ball that leaves a V-shaped wake, rings that bounce off the shore and the
// island, splashes when it lands from a jump, lily pads that bob and tilt on the waves (the ball
// pushes them aside), foam at the shore and on high crests, and caustics on the bottom.
//
//   WASD / arrows   move
//   space           jump
//   V               switch views: the pond, the waves (or the button)
//
// Left alone, the ball drives itself.
const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    background: SKY,
    scaling: 'contain',
    step: 60,
    actions: ACTIONS
});

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

`art/textures.ts`:

```ts
import { createPixels, createPixelTexture, setPixel } from 'nacatamalon/pixels';

/**
 * A soft white dot, 8 pixels a side, for the drops of spray.
 */
export const paintDot = () => {
    const size = 8;
    const pixels = createPixels(size, size);

    for (let y = 0; y < size; y++) {
        for (let x = 0; x < size; x++) {
            const d = Math.hypot(x + 0.5 - size / 2, y + 0.5 - size / 2) / (size / 2);

            setPixel(pixels, x, y, `rgba(255, 255, 255, ${Math.max(0, 1 - d).toFixed(3)})`);
        }
    }

    return createPixelTexture(pixels);
};
```

`components/ball.ts`:

```ts
import { createMesh, useAction, useDirection, useIcoSphereGeometry, useUpdate } from 'nacatamalon';
import { useRandom } from 'nacatamalon/math';
import { heightAt } from '../geometry/terrain';
import { BALL, FIELD, IDLE_SECONDS, SPLASH, WATER_LEVEL } from '../settings';
import type { TWater } from './water';
import type { TSpray } from './spray';

/**
 * How far the ball may go from the middle, either way.
 */
const LIMIT = FIELD.size / 2 - BALL.edge;

/**
 * The red ball. On land it rolls over the ground; in the pond it floats and bobs on the waves,
 * leaves a wake as it moves, and splashes when it lands from a jump. Left alone it crosses the pond
 * in curves by itself.
 */
export const Ball = ({ water, spray }: { water: TWater; spray: TSpray; }) => {
    const mesh = createMesh({
        geometry: useIcoSphereGeometry({
            radius: BALL.radius,
            subdivisions: 3
        }),
        tint: '#f05a3c',
        specular: '#ffffff',
        shininess: 50,
        castShadow: true,
        transform: {
            x: BALL.start.x,
            y: 1,
            z: BALL.start.z
        }
    });

    const move = useDirection('left', 'right', 'up', 'down');
    const jump = useAction('jump');
    const random = useRandom();

    const velocity = {
        x: 0,
        y: 0,
        z: 0
    };

    let idleFor = IDLE_SECONDS;
    let autoTime = 0;
    let autoJump = 3;
    let grounded = false;
    let touching = false;
    let speed = 0;

    useUpdate((delta) => {
        const at = mesh.transform;

        // Up on the stick or the keys goes away from the camera, along -z.
        let { x: ix, y: iz } = move();
        let jumping = jump.justPressed();

        idleFor = ix !== 0 || iz !== 0 || jumping ? 0 : idleFor + delta;

        if (idleFor > IDLE_SECONDS) {
            autoTime += delta * 0.3;
            ix = Math.sin(autoTime * 1.1) * 5.5 - at.x;
            iz = Math.sin(autoTime * 1.8 + 0.7) * 3.6 - at.z;
            autoJump -= delta;

            if (autoJump <= 0) {
                jumping = true;
                autoJump = random.rand(4, 7);
            }
        }

        const length = Math.hypot(ix, iz);

        if (length > 1) {
            ix /= length;
            iz /= length;
        }

        const ground = heightAt(at.x, at.z);
        const inWater = ground < WATER_LEVEL - 0.05;
        const accel = inWater ? BALL.waterAccel : BALL.accel;

        velocity.x += ix * accel * delta;
        velocity.z += iz * accel * delta;

        // The water slows it more than the grass.
        const steering = ix !== 0 || iz !== 0;
        const drag = Math.exp(-((steering ? BALL.drag : BALL.stopDrag) + (inWater ? BALL.waterDrag : 0)) * delta);

        velocity.x *= drag;
        velocity.z *= drag;

        if (jumping && grounded) {
            velocity.y = BALL.jump;
            grounded = false;
        }

        velocity.y -= BALL.gravity * delta;
        at.x += velocity.x * delta;
        at.y += velocity.y * delta;
        at.z += velocity.z * delta;
        at.x = Math.min(Math.max(at.x, -LIMIT), LIMIT);
        at.z = Math.min(Math.max(at.z, -LIMIT), LIMIT);

        // On land it rests on the ground; in the water it floats on the wave under it.
        const floats = WATER_LEVEL + water.waveAt(at.x, at.z).height + BALL.radius * BALL.floats;
        const rest = Math.max(ground + BALL.radius, inWater ? floats : -Infinity);
        let impact = 0;

        if (at.y <= rest) {
            impact = grounded ? 0 : -velocity.y;
            at.y = grounded ? at.y + (rest - at.y) * Math.min(1, delta * 12) : rest;
            velocity.y = 0;
            grounded = true;
        }

        speed = Math.hypot(velocity.x, velocity.z);
        touching = inWater && at.y - BALL.radius < WATER_LEVEL + 0.05;

        if (touching) {
            water.stir(at.x, at.z, BALL.radius, speed);
        }

        // Landing in the water: rings and a burst of spray.
        if (impact > SPLASH.landing && inWater) {
            water.splash(at.x, at.z, Math.min(0.09, impact * 0.011));
            spray.splash(at.x, WATER_LEVEL + 0.05, at.z, Math.min(160, Math.round(impact * 18)));
        }

        // Ploughing through: a few drops in front.
        if (touching && speed > 1.2) {
            spray.splash(at.x + (velocity.x / speed) * BALL.radius * 0.9, WATER_LEVEL + 0.04, at.z + (velocity.z / speed) * BALL.radius * 0.9, Math.min(4, Math.round(speed * 0.8)));
        }
    });

    return {
        mesh,

        /**
         * Whether it is in the water now, and how fast it goes, for what it pushes aside.
         */
        touching: () => touching,
        speed: () => speed
    };
};

export type TBall = ReturnType<typeof Ball>;
```

`components/lily_pads.ts`:

```ts
import { createMesh, useCircleGeometry, useUpdate, type TMesh } from 'nacatamalon';
import { heightAt } from '../geometry/terrain';
import { seeded } from '../geometry/seeded';
import { BALL, LILY_PADS, WATER_LEVEL } from '../settings';
import type { TBall } from './ball';
import type { TWater } from './water';

/**
 * Lily pads: they rise, fall and tilt with the waves under them, and the ball pushes them aside. They
 * never drift onto land. A seeded generator places them, so they start in the same places every
 * time.
 */
export const LilyPads = ({ water, ball }: { water: TWater; ball: TBall; }) => {
    const random = seeded(7);

    const geometry = useCircleGeometry({
        radius: 0.32,
        segments: 14
    });

    const pads: {
        mesh: TMesh;
        x: number;
        z: number;
        vx: number;
        vz: number;
    }[] = [];

    while (pads.length < LILY_PADS) {
        const x = random.rand(-6, 6);
        const z = random.rand(-4.5, 4.5);

        // In water deep enough, and not on top of another.
        if (heightAt(x, z) > WATER_LEVEL - 0.25 || pads.some((pad) => Math.hypot(pad.x - x, pad.z - z) < 0.9)) {
            continue;
        }

        const mesh = createMesh({
            geometry,
            tint: random.chance(0.5) ? '#3e7a32' : '#4d8a3a',
            transform: {
                x,
                y: WATER_LEVEL + 0.01,
                z,
                rotationY: random.rand(0, Math.PI * 2)
            }
        });

        pads.push({
            mesh,
            x,
            z,
            vx: 0,
            vz: 0
        });
    }

    useUpdate((delta) => {
        const at = ball.mesh.transform;
        const speed = ball.speed();

        for (const pad of pads) {
            const dx = pad.x - at.x;
            const dz = pad.z - at.z;
            const d = Math.hypot(dx, dz);

            if (ball.touching() && d < BALL.radius + 0.4 && d > 0.001) {
                pad.vx += (dx / d) * (1.5 + speed) * delta * 6;
                pad.vz += (dz / d) * (1.5 + speed) * delta * 6;
            }

            pad.vx *= Math.exp(-1.5 * delta);
            pad.vz *= Math.exp(-1.5 * delta);

            const nx = pad.x + pad.vx * delta;
            const nz = pad.z + pad.vz * delta;

            // Near the shore it bounces back a little.
            if (heightAt(nx, nz) < WATER_LEVEL - 0.06) {
                pad.x = nx;
                pad.z = nz;
            } else {
                pad.vx *= -0.3;
                pad.vz *= -0.3;
            }

            const wave = water.waveAt(pad.x, pad.z);

            pad.mesh.transform.x = pad.x;
            pad.mesh.transform.z = pad.z;
            pad.mesh.transform.y = WATER_LEVEL + wave.height + 0.012;
            pad.mesh.transform.rotationX = Math.atan(wave.slopeZ) * 0.8;
            pad.mesh.transform.rotation = -Math.atan(wave.slopeX) * 0.8;
        }
    });
};
```

`components/shore.ts`:

```ts
import { createMesh, useConeGeometry, useIcoSphereGeometry } from 'nacatamalon';
import { heightAt } from '../geometry/terrain';
import { seeded } from '../geometry/seeded';
import { REEDS, ROCKS } from '../settings';

/**
 * Clumps of reeds round the shore, and a few rocks. A seeded generator places them, so the shore is
 * the same every time.
 */
export const Shore = () => {
    const random = seeded(42);

    const reed = useConeGeometry({
        radius: 0.025,
        height: 1,
        segments: 4
    });

    for (let k = 0; k < REEDS.clumps; k++) {
        const angle = random.rand(0, Math.PI * 2);
        const cx = Math.cos(angle) * 6.9;
        const cz = Math.sin(angle) * 5.4;

        for (let r = 0; r < REEDS.each; r++) {
            const x = cx + random.rand(-0.5, 0.5);
            const z = cz + random.rand(-0.5, 0.5);
            const h = random.rand(0.7, 1.5);

            createMesh({
                geometry: reed,
                tint: random.chance(0.5) ? '#5f7d36' : '#7a8f42',
                transform: {
                    x,
                    y: heightAt(x, z) + h / 2,
                    z,
                    scaleY: h,
                    rotationX: random.rand(-0.125, 0.125),
                    rotation: random.rand(-0.125, 0.125)
                }
            });
        }
    }

    const rock = useIcoSphereGeometry({
        radius: 1,
        subdivisions: 1
    });

    for (const [x, z, size] of ROCKS) {
        createMesh({
            geometry: rock,
            tint: '#8f8a80',
            castShadow: true,
            transform: {
                x,
                y: heightAt(x, z) + size * 0.25,
                z,
                scaleX: size,
                scaleY: size * 0.6,
                scaleZ: size * 0.85
            }
        });
    }
};
```

`components/spray.ts`:

```ts
import { createParticles3d, emitParticles } from 'nacatamalon';
import { paintDot } from '../art/textures';

/**
 * The drops the ball throws up: a burst when it lands in the water, a few in front as it ploughs
 * through.
 */
export const Spray = () => {
    const spray = createParticles3d({
        effect: {
            kind: 'particles-3d',
            texture: paintDot(),
            worldSpace: true,
            max: 500,
            emission: {
                rate: 0,
                burst: 0
            },
            shape: {
                kind: 'sphere',
                radius: 0.3,
                edge: true
            },
            direction: {
                x: 0,
                y: 1,
                z: 0
            },
            spread: 0.9,
            speed: [2, 4.5],
            gravity: {
                y: -12
            },
            life: [0.4, 0.9],
            size: [0.05, 0.11],
            colorOverLife: [
                {
                    t: 0,
                    color: '#ffffff',
                    alpha: 0.95
                },
                {
                    t: 1,
                    color: '#d8ecf4',
                    alpha: 0
                }
            ]
        }
    });

    return {
        /**
         * Throws `count` drops up from `x`, `y`, `z`.
         */
        splash(x: number, y: number, z: number, count: number) {
            spray.transform.x = x;
            spray.transform.y = y;
            spray.transform.z = z;
            emitParticles(spray, count);
        }
    };
};

export type TSpray = ReturnType<typeof Spray>;
```

`components/views.ts`:

```ts
import { createSprite, createText, listen, useAction, useUpdate } from 'nacatamalon';
import { VIEWS, WIDTH } from '../settings';
import type { TWater } from './water';

/**
 * The two ways to look at the pond, switched with V or the button at the top right: POND as it is,
 * and WAVES, red for the depth, green for the height of the water.
 */
export const Views = ({ water }: { water: TWater; }) => {
    let view = 0;

    const button = createSprite({
        width: 150,
        height: 18,
        tint: '#1c2338',
        anchor: {
            x: 1,
            y: 0
        },
        zIndex: 100,
        transform: {
            x: WIDTH - 8,
            y: 5
        }
    });

    const label = createText({
        text: '',
        tint: '#ffd9a0',
        anchor: {
            x: 0.5,
            y: 0
        },
        zIndex: 101,
        transform: {
            x: WIDTH - 83,
            y: 10
        }
    });

    const show = () => {
        label.text = `[V] VIEW: ${VIEWS[view]}`;
        water.showWaves(VIEWS[view] === 'WAVES');
    };

    const next = () => {
        view = (view + 1) % VIEWS.length;
        show();
    };

    listen(button, {
        onClick: next
    });
    listen(label, {
        onClick: next
    });
    show();

    const switchView = useAction('view');

    useUpdate(() => {
        if (switchView.justPressed()) {
            next();
        }
    });
};
```

`components/water.ts`:

```ts
import { createMaterial, createMesh, usePlaneGeometry, useUpdate } from 'nacatamalon';
import { useRandom } from 'nacatamalon/math';
import { createPixels, createPixelTexture, updatePixelTexture } from 'nacatamalon/pixels';
import { buildTerrain, isWet, paintDepth } from '../geometry/terrain';
import { GROUND_GLSL, GROUND_WGSL } from '../shaders/ground';
import { WATER_GLSL, WATER_WGSL, type TPondKnobs } from '../shaders/water';
import { createWaves } from '../simulation/waves';
import { FIELD, SUN, WATER_LEVEL, WAVES } from '../settings';

/**
 * One step of the waves, in seconds.
 */
const STEP = 1 / 60;

/**
 * The pond and the ground round it. The waves are simulated every step and painted into a picture
 * that both the water and the bottom read: the water for its ripples, the bottom for where the waves
 * focus the caustics. What stirs it (the ball) and what floats on it (the ball, the lily pads) do so
 * through what this returns.
 */
export const Water = () => {
    const terrain = buildTerrain(FIELD.size, FIELD.cells);
    const random = useRandom();

    const waves = createWaves({
        area: WAVES.area,
        cells: WAVES.cells,
        speed: WAVES.speed,
        keep: WAVES.keep,
        wet: isWet
    });

    const wavePixels = createPixels(WAVES.cells, WAVES.cells, '#808080');
    const waveTexture = createPixelTexture(wavePixels);

    const knobs: TPondKnobs = {
        level: [WATER_LEVEL, terrain.low, terrain.high, 0],
        area: [-WAVES.area / 2, -WAVES.area / 2, WAVES.area, 0],
        wave: [255 / WAVES.scale, WAVES.cells / (2 * WAVES.area), 1 / WAVES.cells, 0],
        sun: [Math.sin(SUN.rotationY) * Math.cos(SUN.rotationX), -Math.sin(SUN.rotationX), Math.cos(SUN.rotationY) * Math.cos(SUN.rotationX), 0],
        skyLow: [0.62, 0.75, 0.86, 0],
        skyHigh: [0.36, 0.56, 0.82, 0],
        shallow: [0.3, 0.55, 0.48, 0],
        deep: [0.04, 0.16, 0.17, 0]
    };

    const waveMap = {
        texture: waveTexture,
        wrap: 'clamp',
        smooth: true
    } as const;

    createMesh({
        geometry: terrain.geometry,
        material: createMaterial({
            shader: 'mesh3d',
            name: 'pond ground',
            fragment: GROUND_WGSL,
            fragmentGlsl: GROUND_GLSL,
            maps: {
                waves: waveMap
            },
            uniforms: knobs
        })
    });

    createMesh({
        // In many pieces: the engine works its distance fog out per vertex.
        geometry: usePlaneGeometry({
            width: WAVES.area,
            depth: WAVES.area,
            widthSegments: 36,
            depthSegments: 36
        }),
        material: createMaterial({
            shader: 'mesh3d',
            name: 'pond water',
            transparent: true,
            fragment: WATER_WGSL,
            fragmentGlsl: WATER_GLSL,
            maps: {
                depth: {
                    texture: paintDepth(WAVES.area, 160, terrain.low, terrain.high),
                    wrap: 'clamp',
                    smooth: true
                },
                waves: waveMap
            },
            uniforms: knobs
        }),
        transform: {
            y: WATER_LEVEL
        }
    });

    // What is pushing the water down this step: the floating ball, if it touches it.
    const stirring = {
        on: false,
        x: 0,
        z: 0,
        radius: 0,
        speed: 0
    };

    let owed = 0;

    useUpdate((delta) => {
        owed += Math.min(delta, 0.1);

        while (owed >= STEP) {
            owed -= STEP;

            // Moving, the ball pushes water aside in front of it: faster than the waves, that makes
            // the V of its wake. Still, it barely rocks.
            if (stirring.on) {
                waves.push(stirring.x, stirring.z, stirring.radius * 0.7, Math.min(0.006, 0.0006 + stirring.speed * 0.0016));
            }

            waves.step();
        }

        stirring.on = false;
        waves.paint(wavePixels.data, WAVES.scale);
        updatePixelTexture(waveTexture);
    });

    return {
        /**
         * The water's height at a point (0 still), and how steep it is along x and z.
         */
        waveAt: waves.at,

        /**
         * Something round of `radius` floats at `x`, `z` this step, moving at `speed`.
         */
        stir(x: number, z: number, radius: number, speed: number) {
            stirring.on = true;
            stirring.x = x;
            stirring.z = z;
            stirring.radius = radius;
            stirring.speed = speed;
        },

        /**
         * Something lands in the water at `x`, `z`, pushing it down `strength` metres. Not one dip
         * but a few narrow ones round the point, for richer rings.
         */
        splash(x: number, z: number, strength: number) {
            waves.push(x, z, 0.22, strength);

            for (let k = 0; k < 5; k++) {
                const angle = (k / 5) * Math.PI * 2 + random.rand();

                waves.push(x + Math.cos(angle) * 0.3, z + Math.sin(angle) * 0.3, 0.12, strength * 0.35);
            }
        },

        /**
         * The WAVES view: red for the depth, green for the height of the waves.
         */
        showWaves(on: boolean) {
            knobs.level[3] = on ? 1 : 0;
        }
    };
};

export type TWater = ReturnType<typeof Water>;
```

`geometry/seeded.ts`:

```ts
/**
 * A small generator of its own, always the same numbers for the same seed, for what is placed once
 * and should be in the same place every time (the reeds, the lily pads). The game's own, `useRandom`,
 * is for what happens while it plays.
 */
export const seeded = (seed: number) => {
    let state = seed;

    const next = () => {
        state = (state * 16807) % 2147483647;

        return state / 2147483647;
    };

    return {
        /**
         * A number from `min` up to `max`.
         */
        rand: (min: number, max: number) => min + next() * (max - min),

        /**
         * True `probability` of the time.
         */
        chance: (probability: number) => next() < probability
    };
};
```

`geometry/terrain.ts`:

```ts
import { createGeometry } from 'nacatamalon';
import { createPixels, createPixelTexture } from 'nacatamalon/pixels';
import { ISLAND, POND, WATER_LEVEL } from '../settings';

/**
 * A number from 0 to 1 that is always the same for the same corner of the grid.
 */
const hash = (x: number, y: number) => {
    const s = Math.sin(x * 127.1 + y * 311.7) * 43758.5453;

    return s - Math.floor(s);
};

/**
 * Smooth noise from 0 to 1: the corners' hashes, blended.
 */
const noise = (x: number, y: number) => {
    const ix = Math.floor(x);
    const iy = Math.floor(y);
    const fx = x - ix;
    const fy = y - iy;
    const ux = fx * fx * (3 - 2 * fx);
    const uy = fy * fy * (3 - 2 * fy);
    const a = hash(ix, iy);
    const b = hash(ix + 1, iy);
    const c = hash(ix, iy + 1);
    const d = hash(ix + 1, iy + 1);

    return a + (b - a) * ux + (c - a) * uy + (a - b - c + d) * ux * uy;
};

/**
 * The height of the ground at a point: a grassy bank that slopes down into the pond, and the island.
 */
export const heightAt = (x: number, z: number) => {
    const wobble = 1 + (noise(x * 0.35 + 3, z * 0.35 + 7) - 0.5) * 0.35;
    const d = Math.hypot(x / POND.x, z / POND.z) / wobble;

    // From the shore (d about 0.9 at the water's height) to the deepest (-0.85) down a gentle slope.
    const t = Math.min(1, Math.max(0, (1.12 - d) / 0.6));
    let h = 0.25 - 1.1 * t ** 1.5;

    // The island: a mound that rises out of the water.
    const [ix, iz, ir] = ISLAND;
    const di = Math.hypot(x - ix, z - iz) / ir;

    if (di < 1.6) {
        h = Math.max(h, 0.3 - di * di * 0.45);
    }

    // Some bumps, on land and on the bottom.
    return h + (noise(x * 0.6, z * 0.6) - 0.5) * 0.08 + (noise(x * 2.2 + 5, z * 2.2 + 1) - 0.5) * 0.02;
};

/**
 * Whether there is water at a point.
 */
export const isWet = (x: number, z: number) => heightAt(x, z) < WATER_LEVEL;

/**
 * The ground as a mesh, `size` by `size` world units in `cells` by `cells` cells, and its lowest and
 * highest points.
 */
export const buildTerrain = (size: number, cells: number) => {
    const n = cells + 1;
    const step = size / cells;
    const half = size / 2;
    const positions = new Float32Array(n * n * 3);
    const indices = new Uint32Array(cells * cells * 6);
    let low = Infinity;
    let high = -Infinity;

    for (let z = 0; z < n; z++) {
        for (let x = 0; x < n; x++) {
            const wx = x * step - half;
            const wz = z * step - half;
            const h = heightAt(wx, wz);
            const i = (z * n + x) * 3;

            low = Math.min(low, h);
            high = Math.max(high, h);
            positions[i] = wx;
            positions[i + 1] = h;
            positions[i + 2] = wz;
        }
    }

    let k = 0;

    for (let z = 0; z < cells; z++) {
        for (let x = 0; x < cells; x++) {
            const a = z * n + x;

            indices[k++] = a;
            indices[k++] = a + n;
            indices[k++] = a + 1;
            indices[k++] = a + 1;
            indices[k++] = a + n;
            indices[k++] = a + n + 1;
        }
    }

    return {
        geometry: createGeometry({
            positions,
            indices
        }),
        low,
        high
    };
};

/**
 * The height of the bottom as a picture over the middle `area` by `area` world units, `size` pixels
 * a side, from `low` (black) to `high` (white), so the water knows how deep it is.
 */
export const paintDepth = (area: number, size: number, low: number, high: number) => {
    const half = area / 2;
    const map = createPixels(size, size);

    for (let y = 0; y < size; y++) {
        for (let x = 0; x < size; x++) {
            const wx = ((x + 0.5) / size) * area - half;
            const wz = ((y + 0.5) / size) * area - half;
            const v = Math.round(((heightAt(wx, wz) - low) / (high - low)) * 255);
            const o = (y * size + x) * 4;

            map.data[o] = v;
            map.data[o + 1] = v;
            map.data[o + 2] = v;
            map.data[o + 3] = 255;
        }
    }

    return createPixelTexture(map);
};
```

`scenes/pond.ts`:

```ts
import { cameraLookAt, createScene, createText, useAmbientLight, useCamera3d, useDirectionalLight, useFog, useSpawn, useUpdate } from 'nacatamalon';
import { Ball } from '../components/ball';
import { LilyPads } from '../components/lily_pads';
import { Water } from '../components/water';
import { Shore } from '../components/shore';
import { Spray } from '../components/spray';
import { Views } from '../components/views';
import { HEIGHT, SKY, SUN } from '../settings';

/**
 * A sunny pond with an island, reeds and lily pads. The pond is made first, and handed to the ball,
 * the lily pads and the view button, which stir it, float on it and look at it.
 */
export const Pond = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 50,
        transform: {
            x: 0,
            y: 4.6,
            z: 9
        }
    });

    useFog({
        color: SKY,
        near: 16,
        far: 38
    });
    useAmbientLight({
        color: '#b4c8e4',
        intensity: 0.55
    });
    useDirectionalLight({
        color: '#fff3dc',
        intensity: 1.15,
        castShadow: true,
        shadowArea: 40,
        transform: SUN
    });

    const water = useSpawn(Water)();

    useSpawn(Shore)();

    const spray = useSpawn(Spray)();

    const ball = useSpawn(Ball)({
        water: water.api,
        spray: spray.api
    });

    useSpawn(LilyPads)({
        water: water.api,
        ball: ball.api
    });

    useSpawn(Views)({
        water: water.api
    });

    createText({
        text: 'WASD / ARROWS: MOVE   SPACE: JUMP',
        tint: '#1d3247',
        zIndex: 100,
        transform: {
            x: 8,
            y: 8
        }
    });
    createText({
        text: 'POND · NACATAMALON',
        tint: '#1d3247',
        zIndex: 100,
        transform: {
            x: 8,
            y: HEIGHT - 16
        }
    });

    // The camera follows the ball from above, a little late.
    useUpdate((delta) => {
        const at = ball.api.mesh.transform;
        const follow = 1 - Math.exp(-2.5 * delta);

        camera.transform.x += (at.x * 0.7 - camera.transform.x) * follow;
        camera.transform.z += (at.z * 0.7 + 8 - camera.transform.z) * follow;
        cameraLookAt(camera, {
            x: at.x * 0.7,
            y: 0,
            z: at.z * 0.7
        });
    });

    return createScene();
};
```

`settings.ts`:

```ts
import { INPUT, type TActionDef } from 'nacatamalon';

/**
 * The game's size, in its own pixels.
 */
export const WIDTH = 640;
export const HEIGHT = 360;

/**
 * The sky, also the colour of the fog far away.
 */
export const SKY = '#a9cfe9';

/**
 * Where the sun shines from, as the light's turn about x and y.
 */
export const SUN = {
    rotationX: -0.85,
    rotationY: 0.55
};

/**
 * Moving and jumping as a platformer reads them (WASD or the arrows, space, a pad), and V to switch
 * views.
 */
export const ACTIONS: TActionDef[] = [
    ...INPUT.ACTION_PRESETS.platformer,
    {
        name: 'view',
        bindings: [
            {
                type: 'key',
                key: 'v'
            }
        ]
    }
];

/**
 * What V and the button at the top right show: the pond as it is, and the waves, red for the depth,
 * green for the height of the water.
 */
export const VIEWS = ['POND', 'WAVES'] as const;

/**
 * The ground: `size` by `size` world units (metres) round the pond, in `cells` by `cells` cells.
 */
export const FIELD = {
    size: 30,
    cells: 180
};

/**
 * The height of the water. Wherever the ground is lower there is pond.
 */
export const WATER_LEVEL = 0;

/**
 * The pond, an ellipse with a wobbly shore, `x` by `z` metres from the middle to the edge.
 */
export const POND = {
    x: 7.5,
    z: 5.8
};

/**
 * The island: x, z and radius.
 */
export const ISLAND: readonly [number, number, number] = [2.6, -1.4, 1.1];

/**
 * The waves are simulated on a grid of `cells` by `cells` over the middle `area` by `area` metres:
 * cells of 6.25 cm. Small cells matter: with big ones the shortest wave is a metre long and the water
 * looks like liquid metal. `speed` is how fast they travel (a little over a metre a second, as in a
 * pond, and at most 0.25 or the grid blows up), `keep` how much of them is left after each step.
 * `scale` is how many units of the wave map a metre of height is (128 is still water).
 */
export const WAVES = {
    area: 18,
    cells: 288,
    speed: 0.12,
    keep: 0.992,
    scale: 900
};

/**
 * The red ball, in world units and seconds. It floats, a little more than half of it out of the
 * water, and never goes nearer the edge of the field than `edge`.
 */
export const BALL = {
    radius: 0.45,
    start: {
        x: -3,
        z: 2
    },
    accel: 16,
    waterAccel: 11,
    gravity: 20,
    jump: 7.5,
    edge: 3,
    floats: 0.15,
    /**
     * How fast it slows: gently while it is steered, faster when let go, and more in the water.
     */
    drag: 2.4,
    stopDrag: 4,
    waterDrag: 0.8
};

/**
 * Landing harder than `landing` splashes.
 */
export const SPLASH = {
    landing: 3
};

/**
 * Left alone this many seconds, the ball crosses the pond in curves by itself and jumps now and then.
 */
export const IDLE_SECONDS = 3;

/**
 * Clumps of reeds round the shore: how many clumps, and how many reeds in each.
 */
export const REEDS = {
    clumps: 9,
    each: 14
};

/**
 * The rocks: x, z, size.
 */
export const ROCKS: readonly (readonly [number, number, number])[] = [[-6.5, 4.5, 0.7], [7.2, -3.5, 0.9], [1.8, 6.2, 0.5], [-7.8, -2.0, 0.6]];

/**
 * How many lily pads float on the pond.
 */
export const LILY_PADS = 12;
```

`shaders/ground.ts`:

```ts
// The ground: grass up high, sand at the shore (darker where it is wet), mud deep down. Under the
// water the light loses its red first (everything turns greener the deeper it is) and the sun draws
// caustics: nets of light that move, brighter where the waves focus it. It shares the water's knobs.

export const GROUND_WGSL = /* wgsl */ `
fn groundHash(p: vec2<f32>) -> vec2<f32> {
    let q = vec2<f32>(dot(p, vec2<f32>(127.1, 311.7)), dot(p, vec2<f32>(269.5, 183.3)));
    return fract(sin(q) * 43758.5453);
}

// Moving Voronoi cells: the gap between the nearest point and the second nearest draws a net of lines.
fn causticLayer(p: vec2<f32>, time: f32) -> f32 {
    let cell = floor(p);
    var first = 9.0;
    var second = 9.0;
    for (var j = -1; j <= 1; j = j + 1) {
        for (var i = -1; i <= 1; i = i + 1) {
            let c = cell + vec2<f32>(f32(i), f32(j));
            let h = groundHash(c);
            let point = c + 0.5 + 0.45 * sin(time * (0.6 + h * 0.6) + h * 6.28);
            let d = length(p - point);
            if (d < first) {
                second = first;
                first = d;
            } else if (d < second) {
                second = d;
            }
        }
    }
    return 1.0 - smoothstep(0.0, 0.4, second - first);
}

fn effect(surface: vec4<f32>, ctx: FragContext) -> vec4<f32> {
    let p = ctx.worldPos;
    let depth = mu.level.x - p.y;
    let speck = groundHash(floor(p.xz * 9.0)).x;
    let grass = mix(vec3<f32>(0.27, 0.45, 0.17), vec3<f32>(0.36, 0.55, 0.22), speck);
    let sand = mix(vec3<f32>(0.72, 0.64, 0.47), vec3<f32>(0.8, 0.72, 0.55), speck);
    let mud = vec3<f32>(0.36, 0.33, 0.24);
    var base = mix(sand, grass, smoothstep(0.06, 0.16, -depth));
    base = base * mix(1.0, 0.72, smoothstep(-0.07, 0.0, depth));
    base = mix(base, mud, smoothstep(0.15, 0.7, depth));
    var color = base * ctx.light;

    if (depth > 0.0) {
        let uv = (p.xz - mu.area.xy) / mu.area.z;
        let t = mu.wave.z;
        let around = sampleMap_waves(uv + vec2<f32>(t, 0.0)).r + sampleMap_waves(uv - vec2<f32>(t, 0.0)).r
            + sampleMap_waves(uv + vec2<f32>(0.0, t)).r + sampleMap_waves(uv - vec2<f32>(0.0, t)).r;
        let curve = (around - 4.0 * sampleMap_waves(uv).r) * mu.wave.x;
        let focus = clamp(1.0 + curve * 60.0, 0.3, 3.0);
        let caustics = causticLayer(p.xz * 1.8, mu.time) * causticLayer(p.xz * 2.6 + 3.1, mu.time * 1.3) * focus;
        let absorb = exp(-depth * vec3<f32>(2.2, 0.9, 0.6));
        let sunUp = max(normalize(mu.sun.xyz).y, 0.0);
        color = color * absorb + vec3<f32>(1.0, 0.95, 0.75) * caustics * sunUp * exp(-depth * 2.2) * 0.45;
    }
    return vec4<f32>(color, 1.0);
}
`;

export const GROUND_GLSL = /* glsl */ `
vec2 groundHash(vec2 p) {
    vec2 q = vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3)));
    return fract(sin(q) * 43758.5453);
}

// Moving Voronoi cells: the gap between the nearest point and the second nearest draws a net of lines.
float causticLayer(vec2 p, float time) {
    vec2 cell = floor(p);
    float first = 9.0;
    float second = 9.0;
    for (int j = -1; j <= 1; j++) {
        for (int i = -1; i <= 1; i++) {
            vec2 c = cell + vec2(float(i), float(j));
            vec2 h = groundHash(c);
            vec2 point = c + 0.5 + 0.45 * sin(time * (0.6 + h * 0.6) + h * 6.28);
            float d = length(p - point);
            if (d < first) {
                second = first;
                first = d;
            } else if (d < second) {
                second = d;
            }
        }
    }
    return 1.0 - smoothstep(0.0, 0.4, second - first);
}

vec4 effect(vec4 surface, FragContext ctx) {
    vec3 p = ctx.worldPos;
    float depth = mu.level.x - p.y;
    float speck = groundHash(floor(p.xz * 9.0)).x;
    vec3 grass = mix(vec3(0.27, 0.45, 0.17), vec3(0.36, 0.55, 0.22), speck);
    vec3 sand = mix(vec3(0.72, 0.64, 0.47), vec3(0.8, 0.72, 0.55), speck);
    vec3 mud = vec3(0.36, 0.33, 0.24);
    vec3 base = mix(sand, grass, smoothstep(0.06, 0.16, -depth));
    base *= mix(1.0, 0.72, smoothstep(-0.07, 0.0, depth));
    base = mix(base, mud, smoothstep(0.15, 0.7, depth));
    vec3 color = base * ctx.light;

    if (depth > 0.0) {
        vec2 uv = (p.xz - mu.area.xy) / mu.area.z;
        float t = mu.wave.z;
        float around = sampleMap_waves(uv + vec2(t, 0.0)).r + sampleMap_waves(uv - vec2(t, 0.0)).r
            + sampleMap_waves(uv + vec2(0.0, t)).r + sampleMap_waves(uv - vec2(0.0, t)).r;
        float curve = (around - 4.0 * sampleMap_waves(uv).r) * mu.wave.x;
        float focus = clamp(1.0 + curve * 60.0, 0.3, 3.0);
        float caustics = causticLayer(p.xz * 1.8, mu.time) * causticLayer(p.xz * 2.6 + 3.1, mu.time * 1.3) * focus;
        vec3 absorb = exp(-depth * vec3(2.2, 0.9, 0.6));
        float sunUp = max(normalize(mu.sun.xyz).y, 0.0);
        color = color * absorb + vec3(1.0, 0.95, 0.75) * caustics * sunUp * exp(-depth * 2.2) * 0.45;
    }
    return vec4(color, 1.0);
}
`;
```

`shaders/water.ts`:

```ts
// The pond's water. A single plane: where the ground is above it, the ground hides it.
// - Normal: the simulated waves (the `waves` map) and a faint ripple of wind, with a cap on the tilt.
// - Body: teal, darker and less see-through the deeper it is (the `depth` map, the bottom's height).
// - Reflection: the sky, with Fresnel worked out on a softened normal, and the sun's glint on every
//   wave. That way the waves sparkle without turning the pond into a mirror of liquid metal.
// - Foam: at the shore and on the high crests.

export type TPondKnobs = Record<string, number[]> & {
    /**
     * The water's height, the bottom's lowest and highest (what the depth map's 0 and 1 are), and
     * the WAVES view (0 or 1).
     */
    level: number[];
    /**
     * Where the water lies: x, z of its corner, and its size.
     */
    area: number[];
    /**
     * Metres per unit of the wave map, 1 / (2 × a cell in metres), and a cell in uv.
     */
    wave: number[];
    /**
     * Towards the sun.
     */
    sun: number[];
    skyLow: number[];
    skyHigh: number[];
    shallow: number[];
    deep: number[];
};

export const WATER_WGSL = /* wgsl */ `
fn pondHash(p: vec2<f32>) -> f32 {
    return fract(sin(dot(p, vec2<f32>(127.1, 311.7))) * 43758.5453);
}

fn pondNoise(p: vec2<f32>) -> f32 {
    let i = floor(p);
    let f = fract(p);
    let u = f * f * (3.0 - 2.0 * f);
    return mix(mix(pondHash(i), pondHash(i + vec2<f32>(1.0, 0.0)), u.x),
               mix(pondHash(i + vec2<f32>(0.0, 1.0)), pondHash(i + vec2<f32>(1.0, 1.0)), u.x), u.y);
}

fn effect(surface: vec4<f32>, ctx: FragContext) -> vec4<f32> {
    let p = ctx.worldPos;
    let uv = (p.xz - mu.area.xy) / mu.area.z;
    let ground = mix(mu.level.y, mu.level.z, sampleMap_depth(uv).r);
    let depth = mu.level.x - ground;
    if (depth <= 0.0) {
        return vec4<f32>(0.0);
    }

    let t = mu.wave.z;
    let here = sampleMap_waves(uv).r;
    let height = (here - 0.5) * mu.wave.x;
    let sx = (sampleMap_waves(uv + vec2<f32>(t, 0.0)).r - sampleMap_waves(uv - vec2<f32>(t, 0.0)).r) * mu.wave.x * mu.wave.y;
    let sz = (sampleMap_waves(uv + vec2<f32>(0.0, t)).r - sampleMap_waves(uv - vec2<f32>(0.0, t)).r) * mu.wave.x * mu.wave.y;
    let wind = vec2<f32>(
        pondNoise(p.xz * 3.0 + vec2<f32>(mu.time * 0.6, 0.0)) - pondNoise(p.xz * 3.0 + vec2<f32>(mu.time * 0.6 + 0.3, 0.0)),
        pondNoise(p.xz * 3.0 + vec2<f32>(0.0, mu.time * 0.5)) - pondNoise(p.xz * 3.0 + vec2<f32>(0.0, mu.time * 0.5 + 0.3))
    ) * 0.05;
    let slope = clamp(vec2<f32>(sx, sz) + wind, vec2<f32>(-0.45), vec2<f32>(0.45));
    let n = normalize(vec3<f32>(-slope.x, 1.0, -slope.y));

    let v = normalize(ctx.viewDir);
    let calm = normalize(mix(vec3<f32>(0.0, 1.0, 0.0), n, 0.4));
    let fresnel = 0.02 + 0.55 * pow(1.0 - max(dot(calm, v), 0.0), 5.0);
    let r = reflect(-v, n);
    let sky = mix(mu.skyLow.rgb, mu.skyHigh.rgb, clamp(r.y, 0.0, 1.0));
    let toSun = normalize(mu.sun.xyz);
    let glint = pow(max(dot(r, toSun), 0.0), 700.0) * 3.0 + pow(max(dot(r, toSun), 0.0), 60.0) * 0.25;

    let thick = 1.0 - exp(-depth * 1.5);
    let body = mix(mu.shallow.rgb, mu.deep.rgb, thick);
    var color = body * (1.0 - fresnel) + sky * fresnel + vec3<f32>(1.0, 0.97, 0.88) * glint;
    var alpha = clamp(0.08 + thick * 0.8 + fresnel * 0.4 + glint, 0.0, 1.0) * smoothstep(0.0, 0.02, depth);

    let shore = smoothstep(0.07, 0.0, depth) * (0.35 + clamp(abs(height) * 25.0, 0.0, 0.65));
    let crest = smoothstep(0.035, 0.08, height);
    let foam = clamp(shore + crest, 0.0, 1.0) * (0.6 + pondNoise(p.xz * 14.0 + mu.time) * 0.4);
    color = mix(color, vec3<f32>(0.95, 0.97, 1.0), foam * 0.8);
    alpha = max(alpha, foam * 0.85);

    // The WAVES view: red for the depth, green for the height of the waves.
    let debug = vec3<f32>(depth * 1.5, 0.5 + height * 12.0, 0.4);
    return vec4<f32>(mix(color, debug, mu.level.w), mix(alpha, 0.9, mu.level.w));
}
`;

export const WATER_GLSL = /* glsl */ `
float pondHash(vec2 p) {
    return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
}

float pondNoise(vec2 p) {
    vec2 i = floor(p);
    vec2 f = fract(p);
    vec2 u = f * f * (3.0 - 2.0 * f);
    return mix(mix(pondHash(i), pondHash(i + vec2(1.0, 0.0)), u.x),
               mix(pondHash(i + vec2(0.0, 1.0)), pondHash(i + vec2(1.0, 1.0)), u.x), u.y);
}

vec4 effect(vec4 surface, FragContext ctx) {
    vec3 p = ctx.worldPos;
    vec2 uv = (p.xz - mu.area.xy) / mu.area.z;
    float ground = mix(mu.level.y, mu.level.z, sampleMap_depth(uv).r);
    float depth = mu.level.x - ground;
    if (depth <= 0.0) {
        return vec4(0.0);
    }

    float t = mu.wave.z;
    float here = sampleMap_waves(uv).r;
    float height = (here - 0.5) * mu.wave.x;
    float sx = (sampleMap_waves(uv + vec2(t, 0.0)).r - sampleMap_waves(uv - vec2(t, 0.0)).r) * mu.wave.x * mu.wave.y;
    float sz = (sampleMap_waves(uv + vec2(0.0, t)).r - sampleMap_waves(uv - vec2(0.0, t)).r) * mu.wave.x * mu.wave.y;
    vec2 wind = vec2(
        pondNoise(p.xz * 3.0 + vec2(mu.time * 0.6, 0.0)) - pondNoise(p.xz * 3.0 + vec2(mu.time * 0.6 + 0.3, 0.0)),
        pondNoise(p.xz * 3.0 + vec2(0.0, mu.time * 0.5)) - pondNoise(p.xz * 3.0 + vec2(0.0, mu.time * 0.5 + 0.3))
    ) * 0.05;
    vec2 slope = clamp(vec2(sx, sz) + wind, vec2(-0.45), vec2(0.45));
    vec3 n = normalize(vec3(-slope.x, 1.0, -slope.y));

    vec3 v = normalize(ctx.viewDir);
    vec3 calm = normalize(mix(vec3(0.0, 1.0, 0.0), n, 0.4));
    float fresnel = 0.02 + 0.55 * pow(1.0 - max(dot(calm, v), 0.0), 5.0);
    vec3 r = reflect(-v, n);
    vec3 sky = mix(mu.skyLow.rgb, mu.skyHigh.rgb, clamp(r.y, 0.0, 1.0));
    vec3 toSun = normalize(mu.sun.xyz);
    float glint = pow(max(dot(r, toSun), 0.0), 700.0) * 3.0 + pow(max(dot(r, toSun), 0.0), 60.0) * 0.25;

    float thick = 1.0 - exp(-depth * 1.5);
    vec3 body = mix(mu.shallow.rgb, mu.deep.rgb, thick);
    vec3 color = body * (1.0 - fresnel) + sky * fresnel + vec3(1.0, 0.97, 0.88) * glint;
    float alpha = clamp(0.08 + thick * 0.8 + fresnel * 0.4 + glint, 0.0, 1.0) * smoothstep(0.0, 0.02, depth);

    float shore = smoothstep(0.07, 0.0, depth) * (0.35 + clamp(abs(height) * 25.0, 0.0, 0.65));
    float crest = smoothstep(0.035, 0.08, height);
    float foam = clamp(shore + crest, 0.0, 1.0) * (0.6 + pondNoise(p.xz * 14.0 + mu.time) * 0.4);
    color = mix(color, vec3(0.95, 0.97, 1.0), foam * 0.8);
    alpha = max(alpha, foam * 0.85);

    // The WAVES view: red for the depth, green for the height of the waves.
    vec3 debug = vec3(depth * 1.5, 0.5 + height * 12.0, 0.4);
    return vec4(mix(color, debug, mu.level.w), mix(alpha, 0.9, mu.level.w));
}
`;
```

`simulation/waves.ts`:

```ts
/**
 * The pond's waves: the wave equation on a grid of `cells` by `cells` over the middle `area` by
 * `area` world units. Only the cells where `wet` says there is water count: the dry ones stay at 0,
 * so the waves bounce off the shore and the island. Heights are in metres, 0 for still water.
 *
 * Nothing here comes from the engine: it is plain numbers, stepped by the game.
 */
export const createWaves = ({ area, cells, speed, keep, wet }: {
    area: number;
    cells: number;
    /**
     * How fast the waves travel, per step. Above 0.25 the grid blows up.
     */
    speed: number;
    /**
     * How much of the waves is left after each step.
     */
    keep: number;
    wet: (x: number, z: number) => boolean;
}) => {
    const n = cells;
    const cell = area / n;
    const half = area / 2;
    let now = new Float32Array(n * n);
    let before = new Float32Array(n * n);
    const water = new Uint8Array(n * n);

    for (let z = 0; z < n; z++) {
        for (let x = 0; x < n; x++) {
            water[z * n + x] = wet((x + 0.5) * cell - half, (z + 0.5) * cell - half) ? 1 : 0;
        }
    }

    const at = (x: number, z: number) => now[z * n + x];

    return {
        /**
         * One step forward. The new heights are written over the oldest ones.
         */
        step() {
            const next = before;

            for (let z = 1; z < n - 1; z++) {
                for (let x = 1; x < n - 1; x++) {
                    const i = z * n + x;

                    if (!water[i]) {
                        next[i] = 0;
                        continue;
                    }

                    const sum = now[i - 1] + now[i + 1] + now[i - n] + now[i + n];

                    next[i] = (2 * now[i] - before[i] + (sum - 4 * now[i]) * speed) * keep;
                }
            }

            before = now;
            now = next;
        },

        /**
         * Pushes the water down by `amount` metres in a round dip of `radius` at `x`, `z`.
         */
        push(x: number, z: number, radius: number, amount: number) {
            const cx = (x + half) / cell;
            const cz = (z + half) / cell;
            const r = Math.max(1.5, radius / cell);
            const x0 = Math.max(1, Math.floor(cx - r));
            const x1 = Math.min(n - 2, Math.ceil(cx + r));
            const z0 = Math.max(1, Math.floor(cz - r));
            const z1 = Math.min(n - 2, Math.ceil(cz + r));

            for (let gz = z0; gz <= z1; gz++) {
                for (let gx = x0; gx <= x1; gx++) {
                    const i = gz * n + gx;

                    if (!water[i]) {
                        continue;
                    }

                    const d = Math.hypot(gx + 0.5 - cx, gz + 0.5 - cz) / r;

                    if (d < 1) {
                        now[i] -= amount * (1 - d * d) ** 2;
                    }
                }
            }
        },

        /**
         * The water's height at a point, and how steep it is along x and along z.
         */
        at(x: number, z: number) {
            const gx = Math.floor((x + half) / cell);
            const gz = Math.floor((z + half) / cell);

            if (gx < 1 || gz < 1 || gx >= n - 1 || gz >= n - 1) {
                return {
                    height: 0,
                    slopeX: 0,
                    slopeZ: 0
                };
            }

            return {
                height: at(gx, gz),
                slopeX: (at(gx + 1, gz) - at(gx - 1, gz)) / (2 * cell),
                slopeZ: (at(gx, gz + 1) - at(gx, gz - 1)) / (2 * cell)
            };
        },

        /**
         * Writes the heights into the pixels of a `cells` by `cells` picture, `scale` units of grey a
         * metre, 128 for still water.
         */
        paint(data: Uint8Array | Uint8ClampedArray, scale: number) {
            for (let i = 0; i < n * n; i++) {
                const v = Math.max(0, Math.min(255, Math.round(128 + now[i] * scale)));
                const o = i * 4;

                data[o] = v;
                data[o + 1] = v;
                data[o + 2] = v;
                data[o + 3] = 255;
            }
        }
    };
};

export type TWaves = ReturnType<typeof createWaves>;
```
