# Procedural pixel art

> Procedural art: a sky, hills and palms generated in code from a seed, with no image files and no canvas, and regenerated live.

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

Art someone draws is made in a pixel-art editor and loaded with `useLoadTexture`. This example is about the other case: pictures **generated in code**, for procedural variations, for placeholders, or for an agent that has no image editor. That is what to use instead of drawing on a `<canvas>`, which only exists in a browser.

Every picture in this scene is generated. `createPixels` is a picture in memory, plain bytes; `fillGradient`, `drawLine`, `fillRect`, `mapPixels` and `blitPixels` paint on it; and `createPixelTexture` turns it into a texture a sprite shows like any loaded image.

There are **no image files and no `<canvas>`**. The painting is plain JavaScript, so it runs the same in the browser, on the native runtime and in a test, and paints the same pixels in all three. The sky is cut into fourteen bands dithered where two meet, the palms come from a seed, and the car is stamped together from a body and the same wheel twice.

Press **R** to repaint the hills and the palms with another seed. They are painted over in place and `updatePixelTexture` sends the change: no new textures.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { WIDTH, HEIGHT } from './settings';
import { Game } from './scenes/demo';

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

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

`art/art.ts`:

```ts
import * as Settings from '../settings';
import { getColor } from 'nacatamalon';
import { blitPixels, createPixels, drawLine, fillGradient, fillRect, mapPixels } from 'nacatamalon/pixels';
import type { TRandomHandle } from 'nacatamalon/math';
import type { TPixels } from 'nacatamalon/pixels';

// Every picture the scene shows, painted here. Each function makes (or repaints) one picture in
// memory and hands it back; index.ts turns them into textures and places them.

const c = (hex: string) => getColor(hex);
const CLEAR = c('transparent');

// The sky: seven colours cut into fourteen flat bands, dithered where two bands meet.
export const paintSky = (): TPixels => fillGradient(createPixels(Settings.WIDTH, Settings.HORIZON), {
    colors: ['#140a33', '#2b0f55', '#5a1667', '#9c2a6f', '#e0446e', '#ff7a5c', '#ffb36b'].map(c),
    bands: 14,
    dither: true,
});

// The sun: a gradient cut to a disc, its lower half sliced by stripes that widen towards the horizon.
export const paintSun = (): TPixels => mapPixels(fillGradient(createPixels(72, 72), {
    from: c('#ffe066'),
    to: c('#ff5e7a')
}), (color, x, y) => {
    const dx = x - 35.5;
    const dy = y - 35.5;

    if (dx * dx + dy * dy > 35 * 35) {
        return CLEAR;
    }

    if (y > 40 && y % 6 < (y - 40) / 8) {
        return CLEAR;
    }

    return color;
});

// Hills along the horizon, their outline a sum of two waves the seed shifts. Painted over the picture
// it is given, so the same one can be repainted with another seed.
export const paintHills = (hills: TPixels, seed: number): TPixels => {
    fillRect(hills, 0, 0, hills.width, hills.height, CLEAR);

    return mapPixels(hills, (_, x, y) => {
        const top = 30 - 12 * Math.sin(x * 0.045 + seed * 1.7) - 7 * Math.sin(x * 0.13 + seed * 0.6);

        if (y < top) {
            return CLEAR;
        }

        return y - top < 3 ? c('#7a3a8c') : c('#4a2060');
    });
};

// The ground: green bands down to the bottom edge, and a grid running to a point on the horizon.
export const paintGround = (): TPixels => {
    const ground = fillGradient(createPixels(Settings.WIDTH, Settings.HEIGHT - Settings.HORIZON), {
        from: c('#0f5132'),
        to: c('#1fa05a'),
        bands: 6,
        dither: true
    });

    const line = c('#ff5ec8');

    for (let i = -10; i <= 10; i++) {
        drawLine(ground, Settings.WIDTH / 2, 0, Settings.WIDTH / 2 + i * 48, Settings.HEIGHT - Settings.HORIZON - 1, line);
    }

    for (let k = 1; k < 9; k++) {
        const y = Math.round((k * k * (Settings.HEIGHT - Settings.HORIZON)) / 81);

        drawLine(ground, 0, y, Settings.WIDTH - 1, y, line);
    }

    return ground;
};

// A palm: a leaning trunk two pixels wide, and fronds that droop at their tips. Also painted over
// the picture it is given.
export const paintPalm = (palm: TPixels, rnd: TRandomHandle): TPixels => {
    fillRect(palm, 0, 0, palm.width, palm.height, CLEAR);

    const topX = 20 + rnd.rand(-8, 8);

    for (let w = 0; w < 2; w++) {
        drawLine(palm, 20 + w, 63, topX + w, 16, c('#5b3a29'));
    }

    const fronds = 5 + rnd.randInt(0, 2);

    for (let f = 0; f < fronds; f++) {
        const angle = Math.PI + (f / (fronds - 1)) * Math.PI + rnd.rand(-0.2, 0.2);
        const length = rnd.rand(12, 17);
        const endX = topX + Math.cos(angle) * length;
        const endY = 16 + Math.sin(angle) * length * 0.6;

        drawLine(palm, topX, 16, endX, endY, c('#2e9e5b'));
        drawLine(palm, endX, endY, endX + Math.sign(Math.cos(angle)) * 2, endY + 3, c('#1f6e40'));
    }

    return palm;
};

// The car, put together from parts: a body, then the same wheel stamped twice.
export const paintCar = (): TPixels => {
    const car = createPixels(48, 24);

    fillRect(car, 2, 10, 44, 10, c('#e23d3d'));
    fillRect(car, 10, 3, 28, 8, c('#a8222e'));
    fillRect(car, 12, 4, 24, 6, c('#7ec8e3'));
    fillRect(car, 3, 12, 4, 2, c('#ffe066'));
    fillRect(car, 41, 12, 4, 2, c('#ffe066'));

    const wheel = createPixels(10, 6, c('#141414'));

    fillRect(wheel, 3, 2, 4, 2, c('#9a9a9a'));
    blitPixels(car, wheel, 4, 18);
    blitPixels(car, wheel, 34, 18);

    return car;
};
```

