Skip to content

09.索引缓冲区

绘制正方形

C++
/* 添加顶点绘制正方形 */
float positions[] = {
    -0.5f, -0.5f,
     0.5f, -0.5f,
     0.5f,  0.5f,

     0.5f,  0.5f,
    -0.5f,  0.5f,
    -0.5f, -0.5f,
};

glBufferData(GL_ARRAY_BUFFER, 6 * 2 * sizeof(float), positions, GL_STATIC_DRAW);

glDrawArrays(GL_TRIANGLES, 0, 6);

效果:

使用索引缓冲区

C++
/* 在复制顶点数据,为了减少内存复制,需要用到索引缓冲区,以允许重用顶点 */
float positions[] = {
    -0.5f, -0.5f, // 0
     0.5f, -0.5f, // 1
     0.5f,  0.5f, // 2

     0.5f,  0.5f,
    -0.5f,  0.5f, // 3
    -0.5f, -0.5f,
};
/* 索引缓冲区 */
unsigned int indices[] = {
    0, 1, 2,
    2, 3, 0
};
unsigned int ibo;
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * sizeof(unsigned int), indices, GL_STATIC_DRAW);

glDrawArrays(GL_TRIANGLES, 0, 6);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);