# Scene transitions

> fade, wipe, iris and pixelate on scene.change: the shader is the easy half, the lifecycle is the rest.

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

`scene.change(name, { transition: fade(0.3) })`: one more option on the call that was already there, and without it the change is the hard cut it has always been. **Click** to walk between two rooms, cycling through the built-ins.

The shader is the easy half. What the engine has to own is that the incoming scene **exists without being seen, updated or clicked on** until the screen is covered, and that the swap waits for whichever of the cover and the load finishes last. So a transition hides the cut and hides the load, which is what a black screen between two levels was always for.

`launch` and `stop` take a transition too. **MENU** opens a menu on top with an iris, over a room that paused itself first (the scene underneath keeps running unless the game pauses it), and a click on the menu closes it with another.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { WIDTH, HEIGHT } from './settings';
import { makeRoom } from './scenes/room';
import { makeMenu } from './scenes/menu';
import type { TSelection } from './state/selection';

const state: TSelection = {
    pick: 0,
    under: null
};

const RoomA = makeRoom(state, 0);
const RoomB = makeRoom(state, 1);
const Menu = makeMenu(state);

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

// Declare Scenes
game({
    RoomA,
    RoomB,
    Menu
}, 'RoomA');
```

`art/masks.ts`:

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

export const starMask = (w: number, h: number) => {
    const pixels = createPixels(w, h);

    const reach = (x: number, y: number) => {
        const dx = x - w / 2;
        const dy = y - h / 2;
        const angle = Math.atan2(dy, dx) + Math.PI / 2;
        const point = (Math.cos(angle * 5) + 1) / 2;

        return Math.hypot(dx, dy) / (0.55 + 0.45 * point * point);
    };

    const far = Math.max(reach(0, 0), reach(w - 1, 0), reach(0, h - 1), reach(w - 1, h - 1));

    return mapPixels(pixels, (_, x, y) => {
        const grey = 1 - reach(x, y) / far;

        return {
            r: grey,
            g: grey,
            b: grey,
            a: 1
        };
    });
};
```

`scenes/menu.ts`:

```ts
import { createScene, createSprite, createText, useCleanup, useLoadBitmapFont, usePointer, useScene } from 'nacatamalon';

import { iris } from 'nacatamalon/transitions';
import type { TSelection } from '../state/selection';
import { WIDTH, HEIGHT, ARCADE, LABEL } from '../settings';

export const makeMenu = (state: TSelection) => () => {
    const font = useLoadBitmapFont(ARCADE);
    const scene = useScene();
    let closing = false;

    createSprite({
        anchor: {
            x: 0.5,
            y: 0.5
        },
        transform: {
            x: WIDTH / 2,
            y: HEIGHT / 2
        },
        width: 220,
        height: 110,
        tint: '#0b0f18',
    });
    createText({
        text: 'MENU',
        font,
        style: {
            fontSize: 16
        },
        tint: LABEL,
        anchor: {
            x: 0.5,
            y: 0.5
        },
        transform: {
            x: WIDTH / 2,
            y: HEIGHT / 2 - 18
        }
    });
    createText({
        text: 'CLICK TO GO BACK',
        font,
        style: {
            fontSize: 8
        },
        tint: LABEL,
        anchor: {
            x: 0.5,
            y: 0.5
        },
        transform: {
            x: WIDTH / 2,
            y: HEIGHT / 2 + 20
        }
    });

    usePointer().onDown(() => {
        if (closing) {
            return;
        }

        closing = true;
        scene.stop({
            transition: iris(0.4)
        });
    });
    // At the swap, behind the cover: the room wakes up as the iris opens on it.
    useCleanup(() => {
        if (state.under !== null) {
            scene.resume(state.under);
        }

        state.under = null;
    });

    return createScene();
};
```

`scenes/room.ts`:

```ts
import { createScene, createSprite, createText, getColor, useLoadBitmapFont, usePointer, useScene } from 'nacatamalon';
import { createPixels, createPixelTexture, fillNoise } from 'nacatamalon/pixels';
import { iris } from 'nacatamalon/transitions';
import type { TSelection } from '../state/selection';
import { WIDTH, HEIGHT, ARCADE, LABEL, ROOMS, TRANSITIONS } from '../settings';
import { starMask } from '../art/masks';

export const makeRoom = (state: TSelection, index: number) => () => {
    const room = ROOMS[index];
    const font = useLoadBitmapFont(ARCADE);
    const scene = useScene();

    const masks = {
        grain: createPixelTexture(fillNoise(createPixels(120, 68), {
            seed: 4,
            scale: 3
        }), {
            key: 'grain'
        }),
        star: createPixelTexture(starMask(96, 54), {
            key: 'star'
        }),
    };

    createSprite({
        anchor: {
            x: 0,
            y: 0
        },
        transform: {
            x: 0,
            y: 0
        },
        width: WIDTH,
        height: HEIGHT,
        tint: getColor(room.bg),
    });

    // A grid, so a wipe's edge and an iris's circle have something to travel across.
    for (let y = 0; y < 4; y++) {
        for (let x = 0; x < 7; x++) {
            createSprite({
                anchor: {
                    x: 0,
                    y: 0
                },
                transform: {
                    x: 24 + x * 64,
                    y: 60 + y * 48
                },
                width: 48,
                height: 32,
                tint: getColor(room.block),
            });
        }
    }

    createText({
        text: room.label,
        font,
        style: {
            fontSize: 16
        },
        tint: LABEL,
        transform: {
            x: 24,
            y: 20
        }
    });

    const hint = createText({
        text: 'CLICK: ' + TRANSITIONS[state.pick].label,
        font,
        style: {
            fontSize: 8
        },
        tint: LABEL,
        transform: {
            x: 24,
            y: 240
        },
    });

    const menuButton = createSprite({
        anchor: {
            x: 0,
            y: 0
        },
        transform: {
            x: 384,
            y: 14
        },
        width: 72,
        height: 24,
        tint: '#0b0f18',
    });

    createText({
        text: 'MENU',
        font,
        style: {
            fontSize: 8
        },
        tint: LABEL,
        transform: {
            x: 404,
            y: 22
        }
    });

    usePointer().onDown((info) => {
        if (state.under !== null) {
            return;
        }

        if (info.hits.includes(menuButton)) {
            state.under = room.name;
            scene.pause();
            scene.launch('Menu', {
                transition: iris(0.4)
            });

            return;
        }

        const chosen = TRANSITIONS[state.pick];

        state.pick = (state.pick + 1) % TRANSITIONS.length;
        hint.text = 'CLICK: ' + TRANSITIONS[state.pick].label;

        const transition = chosen.make(masks);

        // No transition = the hard cut change() has always done. Same call, one option.
        if (transition) {
            scene.change(room.next, {
                transition: transition
            });
        } else {
            scene.change(room.next);
        }
    });

    return createScene();
};
```

