Search code examples
opengldepth

Proper depthmap values from framebuffer


I currently get the depthmap from a framebuffer, however the values get stuck at 0.0 or 1.0 or higher. How can I get the depth between 0.0 and 1.0?

Also, I access the depthmap as sampler2D in a fragment shader.

    modelsDepthTextureId = glGenTextures();
    glBindTexture(GL_TEXTURE_2D, modelsDepthTextureId);
    glTexImage2D( GL_TEXTURE_2D, 0, GL14.GL_DEPTH_COMPONENT24, screenWidth, screenHeight, 0,
        GL_DEPTH_COMPONENT, GL_INT, (java.nio.ByteBuffer) null);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

Solution

  • float linearize(float depth) {
        float zNear = 0.1;
        float zFar = 100.0;
    
        return (2.0 * zNear) / (zFar + zNear - depth * (zFar - zNear));
    }
    

    The depth is saved exponetionally in the depthtexture. To linearize the code above is needed with the appropriate near and far values.