基本的OpenGL(python)

时间:2017-10-09 11:57:49

标签: python opengl pyglet

我正在研究opengl和python并创建了一个基本程序,用两个三角形绘制一个矩形。

def draw(self, shader):
    shader.bind()
    #glDrawArrays(GL_TRIANGLES, 1, 3)
    glDrawElements(GL_TRIANGLES,
                   len(self.indices),
                   GL_UNSIGNED_INT,
                   0)
    glBindVertexArray(0)
    shader.unbind()

def _setupMesh(self):
    # VAO
    glGenVertexArrays(1, self._VAO)
    glBindVertexArray(self._VAO)

    #VBO
    glGenBuffers(1, self._VBO)
    glBindBuffer(GL_ARRAY_BUFFER, self._VBO)
    self.vertices_size = (GLfloat * len(self.vertices))(*self.vertices)
    glBufferData(GL_ARRAY_BUFFER,
                 len(self.vertices)*sizeof(GLfloat),
                 self.vertices_size,
                 GL_STATIC_DRAW)


    #EBO
    glGenBuffers(1, self._EBO)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self._EBO)
    self.indices_size = (GLfloat * len(self.indices))(*self.indices)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,
                 len(self.indices)*sizeof(GLfloat),
                 self.indices_size,
                 GL_STATIC_DRAW)

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), c_void_p(0))
    glEnableVertexAttribArray(0)

我发送的数据如下:

vertices: [  0.5,  0.5,  0.0,
         0.5, -0.5,  0.0,
        -0.5, -0.5,  0.0,
        -0.5,  0.5,  0.0] 
indices: [0,1,3,1,2,3]

glDrawElements调用不执行任何操作,glDrawArrays在窗口中绘制一个漂亮的三角形。

很明显我怀疑为什么glDrawElements不起作用?

1 个答案:

答案 0 :(得分:2)

索引的数据类型必须为GL_UNSIGNED_BYTEGL_UNSIGNED_SHORTGL_UNSIGNED_INT。 (见glDrawElements

要创建数据类型为unsigned int的正确值数组,您可以使用array

from array import array

indAr = array("I", self.indices)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indAr.tostring(), GL_STATIC_DRAW)

或者您可以使用numpy.array

import numpy

numIndAr = numpy.array(self.indices, dtype='uint')
glBufferData(GL_ELEMENT_ARRAY_BUFFER, numIndAr, GL_STATIC_DRAW)

如果使用顶点数组对象,那么glDrawElements的第4个参数必须是None而不是0

glDrawElements(GL_TRIANGLES, len(self.indices), GL_UNSIGNED_INT, None)