# Toon shading

> A model's material has two hooks: a colour one that cuts the light into bands and a vertex one that ripples the surface.

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

A model material has **two hooks**, and you may write either, both or neither. Left is a plain sphere, middle has a colour hook that cuts the light into hard bands, right has a vertex hook that ripples the surface. Leave a hook out and the engine's own stands in.

The ripple is the interesting one: after the vertices move, the engine **measures again which way the surface faces**, by calling the hook twice more a hair away. Without that the sphere would ripple and still be lit as a smooth ball, which reads as the light being broken rather than the shape being moved.

## Code

`index.ts`:

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

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

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

`components/spheres.ts`:

```ts
import { createMaterial, createMesh, getColor, useUpdate, useSphereGeometry } from 'nacatamalon';

import { TOON_WGSL, TOON_GLSL, WOBBLE_WGSL, WOBBLE_GLSL } from '../shaders/spheres';

export const Spheres = () => {
    const geometry = useSphereGeometry({
        radius: 1,
        segments: 32,
        rings: 16
    });

    const orange = getColor('#e8a03c');

    // Left: no material of its own, which is the shader the engine has always used.
    const plain = createMesh({
        geometry,
        tint: orange,
        transform: {
            x: -2.6
        }
    });

    // Middle: a colour hook. The shape is untouched.
    const toon = createMaterial({
        name: 'toon',
        shader: 'mesh3d',
        tint: orange,
        fragment: TOON_WGSL,
        fragmentGlsl: TOON_GLSL,
        uniforms: {
            bands: 4,
            rim: [0.25, 0.55, 1, 1]
        },
    });

    const banded = createMesh({
        geometry,
        material: toon
    });

    // Right: a corner hook. The colour is untouched, and it is lit as the shape it became.
    const wobble = createMaterial({
        name: 'wobble',
        shader: 'mesh3d',
        tint: orange,
        vertex: WOBBLE_WGSL,
        vertexGlsl: WOBBLE_GLSL,
        uniforms: {
            amount: 0.16,
            tightness: 7
        },
    });

    const rippling = createMesh({
        geometry,
        material: wobble,
        transform: {
            x: 2.6
        }
    });

    useUpdate((delta) => {
        for (const mesh of [plain, banded, rippling]) {
            mesh.transform.rotationY += delta * 0.5;
        }
    });
};
```

`scenes/demo.ts`:

```ts
import { createScene, useCamera3d, useDirectionalLight, useSpawn } from 'nacatamalon';

import { Spheres } from '../components/spheres';

export const Game = () => {
    useCamera3d({
        projection: 'perspective',
        fov: 50,
        transform: {
            z: 6.5
        }
    });
    useDirectionalLight({
        color: '#fff0d8',
        intensity: 1.2,
        ambient: 0.18,
        transform: {
            rotationX: -0.5,
            rotationY: 0.6
        }
    });

    useSpawn(Spheres)();

    return createScene();
};
```

`settings.ts`:

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

`shaders/spheres.ts`:

```ts
export const TOON_WGSL = `
fn effect(surface: vec4<f32>, ctx: FragContext) -> vec4<f32> {
    let steps = floor(ctx.light.g * mu.bands) / mu.bands;
    let rim = pow(1.0 - max(dot(normalize(ctx.normal), ctx.viewDir), 0.0), 3.0);
    return vec4<f32>(surface.rgb * steps + mu.rim.rgb * rim, surface.a);
}
`;

export const TOON_GLSL = `
vec4 effect(vec4 surface, FragContext ctx) {
    float steps = floor(ctx.light.g * mu.bands) / mu.bands;
    float rim = pow(1.0 - max(dot(normalize(ctx.normal), ctx.viewDir), 0.0), 3.0);
    return vec4(surface.rgb * steps + mu.rim.rgb * rim, surface.a);
}
`;

// Moving the corners. The engine re-measures which way the surface faces afterwards, by sampling
// this hook twice more a hair away, so the ripples are LIT as ripples. Without that a wobbling
// model is lit as though it were still a smooth ball, and it reads as broken light.
export const WOBBLE_WGSL = `
fn vertex(pos: vec3<f32>, ctx: VertContext) -> vec3<f32> {
    let wave = sin(pos.y * mu.tightness + mu.time * 3.0) * mu.amount;
    return pos + ctx.normal * wave;
}
`;

export const WOBBLE_GLSL = `
vec3 vertex(vec3 pos, VertContext ctx) {
    float wave = sin(pos.y * mu.tightness + mu.time * 3.0) * mu.amount;
    return pos + ctx.normal * wave;
}
`;
```
