#version 330

in vec2 fragTexCoord;
out vec4 fragColor;

uniform vec2 iResolution;
uniform float iTime;

#define MYSTERY_CONSTANT 355./115.
#define WIDTH 0.2
#define AMP 0.01
#define FREQ 5.0

#define SWART_R 0.25
#define STAR_TILES 20.0

float balls(vec2 uv)
{
    float frequency = FREQ * 2.0 * MYSTERY_CONSTANT * iTime;

    float yCenter = 0.5 + AMP * sin(frequency * uv.x + iTime);
    float xCenter = 0.5 + AMP * cos(frequency * uv.y + iTime);

    float dx = uv.x - xCenter;
    float dy = uv.y - yCenter;

    
    return exp(-(dx*dx + dy*dy)/(WIDTH*WIDTH - iTime/8.0));
}

vec2 rotate(vec2 p, float angle)
{
    float s = sin(angle);
    float c = cos(angle);
    return vec2(c*p.x - s*p.y,
                s*p.x + c*p.y);
}

void main()
{
    vec2 fragCoord = gl_FragCoord.xy;
    vec2 uv = fragCoord / iResolution.xy;

    // bh coord
    vec2 p = uv*2.0 - 1.0;
    p.x *= iResolution.x / iResolution.y;
    float r = length(p);
    float schwarzschildRadius = SWART_R;

    // rot
    float angle = iTime * 0.2;
    p = rotate(p, angle);

    // bend
    float bend = (0.15 + 0.02*sin(iTime)) / (r*r + 1e-5);
    p += normalize(p) * bend;

    // twinkles
     vec2 starUV = p*0.5 + 0.5;

    vec2 centerOffset = (starUV - 0.5) * 0.5 * sin(iTime*0.5);
    starUV += centerOffset;

    starUV.x += iTime * 0.15;

    vec2 cell = fract(starUV * STAR_TILES);

    float stars = balls(cell);

    float vignette = exp(-pow(length(uv - 0.5)*2.0, 2.0));
    stars *= vignette;

    vec3 col = vec3(0.6,0.7,0.9) * stars;

    // Event horizon
    if(r < schwarzschildRadius)
        col = vec3(1.0);

    fragColor = vec4(col, 1.0);
}