I've got what seems like a very ugly little piece of code that I seem to keep on resorting back to whenever I'm trying to draw arrays with pyglet, of the form:
vertPoints = someArray.flatten().astype(ctypes.c_float)
vertices_gl = vertPoints.ctypes.data_as(ctypes.POINTER(ctypes.c_float))
Which I cobbled together based on the few resources I could find using numpy with pyglet. Is there a more elegant way to get a pointer to a numpy array as c_floats?
Here's the code above in the context of a small example 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()
dtype=np.float32
and use separate arrays for the vertices and colors, then you don't need toflatten
(copy the data to contiguous memory) or useastype
(create a whole new array), and the pointer is justvertices_gl = verticesArray.ctypes.data
, etc. – eryksun Mar 25 at 0:24