#define PI 3.1415926538

float brightness(vec4 col)
{
    return (col.r + col.g + col.b) / 3.0;
}

bool isInside(float x, float y, vec2 res)
{
    return !(x < 0.0 || y < 0.0 || x > res.x || y > res.y);
}

vec4 blur(float x, float y, vec2 res, float blurAmount)
{
    vec4 px = vec4(0, 0, 0, 0);
    for (float xx = x - blurAmount; xx <= x + blurAmount; xx++)
    {
        for (float yy = y - blurAmount; yy <= y + blurAmount; yy++)
        {
            px += texture(iChannel0, vec2(xx, yy) / res);
        }
    }
    
    float numSamples = (blurAmount * 2.0 + 1.0) * (blurAmount * 2.0 + 1.0);
    
    return px / numSamples;
}

const float burstMaxSize = 0.05;
const float burstMinSize = 0.05;

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    // Normalized pixel coordinates (from 0 to 1)
    vec2 uv = fragCoord/iResolution.xy;
    
    vec4 pixel = texture(iChannel0, uv);
    
    float burstMaxDistance = length(burstMaxSize * iResolution.xy);
    float burstMinDistance = length(burstMinSize * iResolution.xy);
    
    // Semi-random. Some stars will have different numbers of spikes
    float numBurstSpikes = 6.0; //int((fragCoord.x + fragCoord.y) % 3) * 2 + 4;
    
    float rotationOffset = iTime / 4.0;
    for (float a = rotationOffset; a < numBurstSpikes + rotationOffset; a++)
    {
        float angle = (a / numBurstSpikes) * 2.0 * PI;
        float maxXLength = cos(angle) * burstMaxDistance;
        float maxYLength = sin(angle) * burstMaxDistance;
        
        float roundX = fragCoord.x;
        float roundY = fragCoord.y;
        float realX = fragCoord.x;
        float realY = fragCoord.y;
        float x = fragCoord.x;
        float y = fragCoord.y;
        float dist = 0.0;
        
        float strength = 1.0;
        if (a == 0.0 || a == 3.0)
            strength = 2.0;
        
        while (isInside(x, y, iResolution.xy) && dist < (burstMaxDistance / strength) && brightness(texture(iChannel0, vec2(x, y) / iResolution.xy)) < 0.9)
        //while (isInside(x, y, iResolution.xy) && dist < (burstMaxDistance / strength) && brightness(blur(x, y, iResolution.xy, 2.0)) < 0.9)
        {
            x += cos(angle);
            y += sin(angle);
            dist = length(fragCoord - vec2(x, y));
        }
        
        if (isInside(x, y, iResolution.xy) && dist < (burstMaxDistance / strength))
        {
            // texture(iChannel0, vec2(x, y) / iResolution.xy);
            // blur(x, y, iResolution.xy, 2.0);
            vec4 foundPixel = texture(iChannel0, vec2(x, y) / iResolution.xy);
            float distFactor = (1.0 - (dist / burstMaxDistance));
            pixel = (pixel + foundPixel * distFactor / strength);
            //pixel = vec4(distFactor, 0, 0, 1);
        }
        else
        {
        }
    }
    
    fragColor = pixel;
}
