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.

  2. var packageName=prompt("Library package name","com.library.display");
  4. var selItems = fl.getDocumentDOM().library.getSelectedItems();
  6. for(var i =0; i<selItems.length; i++){
  7. item = selItems[i];
  9. var;
  11. var sliceIndex=className.lastIndexOf("/");
  12. className.slice(sliceIndex+1,className.length);
  14. className = className.split(" ").join("");
  16. var dotIndex=className.lastIndexOf(".");
  17. if(dotIndex!=-1) className=className.slice(0,dotIndex);
  19. item.linkageExportForAS = true;
  20. item.linkageExportInFirstFrame = true;
  21. item.linkageClassName = packageName+"."+className;
  23. fl.outputPanel.trace(item.linkageClassName);
  24. }
  26. 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.

  2. fl.outputPanel.clear();
  3. fl.outputPanel.trace(templateClass);

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 :

  2. var saveLocation=fl.browseForFolderURL("Save classes location");
  3. var packageName=prompt("Package name","com.library.display");
  4. var folderPath = packageName.split(".").join("/")+"/";
  6. FLfile.createFolder(saveLocation+folderPath);
  8. var selItems=fl.getDocumentDOM().library.getSelectedItems();
  10. for (var i =0; i< selItems.length; i++) {
  11. item= selItems[i];
  13. var;
  15. var sliceIndex=className.lastIndexOf("/");
  16. className.slice(sliceIndex+1,className.length);
  18. className = className.split(" ").join("");
  20. var dotIndex=className.lastIndexOf(".");
  21. if(dotIndex!=-1) className=className.slice(0,dotIndex);
  23. item.linkageExportForAS = true;
  24. item.linkageExportInFirstFrame = true;
  25. item.linkageClassName = packageName+"."+className;
  27. var templateClass='package '+packageName+' {
  28. classImports
  29. public class className extends baseClassName {
  30. public function className() {
  31. classConstructor
  32. }
  33. }
  34. }';
  36. var linkageName=item.linkageClassName;
  38. var;
  40. var sliceIndex=className.lastIndexOf("/");
  41. className.slice(sliceIndex+1,className.length);
  43. className = className.split(" ").join("");
  45. var dotIndex=className.lastIndexOf(".");
  46. if(dotIndex!=-1) className=className.slice(0,dotIndex);
  48. className = className.substr(0, 1).toUpperCase()+className.substr(1, className.length-1);
  50. var baseClassName=item.linkageBaseClass;
  51. var classConstructor='addChild(new (getDefinitionByName("linkageName"))());';
  52. var classImports = ' import flash.utils.getDefinitionByName;\n';
  54. switch (item.itemType) {
  55. case "bitmap" :
  56. baseClassName="flash.display.Bitmap";
  57. classConstructor='super(new (getDefinitionByName("linkageName"))(0, 0));';
  58. break;
  59. case "movieclip" :
  60. baseClassName="flash.display.MovieClip";
  61. break;
  62. case "button" :
  63. baseClassName="flash.display.SimpleButton";
  64. break;
  65. }
  67. classImports+=' import '+baseClassName+';';
  69. templateClass=templateClass.replace(/className/g,className);
  70. templateClass=templateClass.replace(/classImports/g,classImports);
  71. templateClass=templateClass.replace(/classConstructor/g,classConstructor);
  72. templateClass=templateClass.replace(/baseClassName/g,baseClassName);
  73. templateClass=templateClass.replace(/linkageName/g,linkageName);
  75. fl.outputPanel.clear();
  76. fl.outputPanel.trace(templateClass);
  78. fl.outputPanel.clear();
  79. }

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.

  2. var saveLocation=fl.browseForFolderURL("Save class location");
  3. var libraryPackageName=prompt("Library package name","library");
  4. var classPackageName=prompt("Class package name","com.library.display");
  6. var folderPath = classPackageName.split(".").join("/")+"/";
  7. var templateClass = 'package '+classPackageName+' {\n public class LibraryLinkageReference{\n';
  9. FLfile.createFolder(saveLocation+folderPath);
  11. var selItems =fl.getDocumentDOM().library.getSelectedItems();
  13. for (var i =0; i< selItems.length; i++) {
  14. item= selItems[i];
  16. var;
  18. var sliceIndex=className.lastIndexOf("/");
  19. className.slice(sliceIndex+1,className.length);
  21. className = className.split(" ").join("");
  23. var dotIndex=className.lastIndexOf(".");
  24. if(dotIndex!=-1) className=className.slice(0,dotIndex);
  26. className = className.substr(0, 1).toUpperCase()+className.substr(1, className.length-1);
  28. item.linkageExportForAS = true;
  29. item.linkageExportInFirstFrame = true;
  30. item.linkageClassName = libraryPackageName+"."+className;
  32. templateClass+="public static const "+className.toUpperCase()+":String = \""+item.linkageClassName+"\";\n";
  33. }
  35. templateClass+=' }\n}';
  37. fl.outputPanel.clear();
  38. fl.outputPanel.trace(templateClass);
  41. alert("Exported complete saved to : "+saveLocation+folderPath+"");

Hopefully this is some food for thought or very useful. I know I find these techniques and JSFL scripts very handy :)

Setup Library Linkages
Export Library Classes
Export Library References Class

Remove trace using Flex SDK

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 :

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


AES Cryptography for Actionscript & PHP

enigmaOver 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.

Have your say | Filed Under: Source | The Post ›

FITC 2010

FITC_Am10_300x250-02It'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

chameleonIn 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 exaggerate 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;
  3. myDisplayObject.blendShader = BlendModeShader.SOFTLIGHT;


  2. import flash.display.BlendModeShader;
  3. import flash.display.shaders.*;
  5. myDisplayObject.blendShader = new BlendModeSoftlight();

or you can manipulate the shader

  1. import flash.display.BlendModeShader;
  2. import flash.display.shaders.*;
  4. var customBlendMode: BlendModeSoftlight = new BlendModeSoftlight();
  5. customBlendMode.multiply = 2;
  6. customBlendMode.alpha = 0.5;
  7. 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. {
    4. float2 uv = outCoord();
    6. float4 src1Rgba = sampleLinear(src1, uv);
    7. float src1Alpha = src1Rgba.a;
    8. if(src1Alpha>0.0) src1Rgba.rgb *= 1.0/src1Alpha; //This line un-multiplies the alpha from the rgb channels
    9. }
  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. ......
    6. interpolateAlpha = src2Rgba.a;
    7. inverseAlpha = 1.0-interpolateAlpha;
    9. dst.rgb = src2Rgba.rgb+src1Rgba.rgb*inverseAlpha;
    10. dst.a = min(1.0, src1Alpha+src2Alpha);
    11. }
  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. {
    4. float3 minRgb = float3(0.0, 0.0, 0.0);
    5. float3 maxRgb = float3(1.0, 1.0, 1.0);
    7. ......
    9. dst.rgb = clamp(dst.rgb, minRgb, maxRgb);
    10. }
  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 :


I am Shane McCartney an Aussie Flash Developer who's currently working in London on a contractual basis. If you would like to check out some of the work I have done recently, go to my folio at


If you find the source code or information provided on this site of such use that you would like to donate please do it is appreciated.

Your donation will help us to provide even more source code to the community and cover the cost of time to develop and maintain the source code we provide, thank you.

Meet me at

FITC Toronto