#if __VERSION__ >= 300
# define IN in
# define OUT out
#elif __VERSION__ >= 100
# define IN attribute
# define OUT varying
#endif

IN vec2 a_position;
IN vec2 a_texCoord;
IN vec3 a_matrix0;
IN vec3 a_matrix1;
IN vec3 a_matrix2;
IN vec4 a_tint;
IN float a_alpha;
IN float a_unmultiplyAlpha;
IN float a_textureIndex;

OUT vec2 v_texCoord;
OUT vec4 v_tint;
OUT float v_textureIndex;
OUT float v_alpha;
OUT float v_unmultiplyAlpha;

void main(void) {
	mat3 matrix;
	matrix[0] = a_matrix0;
	matrix[1] = a_matrix1;
	matrix[2] = a_matrix2;
	gl_Position = vec4((matrix * vec3(a_position, 1)).xy, 0, 1);

	// In my engine this is:
	// uv.setIdentity();
	// uv = uv.scale(1, -1); // Flip UVs to opengl format
	// uv = uv.translate(0, -1); // Flip UVs to opengl format
	mat3 uv = mat3(
		1,  0,  0,
		0, -1,  0,
		0,  1,  1
	);

	v_texCoord = vec4((uv * vec3(a_texCoord, 1)).xy, 0, 1).xy;
	v_tint = a_tint;
	v_textureIndex = a_textureIndex;
	v_alpha = a_alpha;
	v_unmultiplyAlpha = a_unmultiplyAlpha;
}

##VERTEX_END
precision highp float;

#if __VERSION__ >= 300
# define IN in
# define OUT out
# define TEXTURE2D texture
#elif __VERSION__ >= 100
# define IN varying
# define OUT
# define TEXTURE2D texture2D
#endif

IN vec2 v_texCoord;
IN vec4 v_tint;
IN float v_textureIndex;
IN float v_alpha;
IN float v_unmultiplyAlpha;
OUT vec4 fragColor;

uniform sampler2D u_textures[TEXTURES_MAX];

void main(void) { 
#if 0
	// This doesn't handle the v_textureIndex=-1 case
	vec4 tex = TEXTURE2D(u_textures[int(v_textureIndex)], v_texCoord);
	fragColor = mix(tex, v_tint, v_tint.a);
	fragColor.a = tex.a;
#else
	int samplerIndex = int(v_textureIndex);
	fragColor = v_tint;
	for (int i = 0; i < TEXTURES_MAX; i++) {
		if (i == samplerIndex) {
			vec4 tex = TEXTURE2D(u_textures[i], v_texCoord);
			fragColor = mix(tex, v_tint, v_tint.a);
			fragColor.a = tex.a;

			break;
		}
	}
#endif

	if (v_unmultiplyAlpha >= 0.5) fragColor.rgb /= fragColor.a;
	fragColor.a -= 1.0-v_alpha;

#if __VERSION__ == 100
	gl_FragColor = fragColor;
#endif
}
