#include <GLUT/glut.h>
#include <OpenGL/gl.h>
#include <math.h>
#include <time.h>
#include <stdlib.h>

#define SEED 31415926
#define MAX_V 10000
#define DIV_V 5000.0
#define SUB_V 1


#define MY_PI 3.14159
#define ANG_INCR MY_PI / 8
#define ANG_ROT .25

void renderer(void);
void initialSetup(void);
void changeSize(GLsizei w, GLsizei h);
void tf(int blah);
int rand2();

long long lastseed;

float lastang;

float heightfield [50][50];

int main (int argc, const char * argv[]) 
{
    glutInit(&argc, (char **)argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutCreateWindow("Triangles Demo");
    glutDisplayFunc(renderer);
    glutReshapeFunc(changeSize);
    initialSetup();
    glutTimerFunc(25, tf, 1);
    glutMainLoop();
    return 0;
}

void renderer()
{
    int last=0, i, j;
    
    lastang += ANG_ROT;
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glPushMatrix();
    glRotatef(lastang,1,0,0);
    glFrontFace(GL_CW);
   
    
    //X dir
    for(i=0; i < 49; i++)
    {
        glBegin(GL_TRIANGLE_STRIP);
     //Y dir
        for(j=0; j < 50; j++)
        {
            glColor3f(i/50.0,j/50.0,heightfield[i][j] /10.0);
            glVertex3f(i,j,heightfield[i][j]);
            glColor3f((i+1)/50.0,j/50.0,heightfield[i][j] /10.0);
            glVertex3f(i+1,j, heightfield[i+1][j]);
        }
        glEnd();

    }
    glPopMatrix();
    glutSwapBuffers();
}

void tf(int blah)
{
    glutPostRedisplay();
    glutTimerFunc(15, tf, 1);
}

void changeSize(GLsizei w, GLsizei h)
{
    GLfloat sideRange = 100;
    
    glViewport(0,0,w,h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-10, 60, -sideRange/2, sideRange/2, sideRange, -sideRange);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}


void initialSetup(void)
{
    int i, j;
    
    lastseed = SEED;
    
    lastang =0;
    glShadeModel(GL_FLAT);
    glEnable(GL_DEPTH_TEST);
    glDisable(GL_CULL_FACE);
    glPolygonMode(GL_BACK, GL_FILL);
    glPolygonMode(GL_FRONT, GL_FILL);
    
    glClearColor(0.0, 0.0, 0.0, 1.0);
    
    
    //Generate Height Field
    for(i=0; i < 50; i++)
        for(j=0; j < 50; j++)
            heightfield[i][j] = rand2() % 100 / 10.0;
}


int rand2()
{
    lastseed = lastseed * 16807 % 2147483647;
    return lastseed;
}

