obj2opengl: convert obj 3D models to arrays compatible with iPhone OpenGL ES

Whenever you want to use 3D objects modeled with a software such as Blender, 3ds Max or Cinema 4D in your iPhone Application or any other OpenGL project, you somehow have to make the designed data accessible to you program. To do this you can either load and interpret the files your models are saved into or you could directly provide the needed in-memory representation your program expects.

OBJ2OPENGL does the latter and acts as a converter from model files to C/C++ headers that describe vertices of the faces, normals and texture coordinates as simple arrays of floats.

Texturized and lighted 3D model with 8056 faces on the iPhone

Texturized and lighted 3D model with 8,056 faces on the iPhone

OBJ2OPENGL is a Perl script that reads a Wavefront OBJ file describing a 3D object and writes a C/C++ include file describing the object in a form suitable for use with OpenGL ES. It is compatible with Objective C and the libraries of the iPhone SDK.

The original idea and code base of this script comes from Margaret Geroch who kindly allowed me to enhance and republish this version. It now supports texture mapping and stored normals (instead of recalculating them). I have changed the structure of the generated arrays to work with glDrawArrays instead of glDrawElements. This is particularly needed for normals and textures where a vertex holds different information for some shapes. Also, this version includes several command line options to better control its behavior (such as scaling and moving the origin or setting the object’s and output file’s name).

If you can go with the defaults the conversion is as simple as

./obj2opengl.pl banana.obj

To include the converted object all you have to do is

// include generated arrays
#import "banana.h"

// set input data to arrays
glVertexPointer(3, GL_FLOAT, 0, bananaVerts);
glNormalPointer(GL_FLOAT, 0, bananaNormals);
glTexCoordPointer(2, GL_FLOAT, 0, bananaTexCoords);

// draw data
glDrawArrays(GL_TRIANGLES, 0, bananaNumVerts);

Examples

These are two models and generated sample output that is included in the provided archive:

InputOutputTextureVerticesFaces
cube.obj cube.h   8 6
banana.obj banana.h banana.jpg 4,032 8,056

Downloads

Please use the comment function of this post to discuss any problems or noteworthy results accomplished with help of this script. I will read feature requests, too. Feedback is highly appreciated.
posted @ 2012-06-29 16:59  henry@cnblogs  阅读(481)  评论(0)    收藏  举报