Advertisement
artemisart

Unity3d_OBJ_ImportExport

Oct 6th, 2012
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.96 KB | None | 0 0
  1. public enum SaveFormat {
  2.     OBJ,
  3.     QMO
  4. }
  5. public enum LoadFormat {
  6.     Auto,
  7.     OBJ,
  8.     QMO
  9. }
  10.  
  11. public static class ImportExport {
  12.        
  13.     public static string SaveToText (this Mesh mesh, SaveFormat sFormat = SaveFormat.OBJ) {
  14.         StringBuilder text = new StringBuilder ();
  15.            
  16.         if (sFormat == SaveFormat.OBJ) {
  17.             text.AppendFormat("# ModelisaTools exported obj file\n\no {0}\n\n", mesh.name);
  18.                
  19.             foreach (Vector3 v in mesh.vertices) {
  20.                 text.AppendFormat ("v {0} {1} {2}\n", v.x, v.y, v.z);
  21.             }
  22.  
  23.             text.Append ("\n");
  24.  
  25.             foreach (Vector3 u in mesh.uv) {
  26.                 text.AppendFormat ("vt {0} {1}\n", u.x, u.y);
  27.             }
  28.  
  29.             text.Append ("\n");
  30.  
  31.             foreach (Vector3 n in mesh.normals) {
  32.                 text.AppendFormat ("vn {0} {1} {2}\n", n.x, n.y, n.z);
  33.             }
  34.                
  35.             text.Append ("\ns off\n\n"); // smoothing group, but unity doesn't support it
  36.                
  37.             for (int i = 0; i < mesh.triangles.Length; i += 3) {
  38.                 text.AppendFormat ("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\n", mesh.triangles[i]+1, mesh.triangles[i+1]+1, mesh.triangles[i+2]+1);
  39.             }
  40.         }
  41.            
  42.         if (sFormat == SaveFormat.QMO) {
  43.             throw new NotImplementedException ();
  44.         }
  45.            
  46.         return text.ToString ();
  47.     }
  48.        
  49.     // path = the path where the file will be created, WITHOUT THE EXTENSION
  50.     public static void SaveToFile (this Mesh mesh, string path, SaveFormat sFormat = SaveFormat.OBJ, bool overwrite = false) {
  51.         path = path + '.' + sFormat.ToString ().ToLower ();
  52.  
  53.         try {
  54.             if (!File.Exists (path) || overwrite) {
  55.                 File.WriteAllText (path, mesh.SaveToText (sFormat));
  56.             }
  57.             else {
  58.                 Debug.LogWarning ("This file already exists, can't save mesh : " + mesh.name + ", or set overwrite to true.\n@" + path);
  59.             }
  60.         }
  61.         catch (Exception ex) {
  62.             Debug.LogWarning ("Exception while saving mesh : " + mesh.name + "\n@ " + path + "\nex: " + ex);
  63.         }
  64.     }
  65.  
  66.     // path = the path were the mesh will be loaded, WITH THE EXTENSION if lFormat is AUTO, and WITHOUT if lFormat is : OBJ, QMO
  67.     public static void LoadFromFile (this Mesh mesh, string path, LoadFormat lFormat = LoadFormat.Auto) {
  68.         if (lFormat != LoadFormat.Auto) {
  69.             path = path + '.' + lFormat.ToString ().ToLower ();
  70.         }
  71.  
  72.         try {
  73.             if (File.Exists (path)) {
  74.                 string extension = Path.GetExtension (path);
  75.                 LoadFormat format;
  76.                 if (extension == ".obj") {
  77.                     format = LoadFormat.OBJ;
  78.                 }
  79.                 else if (extension == ".qmo") {
  80.                     format = LoadFormat.QMO;
  81.                 }
  82.                 else {
  83.                     format = LoadFormat.Auto;
  84.                 }
  85.                 mesh.LoadFromStream (File.OpenText (path), format);
  86.             }
  87.             else {
  88.                 Debug.LogWarning ("This file doesn't exists, can't load mesh @ " + path);
  89.             }
  90.         }
  91.         catch (Exception ex) {
  92.             Debug.LogWarning ("Exception while loading mesh : " + mesh.name + "\n@ " + path + "\nex: " + ex);
  93.         }
  94.     }
  95.  
  96.     public static void LoadFromStream (this Mesh mesh, TextReader reader, LoadFormat lFormat) {
  97.         string line;
  98.         int lineNumber = 0;
  99.         string[] datas;
  100.         Vector3 tempVector3;
  101.         Vector2 tempVector2;
  102.         List<Vector3> vertices = new List<Vector3> ();
  103.         List<Vector2> uv = new List<Vector2> ();
  104.         List<Vector3> normals = new List<Vector3> ();
  105.         List<int> triangles = new List<int> ();
  106.  
  107.         if (lFormat == LoadFormat.Auto) {
  108.             Debug.LogWarning ("Can't load mesh : " + mesh.name + ", format is not supported.");
  109.             return;
  110.         }
  111.  
  112.         if (lFormat == LoadFormat.OBJ) {
  113.             while ((line = reader.ReadLine()) != null) {
  114.  
  115.                 datas = line.Split (' '); // so datas[0] == o || v || vt || vn || f || ...
  116.  
  117.                 // mesh name
  118.                 if (line.StartsWith ("o")) {
  119.                     mesh.name = datas[1];
  120.                 }
  121.  
  122.                 // vertex
  123.                 else if (line.StartsWith ("v ")) {
  124.                     try {
  125.                         tempVector3.x = float.Parse (datas[1]);
  126.                         tempVector3.y = float.Parse (datas[2]);
  127.                         tempVector3.z = float.Parse (datas[3]);
  128.                            
  129.                         vertices.Add (tempVector3);
  130.                     }
  131.                     catch (Exception ex) {
  132.                         Debug.LogWarning ("PARSE ERROR (vertex) : line " + lineNumber + " while loading mesh : " + mesh.name + "\n" + ex);
  133.                         vertices.Add (Vector3.zero);
  134.                     }
  135.                 }
  136.  
  137.                 // uv - texture coordinate
  138.                 else if (line.StartsWith ("vt")) {
  139.                     try {
  140.                         tempVector2.x = float.Parse (datas[1]);
  141.                         tempVector2.y = float.Parse (datas[2]);
  142.                            
  143.                         uv.Add (tempVector2);
  144.                     }
  145.                     catch (Exception ex) {
  146.                         Debug.LogWarning ("PARSE ERROR (uv) : line " + lineNumber + " while loading mesh : " + mesh.name + "\n" + ex);
  147.                         uv.Add (Vector2.zero);
  148.                     }
  149.                 }
  150.  
  151.                 // normal
  152.                 else if (line.StartsWith ("vn")) {
  153.                     try {
  154.                         tempVector3.x = float.Parse (datas[1]);
  155.                         tempVector3.y = float.Parse (datas[2]);
  156.                         tempVector3.z = float.Parse (datas[3]);
  157.                            
  158.                         normals.Add (tempVector3);
  159.                     }
  160.                     catch (Exception ex) {
  161.                         Debug.LogWarning ("PARSE ERROR (normal) : line " + lineNumber + " while loading mesh : " + mesh.name + "\n" + ex);
  162.                         normals.Add (Vector3.zero);
  163.                     }
  164.                 }
  165.  
  166.                 // triangle (face)
  167.                 else if (line.StartsWith ("f")) {
  168.                     try {
  169.                         triangles.Add (int.Parse (datas[1].Split ('/')[0]) - 1);
  170.                         triangles.Add (int.Parse (datas[2].Split ('/')[0]) - 1);
  171.                         triangles.Add (int.Parse (datas[3].Split ('/')[0]) - 1);
  172.                     }
  173.                     catch (Exception ex) {
  174.                         Debug.LogWarning ("PARSE ERROR (triangle) : line " + lineNumber + " while loading mesh : " + mesh.name + "\n" + ex);
  175.                         triangles.Add (1);
  176.                         triangles.Add (2);
  177.                         triangles.Add (3); // beurk beurk mais je vois pas comment faire autrement :/
  178.                     }
  179.                 }
  180.  
  181.                 // else it's :
  182.                 //  _ a comment (#...)
  183.                 //  _ a smoothing group, but unity doesn't support it (s on/s off)
  184.                 //  _ a unsupported operation (ex : mtl)
  185.  
  186.                 lineNumber++;
  187.             }
  188.  
  189.             mesh.Clear ();
  190.             mesh.vertices = vertices.ToArray ();
  191.             mesh.uv = uv.ToArray ();
  192.             mesh.normals = normals.ToArray ();
  193.             mesh.triangles = triangles.ToArray ();
  194.         }
  195.  
  196.         if (lFormat == LoadFormat.QMO) {
  197.             //
  198.         }
  199.  
  200.         reader.Close ();
  201.     }
  202.  
  203.     public static void LoadFromText (this Mesh mesh, string text, LoadFormat lFormat) {
  204.         mesh.LoadFromStream (new StringReader (text), lFormat);
  205.     }
  206. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement