#version 330 core

uniform sampler2D light_accumulation;
uniform sampler2D normal_depth;
uniform sampler2D distort;
uniform vec2      TexelSize;
uniform vec4      DistortParams; // offset.xy, scale, alpha

uniform vec4 color;

in vec2 uv;

layout (location = 0) out vec4 frag_color;

vec4 edge_detect(in sampler2D sampler, in vec2 uv, in vec2 texel_size)
{
	vec4 gx, gy, rgba;

	rgba = texture( sampler, uv+vec2(-texel_size.x, texel_size.y) );
	gx = rgba*-1.0;
	gy = rgba*1.0;

	rgba = texture( sampler, uv+vec2( 0.0, texel_size.y) );
	gy += rgba*2.0;

	rgba = texture( sampler, uv+vec2( texel_size.x, texel_size.y) );
	gx += rgba*1.0;
	gy += rgba*1.0;

	rgba = texture( sampler, uv+vec2(-texel_size.x, 0.0 ) );
	gx += rgba*-2.0;

	// rgba = texture( sampler, uv+vec2( 0.0, 0.0 ) );

	rgba = texture( sampler, uv+vec2( texel_size.x, 0.0 ) );
	gx += rgba*2.0;

	rgba = texture( sampler, uv+vec2(-texel_size.x, -texel_size.y) );
	gx += rgba*-1.0;
	gy += rgba*-1.0;

	rgba = texture( sampler, uv+vec2( 0.0, -texel_size.y) );
	gy += rgba*-2.0;

	rgba = texture( sampler, uv+vec2( texel_size.x, -texel_size.y) );
	gx += rgba*1.0;
	gy += rgba*-1.0;

	rgba = sqrt( gx*gx + gy*gy );
	return rgba;
}

void main()
{
	vec2 d = (texture(distort, uv*0.1+DistortParams.xy).rg*2.0 - vec2(1.0))*DistortParams.z*TexelSize;
	vec4 edge = edge_detect(normal_depth, uv+d, TexelSize);
	vec4 a = texture(light_accumulation, uv+d);
	vec4 b = texture(light_accumulation, uv-d);
	vec4 dist = (a + b) * color * (edge.a > (4.0/255.0) ? 1.0 : 0.0) * DistortParams.w;

	frag_color = dist;
}
