uniform sampler2D texture;

uniform float blindness;
uniform float nightVision;
uniform int isEyeInWater;

varying vec4 glcolor;
varying vec2 texcoord;
varying float fogDistance;

#define NV_CLOUD_BRIGHTNESS_LIFT  0.85
#define NV_CLOUD_BRIGHTNESS_FLOOR 0.7
#define NV_CLOUD_TINT_STRENGTH    0.5
#define NV_CLOUD_TINT_R           0.55
#define NV_CLOUD_TINT_G           0.75
#define NV_CLOUD_TINT_B           0.60
#define NV_CLOUD_TINT_BRIGHTNESS  1.4
#define NV_CLOUD_DARK_CUTOFF      0.5

vec3 applyNightVision(vec3 color, float nv) {
    if (nv <= 0.0) return color;
    float luma = dot(color, vec3(0.299, 0.587, 0.114));
    float darknessFactor = 1.0 - smoothstep(0.0, NV_CLOUD_DARK_CUTOFF, luma);
    float strength = nv * darknessFactor;
    color = mix(color, vec3(max(luma, NV_CLOUD_BRIGHTNESS_FLOOR)), strength * NV_CLOUD_BRIGHTNESS_LIFT);
    float nvLuma = dot(color, vec3(0.299, 0.587, 0.114));
    color = mix(vec3(nvLuma), color, 1.0 + 0.15 * strength);
    color = mix(color, color * vec3(NV_CLOUD_TINT_R, NV_CLOUD_TINT_G, NV_CLOUD_TINT_B) * NV_CLOUD_TINT_BRIGHTNESS, strength * NV_CLOUD_TINT_STRENGTH);
    return clamp(color, 0.0, 1.0);
}


void main()
{
    vec3 light = vec3(1.-blindness);
    vec4 col = glcolor * vec4(light,1) * texture2D(texture,texcoord);

    float fog = (isEyeInWater>0) ? 1.-exp(-fogDistance * gl_Fog.density):
        clamp((fogDistance-gl_Fog.start) * gl_Fog.scale, 0., 1.);

    vec3 fogCol = applyNightVision(gl_Fog.color.rgb, nightVision);
    col.rgb = applyNightVision(col.rgb, nightVision);
    col.rgb = mix(col.rgb, fogCol, fog);

    gl_FragData[0] = col;
}
