Depth testing doesn't work when using custom framebuffer

1.2k Views Asked by At

I'm stydying framebuffers and I've made a mirror in my scene. It works fine except the depth testing. Got stuck trying to make it work. (when rendering to default frame buffer - depth testing works fine). Would appreciate any help. Here is the code:

glEnable( GL_DEPTH_TEST );

glViewport( 0, 0, 512, 512 );

unsigned int fbo;
glGenFramebuffers( 1, &fbo );
glBindFramebuffer( GL_FRAMEBUFFER, fbo );

unsigned int rbo;
glGenRenderbuffers( 1, &rbo );
glBindRenderbuffer( GL_RENDERBUFFER, rbo );
glRenderbufferStorage( GL_RENDERBUFFER, GL_DEPTH, 512, 512 );
glBindRenderbuffer( GL_RENDERBUFFER, 0 );

glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, 
GL_RENDERBUFFER, rbo ); //if remove this, mirror works but without depth test
glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 
this->mirror->texturePack[0]->textureId(), 0 ); 

//render scene from mirror camera

glBindFramebuffer( GL_FRAMEBUFFER, 0 );
glViewport( 0, 0, this->width(), this->height() );

//render scene from main camera
2

There are 2 best solutions below

0
3dmodels On BEST ANSWER

I've solved it finally. I've added the glClear( GL_DEPTH_BUFFER_BIT ) command right after binding mirror framebuffer and after that it worked.

1
Rabbid76 On

Your farme buffer is inclomplete, because GL_DEPTH is no valid internal format for a render buffer storage. See glRenderbufferStorage. Try GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT24 or GL_DEPTH_COMPONENT32:

glRenderbufferStorage( GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, 512, 512 );

See OpenGL 4.6 core profile specification, 9.4 Framebuffer Completeness, page 323:

The internal formats of the attached images can affect the completeness of the framebuffer, so it is useful to first define the relationship between the internal format of an image and the attachment points to which it can be attached.

• An internal format is depth-renderable if it is DEPTH_COMPONENT or one of the formats from table 8.13 whose base internal format is DEPTH_- COMPONENT or DEPTH_STENCIL. No other formats are depth-renderable.


Note, the framebuffer completeness can be checked by:

glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE