/* Jin Ding -- Period 3 -- 3/24/98 */
/* mandelbrot.cpp */

#include <iostream.h>
#include "glaux.h"
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <math.h>

const MAX=400,MAXIT=50;
double color[MAXIT][3],
  xcor=0.0,ycor=0.0,z=-0.35,
  zinc=.05;

static void Init (void) {
  glClearColor(0.0,0.0,0.0,1.0);
  glShadeModel(GL_SMOOTH);
}

static void Reshape(int width, int height) {
  glViewport(0,0,(GLsizei)width,(GLsizei)height);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluPerspective(60.0,(GLfloat)width/(GLfloat)height,1.0,0.0);
//  glOrtho(-2.0,2.0,-2.0,2.0,-2.0,2.0);
  glMatrixMode(GL_MODELVIEW);
}

static void key_esc() {
  auxQuit();
}

static void zoomIn() { z -= zinc; }

static void zoomOut() { z += zinc; }

static void moveUp() { ycor += .15; }

static void moveDown() { ycor -= .15; }

static void moveLeft() { xcor += .15; }

static void moveRight() { xcor -= .15; }

static void getPos(AUX_EVENTREC *mousecor) {
  xcor += MAX/2.0 - mousecor->data[0];
  ycor += MAX/2.0 - mousecor->data[1]; 
}

void SetColor() {
  for (int i=0;i<MAXIT;i++) {
/*    color[i][0]=sin(3*i/3.14);
    color[i][1]=cos(2*i/3.14);
    color[i][2]=sin(2*i/3.14);
*/
    color[i][0]=0.0;
    color[i][1]=i/20.0;
    color[i][2]=i/10.0;
  }
}

void DrawMyStuff() {
int x,y,it;
double cx,cy,xnew,ynew,xtemp,ytemp,r,MAXfac;

  MAXfac = MAX*(sqrt(z*z)+1);
  glBegin(GL_POINTS);
  for (x = -(int)MAXfac;x<MAXfac;x++)
    for (y = -(int)MAXfac;y<MAXfac;y++) {
      it = 0; r = 0.0;
      cx = 2.0*x/MAXfac;
      cy = 2.0*y/MAXfac;
      xnew = cx;
      ynew = cy;
      while ((r < 4) && (it < MAXIT)) {
        xtemp = xnew*xnew - ynew*ynew + cx;
        ytemp = 2 * xnew * ynew + cy;
        r = xtemp*xtemp + ytemp*ytemp;
        it++;
        xnew = xtemp;
        ynew = ytemp;
      }
      glColor3f(color[it][0],color[it][1],color[it][2]);
      glVertex3f(cx,cy,0);
    }
  glEnd();
}
 
static void display() {
  glClear(GL_COLOR_BUFFER_BIT);
  SetColor();
  glPushMatrix();
    glLoadIdentity();
    gluLookAt(0.0,0.0,1.01*MAX,0.0,0.0,0.0,0.0,1.0,0.0);
    glTranslatef(xcor,ycor,MAX-z);
    DrawMyStuff();
  glPopMatrix();
  glFlush();
  auxSwapBuffers();
}

int main(int argc,char **argv) {
//AUX_EVENTREC *mousecor;

  auxInitDisplayMode(AUX_RGBA);
  auxInitPosition(50,100,MAX,MAX);
  if (auxInitWindow("Mandelbrot") == GL_FALSE)
    auxQuit();
  Init();
//  auxMouseFunc(AUX_LEFTBUTTON,AUX_MOUSEDOWN,getPos(mousecor));
  auxKeyFunc(AUX_i,zoomIn);
  auxKeyFunc(AUX_o,zoomOut);
  auxKeyFunc(AUX_UP,moveUp);
  auxKeyFunc(AUX_DOWN,moveDown);
  auxKeyFunc(AUX_LEFT,moveLeft);
  auxKeyFunc(AUX_RIGHT,moveRight);
  auxExposeFunc(Reshape);
  auxReshapeFunc(Reshape);
  auxMainLoop(display);
  return 0;
}

