Original Post
Hello! I'm trying to render a primitive in grayscale where black is closest to the viewer and white is far away, like when you render the depth buffer to a texture. So I wrote this fragment shader:
void main()
{
float depth = gl_FragDepth;
gl_FragColor = vec4(depth, depth, depth, 1.0);
}
But the primitive has the same color everywhere, and it doesn't change with distance. Now when I render the depth buffer of this to a texture all I get is black! So, is gl_FragDepth only for writing? Should I instead get the depth by ftransform'ing the vertices of the primitive and getting the z-component, then subtracting fNear and dividing by (fFar - fNear)? Can I get fFar and fNear from the projection matrix in the shader or do I have to pass them as attributes? Like this?
Vertex shader:
varying float depth;
attribute float fNear, fFar;
void main() {
gl_Position = ftransform();
depth = (gl_Position.z - fNear) / (fFar - fNear);
}
Fragment shader:
varying float depth;
void main() {
gl_FragColor = vec4(depth, depth, depth, 1.0);
}