How to draw a cube using GLUT

Back to OpenGL Tutorial Index

After reading this opengl tutorial you should have a fair idea on how to create predefined opengl shapes, specifically cubes using glut. Glut has many different preset 3d shapes for use in opengl which I will list below. You will be able to create both solid and wire opengl cubes with a single line of code.

In glut we are given a group of different 3D shapes to play with
one of them is the cube, it can be drawn with the line:
glutWireCube(2);
or:
glutSolidCube(2);

The 2 is the length of the sides, as it is a cube, all sides are the same.
some other 3D shapes to play with are the:

(for these 3, the more slices and stacks, the smoother the surface.)
glutSolidCone (base length, height, slices, stacks);
glutSolidSphere (radius, slices, stacks);
glutSolidTorus (inner radius, outter radius, slices, stacks);

alternatively there is also the Wire version which is done by replacing
the word Solid with Wire.

There is also a little teapot when playing with different effects, so that
you can see how it would change a more 'modelled' shape which can be called with

glutSolidTeapot(size);

If you have any questions, just email swiftless@gmail.com :-)

#include <GL/gl.h>
#include <GL/glut.h>

void cube (void) {
glColor3f(1.0, 0.0, 0.0); //color the cube red
glutWireCube(2); //draw a wired cube with side lengths of 2
}

void display (void) {
glClearColor (0.0,0.0,0.0,1.0);
glClear (GL_COLOR_BUFFER_BIT);
glLoadIdentity();
gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
cube();
glFlush();
}

void reshape (int w, int h) {
glViewport (0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective (60, (GLfloat)w / (GLfloat)h, 1.0, 100.0);
glMatrixMode (GL_MODELVIEW);
}

int main (int argc, char **argv) {
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow ("A basic OpenGL Window");
glutDisplayFunc (display);
glutReshapeFunc (reshape);
glutMainLoop ();
return 0;
}

Download C++ Source Code for this Tutorial

Download Visual Basic Source Code for this Tutorial

 

     

 

Copyright 2008, Donald Urquhart
Proudly supported by http://www.cdadc.com