Triangulating obj files with a couple perl lines of code

BenQ Digital Camera

BenQ Digital Camera

Today, a friend of mine, while working on a university project came across a “sponza” modele in obj format. The problem was that in the obj file the faces were encoded as quads, and the parser the university provided recognized triangles only. So he was looking around the internet searching for a triangle based obj of the same model.

I made him one using the original obj and a ridiculously simple perl script, without even knowing the internals of obj (just found out about the “face” line encoding). I was so happy that it worked right away that I had to make a post about it! Here is the script:

# triangulate.pl

use strict;

open INPUT, “sponza.obj” or die “Failed to open input file”;

open OUTPUT, “>sponza-tri.obj” or die “Failed to open ouput file”;

while (<INPUT>) {

if ($_ =~ /^f (\d+\/\d+\/\d+) (\d+\/\d+\/\d+) (\d+\/\d+\/\d+) (\d+\/\d+\/\d+) $/) {

print OUTPUT “f $1 $2 $3\n”;

print OUTPUT “f $1 $3 $4\n”;

} else {

print OUTPUT “$_”;

}

}

close OUTPUT;

close INPUT;

Advertisements

One thought on “Triangulating obj files with a couple perl lines of code

  1. Nice 🙂 I like obj just because you can do that sort of thing easily. I used to count polygons in a scene simply by doing: grep ‘^f’ foo.obj | wc -l

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s