The Chapter 3 of The Red Book clarifies the relationship among modeling, viewing, projection, viewport transformations that often confuse the OpenGL beginners. Please be patient in going through following steps one by one:
INC=-I/usr/local/include -I/usr/X11R6/include -I/usr/include/Xft2 -O2 LIB=-L/usr/local/lib -L/usr/X11R6/lib -L$(QTDIR)/lib LIBS=-lGL -lX11 -lGLU -lXmu -lm -lXext -lglut -lXi .c: g++ $@.c $(LIB) $(INC) -v -o $@ $(LIBS)
#include <GL/glut.h>
#include <stdlib.h>
void init(void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_FLAT);
}
void display(void)
{
glClear (GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 1.0, 1.0);
glLoadIdentity (); /* clear the matrix */
/* viewing transformation */
gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glScalef (1.0, 2.0, 1.0); /* modeling transformation */
glutWireCube (1.0);
glFlush ();
}
void reshape (int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h); /* viewport transformation */
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glFrustum (-1.0, 1.0, -1.0, 1.0, 1.5, 50.0); /* projection transformation */
glMatrixMode (GL_MODELVIEW);
}
void keyboard(unsigned char key, int x, int y)
{
switch (key) {
case 27:
exit(0);
break;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow (argv[0]);
init ();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}
Following sequence maps a square image onto a square viewport: gluPerspective(myFovy, 1.0, myNear, myFar); glViewport(0, 0, 400, 400); However, the following sequence projects a nonequilateral rectangular image onto a square viewport. The image appears compressed along the x-axis. gluPerspective(myFovy, 2.0, myNear, myFar); glViewport (0, 0, 400, 400); To avoid the distortion, this line could be used: glViewport(0, 0, 400, 200);