# Flatwood

> A creature animated by hand in one .glb with eleven bones and four movements. Three loop; the fourth ends, and onEnd is told when it gets there.

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

A creature rigged and animated by hand, arriving as a single `.glb` with eleven bones and four movements in it. Three of them go round for ever. The fourth does not, and that is what this example is about. **Click the game, then press 1, 2 or 3 to change gait, space to drop it.**

A looping movement never needs to report anything: it is always in the middle of itself. A movement that finishes does. Its clip says it once, in `clips`: `Death: { loop: false, next: 'Idle' }` runs to its end, stops there and is followed by Idle, and `onEnd` is told once when it arrives: a hit, a death, a door opening. The file has nowhere to say any of it, so it is said here.

The end is not the only moment worth knowing about. A clip's `events` mark instants inside a movement and `onEvent` is told as the movement passes them: here, the two instants in each gait where a foot meets the ground. A mark is passed **once per lap whatever the frame rate**, so a frame long enough to step clean over one still counts it.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { Level } from './scenes/demo';
import { WIDTH, HEIGHT } from './settings';

const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    background: '#0a0d14'
});

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

`components/creature.ts`:

```ts
import { createModel, createText, useKeyboard, useLoadBitmapFont, useLoadModel, useSkeletalAnimation, useUpdate } from 'nacatamalon';
import { CLIPS } from '../data/clips';

export const Creature = () => {
    const font = useLoadBitmapFont({
        json: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.json',
        atlas: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.png',
    });

    const creature = useLoadModel({
        src: '/example-assets/assets/3d/gltf/nightcrawler/nightcrawler.glb'
    });

    const model = createModel({
        model: creature,
        tint: '#aecde2',
        specular: '#5a6e87',
        shininess: 28,
    });

    const moves = useSkeletalAnimation(model, {
        play: 'Idle',
        fade: 0.25,
        clips: CLIPS
    });

    // Text sits in front of the model with no camera of its own: a scene with no 2D camera measures
    // its flat half in screen pixels, which is what a readout wants.
    const label = createText({
        text: '',
        font,
        style: {
            fontSize: 16
        },
        tint: '#aecde2',
        transform: {
            x: 16,
            y: 14
        },
        zIndex: 10
    });

    const kind = createText({
        text: '',
        font,
        style: {
            fontSize: 8
        },
        tint: '#5a7288',
        transform: {
            x: 16,
            y: 38
        },
        zIndex: 10
    });

    const feet = createText({
        text: '',
        font,
        style: {
            fontSize: 8
        },
        tint: '#7fd4a8',
        transform: {
            x: 16,
            y: 56
        },
        zIndex: 10
    });

    const notice = createText({
        text: '',
        font,
        style: {
            fontSize: 8
        },
        tint: '#ffd166',
        transform: {
            x: 16,
            y: 74
        },
        zIndex: 10,
        visible: false
    });

    createText({
        text: '1 Idle  2 Walk  3 Run  Space Death',
        font,
        style: {
            fontSize: 8
        },
        tint: '#44586c',
        transform: {
            x: 16,
            y: 334
        },
        zIndex: 10
    });

    // How much longer the notice stays up. Counted down in seconds, not in frames, so it lasts the
    // same on a slow machine as on a fast one.
    let showing = 0;

    // Counted here and nowhere else. A footstep is a cue, not a consequence: the movement says when
    // a foot lands, and what that means, a sound or a puff of dust, is the game's to decide.
    let steps = 0;

    moves.onEvent((foot) => {
        steps += 1;
        feet.text = 'footsteps ' + steps + ' ' + foot;
    });

    // Idle comes after it by itself: this only says it happened.
    moves.onEnd((clip) => {
        notice.text = 'onEnd told us ' + clip + ' finished';
        notice.visible = true;
        showing = 2;
    });

    const keys = useKeyboard();

    useUpdate((delta) => {
        // Turning all of it at once, so the gait reads from every side. The bones move it from the
        // inside, this moves the whole of it, and the two never meet.
        model.transform.rotationY += delta * 0.5;

        // justPressed, not isDown: play starts a movement from its beginning, so a held key would
        // restart it sixty times a second and the creature would stand frozen on its first frame.
        if (keys.justPressed('1')) {
            moves.play('Idle');
        }

        if (keys.justPressed('2')) {
            moves.play('Walk');
        }

        if (keys.justPressed('3')) {
            moves.play('Run');
        }

        if (keys.justPressed(' ')) {
            moves.play('Death');
        }

        // Read back off the player rather than remembered alongside it. There are two things that
        // change the movement here, a key and the listener, and a copy kept by hand would be wrong
        // every time the other one won.
        label.text = moves.clip ?? '';
        kind.text = moves.clip === 'Death' && CLIPS.Death.loop === false
            ? 'plays once and reports when it is done'
            : 'loops for ever and reports nothing';

        if (showing > 0) {
            showing -= delta;

            if (showing <= 0) {
                notice.visible = false;
            }
        }
    });
};
```

`data/clips.ts`:

```ts
// Eleven bones, four movements, and one of the four ends: Death is not a loop. That difference is
// the whole example. Idle, Walk and Run go round for ever and nobody has to be told anything; a
// movement that finishes has to say so, or the creature is left face down waiting for a key.
//
// clips says, once for each movement, how it plays. Death runs to its end, stops there, and is
// followed by Idle, which stands the creature back up. onEnd is told when it gets there, once: here
// it puts a line on screen so you can see the moment it was told.
//
// The end is not the only moment worth knowing about. A clip's events mark instants inside it, and
// onEvent is told as the movement passes them: here, the two instants in each gait where a foot
// meets the ground. Marked once per lap however the frames fall, so the count is right whether the
// machine is keeping up or not.
//
// Press 1, 2 or 3 to change gait. Press space to drop it.

// How each movement plays, said here because the file does not say: whether something loops, and
// what comes after it, is a decision about the game, not a fact about the animation. Idle says
// nothing of its own, so it goes round for ever, as the animator does.
//
// The footsteps are when each foot is on the floor, in seconds into the movement. Measured off the
// movements themselves rather than guessed: a footstep half a beat out is worse than no footstep.
// Idle has none because standing still has no footsteps, which is the point of naming them per
// movement.
export const CLIPS = {
    Walk: {
        events: [
            {
                at: 0.11,
                name: 'left'
            },
            {
                at: 0.76,
                name: 'right'
            }
        ]
    },
    Run: {
        events: [
            {
                at: 0.18,
                name: 'left'
            },
            {
                at: 0.6,
                name: 'right'
            }
        ]
    },
    Death: {
        loop: false,
        next: 'Idle'
    },
};
```

`scenes/demo.ts`:

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

import { Creature } from '../components/creature';

export const Level = () => {
    useCamera3d({
        projection: 'perspective',
        fov: 45,
        transform: {
            y: 2.3,
            z: 4.6,
            rotationX: -0.26
        }
    });
    useDirectionalLight({
        color: '#dfeaff',
        intensity: 1.15,
        ambient: 0.28,
        transform: {
            rotationX: -0.55,
            rotationY: 0.6
        }
    });

    createMesh({
        geometry: usePlaneGeometry({
            width: 40,
            depth: 40
        }),
        tint: '#2b3244'
    });

    useSpawn(Creature)();

    return createScene();
};
```

`settings.ts`:

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