2

我正在通过https://learnopengl.com/学习 OpenGL 。从该站点以及我在尝试解决此问题时在互联网上的研究中,我了解到顶点数组对象很有用,因为您可以将其与glBindVertexArray, 和

  1. 将设置任何关联的属性。
  2. 绑定到 GL_ARRAY_BUFFER 的缓冲区将被自动绑定。
  3. 关联的 GL_ELEMENT_ARRAY_BUFFER 也将被自动绑定。

因此,我希望下面的设置代码设置两个顶点数组对象,每个对象都有自己的数组缓冲区,当绑定顶点数组对象时,它们会自动绑定。请注意,这本质上是相同代码的两个副本。此外,这是 Zig 的代码片段,与 C 非常相似。

{
    glGenBuffers(1, &rectangle_vertex_buffer_object);

    glGenBuffers(1, &rectangle_element_buffer_object);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, rectangle_element_buffer_object);
    var fill_indices = [_]u32{ 0, 1, 2, 1, 2, 3 };
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, fill_indices.len * @sizeOf(u32), &fill_indices, GL_STATIC_DRAW);

    glGenVertexArrays(1, &rectangle_vertex_array_object);
    glBindVertexArray(rectangle_vertex_array_object);
    glBindBuffer(GL_ARRAY_BUFFER, rectangle_vertex_buffer_object);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, rectangle_element_buffer_object);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * @sizeOf(f32), @intToPtr(*allowzero c_void, 0));
    glEnableVertexAttribArray(0);
    glBindVertexArray(0);
}

{
    glGenBuffers(1, &glyph_vertex_buffer_object);

    glGenBuffers(1, &glyph_element_buffer_object);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, glyph_element_buffer_object);
    var fill_indices = [_]u32{ 0, 1, 2, 1, 2, 3 };
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, fill_indices.len * @sizeOf(u32), &fill_indices, GL_STATIC_DRAW);

    glGenVertexArrays(1, &glyph_vertex_array_object);
    glBindVertexArray(glyph_vertex_array_object);
    glBindBuffer(GL_ARRAY_BUFFER, glyph_vertex_buffer_object);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, glyph_element_buffer_object);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * @sizeOf(f32), @intToPtr(*allowzero c_void, 0));
    glEnableVertexAttribArray(0);
    glBindVertexArray(0);
}

我有一个绘制矩形的功能:

pub fn fillRectangle(x: f32, y: f32, width: f32, height: f32) void {
    var flip_y = -y;
    glBindVertexArray(rectangle_vertex_array_object);
    // glBindBuffer(GL_ARRAY_BUFFER, rectangle_vertex_buffer_object); -- Stuff works if I uncomment this line.
    const vertices = [_]f32{
        x,         flip_y,
        x + width, flip_y,
        x,         flip_y - height,
        x + width, flip_y - height,
    };
    glBufferData(GL_ARRAY_BUFFER, vertices.len * @sizeOf(f32), &vertices, GL_STATIC_DRAW);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, @intToPtr(*allowzero c_void, 0));
    glBindVertexArray(0);
}

如果我显式调用glBindBufferafter glBindVertexArray,那么该函数就可以正常工作,但如果我删除它,那么我会得到GL_INVALID_OPERATION in glBufferData(no buffer bound). 但是,我希望glBindVertexArray调用绑定适当的缓冲区。

帮助!

4

0 回答 0