# Warp tunnel

> The demoscene classic: a wireframe tube that bends and cycles through the rainbow, and 700 stars that stretch into streaks at warp speed.

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

**Move the mouse** to steer, **hold the button** (or space) to jump, and press **P** to switch the screen between clean, eight levels a channel with dither (a Mega Drive) and the NES palette.

Everything is one `useLines` buffer rewritten each frame. The camera never moves forward: the world comes to it and is recycled at the far end, so the numbers never grow.

The jump is mostly the field of view widening, and the three looks are the engine's own post chain (`dither` and `paletteMatch`).

## Code

`index.ts`:

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

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

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

`components/flight.ts`:

```ts
import * as Settings from '../settings';
import { useGame, setLines, useLines, useKeyboard, usePointer, useUpdate, type TCamera3d } from 'nacatamalon';
import { dither, paletteMatch, useLoadPalette, usePostProcess, POST_EFFECTS } from 'nacatamalon/effects';
import { tunnelCentre, writeTunnel } from '../geometry/tunnel';

/**
 * The flight: everything in front of the camera comes towards it, and whatever passes it is sent
 * back to the far end. The camera never moves forward, so nothing ever runs out of numbers.
 *
 * Stars and tunnel go into one buffer of lines, written again every frame: seven numbers a corner
 * (x, y, z, r, g, b, a), two corners a line.
 */
export const Flight = (camera: TCamera3d) => {
    const game = useGame();
    const keys = useKeyboard();
    const pointer = usePointer();
    const lines = useLines();

    // Three looks for the same frame. Installed once and switched, which keeps their order fixed.
    const nes = useLoadPalette({
        src: '/example-assets/palettes/nes.palette'
    });

    const looks = [
        {
            name: 'clean',
            effects: [] as { enabled: boolean; }[]
        },
        {
            name: 'genesis',
            effects: [
                usePostProcess({
                    ...dither({
                        levels: POST_EFFECTS.COLOR_LEVELS.genesis
                    }),
                    enabled: false
                })
            ]
        },
        {
            name: 'nes',
            effects: [
                usePostProcess({
                    ...paletteMatch({
                        dither: 0.6
                    }),
                    palette: nes,
                    enabled: false
                })
            ]
        },
    ];

    let look = 0;

    let speed = Settings.CRUISE;
    let travelled = 0;
    let time = 0;

    const sx = new Float32Array(Settings.STARS);
    const sy = new Float32Array(Settings.STARS);
    const sz = new Float32Array(Settings.STARS);

    const reset = (i: number, z: number) => {
        // Anywhere on a disc around the tunnel's centre at that depth, so the stars fill the tube.
        const angle = Math.random() * Math.PI * 2;
        const radius = 0.6 + Math.random() * 5.5;
        const centre = tunnelCentre(z, travelled);

        sx[i] = centre.x + Math.cos(angle) * radius;
        sy[i] = centre.y + Math.sin(angle) * radius;
        sz[i] = z;
    };

    for (let i = 0; i < Settings.STARS; i++) {
        reset(i, -Math.random() * Settings.DEPTH);
    }

    let aimX = 0;
    let aimY = 0;
    let holding = false;

    pointer.onMove((info) => {
        aimX = info.screenX / game.getWidth() * 2 - 1;
        aimY = info.screenY / game.getHeight() * 2 - 1;
    });
    pointer.onDown(() => {
        holding = true;
    });
    pointer.onUp(() => {
        holding = false;
    });

    const vertices = new Float32Array((Settings.STARS + Settings.RING_COUNT * 64) * 14);

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

        if (keys.justPressed('p')) {
            look = (look + 1) % looks.length;
            looks.forEach((entry, i) => entry.effects.forEach((effect) => {
                effect.enabled = i === look;
            }));
        }

        const warping = holding || keys.isDown(' ');

        speed += ((warping ? Settings.WARP : Settings.CRUISE) - speed) * Math.min(1, delta * (warping ? 1.2 : 2.5));

        const rush = (speed - Settings.CRUISE) / (Settings.WARP - Settings.CRUISE);   // 0 cruising, 1 at full warp

        travelled += speed * delta;

        // Steering turns the camera towards the mouse and banks it, and the jump widens the view:
        // that last one is most of what makes it feel fast.
        camera.transform.rotationY += (-aimX * 0.45 - camera.transform.rotationY) * Math.min(1, delta * 4);
        camera.transform.rotationX += (-aimY * 0.3 - camera.transform.rotationX) * Math.min(1, delta * 4);
        camera.transform.rotation += (aimX * 0.35 - camera.transform.rotation) * Math.min(1, delta * 3);
        camera.fov = 70 + rush * 35;

        let n = 0;
        const streak = 0.05 + speed * 0.012 + rush * 2.5;

        for (let i = 0; i < Settings.STARS; i++) {
            sz[i] += speed * delta;

            // Sent back BEFORE it reaches the camera: a streak with one end behind the lens is cut
            // by it, and what is left on screen is a line from near the middle out to the edge.
            if (sz[i] > -0.3) {
                reset(i, -Settings.DEPTH + Math.random() * 4);
            }

            // Brighter as it comes closer, and bluer the faster we go.
            const near = 1 - Math.min(1, -sz[i] / Settings.DEPTH);
            const light = near * near;
            const r = light * (1 - rush * 0.45);
            const g = light * (1 - rush * 0.15);
            const b = light;

            vertices[n++] = sx[i];
            vertices[n++] = sy[i];
            vertices[n++] = sz[i];
            vertices[n++] = r;
            vertices[n++] = g;
            vertices[n++] = b;
            vertices[n++] = 1;
            vertices[n++] = sx[i];
            vertices[n++] = sy[i];
            vertices[n++] = sz[i] - streak;
            vertices[n++] = 0;
            vertices[n++] = 0;
            vertices[n++] = b * 0.3;
            vertices[n++] = 1;
        }

        n = writeTunnel(vertices, n, travelled, time, rush);
        setLines(lines, vertices.subarray(0, n));
    });
};
```

