# Latte

> A cup of coffee with latte art and a spoon that stirs it: the foam stretches into spirals, keeps swirling after the spoon stops and slowly mixes into the coffee.

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

A cup of coffee with latte art and a spoon that stirs it. The foam stretches into spirals, keeps swirling after the spoon stops and slowly mixes into the coffee until it is all one creamy brown. The surface sinks in the middle and climbs the porcelain as it turns, and steam rises off the top.

Underneath is a 160 × 160 fluid simulated on the CPU, with MacCormack advection for the foam, whose pressure raises and sinks the surface's mesh. The porcelain and the steel are glazed materials lit per pixel. **Drag** to stir; left alone, the spoon stirs by itself. **R** for fresh latte art (a heart, a tulip, plain foam) and **V** to see the flow in colours or the surface's mesh.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { Latte } from './scenes/latte';
import { ACTIONS, BACKGROUND, HEIGHT, WIDTH } from './settings';

// A cup of coffee with latte art and a spoon that stirs it: the foam stretches into spirals, keeps
// swirling after the spoon stops, and slowly mixes into the coffee until it is all one creamy brown.
// The surface sinks in the middle and climbs the porcelain as it turns. Steam rises off the top.
//
//   drag   stir (the spoon follows the pointer over the coffee)
//   R      fresh latte art: a heart, a tulip, plain foam (or the button)
//   V      switch views: the coffee, the flow in colours, the surface's mesh (or the button)
//
// Left alone, the spoon stirs by itself.
const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    background: BACKGROUND,
    scaling: 'contain',
    step: 60,
    actions: ACTIONS
});

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

`art/textures.ts`:

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

/**
 * The table's wood: grain in waves, planks a little darker one in two, and a speck of noise.
 */
export const woodTexture = (random: TRandomHandle) => {
    const size = 64;
    const pixels = createPixels(size, size);

    for (let y = 0; y < size; y++) {
        for (let x = 0; x < size; x++) {
            const grain = Math.sin(y * 0.9 + Math.sin(x * 0.12) * 2.5) * 0.5 + 0.5;
            const plank = Math.floor(y / 16) % 2 === 0 ? 1 : 0.9;
            const k = (0.55 + grain * 0.25) * plank * random.rand(0.94, 1);

            setPixel(pixels, x, y, `rgb(${Math.round(120 * k)}, ${Math.round(78 * k)}, ${Math.round(48 * k)})`);
        }
    }

    return createPixelTexture(pixels);
};

/**
 * A soft round puff of steam, fading to nothing at the edge.
 */
export const steamTexture = () => {
    const size = 32;
    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) ** 2).toFixed(3)})`);
        }
    }

    return createPixelTexture(pixels);
};
```

`components/coffee.ts`:

