# Debug lines and picking

> A grid, the axes and a gizmo on each crate, and the pointer turned into a ray that places a cross on the floor and picks crates.

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

`useHelperGrid` and `useHelperAxis` draw a floor and the axes, and each crate carries a gizmo that turns with it. `screenToRay` turns the pointer into a ray in the world: met with the floor it places the white cross, and tested against the crates it picks one, which `useLines` outlines.

The crates are found by name with `findObjects`, and the camera circles with `cameraLookAt` keeping the middle in view.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import * as Settings from './settings';
import { Yard } from './scenes/demo';

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

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

`components/crate.ts`:

```ts
import { createMesh, useCubeGeometry, useHelperAxis, useTransform, useUpdate } from 'nacatamalon';
import * as Settings from '../settings';

export const Crate = ({ x, z, spin }: { x: number; z: number; spin: number; }) => {
    const place = useTransform({
        x,
        y: Settings.CRATE,
        z
    });

    createMesh({
        geometry: useCubeGeometry(),
        tint: '#b07a3c'
    });
    // Measured from the crate, so it turns with it.
    useHelperAxis({
        size: 0.9
    });
    useUpdate((delta) => {
        place.rotationY += delta * spin;
    });
};
```

`data/cross.ts`:

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

// A white cross lying flat, for where the pointer meets the floor.
export const CROSS: TLine[] = [
    {
        from: {
            x: -0.3,
            y: 0,
            z: 0
        },
        to: {
            x: 0.3,
            y: 0,
            z: 0
        },
        color: '#ffffff'
    },
    {
        from: {
            x: 0,
            y: 0,
            z: -0.3
        },
        to: {
            x: 0,
            y: 0,
            z: 0.3
        },
        color: '#ffffff'
    }
];
```

`helpers/box_edges.ts`:

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

export const boxEdges = (h: number, r: number, g: number, b: number): Float32Array => {
    const c = [[-h, -h, -h], [h, -h, -h], [h, h, -h], [-h, h, -h], [-h, -h, h], [h, -h, h], [h, h, h], [-h, h, h]];
    const pairs = [[0, 1], [1, 2], [2, 3], [3, 0], [4, 5], [5, 6], [6, 7], [7, 4], [0, 4], [1, 5], [2, 6], [3, 7]];
    const out = new Float32Array(pairs.length * 2 * RENDER.LINE_VERTEX_FLOATS);
    let o = 0;

    for (const [a, z] of pairs) {
        for (const p of [c[a], c[z]]) {
            out.set([p[0], p[1], p[2], r, g, b, 1], o);
            o += RENDER.LINE_VERTEX_FLOATS;
        }
    }

    return out;
};
```

`scenes/demo.ts`:

```ts
import { cameraLookAt, createScene, findObjects, screenToRay, useCamera3d, useGame, useHelperAxis, useHelperGrid, useLines, useDirectionalLight, usePointer, useSelf, useSpawn, useUpdate } from 'nacatamalon';
import * as Settings from '../settings';
import { Crate } from '../components/crate';
import { boxEdges } from '../helpers/box_edges';
import { CROSS } from '../data/cross';

export const Yard = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 55,
        near: 0.1,
        far: 100,
        transform: {
            y: 4
        }
    });

    useDirectionalLight({
        intensity: 1,
        ambient: 0.4,
        transform: {
            rotationX: -0.8,
            rotationY: 0.5
        }
    });

    const game = useGame();

    useHelperGrid({
        half: 5
    });
    useHelperAxis({
        size: 1.5
    });

    // Named, so findObjects finds them in a published build too, where function names are shortened.
    const crate = useSpawn(Crate, 'Crate');

    crate({
        x: -2,
        z: 0,
        spin: 0.6
    });
    crate({
        x: 0.5,
        z: -1.5,
        spin: -0.4
    });
    crate({
        x: 2,
        z: 1.5,
        spin: 1
    });

    const crates = findObjects(useSelf(), 'Crate');

    const cross = useLines({
        lines: CROSS,
        visible: false
    });

    const outline = useLines({
        lines: boxEdges(Settings.CRATE * 1.1, 1, 0.85, 0.2),
        visible: false
    });

    let picked: (typeof crates)[number]|null = null;

    const rayAt = (x: number, y: number) => screenToRay(camera, game.getWidth(), game.getHeight(), x, y);

    const pointer = usePointer();

    pointer.onMove((info) => {
        const ray = rayAt(info.screenX, info.screenY);
        // How far along the ray the floor (y = 0) is. Looking up, it never gets there.
        const t = -ray.origin.y / ray.direction.y;

        cross.visible = t > 0;
        cross.transform.x = ray.origin.x + ray.direction.x * t;
        cross.transform.z = ray.origin.z + ray.direction.z * t;
    });
    pointer.onDown((info) => {
        const ray = rayAt(info.screenX, info.screenY);

        // The nearest crate the ray passes close enough to: a sphere round each one is plenty here.
        picked = null;

        let nearest = Infinity;

        for (const crate of crates) {
            const at = crate.transform!;
            const tx = at.x - ray.origin.x;
            const ty = at.y - ray.origin.y;
            const tz = at.z - ray.origin.z;
            const t = tx * ray.direction.x + ty * ray.direction.y + tz * ray.direction.z;
            const miss = Math.hypot(tx - ray.direction.x * t, ty - ray.direction.y * t, tz - ray.direction.z * t);

            if (t > 0 && miss < Settings.CRATE * 1.2 && t < nearest) {
                nearest = t;
                picked = crate;
            }
        }
    });

    let angle = 0;

    useUpdate((delta) => {
        angle += delta * 0.25;
        camera.transform.x = Math.sin(angle) * 8;
        camera.transform.z = Math.cos(angle) * 8;
        cameraLookAt(camera, {
            x: 0,
            y: 0,
            z: 0
        });

        // The outline sits where the picked crate is, turned the way it is turned.
        outline.visible = picked !== null;

        if (picked !== null) {
            const at = picked.transform!;

            outline.transform.x = at.x;
            outline.transform.y = at.y;
            outline.transform.z = at.z;
            outline.transform.rotationY = at.rotationY;
        }
    });

    return createScene();
};
```

`settings.ts`:

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