#version 120
const int nLightCount = 2;
attribute vec4 in_vertex;
attribute vec3 in_normal;
attribute vec2 in_uv;
attribute vec4 in_color;
attribute vec4 in_uv2;

varying vec3 npos, origo;
varying vec3 normal;
varying vec2 uv, uv2, uv3;
varying vec4 pos;
varying vec3 vertMasksPrimary, vertMasksSecondary;
varying vec2 vertLightMask;
uniform int flagNumber;
uniform vec3 wsPos;
uniform vec4 wsRot;

varying vec3 light[nLightCount];

vec3 toLinear(vec3 x) {
	return pow(x, vec3(2.2));
}

float square(float x){
	return x*x;
}

vec3 wsAllign(vec3 x){
	return x + 2.0 * cross(wsRot.xyz, cross(wsRot.xyz, x) + wsRot.w * x);
}
void main()
{
    pos = gl_ModelViewMatrix * in_vertex;
   
    // convert view, normal and light vectors to world space and quaternion correct for model rotation
    mat3 tcamrot = transpose(mat3x3(gl_ModelViewMatrix));
    npos = (wsAllign(normalize(tcamrot * -pos.xyz)));
   
    normal = (tcamrot * (gl_NormalMatrix * wsAllign(normalize(in_normal))));
    for (int i = 0; i < nLightCount; i++) {
        light[i] = wsAllign(normalize((tcamrot * (((gl_LightSource[i].position)).xyz + pos.xyz))));
    }
   
	// store origo for model alligned effects
	origo = in_vertex.xyz;
	
	// prep vertex masks
	vertMasksSecondary = max(vec3(0.0), in_color.rgb * 3.0 -2.0);	//  shield r, windows g, engine b
	vertMasksPrimary = max(vec3(0.0), (1.0 - in_color.rgb) * 3.0 - 2.0); // flags g, warp b, transparency on r
	vertLightMask = vec2(1.0 - vertMasksSecondary.r - vertMasksSecondary.g - vertMasksSecondary.b - vertMasksPrimary.b, floor(1.0 - vertMasksSecondary.b));
	
	uv = in_uv;
	uv.y = 1.0 - uv.y;
	uv2 = in_uv2.xy;
	uv2.y = 1.0 - uv2.y;
	
	// prep flag uv
	uv2 = uv2.xy + vec2((1.0 / 32.0) * clamp(float(flagNumber), 0.0, 20.0) * vertMasksPrimary.g, 0.0);
	
	uv3 = in_uv2.zw;
	uv3.y = 1.0 - uv3.y;
	gl_Position = gl_ProjectionMatrix * pos;
} 