`settings.ts`:

```ts
import { getColor } from 'nacatamalon';

import { dissolve, fade, iris, pixelate, wipe } from 'nacatamalon/transitions';
import type { TTexture } from 'nacatamalon';

// Scene transitions: cover the screen, swap the scenes underneath, uncover.
//
// The shader is the easy half. The half the engine has to own is the LIFECYCLE, and it
// is why a game cannot build this out of usePostProcess alone:
//
//  1. change() has always overlapped the two scenes: the new one starts and the old one
//     leaves in the same breath. Spread that over a 0.3 s fade and it would be the new
//     room drawn underneath the old one for the whole cover. So the incoming scene is
//     HELD: it exists, and its loading has already started, but it neither draws nor
//     updates nor answers the pointer until the swap.
//  2. Not updating matters as much as not drawing. A scene ticking behind a cover arrives
//     at its first visible frame already several frames old, with its character having
//     walked on its own.
//  3. The swap waits for whichever of the COVER and the LOAD finishes last. That is what
//     makes a transition pay for itself twice: it hides the cut and it hides the load,
//     which is what a black screen between two levels has always been for.
//
// Both halves run progress 0 -> 1, with phase saying which is which. A wipe has to leave
// the way it came in; running the second half backwards would play it in mirror image.
//
// launch() and stop() take a transition too: the MENU button opens a menu on top with an
// iris, and a click on the menu closes it with another. The room underneath keeps running
// unless it is paused, which is the game's call, so the room pauses itself first.
//
// And the transition runs FIRST in the post chain, ahead of anything the game put there.
// A fade is something happening in the game; everything after it is the console showing
// the result. So on a game that cuts its colours down, its fades are cut down too, which
// is exactly how they looked on the hardware this is aimed at.
//
// dissolve() covers in the shape of a picture: its greys are the order, darkest first.
// Noise eats the screen grain by grain; a star painted dark outside and light in the
// middle closes on the middle as a star. The pictures are painted in code, given a key
// so both rooms share them. The Transition Masks example has more shapes.

export const WIDTH = 480;
export const HEIGHT = 270;
export const ARCADE = {
    json: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.json',
    atlas: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.png'
};
export const LABEL = getColor('#f2f6fa');
export const ROOMS = [
    {
        name: 'RoomA',
        next: 'RoomB',
        bg: '#1d2b4d',
        block: '#5f8fd8',
        label: 'ROOM A'
    },
    {
        name: 'RoomB',
        next: 'RoomA',
        bg: '#4d2b1d',
        block: '#d8905f',
        label: 'ROOM B'
    },
];
export const TRANSITIONS = [
    {
        label: 'FADE 0.3',
        make: () => fade(0.3)
    },
    {
        label: 'WIPE RIGHT 0.3',
        make: () => wipe(0.3, 'right')
    },
    {
        label: 'WIPE UP 0.3',
        make: () => wipe(0.3, 'up')
    },
    {
        label: 'IRIS 0.4',
        make: () => iris(0.4)
    },
    {
        label: 'IRIS 0.4 OFF CENTRE',
        make: () => iris(0.4, undefined, {
            x: 0.2,
            y: 0.75
        })
    },
    {
        label: 'PIXELATE 0.4',
        make: () => pixelate(0.4)
    },
    {
        label: 'DISSOLVE GRAIN 0.8',
        make: (masks: { grain: TTexture; star: TTexture ;}) => dissolve(0.8, masks.grain)
    },
    {
        label: 'DISSOLVE STAR 0.6',
        make: (masks: { grain: TTexture; star: TTexture ;}) => dissolve(0.6, masks.star, {
            softness: 0.04
        })
    },
    {
        label: 'NO TRANSITION (hard cut)',
        make: () => null
    },
];
```

`state/selection.ts`:

```ts
export type TSelection = { pick: number; under: string | null; };
```
