Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use WebGL drawElements offset?

This is a rather WebGL specific question. I am having trouble understanding the WebGL-specific implementation of drawElements. Here is the API specification. From the WebGL specification.

How exactly do I use the offset? Can I use the offset to mimic the more classic glDrawRangeElements?

void drawElements(GLenum mode, GLsizei count, GLenum type, GLintptr offset) (OpenGL ES 2.0 §2.8, man page)

Draw using the currently bound element array buffer. The given offset is in bytes, and must be a valid multiple of the size of the given type or an INVALID_OPERATION error will be generated; see Buffer Offset and Stride Requirements. If count is greater than zero, then a non-null WebGLBuffer must be bound to the ELEMENT_ARRAY_BUFFER binding point or an INVALID_OPERATION error will be generated.

I have a flat vertices array and a flat indices array, and drawing using one drawElements call has been working out great, but now I want to draw parts of the vertices separately because they are different objects. For instance, indices[0] to indices[99] is one object (e.g. an arm), and indices[100] to indices[149] (e.g. a leg) is another object. The groups must be drawn separately - ultimately because they have different textures, and I will bind a texture before each drawElements call (maybe there is another way to do this altogether?)

Thus, I want to call drawElements on indices[0] to indices[99], and drawElements on indices[100] to indices[149]. Can I do that with the drawElements offset?

With the code I have here, I can draw the first group very nicely, but the rest of the groups don't show up.

for(var g = 0; g < groups.length; g++) {
    var group = groups[g];

    //Set the texture
    var material = group.material;
    material.bindTexture();

    //Draw it!
    var offset = group.offset; //index of the first element of the indices, (e.g. position '0' or position '100', from above)
    var num_items = group.num_items; //number of items in this group, (e.g. '100' elements or '50' elements, from above)
    gl.drawElements(draw_mode, num_items, indices.type, offset);
}
like image 803
SharkCop Avatar asked Apr 19 '12 04:04

SharkCop


1 Answers

Documentation says:

... The given offset is in bytes, and must be a valid multiple of the size of the given type ...

If indices.type is gl.UNSIGNED_SHORT then 2 bytes are been used for each index.

Try using offset * 2 instead of just offset:

gl.drawElements(draw_mode, num_items, indices.type, offset * 2);
like image 101
Juan Mellado Avatar answered Sep 23 '22 18:09

Juan Mellado