I'm currently trying to implement my own OBJ Loader for use with FreeGLUT with C++. This is my current OBJ Loader: #include "OBJLoader.h" #include #include #include #include #include
Mesh* OBJLoader::LoadModel(char* path)
{
Mesh* mesh = new Mesh(); //New Mesh
std::vector<Vertex> vertices;
std::vector<TexCoord> textureCoords;
std::vector<Vector3> normals;
//Loads OBJ file from path
std::ifstream file;
file.open(path);
if (!file.good())
{
std::cout << "Can't open texture file " << path << std::endl;
return nullptr;
}
std::string text;
while (!file.eof())
{
file >> text;
if (text == "v")
{
Vertex vertex;
file >> vertex.X;
file >> vertex.Y;
file >> vertex.Z;
vertices.push_back(vertex);
}
if (text == "vt")
{
TexCoord texCoord;
file >> texCoord.U;
file >> texCoord.V;
textureCoords.push_back(texCoord);
}
}
file.close();
mesh->vertexCount = vertices.size();
mesh->vertices = new Vertex[mesh->vertexCount];
for (int i = 0; i < mesh->vertexCount; i++)
{
mesh->vertices[i].X = vertices[i].X;
mesh->vertices[i].Y = vertices[i].Y;
mesh->vertices[i].Z = vertices[i].Z;
}
mesh->texCoordCount = textureCoords.size();
mesh->texCoords = new TexCoord[mesh->texCoordCount];
for (int i = 0; i < mesh->texCoordCount; i++)
{
mesh->texCoords[i].U = textureCoords[i].U;
mesh->texCoords[i].V = textureCoords[i].V;
}
return mesh;
}
What I do is create 3 vectors to hold the vertices, texture coords and normals, I then put the data in the corresponding vectors from the OBJ file and then finally loop through these vectors to add them to basically 3 array's which will contain the vertices, texture coordinates and normals so I can use them with "glVertexPointer" and "glTexCoordPointer" (I haven't loaded in normals yet but I will eventually)
The problem is that I'm not sure why my model is displaying really strange. It seems like it should work but the model I'm rendering which is meant to be sonic looks like... this:
Is there something I've done wrong? I imagine it's to do with the faces at the bottom of the OBJ File though I just want to make sure.
EDIT This is the section of code I'm using to put the values from the vectors into the array's used in glVertexPointer and glTexCoordPointer:
mesh->vertexCount = vertices.size();
mesh->vertices = new Vertex[mesh->vertexCount];
for (int i = 0; i < mesh->vertexCount; i++)
{
mesh->vertices[i].X = vertices[i].X;
mesh->vertices[i].Y = vertices[i].Y;
mesh->vertices[i].Z = vertices[i].Z;
}
mesh->texCoordCount = textureCoords.size();
mesh->texCoords = new TexCoord[mesh->texCoordCount];
for (int i = 0; i < mesh->texCoordCount; i++)
{
mesh->texCoords[i].U = textureCoords[i].U;
mesh->texCoords[i].V = textureCoords[i].V;
}