# Sand tracks

> A ball presses a track into sand painted in a picture, which the sand's vertex hook reads to move the plane.

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

A ball rolling over sand presses a track into it, pushing the sand aside into low banks, and the wind slowly evens it all out again. **WASD** or the arrows roll it, **R** smooths the sand. Left alone, the ball rolls by itself.

The game never touches the sand's geometry. It paints the sand's shape into a grey picture made with `createPixels`: middle grey is untouched, darker is pressed down, lighter is pushed up. Each frame it sends only the square the ball touched, with `updatePixelTexture(texture, region)`; the wind evens out the whole picture and sends it all. The sand's material reads that picture in its vertex hook, as its `tracks` map, and moves the plane by it, so shaping the sand costs a few pixels a frame instead of new geometry. The track is read at a place worked out from each corner's position, so its sides are measured, and lit, as sides, and they cast shadows because the shadow moves its corners the same way. Packed sand is darker, by how pressed it was, through `carry`.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { Beach } from './scenes/beach';
import { ACTIONS, HEIGHT, SKY, WIDTH } from './settings';

// A ball rolling over sand leaves a track with banks at its sides, and the wind slowly evens it out.
// The game only paints the sand's shape into a picture; the sand's material reads that picture in
// its vertex hook and moves the plane by it, so shaping the sand costs a few pixels sent a frame,
// not new geometry.
//
//   WASD / arrows   roll
//   R               smooth the sand
//
// Left alone, the ball rolls by itself.
const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    background: SKY,
    actions: ACTIONS
});

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

`components/ball.ts`:

```ts
import { createMesh, useDirection, useIcoSphereGeometry, useUpdate, type TMesh } from 'nacatamalon';
import { BALL, SAND } from '../settings';
import type { TSand } from './sand';

/**
 * How far the ball may go from the middle, either way.
 */
const LIMIT = SAND.size / 2 - BALL.radius * 2;

/**
 * The ball that rolls over the sand, pressing a track into it as it goes. Left alone, it rolls by
 * itself, in a figure of eight.
 */
export const Ball = ({ sand }: { sand: TSand; }): { mesh: TMesh; } => {
    const mesh = createMesh({
        geometry: useIcoSphereGeometry({
            radius: BALL.radius,
            subdivisions: 3
        }),
        tint: BALL.color,
        specular: '#ffffff',
        shininess: 40,
        castShadow: true,
        transform: {
            // Sunk into its own track.
            y: BALL.radius - SAND.depth * 0.8
        }
    });

    const move = useDirection('left', 'right', 'up', 'down');

    let idleFor = BALL.idleSeconds;
    let autoTime = 0;

    useUpdate((delta) => {
        const at = mesh.transform;

        // Up on the stick or the keys goes away from the camera, along -z.
        let { x: ix, y: iz } = move();

        idleFor = ix !== 0 || iz !== 0 ? 0 : idleFor + delta;

        if (idleFor > BALL.idleSeconds) {
            autoTime += delta * 0.35;
            ix = Math.sin(autoTime) * 4 - at.x;
            iz = Math.sin(autoTime * 2) * 2.5 - at.z;
        }

        const length = Math.hypot(ix, iz);

        if (length > 1) {
            ix /= length;
            iz /= length;
        }

        const dx = ix * BALL.speed * delta;
        const dz = iz * BALL.speed * delta;

        at.x = Math.max(-LIMIT, Math.min(LIMIT, at.x + dx));
        at.z = Math.max(-LIMIT, Math.min(LIMIT, at.z + dz));

        // Turned by as far as it went, so it looks rolled. `rotation` is the turn about z.
        at.rotationX += dz / BALL.radius;
        at.rotation -= dx / BALL.radius;

        sand.press(at.x, at.z, BALL.trackRadius);
    });

    return {
        mesh
    };
};
```

`components/sand.ts`:

```ts
import { createMaterial, createMesh, usePlaneGeometry, useUpdate } from 'nacatamalon';
import { createPixelTexture, createPixels, updatePixelTexture } from 'nacatamalon/pixels';
import { SAND, WIND } from '../settings';
import { SAND_SHADER } from '../shaders/sand';

/**
 * What the sand lets the others do: press it at a place in the world, or smooth it all.
 */
export type TSand = {
    press: (x: number, z: number, radius: number) => void;
    smooth: () => void;
};

/**
 * The grey of untouched sand: darker is pressed down, lighter is pushed up.
 */
const FLAT = 128;

/**
 * How far out of a track the sand it pushed aside reaches, in track radii, and how high it piles.
 */
const BERM = {
    reach: 1.7,
    height: 70
};

/**
 * The sand. The game only paints the shape of the sand into a picture; its material's vertex hook
 * reads that picture, one of its maps, and moves the plane by it. Nothing about the geometry
 * changes while it plays.
 *
 * The picture is grey: 128 is untouched sand, 0 pressed all the way down, 255 pushed all the way up.
 * Its pixels are written straight into `data`, four bytes each (red, green, blue, alpha), which is
 * the quickest way to paint many.
 */
export const Sand = (): TSand => {
    const shape = createPixels(SAND.mapSize, SAND.mapSize, '#808080');
    const texture = createPixelTexture(shape);

    const material = createMaterial({
        ...SAND_SHADER,
        maps: {
            // Smooth, so a track has sloping sides and not steps; clamped, so the edge of the sand
            // does not read the other side of the picture.
            tracks: {
                texture,
                smooth: true,
                wrap: 'clamp'
            }
        }
    });

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

    const setGrey = (index: number, grey: number) => {
        shape.data[index] = grey;
        shape.data[index + 1] = grey;
        shape.data[index + 2] = grey;
    };

    // The wind evens the sand out a little at a time, tracks and berms alike: the whole picture
    // changes, so the whole picture is sent again.
    let gust = 0;

    useUpdate((delta) => {
        gust += delta;

        if (gust < WIND.every) {
            return;
        }

        gust = 0;

        for (let i = 0; i < shape.data.length; i += 4) {
            const grey = shape.data[i];

            if (grey < FLAT) {
                setGrey(i, Math.min(FLAT, grey + WIND.fill));
            } else if (grey > FLAT) {
                setGrey(i, Math.max(FLAT, grey - WIND.fill));
            }
        }

        updatePixelTexture(texture);
    });

    return {
        // A round dent, deepest in the middle, with a ring of sand pushed up around it. A dent is
        // kept wherever it is deeper than what was there, and a berm only rises where nothing was
        // pressed, so a track crossing another does not fill it in. Only the square it touched is
        // sent again.
        press: (x, z, radius) => {
            const cx = (x / SAND.size + 0.5) * SAND.mapSize;
            const cy = (z / SAND.size + 0.5) * SAND.mapSize;
            const reach = radius * BERM.reach;
            const left = Math.max(0, Math.floor(cx - reach));
            const top = Math.max(0, Math.floor(cy - reach));
            const right = Math.min(SAND.mapSize - 1, Math.ceil(cx + reach));
            const bottom = Math.min(SAND.mapSize - 1, Math.ceil(cy + reach));

            if (right < left || bottom < top) {
                return;
            }

            for (let py = top; py <= bottom; py++) {
                for (let px = left; px <= right; px++) {
                    const distance = Math.hypot(px - cx, py - cy) / radius;
                    const index = (py * SAND.mapSize + px) * 4;
                    const was = shape.data[index];

                    if (distance < 1) {
                        const dent = Math.round(FLAT * distance * distance);

                        if (dent < was) {
                            setGrey(index, dent);
                        }
                    } else if (distance < BERM.reach && was >= FLAT) {
                        const along = (distance - 1) / (BERM.reach - 1);
                        const berm = Math.round(FLAT + BERM.height * Math.sin(along * Math.PI));

                        if (berm > was) {
                            setGrey(index, berm);
                        }
                    }
                }
            }

            updatePixelTexture(texture, {
                x: left,
                y: top,
                width: right - left + 1,
                height: bottom - top + 1
            });
        },
        smooth: () => {
            for (let i = 0; i < shape.data.length; i += 4) {
                setGrey(i, FLAT);
            }

            updatePixelTexture(texture);
        }
    };
};
```

`scenes/beach.ts`:

