Linearization of logarithmic depth

How to linearize the logarithmic depth buffer?

visualization of the linear depth buffer in the fragment shader

float n = 1.0; // camera z near float f = 27000000.0; // camera z far float z = texture( DepthTex, TexCoord ).x; float d = (2.0 * n) / (f + n - z * (f - n)); FragColor=vec4(d,d,d,1); 

spherical vertex shader

 vec4 ClipCoords(vec3 position,mat4 matrix) { vec4 clip = matrix * vec4(position,1.0f); clip.z =((2.0f * log(1.0f * clip.z + 1.0f) / log(1.0f * 27000000.0f + 1.0f)) - 1.0f) * clip.w; return clip; } gl_Position = ClipCoords(position,matrix); 

The left side shows the linearization of the logarithmic depth of the buffer, or rather, its flaws, and the right side shows the linearization without log only gl_Position = matrix * vec4(position,1.0f); enter image description here

+3
source share
1 answer

With a logarithmic depth buffer, the mapping of the scene (camera) depth to values ​​that ultimately fall into the depth buffer (0..1) is:

 depth_value = log(C*z + 1) / log(C*Far + 1) 

where z is the positive depth in the scene, otherwise it is obtained from the w-component in the clip space after projection (in your code you can use ..log (clip.w + 1.0) ..).

To get the depth of the camera space in the fragment shader, the equation must be turned over:

 z = (exp(depth_value*log(C*far+1)) - 1)/C 

or equivalent

 z = (pow(C*far+1,depth_value)-1)/C 

To get a linear mapping from 0..far to 0..1, just divide it by a larger value.

+6
source

All Articles