/*******************************************************************************
*                                                                              *
*                                   Viewmol                                    *
*                                                                              *
*                              E L L I P S E . C                               *
*                                                                              *
*                 Copyright (c) Joerg-R. Hill, October 2003                    *
*                                                                              *
********************************************************************************
*
* $Id: ellipse.c,v 1.6 2003/11/07 11:00:28 jrh Exp $
* $Log: ellipse.c,v $
* Revision 1.6  2003/11/07 11:00:28  jrh
* Release 2.4
*
* Revision 1.5  2000/12/10 15:05:47  jrh
* Release 2.3
*
* Revision 1.4  1999/05/24 01:25:20  jrh
* Release 2.2.1
*
* Revision 1.3  1999/02/07 21:48:28  jrh
* Release 2.2
*
* Revision 1.2  1998/01/26 00:47:39  jrh
* Release 2.1
*
* Revision 1.1  1996/12/10  18:40:46  jrh
* Initial revision
*
*/
#include<GL/gl.h>
#include<math.h>

void ellipse(double x1, double y1, double z1, double x2, double y2, double z2,
             double x3, double y3, double z3, int n)
{
  const double pi2=8.*atan(1.0);
  double step=pi2/(double)n;
  double vx1=x2-x1, vy1=y2-y1, vz1=z2-z1;
  double vx2=x3-x1, vy2=y3-y1, vz2=z3-z1;
  double a, b, tmat[4][4];
  register double t, aa, bb;
  double vertex[3];

  /* First build the transformation matrix for rotating a ellipse defined by
     the points (0,0,0), (a,0,0), and (0,b,0) to the desired position */

  a=sqrt(vx1*vx1+vy1*vy1+vz1*vz1);
  b=sqrt(vx2*vx2+vy2*vy2+vz2*vz2);
  if (a > 1.0e-3 && b > 1.0e-3)
  {
    tmat[0][0]=vx1/a;
    tmat[1][0]=vy1/a;
    tmat[2][0]=vz1/a;
    tmat[0][1]=vx2/b;
    tmat[1][1]=vy2/b;
    tmat[2][1]=vz2/b;

    vertex[0]=a*tmat[0][0]+x1;
    vertex[1]=a*tmat[1][0]+y1;
    vertex[2]=a*tmat[2][0]+z1;
    glBegin(GL_LINE_LOOP);
    glVertex3dv(vertex);

    t=step;
    while (t < pi2)
    {
      aa=a*cos(t);
      bb=b*sin(t);
      vertex[0]=aa*tmat[0][0]+bb*tmat[0][1]+x1;
      vertex[1]=aa*tmat[1][0]+bb*tmat[1][1]+y1;
      vertex[2]=aa*tmat[2][0]+bb*tmat[2][1]+z1;
      t+=step;
      glVertex3dv(vertex);
    }
    glEnd();
  }
  else if (a > 1.0e-3)
  {
    glBegin(GL_LINES);
    vertex[0]=vx1+x1;
    vertex[1]=vy1+y1;
    vertex[2]=vz1+z1;
    glVertex3dv(vertex);
    vertex[0]=x1-vx1;
    vertex[1]=y1-vy1;
    vertex[2]=z1-vz1;
    glVertex3dv(vertex);
    glEnd();
  }
  else if (b > 1.0e-3)
  {
    glBegin(GL_LINES);
    vertex[0]=vx2+x1;
    vertex[1]=vy2+y1;
    vertex[2]=vz2+z1;
    glVertex3dv(vertex);
    vertex[0]=x1-vx2;
    vertex[1]=y1-vy2;
    vertex[2]=z1-vz2;
    glVertex3dv(vertex);
    glEnd();
  }
  else
    return;
}
