Skip to content

Instantly share code, notes, and snippets.

@Popov72
Created October 23, 2019 22:32
Show Gist options
  • Save Popov72/7e856b2589f659b2e9ff7ca0a7a6f815 to your computer and use it in GitHub Desktop.
Save Popov72/7e856b2589f659b2e9ff7ca0a7a6f815 to your computer and use it in GitHub Desktop.
Linearize / Delinearize z depth values in fragment shaders
uniform float zNear = 0.1;
uniform float zFar = 500.0;
// depthSample from depthTexture.r, for instance
float linearDepth(float depthSample)
{
depthSample = 2.0 * depthSample - 1.0;
float zLinear = 2.0 * zNear * zFar / (zFar + zNear - depthSample * (zFar - zNear));
return zLinear;
}
// result suitable for assigning to gl_FragDepth
float depthSample(float linearDepth)
{
float nonLinearDepth = (zFar + zNear - 2.0 * zNear * zFar / linearDepth) / (zFar - zNear);
nonLinearDepth = (nonLinearDepth + 1.0) / 2.0;
return nonLinearDepth;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment