2011-04-20 79 views
1

我想实现功能,以便我可以在运行时向顶点数组添加/移除顶点。 有没有这样做的常见方法?OpenGL ES - 更新顶点数组,添加/删除顶点

顶点数据的推荐格式似乎是C数组的结构, 所以我试了下面。保持一个指向顶点结构数组财产:

@property Vertex *vertices; 

,然后作出一个新的阵列和在

- (void) addVertex:(Vertex)newVertex 
{ 
    int numberOfVertices = sizeof(vertices)/sizeof(Vertex); 
    Vertex newArray[numberOfVertices + 1]; 

    for (int i = 0; i < numberOfVertices; i++) 
     newArray[i] = vertices[i]; 

    newArray[numberOfVertices] = newVertex; 
    self.vertices = newArray; 
} 

,但没有运气的数据复制。我不是在C究竟有信心所以很可能这真是小巫见大巫..

回答

1

这是怎么了我只是做了它:

//verts is an NSMutableArray and I want to have an CGPoint c array to use with 
// glVertexPointer(2, GL_FLOAT, 0, vertices);... so: 

CGPoint vertices[[verts count]]; 
for(int i=0; i<[verts count]; i++) 
{ 
    vertices[i] = [[verts objectAtIndex:i] CGPointValue]; 
} 
0

这里就是我现在就这样做:

// re-allocate the array dynamically. 
// realloc() will act like malloc() if vertices == NULL 
Vertex newVertex = {{x,y},{r,g,b,a}}; 
numberOfVertices++; 
vertices = (Vertex *) realloc(vertices, sizeof(Vertex) * numberOfVertices); 
if(vertices == NULL) NSLog(@"FAIL allocating memory for vertex array"); 
else vertices[numberOfVertices - 1] = newVertex; 

// clean up memory once i don't need the array anymore 
if(vertices != NULL) free(vertices); 

我假设icnivad的上面的方法更灵活,因为你可以用NSMutableArray做更多的事情,但使用带有malloc/realloc的普通C数组应该(更快?)。