Why is my OBJ parser rendering meshes like this?

北战南征 提交于 2019-11-27 05:13:35
Reto Koradi

I haven't downloaded your project. What people mostly struggle with when writing OBJ import code for rendering with OpenGL is the indices. And as @ratched_freak also suspects in his comment, that's very consistent with the visual appearance of your cube.

The OBJ format uses separate indices for positions, normals, and texture coordinates. For OpenGL rendering, you need a single set of indices. This means that you need to generate a vertex for each unique combination of position/normal/texture indices used by triangles in the OBJ file, assign a new index to the combination, and then use that index in your OpenGL index buffer.

I wrote an answer with pseudo-code that outlines how to do this for a similar question recently: OpenGL - Index buffers difficulties.

Edit, to illustrate the problem some more. Here is a "cube" file I found online:

v  0.0  0.0  0.0
v  0.0  0.0  1.0
v  0.0  1.0  0.0
v  0.0  1.0  1.0
v  1.0  0.0  0.0
v  1.0  0.0  1.0
v  1.0  1.0  0.0
v  1.0  1.0  1.0

vn  0.0  0.0  1.0
vn  0.0  0.0 -1.0
vn  0.0  1.0  0.0
vn  0.0 -1.0  0.0
vn  1.0  0.0  0.0
vn -1.0  0.0  0.0

f  1//2  7//2  5//2
f  1//2  3//2  7//2 
f  1//6  4//6  3//6 
f  1//6  2//6  4//6 
f  3//3  8//3  7//3 
f  3//3  4//3  8//3 
f  5//5  7//5  8//5 
f  5//5  8//5  6//5 
f  1//4  5//4  6//4 
f  1//4  6//4  2//4 
f  2//1  6//1  8//1 
f  2//1  8//1  4//1 

The file has 8 positions (v records) and 6 normal (vn records). The f records are faces, triangles in this case. Looking at the first triangle vertex, 1//2 tells you that the vertex uses position 1 and normal 2. When using OpenGL index arrays, you can't have separate indices for positions and normals. So we create a vertex for this position/normal pair, and assign it the first available index. Same for 7//2 and 5//2, so we now have 3 OpenGL vertices (indices 0, 1, and 2).

Now on the second triangle, we find 1//2 again. We already created a vertex for this combination, so we can use our vertex 0 again. 3//2 is new, so we create a new vertex (index 3) for it. 7//2 we saw previously, it's the same as our vertex 1.

So we ended up with 4 OpenGL vertices for the fist 2 triangles. Which makes sense, since the two triangles describe one face of the cube, and we need 4 vertices for a square.

If you continue this process for the whole example, you will end up with 24 vertices you can store in an OpenGL vertex buffer, and an index buffer with 36 entries (12 triangles with 3 corners each).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!