# Height map

> A land raised from a picture: a flat plane whose material reads a height map in its vertex hook.

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

A land raised from a picture. The land is one flat plane; its material carries a grey picture under the name `height`, and the material's vertex hook reads it with `sampleMap_height` and lifts each corner by it. **Space** shows the next map: hills, a crater, a word. The material reads its maps every frame, so swapping the picture changes the land at once, without new geometry.

Two things make it look right. Read the map at a place **worked out from the corner's position** (`pos.xz / size + 0.5`), not at its uv: the engine measures the raised surface again just beside each corner, with the same uv, so a map read at the uv lights the land as if it were still flat. And give the map `smooth: true` and soft slopes: read pixel by pixel, each pixel is a flat step and the land comes out in terraces. The colour comes from how high each corner rose, handed to the colour hook with `carry`. Written with the shader composer (`composerMapSample` in `position`), it draws on WebGPU and WebGL2.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { Landscape } from './scenes/landscape';
import { HEIGHT, SKY, WIDTH } from './settings';

// A land raised from a picture. One flat plane; its material's vertex hook reads a height map, one
// of the material's maps, and lifts each corner by it. Painting the picture again, or swapping it,
// changes the land without touching its geometry.
//
//   space   next height map
const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    background: SKY,
    actions: [
        {
            name: 'next',
            bindings: [
                {
                    type: 'key',
                    key: ' '
                }
            ]
        }
    ]
});

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

`art/heights.ts`:

```ts
import { createPixels, drawText, fillCircle, getPixel, setPixel, type TPixels } from 'nacatamalon/pixels';
import { MAP } from '../settings';

// The height maps, painted in code: grey is height, black the lowest, white the highest. Only the
// red channel is read, so they are painted grey to look like what they are.

/**
 * Averages each pixel with its neighbours, `passes` times: steps become slopes. A height map with
 * hard edges raises walls, because the land is a step wherever one pixel meets the next.
 */
const soften = (pixels: TPixels, passes: number): TPixels => {
    const { width, height } = pixels;

    for (let pass = 0; pass < passes; pass++) {
        const before = Array.from({
            length: width * height
        }, (_, i) => getPixel(pixels, i % width, Math.floor(i / width)).r);

        for (let y = 0; y < height; y++) {
            for (let x = 0; x < width; x++) {
                let sum = 0;
                let count = 0;

                for (let dy = -1; dy <= 1; dy++) {
                    for (let dx = -1; dx <= 1; dx++) {
                        const nx = x + dx;
                        const ny = y + dy;

                        if (nx >= 0 && ny >= 0 && nx < width && ny < height) {
                            sum += before[ny * width + nx];
                            count++;
                        }
                    }
                }

                const grey = sum / count;

                setPixel(pixels, x, y, {
                    r: grey,
                    g: grey,
                    b: grey,
                    a: 1
                });
            }
        }
    }

    return pixels;
};

/**
 * Hills: a few round ones of different heights, worked out pixel by pixel from how far each is.
 */
export const paintHills = (): TPixels => {
    const pixels = createPixels(MAP.size, MAP.size, '#000000');

    const hills = [
        {
            x: 0.3,
            y: 0.3,
            radius: 0.22,
            height: 1
        },
        {
            x: 0.72,
            y: 0.35,
            radius: 0.18,
            height: 0.7
        },
        {
            x: 0.5,
            y: 0.75,
            radius: 0.25,
            height: 0.55
        },
        {
            x: 0.85,
            y: 0.8,
            radius: 0.12,
            height: 0.45
        }
    ];

    for (let y = 0; y < MAP.size; y++) {
        for (let x = 0; x < MAP.size; x++) {
            let grey = 0;

            for (const hill of hills) {
                const distance = Math.hypot(x / MAP.size - hill.x, y / MAP.size - hill.y) / hill.radius;

                grey = Math.max(grey, hill.height * Math.max(0, 1 - distance * distance));
            }

            setPixel(pixels, x, y, {
                r: grey,
                g: grey,
                b: grey,
                a: 1
            });
        }
    }

    return soften(pixels, MAP.soften);
};

/**
 * A crater: a ring of mountains round a lake.
 */
export const paintCrater = (): TPixels => {
    const pixels = createPixels(MAP.size, MAP.size, '#000000');
    const middle = MAP.size / 2;

    fillCircle(pixels, middle, middle, MAP.size * 0.4, '#d0d0d0');
    fillCircle(pixels, middle, middle, MAP.size * 0.28, '#101010');
    fillCircle(pixels, middle - 4, middle + 2, 3, '#606060');

    return soften(pixels, MAP.soften + 2);
};

/**
 * A word, raised out of the plain: any picture is a height map.
 */
export const paintWord = (): TPixels => {
    const pixels = createPixels(MAP.size, MAP.size, '#000000');

    drawText(pixels, 'NACA', MAP.size / 2, MAP.size / 2, {
        fontSize: 11,
        anchor: {
            x: 0.5,
            y: 0.5
        },
        color: '#ffffff'
    });

    return soften(pixels, 1);
};
```

`components/map_preview.ts`:

```ts
import { createSprite, createText, type TTexture } from 'nacatamalon';

/**
 * The picture that raises the land, shown in a corner of the screen, with its name.
 */
export type TMapPreview = {
    show: (map: TTexture, name: string) => void;
};

const SIZE = 96;

export const MapPreview = ({ map, name }: { map: TTexture; name: string; }): TMapPreview => {
    const picture = createSprite({
        texture: map,
        width: SIZE,
        height: SIZE,
        anchor: {
            x: 0,
            y: 0
        },
        zIndex: 100,
        transform: {
            x: 8,
            y: 24
        }
    });

    const label = createText({
        text: name,
        tint: '#1d2a40',
        zIndex: 100,
        transform: {
            x: 8,
            y: 24 + SIZE + 6
        }
    });

    return {
        show: (next, nextName) => {
            picture.texture = next;
            label.text = nextName;
        }
    };
};
```

`components/terrain.ts`:

```ts
import { createMaterial, createMesh, usePlaneGeometry, type TTexture } from 'nacatamalon';
import { LAND, WATER } from '../settings';
import { TERRAIN } from '../shaders/terrain';

/**
 * What the land lets the scene do: show another height map.
 */
export type TTerrain = {
    show: (map: TTexture) => void;
};

/**
 * The land: one flat plane, raised in its material's vertex hook by the picture under `height`,
 * and a lake at a fixed level that the low ground dips under.
 */
export const Terrain = ({ map }: { map: TTexture; }): TTerrain => {
    const ground = createMaterial({
        ...TERRAIN,
        maps: {
            // Smooth, so the land between two pixels of the map is a slope and not a step; clamped,
            // so the edge of the land does not read the other side of the picture.
            height: {
                texture: map,
                smooth: true,
                wrap: 'clamp'
            }
        }
    });

    createMesh({
        geometry: usePlaneGeometry({
            width: LAND.size,
            depth: LAND.size,
            widthSegments: LAND.segments,
            depthSegments: LAND.segments
        }),
        material: ground,
        castShadow: true
    });

    createMesh({
        geometry: usePlaneGeometry({
            width: LAND.size,
            depth: LAND.size
        }),
        tint: WATER.color,
        specular: '#ffffff',
        shininess: 60,
        transform: {
            y: WATER.level
        }
    });

    return {
        // The material reads its maps every frame, so changing the picture shows at once.
        show: (next) => {
            ground.maps!.height.texture = next;
        }
    };
};
```

`scenes/landscape.ts`:

```ts
import { cameraLookAt, createScene, createText, useAction, useAmbientLight, useCamera3d, useDirectionalLight, useFog, useSpawn, useUpdate } from 'nacatamalon';
import { createPixelTexture } from 'nacatamalon/pixels';
import { paintCrater, paintHills, paintWord } from '../art/heights';
import { MapPreview } from '../components/map_preview';
import { Terrain } from '../components/terrain';
import { HEIGHT, LAND, ORBIT, SKY } from '../settings';

/**
 * A land raised from a picture, seen from a camera going slowly round it. Space shows the next
 * height map.
 */
export const Landscape = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 50
    });

    useFog({
        color: SKY,
        near: 12,
        far: 24
    });
    useAmbientLight({
        color: '#c9d8f0',
        intensity: 0.45
    });
    useDirectionalLight({
        color: '#fff2dc',
        intensity: 1.1,
        castShadow: true,
        shadowArea: LAND.size * 1.6,
        transform: {
            rotationX: -0.75,
            rotationY: 0.9
        }
    });

    // The height maps are pictures like any other: painted here, they could as well be loaded.
    const maps = [
        {
            name: 'HILLS',
            texture: createPixelTexture(paintHills())
        },
        {
            name: 'CRATER',
            texture: createPixelTexture(paintCrater())
        },
        {
            name: 'A WORD',
            texture: createPixelTexture(paintWord())
        }
    ];

    let current = 0;

    const terrain = useSpawn(Terrain)({
        map: maps[0].texture
    });

    const preview = useSpawn(MapPreview)({
        map: maps[0].texture,
        name: maps[0].name
    });

    createText({
        text: 'SPACE: NEXT HEIGHT MAP',
        tint: '#1d2a40',
        zIndex: 100,
        transform: {
            x: 8,
            y: 8
        }
    });
    createText({
        text: 'HEIGHT MAP · NACATAMALON',
        tint: '#1d2a40',
        zIndex: 100,
        transform: {
            x: 8,
            y: HEIGHT - 16
        }
    });

    const next = useAction('next');

    useUpdate((_delta, time) => {
        if (next.justPressed()) {
            current = (current + 1) % maps.length;
            terrain.api.show(maps[current].texture);
            preview.api.show(maps[current].texture, maps[current].name);
        }

        const angle = time * ORBIT.speed * Math.PI * 2;

        camera.transform.x = Math.sin(angle) * ORBIT.distance;
        camera.transform.y = ORBIT.height;
        camera.transform.z = Math.cos(angle) * ORBIT.distance;
        cameraLookAt(camera, {
            x: 0,
            y: 0.4,
            z: 0
        });
    });

    return createScene();
};
```

