How to use depth texture with stencil, OpenGL ES 3

2019-09-14 17:13发布

问题:

I have an application where I want to render depth to a texture using stencil mask. I try GL_DEPTH_STENCIL_OES:

Creating texture:

glGenFramebuffers(1, fbo);
glBindFramebuffer(GL_FRAMEBUFFER, *fbo);

glGenTextures(1, depthTexture);
glBindTexture(GL_TEXTURE_2D, *depthTexture);
// using combined format: depth + stencil
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_STENCIL_OES, w, h, 0, GL_DEPTH_STENCIL_OES, GL_UNSIGNED_INT_24_8_OES, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);

// attaching both depth and stencil
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, *depthTexture, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, *depthTexture, 0);

// No color output in the bound framebuffer, only depth.
GLenum drawbuffers[] = { GL_NONE };
glDrawBuffers(1, drawbuffers);

GL_CHECK(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE);

Creating stencil mask for shadow map:

// bind to depth fbo
glBindFramebuffer(GL_FRAMEBUFFER, *fbo);

glEnable(GL_STENCIL_TEST);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
glClear(GL_STENCIL_BUFFER_BIT);

// write to stencil when objects are rendered
glStencilFunc(GL_ALWAYS, 1, 0xFF);
glStencilMask(0xFF);

drawVisibleObjects();

Rendering of depth with stencil mask:

glBindFramebuffer(GL_FRAMEBUFFER, *fbo);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_EQUAL, 1, 0xFF); // Pass test if stencil value is 1
glStencilMask(0x00); // Don't write anything to stencil buffer
glDepthMask(GL_TRUE); // Write to depth buffer

drawObjects();

When the code is executed, the screen is black. This is unexpected, because I dont render depth to default framebuffer, but to a texture. Since the stencil values are stored in the texture, do I have to use them differently?

What is the correct way to use a stencil attachment when combined depth-stencil texture GL_DEPTH_STENCIL_OES is used?

回答1:

The stencil value is a property of the framebuffer you are rendering in to. If you want to use a stencil mask in FBO0 then you need to request a stencil in FBO0 (and populate the mask, etc, while rendering to FBO0).