#version 330 core
precision highp float;

// osmium all-seeing eye: a stylised eye floating in the middle of the screen, drawn over the beat
// background. The iris/pupil glance (uGaze) and the glow/pupil throb (uBeat) are driven by the shared
// BeatClock on the CPU side (osmium.eye), so it darts and pulses in time with the music. Transparent
// outside the eye + glow, so it composites over whatever is below.

in vec2 fragCoord; // pixel coords, [0, iResolution]
out vec4 fragColor;

uniform vec3  iResolution;
uniform float iTime;
uniform vec2  uGaze;   // iris/pupil offset (a bit off-centre), in centred-uv units
uniform float uBeat;   // kick energy [0,1] -> glow brighten + pupil dilation
uniform float uAlpha;  // overall opacity


void main()
{
	vec2 uv = (fragCoord - 0.5 * iResolution.xy) / iResolution.y; // centred, aspect-correct
	uv /= (1.0 + 0.05 * uBeat);                                    // whole eye pulses on the beat

	float d = length(uv);
	float ang = atan(uv.y, uv.x);
	vec3 col = vec3(0.0);
	float a = 0.0;

	// Radiating glow + rays (the "all-seeing" halo).
	float rays = 0.6 + 0.4 * sin(ang * 18.0 - iTime * 2.0);
	float glow = smoothstep(0.55, 0.14, d);
	col += vec3(0.15, 0.45, 1.0) * glow * rays * (0.35 + 0.65 * uBeat);
	a = max(a, glow * (0.28 + 0.35 * uBeat));

	// Sclera (ellipse, wider than tall).
	vec2 e = uv / vec2(0.33, 0.185);
	float ed = length(e);
	float scl = smoothstep(1.02, 0.97, ed);
	vec3 sclera = vec3(0.90, 0.94, 1.0) * (0.92 + 0.08 * sin(uv.x * 34.0 + uv.y * 12.0));
	col = mix(col, sclera, scl);
	a = max(a, scl);

	// Iris (offset by the gaze), clipped to the sclera.
	vec2 ic = uv - uGaze;
	float ir = length(ic);
	float irisR = 0.135;
	float irisM = smoothstep(irisR, irisR - 0.008, ir) * scl;
	float ia = atan(ic.y, ic.x);
	float fib = 0.5 + 0.5 * sin(ia * 44.0 + ir * 36.0 + iTime * 0.5);
	vec3 iris = mix(vec3(0.02, 0.20, 0.60), vec3(0.25, 0.75, 1.0), fib);
	iris *= 0.45 + 0.6 * (ir / irisR); // darker centre
	col = mix(col, iris, irisM);

	// Limbal ring (dark iris edge).
	float limbal = smoothstep(irisR - 0.018, irisR, ir) * step(ir, irisR) * scl;
	col = mix(col, vec3(0.0, 0.02, 0.08), limbal);

	// Pupil (dilates with the beat).
	float pupilR = 0.052 * (1.0 + 0.55 * uBeat);
	float pupM = smoothstep(pupilR, pupilR - 0.006, ir) * scl;
	col = mix(col, vec3(0.0), pupM);

	// Catchlight.
	float hl = smoothstep(0.03, 0.0, length(ic - vec2(-0.045, 0.05)));
	col += hl * 0.9 * scl;

	a = clamp(a, 0.0, 1.0) * uAlpha;
	fragColor = vec4(col, a);
}
