ray*_*_lv 2 python multithreading pyglet concurrent.futures
下面的三个函数展示了我如何使用 pyglet 库在屏幕上绘制正方形。该代码运行良好。但我想让它跑得更快。
根据我对线程的新手理解,我认为使用线程可以使 for 循环draw_grid()
更快,因为它等待一个正方形被绘制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)
Run Code Online (Sandbox Code Playgroud)
在查找了一些有关线程的视频后,我找到了该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()
Run Code Online (Sandbox Code Playgroud)
作为一般规则,切勿混合线程和图形渲染。这是灾难的接待。可以将线程与渲染 (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
Run Code Online (Sandbox Code Playgroud)
您不想使用线程的原因是,几乎 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()
Run Code Online (Sandbox Code Playgroud)
与此类似的事情。但显然您希望在不同的位置创建方块等。但作为指导,在渲染逻辑之外创建批处理和方块,然后.draw()
在渲染周期中调用批处理。
归档时间: |
|
查看次数: |
537 次 |
最近记录: |