Sunday, 19 April 2015

OpenGL program to draw a 3D cube







#include<GL/glut.h>
GLfloat xRotated,yRotated,zRotated;
GLfloat l,r,b,t;

void idle(){

  glutPostRedisplay();
}
void display(){
glMatrixMode(GL_MODELVIEW);
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0,0,-200);
glRotatef(xRotated,1,0,0);
glRotatef(yRotated,0,1,0);
glRotatef(zRotated,0,0,1);
glBegin(GL_QUADS);
glColor3f(0,1,0);
glVertex3f(200,200,-200);
glVertex3f(-200,200,-200);
glVertex3f(-200,200,200);
glVertex3f(200,200,200);
glColor3f(0,0,1);
glVertex3f(200,-200,200);
glVertex3f(-200,-200,200);
glVertex3f(-200,-200,-200);
glVertex3f(200,-200,-200);
glColor3f(1,0,0);
glVertex3f(200,200,200);
glVertex3f(-200,200,200);
glVertex3f(-200,-200,200);
glVertex3f(200,-200,200);
glColor3f(1,1,0);
glVertex3f(200,-200,-200);
glVertex3f(-200,-200,-200);
glVertex3f(-200,200,-200);
glVertex3f(200,200,-200);
glColor3f(0,1,01);
glVertex3f(-200,200,200);
glVertex3f(-200,200,-200);
glVertex3f(-200,-200,-200);
glVertex3f(-200,-200,200);
glColor3f(1,0,1);
glVertex3f(200,200,-200);
glVertex3f(200,200,200);
glVertex3f(200,-200,200);
glVertex3f(200,-200,-200);
glEnd();
glFlush();
glutSwapBuffers(); 
xRotated+=0.01;
yRotated+=0.02;

}

void myinit(){
glClearColor(1,1,1,1);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glOrtho(-500,500,-500,500,-500,500);
}


void reshape(int width, int height) {
   if (height == 0) height = 1;           
   GLfloat aspect = (GLfloat)width / (GLfloat)height;


   glViewport(0, 0, width, height);


   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   if (width <= height) {
         glOrtho(-500.0,500.0,-500.0*(GLfloat)height/(GLfloat)width,500.0*(GLfloat)height/(GLfloat)width,-500,500);

   } else {

 glOrtho(-500.0*(GLfloat)width/(GLfloat)height,500.0*(GLfloat)width/(GLfloat)height,-500.0,500.0,-500,500);
   }
}

void main(int argc,char** argv){
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutCreateWindow("3d");
glutInitWindowSize(500,500);
glutInitWindowPosition(100,100);
glutDisplayFunc(display);
glutIdleFunc(idle);
glutReshapeFunc(reshape);
myinit();
glutMainLoop();


}

No comments:

Post a Comment

Total Pageviews