Archive for the ‘Flash’ Category

Life (Cached)

June 22nd, 2011 2 comments

Sean Cooper recently ran a challenge at Lolapps to create the fastest version of Conway’s game of life in Flash that we could. Of course, he first showed us his version which uses a convolution filter, but that’s not what this challenge was about. The idea was to figure out how to make AS3 both perform and display as fast as possible. Of course I immediately found someone else’s Pixel Bender version but after playing with that I went my own route to see what I could do in pure AS3.

For the impatient, you can view an animation which helps to explain the concept or jump straight to the result.

Pretty quickly, the discussion I was a part of moved towards the possibility of caching. After getting the initial naive version of Life finished, I let the caching idea bounce around in my head and finally came up with an idea. Since (basic) life has only two states per pixel, alive or dead, these map trivially to bits. Taking an arbitrary rectangle of the map and reducing it to a simple integer then is easy. Additionally, operations on this section can be done via bitshifting and bitwise operations, which tend to be extremely fast. Unfortunately, the uint in AS3 is only 32 bits long, so this limits the size of the “chunk” we can put into a single uint, but then again 2^32 would be a lot of states to possibly store and/or calculate. I also found that if I try to make a Vector.<uint> 2^30 long, Flash hangs, then crashes.

Let’s assume for now that we’re going to deal with Life in 3×3 cell chunks. I’ll explain why later on. We’ll start with a 9×9 set of cells:

A 9x9 section of cells

Then break that up into 3×3 chunks of cells.

3x3 chunks

Let’s look at the center chunk:

The center chunk

The simple life rules make each cell depend on its immediate neighbors in every direction.

  • If a cell has less than 2 live neighbors it dies (or stays dead) due to loneliness.
  • If a cell has 2 live neighbors it stays as it is, dead or alive.
  • If a cell has 3 live neighbors it is alive in the next iteration (dead cells come alive, live cells stay alive).
  • If a cell has 4 or more live neighbors it dies of overcrowding.

To run these rules for a single cell we need the ring of cells around it to calculate its next state. In the same way, to calculate the next state of a 3×3 set of cells we need the ring around it, making the chunk we need to look at a 5×5 chunk of cells.


This is what ultimately limits the size of the chunks we can easily cache. 5×5 cells mean we need 25 bits to make them into a uint. 5×6 would make 30 bits and a simple array that big crashes Flash.

Now that we’ve established the basics of what we need it’s just a matter of figuring out how to efficiently calculate, store, and retrieve the values.

We’ll store the state transitions in a simple vector of uints. The index will be the current state and the value is the next state. For the current state we take the 5×5 chunk, turn the pixels into bits, then put them together to make a uint.

5x5 as bits, the top-left is the least significant bit (2^0)

= 9870129

Now we have the center chunk’s current 5×5 state as a uint. 9870129 will be the index into the state transition map. Now we need the state that this will become after the rules are applied.

The next state

Note that the ring around the 3×3 chunk is all empty. Since what we’re calculating for is the 3×3, that’s all we care about. We needed the 5×5 to be able to say what the 3×3 became and in the result we store the uint with only the 3×3 chunk filled out.

Result bits

= 4194688

Once this is done for all of the 3×3 chunks, you run it all over again. In order to get the 5×5 you can mask out the bits needed in the neighbors, bitshift them, and bitwise-or them together to get the 5×5 uint to index back into the state transition map. To speed things up even more you can store those masked and bitshifted parts separately so all you need to do is bitwise-or them together to find out what the next state is.

If you made it this far, thanks for reading. Here again is a link to the explanatory demo, which is where the screenshots above came from.

And, finally, the result. The fastest Life implementation I’ve made thus far. :-) You can press ‘r’ to switch to another pattern (try resizing to 1440×599) and then again to get a random start state. ‘p’ pauses the animation. Enjoy!

Click to view the completed application

Update: I’ve posted my code for this on Github.


Categories: ActionScript, Flash Tags:

Java-style Typesafe Enumerations in AS3: Round 2

December 23rd, 2010 No comments

