#version 330 core

uniform mat4 ModelViewProjectionMatrix;
uniform mat4 ModelViewMatrix;
uniform mat3 NormalMatrix;
uniform samplerBuffer box_coords;

in vec3 POSITION;
in vec3 NORMAL;
in vec2 TEXCOORD;

out vec2 pos_zw;
out vec3 normal;
out vec3 ec_pos;
out vec2 uv;

void main()
{
	vec3 p0 = texelFetch(box_coords, gl_InstanceID*3 + 0).xyz;
	float size = texelFetch(box_coords, gl_InstanceID*3 + 2).y;
	vec3 p1 = texelFetch(box_coords, gl_InstanceID*3 + 3).xyz;

	vec3 t = p1 - p0;
	vec3 n = p1 + p0;
	vec3 b = cross(t, n);
	n = cross(b, t);
	t = normalize(t);
	n = normalize(n);
	b = normalize(b);

	vec3 pos;
	pos.x = dot(POSITION, t);
	pos.y = dot(POSITION, n);
	pos.z = dot(POSITION, b);

	pos = pos*size + p0;

	vec3 nrm;
	nrm.x = dot(NORMAL, t);
	nrm.y = dot(NORMAL, n);
	nrm.z = dot(NORMAL, b);

	//uv = TEXCOORD;
	uv = pos.xy*vec2(1.0/2.5, 1.0/2.5) - vec2(0.5);

	normal = NormalMatrix * nrm;

	ec_pos = vec3(ModelViewMatrix * vec4(pos, 1.0));

	vec4 proj_pos = ModelViewProjectionMatrix * vec4(pos, 1.0);
	pos_zw = proj_pos.zw;
	gl_Position = proj_pos;
}
