# Mode 7

> The floor of a 16-bit kart racer at the SNES's own 320×224: one flat track picture, turned and stretched per pixel by createMode7.

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

Drive with the **arrow keys**: the grass slows you down and the coins go round the track.

There is no 3D here. `createMode7({ texture, height, horizon, fov, outside, haze })` lays the track, one flat picture, on a sprite as large as the screen, and its material does the SNES's maths per pixel: each row below the horizon is a line of floor, further away the nearer it is to the horizon, turned by the camera's angle. The floor's camera is its `uniforms` (`x`, `y`, `angle`, `height`…), in pixels of the track, the same numbers the example reads to know whether the kart is on the grass.

Above the horizon nothing is drawn, so the sky is a `createBackdrop` behind it. Past the edge of the map it is grass (`outside`), and far away the floor fades into the `haze`.

The trees, the coins and the kart itself are ordinary sprites stood on the floor with `placeOnMode7`: placed, scaled by their distance, ordered by depth and hidden behind the camera. Every picture is drawn by the example on a canvas and loaded as a data URL: nothing to download.

## Code

`index.ts`:

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

const game = createGame('#app', {
    width: Settings.WIDTH,
    height: Settings.HEIGHT,
    background: '#000000',
    smooth: false
});

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

`art/paint.ts`:

