Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections.Generic;
- using System.IO;
- using System;
- public class ObjImporter
- {
- public static Mesh[] Import(string filePath)
- {
- List<Mesh> meshes = new List<Mesh>();
- Mesh currMesh = null;
- using (StreamReader stream = File.OpenText(filePath))
- {
- string line = stream.ReadLine();
- List<Vector3> vertices = new List<Vector3>();
- List<Vector3> normals = new List<Vector3>();
- List<Vector2> texCoords = new List<Vector2>();
- List<Vector3> faceData = new List<Vector3>();
- while (line != null)
- {
- string[] comp = line.Split(' ');
- switch (comp[0])
- {
- case "g":
- case "o":
- if (currMesh != null)
- {
- Vector3[] adjVerts = new Vector3[faceData.Count];
- Vector3[] adjNorms = new Vector3[faceData.Count];
- Vector2[] adjTexCoords = new Vector2[faceData.Count];
- int[] tris = new int[(int)(faceData.Count * 1.5f)];
- int t = 0;
- for (int i = 0; i < tris.Length; i += 6)
- {
- tris[i] = t;
- tris[i + 1] = t + 1;
- tris[i + 2] = t + 2;
- tris[i + 3] = t;
- tris[i + 4] = t + 2;
- tris[i + 5] = t + 3;
- t += 4;
- }
- for (int i = 0; i < faceData.Count; i++)
- {
- Vector3 v = faceData[i];
- adjVerts[i] = vertices[(int)v.x - 1];
- if (v.y != 0)
- adjTexCoords[i] = texCoords[(int)v.y - 1];
- if (v.z != 0)
- adjNorms[i] = normals[(int)v.z - 1];
- }
- currMesh.vertices = adjVerts;
- currMesh.triangles = tris;
- currMesh.normals = adjNorms;
- currMesh.uv = adjTexCoords;
- currMesh.RecalculateBounds();
- meshes.Add(currMesh);
- }
- currMesh = new Mesh();
- currMesh.name = comp[1];
- faceData.Clear();
- break;
- case "v":
- vertices.Add(new Vector3(Convert.ToSingle(comp[1]), Convert.ToSingle(comp[2]), Convert.ToSingle(comp[3])));
- break;
- case "vt":
- case "vt1":
- case "vt2":
- texCoords.Add(new Vector2(Convert.ToSingle(comp[1]), Convert.ToSingle(comp[2])));
- break;
- case "vn":
- normals.Add(new Vector3(Convert.ToSingle(comp[1]), Convert.ToSingle(comp[2]), Convert.ToSingle(comp[3])));
- break;
- case "f":
- for (int i = 1; i < comp.Length; i++)
- {
- string[] f = comp[i].Split('/');
- Vector3 vec = Vector3.zero;
- vec.x = Convert.ToInt32(f[0]);
- if (f.Length > 1)
- {
- if (f[1] != "")
- vec.y = Convert.ToInt32(f[1]);
- if (f.Length > 2)
- {
- if (f[2] != "")
- vec.z = Convert.ToInt32(f[2]);
- }
- }
- faceData.Add(vec);
- }
- break;
- }
- line = stream.ReadLine();
- if (line != null)
- line = line.Replace(" ", " ");
- else
- {
- //currStreamMesh.vertices = vertices.ToArray();
- //currStreamMesh.triangles = mTris.ToArray();
- ////currStreamMesh.normals = mNorms.ToArray();
- ////currStreamMesh.uv = mUVs.ToArray();
- //currStreamMesh.RecalculateBounds();
- //currStreamMesh.Optimize();
- //meshes.Add(currStreamMesh);
- }
- }
- }
- return meshes.ToArray();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement