Skip to content

Instantly share code, notes, and snippets.

@pezcode
Last active April 23, 2024 14:25
Show Gist options
  • Save pezcode/1609b61a1eedd207ec8c5acf6f94f53a to your computer and use it in GitHub Desktop.
Save pezcode/1609b61a1eedd207ec8c5acf6f94f53a to your computer and use it in GitHub Desktop.
Reversed Z + infinite far plane projection matrices with GLM
// these matrices are for left-handed coordinate systems, with depth mapped to [1;0]
// the derivation for other matrices is analogous
// to get a perspective matrix with reversed z, simply swap the near and far plane
glm::mat4 perspectiveFovReverseZLH_ZO(float fov, float width, float height, float zNear, float zFar) {
return glm::perspectiveFovLH_ZO(fov, width, height, zFar, zNear);
};
// now let zFar go towards infinity
glm::mat4 infinitePerspectiveFovReverseZLH_ZO(float fov, float width, float height, float zNear) {
const float h = glm::cot(0.5f * fov);
const float w = h * height / width;
glm::mat4 result = glm::zero<glm::mat4>();
result[0][0] = w;
result[1][1] = h;
result[2][2] = 0.0f;
result[2][3] = 1.0f;
result[3][2] = zNear;
return result;
};
// unproject depth, assuming the matrix produced by infinitePerspectiveFovReverseZLH_ZO
// from screen space depth in [1;0] (gl_FragCoord.z or depth buffer value)
float screen_to_eye_depth(float z, float near)
{
return near / z;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment