#pragma clang diagnostic ignored "-Wmissing-prototypes"

#include <metal_stdlib>
#include <simd/simd.h>

using namespace metal;

struct FragmentOut
{
    float4 gl_FragColor [[color(0)]];
};

struct FragmentIn
{
    float2 uv [[user(locn0)]];
    float eyedist [[user(locn1)]];
};

static inline __attribute__((always_inline))
float computeLinearFogFactor(thread float fog_end_unif, thread float& eyedist, thread float fog_start_unif)
{
    float factor = (fog_end_unif - eyedist) / (fog_end_unif - fog_start_unif);
    factor = fast::clamp(factor, 0.0, 1.0);
    return factor;
}

fragment FragmentOut fragmentShader(FragmentIn in [[stage_in]], constant float& fog_end_unif [[buffer(0)]], constant float& fog_start_unif [[buffer(1)]], constant float& alpha_value_unif [[buffer(2)]], constant float4& fog_color_unif [[buffer(3)]], constant float4& color_unif [[buffer(4)]], texture2d<float> tex_unif [[texture(0)]], sampler tex_unifSmplr [[sampler(0)]])
{
    FragmentOut out = {};
    float alpha = tex_unif.sample(tex_unifSmplr, in.uv).w;
    if (alpha < alpha_value_unif)
    {
        discard_fragment();
    }
    out.gl_FragColor = mix(fog_color_unif, tex_unif.sample(tex_unifSmplr, in.uv) * color_unif, float4(computeLinearFogFactor(fog_end_unif, in.eyedist, fog_start_unif)));
    return out;
}

