Reputation: 982
I want to implement functionality so that i can add/remove vertices to/from a vertex array during runtime. Is there a common way of doing this?
The recommended format for vertex data seems to be C arrays of structs, so i've tried the following. Keep a pointer to an array of Vertex structs as property:
@property Vertex *vertices;
and then make a new array and copy the data over
- (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;
}
but no luck. I'm not exactly confident in C so probably this is really trivial..
Upvotes: 1
Views: 1218
Reputation: 982
here's how i do it now:
// 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);
i suppose icnivad's method above is more flexible since you can do more stuff with a NSMutableArray, but using plain C arrays with malloc/realloc should be (much?) faster .
Upvotes: 0
Reputation: 6903
This is how I just did it:
//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];
}
Upvotes: 1