<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.3.3" -->
<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/"
	>

<channel>
	<title>Craftymind</title>
	<link>http://www.craftymind.com</link>
	<description>Hacking away at UI development</description>
	<pubDate>Tue, 25 Aug 2009 14:22:50 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.3.3</generator>
	<language>en</language>
			<item>
		<title>Come see my talk about memory management at Max 2009</title>
		<link>http://www.craftymind.com/2009/08/25/come-see-my-talk-about-memory-management-at-max-2009/</link>
		<comments>http://www.craftymind.com/2009/08/25/come-see-my-talk-about-memory-management-at-max-2009/#comments</comments>
		<pubDate>Tue, 25 Aug 2009 14:22:50 +0000</pubDate>
		<dc:creator>Sean Christmann</dc:creator>
		
		<category><![CDATA[AIR]]></category>

		<category><![CDATA[Flash]]></category>

		<guid isPermaLink="false">http://www.craftymind.com/2009/08/25/come-see-my-talk-about-memory-management-at-max-2009/</guid>
		<description><![CDATA[It seems my obsession with the Flash and AIR internals keeps earning me a spot as a Max speaker. Following up on last years talk on general VM performance, I&#8217;ll be back this year to talk specifically about memory management and optimizations. While I covered memory a bit in last years talk, this year I&#8217;ll [...]]]></description>
			<content:encoded><![CDATA[<p>It seems my <a href="http://www.craftymind.com/2008/04/18/updated-elastic-racetrack-for-flash-9-and-avm2/">obsession with the Flash and AIR internals</a> keeps earning me a spot as a Max speaker. Following up on last years <a href="http://www.craftymind.com/2008/11/20/max-2008-session-material/">talk on general VM performance</a>, I&#8217;ll be back this year to talk specifically about memory management and optimizations. While I covered memory a bit in last years talk, this year I&#8217;ll be going more indepth on memory techniques as well as how to profile your apps. As with all my sessions, you can be sure there&#8217;ll be plenty of code handed out by the end.</p>
<p>My session will be running on Tuesday at 1:30 PM and again on Wednesday at 5:00 PM, hope to see you all there.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.craftymind.com/2009/08/25/come-see-my-talk-about-memory-management-at-max-2009/feed/</wfw:commentRss>
		</item>
		<item>
		<title>360iDev session materials on Quartz 2D</title>
		<link>http://www.craftymind.com/2009/03/04/360idev-session-materials-on-quartz-2d/</link>
		<comments>http://www.craftymind.com/2009/03/04/360idev-session-materials-on-quartz-2d/#comments</comments>
		<pubDate>Wed, 04 Mar 2009 16:51:45 +0000</pubDate>
		<dc:creator>Sean Christmann</dc:creator>
		
		<category><![CDATA[Cocoa]]></category>

		<guid isPermaLink="false">http://www.craftymind.com/2009/03/04/360idev-session-materials-on-quartz-2d/</guid>
		<description><![CDATA[360iDev San Jose has been awesome so far and it&#8217;s not over yet, still a whole day of sessions to go. I&#8217;m putting my session materials up now during the keynote so I don&#8217;t forget after I&#8217;ve presented. Get the zip file here.
Update: I forgot to mention during my presentation, but the samples within the [...]]]></description>
			<content:encoded><![CDATA[<p>360iDev San Jose has been awesome so far and it&#8217;s not over yet, still a whole day of sessions to go. I&#8217;m putting my session materials up now during the keynote so I don&#8217;t forget after I&#8217;ve presented. Get the zip file <a href="http://www.craftymind.com/wp-content/uploads/2009/360iDev%20session%20materials.zip" title="360 iDev session materials">here</a>.</p>
<p>Update: I forgot to mention during my presentation, but the samples within the zip archive may contain memory leaks for the sake of code brevity. If you copy and paste the code samples into your own projects, you might need to make sure you add cleanup code to the end of it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.craftymind.com/2009/03/04/360idev-session-materials-on-quartz-2d/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Creating the &#8216;loupe&#8217; or magnifying glass effect on the iphone.</title>
		<link>http://www.craftymind.com/2009/02/10/creating-the-loupe-or-magnifying-glass-effect-on-the-iphone/</link>
		<comments>http://www.craftymind.com/2009/02/10/creating-the-loupe-or-magnifying-glass-effect-on-the-iphone/#comments</comments>
		<pubDate>Tue, 10 Feb 2009 18:06:57 +0000</pubDate>
		<dc:creator>Sean Christmann</dc:creator>
		
		<category><![CDATA[Cocoa]]></category>

		<guid isPermaLink="false">http://www.craftymind.com/2009/02/10/creating-the-loupe-or-magnifying-glass-effect-on-the-iphone/</guid>
		<description><![CDATA[One of my recent projects tasked me with figuring out how to recreate the magnifying glass effect that Apple uses inside textfields on the iPhone, but in a more generic way so anything on the screen could be magnified. Getting this effect is pretty simple in any visual framework once you figure out how masking [...]]]></description>
			<content:encoded><![CDATA[<p>One of my recent projects tasked me with figuring out how to recreate the magnifying glass effect that Apple uses inside textfields on the iPhone, but in a more generic way so anything on the screen could be magnified. Getting this effect is pretty simple in any visual framework once you figure out how masking works and which api will let you draw a bitmap of a given graphics layer. While the logic was simple enough, finding the right combination of apis was the painful part but I finally figured it out and wanted to share the code with everyone else trying to accomplish this task.</p>
<p>First up an example of what we&#8217;re able to accomplish with this effect.</p>
<p style="text-align: center"><img src="http://www.craftymind.com/wp-content/uploads/2009/02/loupeexample.png" alt="Magnifying effect on iPhone" /></p>
<p>You can magnify any UIView as well as the children of that view, images, text and 2d vectors are captured and magnified appropriately. There are couple critical pieces of this code to pay attention to.</p>
<p>First up, when a touch has been recorded long enough to kick off the magnifier effect, we create a new magnifier view that is the exact size of the view we want to magnify. This is important due to the way we&#8217;re going to be copying a bitmap of the original view. Once we know the view exists we call setNeedsDisplay on it which triggers drawRect inside of it.</p>
<pre>if(loop == nil){
	loop = [[MagnifierView alloc] initWithFrame:self.bounds];
	loop.viewref = self;
	[self addSubview:loop];
}
UITouch *touch = [touches anyObject];
loop.touchPoint = [touch locationInView:self];
[loop setNeedsDisplay];</pre>
<p>Next, when drawRect gets called inside the magnifier view we want to make a copy of the original view first. The reason the magnifier view is teh same size as the original view is because we are rendering the full context of the original view into our new context before grabbing a bitmap of it. If the magnifying view were smaller, the rendered bitmap would also be smaller. We want to cache the final bitmap so we&#8217;re not redrawing the original view every time the user moves their finger around the view. We&#8217;ll destroy that cached view and the magnifying glass when the user lets up off the screen.</p>
<pre>- (void)drawRect:(CGRect)rect {
	if(cachedImage == nil){
		UIGraphicsBeginImageContext(self.bounds.size);
		[self.viewref.layer renderInContext:UIGraphicsGetCurrentContext()];
		cachedImage = [UIGraphicsGetImageFromCurrentImageContext() retain];
		UIGraphicsEndImageContext();
	}</pre>
<p>Following that we need to generate a masked view for the magnified view to sit in, since the loop is a circle we have to mask out the corners and antialias the outer perimeter. This is accomplished using 2 images, the magnifying glass itself and a mask image with appropriate grayscale levels for masking.</p>
<pre>CGImageRef imageRef = [cachedImage CGImage];
CGImageRef maskRef = [[UIImage imageNamed:@"loopmask.png"] CGImage];
CGImageRef overlay = [[UIImage imageNamed:@"loop.png"] CGImage];
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
					CGImageGetHeight(maskRef),
					CGImageGetBitsPerComponent(maskRef),
					CGImageGetBitsPerPixel(maskRef),
                                        CGImageGetBytesPerRow(maskRef),
					CGImageGetDataProvider(maskRef),
					NULL,
					true);
//Create Mask
CGImageRef subImage = CGImageCreateWithImageInRect(imageRef, CGRectMake(touchPoint.x-18, touchPoint.y-18, 36, 36));
CGImageRef xMaskedImage = CGImageCreateWithMask(subImage, mask);</pre>
<p>Lastly, we&#8217;ll draw the magnifying glass and magnfied bitmap copy of our orginal view underneath the mask and we&#8217;re done. Since the iPhone uses a different coordinate system then other languages, we have to remember to flip the view upside down before drawing it.</p>
<pre>CGContextRef context = UIGraphicsGetCurrentContext();
CGAffineTransform xform = CGAffineTransformMake(
					1.0,  0.0,
					0.0, -1.0,
					0.0,  0.0);
CGContextConcatCTM(context, xform);
CGRect area = CGRectMake(touchPoint.x-42, -touchPoint.y, 85, 85);
CGRect area2 = CGRectMake(touchPoint.x-40, -touchPoint.y+2, 80, 80);
CGContextDrawImage(context, area2, xMaskedImage);
CGContextDrawImage(context, area, overlay);</pre>
<p>And that&#8217;s it, now we have a modular magnifying glass that can plug in to any UIView with minimal effort. If you&#8217;re looking for a way to add interactivity underneath the magnifying glass, like moving the cursor within a textfield, that&#8217;s gonna require a bit more custom code on the control you&#8217;re dealing with, and this example doesn&#8217;t really address that.</p>
<p>Download example: <a href="http://www.craftymind.com/wp-content/uploads/2009/02/masktest.zip" title="XCode magnifier example for iPhone">XCode magnifier example for iPhone</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.craftymind.com/2009/02/10/creating-the-loupe-or-magnifying-glass-effect-on-the-iphone/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Max 2008 session material</title>
		<link>http://www.craftymind.com/2008/11/20/max-2008-session-material/</link>
		<comments>http://www.craftymind.com/2008/11/20/max-2008-session-material/#comments</comments>
		<pubDate>Thu, 20 Nov 2008 20:29:45 +0000</pubDate>
		<dc:creator>Sean Christmann</dc:creator>
		
		<category><![CDATA[AIR]]></category>

		<category><![CDATA[Flash]]></category>

		<category><![CDATA[Flex]]></category>

		<guid isPermaLink="false">http://www.craftymind.com/2008/11/20/max-2008-session-material/</guid>
		<description><![CDATA[As promised, here&#8217;s the pdf of my recent Max 2008 session &#8220;Optimizing Adobe AIR for Code Execution, Memory, and Rendering&#8220;. There&#8217;s a good amount of Flash VM tips and tricks in there for reference whether you&#8217;re working in the browser or AIR. Thanks to everyone who attended and gave me high marks for my session. [...]]]></description>
			<content:encoded><![CDATA[<p>As promised, here&#8217;s the pdf of my recent Max 2008 session &#8220;<a href="http://www.craftymind.com/wp-content/uploads/2008/11/sean_christmann_optimizing_air_final.pdf">Optimizing Adobe AIR for Code Execution, Memory, and Rendering</a>&#8220;. There&#8217;s a good amount of Flash VM tips and tricks in there for reference whether you&#8217;re working in the browser or AIR. Thanks to everyone who attended and gave me high marks for my session. I guess I have to start thinking about what to talk about next year. For anyone who didn&#8217;t get to see the session live, the pdf really only tells half the story, so you may want to check out the session when it shows up on <a href="http://tv.adobe.com">http://tv.adobe.com</a> soon.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.craftymind.com/2008/11/20/max-2008-session-material/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Web app to extract torrent files out of Blizzard Downloader</title>
		<link>http://www.craftymind.com/2008/06/28/web-app-to-extract-torrent-files-out-of-blizzard-downloader/</link>
		<comments>http://www.craftymind.com/2008/06/28/web-app-to-extract-torrent-files-out-of-blizzard-downloader/#comments</comments>
		<pubDate>Sat, 28 Jun 2008 23:54:40 +0000</pubDate>
		<dc:creator>Sean Christmann</dc:creator>
		
		<category><![CDATA[Flex]]></category>

		<guid isPermaLink="false">http://www.craftymind.com/2008/06/28/web-app-to-extract-torrent-files-out-of-blizzard-downloader/</guid>
		<description><![CDATA[Diablo 3 was announced today and like many thousands of other gamers online right now I&#8217;m trying to download the 800mb high def gameplay trailer while putting up with the very clumsy Blizzard Downloader application. For those who don&#8217;t know, the Blizzard Downloader is just a mini BitTorrent client with a single torrent file baked [...]]]></description>
			<content:encoded><![CDATA[<p>Diablo 3 was announced today and like many thousands of other gamers online right now I&#8217;m trying to download the 800mb high def gameplay trailer while putting up with the very clumsy Blizzard Downloader application. For those who don&#8217;t know, the Blizzard Downloader is just a mini BitTorrent client with a single torrent file baked in. I&#8217;m not a big fan of the downloader because I already have a BitTorrent client that&#8217;s much better at bandwidth allocation and my firewall&#8217;s already set up for that client. I&#8217;d much rather download the movie with my own client instead of Blizzards so I&#8217;ve written a little flash app to help facilitate that.</p>
<p>To use this, just point the app at the url of any Blizzard Downloader exe file online (I&#8217;m not sure if it&#8217;ll work with the .dmg files) and hit the &#8216;Extract&#8217; button. A link will pop up below that you can click to save the torrent file. The file has no name by default so you&#8217;ll have to rename it &#8216;whatever.torrent&#8217; after it finishes downloading. The resulting torrent will still connect to Blizzards tracker and you&#8217;ll download the same file you would be if you were using the Blizzard Downloader app.</p>
<p>This should work with all browsers other then IE 7 and below, since IE doesn&#8217;t support the data:URI scheme to create dynamic files.</p>
<p style="text-align: center"><iframe src="http://www.craftymind.com/factory/BlizzardDownloader/main.html" style="width: 500px; height: 300px"></iframe><br />
<a href="http://www.craftymind.com/factory/BlizzardDownloader/srcview/">View Source</a></p>
<p>Example URLs:<br />
<a href="http://us.media.blizzard.com/1901200114/_video/downloaders/gameplaytrailer/Diablo3-gameplaytrailer_en-US-downloader.exe">Diablo 3 Gameplay Downloader</a><br />
<a href="http://www.starcraft2.com/movies/gameplay_video/1280_StarCraft2GameplayVideo_EnglishUS2-avi-downloader.exe">Starcraft 2 Gameplay Downloader</a></p>
<p>More Info:<br />
<a href="http://www.wowwiki.com/Blizzard_Downloader">Blizzard Downloader Wiki</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.craftymind.com/2008/06/28/web-app-to-extract-torrent-files-out-of-blizzard-downloader/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Introducing GUIMark - An RIA benchmark for Flex, Silverlight, HTML and more</title>
		<link>http://www.craftymind.com/2008/05/22/introducing-guimark-an-ria-benchmark-for-flex-silverlight-html-and-more/</link>
		<comments>http://www.craftymind.com/2008/05/22/introducing-guimark-an-ria-benchmark-for-flex-silverlight-html-and-more/#comments</comments>
		<pubDate>Thu, 22 May 2008 16:04:14 +0000</pubDate>
		<dc:creator>Sean Christmann</dc:creator>
		
		<category><![CDATA[Flash]]></category>

		<category><![CDATA[Flex]]></category>

		<category><![CDATA[Html]]></category>

		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://www.craftymind.com/2008/05/22/introducing-guimark-an-ria-benchmark-for-flex-silverlight-html-and-more/</guid>
		<description><![CDATA[If you&#8217;re wondering why I&#8217;ve been quiet the past few weeks it&#8217;s because I&#8217;ve been devoting most of my free time to finishing off a new benchmark I&#8217;m releasing today called GUIMark. GUIMark is kinda like an Acid3 test on speed that&#8217;s geared towards RIA technologies. The goal was to figure out how to implement [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re wondering why I&#8217;ve been quiet the past few weeks it&#8217;s because I&#8217;ve been devoting most of my free time to finishing off a new benchmark I&#8217;m releasing today called <a href="http://www.craftymind.com/guimark">GUIMark</a>. GUIMark is kinda like an <a href="http://acid3.acidtests.org/">Acid3 test</a> on speed that&#8217;s geared towards RIA technologies. The goal was to figure out how to implement a reference design in different runtimes and then benchmark how smoothly that design could be animated. So far I have implementations in DHTML, Flex, Java, Silverlight 1 and Silverlight 2. All the results and and implementation details can be found under the <a href="http://www.craftymind.com/guimark">GUIMark page</a>.</p>
<p>GUIMark shares alot in common with another RIA benchmark <a href="http://www.bubblemark.com/">Bubblemark</a>. I&#8217;ve <a href="http://www.craftymind.com/2008/04/11/why-bubblemark-is-a-poor-ui-benchmark/">written a bit</a> about Bubblemark and why I think an alternative is necessary, but I do believe Bubblemark and GUIMark can coexist while serving 2 different purposes. Alexey Gavrilov <a href="http://metalinkltd.com/?p=170">stated it best</a> in that he sees Bubblemark as a sortof &#8216;Hello World&#8217; launchpad into comparing different environments and I agree with him. Bubblemark is a *very* accessible test suite and its easy for any kind of developer to jump in and play around with performance techniques. GUIMark takes a different approach by trying to benchmark the types of UI elements common in our Web 2.0 world. This includes things like vector redraws, alpha transparencies, text reflow, bitmap motion, and 9 scale slicing rules. From there I just fill up the render pipeline until it becomes so over-saturated that it becomes easy to visually distinguish which rendering engines are more efficient then others. As a result, the benchmark is more complicated on a visual level and requires a bit more time then Bubblemark to understand the implementation rules. Lastly with GUIMark I&#8217;ve tried to get into some of the lower level details behind <a href="http://craftymind.com/guimark-inside">how rendering engines work</a> and how that&#8217;s affected the creation of this project.</p>
<p>I&#8217;m hoping that developers and designers will be able to use this test suite to identify any pros or cons to choosing a particular environment when visual transitions are a key element of the experience. I&#8217;m also hoping these benchmarks provide a spotlight for the community that we can turn toward the runtime engineers inside Sun or Adobe or Mozilla to demand better performance.</p>
<p><a href="http://www.craftymind.com/guimark">Go to GUIMark home page</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.craftymind.com/2008/05/22/introducing-guimark-an-ria-benchmark-for-flex-silverlight-html-and-more/feed/</wfw:commentRss>
		</item>
		<item>
		<title>From AS3 to Objective-C: Flex vs iPhone development</title>
		<link>http://www.craftymind.com/2008/04/30/from-as3-to-objective-c-flex-vs-iphone-development/</link>
		<comments>http://www.craftymind.com/2008/04/30/from-as3-to-objective-c-flex-vs-iphone-development/#comments</comments>
		<pubDate>Wed, 30 Apr 2008 16:44:54 +0000</pubDate>
		<dc:creator>Sean Christmann</dc:creator>
		
		<category><![CDATA[Cocoa]]></category>

		<category><![CDATA[Flash]]></category>

		<guid isPermaLink="false">http://www.craftymind.com/2008/04/30/from-as3-to-objective-c-flex-vs-iphone-development/</guid>
		<description><![CDATA[Recently I&#8217;ve been given the opportunity to work full time on commercial iPhone development at EffectiveUI. The most intriguing thing about the platform for me is having access to non traditional user input mechanisms. When I was playing around with Wii remote integration on the desktop, the potential was exciting, but the ubiquity was limiting. [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I&#8217;ve been given the opportunity to work full time on commercial iPhone development at <a href="http://effectiveui.com">EffectiveUI</a>. The most intriguing thing about the platform for me is having access to non traditional user input mechanisms. When I was playing around with Wii remote integration on the desktop, the potential was exciting, but the ubiquity was limiting. In the same way that pc game companies develop for the keyboard and mouse first and then provide hooks for joysticks after the fact, I knew that serious Wii remote integration in a desktop app was limited. Knowing that I can write software for the iPhone that always has access to multitouch and accelerometer data from the outset really allows for unique gestures as a first class citizen within an app.</p>
<p>After working with some code and spending time with the SDK itself, I couldn&#8217;t help but naturally compare UI development on the iPhone with GUI frameworks like Flex or Swing, heres the things that stand out so far.</p>
<ol>
<li>I&#8217;m really spoiled by higher level languages. A good high level language like ECMAScript, Ruby, or Java rides the fine line of &#8220;Making things as simple as possible, but no simpler&#8221;. I&#8217;ve never felt constrained by the language features in these technologies, only by the apis exposed. Stepping *back* into Objective-C certainly provides more power and flexibility in the language, but there&#8217;s a loss in productivity for me that I just can&#8217;t shake. Some of this loss comes from Objective-C&#8217;s design itself, and some of it just comes from XCodes introspection ability. For instance, I&#8217;m not sure if I&#8217;ll ever get to the point where I can read these lines of Objective-C as effeciently as their ActionScript counterparts would probably look.
<pre>NSString *aString = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];</pre>
</li>
<li>Closed source UI frameworks suck. Most of what I learned about custom UI development in Flex I learned by inspecting the source code for the bundled controls. Ripping open Containers to see how layout rules are determined, or Lists to see how delegates are passed around, or the Image control to see how different display types are handled provides invaluable gems about implementing Flash apis. It has also helped me optimize the interactions of an app knowing the intentions of the developer who created the UI controls. With the iPhone SDK, you&#8217;re given documentation for the visual components, but no source to help determine how they work.</li>
<li>Core graphics and animation is really strong. Between Quartz and the OpenGL layer there&#8217;s alot of potential for getting easy access to some of the more complex visual hacks. Although I think 3D user interfaces are prone to usability issues, the iPhone is a much better device to explore them on then a standard keyboard and mouse interface.</li>
<li>Data binding, event listeners, and mxml. The Flash Player and Flex model provide features on top of the ActionScript language that arguably optimize UI needs and keep development more declarative. Cocoa development could really benefit from a &#8216;gui compiler&#8217; that takes Objective-C to a higher level and bakes in features that support common ui design patterns.</li>
<li>Garbage Collection. Objective-C 2.0 provides a unique system that lets you create objects that will be automatically garbage collected, or you can continue to manually manage object allocation/deallocation yourself. The concept sounds cool, but I can imagine allowing both systems to be mixed within the same project is just begging for trouble.</li>
</ol>
<p>So far I think that Objective-C has alot of power and some really awesome features that outclass GUI features in Flash, but compared to Flex development as a whole, I&#8217;d have to say that XCode and the included visual frameworks are not as sophisticated.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.craftymind.com/2008/04/30/from-as3-to-objective-c-flex-vs-iphone-development/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Updated &#8216;Elastic Racetrack&#8217; for Flash 9 and AVM2</title>
		<link>http://www.craftymind.com/2008/04/18/updated-elastic-racetrack-for-flash-9-and-avm2/</link>
		<comments>http://www.craftymind.com/2008/04/18/updated-elastic-racetrack-for-flash-9-and-avm2/#comments</comments>
		<pubDate>Fri, 18 Apr 2008 16:01:02 +0000</pubDate>
		<dc:creator>Sean Christmann</dc:creator>
		
		<category><![CDATA[Flash]]></category>

		<category><![CDATA[avm2]]></category>

		<category><![CDATA[elastic racetrack]]></category>

		<category><![CDATA[flash framerate]]></category>

		<category><![CDATA[flash internals]]></category>

		<guid isPermaLink="false">http://www.craftymind.com/2008/04/18/updated-elastic-racetrack-for-flash-9-and-avm2/</guid>
		<description><![CDATA[In 2005 Ted Patrick posted a great article on the frame execution model inside the Flash Player that he dubbed the &#8216;elastic racetrack&#8216;. It&#8217;s served as a great reference for me over the years to help understand how code execution and rendering were balanced within the processing of a frame. Since the introduction of Flash [...]]]></description>
			<content:encoded><![CDATA[<p>In 2005 Ted Patrick posted a great article on the frame execution model inside the Flash Player that he dubbed the &#8216;<a href="http://www.onflex.org/ted/2005/07/flash-player-mental-model-elastic.php" title="Flash Elastic Racetrack">elastic racetrack</a>&#8216;. It&#8217;s served as a great reference for me over the years to help understand how code execution and rendering were balanced within the processing of a frame. Since the introduction of Flash Player 9 and the new AVM2, I&#8217;ve noticed a few changes to the elastic racetrack model and thought I&#8217;d share them. This information is based on research into Flash player internals as well as observations I&#8217;ve made playing around with the event and rendering model, but the full model hasn&#8217;t been confirmed by Adobe engineers.</p>
<p>The basic premise of the original elastic racetrack is still the same. Given a specific frame rate to operate on, the Flash player will devote the first segment of the frame to execute code, and the second segment to render display objects. Either segment can grow its part of the racetrack to accommodate more processing and effectively extend the duration of the frame.</p>
<p style="text-align: center"><img src="http://www.craftymind.com/wp-content/uploads/2008/04/elasticracetrackexport.png" alt="Flash Player Elastic Racetrack" /></p>
<p>What changes from the previous model is how those segments look under a microscope and how they come together to form a &#8216;frame&#8217;.</p>
<p>AVM2 is controlled by what I&#8217;m going to call the Marshal. The Marshal is responsible for carving out time slices for the Flash Player to operate on. Its important to clarify up front that these time slices are not the same thing as the framerate compiled into a swf, but we&#8217;ll see below how the player ultimately synthesizes a framerate from these slices. Running a Flex compiled swf within Firefox under Mac OS X, the Marshal appears to be carving out 19-20 millisecond slices, but this can be different between platforms and browsers based on what I&#8217;ve observed as well as Adobe employees have <a href="http://www.jamesward.org/wordpress/2008/04/10/bursting-bubbles/">hinted at</a>. This can also change depending on how the swf was compiled, see some of the comments below. For the sake of the article lets assume we&#8217;re only talking about a 20 millisecond slice to make the math easy. This means the Marshal will attempt to generate and execute no more then 50 slices each second, and it may be less depending on the elasticity of code execution or rendering. Inside each slice, 5 possible steps are processed in the following order.</p>
<ol>
<li>Player events are dispatched - This includes events dispatched by the Timer, Mouse, ENTER_FRAMEs, URLLoader, etc&#8230;</li>
<li>User code is executed - Any code listening to events dispatched by step 1 are executed at this stage.</li>
<li>RENDER event is dispatched - This special event is dispatched when the user calls stage.invalidate() during normal user code operation.</li>
<li>Final user code is executed - User code listening specifically for step 3 is executed at this point.</li>
<li>Player renders changes to the display list.</li>
</ol>
<p style="text-align: center"><img src="http://www.craftymind.com/wp-content/uploads/2008/04/marshalledsliceexport.png" alt="AVM2 Marshalled Slice" /></p>
<p>The Marshal executes this 20 millisecond slice over and over and decides on the fly which actions to run. The exact actions processed within a slice will ultimately derive the 2 main racetrack segments (code execution and rendering) that constitute a &#8216;frame&#8217;. User actions and Invalidation actions fill up the code segment track, while Render actions fill up the render segment track. Its important to note that actions will only occur at times predetermined by the Marshal, so a if you have a short running User action, the Marshal will still wait a few milliseconds before moving on to the Invalidate and Render actions.</p>
<p>The best way to illustrate which actions are run and how the elastic racetrack is created, is to look at how those slices are processed on a swf running at 5 fps, 25, fps, and 50 fps.</p>
<p style="margin: auto; overflow: scroll; width: 650px"> <img src="http://www.craftymind.com/wp-content/uploads/2008/04/framemarshalingexport.png" alt="Flash Frame Marshaling Diagram" /></p>
<p>As you can see, the elastic racetrack performs different actions per frame and requires a different visual illustration depending on the framerate that the player is trying to synthesize. So for a swf running at 5 fps, each frame processed 10 User actions, 1 Invalidation action, and 1 Render action. At 25 fps, each frame processed 2 User actions, 1 Invalidation action, and 1 Render action. At 50 fps, each frame processed 1 User action, 1 Invalidation action, and 1 Render action. Whats important to note in the above chart is that some events are only available in certain slices. For instance, the Event.ENTER_FRAME event will only ever be dispatched in a slice that occurs at the start of a frame.</p>
<p>So what does this all mean? Theres a couple quick ideas to take away from this.</p>
<ol>
<li>Long running code execution or render segments can extend a given slice beyond 20 milliseconds. Elasticity will be applied to that particular slice and the duration of the frame may or may not be extended as a result. The Marshal may drop the number of slices that constitute a frame in order to keep the active framerate close to the compiled framerate.</li>
<li>A swfs <em>real</em> framerate won&#8217;t exceed the Marshals rate defined for the player instance. You can set your compiled framerate at 120fps, but Flash will still only process 50 slices max that generate 50 render calls (more or less depending on the system config).</li>
<li>Code can be executed more often then the compiled framerate. A swf compiled at 1 fps can execute a Timer or Mouse event in every slice, even though it will only render in the last slice. Additionally, if you choose, you can render to the screen sooner then the compiled framerate by calling updateAfterEvent() , but only within a Mouse, Timer, or Keyboard event handler. In this instance though, the Marshal will consider that the end of the frame and start a new frame on the next slice. Lastly, Flash will force an automatic render when mousing over any Sprite that has had its visual properties (x,y,width,height,etc..) changed, naturally this still occurs at the end of the slice and any prerender logic will still run.</li>
<li>Compiling a framerate that isn&#8217;t a multiple of the total number of slices per second for your platform will cause irregular rendering as it tries to divide up the slices. If you were to compile in a framerate of 20 on a platform executing 50 slices per second, then the player has to render 2 frames every 5 slices and would follow a 3-2-3-2-3-2 slice-to-render rate.</li>
</ol>
<p>These 4 facts are moving targets though, since for this article we&#8217;re working on a 20 millisecond slice that&#8217;s processed 50 times per second.  In reality you&#8217;ll see time slices as low as 5 milliseconds or as high at 100 milliseconds and some of the math will change as a result.</p>
<p>If you&#8217;d like to test this model for yourself, the easiest route is to create a swf running at 1 fps and another at 100 fps both with a Timer object set on a 1 millisecond interval. Inside the Timer event handler change the x property of a display object and hook a bunch of getTimer() traces up to different player events like Mouse, EnterFrame, and Render and watch the carnage unfold in your console. The rest of the information you can&#8217;t derive from the results comes from alot of context about the player I&#8217;ve learned over the past 2 years and so isn&#8217;t as easily visible. If anyone has any information to help add to or correct the above model, please submit it in the comments.</p>
<p>Thanks to several readers who have clarified some of the differences between Flex and Flash as well as how the Flash API is able to change the default behaviors described above.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.craftymind.com/2008/04/18/updated-elastic-racetrack-for-flash-9-and-avm2/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Why Bubblemark is a poor ui benchmark</title>
		<link>http://www.craftymind.com/2008/04/11/why-bubblemark-is-a-poor-ui-benchmark/</link>
		<comments>http://www.craftymind.com/2008/04/11/why-bubblemark-is-a-poor-ui-benchmark/#comments</comments>
		<pubDate>Fri, 11 Apr 2008 19:37:08 +0000</pubDate>
		<dc:creator>Sean Christmann</dc:creator>
		
		<category><![CDATA[AIR]]></category>

		<category><![CDATA[Flash]]></category>

		<category><![CDATA[Html]]></category>

		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://www.craftymind.com/2008/04/11/why-bubblemark-is-a-poor-ui-benchmark/</guid>
		<description><![CDATA[A few months ago someone on the Adobe boards asked why the Flex testcase in Bubblemark seemed to act so different in AIR versus in the browser. Yesterday, I saw the same question come up again and I figured I&#8217;d finally weigh in on the topic. The simple answer is that the test was created [...]]]></description>
			<content:encoded><![CDATA[<p>A few months ago someone on the Adobe boards asked why the Flex testcase in <a href="http://bubblemark.com/">Bubblemark</a> seemed to act so different in AIR versus in the browser. Yesterday, I saw the <a href="http://graphics-geek.blogspot.com/2008/04/off-bubblemark.html">same question come up again</a> and I figured I&#8217;d finally weigh in on the topic. The simple answer is that the test was created improperly, the complex answer has to do with the inherent limitations of the test itself.</p>
<p>First off, for those who don&#8217;t know what the Bubblemark test is, its a simple animation test case implemented in different GUI frameworks, its kinda like an Acid2 test for rendering speed. The charts should ideally give you a base number to understand how well one technology compares against another for rendering. As a GUI developer I&#8217;ve been a bit underwhelmed with the whole thing and heres why:</p>
<ol>
<li><strong>The author doesn&#8217;t understand Flash&#8217;s rendering engine.</strong> The easiest way to illustrate how incorrectly the Flash test was designed, is to download the source and change the compiled framerate to 1 fps. Re-compile and run the test and you&#8217;ll notice the benchmark framerate running at ~50 fps. You can clearly see the balls only moving once per second, yet the test thinks its flying along. This is because the testcase makes the incorrect assumptions that changing the properties of a DisplayObject causes it to render right away. The reality is, Flash holds on to all display updates till the next render pass and applies all the latest changes at once. Changing the position of an object every 5 milliseconds is meaningless when Flash is bound by a 33 millisecond render pass (or whatever you&#8217;re framerate divided by 1000 happens to be). A correct test case would rely on an ENTER_FRAME handler to change x and y values and get rid of any Timer calls.</li>
<li><strong>Framerate tests above 60 fps are meaningless. </strong>Seriously, any GUI benchmark designed to test above 60 fps is bogus. In fact, a pretty simple optimization technique for Adobe or Sun would be to cap the paint requests that get forwarded to OS X or Windows, simply because the majority of computer users these days are on LCD panels which natively run at 60 fps. Some operating systems even go a step further and limit the effective framerate of paint requests it sends to the videocard (see <a href="http://arstechnica.com/journals/apple.ars/2007/04/17/beam-synchronization-friend-or-foe">Beam Sync</a> on Mac). So when you see the Java test case fly up to 120 fps on Bubblemark, you can realistically only see 60 of those frames, and there might be a chance the other 60 are never even calculated by Javas layout engine.</li>
<li><strong>The test just moves balls around!</strong> This is my biggest beef with the benchmark because it only tests one simple aspect of the rendering engine in these technologies, which is bitmap translation. How do bitmaps moving around the screen tell you anything about the capabilities of the respective technologies? Do the <a href="http://blogs.sun.com/chrisoliver/entry/bubblemark">JavaFX</a> guys really think optimizing this usecase will make their technology relevant? The only thing Bubblemark will tell you is which runtimes might best handle bitmap particle emitters&#8230;.thats about it. Theres a lot more that goes into both the layout engine and the rendering pipeline of these different technologies and its a shame that only the most basic aspect is being tested. The funny thing is, if you open up your task manager while running the tests, you&#8217;ll notice that several of them don&#8217;t even try to run at full speed, my CPU is sitting as low as 20% in some cases. This means the runtimes don&#8217;t even consider the test difficult enough to give it full attention and have opted for using less power over faster motion.</li>
</ol>
<p>I don&#8217;t mean to cut down the developers responsible for Bubblemark because at least they came up with a simple way to help us all compare these different technologies, I just think its  a bit misguided to put any meaning behind these numbers. When evaluating your options for a GUI framework in our flashy web 2.0 world, you need to consider how well a technology can handle object scaling, alpha transparencies, rotations, text reflow, along with basic  x and y translation and dynamic redraws. Even more realistically, developers need to be aware of the limits in the 25-45 framerate region since this is where you can efficiently balance render complexity with smooth animation. I&#8217;ve uploaded a couple quick test cases in <a href="http://www.craftymind.com/test/guimark/FramerateTest.html">Flash</a>, <a href="http://www.craftymind.com/test/guimark/FramerateHtml.html">HTML</a>, and <a href="http://www.craftymind.com/test/guimark/FramerateSilverlight.html">Silverlight </a>that I think provide a good foundation for stressing a rendering engine and hopefully I&#8217;ll get a chance to expand them more into a full test suite.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.craftymind.com/2008/04/11/why-bubblemark-is-a-poor-ui-benchmark/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Kick starting the garbage collector in Actionscript 3 with AIR</title>
		<link>http://www.craftymind.com/2008/04/09/kick-starting-the-garbage-collector-in-actionscript-3-with-air/</link>
		<comments>http://www.craftymind.com/2008/04/09/kick-starting-the-garbage-collector-in-actionscript-3-with-air/#comments</comments>
		<pubDate>Wed, 09 Apr 2008 20:13:05 +0000</pubDate>
		<dc:creator>Sean Christmann</dc:creator>
		
		<category><![CDATA[AIR]]></category>

		<category><![CDATA[Flash]]></category>

		<category><![CDATA[Flex]]></category>

		<guid isPermaLink="false">http://www.craftymind.com/2008/04/09/kick-starting-the-garbage-collector-in-actionscript-3-with-air/</guid>
		<description><![CDATA[During the final months of my work with eBay Desktop, my sights were set squarely on optimization, both memory and cpu. When it came time to start messing with the garbage collector, my sanity went from bad to worse. What I originally thought was going to be a straightforward way of releasing memory in AIR [...]]]></description>
			<content:encoded><![CDATA[<p>During the final months of my work with eBay Desktop, my sights were set squarely on optimization, both memory and cpu. When it came time to start messing with the garbage collector, my sanity went from bad to worse. What I originally thought was going to be a straightforward way of releasing memory in AIR turned into a 2 month long testcase with some discouraging outcomes.</p>
<p>Memory usage in eBay Desktop was something that always lingered in the back of my mind during the entire development cycle. Because of the shifting nature of our requirements, the issue was only explored near the end, even though we knew in the beginning that memory usage had to go through valleys and peaks in a managed way while users spent time in it throughout the day. We had alerts that would open and close, we had an app that would run in the system tray, and we considered making a &#8216;lite&#8217; mode that would sit on top of your desktop all day, each of which had different memory requirements. In the beginning we used a well known <a href="http://www.gskinner.com/blog/archives/2006/08/as3_resource_ma_2.html">hack</a> to test garbage collection until part way through the development of AIR and Flex 3 Adobe finally added support for calling the garbage collector directly. We knew at this point we had a viable route for managing memory since Adobe was now making the effort to acknowledge the need. So now all that was required was a simple call to</p>
<pre>flash.system.System.gc()</pre>
<p>and we were set to go&#8230;.right?</p>
<p>Well, not exactly. First off we learned that a call to System.gc() only does a mark OR a sweep on any given object, but not both in the same call. So in order to have the effect of releasing memory back to the OS, we needed to call it twice in a row. One call to mark any dereferenced objects and sweep away old marks, and the second to now sweep away marks from the first call.</p>
<pre>flash.system.System.gc();
flash.system.System.gc();</pre>
<p>Now this seemed to be releasing memory back with pretty basic test cases, but it wasn&#8217;t working under production scenarios and we had to turn to Adobe engineers to help with the problem. What we learned was that you have to contend with 2 different kinds of pointers when working in AS3; pointers that exist in bytecode, and pointers that *may* exist in the Flash player itself that you&#8217;d never know about. What I started to realize was that the Flash player was never really engineered to be aggressive about memory usage. It was designed to plug memory leaks and manage memory plateaus, but not designed with an assumption that users would be interested in lowering those plateaus. It makes sense because most Flash content is viewed in the browser for a short amount of time before the plugin is destroyed and all memory is released when a user navigates away. With AIR, the rules changed since users are more conscience of discreet application memory usage and applications might not always need the same memory when launched vs after 2 hours of usage.</p>
<p>First up we found that the Flash player was always maintaining a reference to the last Sprite clicked, so if you destroyed an AIR window that the users had interacted with, you couldn&#8217;t get garbage collection to work until interacting with another window, which can become a big problem if you&#8217;re running in system tray mode and there are no windows to click in. Secondly we learned that you have to push any existing enterframe handler off the call stack by creating a new one. Adobe took care of the first problem, but to handle the second one we had to change our GC call a bit.</p>
<pre>private var gcCount:int;
private function startGCCycle():void{
	gcCount = 0;
	addEventListener(Event.ENTER_FRAME, doGC);
}
private function doGC(evt:Event):void{
	flash.system.System.gc();
	if(++gcCount &gt; 1){
		removeEventListener(Event.ENTER_FRAME, doGC);
	}
}</pre>
<p>Another facet we hadn&#8217;t considered was the affects of the Flex framework on garbage collection. Flex kept some of the same design philosophy as the player itself, mainly that end users were loading applications in the browser and then navigating away when done. Garbage collection was therefore considered on a micro level involving user components, but not at the framework level which could be guaranteed to exist throughout the life of the app. Adobe made strides on patching the framework to work better in discreet Windows, but ultimately some things couldn&#8217;t be changed. What we found was that CSS could not be defined in any &lt;mx:Window&gt; component. It had to be defined in the root &lt;mx:WindowedApplication&gt; which would take care of declaring CSS globally for all windows. Also we were forced to clear some global variables ourselves, which caused our code to now look like this.</p>
<pre>private var gcCount:int;
private function startGCCycle():void{
	ContainerGlobals.focusedContainer = this;
	gcCount = 0;
	addEventListener(Event.ENTER_FRAME, doGC);
}
private function doGC(evt:Event):void{
	flash.system.System.gc();
	if(++gcCount &gt; 1){
		removeEventListener(Event.ENTER_FRAME, doGC);
	}
}</pre>
<p>Lastly, not all features in AIR could be unhooked with our enterFrame trick, after another couple days of testing we found components that needed to be unhooked with Timers like the HTML component. One last tweak to our garbage collection cycle and we were home free.</p>
<pre>private var gcCount:int;
private function startGCCycle():void{
	gcCount = 0;
	addEventListener(Event.ENTER_FRAME, doGC);
}
private function doGC(evt:Event):void{
	flash.system.System.gc();
	if(++gcCount &gt; 1){
		removeEventListener(Event.ENTER_FRAME, doGC);
		setTimeout(lastGC, 40);
	}
}
private function lastGC():void{
	flash.system.System.gc();
}</pre>
<p>We were now able to successfully garbage collect any objects that have been dereferenced in Flash. We had three things we had to look out for in the app now.</p>
<ol>
<li>All display objects that added listeners on to model data had to be weakly referenced or they wouldn&#8217;t be automatically dereferenced. This is because our architecture kept model data alive while individual window stages were being destroyed. I feel like I should point out that contrary to <a href="http://gskinner.com/blog/archives/2006/07/as3_weakly_refe.html">some beliefs</a>, it is not a good idea to apply weak references by default throughout your entire app. Trust me when I say that its alot easier to debug an application with memory leaks due to strong listeners, then it is to debug an app in which users report random failures because underneath the hood weakly referenced objects are getting accidentally destroyed when the GC kicks in. You can never avoid bugs, so you should program in a way that makes them consistent to find.</li>
<li>All asynchronous events needed to be explicitly shut down. This included Timers, Loaders, File and DB transactions. Setting these to be weakly referenced is not enough as all asyncronous objects in AS3 register themselves to the Flash player while they are running. It is impossible to access objects that have been dereferenced in code but continue to be referenced by the player like a running timer.</li>
<li>No anonymous closures allowed.</li>
</ol>
<p>After all this was taken care of we began to learn that garbage collecting objects in Flash didn&#8217;t translate so easily to releasing memory back to the OS. If you ever look at the memory graph in the Flex debugger and then open up the Task Manger or Activity Monitor to compare memory usage, you&#8217;ll notice a huge disparity between the two.</p>
<p style="text-align: center"><img src="http://www.craftymind.com/wp-content/uploads/2008/04/flexmemory.png" alt="Flex Builder memory profiler" /><br />
FlexBuilder reports only 15mb of AS3 object data</p>
<p style="text-align: center"><img src="http://www.craftymind.com/wp-content/uploads/2008/04/systemmemory.png" alt="AIR system memory profile" /><br />
AIR private memory really takes up 65mb on the system</p>
<p>The difference you&#8217;re seeing is Object Memory vs. Rendering Memory and the bulk of all memory used by the Flash player goes toward rendering. Displaying an empty stage in Flash can take up anywhere between 10mb and 20mb depending on the width and height and then it climbs by roughly 4k for each display object attached to the stage. This can add up quickly when using the Flex framework where even a simple button uses several display objects.</p>
<p>What we ultimately found was that even though we could successfully release AS3 objects, we couldn&#8217;t reliably get the Flash player to release render data. So an app that started at 20mb would climb to 100mb, and when the entire stage was destroyed, we&#8217;d go back down to only 80mb. You can actually test this for yourself by downloading a sample <a href="http://www.craftymind.com/wp-content/uploads/2008/04/memoryfragmenting.zip" title="Flex 3 project showing memory fragmentation">Flex 3 project</a> and observing the effects. What I&#8217;ve learned from Adobe is that the player ends up fragmenting memory quite a bit. It probably goes back to the heart of the initial design of the Flash player I described above. All the effort was put into making a killer GUI environment that deferred memory management to whether the browser window was open or not, and as a result the memory system was not optimized for more aggressive use cases.  I can only guess the problem comes from the fact that AS3 code is attached to the timeline of the player itself, and managed by the <a href="http://www.onflex.org/ted/2005/07/flash-player-mental-model-elastic.php">elastic racetrack</a>. As a result both AS3 objects and render data get mixed in to the same memory page, and releasing just the render data doesn&#8217;t matter when model data is placed on the same page.</p>
<p>Adobe has assured me they are working on the problem but it realistically won&#8217;t make it in until after AIR 2.0, and its unclear whether those fixes will be merged into the the plugin player given that the need isn&#8217;t very high for web pages. Until then, you can not count on creating an application in AIR that releases memory back to the OS. The best approach is to reuse the smallest amount of displayobjects possible to achieve the desired workflow. Get used to adding and removing children without destroying them but instead sliding them off into a pool for later reuse, as this helps keep the memory plateau low during use.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.craftymind.com/2008/04/09/kick-starting-the-garbage-collector-in-actionscript-3-with-air/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
