0

This function was working when i was using glut that i downloaded from the opengl nvidia examples

void gl_select(int x, int y)
{
    GLint viewport[4];
    GLdouble modelview[16];
    GLdouble projection[16];
    GLfloat winX, winY, winZ;
    GLdouble posX, posY, posZ;

    glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
    glGetDoublev(GL_PROJECTION_MATRIX, projection);
    glGetIntegerv(GL_VIEWPORT, viewport);

    winX = (float)x;
    winY = (float)viewport[3] - (float)y;
    glReadPixels(x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);

    gluUnProject(winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);


    printf("%f %f %f\n", posX, posZ, posY);

    glutPostRedisplay();
}

but then i switched to free glut and now it's not working, can someone tell me why?

datenwolf
  • 159,371
  • 13
  • 185
  • 298
Dean
  • 499
  • 6
  • 13
  • 34

1 Answers1

0

Okay, I think I can guess your problem: You're probably calling gl_select from an input event handler. Now here's the thing: When you read pixels from the main framebuffer, you may actually never get any sensible value. Why? Because the operating system may decide "uh, that part is not visible anyway, so why bother processing it" (this is called the pixel ownership test). Furthermore the contents of the main framebuffer can become lost anytime (damage event).

Well, and then glReadPixels reads from the framebuffer selected for reading. If that is the back buffer and you access it after a buffer swap, the contents are undefined as well (for colours). The depth component of the framebuffer also get corrupted by a swap.

So, if glReadPixels is so unreliable, you may think, how to use it? Well it's not glReadPixels that unreliable, it's just the window framebuffer that's volatile. So you should not use that. Instead, if you want to do pixel space depth selection, you should render first to an FBO, and then copy that to the main window framebuffer. The contents of FBOs are asserted to not get lost. So you can read from an FBO at any time, being sure you get what you asked for.

Furthermore you should not rely on what's in the matrix stack when you call gl_select. Instead you should make snapshot copies of the projection and the modelview matrix in the display code, in the state that represents the transformations as which they apply for the selection.

datenwolf
  • 159,371
  • 13
  • 185
  • 298