// This shader takes the output from the vertex shader.  For each triangle 
//      (i.e., every three vertices), subdivides the triangle into three.
// 
// What is not apparent in the code is that these values (i.e., what is
//      passed into gl_Position) is stored into a transform feedback buffer
//      on the GPU instead of being passed to the rasterizer.  This is
//      specified using OpenGL's transform feedback mechanism and the lack
//      of rasterization occurs because GL_RASTERIZER_DISCARD has been enabled

#version 400 

// This really shouldn't be required, but NVIDIA's driver seems to want it...
#extension GL_EXT_geometry_shader4 : enable

// This says our geometry shader takes triangle primitives as input
//    and runs once for each input triangle (invocations=1 is the default)
layout (triangles, invocations = 1) in;

// This says our geometry shader outputs triangle-strip primitives and 
//    generates at most 9 vertices per geometry shader invocation.  The
//    only valid outputs are points, line_strip, triangle_strip.  The 
//    (pretty stupid) default for max_vertices is 0.
layout (triangle_strip, max_vertices = 9) out;

void main( void )
{
	// Get the input vertices
	vec4 v0 = gl_PositionIn[0];
	vec4 v1 = gl_PositionIn[1];
	vec4 v2 = gl_PositionIn[2];

	// Compute values halfway between
	vec4 v01 = (v0+v1)*0.5;
	vec4 v02 = (v0+v2)*0.5;
	vec4 v12 = (v1+v2)*0.5;
	
	// Output the 3 sub-triangles
	gl_Position = v0;
	EmitVertex();
	gl_Position = v01;
	EmitVertex();
	gl_Position = v02;
	EmitVertex();
	EndPrimitive();
	
	gl_Position = v01;
	EmitVertex();
	gl_Position = v1;
	EmitVertex();
	gl_Position = v12;
	EmitVertex();
	EndPrimitive();
	
	gl_Position = v02;
	EmitVertex();
	gl_Position = v12;
	EmitVertex();
	gl_Position = v2;
	EmitVertex();
	EndPrimitive();
}