# Campfire

> A fire in a clearing at night: flames, sparks that bounce off the ground and smoke, a flickering light, and the moon throwing shadows.

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

**Move the mouse** to walk round the fire and **click** to throw on another log: a shower of sparks and a flare of light.

Three emitters (flames, sparks that bounce off the ground through a particle collider, and smoke), a point light whose intensity and reach flicker with a few waves out of step, logs whose emissive colour pulses, and the moon as the one light that casts shadows.

The logs you throw on exist from the start, hidden: a click happens outside the scene's body, where nothing can be created, so it only shows them.

## Code

`index.ts`:

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

const game = createGame('#app', {
    width: Settings.WIDTH,
    height: Settings.HEIGHT,
    background: '#05070f',
    msaa: 4
});

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

`components/clearing.ts`:

```ts
import { createMesh, getColor, useConeGeometry, useCylinderGeometry, useIcoSphereGeometry, usePlaneGeometry, useParticleCollider3d } from 'nacatamalon';
import { useRandom } from 'nacatamalon/math';

/**
 * Everything that stands still: the ground, a ring of stones, two logs to sit on and the trees.
 * The ground is also what the sparks bounce on, as a particle collider on the same object.
 */
export const Clearing = () => {
    // Seeded, so the forest is the same one every time.
    const random = useRandom();

    random.seed(7);

    createMesh({
        geometry: usePlaneGeometry({
            width: 40,
            depth: 40
        }),
        tint: '#3a4630',
        castShadow: false
    });
    useParticleCollider3d({
        shape: {
            kind: 'plane'
        }
    });

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

    for (let i = 0; i < 11; i++) {
        const a = (i / 11) * Math.PI * 2;

        createMesh({
            geometry: stone,
            tint: getColor(i % 2 ? '#6d6a66' : '#58564f'),
            transform: {
                x: Math.cos(a) * 0.72,
                y: 0.06,
                z: Math.sin(a) * 0.72,
                rotationY: a * 3,
                scaleY: 0.6
            },
        });
    }

    const bench = useCylinderGeometry({
        radius: 0.16,
        height: 1.6,
        segments: 10
    });

    for (const side of [-1, 1]) {
        createMesh({
            geometry: bench,
            tint: '#5a3b24',
            transform: {
                x: side * 2,
                y: 0.16,
                rotationX: Math.PI / 2
            },
        });
    }

    // Pines: a trunk and three cones, scattered round the edge of the light. They cast no shadow:
    // the moon's shadows cover a square IN FRONT of the camera, and a camera that walks round the
    // fire always has some of the forest behind it. What casts is what is in the middle.
    const trunk = useCylinderGeometry({
        radius: 0.12,
        height: 1,
        segments: 8
    });

    const cone = useConeGeometry({
        radius: 1,
        height: 1.6,
        segments: 10
    });

    for (let i = 0; i < 26; i++) {
        const a = random.rand(0, Math.PI * 2);
        const r = random.rand(5, 13);
        const x = Math.cos(a) * r;
        const z = Math.sin(a) * r;
        const s = random.rand(0.8, 1.6);

        createMesh({
            geometry: trunk,
            tint: '#3b2616',
            castShadow: false,
            transform: {
                x,
                y: 0.5 * s,
                z,
                scaleX: s,
                scaleY: s,
                scaleZ: s
            }
        });

        for (let k = 0; k < 3; k++) {
            createMesh({
                geometry: cone,
                tint: getColor(k === 2 ? '#2f5a37' : '#234a2c'),
                castShadow: false,
                transform: {
                    x,
                    y: (1.3 + k * 0.75) * s,
                    z,
                    scaleX: s * (1 - k * 0.22),
                    scaleY: s,
                    scaleZ: s * (1 - k * 0.22)
                },
            });
        }
    }
};
```

`components/fire.ts`:

