Search code examples
c++openglglfwglew

glBufferData not working outside main function


I have a problem that I don't know how to solve. I am using C++ with GLEW and GLFW, I initialise GLFW, create the window, make the window the current context, then I initialise GLEW. All of this happens on the main function.

The problem appears when the code to create the VAO and the VBO is organised in methods, in classes, I see that the VAO is generated, that the VBO is generated, but when the data is sent to the GPU, using glBufferData, it does not work. If I take this piece of code and move it in the main function, everything works just fine, but outside it, it does not work.

This code works perfectly on the main function, but if I move it in other functions, just to make things clear, it stops working. So I think the problem is somehow related with that context. I make the window, the current context, on the main function.

Any Idea?

// MAIN FUNCTION

unsigned int vaoID;
glGenVertexArrays(1, &vaoID);
glBindVertexArray(vaoID);

// if I move this code in a method of a class and pass the vao, to bind it again //there it does not work
// if I leave it here, like this, it works
unsigned int vboID;
unsigned int attribPointer = 0;
glGenBuffers(1, &vboID);
glBindBuffer(GL_ARRAY_BUFFER, vboID);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(attribPointer, 3, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

// the drawing part, just the idea, it's in a while, of course.
glBindVertexArray(vaoID);
glEnableVertexAttribArray(attribPointer);
glDrawArrays(GL_TRIANGLES, 0, 6);

glDisableVertexAttribArray(attribPointer);
glBindVertexArray(0);
//if I move it here, it's dead
void storeDataInAttributeList(int attributeNumber, float data[], int vaoID)
    {
        glBindVertexArray(vaoID);
        unsigned int vboID;
        glGenBuffers(1, &vboID);
        vbos.push_back(vboID);
        glBindBuffer(GL_ARRAY_BUFFER, vboID);
        glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW);
        glVertexAttribPointer(attributeNumber, 3, GL_FLOAT, GL_FALSE, 0, 0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);

    }

Solution

  • The problem is here sizeof(data).

    Within your method data is a pointer, and sizeof(data) returns the size of the pointer, not the size of the original array.

    To solve pass the size as a parameter to the method along with the data. Or use a std::vector<float> instead of an array of floats.