问题
I'm trying to load an object and use VBO and glDrawArrays() to render it. The problem is that a simple float pointer like float f[]={...}
does not work in my case, because I passed the limit of values that this pointer can store. So my solution was to use a vector. And it's not working...
Here is my code:
unsigned int vbo;
vector<float*> vert;
...
vert.push_back(new float(i*size));
vert.push_back(new float(height*h));
vert.push_back(new float(j*size));
...
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vert), &vert, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
and to render:
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, 0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 3);
glDisableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);
I'm having problem on the glBufferData()
where the 3rd parameter is const GLvoid *data
. I'm passing &vert
but It's not working.
回答1:
You want to do:
unsigned int vbo;
vector<float> vert;
...
vert.push_back(i*size);
vert.push_back(height*h);
vert.push_back(j*size);
...
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, vert.size() * sizeof(float), vert.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
It is always good to read the documentation. Also, I would suggest you pick up a good C++ book, which probably would be a good way for you to avoid doing mistakes like these.
回答2:
Remember to check if you have C++11 or vert.data
won't compile.
If you look at the std::vector
doc you'll that std::vector::data()
is tagged with C++11.
http://www.cplusplus.com/reference/vector/vector/data/
If you don't have C++11 you can do the following:
unsigned int vbo;
vector<float> vert;
...
vert.push_back(i*size);
vert.push_back(height*h);
vert.push_back(j*size);
...
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, vert.size(), &vert[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
Taking a reference to the first element of a vector gives you a pointer to the data itself.
来源:https://stackoverflow.com/questions/14234361/opengl-using-vbo-with-stdvector