```ts
import { createGeometry, createMesh, setLines, updateGeometry, useLines, useUpdate } from 'nacatamalon';
import { createPixels, createPixelTexture, updatePixelTexture } from 'nacatamalon/pixels';
import { coffeeMaterial, type TCoffeeUniforms } from '../shaders/coffee';
import { createCupFluid, type TSpoonInCells } from '../simulation/cup_fluid';
import { COFFEE_RADIUS, FLUID, LEVEL, PATTERNS, TO_SUN, VIEWS } from '../settings';

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

/**
 * Every how many points of the mesh a line is drawn, in the MESH view.
 */
const LINE_EVERY = 2;

/**
 * The coffee: a fluid stepped every frame and painted into a picture the surface reads, on a mesh
 * that sinks in the middle and climbs the porcelain as it swirls. The spoon stirs it through `stir`,
 * and floats at the height `surfaceAt` gives.
 */
export const Coffee = () => {
    const m = FLUID.surfaceCells;
    const reach = COFFEE_RADIUS + 0.06;
    const fluid = createCupFluid(FLUID.cells);
    const fluidPixels = createPixels(FLUID.cells, FLUID.cells, '#808080');
    const fluidTexture = createPixelTexture(fluidPixels);

    const uniforms: TCoffeeUniforms = {
        cup: [0, 0, COFFEE_RADIUS, 1 / FLUID.cells],
        light: TO_SUN,
        look: [5, 0, 0, 0]
    };

    // The surface's mesh: a square grid whose outer points are drawn in to the rim, and a little past
    // it, into the porcelain, so that when the coffee rises no gap shows.
    const rest = new Float32Array(m * m * 2);

    for (let j = 0; j < m; j++) {
        for (let i = 0; i < m; i++) {
            let x = (i / (m - 1)) * 2 - 1;
            let z = (j / (m - 1)) * 2 - 1;
            const r = Math.hypot(x, z);

            if (r > 1) {
                x /= r;
                z /= r;
            }

            rest[(j * m + i) * 2] = x * reach;
            rest[(j * m + i) * 2 + 1] = z * reach;
        }
    }

    const indices = new Uint32Array((m - 1) * (m - 1) * 6);

    for (let j = 0, k = 0; j < m - 1; j++) {
        for (let i = 0; i < m - 1; i++) {
            const a = j * m + i;

            indices.set([a, a + m, a + 1, a + 1, a + m, a + m + 1], k);
            k += 6;
        }
    }

    // The height shown follows the fluid's, smoothed, so the surface does not tremble.
    const shown = new Float32Array(m * m);
    const goal = new Float32Array(m * m);
    const positions = new Float32Array(m * m * 3);
    const normals = new Float32Array(m * m * 3);
    const step = (2 * reach) / (m - 1);
    const heightOf = (i: number, j: number) => shown[Math.min(m - 1, Math.max(0, j)) * m + Math.min(m - 1, Math.max(0, i))];

    const surfaceData = () => {
        for (let j = 0; j < m; j++) {
            for (let i = 0; i < m; i++) {
                const p = j * m + i;
                const nx = -(heightOf(i + 1, j) - heightOf(i - 1, j));
                const nz = -(heightOf(i, j + 1) - heightOf(i, j - 1));
                const ny = 2 * step;
                const length = Math.hypot(nx, ny, nz);

                positions[p * 3] = rest[p * 2];
                positions[p * 3 + 1] = LEVEL + shown[p];
                positions[p * 3 + 2] = rest[p * 2 + 1];
                normals[p * 3] = nx / length;
                normals[p * 3 + 1] = ny / length;
                normals[p * 3 + 2] = nz / length;
            }
        }

        return {
            positions,
            normals,
            indices
        };
    };

    const surface = createGeometry(surfaceData());

    createMesh({
        geometry: surface,
        material: coffeeMaterial(fluidTexture, uniforms)
    });

    // The MESH view: the surface in lines, blue where it sinks and orange where it rises.
    const meshLines = useLines();
    let rows = 0;
    let perRow = 0;

    for (let j = 0; j < m; j += LINE_EVERY) {
        rows++;
    }

    for (let i = 0; i + LINE_EVERY < m; i += LINE_EVERY) {
        perRow++;
    }

    // Rows and columns, a line each per stretch, two corners a line, seven numbers a corner.
    const corners = new Float32Array(rows * perRow * 2 * 2 * 7);

    meshLines.visible = false;

    const drawMeshLines = () => {
        let o = 0;

        const corner = (i: number, j: number) => {
            const p = j * m + i;
            const t = Math.max(0, Math.min(1, (shown[p] / (FLUID.heightRange * 0.6)) * 0.5 + 0.5));

            corners.set([rest[p * 2], LEVEL + shown[p] + 0.02, rest[p * 2 + 1], 0.3 + t * 0.7, 0.55, 1 - t * 0.7, 0.9], o);
            o += 7;
        };

        for (let j = 0; j < m; j += LINE_EVERY) {
            for (let i = 0; i + LINE_EVERY < m; i += LINE_EVERY) {
                corner(i, j);
                corner(i + LINE_EVERY, j);
            }
        }

        for (let i = 0; i < m; i += LINE_EVERY) {
            for (let j = 0; j + LINE_EVERY < m; j += LINE_EVERY) {
                corner(i, j);
                corner(i, j + LINE_EVERY);
            }
        }

        setLines(meshLines, corners);
    };

    // Where the spoon is, in cells, for the next steps.
    const cell = (2 * COFFEE_RADIUS) / FLUID.cells;
    const toCell = (w: number) => (w + COFFEE_RADIUS) / cell - 0.5;

    const spoon: TSpoonInCells = {
        x: 0,
        y: 0,
        radius: 1,
        vx: 0,
        vy: 0,
        inside: 0
    };

    let pattern = 0;
    let view = 0;
    let owed = 0;

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

        while (owed >= STEP) {
            owed -= STEP;
            fluid.step(STEP, spoon);
        }

        fluid.paintMap(fluidPixels.data);
        updatePixelTexture(fluidTexture);
        fluid.heights(goal, m);

        // The surface goes towards the height the fluid says, with no jumps. tanh: the spoon's push
        // stays a bump.
        const ease = 1 - Math.exp(-10 * delta);

        for (let i = 0; i < shown.length; i++) {
            shown[i] += (FLUID.heightRange * Math.tanh(goal[i] / FLUID.pressureScale) - shown[i]) * ease;
        }

        updateGeometry(surface, surfaceData());

        if (VIEWS[view] === 'MESH') {
            drawMeshLines();
        }
    });

    return {
        /**
         * How far above or below `LEVEL` the coffee is at `x`, `z`.
         */
        surfaceAt(x: number, z: number) {
            const i = Math.round(((x / reach) * 0.5 + 0.5) * (m - 1));
            const j = Math.round(((z / reach) * 0.5 + 0.5) * (m - 1));

            return heightOf(i, j);
        },

        /**
         * The spoon's bowl is at `x`, `z` (world), `radius` wide and moving at `vx`, `vz` a second.
         */
        stir(x: number, z: number, radius: number, vx: number, vz: number) {
            spoon.x = toCell(x);
            spoon.y = toCell(z);
            spoon.radius = radius / cell;
            spoon.vx = vx / cell;
            spoon.vy = vz / cell;
            spoon.inside = 0.85;
        },

        /**
         * The latte art now, and the next one, poured fresh.
         */
        pattern: () => PATTERNS[pattern],

        nextPattern() {
            pattern = (pattern + 1) % PATTERNS.length;
            fluid.paint(pattern);
        },

        /**
         * The view now, and the next one.
         */
        view: () => VIEWS[view],

        nextView() {
            view = (view + 1) % VIEWS.length;
            uniforms.look[1] = VIEWS[view] === 'FLOW' ? 1 : 0;
            meshLines.visible = VIEWS[view] === 'MESH';
        }
    };
};

export type TCoffee = ReturnType<typeof Coffee>;
```

`components/controls.ts`:

```ts
import { createSprite, createText, listen, useAction, useUpdate } from 'nacatamalon';
import { HEIGHT, WIDTH } from '../settings';
import type { TCoffee } from './coffee';

/**
 * Two buttons at the top right, for fresh latte art and for the view, and the same with R and V.
 * Each says what it is now.
 */
export const Controls = ({ coffee }: { coffee: TCoffee; }) => {
    const button = (y: number, onClick: () => void) => {
        const back = createSprite({
            width: 150,
            height: 18,
            tint: '#1c2338',
            anchor: {
                x: 1,
                y: 0
            },
            zIndex: 100,
            transform: {
                x: WIDTH - 8,
                y
            }
        });

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

        listen(back, {
            onClick
        });
        listen(label, {
            onClick
        });

        return label;
    };

    const patternLabel = button(5, () => coffee.nextPattern());
    const viewLabel = button(27, () => coffee.nextView());

    createText({
        text: 'DRAG TO STIR',
        tint: '#e8d6c0',
        zIndex: 100,
        transform: {
            x: 8,
            y: 8
        }
    });
    createText({
        text: 'LATTE · NACATAMALON',
        tint: '#e8d6c0',
        zIndex: 100,
        transform: {
            x: 8,
            y: HEIGHT - 16
        }
    });

    const pattern = useAction('pattern');
    const view = useAction('view');

    useUpdate(() => {
        if (pattern.justPressed()) {
            coffee.nextPattern();
        }

        if (view.justPressed()) {
            coffee.nextView();
        }

        patternLabel.text = `[R] NEW: ${coffee.pattern()}`;
        viewLabel.text = `[V] VIEW: ${coffee.view()}`;
    });
};
```

