#include <stdlib.h>
#include <GL/glut.h>
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
GLfloat vertices[][3] = {{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0},
{1.0,1.0,-1.0}, {-1.0,1.0,-1.0}, {-1.0,-1.0,1.0},
{1.0,-1.0,1.0}, {1.0,1.0,1.0}, {-1.0,1.0,1.0}};
GLfloat colors[][3] = {{1.0,0.0,0.0},{1.0,0.0,0.0},
{1.0,0.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0},
{1.0,1.0,1.0}, {0.0,0.0,1.0}, {0.0,1.0,1.0}};
void polygon(int a, int b, int c , int d)
{
glBegin(GL_POLYGON);
glColor3fv(colors[a]);
glVertex3fv(vertices[a]);
glVertex3fv(vertices[b]);
glVertex3fv(vertices[c]);
glVertex3fv(vertices[d]);
glEnd();
}
void colorcube()
{
polygon(0,1,2,3);
polygon(2,3,7,6);
polygon(2,7,4,0);
polygon(4,5,1,0);
polygon(6,5,4,7);
polygon(5,1,2,6);
}
static GLfloat theta[] = {0,0,0};
static int xMove = 0,yMove = 0,zMove = 0;
static GLdouble viewer[]= {5.0, 5.0, 5.0};
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/* update viewer position in model-view matrix */
glLoadIdentity();
gluLookAt(viewer[0],viewer[1],viewer[2], 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
/* rotate cube */
glRotatef(theta[0], 1.0, 0.0, 0.0);
glRotatef(theta[1], 0.0, 1.0, 0.0);
glRotatef(theta[2], 0.0, 0.0, 1.0);
glTranslatef (xMove,yMove,zMove);
colorcube();
glFlush();
glutSwapBuffers();
}
void Translate()
{
cout<<"Enter the x position you want cube to move "<<endl;
cin>>xMove;
cout<<"Enter the x position you want cube to move "<<endl;
cin>>yMove;
cout<<"Enter the x position you want cube to move "<<endl;
cin>>zMove;
}
void mouse(int btn, int state, int x, int y)
{
if(btn==GLUT_LEFT_BUTTON && state == GLUT_DOWN)
theta[2] += 2.0;
if(btn==GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
theta[2] -= 2.0;
if(btn==GLUT_MIDDLE_BUTTON && state == GLUT_DOWN)
Translate();
if( theta[2] > 360.0 ) theta[0] -= 360.0;
if( theta[2] < 0) theta[0] += 360;
display();
}
void myReshape(int w, int h)
{
glViewport(0, 0, w, h);
/* use a perspective view */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(w<=h) glFrustum(-2.0, 2.0, -2.0 * (GLfloat) h/ (GLfloat) w,
2.0* (GLfloat) h / (GLfloat) w, 2.0, 20.0);
else glFrustum(-2.0, 2.0, -2.0 * (GLfloat) w/ (GLfloat) h,
2.0* (GLfloat) w / (GLfloat) h, 2.0, 20.0);
/* or we can use gluPerspective */
/* gluPerspective(45.0, w/h, 1.0, 10.0); */
glMatrixMode(GL_MODELVIEW);
}
void main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(500, 500);
glutCreateWindow("colorcube");
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
}