#pragma once

inline const char* vertOrderedSet = R"(
    #version 330 core

    layout(location = 0) in vec2 aPos;

    layout(location = 1) in vec3 iTilePos;
    layout(location = 2) in float height;
    layout(location = 3) in float iSpriteId;
    layout(location = 4) in float iNormalId;
    layout(location = 5) in vec2 spriteScale;

    uniform mat4 prMatrix;
    uniform mat4 camMatrix;

    out vec2 vUV;
    flat out int vSpriteId;
    flat out int vNormalId;
    flat out float vTileNdcY;
    flat out float layerHeight;

    void main()
    {
        vec3 local = vec3(aPos.x, aPos.y, 0);
        vec2 baseUV = aPos + vec2(0.5, 0);
        vec3 tileSize = vec3(spriteScale.x, spriteScale.y, 1);

        vec3 worldPos = (iTilePos * tileSize) + (local * tileSize);

        vec4 clip = prMatrix * camMatrix * vec4(worldPos, 1.0);
        gl_Position = clip;

        vUV = baseUV;
        vSpriteId = int(iSpriteId + 0.5);
        vNormalId = int(iNormalId + 0.5);
        layerHeight = height;

        vec3 localbottom = vec3(0.5, 0, 0);
        vec3 worldPosBottom = (iTilePos * tileSize) + (localbottom * tileSize);
        vec4 clipbottom = prMatrix * camMatrix * vec4(worldPosBottom, 1.0);
        float ndcY = clipbottom.y / clipbottom.w;
        vTileNdcY = ndcY * 0.5 + 0.5;
    }
)";

inline const char* fragOrderedSet = R"(
    #version 330 core

    in vec2 vUV;
    flat in int vSpriteId;
    flat in int vNormalId;
    flat in float vTileNdcY;
    flat in float layerHeight;

    uniform sampler2D atlas;
    uniform vec2 spriteCount;

    layout(location = 0) out vec4 FragColor;
    layout(location = 1) out vec4 FragHeight;
    layout(location = 2) out vec4 FragDepth;

    void main()
    {
        float t = (vTileNdcY + 1.0) * 0.5 *0.8;
        FragDepth = vec4(t, 0, 0, 1.0);

        vec2 tileUVSize = 1.0 / spriteCount;

        int cols = int(spriteCount.x);
        int sx = vSpriteId % cols;
        int sy = vSpriteId / cols;
        
        vec2 atlasOffset = vec2(float(sx), float(sy)) * tileUVSize;
        vec2 atlasUV = atlasOffset + (vUV * tileUVSize);
        vec4 c = texture(atlas, atlasUV);
        if (c.a < 0.01) discard;
        float colorScaler = 1 - ((layerHeight - 1) * -1) * 0.3;
        c = vec4(c.x * colorScaler,c.y * colorScaler,c.z * colorScaler,c.w);
        
        FragColor = c;

        if(vNormalId != -1)
        {
            int sx2 = vNormalId % cols;
            int sy2 = vNormalId / cols;
            vec2 atlasOffsetNormal = vec2(float(sx2), float(sy2)) * tileUVSize;
            vec2 atlasUVNormal = atlasOffsetNormal + (vUV * tileUVSize);
            vec4 cNormal = texture(atlas, atlasUVNormal);
            cNormal.w = layerHeight;
            
            FragHeight = cNormal;
        }
    }
)";
