Parsing a Wavefront .obj file using C++

viraj picture viraj · Oct 17, 2011 · Viewed 10.9k times · Source

While trying to a parse a wavefront .obj file, I thought of two approaches:

  1. Create an 2D array the size of the number of vertices. When a face uses a vertex, get it's coordinates from the array.
  2. Get the starting position of the vertex list and then when a face uses a vertex, scan the lines until you reach the vertex.

IMO, option 1 will be very memory intensive, but much faster. Since option 2 involves extensive file reading, (and because the number of vertices in most objects becomes very large) this will be much slower, but less memmory intensive.

The question is: Comparing the tradeoff between memory and speed, which option would be better suited to an average computer? And, is there an alternative method?

I plan to use OpenGL along with GLFW to render the object.

Answer

datenwolf picture datenwolf · Oct 17, 2011

IMO, Option 1 will be very memory intensive, but much faster.

You must get those vertices into memory anyway. But there's no need for a 2D array, which BTW would cause two pointer indirections, thus a major performance hit. Just use a simple std::vector<Vertex> for your data, the vector index is the index for the accompanying face list.

EDIT due to comment

class Vertex
{
    union { struct { float x, y, z }; float pos[3] };
    union { struct { float nx, ny, nz }; float normal[3] };
    union { struct { float s, t }; float pos[2] };
    Vertex &operator=();
}

std::vector<Vertex>;