#version 120
#include "/lib/settings.glsl"

#include "/lib/uniforms.glsl"
#include "/lib/taa/res_params.glsl"

#include "/lib/shadow_param.glsl"
varying vec4 color;
varying vec3 viewVector;
uniform float far;

varying vec4 lmtexcoord;
uniform mat4 shadowModelViewInverse;

uniform float cosFov;
uniform vec3 shadowViewDir;
uniform vec3 shadowCamera;
uniform vec3 shadowLightVec;
uniform float shadowMaxProj;

vec3 mul3(const in mat4 matrix, const in vec3 vector)
{
    return mat3(matrix) * vector + matrix[3].xyz;
}

bool intersectCone(float coneHalfAngle, vec3 coneTip, vec3 coneAxis, vec3 rayOrig, vec3 rayDir, float maxZ)
{
    vec3 co = rayOrig - coneTip;
    float prod = dot(normalize(co), coneAxis);
    if (prod <= -coneHalfAngle)
        return true; // In view frustrum

    float a = dot(rayDir, coneAxis) * dot(rayDir, coneAxis) - coneHalfAngle * coneHalfAngle;
    float b = 2. * (dot(rayDir, coneAxis) * dot(co, coneAxis) - dot(rayDir, co) * coneHalfAngle * coneHalfAngle);
    float c = dot(co, coneAxis) * dot(co, coneAxis) - dot(co, co) * coneHalfAngle * coneHalfAngle;

    float det = b * b - 4. * a * c;
    if (det < 0.)
        return false; // No intersection with either forward cone and backward cone

    det = sqrt(det);
    float t2 = (-b + det) / (2. * a);
    if (t2 <= 0.0 || t2 >= maxZ)
        return false; // Idk why it works

    return true;
}

void main()
{

    // vec3 position2 = mat3(gl_ModelViewMatrix) * vec3(gl_Vertex) + gl_ModelViewMatrix[3].xyz;

    // vec2 light = vec2(gl_MultiTexCoord1.xy * recip);

    // if (intersectCone(cosFov, shadowCamera, shadowViewDir, position2, -shadowLightVec, shadowMaxProj) && light.y > 0.001)
    {
        vec3 shadowViewPos = mul3(gl_ModelViewMatrix, gl_Vertex.xyz);
        viewVector = mul3(shadowModelViewInverse, shadowViewPos);

        color = gl_Color;
        vec4 position = gl_ModelViewProjectionMatrix * gl_Vertex;
        position.z *= 0.1666666666666667; // 1/6
        if (dhMaterialId != 1)
        {
            position.z += 0.001;
        }

        vec2 shadowDistortion = calcShadowDistortion(position.xyz);
        position.xy = shadowDistortion;

        lmtexcoord.xyzw = vec4(gl_MultiTexCoord0.xy, gl_MultiTexCoord1.xy * 1);

        gl_Position = position;
    }
    // else
    {
        //    color = vec4(0.0);

        //     gl_Position.xyzw = vec4(0.0, 0.0, 1e30, 0.0); // Degenerates the triangle
    }
}