```ts
import { cameraLookAt, createScene, createText, useAction, useAmbientLight, useCamera3d, useDirectionalLight, useSpawn, useUpdate } from 'nacatamalon';
import { Ball } from '../components/ball';
import { Sand } from '../components/sand';
import { HEIGHT, SAND } from '../settings';

/**
 * Sand under a low sun, so the tracks cast shadows, and a ball rolling over it. The sand is made
 * first and handed to the ball, which presses it.
 */
export const Beach = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 50,
        transform: {
            y: 6,
            z: 6
        }
    });

    useAmbientLight({
        color: '#e8dccb',
        intensity: 0.5
    });
    useDirectionalLight({
        color: '#fff0d8',
        intensity: 1.1,
        castShadow: true,
        shadowArea: SAND.size * 1.4,
        transform: {
            // From the far side, so the wall of a track that faces the camera is in shade and the
            // track reads as a dent, not a ridge.
            rotationX: -0.85,
            rotationY: 2.6
        }
    });

    const sand = useSpawn(Sand)();

    const ball = useSpawn(Ball)({
        sand: sand.api
    });

    createText({
        text: 'WASD / ARROWS: ROLL   R: SMOOTH THE SAND',
        tint: '#5a3f22',
        zIndex: 100,
        transform: {
            x: 8,
            y: 8
        }
    });
    createText({
        text: 'SAND TRACKS · NACATAMALON',
        tint: '#5a3f22',
        zIndex: 100,
        transform: {
            x: 8,
            y: HEIGHT - 16
        }
    });

    const smooth = useAction('smooth');

    // The camera follows the ball from above, a little late.
    useUpdate((delta) => {
        if (smooth.justPressed()) {
            sand.api.smooth();
        }

        const at = ball.api.mesh.transform;
        const follow = 1 - Math.exp(-2.5 * delta);

        camera.transform.x += (at.x * 0.6 - camera.transform.x) * follow;
        camera.transform.z += (at.z * 0.6 + 5.5 - camera.transform.z) * follow;
        cameraLookAt(camera, {
            x: at.x * 0.6,
            y: 0,
            z: at.z * 0.6
        });
    });

    return createScene();
};
```

`settings.ts`:

```ts
import { INPUT, type TActionDef } from 'nacatamalon';

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

/**
 * The sky behind the dunes.
 */
export const SKY = '#f2d9b0';

/**
 * Moving as a platformer reads it (WASD or the arrows, a pad), and R to smooth the sand.
 */
export const ACTIONS: TActionDef[] = [
    ...INPUT.ACTION_PRESETS.platformer,
    {
        name: 'smooth',
        bindings: [
            {
                type: 'key',
                key: 'r'
            }
        ]
    }
];

/**
 * The sand: a plane `size` units across, with `segments` squares each way to move, and a picture of
 * its shape, `mapSize` pixels square. Pressed all the way it sinks `depth` units, and the sand it
 * pushes aside rises by up to that much.
 */
export const SAND = {
    size: 16,
    segments: 160,
    mapSize: 128,
    depth: 0.35,
    color: '#e3c48d'
};

/**
 * The wind, which evens the sand out again: how often it blows, in seconds, and how much each gust
 * evens out, in steps of the picture's grey, out of 255.
 */
export const WIND = {
    every: 0.2,
    fill: 3
};

/**
 * The ball: its size, how fast it rolls, how wide a track it leaves, in pixels of the sand's map,
 * and after how many seconds alone it rolls by itself.
 */
export const BALL = {
    radius: 0.45,
    speed: 3.2,
    trackRadius: 5,
    idleSeconds: 3,
    color: '#3f6fd8'
};
```

`shaders/sand.ts`:

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

// The sand'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 map of the sand's shape, from where the corner is (the plane runs
// from -size/2 to size/2, the map from 0 to 1), so the sides of a track are measured, and lit, as
// sides.
const onMap = composerAdd(composerDiv(composerSwizzle(corner, 'xz'), SAND.size), 0.5);

// The map named `tracks`, from 0 to 1 with untouched sand in the middle, turned into -1 (pressed
// all the way down) to 1 (pushed all the way up).
const level = composerSub(composerMul(composerX(composerMapSample('tracks', onMap)), 2), 1);

// Pressed sand is packed and darker, by how far down each corner was pressed, carried to the pixel.
const sand = rgb(SAND.color);
const pressed = composerSmoothstep(0, 1, composerMul(composerX(composerCarry()), -1));
const packed = composerMix(sand, composerMul(sand, 0.7), pressed);

export const SAND_SHADER = compileShader({
    shader: 'mesh3d',
    position: composerAdd(corner, composerVec3(0, composerMul(level, SAND.depth), 0)),
    carry: level,
    color: composerAdd(composerMul(packed, composerLight()), composerShine())
});
```
