用pyglet绘制多边形会创建不需要的重叠区域

时间:2020-09-28 10:04:20

标签: python python-3.x opengl pyglet shapely

我试图用pyglet绘制一个填充的多边形,但出现了不想要它们的重叠区域。

我的(极简)代码:

num_pts = 6 
pts_seq = [500, 129, 505, 92, 505, 114, 516, 114, 516, 93, 520, 129]
color= [255, 255, 200, 100]

pyglet.graphics.draw(
    num_pts,  # points count
    pyglet.gl.GL_POLYGON,  #
    ('v2i', pts_seq),  # data points
    ('c4B', color * num_pts),  # color data
)

结果:

enter image description here

我还尝试了here的答案,并得到了相同的结果。

2 个答案:

答案 0 :(得分:1)

Pyglet基于OpenGL。已弃用的OpenGL Primitive类型GL_POLYGON仅能正确处理凸多边形。
您必须对多边形进行三角剖分,并且必须使用GL_TRIANGLESGL_TRIANGLE_STRIPGL_TRIANGLE_FAN类型的Triangle primitive种类型。

例如,使用基本类型GL_TRIANGLES并通过4个三角形将形状缝合在一起:

num_pts = 12 
pts_seq = [
    500, 129, 505, 92, 505, 114,
    500, 129, 505, 114, 516, 114,
    500, 129, 516, 114, 520, 129,
    516, 114, 516, 93, 520, 129]
color= [255, 255, 200, 100]

pyglet.graphics.draw(
    num_pts,  # points count
    pyglet.gl.GL_TRIANGLES,  #
    ('v2i', pts_seq),  # data points
    ('c4B', color * num_pts),  # color data
)

或更改点的顺序并使用基本类型GL_TRIANGLE_STRIP

num_pts = 6
pts_seq = [505, 92, 500, 129, 505, 114, 520, 129, 516, 114, 516, 93]

color= [255, 255, 200, 100]

pyglet.graphics.draw(
    num_pts,  # points count
    pyglet.gl.GL_TRIANGLE_STRIP,  #
    ('v2i', pts_seq),  # data points
    ('c4B', color * num_pts),  # color data
)

答案 1 :(得分:1)

@ Rabbib76回答了这个问题,我想用三角剖分任意多边形的策略来完成它,这不再是原始问题的一部分,因此,本文作为答案。

我的解决方案与我正在处理的代码部分的开发方式有关,即使用shapely

from shapely.geometry import Polygon as shPolygon
from shapely.ops import triangulate as shTriangulate

for pol_points in list_pol_points:
    obj_polygon = shPolygon(self.points)
    triangulated_objs = shTriangulate(obj_polygon)
    
    for sub_obj in triangulated_objs:
        if sub_obj.centroid.within(obj_polygon):
            sub_obj_points = list(sub_obj.exterior.coords)
            num_pts = len(sub_obj_points)
            pts_seq = []

            for point in sub_obj_points:
                pts_seq.append(point[0])
                pts_seq.append(point[1])

            pyglet.graphics.draw(
                num_pts,  # points count
                pyglet.gl.GL_POLYGON,  #
                ('v2i', pts_seq),  # data points
                ('c4B', color * num_pts),  # color data
            )
相关问题