#version 150

layout(std140) uniform Fog {
    vec4 FogColor;
    float FogEnvironmentalStart;
    float FogEnvironmentalEnd;
    float FogRenderDistanceStart;
    float FogRenderDistanceEnd;
    float FogSkyEnd;
    float FogCloudsEnd;
};

float linear_fog_value(float vertexDistance, float fogStart, float fogEnd) {
    if (vertexDistance <= fogStart) return 0.0;
    if (vertexDistance >= fogEnd) return 1.0;
    return smoothstep(fogStart, fogEnd, vertexDistance);
}

float total_fog_value(float sph, float cyl, float envStart, float envEnd, float rdStart, float rdEnd) {
    float dist = max(sph, cyl);
    float start = min(envStart, rdStart);
    float end = max(envEnd, rdEnd);
    return linear_fog_value(dist, start, end);
}

vec4 apply_fog(vec4 inColor, float sph, float cyl, float envStart, float envEnd, float rdStart, float rdEnd, vec4 fogColor) {
    float fogValue = total_fog_value(sph, cyl, envStart, envEnd, rdStart, rdEnd);
    if (fogValue <= 0.0) return inColor;
    return vec4(mix(inColor.rgb, fogColor.rgb, fogValue), inColor.a);
}

float fog_spherical_distance(vec3 pos) {
    return length(pos);
}

float fog_cylindrical_distance(vec3 pos) {
    return length(pos.xz);
}