```ts
import * as Settings from '../settings';

/** The track's middle line, going round once as t goes from 0 to 1, in map units (0 to 1). */
const centreLine = (t: number) => {
    const a = t * Math.PI * 2;
    const r = 0.33 + 0.07 * Math.sin(a * 2) + 0.035 * Math.cos(a * 3);

    return {
        x: 0.5 + Math.cos(a) * r,
        y: 0.5 + Math.sin(a) * r * 0.85
    };
};

/**
 * A point on the track at t, pushed sideways by offset (in map pixels), and the way the track runs
 * there. In the map's pixels, which is what the floor, the kart and everything on it are measured in.
 */
export const trackPoint = (t: number, offset: number) => {
    const p = centreLine(t);
    const q = centreLine(t + 0.001);
    const dx = q.x - p.x;
    const dy = q.y - p.y;
    const length = Math.hypot(dx, dy);

    return {
        x: p.x * Settings.SIZE - (dy / length) * offset,
        y: p.y * Settings.SIZE + (dx / length) * offset,
        angle: Math.atan2(dx, -dy)
    };
};

export type TrackMap = { canvas: HTMLCanvasElement; pixels: Uint8ClampedArray; };

export const drawTrack = (): TrackMap => {
    const canvas = document.createElement('canvas');

    canvas.width = canvas.height = Settings.SIZE;

    const g = canvas.getContext('2d')!;

    // Grass in checks. Past the map's edge the floor is plain grass (Settings.GRASS), the two greens'
    // middle, so the edge reads as the end of the mowing rather than of the world.
    for (let y = 0; y < 16; y++) {
        for (let x = 0; x < 16; x++) {
            g.fillStyle = (x + y) % 2 ? 'rgb(74,158,66)' : 'rgb(64,143,59)';
            g.fillRect(x * 32, y * 32, 32, 32);
        }
    }

    const path = () => {
        g.beginPath();

        for (let i = 0; i <= 256; i++) {
            const p = centreLine(i / 256);

            if (i === 0) {
                g.moveTo(p.x * Settings.SIZE, p.y * Settings.SIZE);
            } else {
                g.lineTo(p.x * Settings.SIZE, p.y * Settings.SIZE);
            }
        }

        g.closePath();
    };

    g.lineJoin = 'round';

    // Kerbs, red and white, then the tarmac on top leaving only their edges, then the middle line.
    path();
    g.lineWidth = 64;
    g.strokeStyle = '#ffffff';
    g.setLineDash([]);
    g.stroke();
    path();
    g.strokeStyle = '#d8262e';
    g.setLineDash([10, 10]);
    g.stroke();
    path();
    g.lineWidth = 52;
    g.strokeStyle = '#6f6f7c';
    g.setLineDash([]);
    g.stroke();
    path();
    g.lineWidth = 2;
    g.strokeStyle = '#c9c9d4';
    g.setLineDash([12, 14]);
    g.stroke();

    // A chequered start line across the track at t = 0.
    const s = trackPoint(0, 0);

    g.save();
    g.translate(s.x, s.y);
    g.rotate(s.angle);

    for (let i = 0; i < 13; i++) {
        for (let j = 0; j < 2; j++) {
            g.fillStyle = (i + j) % 2 ? '#111' : '#fff';
            g.fillRect(-26 + i * 4, -4 + j * 4, 4, 4);
        }
    }

    g.restore();

    return {
        canvas,
        pixels: g.getImageData(0, 0, Settings.SIZE, Settings.SIZE).data
    };
};

/** Whether a point of the map, in its pixels, is tarmac or kerb, with a margin of grass around it counted too. */
export const onTrack = (map: TrackMap, x: number, y: number, margin: number): boolean => {
    const check = (px: number, py: number) => {
        if (px < 0 || px >= Settings.SIZE || py < 0 || py >= Settings.SIZE) {
            return false;
        }

        const i = (Math.floor(py) * Settings.SIZE + Math.floor(px)) * 4;

        // Grass is the only thing on this map that is clearly green.
        return !(map.pixels[i + 1] > map.pixels[i] + 40 && map.pixels[i + 1] > map.pixels[i + 2] + 40);
    };

    if (margin === 0) {
        return check(x, y);
    }

    for (let a = 0; a < 8; a++) {
        if (check(x + Math.cos(a) * margin, y + Math.sin(a) * margin)) {
            return true;
        }
    }

    return check(x, y);
};

/** Paints a small picture from rows of letters, one letter a pixel. */
const pixelArt = (rows: string[], colors: Record<string, string>): HTMLCanvasElement => {
    const canvas = document.createElement('canvas');

    canvas.width = rows[0].length;
    canvas.height = rows.length;

    const g = canvas.getContext('2d')!;

    rows.forEach((row, y) => [...row].forEach((c, x) => {
        if (colors[c]) {
            g.fillStyle = colors[c];
            g.fillRect(x, y, 1, 1);
        }
    }));

    return canvas;
};

export const drawKart = () => pixelArt(['.......rrrrrrrrrr.......', '......rRRRRRRRRRRr......', '.....rRRRkkkkkkRRRr.....', '.....rRRkssssssskRr.....', '.....rRRkssssssskRr.....', '..kkkrRRRRRRRRRRRRrkkk..', '.kkkkrrRRRRRRRRRRrrkkkk.', '.kggkwwwwwwwwwwwwwwkggk.', '.kggkrRRRRRRRRRRRRrkggk.', '.kkkkrrrrrrrrrrrrrrkkkk.', '..kk...yy......yy...kk..', '........................',], {
    r: '#8c1119',
    R: '#e0303a',
    k: '#1a1a22',
    s: '#ffd3a8',
    w: '#ffffff',
    g: '#55555f',
    y: '#ffe45c'
});

export const drawTree = () => pixelArt(['.....gg.....', '....gGGg....', '...gGGGGg...', '...gGGgGg...', '..gGGGGGGg..', '..gGgGGGGg..', '.gGGGGGgGGg.', '.gGGGGGGGGg.', 'gGGgGGGGGGGg', 'gggggggggggg', '.....bb.....', '.....bb.....', '.....bb.....',], {
    g: '#1d5a2a',
    G: '#2f8a3e',
    b: '#6b3f1f'
});

export const drawCoin = () => pixelArt(['..yyyy..', '.yYYYYy.', 'yYYwYYYy', 'yYwYYYYy', 'yYwYYYYy', 'yYYYYYYy', '.yYYYYy.', '..yyyy..',], {
    y: '#b0700c',
    Y: '#ffd23c',
    w: '#fff7c0'
});

/**
 * The sky above the horizon, as tall as the horizon is low: blue going pale towards the ground, and
 * a range of hills along the bottom. Made to repeat across, since a backdrop lays it end to end and
 * slides it as the camera turns.
 */
export const drawSky = (): HTMLCanvasElement => {
    const canvas = document.createElement('canvas');

    canvas.width = Settings.SKY_WIDTH;
    canvas.height = Settings.HORIZON;

    const g = canvas.getContext('2d')!;
    const sky = g.createLinearGradient(0, 0, 0, Settings.HORIZON);

    sky.addColorStop(0, '#2e5cdb');
    sky.addColorStop(1, '#9ed1ff');
    g.fillStyle = sky;
    g.fillRect(0, 0, Settings.SKY_WIDTH, Settings.HORIZON);

    // Whole waves across the picture, so its two ends meet without a seam.
    for (let x = 0; x < Settings.SKY_WIDTH; x++) {
        const t = (x / Settings.SKY_WIDTH) * Math.PI * 2;
        const hill = 11 + 5.6 * Math.sin(t * 2) + 3.4 * Math.sin(t * 6 + 1.3) + 1.8 * Math.sin(t * 15);

        for (let band = 0; band < 4; band++) {
            g.fillStyle = ['#29694c', '#34785a', '#3f8763', '#4c946b'][band];
            g.fillRect(x, Settings.HORIZON - hill + (hill * band) / 4, 1, Math.ceil(hill / 4) + 1);
        }
    }

    return canvas;
};
```

`components/race.ts`:

```ts
import * as Settings from '../settings';
import { createBackdrop, createMode7, createSprite, createText, mode7ToScreen, placeOnMode7, useKeyboard, useLoadBitmapFont, useLoadTexture, useUpdate, type TSprite } from 'nacatamalon';
import { drawTrack, drawKart, drawTree, drawCoin, drawSky, onTrack, trackPoint } from '../art/paint';

export const Race = () => {
    const keys = useKeyboard();

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

    // Every picture here is drawn by the example on a 2D canvas and handed over as a data URL, so
    // there is nothing to download and the track can be changed by editing art.ts.
    const map = drawTrack();

    const track = useLoadTexture({
        src: map.canvas.toDataURL(),
        key: 'mode7-track'
    });

    const kartPicture = useLoadTexture({
        src: drawKart().toDataURL(),
        key: 'mode7-kart'
    });

    const treePicture = useLoadTexture({
        src: drawTree().toDataURL(),
        key: 'mode7-tree'
    });

    const coinPicture = useLoadTexture({
        src: drawCoin().toDataURL(),
        key: 'mode7-coin'
    });

    const skyPicture = useLoadTexture({
        src: drawSky().toDataURL(),
        key: 'mode7-sky'
    });

    // The sky: one picture laid end to end above the horizon, which the floor leaves empty. It does
    // not follow any camera; it slides sideways as the kart turns, a whole picture per turn.
    const sky = createBackdrop({
        texture: skyPicture,
        parallax: {
            x: 0,
            y: 0
        },
        y: 0
    });

    // The floor. Its camera is its uniforms, in pixels of the track picture.
    const floor = createMode7({
        texture: track,
        height: Settings.CAMERA_HEIGHT,
        horizon: Settings.HORIZON,
        fov: Settings.FOV,
        outside: Settings.GRASS,
        haze: Settings.HAZE
    });

    // Things standing on the floor: trees on the grass around the track, coins on it. Each sprite is
    // as large as it is on the map, and stands on its feet.
    type Prop = { x: number; y: number; size: number; sprite: TSprite; coin: boolean; };

    const props: Prop[] = [];

    const place = (x: number, y: number, size: number, coin: boolean) => {
        const sprite = createSprite({
            texture: coin ? coinPicture : treePicture,
            width: size,
            height: size,
            anchor: {
                x: 0.5,
                y: 1
            },
            visible: false
        });

        props.push({
            x,
            y,
            size,
            sprite,
            coin
        });
    };

    for (let i = 0; i < 44; i++) {
        // Scattered, but never on the track itself.
        let x: number;
        let y: number;

        do {
            x = Math.random() * Settings.SIZE;
            y = Math.random() * Settings.SIZE;
        } while (onTrack(map, x, y, 20));
        place(x, y, 26 + Math.random() * 15, false);
    }

    for (let i = 0; i < 24; i++) {
        const p = trackPoint((i + 0.5) / 24, Math.sin(i * 1.7) * 13);

        place(p.x, p.y, 8, true);
    }

    const start = trackPoint(0, 0);

    const kart = {
        x: start.x,
        y: start.y,
        angle: start.angle,
        speed: 0,
        steer: 0,
        bumped: false
    };

    // The player's kart stands on the floor like the rest, at its own place on the map: drawn where
    // it really is, and in front of or behind a tree as it really is.
    const kartSprite = createSprite({
        texture: kartPicture,
        width: Settings.KART.width,
        height: Settings.KART.height,
        anchor: {
            x: 0.5,
            y: 1
        }
    });

    let coins = 0;

    const hud = createText({
        text: '',
        font,
        tint: '#ffe45c',
        transform: {
            x: 8,
            y: 8
        },
        zIndex: 1
    });

    let time = 0;

    const view = floor.uniforms;

    view.angle = kart.angle;

    useUpdate((delta) => {
        time += delta;

        // Driving.
        const grass = !onTrack(map, kart.x, kart.y, 0);
        const top = grass ? Settings.GRASS_SPEED : Settings.TOP_SPEED;

        if (keys.isDown('ArrowUp')) {
            // Up to the top speed and no further; over it (just onto the grass) it slows down below.
            if (kart.speed < top) {
                kart.speed = Math.min(top, kart.speed + 150 * delta);
            }
        } else if (keys.isDown('ArrowDown')) {
            kart.speed -= 250 * delta;
        } else {
            kart.speed -= 60 * delta;
        }

        if (kart.speed > top) {
            kart.speed += (top - kart.speed) * Math.min(1, delta * 4);
        }

        kart.speed = Math.max(0, kart.speed);

        const steer = (keys.isDown('ArrowRight') ? 1 : 0) - (keys.isDown('ArrowLeft') ? 1 : 0);

        kart.steer += (steer - kart.steer) * Math.min(1, delta * 8);
        kart.angle += kart.steer * delta * 2.2 * Math.min(1, kart.speed / 50);
        kart.x += Math.sin(kart.angle) * kart.speed * delta;
        kart.y -= Math.cos(kart.angle) * kart.speed * delta;

        // Trees are solid: driven into, the kart is put back outside the trunk. The bump slows it once;
        // while it keeps pressing it goes slowly and slides round the trunk, so it can steer away.
        let touching = false;

        for (const prop of props) {
            if (prop.coin) {
                continue;
            }

            const dx = kart.x - prop.x;
            const dy = kart.y - prop.y;
            const away = Math.hypot(dx, dy);
            const reach = prop.size * Settings.TRUNK + Settings.KART.width / 2;

            if (away < reach && away > 0) {
                kart.x = prop.x + (dx / away) * reach;
                kart.y = prop.y + (dy / away) * reach;
                touching = true;
            }
        }

        if (touching) {
            kart.speed = kart.bumped ? Math.min(kart.speed, Settings.SLIDE_SPEED) : kart.speed * 0.3;
        }

        kart.bumped = touching;

        // The camera rides behind, and lags a little in the turns, which is what sells the drift.
        view.angle += (kart.angle - view.angle) * Math.min(1, delta * 6);
        view.x = kart.x - Math.sin(view.angle) * Settings.BEHIND;
        view.y = kart.y + Math.cos(view.angle) * Settings.BEHIND;

        // The sky turns with the camera, far slower than the floor: a whole picture for a whole turn.
        // Turning right slides the hills left, the pattern starting further into the picture.
        sky.tileOffset = {
            x: (view.angle / (Math.PI * 2)) * Settings.SKY_WIDTH,
            y: 0
        };

        // The kart where it is, leaning into the turn and shaking on the grass.
        placeOnMode7(floor, kartSprite, kart.x, kart.y);
        kartSprite.transform.rotation = kart.steer * 0.12;
        kartSprite.transform.y += grass && kart.speed > 10 ? Math.sin(time * 60) : Math.sin(time * 18) * 0.4;

        for (const prop of props) {
            if (prop.coin && Math.hypot(prop.x - kart.x, prop.y - kart.y) < 10) {
                // Collected: gone, and back somewhere else on the track a while later.
                coins++;

                const p = trackPoint(Math.random(), (Math.random() - 0.5) * 26);

                prop.x = p.x;
                prop.y = p.y;
            }

            // Coins spin by narrowing; the floor does the rest: where, how large, which in front.
            if (prop.coin) {
                prop.sprite.width = prop.size * (Math.abs(Math.cos(time * 4 + prop.x / 25)) + 0.1);
            }

            // Too near the camera, it would fill the screen: left out until the camera is past it.
            const at = mode7ToScreen(floor, prop.x, prop.y);

            if (at === null || at.depth < Settings.NEAREST) {
                prop.sprite.visible = false;
                continue;
            }

            placeOnMode7(floor, prop.sprite, prop.x, prop.y);
        }

        hud.text = 'COINS ' + coins + '   ' + Math.round(kart.speed) + ' KMH';
    });
};
```

