#version 120
#extension GL_EXT_gpu_shader4 : enable

#define TONEMAP_ACES

//#define VOLUMETRIC_LIGHT
#define SEA_LEVEL 60.0 //[0 10 20 30 40 50 60 70 80 90 100 110 120 130 150 170 190]
#define ATMOSPHERIC_DENSITY 1.0 //[0.0 0.5 1.0 1.5 2.0 3.0 4.0 5.0]


varying vec2 texcoord;
uniform vec2 texelSize;
uniform sampler2D depthtex0;
uniform sampler2D colortex1;
uniform sampler2D gaux1;
uniform sampler2DShadow shadow;

uniform vec4 lightCol;
uniform vec3 sunColor;
uniform vec3 nsunColor;
uniform int isEyeInWater;
uniform vec3 sunVec;
uniform float sunIntensity;
uniform float skyIntensity;
uniform float skyIntensityNight;
uniform float fogAmount;
uniform float rainStrength;
uniform ivec2 eyeBrightness;
uniform float frameTimeCounter;

#include "lib/color_transforms.glsl"
#include "lib/color_dither.glsl"
#include "lib/projections.glsl"

#include "lib/sky_gradient.glsl"



//////////////////////////////VOID MAIN//////////////////////////////
//////////////////////////////VOID MAIN//////////////////////////////
//////////////////////////////VOID MAIN//////////////////////////////
//////////////////////////////VOID MAIN//////////////////////////////
//////////////////////////////VOID MAIN//////////////////////////////

void main() {
/* DRAWBUFFERS:1 */
	vec3 color = texture2D(colortex1,texcoord).rgb;


	float z = texture2D(depthtex0,texcoord).x;
	#ifndef VOLUMETRIC_LIGHT
  if (isEyeInWater == 0){
		if (z < 1.0){
			vec3 fragpos = toScreenSpace(vec3(texcoord,z));
			float dist = length(fragpos);
			float atten = eyeBrightness.y/255.+0.006;

			vec3 np3 = mat3(gbufferModelViewInverse) * (fragpos/(dist));
			vec3 skyColor = getSkyColorLut(np3,mat3(gbufferModelViewInverse)*sunVec,np3.y,gaux1) ;

			float fogFactorAbs = exp(-dist*fogAmount*0.2);
			float fogFactorScat = exp(-dist*fogAmount*0.7);

			vec3 col0 = normalize(skyColor)*(skyIntensity*mix(vec3(1.),vec3(0.8,0.9,1.),rainStrength)+skyIntensityNight*0.01)*2.;
			vec3 fogColor = mix(col0,skyColor,clamp(dist/512.,0.,1.));

			color.rgb = 10*fogColor*(1.0-fogFactorScat)*atten+color*fogFactorAbs;
			}
	}
	else {
		vec3 fragpos = toScreenSpace(vec3(texcoord,z));
		float dist = length(fragpos);
		float fogFactorAbs = exp2(-dist/10.*0.8);
		float fogFactorScat = fogFactorAbs;
		vec3 waterFogCol = (lightCol.g + skyIntensity + skyIntensityNight)*vec3(0.06,0.27,0.35);
		color.rgb = waterFogCol*(1.0-fogFactorScat)+color*fogFactorAbs;
	}
	#endif

	gl_FragData[0].rgb = color;

}
