我正在尝试使用标准 VBO/VAO/EBO 技术在 OpenGL 和 C++ 中渲染由三角形组成的方形网格,但由于某种原因,这些东西无法正确渲染。
我首先根据 gridSideLength 生成网格的顶点和索引
int gridSideLength= 16; // any power of 2
unsigned int gridVBO, gridVAO, gridEBO;
const uint32_t verticesCount = (gridSideLength + 1) * (gridSideLength + 1);
const uint32_t indicesCount = gridSideLength * gridSideLength* 2;
std::vector<glm::vec3> vertices(verticesCount);
std::vector<glm::vec3> indices(indicesCount);
// populate vertices
uint32_t idx = 0;
for (float i = -(gridSideLength / 2); i <= (gridSideLength / 2); ++i) {
for (float j = -(gridSideLength / 2); j <= (gridSideLength / 2); ++j) {
vertices[idx] = glm::vec3((float)j, 0.0f, (float)i);
idx++;
}
}
// populate indices with clockwise winding
idx = 0;
for (int i = 0; i < gridSideLength; ++i) {
int row1 = i * (gridSideLength + 1);
int row2 = (i + 1) * (gridSideLength + 1);
for (int j = 0; j < gridSideLength; ++j) {
indices[idx++] = glm::uvec3(row1 + j, row1 + j + 1, row2 + j + 1);
indices[idx++] = glm::uvec3(row1 + j, row2 + j + 1, row2 + j);
}
}
据我所知,通过打印值,这会生成正确的顶点和索引。
接下来,设置 VBO、VAO 和 EBO 对象
// bind grid VBO, VAO, and EBO
glGenBuffers(1, &gridVBO);
glBindBuffer(GL_ARRAY_BUFFER, gridVBO);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vertices[0]), &vertices[0], GL_STATIC_DRAW);
glGenVertexArrays(1, &gridVAO);
glBindVertexArray(gridVAO);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glGenBuffers(1, &gridEBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gridEBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(indices[0]), &indices[0], GL_STATIC_DRAW);
这对我来说看起来还不错,我可以用它来渲染一些东西,但我不知道。
最后,我的渲染循环:
while (glfwWindowShouldClose(window) == false)
{
glm::mat4 model = glm::mat4(1.0f);
glm::mat4 view = camera.CalculateViewMatrix();
glm::mat4 projection = glm::perspective(glm::radians(camera.getZoom()), (float)SCREEN_WIDTH / (float)SCREEN_HEIGHT, 0.1f, 100.0f);
// ...
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0.05f, 0.05f, 0.05f, 1.0f);
glBindVertexArray(m_GridVAO);
glDrawElements(GL_TRIANGLES, indices.size() * 3, GL_UNSIGNED_INT, 0);
}
不幸的是,我得到的只是一条线,除了把头撞在墙上之外,我不知道从这里该去哪里。有什么明显的错误吗?感谢您的帮助!
顶点索引必须是整数值:
std::vector<glm::vec3> indices(indicesCount);
std::vector<glm::uvec3> indices(indicesCount);