VBOs with std::vector

允我心安 提交于 2019-11-27 00:27:33

If you have a std::vector<T> v, you may obtain a T* pointing to the start of the contiguous data (which is what OpenGL is after) with the expression &v[0].


In your case, this means passing a Vertex* to glBufferData:

glBufferData(
   GL_ARRAY_BUFFER,
   vertices.size() * sizeof(Vertex),
   &vertices[0],
   GL_STATIC_DRAW
);

Or like this, which is the same:

glBufferData(
   GL_ARRAY_BUFFER,
   vertices.size() * sizeof(Vertex),
   &vertices.front(),
   GL_STATIC_DRAW
);

You can rely on implicit conversion from Vertex* to void const* here; that should not pose a problem.

This should do the trick:

&vertices[0]

Some prefer &vertices.front(), but that's more typing and I'm bone lazy.

To be even lazier, you could overload glBufferData thus:

template <class T>
inline void glBufferData(GLenum target, const vector<T>& v, GLenum usage) {
    glBufferData(target, v.size() * sizeof(T), &v[0], usage);
}

Then you can write:

glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);

and also avoid bugs (your struct is bigger than 3 * sizeof(float)).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!