OpenGL on Android

First grade math bubbles game is my first foray into OpenGL. OpenGL is a standard graphics library that is used to develop games with fast moving graphics. For the bubbles game, the bubbles refresh on the screen at the rate of 30-60 fps (frames per second). To process 30+ fps, you have to work with the graphics processor directly – OpenGL does that. It is a C library, that has a Java wrapper for use in Android.

OpenGL is a standard, but, not an easy one. Going from nil to publishing a game in 2 months… takes a good book. I highly recommend Beginning Android Games by Mario Zechner. It gets you going with the basics, and provides a lot of code samples you can try out on any android device.

Today, I had a different reason for writing this post. We just got our Nexus 7 running Jelly Bean yesterday. I din’t get my hands on it till today. And, right away I discovered a problem on it. The bubbles were not loading. They were running and working, but where the bubble should be, was a black box. There was no errors reported either. Did I mention OpenGL is not so great will telling you something is wrong?

This is what it looked like… vs. what it should look like.

 
Turns out, the problem was with something called Textures. Textures in OpenGL terminology are just the images that you load into the graphics processor, so you can display them fast. The book mentioned that texture bitmap size must be a power of 2 – so, I carefully chose mine to be 256 X 256. It worked on Kindle fire, and on Motorola triumph, but not on Nexus 7. The error was this line of code -
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId);

When I load a bitmap from resources, the exact size of the loaded bitmap is dependant on the screen resolution. Turns out, Nexus 7 was loading it up as a 341 X 341 sized bitmap because of the higher screen resolution of Nexus 7. Uh oh. 341 is not a power of 2. You might have the same problem if your texture loads on some devices, but not on others. Took me the whole morning to find the problem. The solution – put the image in the assets folder and load it using -

Bitmap bitmap = BitmapFactory.decodeStream(context.getAssets().open(resource));

Simple. Once you know it :-)

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