Search code examples
c++openglglfwglm-mathstencil-buffer

I want to know the original stencil value of a pixel/fragment., zero or one? If possible to get what specific action modify the stencil value?


I am confused many things about stencil buffer in OpenGL. I read the opengl tutorials here, https://learnopengl.com/Advanced-OpenGL/Stencil-testing. I simply add one line code

glStencilFunc(GL_EQUAL, 1, 0xFF);

and then nothing will be rendered. if i set the line code as

glStencilFunc(GL_NOTEQUAL, 1, 0xFF);

my objs will be rendered correctly.

I wonder why? Is it that the original stencil value is zero not one? Some code below:

glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_EQUAL, 1, 0xFF);
//glStencilFunc(GL_NOTEQUAL, 1, 0xFF);
//glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
while (!glfwWindowShouldClose(window))
{
    glfwPollEvents();
    glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    shader.use();
    glm::mat4 model = glm::mat4(1.0f);
    glm::mat4 view = g_camera.GetViewMatrix();
    glm::mat4 projection = glm::perspective(g_camera.Zoom, (float)AppGlobal::getInstance()->windowWidth / (float)AppGlobal::getInstance()->windowHeight, 0.1f, 100.0f);
    glUniformMatrix4fv(glGetUniformLocation(shader.m_program, "view"), 1, GL_FALSE, glm::value_ptr(view));
    glUniformMatrix4fv(glGetUniformLocation(shader.m_program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));

    // Floor
    glBindVertexArray(planeVAO);
    glBindTexture(GL_TEXTURE_2D, floorTexture);
    model = glm::mat4(1.0f);
    glUniformMatrix4fv(glGetUniformLocation(shader.m_program, "model"), 1, GL_FALSE, glm::value_ptr(model));
    glDrawArrays(GL_TRIANGLES, 0, 6);
    // some other objects
    glBindVertexArray(0);
    glfwSwapBuffers(window);
}

Solution

  • [...] Is it that the original stencil value is zero not one?

    By default the clear value for the stencil buffer is 0.

    The stencil buffer is cleared when glClear(GL_STENCIL_BUFFER_BIT) is called. The clear value for the stencil buffer can be specified by glClearStencil. The initial value is 0.