After creating my first Enum class for AS3 I found out that Flash was behaving unexpectedly when running the static initializations. Unfortunately, the order of the static declarations isn’t always the order in which Flash runs them. In a simple example with just a few classes I found that the initialization order was the same as the order of the declarations in the file, hence causing the generated ordinal values to be in the defined order, just like in Java. However, in a more complicated application the order became somewhat random, causing the ordinal values to not match what they might be in Java. In the case where you don’t care what the ordinal values are, (i.e. you use the names for storage or network communication or are only using the static vars directly in code) you don’t need to worry about this. However, if you want to use the ordinal values then you’ll have to go back to specifying the ordinal values manually. However, this Enum class still gets you a lot more than just static ints. The type safety alone is worth it in my opinion. Without further ado, the updated class:

package com.reversefold.util {
	import flash.errors.IllegalOperationError;
	import flash.utils.Dictionary;
	import flash.utils.describeType;
	import flash.utils.getQualifiedClassName;
	 * An abstract class to emulate Enum type.
	 * Subclasses should follow this pattern:
	 * package com.example {
	 * 	public class TestEnum extends Enum {
	 * 		public static const ONE : TestEnum = new TestEnum(1);
	 * 		public static const TWO : TestEnum = new TestEnum(2);
	 * 		public static const THREE : TestEnum = new TestEnum(3);
	 * 		public static function get values() : Vector.<testenum> {
	 * 			return Vector.</testenum><testenum>(Enum.getValues(TestEnum));
	 * 		}
	 * 		{
	 * 			initEnumConstant(TestEnum);
	 * 		}
	 * 	}
	 * }
	public class Enum {
		protected static var sequence : Dictionary = new Dictionary();
		 * To protect from instantiation after static initializing.
		private static var values : Dictionary = new Dictionary();//.<vector .<Enum>>
		private static var valuesByName : Dictionary = new Dictionary();//.<object>
		 * Function to call for each enum type declared and in static init.
		protected static function initEnumConstant(inType : Class) : void {
			var className : String = getQualifiedClassName(inType);
			var typeXML : XML = describeType(inType);
			var newValues : Vector.<enum> = new Vector.</enum><enum>();
			var newValuesByName : Object = {};
			for each (var constantXML : XML in typeXML.constant) {
				var name : String = constantXML.@name;
				var constant : Enum = inType[name];
				constant._label = name;
				newValuesByName[name.toUpperCase()] = constant;
			//sort by ordinal
			values[className] = newValues.sort(
				function(lhs : Enum, rhs : Enum) : Number {
					return lhs._ordinal > rhs._ordinal ? 1 : (lhs._ordinal < rhs._ordinal ? -1 : 0);
			valuesByName[className] = newValuesByName;
		protected static function getValues(inType : Class) : Vector.<Enum> {
			return Vector.</enum><enum>(values[getQualifiedClassName(inType)]);
		protected static function getByName(inType : Class, inName : String) : Enum {
			return Enum(valuesByName[getQualifiedClassName(inType)][inName.toUpperCase()]);
		protected static function getByOrdinal(inType : Class, inOrdinal : int) : Enum {
			var values : Vector.</enum><enum> = getValues(inType);
			if (inOrdinal >= values.length) {
				throw new Error("There is no enum value for ordinal " + inOrdinal + " in class " + getQualifiedClassName(inType));
			return values[inOrdinal];
		 * Enum label.
		private var _label : String;
		public function get label() : String {
			return _label;
		private var _ordinal : uint;
		public function get ordinal() : uint {
			return _ordinal;
		public function Enum(inOrdinal : int = -1) {
			var className : String = getQualifiedClassName(this);
			if (values[className]) {
				throw new IllegalOperationError("Cannot instantiate anymore: " + className);
			if (inOrdinal == -1) {
				var seq : uint;
				if (!sequence[className]) {
					seq = 0;
				} else {
					seq = sequence[className] + 1;
				_ordinal = seq;
				sequence[className] = seq;
			} else {
				_ordinal = inOrdinal;
		public function toString() : String {
			return ordinal + " " + label;

Categories: ActionScript, Flash Tags:

More Fractal Letters

February 10th, 2009 No comments

I’ve continued adding bits to my fractal letters over the past few weeks and have finally finished everything to print out my full e-mail address. The @ symbol was particularly interesting and I think it turned out pretty nice.


Fractal Email - first iteration

Fractal Email - third iteration

Fractal Email - third iteration

Fractal Email - fifth iteration

Fractal Email - fifth iteration

The pictures link to the updated app. Enjoy, and as usual, don’t slide the slider up to the max unless you’re willing to wait while your entire browser hangs for several minutes.

Categories: Flash, Flex, Fractal Tags: , ,

Fractal Letters

January 20th, 2009 No comments

On the way home last Thursday I decided to try creating fractal letters. The idea was to replace each “line” in a simple version of a letter with a copy of itself but allow for the aspect ratio of its dimensions to change so that the result is still recognizable as a letter. This is something like an L-system, of which the Dragon curve is one. After a weekend’s worth of work I have what amounts to thirteen different fractal letter algorithms for six different letters. 1 P, 3 A, 2 E, 2 R, 2 C, 3 N. Yes, those spell PAPERCRANE. Here is the first iteration (just the letters).

Fractal Letters, iteration 1

Fractal Letters, iteration 1

And here is the fifth iteration:

Fractal Letters, iteration 5

Fractal Letters, iteration 5

Some letters have variations in how they are drawn or how they repeat, or both (hence the 2 lines). The bottom N uses an algorithm I worked out which didn’t change the aspect ratio and had only one repetition per line. Both of the N variants in the words use two repetitions per line and constrict the width faster than the height, which leaves the N recognizable. The idea here, after all, was to make letters which had a cool fractal look but could still be read.

Click either of the pictures to view the flex app and play with the iterations yourself. Just drag (or click on) the slider on the bottom of the app to change the iteration.

Stay tuned, I have another blog post coming up soon specifically about that N on the bottom, the math required to create the algorithm, and some interesting (and beautiful) results I got when implementing a test program.

Falling Away

October 28th, 2008 No comments

I had a new idea last night on my way home for a simple use of Flash 10′s 3D to do a simple visualization. Imagine that you are looking down at the ground from high up. Suddenly the screen falls away and starts falling to the ground. Then the ground you were looking at falls away and you rezlize that it was only a screen. Repeat.

This screenshot shows the app running with a flickr satellite photo feed displaying on each falling plane. Unfortunately, since my code uses BitmapData.draw(), this won’t work from the web as I don’t want to run a flickr proxy. The linked version simply colors the planes, but you can get the idea from it. Right click the movie to view its code. If you run it locally with USE_FLICKR = true you can see the full effect.

Categories: Flash Tags: , , ,

Flash 10 Camp, 3D, Sound Creation, and IK

October 12th, 2008 No comments

I’ve just come home from Flash(10)Camp and am winding down. I had a lot of fun, saw some coll stuff, and even won Best Audio (with my team) with our app Flash Tones.

I was actually very surprised, there were a lot of well done apps, including others that generated sound but I guess we just had the app polished well enough. Thanks to Rod for that, he gave us the last few bits that really made it look nice. You’ll need Flash Player 10 and a web cam if you want to try it out.

All of the features I saw in Flash Player 10 were ones I’d seen before, except for the sound generation. Things were more in depth and better put together this time, though. The sound generation is nice, but complicated and hard to make it do what you’re expecting. Of course, I’m assuming you know almost nothing about the specifics of sound, like I do.

IK is fun, but I I focused on the other 2 as I didn’t have any IK idea that seemed particularly interesting.

The 3D is very nice, being able to move and rotate objects in all three dimensions opens up a lot of new possibilities. I had a lot of fun creating some simple squares and rotating them, then applying various blend modes and filters. Here are 2 of my favorites:

Those were fun but then someone mentioned webcams. I successfully connected up webcam video to my project and then spent several hours getting the video mapped to each of the rotating squares then getting it all matched up with the video behind it. I then added edge detection (thanks to Luke Walsh’s post), added some more blending and filters and voila!

I was quite proud of that and still think it looks cool. I wish I’d shown it earlier at the Hackathon but then again we won an award so I guess I’m just being greedy.

As an added bonus, here’s an earlier version of Flash Tones which warbled in an interesting way. Try putting your hand up at the very right edge of the screen.

Categories: Flash Tags: , , , ,