#define MAX_LIGHTS 3


#pragma include "p3d_in.glsl"
#pragma include "p3d_uniform.glsl"
#pragma include "rand.glsl"
#pragma include "simplex3d.glsl"
#pragma include "rot.glsl"


// Uniform inputs
uniform int u_NumberOfLights;
uniform float u_PointSize;

uniform int u_NumFrames;  // Number of frames in the instance data buffer
uniform int u_InstanceCount;  // Number of instances
uniform float u_Scale;
uniform float u_Trans;
uniform vec3 u_VertPositionOffset;
uniform float u_Time;

// Outputs to fragment shader
out vec4 vertColor;
//out vec4 domiPosition;
out vec4 vertPosition;
out vec3 vertNormal;
out vec3 binormal;
out vec3 tangent;
out vec4 vertInShadowSpaces[MAX_LIGHTS];
out vec2 vertMultiTexCoord0;
out float neg;


void begin() {
    vertPosition = (p3d_Vertex + vec4(u_VertPositionOffset, 0.0)) * u_Scale;
    vertColor = p3d_Color;
}
#define BEGIN begin()


void endPoint(inout vec4 vertPosition, float pointSize) {
    // Transform the vertex position by the Model-View matrix
    vertPosition = p3d_ModelViewMatrix * vertPosition;

    // Project the transformed position into clip space using the Projection matrix
    gl_Position = p3d_ProjectionMatrix * vertPosition;

    // Calculate the point size based on the distance (negative z-coordinate)
    gl_PointSize = pointSize / -vertPosition.z;
}
#define END_POINT endPoint(vertPosition, u_PointSize)


void endTriangle(
    inout vec4 vertPosition,
    out vec3 vertNormal,
    out vec3 binormal,
    out vec3 tangent,
    out vec4 vertInShadowSpaces[MAX_LIGHTS],
    out vec2 vertMultiTexCoord0
) {
    // Transform vertex position
    vertPosition = p3d_ModelViewMatrix * vertPosition;
    gl_Position = p3d_ProjectionMatrix * vertPosition;

    // Transform and normalize normal, binormal, and tangent vectors
//    vertNormal = normalize(p3d_NormalMatrix * p3d_Normal);
//    tangent = normalize(p3d_NormalMatrix * p3d_Tangent);
//    binormal = cross(vertNormal, tangent);

//    binormal = normalize(p3d_NormalMatrix * p3d_Binormal);
//    binormal = p3d_Binormal;
//    binormal = vec3(0.0, 1.0, 0.1);
//    tangent = vec3(0.0);
//    tangent = p3d_Tangent;

    // Transform vertex position into shadow spaces for each light
    for (int i = 0; i < u_NumberOfLights; ++i) {
        vertInShadowSpaces[i] = p3d_LightSource[i].shadowViewMatrix * vertPosition;
    }

    // Pass texture coordinate
    vertMultiTexCoord0 = p3d_MultiTexCoord0;
}
#define END_TRIANGLE endTriangle(vertPosition, vertNormal, binormal, tangent, vertInShadowSpaces, vertMultiTexCoord0)
