vard
vard

Reputation: 2302

openGL transformation and gluLookAt()

I have a studying project which represents simple 3D scene. I want to draw sphere in some non-origin point. Later I'm going implement this as separate function or method.

I'm setting point of view using gluLookAt() then I'm transforming model-view matrix using glTranslatef() with little offset and drawing sphere. Unfortunately, the sphere isn't shown. Am I right with model-view matrix approaching?

void display(void){    
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();
    gluLookAt(1, 0 ,1, 0, 0, 0, 0, 1, 0);    
    glColor3b(197, 96, 63);    
    glPushMatrix(); 
    glLoadIdentity();
    glTranslatef(0.1, 0, 0);
    glutWireSphere(0.2, 20, 10);
    glPopMatrix();     
    glFlush();
}

void reshape(int w, int h){
    glViewport(0, 0, (GLsizei) w, (GLsizei) h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho ((float)w/(float)h, (float)-w/(float)h, -1, 1, 0.8, 100);
    glMatrixMode(GL_MODELVIEW);
}

Upvotes: 1

Views: 980

Answers (2)

Christian Rau
Christian Rau

Reputation: 45968

Your approach doesn't look that unreasonable. The problem is here:

glPushMatrix(); 
glLoadIdentity();
glTranslatef(0.1, 0, 0);

The pushing (and later popping) is a good idea, but by setting the matrix to identity before the translation, you loose any transformations done before, in particular the viewing transformations established with gluLookAt. So just remove this glLoadIdentity to properly concatenate the individual transformations.

Always keep in mind that all the matrix transformation functions, like glTranslate, glOrtho, or gluLookat always modify the currently selected (with glMatrixMode) matrix and don't just replace it. This is also the reason why you do a glLoadIdentity before the calls to glOrtho and gluLookAt.

Upvotes: 1

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39400

No, you aren't.

gluLookAt(1, 0 ,1, 0, 0, 0, 0, 1, 0); 
glColor3b(197, 96, 63);    
glPushMatrix(); 
glLoadIdentity(); // why it should be there?

By zeroing the view matrix there, you are drawing your object relatively to the origin coordinates, not taking your glLookAt into account. The call to it is effectively ignored. It should be coded as:

  1. Set up the "camera matrix"
  2. Push the matrix on the stack
  3. Translate to the object's position
  4. Draw the object
  5. Pop and go back to 2.

So if you want to set up hypothetical "camera", you have to combine positions of objects with the camera matrix itself.

Upvotes: 3

Related Questions