uniform int nr_lights;

varying vec3 q_tilde;
varying vec3 inv_T_square_v;
varying vec3 inv_T_square_e_c;
varying vec4 ev_clip;
varying vec3 v;
//varying vec3 h[4];
//varying vec3 l[4];
varying vec4 a;
//varying vec4 d;
varying vec4 s;

void main()
{
	// decompress the matrix T
	float R = gl_Vertex.w;
	float inv_R = 1.0/R;

	// determine eye point in parameter space
	vec3 e = gl_ModelViewMatrixInverse[3].xyz;
	vec3 e_tilde = inv_R*(e - gl_Vertex.xyz);

	// compute helper
	float inv_e_square = 1.0/dot(e_tilde,e_tilde);

	// determine silhoutte center in parameter space
	vec3 m_tilde = inv_e_square*e_tilde;

	// determine radius of silhouette in parameter space
	float r = sqrt(1.0-inv_e_square);

	// compute vector x of length r orthogonal to e in parameter space
	vec3 x_tilde = r*normalize(cross(gl_ModelViewMatrixInverse[1].xyz,e_tilde));

	// compute vector y of length r orthogonal to x and e in parameter space
	vec3 y_tilde = r*normalize(cross(e_tilde,x_tilde));

	// compute the corner point in homogeneous object coordinates
	vec3 V_tilde = m_tilde+gl_MultiTexCoord2.x*x_tilde+gl_MultiTexCoord2.y*y_tilde;
	vec3 v_tilde = V_tilde - e_tilde;

	vec4 V;
	V.xyz = R*V_tilde+gl_Vertex.xyz;
	V.w = 1.0;
 
	q_tilde.xy = gl_MultiTexCoord2.xy;
	q_tilde.z = sqrt(inv_e_square);

	// compute vector from eye to vertex in eye space
	v = (gl_ModelViewMatrix*V).xyz;

	// compute components to compute normal in eye space
	inv_T_square_e_c = gl_NormalMatrix*(e_tilde);
	inv_T_square_v   = gl_NormalMatrix*(v_tilde);

	v = -normalize(v);

	gl_Position	   = gl_ModelViewProjectionMatrix * V;
	ev_clip.xy     = (gl_ModelViewProjectionMatrix * gl_ModelViewMatrixInverse[3]).zw;
	ev_clip.zw     = gl_Position.zw - ev_clip.xy;
	a = vec4(0.0,0.0,0.0,0.0);

	vec4 lpos;

	for (int i=0; i<nr_lights; ++i) {
		a += gl_LightSource[i].ambient*gl_Color;
	}

	gl_FrontColor = gl_Color;
	//d = gl_Color;
	s = gl_FrontMaterial.specular;
}