Skip to content Skip to sidebar Skip to footer

GlBufferSubData , Haven't Implemented Type-inference For Lists Yet - Instanced Rendering

Porting over a chapter 7 example of instanced rendering from Superbible OpenGL 7th ed. and run into a problem with the function glBufferSubData Whatever I do to it, it won't accept

Solution 1:

In compare to glBufferData, PyOpenGl's glBufferSubData the size parameter can't be omitted.
You've to pass the size of the buffer (in bytes) and a pointer to the buffer. But note, the 2nd and the 3rd parameter have to be a python int or long, even PyOpneGL's GLuint will cause an error.

You've some possibilities, either create an array PyOpenGL's GLfloat

offset = 0
dataArray = (GLfloat*len(square_vertices))(*square_vertices)
glBufferSubData(GL_ARRAY_BUFFER, offset, len(dataArray)*4, dataArray)

or use pythons built-in ctypes library:

import ctypes
offset = 0
dataArray = (ctypes.c_float*len(square_vertices))(*square_vertices)
glBufferSubData(GL_ARRAY_BUFFER, offset, len(dataArray)*4, dataArray)

or create a NumPy array:

import numpy as np 
offset = 0
dataArray = np.array(square_vertices, dtype='float32')
glBufferSubData(GL_ARRAY_BUFFER, offset, len(dataArray)*4, dataArray)

Note, for the 2nd and 3d parameter you can use a cast to either int (e.g int(offset)) or long (e.g. long(offset)).


Further note, the offset and size parameters to glBufferData, glBufferSubData and glVertexAttribPointer are values in size of bytes rather than the number of elements of the arrays.
The size in bytes is calculated by the number of elements multiplied by the size of 1 element.
The size of 1 element is 4, since the size of float (GLfloat, ctypes.c_float, 'float32') in bytes is 4.

If a named buffer object is bound, then the last parameter of glVertexAttribPointer is treated as a byte offset into the buffer object's data store, but the type of the parameter is still a pointer. So you've to use ctypes.c_void_p(offset). If offset is 0 it is possible to pass None.

bufferSize = (len(square_vertices) + len(instance_colors) + len(instance_positions))*4
glBufferData(GL_ARRAY_BUFFER, bufferSize, None, GL_STATIC_DRAW)

glBufferSubData(GL_ARRAY_BUFFER, offset, len(square_vertices)*4, square_vertices)
offset += len(square_vertices)*4

glBufferSubData(GL_ARRAY_BUFFER, offset, len(instance_colors)*4, instance_colors)
offset += len(instance_colors)*4

glBufferSubData(GL_ARRAY_BUFFER, offset, len(instance_positions)*4, instance_positions)
offset += len(instance_positions)*4

glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, None)
offsetInstanceColor =  len(square_vertices)*4
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(offsetInstanceColor))
offsetInstancPosition =  (len(instance_colors) + len(instance_positions))*4
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(offsetInstancPosition))


Post a Comment for "GlBufferSubData , Haven't Implemented Type-inference For Lists Yet - Instanced Rendering"