How stencil test is performed with multisampling enabled?

Hey! I am trying to implement a stencil routed A-Buffer following this
paper.
I have enabled the multisampling.
When is the stencil test performed? After the fragment shader pass?
Is it performed on each sample produced by multisampling?
Or, is it performed on each fragment?

Sorry for the confusion, any explanation will be appreciated :slight_smile:

If multisample rasterization is properly enabled, stencil ops (test/write/etc.) occur per-sample, not per fragment.

This means that in the multisample render targets being rendered to, there is stencil storage allocated per sample, not just per texel.

To your other question, the stencil test may happen either before or after the fragment shader. Up to the driver. So long as the behavior exhibited corresponds to that defined in the OpenGL spec. In some cases, drivers may run the test before to try to “kill off” whole groups of fragments for efficiency, so that there’s no need to dispatch fragment shaders for them at all.

You can read more about this all here in the OpenGL wiki:

Thanks for the answer and the link, it clarifies a lot.
I have a related question.
Is it possibile to perform different glStencilOp and glStencilFunc for each sample?

Hey! I found my answer to my question.
For the future I post it here.
The inspiration for the code is taken from here:

const uint32_t multiSamples = 0x1u<<3;//suppose we have multiSamples levels

glEnable(GL_STENCIL_TEST);
glStencilOp(GL_KEEP,GL_KEEP,GL_REPLACE);//GL_REPLACE = we want to initialize = write the stencil buffer				
glEnable(GL_MULTISAMPLE);
glEnable(GL_SAMPLE_MASK);
	
for (uint32_t i=0; i<multiSamples; i++){
        
    glStencilFunc(GL_ALWAYS,i+2,multiSamples-1);//In my case I want to write in the stencil value i+2 as ref
    glSampleMaski(0,0x1u<<i);//enable ONLY the specified sample
    driver->setMaterial(initMaterial);//initMaterial is a simple vertex and fragment shaders (basically they don't do nothing)
    driver->drawMeshBuffer(screenTriangleMeshBuffer.get());//Draw a simple screen triangle canvas in order to "Force" the write on the enabled sample stencil value
        
}