`components/car.ts`:

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

import * as Settings from '../settings';
import { place } from '../helpers/place';
import { paintCar } from '../art/art';

export const Car = () => {
    const car = place(paintCar(), Settings.WIDTH / 2 - 24, Settings.HEIGHT - 34, 4).sprite;

    useUpdate((_delta, time) => {
        car.transform.x = Settings.WIDTH / 2 - 24 + Math.sin(time * 1.5) * 40;
    });
};
```

`components/landscape.ts`:

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

import * as Settings from '../settings';
import type { TRandomHandle } from 'nacatamalon/math';
import { place } from '../helpers/place';
import { paintSky, paintSun, paintHills, paintGround, paintPalm } from '../art/art';

export const Landscape = ({ rnd, seed }: { rnd: TRandomHandle; seed: number }) => {
    place(paintSky(), 0, 0, 0);
    place(paintSun(), Settings.WIDTH / 2 - 36, Settings.HORIZON - 64, 1);

    const hills = paintHills(createPixels(Settings.WIDTH, 50), seed);
    const hillsShown = place(hills, 0, Settings.HORIZON - 50, 2);

    place(paintGround(), 0, Settings.HORIZON, 2);

    const palms = [16, 72, 232, 288].map((x) => {
        const pixels = paintPalm(createPixels(40, 64), rnd);

        return {
            pixels,
            shown: place(pixels, x - 20, Settings.HORIZON - 40, 3)
        };
    });

    return {
        repaint: (seed: number) => {
            rnd.seed(seed);
            paintHills(hills, seed);
            updatePixelTexture(hillsShown.texture);

            for (const palm of palms) {
                paintPalm(palm.pixels, rnd);
                updatePixelTexture(palm.shown.texture);
            }
        }
    };
};
```

`helpers/place.ts`:

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

import { createPixelTexture } from 'nacatamalon/pixels';
import type { TPixels } from 'nacatamalon/pixels';

export const place = (pixels: TPixels, x: number, y: number, zIndex: number) => {
    const texture = createPixelTexture(pixels);

    const sprite = createSprite({
        texture,
        width: pixels.width,
        height: pixels.height,
        anchor: {
            x: 0,
            y: 0
        },
        zIndex,
        transform: {
            x,
            y
        },
    });

    return {
        texture,
        sprite
    };
};
```

`scenes/demo.ts`:

```ts
import { createScene, createText, useKeyboard, useUpdate, useSpawn } from 'nacatamalon';
import { useRandom } from 'nacatamalon/math';

import { Landscape } from '../components/landscape';
import { Car } from '../components/car';

export const Game = () => {
    const rnd = useRandom();
    let seed = 1;

    rnd.seed(seed);

    const landscape = useSpawn(Landscape)({
        rnd,
        seed
    }).api;

    useSpawn(Car)();

    const label = createText({
        text: 'SEED 1',
        zIndex: 5,
        transform: {
            x: 8,
            y: 8
        }
    });

    createText({
        text: 'R REPAINT',
        zIndex: 5,
        tint: '#ffd0f0',
        transform: {
            x: 8,
            y: 20
        }
    });

    const keys = useKeyboard();

    useUpdate(() => {
        if (keys.justPressed('r')) {
            landscape.repaint(++seed);
            label.text = 'SEED ' + seed;
        }
    });

    return createScene();
};
```

`settings.ts`:

```ts
export const WIDTH = 320;
export const HEIGHT = 224;
export const HORIZON = 132;
```
