我的VAO没有正确绑定我遇到了一些麻烦(至少那是我认为发生的事情)。
所以,我正在做的是我有一个类从一些原始数据创建一个vbo和vao,在这种情况下是一个指向浮点数组的指针。
RawModel* Loader::loadToVao(float* positions, int sizeOfPositions) {
unsigned int vaoID = this->createVao();
this->storeDataInAttributeList(vaoID, positions, sizeOfPositions);
this->unbindVao();
return new RawModel(vaoID, sizeOfPositions / 3);
}
unsigned int Loader::createVao() {
unsigned int vaoID;
glGenVertexArrays(1, &vaoID);
glBindVertexArray(vaoID);
unsigned int copyOfVaoID = vaoID;
vaos.push_back(copyOfVaoID);
return vaoID;
}
void Loader::storeDataInAttributeList(unsigned int attributeNumber, float* data, int dataSize) {
unsigned int vboID;
glGenBuffers(1, &vboID);
glBindBuffer(GL_ARRAY_BUFFER, vboID);
glBufferData(GL_ARRAY_BUFFER, dataSize * sizeof(float), data, GL_STATIC_DRAW);
glVertexAttribPointer(attributeNumber, 3, GL_FLOAT, false, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
unsigned int copyOfVboID = vboID;
vbos.push_back(copyOfVboID);
}
void Loader::unbindVao() {
glBindVertexArray(0);
}
RawModel只是一个应该接收浮点数组并创建vbo和vao的类。我正在使用的向量vbos
和vaos
就是为了跟踪所有id,以便在完成所有数据后我可以删除它们。
我90%确信这一切都能正常运作。但是,当我尝试运行一些可以绘制它的代码时,OpenGL正在退出,因为它试图从地址0x0000000读取并且它不喜欢它。我将我之前创建的原始模型传递给我的渲染器中的函数,如下所示:
void Renderer::render(RawModel* model) {
glBindVertexArray(model->getVaoID());
glEnableVertexAttribArray(0);
glDrawArrays(GL_TRIANGLES, 0, model->getVertexCount());
glDisableVertexAttribArray(0);
glBindVertexArray(0);
}
我已经检查过以确保当我创建vao时,以及当我尝试检索vao时,VoID是相同的。它实际上是一样的。
我不知道如何读取当前存储在OpenGL当前绑定为顶点属性数组的任何地址,因此我无法测试它是否指向顶点数据。我很确定它出于某种原因指向地址0。
事实证明,这不是硬编码的0是一个问题。它删除了Visual Studio和OpenGL给我的错误,但实际错误是在其他地方。我意识到我在上面的一些代码中传入vaoID
作为attributeNumber
,当我应该传入一个硬编码的0.我在这里编辑了我的代码:
RawModel* Loader::loadToVao(float* positions, int sizeOfPositions) {
unsigned int vaoID = this->createVao();
this->storeDataInAttributeList(0, positions, sizeOfPositions);
this->unbindVao();
return new RawModel(vaoID, sizeOfPositions / 3);
}
我将行this->storeDataInAttributeList(vaoID, positions, sizeOfPositions);
更改为您在上面看到的内容,使用硬编码的0.因此,事实证明我甚至没有将数组绑定到vbo中的正确位置。但是,在改变之后,它运作良好。
您应该使用glVertexAttribPointer
,glEnableVertexAttribArray
和glDisableVertexAttribArray
的顶点属性索引,但你得到的是:
glVertexAttribPointer
一起使用0
和glEnableVertexAttribArray
一起使用的硬编码glDisableVertexAttribArray
(如果您确定该值,这不一定是一个bug)如果您不确定索引值(例如,如果未在着色器中指定布局),则可以使用glGetAttribLocation
调用来获取它:
// The code assumes `program` is created with glCreateProgram
// and `position` is the attribute name in your vertex shader
const auto index = glGetAttribLocation(program, "position");
然后你可以使用index
与上面提到的电话。