skiwi
skiwi

Reputation: 69379

DrawElements not working as expected with multiple objects

In my program I basically put all objects in one buffer, and now I am having issues when I want to draw multiple objects, if I only draw one it still works.
The issues started to occur when I roughly changed all glDrawArrays to glDrawElements calls, and of course all underlying infrastructure.
As of now I simply made a one-to-one mapping from vertices to indices.

I am using Java 8, LWJGL and OpenGL 3.3.

Initialization:

//drawable vertex buffer
vertexBuffer = new StaticDrawArrayBuffer().create().bind().fillData(Drawable.putAllVertexData(drawables));
vertexArray = new VertexArrayObject().create().bind()
        .setAttribute(vertexBuffer, VS_POSITION, 3, GL_FLOAT, false, 0, 0)
        .enableAttributes(VS_POSITION);

//drawable elements buffer
elementBuffer = new StaticDrawElementArrayBuffer().create().bind().fillData(Drawable.putAllElementsData(drawables));

So I do the following:

  1. Create an ARRAY_BUFFER and store all vertex data in there.
  2. Create a Vertex Array Object, and set where the position data can be found.
  3. Create an ELEMENT_ARRAY_BUFFER and store all indices in there.

With contents as follows;

Vertex Data:

-400.0
0.0
-400.0
-400.0
0.0
400.0
400.0
0.0
-400.0
-400.0
0.0
400.0
400.0
0.0
-400.0
400.0
0.0
400.0
1.0
1.0
-1.0
-1.0
1.0
-1.0
-1.0
1.0
1.0
-1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
-1.0
1.0
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
1.0
-1.0
-1.0
1.0
1.0
-1.0
1.0
1.0
-1.0
-1.0
-1.0
1.0
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
1.0
-1.0
-1.0
1.0
-1.0
1.0
1.0
-1.0
1.0
-1.0
-1.0
1.0
1.0
-1.0
-1.0
1.0
1.0
-1.0
1.0
1.0
-1.0
1.0
1.0
1.0
1.0
-1.0
1.0
1.0
1.0
1.0
1.0
1.0
-1.0
1.0
1.0
-1.0
-1.0
1.0
-1.0
-1.0
1.0
1.0
-1.0
1.0
1.0
1.0
1.0
1.0
-1.0
1.0
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
1.0
-1.0
1.0
1.0
-1.0

Indices data:

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

So that is 126 float, that should get mapped by (x, y, z) to 42 indices.

However when I do the following calls subsequently:

gl.glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0)
gl.glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 6)

The objects get drawn all mixed through each other, definately not how they are supposed to look, what I thought the code would do is;

What could be possible reasons that this is not working?

Upvotes: 2

Views: 396

Answers (1)

datenwolf
datenwolf

Reputation: 162327

glDrawElements last parameter used to be a pointer to the index array. With VBOs this parameter gets reused as a byte sized offset into the VBO. So it does not take an index, but a byte offset into the VBO to where the data starts. In your case that would be sizeof(GLfloat) * x where sizeof(GLfloat) usually is 4. So you have to multiply your particular data layout you have to multiply the offset index by 4 to get the byte offset.

Upvotes: 2

Related Questions