简体   繁体   中英

How correctly draw a polygon with OpenTK

I'm new to OpenTK and I'm using the following code to draw large number of polygons using OpenTK

public static void DrawPolygon(Point[] points)
{
    GL.Begin(BeginMode.Polygon); //IF I Change this to LineStrip every things will be OK
    int numberOfPoints = points.Length;
    for (int i = 0; i < numberOfPoints; i++)
    {
        GL.Vertex2(points[i].X, points[i].Y);
    }
    GL.End();
}

And this is the configuration code which executes before calling the DrawPolygon

GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.Ortho(0, width, 0, height, -1, 1); // Bottom-left corner pixel has coordinate (0, 0)
GL.Viewport(0, 0, (int)width, (int)height); 

GL.ClearColor(drawing.Color.Transparent);

GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

GL.MatrixMode(MatrixMode.Modelview);
GL.LoadIdentity();
GL.Color3(pen.Color);
GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line);
GL.PointSize(5f);
GL.LineWidth(2f);

Using this code when I save the rendered image to disk as png, the result will be like this

在此处输入图片说明

result for: GL.Begin(BeginMode.Polygon);

However If I change the first line of the DrawPolygon to GL.Begin(BeginMode.LineStrip); the polygon would be rendered as expected like this:

在此处输入图片说明

result for : GL.Begin(BeginMode.LineStrip);

Anyone knows why those two extra lines appears when using BeginMode.Polygon ?

I believe it's because GL_POLYGON / BeginMode.Polygon only renders convex polygons . I think that if you attempt render a concave polygon, as you're doing, the driver will try split up the geometry that you give it to render it as convex polygons, hence the unexpected lines in your example.

It's inadvisable to use the polygon rendering mode in OpenGL. The rendering of line strips and triangles is much more highly optimized, and therefore much, much quicker. I'd advise staying with line strips.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM