Remove trace using Flex SDK

Trace removal.

I get asked this question quite often so I thought I would post the answer out there just because not too many developers are either sharing this or savvy on this. It’s less than perfect but is very good for a final release where you don’t want to have traces being fired from your project to improve performance for the playback of your Flash movie. I use the ant feature quite often in Eclipse in order to automate various development tasks and I am certainly not an expert at using ant yet but I am always finding it very useful and hungry to learn more. The code is rather basic all you need to do is run a regular expression over all your .as files to remove all instances of the trace function by adding this into an ant xml. It goes a little something like this :

<target name="removeTrace">
<replaceregexp match="trace(.*?);" replace="" flags="gs">
<fileset dir="${classesdir}" includes="**/*.as"/>

How not to hate SWF libraries

I have been playing with JSFL quite a bit recently and this little known technique may save you a a lot of time while working with SWF libraries. One thing I hate about Flash is linking library assets to classes. Actually I think linking library assets to already existing Classes is not a very good programming technique. Instead I always make sure they are anonymous classes generated at compile time.

Anyway I am getting side tracked. The process in either case to do this is really, really, really tedious and on a few occasions now I have been whinging to the guys at Adobe about this and how hopeless it is. But after many years it’s still just the same and lame.

You might ask why not use SWCs to manage library assets? Problem I have with SWCs is if you use them for all the assets in your project then your compile times will eventually go through the roof! This is something which your team could waste days or even weeks of time especially in longer production phases.

This said I still want a process where I can load assets from a SWF library with some kind of strict type safety and have not just rely on resolving library assets at runtime. This could allow for you to be aware that a library asset is missing before compiling.

Creating a bulletproof utility to map existing classes to your library assets would be quite difficult to setup. So instead I have written something simple (initially) which allows for you to automatically set library assets to be exported with linkage ids. This works by basically using the library name as the linkage id for an asset and iterating through selected library assets.

var packageName=prompt("Library package name","com.library.display");

var selItems = fl.getDocumentDOM().library.getSelectedItems(); 

