The Wavefront OBJ Format

We will implement a loader for a subset of this format. Our loader will support models that are composed of triangles only and optionally may contain texture coordinates and normals. The OBJ format also supports storing arbitrary convex polygons, but we won't go into that. Whether you simply find an OBJ model, or create your own, just make sure that it is triangulated, meaning that it's composed of triangles only.

The OBJ format is-line based. Here are the parts of the syntax we are going to process:

v x y z: The v indicates that the line encodes a vertex position, while x, y, and z are the coordinates encoded as floating-point numbers.

vn i j k: The n indicates that the line encodes a vertex normal, with i, j, and k being the x-, y- and z-components of the vertex normal.

vt u v: The vt indicates that the line encodes a texture coordinate pair, with u and v being the texture coordinates.

f v1/vt1/vn1 v2/vt2/vn2 v3/vt3/vn3: The f indicates that the line encodes a triangle. Each of the v/vt/vn blocks contains the indices of the position, texture coordinates, and vertex normal of a single vertex of the triangle. The indices are relative to the vertex positions, texture coordinates, and vertex normal defined previously by the other three line formats. The vt and vn indices can be left out, indicating that there are no texture coordinates or normal for a specific vertex of a triangle.

We will ignore any line that does not start with v, vn, vt, or f; we will also output an error if any of the permissible lines don't follow the formatting just described. Items within a single line are delimited by whitespaces, which can include spaces, tabs, and so on.

NOTE The OBJ format can store a lot more information that we are going to parse her. We can get away with only parsing the syntax shown here and ignoring anything else as long as the models are triangulated and have normal and texture coordinates.

Here's a very simple example, a texture triangle with normals in OBJ format:

Note that the vertex positions, texture coordinates and normals do not have to be defined in such a nice order. They could be intertwined if the software that saved the file chose to do so.

The indices given in an f statement are one based, rather than zero-based (as in the case of a Java array). Some software even outputs negative indices at times. This is permitted by the OBJ format specification but is a major pain. We have to keep track how many vertex positions, texture coordinates, or vertex normals we have loaded so far and then add that negative index to the respective number of positions, vertex coordinates, or normals depending on what vertex attribute that index points at.

0 0

Post a comment