#version 330

uniform float uTime;
uniform float uSpeed;
uniform float uMax;
uniform float uVol;

uniform vec2 uRes;
uniform vec3 uMouse;

uniform sampler2D uTex0;

vec4 crepuscular_rays(vec2 texCoords, vec2 pos) {
    float decay = 0.92;
    float density = 1.0;
    float weight = 0.58767;
    /// NUM_SAMPLES will describe the rays quality, you can play with
    const int nsamples =100;

    vec2 tc = texCoords.xy;
    vec2 deltaTexCoord = tc - pos.xy;
    deltaTexCoord *= (1.0 / float(nsamples) * density);
    float illuminationDecay = 1.0;

    vec4 color = texture2D(uTex0, tc.xy) * vec4(0.4);

    for (int i = 0; i < nsamples; i++)
	{
        tc -= deltaTexCoord;
        vec4 sample = texture2D(uTex0, tc.xy) * vec4(0.4);

        sample *= illuminationDecay * weight;
        color += sample;
        illuminationDecay *= decay;
    }
    
    return color;
}

out vec4 fragColor;

void main ( void )
{
    vec2 uv = gl_FragCoord.xy / uRes.xy - 0.5;
	uv.x *= uRes.x/uRes.y; //fix aspect ratio
    vec3 pos = vec3(uMouse.xy/uRes.xy - 0.5,uMouse.z-.5);
	pos.x *= uRes.x/uRes.y; //fix aspect ratio
	if (uMouse.z<.5)
	{
		pos.x=sin(uTime)*.5;
		pos.y=sin(uTime*.913)*.5;
	}
	fragColor = crepuscular_rays (uv, pos.xy);
}