# 3D diorama

> A small world on a walnut stand, made only in code: a river with a bridge, a cottage with smoke, trees and grass in the wind, fairy lights, day and night, and weather.

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

A small world on a walnut stand, made only in code: a river with a bridge, a cottage with smoke from its chimney, trees and grass bending in gusts of wind, fairy lights, day and night, rain, snow and fog, and a tilt-shift look that makes it all seem a model on a table.

The water, the wind and the snow settling on everything are shader-composer materials, and the textures are painted with the engine's pixel functions. **Drag** to turn it and the **wheel** to zoom; **N** for night and **W** to change the weather.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { Diorama } from './scenes/diorama';
import { ACTIONS, BACKDROP, HEIGHT, WIDTH } from './settings';

// A procedural diorama: a river with a bridge, a cottage, trees, grass in the wind, fairy lights and
// weather, on a walnut stand. Every shape, texture and drop is made in code: no art files.
//
//   drag            turn it
//   wheel           zoom
//   N               day / night (or the button)
//   W               weather: clear, rain, snow, fog (or the button)
const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    background: BACKDROP.day,
    smooth: true,
    msaa: 4,
    scaling: 'contain',
    step: 60,
    actions: ACTIONS
});

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

`art/textures.ts`:

```ts
import { createPixels, createPixelTexture, drawText, fillNoise, type TPixels } from 'nacatamalon/pixels';
import { fbm2, hex, mixRgb, noise2, rand, type TRgb } from '../geometry/noise';

/**
 * Every texture here is painted in code with `nacatamalon/pixels`: no image files.
 */

const put = (p: TPixels, x: number, y: number, c: TRgb, a = 1): void => {
    const i = (y * p.width + x) * 4;

    p.data[i] = Math.max(0, Math.min(255, c[0] * 255));
    p.data[i + 1] = Math.max(0, Math.min(255, c[1] * 255));
    p.data[i + 2] = Math.max(0, Math.min(255, c[2] * 255));
    p.data[i + 3] = a * 255;
};

const paint = (w: number, h: number, colourAt: (x: number, y: number) => TRgb): TPixels => {
    const p = createPixels(w, h);

    for (let y = 0; y < h; y++) {
        for (let x = 0; x < w; x++) {
            put(p, x, y, colourAt(x, y));
        }
    }

    return p;
};

const texture = (p: TPixels, key: string) => createPixelTexture(p, () => {}, {
    key
});

/**
 * Fine grey noise, laid over the ground and the rocks so they are not flat colour up close.
 */
export const detailTexture = () => texture(fillNoise(createPixels(128, 128), {
    seed: 4,
    scale: 10,
    octaves: 4,
    from: '#b4b4b4',
    to: '#ffffff'
}), 'detail');

/**
 * Wood grain that repeats with no seam across.
 */
export const woodTexture = (dark: string, light: string, key: string) => {
    const a = hex(dark);
    const b = hex(light);

    return texture(paint(256, 128, (x, y) => {
        const u = x / 256;
        const warp = (fbm2(Math.cos(u * Math.PI * 2) * 1.2 + 9, Math.sin(u * Math.PI * 2) * 1.2 + y * 0.03, 4) - 0.5) * 7;
        const ring = 0.5 + 0.5 * Math.sin(y * 0.9 + warp);
        const fine = noise2(x * 0.5, y * 1.4);
        const fleck = noise2(x * 0.08, y * 0.5);

        return mixRgb(a, b, Math.pow(ring, 3) * 0.45 + fine * 0.3 + fleck * 0.25);
    }), key);
};

/**
 * Stonework: courses of stones of uneven length, with mortar between.
 */
export const stoneTexture = () => {
    const w = 128;
    const h = 128;
    const rows = 6;
    const p = createPixels(w, h);
    const rowH = h / rows;
    const mortar = hex('#4a443c');

    for (let r = 0; r < rows; r++) {
        let x = -Math.floor(rand() * 20);
        const cuts: number[] = [];

        while (x < w) {
            cuts.push(x);
            x += 14 + Math.floor(rand() * 18);
        }

        cuts.push(w + 8);

        const tones = cuts.map(() => mixRgb(hex('#8d8478'), hex('#b8ad9b'), rand()));

        for (let yy = 0; yy < rowH; yy++) {
            const y = Math.floor(r * rowH + yy);

            for (let xx = 0; xx < w; xx++) {
                let k = 0;

                while (k + 1 < cuts.length && xx >= cuts[k + 1]) {
                    k++;
                }

                const edgeX = Math.min(xx - cuts[k], cuts[k + 1] - xx);
                const edgeY = Math.min(yy, rowH - 1 - yy);
                const n = fbm2(xx * 0.15, y * 0.15, 3);

                if (edgeX < 1.5 || edgeY < 1.2) {
                    put(p, xx, y, mixRgb(mortar, [0.2, 0.18, 0.16], n * 0.5));
                } else {
                    const bevel = Math.min(1, Math.min(edgeX, edgeY) / 4);

                    put(p, xx, y, mixRgb(tones[k], [0.25, 0.23, 0.2], (1 - bevel) * 0.45 + (0.5 - n) * 0.35));
                }
            }
        }
    }

    return texture(p, 'stone');
};

/**
 * Lime plaster, with soft damp stains low down.
 */
export const plasterTexture = () => texture(paint(128, 128, (x, y) => {
    const n = fbm2(x * 0.06, y * 0.06, 5);
    const grit = noise2(x * 1.1, y * 1.1);
    const stain = Math.max(0, (y / 128) - 0.6) * 0.4 * fbm2(x * 0.1, 3, 3);

    return mixRgb(mixRgb(hex('#ece2cc'), hex('#cdbf9f'), n * 0.7 + grit * 0.15), hex('#8f8466'), stain);
}), 'plaster');

/**
 * Old roof tiles in staggered rows, with moss.
 */
export const shingleTexture = () => {
    const w = 128;
    const h = 128;
    const rows = 8;
    const cols = 8;
    const rowH = h / rows;
    const colW = w / cols;
    const tones: TRgb[][] = [];

    for (let r = 0; r < rows; r++) {
        tones.push([]);

        for (let c = 0; c < cols + 1; c++) {
            tones[r].push(mixRgb(hex('#8a3b26'), hex('#b4593a'), rand()));
        }
    }

    return texture(paint(w, h, (x, y) => {
        const r = Math.floor(y / rowH);
        const offset = r % 2 === 0 ? 0 : colW / 2;
        const c = Math.floor(((x + offset) % w) / colW);
        const ly = (y % rowH) / rowH;
        const lx = (((x + offset) % w) % colW) / colW;
        const edge = Math.min(lx, 1 - lx);

        // The shadow under the tile above.
        let colour = mixRgb(tones[r][c], [0.12, 0.05, 0.03], Math.pow(ly, 3) * 0.75);

        if (edge < 0.06) {
            colour = mixRgb(colour, [0.1, 0.04, 0.02], 0.6);
        }

        const moss = Math.max(0, fbm2(x * 0.05, y * 0.05, 4) - 0.58) * 2.2;

        colour = mixRgb(colour, hex('#5d6b2e'), Math.min(0.7, moss));

        return mixRgb(colour, [0, 0, 0], noise2(x * 0.8, y * 0.8) * 0.12);
    }), 'roof');
};

/**
 * A soft round puff, for the smoke and the snowflakes.
 */
export const puffTexture = () => {
    const size = 32;
    const p = createPixels(size, size);

    for (let y = 0; y < size; y++) {
        for (let x = 0; x < size; x++) {
            const d = Math.hypot(x - size / 2 + 0.5, y - size / 2 + 0.5) / (size / 2);
            const n = 0.75 + 0.25 * noise2(x * 0.35, y * 0.35);

            put(p, x, y, [1, 1, 1], Math.max(0, 1 - d) ** 1.6 * n);
        }
    }

    return texture(p, 'puff');
};

/**
 * A point of light, for the fireflies and the fairy lights.
 */
export const glowTexture = () => {
    const size = 16;
    const p = createPixels(size, size);

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

            put(p, x, y, [1, 1, 1], Math.max(0, 1 - d) ** 2.5);
        }
    }

    return texture(p, 'glow');
};

/**
 * The brass plaque on the stand.
 */
export const plaqueTexture = () => {
    const w = 192;
    const h = 32;

    const p = paint(w, h, (x, y) => {
        const brushed = noise2(x * 0.08, y * 2.5) * 0.25;
        const edge = Math.min(x, w - 1 - x, y, h - 1 - y);
        const base = mixRgb(hex('#9c7a3c'), hex('#e3c27a'), 0.55 + brushed);

        return edge < 2 ? mixRgb(base, hex('#5a4320'), 0.6) : base;
    });

    drawText(p, 'NACATAMALON', w / 2, 7, {
        color: '#3b2a12',
        anchor: {
            x: 0.5,
            y: 0
        }
    });
    drawText(p, '3D DIORAMA', w / 2, 18, {
        color: '#4a3618',
        anchor: {
            x: 0.5,
            y: 0
        }
    });

    return texture(p, 'plaque');
};
```

`components/bridge.ts`:

```ts
import { createMaterial, createMesh } from 'nacatamalon';
import { woodTexture } from '../art/textures';
import { range } from '../geometry/noise';
import { block, emptyShape, merge, place, toGeometry } from '../geometry/shapes';
import { heightAt, riverZ } from '../geometry/terrain';
import { BRIDGE_X } from '../settings';

/**
 * The wooden footbridge over the river: planks laid along a gentle arch, the beams under them and a
 * rail on each side, all following the arch.
 */
export const Bridge = () => {
    const planks = emptyShape();
    const frame = emptyShape();
    const middle = riverZ(BRIDGE_X);
    const z0 = middle - 1.15;
    const z1 = middle + 1.15;
    const ends = Math.max(heightAt(BRIDGE_X, z0), heightAt(BRIDGE_X, z1)) + 0.03;
    const deckY = (z: number) => ends + 0.2 * (1 - ((2 * (z - z0)) / (z1 - z0) - 1) ** 2);
    const count = 13;

    for (let i = 0; i < count; i++) {
        const z = z0 + ((i + 0.5) / count) * (z1 - z0);
        const slope = (deckY(z + 0.01) - deckY(z - 0.01)) / 0.02;

        merge(planks, place(block(0.78 + range(-0.03, 0.03), 0.045, 0.15), {
            rx: -Math.atan(slope),
            ry: range(-0.03, 0.03),
            t: [BRIDGE_X + range(-0.02, 0.02), deckY(z), z]
        }));
    }

    // The beams and the rails, in short straight pieces along the arch.
    const steps = 8;

    for (let i = 0; i < steps; i++) {
        const za = z0 + (i / steps) * (z1 - z0);
        const zb = z0 + ((i + 1) / steps) * (z1 - z0);
        const ya = deckY(za);
        const yb = deckY(zb);
        const length = Math.hypot(zb - za, yb - ya);
        const tilt = -Math.atan2(yb - ya, zb - za);

        for (const sx of [-1, 1]) {
            merge(frame, place(block(0.07, 0.09, length + 0.02), {
                rx: tilt,
                t: [BRIDGE_X + sx * 0.3, (ya + yb) / 2 - 0.07, (za + zb) / 2]
            }));
            merge(frame, place(block(0.05, 0.05, length + 0.02), {
                rx: tilt,
                t: [BRIDGE_X + sx * 0.37, (ya + yb) / 2 + 0.36, (za + zb) / 2]
            }));
        }
    }

    // The posts: the ones at the ends go down into the ground.
    for (let i = 0; i <= 4; i++) {
        const z = z0 + (i / 4) * (z1 - z0);

        for (const sx of [-1, 1]) {
            const bottom = i === 0 || i === 4 ? heightAt(BRIDGE_X + sx * 0.37, z) - 0.05 : deckY(z) - 0.05;
            const top = deckY(z) + 0.41;

            merge(frame, place(block(0.065, top - bottom, 0.065), {
                t: [BRIDGE_X + sx * 0.37, (top + bottom) / 2, z]
            }));
        }
    }

    createMesh({
        geometry: toGeometry(planks, {
            uvs: 'box',
            uvScale: 1.6
        }),
        material: createMaterial({
            shader: 'mesh3d',
            name: 'planks',
            texture: woodTexture('#5b4630', '#94795a', 'planks'),
            wrap: 'repeat',
            smooth: true
        })
    });
    createMesh({
        geometry: toGeometry(frame, {
            uvs: 'box',
            uvScale: 1.6
        }),
        material: createMaterial({
            shader: 'mesh3d',
            name: 'timber',
            texture: woodTexture('#2e2116', '#5a4330', 'timber'),
            wrap: 'repeat',
            smooth: true
        })
    });
};
```

`components/controls.ts`:

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

/**
 * Two buttons at the bottom right, one for day and night and one for the weather, and the same with
 * N and W. Each says what it is now.
 */
export const Controls = ({ sky }: { sky: TSky; }) => {
    const button = (right: number, width: number, onClick: () => void) => {
        const sprite = createSprite({
            width,
            height: 34,
            tint: '#2b241d',
            anchor: {
                x: 1,
                y: 1
            },
            zIndex: 100,
            transform: {
                x: WIDTH - right,
                y: HEIGHT - 16
            }
        });

        const label = createText({
            text: '',
            tint: '#f1e4c9',
            style: {
                fontSize: 16
            },
            anchor: {
                x: 0.5,
                y: 0.5
            },
            zIndex: 101,
            transform: {
                x: WIDTH - right - width / 2,
                y: HEIGHT - 33
            }
        });

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

        return label;
    };

    // The weather's is wider: GROUND MIST is its longest name.
    const weatherLabel = button(16, 260, () => sky.nextWeather());
    const nightLabel = button(292, 190, () => sky.toggleNight());

    createText({
        text: 'DRAG: TURN   WHEEL: ZOOM',
        tint: '#d9cdb8',
        style: {
            fontSize: 16
        },
        zIndex: 100,
        transform: {
            x: 16,
            y: HEIGHT - 42
        }
    });

    const night = useAction('night');
    const weather = useAction('weather');

    useUpdate(() => {
        if (night.justPressed()) {
            sky.toggleNight();
        }

        if (weather.justPressed()) {
            sky.nextWeather();
        }

        nightLabel.text = `[N] ${sky.isNight() ? 'NIGHT' : 'DAY'}`;
        weatherLabel.text = `[W] ${sky.weather()}`;
    });
};
```

`components/cottage.ts`:

```ts
import { createMaterial, createMesh, createParticles3d, getColor, lerpColor, useLatheGeometry, usePointLight, useUpdate } from 'nacatamalon';
import { plasterTexture, puffTexture, shingleTexture, stoneTexture, woodTexture } from '../art/textures';
import { mix, rand } from '../geometry/noise';
import { block, emptyShape, merge, place, toGeometry, type TPlace, type TShape } from '../geometry/shapes';
import { fromCottage } from '../geometry/terrain';
import { snowShader } from '../shaders/snow';
import { COTTAGE } from '../settings';
import type { TSky } from './sky';

/**
 * The cottage: a stone footing, plastered walls in a timber frame, a tiled roof, windows that glow
 * at night, a door, a chimney that smokes, firewood and two barrels. It is built in its own frame
 * (x along the front, z out of the door) and then turned and moved into place.
 */
export const Cottage = ({ sky }: { sky: TSky; }) => {
    const parts = {
        stone: emptyShape(),
        plaster: emptyShape(),
        timber: emptyShape(),
        roof: emptyShape(),
        glass: emptyShape(),
        planks: emptyShape()
    };

    // Puts a part in the cottage's frame, then the cottage where it stands.
    const toWorld = (g: TShape, o: TPlace = {
    }) => place(place(g, o), {
        ry: COTTAGE.turn,
        t: [COTTAGE.x, COTTAGE.pad, COTTAGE.z]
    });

    const add = (part: keyof typeof parts, g: TShape, o: TPlace = {
    }) => merge(parts[part], toWorld(g, o));

    const WX = 2.3;
    const WZ = 1.6;
    const FOOT = 0.24;
    const WALL = 1.12;
    const top = FOOT + WALL;

    add('stone', block(WX + 0.12, FOOT, WZ + 0.12), {
        t: [0, FOOT / 2 - 0.02, 0]
    });
    add('plaster', block(WX, WALL, WZ), {
        t: [0, FOOT + WALL / 2, 0]
    });

    // The gable ends: a triangle on each side.
    const gable = (sx: number) => {
        const g = emptyShape();
        const x = sx * WX / 2;

        g.positions.push(x, top, -WZ / 2, x, top, WZ / 2, x, top + 0.86, 0);
        g.colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
        g.normals = [sx, 0, 0, sx, 0, 0, sx, 0, 0];
        g.indices.push(...(sx > 0 ? [1, 0, 2] : [0, 1, 2]));

        return g;
    };

    add('plaster', gable(1));
    add('plaster', gable(-1));

    // The roof: two slopes, and the ridge beam.
    const ridgeY = top + 0.86;
    const eave = 1.07;
    const eaveY = top - 0.86 * (eave - WZ / 2) / (WZ / 2);
    const slope = Math.hypot(eave, ridgeY - eaveY);
    const pitch = Math.atan2(ridgeY - eaveY, eave);

    for (const s of [1, -1]) {
        add('roof', block(WX + 0.5, 0.09, slope + 0.04), {
            rx: s * pitch,
            t: [0, (ridgeY + eaveY) / 2 + 0.05, s * eave / 2]
        });
    }

    add('timber', block(WX + 0.56, 0.08, 0.12), {
        t: [0, ridgeY + 0.07, 0]
    });

    // The timber frame.
    const beam = (w: number, h: number, d: number, o: TPlace) => add('timber', block(w, h, d), o);

    for (const sx of [-1, 1]) {
        for (const sz of [-1, 1]) {
            beam(0.12, WALL, 0.12, {
                t: [sx * (WX / 2 - 0.02), FOOT + WALL / 2, sz * (WZ / 2 - 0.02)]
            });
        }
    }

    for (const sz of [-1, 1]) {
        beam(WX + 0.04, 0.1, 0.06, {
            t: [0, top - 0.05, sz * (WZ / 2 + 0.02)]
        });
        beam(WX + 0.04, 0.08, 0.06, {
            t: [0, FOOT + 0.05, sz * (WZ / 2 + 0.02)]
        });
        beam(0.09, WALL, 0.05, {
            t: [-0.32, FOOT + WALL / 2, sz * (WZ / 2 + 0.02)]
        });
    }

    for (const sx of [-1, 1]) {
        const brace = Math.hypot(WZ / 2, 0.8);

        beam(0.06, 0.1, WZ + 0.04, {
            t: [sx * (WX / 2 + 0.02), top - 0.05, 0]
        });
        beam(0.05, 0.08, brace, {
            t: [sx * (WX / 2 + 0.025), top + 0.3, -WZ / 4],
            rx: -Math.atan2(0.75, WZ / 2)
        });
        beam(0.05, 0.08, brace, {
            t: [sx * (WX / 2 + 0.025), top + 0.3, WZ / 4],
            rx: Math.atan2(0.75, WZ / 2)
        });
        beam(0.05, Math.hypot(0.55, 0.5), 0.08, {
            t: [sx * (WX / 2 + 0.025), FOOT + 0.3, 0.42],
            rx: 0.83
        });
    }

    // The windows: a wooden frame, glass that glows, a cross. Each remembers where its light falls.
    const windows: { x: number; y: number; z: number; }[] = [];

    const addWindow = (x: number, y: number, z: number, ry: number, w = 0.4, h = 0.48) => {
        add('glass', block(w, h, 0.03), {
            ry,
            t: [x, y, z]
        });

        const frame = (fw: number, fh: number, ox: number, oy: number) => add('timber', block(fw, fh, 0.07), {
            ry,
            t: [x + Math.cos(ry) * ox, y + oy, z - Math.sin(ry) * ox]
        });

        frame(w + 0.1, 0.06, 0, h / 2 + 0.02);
        frame(w + 0.16, 0.07, 0, -h / 2 - 0.03);
        frame(0.06, h + 0.06, -w / 2 - 0.02, 0);
        frame(0.06, h + 0.06, w / 2 + 0.02, 0);
        frame(0.03, h, 0, 0);
        frame(w, 0.03, 0, 0);

        const out = toWorld({
            positions: [x + Math.sin(ry) * 0.5, y, z + Math.cos(ry) * 0.5],
            indices: [],
            colors: []
        });

        windows.push({
            x: out.positions[0],
            y: out.positions[1],
            z: out.positions[2]
        });
    };

    const sill = FOOT + 0.6;

    addWindow(-0.72, sill, WZ / 2 + 0.01, 0);
    addWindow(0.72, sill, WZ / 2 + 0.01, 0);
    addWindow(0.3, sill, -WZ / 2 - 0.01, Math.PI);
    addWindow(WX / 2 + 0.01, sill, 0, Math.PI / 2, 0.36);
    addWindow(-WX / 2 - 0.01, sill, 0.25, -Math.PI / 2, 0.36);

    // The door, its lintel and the step.
    add('planks', block(0.44, 0.78, 0.05), {
        t: [0, FOOT + 0.39, WZ / 2 + 0.025]
    });
    add('timber', block(0.56, 0.07, 0.07), {
        t: [0, FOOT + 0.81, WZ / 2 + 0.035]
    });
    add('stone', block(0.7, 0.1, 0.35), {
        t: [0, 0.05, WZ / 2 + 0.2]
    });

    // The chimney.
    add('stone', block(0.32, 1.25, 0.32), {
        t: [0.72, top + 0.4, -0.38]
    });
    add('stone', block(0.38, 0.06, 0.38), {
        t: [0.72, top + 1.03, -0.38]
    });

    const chimney = toWorld({
        positions: [0.72, top + 1.1, -0.38],
        indices: [],
        colors: []
    }).positions;

    // Firewood stacked by the side wall.
    for (let i = 0; i < 9; i++) {
        const row = Math.floor(i / 4);

        add('timber', block(0.09, 0.09, 0.45), {
            t: [-WX / 2 - 0.15 - (i % 4) * 0.1 + row * 0.05, 0.05 + row * 0.085, -0.25],
            rz: 0.785
        });
    }

    const timber = createMaterial({
        shader: 'mesh3d',
        name: 'timber',
        texture: woodTexture('#2e2116', '#5a4330', 'timber'),
        wrap: 'repeat',
        smooth: true
    });

    const planks = createMaterial({
        shader: 'mesh3d',
        name: 'planks',
        texture: woodTexture('#5b4630', '#94795a', 'planks'),
        wrap: 'repeat',
        smooth: true
    });

    const roof = createMaterial({
        ...snowShader(),
        name: 'roof',
        texture: shingleTexture(),
        tint: '#e2d2c8',
        wrap: 'repeat',
        smooth: true,
        shininess: 40
    });

    const glass = createMaterial({
        shader: 'mesh3d',
        name: 'window',
        tint: '#3a2a18',
        emissive: '#ffb45e',
        specular: '#ffffff',
        shininess: 90
    });

    createMesh({
        geometry: toGeometry(parts.stone, {
            uvs: 'box',
            uvScale: 1.6
        }),
        material: createMaterial({
            shader: 'mesh3d',
            name: 'stone',
            texture: stoneTexture(),
            wrap: 'repeat',
            smooth: true
        })
    });
    createMesh({
        geometry: toGeometry(parts.plaster, {
            uvs: 'box',
            uvScale: 0.8
        }),
        material: createMaterial({
            shader: 'mesh3d',
            name: 'plaster',
            texture: plasterTexture(),
            wrap: 'repeat',
            smooth: true
        })
    });
    createMesh({
        geometry: toGeometry(parts.timber, {
            uvs: 'box',
            uvScale: 1.2
        }),
        material: timber
    });
    createMesh({
        geometry: toGeometry(parts.roof, {
            uvs: 'box',
            uvScale: 1.5
        }),
        material: roof
    });
    createMesh({
        geometry: toGeometry(parts.planks, {
            uvs: 'box',
            uvScale: 1.4
        }),
        material: planks
    });
    createMesh({
        geometry: toGeometry(parts.glass),
        material: glass,
        castShadow: false
    });

    // Two barrels by the other side wall.
    const barrel = useLatheGeometry({
        profile: [
            {
                x: 0,
                y: 0
            },
            {
                x: 0.13,
                y: 0
            },
            {
                x: 0.13,
                y: 0
            },
            {
                x: 0.155,
                y: 0.12
            },
            {
                x: 0.16,
                y: 0.19
            },
            {
                x: 0.155,
                y: 0.26
            },
            {
                x: 0.13,
                y: 0.38
            },
            {
                x: 0.13,
                y: 0.38
            },
            {
                x: 0,
                y: 0.37
            }
        ],
        segments: 20
    });

    for (const [lx, lz] of [[1.42, 0.55], [1.48, 0.15]]) {
        const at = fromCottage(lx, lz);

        createMesh({
            geometry: barrel,
            material: planks,
            transform: {
                x: at.x,
                y: COTTAGE.pad,
                z: at.z,
                rotationY: rand() * 6
            }
        });
    }

    // Warm light from the windows at night: one for the front, one for the side.
    const front = usePointLight({
        color: '#ff9a48',
        intensity: 0,
        range: 2.4,
        ambient: 0,
        transform: {
            x: (windows[0].x + windows[1].x) / 2,
            y: windows[0].y - 0.2,
            z: (windows[0].z + windows[1].z) / 2
        }
    });

    const side = usePointLight({
        color: '#ff9a48',
        intensity: 0,
        range: 1.8,
        ambient: 0,
        transform: {
            x: windows[3].x,
            y: windows[3].y - 0.2,
            z: windows[3].z
        }
    });

    const smoke = createParticles3d({
        effect: {
            kind: 'particles-3d',
            texture: puffTexture(),
            max: 90,
            blend: 'alpha',
            emission: {
                rate: 9
            },
            shape: {
                kind: 'sphere',
                radius: 0.05,
                edge: false
            },
            direction: {
                x: 0,
                y: 1,
                z: 0
            },
            spread: 0.35,
            life: [3.5, 5.5],
            speed: [0.22, 0.34],
            size: [0.14, 0.22],
            spin: [-0.4, 0.4],
            gravity: {
                x: 0.07,
                y: 0.015,
                z: 0.03
            },
            damping: 0.12,
            colorOverLife: [
                {
                    t: 0,
                    color: '#8a8580',
                    alpha: 0
                },
                {
                    t: 0.08,
                    color: '#9a948e',
                    alpha: 0.42
                },
                {
                    t: 0.6,
                    color: '#b9b3ac',
                    alpha: 0.2
                },
                {
                    t: 1,
                    color: '#d0cbc5',
                    alpha: 0
                }
            ],
            sizeOverLife: [
                {
                    t: 0,
                    scale: 0.6
                },
                {
                    t: 1,
                    scale: 3.4
                }
            ]
        },
        smooth: true,
        transform: {
            x: chimney[0],
            y: chimney[1],
            z: chimney[2]
        }
    });

    const glassDay = getColor('#6b4a28');
    const glassNight = getColor('#ffb860');

    useUpdate((_delta, time) => {
        const { night, rain, snowCover } = sky.state;
        const flicker = 0.92 + 0.08 * Math.sin(time * 13) * Math.sin(time * 7.3);
        const glow = lerpColor(glassDay, glassNight, night);
        const bright = mix(0.6, 2.4, night);

        roof.uniforms!.snow = snowCover;
        roof.specular.r = roof.specular.g = roof.specular.b = 0.35 * rain;
        glass.emissive.r = glow.r * bright;
        glass.emissive.g = glow.g * bright;
        glass.emissive.b = glow.b * bright;
        front.intensity = night * 1.8 * flicker;
        side.intensity = night * 1.0 * flicker;
        smoke.alpha = 1 - rain * 0.6;
    });
};
```

`components/fairy_light.ts`:

```ts
import { createMaterial, createMesh, createParticles3d, getColor, useIcoSphereGeometry, usePointLight, useTransform, useUpdate, type TTexture } from 'nacatamalon';
import { mix } from '../geometry/noise';
import { heightAt } from '../geometry/terrain';
import type { TSky } from './sky';

/**
 * Two digits of hex for a channel from 0 to 1.
 */
const toHex = (v: number) => Math.round(Math.min(1, v) * 255).toString(16).padStart(2, '0');

/**
 * A fairy light: a glowing bead with a halo that goes with it and a trail of sparks left behind,
 * wandering round its place in sums of sines, never into the ground. It glows brighter at night.
 */
