如何在OpenGL中正确地加载OBJ文件格式的数据?写出c++具体代码
时间: 2024-11-20 07:55:30 浏览: 116
在OpenGL中加载OBJ文件格式的数据通常需要经过几个步骤:解析文件、处理顶点和纹理坐标,以及构建模型矩阵。下面是一个简单的C++示例,使用Tiny OBJ Loader库来帮助解析OBJ文件:
```cpp
#include <tiny_obj_loader.h>
#include <GL/glut.h>
// 创建顶点数组对象
unsigned int vao;
void loadObj(const char* objFile) {
// 使用Tiny OBJ Loader解析文件
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::string err;
if (!tinyobj::LoadObj(&attrib, &shapes, &err, objFile)) {
fprintf(stderr, "Error: %s\n", err.c_str());
return;
}
// 遍历形状并创建VBOs
unsigned int vboMesh[3] = {0};
for (const auto& shape : shapes) {
const tinyobj::shape_t& shapeIt = shape;
if (shapeIt.mesh.indices.size() > 0) {
glGenBuffers(1, &vboMesh[0]); // 索引缓冲区
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboMesh[0]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, shapeIt.mesh.indices.size() * sizeof(int), shapeIt.mesh.indices.data(), GL_STATIC_DRAW);
// 顶点缓冲区
glGenBuffers(1, &vboMesh[1]);
glBindBuffer(GL_ARRAY_BUFFER, vboMesh[1]);
glBufferData(GL_ARRAY_BUFFER, shapeIt.mesh.positions.size() * sizeof(float), shapeIt.mesh.positions.data(), GL_STATIC_DRAW);
// 其他如UVs、 normals等类似处理
// 分配VAO
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glEnableVertexAttribArray(0); // position
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(tinyobj::vec3_t), (void*)offsetof(tinyobj::shape_t, mesh.positions));
// ...其他attribute处理
}
}
// 之后你可以绑定VAO来绘制模型
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutCreateWindow("Load OBJ");
glEnable(GL_DEPTH_TEST);
loadObj("path_to_your_obj_file.obj"); // 替换为你的OBJ文件路径
// ... 进行渲染和事件处理
return glutMainLoop();
}
```
这个例子假设你已经包含了Tiny OBJ Loader库,并且对OpenGL的基本操作有所了解。别忘了替换`"path_to_your_obj_file.obj"`为你的实际OBJ文件路径。
阅读全文
相关推荐















