C++ 带有 std::vector 的 VBO
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7173494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBOs with std::vector
提问by Bojangles
I've written a model loader in C++ an OpenGL. I've used std::vector
s to store my vertex data, but now I want to pass it to glBufferData()
, however the data types are wildly different. I want to know if there's a way to convert between std::vector
to the documented const GLvoid *
for glBufferData()
.
我用 C++ 和 OpenGL 编写了一个模型加载器。我已经使用std::vector
s 来存储我的顶点数据,但现在我想将它传递给glBufferData()
,但是数据类型却大不相同。我想知道如果有之间进行转换的方式std::vector
所记录const GLvoid *
的glBufferData()
。
Vertex type
顶点类型
typedef struct
{
float x, y, z;
float nx, ny, nz;
float u, v;
}
Vertex;
vector<Vertex> vertices;
glBufferData() call
glBufferData() 调用
glBufferData(GL_ARRAY_BUFFER, vertices.size() * 3 * sizeof(float), vertices, GL_STATIC_DRAW);
I get the following (expected) error:
我收到以下(预期的)错误:
error: cannot convert ‘std::vector<Vertex>' to ‘const GLvoid*' in argument passing
How can I convert the vector to a type compatible with glBufferData()
?
如何将向量转换为与 兼容的类型glBufferData()
?
NB. I don't care about correct memory allocation at the moment; vertices.size() * 3 * sizeof(float)
will most likely segfault, but I want to solve the type error first.
注意。我现在不在乎正确的内存分配;vertices.size() * 3 * sizeof(float)
很可能会出现段错误,但我想先解决类型错误。
回答by Lightness Races in Orbit
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]
.
如果您有std::vector<T> v
,则可以通过T*
表达式获得指向连续数据(这是 OpenGL 所追求的)开头的&v[0]
。
In your case, this means passing a Vertex*
to glBufferData
:
在您的情况下,这意味着将 a 传递Vertex*
给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.
您可以依赖从这里Vertex*
到void const*
这里的隐式转换;这应该不会造成问题。
回答by Marcelo Cantos
This should do the trick:
这应该可以解决问题:
&vertices[0]
Some prefer &vertices.front()
, but that's more typing and I'm bone lazy.
有些人更喜欢&vertices.front()
,但打字更多,而且我很懒惰。
To be even lazier, you could overload glBufferData
thus:
为了更懒惰,您可以glBufferData
因此重载:
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)
).
并避免错误(您的结构大于3 * sizeof(float)
)。