# CRT screen

> crt() puts the frame on a tube television: scanlines, phosphor mask, the bulge and glow of the glass, and four ready-made tubes.

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

`crt()` puts the frame on a tube television. Each part is a number in `effect.uniforms`, and a part at 0 is not there at all: `scanlines` (the dark lines between rows), `mask` (the colour grid of the tube: aperture stripes, slot cells or dots, with `maskType`), `curvature` (the bulge of the glass), `vignette` (the corners going dark), `halation` (the glow of bright parts) and `noise` (moving grain). There are more: `sharpness`, `beam` (bright lines widen into the gap), `brightness`, `linearBlend`, `convergence`, `flicker`, `interlace` and `cornerRadius`.

`POST_EFFECTS.CRT_PRESETS` sets all of them as four tubes: `consumer` (the living-room television), `pvm` (a sharp studio monitor), `arcade` (a cabinet) and `composite` (a cheap cable). Use one whole with `crt(POST_EFFECTS.CRT_PRESETS.pvm)`, or change one part of it with `crt({ ...POST_EFFECTS.CRT_PRESETS.consumer, noise: 0 })`.

**One line per row of the game, not of the screen.** The lines follow the game's own pixels, like a console's picture on the tube. This example uses `pixelRatio: 'device'`: on a dense screen each game pixel is two or three real ones, and the line fits inside the row. On a screen of density 1 a row is a single pixel, so every other row is darkened instead, and the mask is best left off.

It goes **last** in the chain: the palette or the dither decide which colours exist, and the tube is only where they are shown. Press **1** to **6** to toggle each part, **M** to change the mask type, **P** to step through the presets and **Space** to switch it off.

## Code

`index.ts`:

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

import { Game } from './scenes/demo';
import { WIDTH, HEIGHT } from './settings';

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

// Declare Scenes
game({
    Game,
});
```

`components/effect_controls.ts`:

```ts
import { createText, useKeyboard, useLoadBitmapFont, useUpdate, useScreenSpace } from 'nacatamalon';
import { crt, usePostProcess, POST_EFFECTS } from 'nacatamalon/effects';

import { PARTS, PRESETS, MASKS, EFFECT_SETTINGS } from '../settings';

export const EffectControls = () => {
    useScreenSpace();

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

    const label = createText({
        text: '',
        font,
        style: {
            fontSize: 8,
        },
        tint: '#ffffff',
        transform: {
            x: 16,
            y: 16,
        },
    });

    createText({
        text: '1-6 PARTS   M MASK   P PRESET   SPACE OFF',
        font,
        style: {
            fontSize: 8,
        },
        tint: '#8c82a6',
        transform: {
            x: 16,
            y: 32,
        },
    });

    // The mask starts on only where it can be drawn: with fewer than two real pixels per game pixel
    // it is coloured columns, not a tube. Press 2 to see that for yourself.
    const dense = window.devicePixelRatio >= 2;

    const effect = usePostProcess(crt({
        ...EFFECT_SETTINGS,
        mask: dense ? EFFECT_SETTINGS.mask : 0
    }));

    let preset = -1;

    const show = () => {
        if (!effect.enabled) {
            label.text = 'OFF  THE FRAME AS DRAWN';

            return;
        }

        const type = effect.uniforms.mask > 0 ? ' ' + MASKS[effect.uniforms.maskType] : '';

        if (preset >= 0) {
            label.text = 'PRESET ' + PRESETS[preset].toUpperCase() + type;

            return;
        }

        const parts = PARTS.filter((part) => effect.uniforms[part.name] > 0).map((part) => part.short);

        label.text = (parts.length > 0 ? parts.join(' ') : 'NOTHING') + type;
    };

    show();

    const keys = useKeyboard();

    useUpdate(() => {
        for (const part of PARTS) {
            if (keys.justPressed(part.key)) {
                effect.uniforms[part.name] = effect.uniforms[part.name] > 0 ? 0 : part.on;
                // Changed by hand, it is no longer the preset it started as.
                preset = -1;
                show();
            }
        }

        if (keys.justPressed('m')) {
            effect.uniforms.maskType = (effect.uniforms.maskType + 1) % 3;
            show();
        }

        // A preset is only a set of settings: the numbers crt() makes of it, written into the same
        // effect, change the tube without installing anything.
        if (keys.justPressed('p')) {
            preset = (preset + 1) % PRESETS.length;
            Object.assign(effect.uniforms, crt(POST_EFFECTS.CRT_PRESETS[PRESETS[preset]]).uniforms);
            show();
        }

        if (keys.justPressed(' ')) {
            effect.enabled = !effect.enabled;
            show();
        }
    });
};
```

`components/stage.ts`:

```ts
import { WIDTH, HEIGHT } from '../settings';
import { createMaterial, createMesh, createSprite, getColor, useCamera3d, useDirectionalLight, useLoadTexture, useUpdate, useSphereGeometry } from 'nacatamalon';

