【问题标题】:Are these rectangles created as a "struct of arrays" or as an "array of structs"?这些矩形是作为“数组结构”还是“结构数组”创建的?
【发布时间】:2011-12-01 07:33:44
【问题描述】:

Apple 正在谈论 avoiding creating a "struct of arrays" and preferring "array of structs" 以获得更好的内存性能。

在下面的示例中,我们创建了一个巨大的彩色矩形网格(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);
    }
}

【问题讨论】:

    标签: iphone ios opengl-es


    【解决方案1】:

    这只是一个循环,为一个矩形创建一组坐标。你不涉及结构。他们专门讨论插入顶点、颜色和纹理坐标。由于您只是设置颜色并仅传递顶点,因此无需进行插值。

    如果您的网格坐标是恒定的,您可以通过在初始化期间用所有顶点填充一个大型数组来看到性能提升。

    然后您可以将 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);
        }
    }
    

    为了回答关于结构数组的原始问题,Vertex Buffers in opengl 有一个示例。

    【讨论】:

    • 在这种情况下,您是否建议使用顶点缓冲区对象?使用 VBO 和您描述的方法有什么区别?每次循环迭代都会改变颜色(只是去掉了那部分以简化它)。
    • 如果你的循环总是以相同的顶点和颜色结束,那么每帧都重新生成它们是非常浪费的。在这种情况下 - 您需要打包颜色和顶点。 Apple 的“结构数组”建议将很有用,我可以向您展示如何做到这一点:) 即使您使用的是 VBO,您也需要先将数据全部打包到一个数组中。
    • 谢谢!我总是使用相同的几何图形(基本上是矩形网格)但颜色不同。每次迭代时颜色都会发生变化。我想“结构数组”不会有用,对吧?我的意思是实际上我只想在每次迭代之后修改每个矩形的颜色,而不是几何形状。一个有两个矩形的简单例子会很棒!很难找到像这样简化的东西:-)
    • 在这种情况下,您实际上可能希望像 Apple 所建议的那样保留两个单独的数组 - 这样您就可以省去重新生成顶点结构的麻烦。您可以采用任何一种方式,具体取决于您的 CPU 或 GPU 在渲染循环期间受到的伤害更大(一种方式需要在 CPU 端进行额外的内存操作,另一种方式可能会在 GPU 上进行渲染期间造成更多的缓存命中)。跨度>
    • 编辑了我的答案,类似于我的意思,即预先计算顶点并在每一帧重用数组。这(丑陋的 C)不一定是为您的目的分配和填充数组的最佳方式(例如,您可以使用 C++ STL 数组来存储顶点)。您可以将此数组放入 VBO,但这是另一个话题。
    猜你喜欢
    • 1970-01-01
    • 2013-08-02
    • 2020-03-03
    • 2015-01-05
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多