// manip.cpp
// Glenn G. Chappell
// 25 Sep 2012
//
// For CS 381 Fall 2012
// 3-D Object Manipulation

// OpenGL/GLUT includes - DO THESE FIRST
#include <cstdlib>       // Do this before GL/GLUT includes
using std::exit;
#ifndef __APPLE__
# include <GL/glut.h>    // GLUT stuff, includes OpenGL headers as well
#else
# include <GLUT/glut.h>  // Apple puts glut.h in a different place
#endif

// Other includes
#include "lib381/bitmapprinter.h"
                         // For class BitmapPrinter
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;


// Global variables
// Keyboard
const int ESCKEY = 27;         // ASCII value of Escape

// Window/viewport
const int startwinsize = 600;  // Start window width & height (pixels)
int winw = 1, winh = 1;        // Window width, height (pixels)
                               //  (Initialize to avoid spurious errors)

// Objects
double hang, vang;             // Horiz & vert rotation angles (deg)
const double angstep = 5.;     // Amt to rotate on single keypress (deg)


// drawSquare
// Draws a filled square, using current GL states,
//  in the x,y plane, centered at the origin, aligned w/ x & y axes,
//  with side 2.
void drawSquare()
{
    glBegin(GL_QUADS);
        glVertex2d(-1., -1.);
        glVertex2d( 1., -1.);
        glVertex2d( 1.,  1.);
        glVertex2d(-1.,  1.);
    glEnd();
}


// drawAxis
// Draws a line segment, using current GL states, along the z-axis,
//  centered at the origin, 2 units long.
void drawAxis()
{
    glBegin(GL_LINES);
        glVertex3d(0., 0., -1.);
        glVertex3d(0., 0., 1.);
    glEnd();
}


// drawCubeWithAxes()
// Draws a cube, centered at origin, side length 2, axis aligned,
// each face a different color. Axis lines also drawn.
void drawCubeWithAxes()
{
    // +x face
    glColor3d(1., 0., 0.);
    glPushMatrix();
    glTranslated(1., 0., 0.);
    glRotated(90., 0., 1., 0.);
    drawSquare();
    glColor3d(0.7, 0., 0.);
    drawAxis();
    glPopMatrix();

    // -x face
    glColor3d(0., 1., 1.);
    glPushMatrix();
    glTranslated(-1., 0., 0.);
    glRotated(90., 0., 1., 0.);
    drawSquare();
    glPopMatrix();

    // +y face
    glColor3d(0., 1., 0.);
    glPushMatrix();
    glTranslated(0., 1., 0.);
    glRotated(90., 1., 0., 0.);
    drawSquare();
    glColor3d(0., 0.7, 0.);
    drawAxis();
    glPopMatrix();

    // -y face
    glColor3d(1., 0., 1.);
    glPushMatrix();
    glTranslated(0., -1., 0.);
    glRotated(90., 1., 0., 0.);
    drawSquare();
    glPopMatrix();

    // +z face
    glColor3d(0., 0., 1.);
    glPushMatrix();
    glTranslated(0., 0., 1.);
    drawSquare();
    glColor3d(0., 0., 0.7);
    drawAxis();
    glPopMatrix();

    // -z face
    glColor3d(1., 1., 0.);
    glPushMatrix();
    glTranslated(0., 0., -1.);
    drawSquare();
    glPopMatrix();

}


// myDisplay
// The GLUT display function
void myDisplay()
{
    glClearColor(0.7f, 0.7f, 0.7f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Draw objects

    // Rotating cube
    glEnable(GL_DEPTH_TEST);
    glLoadIdentity();
    glTranslated(0., 0., -4.);

    // NOTE: The lines below are NOT an especially good way to do
    //  rotations. I suggest that you do not copy this idea. See
    //  manip2.cpp, our flight-simulator code, etc. for nicer methods.
    glRotated(hang, 0.,1.,0.);
    glRotated(vang, 1.,0.,0.);
    drawCubeWithAxes();

    // Draw documentation
    glDisable(GL_DEPTH_TEST);
    glLoadIdentity();
    glMatrixMode(GL_PROJECTION);  // Set up simple ortho projection
    glPushMatrix();
    glLoadIdentity();
    gluOrtho2D(0., double(winw), 0., double(winh));
    glColor3d(0., 0., 0.);        // Black text
    BitmapPrinter p(20., winh-20., 20.);
    p.print("Object manipulation the not-so-great way");
    p.print("Arrows   Rotate object");
    p.print("Esc      Quit");
    glPopMatrix();                // Restore prev projection
    glMatrixMode(GL_MODELVIEW);

    glutSwapBuffers();
}


// myIdle
// The GLUT idle function
void myIdle()
{
    // Print OpenGL errors, if there are any (for debugging)
    static int error_count = 0;
    if (GLenum err = glGetError())
    {
        ++error_count;
        cerr << "OpenGL ERROR " << error_count << ": "
             << gluErrorString(err) << endl;
    }
}


// myKeyboard
// The GLUT keyboard function
void myKeyboard(unsigned char key, int x, int y)
{
    switch (key)
    {
    case ESCKEY:  // Esc: quit
        exit(0);
        break;
    }
}


void mySpecial(int key, int x, int y)
{
    switch (key)
    {
    case GLUT_KEY_LEFT:
        hang += angstep;
        glutPostRedisplay();
        break;
    case GLUT_KEY_RIGHT:
        hang -= angstep;
        glutPostRedisplay();
        break;
    case GLUT_KEY_UP:
        vang += angstep;
        glutPostRedisplay();
        break;
    case GLUT_KEY_DOWN:
        vang -= angstep;
        glutPostRedisplay();
        break;
    }
}


// myReshape
// The GLUT reshape function
void myReshape(int w, int h)
{
    // Set viewport & save window dimensions in globals
    glViewport(0, 0, w, h);
    winw = w;
    winh = h;

    // Set up projection
    // Standard perspective projection
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(60., double(w)/h, 1.0, 10.);

    glMatrixMode(GL_MODELVIEW);  // Always go back to model/view mode
}


// init
// Initialize GL states & global data
// Called by main after window creation
void init()
{
    // Objects
    hang = 0.;
    vang = 0.;

    // OpenGL Stuff
    glLineWidth(2.0);
}


int main(int argc, char ** argv)
{
    // Initialize OpenGL/GLUT
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);

    // Make a window
    glutInitWindowSize(startwinsize, startwinsize);
    glutInitWindowPosition(50, 50);
    glutCreateWindow("CS 381 - Object Manipulation");

    // Initialize GL states & register GLUT callbacks
    init();
    glutDisplayFunc(myDisplay);
    glutIdleFunc(myIdle);
    glutKeyboardFunc(myKeyboard);
    glutSpecialFunc(mySpecial);
    glutReshapeFunc(myReshape);

    // Do something
    glutMainLoop();

    return 0;
}