`components/spoon.ts`:

```ts
import { createMesh, screenToRay, useCylinderGeometry, useGame, usePointer, useSphereGeometry, useUpdate, type TCamera3d } from 'nacatamalon';
import { quatFromAxisAngle } from 'nacatamalon/math';
import { glazeMaterial } from '../shaders/glaze';
import { COFFEE_RADIUS, LEVEL, SPOON_BOWL } from '../settings';
import type { TCoffee } from './coffee';

/**
 * The spoon: a bowl (a flattened sphere) half sunk in the coffee, and a handle that leans out over
 * the rim. Held down, the pointer drags it over the coffee; let go for two seconds, it stirs by
 * itself, in circles and figures of eight.
 */
export const Spoon = ({ coffee, camera }: { coffee: TCoffee; camera: TCamera3d; }) => {
    const game = useGame();
    const pointer = usePointer();

    const steel = glazeMaterial({
        tint: '#c9ced6',
        reflect: 0.85,
        sharpness: 90,
        tinted: true
    });

    const bowl = createMesh({
        geometry: useSphereGeometry({
            radius: 1,
            segments: 20,
            rings: 12
        }),
        material: steel,
        castShadow: true,
        transform: {
            scaleX: 0.55,
            scaleY: 0.14,
            scaleZ: SPOON_BOWL * 1.25
        }
    });

    const handle = createMesh({
        geometry: useCylinderGeometry({
            radius: 0.1,
            height: 1,
            segments: 10
        }),
        material: steel,
        castShadow: true
    });

    const spoon = {
        x: 1.6,
        z: 0,
        vx: 0,
        vz: 0
    };

    const reach = COFFEE_RADIUS - SPOON_BOWL - 0.25;
    let autoTime = 0;
    let idleFor = 0;

    useUpdate((delta) => {
        let targetX = spoon.x;
        let targetZ = spoon.z;
        const held = pointer.isDown() ? pointer.position() : null;

        if (held) {
            // Where the pointer's ray meets the coffee.
            idleFor = 0;

            const ray = screenToRay(camera, game.getWidth(), game.getHeight(), held.screenX, held.screenY);
            const t = (LEVEL - ray.origin.y) / ray.direction.y;

            targetX = ray.origin.x + ray.direction.x * t;
            targetZ = ray.origin.z + ray.direction.z * t;
        } else {
            idleFor += delta;

            if (idleFor > 2) {
                autoTime += delta * 2.2;

                const r = reach * (0.65 + Math.sin(autoTime * 0.23) * 0.3);

                targetX = Math.cos(autoTime) * r;
                targetZ = Math.sin(autoTime) * r * (0.75 + Math.sin(autoTime * 0.5) * 0.25);
            }
        }

        const d = Math.hypot(targetX, targetZ);

        if (d > reach) {
            targetX *= reach / d;
            targetZ *= reach / d;
        }

        const follow = 1 - Math.exp(-14 * delta);
        const nx = spoon.x + (targetX - spoon.x) * follow;
        const nz = spoon.z + (targetZ - spoon.z) * follow;

        spoon.vx = (nx - spoon.x) / Math.max(delta, 1e-4);
        spoon.vz = (nz - spoon.z) / Math.max(delta, 1e-4);
        spoon.x = nx;
        spoon.z = nz;
        coffee.stir(spoon.x, spoon.z, SPOON_BOWL, spoon.vx, spoon.vz);

        // The bowl, half sunk, facing the way the handle goes: out from the middle.
        const away = Math.hypot(spoon.x, spoon.z) > 0.4;
        const outX = away ? spoon.x : 1;
        const outZ = away ? spoon.z : 0.3;
        const outLength = Math.hypot(outX, outZ);
        const ox = outX / outLength;
        const oz = outZ / outLength;

        bowl.transform.x = spoon.x;
        bowl.transform.y = LEVEL + coffee.surfaceAt(spoon.x, spoon.z) - 0.02;
        bowl.transform.z = spoon.z;
        bowl.transform.rotationY = Math.atan2(ox, oz);

        // The handle: from the bowl to past the rim, above it.
        const startX = spoon.x + ox * SPOON_BOWL * 1.1;
        const startY = LEVEL + 0.05;
        const startZ = spoon.z + oz * SPOON_BOWL * 1.1;
        const endX = ox * (COFFEE_RADIUS + 1.7);
        const endY = LEVEL + 2.3;
        const endZ = oz * (COFFEE_RADIUS + 1.7);
        const hx = endX - startX;
        const hy = endY - startY;
        const hz = endZ - startZ;
        const length = Math.hypot(hx, hy, hz);

        handle.transform.x = (startX + endX) / 2;
        handle.transform.y = (startY + endY) / 2;
        handle.transform.z = (startZ + endZ) / 2;
        handle.transform.scaleY = length;

        // Turns the cylinder's y axis to the handle's direction, about the axis square to both.
        const axisX = hz;
        const axisZ = -hx;
        const axisLength = Math.hypot(axisX, axisZ) || 1;

        handle.transform.quaternion = quatFromAxisAngle(axisX / axisLength, 0, axisZ / axisLength, Math.acos(hy / length));
    });
};
```

`components/steam.ts`:

```ts
import { createParticles3d } from 'nacatamalon';
import { steamTexture } from '../art/textures';
import { COFFEE_RADIUS, LEVEL } from '../settings';

/**
 * Steam off the top: soft puffs that rise slowly, open out and fade.
 */
export const Steam = () => {
    createParticles3d({
        effect: {
            kind: 'particles-3d',
            texture: steamTexture(),
            blend: 'additive',
            worldSpace: true,
            max: 120,
            emission: {
                rate: 14
            },
            shape: {
                kind: 'box',
                size: [COFFEE_RADIUS * 1.4, 0.05, COFFEE_RADIUS * 1.4]
            },
            direction: {
                x: 0,
                y: 1,
                z: 0
            },
            spread: 0.35,
            speed: [0.25, 0.6],
            gravity: {
                x: 0.04,
                y: 0.05,
                z: -0.02
            },
            damping: 0.15,
            life: [3, 5],
            size: [1.1, 1.7],
            spin: [-0.4, 0.4],
            sizeOverLife: [
                {
                    t: 0,
                    scale: 0.5
                },
                {
                    t: 1,
                    scale: 2.4
                }
            ],
            colorOverLife: [
                {
                    t: 0,
                    color: '#ffffff',
                    alpha: 0
                },
                {
                    t: 0.25,
                    color: '#ffffff',
                    alpha: 0.13
                },
                {
                    t: 1,
                    color: '#ffffff',
                    alpha: 0
                }
            ]
        },
        transform: {
            y: LEVEL + 0.2
        }
    });
};
```

