#version 150
layout(triangles) in;
layout(triangle_strip, max_vertices=3) out;

uniform float normal_length;
uniform float time;
uniform vec4 light_position;

// GLSL Hacker automatic uniform
uniform mat4 gxl3d_ModelViewProjectionMatrix;
uniform mat4 gxl3d_ModelViewMatrix;
uniform mat4 gxl3d_ViewMatrix;


in Vertex
{
  vec4 normal;
  vec4 color;
} vertex[];

out vec4 vertex_color;
out vec4 vertex_normal;
out vec4 vertex_light_dir;
out vec4 vertex_cam_space;

void main()
{
  //------ Face normal
  //
  vec3 P0 = gl_in[0].gl_Position.xyz;
  vec3 P1 = gl_in[1].gl_Position.xyz;
  vec3 P2 = gl_in[2].gl_Position.xyz;
  
  vec3 V0 = P0 - P1;
  vec3 V1 = P2 - P1;
  
  vec3 N = cross(V1, V0);
  N = normalize(N);
  
  
  vec4 lightEye =  gxl3d_ViewMatrix * light_position;
  

  //------ Generate a new face along th direction of the face normal
  //
  int i;
  for(i=0; i<gl_in.length(); i++)
  {
    vec4 P = gl_in[i].gl_Position;
    float len = sqrt(P.x*P.x + P.z*P.z);
    float scale = 2.0 + 1.0 * cos(time*2.0 + len);
    P = vec4(P.xyz + N * normal_length * scale, 1.0);
    gl_Position = gxl3d_ModelViewProjectionMatrix * P;
    vertex_color = vertex[i].color;
    
    vertex_normal = gxl3d_ModelViewMatrix  * vec4(vertex[i].normal.xyz, 0.0);
    vec4 view_vertex = gxl3d_ModelViewMatrix * P;
    vertex_light_dir = lightEye - view_vertex;
    vertex_cam_space = -view_vertex;
    
    EmitVertex();
  }
  EndPrimitive();
}
