In OpenGL ES 2.0 depth texture buffer is not working when using FBO with texture depth buffer

1.3k views Asked by At

Currently I'm working on a project for rendering applications to Framebuffer Object(FBO) first, and rendering back the applications by using the FBO color and depth texture attachments in OpenGL ES 2.0 .

Now multiple applications are rendered well with color buffers. When I'm trying to use depth information from depth texture buffer, it seems not working.

I tried to render depth texture by sampling it with texture coordinate, it is all white. People say the grayscale may differ quite slightly, namely even in the shadow part it's near to 1.0. So I modify my fragment shader to like following:

    vec4 depth;
    depth = texture2D(s_depth0, v_texCoord);

    if(depth.r == 1.0)
        gl_FragColor = vec4(1.0,0.0,0.0,1.0);

And without surprise, it's all red.

The application code:

void Draw ( ESContext *esContext )
{
UserData *userData = esContext->userData;

// Clear the color buffer
glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Draw a triangle
GLfloat vVertices[] = {  0.0f,  0.5f, 0.5f, 
                       -0.5f, -0.5f,-0.5f,
                        0.5f, -0.5f,-0.5f };

// Set the viewport
glViewport ( 0, 0, esContext->width, esContext->height );

// Use the program object
glUseProgram ( userData->programObject );

// Load the vertex position
glVertexAttribPointer ( 0, 3, GL_FLOAT, GL_FALSE, 0, vVertices );

glEnableVertexAttribArray ( 0 );

glDrawArrays ( GL_TRIANGLES, 0, 3 ); 

eglSwapBuffers ( esContext->eglDisplay, esContext->eglSurface );
}

So, what would be the problem, if color buffer works fine, while depth buffer doesn't work?

2

There are 2 answers

0
Han On BEST ANSWER

I solved it finally. That reason ends up to be a lack of GL_DEPTH_TEST enabling from client applications.

So if you got the same problem, be sure to enable GL_DEPTH_TEST by calling glEnable(GL_DEPTH_TEST); during OpenGL ES initialization. By default it's disabled for the sake of performance I guess.

Thanks for all advices and answers.

6
bvs On

The depth texture needs to be linearized to be seen in the viewport because it's saved in exponential form. Try this in fragment:

uniform float farClip, nearClip;

float depth = texture2D(s_depth0, v_texCoord).x;
float depthLinear = (2 * nearClip) / (farClip + nearClip - depth * (farClip - nearClip));