#version 110

uniform vec3 lights_position[MAX_LIGHTS];

uniform bool normal_map;
uniform int vertextype;
uniform bool fb_texture;
uniform int blend_mode;

uniform mat4 d3dprojection_matrix;
uniform mat4 d3dviewport_matrix;

varying vec3 eye_vector;

varying vec4 normal_light_vector[MAX_LIGHTS];
varying vec3 light_reflection[MAX_LIGHTS];

varying mat3 tbn_matrix;

attribute vec3 tangent;
attribute vec3 binormal;

void main()
{
	vec4 pos = gl_Vertex;
	
	gl_FrontColor.rgba = gl_Color.bgra;
	
	// TLVERTEX
	if(vertextype == 3)
	{
		pos.w = 1.0 / pos.w;
		pos.xyz *= pos.w;
		pos = gl_ProjectionMatrix * pos;
	}
	// LVERTEX and VERTEX
	else
	{
		pos = d3dviewport_matrix * d3dprojection_matrix * gl_ModelViewMatrix * pos;
		
		if(vertextype == 1)
		{
			int i;
			
			eye_vector = vec3(gl_ModelViewMatrix * gl_Vertex);
			
			if(normal_map) tbn_matrix = mat3(normalize(gl_NormalMatrix * tangent), normalize(gl_NormalMatrix * binormal), normalize(gl_NormalMatrix * gl_Normal));
			else tbn_matrix[2] = normalize(gl_NormalMatrix * gl_Normal);
			
			for(i = 0; i < MAX_LIGHTS; i++)
			{
				vec3 light_vector = vec3(lights_position[i] - eye_vector);
				normal_light_vector[i].xyz = normalize(light_vector);
				
				if(!normal_map) light_reflection[i] = reflect(normal_light_vector[i].xyz, tbn_matrix[2]);
				
				normal_light_vector[i].w = length(light_vector);
			}
		}
		
		gl_FrontColor.a = clamp(gl_FrontColor.a, 0.0, 0.5);
	}
	
	// BLEND_NONE
	if(blend_mode == 4) gl_FrontColor.a = 1.0;
	// BLEND_25P
	else if(blend_mode == 3) gl_FrontColor.a = 0.25;
	
	gl_TexCoord[0] = gl_MultiTexCoord0;
	
	if(fb_texture) gl_TexCoord[0].t = 1.0 - gl_TexCoord[0].t;
	
	gl_Position = pos;
}
