c++copenglpolygonopengl-compat

Concave GL_POLYGON doesn't color in?


I have a problem when I try to use GL_POLYGON in OpenGL. I don't know how to explain this but all my vertices are connected with the beginning one. The problem happens when I try to color the object. I want to draw a simple object.

void TOP (float x1, float y1, float x2, float h,float n)
{
  float r = x2-x1;
  if(n==1){glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);} // FOR FILL OR NO FILL OBJECT
  glBegin(GL_POLYGON);
     glVertex2f(x1,y1);
     glVertex2f(x2,y1);
     glVertex2f(x2,y1+h/7);
     y1=y1+h/7;
     glVertex2f(x2-r/5,y1+h/7);
     x2=x2-r/5; y1=y1+h/7;
     glVertex2f(x2,y1+2*h/7);
     y1=y1+2*h/7;
      glVertex2f(x2+r/5,y1+h/7);
      y1=y1+h/7; x2=x2+r/5;
      glVertex2f(x2,y1+2*h/7);
cout<<y1<<endl;
      y1=y1+2*h/7;
       glVertex2f(x2-r/5,y1); x2=x2-r/5;
      glVertex2f(x2,y1-h/7); y1=y1-h/7;
      glVertex2f(x2-r/5,y1);x2=x2-r/5;
      glVertex2f(x2,y1+h/7); y1=y1+h/7;
      glVertex2f(x2-r/5,y1);x2=x2-r/5;

       glVertex2f(x2,y1-h/7); y1=y1-h/7;
       glVertex2f(x2-r/5,y1);x2=x2-r/5;
        glVertex2f(x2,y1+h/7); y1=y1+h/7;
         glVertex2f(x2-r/5,y1);x2=x2-r/5;
         glVertex2f(x2,y1-2*h/7);y1=y1-2*h/7;
         glVertex2f(x2+r/5,y1-h/7);y1=y1-h/7; x2=x2+r/5;
         glVertex2f(x2,y1-2*h/7); y1=y1-2*h/7;
         glVertex2f(x2-r/5,y1-h/7); y1=y1-h/7;x2=x2-r/5;
          glVertex2f(x2,y1-h/7);

  glEnd();
}

Output:

https://i.sstatic.net/BLMSJ.png


Solution

  • GL_POLYGON is only for convex polygons:

    GL_POLYGON: Draws a single, convex polygon. Vertices 1 through N define this polygon.

    For concave polygons you have at least two options:

    1. Triangulate the polygon and use GL_TRIANGLES.

    2. Use the stencil buffer trick.