Saturday, October 11, 2008

Graphics time

I've been attending demo scene events for years, so I have a certain respect for software rendered gfx effects. Now I'm curious about how to push pixels on the iPhone, so let's see how far I can get with that tonight!

First up: diving into the Core Graphics documentation. Hmm.. tried to check how many colors the iPhone screen can actually display. Specs on Apple's page don't mention it. Certainly looks like more than 64k colors, but must be less than full 24-bit color or otherwise they would prominently advertise it as a feature. Just wondering if my framebuffer should be 24bits to make it as native as possible.

... 6 hours pass ...

I created and displayed my first raw bitmap data! Feel free to copy my code (please note it turned out to be too slow for much use). As a disclaimer I just got this to display anything without crashing minutes ago, so there's likely something still wrong with the code. Here's the init part.


CGDataProviderRef provider;
bitmap = malloc(320*480*4);
provider = CGDataProviderCreateWithData(NULL, bitmap, 320*480*4, NULL);
CGColorSpaceRef colorSpaceRef;
colorSpaceRef = CGColorSpaceCreateDeviceRGB();
ir = CGImageCreate(
320,
480,
8,
32,
4 * 320,
colorSpaceRef,
kCGImageAlphaNoneSkipLast,
provider,
NULL,
NO,
kCGRenderingIntentDefault
);


And then when I want to show a buffer:


for (int i=0; i<320*480*4; i++) {
bitmap[i] = rand()%256;
}
CGRect rect = CGRectMake(0, 0, 320, 480);
CGContextDrawImage(context, rect, ir);


My only problem now is that I'm obviously leaking memory by not deallocating anything (I should at the very least free() the bitmap data) and secondly that my code lives in drawRect and is only shown once. I don't know how to get the screen to refresh. Also I have no idea if this will be fast enough to refresh at 30fps, but I'm guessing it should be. It scares me a bit that I can't really know what unnecessary hoops this code is doing on the iPhone, since I'm not really getting a raw display buffer pointer but instead going through some classes that do who knows what before the data actually ends up on the screen.

I discovered another adventure gamish thing that you can do in the Interface Builder - sometimes it's possible to drag code files from Xcode to IB to get IB to notice they exist. I would have never thought about even trying that, just saw it mentioned on another blog. Still trying to wrap my head around the relationship between Xcode and IB.

Ugh! I tried running the above code on a real iPhone device and was only getting around 5fps! Clearly I'm doing something wrong, the iPhone is definitely powerful enough to push pixels if I just figure out a better way to do the updates. But right now I'm too sleepy to think about anything except maybe getting some quality time with HL2DM before getting some sleep =)