// STAGE: a swarm. The chorus in numbers, flocking through a flow field.
//
// The stage owns the flocking; the song owns what is flocking. A swarm of
// notched hexagons and a swarm of hollow circles are not the same video, and
// with the old library they would have been the same scene.

export const swarm = {
    name: 'Swarm',
    family: 'organic',
    kind: 'fragment',
    consumes: ['cast', 'ink', 'staging'],
    texture: 0.5,
    traits: ['shape', 'camera', 'style'],

    params: {
        count:   { type: 'int',   range: [8, 48],     default: 24,  uniform: 'u_count', bias: 'density' },
        size:    { type: 'float', range: [0.02, 0.14],default: 0.05,uniform: 'u_size' },
        speed:   { type: 'float', range: [0.05, 0.9], default: 0.25,uniform: 'u_speed', bias: 'motion', rate: true },
        cohesion:{ type: 'float', range: [0, 1],      default: 0.5, uniform: 'u_cohesion' },
        field:   { type: 'float', range: [0.4, 3.0],  default: 1.2, uniform: 'u_field' },
        palette: { type: 'palette', count: 4 },
    },

    reactive: {
        size:  { feature: 'bandLow', amount: 0.2 },
    },

    shader: `
vec4 scene(vec2 uv, vec2 p) {
    p = sigCamera(p);
    float t = u_time * u_speed + u_seed;

    vec3 col = pal(0) * 0.13;

    for (int i = 0; i < 48; i++) {
        if (i >= u_count) break;
        float fi = float(i);
        // Each member has a home on the song's lattice and rides the same flow
        // field away from it, which is what makes it a swarm rather than a
        // scatter — cohesion decides how far it is allowed to stray.
        vec3 node = stageNode(fi, float(u_count));
        vec2 flow = curl(node.xy * u_field + t * 0.15, t * 0.1);
        vec2 pos = node.xy + flow * mix(0.05, 0.45, u_cohesion);
        pos += vec2(sin(t * 0.7 + fi), cos(t * 0.6 + fi * 1.3)) * 0.06;

        vec2 q = (p - pos) / max(u_size * node.z, 1e-3);
        q = rot(atan(flow.y, flow.x)) * q;          // they face where they go
        float d = castChorus(q) * u_size * node.z;

        col = mix(col, pal(i + 1), inkMask(d, uv));
        col += pal(2) * 0.3 * 0.004 / (0.02 + abs(d));
    }

    return vec4(inkValue(col), 1.0);
}
`,
};

export default swarm;
