#version 300 es

precision mediump float;

// Input attributes
in vec4 aPosition;
in vec2 aTextureCoord;
in vec3 aNormal;
in vec4 aTransform;// xy: position offset, zw: scale factors
in vec4 aUVTransform;// Instance UV transform: xy=scale, zw=offset
in vec4 aExtra;
in vec4 aZAnim;

// Uniforms
uniform mat4 uMVPMatrix;
uniform vec4 u_uv_trans;
uniform float uScale;
uniform float uRate;
uniform float u_aspect_ratio;
uniform float uRandomMin;// Minimum random range value
uniform float uRandom;// Random seed value
uniform float uAnimZ;// Random seed value
uniform vec2 uViewPort;

// Viewport dimensions for UV calculation

// Outputs to fragment shader
out vec2 v_originTexCoord_local;
out vec2 v_originTexCoord;
out vec2 v_viewportUV;// 新增：视口空间的UV坐标
out vec3 vONormal;
out vec3 vNormal;
out float vRandom;
out float isEdge;
out float animZBrightness;
out vec4 sideShadow;

const float PI = 3.141592653589793;

// Optimized random function
float rand(vec2 co) {
    return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);
}

void main() {
    float revRate = 1.0 - uRate;
    float instanceID = float(gl_InstanceID + 1);

    // Interpolate transform based on rate
    vec4 currentTransform = aTransform;

    // Extract scale factors
    vec2 scale = currentTransform.zw;

    // Build transformation matrices
    mat3 scaleMatrix = mat3(
    scale.x, 0.0, 0.0,
    0.0, scale.y, 0.0,
    0.0, 0.0, 1.0
    );

    // Calculate rotation
    //float rotation = aExtra.x > 0.0 ? PI : mix(0.0, PI, uRate);

    // Apply transformations
    vec3 position = scaleMatrix * vec3(aPosition.xyz);
    position.xy += currentTransform.xy;
    position.z += -5.0 + aExtra.y * revRate;

    // animZ
    float packedValue = aZAnim.x;
    float offsetZ = floor(packedValue);
    float diffTop = packedValue - offsetZ;
    sideShadow = vec4(diffTop, aZAnim.y, aZAnim.z, aZAnim.w);
    float animZTmp = offsetZ * 0.001;
    position.z -= animZTmp;

    float brightness = (diffTop+aZAnim.y+aZAnim.z+aZAnim.w) / 4.0;
    animZBrightness = (1.0 - brightness) * 0.25;

    // Final position
    gl_Position = uMVPMatrix * vec4(position, aPosition.w);

    // UV coordinates
    v_originTexCoord_local = aTextureCoord;
    v_originTexCoord = vec2(1.0 - aTextureCoord.x, aTextureCoord.y) * aUVTransform.xy + aUVTransform.zw;

    // Normal and random calculations
    vONormal = normalize(aNormal);
    // float randomMin = uRandomMin * uRate + min(uRandomMin, 0.5 * revRate);
    // float randomMin = uRandomMin * uRate;
    float randomMin = uRandomMin;
    vRandom = rand(vec2(instanceID + uRandom)) * (1.0 - randomMin) + randomMin;
    //vRandom = 1.;

    isEdge = aExtra.x;
}