for(var i =0; i<selItems.length; i++){
item = selItems[i];


var sliceIndex=className.lastIndexOf("/");

className = className.split(" ").join("");

var dotIndex=className.lastIndexOf(".");
if(dotIndex!=-1) className=className.slice(0,dotIndex);

item.linkageExportForAS = true;
item.linkageExportInFirstFrame = true;
item.linkageClassName = packageName+"."+className;


alert("Exported complete!");

Although this saves quite a bit of time it’s still kinda annoying, I would have to copy and paste linkage ids from the woeful Flash IDE library and I would not get any intellisense from FlashBuilder or FDT.

Although we can take this same idea a bit further to accommodate better support for intellisense with library assets from a SWF library with FlashBuilder or FDT. Although it’s important and maybe obvious this technique will require loading the SWF library assets into the parent applicationDomain by just using a Loader instance. Next by using JSFL you can create classes automatically based on the library items type. Here I am probably achieving this by an unintended use of the save function from the outputPanel but it allows for you to write classes and then save them into a particular folder.


I only set this JSFL up for Buttons, MovieClips and Bitmaps but this could be extended to work with other types. The JSFL to do this looks like :

var saveLocation=fl.browseForFolderURL("Save classes location");
var packageName=prompt("Package name","com.library.display");
var folderPath = packageName.split(".").join("/")+"/";


var selItems=fl.getDocumentDOM().library.getSelectedItems();

for (var i =0; i< selItems.length; i++) {
item= selItems[i];


var sliceIndex=className.lastIndexOf("/");

className = className.split(" ").join("");

var dotIndex=className.lastIndexOf(".");
if(dotIndex!=-1) className=className.slice(0,dotIndex);

item.linkageExportForAS = true;
item.linkageExportInFirstFrame = true;
item.linkageClassName = packageName+"."+className;

var templateClass='package '+packageName+' {
public class className extends baseClassName {
public function className() {

var linkageName=item.linkageClassName;


var sliceIndex=className.lastIndexOf("/");

className = className.split(" ").join("");

var dotIndex=className.lastIndexOf(".");
if(dotIndex!=-1) className=className.slice(0,dotIndex);

className = className.substr(0, 1).toUpperCase()+className.substr(1, className.length-1);

var baseClassName=item.linkageBaseClass;
var classConstructor='addChild(new (getDefinitionByName("linkageName"))());';
var classImports = ' import flash.utils.getDefinitionByName;\n';

switch (item.itemType) {
case "bitmap" :
classConstructor='super(new (getDefinitionByName("linkageName"))(0, 0));';
case "movieclip" :
case "button" :

classImports+=' import '+baseClassName+';';



Though if you don’t like using this approach of creating stub classes for retrieving library assets from a SWF library then there is one last technique using JSFL which you can use whilst still having some ability to use intellisense. Like I mentioned before the most annoying part of working with SWF library assets is not having intellisense. We could then instead of creating classes as a reference to the library SWF class, automatically create a single LibraryLinkageReferences class which contains static constants which are references to the library linkage ids.

var saveLocation=fl.browseForFolderURL("Save class location");
var libraryPackageName=prompt("Library package name","library");
var classPackageName=prompt("Class package name","com.library.display");

var folderPath = classPackageName.split(".").join("/")+"/"; 
var templateClass = 'package '+classPackageName+' {\n public class LibraryLinkageReference{\n';


var selItems =fl.getDocumentDOM().library.getSelectedItems();

for (var i =0; i< selItems.length; i++) {
item= selItems[i];


var sliceIndex=className.lastIndexOf("/");

className = className.split(" ").join("");

var dotIndex=className.lastIndexOf(".");
if(dotIndex!=-1) className=className.slice(0,dotIndex);

className = className.substr(0, 1).toUpperCase()+className.substr(1, className.length-1);

item.linkageExportForAS = true;
item.linkageExportInFirstFrame = true;
item.linkageClassName = libraryPackageName+"."+className;

templateClass+="public static const "+className.toUpperCase()+":String = \""+item.linkageClassName+"\";\n";

templateClass+=' }\n}';


alert("Exported complete saved to : "+saveLocation+folderPath+"");

Setup Library Classes

AES Cryptography for Actionscript PHP

Over the last couple of years I have used encryption on many Flash projects and until the other day, this was always a straight forward task. Cryptography has been particularly useful when to protect a server side script from fraudulent attacks. This has included things like a high score board or the progress of players through out a game.

In the past I had always used Hurlant’s crypto library which has quite a few cryptography options and includes my favorite algorithm AES. Advanced Encryption Standard is a quite secure cryptography solution and is supposedly the exact same level of encryption used by American Government’s NSA. I am not a server side guy typically but I can code C#. The nice thing about C# and AES when transacting to and from Flash is it works perfectly. PHP unfortunately does not have an official cryptography package, but thankfully there are many efforts to support this cryptography algorithm from within the community. This might sound OK, but the problem we had with this is Hurlant’s AS3 cryptography library doesn’t seem to be able to interface with the PHP AES options we tried (though it seems to work fine with other languages like C#). We did put in a good hour or so trying several mode, pad and encoding options – no dice. After a quick Google on this issue because usually if you are facing a weird issue there’s a damn good chance others have faced it already. So Google revealed to us this is a common problem and I was told maybe it’s better to find an alternative cryptographic solution. Me being, well me 🙂 I don’t like being beaten on any technical challenge. During my Google link travels I came across this great Javascript implementation of AES which also has a PHP option. Knowing that Javascript and Actionscript fall under the same standards. I figured rather than find using a different encryption option which is less secure. I quickly ported the Javascript code to Actionscript which took about 15 mins and funnily this post took much longer than this to write 🙂

Actionscript AES Encryption

So here is a simple example demo with just pure Actionscript AES encryption and decryption with a block cipher of 256 bits.

PHP AES Encryption from Flash

And here is another example demonstrating Actionscript to PHP AES encryption and decryption with the same block cipher of 256 bits. Both demonstrations use the same key so if you change the keys so they do not match then they will not be able to decrypt between each other. Also in this demonstration I post the key with the text to either encrypt or decrypt, you would of course never do this when using AES normally.

I hope this is sunshine on a rainny day for someone out there, you can download the source code from the Lost In Actionscript repository or download an archived version.

FITC 2010

It’s been a while between posts, I have plenty of excuses but shortly it’s been a really busy year and I have a lot of draft posts I must finish. After my first major conference talk at FITC last year I decided on my own regards that it might be the first and last time that I might do conferences of this calibre again. My reason for making this decision is complicated, but one major reason is because of the sheer amount of time and effort that go’s into pre-planning a conference talk and those who know me professionally I am just *slightly* the control freak and unfortunately time short! So after turning down many offers both local and abroad, I have decided to talk at FITC 2010 and resume conferencing mostly because the organizers are just so damn nice there and who can say no to a trip to Amsterdam – not me.

This year my talk will be much more exciting than last years, despite this the venue was p-a-c-k-e-d. If you missed it, Grant Skinner is pretty much covering a majority of this content in his FITC session Quick as a Flash. Though this year I am excited to say my talk is on Physics and Behavioral Character Motion. This talk will cover how to animate characters in a life like and improvisational using Actionscript and Flash. Though my talk will be best experienced with having a small amount of Actionscript knowledge. I will try to demonstrate tips and tricks to show how you can get these nice motion effects with very little maths ability and some experience in Flash alone.

My talk will begin by explaining how to look clever by making things move with super easy physics equations and how you can combine this knowledge with the new CS5 physics features and the existing IK stuff. Once we have a few things moving and colliding around properly I will then go on to show how to go about making things move under strategic behavioral motion constraints. This will then start to give some indication of AI with things like formation patterns. Lastly we will take the AI a step further by adding needs, desires and personality to our characters with creative and very simple application of complicated sounding things like finite state machines and decision trees so the behavioral motion makes sense.

I think the talk should be really exciting and hopefully inspiring for anyone attending, says me ‘I would go’. Also for free I will be giving attendees the source code from the conference so you can play around at home. I hope to see you there and maybe even have a drink together to talk geek. Mind you had better get in quick because if you are any where in Europe and slightly keen to attend, snatch a bargain with an early bird ticket for FITC Amsterdam because these tickets usually sell like hot cakes.

Custom blend modes for Flash 10

In the last few months I have been working on a collection of blendmodes for Flash 10 which extend the limited set of blendmodes currently and inconsistently supplied by Adobe applications. This can help to achieve all kinds of motion effects which I won’t go into detail here but if you know a little about After Effects you will know that some of these are rather exciting.

If you are familiar with the Adobe product line there is inconsistency between Photoshop/Illustrator/Flash/Fireworks/InDesign and support for various subsets of blendmodes which is rather annoying especially for us Flash guys. This project overzealously named the ‘Ultimate Blend Mode Collection’ is an attempt to standardize this unofficially on Adobes behalf. So marrying up Photoshop designs and Flash layouts with unsupported blendmodes won’t be nearly as annoying as has been previously. Further to this, these custom blendmodes allow for control to and undo the blendmode effects. What this means is you do not have to double up the blendmode effect by duplicating the DisplayObject instance with the same blendmode you can just multiply the single blendmode effect – simple and quite effecient.

So far I have completed the following custom blend modes :

  • Add
  • Hard Mix
  • Hardlight
  • Glow
  • Subtract
  • Stencil Luma
  • Extrapolate
  • Difference
  • Average
  • Lighter Color
  • Lighten
  • Color Dodge
  • Stencil Alpha
  • Stamp
  • Softlight
  • Silhouette Luma
  • Silhouette Alpha
  • Screen
  • PinLight
  • Phoenix
  • Overlay
  • Negation
  • Multiply
  • Linear Light
  • Linear Dodge
  • Linear Burn
  • Darken
  • Desaturate
  • Exclusion
  • Color Burn
  • Alpha
  • Darker Color

These are working though have issues of dirty-ness on alpha channels (explained below) for blending layers :

  • Reflect
  • Freeze
  • Heat
  • Vivid Light

These custom blend modes are currently in development :

  • Color
  • Hue
  • Luminosity
  • Saturation
  • Dissolve

How to use custom blend modes

I have only provided a method to use these custom blend modes included with the ‘Ultimate Blendmode Collection’ for Flex and CS4 users. This is because the PBJ files are compiled into a SWC so you will need to be able to reference SWCs from your FLA or SWF compiler to use the custom blend modes I have mentioned. The syntax to apply a custom blend mode can be achieved via any of the following approaches :

  1. import flash.display.BlendModeShader;
  2. myDisplayObject.blendShader = BlendModeShader.SOFTLIGHT;


  1. import flash.display.BlendModeShader;
  2. import flash.display.shaders.*;
  3. myDisplayObject.blendShader = new BlendModeSoftlight;

or you can manipulate the shader

  1. import flash.display.BlendModeShader;
  2. import flash.display.shaders.*;
  3. var customBlendMode: BlendModeSoftlight = new BlendModeSoftlight;
  4. customBlendMode.multiply = 2;
  5. customBlendMode.alpha = 0.5;
  6. myDisplayObject.blendShader = customBlendMode;

Tips for writing your own custom blend modes

Here are some potentially huge gotchas and lovely time savers for those wanna be pixel shader writers (like myself) :

  1. Un-multiply alpha before carrying out your shader algorithm. You might already know that Flash pre-multiplies the alpha channel onto the rgb channels this means that if you want to know what the actual rgb components are you will need to do the following :
    1. void
    2. evaluatePixel
    3. float2 uv = outCoord;
    4. float4 src1Rgba = sampleLinearsrc1, uv;
    5. float src1Alpha = src1Rgba.a;
    6. ifsrc1Alpha>0.0 src1Rgba.rgb *= 1.0/src1Alpha; //This line un-multiplies the alpha from the rgb channels
  2. When your done manipulating your blending layer against the base layer it’s more than likely you will need to composite your new blending layer and base layers together while preserving the alpha components. The following should be useful for this :
    1. void
    2. evaluatePixel
    3. ……
    4. interpolateAlpha = src2Rgba.a;
    5. inverseAlpha = 1.0-interpolateAlpha;
    6. dst.rgb = src2Rgba.rgb+src1Rgba.rgb*inverseAlpha;
    7. dst.a = min1.0, src1Alpha+src2Alpha;
  3. Make sure you clamp the components you are altering between 0.0 and 1.0 outside these will give you unusual results between tests made with the Pixel Bender Toolkit and from a published Flash movie. This bit of code ought to fix this :
    1. void
    2. evaluatePixel
    3. float3 minRgb = float30.0, 0.0, 0.0;
    4. float3 maxRgb = float31.0, 1.0, 1.0;
    5. ……
    6. dst.rgb = clampdst.rgb, minRgb, maxRgb;
  4. Because Flash premultiplies alpha and I explained earlier about why you may need to un-multiply alpha from the rgb components. It’s important to know from this there is a certain degree of losiness and this article by Mario is a great Actionscript explanation (completely unrelated to shaders) of this and is one among many others crying out for help (like me). You may notice in the example below which demonstrates these custom blend modes (or in your own tests) a certain degree of image dirty-ness and this dirty-ness is due to this. I am still working on a way to reduce or get around this – any ideas are certainly welcome – and I’ve highlighted the shaders above most affected by this.
  5. When applying a shader the input sources for the blending and base layer are automatically set. This is great but doesn’t allow for setting any further image4 inputs. From my tests if I do try to do this then the Flash Player crashes every time. This is bug and generally bugging me because I can’t complete other custom blendmodes based on random math like the Dissolve blendmode

How to get the custom blend modes

I have placed my PBJ, PBK and SWC files on a project. I have also put together a brief getting started page. If you want to get an idea of what’s possible using these custom blend modes the simple example below should help to demonstrate this. Also make sure you try out a few of the various base and blending layers I have set up to see what does what.


If you are interested in writing your own blend modes I used quite a few sources in order to collect the algorithms used in the examples seen above – here are the main sources :

Export Layers to SWF with JSFL

It’s embarrassing but until the other week I hadn’t a reason to do anything (beyond tinkering) with JSFL. JSFL can be especially useful for simplifying or automating tasks in the Flash IDE and that isn’t breaking news. I think I understand why I haven’t been using JSFL too much until recently. The major problem I discovered is the documentation is very poor, if you search JSFL you get exactly diddly squat on how to use JSFL. And alas Googling JSFL aint much better with the term “JSFL Reference” the only adobe link is this one. Considering this help reference is 5 years old doesn’t inflate confidence in learning the latest and greatest JSFL has to offer – this is really pathetic Adobe. If someone can find an official decent resource on JSFL it would be appreciated, SURELY that isn’t it 🙂 So despite not being able to find a great JSFL reference Eventually I was referred to this great JSFL reference. The JSFL script I needed to write was really quite basic and for Actionscript developers writing JSFL it is very familiar territory so I was somehow blindly confident.

So I will describe the usefulness of this JSFL script by first explaining the task or problem at hand it solved for me and hopefully you find it useful also.

The Problem
I had a rather complex vector map (12 MB) in a SWF. Embedding the whole map would be obviously be a BAD idea for loading times but fortunately only very small portions of this map had to be used at any time. Though the sucker punch to this idea is that the map isn’t grouped to these portions – sigh.

The Solution
So I started with some unavoidable and rather laborious instance naming grinding which I did within Flash. Once I had completed this I had literally 100’s of Movieclips associated to Classes that needed to be published and when I hit this I realized – JSFL I love you! So I distributed these MovieClips to layers then ran this script and viola all the layers are published as SWFs using the layer name as the published SWF name – ba da boom ching 🙂

The way this script works is that publishes any layer that isn’t a folder or a guide on the main timeline. Then sets all the layers to guides, then loops through the layers desired to be outputted to SWF then changes them to a normal layer so that only this layer is the only one in the published SWF. Once the publish loop is completed all layers are then set back to their original states.

Rather simple I thought and a huge time saver for mindless SWF publishing. To run this JSFL simply double click it or drag it onto Flash then you will be prompted to select the output directory. Then sit back, relax or even take the evening off and tell your project manager you’re hard at work!

You can view the source or download this script here – get it while it’s hot!

FITC Pixel Bender Source Code

In my efficiency FITC talk I covered some topics regarding programmatically rendering to the DisplayList – efficiently and practically. This covered some simple examples showing what can be done in PixelBender with Shaders including blendModes, lighting effects and transitions. If you would like the source code for these examples you can get them from my repository.

These shader examples only represent a taste of what’s possible using Shaders but I think what’s most important is to note these shader examples are really practical unlike a lot of the psychedelic effects you may of seen. For me I especially found that introducing more blend modes has made the process of matching designs in Flash a whole lot easier. I will shortly post a complete list of brand spanking new blend modes for Flash via Shaders with open source code so that everyone can take advantage of these blend modes.

FITC Amsterdam Presentation

Thanks for all those who attended my FITC talk ‘Efficient Programming Practices for AS3’. I had nightmares hardly anyone would show up but instead the venue was packed with a special mention to the support from the lads at Agency Republic crew – much appreciated!

Despite some early nerves (which I thank you for baring with) the talk covered a lot of practical information regarding efficiency and Actionscript. It’s actually the first time I’ve attended an exclusively Flash conference and ‘god damn’ I talked at it – pretty cool or terrifying.

If you would like to ask me questions regarding my presentation feel free to do so by email. You can also find out more about my presentation here including references and source code examples.

Lastly I would like to thank Shawn Pucknell the organizer of the FITC. I think everyone who attended would agree that him and his crew have done a fantastic job. He even had time to give me some presentation pointers just before I went up – so thanks mate for going an extra mile. Maybe next time I won’t drop the microphone 😉

Object Pooling in AS3

If you’re looking to save memory overhead and increase performance in your Flash creations then implementing the design pattern of Object Pooling is a great place to start. Object Pooling is most beneficial when the cost of construction is high or the frequency of construction is high.

Though it has to be known Object Pooling is not a silver bullet. There are definitely pitfalls to Object Pooling this most of all includes cleaning the Object for reuse. I’ll get back to this in just a moment but first I have to talk about Object Pools generally.

In short an Object Pool allows you to retrieve an instance of a particular type of Object by checking it in and out of a resource pool. The concept of checking in and out resources is very consistent when using an Object Pool. Though handling the situation when a pool is empty is not.

There are three approaches I will talk about when handling an empty pool :
1) The Unbounded Pool
The pool has a boundless size and Objects are added as required to the resource pool on check out. This ensures that an Object will always be returned on check out.

2) The Capped Pool
The pool has a constant size and the resource pool is populated during the construction of the pool. This allows you to have all the memory overhead in the pool construction and not during check out. Though when check outs occur to an empty pool it won’t return an Object.

3) The Queue Pool
The pool has a minimum size and the resource pool is populated during construction like option 1 it has the benefit of a maximum size – allowing the pool to grow. Unlike option 2 when the pool’s maximum size or flood limit is reached and a check out occurs on an empty pool then this request is queued. Requests in the queue will be eventually dropped if not fulfilled within a defined timeout or alternatively resolved once an Object is checked in. This doesn’t guarantee that the check out will be fulfilled by the Object Pool but does ensure that pools don’t grow uncontrollably and when they reach flood limits that the next fulfilled check out should be the last.

Each of these approaches to controlling the resource pool size have unique benefits and the option you choose depends on how size matters :). Lets say in one scenario that Object memory allocation is inexpensive and having 1,000’s to even 10,000’s of Objects is no big deal then option 1 is a good choice. Especially considering it’s simple and reliable. Though in another scenario where the same number of Objects are checked in as out and as a safe guard when a checkout occurs on an empty pool it can be suppressed then option 2 is a good choice. And doubly so considering a lot of the memory overhead of Object construction is on the Object Pool constructor and the pool will never grow out of your control. Though lastly if you can’t suppress check outs on empty pools and the next Object checkout should be the last one and you need to limit your pool size due to the Objects being expensive then option 3 is more than likely the best approach for you.

Now I’ll get back to Object cleaning, this sets an Object to the state it was in after construction which is important because check out is a replacement for constructing anew. The scenario when dirty Objects are added into the resource pool is often known as a cesspool and is considered an anti-pattern but honestly it’s up to you to wether this worries you or not. Though in regard to Object cleaning it’s also important to note this is where a clear pitfall emerges. If the process of cleaning is more expensive than construction then you should really consider not using an Object Pool.

If Object cleaning is important to you it gets interesting when consider the time and place to do this in your Object Pool class. It would seem logical to clean the Object within the check in method to ensure a cesspool never occurs. Though this could limit the Object Pool to containing a specific type of Object. This is because cleaning an Object is almost always subjective to type i.e. cleaning a DisplayObject is different to cleaning a BitmapData. Then thinking about this problem further the solution is “be kind rewind” – so the checkinee must clean before checkin. Problem solved.

And with every problem tackled there is another to solve. Creating an Object is also subjective to type due to parameters it may require in construction 🙁 Unfortunately there isn’t as ideal way to construct a Class with a dynamic number of parameters in Actionscript like function.apply offers for Functions. The simplest and most effective solution to this is once again the create process is external also. Another problem solved – hopefully that’s all 🙂

So now that’s enough talk on Object Pool’s and hopefully it’s given you some points to consider when creating your own Object Pool class. There’s an example below demonstrating the Object Pool concepts I’ve used and discussed above and has a small performance victory. What this example demonstrates is the performance cost in reinitializing the particle effect constantly. As you will see there is quite a noticeable difference between pooling or not but when you compare one pool concept over another there’s not much difference other than size handling features they offer which could save you performance.

If you would like to download the source code used in this example you can do so here.

AS3 SWF Profiler

This handy script applies a profiler option to the right click Flash Context Menu which allows you to debug or track the current FPS or memory used by your SWF. Further to this it also stores a configurable history length of the frame rate and memory performance for the SWF.

Adding this feature into your SWF couldn’t be easier than this line of code SWFProfiler.init(stage, this); and adding an import to the class you can download it here.