I am confused about glDrawElements()
. I was following a tutorial which said that the 4th argument of the glDrawElements()
is "Offset within the GL_ELEMENT_ARRAY_BUFFER
". But I was having an error "Access voilation: Trying to read 0x0000", if I passed 0 as offset.
So I dig further into the problem and found that OpenGL Documentation provides two different definitions of the 4th argument:
First:
indices: Specifies a byte offset (cast to a pointer type) into the buffer bound to GL_ELEMENT_ARRAY_BUFFER to start reading indices from.
(Found Here: https://www.opengl.org/wiki/GLAPI/glDrawElements)
Second:
indices: Specifies a pointer to the location where the indices are stored.
(Found Here: https://www.opengl.org/sdk/docs/man4/index.php and Here: http://www.khronos.org/opengles/sdk/docs/man/xhtml/glDrawElements.xml)
Which one is true and How to use it correctly?
EDIT: Here is my code: http://pastebin.com/fdxTMjnC
Both are correct. The 2 cases relate to how the buffer of indices is uploaded to the GL Hardware and how it is used to draw. These are described below:
(1) Without using VBO (Vertex Buffer Object):
In this case, the parameter indicates a pointer to the array of indices. Everytime glDrawElements
is called, the buffer is uploaded to GL HW.
(2) Using VBO:
For this case - see the definition of Index as "Specifies a byte offset (cast to a pointer type) into the buffer bound to GL_ELEMENT_ARRAY_BUFFER to start reading indices from". This means that the data is already uploaded separately using glBufferData
, and the index is used as an offset only. Everytime glDrawElements
is called, the buffer is not uploaded, but only the offset can change if required. This makes it more efficient, especially where large number of vertices are involved.
If you use direct drawing, then
indices defines the offset into the index buffer object (bound to GL_ELEMENT_ARRAY_BUFFER, stored in the VAO) to begin reading data.
That means, you need to create VAO, bind to it, and then use glDrawElements()
for rendering
The interpretation of that argument depends on whether an internal array has been bound in the GL state machine. If such an array is bound, it's an offset. If no such array is bound, it's a pointer to your memory.
Using an internal array is more performant, so recent documentation (especially wikis) is strongly biased toward that usage. However, there's a long song and dance to set them up.
The function that binds or unbinds the internal array is glBindVertexArray. Check the documentation for these related functions:
(this is an incomplete list. I've got to run so I'll have to edit later.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With