#version 330 core

uniform sampler2D light_accumulation;
uniform sampler2D ssao_buffer;
uniform sampler2D lightstreaks;
uniform sampler2D depth;
uniform vec4      CameraRange; // near, far, far - near, -near*far
uniform vec4      DOFParams; // aperture, Focal length, plane in focus, plane_in_focus - focal_length

in vec2 uv;

layout (location = 0) out vec4 frag_color;


void main()
{
	vec4 la = textureLod(light_accumulation, uv, 0.0);
	// HACK - just blur between the LOD levels for now (even if it adds ghosting atifacts)
	vec4 lb = textureLod(light_accumulation, uv, 1.0)*0.12 + textureLod(light_accumulation, uv, 2.0)*0.25 + textureLod(light_accumulation, uv, 3.0)*0.375 + textureLod(light_accumulation, uv, 4.0)*0.5;

	lb *= (1.0 / 1.245);

	float z = texture2D(depth, uv).x;
	vec4 sb = texture2D(ssao_buffer, uv);
	vec4 ls = texture2D(lightstreaks, uv);

	float object_distance = CameraRange.w / (z*CameraRange.z - CameraRange.y);
	
	float coc = clamp(abs(DOFParams.x*(DOFParams.y * (object_distance - DOFParams.z)) / (object_distance*DOFParams.w)), 0.0, 1.0);
	vec3 l = (la.rgb + sb.rgb)*sb.a*(1.0 - coc) + lb.rgb*coc + ls.rgb*(1.5 - coc);

	frag_color = vec4(l, 1.0);

	//frag_color = vec4(1.0 - coc);
}
