# Mesh instances

> A wood of 1,500 pines in two draws: createMeshInstances draws one shape many times, each instance with its own place, size, colour and numbers.

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

A wood of 1,500 pines swaying in the wind, drawn in two draws: one for every trunk and one for every crown. **Up** and **Down** show more or fewer trees, and **Space** plants the wood again.

`createMeshInstances` takes what `createMesh` takes, and how many there is room for: one shape and one surface, drawn many times over. `set(i, { x, y, z, rotationY, scaleX, tint, data })` places each instance inside the group, with a colour that multiplies in and four numbers of its own, and `count` is how many are drawn. Only the instances that changed are sent to the card. The group is lit, shadowed, fogged and left out off screen as one model. Its material's corner hook runs after each instance is placed, and reads which instance a corner belongs to: `ctx.instance` and `ctx.origin`, or `composerInstanceData()` and `composerInstanceOrigin()` in the composer, which is how every tree here sways to its own beat from one shader.

## Code

`index.ts`:

```ts
import { createGame } from 'nacatamalon';
import { Forest } from './scenes/forest';
import { HEIGHT, SKY, WIDTH } from './settings';

// Many of one shape in one draw. A wood of 1,500 pines is two models made with
// createMeshInstances: every trunk is the same cylinder and every crown the same cone, each placed,
// sized and coloured by its own instance, and swayed by one material that reads which instance a
// corner belongs to.
//
//   up / down   more / fewer trees
//   space       plant the wood again
const game = createGame('#app', {
    width: WIDTH,
    height: HEIGHT,
    background: SKY,
    actions: [
        {
            name: 'more',
            bindings: [
                {
                    type: 'key',
                    key: 'ArrowUp'
                }
            ]
        },
        {
            name: 'fewer',
            bindings: [
                {
                    type: 'key',
                    key: 'ArrowDown'
                }
            ]
        },
        {
            name: 'plant',
            bindings: [
                {
                    type: 'key',
                    key: ' '
                }
            ]
        }
    ]
});

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

`components/wood.ts`:

```ts
import { createMaterial, createMesh, createMeshInstances, useConeGeometry, useCylinderGeometry, usePlaneGeometry } from 'nacatamalon';
import { useRandom } from 'nacatamalon/math';
import { SWAY } from '../shaders/sway';
import { TREE, WOOD } from '../settings';

/**
 * What the wood lets the scene do: show more or fewer of its trees, and plant them all again.
 */
export type TWood = {
    show: (trees: number) => void;
    plant: () => void;
};

/**
 * A wood of pines drawn in two draws: every trunk is one cylinder and every crown one cone, each
 * made with `createMeshInstances` and placed tree by tree with `set`.
 *
 * An instance has a place, a turn and a size inside its group, a colour that multiplies in, and
 * four numbers of its own, which the material's corner hook reads to sway each tree to its own beat.
 */
export const Wood = (): TWood => {
    const random = useRandom();

    createMesh({
        geometry: usePlaneGeometry({
            width: WOOD.size * 1.6,
            depth: WOOD.size * 1.6,
            // Fog and light are worked out at the corners: a ground this big needs some inside it.
            widthSegments: 32,
            depthSegments: 32
        }),
        tint: '#5d7a4a',
        // The ground receives the trees' shadows and casts none of its own.
        castShadow: false
    });

    // One surface for both groups: white, so each instance's own colour shows as it is.
    const material = createMaterial(SWAY);

    // The sway moves the tops past the box the engine measures round the trees: it has to know how
    // far, so it does not leave the wood out when only a leaning top is in view.
    const reach = 1;

    const trunks = createMeshInstances({
        geometry: useCylinderGeometry({
            radius: 0.5,
            height: 1,
            segments: 6
        }),
        material,
        capacity: WOOD.trees,
        boundsMargin: reach
    });

    const crowns = createMeshInstances({
        geometry: useConeGeometry({
            radius: 0.5,
            height: 1,
            segments: 7
        }),
        material,
        capacity: WOOD.trees,
        boundsMargin: reach
    });

    // How many trees are shown.
    let showing = WOOD.trees;

    // How many of each group are drawn, from the first: the rest stay on the card, undrawn.
    const show = (trees: number) => {
        showing = trees;
        trunks.count = trees;
        crowns.count = trees;
    };

    const plant = () => {
        for (let i = 0; i < WOOD.trees; i++) {
            let x: number;
            let z: number;

            // Anywhere in the wood but the clearing in the middle.
            do {
                x = random.rand(-WOOD.size / 2, WOOD.size / 2);
                z = random.rand(-WOOD.size / 2, WOOD.size / 2);
            } while (Math.hypot(x, z) < WOOD.clearing);

            const height = random.rand(TREE.height[0], TREE.height[1]);
            const trunk = height * TREE.trunk;
            const crown = height - trunk;
            const spread = crown * TREE.spread;
            // The tree's own beat: the same number for its trunk and its crown.
            const beat = random.rand();
            const shade = random.rand(0.75, 1.1);

            // Both shapes are one unit tall round their middle, so each is sized to its part of the
            // tree and stood on what is below it.
            trunks.set(i, {
                x,
                y: trunk / 2,
                z,
                scaleX: height * 0.06,
                scaleY: trunk,
                scaleZ: height * 0.06,
                tint: {
                    r: 0.42 * shade,
                    g: 0.3 * shade,
                    b: 0.2 * shade,
                    a: 1
                },
                data: [beat]
            });

            crowns.set(i, {
                x,
                y: trunk + crown / 2,
                z,
                rotationY: random.rand(Math.PI * 2),
                scaleX: spread,
                scaleY: crown,
                scaleZ: spread,
                tint: {
                    r: random.rand(0.16, 0.3) * shade,
                    g: random.rand(0.42, 0.6) * shade,
                    b: random.rand(0.2, 0.32) * shade,
                    a: 1
                },
                data: [beat]
            });
        }

        // Setting an instance past the ones drawn draws as far as it: back to what was shown.
        show(showing);
    };

    plant();

    return {
        show,
        plant
    };
};
```

`scenes/forest.ts`:

```ts
import { cameraLookAt, createScene, createText, useActions, useAmbientLight, useCamera3d, useDirectionalLight, useFog, useSpawn, useUpdate } from 'nacatamalon';
import { Wood } from '../components/wood';
import { HEIGHT, ORBIT, SKY, WOOD } from '../settings';

