Dividing gl_Position by gl_Position.w

Hi,

since I need the actual gl_Position values several times, I decided to divide by w after the transform at the end of my vertex shader like this gl_Position /= gl_Position.w;. For vertices with positive z-value this works perfectly, but vertices with negative z-values get complety wrong positions, so that I do if (0.0 < gl_Position.z) gl_Position /= gl_Position.w; now and this works fine. I’m just wondering why do I have to do this? Why is it not working for z-values below 0? Has somebody an idea?

Thanks and Regards

Perspective projection maps a 3D point to a 2D point by calculating where a line through the 3D point and the viewpoint intersects a 2D plane. Think about what happens when the point is behind the viewpoint (hint: a line is not a line segment; it extends to infinity in both directions).

This is why clipping is performed, why it is performed in clip space, prior to division by W, and a large part of the reason why you have a near plane, and why the near distance must be positive for a perspective projection.

IOW, you can’t perform the conversion from clip space to NDC yourself.

Aside from the issues with clipping, it will result in the interpolation of attributes such as texture coordinates being performed in screen space rather than world space (i.e. the interpolation won’t be perspective-correct). Dividing by W then interpolating gives a different result to interpolating then dividing by W.

Before perspective division, there is a clipping stage, hence you cannot produce correct values of NDC space by yourself. I had tried it and it does not work. What is your use case?