Vertexbuffer混合了顶点

VertexBuffer getting the vertices mixed

本文关键字:顶点 混合 Vertexbuffer      更新时间:2023-10-16

我正在尝试从简单的2D渲染器更改为批处理渲染器,它几乎有效,除了似乎是第二个呼叫的事实使顶点混合在一起。我尝试更改所有内容,从缓冲区数据和属性转换为顶点和顶点本身,现在仍然可以使用代码,现在给定的位置(0,0(和大小(1,1(一个红色正方形,但在第二个红色正方形上,应该在第一个我得到一个红色三角形的情况下绘制,然后在第三个红色正方形,在第四个三角形等等。

着色器仅获取位置0 vec2,gl_position设置为。

#define RENDERER_MAX_SPRITES 10000
#define RENDERER_SPRITE_SIZE (sizeof(float) * 2)
#define RENDERER_BUFFER_SIZE (RENDERER_SPRITE_SIZE * 6 * RENDERER_MAX_SPRITES)
void BatchRenderer::Initialize() {
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, RENDERER_BUFFER_SIZE, nullptr, GL_DYNAMIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, RENDERER_SPRITE_SIZE, (void*)0);
    glBindVertexArray(0);
}
void BatchRenderer::Add(iVec2 position, iVec2 size, Color& color, Texture& texture) {
    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    float vertices[12] = {
        position.x,          position.y,         
        position.x,          position.y + size.y,
        position.x + size.x, position.y + size.y,
        position.x + size.x, position.y + size.y,
        position.x + size.x, position.y,         
        position.x,          position.y      
    };
    glBufferSubData(GL_ARRAY_BUFFER, VertexSum, sizeof(vertices), &vertices);
    VertexSum += 12;
    VertexCount += 6;
    glBindVertexArray(0);
}
void BatchRenderer::Flush() {
    shader.Use();
    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glDrawArrays(GL_TRIANGLES, 0, VertexCount);
    glBindVertexArray(0);
    VertexCount = 0;
    VertexSum = 0;
}

对于第二个参数, glBufferSubData期望字节中的偏移。这意味着,对于您Add的每个六个顶点,偏移量应由6*2*sizeof(float)提出,或等效于sizeof(vertices)

glBufferSubData(GL_ARRAY_BUFFER, VertexSum, sizeof(vertices), &vertices);
VertexSum += sizeof(vertices);
VertexCount += 6;