export const FairyLight = ({ x, y, z, color, seed, sky, glow }: { x: number; y: number; z: number; color: string; seed: number; sky: TSky; glow: TTexture; }) => {
    const at = useTransform({
        x,
        y,
        z
    });

    const c = getColor(color);
    const solid = `#${toHex(c.r)}${toHex(c.g)}${toHex(c.b)}`;
    const soft = `#${toHex(0.6 + c.r * 0.4)}${toHex(0.6 + c.g * 0.4)}${toHex(0.6 + c.b * 0.4)}`;

    const bead = createMaterial({
        shader: 'mesh3d',
        name: 'fairy light',
        tint: color,
        emissive: color
    });

    createMesh({
        geometry: useIcoSphereGeometry({
            radius: 0.06,
            subdivisions: 2
        }),
        material: bead,
        castShadow: false
    });

    const light = usePointLight({
        color,
        intensity: 0.6,
        range: 1.6,
        ambient: 0
    });

    // The halo, in the light's own space so it goes with it.
    createParticles3d({
        effect: {
            kind: 'particles-3d',
            texture: glow,
            max: 12,
            blend: 'additive',
            worldSpace: false,
            emission: {
                rate: 9
            },
            shape: {
                kind: 'point'
            },
            life: [0.6, 0.9],
            speed: 0,
            size: [0.6, 0.75],
            colorOverLife: [
                {
                    t: 0,
                    color: solid,
                    alpha: 0
                },
                {
                    t: 0.4,
                    color: solid,
                    alpha: 0.4
                },
                {
                    t: 1,
                    color: solid,
                    alpha: 0
                }
            ]
        },
        smooth: true
    });

    // The sparks, in the world's space so they stay behind.
    createParticles3d({
        effect: {
            kind: 'particles-3d',
            texture: glow,
            max: 60,
            blend: 'additive',
            worldSpace: true,
            emission: {
                rate: 40
            },
            shape: {
                kind: 'sphere',
                radius: 0.04,
                edge: false
            },
            direction: {
                x: 0,
                y: -1,
                z: 0
            },
            spread: Math.PI,
            life: [0.7, 1.4],
            speed: [0.02, 0.1],
            size: [0.06, 0.11],
            gravity: {
                x: 0,
                y: -0.06,
                z: 0
            },
            colorOverLife: [
                {
                    t: 0,
                    color: soft,
                    alpha: 0.9
                },
                {
                    t: 0.3,
                    color: solid,
                    alpha: 0.8
                },
                {
                    t: 1,
                    color: solid,
                    alpha: 0
                }
            ],
            sizeOverLife: [
                {
                    t: 0,
                    scale: 1
                },
                {
                    t: 1,
                    scale: 0.2
                }
            ]
        },
        smooth: true
    });

    const radius = 0.55 + (seed % 3) * 0.2;

    useUpdate((_delta, time) => {
        const k = time * (0.45 + (seed % 4) * 0.07) + seed * 1.7;
        const night = sky.state.night;
        const pulse = 0.82 + 0.18 * Math.sin(time * 5.3 + seed * 2.1);
        const bright = mix(1.1, 1.9, night) * pulse;

        at.x = x + Math.sin(k) * radius + Math.sin(k * 2.3 + seed) * 0.18;
        at.z = z + Math.cos(k * 0.8) * radius + Math.cos(k * 1.9 + seed * 0.5) * 0.18;
        at.y = Math.max(heightAt(at.x, at.z) + 0.18, y + Math.sin(k * 1.6) * 0.2 + Math.sin(k * 4.1) * 0.05);
        light.intensity = mix(0.5, 1.5, night) * pulse;
        bead.emissive.r = c.r * bright;
        bead.emissive.g = c.g * bright;
        bead.emissive.b = c.b * bright;
    });
};
```

`components/fence.ts`:

```ts
import { createMaterial, createMesh, usePointLight, useUpdate } from 'nacatamalon';
import { woodTexture } from '../art/textures';
import { mix, range } from '../geometry/noise';
import { block, emptyShape, merge, place, toGeometry } from '../geometry/shapes';
import { heightAt } from '../geometry/terrain';
import { LAMP } from '../settings';
import type { TSky } from './sky';

/**
 * The fence round the yard behind the cottage, leaning posts and two rails that follow the ground,
 * and the lamp by the path, which lights up at night.
 */
export const Fence = ({ sky }: { sky: TSky; }) => {
    const fence = emptyShape();

    const line = [
        {
            x: 3.45,
            z: -0.95
        },
        {
            x: 4.75,
            z: -1.45
        },
        {
            x: 4.75,
            z: -4.75
        },
        {
            x: 3.4,
            z: -4.75
        }
    ];

    let previous: { x: number; y: number; z: number; } | null = null;

    for (let s = 0; s < line.length - 1; s++) {
        const a = line[s];
        const b = line[s + 1];
        const count = Math.ceil(Math.hypot(b.x - a.x, b.z - a.z) / 0.42);

        for (let i = s === 0 ? 0 : 1; i <= count; i++) {
            const x = a.x + ((b.x - a.x) * i) / count;
            const z = a.z + ((b.z - a.z) * i) / count;
            const y = heightAt(x, z);

            merge(fence, place(block(0.05, 0.42, 0.05), {
                rz: range(-0.06, 0.06),
                rx: range(-0.05, 0.05),
                t: [x, y + 0.17, z]
            }));

            if (previous) {
                const dx = x - previous.x;
                const dz = z - previous.z;
                const dy = y - previous.y;
                const length = Math.hypot(dx, dz);

                for (const height of [0.14, 0.3]) {
                    merge(fence, place(block(0.03, 0.035, length + 0.04), {
                        rx: -Math.atan2(dy, length),
                        ry: Math.atan2(dx, dz),
                        t: [(x + previous.x) / 2, (y + previous.y) / 2 + height, (z + previous.z) / 2]
                    }));
                }
            }

            previous = {
                x,
                y,
                z
            };
        }
    }

    // The lamp: a post with an arm, a little roof and a glass box.
    const { x, z } = LAMP;
    const y = heightAt(x, z);

    const pole = place(block(0.06, 1.0, 0.06), {
        t: [x, y + 0.5, z]
    });

    merge(pole, place(block(0.24, 0.04, 0.04), {
        t: [x + 0.1, y + 0.98, z]
    }));
    merge(pole, place(block(0.16, 0.03, 0.16), {
        t: [x + 0.2, y + 0.92, z]
    }));
    merge(pole, place(block(0.12, 0.02, 0.12), {
        t: [x + 0.2, y + 0.74, z]
    }));

    const timber = createMaterial({
        shader: 'mesh3d',
        name: 'timber',
        texture: woodTexture('#2e2116', '#5a4330', 'timber'),
        wrap: 'repeat',
        smooth: true
    });

    const lampGlass = createMaterial({
        shader: 'mesh3d',
        name: 'lamp',
        tint: '#ffe6b0',
        emissive: '#ffb050'
    });

    createMesh({
        geometry: toGeometry(fence, {
            uvs: 'box',
            uvScale: 2
        }),
        material: timber
    });
    createMesh({
        geometry: toGeometry(pole, {
            uvs: 'box',
            uvScale: 2
        }),
        material: timber
    });
    createMesh({
        geometry: toGeometry(place(block(0.1, 0.16, 0.1), {
            t: [x + 0.2, y + 0.83, z]
        })),
        material: lampGlass,
        castShadow: false
    });

    const light = usePointLight({
        color: '#ffae5a',
        intensity: 0,
        range: 3.4,
        ambient: 0,
        transform: {
            x: x + 0.2,
            y: y + 0.8,
            z
        }
    });

    useUpdate((_delta, time) => {
        const night = sky.state.night;
        const flicker = 0.92 + 0.08 * Math.sin(time * 13) * Math.sin(time * 7.3);

        light.intensity = night * 2.6 * flicker;
        lampGlass.emissive.r = mix(0.35, 3, night);
        lampGlass.emissive.g = mix(0.22, 2, night);
        lampGlass.emissive.b = mix(0.1, 0.8, night);
    });
};
```

`components/grass.ts`:

```ts
import { createMaterial, createMesh, useUpdate } from 'nacatamalon';
import {
    compileShader, composerAdd, composerCarry, composerLight, composerMul, composerSin, composerSurface, composerSwizzle, composerTime, composerUniform, composerUv,
    composerVec3, composerVertexPosition, composerX, composerY, composerZ
} from 'nacatamalon/shader';
import { fbm2, hex, mixRgb, mulRgb, rand, range, smoothstep, type TRgb } from '../geometry/noise';
import { emptyShape, toGeometry } from '../geometry/shapes';
import { groundColour, heightAt, pathDistance, riverZ, toCottage } from '../geometry/terrain';
import { snowyColor } from '../shaders/snow';
import { windAt } from '../shaders/wind';
import { BLOCK, BRIDGE_X, WIND } from '../settings';
import type { TSky } from './sky';

/**
 * The grass: sixteen thousand blades and a few flowers in one mesh, and reeds along the river. The
 * wind bends them in the vertex shader, in gusts that sweep across the field, and the bent grass
 * catches the light: the gust is carried from the vertex to the colour. It blows harder in the rain,
 * and snow settles on it.
 */
export const Grass = ({ sky }: { sky: TSky; }) => {
    const g = emptyShape();
    const normals: number[] = (g.normals = []);
    const uvs: number[] = (g.uvs = []);
    const tips = [hex('#8fae48'), hex('#a7bb58'), hex('#6f9a3a'), hex('#b8b864')];
    const flowers = [hex('#f4f1e6'), hex('#f2cf4a'), hex('#d9708f'), hex('#9a7fd6'), hex('#e8873a')];
    const half = BLOCK.half;

    // One blade: a triangle whose tip leans to one side. Its uv's y is 0 at the foot and 1 at the tip,
    // which is how the shader knows how much of it bends.
    const blade = (x: number, z: number, y: number, height: number, width: number, base: TRgb, tip: TRgb) => {
        const a = rand() * Math.PI * 2;
        const ca = Math.cos(a) * width;
        const sa = Math.sin(a) * width;
        const lean = range(-0.3, 0.3) * height;
        const lx = Math.cos(a + 1.57) * lean;
        const lz = Math.sin(a + 1.57) * lean;
        const b = g.positions.length / 3;

        g.positions.push(x - ca, y - 0.01, z - sa, x + ca, y - 0.01, z + sa, x + lx, y + height, z + lz);
        normals.push(0, 1, 0, 0, 1, 0, 0, 1, 0);
        uvs.push(0, 0, 1, 0, 0.5, 1);
        g.colors.push(base[0], base[1], base[2], 1, base[0], base[1], base[2], 1, tip[0], tip[1], tip[2], 1);
        g.indices.push(b, b + 1, b + 2);
    };

    // A flower: a diamond of colour at the top of a blade.
    const flower = (x: number, y: number, z: number, colour: TRgb) => {
        const s = 0.022;
        const b = g.positions.length / 3;

        g.positions.push(x - s, y, z, x, y, z + s, x + s, y, z, x, y, z - s, x, y + 0.006, z);

        for (let q = 0; q < 5; q++) {
            normals.push(0, 1, 0);
            uvs.push(0.5, 1);
            g.colors.push(colour[0], colour[1], colour[2], 1);
        }

        g.indices.push(b, b + 1, b + 4, b + 1, b + 2, b + 4, b + 2, b + 3, b + 4, b + 3, b, b + 4);
    };

    let placed = 0;

    for (let i = 0; i < 60000 && placed < 16000; i++) {
        const x = range(-half + 0.03, half - 0.03);
        const z = range(-half + 0.03, half - 0.03);
        const h = heightAt(x, z);
        const path = pathDistance(x, z);
        const { lx, lz } = toCottage(x, z);

        // Not in the water, on the path or under the cottage, and in patches.
        if (h < BLOCK.water + 0.04 || path < 0.2 || (Math.abs(lx) < 1.25 && Math.abs(lz) < 0.9)) {
            continue;
        }

        const density = smoothstep(0.35, 0.65, fbm2(x * 0.9 + 3, z * 0.9, 3)) * 0.8 + 0.2;

        if (rand() > density * smoothstep(0.2, 0.45, path)) {
            continue;
        }

        const nearWater = smoothstep(BLOCK.water + 0.3, BLOCK.water + 0.06, h);
        const ground = groundColour(x, z, h);
        const tip = mixRgb(mixRgb(tips[Math.floor(rand() * tips.length)], ground, 0.35), hex('#c8c070'), smoothstep(0.5, 1.2, h) * 0.4);
        const height = range(0.07, 0.17) * (1 + nearWater * 1.4);

        blade(x, z, h, height, range(0.012, 0.022), mulRgb(ground, 0.78), tip);
        placed++;

        if (rand() < 0.035 && nearWater < 0.2) {
            flower(x, h + height * 0.9, z, flowers[Math.floor(rand() * flowers.length)]);
        }
    }

    // Reeds and bulrushes at the water's edge.
    for (let i = 0; i < 4000; i++) {
        const x = range(-4.9, 4.9);
        const z = riverZ(x) + (rand() < 0.5 ? -1 : 1) * range(0.45, 0.8);
        const h = heightAt(x, z);

        if (h > BLOCK.water + 0.12 || h < BLOCK.water - 0.08 || Math.abs(x - BRIDGE_X) < 0.5 || fbm2(x * 1.2, z * 1.2, 2) < 0.48) {
            continue;
        }

        blade(x, z, Math.max(h, BLOCK.water - 0.02), range(0.3, 0.55), 0.012, hex('#2d3f1c'), hex('#7d8f45'));
    }

    // A sway that never stops, the gust that lays the grass down, and a fine flutter on top.
    const vertex = composerVertexPosition();
    const tip = composerY(composerUv());
    const tip2 = composerMul(tip, tip);
    const time = composerTime();
    const { gust, along } = windAt(vertex, time);
    const idle = composerMul(composerSin(composerAdd(composerMul(time, 2.1), composerMul(along, 1.3))), composerUniform('sway', 0.012));
    const flutter = composerMul(composerSin(composerAdd(composerMul(time, 9.0), composerAdd(composerMul(composerX(vertex), 17.0), composerMul(composerZ(vertex), 13.0)))), composerMul(gust, 0.008));
    const bend = composerMul(tip2, composerAdd(composerAdd(idle, composerMul(gust, composerUniform('gust', 0.085))), flutter));
    const position = composerAdd(vertex, composerVec3(composerMul(bend, WIND.x), composerMul(composerMul(tip2, gust), -0.035), composerMul(bend, WIND.z)));

    // Bent grass shines: the gust is handed on to the colour.
    const sheen = composerX(composerCarry());
    const lit = composerMul(composerSwizzle(composerSurface(), 'rgb'), composerLight());
    const colour = composerAdd(composerMul(lit, composerAdd(1, composerMul(sheen, 0.55))), composerMul(composerVec3(0.12, 0.11, 0.05), sheen));

    const material = createMaterial({
        ...compileShader({
            shader: 'mesh3d',
            position,
            carry: composerMul(gust, tip),
            color: snowyColor(colour)
        }),
        name: 'grass',
        cull: 'none'
    });

    createMesh({
        geometry: toGeometry(g),
        material,
        castShadow: false,
        boundsMargin: 0.1
    });

    useUpdate(() => {
        const { rain, snow, snowCover } = sky.state;

        material.uniforms!.snow = snowCover;

        // The rain brings a stronger wind.
        material.uniforms!.gust = 0.085 + rain * 0.07 + snow * 0.02;
        material.uniforms!.sway = 0.012 + rain * 0.01;
    });
};
```

`components/land.ts`:

```ts
import { createMaterial, createMesh, useUpdate } from 'nacatamalon';
import { detailTexture } from '../art/textures';
import { fbm2, mix, mixRgb, mulRgb, noise2, type TRgb } from '../geometry/noise';
import { emptyShape, grid, toGeometry } from '../geometry/shapes';
import { groundColour, heightAt, SOIL } from '../geometry/terrain';
import { snowShader } from '../shaders/snow';
import { BLOCK } from '../settings';
import type { TSky } from './sky';

/**
 * The block of land: its top, coloured point by point, and its four cut sides, layers of roots,
 * topsoil, clay and rock. Snow settles on it, and it shines when it is wet.
 */
