#include <GL/glut.h>
#include <GL/gl.h>


#include <d2simplexintersection.h>

#include <d2arrow.h>


void d2simplexintersection::draw()
{
  glPushAttrib(GL_LIGHTING);
  glPushAttrib(GL_CURRENT_BIT);

  glDisable(GL_LIGHTING);

  if (intersection)
  {
    glColor3ub(255,0,0);

    d2simplexFill(s1).draw();
    d2simplexFill(s2).draw();
  }

  glColor3ub(0,255,127);
  s1g.draw();
  d2simplexNormals(s1).draw();

  glColor3ub(255,255,0);
  s2g.draw();
  d2simplexNormals(s2).draw();

  glPopAttrib();
  glPopAttrib();
}

d2simplexintersection::d2simplexintersection
(
  d2simplex & _s1,
  d2simplex & _s2
)
  : s1(_s1), s2(_s2), s1g(s1), s2g(s2), intersection(false) 
{
}


d2simplexOutline::d2simplexOutline(d2simplex & _s)
  : s(_s)
{
}

void d2simplexOutline::draw()
{
  glBegin(GL_LINES);

  glVertex3f(s.v[0].x,s.v[0].y,0.0);
  glVertex3f(s.v[1].x,s.v[1].y,0.0);
  glVertex3f(s.v[1].x,s.v[1].y,0.0);
  glVertex3f(s.v[2].x,s.v[2].y,0.0);
  glVertex3f(s.v[0].x,s.v[0].y,0.0);
  glVertex3f(s.v[2].x,s.v[2].y,0.0);

  glEnd();
}


d2simplexFill::d2simplexFill(d2simplex & _s)
  : s(_s)
{
}

void d2simplexFill::draw()
{
  glBegin(GL_TRIANGLES);

  glVertex3f(s.v[0].x,s.v[0].y,0.0);
  glVertex3f(s.v[1].x,s.v[1].y,0.0);
  glVertex3f(s.v[2].x,s.v[2].y,0.0);

  glVertex3f(s.v[2].x,s.v[2].y,0.0);
  glVertex3f(s.v[1].x,s.v[1].y,0.0);
  glVertex3f(s.v[0].x,s.v[0].y,0.0);

  glEnd();
}

d2simplexNormals::d2simplexNormals(d2simplex & _s)
  : s(_s), arrowlength(0.1), headlength(0.03)
{
}

void d2simplexNormals::draw()
{
//  double const arrowlength=0.1;
//  double const headlength=0.03;
  d2arrow * arrow[3];
  arrow[0] = new d2arrow(s.v[1],s.v[0],arrowlength,headlength);
  arrow[1] = new d2arrow(s.v[2],s.v[1],arrowlength,headlength);
  arrow[2] = new d2arrow(s.v[0],s.v[2],arrowlength,headlength);

  for (uint i=0; i<3; ++i)
  {
    arrow[i]->draw();
    delete arrow[i];
  }

  // Note the more efficient way of doing this is to construct the
  // arrows once and transform the points as the simplex points are
  // transformed.  

  // I am currently assuming that the graphics is separate from the
  // simplex so an on the fly computation is needed.  When the simplex
  // is rotated so too is the normals but I would need to redesign
  // the interfaces.  The on the fly computation creates a separation
  // at the cost of performance, though in this case it is not too bad
  // because vector calculus is good.

}







