Getting the OpenGL-ES Stencil Buffer Working

Moncader picture Moncader · Jun 29, 2010 · Viewed 7.4k times · Source

With the stencil buffer in opengl-es for Android, I'm simply trying to mask out drawing part of the screen. I think I have it set up right, but it is not masking out the non-stenciled parts. Below is an extraction of code for what I'm doing.

gl.glEnable(GL10.GL_STENCIL_TEST);
gl.glClearStencil(0);
gl.glClear(GL10.GL_STENCIL_BUFFER_BIT);
gl.glColorMask(false, false, false, false);
gl.glDepthMask(false);
gl.glStencilFunc(GL10.GL_ALWAYS, 1, 1);
gl.glStencilOp(GL10.GL_REPLACE, GL10.GL_REPLACE, GL10.GL_REPLACE);

drawMask(); //I have confirmed this draws to the correct location by allowing colour to show. Trust that this draws the mask to the correct location.

gl.glColorMask(true, true, true, true);
gl.glDepthMask(true);
gl.glStencilFunc(GL10.GL_EQUAL, 1, 1);
gl.glStencilOp(GL10.GL_KEEP, GL10.GL_KEEP, GL10.GL_KEEP);

drawItems(); //Draw everything. Only items inside the masked area should be drawn. But everything is drawn with this code...

gl.glDisable(GL10.GL_STENCIL_TEST);

Anyone spot anything wrong with this? What it does basically is draw a box for say, half the screen (this works if I had colour enabled) which is setting the stencil buffer to 1 for that area. And at the end I draw to the whole screen. I want it to draw to the top half only, but it draws everything.

Thanks in advance.

Answer

Pete picture Pete · Jun 15, 2011

You have to set the stencilSize using setEGLConfigChooser. Note that different phones have different surfaces which may or may not support this.

For example:

    // void android.opengl.GLSurfaceView.setEGLConfigChooser(int redSize, int greenSize, int blueSize, int alphaSize, int depthSize, int stencilSize)
    mGLSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 8);