`scenes/demo.ts`:

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

import { Race } from '../components/race';

export const Track = () => {
    useSpawn(Race)();

    return createScene();
};

// 320 x 224 is the SNES's own screen, and smooth: false keeps its pixels square and hard.
```

`settings.ts`:

```ts
export const WIDTH = 320;
export const HEIGHT = 224;
// Every picture of the example, drawn on 2D canvases. The track is also READ back on the CPU, to
// know whether the kart is on the tarmac or on the grass. Every distance is in pixels of it, SIZE
// across: the camera's height, how far behind the kart it rides, the speeds and where things stand.
export const SIZE = 512;

// The camera. These numbers are the whole look: how high above the floor, the row of the screen
// the horizon sits on, and how wide the view opens, in degrees.
export const CAMERA_HEIGHT = 34;
export const HORIZON = 76;
export const FOV = 60;
export const BEHIND = 69;
// how far behind the kart the camera rides: with the three above, what puts the kart near the
// bottom of the screen, drawn four times its size on the map (64 x 32)

// The kart's size on the map. It is stood on the floor like everything else, so it is drawn exactly
// where it is: on the grass when it is on the grass.
export const KART = {
    width: 16,
    height: 8
};

// Nothing is drawn nearer the camera than this, just short of the kart (BEHIND): a tree between the
// camera and the kart would otherwise hide the kart, or fill the screen as the camera passes it.
export const NEAREST = 60;

// How much of a tree's size is its trunk, which the kart bumps into, and how fast it slides round
// one while it keeps pressing.
export const TRUNK = 0.2;
export const SLIDE_SPEED = 40;

export const TOP_SPEED = 174;
// map pixels per second
export const GRASS_SPEED = 61;

// Past the edge of the map it is grass, and far away everything fades into the haze, which also
// hides the shimmer of hard pixels that far off (the SNES left it in).
export const GRASS = '#47963f';
export const HAZE = {
    color: '#9ed1ff',
    from: 300,
    to: 1500
};

// How wide the sky picture is, and so how far the hills go before they come round again.
export const SKY_WIDTH = 512;
```