/**
 * A wood of pines swaying in the wind, seen from a camera going slowly round it. The arrows show
 * more or fewer trees, and space plants them all again.
 */
export const Forest = () => {
    const camera = useCamera3d({
        projection: 'perspective',
        fov: 50,
        far: 200
    });

    useAmbientLight({
        color: '#cfe0f0',
        intensity: 0.45
    });
    useDirectionalLight({
        color: '#fff0d2',
        intensity: 0.95,
        castShadow: true,
        shadowArea: WOOD.size * 1.1,
        transform: {
            rotationX: -0.75,
            rotationY: 0.7
        }
    });
    useFog({
        color: SKY,
        near: 55,
        far: 140
    });

    const wood = useSpawn(Wood)();

    createText({
        text: 'UP / DOWN: MORE / FEWER TREES    SPACE: PLANT AGAIN',
        tint: '#1d2a40',
        zIndex: 100,
        transform: {
            x: 8,
            y: 8
        }
    });

    const state = createText({
        text: '',
        tint: '#1d2a40',
        zIndex: 100,
        transform: {
            x: 8,
            y: 22
        }
    });

    createText({
        text: 'MESH INSTANCES · NACATAMALON',
        tint: '#1d2a40',
        zIndex: 100,
        transform: {
            x: 8,
            y: HEIGHT - 16
        }
    });

    const input = useActions();
    let trees = WOOD.trees;
    let shown = -1;

    useUpdate((delta, time) => {
        if (input.isDown('more')) {
            trees = Math.min(trees + WOOD.step * delta, WOOD.trees);
        }

        if (input.isDown('fewer')) {
            trees = Math.max(trees - WOOD.step * delta, 0);
        }

        if (input.justPressed('plant')) {
            wood.api.plant();
        }

        if (Math.floor(trees) !== shown) {
            shown = Math.floor(trees);
            wood.api.show(shown);
            state.text = `${shown} TREES IN 2 DRAWS: THE TRUNKS AND THE CROWNS`;
        }

        const angle = time * ORBIT.speed * Math.PI * 2;

        camera.transform.x = Math.sin(angle) * ORBIT.distance;
        camera.transform.y = ORBIT.height;
        camera.transform.z = Math.cos(angle) * ORBIT.distance;
        cameraLookAt(camera, {
            x: 0,
            y: 2,
            z: 0
        });
    });

    return createScene();
};
```

`settings.ts`:

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

/**
 * The sky, and the haze the far trees fade into.
 */
export const SKY = '#bcd7e8';

/**
 * The wood: a square `size` units across with room for `trees` trees, `step` more or fewer shown
 * each second an arrow is held, and none planted within `clearing` units of the middle.
 */
export const WOOD = {
    size: 80,
    trees: 1500,
    step: 600,
    clearing: 5
};

/**
 * A tree: how tall it can be, how much of that is trunk, and how wide its crown is for its height.
 */
export const TREE = {
    height: [2.5, 6.5] as [number, number],
    trunk: 0.28,
    spread: 0.38
};

/**
 * The wind: which way it blows over the ground (x, z), how far it leans a tree for each unit of
 * height squared, and how fast the trees sway.
 */
export const WIND = {
    x: 1,
    z: 0.4,
    lean: 0.012,
    speed: 1.7
};

/**
 * How fast the camera goes round, in turns a second, and how far out and up it stays.
 */
export const ORBIT = {
    speed: 0.02,
    distance: 50,
    height: 20
};
```

`shaders/sway.ts`:

```ts
import {
    compileShader, composerAdd, composerInstanceData, composerInstanceOrigin, composerMul, composerSin, composerTime,
    composerVec3, composerVertexPosition, composerX, composerY, composerZ
} from 'nacatamalon/shader';
import { WIND } from '../settings';

// The sway of every tree, written once with the shader composer so it draws on both cards.
//
// On a model drawn as many, the corner hook runs after each instance has been placed: the corner is
// already where it stands in the wood, so the wind is one direction for all of them.

const corner = composerVertexPosition();

// Where the instance this corner belongs to stands, and its four numbers: the first is the tree's
// own beat, the same for its trunk and its crown, so the two sway as one.
const foot = composerInstanceOrigin();
const beat = composerX(composerInstanceData());

// Each tree a little out of step with its neighbours, and a slow wave crossing the wood.
const phase = composerAdd(
    composerMul(composerTime(), WIND.speed),
    composerAdd(composerMul(beat, Math.PI * 2), composerAdd(composerMul(composerX(foot), 0.21), composerMul(composerZ(foot), 0.13)))
);

// The ground is at 0, so a corner's height is how far up the tree it is: the foot stays put and the
// top leans the most.
const height = composerY(corner);
const lean = composerMul(composerSin(phase), composerMul(composerMul(height, height), WIND.lean));

export const SWAY = compileShader({
    shader: 'mesh3d',
    position: composerAdd(corner, composerVec3(composerMul(lean, WIND.x), 0, composerMul(lean, WIND.z)))
});
```
