#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#include <stdio.h>
#include <GL/glut.h>
#include <GL/gl.h>

float viewRotY = 0, viewRotX = 0;


void drawEverything(void);
void drawWaveMesh(int columns,int rows,float timeOffset);
float currentTime(void);
void checkGLError(char *);
void idle(void);
void key(unsigned char k, int x, int y);
void specialkey(int k, int x, int y);



int main(int argc, char *argv[])
    {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("example");
    glutDisplayFunc(drawEverything);
    glutKeyboardFunc(key);
    glutSpecialFunc(specialkey);
    glutIdleFunc(idle);
    glutMainLoop();
    return 0;
    }


void drawEverything(void)
    {
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);
    
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(50.0, 1.0, 1.0, 100.0);
    glMatrixMode(GL_MODELVIEW);

    glLoadIdentity();
    glTranslatef(0.0, 0.0, -15.0);
    glRotatef(viewRotX, 1.0, 0.0, 0.0);
    glRotatef(viewRotY, 0.0, 1.0, 0.0);
    
    drawWaveMesh(24,24,currentTime());
    
    glutSwapBuffers();
    
    checkGLError("end-of-frame");
    }


void drawWaveMesh(int columns,int rows,float timeOffset)
    {
    int i,j;
    float x,y,z;
    srand48(0);
    for (j = 0; j < rows; j++)
        {
        glBegin(GL_TRIANGLE_STRIP);
        for (i = 0; i < columns; i++)
            {
            x = (((float)i) / columns) * 10.0 - 5.0;
            z = (((float)j) / rows) * 10.0 - 5.0;
            y = sin(x+timeOffset) * sin(z+timeOffset);
            glColor3f(drand48(), drand48(), drand48());
            glVertex3f(x,y,z);

            z = (((float)j+1) / rows) * 10.0 - 5.0;
            y = sin(x+timeOffset) * sin(z+timeOffset);
            glVertex3f(x,y,z);
            }
        glEnd();
        }
    }


float currentTime(void)
    {
    static struct timeval startTime;
    static int firstCall=1;
    struct timeval t;
    if (firstCall)
        {
        firstCall = 0;
        gettimeofday(&startTime, NULL);
        }
    gettimeofday(&t,NULL);
    return (t.tv_sec-startTime.tv_sec) +
           (t.tv_usec - startTime.tv_usec) / 1000000.0;
    }


void checkGLError(char *prefix)
    {
    GLenum err = glGetError();
    if (err != GL_NO_ERROR)
        printf("%s GL error '%s'\n",prefix,gluErrorString(err));
    }


void idle(void)
    {
    glutPostRedisplay();
    }


void key(unsigned char k, int x, int y)
    {
    if (k == 27)
        exit(0);
    glutPostRedisplay();
    }


void specialkey(int k, int x, int y)
    {
    if (k == GLUT_KEY_LEFT)
        viewRotY += 3;
    else if (k == GLUT_KEY_RIGHT)
        viewRotY -= 3;
    else if (k == GLUT_KEY_UP)
        viewRotX += 3;
    else if (k == GLUT_KEY_DOWN)
        viewRotX -= 3;
    glutPostRedisplay();
    }

