how to order triangles when exporting obj

2019-09-11 11:27发布

I'm trying to export a mesh into an obj with unity and I found 2 script that does it but the way they export the triangles is quite different and I would like to understand the reason for each one of them:

first:

        foreach(Vector3 lv in m.vertices) 
        {
            Vector3 wv = mf.transform.TransformPoint(lv);

            //This is sort of ugly - inverting x-component since we're in
            //a different coordinate system than "everyone" is "used to".
            sb.Append(string.Format("v {0} {1} {2}\n",-wv.x,wv.y,wv.z));
        }

    foreach(Vector3 lv in m.normals) 
    {
        Vector3 wv = mf.transform.TransformDirection(lv);

        sb.Append}

            for (int i=0;i<triangles.Length;i+=3) 
            {
                //Because we inverted the x-component, we also needed to alter the triangle winding.
                sb.Append(string.Format("f {1}/{1}/{1} {0}/{0}/{0} {2}/{2}/{2}\n", 
                    triangles[i]+1 + vertexOffset, triangles[i+1]+1 + normalOffset, triangles[i+2]+1 + uvOffset));
            }

(I kept the comments), http://wiki.unity3d.com/index.php?title=ObjExporter

this is the first method, and the second below:

foreach(Vector3 vv in m.vertices)
        {
            Vector3 v = t.TransformPoint(vv);
            numVertices++;
            sb.Append(string.Format("v {0} {1} {2}\n",v.x,v.y,-v.z));
        }
        sb.Append("\n");
        foreach(Vector3 nn in m.normals) 
        {
            Vector3 v = r * nn;
            sb.Append(string.Format("vn {0} {1} {2}\n",-v.x,-v.y,v.z));
        }
        for (int i=0;i<triangles.Length;i+=3) {
                sb.Append(string.Format("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\n", 
                    triangles[i]+1+StartIndex, triangles[i+1]+1+StartIndex, triangles[i+2]+1+StartIndex));
            }

link: http://wiki.unity3d.com/index.php?title=ExportOBJ

The first method works perfectly and the second one aswell but it's rotated 180degres in the Up axis. The thing is I don't understand why they need to reorder the triangle components on the first method and still works and why the normal components sign in the second method doesn't match with the position components sign but still works

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-11 12:07

I don't understand why they need to reorder the triangle components

Many renderers use the ordering of triangle points to indicate which side of a polygon is the "front" or "back" of the triangle. That's especially important if back-face culling is enabled.

You can try mixing clockwise and counter-clockwise triangles on a mesh; Unity's default behavior will cull the back faces and you'll end up seeing a bunch of holes!

Flipping an axis or two is fairly common when importing/exporting geometry data. It would be convenient if every file format agreed on that sort of thing, but sometimes they don't.

查看更多
登录 后发表回答