How to access Z value before Z-buffering

Hi, there,

I need to access the z values of the fragments before the z-buffering test, Not after the test which leave only the nearest point’s Z value in the z-buffer.

Is there any way to do this? Your help will be greatly appreciated.


The z value can be calculated (by you) from one of your triangles simply. You cannot read a Z value from the Z buffer before the Z buffer test. That would be like reading a book before it has been written

If you need some Z value before rendering an object, you should be using simple geometry to do this before you hit OpenGL with your scene.

Hope this helps.

rca, you must read the zbuffer after the primitive you are interested in get’s drawn.

You can also z test without writing Z, that might help in some situations by leaving an earlier z result in the framebuffer but still allowing some rendering.

[This message has been edited by dorbie (edited 06-12-2002).]

Hi, Thanks for the help, I really appreciate it.

Robbo, All I need is to take advantage of opengl hardware process, I can do the calculation by myself. but it is not the point.

In the opengl programming guide it says when opengl does z-buffering, it compares the incoming fragment’s z value with the one in z-buffer, so I think it should be already calculated by opengl and stored in the fragment. what I need is to access it before z-buffering.

Hi, dorbie, your way does work but the problem is if I want to get all the z value of every polygons, I need to render them respectively, and that will take a lot of time.

still thanks for your help.

If you’re interested in the z values, but not the final image, you could check out the gluProject() function. That will calculate your screen-z based on the projection and modelview matrices you supply.
However, that will not use any hardware acceleration afaik, since the gluProject is implemented in software.

Another way could be to disable depth testing, but enable depth writing and reading back the z values after each primitive. However, you would have to determine which pixel to readback…
If you only need one depth value per primitive, perhaps setting up a viewport of 1 pixel will help you --> anything drawn will always result in the same pixel in the frame buffer being updated.

I have no idea which method will be quicker.



Hi, JML, many thanks for the ideas.

What I want to do is to take advantage of opengl functionality so that I dont need to do all the calculation by myself. I just want to make sure that if there is a direct way to get access to z values and seems there is not.

Anyway, thanks to all you guys.


you can use glReadPixels(…,GL_DEPTH_COMPONENT,…); to get the z value of a pixel, look into the redbook for further details