// The test card every post-processing example draws, so the only thing that changes between them
// is the effect. Each part is here because it shows something a screen effect does:
//
//   lit balls   smooth gradients that nobody drew, made by the light as it turns. Banding shows
//               there first, because a gradient is exactly what a few steps cannot hold.
//   hue ramp    every colour at once, which is where a palette has to make its hardest choices.
//   grey ramp   sixteen even steps: whether an effect keeps them even is visible at a glance.
//   gammix      pixel art, already limited, so it shows what an effect does to a sprite that was
//               drawn for a small palette in the first place.

export const Stage = () => {
    useCamera3d({
        projection: 'perspective',
        fov: 50,
        transform: {
            z: 5,
            y: 0.4
        },
    });

    const light = useDirectionalLight({
        color: '#ffffff',
        intensity: 1.2,
        ambient: 0.25,
        transform: {
            rotationX: -0.5
        },
    });

    const geometry = useSphereGeometry();

    ['#ff7a3d', '#3dd6c6', '#9b5cff'].forEach((hex, i) => {
        const material = createMaterial({
            name: 'post-card-' + i,
            shader: 'mesh3d',
            tint: getColor(hex),
            specular: '#ffffff',
            shininess: 24,
        });

        createMesh({
            geometry,
            material,
            transform: {
                x: (i - 1) * 2.1,
                y: 0.6,
            },
        });
    });

    // The light swings from side to side in front of the balls, so the gradients move and a
    // static effect cannot hide in one lucky frame.
    useUpdate((_, time) => {
        light.transform.rotationY = Math.sin(time * 0.8) * 0.9;
    });

    for (let i = 0; i < 48; i++) {
        createSprite({
            width: WIDTH / 48,
            height: 18,
            tint: getColor('hsl(' + Math.round((i / 48) * 360) + ', 85%, 55%)'),
            transform: {
                x: (i + 0.5) * WIDTH / 48,
                y: HEIGHT - 38,
            },
        });
    }

    for (let i = 0; i < 16; i++) {
        const v = Math.round((i / 15) * 255);

        createSprite({
            width: WIDTH / 16,
            height: 18,
            tint: getColor('rgb(' + v + ',' + v + ',' + v + ')'),
            transform: {
                x: (i + 0.5) * WIDTH / 16,
                y: HEIGHT - 18,
            },
        });
    }

    const gammix = useLoadTexture({
        src: '/example-assets/assets/gammix.png',
        key: 'gammix',
    });

    createSprite({
        texture: gammix,
        width: 48,
        height: 48,
        transform: {
            x: WIDTH - 34,
            y: 34,
        },
    });
};
```

`scenes/demo.ts`:

```ts
import { createScene, useSpawn } from 'nacatamalon';
import { Stage } from '../components/stage';
import { EffectControls } from '../components/effect_controls';

export const Game = () => {
    useSpawn(Stage)();
    useSpawn(EffectControls)();

    return createScene();
};
```

`settings.ts`:

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

// crt() puts the frame on a television tube. Every part is a number in effect.uniforms, and a part
// at 0 is not there at all. The ones this example lets you switch:
//
//   scanlines  the dark gaps between the rows of the picture, one per row of the GAME
//   mask       the coloured grid of the tube (maskType 0 aperture stripes, 1 slot cells, 2 dots)
//   curvature  the bulge of the glass
//   vignette   the corners going dark
//   halation   the glow bright parts throw across the glass
//   noise      moving grain
//
// It has more (sharpness, beam, brightness, gamma, convergence, flicker, interlace, cornerRadius),
// and POST_EFFECTS.CRT_PRESETS sets all of them at once as four tubes: consumer, pvm, arcade and composite.
//
// The game runs at pixelRatio 'device': one real pixel of the buffer per real pixel of the screen.
// On a dense screen that gives every game pixel two or three real ones, which is what lets a
// scanline sit INSIDE a row, take the shape of a beam, and the mask draw its red, green and blue.
// On a screen of density 1 a row is one real pixel, so the lines fall back to darkening every other
// row and the mask reads as coloured columns.
//
// It goes last in a chain: whatever palette or dither runs first decides the colours, and the tube
// is only what they are shown on.

// `short` is what the label calls each part: six full names do not fit across the screen.
export const PARTS = [
    {
        key: '1',
        name: 'scanlines',
        short: 'LINES',
        on: 0.45
    },
    {
        key: '2',
        name: 'mask',
        short: 'MASK',
        on: 0.35
    },
    {
        key: '3',
        name: 'curvature',
        short: 'CURVE',
        on: 0.08
    },
    {
        key: '4',
        name: 'vignette',
        short: 'VIGNETTE',
        on: 0.35
    },
    {
        key: '5',
        name: 'halation',
        short: 'GLOW',
        on: 0.2
    },
    {
        key: '6',
        name: 'noise',
        short: 'NOISE',
        on: 0.05
    },
] as const;

export const PRESETS = ['consumer', 'pvm', 'arcade', 'composite'] as const;

export const MASKS = ['APERTURE', 'SLOT', 'DOTS'];

export const EFFECT_SETTINGS = {
    scanlines: 0.45,
    mask: 0.35,
    curvature: 0.08,
    vignette: 0.35,
};
```
