BitmapData Frame Animation (w/ linked list)

[SWF(width = 100, height = 100)]
var circle:Shape = new Shape();
with(circle.graphics) beginFill(0x000000), drawCircle(20,20,20);

var currFrame:Frame;

// populate the linked list
generateAnimation();

var canvas:BitmapData = new BitmapData(stage.stageWidth,stage.stageHeight,false, 0x000000);
addChild(new Bitmap(canvas));
var loc:Point = new Point(20, 20);

addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
	// clear the canvas
	canvas.fillRect(canvas.rect, 0x000000);
	// draw the current frame
	canvas.copyPixels(currFrame.bitmap, currFrame.bitmap.rect, loc, null, null, true);
	// get the next frame of the animation
	currFrame = currFrame.next;
}

// generate and capture 40 bitmaps by altering the colorTransform of the circle shape
function generateAnimation():void{
	var channel:uint = 0;
	var ct:ColorTransform = new ColorTransform();
	var increase:Boolean = true;
	var firstFrame:Frame;
    var pFrame:Frame;
	for (var i:int = 0; i<40; i++){
		if (increase){
		   channel += 10;
		   if (channel == 200){
			  increase = false;   
		   }
		}else{
		   channel -= 10;
		}
		ct.color = channel << 16 | channel << 8 | channel;
		circle.transform.colorTransform = ct;
		// populate linked list
		currFrame = capture(circle); 
		if (pFrame){
		   pFrame.next = currFrame;
		}
		if (i == 0){
		   firstFrame = currFrame;
		}
		pFrame = currFrame;
	}
	// close the list
	currFrame.next = firstFrame;
	currFrame = firstFrame;
}

// create the Frame instance and draw the circle to it
// preserving the colorTransform information
function capture(target:Shape):Frame{
	var frame:Frame = new Frame();
	frame.bitmap = new BitmapData(target.width, target.height, true, 0x00000000);
	frame.bitmap.draw(target, null, target.transform.colorTransform);
	return frame;
}

Requires this little Frame class

package {
	import flash.display.*;
	final public class Frame{
		public var bitmap:BitmapData;
		public var next:Frame;
	}
}

This is a small test I did today to see how easy it would be to use a circular linked list to loop an animation of bitmaps. I did this because I was thinking about using some animated sprites in conjunction with Utils3D.projectVectors() to do an orthographic 3D demo with lots of animating sprites. In the past I’ve had up to 7,000 animated sprites running nicely using arrays and copyPixels… figured it would be interesting to try and do the same with a circular linked list.

When compiled, this test simply draws a circle that fades from black to gray and back again… Pretty boring, but I threw it up over at wonderfl anyway… check it out.

I recently saw a few tweets (forget who from) about using the final keyword on linked list nodes… haven’t tested it myself but it’s supposed to be faster…

1 comment

Leave a Reply

Your email address will not be published. Required fields are marked *