I am attempting to draw concave polygons using the stencil buffer trick outlined in the OpenGL redbook but I can't seem to get it working correctly.
Per the redbook, I clear the stencil buffer first prior to enabling the stencil test. Next, I then disable any writes to the color buffer and draw my triangles. The redbook noted that I can use any arbitrary point for the start of my triangle fan call, so I used (0, 0). See the code below for reference:
glMatrixMode(GL_MODELVIEW);
glPushAttrib( GL_CURRENT_BIT );
glDisable(GL_DEPTH_TEST);
glPushMatrix();
glClear( GL_STENCIL_BUFFER_BIT );
glEnable( GL_STENCIL_TEST );
glColorMask( GL_FALSE,GL_FALSE,GL_FALSE,GL_FALSE );
glStencilOp( GL_KEEP, GL_KEEP, GL_INVERT );
glStencilFunc( GL_ALWAYS, 0x1, 0x1 );
glBegin(GL_TRIANGLE_FAN);
glVertex2d(0.0, 0.0);
for(int i = 0; i < oglPoints.size(); i++)
{
glVertex2d(oglPoints[i].x, oglPoints[i].y);
}
glVertex2d(oglPoints[0].x, oglPoints[0].y);
glEnd();
glColor3d(1.0, 1.0, 0.0);
glColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE );
glStencilFunc( GL_EQUAL, 0x1, 0x1 );
glBegin(GL_TRIANGLE_FAN);
for(int i = 0; i < oglPoints.size(); i++)
{
glVertex2d(oglPoints[i].x, oglPoints[i].y);
}
// glVertex2d(oglPoints[0].x, oglPoints[0].y);
glEnd();
glDisable( GL_STENCIL_TEST );
glPopMatrix();
glPopAttrib();
As can be seen from my attached images, I get mixed results. For some points it works, but for others it doesn't.
Correct concave polygon:
Incorrect concave polygon 1:
Incorrect concave polygon 2: