I am trying to draw a 3D model from an .obj file, and have met big trouble. I think my model draws with wrong faces, but I can't understand why.
Original model:
This is my code for reading the model:
using (StreamReader streamReader = new StreamReader("Content/Models/" + path))
{
while (!streamReader.EndOfStream)
{
List<string> words = new List<string>(streamReader.ReadLine().ToLower().Split(' '));
words.RemoveAll(s => s == string.Empty);
if (words.Count == 0)
continue;
string type = words[0];
words.RemoveAt(0);
switch (type)
{
// vertex
case "v":
vertices.Add(new Vector4(float.Parse(words[0], new CultureInfo("en-US").NumberFormat),
float.Parse(words[1], new CultureInfo("en-US").NumberFormat),
float.Parse(words[2], new CultureInfo("en-US").NumberFormat),
words.Count < 4 ? 1 : float.Parse(words[3], new CultureInfo("en-US").NumberFormat)));
break;
case "vt":
textureVertices.Add(new Vector3(float.Parse(words[0], new CultureInfo("en-US").NumberFormat),
float.Parse(words[1], new CultureInfo("en-US").NumberFormat),
words.Count < 3 ? 0 : float.Parse(words[2], new CultureInfo("en-US").NumberFormat)));
break;
case "vn":
normals.Add(new Vector3(float.Parse(words[0], new CultureInfo("en-US").NumberFormat),
float.Parse(words[1], new CultureInfo("en-US").NumberFormat),
float.Parse(words[2], new CultureInfo("en-US").NumberFormat)));
break;
// face
case "f":
foreach (string w in words)
{
if (w.Length == 0)
continue;
string[] comps = w.Split('/');
// subtract 1: indices start from 1, not 0
vertexIndices.Add(uint.Parse(comps[0]) - 1);
if (comps.Length > 1 && comps[1].Length != 0)
textureIndices.Add(uint.Parse(comps[1]) - 1);
if (comps.Length > 2)
normalIndices.Add(uint.Parse(comps[2]) - 1);
}
break;
default:
break;
}
}
}
This is code is also available on GitHub - github.com/Freaky-Brainstorm/Deep.