Search code examples
copengl3dglut

Setting dimensions of 3D space in OpenGL


#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <freeglut.h>
#include <FreeImage.h>

void display(void) {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    GLint viewport[4];
    glGetIntegerv(GL_VIEWPORT, viewport);
    double aspect = (double)viewport[2] / (double)viewport[3];
    gluPerspective(60, aspect, 1, 100);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(0,0,-35);
    static float angle = 0;
    angle += 4.0f;
    //magenta middle cube
    glPushMatrix();
    glTranslatef(0, 0, 0);
    glRotatef(angle, 0.1, 0.2, 0.5);
    glColor3ub(224,8,133);
    glutSolidCube(5);
    glPopMatrix();
    //yellow right cube
    glPushMatrix();
    glTranslatef(10, 5, 0);
    glRotatef(angle, 0.2, 0.3, 0.1);
    glColor3ub(250, 224, 20);
    glutSolidCube(5);
    glPopMatrix();
    //cyan left cube
    glPushMatrix();
    glTranslatef(-10, -5, 0);
    glRotatef(angle, 0.3, 0.2, 0.6);
    glColor3ub(0, 162, 211);
    glutSolidCube(5);
    glPopMatrix();
    glFlush();
    glutSwapBuffers();
}

void repeat(int val) {
    glutPostRedisplay();
    glutTimerFunc(10, repeat, 0);
}

int main(int argc, char** argv)
{
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
    glutInitWindowSize(500,500);
    glutCreateWindow("SIMPLE DISPLAY");
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_COLOR_MATERIAL);
    glShadeModel(GL_SMOOTH);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-500,500,-500,500,-500,500);
    glutDisplayFunc(display);
    glutTimerFunc(0, repeat, 0);
    glutMainLoop();
    return 0;
}

I have code that draws three cubes in 3-space and rotates them. I noticed the working area is very small despite using glOrtho(-500,500,-500,500,-500,500). Translating the cubes in three directions makes it seems like the working area is only 50x50x50 (not sure on the z-dimensions, as it'll go 50 back before it disappears but can't confirm distance in front). Translating a cube 25 to the left or right makes it go out of the window bounds.

I thought glOrtho() set the working area size, in this case 1000x1000x1000?


Solution

  • You are overriding the glOrtho call at the begin of the display function by the gluPerspective call. You can only have one projection applied, either perspective or orthographic.

    glOrtho does not define the size of the screen but a orthographic projection matrix (which can somehow be seen as the size of the working area as long as the camera is not moved).