#version 450

layout(location = 0) in vec3 nearPoint;
layout(location = 1) in vec3 farPoint;
layout(location = 0) out vec4 outColor;

layout(set = 1, binding = 0) uniform CameraData
{
    mat4 viewProjection;
    mat4 view;
    mat4 projection;
    vec4 camPos;
    float near;
    float far;
} cam;

vec4 grid(vec3 fragPos3D, float scale)
{
    vec2 coord = fragPos3D.xz * scale;
    vec2 derivative = fwidth(coord);
    vec2 grid = abs(fract(coord - 0.5) - 0.5) / derivative;
    float line = min(grid.x, grid.y);
    float visible = 1.0 - min(line, 1);
    vec4 color = vec4(0.2, 0.2, 0.2, visible);
    // z axis
    float minimumx = 2 * min(derivative.x, 1);
    if(fragPos3D.x > -0.1 * minimumx && fragPos3D.x < 0.1 * minimumx)
    {
    	color.xy *= 0.4;
    	color.z = 1.0;
    	color.a *= 2;
    }
    // x axis
    float minimumz = 2 * min(derivative.y, 1);
    if(fragPos3D.z > -0.1 * minimumz && fragPos3D.z < 0.1 * minimumz)
    {
    	color.x = 1.0;
    	color.yz *= 0.4;
    	color.a *= 2;
    }
    return color;
}

float computeDepth(vec3 pos)
{
    vec4 clip_space_pos = cam.viewProjection * vec4(pos.xyz, 1.0);
    return (clip_space_pos.z / clip_space_pos.w);
}

float computeLinearDepth(vec3 pos)
{
    vec4 clip_space_pos = cam.viewProjection * vec4(pos.xyz, 1.0);
    float clip_space_depth = (clip_space_pos.z / clip_space_pos.w) * 2.0 - 1.0; // put back between -1 and 1
    float linearDepth = (2.0 * cam.near * cam.far) / (cam.far + cam.near - clip_space_depth * (cam.far - cam.near)); // get linear value between 0.01 and 100
    return linearDepth / cam.far; // normalize
}

void main()
{
    float t = -nearPoint.y / (farPoint.y - nearPoint.y);
    vec3 fragPos3D = nearPoint + t * (farPoint - nearPoint);

    gl_FragDepth = computeDepth(fragPos3D);

    float linearDepth = computeLinearDepth(fragPos3D);
    float fading = max(0, (0.5 - linearDepth));

    outColor = (grid(fragPos3D, 1) + grid(fragPos3D, 4) / 2.0) * float(t > 0); // adding multiple resolution for the grid
    outColor.a *= fading;
}