export const Land = ({ sky }: { sky: TSky; }) => {
    const half = BLOCK.half;

    const ground = createMaterial({
        ...snowShader(),
        name: 'ground',
        texture: detailTexture(),
        wrap: 'repeat',
        smooth: true,
        shininess: 30
    });

    const top = grid(150, -half, half, (x, z) => {
        const y = heightAt(x, z);

        return {
            y,
            color: groundColour(x, z, y)
        };
    });

    createMesh({
        geometry: toGeometry(top, {
            uvs: 'planar',
            uvScale: 1.3
        }),
        material: ground
    });

    // The four sides, each a strip of columns from the top down to the bottom of the block.
    const sides: [number, number, number, number, [number, number, number]][] = [[-half, half, half, half, [0, 0, 1]], [half, half, half, -half, [1, 0, 0]], [half, -half, -half, -half, [0, 0, -1]], [-half, -half, -half, half, [-1, 0, 0]]];

    const soil = emptyShape();
    const normals: number[] = (soil.normals = []);
    const uvs: number[] = (soil.uvs = []);
    const columns = 150;

    for (const [x0, z0, x1, z1, n] of sides) {
        const cols: { x: number; z: number; ys: number[]; cs: TRgb[][]; }[] = [];

        for (let i = 0; i <= columns; i++) {
            const t = i / columns;
            const x = x0 + (x1 - x0) * t;
            const z = z0 + (z1 - z0) * t;
            const surface = heightAt(x, z);
            const w = fbm2(x * 0.9 + z * 0.9, 3.3, 3);
            const b1 = surface - 0.05;
            const b2 = Math.min(b1 - 0.03, surface - (0.24 + 0.1 * w));
            const b3 = Math.min(b2 - 0.04, -0.82 + 0.16 * (w - 0.5));
            const b4 = Math.min(b3 - 0.04, -1.18 + 0.12 * (fbm2(x * 1.7 + z * 1.7, 9, 3) - 0.5));
            const k = 0.85 + 0.3 * noise2((x + z) * 6, 1);
            const lip = surface < BLOCK.water + 0.05 ? SOIL.mud : groundColour(x, z, surface);

            cols.push({
                x,
                z,
                ys: [surface, b1, b2, b3, b4, BLOCK.bottom].map((y) => Math.max(BLOCK.bottom, y)),
                cs: [[lip, mulRgb(SOIL.roots, k)], [mulRgb(SOIL.roots, k), mulRgb(SOIL.topsoil, k)], [mulRgb(mixRgb(SOIL.clay, SOIL.sand, w), k), mulRgb(SOIL.clay, k * 0.9)], [mulRgb(SOIL.rock, k), mulRgb(SOIL.rock, k * 0.75)], [mulRgb(SOIL.rock, k * 0.8), mulRgb(SOIL.rock, k * 0.55)]]
            });
        }

        for (let layer = 0; layer < 5; layer++) {
            // The rock is tall: in a few rows, so its grain shows.
            const rows = layer >= 3 ? 3 : 1;

            for (let r = 0; r < rows; r++) {
                const base = soil.positions.length / 3;

                for (const c of cols) {
                    for (const e of [r / rows, (r + 1) / rows]) {
                        const y = mix(c.ys[layer], c.ys[layer + 1], e);
                        let colour = mixRgb(c.cs[layer][0], c.cs[layer][1], e);

                        if (layer >= 3) {
                            colour = mulRgb(colour, 0.82 + 0.36 * fbm2((c.x + c.z) * 2.2, y * 5, 3));
                        }

                        soil.positions.push(c.x, y, c.z);
                        normals.push(n[0], n[1], n[2]);
                        uvs.push((c.x + c.z) * 0.9, -y * 0.9);
                        soil.colors.push(colour[0], colour[1], colour[2], 1);
                    }
                }

                for (let i = 0; i < columns; i++) {
                    // a: top left, a + 1: bottom left; a + 2 and a + 3 the same on the right.
                    const a = base + i * 2;

                    soil.indices.push(a + 1, a + 3, a + 2, a + 1, a + 2, a);
                }
            }
        }
    }

    createMesh({
        geometry: toGeometry(soil),
        material: ground,
        castShadow: false
    });

    useUpdate(() => {
        ground.uniforms!.snow = sky.state.snowCover;

        // Wet ground shines.
        ground.specular.r = ground.specular.g = ground.specular.b = 0.28 * sky.state.rain;
    });
};
```

`components/look.ts`:

```ts
import { useUpdate } from 'nacatamalon';
import { bloom, colorAdjust, grain, tiltShift, usePostProcess } from 'nacatamalon/effects';
import { mix } from '../geometry/noise';
import { VIGNETTE_GLSL, VIGNETTE_WGSL } from '../shaders/vignette';
import type { TSky } from './sky';

/**
 * What makes it look like a photo of a model: a colour grade, a glow on what is bright, a narrow
 * band in focus (the rest blurred, as with a close lens), dark corners and a little film grain. At
 * night the glow spreads further and the colours go cooler; grey weather takes some colour out.
 */
export const Look = ({ sky }: { sky: TSky; }) => {
    const grade = usePostProcess(colorAdjust({
        contrast: 1.08,
        saturation: 1.12,
        gamma: 1.02,
        tint: [1.02, 0.99, 0.95]
    }));

    const glow = usePostProcess(bloom({
        threshold: 0.78,
        intensity: 0.55,
        radius: 10
    }));

    usePostProcess(tiltShift({
        focus: 0.56,
        band: 0.17,
        feather: 0.22,
        radius: 3.2
    }));

    usePostProcess({
        name: 'vignette',
        fragment: VIGNETTE_WGSL,
        fragmentGlsl: VIGNETTE_GLSL,
        uniforms: {
            amount: 0.55
        }
    });

    usePostProcess(grain({
        amount: 0.035,
        size: 1,
        animated: true
    }));

    useUpdate(() => {
        const { night, overcast } = sky.state;

        glow.uniforms.threshold = mix(0.78, 0.5, night);
        glow.uniforms.intensity = mix(0.55, 1.1, night);
        grade.uniforms.saturation = mix(1.12, 0.9, night) * (1 - overcast * 0.22);
    });
};
```

`components/mist.ts`:

```ts
import { createMaterial, createMesh, useUpdate } from 'nacatamalon';
import { mix, smoothstep } from '../geometry/noise';
import { emptyShape, toGeometry } from '../geometry/shapes';
import { heightAt } from '../geometry/terrain';
import { mistShader } from '../shaders/mist';
import { BLOCK } from '../settings';
import type { TSky } from './sky';

/**
 * How many sheets the mist is made of, and how many cells each sheet has across.
 */
const SHEETS = 12;
const CELLS = 72;

/**
 * Mist close to the ground: thin sheets stacked over the land, each following its rise and fall,
 * more of them low down. It pools in the low ground (the river, the hollow) and thins out on the
 * hill and towards the edges of the block. It comes with its own weather, and some of it with the
 * fog; it takes the sky's colour and goes cooler at night.
 */
export const Mist = ({ sky }: { sky: TSky; }) => {
    const half = BLOCK.half;

    const material = createMaterial({
        ...mistShader(),
        name: 'ground mist',
        transparent: true,
        cull: 'none'
    });

    const sheets = emptyShape();
    const normals: number[] = (sheets.normals = []);

    for (let k = 0; k < SHEETS; k++) {
        const layer = k / (SHEETS - 1);
        const lift = 0.03 + Math.pow(layer, 1.3) * 0.62;
        const thickness = 0.3 * Math.pow(1 - layer, 1.3) + 0.03;
        const base = sheets.positions.length / 3;

        for (let j = 0; j <= CELLS; j++) {
            for (let i = 0; i <= CELLS; i++) {
                const x = -half + (i / CELLS) * 2 * half;
                const z = -half + (j / CELLS) * 2 * half;
                const h = heightAt(x, z);
                const pool = mix(1.25, 0.3, smoothstep(-0.1, 1.1, h));
                const edge = smoothstep(half, half - 0.55, Math.max(Math.abs(x), Math.abs(z)));

                sheets.positions.push(x, Math.max(h, BLOCK.water) + lift, z);
                normals.push(0, 1, 0);
                sheets.colors.push(layer, 0, 0, thickness * pool * edge);
            }
        }

        for (let j = 0; j < CELLS; j++) {
            for (let i = 0; i < CELLS; i++) {
                const a = base + j * (CELLS + 1) + i;

                sheets.indices.push(a, a + CELLS + 1, a + 1, a + 1, a + CELLS + 1, a + CELLS + 2);
            }
        }
    }

    createMesh({
        geometry: toGeometry(sheets),
        material,
        castShadow: false,
        boundsMargin: 0.1
    });

    useUpdate(() => {
        const n = sky.state.night;

        material.uniforms!.mist = sky.state.mist;
        material.uniforms!.mistTint = [mix(0.88, 0.62, n), mix(0.9, 0.7, n), mix(0.95, 0.9, n)];
    });
};
```

`components/orbit.ts`:

```ts
import { cameraLookAt, useCamera3d, usePointer, useUpdate } from 'nacatamalon';
import { ORBIT } from '../settings';

/**
 * The camera, turning round the diorama: dragging turns it and tilts it, the wheel brings it nearer
 * or further. Left alone for a few seconds, it starts turning slowly by itself.
 */
export const Orbit = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 30,
        near: 0.1,
        far: 200
    });

    const pointer = usePointer();
    let yaw = ORBIT.yaw;
    let pitch = ORBIT.pitch;
    let distance = ORBIT.distance;

    // Starts turning by itself right away.
    let idle = ORBIT.idle * 2.5;

    pointer.onMove((info) => {
        if (pointer.isDown()) {
            yaw -= info.movementX * 0.006;
            pitch = Math.min(1.25, Math.max(0.12, pitch + info.movementY * 0.004));
            idle = 0;
        }
    });

    pointer.onWheel(({ deltaY }) => {
        distance = Math.min(ORBIT.far, Math.max(ORBIT.near, distance * Math.exp(deltaY * 0.001)));
        idle = 0;
    });

    useUpdate((delta) => {
        const { target } = ORBIT;

        idle += delta;

        // Eases into the turn rather than starting at full speed.
        if (idle > ORBIT.idle) {
            yaw += delta * 0.06 * Math.min(1, (idle - ORBIT.idle) / 2);
        }

        camera.transform.x = target.x + Math.sin(yaw) * Math.cos(pitch) * distance;
        camera.transform.y = target.y + Math.sin(pitch) * distance;
        camera.transform.z = target.z + Math.cos(yaw) * Math.cos(pitch) * distance;
        cameraLookAt(camera, target);
    });
};
```

`components/river.ts`:

```ts
import { createMaterial, createMesh, useUpdate } from 'nacatamalon';
import { mix } from '../geometry/noise';
import { emptyShape, grid, toGeometry } from '../geometry/shapes';
import { heightAt } from '../geometry/terrain';
import { riverShader } from '../shaders/river';
import { BLOCK } from '../settings';
import type { TSky } from './sky';

/**
 * The river: a plane of water over the whole block, which the ground hides wherever it is higher,
 * and the water seen side on where the river meets the block's left and right cuts. It runs faster
 * and the drops ring it in the rain, and it reflects a darker sky at night.
 */
export const River = ({ sky }: { sky: TSky; }) => {
    const half = BLOCK.half;

    const water = createMaterial({
        ...riverShader(),
        name: 'water',
        transparent: true,
        specular: '#fff1d0',
        shininess: 120
    });

    createMesh({
        geometry: toGeometry(grid(90, -half, half, () => ({
            y: BLOCK.water,
            color: [1, 1, 1]
        }))),
        material: water,
        castShadow: false,
        boundsMargin: 0.05
    });

    // The water side on: from its surface down to the bed, on the two cuts the river crosses.
    const side = emptyShape();
    const normals: number[] = (side.normals = []);
    const columns = 150;

    for (const sx of [1, -1]) {
        const x = sx * half;
        const base = side.positions.length / 3;

        for (let i = 0; i <= columns; i++) {
            const z = sx > 0 ? half - (i / columns) * 2 * half : -half + (i / columns) * 2 * half;
            const bottom = Math.max(BLOCK.bottom, Math.min(heightAt(x, z), BLOCK.water));

            side.positions.push(x, BLOCK.water - 0.004, z, x, bottom, z);
            normals.push(sx, 0, 0, sx, 0, 0);
            side.colors.push(1, 1, 1, 1, 0.55, 0.7, 0.75, 1);
        }

        for (let i = 0; i < columns; i++) {
            const a = base + i * 2;

            side.indices.push(a + 1, a + 3, a + 2, a + 1, a + 2, a);
        }
    }

    createMesh({
        geometry: toGeometry(side),
        material: createMaterial({
            shader: 'mesh3d',
            name: 'water side',
            tint: '#2f6f78',
            alpha: 0.62,
            emissive: '#06161a',
            specular: '#ffffff',
            shininess: 80
        }),
        castShadow: false
    });

    useUpdate(() => {
        const { night, rain, overcast } = sky.state;

        water.uniforms.rain = rain;
        water.uniforms.flow = 0.7 + rain * 0.5;
        water.uniforms.skyCol = [mix(0.62, 0.1, night), mix(0.72, 0.14, night), mix(0.82, 0.26, night)];
        water.uniforms.glint = mix(0.9, 0.15, night) * (1 - overcast * 0.8);
    });
};
```

`components/rocks.ts`:

```ts
import { createMaterial, createMesh, useUpdate } from 'nacatamalon';
import { detailTexture } from '../art/textures';
import { hex, mixRgb, rand, range } from '../geometry/noise';
import { emptyShape, merge, place, rock, toGeometry } from '../geometry/shapes';
import { heightAt, riverZ } from '../geometry/terrain';
import { snowShader } from '../shaders/snow';
import { BRIDGE_X } from '../settings';
import type { TSky } from './sky';

/**
 * The rocks, in one mesh: along the river's banks, on the hill, and a few stepping stones across the
 * water. Snow settles on them.
 */
export const Rocks = ({ sky }: { sky: TSky; }) => {
    const rocks = emptyShape();

    // `sink` is how much of it is buried.
    const put = (x: number, z: number, s: number, sink = 0.35) => {
        const y = heightAt(x, z);
        const shape = rock(s * range(0.9, 1.3), s * range(0.55, 0.85), s * range(0.8, 1.2), rand() * 50, mixRgb(hex('#7a756b'), hex('#9a9282'), rand()), hex('#57702c'));

        merge(rocks, place(shape, {
            ry: rand() * 6,
            rx: range(-0.15, 0.15),
            t: [x, y - s * sink * 0.5, z]
        }));
    };

    // Along the banks, but not under the bridge, up to 26 rocks.
    for (let i = 0; i < 120 && rocks.positions.length < 3 * 162 * 26; i++) {
        const x = range(-4.7, 4.7);
        const z = riverZ(x) + (rand() < 0.5 ? -1 : 1) * range(0.55, 0.95);

        if (Math.abs(x - BRIDGE_X) >= 0.7) {
            put(x, z, range(0.08, 0.2));
        }
    }

    for (const [x, z, s] of [[-3.0, -3.0, 0.32], [-3.8, -2.85, 0.22], [-2.2, -3.0, 0.18], [3.7, 3.6, 0.26], [3.95, 3.2, 0.14], [-4.4, -0.9, 0.2]]) {
        put(x, z, s);
    }

    for (let k = 0; k < 4; k++) {
        const x = 2.6 + k * 0.22;

        put(x, riverZ(x) - 0.45 + k * 0.32, 0.13, 0.1);
    }

    const material = createMaterial({
        ...snowShader(),
        name: 'rock',
        texture: detailTexture(),
        wrap: 'repeat',
        smooth: true,
        specular: '#2a2a2a',
        shininess: 18
    });

    createMesh({
        geometry: toGeometry(rocks, {
            flat: true,
            uvs: 'box',
            uvScale: 2
        }),
        material
    });

    useUpdate(() => {
        material.uniforms!.snow = sky.state.snowCover;
    });
};
```

`components/sky.ts`:

```ts
import { getColor, lerpColor, useAmbientLight, useDirectionalLight, useFog, useGame, useUpdate } from 'nacatamalon';
import { useRandom } from 'nacatamalon/math';
import { mix } from '../geometry/noise';
import { BACKDROP, WEATHERS, type TWeather } from '../settings';

