苹果正在讨论避免创建"数组结构体"而更倾向于"结构体数组"以获得更好的内存性能。
在下面的例子中,我们创建了一个巨大的彩色矩形网格(32 x 48个矩形,每个10 x 10大)。这是生成一个"数组结构"吗?我只是想知道我的周末会有多糟糕…
- (void)drawFrame {
// draw grid
for (int i = 0; i < numRectangles; i++) {
// ... calculate CGPoint values for vertices ...
GLshort vertices[ ] = {
bottomLeft.x, bottomLeft.y,
bottomRight.x, bottomRight.y,
topLeft.x, topLeft.y,
topRight.x, topRight.y
};
glVertexPointer(2, GL_SHORT, 0, vertices);
glColor4f(r, g, b, 1);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
}
这只是一个循环,为一个矩形创建一个坐标数组。你没有涉及结构体。他们特别讨论的是插值顶点、颜色和纹理坐标。因为你只是设置颜色和传递顶点,没有插值要做。
如果你的网格坐标是恒定的,你可以通过在初始化过程中一次性填充所有顶点的大数组来提高性能。
你可以增加first
参数glDrawArrays步进数组和绘制单独的矩形,简化内存操作在你的渲染循环(因为你已经有顶点数组为每个渲染调用)。
// assuming you know the numbers beforehand
// also you should probably put this in a property
GLshort gridVerts[numRectangles][8];
- (void)init() {
for (int i = 0; i < numRectangles; i++) {
// calculate the vertices
GLshort vertices[] = {
bottomLeft.x, bottomLeft.y,
bottomRight.x, bottomRight.y,
topLeft.x, topLeft.y,
topRight.x, topRight.y
};
memcpy(&gridVerts[i][0], vertices, sizeof(GLshort) * 8));
}
}
- (void)drawFrame() {
glVertexPointer(2, GL_SHORT, 0, gridVerts);
for (int i = 0; i < numRectangles; i++) {
// calculate the color for this iteration
glColor4f(r, g, b, 1);
glDrawArrays(GL_TRIANGLE_STRIP, i * 4, 4);
}
}
为了回答关于结构体数组的原始问题,opengl中的顶点缓冲有一个例子。