precision mediump float;

uniform sampler2D texture;
uniform float alpha;
uniform vec2 texAtlasSize;
uniform float texAtlasIndex;
uniform vec3 color;

varying vec2 pass_TexCoords;

vec2 getTexCoordsInAtlas(in float atlasIndex);

void main() {

    vec2 texAtlasCoords = getTexCoordsInAtlas(texAtlasIndex);
    gl_FragColor = texture2D(texture, texAtlasCoords);
    gl_FragColor.a = min(gl_FragColor.a, alpha);
    if(color != vec3(-1, -1, -1)){
        gl_FragColor.rgb = color;
    }

}

vec2 getTexCoordsInAtlas(in float atlasIndex){

     vec2 texAtlasCoords = vec2(0.0, 0.0);
     texAtlasCoords.x = mod(pass_TexCoords.x, 1.0) / texAtlasSize.x;
     texAtlasCoords.x += mod(atlasIndex, texAtlasSize.x) / texAtlasSize.x;
     texAtlasCoords.y = mod(pass_TexCoords.y, 1.0) / texAtlasSize.y;
     texAtlasCoords.y += floor(atlasIndex / texAtlasSize.y) / texAtlasSize.y;
     return texAtlasCoords;

}