gpt4 book ai didi

python - pygame中有popMatrix、pushMatrix、Translate吗?

转载 作者:行者123 更新时间:2023-12-02 08:45:34 24 4
gpt4 key购买 nike

pygame 中是否有 PopMatrix、PushMatrix、平移和/或旋转等效方法?

如果没有,开发它们会面临哪些挑战?为什么它们还不存在?

最佳答案

开发矩阵堆栈来跟踪您的转换相对简单。这是我制作的一个简单的类(没有仔细检查此代码是否有错误),它复制了您在 Processing's API reference 中可能会看到的许多功能。 (查看变换部分):

ma​​tstack.py

import math
import numpy as np

_stack = [np.identity(4)]

def apply_mat(mat):
_stack[-1] = np.dot(_stack[-1], mat)

def pop_mat():
_stack.pop()

def push_mat():
_stack.append(get_mat())

def get_mat():
return _stack[-1]

def reset_mat():
_stack[-1] = np.identity(4)

def rotate_mat(radians):
c = math.cos(radians)
s = math.sin(radians)
rotate = np.array([
[c, s, 0, 0],
[-s, c, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
], dtype=np.float32)
apply_mat(rotate)

def translate_mat(x_shift, y_shift):
x, y = x_shift, y_shift
translate = np.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[x, y, 0, 1],
], dtype=np.float32)
apply_mat(translate)

def scale_mat(x_scale, y_scale):
x, y = x_scale, y_scale
scale = np.array([
[x, 0, 0, 0],
[0, y, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
], dtype=np.float32)
apply_mat(scale)

这个类的使用也非常简单:

ma​​in.py

import math
import matstack as ms

if __name__ == "__main__":
ms.reset_mat()
ms.translate_mat(rect.x, rect.y)
ms.rotate_mat(math.radians(45))
ms.scale_mat(2, 0.5)
print(ms.get_mat())

然而,问题在于决定如何应用这些矩阵,以便它们真正影响 pygame 中曲面的绘制。问题是 pygame 中的所有内容都围绕着低级的 pygame.Rect 对象。如果我们看一下documentation ,我们发现 pygame.Rect 构造函数的形式为 Rect(left, top, width, height) -> Rect。这意味着从根本上来说,pygame.Rect 必须是一个轴对齐的最小边界框 (AABB),其边缘必须始终平行于 x = 0 并且y = 0。这有许多有用的属性(请参阅文档中的所有这些辅助函数!),但最终会阻止复杂的转换,例如旋转。

至于为什么会出现这种情况,我相信这可以归因于pygame所依赖的母技术,即SDL ,特别是(过时的)SDL 1.2。虽然像Processing(可能依赖于OpenGL)这样的东西使用硬件加速进行绘图(将类似的4x4矩阵传递给GPU并执行超快速转换),但SDL 1.2是一个软件渲染器,在设计时并未考虑到GPU。由于 GPU 无法用于执行转换,因此工作必须在 CPU 级别完成,操作和“位 block 传送”像素框以获得所需的效果。

为了解决此限制,SDL 有一个模块 SDL_gfx,这可能是 pygame 在其 pygame.transform 模块中使用的模块。这可以使用内置函数处理多个固定选项,例如旋转和缩放。但是,这些函数仅返回包含新转换的像素的 Surface 对象。因此,管道中没有地方可以传递我们的矩阵!

如果您的应用程序中确实需要矩阵和堆栈,我建议您使用 PyOpenGL 来使用 OpenGL。然后,您可以使用我在对您的问题的评论中讨论过的固定函数(顺便说一下,已经过时了)矩阵堆栈操作。您可以在此过程中仍然使用 pygame 来管理窗口和输入。

如果你特别想要一些受Processing启发的东西,但对于Python来说,已经采用了这种方法,我发现this p5 library当我在网上搜索时。如果您只想使用处理生态系统,但使用“python”语法(用 Java 实现),python-mode可能是更好的选择。希望这能让您深入了解这个问题并提供一些可能的解决方案!

关于python - pygame中有popMatrix、pushMatrix、Translate吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46752103/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com