
import java.awt.*;

public class SimplexCanvas
  extends Canvas
{
  public Vertex V[];
  public int ix[];
  public int iy[];
  public int nVertex;
  private double xc, yc, rad;
  public Vertex vMouse = new Vertex( 2 );

  public void setVertices( Vertex v[] )
  {
    V = v;
    nVertex = V.length;
    ix = new int[nVertex];
    iy = new int[nVertex];
    xc = V[0].coord[0];
    yc = V[0].coord[1];
    rad = 3 * Vertex.getDiameter( V );
  }

  public void paint( Graphics g )
  {
    if( V == null )
      return;
    int w, h, ir;
    int i, j;
    int x0, y0, x1, y1;

    double nxc, nyc, nrad;
    double dx, dy;
    nrad = 2 * Vertex.getDiameter( V );
    nxc = V[0].coord[0];
    nyc = V[0].coord[1];
    dx = nxc - xc;
    dy = nyc - yc;
    if( ( Math.sqrt( dx*dx + dy *dy ) + nrad > ( 2 * rad / 3 ) )
        || ( nrad < 0.25 * rad ) ) {
      xc = nxc;
      yc = nyc;
      rad = 1.5 * nrad;
      if( rad < 1e-6 )
        rad = 1e-6;
    }
    w = size().width;
    h = size().height;
    ir = ( ( w < h ) ? w : h ) / 2;

    g.setColor( Color.blue );
    for( i = 0; i < nVertex; i++ ) {
      ix[i] = (int)( w/2 + ( ( V[i].coord[0] - xc ) / rad ) * ir );
      iy[i] = (int)( h/2 - ( ( V[i].coord[1] - yc ) / rad ) * ir );
    }
    for( i = 0; i < nVertex; i++ )
      for( j = 0; j < i; j++ )
        g.drawLine( ix[i], iy[i], ix[j], iy[j] );
    g.setColor( Color.green );
    g.fillRect( ix[0]-2, iy[0]-2, 5, 5 );
    g.setColor( Color.red );
    g.fillRect( ix[nVertex-1]-2, iy[nVertex-1]-2, 5, 5 );
    if( nVertex > 2 ) {
      g.setColor( Color.orange );
      g.fillRect( ix[nVertex-2]-2, iy[nVertex-2]-2, 5, 5 );
    }

    g.setColor( Color.black );
    String txt = "Center:( " + xc + ", " + yc + " ); Radius:" + rad;
    g.drawString( txt, 2, h-5 );
  }

  public Vertex xyToVertex( int ix, int iy )
  {
    int w, h, ir;
    w = size().width;
    h = size().height;
    ir = ( ( w < h ) ? w : h ) / 2;
    vMouse.coord[0] = xc + ( rad * ( ix - w/2 ) ) / ir;
    vMouse.coord[1] = yc + ( rad * ( h/2 - iy ) ) / ir;
    return vMouse;
  }
  public boolean handleEvent( Event evt )
  {
    if( evt.id == Event.MOUSE_MOVE ) {
      if( evt.target == this ) {
        postEvent( new Event( this, Event.ACTION_EVENT,
                                xyToVertex( evt.x, evt.y ) ) );
      }
    }
    return super.handleEvent( evt );
  }
  public Vertex getMouseVertex()
  {
    return vMouse;
  }
}
