#version 330 core

uniform sampler2D ao;
uniform sampler2D normal_depth;
uniform vec3 offsets[9];
uniform vec2 TexelSize;

in vec2 uv;

layout (location = 0) out vec4 frag_color;

#include <deferred/gbuffer_read_include.frag>

void main()
{
	vec4 nd = texture(normal_depth, uv);
	vec3 currPos = calc_position(uv, nd.w);
	vec3 currNorm = nd.xyz;
	vec3 ss = vec3(0.0);
	float weight = 0.0;

	for (int i=0; i < 9; ++i)
	{
		vec2 offs = uv + offsets[i].xy*TexelSize;
		vec4 nd = texture(normal_depth, offs);

		float normWeight = pow( (dot(currNorm, nd.xyz) + 1.2) / 2.2, 8.0);

		float depthWeight = 1.0 / (1.0 + abs(currPos.z - calc_position(offs, nd.w).z)*0.2);
		depthWeight = pow(depthWeight, 16.0);
		
		float smpWeight = normWeight * depthWeight * offsets[i].z;
		weight += smpWeight;
		ss += texture(ao, offs).xyz * smpWeight;
	}
	frag_color.rgb = ss / weight;
	frag_color.a = 0.0;
}
