Converting quadriladerals in an OBJ file into triangles?

后端 未结 2 1024
无人共我
无人共我 2020-12-05 05:24

At first, it seemed obvious... Make 2 triangles per face wherever 4 indices were found, right?
Meaning, the following:

v 1.000000 1.000000 0.000000
v -1.         


        
相关标签:
2条回答
  • 2020-12-05 06:01

    Writing my own obj loader and reading the spec very carefully, the details on the 'f' parameter are very vague, especially seeing some files contain 'f' lines with > 4 arguments on them.

    Turns out that these are actually a triangle strip in an odd order. Correct conversion to triangles is as follows (psuedo code):

    n = 0;
    triangles[n++] = [values[0], values[1], values[2]];
    for(i = 3; i < count(values); ++i)
      triangles[n++] = [
        values[i - 3],
        values[i - 1],
        values[i]
      ];
    

    Example:

    f: A B C D E F G
    

    Would be the following 5 triangles:

    A B C
    A C D
    B D E
    C E F
    D F G
    
    0 讨论(0)
  • 2020-12-05 06:19

    If you have 4 indices, e.g.:

    0 1 2 3
    

    The division into two triangles would be one with the first 3 indices, and one with the first, third, and fourth. In this example:

    0 1 2
    0 2 3
    

    Let's try some ASCII art to illustrate this:

    3-------2
    |      /|
    |    /  |
    |  /    |
    |/      |
    0-------1
    

    Here you see 0 1 2 3 as the quad, 0 1 2 as the first triangle (bottom-right), and 0 2 3 as the second triangle (top left).

    More generally, for faces with n vertices, you generate triangles:

    0 (i) (i + 1)  [for i in 1..(n - 2)]
    

    If you don't insist on separate triangles, you can also use GL_TRIANGLE_FAN primitives, which are still in core OpenGL. That way, you can draw any convex polygon with a triangle fan, using the original sequence of indices. So a triangle fan with vertex sequence 0 1 2 3 describes the quad in this case, and it very easily generalizes to faces with more than 4 vertices.

    Edit: Since you still appear to have problems, let's see how this applies to the example in your post. I'll list the original index sequence of the quad for each face, and the index sequence for the two triangles after splitting the quad.

    f 1 2 3 4 --> (1 2 3) (1 3 4)
    f 8 7 6 5 --> (8 7 6) (8 6 5)
    f 4 3 7 8 --> (4 3 7) (4 7 8)
    f 5 1 4 8 --> (5 1 4) (5 4 8)
    f 5 6 2 1 --> (5 6 2) (5 2 1)
    f 2 6 7 3 --> (2 6 7) (2 7 3)
    

    That looks correct to me when I draw the cube. Remember to subtract 1 from the indices for your use, since these are 1-based indices, and you will almost certainly need 0-based indices.

    0 讨论(0)
提交回复
热议问题