glDrawElements没有绘图

时间:2016-12-28 11:06:21

标签: c++ opengl drawing render

我使用以下代码创建缓冲区:

//generate buffers
glGenVertexArrays(1, &VAO);
//glGenBuffers(1, &EBO);
glGenBuffers(1, &VBO_vertices);
glGenBuffers(1, &VBO_colors);
glGenBuffers(1, &VBO_normals);

// Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
glBindVertexArray(VAO);

// Copy our vertices array in a buffer for OpenGL to use
glBindBuffer(GL_ARRAY_BUFFER, VBO_vertices);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*vertices.size(), &vertices[0], GL_STATIC_DRAW);


glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, vTable.size() * sizeof(int), &vTable[0], GL_STATIC_DRAW);

// Position attribute
glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0); //size = 3 (X,Y,Z)
glEnableVertexAttribArray(0);


//Buffer for color
glBindBuffer(GL_ARRAY_BUFFER, VBO_colors);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*vertices.size(), &v_color[0], GL_STATIC_DRAW);

// Color attribute
glVertexAttribPointer((GLuint)1, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0); //size = 3 (R,G,B)
glEnableVertexAttribArray(1);


//Buffer for normals
glBindBuffer(GL_ARRAY_BUFFER, VBO_normals);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*vertices.size(), &v_normals[0], GL_STATIC_DRAW);

//normal attribute
glVertexAttribPointer((GLuint)2, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0); //size = 3 (R,G,B)
glEnableVertexAttribArray(2);


// Unbind the VAO
glBindVertexArray(0);

我的数据是:

vector<vec3> vertices, v_normals,v_color;
vector<int> vTable;

我有每个顶点的顶点,法线和颜色以及一个带有每个三角形的索引顶点的索引表。

当我尝试渲染时,窗口上没有任何内容。

glBindVertexArray(VAO); //Bind VAO
glDrawElements(GL_TRIANGLES, vTable.size(), GL_UNSIGNED_INT, &vTable[0]);
glBindVertexArray(0); //Unbind VAO

如果我用过这个:

glDrawArrays(GL_TRIANGLES,0,vTable.size());

它绘制的东西只是一个不完整的对象,就像链接图像一样。

image

有人知道会发生什么吗?提前致谢

1 个答案:

答案 0 :(得分:2)

您的 glDrawElements 调用错误,最后一个参数应该是保存索引的GL_ELEMENT_ARRAY_BUFFER的字节偏移量,而不是指向系统内存的指针。

glDrawElements(GL_TRIANGLES, vTable.size(), GL_UNSIGNED_INT, 0);