/* Sierpinski Gasket in GLUT, gkf 3jan2K */ 
/* modified to mouse the starting point 12jan2K */
#include <stdlib.h>
#include <stdio.h>
#include <gl\glut.h>
#include <math.h>
float v[3][2] = {{1.,0.},{0.,1.},{0.,0.}};   /* a triangle */
float vv[2]={.2,.9};                        /* initial pos'n */
#define NAP  1                           /* microseconds */
#define RND ((float)rand()/RAND_MAX)         /* random fraction */
#define INT(X) ((int)floor(X))                  /* integer part */
#define DG .01745
#define C(u) cos(u*DG)
#define S(u) sin(u*DG)
#define X2x(u)  ( ((float)u-200)*4/400 )
#define Y2y(u)  ( (200-(float)u)*4/400 )
/***********************************************************/
void usleep(int nap){int ii; for(ii=0;ii< nap; ii++);}
/***********************************************************/
void move(int ii){
  vv[0]= (vv[0] + v[ii][0])/2;  /* half-way toward that vertex */
  vv[1]= (vv[1] + v[ii][1])/2;  
}
void plot(int ii){
  glBegin(GL_POINTS);                    /* draw  a */              
    glColor3f((ii==0),(ii==1),(ii==2)); /* colored point */
    glVertex2fv(vv);                  
  glEnd(); 
}

/***********************************************************/
void display(){       
  int ii = INT(3*(RND));      /* pick randomly ii = 0,1,2 */
  plot(ii);
  move(ii);
  usleep(NAP);    
}
/***********************************************************/
void kircle(float radius, float xcenter, float ycenter){
     int th; 
     glColor3f(0.0,1.0,0.0);   /* green circle */
     glBegin(GL_LINE_STRIP);
     for( th=0 ; th < 360; th += 5){
        glVertex2f( xcenter + radius*C(th), ycenter + radius*S(th));
     }
     glEnd();
 
}
/***********************************************************/
void pickaspot(float xx, float yy){
     glClear(GL_COLOR_BUFFER_BIT);
     kircle(0.1,xx,yy);   
     v[2][0]=xx; v[2][1]=yy;
}
/***********************************************************/
void keyboard(unsigned char key, int X, int Y){
  switch(key){ 
     case  27: fprintf(stderr," Thanks for using GLUT ! \n"); exit(0); break;
     case 'w': {pickaspot(X2x(X),Y2y(Y)); break;}; 
     case 'W': {break;};
   }
  printf("x = %d y= %d \n", X,Y);
}
/***********************************************************/
void idle(void){ glutPostRedisplay(); } 
/***********************************************************/
int main(int argc, char **argv){ 
  glutInitWindowSize(400, 400);        
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_RGB); 
  glutCreateWindow("<< Sierpinski in GLUT >>");
  glutDisplayFunc(display);
  glutKeyboardFunc(keyboard);
  glutIdleFunc(idle); 
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(-2.0,2.0,-2.0,2.0,-2.0,2.0);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  glutMainLoop();
  return 0;             /* ANSI C requires main to return int. */
}
