# Click what you see

> castRay meets the pieces on a table as they are drawn, coins as instances included; rayOnPlane finds the felt under the pointer to put them down.

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

**Click** a piece to pick it up, and click the felt to put it down.

No physics here. `screenToRay` turns the pointer into a ray from the camera, and `castRay` says what that ray meets among the models, as they are drawn: the nearest first, with the point where it touched. It reaches the coins too, which are instances of one mesh, and says which one. What is under the pointer is drawn a little brighter.

To put a piece down, `rayOnPlane` finds where the same ray crosses the table's top, a flat plane, and the piece goes there.

## Code

`index.ts`:

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

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

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

`components/hand.ts`:

```ts
import { castRay, createMesh, createText, rayOnPlane, screenToRay, useGame, useLoadBitmapFont, usePointer, useScreenSpace, useSpawn, useTorusGeometry, useUpdate } from 'nacatamalon';
import type { TCamera3d, TGameObject, TRay, TRayHit } from 'nacatamalon';
import type { TPiece, TPieces } from './pieces';
import { HEIGHT, HIGHLIGHT, LIFT, TABLE } from '../settings';

const FONT = {
    json: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.json',
    atlas: '/example-assets/fonts/bitmaps/nacatamal-arcade/nacatamal-arcade.png'
};

// A ring on the felt where the pointer is: a ray met against the table's plane, no model needed.
const Cursor = () => createMesh({
    geometry: useTorusGeometry({
        radius: 0.18,
        tube: 0.02
    }),
    tint: '#ffffff',
    castShadow: false
});

const Labels = () => {
    useScreenSpace();

    const font = useLoadBitmapFont(FONT);

    createText({
        text: 'CLICK A PIECE TO PICK IT UP, CLICK THE FELT TO PUT IT DOWN',
        font,
        tint: '#8c9aa6',
        transform: {
            x: 8,
            y: HEIGHT - 18
        }
    });

    return createText({
        text: '',
        font,
        transform: {
            x: 8,
            y: 8
        }
    });
};

// What is under the pointer, every frame: a ray from it, met against everything on the table as it
// is drawn, nearest first. What it meets is lit up; a click picks it up, and the next puts it down
// where the ray meets the felt.
export const Hand = (camera: TCamera3d, scene: TGameObject, { pieces, coins, coinPlaces }: TPieces) => {
    const game = useGame();
    const pointer = usePointer();
    const cursor = Cursor();
    const label = useSpawn(Labels)().api;
    let lit: TPiece | null = null;
    let litCoin: number | null = null;
    let held: TPiece | null = null;

    const pieceOf = (hit: TRayHit) => pieces.find((piece) => piece.box === hit.box) ?? null;
    // The nearest thing the ray meets, leaving out the ring and what is being carried.
    const nearest = (ray: TRay) => castRay(ray, scene).find((hit) => hit.mesh !== cursor && (held === null || hit.box !== held.box));

    const light = (piece: TPiece | null, on: boolean) => {
        if (piece !== null) {
            piece.mesh.material.tint = on
                ? {
                    r: Math.min(1, piece.tint.r * HIGHLIGHT),
                    g: Math.min(1, piece.tint.g * HIGHLIGHT),
                    b: Math.min(1, piece.tint.b * HIGHLIGHT),
                    a: 1
                }
                : piece.tint;
        }
    };

    const lightCoin = (i: number | null, on: boolean) => {
        if (i !== null) {
            coins.set(i, {
                ...coinPlaces[i]!,
                tint: on ? '#fff2a8' : '#ffffff'
            });
        }
    };

    pointer.onDown((info) => {
        const ray = screenToRay(camera, game.getWidth(), game.getHeight(), info.screenX, info.screenY);

        if (held !== null) {
            const at = rayOnPlane(ray, {
                point: {
                    x: 0,
                    y: TABLE.top,
                    z: 0
                }
            });

            if (at !== null) {
                held.box.transform!.x = at.point.x;
                held.box.transform!.y = TABLE.top + held.half;
                held.box.transform!.z = at.point.z;
                held = null;
            }

            return;
        }

        const hit = nearest(ray);

        held = hit === undefined ? null : pieceOf(hit);
    });

    useUpdate((_delta, time) => {
        const at = pointer.position();

        if (at === null) {
            return;
        }

        const ray = screenToRay(camera, game.getWidth(), game.getHeight(), at.screenX, at.screenY);

        const onFelt = rayOnPlane(ray, {
            point: {
                x: 0,
                y: TABLE.top,
                z: 0
            }
        });

        if (onFelt !== null) {
            cursor.transform.x = onFelt.point.x;
            cursor.transform.y = TABLE.top + 0.01;
            cursor.transform.z = onFelt.point.z;
        }

        // What is carried floats over the felt under the pointer.
        if (held !== null && onFelt !== null) {
            held.box.transform!.x = onFelt.point.x;
            held.box.transform!.y = TABLE.top + held.half + LIFT + Math.sin(time * 4) * 0.04;
            held.box.transform!.z = onFelt.point.z;
        }

        const hit = nearest(ray);
        const piece = hit === undefined ? null : pieceOf(hit);
        const coin = hit !== undefined && hit.mesh === coins ? hit.instance : null;

        if (piece !== lit) {
            light(lit, false);
            light(piece, true);
            lit = piece;
        }

        if (coin !== litCoin) {
            lightCoin(litCoin, false);
            lightCoin(coin, true);
            litCoin = coin;
        }

        label.text = hit === undefined
            ? ''
            : (piece !== null ? piece.name : coin !== null ? 'COIN ' + (coin + 1) : 'THE TABLE') + '  ' + hit.distance.toFixed(2) + ' AWAY';
    });
};
```

