Getting depth texture values in shader


I am rendering into an FBO with a depth-texture attached to it (and with other color attachments). I can easily access all texture values in the fragment shader if they are color attachments but not the values from the depth texture. They are always black (default) or grey (if I clamp them from [-1,1] to [0,1] to ensure values were not negative).

I’ve searched in many places and the most interresting thing I’ve found was this:

As I understood, I can’t use texture2D in the fragment shader with a depth texture if I don’t deactivate texture comparison, which I did, but without more success.

Here is what I do:

uniform sampler2D sampler;

varying vec2 tex_coord;

void main()
   float depth = texture2D (sampler, tex_coord).r;
   //depth = (depth + 1.) * .5;
   gl_FragColor = vec4 (depth,depth,depth,1.);

Any hints to resolve this ?

Depth values are not linear, directly outputing them will result in mostly monochrome images.


I’m sure there’s better sources though, so just search for linearizing depth values if you prefer.

Yes, but I should at least see some shades in the image (I can see the depth map of the shadow texture - but without shader, for example). EDIT: and if that was the linearisation problem, the image should be white, not black.

The depth value is absolutely equal to 0, I ensured it.

It is very strange since when I don’t use the depth texture, when I render other color attachments I could effectively see that depth testing is not working (far objects are rendered first and overdraw near objects). So the depth test is working well when I use this attachment, and so the depth texture should be correctly filled… Or am I wrong somewhere ?

That would completely depend on what you are rendering because…

They are always black (default)…

… the default glClear value for a depth surface is not 0, but 1. Unless you changed it, but then it’s no longer the default.

Most values due to how projection works will be squashed very near 0.

If all your values are 0, then you haven’t attached the texture to your FBO correctly. If you had, you’d see 1.0 after glClear and wherever your objects didn’t touch the buffer.

Attach the texture and read from it with glGetTexImage to make sure, or linearize the values and magnify them to ensure it’s not simply clamping very close to 0.

If you still think your FBO is correct, then there’s a problem with how you are attaching the texture to feed the shader. A lot of possibilities there.

Indeed, you was right. Linearizing the depth values resolved the problem. I made a mistake when I check that values where all equal to 0 (there were not).

Between, I changed the default color values to (0,0,0,0).