0

Basically what I want to do is generate my vertex coordinates programmatically instead of storing it in a statically predefined array. Unfortunately I am not able to convert a very simple example to a dynamic array.

Everything works fine if I stick to static arrays:

typedef struct {
    GLfloat Position[3];
    GLfloat Color[4];
    GLfloat TexCoord[2];
    float Normal[3];
} Vertex;


Vertex sphereVertices[] = {
    {{1, -1, 1}, {1, 0, 0, 1}, {1, 0}, {0, 0, 1}},
    {{1, 1, 1}, {0, 1, 0, 1}, {1, 1}, {0, 0, 1}},
    {{-1, 1, 1}, {0, 0, 1, 1}, {0, 1}, {0, 0, 1}},
    {{-1, -1, 1}, {0, 0, 0, 1}, {0, 0}, {0, 0, 1}}
};

GLubyte sphereIndices [] = {
    0, 1, 2,
    2, 3, 0
};

...

glGenBuffers(1, &sphereIndexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sphereIndexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(sphereIndices), sphereIndices, GL_STATIC_DRAW);

glEnableVertexAttribArray(GLKVertexAttribPosition);
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid *) offsetof(Vertex, Position));

...

glDrawElements(GL_TRIANGLES, 6 * sizeof(GLubyte), GL_UNSIGNED_BYTE, 0);

As soon as I switch my indices to a dynamic array only the first triangle shows up.

GLubyte *sphereIndices;

+(void)initialize {
    sphereIndices = malloc(6 * sizeof(GLubyte));
    sphereIndices[0] = 0;
    sphereIndices[1] = 1;
    sphereIndices[2] = 2;
    sphereIndices[3] = 2;
    sphereIndices[4] = 3;
    sphereIndices[5] = 0;
}

Probably this has something to do with pointers. Does anybody know what I am doing wrong?

Thanks!

1 Answer 1

4

I was able to solve the problem myself. As I already expected the problem had to do with my missing understanding of pointers.

As far as I found out, there is no way to get the size of a dynamic array. Because of that sizeof(sphereIndices) always returns 4 which is the size of the pointer not the size of the data. That's why glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(sphereIndices), sphereIndices, GL_STATIC_DRAW) only sends 4 indices to openGL instead of 6.

I fixed the problem by introducing an additional variable to keep track of the number of indices.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.