<?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>dispatchEvent()™ &#187; Programming</title>
	<atom:link href="http://dispatchevent.org/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://dispatchevent.org</link>
	<description>Collective thoughts on the Flash Platform, iOS, Unity, and any other technology we use.</description>
	<lastBuildDate>Mon, 23 Apr 2012 19:07:06 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Ludum Dare 23 &#8211; Pre-Game</title>
		<link>http://dispatchevent.org/mims/ludum-dare-23-pre-game/</link>
		<comments>http://dispatchevent.org/mims/ludum-dare-23-pre-game/#comments</comments>
		<pubDate>Sat, 21 Apr 2012 00:13:03 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Videogames]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=1094</guid>
		<description><![CDATA[So this year I&#8217;m doing my first Ludum Dare game competition. I&#8217;m very excited and have been trying to get my system ready to go before the theme is announced at 18:00 Pacific time. I&#8217;m running down my pre-flight checklist now. My loadout: (note: I&#8217;d love to put a link to every single one of [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://ludumdare.com"><img class="alignnone size-medium wp-image-1095" title="hub-header" src="http://dispatchevent.org/wp-content/uploads/2012/04/hub-header-300x64.png" alt="" width="300" height="64" /></a></p>
<p>So this year I&#8217;m doing my first <a href="http://ludumdare.com">Ludum Dare</a> game competition. I&#8217;m very excited and have been trying to get my system ready to go before the theme is announced at 18:00 Pacific time. I&#8217;m running down my pre-flight checklist now.</p>
<p>My loadout:</p>
<div id="attachment_1097" class="wp-caption alignnone" style="width: 310px"><a href="http://dispatchevent.org/wp-content/uploads/2012/04/workspace.jpg"><img class="size-medium wp-image-1097" title="workspace" src="http://dispatchevent.org/wp-content/uploads/2012/04/workspace-300x224.jpg" alt="" width="300" height="224" /></a><p class="wp-caption-text">Note the inspirational collages and ferret poster</p></div>
<p>(note: I&#8217;d love to put a link to every single one of these but that&#8217;ll take a long time and you can google them yourself.)</p>
<p><strong>Software:</strong></p>
<ul>
<li>FlashBuilder</li>
<li>Text Mate</li>
<li>Adobe Creative Suite</li>
<li>bfxr</li>
<li>Garage Band</li>
<li>Amadeus Pro</li>
<li>Art Rage</li>
</ul>
<p><strong>Libraries (probably won&#8217;t use all of these but they&#8217;re in there just in case):</strong></p>
<ul>
<li>FlashPunk</li>
<li>KitchenSync</li>
<li>Abstract AS3</li>
<li>AS3 Signals</li>
<li>AS3 Utils</li>
<li>AS3 Core Lib</li>
<li>AS3 Data Structures</li>
<li>Google Analytics</li>
<li>Sterling</li>
<li>zOMGamezLib (This is an old game engine that probably doesn&#8217;t even compile but I might pull some useful stuff from it. <a href="http://dispatchevent.org/wp-content/uploads/2012/04/zomgamezlib.zip">source</a>)</li>
</ul>
<div>Hardware:</div>
<div>
<ul>
<li>MacBook Pro</li>
<li>Wacom Intuos5 tablet</li>
<li>M-Audio Oxygen</li>
<li>Blue Snowball Mic</li>
<li>iPhone / iPad (not sure what for)</li>
<li>Headphones</li>
<li>Scanner</li>
<li>Camera</li>
<li>Sketchbooks &amp; Pens</li>
<li>Jones Coffee</li>
</ul>
</div>
<p>You can follow me here or on Twitter <a href="http://twitter.com/mimshwright">@mimshwright</a></p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/ludum-dare-23-pre-game/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Matryoshka Functions</title>
		<link>http://dispatchevent.org/mims/matryoshka-functions/</link>
		<comments>http://dispatchevent.org/mims/matryoshka-functions/#comments</comments>
		<pubDate>Fri, 07 Jan 2011 19:22:40 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[AS3]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tips, Tricks, and Hacks]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=869</guid>
		<description><![CDATA[The other day, I was working with the Flex function BindingUtil.bindProperty(). I always have a hard time remembering which pair of arguments comes first, the &#8216;site&#8217; or the &#8216;host&#8217; and to be honest, the names don&#8217;t really make much sense to me. &#8220;Oh, if only this were an Objective-C project I would have to laboriously [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://dispatchevent.org/wp-content/uploads/2011/01/First-matryoshka-museum-doll-open.jpeg"><img src="http://dispatchevent.org/wp-content/uploads/2011/01/First-matryoshka-museum-doll-open-300x211.jpg" alt="" width="300" height="211" class="alignnone size-medium wp-image-870" /></a><br />
The other day, I was working with the Flex function BindingUtil.bindProperty(). I always have a hard time remembering which pair of arguments comes first, the &#8216;site&#8217; or the &#8216;host&#8217; and to be honest, the names don&#8217;t really make much sense to me. &#8220;Oh, if only this were an Objective-C project I would have to laboriously type out each name of each parameter.&#8221; I thought, &#8220;It would be so much more obvious if it were writen like <code>Bind.property("foo").fromObject(bar).toTheValueOfProperty("foo").ofObject(baz);</code>.&#8221; </p>
<p>What followed was the discovery/invention of just such a thing, a nested, super-verbose function. The function achieves this by returning an instance of an internal class with nothing in it except for the next step in the chain.</p>
<pre lang="actionscript3">
package
{
	public class Bind
	{
		public static function updateProperty(object:Object, property:String):BindSource {
			return new BindSource(object, property);
		}
	}
}
import mx.binding.utils.BindingUtils;
class BindSource {

	private var targetObject:Object;
	private var targetProperty:String;

	public function BindSource(targetObject:Object, targetProperty:String):void {
		this.targetObject = targetObject;
		this.targetProperty = targetProperty;
	} 

	public function whenSourcePropertyChanges(object:Object, property:String):void {
		BindingUtils.bindProperty(targetObject, targetProperty, object, property);
	}
}
</pre>
<p>To call this function you would use:</p>
<pre lang="actionscript3">Bind.updateProperty(foo, "bar").whenSourcePropertyChanges(baz, "bar");</pre>
<p>Kinda cool! I soon realized that this technique has some characteristics that Objective-C messages don&#8217;t have. For example, each step can use more than one parameter (plus they each get their own code hinting). You can also provide multiple choices for what to do next providing a sort of branching behavior.</p>
<pre lang="actionscript3">
AngleFinder.getAngleOfVector(4, 4).inDegrees() 	// 45Â°
AngleFinder.getAngleOfVector(4, 4).inRadians() 	// Ï€/4
</pre>
<p>You can even do free-form stacking of functions like this.</p>
<pre lang="actionscript3">
new Calculator	(5)                    // 5
                        .plus(3)            // 8
                        .times(2)          // 16
                        .dividedBy(4)   // 4
                        .minus(1)         // 3
                        .plus(2)            // 5
                        .equals();
</pre>
<p>I proudly named these &#8220;Matryoshka Functions&#8221; after the Russian stacking dolls even though I&#8217;m sure I&#8217;m not the first to try something like this. As it turns out, they&#8217;re about 10% practical and 90% clever hack. Even though there could be some potential use for this (especially with complicated, repetitive tasks), this technique conflicts too much with the way we normally code in ActionScript. Still, I thought it was cool enough to share with everyone.</p>
<p>Pros:</p>
<ul>
<li>Very descriptive</li>
<li>Branching and stacking effect is interesting and potentially useful</li>
<li>Code hinting shows the next step in the function as well as the parameter names</li>
<li>Looks cool!</li>
</ul>
<p>Cons:</p>
<ul>
<li>Abominable code style. Too weird to be useful.</li>
<li>Difficult to know when to stop calling functions</li>
<li>Not completing the function will produce unexpected results with no compile-time errors</li>
<li>Each step requires you to pass the parameters from the previous step</li>
</ul>
<p>Can you find any use of these? Can you think of a more efficient way to write the functions? Any other thoughts?</p>
<p>Check out the source with multiple examples (FlashBuilder project).<br />
<a href='http://dispatchevent.org/wp-content/uploads/2011/01/MatroshkaFunctionDemo.zip'>MatroshkaFunctionDemo</a></p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/matryoshka-functions/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>IDisplayObject? &#8211; Getting around the lack of an interface for the DisplayObject in Flash</title>
		<link>http://dispatchevent.org/mims/idisplayobject/</link>
		<comments>http://dispatchevent.org/mims/idisplayobject/#comments</comments>
		<pubDate>Mon, 15 Mar 2010 02:27:22 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tips, Tricks, and Hacks]]></category>
		<category><![CDATA[displayobject]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[idisplayobject]]></category>
		<category><![CDATA[interface]]></category>
		<category><![CDATA[workaround]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=838</guid>
		<description><![CDATA[Interfaces are amazing things. When I was young and green, I didn&#8217;t understand their purpose, but after working with them for a while, I will defend their use to the end. I try to create lots of interfaces early on in my projects and I find that by keeping things flexible, it saves more time [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://dispatchevent.org/wp-content/uploads/2010/03/DisplayObject_subclasses.png"><img class="alignnone size-medium wp-image-840" title="DisplayObject_subclasses" src="http://dispatchevent.org/wp-content/uploads/2010/03/DisplayObject_subclasses-300x156.png" alt="" width="300" height="156" /></a></p>
<p>Interfaces are amazing things.  When I was young and green, I didn&#8217;t understand their purpose, but after working with them for a while, I will defend their use to the end. I try to create lots of interfaces early on in my projects and I find that by keeping things flexible, it saves more time despite the extra typing, pardon the double entendre.</p>
<p>But this is not an article about why interfaces are so great. No, this is an article about the mysterious gap in the Flash Player API with regards to an interface for DisplayObjects. If you have a class typed as something like <code>IView</code>, there&#8217;s no way to enure that <code>IView</code> can be a parameter of display list functions like <code> addChild()</code>.</p>
<p><span id="more-838"></span>Why can&#8217;t we guarantee that something is a DisplayObject through interfaces?Â There is a practical answer. The inner workings of the Flash Player are slowing unfolding to us with each version. We now have low level access to sound, byte streams, and text rendering. However, the display list still relies exclusively on one of the only truly abstract classes in ActionScript 3.0, the DisplayObject. Because a low-level drawing engine is not exposed to AS3 programmers, we don&#8217;t know how it works and we cannot guarantee through an interface that an arbitrary class can be drawn.</p>
<p>Fortunately, there are some workarounds that can help, each with their own strengths and weaknesses. Personally, I think #2 is the way to go. It&#8217;s practically dripping with polymorphic goodness.</p>
<ol>
<li>
<h3>Make your interface inherit from IBitmapDrawable and IEventDispatcher</h3>
<p>DisplayObject is the only class that uses both of these two interfaces so by combining them in your interface, you can sort of be sure you&#8217;re working with a DisplayObject. Still, this is my least favorite solution</p>
<h4>Pros:</h4>
<ul>
<li>Uses interfaces exclusively.</li>
<li>Only a DisplayObject would implement both of these.</li>
</ul>
<h4>Cons:</h4>
<ul>
<li>There&#8217;s nothing to stop you from using this to create a class that isn&#8217;t a DisplayObject and that could cause problems.</li>
<li>You would still have to type cast to DisplayObject to use this as an argument for <code>addChild()</code>.</li>
</ul>
</li>
<li>
<h3>Create an interface that exposes a method to return the object as a DisplayObject</h3>
<p>My personal favorite solution. It not only solves the problem of guaranteeing that a class can go in the display list, it doesn&#8217;t even require that the class be a DisplayObject.</p>
<p>Here&#8217;s an example of what this would look like. <a href="http://gist.github.com/332408">IDisplayObject.as</a></p>
<h4>Pros:</h4>
<ul>
<li>Flexible solution that conforms to good OOD principles.</li>
<li>Uses interfaces exclusively.</li>
<li>Easy to apply. You can usually implement it with a single line of code: <code>return this;</code></li>
</ul>
<h4>Cons:</h4>
<ul>
<li>Requires you to use <code>asDisplayObject()</code> every time you want to use the object as a DisplayObject.</li>
<li>Calling <code>foo.asDisplayObject()</code> would throw an exception if <code>foo</code> was null so additional checks may be necessary.</li>
</ul>
</li>
<li>
<h3>Use an <a href="http://en.wikipedia.org/wiki/Abstract_type">abstract class</a> that inherits from DisplayObject</h3>
<p>Not an ideal solution primarily because Flash doesn&#8217;t have true abstract classes (although <a href="http://dispatchevent.org/mims/abstract-classes-in-as3/">there are workarounds</a>) but still totally valid.</p>
<h4>Pros:</h4>
<ul>
<li>Guarantees that the object is a DisplayObject. No type casting required.</li>
<li>Abstract classes can be treated virtually the same as an interface for practical use.</li>
</ul>
<h4>Cons:</h4>
<ul>
<li>No true abstract classes in Flash.</li>
<li>Not as flexible as an interface-based solution since it forces you to inherit from DisplayObject.</li>
</ul>
</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/idisplayobject/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Using XML Schemas in Eclipse / FlexBuilder</title>
		<link>http://dispatchevent.org/mims/using-xml-schemas-in-eclipse-flexbuilder/</link>
		<comments>http://dispatchevent.org/mims/using-xml-schemas-in-eclipse-flexbuilder/#comments</comments>
		<pubDate>Mon, 20 Apr 2009 05:00:16 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tips, Tricks, and Hacks]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[flexbuilder]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[xml]]></category>
		<category><![CDATA[xml-schema]]></category>
		<category><![CDATA[xsd]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=626</guid>
		<description><![CDATA[UPDATE: After reading the entry by Misprintt on the SchemaManager and XMLDecoder more thoroughly, I felt the need to tell you all to go check it out! This is a very powerful undocumented feature of Flex (why undocumented?) that could potentially save loads of time on a larger project. Along with the rest of this [...]]]></description>
			<content:encoded><![CDATA[<p><strong>UPDATE:</strong> After reading the <a href="http://blog.misprintt.net/?p=192">entry by Misprintt on the SchemaManager and XMLDecoder</a> more thoroughly, I felt the need to tell you all to go check it out! This is a very powerful undocumented feature of Flex (why undocumented?) that could potentially save loads of time on a larger project. Along with the rest of this article, you could automate the parsing of your XML files into bindable model classes with ease.</p>
<p><a href="http://www.w3schools.com/Schema/default.asp">XML-Schema</a> (.XSD extension) are documents used to describe the format of XML files. They are similar to DTD (Document type declaration) files but much more powerful.</p>
<p><a href="http://dispatchevent.org/wp-content/uploads/2009/02/picture-1.png"><img class="alignnone size-full wp-image-633" title="xsd editor" src="http://dispatchevent.org/wp-content/uploads/2009/02/picture-1.png" alt="xsd editor" width="435" height="355" /></a></p>
<p>While working on some XML documents for a Flash site, I stumbled across the XML-Schema editor for Eclipse. The editor shows the XSD as a graphical representation of the model that you&#8217;re editing that looks similar to a UML class diagram.</p>
<p><a href="http://wiki.eclipse.org/index.php/Introduction_to_the_XSD_Editor">Here&#8217;s a great article on how it works.</a></p>
<h3><span id="more-626"></span>Benefits of using XSD</h3>
<p>As I said, XSD allows you to define the format of your XML document but with much more detail that DTD.</p>
<ul>
<li>XSD allows you to type your data (integers, strings, booleans) so that you can better predict what format the xml will be</li>
<li>It allows the creation of custom types which gives it an object oriented aspect</li>
<li>You can use all kinds of restrictions for what kind of content can appear within a tag including the number of elements, whether values are required or not, you can even use regular expressions to limit the acceptable values. This is very nice when you&#8217;re working with a 3rd party who is generating the XML data.</li>
<li>Using an XSD file can allow you to automate the validation of an XML file&#8217;s format</li>
</ul>
<p>Once you&#8217;ve created your XSD file, you can use the new XML document wizard to create an XML file that links to your schema file. The wizard will automatically populate the XML document with valid data! Furthermore, as you edit the XML file you will get warnings and errors if you go outside the formatting requirements defined in the XSD. For example, if you define a tag &lt;description&gt; as having a maximum length of 128, you will see a visual error if your tag contains more than 128 characters. It&#8217;s a great way to forsee problems as you write them.</p>
<p><span style="text-decoration: line-through;">I hope in the future to write some kind of tool to parse XML based on an XSD file in flash.</span> Apparently, Adobe had created an undocumented Flex feature to validate XML against XSD. <a href="http://blog.misprintt.net/?p=181">Via Misprintt</a></p>
<h3>Installing the XML extensions</h3>
<p>Unfortunately, the editor is not installed by default and nstalling software in Eclipse is not very intuitive. I&#8217;ve done my best to describe the process here but if you need further help, <a href="http://dispatchevent.org/mims/pimp-my-clipse-a-list-of-must-have-eclipse-plug-ins-for-flexflash-development/">check this entry</a>.</p>
<ol>
<li>Open Eclipse or FlexBuilder</li>
<li>Go to Help&gt;Software Updates&#8230; ( &gt; Find and Install for Eclipse 3.3)<br />
<a href="http://dispatchevent.org/wp-content/uploads/2009/02/softwareupdate.png"><img class="alignnone size-full wp-image-630" title="softwareupdate" src="http://dispatchevent.org/wp-content/uploads/2009/02/softwareupdate.png" alt="softwareupdate" /></a></li>
<li>Make sure you have the <a href="http://www.eclipse.org/europa/">Europa</a> or <a href="http://www.eclipse.org/ganymede/">Ganymede</a> update sites in the list of update sites:
<pre style="margin: 0em;">Eclipse 3.4 users:
<a class="external free" title="http://download.eclipse.org/releases/ganymede/" rel="nofollow" href="http://download.eclipse.org/releases/ganymede/">http://download.eclipse.org/releases/ganymede/</a>

<a href="http://download.eclipse.org/releases/europa/site.xml">http://download.eclipse.org/releases/europa/site.xml</a></pre>
</li>
<li>Select the XML and XSD extensions in this screenshot. In Eclipse 3.4 you can search for them, in 3.3 you will have to look through the packages for them manually.<a href="http://dispatchevent.org/wp-content/uploads/2009/02/xmlextensions.png"><img class="alignnone size-full wp-image-629" title="xmlextensions" src="http://dispatchevent.org/wp-content/uploads/2009/02/xmlextensions.png" alt="xmlextensions" width="400" /></a></li>
<li>Restart Eclipse after the install is complete</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/using-xml-schemas-in-eclipse-flexbuilder/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>MVC cheat sheet</title>
		<link>http://dispatchevent.org/mims/mvc-cheat-sheet/</link>
		<comments>http://dispatchevent.org/mims/mvc-cheat-sheet/#comments</comments>
		<pubDate>Wed, 18 Mar 2009 23:55:08 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[link]]></category>
		<category><![CDATA[moock]]></category>
		<category><![CDATA[mvc]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=666</guid>
		<description><![CDATA[Sometimes I forget the details of whether my Model should know about my Controller and that sort of thing. I found this little MVC cheat sheet on the internet that got me straightened out in a jiffy with step-by-step instructions. The page is actually the lecture notes from one of Colin Moock&#8216;s presentations circa the [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes I forget the details of whether my <a href="http://www.swinburne.edu.au/design/tutorials/P-flash/T-The-Model-View-Controller-Design-Pattern-in-Actionscript-3/ID-144/">Model</a> should know about my <a href="http://www.swinburne.edu.au/design/tutorials/P-flash/T-The-Model-View-Controller-Design-Pattern-in-Actionscript-3/ID-144/">Controller</a> and that sort of thing. I found this <a href="http://www.moock.org/lectures/mvc/">little MVC cheat sheet</a> on the internet that got me straightened out in a jiffy with step-by-step instructions. The page is actually the lecture notes from one of <a href="http://www.moock.org/">Colin Moock</a>&#8216;s presentations circa the <a href="http://books.google.com/books?id=wQlYlMuTbwYC&amp;dq=essential+actionscript+2.0&amp;printsec=frontcover&amp;source=bn&amp;hl=en&amp;ei=y4jBSdHXIoHasAOs4cX3Bg&amp;sa=X&amp;oi=book_result&amp;resnum=7&amp;ct=result">Essential AS 2.0</a> days but it&#8217;s still very useful. Those of you struggling with the lingo, replace Observer with EventDispatcher and ignore the junk about attachMovie. God, how did we ever write <a href="http://dispatchevent.org/mims/converting-as3-to-as2/">AS2</a>!?</p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/mvc-cheat-sheet/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Using Abstract Classes in the Flash CS3/4 Library</title>
		<link>http://dispatchevent.org/mims/abstract-classes-in-the-library/</link>
		<comments>http://dispatchevent.org/mims/abstract-classes-in-the-library/#comments</comments>
		<pubDate>Wed, 11 Mar 2009 21:38:25 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[Flash]]></category>
		<category><![CDATA[Greatest Hits]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tips, Tricks, and Hacks]]></category>
		<category><![CDATA[cs3]]></category>
		<category><![CDATA[cs4]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[symbol]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=654</guid>
		<description><![CDATA[Here&#8217;s a little trick that can help you save lots of time that might otherwise be spent creating multiple specialized classes in your Flash project. This trick makes use of the Base Class field in a symbol&#8217;s actionscript properties. (For info on creating pseudo-abstract classes in AS3, go here) By the way, this tip may [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a little trick that can help you save lots of time that might otherwise be spent creating multiple specialized classes in your Flash project. This trick makes use of the Base Class field in a symbol&#8217;s actionscript properties. (For info on creating pseudo-abstract classes in AS3, <a href="http://dispatchevent.org/mims/abstract-classes-in-as3/">go here</a>)</p>
<p>By the way, this tip may be common knowledge to Flash users. I use FlexBuilder almost exclusively these days but recently have had to dip back into the twisted world of the Flash IDE so please refrain from leaving any comments about how I shouldn&#8217;t use the timeline.</p>
<h3>The Problem</h3>
<p>Say you have several different buttons for a site that each look of behave slightly differently but all share the same underlying functionality. In this example, I&#8217;ll be using a crude set of video controls. I want each of these different controls to respond to rollovers by showing the label beneath the icon.</p>
<p><img class="alignnone size-full wp-image-656" title="picture-1" src="http://dispatchevent.org/wp-content/uploads/2009/03/picture-1.png" alt="picture-1" /></p>
<p>EachÂ  control has different icons and text so they&#8217;re going to need to be kept in different symbols. One solution might be to try to cram all the icons into one master symbol and change between the different icon frames using code. But that&#8217;s sloppy and unnecessary. Another solution might be to create 4 different classes that each implement the functionality or each extend a class with common functionality. This is a much better solution, but requires you to create 4 AS files for what functionally is just 1 type. You cannot use the same class for multiple symbols in your library though. Fortunately, Flash offers another solution that may be a bit less intuitive.</p>
<h3>The Solution</h3>
<p>If you needed to create the same sort of control components purely using code (using Flex for example), your first step would likely be to create some sort of base class that implements the common functionality of the 4 controls. Here&#8217;s an example of a base class for these 4 controls.</p>
<pre lang="actionscript3">package {

	import flash.text.*;
	import flash.display.*;
	import flash.events.*;

	public class AbstractVideoControl extends MovieClip {
		// you'll need to create this text field on the timeline
		// and set the instance name to "label"
		public var label:TextField;

		public function AbstractVideoControl() {
			label.visible = false;
			addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
			addEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
		}

		protected function onMouseOver(event:MouseEvent):void {
			label.visible = true;
		}

		protected function onMouseOut(event:MouseEvent):void {
			label.visible = false;
		}
	}
}</pre>
<p>Note: In many non-ActionScript languages, there is a construct called an &#8220;<em>abstract type</em>&#8221; whichÂ  is simply a base class that cannot be instantiated on its own, only extended. In Flash, proper abstract types don&#8217;t exist, but we can consider a class Abstract if it <em>shouldn&#8217;t</em> be instantiated without being subclassed. More on that <a href="http://en.wikipedia.org/wiki/Abstract_type">at Wikipedia</a>.</p>
<p>Next, let&#8217;s make our controls extend this class. For each symbol, check the Export for ActionScript box in the symbol properties. Since Flash can automatically generate classes for symbols when an .as file doesn&#8217;t exist, the only thing you&#8217;ll need to fill in is the Base Class field (later, you can create a class for PlayButton if you need one). Make sure you use the fully qualified name if you&#8217;re using packages.</p>
<p><img class="alignnone size-full wp-image-661" title="picture-3" src="http://dispatchevent.org/wp-content/uploads/2009/03/picture-3.png" alt="picture-3" width="562" height="602" /></p>
<h3>Moar</h3>
<p>I found this technique was very useful for when I wanted to animate TextFields on the timeline. Timeline animations, as you probably are aware, only work with MovieClip symbols. That means that even simple animations on text require the text to be contained in a symbol. I created an AbstractTextFieldWrapper class so that I could easily work with animated type without having to create new classes every time the format changes.</p>
<pre lang="actionscript3">package {
	import flash.display.MovieClip;
	import flash.text.TextField;

	/**
	 * This class allows you to create an animated text field on the
	 * timeline and still set the text of the field without creating a new
	 * class for each text field that does this.
	 *
	 * @use In the flash library, create a new movieclip symbol containing the
	 * 		textField. Make sure you set the instance name for the text field to
	 * 		"textField". Make the base class for the symbol
	 * 		"AbstractTextFieldWrapper".
	 * 		In another class, use the type AbstractTextFieldWrapper insatead of
	 * 		TextField for your text field variable.
	 */
	public class AbstractTextFieldWrapper extends MovieClip
	{
		public var textField:TextField;
		public function set text(text:String):void {
			textField.text = text;
		}
		public function get text():String {
			return textField.text;
		}
	}
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/abstract-classes-in-the-library/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>The quest for the elusive &#8220;N-gleton&#8221;</title>
		<link>http://dispatchevent.org/mims/the-quest-for-the-elusive-n-gleton/</link>
		<comments>http://dispatchevent.org/mims/the-quest-for-the-elusive-n-gleton/#comments</comments>
		<pubDate>Tue, 24 Feb 2009 06:08:08 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[Lab]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tips, Tricks, and Hacks]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=638</guid>
		<description><![CDATA[Sure, we&#8217;ve all heard of Singleton, the design pattern that limits the number of instances of a class to one. It&#8217;s a feel good pattern because it&#8217;s easy to use and make us feel smarter in front of our co-workers, even though some would argue that Singletons are just glorified global variables. But for a [...]]]></description>
			<content:encoded><![CDATA[<p>Sure, we&#8217;ve all heard of <a href="http://en.wikipedia.org/wiki/Singleton">Singleton</a>, the design pattern that limits the number of instances of a class to one. It&#8217;s a feel good pattern because it&#8217;s easy to use and make us feel smarter in front of our co-workers, even though some would argue that Singletons are just glorified global variables. But for a long time, I have wondered if it would be possible to use the same idea to limit the number of instances to <em>two or more</em> instead of just one. I called this hypothetical pattern an <em>&#8220;N-gleton&#8221;</em>, pronounced &#8220;en-gull-ton&#8221;. (UPDATE: Comments from readers inform me that this is called a &#8220;<a href="http://en.wikipedia.org/wiki/Multiton_pattern">Multiton</a>&#8220;) It may not be possible to make a poly-instance singleton, it may not be good programming practices, I&#8217;m not even sure I can think of a reason why it might be useful, but today, I tried my hand at inventing it and found something else entirely.</p>
<p><span id="more-638"></span></p>
<h3>The Hard Limit approach</h3>
<p>The first attempt I made at the N-gleton was to simply throw an error when the class had been instantiated too many times.</p>
<pre lang="actionscript3">package {
	public class NGletonHardLimit {
		protected static var maxInstances:int = 3;
		protected static var numberOfInstances:int = 0;

		public function NGletonHardLimit() {
			if (numberOfInstances &gt;= maxInstances) {
				throw new Error ("There can only be " + maxInstances + " instances of this class");
			}
			numberOfInstances++;

			// initialize code
		}
	}
}</pre>
<p>This was shortly followed by a slightly more friendly version of the same idea&#8230;</p>
<pre lang="actionscript3">package {
	public class NGletonRequestInstance {
		protected static var maxInstances:int = 3;
		protected static var numberOfInstances:int = 0;

		public static function requestInstance():NGletonRequestInstance {
			if (numberOfInstances &gt;= maxInstances) {
				return null;
			} else {
				return new NGletonRequestInstance(new Key());
			}
		}

		public function NGletonRequestInstance(key:Key) {
			// initialize code
		}
	}
}
class Key {}</pre>
<p>However, I soon realized that this method is quite flawed in its logic. The counter is actually just counting the number of times the <code>requestInstance()</code> method is being called rather than truly controlling the number of instances of the class. It also doesn&#8217;t allow you to release an instance and decrement the instance count. Perhaps something like this would work in C where you can use <code>alloc</code> and <code>dealloc</code> but for Flash, it doesn&#8217;t really make sense. Besides, It doesn&#8217;t really seem useful.</p>
<h3>Cycling through instances</h3>
<p>Next, I tried looping through the same limited set of instances. Each time you request an instance you get a new one until you&#8217;ve reached your limit, then it starts over with the first instance again.</p>
<pre lang="actionscript3">	package
	{
		public class NGletonLoop
		{
			protected static var maxInstances:int = 3;
			protected static var numberOfInstances:int = 0;
			protected static var instances:Array = [];

			public function NGletonLoop(key:Key) {
				// initialize code
			}

			public static function requestInstance():NGletonLoop {
				var n:int = numberOfInstances++ % maxInstances;
				if (instances[n] == null) {
					instances[n] = new NGletonLoop(new Key());
				}
				return NGletonLoop(instances[n]);
			}
		}
	}
	class Key {}</pre>
<p>This approach just felt wrong. In fact, it was totally stupid. There is no way to know what you&#8217;re going to get when you request an instance and it seems like it would be very easy to overwrite data without even knowing it. You still have the problem of the instantiation being counted rather than the actual objects. Besides, it&#8217;s really totally useless.</p>
<p>It was looking like the whole idea of an N-gleton may not really have a practical application. But in the name of theoretical computer science, I chose to press on and try one more idea I had.</p>
<h3>Tracking individual instances</h3>
<p>The previous idea of storing instances in an Array seemed to make some kind of sense to me but it was missing individual control over the instances. So I decided to try using an index to track the instances. I soon realized that a Dictionary that uses objects as keys might give a more useful identifier than an integer. The <code>maximumInstances</code> didn&#8217;t really make sense any more so I took it out. I seemed to be onto something but it wasn&#8217;t really the N-gleton I had imagined, it was something more useful. I called it an <code><em>IndexedObject</em></code>.</p>
<pre lang="actionscript3">	package {
		import flash.utils.Dictionary;

		/**
		 * An example of a class that tracks multiple individual instances by using a dictionary.
		 */
		public class IndexedObject {

			/**
			 * Stores the actual instances of the class.
			 */
			protected static var _instances:Dictionary = new Dictionary(false);

			/**
			 * The identifier that the dictionary uses to reference this instance.
			 */
			public function get id():* { return _id; }
			protected function set id (id:*):void { _id = id; }
			protected var _id:*;  

			/**
			 * Gets an instance of the class. Similar to how a singleton would get the
			 * instance but uses an identifier token to specify which instance to get.
			 */
			public static function getInstance(id:*):IndexedObject {
				if (_instances[id] == null) {
					_instances[id] = new IndexedObject(new Key)
				}
				var instance:IndexedObject = _instances[id] as IndexedObject;
				instance._id = id;
				return instance;
			}

			/**
			 * Returns all of the created instances as an array.
			 */
			public static function get allInstances():Array {
				var array:Array = [];
				var obj:IndexedObject;

				for each (obj in _instances) {
					array.push(obj);
				}
				return array;
			}

			/**
			* Removes an item from the list of instances.
			* Actually, doesn't quite work because an instance referenced by a variable
			* outside of the class could still hold a reference to the deleted instance.
			*/
			public static function deleteObject(id:*):void {
				delete _instances[id];
			}

			/** Just used for testing */
			public var name:String;

			/**
			 * Constructor can't be used by outsided classes.
			 */
			public function IndexedObject(key:Key) {
				// Initialize code
			}
		}
	}
	class Key{}</pre>
<p>So essentially what&#8217;s happening here is the Singleton&#8217;s <code>getInstance()</code> method is being replaced with one that allows you to specify a particular instance. Any class could create new instances or access the same instances provided they had the same id. Here&#8217;s a little demo. I&#8217;m using a <code>name</code> property to show the example.</p>
<pre lang="actionscript3">	var thing:IndexedObject = IndexedObject.getInstance(5);
	thing.name = "thing 5";

	thing = IndexedObject.getInstance("foo");
	thing.name = "thing foo";

	for each (var obj:IndexedObject in IndexedObject.allInstances) {
		trace("IndexedObject.getInstance(",obj.id,") =", IndexedObject.getInstance(obj.id).name);
	}</pre>
<p>Results in:</p>
<p><code>IndexedObject.getInstance( foo ) = thing foo<br />
IndexedObject.getInstance( 5 ) = thing 5</code></p>
<p>Voila. The &#8220;indexed object&#8221;. I think for me the jury is still out on whether this is a good idea. It seems like it might be kind of a hack since it, like Singleton, is essentially just a complicated implementation of global variables but even more so and without Singleton&#8217;s benefits. It also intuitively feels like it could be very useful. Either way, I&#8217;m proud of it.</p>
<p>So what do you think? What would you use this for? Is it a hack? Pattern or anti-pattern?</p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/the-quest-for-the-elusive-n-gleton/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>AS3 number to hex converter</title>
		<link>http://dispatchevent.org/mims/as3-number-to-hex-converter/</link>
		<comments>http://dispatchevent.org/mims/as3-number-to-hex-converter/#comments</comments>
		<pubDate>Fri, 30 Jan 2009 01:38:44 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[AS3]]></category>
		<category><![CDATA[Lab]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[as3lib]]></category>
		<category><![CDATA[bitwise]]></category>
		<category><![CDATA[converter]]></category>
		<category><![CDATA[hex]]></category>
		<category><![CDATA[hexadecimal]]></category>
		<category><![CDATA[hexit]]></category>
		<category><![CDATA[math]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=618</guid>
		<description><![CDATA[I&#8217;ve been working on some code for converting colors lately and getting quite into bitwise operations. In one of the demos I was making, I needed a quick and easy way to see the results of a color calculation. Of course, simply tracing a number, even if it&#8217;s in the format 0xFF, will result in [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been working on some code for converting colors lately and getting quite into bitwise operations. In one of the demos I was making, I needed a quick and easy way to see the results of a color calculation. Of course, simply tracing a number, even if it&#8217;s in the format 0xFF, will result in a digital number string &#8220;255&#8243;. I&#8217;ve always been a little stumped about how to do this calculation but I realized that it&#8217;s actually very easy to do with the <a href="http://livedocs.adobe.com/flex/3/langref/operators.html#bitwise_AND">&amp;</a> and <a href="http://livedocs.adobe.com/flex/3/langref/operators.html#bitwise_unsigned_right_shift">&gt;&gt;&gt;</a> bitwise operators.</p>
<p><code><br />
getNumberAsHexString(255); // 0xFF<br />
getNumberAsHexString(0xABCDEF); // 0xABCDEF<br />
getNumberAsHexString(0x00FFCC); // 0xFFCC<br />
getNumberAsHexString(0x00FFCC, 6); // 0x00FFCC - Uses 6 as a minimum number of hexits</code></p>
<p>I&#8217;ve added the code to the <a href="http://as3lib.org">AS3lib</a> asÂ  as a global function. I may move it to a utility class later on. You can <a href="http://code.google.com/p/as3lib/source/browse/trunk/src/org/as3lib/math/getNumberAsHexString.as">view the source</a> on Google Code.</p>
<p>Incidentally, in a moment of bug-fixing frustration, I found <a href="http://kinderas.blogspot.com/2008/01/quicktip-actionscript-3-and-number.html">this article on O.C.A.S.</a> which describes how the same functionality is already built into the <code>toString()</code> method! However, the work isn&#8217;t completely wasted since my version includes the option to show leading zeroes and adds &#8220;<code>0x</code>&#8221; at the front of the result.</p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/as3-number-to-hex-converter/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Q&amp;A &#8211; is, as, and type conversion</title>
		<link>http://dispatchevent.org/mims/is-and-as/</link>
		<comments>http://dispatchevent.org/mims/is-and-as/#comments</comments>
		<pubDate>Tue, 27 Jan 2009 07:41:08 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tips, Tricks, and Hacks]]></category>
		<category><![CDATA[as]]></category>
		<category><![CDATA[coercion]]></category>
		<category><![CDATA[cs]]></category>
		<category><![CDATA[downcasting]]></category>
		<category><![CDATA[is]]></category>
		<category><![CDATA[lesson]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[types]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=591</guid>
		<description><![CDATA[A question from a reader gave me an excuse to write a huge rant about type conversions: I&#8217;m doing a little exercise in a book that makes a textfield in which each letter can only be entered once. Not very useful, more of a teaching thing really. However there&#8217;s a bit of code that says: [...]]]></description>
			<content:encoded><![CDATA[<p>A question from a reader gave me an excuse to write a huge rant about type conversions:</p>
<blockquote><p>I&#8217;m doing a little exercise in a book that makes a textfield in which each letter can only be entered once. Not very useful, more of a teaching thing really. However there&#8217;s a bit of code that says:</p>
<p><code>var tf:TextField = event.target as TextField;</code></p>
<p>I don&#8217;t understand this at all! What the hell is <code>event.target as TextField</code>? Anyway here&#8217;s the full code for context&#8217;s sake:</p>
<pre lang="actionscript3">
package com.FoundationAS3.ch6 {

	import flash.display.Sprite;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.events.TextEvent;

	public class PreventDefaultTest extends Sprite {

		public function PreventDefaultTest() {
			var tf:TextField = new TextField();
			addChild(tf);

			tf.width = stage.stageWidth;
			tf.height = stage.stageHeight;
			tf.type = TextFieldType.INPUT;
			tf.wordWrap = true;

			tf.addEventListener(TextEvent.TEXT_INPUT, onTextFieldTextInput);
		}

		private function onTextFieldTextInput(event:TextEvent):void {
			var tf:TextField = event.target as TextField;
			if (tf.text.indexOf(event.text) &gt; -1) {
				event.preventDefault();
			}
		}
	}
}
</pre>
<p>Thanks,<br />
-Neal
</p></blockquote>
<p>My response after the jump.<br />
<span id="more-591"></span><br />
Neal,</p>
<p>First of all, let me say that preventing the default event handler, e.g. for a <code>TextField</code>, is rarely used and isn&#8217;t worth spending a lot of time discussing.</p>
<p>On the other hand, the <code>as</code> operator (along with the <code>is</code> operator and the type cast) are totally useful and you should learn all about them. First, let me cover <code>is</code>:</p>
<h3>is</h3>
<p><code><a href="http://livedocs.adobe.com/flex/2/langref/operators.html#is">is</a></code> is an operator that evaluates whether some object <em>is</em> of a certain type. The syntax is <code>[object] is [type]</code>. The term &#8216;type&#8217; is similar but not interchangeable with &#8216;class&#8217;. A type can refer to not only the class of an object, but also the super-classes it extends and interfaces it implements. An example:</p>
<pre lang="actionscript3">
var sprite:Sprite = new Sprite();
trace(sprite is Sprite); // true, because the sprite object is an instance of Sprite
trace(sprite is DisplayObject); // true, Sprite is a subclass of DisplayObject
trace(sprite is MovieClip); // false, MovieClip is a subclass of Sprite.
trace(sprite is IEventDispatcher); // true, DisplayObject extends EventDispatcher which implements IEventDispatcher.
</pre>
<p>Note that sprite is not a MovieClip but a MovieClip is a Sprite. Because MovieClip extends Sprite and contains all the same methods and properties as Sprite but not the other way around. </p>
<p>Note: the <code>instanceof</code> operator commonly used in AS1/2 still exists in AS3 but is for all practical purposes deprecated by <code>is</code> (although still useful if you&#8217;re manipulating prototypes). <code>typeof</code> is also related but shouldn&#8217;t be used in place of <code>is</code> because it only returns strings for primitive data types like Object and String. In order to get the actual name of the class that an object is an instance of, you can use the <code>flash.utils.getQualifiedClassName()</code> global function.</p>
<h3>as</h3>
<p><code><a href="http://livedocs.adobe.com/flex/2/langref/operators.html#as">as</a></code> functions similarly to is except that it actually will attempt to coerce the object into the data type that you ask for. <a href="http://en.wikipedia.org/wiki/Type_conversion">Coercion</a>, AKA type conversion or casting, is the act of changing the data type of an object. </p>
<p>With the case from your book, an <code>Event</code> object has a <code>target</code> property which refers back to the object that originally dispatched the event. Since the <code>Event</code> object is designed to be sent out from all different types of objects, the target&#8217;s data type is <code>Object</code> (the mother of all the other classes). So, if the variable you&#8217;re defining is a TextField, you&#8217;re expecting an object with a <code>text</code> property. <code>Object</code>, doesn&#8217;t have a <code>text</code> property so you have a dilemma. The solution is to cast the object into the type you want it to be, basically forcing it to be more specific.</p>
<pre lang="actionscript3">
var textField:TextField = event.target; // Throws compile error because target is an Object not a TextField

var textField:TextField = event.target as TextField; // OK! as long as the event target actually is a text field
</pre>
<p>Going from a more generic type to a more specific type is called a <em>downcast</em>. Going from a more specific type to a more generic type is called an <em>upcast</em>. Upcasting in ActionScript, as with most other languages, is done automatically and is always safe. e.g. a Sprite can be used as a parameter for a function that requires a DisplayObject. Downcasting on the other hand is unsafe meaning that you can&#8217;t always guarantee that it will work. A DisplayObject is not necessarily a Sprite. </p>
<p>When an attempt to downcast with <code>as</code> fails, the value returned will be <code>null</code>:</p>
<pre lang="actionscript3">
var string:String = new String();
var textField:TextField = string as TextField // string can't be converted. textField will be set to null
</pre>
<p>If you&#8217;re not sure whether your object is the right type (and you should never assume it is) check to see if the value is null before proceeding:</p>
<pre lang="actionscript3">
var typedObject:TypedObject = mysteryObject as TypedObject;
if (typedObject != null) {
	// conversion was successful! do something with typedObject
} else {
	// conversion failed
}
</pre>
<h3>Type casts</h3>
<p>Another way to do this with slightly different results is by type casting. Type casting works with the syntax <code>Type(object)</code> and is functionally similar to <code>object as Type</code>. The only difference is with a type cast, you get a runtime error if the coercion fails.</p>
<p><code>var textField:TextField = TextField(event.target); // if event.target is a TextField, you're good. If not, you get an error.<br />
</code></p>
<p>you can also shortcut like this:</p>
<p><code>TextField(event.target).text = "foo";</code></p>
<h3>Conclusion</h3>
<p>Why are objects like <code>event.target</code> given such generic data types? The idea is that you want to minimize the requirements of a property, parameter, or function to maximize the number of objects that will qualify thus making your program more flexible. In other words, strive to use the most broadly defined data types that you can get away with. </p>
<p>For example, say you&#8217;re creating a simulator program for getting a person from their home to their job. You may be tempted to define your <code>modeOfTransportation</code> variable with a type of <code>Car</code>. But down the road the company you&#8217;re working for wants to create a more green image for themselves and suggests using alternative modes of transportation. If you&#8217;re code is based on Car, it&#8217;s limited in what you can do with it. However, if you had used a <code>Vehicle</code> type (includes Car, Bike, Motorcycle, Donkey) instead, you may not have had a problem. Using interfaces like <code>IConveyance</code> makes your program even more flexible because you can include non-vehicluar objects like MolecularTransporter, Feet, and CrowdSurfing as long as they satisfy the interface. In fact, I would suggest as an experiment that the next time you start a project, try coding all the interfaces first before you move on to coding specific classes. You&#8217;ll be surprised at how flexible it is and how it forces you to consider the roles of your classes from a higher level. </p>
<p>Though you should strive for generic types, sometimes you will need to get specific. If your program has a gas station simulator in it, the <code>fillTankOfVehicle()</code> method might require a <code>MotorVehicle</code> class (includes Car, Motorcycle, Plane) instead of simply <code>Vehicle</code>. Still, you should only get very specific when your program requires it. If you are making a racing program, use <code>F1RaceCar</code> only when a simple <code>Car</code> won&#8217;t cut it.</p>
<p>I hope this helps! This is definitely a difficult topic even for experienced programmers to grasp!</p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/is-and-as/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>AS2 EventDispatcher</title>
		<link>http://dispatchevent.org/mims/as2-eventdispatcher/</link>
		<comments>http://dispatchevent.org/mims/as2-eventdispatcher/#comments</comments>
		<pubDate>Fri, 09 Jan 2009 01:09:49 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[Flash]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[as2]]></category>
		<category><![CDATA[eventdispatcher]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=572</guid>
		<description><![CDATA[I recently went back to some AS2 code and created a replica of the AS3 EventDispatcher in ActionScript 2.0. The code is based on Danny Patterson&#8217;s original EventBroadcaster code. I tried my best to match the syntax of the AS3 events package. I have made it available for you to use freely. AS2 EventDispatcher Note: [...]]]></description>
			<content:encoded><![CDATA[<p>I recently went back to some AS2 code and created a replica of the AS3 EventDispatcher in ActionScript 2.0. The code is based on Danny Patterson&#8217;s original EventBroadcaster code. I tried my best to match the syntax of the AS3 events package. I have made it available for you to use freely.</p>
<p><a href="http://dispatchevent.org/wp-content/uploads/2009/01/as2eventdispatcher.zip">AS2 EventDispatcher</a></p>
<p>Note: I just wrote about this in <a href="http://dispatchevent.org/mims/converting-as3-to-as2/">my previous post about converting AS3 to AS2</a> but I wanted to repost it for easy search purposes.</p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/as2-eventdispatcher/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Downsampling Flash &#8211; Converting AS3 to AS2</title>
		<link>http://dispatchevent.org/mims/converting-as3-to-as2/</link>
		<comments>http://dispatchevent.org/mims/converting-as3-to-as2/#comments</comments>
		<pubDate>Fri, 09 Jan 2009 01:03:32 +0000</pubDate>
		<dc:creator>Mims H Wright</dc:creator>
				<category><![CDATA[AS3]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=565</guid>
		<description><![CDATA[I recently came across a situation where I was forced to convert a working project in Flash 9 AS3 to Flash 8 AS2. I wanted to share some of my experiences to help other weary programmers in the same predicament. Before I begin, I must stress to you, if there is any way you can [...]]]></description>
			<content:encoded><![CDATA[<p>I recently came across a situation where I was forced to convert a working project in Flash 9 AS3 to Flash 8 AS2. I wanted to share some of my experiences to help other weary programmers in the same predicament.</p>
<p><span id="more-565"></span></p>
<p>Before I begin, I must stress to you, <strong>if there is any way you can avoid downgrading your code, you should avoid it!</strong> If it&#8217;s a matter of making two systems communicate, there are countless reasons that it would be better to upgrade your code from AS2 to AS3. There are even ways to host your AS2 code in an AS3 wrapper. In my case, an important requirement (that the deliverable absolutely must be AS2) was left out of the original scope of work due to a misunderstanding but anything that doesn&#8217;t cause project stoppage should be considered carefully.</p>
<p>I must also preface this article by reminding the reader that there is no 1-to-1 conversion from AS3 to AS2 (nor the other way around). There are loads of features added to Flash Player 9 that simply don&#8217;t exist in Player 8. Some things you&#8217;ll be able to convert with a simple find and replace. Some things you&#8217;ll need to re-create in AS2 or re-think completely. Some things you just won&#8217;t be able to do. This article only covers the stuff I ran across while converting my files and is by no means comprehensive. However, I hope it gives you a good starting point to work from.</p>
<p><strong>Converting the document class </strong></p>
<p>Since you&#8217;re a smart, cool AS3 programmer with a good sense of humour, I know you use a document class in your FLA files or a main application class for your FlexBuilder project. Right? Good. Of course, AS2 does not support document classes and all code must be run from the timeline. You have a couple of options here. You could move your document class to the timeline and remove the class specific portions of the code. Perhaps a quicker and easier solution is to modify your document class to take a reference to the root. So you have something like this on the first frame&#8230;</p>
<pre>var documentClass:MyDocumentClass = new MyDocumentClass(this);</pre>
<p>Just keep in mind that your document class will need to store a reference to the root that&#8217;s passed in as well as make references to things that were on the stage. For example&#8230;</p>
<pre>public function MyDocumentClass(mc:MovieClip) {
   this._mc = mc;
   this.thingOnStage = _mc.thingOnStage;
}</pre>
<p><strong>Cleaning up syntax errors</strong></p>
<p>The first step to take once you can compile your code is to run it and fix each compile time error one at a time. To save you the trouble of some of the more common ones I found, I created this list of common syntax problems.</p>
<p><strong>Search and replace:</strong></p>
<ul>
<li>void -&gt; Void</li>
<li>int and uint -&gt; Number</li>
<li>DisplayObject, DisplayObjectContainer, Sprite -&gt; MovieClip</li>
<li>public class -&gt; class</li>
<li>internal -&gt; public</li>
<li>protected -&gt; private</li>
<li>override -&gt; (nothing)</li>
<li>mouseEnabled -&gt; enabled</li>
<li>[obj] as [type] -&gt; [type]([obj])</li>
<li>[obj] is [type] -&gt; [obj] instanceof [type]</li>
<li>const -&gt; var (or optionally, to implicit getter)</li>
<li>Add underscores before MovieClip variables. e.g.: x, scaleY, alpha -&gt; _x, _yscale, _alpha including:
<ul>
<li>alpha -&gt; _alpha</li>
<li>x,y -&gt; _x, _y</li>
<li>scaleX,Y -&gt; _xscale, _yscale</li>
<li>mouseX,Y -&gt; _xmouse, _ymouse</li>
<li>visible -&gt; _visible</li>
<li>currentFrame -&gt; _currentFrame</li>
<li>totalFrames -&gt; _totalframes</li>
</ul>
</li>
</ul>
<p><strong>Add:</strong></p>
<ul>
<li>import statements for classes within the same package (not required in AS3)</li>
</ul>
<p><strong>Remove:</strong></p>
<ul>
<li>import statements for AS3 packages (e.g. flash.display.* )</li>
</ul>
<p><strong>Convert:</strong></p>
<ul>
<li> _xscale, _yscale, _alpha &#8211; Convert from decimal to integer (0.2 becomes 20).</li>
<li> Convert Timer to setInterval</li>
<li> Convert Loader to MovieClipLoader</li>
<li> Remove package declaration but copy the package name and put it before the class name. Also remove closing } from the end of the file.<br />
e.g. :</p>
<pre>package com.mysite.package {
	public class Foo {
	 	//...
	}
}</pre>
<p>becomes</p>
<pre>class com.mysite.package.Foo {

	//...

}</pre>
</li>
</ul>
<p><strong>Other tips</strong></p>
<p>Events are a huge part of AS3 development and Player 9 supports a fully event-driven development style. Unfortunately, AS2 is heavily lacking in this department and while events can be recreated in AS2, it lacks method closures and bubbling that make AS3 so nice. To downgrade, I did two things. First, I recreated the event dispatcher in as2 and second, I made heavy use of event callbacks and the Delegate class.</p>
<p><strong>com.mimswright.events</strong></p>
<p>In order to change as little of the event code as possible, I looked back to previous AS2 projects where I had used <a href="http://dannypatterson.com">Danny Patterson</a>&#8216;s EventBroadcaster classes. These classes worked roughly the same as the EventDispatcher class in AS3. I took the liberty of brushing up the code and making it look as much like the AS3 EventDispatcher as I could. I&#8217;m making it freely available for use.</p>
<p><a href="http://dispatchevent.org/wp-content/uploads/2009/01/as2eventdispatcher.zip">as2eventdispatcher</a></p>
<p><strong>event callbacks</strong></p>
<p>Most of the events you&#8217;ll probably be using must be triggered by callbacks in AS2. That is, you define a function that gets called when an event takes place like</p>
<pre>onMouseMove = function ():Void {
   //do something
}</pre>
<p>Keep in mind that in AS2 there are no method closures as there are in AS3. That is, a function isn&#8217;t necessarily executed in the scope that it exists in. In even simpler terms, a function doesn&#8217;t know what object it&#8217;s associated with. Because of this, code such as <code>button.onRelease = object.handleClick;</code> executes the <code>handleClick</code> function from the <code>button</code> context and my not work properly. Fortunately, AS2 code can make use of the <code>mx.utils.Delegate</code> class &#8211; specifically, the <code>Delegate.create()</code> method. This artificially maintains the context in which the function was supposed to be called. So your code should look like <code>button.onRelease = mx.utils.Delegate.create(object, object.handleClick);</code></p>
<p>I hope this has been a helpful start for you poor souls who are faced with the challenge of down-converting code. Good luck to you and feel free to add your experiences to the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/mims/converting-as3-to-as2/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Flash Player 10 &#8211; 3D Example</title>
		<link>http://dispatchevent.org/calebjohnston/flash-player-10-3d-example/</link>
		<comments>http://dispatchevent.org/calebjohnston/flash-player-10-3d-example/#comments</comments>
		<pubDate>Tue, 21 Oct 2008 16:06:27 +0000</pubDate>
		<dc:creator>Caleb Johnston</dc:creator>
				<category><![CDATA[AS3]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Lab]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[3D]]></category>
		<category><![CDATA[Flash 10]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=431</guid>
		<description><![CDATA[I&#8217;ve tinkered a bit with Flash Player 10. One thing that seems almost funny about the 3D effects of Flash thus far is that very few examples show off actually 3D objects. Most examples I&#8217;ve examined show 2D planes transformed in 3D space. So, I&#8217;ve created a sample 3D cube primitive in AS3 as a [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve tinkered a bit with Flash Player 10. One thing that seems almost funny about the 3D effects of Flash thus far is that very few examples show off actually 3D objects. Most examples I&#8217;ve examined show 2D planes transformed in 3D space. So, I&#8217;ve created a sample 3D cube primitive in AS3 as a convenient example for people who want to get started with their own parsers or drawing tools (etc).</p>
<p><span id="more-431"></span></p>
<p>My current configuration is Mac OS X 5.2 + TextMate 1.5.7 + Flex SDK 4.0.0.3504. I have two shell scripts in place:<a title="txt version of textmate bundle command" href="http://www.calebjohnston.com/storage/scripts/textmate_compile.txt"><br />
</a></p>
<ol>
<li><a title="txt version of mxmlc script" href="http://www.calebjohnston.com/storage/scripts/mxmlc.txt">/usr/bin/mxmlc</a></li>
<li><a title="txt version of textmate bundle command" href="http://www.calebjohnston.com/storage/scripts/textmate_compile.txt">A TextMate run bundle</a> set to a hotkey, &#8220;command + R&#8221;</li>
<li>I&#8217;ve also have my <a title="Flex 4 SDK download" href="http://opensource.adobe.com/wiki/display/flexsdk/Download+Flex+4">Flex SDK</a> set to the absolute path of: <em>/Developer/SDKs/Flex/4.0.0.3504</em></li>
</ol>
<p>This configuration requires a flex-config.xml in the same directory as the AS3 class file that you&#8217;re compiling. When you run the TextMate script (or something similar in your Terminal shell) it will compile the filename you pass in and default to using a config.xml which acts as a local flex-config.xml file. All of these can be customized as needed.</p>
<p>Example Flash 10 3D cube rotation:<br />
[kml_flashembed movie="http://www.calebjohnston.com/storage/fl10_examples/01_cube_rotation/CubeRotationExample.swf" height="260" width="410" bgcolor="#FFFFFF" /]</p>
<p>Obviously, the above swf won&#8217;t work without Flash player 10 installed.</p>
<p><a title="Flash 10 3D cube rotation example source" href="http://www.calebjohnston.com/storage/fl10_examples/01_cube_rotation.zip">Download the source here.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/calebjohnston/flash-player-10-3d-example/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Double Dissapointment</title>
		<link>http://dispatchevent.org/calebjohnston/double-dissapointment/</link>
		<comments>http://dispatchevent.org/calebjohnston/double-dissapointment/#comments</comments>
		<pubDate>Sat, 23 Aug 2008 00:22:59 +0000</pubDate>
		<dc:creator>Caleb Johnston</dc:creator>
				<category><![CDATA[AIR]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Discussion]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Meta]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Videogames]]></category>
		<category><![CDATA[standards]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=319</guid>
		<description><![CDATA[ECMA script 4 (or 3.1) and OpenGL 3. I may be in the (rare?) position of being highly interested in two disparate technologies. The first being an online scripting language standard governed by ECMA (used in Javascript &#38; Actionscript). The second, an open standard for real-time rendering governed by the Khronos Group (OpenGL). In recent [...]]]></description>
			<content:encoded><![CDATA[<p><a title="ES 3.1 harmony" href="http://ejohn.org/blog/ecmascript-harmony/">ECMA script 4 (or 3.1)</a> and <a title="OpenGL 3 spec" href="http://www.tojiart.com/OpenGL/">OpenGL 3</a>.</p>
<p>I may be in the (rare?) position of being highly interested in two disparate technologies. The first being an online scripting language standard governed by <a title="ECMA international standards organization" href="http://www.ecma-international.org/">ECMA</a> (used in Javascript &amp; Actionscript). The second, an open standard for real-time rendering governed by the <a title="Khronos group" href="http://www.khronos.org/">Khronos Group</a> (<a title="OpenGL" href="http://en.wikipedia.org/wiki/OpenGL">OpenGL</a>). In recent days these two languages have faced most unfortunate developments. First the ECMA script 4&#8230;</p>
<p><span id="more-319"></span></p>
<p>On Nov 7, 2006 Adobe announced the <a title="Emmy Huang on Tamarin" href="http://www.adobe.com/devnet/logged_in/ehuang_tamarin.html">contribution of their ECMA scripting engine to the open source community</a> under the name &#8220;Tamarin&#8221;. <a title="Tamarin project home" href="http://www.mozilla.org/projects/tamarin/">Tamarin</a> is also being used as the JS scripting engine for Mozilla Firefox under the name &#8220;<a title="SpiderMonkey project home" href="http://www.mozilla.org/js/spidermonkey/">SpiderMonkey</a>&#8220;. It seemed like a good idea at the time of release. But now look at the situation: we have AVM2, directly connected to Firefox AND the ECMA committee &#8211;slowing the progress of Actionscript and the Flash Player (and the internet for that matter). Needless to say, this is a disappointment. But it doesn&#8217;t end there&#8230;</p>
<p>Though having plenty of contributors, the realm of real-time rendering is primarily controlled by Microsoft, Nvida, ATI/AMD, Apple, and (more recently) Intel. Microsoft hasn&#8217;t really contributed to the Khronos Group because long ago they decided to pursue their own 3D graphics rendering API known as Direct3D. The evolution of OpenGL has become painfully slow while <a title="DirectX API" href="http://en.wikipedia.org/wiki/DirectX">DirectX</a> and <a title="D3D API" href="http://en.wikipedia.org/wiki/Direct3D">Direct3D</a> are becoming the (de-facto) standard. Finally, the Khronos group promised to improve the long lost API by introducing an object-oriented structure in stark contrast to its current state machine model. That was in October 2007. Last week the specification was finally unveiled and it remains largely the same. Not only is this a big let down, but it will definitely damage all future 3D software and game development releases for non-Windows platforms (including future consoles). Very unfortunate.</p>
<h5>DISCLAIMER: Both of these developments are FAR more complex than what this post outlines -and there&#8217;s justification behind both developments. But on the whole, they both seem bad for everybody (or just me?).</h5>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/calebjohnston/double-dissapointment/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Papervision3D Part 3: Features continued</title>
		<link>http://dispatchevent.org/calebjohnston/papervision3d-introduction-p3/</link>
		<comments>http://dispatchevent.org/calebjohnston/papervision3d-introduction-p3/#comments</comments>
		<pubDate>Sun, 17 Aug 2008 21:56:37 +0000</pubDate>
		<dc:creator>Caleb Johnston</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=290</guid>
		<description><![CDATA[This posting is part 3 of a series. If you find that you&#8217;d rather start from the beginning, check out Part 1 and Part 2 first. In this post, I&#8217;ll cover Papervision animation, the ASCollada project, render statistics, performance optimization. Animation Animation in Papervision3D can be performed the exact same way animation would be performed [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://dispatchevent.org/wp-content/uploads/2008/07/pv3dlogo.png"><img class="alignleft size-medium wp-image-289" src="http://dispatchevent.org/wp-content/uploads/2008/07/pv3dlogo.png" alt="" width="226" height="111" /></a>This posting is part 3 of a series. If you find that you&#8217;d rather start from the beginning, check out <a href="http://dispatchevent.org/calebjohnston/papervision3d-introduction-p1/">Part 1</a> and <a href="http://dispatchevent.org/calebjohnston/papervision3d-introduction-p2/">Part 2</a> first. In this post, I&#8217;ll cover Papervision animation, the ASCollada project, render statistics, performance optimization.</p>
<p><em><strong>Animation</strong></em><br />
Animation in Papervision3D can be performed the exact same way animation would be performed in 2D. Simply apply any tween or algorithm to an object property (like x, y, rotationX, scaleY, etc) and re-render the scene. But, for imported animations its not quite that simple. Lately Moses&#8217;s GoASAP package is being adopted in testing for the Papervision engine. It could soon become adopted by the system.</p>
<p><em><strong>The Collada DAE Parser</strong></em><br />
Imported animations come in plenty of flavors but must conform to the same system. That&#8217;s the reason the animations package exists. Papervision has long supported externally created 3D assets. You&#8217;ll find those file parsers in <a title="pv3d.objects.parsers" href="http://code.google.com/p/papervision3d/source/browse/#svn/trunk/branches/GreatWhite/src/org/papervision3d/objects/parsers">pv3d.objects.parsers</a>. Although, these importers are nice to have, a big part of Great White was the introduction of the open source project ASCollada. ASCollada is an amazing parser for the standard 3D asset interchange format known as <a href="http://en.wikipedia.org/wiki/COLLADA">Collada</a>. Collada files are basically very dense XML files that use a .dae file extension. Collada files can be exported from Maya, 3D Studio Max, Blender, Google Sketchup, and XSI. However, level of support for those programs probably follows this order: 3D Studio Max, Maya, Blender, Google Sketchup, XSI. Also, if you&#8217;re importing MD2 models, the MD2 file parser will import most animations as well.</p>
<p><span id="more-290"></span></p>
<p>You can try it out using the DAE class like so:</p>
<p><span style="#0000ff;"><code>import org.papervision3d.events.FileLoadEvent;<br />
import org.papervision3d.objects.parsers.DAE;<br />
daeScene = new DAE();<br />
daeScene.addEventListener(FileLoadEvent.LOAD_COMPLETE, onSceneGeometryLoaded);<br />
daeScene.addEventListener(FileLoadEvent.ANIMATIONS_COMPLETE, onSceneAnimationsLoaded);<br />
daeScene.load("your_scene.dae");<br />
var animChannel:AbstractChannel3D = daeScene.getAnimationChannels()[0];<br />
var frame:uint = 20;<br />
var animObject:DisplayObject3D = animChannel.defaultTarget;<br />
animChannel.updateToFrame(frame, animObject);</code></span></p>
<p><em><strong>Render Statistics</strong></em><br />
Papervision records all the primary rendering tasks. If you want to monitor rendering statistics, you can have them captured when you execute the BasicRenderEngine instance method &#8220;renderScene().&#8221; When traced, a typical render report will appear like this:</p>
<p><span style="#0000ff;">ProjectionTime:0 RenderTime:1 Particles:0 CulledParticles:0 Triangles:38 ShadedTriangles:0 CulledTriangles:82 FilteredObjects:0 CulledObjects:0</span></p>
<p>You can use this information to determine how well your scene is rendering. And it could give you ideas on how you can improve rendering by adjusting camera settings, culling plans, and clipping.</p>
<p><em><strong>Optimization</strong></em><br />
Great White has gained many huge performance advantages over previous versions of Papervision. One important advantage is that nearly all materials will render a surface to BitmapData. This is great because, as of Flash Player Update 3 (9.0.115, mid-2007) <a title="flash.display.BitmapData multi-core support" href="http://www.kaourantin.net/2007/06/multi-core-support.html">Multicore CPU support has been added to much of the BitmapData operations</a>.</p>
<p>Clipping is a flag added to the Viewport3D constructor in Great White that will force the engine to perform clipping of all objects outside the the viewing rectangle (the viewport). This feature may seem obvious, but a lot of public engines neglect this.</p>
<p><em><strong>Culling Algorithms</strong></em><br />
Drawing is the most expensive process that Papervision performs. As such, there are a few <a title="Hidden surface removal" href="http://en.wikipedia.org/wiki/Hidden_surface_determination">different standard methods</a> for removing items from the render queue in any 3D drawing API. This helps speed up render times by removing renderable triangles that would otherwise be drawn. Papervision3D performs backface culling, view frustum culling, and contribution culling but NOT occlusion culling. Occlusion culling is a huge process that is more built into accelerated APIs like OpenGL. Though it can be very difficult to perform well, it can also add extrordinary benefits to rendering performance.</p>
<p><em><strong>MovieClip Materials</strong></em><br />
Papervision3D supports interactive, animated, and smoothed <a title="org.papervision3d.materials.MovieMaterial" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/materials/MovieMaterial.as">MovieClip</a> materials. However, those features come at a cost. You may already be aware that BitmapData smoothing (anti-aliasing) is slower than normal BitmapData rendering. Anti-aliasing algorithms are simply expensive operations and thats the bottom line. The other two features are performance hogs because they require that the Flash player to update the surface BitmapData object on each frame update &#8211;instead of reusing the original object that was derived from the MovieClip.</p>
<p><em><strong>Relative Performance</strong></em><br />
I&#8217;m currently coding lots of Flash player performance tests as they relate to Papervision. Right now I&#8217;m only using the following methods for testing: Math.sqrt(), Math.sin(), Matrix3D.multiply3x3(), and BitmapData.draw(). The test is simply a for loop that iterates 9999 times. It looks interesting and helps me make another point about PV3D performance. I&#8217;ll have to publish this application elsewhere, but for now here&#8217;s a sample of what I&#8217;m finding:</p>
<table style="134px;" border="0" cellspacing="0" cellpadding="3" width="301">
<tbody>
<tr>
<td>method</td>
<td>milliseconds</td>
</tr>
<tr>
<td>Math.sqrt(x)</td>
<td>1</td>
</tr>
<tr>
<td>Math.sin(x)</td>
<td>2</td>
</tr>
<tr>
<td>Matrix3D.multiply3x3(a,b)</td>
<td>13</td>
</tr>
<tr>
<td>BitmapDataObject1.draw(c)</td>
<td>661</td>
</tr>
<tr>
<td>BitmapDataObject2.draw(d)</td>
<td>2037</td>
</tr>
</tbody>
</table>
<p>Figure A: Performance timetable for 4 operations in a for loop lasting 9999 iterations. BitmapDataObject1 is 40&#215;40, transparent and BitmapDataObject2 is 600&#215;600, transparent. They both draw a single purple circle.</p>
<p>As you can see bitmap drawing is the most expensive operation here. In almost every instance that I can think of, drawing will be the most performance intensive activity in any 3D rendering API. I could explain that here, but it would probably double the size of this post. ;)Â  In a nutshell, it always helps to render only when you actually need to feature interaction and/or animation. Additionally, actively perform any reasonable operation to limit the number of objects in the scene. Again, the library does a lot for you there, but gains can always be made. Also, a little experience will show you that keeping the renderable area small will help also.</p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/calebjohnston/papervision3d-introduction-p3/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Papervision3D Part 2: Features</title>
		<link>http://dispatchevent.org/calebjohnston/papervision3d-introduction-p2/</link>
		<comments>http://dispatchevent.org/calebjohnston/papervision3d-introduction-p2/#comments</comments>
		<pubDate>Fri, 25 Jul 2008 04:50:12 +0000</pubDate>
		<dc:creator>Caleb Johnston</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dispatchevent.org/?p=287</guid>
		<description><![CDATA[This is part 2 of a 4 part series outlining 3D in Flash by dissecting the open source Papervision3D library. Before getting deep into features let me first make a few points about using Papervision3D. The Papervision3d source SVN location includes the standard AS3 version of Papervision3D (version 1.7 as of this writing). If you [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://dispatchevent.org/wp-content/uploads/2008/07/pv3dlogo.png"><img class="alignleft size-medium wp-image-289" src="http://dispatchevent.org/wp-content/uploads/2008/07/pv3dlogo.png" alt="" width="226" height="111" /></a>This is part 2 of a 4 part series outlining 3D in Flash by dissecting the open source Papervision3D library. Before getting deep into features let me first make a few points about using Papervision3D.</p>
<p>The <a title="Google Code PV3D SVN source" href="http://code.google.com/p/papervision3d/">Papervision3d source SVN location</a> includes the standard AS3 version of Papervision3D (<a title="pv3d.Papervision3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/as3/trunk/src/org/papervision3d/Papervision3D.as">version 1.7</a> as of this writing). If you look at the branches folder inside trunk you will find <a title="pv3d.Papervision3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/Papervision3D.as">version 2.0</a> which is code-named &#8220;Great White&#8221;. This series is focused on that branch, and NOT version 1.7. Also, its important to know that Great White is probably the fastest and most frequently changing part of the Papervision source and thus details in this article will likely change over time.</p>
<p>Also, as a convention in these posts, I&#8217;ll be putting direct references to actual Google Code hosted repository files inside this page. If you don&#8217;t wish to open that repository each time you want to know the path of a class, then simply mouse over the link and look at the link address or the tool tip that shows up for the link. All references to Papervision3D classes assume that all uses of the term &#8220;pv3d&#8221; refer to the root Papervision3D package.</p>
<p><span id="more-287"></span></p>
<p>All Flash demonstrations are interactive. After focusing on the Flash applet, you can use the following key controls to control the camera.</p>
<table border="0" cellspacing="0" cellpadding="2" width="400">
<tbody>
<tr>
<td>key</td>
<td>control</td>
</tr>
<tr>
<td>w</td>
<td>move forward</td>
</tr>
<tr>
<td>s</td>
<td>move backward</td>
</tr>
<tr>
<td>a</td>
<td>move left</td>
</tr>
<tr>
<td>d</td>
<td>move right</td>
</tr>
<tr>
<td>q</td>
<td>decrease rotation Z</td>
</tr>
<tr>
<td>e</td>
<td>increase rotation Z</td>
</tr>
<tr>
<td>r</td>
<td>increase field of view</td>
</tr>
<tr>
<td>f</td>
<td>decrease field of view</td>
</tr>
<tr>
<td>t</td>
<td>increase distance of the near clipping plane</td>
</tr>
<tr>
<td>g</td>
<td>decrease distance of the near clipping plane</td>
</tr>
<tr>
<td>y</td>
<td>increase distance of the far clipping plane</td>
</tr>
<tr>
<td>h</td>
<td>decrease distance of the far clipping plane</td>
</tr>
<tr>
<td>mouse Y</td>
<td>pitch</td>
</tr>
<tr>
<td>mouse X</td>
<td>yaw</td>
</tr>
</tbody>
</table>
<p>Please note that nothing will promote your understanding of the code better than just reading it yourself. Although that may seem daunting, you&#8217;ll end up doing it anyway if you really get into the project. A good place to start might be reading the comments for classes in the folder pv3d.core.proto. If you&#8217;ve happened upon this page but are unfamiliar with computer graphics from a technical standpoint, please <a title="introduction" href="http://dispatchevent.org/calebjohnston/papervision3d-introduction-p1/">read Part 1</a></p>
<p><em><strong>Geometry</strong></em><br />
In Papervision, all geometry is basically stored in the form of vertex data (<a title="pv3d.core.geom.renderables.Vertex3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/core/geom/renderables/Vertex3D.as">Vertex3D</a>). Collections of Vertices are stored in <a title="pv3d.core.proto.GeometryObject3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/core/proto/GeometryObject3D.as?r=595">GeometryObject3D</a> instances. Every <a title="pv3d.objects.DisplayObject3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/objects/DisplayObject3D.as">DisplayObject3D</a> class contains object information (such as location, transformation, orientation axis, etc) AND a reference to a <a title="pv3d.core.proto.GeometryObject3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/core/proto/GeometryObject3D.as?r=595">GeometryObject3D</a> instance. The <a title="pv3d.objects.DisplayObject3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/objects/DisplayObject3D.as">DisplayObject3D</a> class is the building block of all 3D data in Papervision &#8211;much like the flash.display.DisplayObject class is the building block of a 2D stage. However, one important difference is that a <a title="pv3d.objects.DisplayObject3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/objects/DisplayObject3D.as">DisplayObject3D</a> will not contain any rasterized visual data (as the DisplayObject does in its graphics object). It contains only data that is used by the rendering engine (<a title="pv3d.render.BasicRenderEngine" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/render/BasicRenderEngine.as">BasicRenderEngine</a>) and the object&#8217;s material (* <a title="pv3d.core.proto.MaterialObject3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/core/proto/MaterialObject3D.as">MaterialObject3D</a>) which is used to draw the object onto a <a title="pv3d.view.Viewport3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/view/Viewport3D.as">Viewport3D</a> object.</p>
<p>*Note: the actual method performing all drawing operations is NOT <a title="pv3d.core.proto.MaterialObject3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/core/proto/MaterialObject3D.as">MaterialObject3D</a>.drawTriangle but instead any of its subclassses that are overriding that method (for example <a title="pv3d.materials.ColorMaterial" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/materials/ColorMaterial.as">ColorMaterial</a>.drawTriangle).</p>
<p><em><strong>Texture Mapping</strong></em><br />
Up until now, all discussion about 3D rendering has excluded the use of images used on geometric surfaces. This feature, called texture mapping, is very widely used. Unfortunately, it can also be quite an expensive process in terms of CPU cylces. Texture mapping has also evolved to allow for plenty of visual effects like <a title="bump mapping" href="http://en.wikipedia.org/wiki/Bump_mapping">bump mapping</a>, <a title="normal mapping" href="http://en.wikipedia.org/wiki/Normal_mapping">normal mapping</a>, <a title="displacement mapping" href="http://en.wikipedia.org/wiki/Displacement_map">displacement mapping</a>, light mapping and more.</p>
<p>As you may recall from <a title="Papervision3D Introduction part 1" href="http://dispatchevent.org/calebjohnston/papervision3d-introduction-p1/">Part 1</a>, all surface geometry in Papervision is divided into triangles. However, since images used in texture mapping are rectangular, something must be done to determine how the image can be mapped onto triangles in order to render the rectangular map as a single image. This is where the <a title="uv mapping" href="http://en.wikipedia.org/wiki/UV_mapping">UV coordinates</a> come in. A UV is simply a 2D coordinate that represents a location on the texture map that is associated with the 3D point on a triangle. Figure A1 shows this relationship.</p>
<p>Figure A1: Three example UVs for texture mapping a rectangular plane.</p>
<p><img src="http://www.calebjohnston.com/storage/posts/uvs.jpg" alt="UV mapping example" width="450" height="168" /></p>
<p>In Papervision, all the actual drawing commands exist in the material class being used for an object (as I mentioned above). Please note that two options for texture mapping exist. There&#8217;s &#8216;normal&#8217; texture mapping which is also known as &#8216;<a title="Affine transformation of a plane" href="http://en.wikipedia.org/wiki/Affine_transformation#Affine_transformation_of_the_plane">affine</a>&#8216; texture mapping. And then there&#8217;s &#8216;precise&#8217; texture mapping which would be perspective correct. Normal texture mapping is a bit less accurate but far faster in rendering then precise textures. Exhibit A2 shows an example.</p>
<p>Exhibit A2: Normal (left) vs precise (right) texture mapping in Papervision3D 2.0</p>
<p>[kml_flashembed movie="http://www.calebjohnston.com/storage/posts/textureExample.swf" height="250" width="450" /]</p>
<p><strong><em>Materials</em></strong><br />
A Material is a term borrowed from 3D development tools (like 3D Studio Max) that describes a collection of properties that will determine how a 3D surface will be rendered. Materials can become very complicated in production 3D rendering tools, but in Papervision a material has only a few properties. Those properties will determine whether lines, fills and/or a bitmap is drawn and how they&#8217;re drawn. The real key component of all materials is the drawTriangle method which is called by the engine during the render cycle.</p>
<p><strong><em>Lighting and Shading</em></strong><br />
Light simulation is probably one of the most intricate and complicated aspects of 3D rasterisation. Other forms of computer rendering (like <a title="ray tracing" href="http://en.wikipedia.org/wiki/Ray_tracing">ray tracing</a>) don&#8217;t treat lighting the way the rasterisation technique does. The reason is simple, performance. So in order to mimic light phenomena using rasterisation, shaders can be used. With the Great White branch of Papervision, lighting and shading have been added. Outside of Papervision, the term &#8220;<a title="shader explanation" href="http://en.wikipedia.org/wiki/Shader">shader</a>&#8221; sort of has multiple definitions. Shaders are used in 3D development tools to determine how light will appear on a surface. But in real-time rendering APIs (like <a title="OpenGL API" href="http://en.wikipedia.org/wiki/OpenGL">OpenGL</a> and <a title="Microsoft Direct3D" href="http://en.wikipedia.org/wiki/Direct3D">Direct3D</a>) a shader is used to modify the <a title="graphics pipeline" href="http://en.wikipedia.org/wiki/Graphics_pipeline">graphics pipeline</a>. There are actually several languages that govern shader authoring. Even Adobe has their own brand of shader language called <a title="Adobe Image Foundation toolkit" href="http://labs.adobe.com/wiki/index.php/AIF_Toolkit">Adobe Image Foundation</a>. Although shading and lighting are rather complicated features in GPU accelerated APIs, in Great White they&#8217;re actually much simpler.</p>
<p>With Papervision, shaders are probably most useful for applying native flash effects (filters and blend modes) to any desired surface. Although, filters are not fully supported yet. Aside from that, applying a shader to a material is basically the same as applying a gradient-like light map to the BitmapData surface. So if you understand gradients and BitmapData objects in Flash, you basically understand Papervision shading as well. There are really 4 types of light maps you can use and those are <a title="pv3d.materials.shaders.PhongShader" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/materials/shaders/PhongShader.as">Phong</a>, <a title="pv3d.materials.shaders.FlatShader" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/materials/shaders/FlatShader.as">Flat</a>, <a title="pv3d.materials.shaders.GouraudShader" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/materials/shaders/GouraudShader.as">Gouraud</a>, and <a title="pv3d.materials.shaders.CellShader" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/materials/shaders/CellShader.as">Cell</a>. For each of those light maps there is a shader. There is also one other shader that can create an environment map. Its the <a title="pv3d.materials.shaders.EnvMapShader" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/materials/shaders/EnvMapShader.as">EnvMapShader</a>. It allows one to pass in bitmap objects that are used in combination with the surface texture map. Also you can use bump maps in Papervision3D shaders. See the <a title="pv3d.materials.utils.BumpmapGenerator" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/materials/utils/BumpmapGenerator.as">BumpmapGenerator</a> class. Exhibit B illustrates a simple example of various shaders. While this is not really the same &#8216;shading&#8217; that happens in video games, with Flash 10, shading could definitely change radically in Papervision.</p>
<p>Exhibit B: Shading examples in Papervision3D 2.0</p>
<p>[kml_flashembed movie="http://www.calebjohnston.com/storage/posts/shadersExample.swf" height="250" width="450" /]</p>
<p>Its also important to note that shading requires a light source. Unlike other popular 3D APIs, there is no default ambient light. And any light sources that are used are not a part of the scene. Instead you must add a light source to the shader and its position is used in determining what the light map looks like. At the time of this writing there is only one light source supported per shader in Papervision3D. Also there is only one type of light to choose from -a <a title="pv3d.lights.PointLight3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/lights/PointLight3D.as">point light</a>.</p>
<p><em><strong>Cameras</strong></em><br />
Cameras aren&#8217;t that complicated in Papervision3D. There are three types of Cameras: free, target, and debug. A free camera is totally unattached to anything that exists in the environment and can be moved &#8216;freely&#8217;. But a target camera will have a focus object within the scene. That object can be moved freely, but the camera will always come along. It works just like a focus camera object would work in a 3D development tool like 3D Studio Max or Maya. And thus a key aspect of that behavior is that if you want to translate a <a title="pv3d.cameras.Camera3D" href="http://code.google.com/p/papervision3d/source/browse/trunk/branches/GreatWhite/src/org/papervision3d/cameras/Camera3D.as">Camera3D</a> object, it will actually rotate about its focus object. The last type of camera (debug) allows for key control, so that you can move the camera around as desired. This is highly useful when you&#8217;re building a complex scene or importing geometry from an external editor.</p>
<p>The only three camera-specific properties you can manipulate to control the view are zoom, focus and field of view (fov). The fov is in degrees. Normally 60 is representative of a normal 35mm camera lens. But the debug camera defaults to 90 degrees. Zoom and focus can be determined based on the fov and the camera&#8217;s distance to the near clipping plane. Exhibit C demonstrates the interaction of the fov and focus value. Also, here are some rather crude numbers for comparison:</p>
<table border="0" cellspacing="3" cellpadding="0" width="460">
<tbody>
<tr>
<td>lens focal length</td>
<td>lens type</td>
<td>PV3D camera focus</td>
<td>PV3D field of view</td>
</tr>
<tr>
<td>21 mm</td>
<td>very wide angle</td>
<td>6-</td>
<td>120+</td>
</tr>
<tr>
<td>21-35 mm</td>
<td>wide angle</td>
<td>6-12</td>
<td>80-120</td>
</tr>
<tr>
<td>37-70 mm</td>
<td>normal</td>
<td>12-17</td>
<td>60-80</td>
</tr>
<tr>
<td>70-135 mm</td>
<td>medium telephoto</td>
<td>17-27</td>
<td>40-60</td>
</tr>
<tr>
<td>135-300 mm</td>
<td>telephoto</td>
<td>27+</td>
<td>40-</td>
</tr>
</tbody>
</table>
<p>Note: all camera focus values are used with a default debug zoom value of 24. Field of view values are in degrees.</p>
<p>Exhibit C: Demonstration of camera field of view and focus. Use keys r and f to increase and decrease the fov respectively.</p>
<p>[kml_flashembed movie="http://www.calebjohnston.com/storage/posts/cameraExample.swf" height="250" width="450" /]</p>
<p>Stay tuned for more feature dissection in Part 3. In the meantime, <a title="Papervision3d introduction part2 examples" href="http://www.calebjohnston.com/storage/posts/Papervision3D-introduction-part2.zip">download examples source files here.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://dispatchevent.org/calebjohnston/papervision3d-introduction-p2/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>