`components/pieces.ts`:

```ts
import { createMaterial, createMesh, createMeshInstances, useCubeGeometry, useCylinderGeometry, useLatheGeometry, useSpawn, useTransform } from 'nacatamalon';
import type { TColor, TGeometry, TGameObject, TMesh, TMeshInstances } from 'nacatamalon';
import { COINS, TABLE } from '../settings';

export type TPiece = { name: string; box: TGameObject; mesh: TMesh; tint: TColor; half: number };

const colorOf = (hex: string): TColor => ({
    r: parseInt(hex.slice(1, 3), 16) / 255,
    g: parseInt(hex.slice(3, 5), 16) / 255,
    b: parseInt(hex.slice(5, 7), 16) / 255,
    a: 1
});

// One thing on the table, in a box of its own so it can be picked up and put down.
const Thing = ({ geometry, tint, x, z, half }: { geometry: TGeometry; tint: string; x: number; z: number; half: number }) => {
    useTransform({
        x,
        y: TABLE.top + half,
        z
    });

    const mesh = createMesh({
        geometry,
        material: createMaterial({
            shader: 'mesh3d',
            tint,
            specular: '#505050',
            shininess: 30,
            perPixel: true
        })
    });

    return {
        mesh,
        tint: colorOf(tint)
    };
};

// The pieces, each its own object, and a pile of coins drawn as instances of one model.
export const Pieces = () => {
    const spawn = useSpawn(Thing);

    const die = useCubeGeometry({
        width: 0.5,
        height: 0.5,
        depth: 0.5,
        bevel: {
            size: 0.08,
            segments: 3
        }
    });

    const chip = useCylinderGeometry({
        radius: 0.28,
        height: 0.08,
        segments: 32
    });

    const vase = useLatheGeometry({
        profile: [
            {
                x: 0,
                y: -0.45
            },
            {
                x: 0.25,
                y: -0.45
            },
            {
                x: 0.3,
                y: -0.1
            },
            {
                x: 0.18,
                y: 0.3
            },
            {
                x: 0.22,
                y: 0.45
            }
        ],
        creaseAngle: Math.PI / 6
    });

    const made = [['RED DIE', die, '#d84a4a', -2.2, -0.8, 0.25], ['BLUE DIE', die, '#4a78d8', -1.3, 0.6, 0.25], ['CHIP', chip, '#e8c547', 0.2, -1, 0.04], ['GREEN CHIP', chip, '#6ad89a', 0.8, 0.9, 0.04], ['VASE', vase, '#c9a0ff', 2.3, -0.5, 0.45]] as const;

    const pieces: TPiece[] = made.map(([name, geometry, tint, x, z, half]) => {
        const thing = spawn({
            geometry,
            tint,
            x,
            z,
            half
        });

        return {
            name,
            box: thing,
            mesh: thing.api.mesh,
            tint: thing.api.tint,
            half
        };
    });

    // The coins: one model drawn eight times, in one draw. A ray says which one it met.
    const coins = createMeshInstances({
        geometry: useCylinderGeometry({
            radius: 0.16,
            height: 0.04,
            segments: 24
        }),
        capacity: COINS,
        tint: '#d8b04a'
    }) as TMeshInstances;

    const coinPlaces = Array.from({
        length: COINS
    }, (_, i) => ({
        x: -0.6 + (i % 4) * 0.4,
        y: TABLE.top + 0.02,
        z: 1.5 + Math.floor(i / 4) * 0.4
    }));

    coinPlaces.forEach((place, i) => coins.set(i, place));

    return {
        pieces,
        coins,
        coinPlaces
    };
};

export type TPieces = ReturnType<typeof Pieces>;
```

`components/table.ts`:

```ts
import { createMaterial, createMesh, useCubeGeometry } from 'nacatamalon';
import { TABLE } from '../settings';

// The felt, on a table top with its edges rounded off.
export const Table = () => {
    createMesh({
        geometry: useCubeGeometry({
            width: TABLE.width,
            height: TABLE.height,
            depth: TABLE.depth,
            bevel: {
                size: 0.1,
                segments: 3
            }
        }),
        material: createMaterial({
            shader: 'mesh3d',
            tint: '#1f6b3a',
            perPixel: true
        }),
        transform: {
            y: TABLE.top - TABLE.height / 2
        }
    });
};
```

`scenes/demo.ts`:

```ts
import { cameraLookAt, createScene, useCamera3d, useDirectionalLight, useSelf, useSpawn } from 'nacatamalon';
import { Hand } from '../components/hand';
import { Pieces } from '../components/pieces';
import { Table as Felt } from '../components/table';

export const Table = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 45,
        transform: {
            y: 5,
            z: 5.5
        }
    });

    cameraLookAt(camera, {
        x: 0,
        y: 0,
        z: 0.3
    });
    useDirectionalLight({
        intensity: 1,
        ambient: 0.3,
        castShadow: true,
        transform: {
            rotationX: -1,
            rotationY: 0.4
        }
    });

    // The whole scene is where the ray looks.
    const scene = useSelf();

    useSpawn(Felt)();

    const pieces = useSpawn(Pieces)().api;

    useSpawn(Hand)(camera, scene, pieces);

    return createScene();
};
```

`settings.ts`:

```ts
export const WIDTH = 640;
export const HEIGHT = 400;

export const TABLE = {
    width: 7,
    height: 0.3,
    depth: 4.5,
    // Its top, where things stand and where the pointer is followed across it.
    top: 0.3
};

// How much brighter what is under the pointer is drawn.
export const HIGHLIGHT = 1.6;
// How high something picked up is carried.
export const LIFT = 0.5;
export const COINS = 8;
```
