
#include "gamma.sdr"

in vec4 fragTexCoord;

out vec4 fragOut0;

uniform sampler2D tex;
uniform sampler2D depth_tex;

layout (std140) uniform genericData {
	vec3 fog_color;
	float fog_start;

	float fog_density;
	float zNear;
	float zFar;

	float clip_inf_dist;
	float clip_dist;
};

void main()
{
	vec4 color_in = texture(tex, fragTexCoord.xy);

	// If the scene is in fog then we change the color we operate on based on the depth of the pixel
	float depth_val = texture(depth_tex, fragTexCoord.xy).x;
	// Transform depth value from [0, 1] to [-1, 1]
	float depth_normalized = 2 * depth_val - 1;
	// Now we compute the depth value in projection space using the clipping plane information
	float view_depth = 2.0 * zNear * zFar / (zFar + zNear - depth_normalized * (zFar - zNear));

	float skybox_compat_fake = step(1.0, depth_val);
	view_depth = clamp(view_depth, 0.0, mix(clip_dist, clip_inf_dist, skybox_compat_fake));

	if (isinf(view_depth)) {
		fragOut0.rgb = color_in.rgb;
	} else {
		float fog_dist = clamp(1 - pow(fog_density, view_depth - fog_start) , 0.0, 1.0);
		vec3 finalFogColor = srgb_to_linear(fog_color);

		fragOut0.rgb = mix(color_in.rgb, finalFogColor, fog_dist);
	}
	fragOut0.a = 1.0;
}
