<?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>JetpackHQ &#187; Programming</title>
	<atom:link href="http://www.jetpackhq.com/blog/category/development-news/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.jetpackhq.com/blog</link>
	<description>A chronicle of the development of a video game</description>
	<lastBuildDate>Sun, 18 Jul 2010 14:44:38 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Control Me</title>
		<link>http://www.jetpackhq.com/blog/2010/01/18/control-me/</link>
		<comments>http://www.jetpackhq.com/blog/2010/01/18/control-me/#comments</comments>
		<pubDate>Mon, 18 Jan 2010 19:58:35 +0000</pubDate>
		<dc:creator>Adam</dc:creator>
				<category><![CDATA[Input Requested]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Status Updates]]></category>
		<category><![CDATA[Tech Demos]]></category>

		<guid isPermaLink="false">http://www.jetpackhq.com/blog/?p=171</guid>
		<description><![CDATA[In the good old days of Jetpack 1, things were much simpler.  Input from the keyboard or joystick was translated directly into action.
It was along the lines of:

if(key[right arrow]) speedx += 10;
sprite.posx += speedx;

Sometimes I miss the old days&#8230;  The new path from input to action now looks like:

set up key bindings from [...]]]></description>
			<content:encoded><![CDATA[<p>In the good old days of Jetpack 1, things were much simpler.  Input from the keyboard or joystick was translated directly into action.</p>
<p>It was along the lines of:</p>
<ul>
<li>if(key[right arrow]) speedx += 10;</li>
<li>sprite.posx += speedx;</li>
</ul>
<p>Sometimes I miss the old days&#8230;  The new path from input to action now looks like:</p>
<ul>
<li>set up key bindings from default or configuration data</li>
<li>for each human player, translate input into commands based on bindings table; &#8220;right arrow&#8221; becomes &#8220;move right&#8221;</li>
<li>send commands to each player&#8217;s controlled entity</li>
<li>each entity processes commands through its state machine(s); if we&#8217;re on the ground, &#8220;move right&#8221; becomes &#8220;run right&#8221;</li>
<li>active states run actions &#8211; in this case, the &#8220;run right&#8221; state applies horizontal force to the entity&#8217;s physical body</li>
<li>the graphical representation of the physical body is updated</li>
</ul>
<p>The new process is certainly more powerful, but requires somewhere around 1000x more effort to write.  Below lies the implementation of the above process, the control tech demo.  You can use the arrows to control all the various entities, and [square backets] or the mouse to switch entities.  Your entity&#8217;s active state machines are displayed in the debug line at the bottom.</p>
<div style="text-align: center;">
<object id="iefix_unique2010_01" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="800" height="600" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="src" value="/r/launcher.swf?launch=/r/2010-01_control.swf" /><embed type="application/x-shockwave-flash" width="800" height="600" src="/r/launcher.swf?launch=/r/2010-01_control.swf"></embed></object></div>
<p>One of the nice things about this newfangled control system is that it meshes very well with the AI, which only needs to supply a command list to an entity, and not worry about the implementation details.  You can see this in action when you launch a guided missile &#8211; it will follow the mouse cursor using a generic AI &#8220;chase&#8221; algorithm.  This release also incorporates various other enhancements, including the <a href="/blog/2009/11/17/using-a-launcher-swf/">launcher from a previous post</a>.</p>
<h2>Jetpack 2 Engine Status</h2>
<p>I meant to have this demo out a month ago, but I opened up the Pandora&#8217;s Box of AS3 code optimization and fell in.  This had to be done at some point, so I&#8217;m glad its mostly out of the way.  On the plus side, I found several optimizations that doubled the frame rate of the game engine &#8211; there will be a big post on this later.  The engine is pretty close to basic playability now, and I&#8217;ll be releasing a special retro version of Jetpack in March.</p>
<h2>Personal Stuff</h2>
<p>My gallbladder surgery was successful, but I&#8217;m only feeling about 25% better.  I think it was worth it, but it looks like that wasn&#8217;t the cure-all I was hoping for.  Thanks to all the well-wishers!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jetpackhq.com/blog/2010/01/18/control-me/feed/</wfw:commentRss>
		<slash:comments>33</slash:comments>
		</item>
		<item>
		<title>Using a Launcher SWF</title>
		<link>http://www.jetpackhq.com/blog/2009/11/17/using-a-launcher-swf/</link>
		<comments>http://www.jetpackhq.com/blog/2009/11/17/using-a-launcher-swf/#comments</comments>
		<pubDate>Tue, 17 Nov 2009 14:01:49 +0000</pubDate>
		<dc:creator>Adam</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.jetpackhq.com/blog/?p=145</guid>
		<description><![CDATA[Since this blog could potentially have many SWF examples on a single page, I have to consider effect of having them load and run all at once, both on the browser and on my bandwidth.  Users will not always want to see every SWF, so ideally a &#8220;click to start&#8221; intro would precede the loading [...]]]></description>
			<content:encoded><![CDATA[<p>Since this blog could potentially have many SWF examples on a single page, I have to consider effect of having them load and run all at once, both on the browser and on my bandwidth.  Users will not always want to see every SWF, so ideally a &#8220;click to start&#8221; intro would precede the loading of each example.</p>
<p>I tried this with just an image: when it was clicked, it would hide itself and embed the SWF where the image had been. Unfortunately, the SWF was not focused and would have to be clicked again, and Firefox has a flaw that does not always allow javascript to focus a SWF <img src='http://www.jetpackhq.com/blog/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> . Therefore the nice and simple image idea had to give way to a whole separate SWF as a launcher for the examples. The launcher is always running, but it&#8217;s small and the frame rate is low and it doesn&#8217;t do too much. Once the launcher is clicked it loads the example SWF and bumps up the frame rate to the proper level.  Of course, since this is Actionscript, what takes a sentence to write took 2 days to implement.</p>
<p>This is a form of preloader, and I&#8217;ve gotten confused a few times when thinking about this, so I&#8217;ll document it here.  It also helped me to refer back to my <a href="/blog/2008/03/25/writing-a-preloader-in-actionscript-3/">post on preloaders</a>.</p>
<h3>preloader via separate swf</h3>
<ul>
<li>displays &#8220;click to start&#8221; and waits &#8211; this can be bypassed via an argument to the swf</li>
<li> loads the main swf while updating progress</li>
<li> sets the new framerate, activates the main swf, and goes away</li>
</ul>
<h3>preloader embedded in main swf</h3>
<ul>
<li>the preloader is on frame 1 of the timeline, and begins to execute while the rest of the timeline loads</li>
<li> large assets are embedded in later frames</li>
<li> the preloader passes control to the main program once the swf fully loads</li>
</ul>
<p>For Jetpack, I&#8217;m going to attempt a combination of the 2 methods, so the user experience will be as follows:</p>
<ul>
<li>The game window will instantly show loading progress (preloader swf)</li>
<li>The preloader will fade away, revealing a Jetpack level in demo playback (main swf preloader)</li>
<li>While the demo game runs, a status bar will show progress as the rest of the assets (mp3 music) load<br />
(At this point, an in-game ad could be shown, but the income from those is not impressive and I&#8217;d rather not clutter up the game.)</li>
<li>When loading is complete, the main menu will fade into view</li>
</ul>
<p>There are some other advantages to using a launcher swf that I can think of:</p>
<ul>
<li> When users embed the launcher swf on their own websites, it will always load the latest version of Jetpack from JetpackHQ.</li>
<li> I&#8217;ll have full stats on who is playing and where.</li>
<li> Security against game reskinning is improved, by having the launcher and the main swf validate eachother.</li>
</ul>
<p>Getting the launcher just right took some struggling with Actionscript, but the result works great.  It&#8217;s only 2k, and can serve just about any swf file (on the same server).  I was able to find a way to read the target framerate from the loaded swf and set that before launching it.  You can also read the width &amp; height, but I know no way of resizing the SWF at runtime without using javascript.  I&#8217;ve attached the source code to this project at the bottom of this post.  Here&#8217;s a sample:</p>
<blockquote>
<pre>function Startup()
{
    // ARGS - launch='', now=0/1
    var args = stage.loaderInfo.parameters;
    if(args.launch!=undefined) launch_swf_path = args.launch;
    if(args.now!=undefined) wait_for_click = !int(args.now);
    if(!launch_swf_path) Fail("usage: launcher.swf?launch=abc.swf&amp;now=0");

    if(wait_for_click)
    {
        Show_WaitForClick();
        stage.addEventListener(MouseEvent.CLICK, StartLaunch);
    }
    else StartLaunch();
}

//--------------------------------------

function Shutdown()
{
    root.Shutdown();
    root = null;
    System.gc();
}

//------------------------------------------------------------------------------

function StartLaunch(event:MouseEvent=null)
{
    if(wait_for_click)
    {
        stage.removeEventListener(MouseEvent.CLICK, StartLaunch);
        Hide_WaitForClick();
    }
    Show_Preloader();
    loader = new Loader();
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, CheckReady_Hack);
    stage.addEventListener(Event.ENTER_FRAME, CheckReady_Hack);
    loader.load(new URLRequest(launch_swf_path));
}

//--------------------------------------

function CheckReady_Hack(event:Event)
{
    // in certain cases when not waiting for click, complete/init fires but loaderInfo.frameRate
    // is not accessible.  misinformation from the official ActionScript docs: "When the loaderInfo
    // object dispatches the init event, you can access all properties of the loaderInfo object"
    if(event.type==Event.COMPLETE)
    {
        ready_hack = true;
        loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, CheckReady_Hack);
    }
    if(event.type==Event.ENTER_FRAME)
    {
        if(!ready_hack) return;
        stage.removeEventListener(Event.ENTER_FRAME, CheckReady_Hack);
        Launch();
    }
}

//--------------------------------------

function Launch()
{
    Hide_Preloader();

    var swf:DisplayObject = loader.content;
    // frameRate, width, height are only available before unload()
    stage.frameRate = swf.loaderInfo.frameRate;
    loader.unload();
    loader = null;

    // clear the stage
    while(stage.numChildren) stage.removeChildAt(0);
    // launch the loaded swf
    stage.addChild(swf);
    Shutdown();
}</pre>
</blockquote>
<p><img style="vertical-align:middle;" src="/r/download_icon.png" alt="" width="32" height="32" /> <a href="/r/launcher-2009-11-17.zip">Download launcher-2009-11-17.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.jetpackhq.com/blog/2009/11/17/using-a-launcher-swf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Actionscript Caveats, Gotchas, &amp; WTF &#8211; Part 1</title>
		<link>http://www.jetpackhq.com/blog/2009/09/16/actionscript-caveats-gotchas-wtf-part-1/</link>
		<comments>http://www.jetpackhq.com/blog/2009/09/16/actionscript-caveats-gotchas-wtf-part-1/#comments</comments>
		<pubDate>Wed, 16 Sep 2009 16:10:36 +0000</pubDate>
		<dc:creator>Adam</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.jetpackhq.com/blog/?p=124</guid>
		<description><![CDATA[This is what I would like to do to the designers of Actionscript:

There are very few good large scale games written for Flash, and there&#8217;s a good reason why: Actionscript is chock full of undocumented problems that Adobe is either unaware of or unwilling to fix.  I feel bad for anyone who was introduced to [...]]]></description>
			<content:encoded><![CDATA[<p>This is what I would like to do to the designers of Actionscript:</p>
<div style="text-align:center;"><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="445" height="364" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube-nocookie.com/v/OgWvLkTkTBY&amp;hl=en&amp;fs=1&amp;color1=0x3a3a3a&amp;color2=0x999999&amp;border=1" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="445" height="364" src="http://www.youtube-nocookie.com/v/OgWvLkTkTBY&amp;hl=en&amp;fs=1&amp;color1=0x3a3a3a&amp;color2=0x999999&amp;border=1" allowscriptaccess="always" allowfullscreen="true"></embed></object></div>
<p>There are very few good large scale games written for Flash, and there&#8217;s a good reason why: Actionscript is chock full of undocumented problems that Adobe is either unaware of or unwilling to fix.  I feel bad for anyone who was introduced to programming with this language.  I wish I had documented all the roadblocks I&#8217;ve had to work around, but I&#8217;ve only got a small sample of the most heinous or recent ones that are causing headaches.  I don&#8217;t have any saved up for part 2 of this series, but I&#8217;m confident that won&#8217;t be a problem.</p>
<h3>Mysterious Arrow &amp; Numeric Key Issue</h3>
<p>Recently, on one of my computers, arrow and number keys are firing key-up immediately after key-down, so you can&#8217;t tell if one of the keys is held down.  Many flash games never catch the key-down event at all, so most flash games are unplayable for me on this computer.  I have no idea why &#8211; I&#8217;ve tried several recent versions of the Flash player and both the debug/release versions, both in-browser and standalone.</p>
<h3>Mysterious Faint Box</h3>
<p>On another one of my computers, whenever an object is rotated a very faint solid rectangle appears behind it.</p>
<h3>The Registration Point Problem</h3>
<p>Most graphical objects in Actionscript have a registration point (or &#8220;center&#8221;) at the object&#8217;s center, meaning when you set an object&#8217;s position you are saying where the center of the object should be.  This also means that rotation occurs more or less as you would expect.  Bitmaps don&#8217;t work this way &#8211; the registration point is the top left of the object.  There is no way to move the registration point.  What you have to do &#8211; and all this is completely undocumented &#8211; is hack a solution by applying an offset via matrix transformation, and never again using the object&#8217;s x, y, or rotation properties.  There are many many people asking about this problem on the web, and only a few partial solutions are out there.  I wasted an entire day and pulled out a lot of hair figuring this out.</p>
<h3>Alpha / ColorTransform is slow</h3>
<p>If you change the opacity of your visuals, you&#8217;ll notice a significant drop in performance.  I was suprised by this, because I&#8217;m also importing graphics with an alpha channel, and those don&#8217;t have the slowdown.  I&#8217;m guessing that Flash&#8217;s drawing algorithm must be applying the alpha as a separate step before the blit, rather than doing it during the blit.  To get around this and other suboptimal behavior, I&#8217;ve written a system to automatically cache a graphic after all the effects are applied, and mark the cache dirty when an effect changes.  Also, when opacity is set to zero the processing continues unabated &#8211; you need to manually set the graphic&#8217;s visibility off when this happens.</p>
<h2>More Reading</h2>
<p>There used to be some other websites with more Actionscript issues, but they seem to be gone.  If you find any more, please share them.<strong><br />
</strong></p>
<p><a href="http://blog.iconara.net/category/actionscript/architectural-atrocities/">Iconara&#8217;s Architectural Atrocities</a><br />
Choice quote:</p>
<blockquote><p>The ActionScript 3.0 API:s have a few interfaces, in general it’s a good thing, it shows that the Macromedia/Adobe developers actually understand something, which hasn’t been obvious in the past.<br />
The decision to include interfaces in AS2 was probably a manager or marketing executive saying “hey, all the other languages have something called ‘interfaces’, why don’t we?”, and the developers quietly obeyed.</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.jetpackhq.com/blog/2009/09/16/actionscript-caveats-gotchas-wtf-part-1/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Protecting Flash Source Code</title>
		<link>http://www.jetpackhq.com/blog/2009/07/26/protecting-flash-source-code/</link>
		<comments>http://www.jetpackhq.com/blog/2009/07/26/protecting-flash-source-code/#comments</comments>
		<pubDate>Sun, 26 Jul 2009 16:44:09 +0000</pubDate>
		<dc:creator>Adam</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.jetpackhq.com/blog/?p=14</guid>
		<description><![CDATA[Imagine spending months or years creating a game, only to have several remarkably similar games appear on the market at the same time.  If your source code is leaked or stolen, you could easily find yourself in the position of competing for income with your own work.  Languages like C++ are compiled into machine code, [...]]]></description>
			<content:encoded><![CDATA[<p>Imagine spending months or years creating a game, only to have several remarkably similar games appear on the market at the same time.  If your source code is leaked or stolen, you could easily find yourself in the position of competing for income with your own work.  Languages like C++ are compiled into machine code, but a major downside of Actionscript is that your source code is maintained virtually intact in your released SWF.  While the few flash decompilers out there are admittedly very buggy, the opporunity exists for a dastardly thief to spend minimal effort to produce a game very similar to your own.  Legal options are often available, but its much easier to avoid the expense and hassle by protecting your code.  This is why SWF obfuscation tools exist.</p>
<p>I evaluated <a href="http://www.kindisoft.com/secureSWF/">Kindisoft&#8217;s secureSWF</a>, <a href="http://www.amayeta.com/software/swfencrypt/">Amayeta&#8217;s SWF Encrypt</a>, <a href="http://www.ambiera.com/irrfuscator/">Ambiera&#8217;s irrFuscator</a>, and <a href="http://www.locklizard.com/flash_security.htm">LockLizard&#8217;s Lizard Flashguard</a>.  Based on the level of security features, ease of use, and stability, the tool I&#8217;ve chosen for this task is <strong>secureSWF</strong>.  It offers several good features, and the ones I found most useful are:</p>
<ul>
<li>renames identifiers</li>
<li>uses several techniques to obscure code flow</li>
<li>encrypts strings</li>
<li>optimizes code</li>
<li>has build process integration</li>
</ul>
<p>Obfuscating Actionscript is a pretty complex task and secureSWF handles it well &#8211; my SWF ran perfectly with adjustments to all security settings.  Here are the results of my rough performance comparisons:</p>
<p><span style="text-decoration: underline;"><strong>no security</strong></span><br />
plain SWF: 211k , 37fps</p>
<p><span style="text-decoration: underline;"><strong>default settings</strong></span><br />
secure SWF: 293k, 35fps<br />
40% larger, 6% slower</p>
<p><span style="text-decoration: underline;"><strong>custom settings &#8211; disabled &#8220;control flow obfuscation&#8221;</strong></span><br />
secure SWF: 244k, 37fps<br />
15% larger, no performance loss</p>
<p>Tweaking the settings for less aggressive encryption can give better size and performance, but I consider the small performance hit to be a mandatory cost of business for creating a mid-scale game using Actionscript.  If you have a lot of high quality original source code that you want protected, I highly recommend <strong><a href="http://www.kindisoft.com/secureSWF/">Kindisoft&#8217;s secureSWF</a></strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jetpackhq.com/blog/2009/07/26/protecting-flash-source-code/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Progress Report</title>
		<link>http://www.jetpackhq.com/blog/2009/06/23/progress-update/</link>
		<comments>http://www.jetpackhq.com/blog/2009/06/23/progress-update/#comments</comments>
		<pubDate>Wed, 24 Jun 2009 01:47:30 +0000</pubDate>
		<dc:creator>Adam</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Status Updates]]></category>

		<guid isPermaLink="false">http://www.jetpackhq.com/blog/?p=39</guid>
		<description><![CDATA[Back in July 2008, there was quite a bit of work done that I didn&#8217;t have time to discuss or demo (last year I put the project on hold for 5 months to work on the Obama for America campaign website &#8211; and ended up adding another 5 months because of talks with potential publishers).  [...]]]></description>
			<content:encoded><![CDATA[<p>Back in July 2008, there was quite a bit of work done that I didn&#8217;t have time to discuss or demo (last year I put the project on hold for 5 months to work on the Obama for America campaign website &#8211; and ended up adding another 5 months because of talks with potential publishers).  I did spent some of that time working on the website back end, so a lot of that is done as well.</p>
<h2>What&#8217;s Done</h2>
<ul>
<li><strong>input</strong> <strong>handler:</strong> command bindings &gt; state machine &gt; entity (command stream input for the state machine could eventually be: an AI, a network player, or demo playback)</li>
<li><strong>world cycle:</strong> graphics &amp; basic physics &#8211; auto adapting frame rate independent from game tick, client-render-prediction-capable</li>
<li><strong>animation system: </strong>vector &amp; bitmap, automatic cacheing, adapts to frame rate</li>
<li><strong>original map import</strong>: to faux-3d tiles, layered parallax rendering</li>
<li><strong>basic gui &amp; menu system</strong></li>
<li><strong>asset loading &amp; management system</strong></li>
<li><strong>flash platform: </strong>source encryption system, security wrapper, preloader</li>
<li><strong>website: </strong>improved template/page module system, nice request routing system, smooth deploy system</li>
</ul>
<h2>What&#8217;s New</h2>
<h3>Physics Engine</h3>
<p>I&#8217;m tinkering with the <a href="http://box2dflash.sourceforge.net/">Box2d physics engine</a> for ActionScript 3, and I&#8217;m very impressed with its power and flexibility.  It has many more features than I need, and I&#8217;m just hoping it turns out to be fast enough on slow computers. We&#8217;ll be able to have much more realistic effects without any extra work as long as this library turns out to be fast enough.  I&#8217;ll be releasing a demo soon.</p>
<h3>Refactoring (warning, serious programmer-speak ahead)</h3>
<p>In the last couple weeks, I&#8217;ve refactored a good chunk of the code to accomodate some ideas I&#8217;ve been exposed to &#8211; the benefits of <a href="http://en.wikipedia.org/wiki/Dependency_injection">dependency injection</a> and <a href="http://martinfowler.com/articles/injection.html#ServiceLocatorVsDependencyInjection">service locators</a>.  These  two patterns may seem to be at odds, but I think each has benefits in different circumstances.  By focusing on using DI as much as possible without major inconvenience, I have increased the logic and readability of my code.  By falling back on a service locator to avoid bending over backwards to be 100% DI, I&#8217;ve kept the code clear and the configuration centralized.  The result is, the code is a lot better organized and easier to work with.</p>
<p>I&#8217;ve also decided to abstract the platform.  Initially I didn&#8217;t bother, since Actionscript is so intertwined with Flash/Flex, and I&#8217;m only targeting one platform, but I think abstraction is worth it for two reasons: logical code separation and future portability.  The basics like Math functions I&#8217;m leaving in place, but I&#8217;m wrapping input devices, graphical objects, and certain platform-specific functionality like event handling.  It makes the code a lot clearer to have most of the obscure Flash specifics in one place, and it will be that much easier to port the code if it&#8217;s ever needed.  Also, it brings a great feeling of inner peace to look at code and not see a single reference to MovieClip.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jetpackhq.com/blog/2009/06/23/progress-update/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Writing a preloader in ActionScript 3</title>
		<link>http://www.jetpackhq.com/blog/2008/03/25/writing-a-preloader-in-actionscript-3/</link>
		<comments>http://www.jetpackhq.com/blog/2008/03/25/writing-a-preloader-in-actionscript-3/#comments</comments>
		<pubDate>Tue, 25 Mar 2008 14:49:25 +0000</pubDate>
		<dc:creator>Adam</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.jetpackhq.com/blog/2008/03/25/writing-a-preloader-in-actionscript-3/</guid>
		<description><![CDATA[Note: This is a pretty technical post, if you&#8217;re not a programmer you will probably not be interested!
A preloader gives the user something to look at while the rest of your program loads.  This is one of the nice things about SWF&#8217;s, they are capable of streaming &#8211; showing part of their content before [...]]]></description>
			<content:encoded><![CDATA[<p>Note: This is a pretty technical post, if you&#8217;re not a programmer you will probably not be interested!</p>
<p>A preloader gives the user something to look at while the rest of your program loads.  This is one of the nice things about SWF&#8217;s, they are capable of streaming &#8211; showing part of their content before fully downloaded.  The way you do this is by putting all the content to be loaded later on a later frame of the SWF timeline.  This does get a little complicated, because ideally you should preload not just your data, but your code as well.  Any classes you don&#8217;t need for the preloader should be placed on a later frame along with any library assets.</p>
<p>This is where a big bug in ActionScript 3 shows up &#8211; the &#8220;Export classes in frame&#8221; setting appears to be badly broken, as <a href="http://www.actionscript.org/forums/showthread.php3?t=149468">discussed on actionscript.org</a>.  As you can tell, Adobe&#8217;s error is making some professionals desperate to find a workaround.  Well, thanks to others in the ActionScript community, I&#8217;ve finally discovered the workaround.  Unfortunately it involves abandoning Flash in favor of Flex.  But, this isn&#8217;t as bad as it may sound.  While I detest the Eclipse-based Flex Builder IDE, I discovered a fantastic (and <strong>free</strong>) tool called <a href="http://osflash.org/flashdevelop">FlashDevelop</a> that is a superior development environment to Flex Builder or Flash, and offers easier customization while lacking just a little polish (for one thing, syntax highlighting must be edited via XML file).  FlashDevelop uses the command-line SWF compiler mxmlc that comes in the new (also free) <a href="http://opensource.adobe.com/wiki/display/flexsdk/Flex+SDK">Flex 3 SDK</a>.</p>
<p>Actually since Adobe has all these nebulous products floating around that all pretty much do the same thing (Flash, Flex, Air, who knows what else), it&#8217;s a little confusing what language you are using for your source files.  It&#8217;s ActionScript but it&#8217;s the Flex brand of ActionScript, which is a few tweaks different from Flash ActionScript.  They could just merge all these tweaks into a single language and let you choose which features you want to use, but I imagine like in many other things computer, there&#8217;s less money in making things simple.  Anyway, basically in Flex-ActionScript, you can embed all your library assets via source code, rather than via an IDE.  Although the way you do this is a little awkward, I find it highly preferable.  And you can still use advanced layouts and components by just <a href="http://www.flashdevelop.org/community/viewtopic.php?t=2392">including them via SWC</a></p>
<p>Once you get your project converted to Flex, here is the fix: instead of monkeying around with the timeline, set your preloader as your primary build class, and use the <a href="http://livedocs.adobe.com/flex/201/html/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Book_Parts&amp;file=compilers_123_24.html#157203">command-line option</a> &#8220;-frame&#8221; to put your main program on frame 2 (placing the line [Frame(extraClass="Main")] in your preloader appears to be equivalent).  Thanks to <a href="http://www.nulldesign.de/2007/11/30/as3-preloading-continued/">Lars Gerckens</a> for his research, and <a href="http://www.bit-101.com/blog/?p=946">BIT-101 for this alternate solution</a>.  And of course thanks to Adobe for providing such horrendously incomplete documentation that things like this have to be discovered through much trial and error.  I can&#8217;t fault them too much though, since they are at least finally strangling the abomination that was Macromedia&#8217;s ActionScript 2.</p>
<p>After your preloading is done, you have to start the main class &#8211; but you can&#8217;t reference it because then Flex will include it, and all the classes it uses, along with the preloader on frame 1.  Here&#8217;s how you instantiate it without referencing it (&#8216;Main&#8217; is the name of the main class):</p>
<p><code><br />
nextFrame();	// goto Main frame<br />
var classdef:Class = getDefinitionByName("Main") as Class;<br />
var main:DisplayObject = new classdef();	// runs itself<br />
</code></p>
<p>Now there&#8217;s another problem &#8211; your Main class won&#8217;t have a stage object until after you call addChild(main) &#8211; but how does Preloader tell Main to initialize after adding it, when Preloader doesn&#8217;t know what class Main is?  The way I do it is by storing the stage in a global variable, then letting main add itself to the stage in the constructor.  I use a class called Config that contains static variables for build type, debug mode, stage, and a few other globals.  Generally globals are a bad thing, but in certain cases like this the time they save is worth it.</p>
<p>If you find any caveats or improvements, let me know!</p>
<p>=======================</p>
<p>One problem still exists: when loading this in a web browser, loaderInfo.bytesLoaded seems to only reflect the first frame.  We need to know the total bytes for the entire SWF to accurately show load progress.   From looking at the source code to mx.preloaders.DownloadProgressBar, Adobe&#8217;s own code actually has to guess at the size of the SWF it&#8217;s loading.  Weak.  So no &#8220;percentage loaded&#8221; indicator is going to be accurate unless you explicitly provide it with the estimated size of your SWF.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jetpackhq.com/blog/2008/03/25/writing-a-preloader-in-actionscript-3/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Theft Prevention</title>
		<link>http://www.jetpackhq.com/blog/2008/02/21/theft-prevention/</link>
		<comments>http://www.jetpackhq.com/blog/2008/02/21/theft-prevention/#comments</comments>
		<pubDate>Thu, 21 Feb 2008 15:20:35 +0000</pubDate>
		<dc:creator>Adam</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.jetpackhq.com/blog/2008/02/21/theft-prevention/</guid>
		<description><![CDATA[One of the biggest challenges Flash developers must face is just how easy it is for people to steal your source code.  SWF files include basically your complete source code, sure there are no comments included, but good programming is self documenting.  Unfortunately all your variable &#038; function names are kept intact.  [...]]]></description>
			<content:encoded><![CDATA[<p>One of the biggest challenges Flash developers must face is just how easy it is for people to steal your source code.  SWF files include basically your complete source code, sure there are no comments included, but good programming is self documenting.  Unfortunately all your variable &#038; function names are kept intact.  This means that any schmo could come along and get the complete source code to Jetpack, and create their own version from my hard work.  This isn&#8217;t simple software piracy, it&#8217;s closer to actual theft, where someone else is profiting from your work.  Even if the hacked game is not sold, there is revenue from ads, or just increased site traffic.  A copyright helps, but still there are many examples of flash games being reskinned, and published as original works.</p>
<p>This is why I haven&#8217;t released any flash demos yet, I&#8217;m trying to find a resolution to this problem before releasing a simple demo that contains my entire source code.  There are tools out there to encrypt ActionScript, but none of them work with ActionScript 3 yet &#8211; and from what I understand, a separate tool is needed to obscure variable names, a feature that is very important to protecting code.</p>
<p>Maybe this issue is why there are very few large games created for Flash?  Still, I intend to continue on this path, at least for this game.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jetpackhq.com/blog/2008/02/21/theft-prevention/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
	</channel>
</rss>