/**
 * The light and the weather. The sun is a low evening sun with a bluish sky to fill in; by night it
 * turns into moonlight. Rain, snow, fog and ground mist come and go gradually, the snow settles
 * slowly and melts slowly, and in the rain lightning flashes now and then.
 *
 * Everything else reads `state` every frame to follow it: this is spawned first, so it is up to date
 * by the time they look.
 */
export const Sky = () => {
    const game = useGame();
    const random = useRandom();

    const sun = useDirectionalLight({
        color: '#ffd2a1',
        intensity: 1.7,
        ambient: 0.12,
        castShadow: true,
        shadowArea: 40,
        shadowDistance: 40,
        shadowBias: 0.01,
        shadowStrength: 0.9,
        transform: {
            rotationX: -0.68,
            rotationY: -0.55
        }
    });

    const fill = useAmbientLight({
        color: '#9db3d6',
        intensity: 0.42
    });

    const fog = useFog({
        color: BACKDROP.day,
        near: 26,
        far: 62
    });

    const C = {
        sunDay: getColor('#ffd2a1'),
        sunNight: getColor('#8aa4ee'),
        sunGrey: getColor('#c9d2de'),
        skyDay: getColor('#9db3d6'),
        skyNight: getColor('#3a4a80'),
        skyGrey: getColor('#b9c3d0'),
        day: getColor(BACKDROP.day),
        night: getColor(BACKDROP.night),
        storm: getColor(BACKDROP.storm),
        stormNight: getColor(BACKDROP.stormNight),
        fog: getColor(BACKDROP.fog),
        fogNight: getColor(BACKDROP.fogNight),
        flash: getColor('#9aa6c0')
    };

    /**
     * How much of each there is right now, all from 0 to 1. `overcast` is how grey the day is, `bolt`
     * the lightning.
     */
    const state = {
        night: 0,
        rain: 0,
        snow: 0,
        fog: 0,
        mist: 0,
        snowCover: 0,
        overcast: 0,
        bolt: 0
    };

    let weather: TWeather = 'CLEAR';
    let nightGoal = 0;
    let flash = 0;
    let nextFlash = 4;

    useUpdate((delta, time) => {
        state.night += (nightGoal - state.night) * Math.min(1, delta * 1.6);

        // The weather comes in little by little.
        const k = Math.min(1, delta * 0.9);

        state.rain += ((weather === 'RAIN' ? 1 : 0) - state.rain) * k;
        state.snow += ((weather === 'SNOW' ? 1 : 0) - state.snow) * k;
        state.fog += ((weather === 'FOG' ? 1 : 0) - state.fog) * k;
        // The ground mist comes more slowly; some of it comes with the fog too.
        state.mist += ((weather === 'GROUND MIST' ? 1 : weather === 'FOG' ? 0.7 : 0) - state.mist) * Math.min(1, delta * 0.6);
        state.snowCover = Math.min(1, Math.max(0, state.snowCover + (weather === 'SNOW' ? delta * 0.09 : -delta * 0.12)));
        state.overcast = Math.min(1, state.rain + state.snow * 0.7 + state.fog * 0.8);

        const { night: n, rain, snow, fog: misty, overcast } = state;

        // Lightning now and then while it rains.
        nextFlash -= delta;

        if (rain > 0.7 && nextFlash < 0) {
            flash = 1;
            nextFlash = random.rand(5, 13);
        }

        flash = Math.max(0, flash - delta * 3.5);
        state.bolt = flash * (0.6 + 0.4 * Math.sin(time * 60)) * rain;

        sun.color = lerpColor(lerpColor(C.sunDay, C.sunNight, n), C.sunGrey, overcast * 0.7);
        sun.intensity = mix(1.7, 0.75, n) * (1 - 0.62 * rain - 0.45 * snow - 0.55 * misty);
        sun.shadowStrength = 0.9 * (1 - overcast * 0.75);
        fill.color = lerpColor(lerpColor(C.skyDay, C.skyNight, n), C.skyGrey, overcast * 0.6);
        fill.intensity = mix(0.42, 0.45, n) * (1 + 0.35 * overcast) + state.bolt * 2.2;

        let backdrop = lerpColor(C.day, C.night, n);

        backdrop = lerpColor(backdrop, lerpColor(C.storm, C.stormNight, n), Math.max(rain, snow) * 0.8);
        backdrop = lerpColor(backdrop, lerpColor(C.fog, C.fogNight, n), misty);
        backdrop = lerpColor(backdrop, C.flash, state.bolt * 0.5);
        game.setBackground(backdrop);
        fog.color = backdrop;
        fog.near = mix(26, 7, misty) - rain * 8 - snow * 6;
        fog.far = mix(62, 24, misty) - rain * 18 - snow * 14;
    });

    return {
        state,

        /**
         * The weather now.
         */
        weather: () => weather,

        /**
         * Whether it is night, or getting dark.
         */
        isNight: () => nightGoal > 0.5,

        toggleNight() {
            nightGoal = nightGoal > 0.5 ? 0 : 1;
        },

        nextWeather() {
            weather = WEATHERS[(WEATHERS.indexOf(weather) + 1) % WEATHERS.length];
        }
    };
};

export type TSky = ReturnType<typeof Sky>;
```

`components/table.ts`:

```ts
import { createMaterial, createMesh } from 'nacatamalon';
import { woodTexture, plaqueTexture } from '../art/textures';
import { box, emptyShape, grid, merge, toGeometry } from '../geometry/shapes';
import { BLOCK } from '../settings';

/**
 * What the diorama stands on: a dark wooden table, a walnut stand, and a brass plaque on its front.
 */
export const Table = () => {
    const half = BLOCK.half;

    const table = grid(48, -35, 35, (x, z) => ({
        y: BLOCK.bottom - 0.5,
        color: [1, 1, 1],
        uv: [x * 0.05, z * 0.6]
    }));

    createMesh({
        geometry: toGeometry(table),
        material: createMaterial({
            shader: 'mesh3d',
            name: 'table',
            texture: woodTexture('#1a120c', '#2c1f15', 'table'),
            wrap: 'repeat',
            smooth: true,
            specular: '#1c1712',
            shininess: 24
        }),
        castShadow: false
    });

    const stand = emptyShape();

    merge(stand, box(0, BLOCK.bottom - 0.22, 0, 2 * half + 0.5, 0.44, 2 * half + 0.5));
    merge(stand, box(0, BLOCK.bottom - 0.47, 0, 2 * half + 0.75, 0.06, 2 * half + 0.75, [0.8, 0.8, 0.8]));

    createMesh({
        geometry: toGeometry(stand, {
            uvs: 'box',
            uvScale: 0.22
        }),
        material: createMaterial({
            shader: 'mesh3d',
            name: 'walnut',
            texture: woodTexture('#2a1a10', '#5c3a22', 'walnut'),
            wrap: 'repeat',
            smooth: true,
            specular: '#3a2c20',
            shininess: 40
        })
    });

    // The plaque: the whole picture on each face; only the front one is seen.
    const plaque = box(0, BLOCK.bottom - 0.22, half + 0.255, 2.6, 0.42, 0.02);

    plaque.uvs = [];

    for (let f = 0; f < 6; f++) {
        plaque.uvs.push(0, 1, 1, 1, 1, 0, 0, 0);
    }

    createMesh({
        geometry: toGeometry(plaque),
        material: createMaterial({
            shader: 'mesh3d',
            name: 'plaque',
            texture: plaqueTexture(),
            smooth: true,
            specular: '#ffe2a0',
            shininess: 60
        })
    });
};
```

`components/trees.ts`:

```ts
import { createMaterial, createMesh, useUpdate } from 'nacatamalon';
import { compileShader, composerAdd, composerMul, composerSin, composerSmoothstep, composerTime, composerVec3, composerVertexPosition, composerX, composerY, composerZ } from 'nacatamalon/shader';
import { hex, mixRgb, rand, range } from '../geometry/noise';
import { blob, emptyShape, merge, pine, place, trunk } from '../geometry/shapes';
import { toGeometry } from '../geometry/shapes';
import { heightAt } from '../geometry/terrain';
import { snowyColor } from '../shaders/snow';
import { windAt } from '../shaders/wind';
import { BROADLEAVES, BUSHES, PINES, WIND } from '../settings';
import type { TSky } from './sky';

/**
 * The trees and bushes, all in one mesh: broadleaves with round lumpy tops, layered pines, and loose
 * bushes. The wind sways them, the higher the more, and snow settles on them.
 */
export const Trees = ({ sky }: { sky: TSky; }) => {
    const foliage = emptyShape();

    BROADLEAVES.forEach((t, k) => {
        const s = t.s;
        const y = heightAt(t.x, t.z) - 0.05;
        const lean = range(-0.15, 0.15);

        merge(foliage, place(trunk(1.25 * s, 0.11 * s, lean), {
            t: [t.x, y, t.z],
            ry: rand() * 6
        }));

        const green = mixRgb(hex('#355a1c'), hex('#587a26'), rand());
        const lumps = 9 + Math.floor(rand() * 3);

        for (let b = 0; b < lumps; b++) {
            // Round the middle one, by the golden angle.
            const a = b * 2.39996 + rand() * 0.4;
            const up = b === 0 ? 0.2 : range(-0.25, 0.45);
            const out = b === 0 ? 0 : (0.5 - Math.abs(up) * 0.45) * s;
            const radius = (b === 0 ? 0.55 : range(0.3, 0.4)) * s;

            merge(foliage, blob(t.x + lean + Math.cos(a) * out, y + 1.5 * s + up * s, t.z + Math.sin(a) * out, radius, 0.9, mixRgb(green, hex('#4c6a1f'), rand() * 0.5), k * 13.7 + b * 3.1, 0.38));
        }
    });

    PINES.forEach((t) => {
        const y = heightAt(t.x, t.z) - 0.04;

        merge(foliage, place(trunk(0.7 * t.s, 0.07 * t.s, 0), {
            t: [t.x, y, t.z]
        }));
        merge(foliage, place(pine(1.9 * t.s, 0.62 * t.s, mixRgb(hex('#22432a'), hex('#35583a'), rand())), {
            t: [t.x, y, t.z],
            ry: rand() * 6
        }));
    });

    BUSHES.forEach(([x, z], k) => {
        const y = heightAt(x, z);
        const c = mixRgb(hex('#3d6322'), hex('#6a8a30'), rand());

        merge(foliage, blob(x, y + 0.12, z, 0.26, 0.7, c, 50 + k * 4.3, 0.3));
        merge(foliage, blob(x + 0.2, y + 0.08, z + 0.1, 0.18, 0.7, c, 70 + k * 2.3, 0.3));
    });

    // The higher a point, the more it sways; the trunks barely move.
    const vertex = composerVertexPosition();
    const time = composerTime();
    const { gust } = windAt(vertex, time);
    const up = composerSmoothstep(0.4, 2.6, composerY(vertex));
    const idle = composerMul(composerSin(composerAdd(composerMul(time, 1.3), composerMul(composerX(vertex), 0.7))), 0.012);
    const leaves = composerMul(composerSin(composerAdd(composerMul(time, 6.0), composerMul(composerAdd(composerX(vertex), composerZ(vertex)), 9.0))), composerMul(gust, 0.006));
    const sway = composerAdd(composerMul(up, composerAdd(idle, composerMul(gust, 0.05))), leaves);

    const material = createMaterial({
        ...compileShader({
            shader: 'mesh3d',
            color: snowyColor(),
            position: composerAdd(vertex, composerVec3(composerMul(sway, WIND.x), 0, composerMul(sway, WIND.z)))
        }),
        name: 'foliage'
    });

    createMesh({
        geometry: toGeometry(foliage),
        material,
        boundsMargin: 0.15
    });

    useUpdate(() => {
        material.uniforms!.snow = sky.state.snowCover;
    });
};
```

`components/weather.ts`:

```ts
import { createParticles3d, useUpdate, type TTexture } from 'nacatamalon';
import { puffTexture } from '../art/textures';
import { smoothstep } from '../geometry/noise';
import type { TSky } from './sky';

/**
 * What falls from the sky and what flies at night: rain in streaks, slow snowflakes, and fireflies
 * that blink over the grass after dark (not in the rain or the snow). They are always there and fade
 * in and out with the weather.
 */
export const Weather = ({ sky, glow }: { sky: TSky; glow: TTexture; }) => {
    const rain = createParticles3d({
        effect: {
            kind: 'particles-3d',
            max: 1100,
            blend: 'alpha',
            emission: {
                rate: 1300
            },
            shape: {
                kind: 'box',
                size: [10.5, 0.3, 10.5]
            },
            direction: {
                x: 0.12,
                y: -1,
                z: 0.05
            },
            spread: 0.02,
            life: [0.62, 0.72],
            speed: [8.5, 10],
            size: [0.022, 0.03],
            gravity: {
                x: 0,
                y: -4,
                z: 0
            },
            colorOverLife: [
                {
                    t: 0,
                    color: '#c8d6e6',
                    alpha: 0
                },
                {
                    t: 0.1,
                    color: '#c8d6e6',
                    alpha: 0.7
                },
                {
                    t: 1,
                    color: '#dfe8f2',
                    alpha: 0.55
                }
            ],
            trail: {
                length: 6,
                width: 0.8,
                fade: true
            }
        },
        alpha: 0,
        transform: {
            x: 0,
            y: 6.2,
            z: 0
        }
    });

    const snow = createParticles3d({
        effect: {
            kind: 'particles-3d',
            texture: puffTexture(),
            max: 1400,
            blend: 'alpha',
            emission: {
                rate: 170
            },
            shape: {
                kind: 'box',
                size: [11, 0.3, 11]
            },
            direction: {
                x: 0,
                y: -1,
                z: 0
            },
            spread: 0.5,
            life: [7, 9],
            speed: [0.45, 0.75],
            size: [0.05, 0.09],
            spin: [-1, 1],
            gravity: {
                x: 0.08,
                y: -0.02,
                z: 0.03
            },
            colorOverLife: [
                {
                    t: 0,
                    color: '#ffffff',
                    alpha: 0
                },
                {
                    t: 0.08,
                    color: '#ffffff',
                    alpha: 0.95
                },
                {
                    t: 0.9,
                    color: '#ffffff',
                    alpha: 0.9
                },
                {
                    t: 1,
                    color: '#ffffff',
                    alpha: 0
                }
            ]
        },
        smooth: true,
        alpha: 0,
        transform: {
            x: 0,
            y: 5.4,
            z: 0
        }
    });

    const fireflies = createParticles3d({
        effect: {
            kind: 'particles-3d',
            texture: glow,
            max: 70,
            blend: 'additive',
            emission: {
                rate: 9
            },
            shape: {
                kind: 'box',
                size: [8.5, 0.7, 8.5]
            },
            direction: {
                x: 0,
                y: 1,
                z: 0
            },
            spread: Math.PI,
            life: [3, 6],
            speed: [0.03, 0.09],
            size: [0.06, 0.1],
            gravity: {
                x: 0,
                y: 0.01,
                z: 0
            },
            colorOverLife: [
                {
                    t: 0,
                    color: '#d8ff7a',
                    alpha: 0
                },
                {
                    t: 0.3,
                    color: '#e6ff8c',
                    alpha: 1
                },
                {
                    t: 0.55,
                    color: '#d8ff7a',
                    alpha: 0.2
                },
                {
                    t: 0.75,
                    color: '#e6ff8c',
                    alpha: 0.9
                },
                {
                    t: 1,
                    color: '#d8ff7a',
                    alpha: 0
                }
            ]
        },
        smooth: true,
        alpha: 0,
        transform: {
            x: 0,
            y: 0.45,
            z: 0
        }
    });

    useUpdate(() => {
        const { night, rain: wet, snow: cold } = sky.state;

        rain.alpha = wet;
        snow.alpha = cold;
        fireflies.alpha = smoothstep(0.3, 1, night) * (1 - Math.max(wet, cold) * 0.9);
    });
};
```

`geometry/noise.ts`:

```ts
/**
 * Noise and colour arithmetic in plain TypeScript, for building the terrain, the rocks and the
 * treetops. All of it is deterministic: the same seed builds the same diorama every time.
 */

let state = 1337;

/**
 * Starts the sequence `rand` draws from again, so every run builds the same world.
 */
export const seedNoise = (seed: number) => {
    state = seed;
};

/**
 * A number from 0 up to 1, the next of the sequence.
 */
export const rand = (): number => {
    state = (state * 1664525 + 1013904223) >>> 0;

    return state / 4294967296;
};

/**
 * A number from `a` up to `b`.
 */
export const range = (a: number, b: number): number => a + (b - a) * rand();

const hash2 = (x: number, y: number): number => {
    let h = (x * 374761393 + y * 668265263) | 0;

    h = Math.imul(h ^ (h >>> 13), 1274126177);

    return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
};

const hash3 = (x: number, y: number, z: number): number => hash2(x + z * 1013, y - z * 7919);

const fade = (t: number): number => t * t * (3 - 2 * t);

export const mix = (a: number, b: number, t: number): number => a + (b - a) * t;

/**
 * Smooth noise from 0 to 1 on a plane.
 */
export const noise2 = (x: number, y: number): number => {
    const xi = Math.floor(x);
    const yi = Math.floor(y);
    const u = fade(x - xi);
    const v = fade(y - yi);

    return mix(mix(hash2(xi, yi), hash2(xi + 1, yi), u), mix(hash2(xi, yi + 1), hash2(xi + 1, yi + 1), u), v);
};

/**
 * Smooth noise from 0 to 1 in space.
 */
export const noise3 = (x: number, y: number, z: number): number => {
    const xi = Math.floor(x);
    const yi = Math.floor(y);
    const zi = Math.floor(z);
    const u = fade(x - xi);
    const v = fade(y - yi);
    const w = fade(z - zi);
    const c = (dx: number, dy: number, dz: number) => hash3(xi + dx, yi + dy, zi + dz);

    return mix(
        mix(mix(c(0, 0, 0), c(1, 0, 0), u), mix(c(0, 1, 0), c(1, 1, 0), u), v),
        mix(mix(c(0, 0, 1), c(1, 0, 1), u), mix(c(0, 1, 1), c(1, 1, 1), u), v),
        w
    );
};

/**
 * Several layers of `noise2`, each finer and fainter: detail on top of the broad shapes.
 */
export const fbm2 = (x: number, y: number, octaves = 4): number => {
    let sum = 0;
    let amplitude = 0.5;
    let frequency = 1;
    let total = 0;

    for (let i = 0; i < octaves; i++) {
        sum += amplitude * noise2(x * frequency, y * frequency);
        total += amplitude;
        amplitude *= 0.5;
        frequency *= 2.03;
    }

    return sum / total;
};

/**
 * The same as `fbm2`, in space.
 */
export const fbm3 = (x: number, y: number, z: number, octaves = 3): number => {
    let sum = 0;
    let amplitude = 0.5;
    let frequency = 1;
    let total = 0;

    for (let i = 0; i < octaves; i++) {
        sum += amplitude * noise3(x * frequency, y * frequency, z * frequency);
        total += amplitude;
        amplitude *= 0.5;
        frequency *= 2.1;
    }

    return sum / total;
};

export const smoothstep = (e0: number, e1: number, x: number): number => {
    const t = Math.min(1, Math.max(0, (x - e0) / (e1 - e0)));

    return t * t * (3 - 2 * t);
};

/**
 * A colour as red, green and blue from 0 to 1, for the vertex colours.
 */
export type TRgb = [number, number, number];

export const hex = (h: string): TRgb => {
    const n = parseInt(h.slice(1), 16);

    return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
};

export const mixRgb = (a: TRgb, b: TRgb, t: number): TRgb => [mix(a[0], b[0], t), mix(a[1], b[1], t), mix(a[2], b[2], t)];

export const mulRgb = (a: TRgb, k: number): TRgb => [a[0] * k, a[1] * k, a[2] * k];
```

`geometry/shapes.ts`:

```ts
import { createGeometry } from 'nacatamalon';
import { fbm3, hex, mixRgb, mulRgb, noise2, rand, type TRgb } from './noise';

/**
 * A shape as plain lists, before it becomes a geometry: many are merged into one to draw them all at
 * once.
 */
export type TShape = {
    positions: number[];
    indices: number[];
    colors: number[];
    normals?: number[];
    uvs?: number[];
};

export const emptyShape = (): TShape => ({
    positions: [],
    indices: [],
    colors: []
});

/**
 * Adds `part` to `into`, so they are drawn as one.
 */
export const merge = (into: TShape, part: TShape): TShape => {
    const base = into.positions.length / 3;

    into.positions.push(...part.positions);
    into.colors.push(...part.colors);

    for (const i of part.indices) {
        into.indices.push(i + base);
    }

    if (part.normals) {
        (into.normals ??= []).push(...part.normals);
    }

    if (part.uvs) {
        (into.uvs ??= []).push(...part.uvs);
    }

    return into;
};

/**
 * How to move a shape: scale, turn about x, y and z (in that order: z, then x, then y), then move.
 */
export type TPlace = {
    s?: [number, number, number];
    rx?: number;
    ry?: number;
    rz?: number;
    t?: [number, number, number];
};

/**
 * Moves the points (and turns the normals) of a shape where it is.
 */
export const place = (g: TShape, o: TPlace): TShape => {
    const [sx, sy, sz] = o.s ?? [1, 1, 1];
    const [tx, ty, tz] = o.t ?? [0, 0, 0];
    const cx = Math.cos(o.rx ?? 0);
    const snx = Math.sin(o.rx ?? 0);
    const cy = Math.cos(o.ry ?? 0);
    const sny = Math.sin(o.ry ?? 0);
    const cz = Math.cos(o.rz ?? 0);
    const snz = Math.sin(o.rz ?? 0);

    const turn = (x: number, y: number, z: number): [number, number, number] => {
        const x1 = x * cz - y * snz;
        const y1 = x * snz + y * cz;
        const y2 = y1 * cx - z * snx;
        const z2 = y1 * snx + z * cx;

        return [x1 * cy + z2 * sny, y2, -x1 * sny + z2 * cy];
    };

    for (let i = 0; i < g.positions.length; i += 3) {
        const p = turn(g.positions[i] * sx, g.positions[i + 1] * sy, g.positions[i + 2] * sz);

        g.positions[i] = p[0] + tx;
        g.positions[i + 1] = p[1] + ty;
        g.positions[i + 2] = p[2] + tz;
    }

    if (g.normals) {
        for (let i = 0; i < g.normals.length; i += 3) {
            const n = turn(g.normals[i] / sx, g.normals[i + 1] / sy, g.normals[i + 2] / sz);
            const l = Math.hypot(n[0], n[1], n[2]) || 1;

            g.normals[i] = n[0] / l;
            g.normals[i + 1] = n[1] / l;
            g.normals[i + 2] = n[2] / l;
        }
    }

    return g;
};

/**
 * Turns the lists into a geometry. `flat` gives every face its own normal; `uvs` makes texture
 * coordinates for a shape that has none.
 */
export const toGeometry = (g: TShape, extra: { flat?: boolean; uvs?: 'box' | 'planar'; uvScale?: number; } = {
}) => createGeometry({
    positions: g.positions,
    indices: g.indices,
    colors: g.colors,
    ...(g.normals && !extra.flat ? {
        normals: g.normals
    } : {
    }),
    ...(g.uvs ? {
        uvs: g.uvs
    } : extra.uvs ? {
        uvs: extra.uvs,
        uvScale: extra.uvScale ?? 1
    } : {
    }),
    flat: extra.flat ?? false
});

/**
 * A flat grid of `n` by `n` cells, with the height and colour of each point given by `at`.
 */
export const grid = (n: number, from: number, to: number, at: (x: number, z: number) => { y: number; color: TRgb; uv?: [number, number]; }): TShape => {
    const g = emptyShape();

    for (let j = 0; j <= n; j++) {
        for (let i = 0; i <= n; i++) {
            const x = from + (i / n) * (to - from);
            const z = from + (j / n) * (to - from);
            const { y, color, uv } = at(x, z);

            g.positions.push(x, y, z);
            g.colors.push(color[0], color[1], color[2], 1);

            if (uv) {
                (g.uvs ??= []).push(uv[0], uv[1]);
            }
        }
    }

    for (let j = 0; j < n; j++) {
        for (let i = 0; i < n; i++) {
            const a = j * (n + 1) + i;

            g.indices.push(a, a + n + 1, a + 1, a + 1, a + n + 1, a + n + 2);
        }
    }

    return g;
};

/**
 * A sphere of triangles, `subdivisions` times finer than an icosahedron: its points and faces.
 */
const icosphere = (subdivisions: number): { v: number[][]; f: number[][]; } => {
    const t = (1 + Math.sqrt(5)) / 2;

    const v = [[-1, t, 0], [1, t, 0], [-1, -t, 0], [1, -t, 0], [0, -1, t], [0, 1, t], [0, -1, -t], [0, 1, -t], [t, 0, -1], [t, 0, 1], [-t, 0, -1], [-t, 0, 1]].map((p) => {
        const l = Math.hypot(p[0], p[1], p[2]);

        return [p[0] / l, p[1] / l, p[2] / l];
    });

    let f = [[0, 11, 5], [0, 5, 1], [0, 1, 7], [0, 7, 10], [0, 10, 11], [1, 5, 9], [5, 11, 4], [11, 10, 2], [10, 7, 6], [7, 1, 8], [3, 9, 4], [3, 4, 2], [3, 2, 6], [3, 6, 8], [3, 8, 9], [4, 9, 5], [2, 4, 11], [6, 2, 10], [8, 6, 7], [9, 8, 1]];

    for (let s = 0; s < subdivisions; s++) {
        const cache = new Map<string, number>();

        const middle = (a: number, b: number): number => {
            const key = a < b ? `${a}_${b}` : `${b}_${a}`;
            const hit = cache.get(key);

            if (hit !== undefined) {
                return hit;
            }

            const p = [(v[a][0] + v[b][0]) / 2, (v[a][1] + v[b][1]) / 2, (v[a][2] + v[b][2]) / 2];
            const l = Math.hypot(p[0], p[1], p[2]);

            v.push([p[0] / l, p[1] / l, p[2] / l]);
            cache.set(key, v.length - 1);

            return v.length - 1;
        };

        const next: number[][] = [];

        for (const [a, b, c] of f) {
            const ab = middle(a, b);
            const bc = middle(b, c);
            const ca = middle(c, a);

            next.push([a, ab, ca], [b, bc, ab], [c, ca, bc], [ab, bc, ca]);
        }

        f = next;
    }

    return {
        v,
        f
    };
};

/**
 * A soft lump (a treetop, a bush): a sphere pushed out of shape, darker underneath.
 */
export const blob = (cx: number, cy: number, cz: number, r: number, squash: number, color: TRgb, seed: number, rough = 0.22): TShape => {
    const { v, f } = icosphere(3);
    const g = emptyShape();
    const light = mixRgb(color, [0.7, 0.78, 0.38], 0.22);

    for (const p of v) {
        const n = fbm3(p[0] * 2.6 + seed, p[1] * 2.6, p[2] * 2.6 - seed, 3);
        const d = r * (1 + (n - 0.5) * 2 * rough);

        g.positions.push(cx + p[0] * d, cy + p[1] * d * squash, cz + p[2] * d);

        // Painted-in shade: the inside and the underside of the top get less light.
        const shade = 0.42 + 0.58 * Math.pow((p[1] + 1) / 2, 0.9);
        const speck = 0.7 + 0.55 * fbm3(p[0] * 7 + seed, p[1] * 7, p[2] * 7, 2);
        const c = mulRgb(mixRgb(color, light, Math.max(0, p[1]) * 0.6), shade * speck);

        g.colors.push(c[0], c[1], c[2], 1);
    }

    for (const t of f) {
        g.indices.push(t[0], t[1], t[2]);
    }

    return g;
};

/**
 * A faceted rock: a sphere pushed far out of shape, flat underneath, with moss on top.
 */
export const rock = (sx: number, sy: number, sz: number, seed: number, stone: TRgb, moss: TRgb): TShape => {
    const { v, f } = icosphere(2);
    const g = emptyShape();

    for (const p of v) {
        const n = fbm3(p[0] * 1.3 + seed, p[1] * 1.3, p[2] * 1.3 + seed * 0.5, 3);
        const d = 0.7 + n * 0.6;
        const y = p[1] < -0.3 ? -0.3 + (p[1] + 0.3) * 0.25 : p[1];

        g.positions.push(p[0] * d * sx, y * d * sy, p[2] * d * sz);

        const mossy = Math.max(0, (p[1] - 0.35) / 0.65) * (0.6 + 0.4 * n);
        const shade = 0.55 + 0.45 * (p[1] + 1) / 2;
        const c = mulRgb(mixRgb(stone, moss, mossy), shade * (0.85 + rand() * 0.25));

        g.colors.push(c[0], c[1], c[2], 1);
    }

    for (const t of f) {
        g.indices.push(t[0], t[1], t[2]);
    }

    return g;
};

/**
 * A layered pine: cone skirts with a ragged, drooping edge.
 */
export const pine = (height: number, radius: number, color: TRgb): TShape => {
    const g = emptyShape();
    const layers = 5;
    const sides = 22;

    for (let l = 0; l < layers; l++) {
        const k = l / (layers - 1);
        const y0 = 0.28 * height + k * height * 0.58;
        const r = radius * (1 - k * 0.72) * (0.92 + rand() * 0.16);
        const top = y0 + height * 0.34 * (1 - k * 0.25);
        const base = g.positions.length / 3;
        const tip = mixRgb(color, [0.45, 0.6, 0.3], 0.2 + k * 0.2);

        g.positions.push(0, top, 0);
        g.colors.push(tip[0], tip[1], tip[2], 1);

        for (let s = 0; s < sides; s++) {
            const a = (s / sides) * Math.PI * 2 + l * 0.37;
            const jag = s % 2 === 0 ? 1 : 0.78 + rand() * 0.1;
            const droop = s % 2 === 0 ? -0.06 * height : 0;
            const c = mulRgb(color, 0.55 + 0.25 * k + rand() * 0.12);

            g.positions.push(Math.cos(a) * r * jag, y0 + droop, Math.sin(a) * r * jag);
            g.colors.push(c[0], c[1], c[2], 1);
        }

        // The dark middle of the underside, a little in and up.
        const under = g.positions.length / 3;
        const uc = mulRgb(color, 0.22);

        g.positions.push(0, y0 + height * 0.08, 0);
        g.colors.push(uc[0], uc[1], uc[2], 1);

        for (let s = 0; s < sides; s++) {
            const a = base + 1 + s;
            const b = base + 1 + ((s + 1) % sides);

            g.indices.push(base, b, a, under, a, b);
        }
    }

    return g;
};

const WHITE: TRgb = [1, 1, 1];

/**
 * A box with its own normal on each face, darker underneath, centred at `cx`, `cy`, `cz`.
 */
export const box = (cx: number, cy: number, cz: number, w: number, h: number, d: number, color: TRgb = WHITE): TShape => {
    const g = emptyShape();
    const x = w / 2;
    const y = h / 2;
    const z = d / 2;

    const faces: [number[], number[][]][] = [[[0, 0, 1], [[-x, -y, z], [x, -y, z], [x, y, z], [-x, y, z]]], [[0, 0, -1], [[x, -y, -z], [-x, -y, -z], [-x, y, -z], [x, y, -z]]], [[1, 0, 0], [[x, -y, z], [x, -y, -z], [x, y, -z], [x, y, z]]], [[-1, 0, 0], [[-x, -y, -z], [-x, -y, z], [-x, y, z], [-x, y, -z]]], [[0, 1, 0], [[-x, y, z], [x, y, z], [x, y, -z], [-x, y, -z]]], [[0, -1, 0], [[-x, -y, -z], [x, -y, -z], [x, -y, z], [-x, -y, z]]]];

    g.normals = [];

    for (const [n, quad] of faces) {
        const b = g.positions.length / 3;
        const k = n[1] < 0 ? 0.5 : 1;

        for (const p of quad) {
            g.positions.push(cx + p[0], cy + p[1], cz + p[2]);
            g.normals.push(n[0], n[1], n[2]);
            g.colors.push(color[0] * k, color[1] * k, color[2] * k, 1);
        }

        g.indices.push(b, b + 1, b + 2, b, b + 2, b + 3);
    }

    return g;
};

/**
 * A box at the origin, to be put in place with `place`.
 */
export const block = (w: number, h: number, d: number) => box(0, 0, 0, w, h, d);

/**
 * A tapering trunk whose roots spread at the foot, in bark colours. `lean` bends it towards x.
 */
export const trunk = (h: number, r: number, lean: number): TShape => {
    const g = emptyShape();
    const sides = 10;
    const rows = 7;
    const bark = hex('#4a3826');

    for (let j = 0; j <= rows; j++) {
        const t = j / rows;
        const rr = r * (1 - t * 0.55) * (1 + 0.6 * Math.pow(1 - t, 6));

        for (let s = 0; s < sides; s++) {
            const a = (s / sides) * Math.PI * 2;
            const flare = 1 + 0.25 * Math.pow(1 - t, 8) * (0.5 + 0.5 * Math.sin(a * 3));
            const c = mulRgb(bark, (0.55 + 0.45 * t) * (0.85 + 0.3 * noise2(s * 3.1, j * 1.7)));

            g.positions.push(Math.cos(a) * rr * flare + lean * t * t, t * h, Math.sin(a) * rr * flare);
            g.colors.push(c[0], c[1], c[2], 1);
        }
    }

    for (let j = 0; j < rows; j++) {
        for (let s = 0; s < sides; s++) {
            const a = j * sides + s;
            const b = j * sides + ((s + 1) % sides);

            g.indices.push(a, a + sides, b, b, a + sides, b + sides);
        }
    }

    return g;
};
```

`geometry/terrain.ts`:

```ts
import { BLOCK, BRIDGE_X, BROADLEAVES, COTTAGE, PINES } from '../settings';
import { fbm2, hex, mix, mixRgb, mulRgb, noise2, smoothstep, type TRgb } from './noise';

/**
 * Where the middle of the river is along z, for each x.
 */
export const riverZ = (x: number): number => 0.85 * Math.sin(x * 0.48 + 0.5) + 0.55;

const cosTurn = Math.cos(COTTAGE.turn);
const sinTurn = Math.sin(COTTAGE.turn);

/**
 * A point in the cottage's own frame: x along its front, z out of its door.
 */
export const toCottage = (x: number, z: number) => {
    const dx = x - COTTAGE.x;
    const dz = z - COTTAGE.z;

    return {
        lx: dx * cosTurn - dz * sinTurn,
        lz: dx * sinTurn + dz * cosTurn
    };
};

/**
 * A point in the cottage's frame, back in the world.
 */
export const fromCottage = (lx: number, lz: number) => ({
    x: COTTAGE.x + lx * cosTurn + lz * sinTurn,
    z: COTTAGE.z - lx * sinTurn + lz * cosTurn
});

/**
 * The path: from the cottage door to the bridge, and from the bridge to the front edge.
 */
const door = {
    x: COTTAGE.x + Math.sin(COTTAGE.turn) * 1.25,
    z: COTTAGE.z + Math.cos(COTTAGE.turn) * 1.25
};

const PATH: { x: number; z: number; }[] = [
    door,
    {
        x: 1.1,
        z: -1.05
    },
    {
        x: -0.2,
        z: riverZ(-0.4) - 1.55
    },
    {
        x: BRIDGE_X,
        z: riverZ(BRIDGE_X) - 1.15
    },
    {
        x: BRIDGE_X,
        z: riverZ(BRIDGE_X) + 1.15
    },
    {
        x: -1.6,
        z: 3.2
    },
    {
        x: -1.1,
        z: 5.2
    }
];

const segmentDistance = (px: number, pz: number, a: { x: number; z: number; }, b: { x: number; z: number; }): number => {
    const dx = b.x - a.x;
    const dz = b.z - a.z;
    const t = Math.max(0, Math.min(1, ((px - a.x) * dx + (pz - a.z) * dz) / (dx * dx + dz * dz)));

    return Math.hypot(px - (a.x + dx * t), pz - (a.z + dz * t));
};

/**
 * How far a point is from the path.
 */
export const pathDistance = (x: number, z: number): number => {
    let d = Infinity;

    for (let i = 0; i < PATH.length - 1; i++) {
        // The stretch over the bridge leaves no mark on the ground.
        if (i !== 3) {
            d = Math.min(d, segmentDistance(x, z, PATH[i], PATH[i + 1]));
        }
    }

    return d;
};

/**
 * How much a point belongs to the river's channel: 1 in the middle, 0 outside.
 */
const channel = (x: number, z: number): number => {
    const w = 1.05 + 0.18 * Math.sin(x * 1.3);

    return smoothstep(w, w * 0.32, Math.abs(z - riverZ(x)));
};

/**
 * The height of the ground at a point.
 */
export const heightAt = (x: number, z: number): number => {
    let h = (fbm2(x * 0.32 + 11, z * 0.32 - 4, 5) - 0.5) * 0.42;

    // A hill at the back on the left, a rise at the front on the right.
    h += 1.25 * Math.exp(-((x + 3.3) ** 2 + (z + 3.2) ** 2) / 4.2);
    h += 0.45 * Math.exp(-((x - 3.5) ** 2 + (z - 3.4) ** 2) / 2.6);
    h += 0.18 * Math.exp(-((x + 3.6) ** 2 + (z - 3.6) ** 2) / 1.8);

    // The flat ground the cottage stands on.
    h = mix(h, COTTAGE.pad, smoothstep(2.1, 1.35, Math.hypot(x - COTTAGE.x, z - COTTAGE.z)));

    // The path, barely sunk.
    h -= 0.025 * smoothstep(0.32, 0.1, pathDistance(x, z));

    // The river.
    const bed = BLOCK.bed + (fbm2(x * 1.4, z * 1.4, 3) - 0.5) * 0.12;

    return mix(h, bed, channel(x, z));
};

/**
 * The ground's colours.
 */
export const SOIL = {
    grassA: hex('#4b7428'),
    grassB: hex('#7a9a3c'),
    dry: hex('#a59e58'),
    moss: hex('#385622'),
    mud: hex('#6a573a'),
    bed: hex('#3e3628'),
    path: hex('#8f7856'),
    pebble: hex('#a8987c'),
    roots: hex('#33281b'),
    topsoil: hex('#4f3b26'),
    clay: hex('#8d6b45'),
    sand: hex('#a88a5e'),
    rock: hex('#6c675f')
};

/**
 * Where the trees stand and how wide they are, for the shade under them.
 */
const TREES = [
    ...BROADLEAVES.map((t) => ({
        x: t.x,
        z: t.z,
        r: 0.9 * t.s
    })),
    ...PINES.map((t) => ({
        x: t.x,
        z: t.z,
        r: 0.55 * t.s
    }))
];

/**
 * The colour of the ground at a point of height `h`: grass, dry on the heights, moss, the path, mud
 * by the water and the river's bed, darker under the trees and round the cottage.
 */
export const groundColour = (x: number, z: number, h: number): TRgb => {
    const n1 = fbm2(x * 0.7, z * 0.7, 4);
    const n2 = fbm2(x * 1.9 + 7, z * 1.9, 3);
    let c = mixRgb(SOIL.grassA, SOIL.grassB, smoothstep(0.3, 0.75, n1));

    c = mixRgb(c, SOIL.dry, smoothstep(0.35, 1.2, h) * 0.55);
    c = mixRgb(c, SOIL.moss, smoothstep(0.55, 0.72, n2) * 0.5);

    const path = smoothstep(0.32, 0.15, pathDistance(x, z)) * (0.8 + 0.2 * n2);

    c = mixRgb(c, mixRgb(SOIL.path, SOIL.pebble, smoothstep(0.6, 0.8, noise2(x * 14, z * 14))), path);
    c = mixRgb(c, SOIL.mud, smoothstep(BLOCK.water + 0.17, BLOCK.water + 0.02, h));
    c = mixRgb(c, SOIL.bed, smoothstep(BLOCK.water, BLOCK.bed, h) * 0.8);

    // Contact shade under the trees and round the cottage.
    let shade = 1;

    for (const t of TREES) {
        shade *= 1 - 0.4 * Math.exp(-((x - t.x) ** 2 + (z - t.z) ** 2) / (t.r * t.r * 0.8));
    }

    const { lx, lz } = toCottage(x, z);
    const fromWalls = Math.max(Math.abs(lx) - 1.2, Math.abs(lz) - 0.85, 0);

    shade *= 1 - 0.45 * Math.exp(-(fromWalls * fromWalls) / 0.05);

    return mulRgb(c, shade * 1.12);
};
```

`scenes/diorama.ts`:

```ts
import { createScene, useSpawn } from 'nacatamalon';
import { glowTexture } from '../art/textures';
import { Bridge } from '../components/bridge';
import { Controls } from '../components/controls';
import { Cottage } from '../components/cottage';
import { FairyLight } from '../components/fairy_light';
import { Fence } from '../components/fence';
import { Grass } from '../components/grass';
import { Land } from '../components/land';
import { Look } from '../components/look';
import { Mist } from '../components/mist';
import { Orbit } from '../components/orbit';
import { River } from '../components/river';
import { Rocks } from '../components/rocks';
import { Sky } from '../components/sky';
import { Table } from '../components/table';
import { Trees } from '../components/trees';
import { Weather } from '../components/weather';
import { seedNoise } from '../geometry/noise';
import { ORBS } from '../settings';

/**
 * A small world on a walnut stand, every piece of it made in code. The sky is spawned first: it
 * keeps the time of day and the weather, and everything after it follows what it says.
 */
export const Diorama = () => {
    // The same trees, rocks and grass every time.
    seedNoise(1337);

    const sky = useSpawn(Sky)().api;

    useSpawn(Orbit)();
    useSpawn(Table)();
    useSpawn(Land)({
        sky
    });
    useSpawn(River)({
        sky
    });
    useSpawn(Mist)({
        sky
    });
    useSpawn(Trees)({
        sky
    });
    useSpawn(Rocks)({
        sky
    });
    useSpawn(Grass)({
        sky
    });
    useSpawn(Cottage)({
        sky
    });
    useSpawn(Bridge)();
    useSpawn(Fence)({
        sky
    });

    const glow = glowTexture();

    useSpawn(Weather)({
        sky,
        glow
    });

    const fairyLight = useSpawn(FairyLight);

    ORBS.forEach((orb, i) => {
        fairyLight({
            ...orb,
            seed: i * 3 + 1,
            sky,
            glow
        });
    });

    useSpawn(Look)({
        sky
    });
    useSpawn(Controls)({
        sky
    });

    return createScene();
};
```

`settings.ts`:

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

/**
 * The game's size, in its own pixels: wide and sharp, since this is a picture to look at.
 */
export const WIDTH = 1280;
export const HEIGHT = 720;

/**
 * N switches day and night, W goes to the next weather.
 */
export const ACTIONS: TActionDef[] = [
    {
        name: 'night',
        bindings: [
            {
                type: 'key',
                key: 'n'
            }
        ]
    },
    {
        name: 'weather',
        bindings: [
            {
                type: 'key',
                key: 'w'
            }
        ]
    }
];

/**
 * The weathers W goes through, in order.
 */
export const WEATHERS = ['CLEAR', 'RAIN', 'SNOW', 'FOG', 'GROUND MIST'] as const;

export type TWeather = (typeof WEATHERS)[number];

/**
 * The block of land: from -`half` to `half` on x and z, cut off at `bottom`. The river's water is at
 * `water`, its bed at `bed`.
 */
export const BLOCK = {
    half: 5,
    bottom: -1.6,
    water: -0.24,
    bed: -0.62
};

/**
 * The cottage: where it stands, how it is turned, and the height of the flat ground it sits on.
 */
export const COTTAGE = {
    x: 2.0,
    z: -2.55,
    turn: -0.32,
    pad: 0.1
};

/**
 * Where the bridge crosses the river, along x.
 */
export const BRIDGE_X = -1.35;

/**
 * Where the wind blows towards, on the ground. It bends the grass and the trees, and carries the
 * smoke.
 */
export const WIND = {
    x: 0.91,
    z: 0.41
};

/**
 * The broadleaf trees and the pines: x, z and size.
 */
export const BROADLEAVES: readonly { x: number; z: number; s: number; }[] = [
    {
        x: -0.4,
        z: -3.7,
        s: 1.1
    },
    {
        x: 4.0,
        z: -0.75,
        s: 0.95
    },
    {
        x: 0.7,
        z: 3.7,
        s: 1.15
    },
    {
        x: 3.0,
        z: 3.05,
        s: 0.8
    },
    {
        x: -3.95,
        z: 1.45,
        s: 1.0
    },
    {
        x: 4.25,
        z: -4.1,
        s: 0.85
    },
    {
        x: -2.55,
        z: 3.65,
        s: 0.75
    }
];

export const PINES: readonly { x: number; z: number; s: number; }[] = [
    {
        x: -3.6,
        z: -3.4,
        s: 1.25
    },
    {
        x: -2.55,
        z: -4.2,
        s: 1.05
    },
    {
        x: -4.35,
        z: -2.2,
        s: 1.0
    },
    {
        x: -2.9,
        z: -2.35,
        s: 0.85
    },
    {
        x: -4.25,
        z: -4.3,
        s: 0.95
    },
    {
        x: -1.7,
        z: -3.6,
        s: 0.7
    },
    {
        x: -4.1,
        z: 4.1,
        s: 0.9
    },
    {
        x: -3.35,
        z: -1.35,
        s: 0.65
    }
];

/**
 * Loose bushes: x, z.
 */
export const BUSHES: readonly (readonly [number, number])[] = [[0.4, -1.9], [3.35, -1.6], [-2.2, 2.25], [1.9, 2.4], [-0.6, 2.75], [4.4, 1.9], [0.2, -4.4], [-4.5, 0.2]];

/**
 * The fairy lights that wander about, each round its own place.
 */
export const ORBS: readonly { x: number; y: number; z: number; color: string; }[] = [
    {
        x: -2.2,
        y: 0.75,
        z: 1.9,
        color: '#7fe9ff'
    },
    {
        x: 0.9,
        y: 0.6,
        z: -1.6,
        color: '#ff8fe1'
    },
    {
        x: 3.4,
        y: 0.85,
        z: 1.5,
        color: '#ffe27a'
    },
    {
        x: -3.2,
        y: 1.6,
        z: -2.4,
        color: '#b99bff'
    },
    {
        x: 0.3,
        y: 0.55,
        z: 2.6,
        color: '#8fffb4'
    },
    {
        x: 3.6,
        y: 0.9,
        z: -2.9,
        color: '#ffb27a'
    }
];

/**
 * The street lamp by the path: x, z.
 */
export const LAMP = {
    x: 0.95,
    z: -0.85
};

/**
 * The camera turns round `target`: `yaw` about it, `pitch` above it, `distance` away. Left alone
 * for `idle` seconds, it starts turning by itself.
 */
export const ORBIT = {
    target: {
        x: 0,
        y: -0.35,
        z: 0
    },
    yaw: 0.62,
    pitch: 0.5,
    distance: 19.5,
    near: 10,
    far: 32,
    idle: 4
};

/**
 * The background and fog: by day, by night, in a storm and in fog.
 */
export const BACKDROP = {
    day: '#24201c',
    night: '#0c0f1c',
    storm: '#3a3d44',
    stormNight: '#0a0c12',
    fog: '#6d737a',
    fogNight: '#1a1e2a'
};
```

`shaders/mist.ts`:

```ts
import {
    compileShader, composerAdd, composerFbm, composerLight, composerMul, composerSin, composerSmoothstep, composerSub, composerSurface, composerSwizzle,
    composerTime, composerUniform, composerVec2, composerVec3, composerVec4, composerVertexPosition, composerWorldPos, composerX
} from 'nacatamalon/shader';
import { WIND } from '../settings';

/**
 * One sheet of the ground mist, built from composer nodes so it runs on both cards.
 *
 * Each point brings its sheet in the red of its colour (0 at the bottom, 1 at the top) and how thick
 * the mist is there in the alpha. Two layers of noise drift with the wind, each sheet seeing them a
 * little shifted, so stacked together they read as one body of mist and not as flat layers. It is
 * lit by what lights the ground (the sun with its shadows, the lamp, the fairy lights), with a
 * little light of its own, and the sheets sway a little, in the vertex shader.
 *
 * Its knobs: `mist` (how much, 0 to 1) and `mistTint`.
 */
export const mistShader = () => {
    const world = composerWorldPos();
    const time = composerTime();
    const surface = composerSurface();
    const layer = composerX(surface);
    const thickness = composerSwizzle(surface, 'w');
    const ground = composerSwizzle(world, 'xz');
    const drift = composerMul(composerVec2(WIND.x, WIND.z), composerMul(time, 0.22));

    const n1 = composerFbm(composerAdd(composerMul(composerSub(ground, drift), 0.55), composerMul(layer, 1.9)), 4);
    const n2 = composerFbm(composerAdd(composerMul(composerSub(ground, composerMul(drift, 1.7)), 1.5), 7.0), 3);
    const body = composerSmoothstep(0.32, 0.78, composerAdd(composerMul(n1, 0.72), composerMul(n2, 0.42)));
    const alpha = composerMul(composerMul(thickness, body), composerUniform('mist', 0));
    const colour = composerMul(composerUniform('mistTint', [0.86, 0.9, 0.95]), composerAdd(composerMul(composerLight(), 0.9), 0.22));

    const vertex = composerVertexPosition();
    const sway = composerMul(composerSin(composerAdd(composerMul(composerX(vertex), 1.3), composerMul(time, 0.6))), 0.02);

    return compileShader({
        shader: 'mesh3d',
        color: composerVec4(colour, alpha),
        position: composerAdd(vertex, composerVec3(0, sway, 0))
    });
};
```

`shaders/river.ts`:

```ts
import {
    compileShader, composerAbs, composerAdd, composerCellularNoise, composerFbm, composerFresnel, composerLight, composerMix, composerMul, composerPow,
    composerSaturate, composerShine, composerSin, composerSmoothstep, composerSub, composerSwizzle, composerTime, composerUniform, composerVec2, composerVec3,
    composerVec4, composerVertexPosition, composerWorldPos, composerX, composerZ
} from 'nacatamalon/shader';

/**
 * The river's water, built from composer nodes so it runs on both cards.
 *
 * Along the river and across it: `u` runs down the channel and the current moves along it, faster
 * in the middle than at the banks; `v` goes from bank to bank. Two layers of noise give deep and
 * shallow water, the sky shows in it edge on (Fresnel), long glints run with the current, foam
 * gathers at the banks and in streaks, and in the rain drops ring the surface. The surface itself
 * rocks a little, in the vertex shader.
 *
 * Its knobs: `flow` (how fast), `skyCol`, `glint` and `rain` (0 to 1).
 */
export const riverShader = () => {
    const world = composerWorldPos();
    const time = composerTime();
    const wx = composerX(world);

    // The same curve as `riverZ`, so the water knows where the middle of the channel is.
    const middle = composerAdd(composerMul(composerSin(composerAdd(composerMul(wx, 0.48), 0.5)), 0.85), 0.55);
    const v = composerSub(composerZ(world), middle);
    const across = composerAbs(v);
    const flow = composerUniform('flow', 0.7);
    const speed = composerMul(flow, composerSub(1.25, composerMul(composerSmoothstep(0.0, 0.9, across), 0.6)));
    const u = composerSub(wx, composerMul(time, speed));

    const n1 = composerFbm(composerVec2(composerMul(u, 1.1), composerMul(v, 3.2)), 4);
    const n2 = composerFbm(composerVec2(composerAdd(composerMul(u, 2.4), composerMul(time, -0.25)), composerAdd(composerMul(v, 6.5), 3.0)), 3);
    const streak = composerFbm(composerVec2(composerMul(u, 0.9), composerMul(v, 14.0)), 2);
    const n = composerMul(composerAdd(n1, n2), 0.5);

    const deep = composerVec3(0.03, 0.12, 0.13);
    const shallow = composerVec3(0.14, 0.34, 0.31);
    const shallowness = composerSaturate(composerAdd(composerSmoothstep(0.3, 0.72, n), composerMul(composerSmoothstep(0.25, 0.65, across), 0.5)));
    const lit = composerMul(composerMix(deep, shallow, shallowness), composerAdd(composerLight(), 0.15));
    const fresnel = composerFresnel(3.5);
    const reflected = composerMix(lit, composerUniform('skyCol', [0.62, 0.72, 0.82]), composerMul(fresnel, 0.55));

    // Glints drawn out along the current.
    const glints = composerMul(composerPow(composerSmoothstep(0.54, 0.72, composerMul(composerAdd(n2, streak), 0.5)), 2), composerUniform('glint', 0.9));

    // Foam: by the banks, and in streaks that go down with the water.
    const bank = composerSmoothstep(0.35, 0.62, across);
    const foamNoise = composerFbm(composerVec2(composerMul(composerSub(wx, composerMul(time, composerMul(flow, 0.8))), 2.2), composerMul(v, 16.0)), 3);
    const foam = composerAdd(composerMul(bank, composerSmoothstep(0.52, 0.68, foamNoise)), composerMul(composerSmoothstep(0.66, 0.78, streak), 0.22));
    const foamColour = composerMul(composerVec3(0.82, 0.88, 0.86), composerAdd(composerLight(), 0.2));
    const water = composerMix(reflected, foamColour, composerMul(composerSaturate(foam), 0.7));

    // Raindrops: points that appear and fade on the water.
    const drops = composerCellularNoise(composerVec3(composerMul(composerSwizzle(world, 'xz'), 7.0), composerMul(time, 2.2)));
    const ripple = composerMul(composerSmoothstep(0.14, 0.03, drops), composerUniform('rain', 0));

    const colour = composerAdd(
        composerAdd(composerAdd(water, composerMul(composerShine(), 1.6)), composerMul(composerVec3(1, 0.86, 0.62), glints)),
        composerMul(composerVec3(0.55, 0.62, 0.66), composerMul(ripple, composerAdd(composerLight(), 0.3)))
    );

    const alpha = composerSaturate(composerAdd(composerMix(0.72, 0.96, fresnel), composerMul(foam, 0.3)));

    const vertex = composerVertexPosition();

    const wave = composerAdd(
        composerMul(composerSin(composerSub(composerMul(composerX(vertex), 2.3), composerMul(time, 2.2))), 0.01),
        composerMul(composerSin(composerSub(composerMul(composerZ(vertex), 3.1), composerMul(time, 1.1))), 0.008)
    );

    return compileShader({
        shader: 'mesh3d',
        color: composerVec4(colour, alpha),
        position: composerAdd(vertex, composerVec3(0, wave, 0))
    });
};
```

`shaders/snow.ts`:

```ts
import { compileShader, composerAdd, composerFbm, composerLight, composerMix, composerMul, composerSaturate, composerShine, composerSmoothstep, composerSub, composerSurface, composerSwizzle, composerUniform, composerVec3, composerVec4, composerWorldNormal, composerWorldPos, composerY, type TComposerNode } from 'nacatamalon/shader';

/**
 * The usual colour (surface × light + shine), or `lit` if given, with snow on top wherever a face
 * looks up. How much has settled is the material's `snow` knob: 0 none, 1 covered.
 */
export const snowyColor = (lit?: TComposerNode) => {
    const base = lit ?? composerAdd(composerMul(composerSwizzle(composerSurface(), 'rgb'), composerLight()), composerShine());
    const up = composerY(composerWorldNormal());
    const patchy = composerFbm(composerMul(composerSwizzle(composerWorldPos(), 'xz'), 2.6), 3);
    const amount = composerUniform('snow', 0);

    const cover = composerMul(
        composerSmoothstep(0.45, 0.8, composerAdd(up, composerMul(composerSub(patchy, 0.5), 0.5))),
        composerSmoothstep(0.0, 1.0, composerSub(composerMul(amount, 1.6), composerMul(composerSub(1, patchy), 0.6)))
    );

    const white = composerMul(composerVec3(0.9, 0.93, 1.0), composerAdd(composerMul(composerLight(), 0.95), 0.12));

    return composerVec4(composerMix(base, white, composerSaturate(cover)), 1);
};

/**
 * A `mesh3d` shader with nothing but the snow added, for materials that only need that.
 */
export const snowShader = () => compileShader({
    shader: 'mesh3d',
    color: snowyColor()
});
```

`shaders/vignette.ts`:

```ts
/**
 * A full-screen effect that darkens the corners, as a photo of a model does. `amount` is how much.
 */
export const VIGNETTE_WGSL = /* wgsl */ `
fn effect(color: vec4<f32>, uv: vec2<f32>) -> vec4<f32> {
    let d = distance(uv, vec2<f32>(0.5, 0.52)) * 1.35;
    let v = 1.0 - smoothstep(0.45, 1.05, d) * mu.amount;
    return vec4<f32>(color.rgb * v, color.a);
}
`;

export const VIGNETTE_GLSL = /* glsl */ `
vec4 effect(vec4 color, vec2 uv) {
    float d = distance(uv, vec2(0.5, 0.52)) * 1.35;
    float v = 1.0 - smoothstep(0.45, 1.05, d) * mu.amount;
    return vec4(color.rgb * v, color.a);
}
`;
```

`shaders/wind.ts`:

```ts
import { composerAdd, composerMul, composerPow, composerSimplexNoise, composerSin, composerSmoothstep, composerSub, composerVec2, composerX, composerZ, type TComposerNode } from 'nacatamalon/shader';
import { WIND } from '../settings';

/**
 * How hard the wind pushes at a point, from 0 to about 1: gusts that sweep the field like waves
 * (bands that travel the way the wind blows, broken up by noise), for the grass and the trees.
 * `along` is how far the point is in the wind's direction.
 */
export const windAt = (position: TComposerNode, time: TComposerNode) => {
    const along = composerAdd(composerMul(composerX(position), WIND.x), composerMul(composerZ(position), WIND.z));
    const across = composerSub(composerMul(composerZ(position), WIND.x), composerMul(composerX(position), WIND.z));

    // The gust's wave, travelling at about 1.6 units a second.
    const front = composerSub(composerMul(along, 0.9), composerMul(time, 1.45));
    const wave = composerPow(composerAdd(composerMul(composerSin(front), 0.5), 0.5), 3);

    // Not a straight line: noise cuts the bands into patches that travel with them.
    const patch = composerSimplexNoise(composerVec2(composerSub(composerMul(along, 0.28), composerMul(time, 0.4)), composerMul(across, 0.35)));

    return {
        gust: composerMul(wave, composerSmoothstep(0.25, 0.75, patch)),
        along
    };
};
```
