# Posterize

> posterize() moves every colour to the nearest of a few steps: a gradient turns into flat bands.

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

`posterize()` cuts every colour channel down to a few even steps and nothing else: each colour moves to the nearest step, so a gradient turns into flat bands. It is the plainest way to take colours away, and the bands are the point: a comic, a poster, a toon look.

Its one number is `effect.uniforms.levels`, steps per channel. Two steps is eight colours in all (two per channel, cubed); 32 is what a SNES could store and is close to invisible.

**Click** to change the steps and **Space** to switch it off. **D** switches to `dither()` at the same steps: the same colours available, and the only difference is the pattern that hides where each band ends.

## 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,
    background: '#0b0710'
});

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

`components/effect_controls.ts`:

```ts
import { createText, useKeyboard, useLoadBitmapFont, usePointer, useUpdate, useScreenSpace } from 'nacatamalon';
import { dither, posterize, usePostProcess } from 'nacatamalon/effects';

import { LEVELS, EFFECT_SETTINGS, INITIAL_LEVEL_INDEX } 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: 12,
            y: 14,
        },
    });

    createText({
        text: 'CLICK LEVELS   D DITHER   SPACE OFF',
        font,
        style: {
            fontSize: 8,
        },
        tint: '#8c82a6',
        transform: {
            x: 12,
            y: 30,
        },
    });

    let index = INITIAL_LEVEL_INDEX;

    let usingDither = false;

    let on = true;

    const bands = usePostProcess(posterize(EFFECT_SETTINGS));

    const pattern = usePostProcess({
        ...dither({
            levels: LEVELS[index],
        }),
        enabled: false,
    });

    const apply = () => {
        bands.uniforms.levels = LEVELS[index];
        pattern.uniforms.levels = LEVELS[index];
        bands.enabled = on && !usingDither;
        pattern.enabled = on && usingDither;

        const colours = Math.pow(LEVELS[index], 3);

        label.text = on
            ? (usingDither ? 'DITHER ' : 'POSTERIZE ') + LEVELS[index] + ' LEVELS  ' + colours + ' COLOURS'
            : 'OFF  THE FRAME AS DRAWN';
    };

    apply();

    usePointer().onDown(() => {
        index = (index + 1) % LEVELS.length;
        apply();
    });

    const keys = useKeyboard();

    useUpdate(() => {
        if (keys.justPressed('d')) {
            usingDither = !usingDither;
            apply();
        }

        if (keys.justPressed(' ')) {
            on = !on;
            apply();
        }
    });
};
```

`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;

// posterize() cuts every colour channel down to a few even steps and nothing else: every colour is
// moved to the nearest step, so a gradient turns into flat bands. It is the plainest way to take
// colours away, and the bands are the point: a comic, a poster, a toon look.
//
// Its one number is effect.uniforms.levels, steps per channel. Two levels is eight colours in
// all (two per channel, cubed); 32 is what a SNES could store and is close to invisible.
//
// D switches to dither() at the same levels, installed right after it and off until then. Same
// steps, same colours available; the only difference is the pattern that hides where one band ends.
export const LEVELS = [2, 3, 4, 6, 8, 16, 32];
export const INITIAL_LEVEL_INDEX = 2;

export const EFFECT_SETTINGS = {
    levels: LEVELS[INITIAL_LEVEL_INDEX],
};
```
