
uniform sampler2DArray u_textures;

flat in float v_atlas;
in vec2 v_offset;
in float v_brightness;
in vec3 v_normal;
in vec3 v_fragpos;

#ifdef selection
in vec3 v_position;
uniform float u_cycle;
#endif

layout (location = 0) out vec4 frag_color;

#if !defined shadow_pass
    layout (location = 1) out vec3 g_normal;
    layout (location = 2) out vec3 g_position;
#endif

void main() {
    ivec3 texture_size = textureSize(u_textures, 0);
    vec4 col = texture(u_textures, vec3(v_offset / texture_size.xy, v_atlas));
    // Remove transparant parts
    if (col.a < 0.3) {
        discard;
    }
    frag_color.rgb = col.rgb;
    frag_color.a = 1.0;
    #ifdef selection
        // Brightness is abused in selection mode to mark whether a tile is valid
        // or not.
        bool valid = v_brightness > 0.5;
        // Base color based on whether the selection is valid or not
        vec3 overcol = valid ? SELECTION_VALID : SELECTION_INVALID;
        vec3 grid = abs(mod(v_position, 0.25) - 0.125) / 0.125;
        if ((grid.x != 1.0 && grid.x > 0.85)
            || (grid.y != 1.0 && grid.y > 0.85)
            || (grid.z != 1.0 && grid.z > 0.85)) {
            // Darker color for grid lines
            overcol *= 0.6;
        }
        vec3 sel_col = overcol * dot(frag_color.rgb, vec3(0.2126, 0.7152, 0.0722)); // Grid * brightness
        // Pulsing
        float sel = abs((u_cycle - 100.0) / 100.0);
        // Hold on the grid pattern longer than the normal look
        sel = clamp(sel + 0.4, 0.0, 1.0);
        frag_color.rgb = (1.0 - sel) * frag_color.rgb + sel * sel_col;
    #else
        frag_color.rgb *= v_brightness;
    #endif
    #if !defined shadow_pass
        vec3 normal = normalize(v_normal);
        g_normal = v_normal * 0.5 + 0.5;
        g_position = v_fragpos;
    #endif
}