`components/table_set.ts`:

```ts
import { createMesh, useLatheGeometry, usePlaneGeometry, useTorusGeometry } from 'nacatamalon';
import { useRandom } from 'nacatamalon/math';
import { woodTexture } from '../art/textures';
import { glazeMaterial } from '../shaders/glaze';
import { CUP_PROFILE } from '../settings';

/**
 * The wooden table, and the saucer and the cup on it, in glazed porcelain: the saucer and the cup
 * turned on a lathe, the handle a ring.
 */
export const TableSet = () => {
    const porcelain = glazeMaterial({
        tint: '#f6f2ea',
        reflect: 0.12,
        sharpness: 160,
        tinted: false
    });

    createMesh({
        geometry: usePlaneGeometry({
            width: 90,
            depth: 90,
            widthSegments: 18,
            depthSegments: 18
        }),
        texture: woodTexture(useRandom()),
        tint: '#ffffff',
        transform: {
            y: -0.3
        }
    });

    createMesh({
        geometry: useLatheGeometry({
            profile: [
                {
                    x: 0,
                    y: 0
                },
                {
                    x: 5.6,
                    y: 0
                },
                {
                    x: 6.4,
                    y: 0.25
                },
                {
                    x: 6.6,
                    y: 0.42
                },
                {
                    x: 6.2,
                    y: 0.38
                },
                {
                    x: 4.2,
                    y: 0.12
                },
                {
                    x: 0,
                    y: 0.12
                }
            ],
            segments: 48
        }),
        material: porcelain,
        castShadow: true,
        transform: {
            y: -0.3
        }
    });

    createMesh({
        geometry: useLatheGeometry({
            profile: CUP_PROFILE,
            segments: 56
        }),
        material: porcelain,
        castShadow: true
    });

    createMesh({
        geometry: useTorusGeometry({
            radius: 1.15,
            tube: 0.26,
            radialSegments: 12,
            tubularSegments: 28
        }),
        material: porcelain,
        castShadow: true,
        transform: {
            x: 4.45,
            y: 2.5,
            z: 0,
            rotationX: Math.PI / 2
        }
    });
};
```

`scenes/latte.ts`:

```ts
import { cameraLookAt, createScene, useAmbientLight, useCamera3d, useDirectionalLight, useSpawn } from 'nacatamalon';
import { Coffee } from '../components/coffee';
import { Controls } from '../components/controls';
import { Spoon } from '../components/spoon';
import { Steam } from '../components/steam';
import { TableSet } from '../components/table_set';
import { SUN } from '../settings';

/**
 * A cup of coffee on a wooden table, seen from above at a slant. The coffee is made first, and
 * handed to the spoon, which stirs it and floats on it, and to the buttons, which change it.
 */
export const Latte = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 45,
        transform: {
            x: 0,
            y: 9.6,
            z: 10.8
        }
    });

    cameraLookAt(camera, {
        x: 0,
        y: 2.8,
        z: 0.4
    });

    useAmbientLight({
        color: '#e6d8c8',
        intensity: 0.78
    });
    useDirectionalLight({
        color: '#fff0dc',
        intensity: 1.05,
        castShadow: true,
        shadowArea: 24,
        transform: SUN
    });

    useSpawn(TableSet)();

    const coffee = useSpawn(Coffee)().api;

    useSpawn(Spoon)({
        coffee,
        camera
    });
    useSpawn(Steam)();
    useSpawn(Controls)({
        coffee
    });

    return createScene();
};
```

`settings.ts`:

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

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

/**
 * The room behind the table.
 */
export const BACKGROUND = '#2b1e16';

/**
 * R pours fresh latte art, V switches views.
 */
export const ACTIONS: TActionDef[] = [
    {
        name: 'pattern',
        bindings: [
            {
                type: 'key',
                key: 'r'
            }
        ]
    },
    {
        name: 'view',
        bindings: [
            {
                type: 'key',
                key: 'v'
            }
        ]
    }
];

/**
 * The latte art R goes through: a heart, a tulip (three drops stacked) and plain foam.
 */
export const PATTERNS = ['HEART', 'TULIP', 'FOAM'] as const;

/**
 * What V shows: the coffee as it is, the flow in colours (red and blue the current, green the foam)
 * and the surface's mesh in lines (blue where it sinks, orange where it rises).
 */
export const VIEWS = ['COFFEE', 'FLOW', 'MESH'] as const;

/**
 * Where the sun shines from, as the light's turn about x and y, and the same as a direction towards
 * it, for the materials that work their shine out per pixel.
 */
export const SUN = {
    rotationX: -0.95,
    rotationY: 0.65
};

export const TO_SUN = [Math.sin(SUN.rotationY) * Math.cos(SUN.rotationX), -Math.sin(SUN.rotationX), Math.cos(SUN.rotationY) * Math.cos(SUN.rotationX), 0];

/**
 * The cup, in profile (radius, height), as the lathe turns it: the outside, the rim and the inside.
 */
export const CUP_PROFILE = [
    {
        x: 0,
        y: 0
    },
    {
        x: 3.2,
        y: 0
    },
    {
        x: 3.4,
        y: 0.12
    },
    {
        x: 3.95,
        y: 4.4
    },
    {
        x: 4.08,
        y: 4.6
    },
    {
        x: 3.86,
        y: 4.62
    },
    {
        x: 3.78,
        y: 4.4
    },
    {
        x: 3.25,
        y: 0.5
    },
    {
        x: 0,
        y: 0.42
    }
];