`geometry/tunnel.ts`:

```ts
import * as Settings from '../settings';
import { fromHsl } from 'nacatamalon';

// every fifth corner of a ring is joined to the next ring

/**
 * Where the middle of the tube is at a given depth. The bend travels towards the camera, which is
 * what makes a straight flight look like it is taking curves.
 */
export const tunnelCentre = (z: number, travelled: number) => ({
    x: Math.sin((z - travelled) * 0.045) * 3.2,
    y: Math.cos((z - travelled) * 0.031) * 2.2,
});

/**
 * Writes the tube: a ring every few units, each one a polygon, and ribs running between them. The
 * rings keep their place in the pattern as they come closer (their colour is picked by which ring
 * they are, not where they are), so the rainbow flows towards the camera instead of standing still.
 */
export const writeTunnel = (out: Float32Array, start: number, travelled: number, time: number, rush: number): number => {
    let n = start;
    const shift = travelled % Settings.RING_GAP;
    const first = Math.floor(travelled / Settings.RING_GAP);

    const corner = (ring: number, side: number) => {
        const z = -(Settings.RING_COUNT - ring) * Settings.RING_GAP + shift;
        const centre = tunnelCentre(z, travelled);
        // A twist that rolls along the tube.
        const angle = (side / Settings.SIDES) * Math.PI * 2 + z * 0.02 + time * 0.3;
        const pulse = 1 + Math.sin(time * 3 + ring * 0.7) * 0.06;

        return {
            x: centre.x + Math.cos(angle) * Settings.RADIUS * pulse,
            y: centre.y + Math.sin(angle) * Settings.RADIUS * pulse,
            z
        };
    };

    const put = (p: { x: number; y: number; z: number; }, color: { r: number; g: number; b: number; }, fade: number) => {
        out[n++] = p.x;
        out[n++] = p.y;
        out[n++] = p.z;
        out[n++] = color.r * fade;
        out[n++] = color.g * fade;
        out[n++] = color.b * fade;
        out[n++] = 1;
    };

    // A ring right by the camera, turned as it is, would have corners behind the lens, and those
    // edges are cut into lines shooting across the screen. By this depth it is past the edges anyway.
    const close = (ring: number) => -(Settings.RING_COUNT - ring) * Settings.RING_GAP + shift > -3.5;

    for (let ring = 0; ring < Settings.RING_COUNT; ring++) {
        if (close(ring)) {
            continue;
        }

        // Which ring of the whole, endless tube this is: that is what its colour follows.
        const id = Settings.RING_COUNT - ring - first;
        const color = fromHsl((id * 17 + time * 40) % 360, 0.85, 0.52 + rush * 0.08);
        // Black in the distance, full near the camera, and gone again right at it.
        const t = ring / (Settings.RING_COUNT - 1);
        const fade = Math.min(1, t * 1.6) * Math.min(1, (1 - t) * 6 + 0.15);

        for (let side = 0; side < Settings.SIDES; side++) {
            put(corner(ring, side), color, fade);
            put(corner(ring, (side + 1) % Settings.SIDES), color, fade);

            if (ring < Settings.RING_COUNT - 1 && !close(ring + 1) && side % Settings.RIBS === 0) {
                put(corner(ring, side), color, fade * 0.6);
                put(corner(ring + 1, side), color, fade * 0.6);
            }
        }
    }

    return n;
};
```

`scenes/demo.ts`:

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

import { Flight } from '../components/flight';

export const Space = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 70,
        near: 0.1,
        far: 120
    });

    useSpawn(Flight)(camera);

    return createScene();
};
```

`settings.ts`:

```ts
export const WIDTH = 480;
export const HEIGHT = 320;
export const STARS = 700;
export const DEPTH = 90; // how far ahead a star is born
export const CRUISE = 14; // units per second
export const WARP = 95;
export const RING_COUNT = 22;
export const RING_GAP = 4.5;
export const SIDES = 20;
export const RADIUS = 6.5;
export const RIBS = 5;
```
