Question

The article here says:

Dividing x, y, and z by w accomplishes this. The resulting coordinates are called normalized device coordinates. Now all the visible geometric data lies in a cube with positions between <-1, -1, -1> and <1, 1, 1> in OpenGL, and between <-1, -1, 0> and <1, 1, 1> in Direct3D.

This raises a problem for cross-platform shaders which want to test the Z coordinate for some specific reason. Is there a way to get a Z coord in the same range, regardless of platform?

Was it helpful?

Solution

Where are you doing this testing of Z that you want to do?

If you're doing it in the fragment shader, then you shouldn't care. gl_FragCoord.z or whatever Cg's equivalent to this is in window-space. The window-space Z extent is defined by glDepthRange; by default, it goes from 0 to 1.

If you're doing this test in the vertex shader, then you'll just have to live with it. A better test might be one done in camera space, rather than clip-space or NDC space. At least then, you're usually dealing with world-sized distances.

OTHER TIPS

Interresting question, but I doubt that it's achievable, since the viewport transformation is still fixed-function.

The first thing that comes to mind is to use glDepthRange (or its possible D3D counterpart) to change the mapping from NDC z to depth. But this won't work, since passing [-1,1] to glDepthRange will just clamp it to [0,1] and neither can you set it in D3D to [0.5,1], since before that everything will still be clipped against [0,1].

But I don't think you need it too often, since in the fragment/pixel shader you get window coordinates with a normalized [0,1] depth (I expect Cg to behave similar to GLSL here). And in the vertex shader you would more often need the world or view space depth anyway, instead of the NDC z. If you really need it you may just base the decision on a preprocessor definition in the shader.

Using the nonlinear z/w value of NDC space is normally avoided. One normally does this by passing the absolute vertex Z distance by an additional varying. That way things stay portable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top