<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Mike Chambers &#187; ActionScript</title>
	<atom:link href="http://www.mikechambers.com/blog/category/actionscript/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.mikechambers.com/blog</link>
	<description>code = joy</description>
	<lastBuildDate>Sun, 15 Jan 2012 05:46:39 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.3</generator>
		<item>
		<title>FITC Amsterdam : Building High Performance iPhone Applications with ActionScript 3</title>
		<link>http://www.mikechambers.com/blog/2010/01/25/fitc-amsterdam-building-high-performance-iphone-applications-with-actionscript-3/</link>
		<comments>http://www.mikechambers.com/blog/2010/01/25/fitc-amsterdam-building-high-performance-iphone-applications-with-actionscript-3/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 17:13:48 +0000</pubDate>
		<dc:creator>mikechambers</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[Conferences]]></category>
		<category><![CDATA[amsterdam]]></category>
		<category><![CDATA[fitc]]></category>
		<category><![CDATA[flashcs5]]></category>
		<category><![CDATA[iphone]]></category>

		<guid isPermaLink="false">http://www.mikechambers.com/blog/?p=1949</guid>
		<description><![CDATA[Sorry for the two month hiatus on posting. I was on a sabbatical and vacation from work for the last 6 weeks of 2009, and have spent the first couple of weeks of 2010 busy working on code, and preparing some events for the spring (more on that in another post). Some of the stuff [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.mikechambers.com%2Fblog%2F2010%2F01%2F25%2Ffitc-amsterdam-building-high-performance-iphone-applications-with-actionscript-3%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif&amp;source=mesh&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Sorry for the two month hiatus on posting. I was on a sabbatical and vacation from work for the last 6 weeks of 2009, and have spent the first couple of weeks of 2010 busy working on code, and preparing some events for the spring (more on that in another post). </p>
<p>Some of the stuff I have continued to spend a lot of time working on, has been <a href="http://labs.adobe.com/technologies/flashcs5/appsfor_iphone/">building iPhone content using the Flash CS5 private beta</a>. I have been doing a lot of work on trying to figure out how to get the best performance, and understand the limits of Flash content on the device. I plan to make a separate post on that in the next couple of days.<br />
<span id="more-1949"></span><br />
Anyways, the conference season is about to be in full swing, and the first talk I am doing this year, will be at <a href="http://www.fitc.ca/events/about/?event=101">FITC Amsterdam</a> next month on Flash and iPhone. The talk is titled &#8220;<a href="http://www.fitc.ca/events/presentations/presentation.cfm?event=101&#038;presentation_id=1130">Building High Performance iPhone Applications with ActionScript 3</a>&#8221; and will discuss how to get the best performance from your Flash content, as well as what type of Flash content is best suited for the device. In addition to talking about some general tips and tricks, I will also be discussing some of the new hardware accelerated APIs, and showing some games I have been working on (including my new game <a href="http://www.twitpic.com/q00ox">Unicorn Bacon Adventure!</a>).</p>
<p>If you are in Europe, and haven&#8217;t signed up for FITC yet, then what are you waiting for?!?!? This is one of the best conferences in the world, and the <a href="http://www.fitc.ca/events/speakers/?event=101">speaker line up for Amsterdam</a> is simply amazing.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mikechambers.com/blog/2010/01/25/fitc-amsterdam-building-high-performance-iphone-applications-with-actionscript-3/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Case Study : ActionScript 3 Performance Optimization</title>
		<link>http://www.mikechambers.com/blog/2009/10/13/case-study-actionscript-3-performance-optimization/</link>
		<comments>http://www.mikechambers.com/blog/2009/10/13/case-study-actionscript-3-performance-optimization/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 17:27:49 +0000</pubDate>
		<dc:creator>mikechambers</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[actionscript3]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://www.mikechambers.com/blog/?p=1865</guid>
		<description><![CDATA[Prompted by some of the work from Grant Skinner (in particular his FOTB 2009 session) and Thibault Imbert, I have been doing a lot of research lately into optimizing ActionScript 3 content. Not just how to make it run faster, but how to approach the process of optimization. I am also starting to work on [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.mikechambers.com%2Fblog%2F2009%2F10%2F13%2Fcase-study-actionscript-3-performance-optimization%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif&amp;source=mesh&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Prompted by some of the work from <a href="http://www.gskinner.com/blog/">Grant Skinner</a> (in particular his <a href="http://gskinner.com/blog/archives/2004/06/conference_sess.html">FOTB 2009 session</a>) and <a href="http://www.bytearray.org/">Thibault Imbert</a>, I have been doing a lot of research lately into optimizing ActionScript 3 content. Not just how to make it run faster, but how to approach the process of optimization.</p>
<p>I am also starting to work on a small project which works with pixel data from images, and on which I anticipate performance might be an issue when working with larger images. I figured this would be a good opportunity to use some of the early code as a case study. I wanted to post the process and results here.<br />
<span id="more-1865"></span><br />
The task that I will focus on is grabbing a palette of 16 colors from an image, created by averaging the colors within that image. Upon searching on google, I found a <a href="http://blog.soulwire.co.uk/flash/actionscript-3/extract-average-colours-from-bitmapdata/">very good solution over at soulwire.co.uk</a>, which I will use as the base for creating the palette. I want to point out that the original code targeted Flash Player 9 (and thus couldn&#8217;t take advantage of some things such as Vectors), and already ran pretty blazingly fast.</p>
<p>I am using Grant Skinner&#8217;s <a href="http://www.gskinner.com/blog/archives/2009/04/as3_performance.html">performance test harness</a> to profile performance. Each test is run 50 times, and is tested in Flash Player MAC 10,0,32,18 (debug) in the browser. </p>
<p>You can download all of the code from <a href="/blog/files/examples/PixelSort.zip">here</a>.</p>
<p>First, here is the original test case, based on soulwire&#8217;s code:</p>
<div class="highlight">
<pre><span style="color: #408080; font-style: italic">/*</span>
<span style="color: #408080; font-style: italic">	Code adapted from:</span>
<span style="color: #408080; font-style: italic">	http://blog.soulwire.co.uk/flash/actionscript-3/colourutils-bitmapdata-extract-colour-palette/</span>
<span style="color: #408080; font-style: italic">*/</span>

package
{
	<span style="color: #008000; font-weight: bold">import</span> flash.display.Bitmap<span style="color: #666666">;</span>
	<span style="color: #008000; font-weight: bold">import</span> flash.display.<span style="color: #008000">BitmapData</span><span style="color: #666666">;</span>
	<span style="color: #008000; font-weight: bold">import</span> flash.display.Sprite<span style="color: #666666">;</span>
	<span style="color: #008000; font-weight: bold">import</span> flash.events.Event<span style="color: #666666">;</span>
	<span style="color: #008000; font-weight: bold">import</span> flash.geom.<span style="color: #008000">Rectangle</span><span style="color: #666666">;</span>
	<span style="color: #008000; font-weight: bold">import</span> flash.geom.<span style="color: #008000">Point</span><span style="color: #666666">;</span>

	<span style="color: #008000; font-weight: bold">import</span> com.gskinner.utils.PerformanceTest<span style="color: #666666">;</span>

	<span style="color: #008000; font-weight: bold">public</span> <span style="color: #008000; font-weight: bold">class</span> PixelSort <span style="color: #008000; font-weight: bold">extends</span> Sprite
	{

		[Embed(source<span style="color: #666666">=</span><span style="color: #BA2121">&quot;../graphics/image.jpg&quot;</span>)]
		<span style="color: #008000; font-weight: bold">public</span> <span style="color: #008000; font-weight: bold">var</span> TestImage<span style="color: #666666">:</span>Class<span style="color: #666666">;</span>

		<span style="color: #008000; font-weight: bold">public</span> <span style="color: #008000; font-weight: bold">function</span> PixelSort()
		{
			addEventListener(Event.ADDED_TO_STAGE<span style="color: #666666">,</span> onAddedToStage);
		}

		<span style="color: #008000; font-weight: bold">private</span> <span style="color: #008000; font-weight: bold">var</span> d<span style="color: #666666">:</span><span style="color: #008000">BitmapData</span><span style="color: #666666">;</span>
		<span style="color: #008000; font-weight: bold">private</span> <span style="color: #008000; font-weight: bold">function</span> onAddedToStage(evet<span style="color: #666666">:</span>Event)<span style="color: #666666">:</span>void
		{
			removeEventListener(Event.ADDED_TO_STAGE<span style="color: #666666">,</span> onAddedToStage);

			<span style="color: #008000; font-weight: bold">var</span> b<span style="color: #666666">:</span>Bitmap <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">new</span> TestImage();

			d <span style="color: #666666">=</span> b.bitmapData<span style="color: #666666">;</span>

			<span style="color: #008000; font-weight: bold">var</span> perfTest<span style="color: #666666">:</span>PerformanceTest <span style="color: #666666">=</span> PerformanceTest.getInstance();
			perfTest.out <span style="color: #666666">=</span> <span style="color: #0000FF">trace</span><span style="color: #666666">;</span>
			perfTest.testFunction(run<span style="color: #666666">,</span> <span style="color: #666666">50,</span> <span style="color: #BA2121">&quot;averagecolors&quot;</span><span style="color: #666666">,</span> <span style="color: #BA2121">&quot;averagecolors&quot;</span>);
		}

		<span style="color: #008000; font-weight: bold">private</span> <span style="color: #008000; font-weight: bold">function</span> run()<span style="color: #666666">:</span>void
		{
			<span style="color: #008000; font-weight: bold">var</span> out<span style="color: #666666">:</span><span style="color: #008000">Array</span> <span style="color: #666666">=</span> averagecolors(d<span style="color: #666666">,</span> <span style="color: #666666">16</span>);
		}

		<span style="color: #008000; font-weight: bold">public</span> <span style="color: #008000; font-weight: bold">function</span> averageColour( source<span style="color: #666666">:</span><span style="color: #008000">BitmapData</span> )<span style="color: #666666">:</span>uint
		{
			<span style="color: #008000; font-weight: bold">var</span> red<span style="color: #666666">:</span><span style="color: #008000">Number</span> <span style="color: #666666">=</span> <span style="color: #666666">0;</span>
			<span style="color: #008000; font-weight: bold">var</span> green<span style="color: #666666">:</span><span style="color: #008000">Number</span> <span style="color: #666666">=</span> <span style="color: #666666">0;</span>
			<span style="color: #008000; font-weight: bold">var</span> blue<span style="color: #666666">:</span><span style="color: #008000">Number</span> <span style="color: #666666">=</span> <span style="color: #666666">0;</span>

			<span style="color: #008000; font-weight: bold">var</span> count<span style="color: #666666">:</span><span style="color: #008000">Number</span> <span style="color: #666666">=</span> <span style="color: #666666">0;</span>
			<span style="color: #008000; font-weight: bold">var</span> pixel<span style="color: #666666">:</span><span style="color: #008000">Number</span><span style="color: #666666">;</span>

			<span style="color: #008000; font-weight: bold">for</span> (<span style="color: #008000; font-weight: bold">var</span> x<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0;</span> x <span style="color: #666666">&lt;</span> source.width<span style="color: #666666">;</span> x<span style="color: #666666">++</span>)
			{
				<span style="color: #008000; font-weight: bold">for</span> (<span style="color: #008000; font-weight: bold">var</span> y<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0;</span> y <span style="color: #666666">&lt;</span> source.height<span style="color: #666666">;</span> y<span style="color: #666666">++</span>)
				{
					pixel <span style="color: #666666">=</span> source.getPixel(x<span style="color: #666666">,</span> y);

					red <span style="color: #666666">+=</span> pixel <span style="color: #666666">&gt;&gt;</span> <span style="color: #666666">16</span> <span style="color: #666666">&amp;</span> <span style="color: #666666">0</span>xFF<span style="color: #666666">;</span>
					green <span style="color: #666666">+=</span> pixel <span style="color: #666666">&gt;&gt;</span> <span style="color: #666666">8</span> <span style="color: #666666">&amp;</span> <span style="color: #666666">0</span>xFF<span style="color: #666666">;</span>
					blue <span style="color: #666666">+=</span> pixel <span style="color: #666666">&amp;</span> <span style="color: #666666">0</span>xFF<span style="color: #666666">;</span>

					count<span style="color: #666666">++</span>
				}
			}

			red <span style="color: #666666">/=</span> count<span style="color: #666666">;</span>
			green <span style="color: #666666">/=</span> count<span style="color: #666666">;</span>
			blue <span style="color: #666666">/=</span> count<span style="color: #666666">;</span>

			<span style="color: #008000; font-weight: bold">return</span> red <span style="color: #666666">&lt;&lt;</span> <span style="color: #666666">16</span> <span style="color: #666666">|</span> green <span style="color: #666666">&lt;&lt;</span> <span style="color: #666666">8</span> <span style="color: #666666">|</span> blue<span style="color: #666666">;</span>
		}		

		<span style="color: #008000; font-weight: bold">public</span> <span style="color: #008000; font-weight: bold">function</span> averagecolors( source<span style="color: #666666">:</span><span style="color: #008000">BitmapData</span><span style="color: #666666">,</span> colors<span style="color: #666666">:</span>int )<span style="color: #666666">:</span><span style="color: #008000">Array</span>
		{
			<span style="color: #008000; font-weight: bold">var</span> averages<span style="color: #666666">:</span><span style="color: #008000">Array</span> <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">new</span> <span style="color: #008000">Array</span>();
			<span style="color: #008000; font-weight: bold">var</span> columns<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #008000">Math</span>.round( <span style="color: #008000">Math</span>.sqrt( colors ) );

			<span style="color: #008000; font-weight: bold">var</span> row<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0;</span>
			<span style="color: #008000; font-weight: bold">var</span> col<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0;</span>

			<span style="color: #008000; font-weight: bold">var</span> x<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0;</span>
			<span style="color: #008000; font-weight: bold">var</span> y<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0;</span>

			<span style="color: #008000; font-weight: bold">var</span> w<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #008000">Math</span>.round( source.width <span style="color: #666666">/</span> columns );
			<span style="color: #008000; font-weight: bold">var</span> h<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #008000">Math</span>.round( source.height <span style="color: #666666">/</span> columns );

			<span style="color: #008000; font-weight: bold">for</span> (<span style="color: #008000; font-weight: bold">var</span> i<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0;</span> i <span style="color: #666666">&lt;</span> colors<span style="color: #666666">;</span> i<span style="color: #666666">++</span>)
			{
				<span style="color: #008000; font-weight: bold">var</span> rect<span style="color: #666666">:</span><span style="color: #008000">Rectangle</span> <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">new</span> <span style="color: #008000">Rectangle</span>( x<span style="color: #666666">,</span> y<span style="color: #666666">,</span> w<span style="color: #666666">,</span> h );

				<span style="color: #008000; font-weight: bold">var</span> box<span style="color: #666666">:</span><span style="color: #008000">BitmapData</span> <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">new</span> <span style="color: #008000">BitmapData</span>( w<span style="color: #666666">,</span> h<span style="color: #666666">,</span> <span style="color: #008000; font-weight: bold">false</span> );
				box.copyPixels( source<span style="color: #666666">,</span> rect<span style="color: #666666">,</span> <span style="color: #008000; font-weight: bold">new</span> <span style="color: #008000">Point</span>() );

				averages.push( averageColour( box ) );
				box.dispose();

				col <span style="color: #666666">=</span> i <span style="color: #666666">%</span> columns<span style="color: #666666">;</span>

				x <span style="color: #666666">=</span> w <span style="color: #666666">*</span> col<span style="color: #666666">;</span>
				y <span style="color: #666666">=</span> h <span style="color: #666666">*</span> row<span style="color: #666666">;</span>

				<span style="color: #008000; font-weight: bold">if</span> ( col <span style="color: #666666">==</span> columns <span style="color: #666666">-</span> <span style="color: #666666">1</span> ) row<span style="color: #666666">++;</span>
			}

			<span style="color: #008000; font-weight: bold">return</span> averages<span style="color: #666666">;</span>
		}
	}
}
</pre>
</div>
<p>&nbsp;</p>
<p>And here is the initial performance test:</p>
<pre>––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
averagecolors (50 iterations)
Player version: MAC 10,0,32,18 (debug)
averagecolors
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
method...................................................ttl ms...avg ms
averagecolors                                              1264    25.28
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––</pre>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>First, considering what the code is doing, it is already pretty fast, taking only 25 ms to split the image into a grid, and loop through all of the pixels and averaging the values. However, there is probably some room for improvement, especially given that the original code targets Flash Player 9 and thus cant take care of Flash Player 10 optimizations such as using Vectors.</p>
<p>Now, the first thing I would normally do is to profile the SWF using the profiler in Flash Builder to find out where the most time is being sent. However, in this case, there are only two methods that do anything, <em>averageColors</em> and <em>averageColor</em>. <em>averageColors</em> is called once, while <em>averageColor</em> is called once for each swatch we want to create (in this case 16), and ends up looping over each pixel in the image (over those 16 calls). So these are the two areas we will focus on, with particular attention directed to <em>averageColor</em>.</p>
<p>The first thing I did was look at updating the content to Flash Player 10 by converting all of the Arrays to Vectors. I expected to get a decent boost from this, but the improvement was minimal.</p>
<p>Within the <em>averageColors</em> method, I looked at reusing the <em>Point</em>, <em>Rectangle</em> and <em>BitmapData</em> instances, instead of creating new ones on each iteration of the loop. Again, on the desktop this didn&#8217;t really make any difference. However, one thing to consider is that on a mobile device where memory allocation can be more expensive (and there is less RAM altogether), this change may have had a bigger impact (which I didnt test). This leads to an important point. It is important to test performance on the platforms which you are targeting, as some optimizations can have a different impact depending on where the content is running.</p>
<p>Next, I set the <em>averageColor</em> and <em>averageColors</em> methods as <em>final</em>, which allows them too be looked up at compile time (as opposed to runtime), this led to small improvement in performance, but again, not really anything significant.</p>
<p>At this point, I was getting a very slight performance improvement, but not really anything that mattered (basically, small enough to be insignificant),</p>
<pre>––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
averagecolors (50 iterations)
Player version: MAC 10,0,32,18 (debug)
averagecolors
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
method...................................................ttl ms...avg ms
averagecolors                                              1224    24.48
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––</pre>
<p>&nbsp;</p>
<p>Next, I moved on to the <em>averageColor</em> method, where I expected (and hoped) to have better results, as this is where the bulk of the work occurs.</p>
<p>First I converter some of the Numbers to ints and uints in places where Numbers were not needed. This led to a small improvement.</p>
<pre>––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
averagecolors (50 iterations)
Player version: MAC 10,0,32,18 (debug)
averagecolors
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
method...................................................ttl ms...avg ms
averagecolors                                              1190    23.80
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––</pre>
<p>&nbsp;</p>
<p>Next, I changed the <code>bitmapData.getPixel</code> call to use <code>bitmapData.getVector</code>. Doing this then allowed me to loop through the pixels using a single loop, instead of a nested double loop, and also eliminated a <em>getPixel</em> call for each pixel. I used a <em>for each</em> loop to loop through the pixel color values.</p>
<p>This provided another slight improvement (although not quite as much as I expected). We are now making some small gains.</p>
<pre>––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
averagecolors (50 iterations)
Player version: MAC 10,0,32,18 (debug)
averagecolors
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
method...................................................ttl ms...avg ms
averagecolors                                              1137    22.74
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––</pre>
<p>&nbsp;</p>
<p>Next, I decided to try a <em>for</em> loop, instead of a <em>for each</em> loop.</p>
<pre>––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
averagecolors (50 iterations)
Player version: MAC 10,0,32,18 (debug)
averagecolors
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
method...................................................ttl ms...avg ms
averagecolors                                               282     5.64
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––</pre>
<p>&nbsp;</p>
<p>Wow! As you can see, that makes a huge difference.</p>
<p>Finally, I explicitly cast <em>i</em> to an <em>int</em> when pulling the value from the Vector. This gave a small improvement, but again, nothing significant:</p>
<pre>––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
averagecolors (50 iterations)
Player version: MAC 10,0,32,18 (debug)
averagecolors
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
method...................................................ttl ms...avg ms
averagecolors                                               268     5.36
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––</pre>
<p>&nbsp;</p>
<p>I tried a couple of more optimizations in the method, around converting division operations to multiplication operation, and replacing <code>Math.round</code> calls but in this case it didnt make any difference.</p>
<p>I also looked at caching some constants used in some of the bitwise operations, changing</p>
<div class="highlight">
<pre>red <span style="color: #666666">+=</span> pixel <span style="color: #666666">&gt;&gt;</span> <span style="color: #666666">16</span> <span style="color: #666666">&amp;</span> <span style="color: #666666">0</span>xFF<span style="color: #666666">;</span>
green <span style="color: #666666">+=</span> pixel <span style="color: #666666">&gt;&gt;</span> <span style="color: #666666">8</span> <span style="color: #666666">&amp;</span> <span style="color: #666666">0</span>xFF<span style="color: #666666">;</span>
</pre>
</div>
<p>&nbsp;</p>
<p>to</p>
<div class="highlight">
<pre><span style="color: #008000; font-weight: bold">private</span> <span style="color: #008000; font-weight: bold">var</span> s16<span style="color: #666666">:</span><span style="color: #008000">Number</span> <span style="color: #666666">=</span> <span style="color: #666666">16</span> <span style="color: #666666">&amp;</span> <span style="color: #666666">0</span>xFF<span style="color: #666666">;</span>
<span style="color: #008000; font-weight: bold">private</span> <span style="color: #008000; font-weight: bold">var</span> s8<span style="color: #666666">:</span><span style="color: #008000">Number</span> <span style="color: #666666">=</span> <span style="color: #666666">8</span> <span style="color: #666666">&amp;</span> <span style="color: #666666">0</span>xFF<span style="color: #666666">;</span>

red <span style="color: #666666">+=</span> pixel <span style="color: #666666">&gt;&gt;</span> s16<span style="color: #666666">;</span>
green <span style="color: #666666">+=</span> pixel <span style="color: #666666">&gt;&gt;</span> s8<span style="color: #666666">;</span>
</pre>
</div>
<p>&nbsp;</p>
<p>First, that optimization actually produces the wrong result (I had my operator precedence backwards). Second, it was actually slower:</p>
<pre>––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
averagecolors (50 iterations)
Player version: MAC 10,0,32,18 (debug)
averagecolors
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
method...................................................ttl ms...avg ms
averagecolors                                               349     6.98
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––</pre>
<p>&nbsp;</p>
<p>There are two lessons from this. First, make sure your optimizations produce the same results (ideally by creating and using unit tests). Second, bitwise operations are really, really fast. In this case, they are even faster than doing a variable lookup.</p>
<p>So, after going through the code, and applying a number of different optimizations, I was able to improve performance from an average of 25.28 ms, to 5.36 ms, an improvement of about 470%.</p>
<p>Here is the final code:</p>
<div class="highlight">
<pre><span style="color: #408080; font-style: italic">/*</span>
<span style="color: #408080; font-style: italic">	Code adapted from:</span>
<span style="color: #408080; font-style: italic">	http://blog.soulwire.co.uk/flash/actionscript-3/colourutils-bitmapdata-extract-colour-palette/</span>
<span style="color: #408080; font-style: italic">*/</span>

package
{
	<span style="color: #008000; font-weight: bold">import</span> flash.display.Bitmap<span style="color: #666666">;</span>
	<span style="color: #008000; font-weight: bold">import</span> flash.display.<span style="color: #008000">BitmapData</span><span style="color: #666666">;</span>
	<span style="color: #008000; font-weight: bold">import</span> flash.display.Sprite<span style="color: #666666">;</span>
	<span style="color: #008000; font-weight: bold">import</span> flash.events.Event<span style="color: #666666">;</span>
	<span style="color: #008000; font-weight: bold">import</span> flash.geom.<span style="color: #008000">Rectangle</span><span style="color: #666666">;</span>
	<span style="color: #008000; font-weight: bold">import</span> flash.geom.<span style="color: #008000">Point</span><span style="color: #666666">;</span>

	<span style="color: #008000; font-weight: bold">import</span> com.gskinner.utils.PerformanceTest<span style="color: #666666">;</span>

	<span style="color: #008000; font-weight: bold">public</span> <span style="color: #008000; font-weight: bold">class</span> PixelSort <span style="color: #008000; font-weight: bold">extends</span> Sprite
	{

		[Embed(source<span style="color: #666666">=</span><span style="color: #BA2121">&quot;../graphics/image.jpg&quot;</span>)]
		<span style="color: #008000; font-weight: bold">public</span> <span style="color: #008000; font-weight: bold">var</span> TestImage<span style="color: #666666">:</span>Class<span style="color: #666666">;</span>

		<span style="color: #008000; font-weight: bold">public</span> <span style="color: #008000; font-weight: bold">function</span> PixelSort()
		{
			addEventListener(Event.ADDED_TO_STAGE<span style="color: #666666">,</span> onAddedToStage);
		}

		<span style="color: #008000; font-weight: bold">private</span> <span style="color: #008000; font-weight: bold">var</span> d<span style="color: #666666">:</span><span style="color: #008000">BitmapData</span><span style="color: #666666">;</span>
		<span style="color: #008000; font-weight: bold">private</span> <span style="color: #008000; font-weight: bold">function</span> onAddedToStage(evet<span style="color: #666666">:</span>Event)<span style="color: #666666">:</span>void
		{
			removeEventListener(Event.ADDED_TO_STAGE<span style="color: #666666">,</span> onAddedToStage);

			<span style="color: #008000; font-weight: bold">var</span> b<span style="color: #666666">:</span>Bitmap <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">new</span> TestImage();

			d <span style="color: #666666">=</span> b.bitmapData<span style="color: #666666">;</span>

			<span style="color: #008000; font-weight: bold">var</span> perfTest<span style="color: #666666">:</span>PerformanceTest <span style="color: #666666">=</span> PerformanceTest.getInstance();
			perfTest.out <span style="color: #666666">=</span> <span style="color: #0000FF">trace</span><span style="color: #666666">;</span>
			perfTest.testFunction(run<span style="color: #666666">,</span> <span style="color: #666666">50,</span> <span style="color: #BA2121">&quot;averagecolors&quot;</span><span style="color: #666666">,</span> <span style="color: #BA2121">&quot;averagecolors&quot;</span>);
		}

		<span style="color: #008000; font-weight: bold">private</span> <span style="color: #008000; font-weight: bold">function</span> run()<span style="color: #666666">:</span>void
		{
			<span style="color: #008000; font-weight: bold">var</span> out<span style="color: #666666">:</span>Vector.<span style="color: #666666">&lt;</span>uint<span style="color: #666666">&gt;</span> <span style="color: #666666">=</span> averagecolors(d<span style="color: #666666">,</span> <span style="color: #666666">16</span>);
		}		

		<span style="color: #008000; font-weight: bold">public</span> final <span style="color: #008000; font-weight: bold">function</span> averageColour( source<span style="color: #666666">:</span><span style="color: #008000">BitmapData</span> )<span style="color: #666666">:</span>uint
		{
			<span style="color: #008000; font-weight: bold">var</span> red<span style="color: #666666">:</span><span style="color: #008000">Number</span> <span style="color: #666666">=</span> <span style="color: #666666">0;</span>
			<span style="color: #008000; font-weight: bold">var</span> green<span style="color: #666666">:</span><span style="color: #008000">Number</span> <span style="color: #666666">=</span> <span style="color: #666666">0;</span>
			<span style="color: #008000; font-weight: bold">var</span> blue<span style="color: #666666">:</span><span style="color: #008000">Number</span> <span style="color: #666666">=</span> <span style="color: #666666">0;</span>

			<span style="color: #008000; font-weight: bold">var</span> count<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0;</span>
			<span style="color: #008000; font-weight: bold">var</span> pixel<span style="color: #666666">:</span>uint<span style="color: #666666">;</span>

			<span style="color: #008000; font-weight: bold">var</span> pixels<span style="color: #666666">:</span>Vector.<span style="color: #666666">&lt;</span>uint<span style="color: #666666">&gt;</span> <span style="color: #666666">=</span> source.getVector(<span style="color: #008000; font-weight: bold">new</span> <span style="color: #008000">Rectangle</span>(<span style="color: #666666">0,0,</span> source.width<span style="color: #666666">,</span> source.height));
			<span style="color: #008000; font-weight: bold">var</span> len<span style="color: #666666">:</span>int <span style="color: #666666">=</span> pixels.length<span style="color: #666666">;</span>

			<span style="color: #008000; font-weight: bold">for</span>(<span style="color: #008000; font-weight: bold">var</span> i<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0;</span> i <span style="color: #666666">&lt;</span> len<span style="color: #666666">;</span> i<span style="color: #666666">++</span>)
			{
				pixel <span style="color: #666666">=</span> pixels[int(i)];

				red <span style="color: #666666">+=</span> pixel <span style="color: #666666">&gt;&gt;</span> <span style="color: #666666">16</span> <span style="color: #666666">&amp;</span> <span style="color: #666666">0</span>xFF<span style="color: #666666">;</span>
				green <span style="color: #666666">+=</span> pixel <span style="color: #666666">&gt;&gt;</span> <span style="color: #666666">8</span> <span style="color: #666666">&amp;</span> <span style="color: #666666">0</span>xFF<span style="color: #666666">;</span>
				blue <span style="color: #666666">+=</span> pixel <span style="color: #666666">&amp;</span> <span style="color: #666666">0</span>xFF<span style="color: #666666">;</span>

				count<span style="color: #666666">++;</span>
			}

			red <span style="color: #666666">/=</span> count<span style="color: #666666">;</span>
			green <span style="color: #666666">/=</span> count<span style="color: #666666">;</span>
			blue <span style="color: #666666">/=</span> count<span style="color: #666666">;</span>

			<span style="color: #008000; font-weight: bold">return</span> red <span style="color: #666666">&lt;&lt;</span> <span style="color: #666666">16</span> <span style="color: #666666">|</span> green <span style="color: #666666">&lt;&lt;</span> <span style="color: #666666">8</span> <span style="color: #666666">|</span> blue<span style="color: #666666">;</span>
		}		

		<span style="color: #008000; font-weight: bold">public</span> final <span style="color: #008000; font-weight: bold">function</span> averagecolors( source<span style="color: #666666">:</span><span style="color: #008000">BitmapData</span><span style="color: #666666">,</span> colors<span style="color: #666666">:</span>int )<span style="color: #666666">:</span>Vector.<span style="color: #666666">&lt;</span>uint<span style="color: #666666">&gt;</span>
		{

			<span style="color: #008000; font-weight: bold">var</span> averages<span style="color: #666666">:</span>Vector.<span style="color: #666666">&lt;</span>uint<span style="color: #666666">&gt;</span> <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">new</span> Vector.<span style="color: #666666">&lt;</span>uint<span style="color: #666666">&gt;</span>(colors<span style="color: #666666">,</span> <span style="color: #008000; font-weight: bold">false</span>);
			<span style="color: #008000; font-weight: bold">var</span> columns<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #008000">Math</span>.round( <span style="color: #008000">Math</span>.sqrt( colors ) );

			<span style="color: #008000; font-weight: bold">var</span> row<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0;</span>
			<span style="color: #008000; font-weight: bold">var</span> col<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0;</span>

			<span style="color: #008000; font-weight: bold">var</span> x<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0;</span>
			<span style="color: #008000; font-weight: bold">var</span> y<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0;</span>

			<span style="color: #008000; font-weight: bold">var</span> w<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #008000">Math</span>.round( source.width <span style="color: #666666">/</span> columns );
			<span style="color: #008000; font-weight: bold">var</span> h<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #008000">Math</span>.round( source.height <span style="color: #666666">/</span> columns );

			<span style="color: #008000; font-weight: bold">var</span> p<span style="color: #666666">:</span><span style="color: #008000">Point</span> <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">new</span> <span style="color: #008000">Point</span>();
			<span style="color: #008000; font-weight: bold">var</span> rect<span style="color: #666666">:</span><span style="color: #008000">Rectangle</span> <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">new</span> <span style="color: #008000">Rectangle</span>(<span style="color: #666666">0,0,0,0</span>);
			<span style="color: #008000; font-weight: bold">var</span> box<span style="color: #666666">:</span><span style="color: #008000">BitmapData</span> <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">new</span> <span style="color: #008000">BitmapData</span>( w<span style="color: #666666">,</span> h<span style="color: #666666">,</span> <span style="color: #008000; font-weight: bold">false</span> );

			<span style="color: #008000; font-weight: bold">for</span> (<span style="color: #008000; font-weight: bold">var</span> i<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0;</span> i <span style="color: #666666">&lt;</span> colors<span style="color: #666666">;</span> i<span style="color: #666666">++</span>)
			{
				rect.x <span style="color: #666666">=</span> x<span style="color: #666666">;</span>
				rect.y <span style="color: #666666">=</span> y<span style="color: #666666">;</span>
				rect.width <span style="color: #666666">=</span> w<span style="color: #666666">;</span>
				rect.height <span style="color: #666666">=</span> h<span style="color: #666666">;</span>

				box.copyPixels( source<span style="color: #666666">,</span> rect<span style="color: #666666">,</span> p );

				averages[i] <span style="color: #666666">=</span>  averageColour( box );

				col <span style="color: #666666">=</span> i <span style="color: #666666">%</span> columns<span style="color: #666666">;</span>

				x <span style="color: #666666">=</span> w <span style="color: #666666">*</span> col<span style="color: #666666">;</span>
				y <span style="color: #666666">=</span> h <span style="color: #666666">*</span> row<span style="color: #666666">;</span>

				<span style="color: #008000; font-weight: bold">if</span> ( col <span style="color: #666666">==</span> columns <span style="color: #666666">-</span> <span style="color: #666666">1</span> )
				{
					row<span style="color: #666666">++;</span>
				}
			}
			box.dispose();
			<span style="color: #008000; font-weight: bold">return</span> averages<span style="color: #666666">;</span>
		}
	}
}
</pre>
</div>
<p>&nbsp;</p>
<p><strong>Lessons learned</strong></p>
<p><strong>Profile content to isolate bottlenecks</strong> : I skipped that step in this case since my code consisted of only two methods, but even in that case, the most significant improvement came from a single optimization. Profile so you know where to focus your efforts.</p>
<p><strong>Test and profile all optimizations</strong> : Make sure to test performance after each optimization, as optimizations do not always have the desired effect.</p>
<p><strong>Test on target devices and platforms</strong> : Optimizations can have a different impact on where they are run. This includes browser, platform and device, as well as player type (debug vs release). For example, when testing directly from Flash Authoring, results where significantly slower than when testing in the browser. </p>
<p><strong>Test the results of the optimizations</strong> : Make sure that your optimizations do not break your code or content. The best way to do this is by using unit tests and running them after each optimization.</p>
<p>There is still some potential for optimization. In particular, since the code is essentially looping over all of the pixels of a bitmap and then doing some math operations on their values, this could be a good candidate for porting to PixelBender.</p>
<p>If you have any additional optimizations, questions or suggestions, post them in the comments.</p>
<p>Also, make sure to check out <a href="http://blog.soulwire.co.uk/">soulwire&#8217;s blog</a>, as he is doing some very cool stuff with ActionScript 3 and Flash.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mikechambers.com/blog/2009/10/13/case-study-actionscript-3-performance-optimization/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>Parsing and displaying BMP files via ActionScript</title>
		<link>http://www.mikechambers.com/blog/2009/09/17/parsing-and-displaying-bmp-files-via-actionscript/</link>
		<comments>http://www.mikechambers.com/blog/2009/09/17/parsing-and-displaying-bmp-files-via-actionscript/#comments</comments>
		<pubDate>Thu, 17 Sep 2009 21:32:20 +0000</pubDate>
		<dc:creator>mikechambers</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[bytearray]]></category>

		<guid isPermaLink="false">http://www.mikechambers.com/blog/?p=1830</guid>
		<description><![CDATA[I dont have a formal computer science training / education, so I never got the chance to learn about working with low level data structures (bits and bytes). I have wanted to learn this for some time, but had difficulty finding resources for it which didnt assume I had a computer science degree. Well, yesterday, [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.mikechambers.com%2Fblog%2F2009%2F09%2F17%2Fparsing-and-displaying-bmp-files-via-actionscript%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif&amp;source=mesh&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>I dont have a formal computer science training / education, so I never got the chance to learn about working with low level data structures (bits and bytes). I have wanted to learn this for some time, but had difficulty finding resources for it which didnt assume I had a computer science degree.</p>
<p>Well, yesterday, FITC posted <a href="http://www.fitc.ca/media/">all of the video sessions from FITC Toronto</a>, and I spent some time watching Lee Brimelow&#8217;s presentation on working with ByteArrays. It is a really great session, that provides a clear and solid foundation and understanding of working with ByteArrays and bits and bytes.</p>
<p>Anyways, after watching Lee&#8217;s session, it all finally clicked for me, and I spent some time last night putting together a simple parser that would dynamically load and display a <a href="http://en.wikipedia.org/wiki/BMP%5Ffile%5Fformat">24Bit BMP image file</a> within Flash.<br />
<span id="more-1830"></span><br />
I wanted to post the code below, along with complete comments, in order to provide a simple, real world example for anyone else interested in learning how to work with lower level file formats. </p>
<p>The code requires Adobe AIR (so I can load the BMP directly). In order to convert to the Flash Player in the browser, just replace the File loading with FileReference.browse.</p>
<div class="highlight">
<pre>package
{
	<span style="color: #008000; font-weight: bold">import</span> flash.filesystem.File<span style="color: #666666">;</span>
	<span style="color: #008000; font-weight: bold">import</span> flash.filesystem.FileStream<span style="color: #666666">;</span>
	<span style="color: #008000; font-weight: bold">import</span> flash.filesystem.FileMode<span style="color: #666666">;</span>

	<span style="color: #008000; font-weight: bold">import</span> flash.display.Sprite<span style="color: #666666">;</span>
	<span style="color: #008000; font-weight: bold">import</span> flash.display.<span style="color: #008000">BitmapData</span><span style="color: #666666">;</span>
	<span style="color: #008000; font-weight: bold">import</span> flash.display.Bitmap<span style="color: #666666">;</span>
	<span style="color: #008000; font-weight: bold">import</span> flash.utils.Endian<span style="color: #666666">;</span>

	<span style="color: #008000; font-weight: bold">import</span> flash.geom.<span style="color: #008000">Rectangle</span><span style="color: #666666">;</span>

	[SWF(width<span style="color: #666666">=</span><span style="color: #BA2121">&#39;550&#39;</span><span style="color: #666666">,</span> height<span style="color: #666666">=</span><span style="color: #BA2121">&#39;400&#39;</span><span style="color: #666666">,</span> backgroundColor<span style="color: #666666">=</span><span style="color: #BA2121">&#39;#FFFFFF&#39;</span><span style="color: #666666">,</span> frameRate<span style="color: #666666">=</span><span style="color: #BA2121">&#39;12&#39;</span>)]
	<span style="color: #008000; font-weight: bold">public</span> <span style="color: #008000; font-weight: bold">class</span> BMPViewer <span style="color: #008000; font-weight: bold">extends</span> Sprite
	{
		<span style="color: #008000; font-weight: bold">private</span> <span style="color: #008000; font-weight: bold">static</span> const MAGIC_NUMBER<span style="color: #666666">:</span><span style="color: #008000">String</span> <span style="color: #666666">=</span> <span style="color: #BA2121">&quot;BM&quot;</span><span style="color: #666666">;</span>
		<span style="color: #008000; font-weight: bold">private</span> <span style="color: #008000; font-weight: bold">static</span> const BMP_DATA_OFFSET_POSITION<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0</span>xA<span style="color: #666666">;</span>
		<span style="color: #008000; font-weight: bold">private</span> <span style="color: #008000; font-weight: bold">static</span> const WIDTH_POSITION<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0x12;</span>
		<span style="color: #008000; font-weight: bold">private</span> <span style="color: #008000; font-weight: bold">static</span> const HEIGHT_POSITION<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0x16;</span>

		<span style="color: #008000; font-weight: bold">public</span> <span style="color: #008000; font-weight: bold">function</span> BMPViewer()
		{
			loadBMP();
			<span style="color: #008000; font-weight: bold">super</span>();
		}

		<span style="color: #408080; font-style: italic">/*</span>
<span style="color: #408080; font-style: italic">			Loads and reads a 24 Bit bitmap file.</span>
<span style="color: #408080; font-style: italic">			</span>
<span style="color: #408080; font-style: italic">			Based on BMP info from:</span>
<span style="color: #408080; font-style: italic">			http://en.wikipedia.org/wiki/BMP%5Ffile%5Fformat</span>
<span style="color: #408080; font-style: italic">		*/</span>
		<span style="color: #008000; font-weight: bold">private</span> <span style="color: #008000; font-weight: bold">function</span> loadBMP()<span style="color: #666666">:</span>void
		{
			<span style="color: #408080; font-style: italic">//Load BMP. This requires AIR.</span>
			<span style="color: #408080; font-style: italic">//Use FileReference.browse for</span>
			<span style="color: #408080; font-style: italic">//Flash Player</span>
			<span style="color: #008000; font-weight: bold">var</span> bmpFile<span style="color: #666666">:</span>File <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">new</span> File(<span style="color: #BA2121">&quot;app:/image.bmp&quot;</span>);
			<span style="color: #008000; font-weight: bold">var</span> fs<span style="color: #666666">:</span>FileStream <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">new</span> FileStream();

			<span style="color: #408080; font-style: italic">//BMP files are Little Endian, which means their</span>
			<span style="color: #408080; font-style: italic">//least significant byte is first (right to left)</span>
			fs.endian <span style="color: #666666">=</span> Endian.LITTLE_ENDIAN<span style="color: #666666">;</span>

			<span style="color: #408080; font-style: italic">//open the file in READ mode</span>
			fs.open(bmpFile<span style="color: #666666">,</span> FileMode.READ);

			<span style="color: #408080; font-style: italic">//check the first two bytes to make sure</span>
			<span style="color: #408080; font-style: italic">//it is a valid BMP file</span>
			<span style="color: #008000; font-weight: bold">if</span>(fs.readUTFBytes(<span style="color: #666666">2</span>) <span style="color: #666666">!=</span> MAGIC_NUMBER)
			{
				<span style="color: #0000FF">trace</span>(<span style="color: #BA2121">&quot;FAIL : NOT A BMP FILE&quot;</span>);

				<span style="color: #408080; font-style: italic">//not a BMP file, close steam</span>
				<span style="color: #408080; font-style: italic">//and exit</span>
				fs.close();
				<span style="color: #008000; font-weight: bold">return</span><span style="color: #666666">;</span>
			}

			<span style="color: #408080; font-style: italic">//note, we could also grab the length from the </span>
			<span style="color: #408080; font-style: italic">//header and make sure the file was the correct</span>
			<span style="color: #408080; font-style: italic">//length</span>

			<span style="color: #408080; font-style: italic">//change the cursors position to the point</span>
			<span style="color: #408080; font-style: italic">//in the header that contains the value / offset</span>
			<span style="color: #408080; font-style: italic">//of where the actual bitmap data begins</span>
			<span style="color: #408080; font-style: italic">//read in the 4 Bytes that contain the value</span>
			fs.position <span style="color: #666666">=</span> BMP_DATA_OFFSET_POSITION<span style="color: #666666">;</span>
			<span style="color: #008000; font-weight: bold">var</span> dataPosition<span style="color: #666666">:</span>int <span style="color: #666666">=</span> fs.readInt();

			<span style="color: #408080; font-style: italic">//set cursor position to where the BMP</span>
			<span style="color: #408080; font-style: italic">//width is stored</span>
			fs.position <span style="color: #666666">=</span> WIDTH_POSITION<span style="color: #666666">;</span>

			<span style="color: #408080; font-style: italic">//read in the 4 Bytes that contain the width</span>
			<span style="color: #008000; font-weight: bold">var</span> bmpWidth<span style="color: #666666">:</span>int <span style="color: #666666">=</span> fs.readInt();

			<span style="color: #408080; font-style: italic">//read in the 4 Bytes that contain the height</span>
			<span style="color: #008000; font-weight: bold">var</span> bmpHeight<span style="color: #666666">:</span>int <span style="color: #666666">=</span> fs.readInt();

			<span style="color: #408080; font-style: italic">//set cursor to where the BMP pixel data begins</span>
			fs.position <span style="color: #666666">=</span> dataPosition<span style="color: #666666">;</span>

			<span style="color: #008000; font-weight: bold">var</span> row<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0;</span>
			<span style="color: #008000; font-weight: bold">var</span> column<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0;</span>

			<span style="color: #408080; font-style: italic">//every row length in a BMP file must bee a multiple</span>
			<span style="color: #408080; font-style: italic">//of 4 (see the spec). So, we need to determine how much</span>
			<span style="color: #408080; font-style: italic">//padding we need to add at the end of each line. </span>
			<span style="color: #008000; font-weight: bold">var</span> padding<span style="color: #666666">:</span>int <span style="color: #666666">=</span> (bmpWidth <span style="color: #666666">%</span> <span style="color: #666666">4</span>);

			<span style="color: #408080; font-style: italic">//create a fixed length Vector to store the pixel</span>
			<span style="color: #408080; font-style: italic">//values as we read them.</span>
			<span style="color: #008000; font-weight: bold">var</span> pixels<span style="color: #666666">:</span>Vector.<span style="color: #666666">&lt;</span>uint<span style="color: #666666">&gt;</span> <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">new</span> Vector.<span style="color: #666666">&lt;</span>uint<span style="color: #666666">&gt;</span>(bmpWidth <span style="color: #666666">*</span> bmpHeight<span style="color: #666666">,</span> <span style="color: #008000; font-weight: bold">true</span>);

			<span style="color: #408080; font-style: italic">//loop through data (rows and columns)</span>
			<span style="color: #408080; font-style: italic">//note that data stored in BMP is backwards to Flash and is</span>
			<span style="color: #408080; font-style: italic">//stored from bottom row up, not top row down.</span>
			<span style="color: #408080; font-style: italic">//So we have to loop backwards</span>
			<span style="color: #008000; font-weight: bold">var</span> counter<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0;</span>
			<span style="color: #008000; font-weight: bold">for</span>(<span style="color: #008000; font-weight: bold">var</span> i<span style="color: #666666">:</span>int <span style="color: #666666">=</span> bmpHeight<span style="color: #666666">;</span> i <span style="color: #666666">&gt;</span> <span style="color: #666666">0;</span> i<span style="color: #666666">--</span>)
			{
				<span style="color: #008000; font-weight: bold">for</span>(<span style="color: #008000; font-weight: bold">var</span> k<span style="color: #666666">:</span>int <span style="color: #666666">=</span> <span style="color: #666666">0;</span> k <span style="color: #666666">&lt;</span> bmpWidth<span style="color: #666666">;</span> k<span style="color: #666666">++</span>)
				{

					<span style="color: #008000; font-weight: bold">var</span> position<span style="color: #666666">:</span>int <span style="color: #666666">=</span> ((i <span style="color: #666666">-</span> <span style="color: #666666">1</span>) <span style="color: #666666">*</span> bmpWidth) <span style="color: #666666">+</span> k<span style="color: #666666">;</span>
					<span style="color: #408080; font-style: italic">/*</span>
<span style="color: #408080; font-style: italic">						This is the original code that I had which works fine</span>
<span style="color: #408080; font-style: italic">						but is not as effecient as what I have now.</span>
<span style="color: #408080; font-style: italic">						</span>
<span style="color: #408080; font-style: italic">						Basically, Pixels are stored within 3 sucessive Bytes</span>
<span style="color: #408080; font-style: italic">						in a BMP file, with one Byte each for Blue, Green and</span>
<span style="color: #408080; font-style: italic">						Red values (in that order).</span>
<span style="color: #408080; font-style: italic">						</span>
<span style="color: #408080; font-style: italic">						So, this reads the Bytes for each pixel, one at a time</span>
<span style="color: #408080; font-style: italic">						and then combines them into a single value which is</span>
<span style="color: #408080; font-style: italic">						the combined RGB pixel value.</span>
<span style="color: #408080; font-style: italic">						</span>
<span style="color: #408080; font-style: italic">						I left the code as I think it make it a little easier to</span>
<span style="color: #408080; font-style: italic">						understand what is going on, as well as how some of these</span>
<span style="color: #408080; font-style: italic">						calls can be optimized.</span>
<span style="color: #408080; font-style: italic">					*/</span>

					<span style="color: #408080; font-style: italic">/*</span>
<span style="color: #408080; font-style: italic">					var blue:int = fs.readUnsignedByte();</span>
<span style="color: #408080; font-style: italic">					var green:int = fs.readUnsignedByte();</span>
<span style="color: #408080; font-style: italic">					var red:int = fs.readUnsignedByte();</span>
<span style="color: #408080; font-style: italic">					</span>
<span style="color: #408080; font-style: italic">					pixels[position] = (red &lt;&lt; 16 ^ green &lt;&lt; 8 ^ blue);</span>
<span style="color: #408080; font-style: italic">					*/</span>

					<span style="color: #408080; font-style: italic">/*</span>
<span style="color: #408080; font-style: italic">						Here is the final code which is more efficient, as it only</span>
<span style="color: #408080; font-style: italic">						needs to make 2 read calls in order to get the values.</span>
<span style="color: #408080; font-style: italic">						</span>
<span style="color: #408080; font-style: italic">						Thanks to Thibault Imbert (bytearray.org) for pointing out</span>
<span style="color: #408080; font-style: italic">						and helping me understand the optimization.</span>
<span style="color: #408080; font-style: italic">					*/</span>

					<span style="color: #408080; font-style: italic">//bytes in file are in Blue, Green, Red order</span>
					<span style="color: #408080; font-style: italic">//int is 32 bits (8 bytes). So, we store the first two bytes of the pixel</span>
					<span style="color: #408080; font-style: italic">// (which contain the Red value), and</span>
					<span style="color: #408080; font-style: italic">//then shift everything over 1 byte (8bits) to make room for</span>
					<span style="color: #408080; font-style: italic">//the green and blue values (remember the file is little endian), which we</span>
					<span style="color: #408080; font-style: italic">// then write into the int in the right position</span>
					<span style="color: #408080; font-style: italic">//The final value has the colors in the correct order (Red, Green, Blue)</span>

					<span style="color: #008000; font-weight: bold">var</span> pixelValue<span style="color: #666666">:</span>uint <span style="color: #666666">=</span> fs.readUnsignedByte() <span style="color: #666666">|</span> fs.readUnsignedShort() <span style="color: #666666">&lt;&lt;</span> <span style="color: #666666">8;</span>
					pixels[position] <span style="color: #666666">=</span> pixelValue<span style="color: #666666">;</span>
				}

				<span style="color: #408080; font-style: italic">//we are at the end of the row, so now we have to move the cursor</span>
				<span style="color: #408080; font-style: italic">//forward so it ends on a multiple of 4</span>
				<span style="color: #008000; font-weight: bold">if</span>(padding)
				{
					fs.position <span style="color: #666666">+=</span> padding<span style="color: #666666">;</span>
				}
			}

			<span style="color: #408080; font-style: italic">//done reading file, close stream.</span>
			fs.close();

			<span style="color: #408080; font-style: italic">//create a Rectangle with width / height of Bitmap</span>
			<span style="color: #008000; font-weight: bold">var</span> rect<span style="color: #666666">:</span><span style="color: #008000">Rectangle</span> <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">new</span> <span style="color: #008000">Rectangle</span>(<span style="color: #666666">0,</span> <span style="color: #666666">0,</span> bmpWidth<span style="color: #666666">,</span> bmpHeight);

			<span style="color: #408080; font-style: italic">//create the BitmapData object to hold hold the BMP data.</span>
			<span style="color: #408080; font-style: italic">//we do a red fill here so it is easier to see if we have any errors</span>
			<span style="color: #408080; font-style: italic">//in our code</span>
			<span style="color: #008000; font-weight: bold">var</span> bmpData<span style="color: #666666">:</span><span style="color: #008000">BitmapData</span> <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">new</span> <span style="color: #008000">BitmapData</span>(bmpWidth<span style="color: #666666">,</span> bmpHeight<span style="color: #666666">,</span> <span style="color: #008000; font-weight: bold">false</span><span style="color: #666666">,</span> <span style="color: #666666">0</span>xFF0000);

			<span style="color: #408080; font-style: italic">//copy the BMP pixel data into the BitmapData</span>
			bmpData.setVector(rect<span style="color: #666666">,</span> pixels);

			<span style="color: #408080; font-style: italic">//create a new Bitmap instance using the BitmapData</span>
			<span style="color: #008000; font-weight: bold">var</span> bitmap<span style="color: #666666">:</span>Bitmap <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">new</span> Bitmap(bmpData);
			bitmap.x <span style="color: #666666">=</span> <span style="color: #666666">10;</span>
			bitmap.y <span style="color: #666666">=</span> <span style="color: #666666">10;</span>

			<span style="color: #408080; font-style: italic">//add Bitmap to the display list</span>
			addChild(bitmap);
		}
	}
}
</pre>
</div>
<p>&nbsp;</p>
<p>You can download the example from <a href="/blog/files/examples/BMPViewer.zip">here</a>.</p>
<p>Thanks to <a href="http://www.theflashblog.com">Lee</a> for his presentation, and <a href="http://www.bytearray.org">Thibault Imber</a>t who helped me understand some of the details around endianes, as well as made some suggestions for optimizations.</p>
<p>If you are interested in learning more, I strong suggest watching L<a href="http://www.fitc.ca/media/">ee&#8217;s FITC Presentation</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mikechambers.com/blog/2009/09/17/parsing-and-displaying-bmp-files-via-actionscript/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Converting from Matrix3D to Matrix in ActionScript 3</title>
		<link>http://www.mikechambers.com/blog/2009/09/09/converting-from-a-matrix3d-to-matrix-in-actionscript-3/</link>
		<comments>http://www.mikechambers.com/blog/2009/09/09/converting-from-a-matrix3d-to-matrix-in-actionscript-3/#comments</comments>
		<pubDate>Wed, 09 Sep 2009 17:48:06 +0000</pubDate>
		<dc:creator>mikechambers</dc:creator>
				<category><![CDATA[ActionScript]]></category>

		<guid isPermaLink="false">http://www.mikechambers.com/blog/?p=1791</guid>
		<description><![CDATA[For the past month or two, I have been spending time building a game (something I havent done since my Flash 4 days). This has really been a lot of fun, as it has allowed me to use some of the Flash Player APIs which I really haven&#8217;t had a chance or need to use [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.mikechambers.com%2Fblog%2F2009%2F09%2F09%2Fconverting-from-a-matrix3d-to-matrix-in-actionscript-3%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif&amp;source=mesh&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>For the past month or two, I have been spending time building a game (something I havent done since my Flash 4 days). This has really been a lot of fun, as it has allowed me to use some of the Flash Player APIs which I really haven&#8217;t had a chance or need to use before. </p>
<p>One thing which I have been (slowly) learning about are using Matrix transformations on DisplayObjects. I made a post earlier showing how (with much, much help from <a href="http://www.senocular.com/">Senocular</a>), I was able to <a href="http://www.mikechambers.com/blog/2009/06/24/using-bitmapdata-hittest-for-collision-detection/">use Matrix to do hit tests using BitmapData.hitTest on DisplayObjects</a> which have had transformations applied to them (in this case, rotation).</p>
<p>Well, I recently had the need to convert some of my DisplayObjects to use the 2.5D APIs (by setting the z property to a value). Unfortunately, this ended up breaking a lot of my code, mostly because of how it changes how transformations are applied to a DisplayObject. Specifically, when you set the <code>DisplayObject.z</code> property to any value, <code>DisplayObject.transform.matrix</code> will return null, and you must use <code>DisplayObject.transform.matrix3D</code> instead. Where this causes problems is when you are using APIs that expect to use a <code>Matrix</code> instance, as opposed to <code>Matrix3D</code> instance, such as <code>BitmapData.draw</code>.<br />
<span id="more-1791"></span><br />
This is exactly the scenario I ran into, and this post will show one solution for how to convert from a Matrix3D to a Matrix instance, which can then be passed to the BitmapData.draw.</p>
<p>First, lets look at my original code:</p>
<div class="highlight">
<pre>shipBmpData <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">new</span> <span style="color: #008000">BitmapData</span>(shipBounds.width<span style="color: #666666">,</span>
				shipBounds.height<span style="color: #666666">,</span> <span style="color: #008000; font-weight: bold">true</span><span style="color: #666666">,</span> <span style="color: #666666">0</span>);

<span style="color: #008000; font-weight: bold">var</span> shipOffset<span style="color: #666666">:</span><span style="color: #008000">Matrix</span> <span style="color: #666666">=</span> ship.transform.matrix<span style="color: #666666">;</span>
shipOffset.tx <span style="color: #666666">=</span> ship.x <span style="color: #666666">-</span> shipBounds.x<span style="color: #666666">;</span>
shipOffset.ty <span style="color: #666666">=</span> ship.y <span style="color: #666666">-</span> shipBounds.y<span style="color: #666666">;</span>			

shipBmpData.draw(ship<span style="color: #666666">,</span> shipOffset);
</pre>
</div>
<p>&nbsp;</p>
<p>Basically, this draws the bitmap data for my ship into a <code>BitmapData</code> instance, taking into account any transformations which have been applied to the ship (in this case rotation). In my code, this bitmap data is cached, and then later used with <code>BitmapData.hitTest</code> for collision detection (not shown here).</p>
<p>However, as soon as I set the z property on the ship (which is a DisplayObject), this code will no longer work, as <code>ship.transform.matrix</code> will return null (since 3D transformations are now being used).</p>
<p>At first, I figured I would just change my code to access the Matrix3D instance like so:</p>
<div class="highlight">
<pre><span style="color: #008000; font-weight: bold">var</span> shipOffset<span style="color: #666666">:</span>Matrix3D <span style="color: #666666">=</span> ship.transform.matrix3D<span style="color: #666666">;</span>
</pre>
</div>
<p>&nbsp;</p>
<p>and then pass this to the <code>BitmapData.draw</code> API. However, I was quickly reminded (by the compiler) that <code>Matrix3D</code> does not inherit from <code>Matrix</code>, and thus cannot be passed to <code>BitmapData.draw</code>.</p>
<p>Because of this I needed to convert from a <code>Matrix3D</code> to a <code>Matrix</code> instance, which could then be passed to <code>BitmapData.draw</code>. After some help from <a href="http://www.unitzeroone.com/blog/">Ralph Hauwert</a> (who tracked down a couple of bugs) I was able to get it working.</p>
<p>Before I show the code, it will be useful to look at which values <code>Matrix</code> and <code>Matrix3D</code> contain. First, here are the values held by a <code>Matrix</code> instance:</p>
<pre><code>a  c  tx
b  d  ty
u  v  w</code></pre>
<p>&nbsp;</p>
<p>You can find a description of the properties in the <a href="http://livedocs.adobe.com/flex/3/langref/flash/geom/Matrix.html#propertySummary">Matrix docs</a>.</p>
<p>Here are the values held by a Matrix3D instance:</p>
<pre><code>scaleX  0         0          tx
0         scaleY  0          ty
0         0           scaleZ  tz
0         0          0          tw</code></pre>
<p>&nbsp;</p>
<p>From the <a href="http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/geom/Matrix3D.html">Matrix3D docs</a>:</p>
<blockquote><p>The Matrix3D class uses a 4&#215;4 square matrix: a table of four rows and columns of numbers that hold the data for the transformation. The first three rows of the matrix hold data for each 3D axis (x,y,z). The translation information is in the last column. The orientation and scaling data are in the first three columns. The scaling factors are the diagonal numbers in the first three columns</p></blockquote>
<p>Basically, in addition to holding values for x and y, the <code>Matrix3D</code> class also has slots for z properties. Because the <code>Matrix</code> is a 3&#215;3 matrix, and the <code>Matrix3D</code> is a 4&#215;4 matrix converting from <code>Matrix3d</code> to <code>Matrix</code> means that we will have to discard some information. Luckily, in my case, I didnt need the z information, so i was able to discard it and map the related x, y values to the <code>Matrix</code> instance. We can then pass this new <code>Matrix</code> instance to the <code>BitmapData.draw</code> class.</p>
<p>For our purposes, the <code>Matrix3D</code> mapping to <code>Matrix</code> is:</p>
<pre><code>a  c   0          tx
b  d  0          ty
0  0  scaleZ  tz
0  0  0          tw</code></pre>
<p>Here is the code that maps between the two:</p>
<div class="highlight">
<pre><span style="color: #008000; font-weight: bold">var</span> shipOffset<span style="color: #666666">:</span>Matrix3D <span style="color: #666666">=</span> ship.transform.matrix3D<span style="color: #666666">;</span>

<span style="color: #008000; font-weight: bold">var</span> rawMatrixData<span style="color: #666666">:</span>Vector.<span style="color: #666666">&lt;</span><span style="color: #008000">Number</span><span style="color: #666666">&gt;</span> <span style="color: #666666">=</span> shipOffset.rawData<span style="color: #666666">;</span>

<span style="color: #008000; font-weight: bold">var</span> matrix<span style="color: #666666">:</span><span style="color: #008000">Matrix</span> <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">new</span> <span style="color: #008000">Matrix</span>();
matrix.a <span style="color: #666666">=</span> rawMatrixData[<span style="color: #666666">0</span>];
matrix.c <span style="color: #666666">=</span> rawMatrixData[<span style="color: #666666">1</span>];
matrix.tx <span style="color: #666666">=</span> ship.x <span style="color: #666666">-</span> shipBounds.x<span style="color: #666666">;</span>

matrix.b <span style="color: #666666">=</span> rawMatrixData[<span style="color: #666666">4</span>];
matrix.d <span style="color: #666666">=</span> rawMatrixData[<span style="color: #666666">5</span>];
matrix.ty <span style="color: #666666">=</span> ship.y <span style="color: #666666">-</span> shipBounds.y<span style="color: #666666">;</span>

ship.transform.matrix3D <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">null</span><span style="color: #666666">;</span>
shipBmpData.draw(ship<span style="color: #666666">,</span> matrix);
ship.transform.matrix3D <span style="color: #666666">=</span> shipOffset<span style="color: #666666">;</span>
</pre>
</div>
<p>&nbsp;</p>
<p>Basically, we get an instance of the <code>Matrix3D</code> class for the <code>DisplayObject</code>. We then access the raw data of the <code>Matrix3D</code> instance, and copy it into a new <code>Matrix</code> instance (ignoring and dropping the z values), and apply the transformation corrections in the process.</p>
<p>We can then pass this new <code>Matrix</code> instance to the <code>BitmapData.draw</code> API. However, as you probably noticed in the code, I had to first do an additional step. Specifically:</strike ></p>
<div class="highlight">
<pre>ship.transform.matrix3D <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">null</span><span style="color: #666666">;</span>
shipBmpData.draw(ship<span style="color: #666666">,</span> matrix);
ship.transform.matrix3D <span style="color: #666666">=</span> shipOffset<span style="color: #666666">;</span>
</pre>
</div>
<p>&nbsp;</p>
<p>Before we draw the data to the <code>BitmapData</code> instance, we have to clear out the existing <code>Matrix3D</code> applied to the <code>DisplayObject</code>. This is to work around a bug discovered by <a href="http://www.unitzeroone.com/blog/">Ralph Hauwert</a>. When passing a <code>DisplayObject</code> which does not have a <code>Matrix3D</code> transformation (as in our first example) to <code>BitmapData.draw</code>, any transformations on the <code>DisplayObject</code> ARE NOT taken into account when drawing. However, when the the <code>DisplayObject</code> does have a <code>Matrix3D</code> transformation applied to it (such as when the z property has been set to a value), then any transformations ARE applied when drawing to <code>BitmapData.draw</code>. Because of this, we have to first store the <code>Matrix3D</code> associated with the DisplayObject, set it to null, draw the <code>DisplayObject</code> to the <code>BitmapData</code> instance, and then reapply the <code>Matrix3D</code> to the <code>DisplayObject</code>.</p>
<p><strike><strong>Update</strong>: as <a href="http://www.mikechambers.com/blog/2009/09/09/converting-from-a-matrix3d-to-matrix-in-actionscript-3/#comment-16700">Ben Garney points out in the comments</a>, since the transformation is applied to <code>BitmapData.draw</code> when <code>Matrix3D</code> is set, all we need to do is pass in either an identiy matrix, or null to the second argument of the API. So, in my case, this solves my problems, and removes the need to convert bewteen the matrix types.</strike></p>
<p><strike>The updated code is simply:</strike></p>
<p><strike>
<div class="highlight">
<pre>shipBmpData <span style="color: #666666">=</span> <span style="color: #008000; font-weight: bold">new</span> <span style="color: #008000">BitmapData</span>(shipBounds.width<span style="color: #666666">,</span>
				shipBounds.height<span style="color: #666666">,</span> <span style="color: #008000; font-weight: bold">true</span><span style="color: #666666">,</span> <span style="color: #666666">0</span>);
shipBmpData.draw(ship<span style="color: #666666">,</span> <span style="color: #008000; font-weight: bold">null</span>);
</pre>
</div>
<p></strike></p>
<p>&nbsp;</p>
<p><strike>which turns out to be much less complex than when you use the 2D APIs. However, the technique above for converting between matrix types is still valid.</strike></p>
<p><strong>Update 2</strong>: It turns out passing in null or an identity matrix to <code>BitmapData.draw</code>. does not work correctly.</p>
<p>Of course, this is not always necessary when converting from a <code>Matrix</code> instance to a <code>Matrix3D</code> instance, but in my case it was. As you can imagine, this can have some significant performance implications, both because of memory allocation and deallocation, as well as the fact that removing the <code>Matrix3D</code>, even temporarily, changes how the <code>DisplayObject</code> is rendered.</p>
<p>Right now, this trade off is ok in my case, although I am not sure if it will be for the long term. Again, in my case, I may need to look at some re-architecting so I don&#8217;t have to work around this issue (such as nesting clips and cacheing the parent <code>BitmapData</code>, so I don&#8217;t have to apply the transformations).</p>
<p>Anyways, I am just learning the implications of using the 2.5D APIs in the Flash Player. This is an area where there is not currently a lot of information or documentation, especially information on the implications of moving from 2D to 2.5D APIs. Hopefully this will be useful.</p>
<p>Here are a couple of other resources which I found useful:</p>
<p><a href="http://adobe.com/go/AS3LR">API docs for Matrix, Matrix3D, Transformation and DisplayObject</a>.</p>
<p><a href="http://www.bytearray.org/wp-content/projects/fp10-session/">Thibault Imbert&#8217;s Flash Player 10 Presentation</a>, which has some good info on the 2.5D APIS.</p>
<p><a href="http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WSF24A5A75-38D6-4a44-BDC6-927A2B123E90.html">Flash CS4 Docs : Working in three dimensions</a></p>
<p>As I mentioned above, I am still getting my head around some of this stuff, so if you have any clarifications or corrections, post them in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mikechambers.com/blog/2009/09/09/converting-from-a-matrix3d-to-matrix-in-actionscript-3/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>What new game APIs do you want in the Flash Player?</title>
		<link>http://www.mikechambers.com/blog/2009/06/16/what-new-game-apis-do-you-want-in-the-flash-player/</link>
		<comments>http://www.mikechambers.com/blog/2009/06/16/what-new-game-apis-do-you-want-in-the-flash-player/#comments</comments>
		<pubDate>Tue, 16 Jun 2009 19:03:57 +0000</pubDate>
		<dc:creator>mikechambers</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[flashplayer]]></category>
		<category><![CDATA[games]]></category>

		<guid isPermaLink="false">http://www.mikechambers.com/blog/?p=1741</guid>
		<description><![CDATA[I have been learning some game development lately, and building my first game (well, at least my first game since Flash 4). I think game development and deployment are some of the real strengths of the Flash player, but ones which we haven&#8217;t specifically focused on in a while. While working on my game, there [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.mikechambers.com%2Fblog%2F2009%2F06%2F16%2Fwhat-new-game-apis-do-you-want-in-the-flash-player%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif&amp;source=mesh&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>I have been learning some game development lately, and building my first game (well, at least my first game since Flash 4). I think game development and deployment are some of the real strengths of the Flash player, but ones which we haven&#8217;t specifically focused on in a while.</p>
<p>While working on my game, there were a couple of things I needed to do where additional player APIs could have made the development easier (as well as likely speeding up execution). This got me to thinking about other APIs that would be useful for game development. So, what new Flash Player APIs would you like to see that would make game development easier?</p>
<p>Here are a couple from me:<br />
<span id="more-1741"></span><br />
Hit test that tests visible bounds of Sprites. Something like:</p>
<div class="highlight">
<pre>sprite.hitTestVisible(anotherSprite)<span style="color: #666666">:</span><span style="color: #008000">Boolean</span>
</pre>
</div>
<p>&nbsp;</p>
<p>Basically, something similar the <a href="http://www.gskinner.com/blog/archives/2005/10/source_code_sha.html">API Grant Skinner created</a>, but native to the player.</p>
<p>The next API I would like is one that would check for hits against multiple sprites, and return a vector of sprites that we colliding.</p>
<div class="highlight">
<pre>sprite.hitTestMultiple(sprites<span style="color: #666666">:</span>Vector.<span style="color: #666666">&lt;</span>Sprite<span style="color: #666666">&gt;</span>)<span style="color: #666666">:</span>Vector.<span style="color: #666666">&lt;</span>Sprite<span style="color: #666666">&gt;;</span>
</pre>
</div>
<p>&nbsp;</p>
<p>This would make it easy to do collision detection for multiple items, and perhaps lead to a performance boost.</p>
<p>So, what APIs would you like to see that would make game development easier. Please be as specific as possible (i.e. don&#8217;t just say &#8220;Physics engine&#8221; or 3D support). Leave you suggestions in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mikechambers.com/blog/2009/06/16/what-new-game-apis-do-you-want-in-the-flash-player/feed/</wfw:commentRss>
		<slash:comments>92</slash:comments>
		</item>
		<item>
		<title>Update to JSON support in as3corelib</title>
		<link>http://www.mikechambers.com/blog/2008/12/23/update-to-json-support-in-as3corelib/</link>
		<comments>http://www.mikechambers.com/blog/2008/12/23/update-to-json-support-in-as3corelib/#comments</comments>
		<pubDate>Tue, 23 Dec 2008 19:55:54 +0000</pubDate>
		<dc:creator>mikechambers</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[as3corelib]]></category>

		<guid isPermaLink="false">http://www.mikechambers.com/blog/?p=1639</guid>
		<description><![CDATA[Darron Schall has just checked in some changes and bug fixes to the JSON support in as3corelib. Among other things, Darron has added a strict mode which allows you to specify how strict of a conformance to the JSON spec you want the library to follow. You can read all of the details over on [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.mikechambers.com%2Fblog%2F2008%2F12%2F23%2Fupdate-to-json-support-in-as3corelib%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif&amp;source=mesh&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p><a href="http://www.darronschall.com/weblog/2008/12/as3-json-library-now-a-little-less-strict.cfm">Darron Schall</a> has just checked in some changes and bug fixes to the JSON support in <a href="http://code.google.com/p/as3corelib/">as3corelib</a>. Among other things, Darron has <a href="http://www.darronschall.com/weblog/2008/12/as3-json-library-now-a-little-less-strict.cfm">added a strict mode</a> which allows you to specify how strict of a conformance to the JSON spec you want the library to follow.<br />
<span id="more-1639"></span><br />
You can <a href="http://www.darronschall.com/weblog/2008/12/as3-json-library-now-a-little-less-strict.cfm">read all of the details over on Darron&#8217;s blog</a>. As Darron notes, these are not in the build yet, so if you want to play around with the changes, you have to grab the source.</p>
<p>I will try and do a new build soon with some more JSON changes, as well as some new code contributed from the community.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mikechambers.com/blog/2008/12/23/update-to-json-support-in-as3corelib/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adobe drops restrictions on SWF, FLV formats</title>
		<link>http://www.mikechambers.com/blog/2008/05/01/adobe-drops-restrictions-on-swf-flv-formats/</link>
		<comments>http://www.mikechambers.com/blog/2008/05/01/adobe-drops-restrictions-on-swf-flv-formats/#comments</comments>
		<pubDate>Thu, 01 May 2008 16:34:44 +0000</pubDate>
		<dc:creator>mikechambers</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[flv swf adobe open]]></category>

		<guid isPermaLink="false">http://www.mikechambers.com/blog/?p=1236</guid>
		<description><![CDATA[As you have probably seen, Adobe has dropped the licensing restrictions on both the SWF and FLV file formats. Among other things, you can know use the formats to create players that read in the formats. Check out Ryan Stewart&#8217;s weblog for more discussion We have also put up a site with some information, which [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.mikechambers.com%2Fblog%2F2008%2F05%2F01%2Fadobe-drops-restrictions-on-swf-flv-formats%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif&amp;source=mesh&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>As you have probably seen, <a href="http://www.adobe.com/openscreenproject/developers/">Adobe has dropped the licensing restrictions on both the SWF and FLV file formats</a>. Among other things, you can know use the formats to create players that read in the formats.</p>
<p>Check out Ryan Stewart&#8217;s weblog for more <a href="http://blog.digitalbackcountry.com/?p=1404">discussion</a></p>
<p>We have also put up a <a href="http://www.adobe.com/openscreenproject/developers/">site with some information</a>, which includes a <a href="http://www.adobe.com/openscreenproject/faq/">FAQ</a>.</p>
<p>You can also download the specs:</p>
<ul>
<li><a href="http://www.adobe.com/devnet/swf/">SWF 9</a></li>
<li><a href="http://www.adobe.com/devnet/flv/">FLV</a></li>
<li><a href="http://opensource.adobe.com/wiki/display/blazeds/Developer+Documentation">AMF Specification</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.mikechambers.com/blog/2008/05/01/adobe-drops-restrictions-on-swf-flv-formats/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>initializing for loop counter outside of loop in ActionScript</title>
		<link>http://www.mikechambers.com/blog/2007/10/23/initializing-for-loop-counter-outside-of-loop-in-actionscript/</link>
		<comments>http://www.mikechambers.com/blog/2007/10/23/initializing-for-loop-counter-outside-of-loop-in-actionscript/#comments</comments>
		<pubDate>Wed, 24 Oct 2007 07:43:47 +0000</pubDate>
		<dc:creator>mikechambers</dc:creator>
				<category><![CDATA[ActionScript]]></category>

		<guid isPermaLink="false">http://www.mikechambers.com/blog/2007/10/23/initializing-for-loop-counter-outside-of-loop-in-actionscript/</guid>
		<description><![CDATA[Continuing my series of posts of interesting, but not too useful ActionScript tips (which I learned from studying Objective-C), did you know that you dont have to initialize your counter variable within a for loop. For example, this is perfectly valid: package { import flash.display.Sprite; public class LoopTest extends Sprite { public function LoopTest() { [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.mikechambers.com%2Fblog%2F2007%2F10%2F23%2Finitializing-for-loop-counter-outside-of-loop-in-actionscript%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif&amp;source=mesh&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Continuing my series of posts of interesting, but not too useful ActionScript tips (which I learned from studying Objective-C), did you know that you dont have to initialize your counter variable within a for loop.</p>
<p>For example, this is perfectly valid:<br />
<span id="more-1189"></span><br />
<code>
<pre>package {
	import flash.display.Sprite;

	public class LoopTest extends Sprite
	{
		public function LoopTest()
		{
			var i:int = 0;
			for(; i < 5; i++)
			{
				trace(i);
			}

		}
	}
}</pre>
<p></code></p>
<p>As you can see, the variable is initialized outside of the loop.</p>
<p>You also don't have to include the test condition in the loop:</p>
<p><code>
<pre>package {
	import flash.display.Sprite;

	public class LoopTest extends Sprite
	{
		public function LoopTest()
		{
			var i:int = 0;
			for(; ; i++)
			{
				trace(i);

				if(i > 5)
				{
					break;
				}
			}

		}
	}
}</pre>
<p></code></p>
<p>However, if you do this (which you probably shouldn't) you have to have code in the loop to exit, or else you will freeze up the player with an infinite loop.</p>
<p>And what the heck, lets get rid of incrementing the variable in the loop definition:</p>
<p><code>
<pre>package {
	import flash.display.Sprite;

	public class LoopTest extends Sprite
	{
		public function LoopTest()
		{
			var i:int = 0;
			for(; ; )
			{
				trace(i);

				if(i > 5)
				{
					break;
				}

				i++;
			}

		}
	}
}</pre>
<p></code></p>
<p>I can't think of any reasons off the top of my head why this would be useful, but if you have any thoughts / uses, post them in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mikechambers.com/blog/2007/10/23/initializing-for-loop-counter-outside-of-loop-in-actionscript/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Using Bitwise XOR to exchange variable values in ActionScript</title>
		<link>http://www.mikechambers.com/blog/2007/10/22/using-bitwise-xor-to-exchange-variable-values-in-actionscript/</link>
		<comments>http://www.mikechambers.com/blog/2007/10/22/using-bitwise-xor-to-exchange-variable-values-in-actionscript/#comments</comments>
		<pubDate>Tue, 23 Oct 2007 05:57:33 +0000</pubDate>
		<dc:creator>mikechambers</dc:creator>
				<category><![CDATA[ActionScript]]></category>

		<guid isPermaLink="false">http://www.mikechambers.com/blog/2007/10/22/using-bitwise-xor-to-exchange-variable-values-in-actionscript/</guid>
		<description><![CDATA[I have been studying some Objective-C in my spare time, and was reading up on Bitwise operators tonight. I came across a simple way to exchange the value of two variables using the Exclusive-OR (XOR) operator that doesn&#8217;t require creating a temporary variable. Normally, if you wanted to exchange the value of two variables, you [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.mikechambers.com%2Fblog%2F2007%2F10%2F22%2Fusing-bitwise-xor-to-exchange-variable-values-in-actionscript%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif&amp;source=mesh&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>I have been <a href="http://www.amazon.com/Programming-Objective-C-Stephen-Kochan/dp/0672325861">studying some Objective-C</a> in my spare time, and was reading up on Bitwise operators tonight. I came across a simple way to exchange the value of two variables using the <a href="http://en.wikipedia.org/wiki/Bitwise_XOR#XOR">Exclusive-OR (XOR)</a> operator that doesn&#8217;t require creating a temporary variable.</p>
<p>Normally, if you wanted to exchange the value of two variables, you would have to create a temp variable to store values temporarily (which uses additional memory). For example:<br />
<span id="more-1188"></span><br />
<code>
<pre>package
{
	import flash.display.Sprite;
	import flash.system.System;

	public class SwitchVariables extends Sprite
	{
		public function SwitchVariables()
		{
			var a:int = 5;
			var b:int = 6;
			var temp:int;

			trace("a = " + a + " : b = " + b);

			temp = a;
			a = b;
			b = temp;

			trace("a = " + a + " : b = " + b);
		}
	}
}</pre>
<p></code></p>
<p>Notice that you have to create an additional variable, named <code>temp</code> to temporarily store the value while it is switched.</p>
<p>However, you can use the Bitwise XOR Operator to switch the values without having to create the temporary variable. For example:</p>
<p><code>
<pre>package
{
	import flash.display.Sprite;
	import flash.system.System;

	public class SwitchVariables extends Sprite
	{
		public function SwitchVariables()
		{
			var a:int = 5;
			var b:int = 6;

			trace("a = " + a + " : b = " + b);

			a ^= b;
			b ^= a;
			a ^= b;

			trace("a = " + a + " : b = " + b);
		}
	}
}</pre>
<p></code></p>
<p>You can find a good explanation of what the Exclusive OR operator does <a href="http://en.wikipedia.org/wiki/Bitwise_XOR#XOR">here</a> and a discussion of the XOR swap algorithm <a href="http://en.wikipedia.org/wiki/Xor_swap_algorithm">here</a>.</p>
<p>This is probably not needed in most cases (it can make the code a little harder to read), but if you are exchanging the value of variables in a loop and running into memory issues, this might come in handy.</p>
<p>Have any other bitwise operator tips? Post them in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mikechambers.com/blog/2007/10/22/using-bitwise-xor-to-exchange-variable-values-in-actionscript/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Handling Flash File Uploads with .NET</title>
		<link>http://www.mikechambers.com/blog/2007/08/06/handling-flash-file-uploads-with-net/</link>
		<comments>http://www.mikechambers.com/blog/2007/08/06/handling-flash-file-uploads-with-net/#comments</comments>
		<pubDate>Tue, 07 Aug 2007 02:51:38 +0000</pubDate>
		<dc:creator>mikechambers</dc:creator>
				<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[On AIR Tour]]></category>

		<guid isPermaLink="false">http://www.mikechambers.com/blog/2007/08/06/handling-flash-file-uploads-with-net/</guid>
		<description><![CDATA[Denis Sosnovtsev has posted a really useful blog post over on the atellis labs site. The post shows how to upload files from Flash to a .NET backend. The example includes both ActionScript and .NET / C# code snippets. You can view the entire post here. You can also view Mark Piller&#8217;s session from the [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.mikechambers.com%2Fblog%2F2007%2F08%2F06%2Fhandling-flash-file-uploads-with-net%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif&amp;source=mesh&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Denis Sosnovtsev has posted a really useful blog post over on the <a href="http://labs.atellis.com">atellis labs site</a>. The post shows <a href="http://labs.atellis.com/2007/08/01/uploading-files-from-flex-to-your-net-server/">how to upload files from Flash to a .NET backend</a>. The example includes both ActionScript and .NET / C# code snippets.</p>
<p>You can view the entire post <a href="http://labs.atellis.com/2007/08/01/uploading-files-from-flex-to-your-net-server/">here</a>.</p>
<p>You can also view <a href="http://onair.adobe.com/blogs/videos/2007/07/31/mark-pillar-integrating-air-applications-with-net/">Mark Piller&#8217;s session from the on AIR Bus tour on integrating .NET with Adobe AIR applications</a>.</p>
<p>Know any other good ActionScript / .NET resources and tutorials? Post them in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mikechambers.com/blog/2007/08/06/handling-flash-file-uploads-with-net/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

