# How can I draw the depth value in GLSL?

I want to draw the depth buffer in the fragment shader, I do this:

varying vec4 position_;

gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
position_ = gl_ModelViewProjectionMatrix * gl_Vertex;


float depth = ((position_.z / position_.w) + 1.0) * 0.5;

gl_FragColor = vec4(depth, depth, depth, 1.0);


But all I print is white, what am I doing wrong?

• Do you want to draw depth buffer of rendered scene or draw scene objects with coloring based on pixel depth? – kravemir Jul 3 '12 at 9:01

position_.z shouldn't be larger than 1 or lower than 0. You should try to use linear depth for the display, which after applying the projection matrix is (usually) stored in the w coordinate instead. Take that, divide by an appropriate number (depending on the scale of your game) to bring the numbers between 0 and 1 for your interesting depth and watch.

gl_fragcoord is not relevant to this discussion; gl_fragdepth is an output variable to modify the post-projection depth in the pixel shader. You're not trying to do that, so don't use that either.

A cheesy way might be to set up some linear fog. Make the fog colour black, draw all your geometry white, and voila.

• Nice idea for a fixed-function pipeline, never thought about that. – Chris says Reinstate Monica Aug 22 '11 at 12:15

Maybe you can try one of these two variables. gl_fragcoord or gl_fragdepth

I didn't read those manuals, but I think, it could be helpful.