简体   繁体   English

OpenGL-添加顶点

[英]OpenGL - add vertices

I have a subfunction that reads a data stream and creates an array of vertex data based on that. 我有一个子函数,它读取数据流并基于该子函数创建一个顶点数据数组。 The main function calls this subfunction repeatedly and updates the vertex data array, which is then bound to a buffer and drawn. 主函数反复调用此子函数并更新顶点数据数组,然后将其绑定到缓冲区并绘制。 So far, so good. 到现在为止还挺好。 However, I cannot figure out how to add vertices. 但是,我不知道如何添加顶点。 C++ does not let you reassign or resize entire arrays. C ++不允许您重新分配或调整整个数组的大小。 I can't use vectors because the OpenGL functions take in arrays, not vectors. 我不能使用向量,因为OpenGL函数采用数组而不是向量。

You can use vectors to populate an OpenGL vertex buffer. 您可以使用向量来填充OpenGL顶点缓冲区。 The values in a vector are guaranteed to be contiguous. vector中的值保证是连续的。 See for example these discussions for details on the related language standards: 例如,请参阅以下讨论以获取有关语言标准的详细信息:

This means that code like the following is safe: 这意味着下面的代码是安全的:

std::vector<GLfloat> vertexPositions;
// Populate vector with vertex positions.
GLuint bufId = 0;
glGenBuffers(1, &bufId);
glBindBuffer(GL_ARRAY_BUFFER, bufId);
glBufferData(GL_ARRAY_BUFFER, vertexPositions.size() * sizeof(GLfloat),
             &vertexPositions[0], GL_STATIC_DRAW);

The subtle but critical part is that you pass in the address of the first element of the vector, not the address of the vector object. 微妙但关键的部分是您传入向量的第一个元素的地址,而不是向量对象的地址。

I would make a slight edit. 我会稍作修改。 While you can use &vertexPositions[0] as the address of the beginning of an STL vector, I prefer to use the function designed to return the address of the beginning of the vector memory, vertexPositions.data(). 虽然您可以将&vertexPositions [0]用作STL向量的开始地址,但我更喜欢使用旨在返回向量存储器的开始地址的函数vertexPositions.data()。

std::vector<GLfloat> vertexPositions;
// Populate vector with vertex positions.
GLuint bufId = 0;
glGenBuffers(1, &bufId);
glBindBuffer(GL_ARRAY_BUFFER, bufId);
glBufferData(GL_ARRAY_BUFFER, vertexPositions.size() * sizeof(GLfloat), vertexPositions.data(), GL_STATIC_DRAW);

I use STL vectors for OGL data for a number of reasons. 由于多种原因,我将STL向量用于OGL数据。 It's easy to preallocate if you know the size, and they will grow (and stay contiguous) when you add items. 如果您知道大小,则可以轻松进行预分配,并且在添加项目时它们会增长(并保持连续)。 They are easy to iterate through. 它们很容易迭代。 You can easily create vectors of structures if you want to pass in interleaved data. 如果要传递交错数据,则可以轻松创建结构的向量。 It all works the same. 一切都一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM