Could you explain to me what is the purpose of -1 in the last row of the gl_projection matrix? And how it affects the perspective division step ?
1 Answer
It's purpose is simple, the -1 gets multiplied with the z-value of any vertex you multiply the perspective matrix with.
So w = -z
Then during the perspective division each component (x, y, z, w) get's divided by w, (x/w, y/w, z/w, w/w). So the bigger the z-value is, the bigger the values x,y,z are divided by and the closer to zero the values become. Zero being the center of the screen thus making the objects appear smaller and closer to the center.
The reason it's -1 and not 1 is because the typical convention in OpenGL is to use a right-handed coordinate system. This means that z's negative direction is inward into the screen. However OpenGL defines normalized device coordinates (NDC) to have z be positive into the screen, so we need to flip the z axis before rendering and having it be -1 is one of the side-effects. If you look at a perspective-projection matrix for DirectX it should say 1 instead as it by convention uses left-handed coordinate system.
I recommend this resource if you want to learn more: http://www.songho.ca/opengl/gl_projectionmatrix.html