#version 330 core
#pragma optionNV (unroll all)

const float motionBlurIterations = 5;
const float motionBlurQuality = 4;
const float blurStrength=1f;

in vec2 uv;

uniform sampler2D colorTexture;
uniform sampler2D dataTexture;

uniform float playerSpeedMult;

layout(location = 0) out vec3 fragColor;

void main(){
	fragColor = vec3(0);
	vec4 blurData = texture2D( dataTexture, uv.xy ).xyzw;
	//Motion Blur
	vec2 motionBlurDir = blurData.xy / (100*motionBlurIterations);
	//Radial Blur
	vec2 radialBlurDir = vec2(0);
	if (blurData.z>.7) {
		radialBlurDir = (uv-.5);
		radialBlurDir.x = radialBlurDir.x*radialBlurDir.x*radialBlurDir.x*0.08;
		radialBlurDir.y = radialBlurDir.y*radialBlurDir.y*radialBlurDir.y*0.08;
		radialBlurDir *= playerSpeedMult;
	}

	vec2 blurDir = motionBlurDir + radialBlurDir;
	int added=1;

	vec3 unblurred = texture2D( colorTexture, uv.xy ).xyz;
	fragColor += unblurred;
	if (texture2D( dataTexture, uv).z>.7) {
		for (float i=0;i<motionBlurIterations*motionBlurQuality;i++) {
			vec2 offset = -blurDir*motionBlurIterations/2;
			vec2 texPos = uv.xy + blurDir*(i/motionBlurQuality) + offset;
			if (texPos.x>=0 && texPos.x<=1 && texPos.y>=0 && texPos.y<=1
					&& texture2D( dataTexture, texPos).z>.7) {
				added++;
				fragColor += texture2D( colorTexture, texPos).xyz;
			}
		}
	}
	
	fragColor = fragColor/added;

	fragColor = mix(unblurred, fragColor, blurStrength);
}