Monday, 22 August 2011

Wavefront.obj Parser

When I started investigating the Wavefront.obj format I was really unsure of where I was going and how I was going to use the file format but after a little searching I came across the following link that looked of some interest, Spark3d project The project appears pretty old and dose not look as if anything has happened to it in a long while, this was ok for me as I was actually only interested in the file parser, or how to parse a file.

The code that I am using is very similar to the original Spark3d parser, however it has been re-written by me so that I can understand what is going on and there are a few tweaks that I have added and quite a bit that I have removed, I don't need anything complicated and to be honest at my level of C# I simply don't understand some of the code, so if I dont understand it, remove it :)

Here is an example of the wavefront.obj file format and its the first one I started working with. This is a simple wireframe cube with no textures (there are no vt entries in the file).
You can copy and paste the contents into notepad.



If you look closely at the file you will notice that there are some spaces ' ' after some of the 'f' entries, the first one is 'f 1 2 3 4 '. The extra space has been added to the lines so that the code can handle the space, my first version worked fine without the space but fell over with an out-of-bounds, If this code was being used for anything other than a simple learning tool I would improve the stability and add some error trappings for such issues.

So the Basic parser will do 2 simple things.
  • It will read all the v entries into a list.
  • It will create a list based on the correct v entries as read from the file f entries!

    So as an example
    f 8 7 6 5

    Is Actually:

    2.000000 2.000000 0.000000
    2.000000 0.000000 0.000000
    0.000000 0.000000 0.000000
    0.000000 2.000000 0.000000


    The file will actually build a list of 24 vector3d's into an array which we will draw, There are '# 6 elements' each with 4 entries making a total of 24. I also have a file of a pitcher that I am working with that contains just short of 30,000 lines of entries (vertices and face definitions) which generates almost 60,000 vectors3d's when processed and actually works through this parser!!! (yep I was surprised too)

    So down to Business, the ObjParser.cs Class and its supporting Polygon.cs Class.





    The loadObjects() method is a pretty simple call to the class passing in the relevant file, firstly setting up the required variables.





    That's a simple object loaded from a file and displayed in the glControl1 control on the main form, nice and simple. I have tested this with a few wavefront.obj files downloaded from various sources around the web and it appears to be working without any issues, but its only doing the vertices. I will be working on textures next.

  • No comments:

    Post a Comment