Tue, Jun 23, 2009

Realtime bloom filter in AS3

Click and drag the above example to rotate the camera.
One of my favorite post processing graphical effects in modern gaming is the bloom filter. This is the appearance of light spilling into darker areas producing a glow around bright objects such as a window in a dark room looking out on a bright landscape.

Modern hardware can now produce accurate bloom effects using HDR imagery however similar results have been achieved for years on lesser hardware.

One approach is to separate the image into pixels above a certain brightness level, blur this image and then blend the result back into the original image using additive blending. While not as accurate as a full HDR approach, visually the difference is negligible.
To reproduce the bloom effect in Flash manually would be too processor intensive for realtime use as per pixel BitmapData manipulation is extremely slow. Luckily the BitmapData class provides all the tools we need without having to read a single pixel.

By using a ColorTransform object the image can be converted to grayscale in a single pass. This grayscale version can then be used as the source in a threshold operation to limit the output image to pixels above a certain grayscale value. At this point we now have a version of the image with only areas that are above our set brightness threshold, this image can now be blurred and mixed with the original image using additive blending - voila bloom filter!
Since each of these steps utilize specific methods of the BitmapData class we get native speed operations which are many many times faster than could ever hope to be achieved using getPixel/setPixel. There is however a final trick that can be used to speed up the process even further.

Because the final step before blending is a blur we can get away with processing a scaled down version of the image and the scaling back up just before blending. In the example above the frame is scaled down by 0.25 before it is processed, that's a quarter of the pixels to process!


By adjusting the properties of the bloom filter many effects can be achieved ranging from subtle glows to full light trails. Get the source from my experiments repository on google code and try it out for yourself!

Bloom filter source on google code