python - 如何创建一个 numpy 数组来描述三角形的顶点?

标签 python arrays numpy glsl

我喜欢使用 Numpy 创建要传递到 glsl 的顶点数组。

Vertices 将是一个 numpy 数组,包含 3 个顶点的信息。

每个顶点包含:

  1. pos = (x, y) 具有 32 位的 64 位有符号浮点格式 R 分量位于字节 0..3 中,32 位 G 分量位于字节 4..7 中, 和
  2. color = (r, g, b) 96 位有符号浮点格式,具有 32 位 R 分量(以字节 0..3 为单位),32 位 G 分量(以字节为单位) 4..7,以及字节 8..11 中的 32 位 B 组件

即每个顶点 = (pos, color) = ( (x, y), (r, g, b) )

三角形有3个顶点,所以最后我需要一个一维numpy数组来描述

Vertices = [vertex1, vertex2, vertex3]
         = [ ( (x, y), (r, g, b) ), 
             ( (x, y), (r, g, b) ), 
             ( (x, y), (r, g, b) ) ] 

如何在 numpy 中创建顶点以下语法看起来错误。

Vertices = np.array([( (x1, y1), (r1, g1, b1) ), 
                     ( (x2, y2), (r2, g2, b2) ), 
                     ( (x3, y3), (r3, g3, b3) )], dtype=np.float32)

每个顶点的字节大小应为 64/8 + 96/8 = 8 + 12 = 20 字节。 Vertices 的字节大小应为 20 字节 x 3 = 60 字节。

最佳答案

这实际上非常简单,在 numpy 中。使用structured arrays :

In [21]: PosType = np.dtype([('x','f4'), ('y','f4')])

In [22]: ColorType = np.dtype([('r','f4'), ('g', 'f4'), ('b', 'f4')])

In [23]: VertexType = np.dtype([('pos', PosType),('color', ColorType)])

In [24]: VertexType
Out[24]: dtype([('pos', [('x', '<f4'), ('y', '<f4')]), ('color', [('r', '<f4'), ('g', '<f4'), ('b', '<f4')])])

In [25]: VertexType.itemsize
Out[25]: 20

然后简单地:

In [26]: vertices = np.array([( (1, 2), (3, 4, 5) ),
    ...:                      ( (6, 7), (8, 9, 10) ),
    ...:                      ( (11, 12), (13, 14, 15) )], dtype=VertexType)

In [27]: vertices.shape
Out[27]: (3,)

和基本索引:

In [28]: vertices[0]
Out[28]: (( 1.,  2.), ( 3.,  4.,  5.))

In [29]: vertices[0]['pos']
Out[29]: ( 1.,  2.)

In [30]: vertices[0]['pos']['y']
Out[30]: 2.0

In [31]: VertexType.itemsize
Out[31]: 20

numpy 曾经提供记录数组,因此您可以使用属性访问而不是索引:

In [32]: vertices = np.rec.array([( (1, 2), (3, 4, 5) ),
    ...:                          ( (6, 7), (8, 9, 10) ),
    ...:                          ( (11, 12), (13, 14, 15) )], dtype=VertexType)

In [33]: vertices[0].pos
Out[33]: (1.0, 2.0)

In [34]: vertices[0].pos.x
Out[34]: 1.0

In [35]: vertices[2].color.g
Out[35]: 14.0

关于python - 如何创建一个 numpy 数组来描述三角形的顶点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51891518/

相关文章:

java - 在java中表示转换函数的方法?

将 char 数组转换为整数

php - 按用户级别从 MySql 表中选择所有 ID,并将每个级别的 ID 数存储在数组中?

python - 列表和元组的行为不同

python - Numpy 字典顺序

python - 为什么在 Python 中 -103/100 == -2 但 103/100 == 1?

python - 在 Python 中,两个对象何时相同?

python - 正则表达式 - 函数体提取

python - 如何在 Python 中查询和管理 Debian 包存储库?

python - 如何创建一个具有不同 Id 和其他两个列的不同值的新列?