```ts
import { createMesh, createParticles3d, emitParticles, useCylinderGeometry, useGame, useLoadParticles, usePointLight, usePointer, useUpdate, type TCamera3d, type TMesh } from 'nacatamalon';

/**
 * The fire: logs leaning together, glowing where they burn, three emitters (flames, sparks, smoke)
 * and a warm point light that never holds still. It also drives the camera, which walks round it.
 */
export const Fire = (camera: TCamera3d) => {
    const game = useGame();
    const pointer = usePointer();

    // The fire's own light, kept so the flicker below can move it.
    const light: ReturnType<typeof usePointLight> | null = usePointLight({
        color: '#ff9a3c',
        intensity: 1.6,
        range: 9,
        transform: {
            y: 0.7
        }
    });

    // Logs leaning into a cone. The glow is their emissive colour, pulsed from the update below.
    const log = useCylinderGeometry({
        radius: 0.07,
        height: 1.1,
        segments: 8
    });

    // Every log there will ever be is made now, the spare ones hidden: a click happens outside the
    // scene's body, where nothing can be created, so throwing one on only shows it.
    const logs: TMesh[] = [];

    for (let i = 0; i < 14; i++) {
        const turn = i < 5 ? (i / 5) * Math.PI * 2 : Math.random() * Math.PI * 2;
        const lean = i < 5 ? 0.55 : 0.8 + Math.random() * 0.5;

        logs.push(createMesh({
            geometry: log,
            tint: '#4a2d18',
            emissive: '#000000',
            visible: i < 5,
            transform: {
                x: Math.cos(turn) * 0.22,
                y: i < 5 ? 0.36 : 0.28,
                z: Math.sin(turn) * 0.22,
                rotationY: -turn,
                rotation: lean
            },
        }));
    }

    let burning = 5;

    createParticles3d({
        effect: useLoadParticles({
            src: '/example-assets/effects/campfire3d.particles'
        }),
        transform: {
            y: 0.15
        }
    });

    const sparks = createParticles3d({
        effect: useLoadParticles({
            src: '/example-assets/effects/embers3d.particles'
        }),
        transform: {
            y: 0.4
        }
    });

    createParticles3d({
        effect: useLoadParticles({
            src: '/example-assets/effects/smoke3d.particles'
        }),
        transform: {
            y: 1.3
        }
    });

    // A new log: a shower of sparks and a flare of light that dies down.
    let flare = 0;

    pointer.onDown(() => {
        if (burning < logs.length) {
            logs[burning++].visible = true;
        }

        emitParticles(sparks, 140);
        flare = 1;
    });

    let orbit = 0.6;
    let aim = orbit;

    pointer.onMove((info) => {
        aim = (info.screenX / game.getWidth() - 0.5) * Math.PI * 1.6;
    });

    let time = 0;

    useUpdate((delta) => {
        time += delta;
        flare = Math.max(0, flare - delta * 0.8);

        // Flicker: a few waves out of step add up to something that never quite repeats.
        const flicker = 0.75 + 0.12 * Math.sin(time * 11) + 0.08 * Math.sin(time * 23 + 1.3) + 0.05 * Math.sin(time * 37 + 2.1);

        if (light !== null) {
            light.intensity = 1.5 * flicker + flare * 2.2;
            light.range = 8 + flicker * 2 + flare * 4;
            light.transform.x = Math.sin(time * 7) * 0.05;
            light.transform.z = Math.cos(time * 5) * 0.05;
        }

        logs.forEach((mesh, i) => {
            const glow = (0.35 + 0.25 * Math.sin(time * 6 + i * 1.9)) * (flicker + flare);

            mesh.material.emissive = {
                r: glow,
                g: glow * 0.32,
                b: glow * 0.05,
                a: 1
            };
        });

        // The camera walks round the fire, and follows the mouse.
        orbit += (aim + time * 0.05 - orbit) * Math.min(1, delta * 1.5);
        camera.transform.x = Math.sin(orbit) * 5.2;
        camera.transform.z = Math.cos(orbit) * 5.2;
        camera.transform.y = 1.7;
        camera.transform.rotationY = orbit;
        camera.transform.rotationX = -0.22;
    });
};
```

`scenes/demo.ts`:

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

import { Clearing } from '../components/clearing';
import { Fire } from '../components/fire';

export const Night = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 50,
        near: 0.1,
        far: 80,
        transform: {
            x: 3.1,
            y: 1.7,
            z: 4.2,
            rotationY: 0.6,
            rotationX: -0.22
        }
    });

    // The moon: cold, dim, and the one light allowed to cast shadows. A point light cannot (it would
    // need six shadow maps, one per side of a cube), so the fire lights the scene and the moon draws
    // the long shadows across it.
    useDirectionalLight({
        color: '#9fb8ff',
        intensity: 0.6,
        ambient: 0.1,
        transform: {
            rotationX: -0.75,
            rotationY: 2.4
        },
        castShadow: true,
        shadowArea: 16,
        shadowDistance: 30,
    });

    useSpawn(Clearing)();
    useSpawn(Fire)(camera);

    return createScene();
};
```

`settings.ts`:

```ts
export const WIDTH = 480;
export const HEIGHT = 320;
```
