# Material maps

> Up to four extra pictures on a model material, read by its shader by name: chrome, a dissolve that keeps its colour, a detail map and water.

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

A model's material can carry up to four extra pictures besides the one it is covered with: its `maps`, each with a name. Its shader reads one with `sampleMap_<name>(uv)`, wherever it likes. That is how the last consoles of the era combined several textures in one pass, and it is what each of these four needs:

- **Chrome** reads an `env` map of the sky and the ground where the surface would reflect them; `envUv(ctx)` gives that place.
- **Dissolve** burns bricks away through a separate `noise` map, so the colour stays the brick.
- **Detail** repeats a fine map eight times over a coarse picture, so it does not go blurry up close. The map has mipmaps and is read with `{ scale: 8 }`, so far away it is read from the copy that suits it.
- **Water** reads its tiles through a moving `ripple` map that shifts where each pixel looks.

The four effects are built with the **shader composer** (`shaders/materials.ts`): `composerMapSample('noise', uv)` reads a map and `composerEnvUv()` gives the reflection's place, and `compileShader` writes each one in both shader languages. Every picture is painted in code (`art/textures.ts`). A map the material does not carry reads as white, with a warning in the console.

## Code

`index.ts`:

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

import * as Settings from './settings';
import { Game } from './scenes/demo';

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

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

`art/textures.ts`:

```ts
import { getColor } from 'nacatamalon';
import { createPixels, fillChecker, fillGradient, fillNoise, fillRect, mapPixels } from 'nacatamalon/pixels';
import type { TPixels } from 'nacatamalon/pixels';

// Every picture the four materials use, painted here: each model's own picture, and its maps.

const c = (hex: string) => getColor(hex);

// CHROME: plain steel as its picture, and a sky over brown ground as the 'env' map it reflects.
export const paintSteel = (): TPixels => createPixels(4, 4, c('#9aa4b2'));
export const paintSky = (): TPixels =>
    fillGradient(createPixels(64, 64), {
        colors: ['#0b1d4a', '#4aa3ff', '#e8f4ff', '#8a6a44', '#2a1a0a'].map(c)
    });

// DISSOLVE: bricks as its picture, and the 'noise' map that decides where it burns away.
export const paintBricks = (): TPixels => mapPixels(
    fillNoise(createPixels(64, 64), {
        seed: 4,
        scale: 8,
        octaves: 3,
        from: c('#7a2e1e'),
        to: c('#c4583a')
    }),
    (color, x, y) => (y % 8 === 7 || (x + (Math.floor(y / 8) % 2) * 8) % 16 === 15 ? c('#c9c1b0') : color),
);
export const paintNoise = (): TPixels => fillNoise(createPixels(64, 64), {
    seed: 11,
    scale: 8,
    octaves: 3
});

// DETAIL: a coarse 8 x 8 picture, and a fine 'detail' map repeated over it.
export const paintCoarse = (): TPixels => fillChecker(createPixels(8, 8), 2, c('#5d6b3a'), c('#7a8a4a'));
export const paintDetail = (): TPixels => fillNoise(createPixels(32, 32), {
    seed: 2,
    scale: 2,
    octaves: 2
});

// WATER: pool tiles with grout lines, and the 'ripple' map that bends how they are seen.
export const paintTiles = (): TPixels => {
    const tiles = fillChecker(createPixels(64, 64), 8, c('#e8f2f8'), c('#bcd6e6'));

    for (let i = 0; i < 64; i += 8) {
        fillRect(tiles, i, 0, 1, 64, c('#7aa0b8'));
        fillRect(tiles, 0, i, 64, 1, c('#7aa0b8'));
    }

    return tiles;
};
export const paintRipple = (): TPixels => fillNoise(createPixels(64, 64), {
    seed: 5,
    scale: 16,
    octaves: 2
});
```

`components/exhibit.ts`:

