/*
* oZone3D.Net SURFACE DEFORMER Benchmark
* Vertex Shader
* Author: Jerome 'JeGX' Guinot
* URL: http://www.ozone3d.net/demos_projects/surface_deformer_benchmark.php
*/

uniform float time;
uniform float frequency;

#define NUM_LIGHTS 2
varying vec3 normal, lightDir[NUM_LIGHTS], eyeVec;

vec3 computeNormal( vec3 position, vec3 tangent, vec3 binormal, float phase, float freq )
{
	mat3 J;
	
	float dist = sqrt(position.x*position.x + position.z*position.z);
	float jac_coef = cos(freq*dist + phase) / (dist+0.00001);
	
	// A matrix is an array of column vectors so J[2] is the third column of J.
	
	J[0][0] = 1.0;
	J[0][1] = jac_coef * position.x;
	J[0][2] = 0.0;
	
	J[1][0] = 0.0;
	J[1][1] = 1.0;
	J[1][2] = 0.0;

	J[2][0] = 0.0;
	J[2][1] = jac_coef * position.z;
	J[2][2] = 1.0;
	
	vec3 u = J * tangent;
	vec3 v = J * binormal;
	
	vec3 n = cross(v, u);
	return normalize(n);
}

vec4 displaceVertexFunc( vec4 pos, float phase, float frequency ) 
{
	vec4 new_pos;
	
	new_pos.x = pos.x;
	new_pos.z = pos.z;
	new_pos.w = pos.w;
	
	float dist = sqrt(pos.x*pos.x + pos.z*pos.z);
	new_pos.y = pos.y + 20.0 * sin( frequency * dist + phase );
	
	return new_pos;
}

void main(void)
{
	//
	// if the engine does not provide the tangent vector (but oZone3D does!) you can compute it
	// with the following chunk of code:
	//
	vec3 tangent; 
	vec3 binormal; 
	
	vec3 c1 = cross(gl_Normal, vec3(0.0, 0.0, 1.0)); 
	vec3 c2 = cross(gl_Normal, vec3(0.0, 1.0, 0.0)); 
	
	if(length(c1)>length(c2))
	{
		tangent = c1;	
	}
	else
	{
		tangent = c2;	
	}
	
	tangent = normalize(tangent);
	
	//binormal = cross(tangent, gl_Normal); 
	binormal = cross(gl_Normal, tangent); 
	binormal = normalize(binormal);
	
	vec4 displacedVertex = displaceVertexFunc(gl_Vertex, time*2.0, frequency );
	gl_Position = gl_ModelViewProjectionMatrix * displacedVertex;	   	
	
	
	vec3 displacedNormal = computeNormal( displacedVertex.xyz, tangent, binormal, time*2.0, frequency );
	normal = -normalize(gl_NormalMatrix * displacedNormal);
	

	vec3 vVertex = vec3(gl_ModelViewMatrix * displacedVertex);
	
	int i = 0;
	for( i=0; i<NUM_LIGHTS; i++ )
	{
		lightDir[i] = vec3(gl_LightSource[i].position.xyz - vVertex);
	}

	eyeVec = -vVertex;
	
	/*
	normal = gl_NormalMatrix * gl_Normal;
	gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;	   	
	
	vec3 vVertex = vec3(gl_ModelViewMatrix * gl_Vertex);
	
	int i = 0;
	for( i=0; i<NUM_LIGHTS; i++ )
	{
		lightDir[i] = vec3(gl_LightSource[i].position.xyz - vVertex);
	}

	eyeVec = -vVertex;
	*/
}