`settings.ts`:

```ts
/**
 * The game's size, in its own pixels.
 */
export const WIDTH = 640;
export const HEIGHT = 360;

/**
 * The sky, and the fog that fades the far side of the land into it.
 */
export const SKY = '#9fc4e8';

/**
 * The land: a plane `size` units across, cut into `segments` squares each way so there are corners
 * to raise, and raised `height` units where its height map is white.
 */
export const LAND = {
    size: 10,
    segments: 96,
    height: 2.2
};

/**
 * The height maps, `size` pixels square. More pixels give finer shapes; the land follows them only
 * as finely as its segments allow.
 */
export const MAP = {
    size: 64,
    // How many times each map is softened: a height map wants gentle slopes, not steps.
    soften: 3
};

/**
 * The lake, at this height, and its colour.
 */
export const WATER = {
    level: 0.35,
    color: '#3f7fc8'
};

/**
 * The colours the land takes by how high it is, from the shore up.
 */
export const BANDS = {
    sand: '#d9c58f',
    grass: '#5f9a46',
    rock: '#7d7468',
    snow: '#f4f6fb'
};

/**
 * How fast the camera goes round, in turns a second, and how far out and up it stays.
 */
export const ORBIT = {
    speed: 0.025,
    distance: 11,
    height: 6.5
};
```

`shaders/terrain.ts`:

```ts
import { getColor } from 'nacatamalon';
import {
    compileShader, composerAdd, composerCarry, composerDiv, composerLight, composerMapSample, composerMix, composerMul,
    composerShine, composerSmoothstep, composerSwizzle, composerVec3, composerVertexPosition, composerX
} from 'nacatamalon/shader';
import { BANDS, LAND, WATER } from '../settings';

// The land's material, written once with the shader composer so it draws on both cards.

/**
 * A colour from settings, as the three numbers a graph works with.
 */
const rgb = (color: string) => {
    const { r, g, b } = getColor(color);

    return composerVec3(r, g, b);
};

const corner = composerVertexPosition();

// Where this corner falls on the height map, worked out from where the corner is: the plane runs
// from -size/2 to size/2, the map from 0 to 1. Not the corner's uv: the engine measures the raised
// surface again a hair to each side of the corner, with the same uv, so a map read at the uv would
// rise just as much there and the land would be lit as if it were still flat.
const onMap = composerAdd(composerDiv(composerSwizzle(corner, 'xz'), LAND.size), 0.5);

// How high, 0 to 1, read from the material's map named `height`.
const rise = composerX(composerMapSample('height', onMap));

// Coloured by how high each corner was raised, carried from the corner to the pixel: sand by the
// water, grass, rock, and snow on the tops.
const height = composerX(composerCarry());
const shore = WATER.level / LAND.height;
const sandToGrass = composerMix(rgb(BANDS.sand), rgb(BANDS.grass), composerSmoothstep(shore, shore + 0.06, height));
const toRock = composerMix(sandToGrass, rgb(BANDS.rock), composerSmoothstep(0.45, 0.6, height));
const toSnow = composerMix(toRock, rgb(BANDS.snow), composerSmoothstep(0.72, 0.8, height));

export const TERRAIN = compileShader({
    shader: 'mesh3d',
    position: composerAdd(corner, composerVec3(0, composerMul(rise, LAND.height), 0)),
    carry: rise,
    // Lit as the engine lights any model: the colour times the light, and the shine on top.
    color: composerAdd(composerMul(toSnow, composerLight()), composerShine())
});
```