/**
 * How high the coffee stands in the cup, and its radius there: the inside of the cup at that height.
 */
export const LEVEL = 3.9;
export const COFFEE_RADIUS = 3.25 + ((LEVEL - 0.5) / 3.9) * 0.53 - 0.02;

/**
 * The coffee as a fluid: `cells` by `cells` cells over the square the coffee fits in. The surface's
 * mesh has `surfaceCells` points a side, and rises and sinks by up to `heightRange` (world units)
 * with the swirl; `pressureScale` is how much pressure makes that much.
 */
export const FLUID = {
    cells: 160,
    surfaceCells: 80,
    heightRange: 0.34,
    pressureScale: 120
};

/**
 * The spoon's bowl: its half-length, in world units.
 */
export const SPOON_BOWL = 0.62;
```

`shaders/coffee.ts`:

```ts
import { createMaterial, type TTexture } from 'nacatamalon';

/**
 * The coffee's surface, a mesh that reads the fluid's picture (red the foam, green and blue the
 * current):
 *
 * - Colour: from dark coffee to crema to white foam, by how much foam there is.
 * - Relief: the mesh sinks and rises with the swirl (its normal comes with it), and the foam stands
 *   a little proud, so its edge shades and catches the light; that normal comes from how the foam
 *   changes from one cell to the next.
 * - Microfoam: a soft mottle where the foam is thin.
 * - Shine: coffee with no foam is liquid and reflects the light; the foam is matte.
 * - Meniscus: a dark ring and a thread of light where the coffee meets the porcelain.
 */
const COFFEE_WGSL = /* wgsl */ `
fn cupHash(p: vec2<f32>) -> f32 {
    return fract(sin(dot(p, vec2<f32>(127.1, 311.7))) * 43758.5453);
}

fn cupNoise(p: vec2<f32>) -> f32 {
    let i = floor(p);
    let f = fract(p);
    let u = f * f * (3.0 - 2.0 * f);
    return mix(mix(cupHash(i), cupHash(i + vec2<f32>(1.0, 0.0)), u.x),
               mix(cupHash(i + vec2<f32>(0.0, 1.0)), cupHash(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 local = (p.xz - mu.cup.xy) / mu.cup.z;
    let uv = local * 0.5 + 0.5;
    let r = length(local);
    let here = sampleMap_fluid(uv);
    let f = here.r;
    let t = mu.cup.w;
    let fx = sampleMap_fluid(uv + vec2<f32>(t, 0.0)).r - sampleMap_fluid(uv - vec2<f32>(t, 0.0)).r;
    let fz = sampleMap_fluid(uv + vec2<f32>(0.0, t)).r - sampleMap_fluid(uv - vec2<f32>(0.0, t)).r;
    // The swirl's relief comes in the mesh's normal; the foam adds its own on top.
    let n = normalize(normalize(ctx.normal) + vec3<f32>(-fx * mu.look.x, 0.0, -fz * mu.look.x));

    let coffee = vec3<f32>(0.11, 0.055, 0.028);
    let crema = vec3<f32>(0.6, 0.39, 0.21);
    let milk = vec3<f32>(0.97, 0.93, 0.85);
    var base = mix(coffee, crema, smoothstep(0.0, 0.42, f));
    base = mix(base, milk, smoothstep(0.45, 0.95, f));

    // Microfoam: a soft mottle, mostly where the foam is thin. In patches of a few pixels: dots smaller
    // than a pixel read as flickering noise.
    let mottle = cupNoise(p.xz * 5.0) * 0.6 + cupNoise(p.xz * 11.0 + 3.7) * 0.4;
    let bubble = smoothstep(0.55, 0.85, mottle) * smoothstep(0.15, 0.5, f) * (1.0 - smoothstep(0.75, 1.0, f));
    base = base * (1.0 - bubble * 0.15);

    let toLight = normalize(mu.light.xyz);
    let v = normalize(ctx.viewDir);
    let diffuse = 0.72 + 0.35 * dot(n, toLight);
    let wet = 1.0 - smoothstep(0.2, 0.6, f);
    let spec = pow(max(dot(reflect(-v, n), toLight), 0.0), 90.0) * wet * 0.9;

    // The meniscus against the wall.
    let rim = smoothstep(0.9, 1.0, r);
    var color = base * diffuse * (1.0 - rim * 0.45) + vec3<f32>(1.0, 0.95, 0.85) * (spec + smoothstep(0.975, 0.995, r) * 0.25);

    // The FLOW view: the foam in green and the current in red and blue.
    let flow = (here.gb - vec2<f32>(0.5)) * 6.0;
    let debug = vec3<f32>(0.5 + flow.x, f, 0.5 + flow.y);
    color = mix(color, debug, mu.look.y);
    return vec4<f32>(color, 1.0);
}
`;

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

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

vec4 effect(vec4 surface, FragContext ctx) {
    vec3 p = ctx.worldPos;
    vec2 local = (p.xz - mu.cup.xy) / mu.cup.z;
    vec2 uv = local * 0.5 + 0.5;
    float r = length(local);
    vec4 here = sampleMap_fluid(uv);
    float f = here.r;
    float t = mu.cup.w;
    float fx = sampleMap_fluid(uv + vec2(t, 0.0)).r - sampleMap_fluid(uv - vec2(t, 0.0)).r;
    float fz = sampleMap_fluid(uv + vec2(0.0, t)).r - sampleMap_fluid(uv - vec2(0.0, t)).r;
    vec3 n = normalize(normalize(ctx.normal) + vec3(-fx * mu.look.x, 0.0, -fz * mu.look.x));

    vec3 coffee = vec3(0.11, 0.055, 0.028);
    vec3 crema = vec3(0.6, 0.39, 0.21);
    vec3 milk = vec3(0.97, 0.93, 0.85);
    vec3 base = mix(coffee, crema, smoothstep(0.0, 0.42, f));
    base = mix(base, milk, smoothstep(0.45, 0.95, f));

    float mottle = cupNoise(p.xz * 5.0) * 0.6 + cupNoise(p.xz * 11.0 + 3.7) * 0.4;
    float bubble = smoothstep(0.55, 0.85, mottle) * smoothstep(0.15, 0.5, f) * (1.0 - smoothstep(0.75, 1.0, f));
    base *= 1.0 - bubble * 0.15;

    vec3 toLight = normalize(mu.light.xyz);
    vec3 v = normalize(ctx.viewDir);
    float diffuse = 0.72 + 0.35 * dot(n, toLight);
    float wet = 1.0 - smoothstep(0.2, 0.6, f);
    float spec = pow(max(dot(reflect(-v, n), toLight), 0.0), 90.0) * wet * 0.9;

    float rim = smoothstep(0.9, 1.0, r);
    vec3 color = base * diffuse * (1.0 - rim * 0.45) + vec3(1.0, 0.95, 0.85) * (spec + smoothstep(0.975, 0.995, r) * 0.25);

    vec2 flow = (here.gb - vec2(0.5)) * 6.0;
    vec3 debug = vec3(0.5 + flow.x, f, 0.5 + flow.y);
    color = mix(color, debug, mu.look.y);
    return vec4(color, 1.0);
}
`;

/**
 * The coffee's uniforms, shared with the scene, which changes `look` to switch views.
 */
export type TCoffeeUniforms = {
    /**
     * The cup's middle on x and z, the coffee's radius, and one cell of the picture in uv.
     */
    cup: number[];
    /**
     * Towards the sun.
     */
    light: number[];
    /**
     * How proud the foam stands, and 1 for the FLOW view.
     */
    look: number[];
};

export const coffeeMaterial = (fluid: TTexture, uniforms: TCoffeeUniforms) => createMaterial({
    shader: 'mesh3d',
    name: 'coffee surface',
    fragment: COFFEE_WGSL,
    fragmentGlsl: COFFEE_GLSL,
    maps: {
        fluid: {
            texture: fluid,
            wrap: 'clamp',
            smooth: true
        }
    },
    uniforms
});
```

`shaders/glaze.ts`:

```ts
import { createMaterial } from 'nacatamalon';
import { TO_SUN } from '../settings';

/**
 * Glaze (ceramic) and metal. The engine lights per vertex, as the consoles of the time did, and on a
 * curved piece the highlight smears. Here it is worked out per pixel, with three things:
 *
 * - the sun's highlight, small and sharp;
 * - a reflection of the room: light above, the dark table below, and a bright window towards the
 *   sun;
 * - Fresnel: at a grazing angle it reflects more, which is why the cup's rim looks lighter.
 *
 * `glaze.x` is how much it reflects the room (little the ceramic, a lot the metal), `glaze.y` how
 * sharp the highlight is and `glaze.z` how much the piece's colour tints the reflection (the metal's
 * does, the ceramic's does not).
 */
const GLAZE_WGSL = /* wgsl */ `
fn effect(surface: vec4<f32>, ctx: FragContext) -> vec4<f32> {
    let n = normalize(ctx.normal);
    let v = normalize(ctx.viewDir);
    let toLight = normalize(mu.light.xyz);
    // The engine's light already has the shadows in it; the shine goes out where the piece is in shadow.
    let lit = ctx.light;
    let level = clamp(dot(lit, vec3<f32>(0.3333)), 0.0, 1.0);
    let sunlit = smoothstep(0.45, 0.85, level);

    let h = normalize(toLight + v);
    let spec = (pow(max(dot(n, h), 0.0), mu.glaze.y) * 1.6 + pow(max(dot(n, h), 0.0), 18.0) * 0.06) * sunlit;
    let fresnel = 0.04 + 0.96 * pow(1.0 - max(dot(n, v), 0.0), 4.0);
    let r = reflect(-v, n);
    let room = mix(vec3<f32>(0.22, 0.15, 0.1), vec3<f32>(0.96, 0.93, 0.88), smoothstep(-0.25, 0.55, r.y));
    let window = smoothstep(0.93, 0.975, dot(r, toLight));
    let tint = mix(vec3<f32>(1.0), surface.rgb, mu.glaze.z);
    let reflection = (room * mix(mu.glaze.x, 1.0, fresnel) + vec3<f32>(1.0) * window * 0.8) * tint * mix(mu.glaze.x, 0.6, fresnel);

    let color = surface.rgb * lit * (1.0 - mu.glaze.x * 0.6) + reflection + vec3<f32>(1.0, 0.97, 0.92) * spec;
    return vec4<f32>(color, 1.0);
}
`;

const GLAZE_GLSL = /* glsl */ `
vec4 effect(vec4 surface, FragContext ctx) {
    vec3 n = normalize(ctx.normal);
    vec3 v = normalize(ctx.viewDir);
    vec3 toLight = normalize(mu.light.xyz);
    vec3 lit = ctx.light;
    float level = clamp(dot(lit, vec3(0.3333)), 0.0, 1.0);
    float sunlit = smoothstep(0.45, 0.85, level);

    vec3 h = normalize(toLight + v);
    float spec = (pow(max(dot(n, h), 0.0), mu.glaze.y) * 1.6 + pow(max(dot(n, h), 0.0), 18.0) * 0.06) * sunlit;
    float fresnel = 0.04 + 0.96 * pow(1.0 - max(dot(n, v), 0.0), 4.0);
    vec3 r = reflect(-v, n);
    vec3 room = mix(vec3(0.22, 0.15, 0.1), vec3(0.96, 0.93, 0.88), smoothstep(-0.25, 0.55, r.y));
    float window = smoothstep(0.93, 0.975, dot(r, toLight));
    vec3 tint = mix(vec3(1.0), surface.rgb, mu.glaze.z);
    vec3 reflection = (room * mix(mu.glaze.x, 1.0, fresnel) + vec3(1.0) * window * 0.8) * tint * mix(mu.glaze.x, 0.6, fresnel);

    vec3 color = surface.rgb * lit * (1.0 - mu.glaze.x * 0.6) + reflection + vec3(1.0, 0.97, 0.92) * spec;
    return vec4(color, 1.0);
}
`;

/**
 * Glazed ceramic (`reflect` low) or metal (`reflect` high, tinted by its colour).
 */
export const glazeMaterial = ({ tint, reflect, sharpness, tinted }: { tint: string; reflect: number; sharpness: number; tinted: boolean; }) => createMaterial({
    shader: 'mesh3d',
    tint,
    name: tinted ? 'metal' : 'glazed ceramic',
    fragment: GLAZE_WGSL,
    fragmentGlsl: GLAZE_GLSL,
    uniforms: {
        light: TO_SUN,
        glaze: [reflect, sharpness, tinted ? 1 : 0, 0]
    }
});
```

