Tuesday, August 7, 2012

Intro to AS3 Workers (Part 2): Image Processing

In Part 1 of my Intro to AS3 Workers series I looked at the fundamentals of AS3 workers, including the various communication methods, and showed an example of a simple Hello World worker. In this next post, I’ll take it a step further and show how you can start doing something useful, like image processing! In this case, I’ll be applying a Sharpen Filter to a large bitmap, while the main UI thread continues to render at 30fps. First a demo. In order to view these swf’s:
DEMO: Single-Threaded Here you can take a look at what we’re going to make. This version does not use workers, and you can see that the slider locks up completely as the image is processed:
Make sure you have downloaded and enabled Flash Player 11.4.
DEMO: Multi-Threaded Here is the same demo, but using a Worker. You can see the UI renders at a smooth 30fps:
Make sure you have downloaded and enabled Flash Player 11.4.

The Code

Before actually jumping into the code, it’s important to plan ahead. Especially when dealing with concurrency, we really need to create an efficient system for marshaling data between the workers, otherwise your main thread will begin to bog down due to the heavy cost of serializing and de-serializing data. After a bit of a thought, I decided to architect the app like so:
  • The bitmapData would be shared with the worker using  a shareable byteArray
  • We will use the bitmapData.setPixels(), and bitmapData.copyPixelsToByteArray() API’s to convert the bitmap > byteArray, and vice versa.
  • The main thread will issue “SHARPEN” commands to the worker, and the worker will send “SHARPEN_COMPLETE” when it’s done
  • The worker will use a 500ms timer to check whether it needs to run a new Sharpen operation. This prevents excessive Sharpen operations.
The Document Class First up is the constructor, here we’ll use the same loaderInfo.bytes trick as we did in the last tutorial. This constructor is run twice, the second instance is the worker, and it creates a SharpenWorkerinstance which will handle all communication back to the main thread [...]
Read more: Intro to AS3 Workers (Part 2): Image Processing

No comments:

Post a Comment