2012-08-15 79 views
0

基本上我想要做的是以编程方式生成我的顶点坐标,而不是将其存储在静态预定义的数组中。不幸的是,我无法将一个非常简单的示例转换为动态数组。以编程方式在iOS中生成OpenGL顶点数据

一切工作正常,如果我坚持静态数组:

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); 

只要将我的指数为动态数组只显示第一个三角形。

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; 
} 

也许这与指针有关。有人知道我做错了什么吗?

谢谢!

回答

4

我自己能够解决问题。正如我所预料的那样,这个问题与我对指针缺少的理解有关。

据我发现,没有办法获得动态数组的大小。因为sizeof(sphereIndices)总是返回4,这是指针的大小而不是数据的大小。这就是为什么glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(sphereIndices), sphereIndices, GL_STATIC_DRAW)只发送4个指数OpenGL的,而不是6

我通过引入额外的变量来跟踪指数的数的解决了这一问题。