OpenGL using std::vector with glm::vec3

a_learner picture a_learner · Jan 25, 2015 · Viewed 12.5k times · Source

I'm having the following issue.

I've loaded 8 glm::vec3 into a std::vector, such that:

std::vector <glm::vec3> vertices;

returns:

0.250000 -0.250000 -0.250000
0.250000 -0.250000 0.250000
-0.250000 -0.250000 0.250000
-0.250000 -0.250000 -0.250000
0.250000 0.250000 -0.250000
0.250000 0.250000 0.250000
-0.250000 0.250000 0.250000
-0.250000 0.250000 -0.250000

if:

for(int i{0}; i<8; i++){
    std::cout<<"\n";
    for(int j{0}; j<3; j++){
    std::cout<<vertices[i][j]<<" ";
    }
}

When I pass the following code into OpenGL,

glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * vertices.size(), &vertices[0],  GL_DYNAMIC_DRAW);  

glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); 

glBindVertexArray(buffer);  

my shader program loads and the window opens, however there is no cube.

A slight alteration to the first line,

glBufferData(GL_ARRAY_BUFFER, sizeof(vert), &vert, GL_DYNAMIC_DRAW); //Here

glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

glBindVertexArray(buffer); 

while taking vectors from,

const GLfloat vert[9] =
{-0.5,-0.5, 0.0,
  0.0, 0.5, 0.0,
  0.5,-0.5, 0.0};

and a pretty red triangle is drawn onto the screen.

My question: Is it possible to use a vector container in combination with glm? If so, how can it be implemented?
My hypothesis:The glVertexAttribPointer function is reading sequentially from the starting address of the vertices container. The elements of the vertices container are fragmented throughout my memory.

Answer

Axalo picture Axalo · Jan 25, 2015

In your glBufferData() &vertices[0] should probably have been, &vertices[0].x.
That's because &vertices[0] points to a glm::vec3 but you want it to point to a float
because that's what OpenGL expects.