Using Pixel Bender to Create Custom Filters

by Ryan Taylor

Level 201

Introduction

One of the most exciting features in Flash Player 10 is support for Pixel Bender, Adobe's powerful new pixel shader technology. But what exactly is a pixel shader? It’s a set of instructions, optimized for graphics processing. Typically, shaders use the GPU, but with Flash Player 10, the CPU processes all pixel shaders. The good news is that they execute on a different thread than ActionScript, thus giving us the closest thing to multi-threading that we have ever had in Flash.

A pixel shader computes the color of each pixel in a given region. You can write pixel shaders to do all sorts of image processing tasks, such as blurring, sharpening, and bump mapping. To understand what a pixel shader does, let's compare a traditional BitmapData operation to that of a pixel shader. Listing 1 shows an ActionScript method which replaces each pixel of a given color in a given Bitmap with a completely transparent pixel.

Listing 1 - An ActionScript Method public function chromaKey(bitmap:Bitmap, color:uint):void
{
var bd:BitmapData = bitmap.bitmapData;
var width:Number = bd.width;
var height:Number = bd.height;
bd.lock();
for (var i:int = 0; i < height; i++)
{
for (var j:int = 0; j < width; j++)
{
var pixelColor:uint = bd.getPixel32(j, i);
if (pixelColor == color)
bd.setPixel32(j, i, 0x00000000);
}
}
bd.unlock();
}

Listing 2 demonstrates the exact same task, handled by a Pixel Bender kernel rather than ActionScript.

Listing 2 - Pixel Bender Equivalent to Listing 1
void
evaluatePixel()
{
float4 sample = sampleNearest(src, outCoord());
dst = (sample == color) ? float4(0.0, 0.0, 0.0, 0.0) : sample;
}

Not only does Pixel Bender require a lot less code, but the entire process works dramatically faster than in ActionScript. This is the power of pixel shaders.

In the sections that follow, you will learn how to author your own pixel shader and implement it in a Flex project.

Read more of this article by buying Flex Authority Volume 2 Issue 2!

Purchase the Issue or Subscribe to Flex Authority!

ColdFusion 8 VPS hosting plans