Using numpy and ctypes arrays for OpenGL calls in Pyglet

I have something that seems like a very ugly little piece of code that seems to me to keep coming back when I try to draw arrays using a piglet, form:

vertPoints = someArray.flatten().astype(ctypes.c_float) vertices_gl = vertPoints.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) 

Which I put together based on several resources that I could find using numpy with pyglet. Is there a more elegant way to get a pointer to a numpy array like c_floats?

Here is the code above in the context of a small example that I wrote:

 import numpy as np; import ctypes import pyglet; import pyglet.gl as gl def drawArray(someArray): vertPoints = someArray[:,:2].flatten().astype(ctypes.c_float) vertices_gl = vertPoints.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) vertColors = someArray[:,2:].flatten().astype(ctypes.c_float) colors_gl = vertColors.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) gl.glVertexPointer(2, gl.GL_FLOAT, 0, vertices_gl) gl.glColorPointer(3, gl.GL_FLOAT, 0, colors_gl) gl.glDrawArrays(gl.GL_POINTS, 0, len(vertPoints) // 2) window = pyglet.window.Window(400,400) @window.event def on_draw(): gl.glPointSize(10.0) gl.glEnable(gl.GL_POINT_SMOOTH) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnableClientState(gl.GL_VERTEX_ARRAY) gl.glEnableClientState(gl.GL_COLOR_ARRAY) points = np.random.random((50,5))*np.array([400,400,1,1,1]) drawArray(points) pyglet.app.run() 
+4
source share
2 answers

I think you do not need to convert the data address to a float pointer, you can directly pass the address:

 gl.glVertexPointer(2, gl.GL_FLOAT, 0, vertPoints.ctypes.data) gl.glColorPointer(3, gl.GL_FLOAT, 0, vertColors.ctypes.data) 
+3
source

You can use Numpy float arrays directly with vertex buffer objects. However, I did not use them in the context of Pyglet. Sort of:

 from OpenGL.arrays import vbo # setup vertices_gl = vbo.VBO(vertPoints) colours_gl = vbo.VBO(vertPoints) # in drawing code vertices.bind() colours.bind() glVertexPointer(2, gl.GL_FLOAT, 0, vertices_gl) glColorPointer(2, gl.GL_FLOAT, 0, vertices_gl) 
+2
source

All Articles