Archive for the ‘Helpful Hints’ Category

Hint For Using Texture Coordinates Generated By Blender

Saturday, December 19th, 2009

While I was developing ShutterBox, I used Blender to create the models of the dice and tiles that you see on the game board.  The models are pretty simple, but the thing I really needed from Blender was the UV mapping.  For those who don’t know, UV mapping is the process where you map coordinates from a texture (i.e. an image) on to your 3D model.  What this entails is ‘unzipping’ you model so that it lays flat.  Then you place parts of the model on the image so that Blender knows what parts of the image to paste on to your model.  Blender (and really any 3D modeling software) lets you save the UV coordinates which map texture coordinates to, and you can read these coordinates into your code that runs on the iPhone.

The UV mapping works really well in Blender, but there is one thing I found that needs to be done before you can use the texture coordinates in your own code.  The problem is that Blender considers the ‘0′ coordinate for the ‘y’ axis to be in the lower left corner of the image.  However, when you are using a texture with OpenGL (and reading it in with glTexImage2D) the ‘0′ for the ‘y’ axis is at the UPPER left hand corner and ‘y’ grows in the downward direction.

Why does this matter you may ask?  Well, if you do the texture mapping inside Blender and then just read that same image in with glTexImage2D you will see that the texture appears upside down.  Maybe for something like a wood texture you don’t care, but if you are using textures to apply more detailed features to your models then you need to invert the coordinates of your textures.

The easiest way to do this is to just use Preview that comes with your mac.  Preview has a tool ‘Flip Vertical’ that does what you need. So just Flip Vertical, save the file and add it to your project in Xcode.  My textures do not change very often so this manual method of inverting the texture works well for me.  Of course, if you are tweaking textures a lot, manually flipping the textures might get kind of annoying.  Anyway, I wanted to post this hint because when I first started using textures I was surprised at first to see everything looked upside down. Hopefully this saves you a few cycles if your textures don’t look as expected.

Coordinates in Blender:


Coordinates used by OpenGL: