glReadPixels and GL_DEPTH_COMPONENT

float comp;

glBegin(GL_QUADS);
glColor4d(0.1, 0.2, 0.3, 0.4);
glVertex3d(0, 0, 0.5);
glVertex3d(0, 10, 0.5);
glVertex3d(10, 10, 0.5);
glVertex3d(10, 0, 0.5);
glEnd();

glReadPixels(9, 9, 1, 1, GL_RED, GL_FLOAT, &comp);

It works for GL_RED, GL_GREEN, GL_BLUE, but as for GL_ALPHA, GL_DEPTH_COMPONENT, comp is either 1.0 or 0.0?

Alpha could be that you haven’t asked for a destination alpha channel (you may not get one unless you ask for one), and depth component could be a bad projection matrix setup. Without more information, we can’t say anything.

What a fast reply, only half an hour past!

float component;

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glBegin(GL_QUADS);
glColor3d(0.1, 0.2, 0.3);
glVertex3d(0, 0, 0.5);
glVertex3d(0, 10, 0.5);
glVertex3d(10, 10, 0.5);
glVertex3d(10, 0, 0.5);
glEnd();

glReadPixels(9, 9, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &component); //Read 1 pixel’s component

assert(glGetError() == GL_NO_ERROR);

with GL_DEPTH_COMPONENT and GL_ALPHA I got
1.0, but with GL_RED, GL_GREEN, GL_BLUE I got
0.1, 0.2, 0.3

and some more codes on initializing…

glViewport(0, 0, 640, 480);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 640, 0, 480, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

That’s all my program, I just want to test the glReadPixel function.

Projection matrix is OK. But I still don’t know how you setup your pixel format.

My next guess on the depth component is that you don’t enable depth test. No depth test means no depth writes either, so you’re left with whatever the depth clear value is set to, which is 1.0 by default.

glEnable(GL_DEPTH_TEST) solves the problem but what do you mean by “Alpha could be that you haven’t asked for a destination alpha channel (you may not get one unless you ask for one)”?

When you setup the pixel format, you tell the OS what you want. For example, 8 bits of red green and blue, and 24 bits Z. If you don’t say you also want 8 bits alpha, you don’t get any bits at all. So if you want an alpha channel, you must tell the OS you want one. And you need an alpha channel to be able to draw and then read back alpha values. This is the destination alpha channel. Don’t confuse this with the source alpha, the alpha you set in glColor for example. Even though you don’t have a destination alpha channel, you can still perform (some types of) alpha blending since it’s only uses the source alpha channel.

For example, with GLUT, you add GLUT_ALPHA to glutInitDisplayMode, just like you ask for a depth buffer with GLUT_DEPTH, and a stencil buffer with GLUT_STENCIL.

If you instead use the PIXELFORMATDESCRIPTOR under Win32, you specify the amount of alpha bits in cAlphaBits field. Again, just like you put the number of depth bits cDepthBits, and same for cStencilBits, and so on.

Thanks.