layout(location = 0, index = 0) out vec4 outcol0;

uniform sampler2D tex0;
uniform vec4 tex0siz; //xy=size in pixels, zw = 1/xy
uniform vec4 time_s;

uniform vec4 dist;
uniform vec4 multiplier;

in vec2 texcoord0_nm;

//note: [0;1]
float rand( vec2 n ) {
  return fract(sin(dot(n.xy, vec2(12.9898, 78.233)))* 43758.5453);
}

void main()
{
	const vec2 blur_center = vec2(0.5);
	const float max_num_samples = 50;
	const float propagation = 1.5f;
	//const float multiplier = 1;

	//float dist_nm = dist.x * tex0siz.z;
	float dist_nm = 1400 * tex0siz.z;

	float rnd = rand( texcoord0_nm + mod(time_s.x, 10) );

	vec2 vc = blur_center - texcoord0_nm;
	float len = length(vc);
	len = max( 0.01, len + 0.01f * (2*rnd-1) );

	float num_samples = 2*max_num_samples * sqrt(len);
	float reci_num_samples = 1.0f / num_samples;
	float c = min(len, dist_nm) / num_samples;

	//c += 0.125 * dist_nm * rnd * len * reci_num_samples;

	vc = c * vc / len;

	vec4 s0 = texture( tex0, texcoord0_nm + vc );
	float alpha = s0.a; //note: premult-alpha, so doesn't hide anything but org image (the rest is additive)

	float its = clamp( 2*len, 0, 1);
	vec4 sum = its * s0;
	for(int i=2; i<=num_samples; i++)
	{
		float fi = float(i);
		sum.rgb += its * texture( tex0, texcoord0_nm + fi*vc ).rgb;
	}

	//outcol0 = vec4( mix( s0.rgb, sum.rgb * reci_num_samples, multiplier.x), alpha);
	outcol0 = vec4( s0.rgb + sum.rgb * reci_num_samples * multiplier.x, 1 );

	//DEBUG
	//colOut = vec4( IN.texcoords.xy / 1280.0f, 0, 1 );
	//colOut = vec4( 1, 0, 0, 1 );
	//colOut = vec4( sum.rgb, 1 );
	//colOut = vec4( float3(alpha), 1 );
}
