OpenGL, how to use depthbuffer from framebuffer as usual depth buffer

ShPavel picture ShPavel · Mar 28, 2012 · Viewed 8k times · Source

I have frame buffer, with depth component and 4 color attachments with 4 textures

I draw some stuff into it and unbind the buffer after, using 4 textures for fragment shader (deferred lighting). Later i want to draw some more stuff on the screen, using the depth buffer from my framebuffer, is it possible?

I tried binding the framebuffer again and specifying glDrawBuffer(GL_FRONT), but it does not work.

Answer

Christian Rau picture Christian Rau · Mar 28, 2012

Like Nicol already said, you cannot use an FBOs depth buffer as the default framebuffer's depth buffer directly.

But you can copy the FBO's depth buffer over to the default framebuffer using the EXT_framebuffer_blit extension (which should be core since GL 3):

glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, 
                  GL_DEPTH_BUFFER_BIT, GL_NEAREST);

If this extension is not supported (which I doubt when you already have FBOs), you can use a depth texture for the FBO's depth attachment and render this to the default framebuffer using a textured quad and a simple pass through fragment shader that writes into gl_FragDepth. Though this might be slower than just blitting it over.