```ts
import { createMaterial, createMesh, useCubeGeometry, usePlaneGeometry, useTorusGeometry, useUpdate } from 'nacatamalon';
import { createPixelTexture } from 'nacatamalon/pixels';
import type { TMaterialMap, TTexture } from 'nacatamalon';
import type { TPixels } from 'nacatamalon/pixels';
import type { TCompiledShader } from 'nacatamalon/shader';

import { CHROME, DETAIL, DISSOLVE, WATER } from '../shaders/materials';
import { paintBricks, paintCoarse, paintDetail, paintNoise, paintRipple, paintSky, paintSteel, paintTiles } from '../art/textures';

export const Exhibit = () => {
    const material = (
        picture: TPixels,
        maps: Record<string, TTexture | TMaterialMap>,
        effect: TCompiledShader<'mesh3d'>,
    ) => createMaterial({
        ...effect,
        texture: createPixelTexture(picture),
        maps,
        specular: '#ffffff',
        shininess: 48,
    });

    const spinning = [
        createMesh({
            geometry: useTorusGeometry({
                radius: 0.55,
                tube: 0.24
            }),
            material: material(paintSteel(), {
                env: {
                    texture: createPixelTexture(paintSky()),
                    smooth: true
                }
            }, CHROME),
            transform: {
                x: -3,
                y: 0.4
            },
        }),
        createMesh({
            geometry: useCubeGeometry({
                width: 1.1,
                height: 1.1,
                depth: 1.1
            }),
            material: material(paintBricks(), {
                noise: createPixelTexture(paintNoise())
            }, DISSOLVE),
            transform: {
                x: -1,
                y: 0.4
            },
        }),
        createMesh({
            geometry: useCubeGeometry({
                width: 1.1,
                height: 1.1,
                depth: 1.1
            }),
            material: material(paintCoarse(), {
                // With mipmaps: repeated eight times, the fine map is read far smaller than it is,
                // and the copies keep it from shimmering when the cube is seen from afar.
                detail: createPixelTexture(paintDetail(), {
                    mipmaps: true
                })
            }, DETAIL),
            transform: {
                x: 1,
                y: 0.4
            },
        }),
    ];

    createMesh({
        geometry: usePlaneGeometry({
            width: 2.2,
            depth: 2.2
        }),
        material: material(paintTiles(), {
            ripple: createPixelTexture(paintRipple())
        }, WATER),
        transform: {
            x: 3,
            y: -0.2
        },
    });

    useUpdate((delta) => {
        for (const mesh of spinning) {
            mesh.transform.rotationY += delta * 0.6;
            mesh.transform.rotationX += delta * 0.2;
        }
    });
};
```

`scenes/demo.ts`:

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

import { Exhibit } from '../components/exhibit';

export const Game = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 50,
        transform: {
            y: 2.4,
            z: 7
        }
    });

    cameraLookAt(camera, {
        x: 0,
        y: 0,
        z: 0
    });
    useDirectionalLight({
        color: '#fff0d8',
        intensity: 1.1,
        ambient: 0.35,
        transform: {
            rotationX: -0.7,
            rotationY: 0.5
        }
    });

    useSpawn(Exhibit)();
    createText({
        text: 'CHROME  DISSOLVE  DETAIL   WATER',
        tint: '#8fb7ff',
        transform: {
            x: 56,
            y: 290
        }
    });

    return createScene();
};
```

`settings.ts`:

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

`shaders/materials.ts`:

```ts
import { compileShader, composerAdd, composerEnvUv, composerFract, composerLight, composerMapSample, composerMix, composerMul, composerShine, composerSmoothstep, composerStep, composerSub, composerSurface, composerSwizzle, composerTextureSample, composerTime, composerUv, composerVec2, composerVec3, composerVec4, composerX } from 'nacatamalon/shader';

// The four colour effects, written with the shader composer: each is built once from typed nodes and
// compileShader turns it into both shader languages. Each reads its material's maps by name with
// composerMapSample.

// The surface's own colour, lit by the scene's lamps.
const lit = () => composerMul(composerSwizzle(composerSurface(), 'rgb'), composerLight());

// CHROME: the 'env' map read where the surface would reflect it (composerEnvUv), over the lit steel,
// with the lamps' highlight on top.
export const CHROME = compileShader({
    shader: 'mesh3d',
    color: composerAdd(
        composerMix(lit(), composerSwizzle(composerMapSample('env', composerEnvUv()), 'rgb'), 0.8),
        composerShine(),
    ),
});

// DISSOLVE: the 'noise' map against a threshold that rises over time. Below it the surface is cut
// away (alpha 0); just above it, it burns orange; past that it keeps the picture's colour.
const threshold = composerSub(composerMul(composerFract(composerMul(composerTime(), 0.25)), 1.2), 0.1);
const left = composerSub(composerX(composerMapSample('noise', composerUv())), threshold);
const kept = composerStep(0, left);
const burnt = composerMix(composerVec3(1, 0.55, 0.1), lit(), composerSmoothstep(0, 0.08, left));

export const DISSOLVE = compileShader({
    shader: 'mesh3d',
    color: composerVec4(composerMul(burnt, kept), kept),
});

// DETAIL: the fine 'detail' map repeated eight times, brightening and darkening the coarse picture.
// The map has mipmaps, and `scale: 8` says it is read eight times as fast as the uv, so the copy it
// is read from is the one that suits it.
export const DETAIL = compileShader({
    shader: 'mesh3d',
    color: composerMul(lit(), composerAdd(0.55, composerMul(composerX(composerMapSample('detail', composerMul(composerUv(), 8), {
        scale: 8
    })), 0.9))),
});

// WATER: the moving 'ripple' map shifts where the material's own picture is read, an indirect read.
const flow = composerVec2(composerMul(composerTime(), 0.05), composerMul(composerTime(), 0.03));
const ripple = composerSwizzle(composerMapSample('ripple', composerAdd(composerMul(composerUv(), 2), flow)), 'rg');
const shift = composerMul(composerSub(ripple, 0.5), 0.08);
const seen = composerSwizzle(composerTextureSample(composerAdd(composerUv(), shift)), 'rgb');

export const WATER = compileShader({
    shader: 'mesh3d',
    color: composerMul(composerMul(seen, composerVec3(0.55, 0.8, 1)), composerLight()),
});
```