`simulation/cup_fluid.ts`:

```ts
/**
 * Where the spoon is for the fluid: in cells, its radius in cells, its speed in cells a second, and
 * how much it holds the coffee under it (0 when it is out).
 */
export type TSpoonInCells = {
    x: number;
    y: number;
    radius: number;
    vx: number;
    vy: number;
    inside: number;
};

/**
 * The coffee in the cup as a 2D fluid (stable fluids) on a grid of `cells` by `cells` that covers
 * the surface. Outside the circle of the cup the cells are wall.
 *
 * - The spoon is an obstacle that moves: where it is, the coffee goes at its speed. Going round, it
 *   drags all the liquid with it, and when it stops the swirl keeps going for a good while.
 * - The foam travels with the current. With the simple way (semi-Lagrangian) it would blur at once;
 *   with MacCormack (back, forward again, and half the error corrected) the latte art stays thin as
 *   it stretches into spirals, and mixes slowly into the coffee until it is all one creamy brown,
 *   as in a real cup.
 *
 * Nothing here comes from the engine: it is plain numbers, stepped by the game.
 */
export const createCupFluid = (cells: number) => {
    const n = cells;
    const size = n * n;
    const center = (n - 1) / 2;
    const radius = n / 2 - 1.5;
    let u = new Float32Array(size);
    let v = new Float32Array(size);
    let u2 = new Float32Array(size);
    let v2 = new Float32Array(size);
    let foam = new Float32Array(size);
    let foam2 = new Float32Array(size);
    const foamBack = new Float32Array(size);
    const pressure = new Float32Array(size);
    const divergence = new Float32Array(size);
    const curl = new Float32Array(size);
    const wall = new Uint8Array(size);

    for (let y = 0; y < n; y++) {
        for (let x = 0; x < n; x++) {
            wall[y * n + x] = Math.hypot(x - center, y - center) > radius ? 1 : 0;
        }
    }

    const sample = (field: Float32Array, x: number, y: number) => {
        x = Math.min(Math.max(x, 0), n - 1.001);
        y = Math.min(Math.max(y, 0), n - 1.001);

        const x0 = x | 0;
        const y0 = y | 0;
        const fx = x - x0;
        const fy = y - y0;
        const i = y0 * n + x0;
        const a = field[i] + (field[i + 1] - field[i]) * fx;
        const b = field[i + n] + (field[i + n + 1] - field[i + n]) * fx;

        return a + (b - a) * fy;
    };

    // In the wall the pressure copies the cell inside: the coffee does not go through it.
    const pressureLeft = (i: number) => (wall[i - 1] ? pressure[i] : pressure[i - 1]);
    const pressureRight = (i: number) => (wall[i + 1] ? pressure[i] : pressure[i + 1]);
    const pressureDown = (i: number) => (wall[i - n] ? pressure[i] : pressure[i - n]);
    const pressureUp = (i: number) => (wall[i + n] ? pressure[i] : pressure[i + n]);

    const enforceWalls = () => {
        for (let i = 0; i < size; i++) {
            if (wall[i]) {
                u[i] = 0;
                v[i] = 0;
            }
        }
    };

    // Takes out of the flow whatever would pile coffee up or leave a hole: what is left goes round.
    const project = () => {
        for (let y = 1; y < n - 1; y++) {
            for (let x = 1; x < n - 1; x++) {
                const i = y * n + x;

                divergence[i] = wall[i] ? 0 : (u[i + 1] - u[i - 1] + v[i + n] - v[i - n]) * 0.5;
            }
        }

        for (let k = 0; k < 26; k++) {
            for (let y = 1; y < n - 1; y++) {
                for (let x = 1; x < n - 1; x++) {
                    const i = y * n + x;

                    if (!wall[i]) {
                        pressure[i] = (pressureLeft(i) + pressureRight(i) + pressureDown(i) + pressureUp(i) - divergence[i]) * 0.25;
                    }
                }
            }
        }

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

                if (!wall[i]) {
                    u[i] -= (pressureRight(i) - pressureLeft(i)) * 0.5;
                    v[i] -= (pressureUp(i) - pressureDown(i)) * 0.5;
                }
            }
        }
    };

    const advect = (out: Float32Array, field: Float32Array, dt: number) => {
        for (let y = 0; y < n; y++) {
            for (let x = 0; x < n; x++) {
                const i = y * n + x;

                out[i] = wall[i] ? field[i] : sample(field, x - u[i] * dt, y - v[i] * dt);
            }
        }
    };

    const fluid = {
        /**
         * Pours fresh latte art: 0 a heart, 1 a tulip, 2 plain foam. In all of them the pale crema
         * covers the cup and the darker coffee shows towards the rim. The coffee comes to a stop.
         */
        paint(pattern: number) {
            for (let y = 0; y < n; y++) {
                for (let x = 0; x < n; x++) {
                    const px = (x - center) / radius;
                    const py = (y - center) / radius;
                    const r = Math.hypot(px, py);
                    let f = 0.42 - Math.max(0, r - 0.78) * 1.2;

                    if (pattern === 0) {
                        // A heart: (x² + y² - 1)³ - x²·y³ < 0, its point towards the camera.
                        const hx = px / 0.55;
                        const hy = -(py - 0.05) / 0.55;
                        const k = hx * hx + hy * hy - 1;

                        if (k * k * k - hx * hx * hy * hy * hy < 0) {
                            f = 1;
                        }
                    } else if (pattern === 1) {
                        for (let k = 0; k < 3; k++) {
                            const cy = -0.38 + k * 0.33;
                            const rr = 0.36 - k * 0.07;

                            if (Math.hypot(px / 1.05, (py - cy) / 0.8) < rr) {
                                f = 1;
                            }
                        }

                        // The line the jug draws through the drops.
                        if (Math.abs(px) < 0.03 && py > -0.6 && py < 0.55) {
                            f = 0.5;
                        }
                    } else if (r < 0.93) {
                        f = 0.95;
                    }

                    foam[y * n + x] = wall[y * n + x] ? 0 : Math.max(0, Math.min(1, f));
                }
            }

            u.fill(0);
            v.fill(0);
            pressure.fill(0);
        },

        /**
         * One step of `dt` seconds, with the spoon where `spoon` says.
         */
        step(dt: number, spoon: TSpoonInCells) {
            // The spoon: the coffee under it goes at its speed.
            if (spoon.inside > 0) {
                const r = spoon.radius;

                for (let y = Math.max(1, Math.floor(spoon.y - r)); y <= Math.min(n - 2, Math.ceil(spoon.y + r)); y++) {
                    for (let x = Math.max(1, Math.floor(spoon.x - r)); x <= Math.min(n - 2, Math.ceil(spoon.x + r)); x++) {
                        const i = y * n + x;
                        const d = Math.hypot(x - spoon.x, y - spoon.y) / r;

                        if (d < 1 && !wall[i]) {
                            const w = (1 - d * d) * spoon.inside;

                            u[i] += (spoon.vx - u[i]) * w;
                            v[i] += (spoon.vy - v[i]) * w;
                        }
                    }
                }
            }

            // Vorticity confinement: gives the swirls back what the grid takes from them.
            for (let y = 1; y < n - 1; y++) {
                for (let x = 1; x < n - 1; x++) {
                    const i = y * n + x;

                    curl[i] = (v[i + 1] - v[i - 1] - (u[i + n] - u[i - n])) * 0.5;
                }
            }

            for (let y = 2; y < n - 2; y++) {
                for (let x = 2; x < n - 2; x++) {
                    const i = y * n + x;

                    if (!wall[i]) {
                        const gx = (Math.abs(curl[i + 1]) - Math.abs(curl[i - 1])) * 0.5;
                        const gy = (Math.abs(curl[i + n]) - Math.abs(curl[i - n])) * 0.5;
                        const len = Math.hypot(gx, gy) + 1e-5;

                        u[i] += 4 * (gy / len) * curl[i] * dt;
                        v[i] -= 4 * (gx / len) * curl[i] * dt;
                    }
                }
            }

            // The flow carries itself and slows down slowly: the coffee keeps turning after you let go.
            const keep = Math.exp(-0.22 * dt);

            for (let y = 0; y < n; y++) {
                for (let x = 0; x < n; x++) {
                    const i = y * n + x;
                    const bx = x - u[i] * dt;
                    const by = y - v[i] * dt;

                    u2[i] = sample(u, bx, by) * keep;
                    v2[i] = sample(v, bx, by) * keep;
                }
            }

            [u, u2] = [u2, u];
            [v, v2] = [v2, v];
            enforceWalls();
            project();
            enforceWalls();

            // The foam with MacCormack: forward, back, and half the error corrected. Kept between the
            // four cells it came from, so the correction does not make values up.
            advect(foam2, foam, dt);
            advect(foamBack, foam2, -dt);

            for (let y = 0; y < n; y++) {
                for (let x = 0; x < n; x++) {
                    const i = y * n + x;

                    if (wall[i]) {
                        continue;
                    }

                    const bx = Math.min(Math.max(x - u[i] * dt, 0), n - 1.001);
                    const by = Math.min(Math.max(y - v[i] * dt, 0), n - 1.001);
                    const j = (by | 0) * n + (bx | 0);
                    const lo = Math.min(foam[j], foam[j + 1], foam[j + n], foam[j + n + 1]);
                    const hi = Math.max(foam[j], foam[j + 1], foam[j + n], foam[j + n + 1]);
                    const corrected = foam2[i] + (foam[i] - foamBack[i]) * 0.5;

                    foam2[i] = Math.min(hi, Math.max(lo, corrected));
                }
            }

            [foam, foam2] = [foam2, foam];
        },

        /**
         * Writes the fluid into a picture of `cells` by `cells`: red the foam, green and blue the
         * flow along x and y (128 still).
         */
        paintMap(data: Uint8ClampedArray | Uint8Array) {
            for (let i = 0; i < size; i++) {
                const o = i * 4;

                data[o] = Math.round(foam[i] * 255);
                data[o + 1] = Math.max(0, Math.min(255, Math.round(128 + u[i] * 2)));
                data[o + 2] = Math.max(0, Math.min(255, Math.round(128 + v[i] * 2)));
                data[o + 3] = 255;
            }
        },

        /**
         * The surface's height, read from the pressure onto a coarser grid of `m` by `m` (the mesh's).
         * In a liquid going round, the pressure is higher against the wall and lower in the middle,
         * which is just what makes the middle sink and the coffee climb the porcelain; in front of the
         * spoon it rises too, and behind it it drops. Centred on zero, so the coffee neither gains nor
         * loses any.
         */
        heights(out: Float32Array, m: number) {
            let sum = 0;

            for (let j = 0; j < m; j++) {
                for (let i = 0; i < m; i++) {
                    const x = Math.min(n - 1, Math.max(0, Math.round((i / (m - 1)) * (n - 1))));
                    const y = Math.min(n - 1, Math.max(0, Math.round((j / (m - 1)) * (n - 1))));
                    let k = y * n + x;

                    // In the wall, the nearest cell inside, towards the middle.
                    if (wall[k]) {
                        const dx = x - center;
                        const dy = y - center;
                        const d = Math.hypot(dx, dy) || 1;

                        k = Math.round(center + (dy / d) * (radius - 1)) * n + Math.round(center + (dx / d) * (radius - 1));
                    }

                    const h = pressure[k] + foam[k] * 0.6;

                    out[j * m + i] = h;
                    sum += h;
                }
            }

            const mean = sum / (m * m);

            for (let i = 0; i < m * m; i++) {
                out[i] -= mean;
            }
        }
    };

    fluid.paint(0);

    return fluid;
};
```
