Skip to content

Enabling the stencil buffer in JOGL (OpenGL & Java)

February 19, 2010

In OpenGL the stencil buffer is used to mask pixels on the screen. This can be used for shadow volume rendering, as well as a myriad of other applications. Constructing stencil tests is the same as in C, for example glStencilFunc(GL_KEEP,GL_KEEP, GL_INCR); is just as valid in Java.  However, if you’re noticing that your stencil test is always passing, i.e. your stencil bits are always returned as 0, then you probably haven’t initialized the stencil bits.

In order to use stencil tests, you MUST (emphasize MUST) request stencil bits to the canvas.  Otherwise, the test will always pass. This isn’t incredibly well documented for JOGL… It took a few days of internet searching until I found a breadcrumb of help on this.  In C, one would be using GLUT, so calling glutInitDisplayMode() would be the function to call to request stencil bits.  In Java, this is in the GLCapabilities object.

So, to request stencil bits, in your init() function, put:

GLCapabilities cap = new GLCapabilities();
cap.setStencilBits(8);
GLCanvas canvas = new GLCanvas(cap);

or incorporate this into your code wherever deems fit.  Basically this says, initialize new GLCapabilities, and assign 8 bits in the stencil buffer. Then when you create your GLCanvas, set it as a parameter.  Now you’re good to go, and your stencil tests should work!

Advertisement
2 Comments leave one →
  1. August 9, 2010 4:09 pm

    Thank you. Saved me a lot of frustration. :-)
    Luckily this website came up as one of the first when searching for this problem.

  2. paul permalink
    November 1, 2010 9:45 am

    thx, saved me a lot of time.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.