How to use glBufferData() in PyOpenGL?
Asked Answered
M

2

6

How do you use glBufferData() in the PyOpenGL python bindings to OpenGL?

When I run the following code

import sys
from OpenGL.GL import *
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtOpenGL import *

class SimpleTestWidget(QGLWidget):

    def __init__(self):
        QGLWidget.__init__(self)

    def initializeGL(self):
        self._vertexBuffer = glGenBuffers(1)
        glBindBuffer(GL_ARRAY_BUFFER, self._vertexBuffer)
        vertices = [0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5]
        glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW)    # Error

    def paintGL(self):
        glViewport(0, 0, self.width(), self.height())
        glClearColor(0.0, 1.0, 0.0, 1.0)
        glClear(GL_COLOR_BUFFER_BIT)

        glEnableClientState(GL_VERTEX_ARRAY)
        glBindBuffer(GL_ARRAY_BUFFER, self._vertexBuffer)
        glVertexPointer(2, GL_FLOAT, 0, 0)
        glColor3f(1.0, 0.0, 0.0)
        glDrawArrays(GL_QUADS, 0, 4)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = SimpleTestWidget()
    w.show()
    app.exec_()

then the call to glBufferData() results in the error message

Haven't implemented type-inference for lists yet

The code is supposed to paint a red rectangle on a green background.

Milner answered 20/6, 2012 at 18:26 Comment(0)
S
10

As a workaround, until lists are supported, pass the vertices as a numpy array:

vertices = numpy.array([0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5], 
                       dtype='float32')

The glVertexPointer call should be glVertexPointer(2, GL_FLOAT, 0, None)

Successor answered 20/6, 2012 at 20:24 Comment(2)
I'm puzzled that the fourth argument to glVertexPointer should be None; see follow up question: #11133216Nebulose
Additionally, you can avoid having to bind the buffers manually by using the VBO wrapper.Sidoney
J
3

You can also use the array object of the array module:

from array import array
vert=[0.0,0.0,0.0,
      1.0,0.0,0.0,
      1.0,1.0,0.0,
      0.0,1.0,0.0]

ar=array("f",vert)
glBufferData(GL_ARRAY_BUFFER, ar.tostring(), GL_STATIC_DRAW)

https://docs.python.org/2/library/array.html

Johnettajohnette answered 14/9, 2015 at 15:27 Comment(1)
personally I believe this should be the accepted answer as it performs betterCarolinian

© 2022 - 2024 — McMap. All rights reserved.