python - 有没有更快的方法使用 pyglet 和线程在屏幕上绘图?
问题描述
下面的三个函数展示了我如何使用 pyglet 库在屏幕上绘制正方形。代码工作正常。但我想让它运行得更快。
以我对线程的新手理解,我认为draw_grid()
使用线程可以使 for 循环更快,因为它等待一个正方形使用pos
然后绘制一个新正方形。既然all_positions
已经提供了,有没有办法同时绘制所有的正方形?
def draw_square(single_location):
# draws a single square
pyglet.graphics.draw_indexed(4, pyglet.graphics.gl.GL_TRIANGLES,
[0,1,2,1,2,3],
('v2i', single_location))
def position_array():
# returns an 2D array with each row representing the coordinates of the rectangle to draw
...relevant code...
return all_positions
def draw_grid(all_positions):
# uses draw_square function and all_positions to draw multiple squares at the specified locations.
for pos in all_positions:
draw_square(pos)
在查找了一些有关线程的视频后,我找到了该concurrent.futures
库。所以我试图实现它,它给了我错误。所以现在我被卡住了。
这是我concurrent.futures.ThreadPoolExecutor()
在里面使用的方式draw_grid()
def draw_grid(all_positions):
# uses draw_square function and all_positions to draw multiple squares at the specified locations.
with concurrent.futures.ThreadPoolExecutor as executor:
for pos in all_positions:
f1 = executor.submit(draw_square, pos)
f1.result()
解决方案
作为一般规则,永远不要混合线程和图形渲染。这是灾难的收据。可以将线程与渲染 (GL) 结合使用。但同样,不建议这样做。
相反,您可能想看的是批处理渲染。
有大量关于批量渲染的文档,您可能会发现它们很容易理解。
请记住,如果要在将顶点添加到补丁后对其进行修改,则需要将它们存储并修改从批处理返回,不要尝试直接操作批处理。
vertex_list = batch.add(2, pyglet.gl.GL_POINTS, None,
('v2i', (10, 15, 30, 35)),
('c3B', (0, 0, 255, 0, 255, 0))
)
# vertex_list.vertices <-- Modify here
您不想使用线程的原因是,几乎 99.9% 的保证您最终会因竞争条件而出现分段错误。当你渲染你试图操纵的东西时,有东西试图更新屏幕。
此处评论中的更多信息:Update and On_Draw Pyglet in Thread
因此,相反,将所有方块添加到一批中,然后这样做batch.draw()
,它会一次模拟地绘制所有方块。而不是浪费 CPU 周期调用函数并每次重新创建正方形,然后一个一个地渲染它们。
batch = pyglet.graphics.Batch()
batch.add(2, pyglet.gl.GL_TRIANGLES, None,
('v2i', [0,1,2,1,2,3])
)
def on_draw():
batch.draw()
与此类似的东西。但显然你想在不同的位置创建正方形等。但作为指导,在渲染逻辑之外创建批处理和正方形,然后.draw()
在渲染周期中调用批处理。
推荐阅读
- vim - 从多个文件grep,在vim中交互修改匹配行的内容,保存后,更改应保存到相应文件
- mongodb - MongoDB:最新的 docker 容器以退出代码 14 终止
- python - pip安装,我应该如何在windows上添加include和lib目录?
- cassandra - Cassandra 节点在批量插入时失败
- java - 如何在 spring application.properites 中注入包含 ${...} 的字符串
- android - Libgdx-音乐不会停止
- ssl - 在 Google Cloud DNS 中添加 AAAA 记录
- javascript - javascript 中似乎不存在的循环引用错误
- uwp - 如何在 UWP 应用程序中获取 Windows 10 设备 ID?
- azure-cosmosdb - 调用属性后如何返回顶点