HalloweenJack
HalloweenJack

Reputation: 281

VertexBuffer getting the vertices mixed

I'm trying to change from a simple 2D renderer to a batch renderer, it almost works, except for the fact that what seems to be the second call gets the vertices mixed. I tried changing everything, from the Buffer Data and AttribPointer to the VertexCount and the vertices themselves, still getting with the code right now given position (0,0) and size (1,1) a red square but on the second red square that should be drawn over the first I get a red triangle, then on the third the same red square and on the fourth the triangle and so on...

The Shader only gets the location 0 vec2 and gl_Position gets set to that.

#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;
}

Upvotes: 3

Views: 56

Answers (1)

Yakov Galka
Yakov Galka

Reputation: 72539

For the second argument, glBufferSubData expect the offset in bytes. That means that for each six vertices you Add the offset shall be advanced by 6*2*sizeof(float), or equivalently, sizeof(vertices):

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

Upvotes: 4

Related Questions