# Matcap

> A diorama with no lamp: each model is coloured by matcap(), a picture of a ball already lit painted with paintMatcap(), and the floor's orange comes up onto them with groundBounce().

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

Press **space** to turn the ground's bounce on and off.

There is not a single light in this scene. `matcap(texture, { tint })` is a material recipe that colours a model with a picture of a ball already lit, read by which way each part faces the camera: its colour, its shadow and its shine. It is the soft look of a clay model or a product shot, with the light always coming from the same side of the screen.

The pictures are painted by the example with `paintMatcap({ base, shade, shine, gloss })` from `nacatamalon/pixels`, one per colour. A matcap from a 3D program loads just the same.

On top of each material, the `groundBounce({ color, reach, amount })` step brings the floor's orange up onto what stands on it: more the closer a part is to the ground and the more it looks down. Its amount is a uniform, so space changes it while the game runs.

## Code

`index.ts`:

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

const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    keep: 'height',
    fullscreenScaling: 'contain',
    background: FLOOR.far,
    actions: ACTIONS
});

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

`art/floor.ts`:

```ts
import { createPixels, mapPixels } from 'nacatamalon/pixels';
import type { TPixels } from 'nacatamalon/pixels';

const rgb = (hex: string): [number, number, number] => {
    const n = parseInt(hex.slice(1), 16);
    return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
};

const mix = (a: number, b: number, t: number): number => a + (b - a) * t;

/**
 * The floor's picture: four colours, one at each corner, run smoothly into each other.
 */
export const paintFloor = (corners: { near: string; left: string; right: string; far: string }, size = 32): TPixels => {
    const near = rgb(corners.near);
    const left = rgb(corners.left);
    const right = rgb(corners.right);
    const far = rgb(corners.far);

    return mapPixels(createPixels(size, size), (_color, px, py) => {
        const u = px / (size - 1);
        const v = py / (size - 1);
        const channel = (i: 0 | 1 | 2): number => mix(mix(far[i], right[i], u), mix(left[i], near[i], u), v);
        return {
            r: channel(0),
            g: channel(1),
            b: channel(2),
            a: 1
        };
    });
};
```

`components/floor.ts`:

```ts
import { createMaterial, createMesh, usePlaneGeometry } from 'nacatamalon';
import { createPixelTexture } from 'nacatamalon/pixels';
import { unlitLighting } from 'nacatamalon/shader';
import { paintFloor } from '../art/floor';
import { FLOOR } from '../settings';

export const Floor = () => createMesh({
    geometry: usePlaneGeometry({
        width: FLOOR.size,
        depth: FLOOR.size
    }),
    // No lamp lights it: its colours are the ones painted.
    material: createMaterial({
        shader: 'mesh3d',
        lighting: unlitLighting(),
        texture: createPixelTexture(paintFloor(FLOOR, 256))
    })
});
```

`components/hud.ts`:

```ts
import { createText, useAction, useGame, useLoadBitmapFont, useScreenSpace, useUpdate } from 'nacatamalon';
import type { TMesh } from 'nacatamalon';
import { BOUNCE } from '../settings';

export const Hud = (props: TMesh[]) => {
    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 hint = createText({
        text: 'SPACE BOUNCE ON',
        font,
        tint: '#fff4e8',
        transform: {
            scaleX: 2,
            scaleY: 2
        }
    });

    const game = useGame();
    const toggle = useAction('toggle');
    let bouncing = true;

    const place = () => {
        hint.transform.x = game.getWidth() / 2 - hint.text.length * 8;
        hint.transform.y = game.getHeight() - 48;
    };

    place();
    game.onResized(place);

    // How much the floor bounces onto them is a uniform of each material, so it changes while it runs.
    useUpdate(() => {
        if (toggle.justPressed()) {
            bouncing = !bouncing;
            props.forEach((prop) => {
                prop.material.uniforms!.groundBounceAmount = bouncing ? BOUNCE.amount : 0;
            });
            hint.text = bouncing ? 'SPACE BOUNCE ON' : 'SPACE BOUNCE OFF';
            place();
        }
    });
};
```

`components/prop.ts`:

```ts
import { createMaterial, createMesh, matcap as matcapOf, useBlobShadow, useConeGeometry, useCubeGeometry, useCylinderGeometry, useSphereGeometry, useTorusGeometry, useUpdate } from 'nacatamalon';
import type { TGeometry, TTexture } from 'nacatamalon';
import { groundBounce } from 'nacatamalon/shader';
import { BOUNCE, PROPS } from '../settings';

type TPropProps = {
    prop: (typeof PROPS)[number];
    matcap: TTexture;
};

const shapeOf = (prop: TPropProps['prop']): { geometry: TGeometry; rest: number } => {
    const s = prop.size;
    switch (prop.shape) {
        case 'sphere':
            return {
                geometry: useSphereGeometry({
                    radius: s,
                    segments: 40,
                    rings: 28
                }),
                rest: s
            };
        case 'cube':
            return {
                geometry: useCubeGeometry({
                    width: s,
                    height: s,
                    depth: s
                }),
                rest: s / 2
            };
        case 'torus':
            return {
                geometry: useTorusGeometry({
                    radius: s,
                    tube: s * 0.45,
                    radialSegments: 20,
                    tubularSegments: 48
                }),
                rest: s * 1.45
            };
        case 'cone':
            return {
                geometry: useConeGeometry({
                    radius: s,
                    height: s * 2,
                    segments: 40
                }),
                rest: s
            };
        case 'cylinder':
            return {
                geometry: useCylinderGeometry({
                    radius: s,
                    height: s * 2,
                    segments: 40
                }),
                rest: s
            };
    }
};

export const Prop = ({ prop, matcap }: TPropProps) => {
    const { geometry, rest } = shapeOf(prop);

    // The matcap colours it, lit as it was painted; the floor's orange comes up onto it after.
    const mesh = createMesh({
        geometry,
        material: createMaterial({
            ...matcapOf(matcap),
            steps: [groundBounce(BOUNCE)]
        }),
        transform: {
            x: prop.x,
            y: rest,
            z: prop.z
        }
    });

    // A soft dark disc under it in place of a cast shadow: the scene has no lamp to cast one.
    useBlobShadow({
        target: mesh,
        radius: prop.size * 1.3,
        opacity: 0.35,
        softness: 0.6,
        followHeight: prop.hops === true
    });

    useUpdate((delta, time) => {
        if (prop.hops) {
            mesh.transform.y = rest + Math.abs(Math.sin(time * 2.2)) * 1.3;
        } else if (prop.shape === 'torus') {
            mesh.transform.rotationY += delta * 0.6;
        } else {
            mesh.transform.rotationY += delta * 0.35;
        }
    });

    return mesh;
};
```

`scenes/demo.ts`:

```ts
import { createScene, useCamera3d, useSpawn } from 'nacatamalon';
import { createPixelTexture, paintMatcap } from 'nacatamalon/pixels';
import { Floor } from '../components/floor';
import { Hud } from '../components/hud';
import { Prop } from '../components/prop';
import { MATCAPS, PROPS } from '../settings';
import type { TMatcapName } from '../settings';

export const Diorama = () => {
    useCamera3d({
        projection: 'perspective',
        fov: 50,
        transform: {
            y: 4.6,
            z: 4.6,
            rotationX: -0.8
        }
    });

    // No lamp at all: every colour comes from a picture.
    useSpawn(Floor)();

    const matcaps = Object.fromEntries(
        Object.entries(MATCAPS).map(([name, colors]) => [name, createPixelTexture(paintMatcap(colors))]),
    ) as Record<TMatcapName, ReturnType<typeof createPixelTexture>>;

    const spawnProp = useSpawn(Prop);
    const props = PROPS.map((prop) => spawnProp({
        prop,
        matcap: matcaps[prop.matcap]
    }).api);

    useSpawn(Hud)(props);

    return createScene();
};
```

`settings.ts`:

```ts
import type { TActionMap } from 'nacatamalon';

export const WIDTH = 640;
export const HEIGHT = 480;

// The floor's four corners, as a 2 x 2 picture would give them: the colours run into each other
// across the whole floor. The far one is the game's background too, so the floor has no edge.
export const FLOOR = {
    near: '#ff8a3d',
    left: '#f2733a',
    right: '#ffa04a',
    far: '#e8643a',
    size: 60
};

// How the floor's orange bounces onto what stands on it (groundBounce): the closer to the ground
// and the more a face looks down, the more orange it gets.
export const BOUNCE = {
    color: '#ff7a33',
    reach: 1.4,
    amount: 0.55
};

// Each matcap is a ball painted lit, as the camera sees it (paintMatcap): its colour, its dark
// side and how glossy, lit from up and to the left.
export const MATCAPS = {
    white: {
        shade: '#8f7f86',
        base: '#f4ece6',
        gloss: 0.5
    },
    red: {
        shade: '#5a1424',
        base: '#e2414b',
        gloss: 0.6
    },
    teal: {
        shade: '#123c4a',
        base: '#3fb3b0',
        gloss: 0.8
    },
    yellow: {
        shade: '#6a3a10',
        base: '#ffc93f',
        gloss: 0.4
    },
    brown: {
        shade: '#2a1610',
        base: '#7a4a32',
        gloss: 0.3
    }
};

export type TMatcapName = keyof typeof MATCAPS;

// What stands on the floor, and which matcap colours it.
export const PROPS: { shape: 'sphere' | 'cube' | 'torus' | 'cone' | 'cylinder'; matcap: TMatcapName; x: number; z: number; size: number; hops?: boolean }[] = [
    {
        shape: 'sphere',
        matcap: 'white',
        x: 0,
        z: 0.4,
        size: 0.6,
        hops: true
    },
    {
        shape: 'cube',
        matcap: 'red',
        x: -2.1,
        z: -0.4,
        size: 1
    },
    {
        shape: 'torus',
        matcap: 'teal',
        x: 2.1,
        z: -0.3,
        size: 0.55
    },
    {
        shape: 'cone',
        matcap: 'yellow',
        x: -1.2,
        z: -2.4,
        size: 0.6
    },
    {
        shape: 'cylinder',
        matcap: 'brown',
        x: 1.3,
        z: -2.5,
        size: 0.5
    }
];

export const ACTIONS: TActionMap = [
    {
        name: 'toggle',
        bindings: [
            {
                type: 'key',
                key: ' '
            },
            {
                type: 'button',
                button: 'a'
            }
        ]
    }
];
```
