Problem cleaning stencil buffer

Hi everyone

I’ve been working with stenci buffer and after some test I realize that something strange is happening. Here’s my code


glEnable(GL_DEPTH_TEST);
glEnable(GL_STENCIL_TEST);
	
glClearStencil(0);
glClearDepth(1);

glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

glDepthFunc(GL_LESS);
glStencilFunc(GL_ALWAYS, 0, 0);
glStencilOp(GL_KEEP, GL_KEEP, GL_INCR);

GLfloat stencil[SCREEN_RES_X*SCREEN_RES_Y];

for(uint i=0;i<10;i++)
{
    //render something
    glClearStencil(0);
    glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glReadPixels(0,0,SCREEN_RES_X,SCREEN_RES_Y,GL_STENCIL_INDEX,GL_FLOAT,stencil);
    //print stencil[]
}

In this case stencil array should be all 0s. In the first iteration is rigth, but in the following iterations some pixels are 1 (the ones rendered in my scene).

On the other hand executing this:


glEnable(GL_DEPTH_TEST);
glEnable(GL_STENCIL_TEST);
	
glClearStencil(0);
glClearDepth(1);

glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

glDepthFunc(GL_LESS);
glStencilFunc(GL_ALWAYS, 0, 0);
glStencilOp(GL_KEEP, GL_KEEP, GL_INCR);

GLfloat stencil[SCREEN_RES_X*SCREEN_RES_Y];

for(uint i=0;i<10;i++)
{
    //render something
    glClearDepth(1);
    glClearStencil(0);
    glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glReadPixels(0,0,SCREEN_RES_X,SCREEN_RES_Y,GL_STENCIL_INDEX,GL_FLOAT,stencil);
    //print stencil[]
}

Just adding glClearDepth(1) inside the loop all works fine.

This is very strange. It seems like OpenGL needs the value every time you want to clean. This souldn’t happen since OpenGL is a state machine.

Can anyone explain me this?

Thank you for your time.