#version 430 core
layout (triangles) in;
layout (triangle_strip, max_vertices = 5) out;
in vec4 vColor[];
in vec2 vPosOff[];
in float vRadMag[];
out vec4 gColor;
out float wStart;
out float wEnd;
out vec3 gBoundingBox;

out vec2 box2 ;

vec2 normV2 (vec2 v)
{   return vec2(-v.y,v.x) ;
}
float lhs (vec2 da, vec2 db)
{   return sign(dot(da, normV2(db))) ;
}

float extrapolate (vec2 inOne, vec2 inZeroA, vec2 inZeroB, vec2 xy)
{ 
    float det = inOne.x * (inZeroA.y - inZeroB.y)
                + inZeroA.x * (inZeroB.y - inOne.y)
                + inZeroB.x * (inOne.y   - inZeroA.y)
                ;
    float r = (inZeroA.y - inZeroB.y) ;
    float s = (inZeroB.x - inZeroA.x) ;
    float t = (inZeroA.x * inZeroB.y - inZeroB.x * inZeroA.y) ;
    return r * xy.x + s * xy.y + t
            / det ;
}

void main()
{
  vec3 pa = gl_in[0].gl_Position.xyz;
  vec3 pb = gl_in[1].gl_Position.xyz;
  vec3 pc = gl_in[2].gl_Position.xyz;

  wStart = vRadMag [0];
  wEnd   = vRadMag [2];

  box2 = vec2 (1,0);
  gBoundingBox = vec3 (0.9,0.1,0);
  gColor = vColor[0];
  gl_Position = vec4 (vPosOff[0] , pa.z , 1);
  EmitVertex();
  box2 = vec2 (0,1);
  gBoundingBox = vec3 (0.1,0.9,0);
  gColor = vColor[2];
  gl_Position = vec4 (vPosOff[2] , pc.z , 1);
  EmitVertex();
  box2 = vec2( extrapolate(vPosOff[0],vPosOff[2],pb.xy,pa.xy)
             , extrapolate(vPosOff[2],vPosOff[0],pb.xy,pa.xy)
             ) ;
  box2 = vec2(0.2,0);
  gBoundingBox = vec3 (1,0,1);
  gColor = vColor[0];
  gl_Position = vec4 (pa, 1);
  EmitVertex();
  box2 = vec2( extrapolate(vPosOff[0],vPosOff[2],pb.xy,pc.xy)
             , extrapolate(vPosOff[2],vPosOff[0],pb.xy,pc.xy)
             ) ;
  box2 = vec2(0,0.2);
  gBoundingBox = vec3 (0,1,1);
  gColor = vColor[2];
  gl_Position = vec4 (pc, 1);
  EmitVertex();
  box2 = vec2( 0,0 ) ;
  gBoundingBox = vec3 (0,0,0);
  gColor = vColor[1];
  gl_Position = vec4 (pb, 1);
  EmitVertex();

  EndPrimitive();
}
