opengl glulookat strange behavior

Tag: opengl , glulookat Author: skyboy10000 Date: 2013-09-24

can someone please explain me why is the camera in my code moving on every onIdle callback? I am not changing any parameters so it seems to me that it should display the same all the time. Still cannot figure it out by myself, thanks for help

#include <iostream>
#include <math.h>
#include "gl/glut.h"
#include <windows.h>

using namespace std;

void Display(void){

    glMatrixMode(GL_PROJECTION);
    glFrustum(-0.5, 0.5, -0.5, 0.5, 0.8, 2);

    gluLookAt (0,0,1,  0,0,0,  0,1,1);

    glMatrixMode(GL_MODELVIEW);
    glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);

    glutWireCube(0.2);

    glFlush();

}


void onIdle(void){

    Sleep(1000);
    glutPostRedisplay();

}

int main(void){

glutInitDisplayMode(GLUT_DEPTH | GLUT_RGBA);
glEnable(GL_DEPTH_TEST);
glutCreateWindow("camera");

glutDisplayFunc(Display);
glutIdleFunc(onIdle);
glutMainLoop();
return 0;
}

Other Answer1

That is because you don't reset the matrices, after each render or at the beginning of each render.

Basically, you need to call glLoadIdentity(); that will reset the current selected matrix, but setting the matrix's values to the default values (Matrix Identity).

comments:

Well, there's that and then there's also the fact that he's combining projection and modelview into one ugly matrix. And then there's the fact that the up vector is zero. This whole code is a mess :)
Alternatively (and perhaps faster) than calling glLoadIdentity() each frame is doing a glPushMatrix() before your viewing transform call (e.g. gluLookAt()), and then calling glPopMatrix() after all of your rendering is complete (i.e., say, right before calling glFlush() in your case).
@AndonM.Coleman Err, the second "set" of parameters to gluLookAt is the point you're looking at, and in the OP's case is the origin, and not the up vector, if that's what you were saying. The last three parameters are the up vector, which unless I'm looking at an edited version of the post, isn't a zero vector.
@radical7: Yeah, you're right. I am used to a different API, which has the forward and up vectors reversed in its LookAt. The good news is GLU is not part of OpenGL, so I do not care that I cannot remember the proper order for that particular API function =P. I still stand by my assertion that moving gluLookAt (...) to come after the switch to GL_MODELVIEW will fix a lot of issues in the fixed-function pipeline, however.
@radical7 An even faster and much better alternative would be to use and calculate all the Matrices yourself.