<?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>blog.joa-ebert.com - Blog of Joa Ebert &#187; experiments</title>
	<atom:link href="http://blog.joa-ebert.com/category/flash/experiments/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.joa-ebert.com</link>
	<description>Actionscript3, Flash, Scala, Java, C#, C++, Algorithms &#38; Imageprocessing</description>
	<lastBuildDate>Fri, 11 Nov 2011 11:13:29 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Opening The Blackbox</title>
		<link>http://blog.joa-ebert.com/2010/10/03/opening-the-blackbox/</link>
		<comments>http://blog.joa-ebert.com/2010/10/03/opening-the-blackbox/#comments</comments>
		<pubDate>Sun, 03 Oct 2010 17:57:00 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[experiments]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[apparat]]></category>
		<category><![CDATA[avm]]></category>
		<category><![CDATA[flashplayer]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jitb]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=674</guid>
		<description><![CDATA[The Flash Player is to many of us developers a blackbox. We use it every day in our job but do not really know much about it. Of course we do not have to understand its inner workings but it is sometimes very interesting to know more a little bit about specific implementation details. A [...]]]></description>
			<content:encoded><![CDATA[<p>The Flash Player is to many of us developers a blackbox. We use it every day in our job but do not really know much about it. Of course we do not have to understand its inner workings but it is sometimes very interesting to know more a little bit about specific implementation details.</p>
<p><span id="more-674"></span></p>
<p>A part of the Flash Player is the ActionScript Virtual Machine (AVM) which is responsible for executing the code that is bundeled in your SWF file. This piece of software called <a href="http://www.mozilla.org/projects/tamarin/" target="_blank" title="Tamarin">Tamarin</a> is open source and released under the <a href="http://www.mozilla.org/projects/tamarin/faq.html#license" target="_blank" title="Tamarin License">MPL/GPL/LGPL Triple License</a>.</p>
<p>Being able to look at the heart of the Flash Player does reveal a lot to the interesting reader. However such a virtual machine is a complex piece of software and you can be lost without any guidance and will maybe not even be able to compile it unless you are familiar with such systems. <a href="http://jpauclair.net" target="_blank" title="jpauclair">Jean-Philippe Auclair&#8217;s blog</a> contains a lot of interesting Tamarin and Flash Player releated articles if you want to know more about the VM. Of course you can also read about <a href="https://developer.mozilla.org/en/MMgc" title="MMgc" target="_blank">MMgc</a> &#8212; the garbage collection &#8212; directly at the Mozilla developer network.</p>
<p>This article is titled &#8220;Opening The Blackbox&#8221;. Although Tamarin might be some kind of blackbox to most of us the source code is available. We can dig into it and understand how it works. The Flash Player however is not completely open source and we do not know about its implementation details. Unless Adobe is opening up the source code we will not know which exact algorithm is used for <a href="http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/display/BitmapData.html#noise()" target="_blank" title="flash.display.BitmapData">BitmapData.noise</a> for instance.</p>
<blockquote><p>Fills an image with pixels representing random noise.</p></blockquote>
<p>This quote taken from the documentation does not tell you much about how to calculate this noise. In this situation I would create some algorithm that fills a BitmapData also with random noise. But until we know which algorithm is used to calculate that noise it will never be the exact same noise as the one of the Flash Player. For now we will have to live with it. There is no (legal) way to figure out the algorithm.<br />
Of course there are also other classes like ByteArray which have methods like <code>readByte</code> that do not need any extra explanation. But ByteArray also has some implementation specific details. How does it grow when you exceed its length for instance? Fortunately ByteArray is something <a href="http://hg.mozilla.org/tamarin-central/file/fbecf6c8a86f/axscript/ByteArrayGlue.cpp#l138" target="_blank" title="ByteArrayGlue.cpp">you can find</a> in the Tamarin source code. JITB uses a different algorithm however which you can find <a href="http://code.google.com/p/apparat/source/browse/apparat-playerglobal/src/main/java/flash/utils/ByteArray.java#161" target="_blank" title="ByteArray.java">here</a>.</p>
<p>But what else do we got? There are some funny things you will notice. Usually <code>Sprite(x)</code> is an explicit cast. This is true for any statement like this. However <a href="http://help.adobe.com/en_US/AS3LCR/Flash_10.0/package.html#Number()" target="_blank" title="Number()"><code>Number(x)</code></a> is a conversion with specific details how a value is converted. This is also true for some other expressions like <code>Boolean()</code>.</p>
<p>The <code>playerglobal.swc</code> contains all classes the Flash Player knows about. It should and it does with some minor differences. Of course it could be a bug on my end but some interfaces are missing. And they are suspicious since they cause/have special behaviour. Have a look at the <a href="http://code.google.com/p/apparat/source/browse/apparat-taas/src/main/scala/apparat/taas/frontend/abc/AbcFrontend.scala#32" target="_blank" title="AbcFrontend.scala">AbcFrontend</a> code. The <code>Synthetic</code> object contains part of the AST that is synthesized since those interfaces are missing in <code>playerglobal.swc</code>.</p>
<p>A lot of the Flash Player implementation details have made it into the <code>DisplayObject</code> and its subclasses. You cannot extend from <code>DisplayObject</code> and you cannot implement <code>IBitmapDataDrawable</code>. Even more interesting is the amount of classes that you cannot really use. <a href="http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/geom/Transform.html" target="_blank" title="flash.geom.Transform"><code>flash.geom.Transform</code></a> is such a class. How is <code>concatenatedMatrix</code> working if you would create your own instance of the <code>Transform</code> object?</p>
<p>Of course somewhere in the Flash Player will be some code that creates a <code>Transform</code> object. This will hold a reference to the original <code>DisplayObject</code> and concat the matrices up to the stage if you call <code>concatenatedMatrix</code>. The JITB implementation adds some special methods to the <code>Transform</code> class in such cases. Those methods are always prefixed with JITB$ if they are public. Another interesting fact is that you can modify the appearance of a <code>DisplayObject</code> by setting the matrix of the <code>Transform</code> object. This also has to change the scale, x, y and rotation values of the <code>DisplayObject</code>. There are a dozen of souch cases. Graphics would be an obvious candidate to talk about. I would advise you to take a look at <a href="http://wahlers.com.br/claus/blog/" target="_blank">Claus&#8217; blog</a> for <a href="http://wahlers.com.br/claus/blog/hacking-swf-1-shapes-in-flash/" target="_blank">everything you never wanted to know about shapes</a>.</p>
<p>Also something you probably never cared about is the way how <code>URLLoader</code> works. I do not care about the specific implementation details either. However one thing is important to keep in mind. Loaders have to work asynchronous since they do not block. This means your Flash content runs while waiting for an event like <code>Event.COMPLETE</code>. This is where it gets interesting since threads enter the game. This would be a simple view: ActionScript runs in one thread, the loader in a second thread. First of all we have to keep in mind that the ActionScript code runs in a loop which is basically only triggered by events like <code>Event.ENTER_FRAME</code> or user input. Only the code in your <code>DocumentClass</code> is the one that is initiated without an event. So how does this look like in pseudo-code?</p>
<pre>
while(NoErrorOccurred &#038;&#038; Running) {
  Dispatch Event.ENTER_FRAME to each DisplayObject
  Render DisplayList
  Dispatch Event.EXIT_FRAME to each DisplayObject
  Sleep(1000 / FrameRate - Elapsed)
}
</pre>
<p>Okay but how does an <code>Event.COMPLETE</code> make it into this loop when it comes from a different thread in which the loader runs? If the loader would simply dispatch this event when it completes the code would not run in the main thread. This means you could end up with ActionScript code running in parallel which would cause chaos and destruction. So what do you do? The current approach in JITB is to gather all events and dispatch them at the beginning of a frame. So basically the code looks now like this:</p>
<pre>
while(NoErrorOccurred &#038;&#038; Running) {
  Dispatch All Gathered Events
  Dispatch Event.ENTER_FRAME to each DisplayObject
  Render DisplayList
  Dispatch Event.EXIT_FRAME to each DisplayObject
  Sleep(1000 / FrameRate - Elapsed)
}
</pre>
<p>The implementation specific details can be found in <a href="http://code.google.com/p/apparat/source/browse/apparat-playerglobal/src/main/java/jitb/events/EventSystem.java" target="_blank" title="EventSystem.java">EventSystem.java</a> class. There are also some utility methods like <code>futureDispatch</code> to make development easier. Dynamic audio requires to dispatch an event that is filled with content. The thread in which the audio is passed to the sound card has to wait until <code>SampleDataEvent</code> is filled with new content. This also reveals a problem. The audio calculation has to wait for a complete ActionScript frame until new material is available. In fact such synchronization points are problematic for a task that requires very low latency. You can hear this when your ActionScript code takes very long to process the new audio and you get a stutter-noise or audible gap. Unfortunately there is nothing you can do about this problem at the moment besides keeping the cost of your ActionScript code as low as possible.</p>
<p>Of course everything is only my interpretation. The Flash Player might not suffer from the problems I describe here since someone might have come up with a better implementation. In fact I would doubt that the Flash Player works for dynamic audio the same way I do it currently.</p>
<p>The last blog post of this series will be more about how you can implement parts of the Flash Player API in Java so that JITB understands them and vice versa. Of course we can create our own <code>playerglobal.swc</code> as well and add new native classes like <a href="http://code.google.com/r/joaebert-sf2010-sprint/source/browse/apparat-playerglobal/src/main/java/jitb/display/GLSLShader.java" target="_blank" title="GLSLShader.java"><code>GLSLShader</code></a> which I demoed at FOTB. </p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2010/10/03/opening-the-blackbox/" size="standard" count="true"></div></div> <p><a href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=674&amp;md5=1bf8f52bd4912172087d59fed924367f" title="Flattr" target="_blank"><img src="http://blog.joa-ebert.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2010/10/03/opening-the-blackbox/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<atom:link rel="payment" href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=674&amp;md5=1bf8f52bd4912172087d59fed924367f" type="text/html" />
	</item>
		<item>
		<title>How JITB converts ActionScript to Java</title>
		<link>http://blog.joa-ebert.com/2010/10/02/how-jitb-converts-actionscript-to-java/</link>
		<comments>http://blog.joa-ebert.com/2010/10/02/how-jitb-converts-actionscript-to-java/#comments</comments>
		<pubDate>Sat, 02 Oct 2010 16:45:23 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[experiments]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[apparat]]></category>
		<category><![CDATA[avm]]></category>
		<category><![CDATA[bytecode]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jitb]]></category>
		<category><![CDATA[jvm]]></category>
		<category><![CDATA[taas]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=670</guid>
		<description><![CDATA[One of the biggest challenges when writing a program like JITB is to convert ActionScript to Java. There are major differences between ActionScript 3.0 and Java 1.6 which JITB currently targets. ActionScript 3.0 is a dynamically typed language with function closures. Furthermore it has native XML support, scope-changes, implicit getters and setters etc. The main [...]]]></description>
			<content:encoded><![CDATA[<p>One of the biggest challenges when writing a program like JITB is to convert ActionScript to Java. There are major differences between ActionScript 3.0 and Java 1.6 which JITB currently targets.</p>
<p>ActionScript 3.0 is a dynamically typed language with function closures. Furthermore it has native XML support, scope-changes, implicit getters and setters etc. The main issue however is to convert the set of bytecodes ahead of time to statically typed Java code. JITB does not know anything about what is going on since it compiles all the code ahead of time.</p>
<p><span id="more-670"></span></p>
<h3>JITB and TAAS</h3>
<p>JITB makes use of TAAS. A three address code intermediate language. TAAS has its own set of rules and typesystem that I defined for myself. Method overloading is supported for instance. And there is no concept of array access. Code like <code>x = a[0]</code> is converted to <code>x = a.getIndex(0)</code>. In TAAS terms the name of a method is also not worth a penny since it is always using a reference based lookup.</p>
<p>What I love about TAAS is that it has a really small instruction set. Array access is just a method call like any other method call. No extra instructions added. This makes optimizations really slick and easy to develop. Since the code is statically typed you also always know which method is being called and you could construct a call graph and do whole program optimizations which is a huge bonus. Escape analysis is something that is now finally possible for me.</p>
<p>JITB uses a frontend that parses ActionScript bytecode and creates an AST which is then transformed and passed to a backend that creates Java bytecode. The class and package structure is stored in a tree form. Method bodies are always stored in a graph representation. The interesting problem is to convert ActionScript into TAAS since it is no direct mapping and some statements are not supported in the same way you get them form the ActionScript bytecode. Then the next interesting problem is to convert this code into Java bytecode which is also not a direct mapping.</p>
<p>An example for such a problem are implicit getters and setters. TAAS does not have a concept of getters and setters but understands methods. So whenever the ActionScript bytecode has a <code>GetProperty</code> instruction I try to figure out if this is a field or not. If it is a field I generate a <code>TLoad</code> instruction, if it is an implicit getter it will be converted to a <code>TCall</code> instruction. However if it cannot be determined since the class might be dynamic a <code>TCall</code> instruction will be generated which uses the special <code>TGetProperty</code> method and this will be resolved at runtime.<br />
When converting to Java a <code>TLoad</code> can be easily translated to a <code>GETFIELD</code> operation. When it is a <code>TCall</code> I first lookup whether or not it is a special native function. If it is a special function like <code>TGetProperty</code> I insert Java code like <code>object.JITB$getProperty(name)</code>. If it is a normal function I simply insert an invoke operation.</p>
<h3>Closures for Java</h3>
<p>Java 1.6 does not support closures. This means Java does not understand the concept of a reference to a function. Code like <code>addEventListener(Event.ENTER_FRAME, onEnterFrame)</code> is not possible with Java since <code>onEnterFrame</code> is a reference to the <code>onEnterFrame</code> function which is defined somewhere else in your code.</p>
<p>I took the idea from Scala and how they support closures in the JVM. Basically when code like <code>addEventListener(Event.ENTER_FRAME, onEnterFrame)</code> occurrs it will be translated to the TAAS instruction <code>TCall(TReg(0), TaasMethod(addEventListener, ...), List(TString("enterFrame"), TClosure(TaasMethod(onEnterFrame, ...))), None)</code>. This basically means that the method <code>addEventListener</code> is called on the object in register zero with two arguments of which one a closure and it has no result which is indicated by <code>None</code>.</p>
<p>This instruction is expanded to the following Java code. Please remember that it is always Java bytecode. I think it is just easier to understand if I write the corresponding Java code here.</p>
<pre>
this.addEventListener("enterFrame", new Function1<Event, Object>() {
  override Object call(Event arg) { callVoid(arg); return null; }
  override void callVoid(Event arg) { onEnterFrame(arg); }
});
</pre>
<p>Function1 represents a function of arity one. The AVM can call any method as either void or with an expected result. If the method has a result and you call it via <code>CallPropVoid</code> the resulting object is ignored. If however you have a method that does not have a result and you call it via <code>CallProperty</code> the <code>null</code> object will be pushed on the stack.</p>
<p>The Java code in EventDispatcher which would call closures basically now only looks like this:</p>
<pre>
void dispatchEvent(Event event) {
  for(Function1<Event, Object> listener : listenersFor(event.type))
    listener.call(event)
}
</pre>
<h3>Dynamic code in Java</h3>
<p>Since I want to target Java 1.6 I do not make use of the Java 1.7 opcodes like <code>invokedynamic</code>. Because TAAS is already statically typed we have only in very rare cases the need to make a dynamic lookup. This is done by some helper classes or methods. Every ActionScript based class extends from <code>jitb.lang.Object</code>. The <code>jitb.lang</code> package represents the ActionScript&#8217;s toplevel. The <code>Object</code> class has certain helper methods like <code>JITB$getProperty</code> and <code>JITB$setProperty</code>. Those methods throw an error by default if an object is not dynamic but they can implement the behaviour to store values in a HashMap for dynamic classes.<br />
However currently dynamic method lookup is not supported. Code like <code>a['method'+Math.random()]()</code> fails since it is impossible to know upfront which method is called. But this can be supported as well. It is just very cumbersome and annoying.</p>
<h3>Emulating the AVM in the JVM</h3>
<p>What kind of error do you expect for this kind of code: <code>var x: String = null; trace(x.toString());</code>? This creates a TypeError in ActionScript but a NullPointerException in Java. Same for things like <code>var x: A = new A(); var y: B = B(x);</code> which would result in a Java ClassCastException if A is not assignable to B.<br />
JITB offers an option which is by default turned on the get the exact same exceptions like the AVM would throw them. This means that a Java cast is converted to a call like <code>AVM.cast(x, B.class)</code> with the option turned on or the simple Java <code>CHECKCAST</code> bytecode when the option is turned off. Basically expecting something to be null in a try-catch block is very silly in my honest opinion. So to get rid of this overhead you can disable this extra step of correctness.</p>
<p>Another interesting issue is the fact thatthe AVM can throw any object. Java however expects that a throwable object extends from the Throwable class. Of course the basic <code>jitb.lang.Object</code> class could simply extend Throwable. However I do not want that overhead and at any time. Also I do not want to break how classes extend each other. If you do something like <code>throw "string"</code> it is converted to <code>throw new Throw<String>("string")</code>. Throw does extend Throwable and whenever it is catched the value is simply extracted.</p>
<h3>To box or not to box?</h3>
<p>ActionScript allows you do use int as an object with a lot of special behaviours. Same happens for values like Boolean or Number. <code>var x: int; trace(x);</code> outputs 0 but not null. But it is also possible to call <code>0.toString()</code> which indicates that the integer value <code>0</code> is treated like an object that has methods like <code>toString()</code>.<br />
In Java however you have a real <code>int</code> primitive and the <code>Integer</code> object. <code>0.toString()</code> does not compile but you would rather do <code>Integer.toString(0)</code>.</p>
<p>Of course Java is much faster when using primitive data types when appropriate. JITB does this since it handles primitive types like real primtives for Java. This means a method like <code>function add(x: int, y: int): int { return x + y}</code> is converted to <code>int add(int x, int y) { return x + y }</code>. However when you have a method that expects an Object type a primitive will be boxed into a compatible type.</p>
<p>Last but not least what happens for code like <code>0.toString()</code> or other methods? A possibility would be to emit code like <code>new jitb.lang.Number(0).toString()</code> but that does not make sense in most of the cases. Instead those calls are treated specially with a call like <code>jitb.lang.Number.JITB$toString(0)</code> and we get rid of an extra allocation.</p>
<h3>Conclusion</h3>
<p>I hope you understand a little bit better now how JITB works internally and what the main gotchas are in such an implementaiton. The journey is not over since I have to add support for anonymous methods and although I talked about things like <code>throw</code> I still have to add support for try-catch. Also a lot of other basic features are still missing but I doubt that they would cause any problems.</p>
<p>The other side of the story is the Flash Player API inside of JITB which is maybe worth a blog post like this as well since it reveals a lot of other funny and interesting gotchas.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2010/10/02/how-jitb-converts-actionscript-to-java/" size="standard" count="true"></div></div> <p><a href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=670&amp;md5=d839aa2d65bc21169a914c85dee2bda9" title="Flattr" target="_blank"><img src="http://blog.joa-ebert.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2010/10/02/how-jitb-converts-actionscript-to-java/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<atom:link rel="payment" href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=670&amp;md5=d839aa2d65bc21169a914c85dee2bda9" type="text/html" />
	</item>
		<item>
		<title>JITB&#8217;s PixelBender support</title>
		<link>http://blog.joa-ebert.com/2010/10/01/jitbs-pixelbender-support/</link>
		<comments>http://blog.joa-ebert.com/2010/10/01/jitbs-pixelbender-support/#comments</comments>
		<pubDate>Fri, 01 Oct 2010 15:35:37 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[experiments]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[hydra]]></category>
		<category><![CDATA[apparat]]></category>
		<category><![CDATA[glsl]]></category>
		<category><![CDATA[jitb]]></category>
		<category><![CDATA[pixelbender]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=664</guid>
		<description><![CDATA[I have demoed support for PixelBender shaders in JITB at the FOTB 2010 conference. It turned out that JITB can run PixelBender code really fast and well. I have demoed a Julia and Terrain raytracer which were both kindly contributed by David Lenaerts. I only showed the demos since I would have been running out [...]]]></description>
			<content:encoded><![CDATA[<p>I have demoed support for PixelBender shaders in JITB at the <a href="http://www.flashonthebeach.com/" target="_blank">FOTB 2010</a> conference. It turned out that JITB can run PixelBender code really fast and well. I have demoed a Julia and Terrain raytracer which were both kindly contributed by <a href="http://www.derschmale.com/" target="_blank">David Lenaerts</a>. I only showed the demos since I would have been running out of time. I still owe you an explanation of how it all works.<br />
<span id="more-664"></span></p>
<h3>Step #1: Parsing PixelBender data</h3>
<p>PixelBender compiles down to PBJ which is a two-address based bytecode format. Basically it contains instructions like this one which I have taken from <a href="http://www.ncannasse.fr/projects/pbj" target="_blank">Nicolas&#8217; blog</a>:</p>
<pre>  sampleNearest f2, text0[f0.rg]
  sampleNearest f3, text1[f0.rg]
  mov f4, f2
  mul f4, f3
  mov f1, f4</pre>
<p>Those PBJ files are parsed by Apparat into high level structures. This happens basically the same way I do it for ActionScript bytecode. Thanks to the work of Nicolas Cannasse this was a walk in the park.</p>
<h3>Step #2: Optimizing PixelBender bytecode</h3>
<p>The PixelBender compiler does not produce optimal code as noted by Nicolas. You can see it in the code I just posted. Or you can simply compile and empty shader and take a look at the disassembled output. Apparat performs only two very simple optimizations for PixelBender which are written especially for PBJ. Thos include copy propagation and dead code elimination. The compiler does create code which is not bad thanks to <a href="http://www.llvm.org/" target="_blank">LLVM</a> but there are unnecessary copies going on which are removed by Apparat.</p>
<h3>Step #3: Loop detection</h3>
<p>PixelBender <b>still</b> has no loops since its initial introduction in October 1st in 2007. Tomorrow it is October 1st in 2010. Go figure. So since there are no loops the only way people write loops in PixelBender is basically by copy and paste or using preprocessor directives. With JITB I want to send real shaders to the graphics card and I do want to make use of loops. So I wrote a PBJ bytecode based copy and paste detector which is based on ideas of the <a href="http://pmd.sourceforge.net/" target="_blank">PMD</a> copy and paste detector. When a segment is detected in a sequence I convert it to a loop. That way I can reduce the amount of data I have to send to the graphics card. This is very important since in the case of the demos I showed at FOTB they contained around 50.000 instructions. And my cheap graphics card was complaining that there are too many instrucitons. With the loop conversion this number drastically decreased.</p>
<h3>Step #4: Converting PixelBender bytecode to GLSL</h3>
<p>It is very easy to convert PixelBender to GLSL. The two address code format can be translated with some minor tweaks to GLSL with a very simple mapping. However this is not really optimal since you have only a two address code. When exporting to GLSL I perform one additional step which expands the two address based code to a three address based code. That way I do not emit a lot of unnecessary copies again.</p>
<p>That is basically the recipie to convert PixelBender PBJ files to GLSL shaders that perform well on current graphics card hardware. There are additional steps involved to get OpenGL shaders to work like PixelBender in Flash but they are only minor tweaks. I have no comparable metrics right now. However I will create a JITB applet version so you can have a look for yourself soon.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2010/10/01/jitbs-pixelbender-support/" size="standard" count="true"></div></div> <p><a href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=664&amp;md5=0cf6eb4a85dfbfd59053adc3948edf8e" title="Flattr" target="_blank"><img src="http://blog.joa-ebert.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2010/10/01/jitbs-pixelbender-support/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=664&amp;md5=0cf6eb4a85dfbfd59053adc3948edf8e" type="text/html" />
	</item>
		<item>
		<title>So I Recorded A New Video</title>
		<link>http://blog.joa-ebert.com/2010/08/31/so-i-recorded-a-new-video/</link>
		<comments>http://blog.joa-ebert.com/2010/08/31/so-i-recorded-a-new-video/#comments</comments>
		<pubDate>Tue, 31 Aug 2010 12:38:49 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[experiments]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[apparat]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jitb]]></category>
		<category><![CDATA[jvm]]></category>
		<category><![CDATA[taas]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=647</guid>
		<description><![CDATA[This time recorded on Ubuntu. Did I mention 64bit already? Do not miss my session at FOTB for a live demo.]]></description>
			<content:encoded><![CDATA[<div align="center"><object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/atzHF7YGp6Y?fs=1&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/atzHF7YGp6Y?fs=1&amp;hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object></div>
<p>This time recorded on Ubuntu. Did I mention 64bit already?<br />
Do not miss my session at <a href="http://www.flashonthebeach.com/" target="_blank">FOTB</a> for a live demo.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2010/08/31/so-i-recorded-a-new-video/" size="standard" count="true"></div></div> <p><a href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=647&amp;md5=66836cca038fcf8883ba718d7edfd8de" title="Flattr" target="_blank"><img src="http://blog.joa-ebert.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2010/08/31/so-i-recorded-a-new-video/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		<atom:link rel="payment" href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=647&amp;md5=66836cca038fcf8883ba718d7edfd8de" type="text/html" />
	</item>
		<item>
		<title>Putting Things In Perspective</title>
		<link>http://blog.joa-ebert.com/2010/08/30/putting-things-in-perspective/</link>
		<comments>http://blog.joa-ebert.com/2010/08/30/putting-things-in-perspective/#comments</comments>
		<pubDate>Mon, 30 Aug 2010 16:34:18 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[experiments]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[apparat]]></category>
		<category><![CDATA[avm]]></category>
		<category><![CDATA[jitb]]></category>
		<category><![CDATA[jvm]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=642</guid>
		<description><![CDATA[I am back home in Germany from my trip to San Francisco where I initially announced JITB at FITC. I did not expect it to get around that quickly and that a quick-and-dirty video filmed with my phone would get so much coverage. I want to put a lot of things regarding JITB in perspective [...]]]></description>
			<content:encoded><![CDATA[<p>I am back home in Germany from my trip to San Francisco where I initially announced JITB at <a href="http://www.fitc.ca/" target="_blank" title="FITC">FITC</a>. I did not expect it to get around that quickly and that a quick-and-dirty video filmed with my phone would get so much coverage.</p>
<p>I want to put a lot of things regarding JITB in perspective here as a followup to the various comments that I received via mail, reddit, etc.</p>
<h3>Flash Replacement</h3>
<p>JITB is not a Flash replacement. Imagine a F1 race car and a family van. The family van comes with air conditioning, a radio and a lot of comfort. For the F1 car you will probably have to wear a helmet and need an engineering team to get it running.<br />
The important factor for me is that JITB will run very fast under certain conditions. A race car is also not a jeep. JITB will not support all features of the Flash Player. If you search for a Flash replacement you might want to take a look at  <a href="http://sourceforge.net/apps/trac/lightspark" target="_blank">lightspark</a>.</p>
<h3>Performance</h3>
<p>Java is slow and the world is flat. That being said I will not talk about Java performance. JITB compiles to native Java code with a certain overhead. An ActionScript 3 closure is converted into an anonymous class for instance.<br />
JITB converts ActionScript 3 bytecode to Java bytecode at runtime and performs various optimizations. This way we can leverage the speed of the JVM for ActionScript and get great results.<br />
That being said there is also a problem of course. Startup time is not very good. JITB and its parent project Apparat are implemented in the <a href="http://www.scala-lang.org/" target="_blank">Scala</a> programming language and written for multi core architectures. The startup costs are high and JITB is only useful for long living applications. However compiling ActionScript to Java can be done <a href="http://en.wikipedia.org/wiki/AOT_compiler" target="_blank" title="AOT compiler on Wikipedia">AOT</a>. This means you need to deal only with the normal JVM startup time. The Flash Player API is implemented in pure Java.</p>
<p>The compiler used for JITB is doing relatively naive optimizations at the moment. Namely constant folding, copy propagation, dead code elimination and strength reduction. An older proof of concept version I implemented a year ago featured also loop invariant code motion, inline expansion and tail-recursive optimizations. The new compiler framework is very powerful and I will add even more algorithms and a graph coloring register allocator for example. So there is some more NP-complete fun ahead making startup time even worse.</p>
<h3>Purpose</h3>
<p>We need a Flash Player that performs very fast for special purposes. We could use JITB at <a href="http://www.audiotool.com/" target="_blank" title="Audiotool">Audiotool</a> to render mixdowns of tracks or other companies could use it to run their ActionScript code on the server side. You can use JITB to create an offline application that runs on a client machine. You can hack JITB to do what you want. Someone could potentially write a web framework for ActionScript and you could execute that code on Google App Engine if compiled AOT. And it is definitly possible to create Android applications using ActionScript. JITB&#8217;s terrain is everything but the browser in my opinion. However I can imagine that someone would be interested in creating a plugin version. With some <del datetime="2010-08-30T16:00:23+00:00">clever</del> simple caching algorithms it could make sense to get around startup costs but I am not interested in doing this. </p>
<h3>Legal</h3>
<p>There are no legal obligations to face since both the AVM2 and SWF specifications are published by Adobe. It is also not illegal to compile code for the JVM.</p>
<h3>ActionScript Subset</h3>
<p>By &#8220;a subset of the language&#8221; I really mean the language and not the API. JITB supports currently only statically typed ActionScript code. However the internal language model can be adjusted to support dynamic typing as well and with Java 7 things got even easier. In fact JITB does support dynamic code as long as it is able to infer types correct. Does this mean that I am willing to implement the full Flash Player API all by myself? Hell no.</p>
<p>In the next weeks I will probably create a better example that is easier to understand and get some other stuff ready so that you can try everything for yourself.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2010/08/30/putting-things-in-perspective/" size="standard" count="true"></div></div> <p><a href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=642&amp;md5=a7fc274af0332ec97d12c0a14f5f1cda" title="Flattr" target="_blank"><img src="http://blog.joa-ebert.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2010/08/30/putting-things-in-perspective/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		<atom:link rel="payment" href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=642&amp;md5=a7fc274af0332ec97d12c0a14f5f1cda" type="text/html" />
	</item>
		<item>
		<title>Introducing JITB</title>
		<link>http://blog.joa-ebert.com/2010/08/19/introducing-jitb/</link>
		<comments>http://blog.joa-ebert.com/2010/08/19/introducing-jitb/#comments</comments>
		<pubDate>Thu, 19 Aug 2010 02:07:41 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[experiments]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[actionscript]]></category>
		<category><![CDATA[apparat]]></category>
		<category><![CDATA[fitc]]></category>
		<category><![CDATA[flashplayer]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jitb]]></category>
		<category><![CDATA[opengl]]></category>
		<category><![CDATA[san francisco]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=636</guid>
		<description><![CDATA[My talk at FITC San Francisco is over and I want to share some of the anouncements from today with you. At the end of my talk I was showing JITB. What you see in the YouTube video I posted a while ago is a Java program executing a SWF. For FITC I added some [...]]]></description>
			<content:encoded><![CDATA[<div align="center"><object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/EMm893PRDJM?fs=1&amp;hl=de_DE"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/EMm893PRDJM?fs=1&amp;hl=de_DE" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object></div>
<p>My talk at FITC San Francisco is over and I want to share some of the anouncements from today with you. At the end of my talk I was showing <a href="http://www.youtube.com/watch?v=-IXvf17GWVI" target="_blank" title="JITB">JITB</a>.</p>
<p>What you see in the YouTube video I posted a while ago is a Java program executing a SWF. For FITC I added some more code and an OpenGL based Display List renderer. In other words: I wrote a Flash Player.</p>
<p>However I should rephrase that statement and say I am attempting to build a Flash Player. The current state is available in the <a href="http://code.google.com/r/joaebert-sf2010-sprint/source/list" target="_blank" title="sf2010-sprint clone">sf2010-sprint</a> clone of Apparat. I will merge the changes into the main Apparat branch when I am back home in Germany.</p>
<p>JITB is currently able to translate a subset of ActionScript code at runtime into Java bytecode and runs nearly at the same speed as native Java. This is a really huge improvement compared to standard ActionScript performance. A lot of smart people worked on the JVM and made it really fast. Apparat will allow you to leverage all this hard work in the future. I am also shooting for Java interoperability at some level so that you can call Java classes from within ActionScript. Hopefully you will be able to use JITB on your desktop machine, on a server or on an Android phone. Basically everywhere Java runs.</p>
<p>There are still a lot of things missing. The whole Flash API needs to be implemented. And the Display List rendering needs a proper OpenGL implementation. However I thought this might be some cool stuff to share with you in its early stages.<br />
My hope is that more people start contributing to the project. Maybe some OpenGL guru wants to take care of the Display List rendering or someone else likes to help implement the Flash API in Java.</p>
<p>I also showed a Raytracer by Nico Zimmermann during my presentation and promised to put the URL on my blog so here it is. His company is called Britzpetermann and the address is <a href="http://www.britzpetermann.com/" target="_blank" title="Britzpetermann">http://www.britzpetermann.com/</a>.</p>
<p><b>Update:</b> Please do not think that this implementation is 30x faster than the Flash Player developed by Adobe. One(!) microbenchmark is never a number you should count on. I would like to make clear that I never said this.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2010/08/19/introducing-jitb/" size="standard" count="true"></div></div> <p><a href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=636&amp;md5=e3cd48304d4dfb8fee13de1b216671c2" title="Flattr" target="_blank"><img src="http://blog.joa-ebert.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2010/08/19/introducing-jitb/feed/</wfw:commentRss>
		<slash:comments>53</slash:comments>
		<atom:link rel="payment" href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=636&amp;md5=e3cd48304d4dfb8fee13de1b216671c2" type="text/html" />
	</item>
		<item>
		<title>New Apparat Example</title>
		<link>http://blog.joa-ebert.com/2010/05/26/new-apparat-example/</link>
		<comments>http://blog.joa-ebert.com/2010/05/26/new-apparat-example/#comments</comments>
		<pubDate>Wed, 26 May 2010 11:50:54 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[experiments]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[news]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[apparat]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[inline]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=595</guid>
		<description><![CDATA[Good news everyone. The Apparat inline expansion works now to full extent after fixing some minor bugs. A complete example is also available. Just change the paths in the build.properties file and compile everything using Ant. Use the inline feature with care. Apparat does not try to optimize your code and performs nothing but dead [...]]]></description>
			<content:encoded><![CDATA[<p>Good news everyone. The Apparat inline expansion works now to full extent after fixing some minor bugs. A complete example is also available. Just change the paths in the <code>build.properties</code> file and compile everything using Ant.</p>
<div align="center"><img src="http://blog.joa-ebert.com/wp-content/images/apparat-shot.png" width="399" height="183" alt="Apparat Example"/></div>
<p>Use the inline feature with care. Apparat does not try to optimize your code and performs nothing but dead simple inlining. This can lead to <b>slower</b> code due to the creation of lots of local registers. Your code gets also much bigger and will require more space in memory. I am actually not a fan of manual inlining at all. I think it makes only sense to inline code if you have a powerful optimizer available that will cleanup the whole mess.</p>
<p>The fun story about this example is that the inlined version is slower using the lastes Flash Player release candidate if you have only 40.000 particles. That is why I increased the number of particles to 80.000 ;). I developed the example using an old standalone player and the inlined version was nearly twice as fast. However when I watched the example in the browser with the latest release candidate the game was completely different. Kudos to Adobe for significantly improving the Flash Player performance!</p>
<ul>
<li><a href="http://www.joa-ebert.com/swfs/apparat-example/as3" target="_blank" title="Pure AS3 version">AS3-only Version</a></li>
<li><a href="http://www.joa-ebert.com/swfs/apparat-example/apparat" target="_blank" title="Inline version">Inline Version</a></li>
<li><a href="http://code.google.com/p/apparat/downloads/detail?name=apparat-ant-example.zip" target="_blank" title="Source">Source</a></li>
</ul>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2010/05/26/new-apparat-example/" size="standard" count="true"></div></div> <p><a href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=595&amp;md5=2ce2a0467b1d8ded7f90f209404288e1" title="Flattr" target="_blank"><img src="http://blog.joa-ebert.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2010/05/26/new-apparat-example/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		<atom:link rel="payment" href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=595&amp;md5=2ce2a0467b1d8ded7f90f209404288e1" type="text/html" />
	</item>
		<item>
		<title>Polyglott Programming On The AVM2</title>
		<link>http://blog.joa-ebert.com/2009/11/16/polyglott-programming-on-the-avm2/</link>
		<comments>http://blog.joa-ebert.com/2009/11/16/polyglott-programming-on-the-avm2/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 10:49:19 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[experiments]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[apparat]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jvm]]></category>
		<category><![CDATA[polyglott]]></category>
		<category><![CDATA[taas]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=502</guid>
		<description><![CDATA[Take some time and think about this tweet for a moment. It took me a while to realize that Joel Hooks is right. I was embaressed of myself. How could I forget about that? But I had also a big smile on my face at the same same time. Let me explain why. The Java [...]]]></description>
			<content:encoded><![CDATA[<p>Take some time and think about <a href="http://twitter.com/jhooks/status/5688660297" target="_blank" title="@jhooks on twitter">this tweet</a> for a moment. It took me a while to realize that Joel Hooks is right. I was embaressed of myself. How could I forget about that? But I had also a big smile on my face at the same same time. Let me explain why.</p>
<p>The Java to SWF compiler does not compile Java sourcecode but JVM bytecode to ActionScript bytecode. This means I do not have to teach my program the Java language. It only understands JVM bytecode. This seems like an akward decision on the one hand since working on the bytecode level implies lots of problems. But it turns out that this was a really cool decision on the other hand. &#8220;<i>Java</i> to SWF compiler&#8221; is maybe the wrong description. &#8220;<i>any language that compiles to JVM bytecode</i> to SWF compiler&#8221; is maybe better.</p>
<p>So what does any language mean? Here is a <a href="http://en.wikipedia.org/wiki/List_of_JVM_languages" target="_blank" title="List of JVM languages">list of JVM languages</a>. Now you feel maybe like I did after reading that tweet. And I am really looking forward to get <a href="http://www.scala-lang.org/" target="_blank" title="Scala Language">Scala</a> up and running.</p>
<p>Some problems still exist. Threading is one issue and I will basically have to do what Scott Peterson did for Alchemy. But reflections, annotations and method overloading have to be solved as well. Some glitches may exist even after figuring everything out. Stacktraces will look pretty weird. However I think this is a really cool project.</p>
<p><b>Update:</b> I forgot to mention something important. Java supports native code. This means you can build a library that works with OpenGL for instance. Those native methods can not be converted. There are also some other things that do not work. File access is just one of them.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2009/11/16/polyglott-programming-on-the-avm2/" size="standard" count="true"></div></div> <p><a href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=502&amp;md5=db5b3cc37122ba7cbea80270388ca1c2" title="Flattr" target="_blank"><img src="http://blog.joa-ebert.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2009/11/16/polyglott-programming-on-the-avm2/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<atom:link rel="payment" href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=502&amp;md5=db5b3cc37122ba7cbea80270388ca1c2" type="text/html" />
	</item>
		<item>
		<title>Getting Rid Of null</title>
		<link>http://blog.joa-ebert.com/2009/11/06/getting-rid-of-null/</link>
		<comments>http://blog.joa-ebert.com/2009/11/06/getting-rid-of-null/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 18:15:51 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[experiments]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[null]]></category>
		<category><![CDATA[option]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=495</guid>
		<description><![CDATA[A couple of weeks ago I started learning Scala. I can highly recommend it. The language has a lot of great approaches to multithreading and scalability. The reason why I like Scala is because it is so simple yet powerful. Of course doing something at home influences work. I decided to write a build tool [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of weeks ago I started learning <a href="http://www.scala-lang.org/" target="_blank" title="Scala">Scala</a>. I can highly recommend it. The language has a lot of great approaches to multithreading and scalability. The reason why I like Scala is because it is so simple yet powerful.</p>
<p>Of course doing something at home influences work. I decided to write a build tool for the Hobnox AudioTool which is about 200 lines of Scala code. Cool thing is that this tool replaces a manually maintained Ant build and all project dependencies are always correct. Plus analyzing the dependencies in a more powerful way allows me to spawn the compiler in parallel. Building the AudioTool is now twice as fast and much more comfortable.</p>
<p>When learning a new programming language you also learn about new concepts. Functional languages in general have a different approach to nullable types. I know Scala is not the only one but let me introduce the concept in terms of ActionScript.</p>
<p>When you have a method that returns either a result or nothing: what do you do? Imagine you have some kind of service and a Dictionary of users. Requesting a user works by his unique id. The Dictionary is private to the class since you want to keep it read only.</p>
<p><code>
<pre>function getUser(id: String): User {
  return hasUser(id) ? users[id] : null;
}</pre>
<p></code></p>
<p>If I would now simply ask the service for an unknown user and do something like <code>if(getUser('xyz').isLoggedIn) { trace('Hooray'); }</code> I could probably and up with a null-reference error. No one checks for me if the user exists. So what else could we do? Write a lot of boilerplate code and prepend a check if the user is null or not each time we request one from the service. A much better approach in my opinion is to throw an error as early as possible. In this case we would rewrite the method to something like this:</p>
<p><code>
<pre>function getUser(id: String): User {
  if(hasUser(id)) return users[id];
  throw new NoSuchUserError(id);
}</pre>
<p></code></p>
<p>In this scenario we get informed about the error as early as possible. But we are stuck again. First of all ActionScript does not enforce you to catch possible exceptions. This means if you do not read the documentation of a method carefully or look into the source code of a method before calling it somewhere you will never know that it throws an exception. And what if we are actually in a scenario where we do not expect errors for non-existing objects? Think of the Dictionary object throwing each time an error when you access it and the result is null. How could I even check if an object exists in a Dictionary?</p>
<p><code>
<pre>try {
  dictionary[key];
  return true;
}
catch(noSuchElementError: NoSuchElementError) {
  return false;
}</pre>
<p></code></p>
<p>I guess you see that this can not be the solution to our problem. In a real world example you may deal with your own collection of objects instead of a Dictionary of course. So we have to get rid of exceptions and null for the optimal solution. Scala&#8217;s approach to this problem is the <a href="http://www.scala-lang.org/docu/files/api/scala/Option.html" target="_blank" title="Option type">Option</a> type. We always abuse <code>null</code> as a placeholder when we want to express that an element does not exist. The <code>Option</code> means that either <code>Some</code> or <code>None</code> result exists. Rewriting our <code>getUser</code> function using this approach would yield the following ActionScript code.</p>
<p><code>
<pre>function getUser(id: String): Option {
  return hasUser(id) ? new Some(user[id]) : new None();
}</pre>
<p></code></p>
<p>Why is this much better than the old approach? When calling the method you will always know that the method has only an optional result value. We get rid of the exception and <code>null</code> values. Our only problem at the moment is ActionScript. The result is now untyped. In an ideal world this method would be written as:</p>
<p><code>
<pre>function getUser(id: String): Option.&lt;User&gt; {
  return hasUser(id) ? new Some.&lt;User&gt;(user[id]) : new None.&lt;User&gt;();
}</pre>
<p></code></p>
<p>However we can still tackle this issue by implementing null-representations of our objects. Imagine the <code>User</code> class. You could rewrite the code to something like this.</p>
<p><code>
<pre>function getUser(id: String): IUser {
  return hasUser(id) ? user[id] : new NullUser();
}

final class NullUser implements IUser {
  public function get isLoggedIn(): Boolean { return false; }
  public function get name(): String { return 'null'; }
}</pre>
<p></code></p>
<p>And even if you are interested in null-reference errors you could rewrite your code to something like this:</p>
<p><code>
<pre>final class NullUser implements IUser {
  public function get isLoggedIn(): Boolean {
    CONFIG::ThrowNullReferenceErrors { throw new NullReferenceError(); }
    return false;
  }
  public function get name(): String {
    CONFIG:: ThrowNullReferenceErrors { throw new NullReferenceError(); }
    return 'null';
  }
}</pre>
<p></code></p>
<p>It is definitely a very different approach. A functional language like Scala allows you to deal much better with Options. But it makes sense to diferentiate between an uninitialized variable which is <code>null</code> and an optional result of a function. Unfortunately this is at the moment very painful with the lack of generics in ActionScript.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2009/11/06/getting-rid-of-null/" size="standard" count="true"></div></div> <p><a href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=495&amp;md5=801ee4b53d791afbeae82b0f432c0193" title="Flattr" target="_blank"><img src="http://blog.joa-ebert.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2009/11/06/getting-rid-of-null/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		<atom:link rel="payment" href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=495&amp;md5=801ee4b53d791afbeae82b0f432c0193" type="text/html" />
	</item>
		<item>
		<title>Compiling Java and C# to SWF</title>
		<link>http://blog.joa-ebert.com/2009/09/28/compiling-java-and-c-to-swf/</link>
		<comments>http://blog.joa-ebert.com/2009/09/28/compiling-java-and-c-to-swf/#comments</comments>
		<pubDate>Mon, 28 Sep 2009 13:41:03 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[experiments]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[apparat]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[soot]]></category>
		<category><![CDATA[taas]]></category>
		<category><![CDATA[visualbasic]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=480</guid>
		<description><![CDATA[At the end of my Leaving the Sandbox session I showed two projects I have been working on without telling anyone. The first was a compiler that could compile C# to SWF. The second was another compiling being able to compile Java to SWF. First of all I have to say that both tools are [...]]]></description>
			<content:encoded><![CDATA[<p>At the end of my Leaving the Sandbox session I showed two projects I have been working on without telling anyone. The first was a compiler that could compile C# to SWF. The second was another compiling being able to compile Java to SWF. First of all I have to say that both tools are far from being finished. They are a so called proof-of-concept. For me it is enough to know that this is possible. I am also not sure if I will finish one of those tools.</p>
<p>So how does this work? Because I am now working on the AudioTool backend for our highly anticipated launch I had to switch to fulltime Java development. In order to understand the JVM better I started to search for the optimizations that the HotSpot VM performs and stumbled upon a framework called <a href="http://en.wikipedia.org/wiki/Soot_(computer_science)" target="_blank">Soot</a>. Voilà. Reading about Soot made me question why nobody is working on such a framework for ActionScript. Probably because universities see Flash just as a toy. For us developers being dependent on the Flash Platform it is of course more than that.</p>
<p>I will quickly explain what Soot does. It reads compiled Java <code>class</code> files and converts the machine code they contain into a three address code representaiton. This code is then heavily optimized. TAAS is basically doing the same. I also want to note that Soot is by far more complex and complete than TAAS right now. It would be megalomania saying that TAAS is Soot for ActionScript. But you get the idea. The one framework converts Java to three address code and the other framework converts ActionScript to three address code. Maybe it is possible to connect them.</p>
<p>This is what I did for the Java compiler. The whole pipeline looks like this:</p>
<ol>
<li>Compile Java sourcecode with the Java compiler of your choise</li>
<li>Use Soot to get the three address code representation of a compiled binary</li>
<li>Create TAAS expressions for the expressions that Soot uses</li>
<li>Connect the TAAS graph the same way the Soot graph is connected</li>
<li>Compile the TAAS graph to a SWF</li>
</ol>
<p>This is about it. There is some glue-code involved here and there and I did not implement all Java expressions yet. I did also not bother about threads. Basically one could do what Scott has done for Alchemy.  The cool thing is that we get highly optimized Java code because of the Java compiler and Soot. Then the TAAS compiler can run a second time after linking is done and perform platform specific optimizations like inlining and loop invariant code motion for certain expressions.</p>
<p>I already wrote a couple of classes and packed them in a SWC. Those mimic the behaviour of the Java classes like <code>java.lang.System</code> or <code>java.util.LinkedList</code>.  On the Java side I implemented the Flash classes like <code>flash.display.Sprite</code> and <code>flash.events.EventDispatcher</code>. The interesting part is that all the methods those classes contain are marked native which means they have no implementation since they are native to the Flash Player.<br />
This is also a great advantage. It is slow in Alchemy to call Flash methods and to communicate with Flash classes. The Java approach does not have this tradeoff. I also do not have to trigger the ActionScript compiler. The conversion form <code>class</code> to <code>swf</code> is entirely done using Soot and TAAS.</p>
<p>So far for the Java compiler. But in order to show a little bit more of the potential I wanted to have a C# compiler working as well. The great thing about advanced languages and a large community is that people have already built a lot of tools. It did not take too long to find an advanced framework that converts C# to Java. Actually this is not be the best approach. But I could not find the &#8220;Soot for C#&#8221; the evening before my FOTB session.</p>
<p>So I am using <a href="https://net2java.dev.java.net/">net2java</a> to convert .NET code like C# or VisualBasic to Java. That code is then compiled using the Java compiler and I am using Soot again to convert the code to TAAS without much stress.</p>
<p>For me the most important part is to know that it is possible to compile .NET source code and Java binaries to SWF. To complete those tools one just has to implement all the missing expressions and the standard Java library in Flash. Everything could also work the other way around. Compiling from TAAS to .NET, Silverlight and Java is another option.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2009/09/28/compiling-java-and-c-to-swf/" size="standard" count="true"></div></div> <p><a href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=480&amp;md5=710ffb48f715a13750695bc72e04a89c" title="Flattr" target="_blank"><img src="http://blog.joa-ebert.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2009/09/28/compiling-java-and-c-to-swf/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		<atom:link rel="payment" href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=480&amp;md5=710ffb48f715a13750695bc72e04a89c" type="text/html" />
	</item>
		<item>
		<title>TAAS progress</title>
		<link>http://blog.joa-ebert.com/2009/09/07/taas-progress/</link>
		<comments>http://blog.joa-ebert.com/2009/09/07/taas-progress/#comments</comments>
		<pubDate>Mon, 07 Sep 2009 14:50:07 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[experiments]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[apparat]]></category>
		<category><![CDATA[taas]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=472</guid>
		<description><![CDATA[I have developed some other optimizations during the past couple of days. Including strength reduction and optimizing tail recursive calls. Strength reduction can already handle about 55 different cases at the moment. For instance it will convert code like if( x - 1 == 0 ) into if( x == 1 ). But it will [...]]]></description>
			<content:encoded><![CDATA[<p>I have developed some other optimizations during the past couple of days. Including <a href="http://en.wikipedia.org/wiki/Strength_reduction" target="_blank" title="Strength Reduction">strength reduction</a> and optimizing <a href="http://en.wikipedia.org/wiki/Tail_recursion" target="_blank" title="Tail Recursion">tail recursive</a> calls.</p>
<p>Strength reduction can already handle about 55 different cases at the moment. For instance it will convert code like <code>if( x - 1 == 0 )</code> into <code>if( x == 1 )</code>. But it will also remove expressions that other optimizations could introduce. <code>x + 0</code> is something that might occur during inline expansion. Or <code>x + Number.NaN</code> for example. </p>
<p>But I really like the tail recursive optimizations. TAAS can detect if a method needs to call itself or not. Take this code for example:<br />
<code>
<pre>private function sum( i: int, value: int ): int
{
	if( i == 0 )
	{
		return value;
	}

	return sum( i - 1, value + i );
}
</pre>
<p></code></p>
<p>You see that the last statement <code>sum( i - 1, value + i )</code> is tail recursive. This means we can replace the recursive call to <code>sum()</code> with a jump to the beginning of the method after changing the method parameters. The <code>sum()</code> method becomes converted to something like a simple while loop. This means also that one could have written code like this in the first place since this optimization applies only to methods that do not have to be recursive after all.</p>
<p>Knock yourself out with some examples:</p>
<ul>
<li><a href="http://www.joa-ebert.com/swfs/taas/b00" target="_blank">Before</a> / <a href="http://www.joa-ebert.com/swfs/taas/a00" target="_blank">After</a> (Inline)</li>
<li><a href="http://www.joa-ebert.com/swfs/taas/b01" target="_blank">Before</a> / <a href="http://www.joa-ebert.com/swfs/taas/a01" target="_blank">After</a> (Inline)</li>
<li><a href="http://www.joa-ebert.com/swfs/taas/b02" target="_blank">Before</a> / <a href="http://www.joa-ebert.com/swfs/taas/a02" target="_blank">After</a> (Tail recursion)</li>
</ul>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2009/09/07/taas-progress/" size="standard" count="true"></div></div> <p><a href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=472&amp;md5=5a5d4a856fb529f41231690198c04f53" title="Flattr" target="_blank"><img src="http://blog.joa-ebert.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2009/09/07/taas-progress/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		<atom:link rel="payment" href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=472&amp;md5=5a5d4a856fb529f41231690198c04f53" type="text/html" />
	</item>
		<item>
		<title>First results of TAAS</title>
		<link>http://blog.joa-ebert.com/2009/09/01/first-results-of-taas/</link>
		<comments>http://blog.joa-ebert.com/2009/09/01/first-results-of-taas/#comments</comments>
		<pubDate>Tue, 01 Sep 2009 17:42:00 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[experiments]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[apparat]]></category>
		<category><![CDATA[taas]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=463</guid>
		<description><![CDATA[Finally I am able to present the first results of TAAS. It was a long way to get here. I was actually not sure at all if I will manage to show something at FOTB 09. Let me explain what happens here. In the image is the original ActionScript code on the left. The ActionScript [...]]]></description>
			<content:encoded><![CDATA[<div align="center"><a href="http://blog.joa-ebert.com/wp-content/images/taas_test.gif" target="_self" title="TAAS in action" rel="lightbox[463]"><img src="http://blog.joa-ebert.com/wp-content/images/taas_test_s.gif" width="420" height="187" alt="TAAS in action" border="0"/></a></div>
<p>Finally I am able to present the first results of <a href="http://apparat.googlecode.com/" target="_blank" title="apparat: TAAS">TAAS</a>. It was a long way to get here. I was actually not sure at all if I will manage to show something at <a href="http://www.flashonthebeach.com/" target="_blank" title="FOTB 09">FOTB 09</a>. Let me explain what happens here.</p>
<p>In the image is the original ActionScript code on the left. The ActionScript bytecode produced by the ASC is in the middle and the compiled TAAS version is on the right. You see that I am running a loop and call a method inside that loop. It would be nice to have small helper methods like this one inlined automatically. TAAS can do this for you now.</p>
<p>So how does this work? First of all an SWF file is parsed and the bytecode is extracted. This bytecode is transformed into a <a href="http://en.wikipedia.org/wiki/Control_flow_graph" target="_blank" title="Control flow graph">control flow graph</a>. This control flow graph is converted into a graph of TAAS expressions which a lot of benifits. The conversion step works like the Flash Player and kind of executes your code. The result is that all methods and local variables are typed if that is possible.</p>
<p>It is much easier to perform a lot of optimizations now. Like <a href="http://en.wikipedia.org/wiki/Inline_expansion" target="_blank" title="Inline Expansion">inline expansion</a>. In order to do that I can simply compile the method that is called to TAAS and connect the vertices together in the graph after some adjustments have been made. The inline expansion step will automatically inline methods when it thinks it is useful and possible. You can only inline methods that are private or final and make no use of reflections.</p>
<p>Inlined methods create a lot of overhead. Usually they contribute additional local variables and the code gets bigger. So one step after the inline expansion is to clean everything up again. In this example I can remove those registers thanks to <a href="http://en.wikipedia.org/wiki/Copy_propagation" title="Copy propagation" target="_blank">copy propagation</a> and <a href="http://en.wikipedia.org/wiki/Dead_code_elimination" target="_blank" title="Dead code elimination">dead code elimination</a>.<br />
And it gets even better. If you take a closer look at the example, the <code>calc</code> method expects two paramters that are of type <code>Number</code>. Therefore the original method uses an <code>Add</code> instruction. TAAS knows about the types and sees that it will pass two integers into this method. Since it makes no sense to convert from <code>int</code> to <code>Number</code> to <code>int</code> it stays with integer in this case.</p>
<p>So after inlining the method ends up with even less local variables. The original local variable <code>t1</code> is considered useless since it is only used one time. TAAS will put the code <code>getTimer()</code> at the position where <code>t1</code> has been used and we end up with a heavily optimized method. What I like the most is that I do not have to change the way I write my ActionScript code. All happens behind the scenes automatically.<br />
Some other optimizations are implicit. TAAS will use <code>AddInt</code> instead of <code>Add</code> if both operands are typed <code>int</code>. A <a href="http://code.google.com/p/apparat/wiki/TaasProposals" target="_blank" title="TAAS Proposals">FlowOptimizer</a> is also involved and will invert the if expression for the loop. This can reduce the number of required jumps in a method by 50%.</p>
<p>I know that the output is not perfect. But this is all a work in progress and really the first result that I can share. The SWFs speak for them self.</p>
<ul>
<li><a href="http://www.joa-ebert.com/swfs/taas/before" target="_blank" title="Before TAAS">Before</a></li>
<li><a href="http://www.joa-ebert.com/swfs/taas/after" target="_blank" title="After TAAS">After</a></li>
</ul>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2009/09/01/first-results-of-taas/" size="standard" count="true"></div></div> <p><a href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=463&amp;md5=6731797bc118015b8d95d9ddf806c82f" title="Flattr" target="_blank"><img src="http://blog.joa-ebert.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2009/09/01/first-results-of-taas/feed/</wfw:commentRss>
		<slash:comments>27</slash:comments>
		<atom:link rel="payment" href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=463&amp;md5=6731797bc118015b8d95d9ddf806c82f" type="text/html" />
	</item>
		<item>
		<title>TDSI Examples</title>
		<link>http://blog.joa-ebert.com/2009/08/05/tdsi-examples/</link>
		<comments>http://blog.joa-ebert.com/2009/08/05/tdsi-examples/#comments</comments>
		<pubDate>Wed, 05 Aug 2009 13:53:59 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[experiments]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[alchemy]]></category>
		<category><![CDATA[lorenz attractor]]></category>
		<category><![CDATA[tdsi]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=403</guid>
		<description><![CDATA[Everyone likes examples. So here are three examples using TDSI. The archive includes a ready-to-go FDT project with post-compile ANT tasks configured. Example01 This is the old code of the already optimized attractor using the Memory API instead of a Vector.&#60;uint&#62;. Example02 In this case there exists no Particle class at all and no linked [...]]]></description>
			<content:encoded><![CDATA[<p>Everyone likes examples. So here are three examples using TDSI. The archive includes a ready-to-go FDT project with post-compile ANT tasks configured.</p>
<h3><a href="http://www.joa-ebert.com/swfs/alchemy/Example01" target="_blank">Example01</a></h3>
<p>This is the old code of the already optimized attractor using the Memory API instead of a <code>Vector.&lt;uint&gt;</code>.</p>
<h3><a href="http://www.joa-ebert.com/swfs/alchemy/Example02" target="_blank">Example02</a></h3>
<p>In this case there exists no Particle class at all and no linked list. The particle information is stored inside the memory as well. Particles are extended to a fourth value so indexing a particle can be done with a simple bitshift which is very fast.</p>
<h3><a href="http://www.joa-ebert.com/swfs/alchemy/Example03" target="_blank">Example03</a></h3>
<p>The last example uses float instead of double values for the particles. The framerate stays the same which is really cool because the memory usage drops. Before a particle consisted of four doubles which is a total of <code>4 * 8b = 32b</code>. In this example each particle takes up only <code>16b</code>. There the memory difference is <code>0x4B0000b</code> which is about <code>4.7mb</code> in total.<br />
And also the first version needs about <code>20mb</code> on my machine which means about <code>12mb</code> of RAM are not wasted.  Pretty cool when thinking about devices with less memory.</p>
<p>By the way I just stumpled across a bug when using <code>[Embed]</code>. Hopefully it will be easy to fix.</p>
<ul>
<li><a href="http://www.joa-ebert.com/files/swf/alchemy/alchemy.example.zip" target="_blank">Download Examples</a></li>
</ul>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2009/08/05/tdsi-examples/" size="standard" count="true"></div></div> <p><a href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=403&amp;md5=dab5c584fb75f7051e51700c6c736d8b" title="Flattr" target="_blank"><img src="http://blog.joa-ebert.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2009/08/05/tdsi-examples/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<atom:link rel="payment" href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=403&amp;md5=dab5c584fb75f7051e51700c6c736d8b" type="text/html" />
	</item>
		<item>
		<title>TurboDieselSportInjection</title>
		<link>http://blog.joa-ebert.com/2009/08/05/turbodieselsportinjection/</link>
		<comments>http://blog.joa-ebert.com/2009/08/05/turbodieselsportinjection/#comments</comments>
		<pubDate>Wed, 05 Aug 2009 11:03:51 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[experiments]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[abc]]></category>
		<category><![CDATA[alchemy]]></category>
		<category><![CDATA[bytecode]]></category>
		<category><![CDATA[inline]]></category>
		<category><![CDATA[taas]]></category>
		<category><![CDATA[tdsi]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=401</guid>
		<description><![CDATA[I am definitly not good at choosing names for software projects. However TurboDieselSportInjection is a release of my experiments from yesterday. It is a spinoff from the whole framework and allows you to inline __bytecode and of course to use the new Memory API. Hopefully you are kind enough to provide me with some feedback. [...]]]></description>
			<content:encoded><![CDATA[<p>I am definitly not good at choosing names for software projects. However TurboDieselSportInjection is a release of my experiments from yesterday. It is a spinoff from the whole framework and allows you to inline <code>__bytecode</code> and of course to use the new Memory API.</p>
<p>Hopefully you are kind enough to provide me with some feedback. I am especially interested in Exceptions that occur when reading or writing ABC files. Have fun!</p>
<ul>
<li><a href="http://www.joa-ebert.com/files/zip/tdsi.zip" target="_blank" title="TDSI Download">Download</a></li>
</ul>
<p><b>Update:</b> TDSI is now <a href="http://blog.joa-ebert.com/2009/08/11/apparat-is-now-open-source/" target="_self" title="Apparat is now Open Source">open source</a>!</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2009/08/05/turbodieselsportinjection/" size="standard" count="true"></div></div> <p><a href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=401&amp;md5=a7697b4e320b7586ad3300827c64332d" title="Flattr" target="_blank"><img src="http://blog.joa-ebert.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2009/08/05/turbodieselsportinjection/feed/</wfw:commentRss>
		<slash:comments>50</slash:comments>
		<atom:link rel="payment" href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=401&amp;md5=a7697b4e320b7586ad3300827c64332d" type="text/html" />
	</item>
		<item>
		<title>Alchemy for ActionScript</title>
		<link>http://blog.joa-ebert.com/2009/08/05/alchemy-for-actionscript/</link>
		<comments>http://blog.joa-ebert.com/2009/08/05/alchemy-for-actionscript/#comments</comments>
		<pubDate>Tue, 04 Aug 2009 22:34:26 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[experiments]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[as3c]]></category>
		<category><![CDATA[asm]]></category>
		<category><![CDATA[bytecode]]></category>
		<category><![CDATA[inline]]></category>
		<category><![CDATA[taas]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=398</guid>
		<description><![CDATA[Today I had to do something else than backend development and since FOTB is getting closer and I could not really continue working on TAAS I decided to add something which is easy to implement and has a huge benifit: Alchemy support in ActionScript. So what is the idea? TAAS is part of a framework [...]]]></description>
			<content:encoded><![CDATA[<p>Today I had to do something else than backend development and since <a href="http://www.flashonthebeach.com/" target="_blank" title="FOTB 2009">FOTB</a> is getting closer and I could not really continue working on <a href="http://blog.joa-ebert.com/tag/taas/" target="_self" title="Posts tagged TAAS">TAAS</a> I decided to add something which is easy to implement and has a huge benifit: Alchemy support in ActionScript.</p>
<p>So what is the idea? TAAS is part of a framework I developed to manipulate SWF, SWC and ABC files. The main focus are of course ABC files since they contain the bytecode which gets executed.<br />
Part of the framework are tools for control flow analysis, various bytecode analyzers and also a search-and-replace system which work on a bytecode level. There are for instance pattern matchers that search for bad code produced by the ASC and replace the match with a more performant set of instructions.</p>
<p>With all those weapons in my arsenal I thought it should be a walk in the park to implement the Alchemy features in a way that makes sense. So the first idea is to have the old functionality <a href="http://as3c.googlecode.com/" target="_blank" title="AS3C">AS3C</a> had but more robust. AS3C had a feature that was the <code>__asm</code> function which allowed you to inline instructions. The new framework comes with the old <code>__asm</code> and also another cool method: <code>__bytecode</code>! This will inline raw bytes. This means also you would have to know all the indices for variables you want to use from the constant pool in advance so <code>__asm</code> will still be your friend.</p>
<p>With the <code>__bytecode</code> method it is already possible to use all Alchemy features again. It would also be possible with the <code>__asm</code> method but writing plain bytes is simply more elitist. In order to make it easy for the developer I want a high-level API. Having a class with some static methods is nice of course but also slow. Alchemy is fast because those opcodes that write and read from a ByteArray are no method calls. They are low-level FlashPlayer features.</p>
<p><a href="http://blog.joa-ebert.com/wp-content/images/inline_big.png" target="_self" rel="lightbox[398]"><img style="float: left; padding-right: 3px" src="http://blog.joa-ebert.com/wp-content/images/inline_small.png" border="0"/></a>The first attempt was to write a Memory class that allows you to use the Alchemy features. This class contains raw bytecode implementations and ActionScript code. This means if you do not use the optimizer everything will still work &#8212; only 1000 times slower. When looking at the memory class there is another tool of the framework that becomes very helpful. Both the <code>__bytecode</code> and ActionScript stuff should not co-exist with each other. So when we inline the bytecode a dead-code-elimination will simply cleanup afterwards. Since the <code>0x47</code> byte for instance is &#8220;ReturnVoid&#8221; the ActionScript code which would follow afterwards can be dropped. That code is now unreachable.</p>
<p>Step two is to replace all calls to the Memory class with the correct Alchemy opcode. This was really simple and the result is a really really fast way to access a ByteArray while still maintaining a high comfort. Of course one might think now that the <code>__bytecode</code> method becomes useless since no methods of the Memory class are called at all. But if anyone is crazy enough to access the Memory class untyped with a runtime namespace for instance you are still happy to have the code optimized inside. In some circumstances it is simply impossible to figure out that someone called <code>Memory.writeByte()</code>. End of the story: your calls to a ByteArray are always optimized in the best way possible.</p>
<p>This is an example of the <code>Memory.readByte()</code> method before applying optimizations:<br />
<code>
<pre>
0x000000       GetLocal0
0x000001       PushScope
0x000002       FindPropStrict       QName(PackageNamespace("com.joa_ebert.abc.bytecode.asbridge"), "__bytecode")
0x000004       PushShort            0xd1
0x000007       PushByte             0x35
0x000009       PushByte             0x48
0x00000b       CallPropVoid         QName(PackageNamespace("com.joa_ebert.abc.bytecode.asbridge"), "__bytecode"), 3
0x00000e       GetLex               QName(PackageNamespace("flash.system"), "ApplicationDomain")
0x000010       GetProperty          QName(PackageNamespace(""), "currentDomain")
0x000012       GetProperty          QName(PackageNamespace(""), "domainMemory")
0x000014       GetLocal1
0x000015       SetProperty          QName(PackageNamespace(""), "position")
0x000017       GetLex               QName(PackageNamespace("flash.system"), "ApplicationDomain")
0x000019       GetProperty          QName(PackageNamespace(""), "currentDomain")
0x00001b       GetProperty          QName(PackageNamespace(""), "domainMemory")
0x00001d       CallProperty         QName(PackageNamespace(""), "readUnsignedByte"), 0
0x000020       ReturnValue
</pre>
<p></code></p>
<p>The same method after inlining the bytes and applying various other analysis like dead-code-elimination:<br />
<code>
<pre>
0x000000       GetLocal0
0x000001       PushScope
0x000000       GetLocal1
0x000001       GetByte
0x000002       ReturnValue
</pre>
<p></code></p>
<p>This is an example of the famous inverse square root using the Memory API:<br />
<code>
<pre>
private function invSqrt( value: Number ): Number
{
	var half: Number = 0.5 * value;
	Memory.writeFloat( value, 0 );
	Memory.writeInt( 0x5f3759df - ( Memory.readInt( 0 ) >> 1 ), 0 );
	value = Memory.readFloat( 0 );
	value = value * ( 1.5 - half * value * value );
	return value;
}
</pre>
<p></code></p>
<p>The same method before optimization in bytecode representation:<br />
<code>
<pre>
0x000000       GetLocal0
0x000001       PushScope
0x000002       PushDouble           0.5
0x000004       GetLocal1
0x000005       Multiply
0x000006       ConvertDouble
0x000007       SetLocal2
0x000008       GetLex               QName(PackageNamespace("com.joa_ebert.abc.bytecode.asbridge"), "Memory")
0x00000a       GetLocal1
0x00000b       PushByte             0x0
0x00000d       CallPropVoid         QName(PackageNamespace(""), "writeFloat"), 2
0x000010       GetLex               QName(PackageNamespace("com.joa_ebert.abc.bytecode.asbridge"), "Memory")
0x000012       PushInt              0x5f3759df
0x000014       GetLex               QName(PackageNamespace("com.joa_ebert.abc.bytecode.asbridge"), "Memory")
0x000016       PushByte             0x0
0x000018       CallProperty         QName(PackageNamespace(""), "readInt"), 1
0x00001b       PushByte             0x1
0x00001d       ShiftRight
0x00001e       Subtract
0x00001f       PushByte             0x0
0x000021       CallPropVoid         QName(PackageNamespace(""), "writeInt"), 2
0x000024       GetLex               QName(PackageNamespace("com.joa_ebert.abc.bytecode.asbridge"), "Memory")
0x000026       PushByte             0x0
0x000028       CallProperty         QName(PackageNamespace(""), "readFloat"), 1
0x00002b       ConvertDouble
0x00002c       SetLocal1
0x00002d       GetLocal1
0x00002e       PushDouble           1.5
0x000030       GetLocal2
0x000031       GetLocal1
0x000032       Multiply
0x000033       GetLocal1
0x000034       Multiply
0x000035       Subtract
0x000036       Multiply
0x000037       ConvertDouble
0x000038       SetLocal1
0x000039       GetLocal1
0x00003a       ReturnValue
</pre>
<p></code></p>
<p>The same method after inlining the Memory API:<br />
<code>
<pre>
0x000000       GetLocal0
0x000001       PushScope
0x000002       PushDouble           0.5
0x000004       GetLocal1
0x000005       Multiply
0x000006       ConvertDouble
0x000007       SetLocal2
0x00000a       GetLocal1
0x00000b       PushByte             0x0
0x000000       SetFloat
0x000012       PushInt              0x5f3759df
0x000016       PushByte             0x0
0x000000       GetInt
0x00001b       PushByte             0x1
0x00001d       ShiftRight
0x00001e       Subtract
0x00001f       PushByte             0x0
0x000000       SetInt
0x000026       PushByte             0x0
0x000000       GetFloat
0x00002b       ConvertDouble
0x00002c       SetLocal1
0x00002d       GetLocal1
0x00002e       PushDouble           1.5
0x000030       GetLocal2
0x000031       GetLocal1
0x000032       Multiply
0x000033       GetLocal1
0x000034       Multiply
0x000035       Subtract
0x000036       Multiply
0x000037       ConvertDouble
0x000038       SetLocal1
0x000039       GetLocal1
0x00003a       ReturnValue
</pre>
<p></code></p>
<p>As you can see this is blazing fast. Now the next job is to finish TAAS. Once TAAS is complete even a method like the inverse square root might be inlined and optimized  much better. I did a simple test using the <a href="http://blog.joa-ebert.com/2009/04/03/massive-amounts-of-3d-particles-without-alchemy-and-pixelbender/" target="_blank">Lorenz attractor</a> from before and replacing the <code>Vector.&lt;uint&gt;</code> buffer with a ByteArray gave a performance boost of about 5fps. Afterwards I tried getting rid of the Particle class completly and the framerate dropped a little bit. But imagine having 300.000 particle&#8217;s x, y and z coodrinates stored in an Array. It was still faster than the old version but not as fast as combining the power of Alchemy with simple ActionScript optimizations like linked lists.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2009/08/05/alchemy-for-actionscript/" size="standard" count="true"></div></div> <p><a href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=398&amp;md5=bd2f8704d521897eef1d1771823b5ef3" title="Flattr" target="_blank"><img src="http://blog.joa-ebert.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2009/08/05/alchemy-for-actionscript/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<atom:link rel="payment" href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=398&amp;md5=bd2f8704d521897eef1d1771823b5ef3" type="text/html" />
	</item>
		<item>
		<title>A Simple Method And Taas</title>
		<link>http://blog.joa-ebert.com/2009/06/23/a-simple-method-and-taas/</link>
		<comments>http://blog.joa-ebert.com/2009/06/23/a-simple-method-and-taas/#comments</comments>
		<pubDate>Tue, 23 Jun 2009 14:36:45 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[experiments]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[asc]]></category>
		<category><![CDATA[bytecode]]></category>
		<category><![CDATA[taas]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=383</guid>
		<description><![CDATA[I just want to share with you how Taas can actually optimize code and what happens behind the scenes. So in my last post I talked about stackless code and optimizations that are possible but how does it work at all? Imagine you have got this ActionScript code: var x: Number = 1.0; var y: [...]]]></description>
			<content:encoded><![CDATA[<p>I just want to share with you how Taas can actually optimize code and what happens behind the scenes. So in my last post I talked about stackless code and optimizations that are possible but how does it work at all?<br />
Imagine you have got this ActionScript code:</p>
<pre><code>var x: Number = 1.0;
var y: Number;

if(true)
{
	y = 3.0;
}
else
{
	y = 2.0;
}

x += y;

return x;</code></pre>
<p>For the sake of simplicity I will not use local variables in the bytecode. But it will be easier to figure out what happens in the bytecode.</p>
<pre><code>      PushDouble           1.0
      PushTrue
      IfTrue               L0

      PushDouble           2.0
      Jump                 L1

L0:   PushDouble           3.0
L1:   Add
      ReturnValue</code></pre>
<p>This bytecode is nearly the same as the method but without local variables. This should be fairly simple to understand.</p>
<p><a href="http://blog.joa-ebert.com/wp-content/images/taas/bytecode_taas_cfg.png" target="_blank" rel="lightbox[383]"><img src="http://blog.joa-ebert.com/wp-content/images/taas/bytecode_taas_cfg_s.png" border="0" style="float: left; padding-right: 3px"/></a>When converting bytecode to Taas, its corresponding control flow graph is converted into a control flow graph of Taas expressions. I do not want to go into much detail how the stack based code is converted but <a href="http://blog.joa-ebert.com/wp-content/images/taas/bytecode_taas_cfg.png" target="_blank" rel="lightbox[383]">here</a> is the graph before and after the transformation from bytecode to Taas. It looks quite similar but there is a major difference. All those constant values in the Taas graph are not values pushed on a stack but assignments to virtual variables which exist only in theory. You can see also that the <code>Add</code> in the bytecode has known operands and type in the Taas version. Since it is currently not know if <code>2.0</code> or <code>3.0</code> has been used there is a Φ function that says &#8220;This value is either 2.0 or 3.0 depending on the path taken at runtime&#8221;.</p>
<p>So as I said this code can be optimized much better than stack based code. This graph is very redundant. There are three utilities to compact and simplify the current graph of Taas expressions. The algorithm has been developed for Java bytecode but works with ActionScript very well tool. The concept is quite simple. Perform copy propagation, constant folding and dead code elimination until the graph stops changing. Applying these techniques to the Taas graph yields the following results.</p>
<h3><a href="http://en.wikipedia.org/wiki/Copy_propagation" target="_blank">Copy propagation</a>:</h3>
<p>Most of the theoretical variables have been eliminated using copy propagation.</p>
<div align="center"><a href="http://blog.joa-ebert.com/wp-content/images/taas/graph1.png" target="_blank" rel="lightbox[383]"><img src="http://blog.joa-ebert.com/wp-content/images/taas/graph1_s.png"/></a></div>
<h3><a href="http://en.wikipedia.org/wiki/Constant_folding" target="_blank">Constant folding</a>:</h3>
<p>Known constants have been replaced. Even the if condition is no longer needed and the <code>false</code> branch has been removed. The dead code elimination will clean up this code afterwards.</p>
<div align="center"><a href="http://blog.joa-ebert.com/wp-content/images/taas/graph2.png" target="_blank" rel="lightbox[383]"><img src="http://blog.joa-ebert.com/wp-content/images/taas/graph2_s.png"/></a></div>
<h3><a href="http://en.wikipedia.org/wiki/Dead_code_elimination" target="_blank" title="Dead code elimination">Dead code elimination</a>:</h3>
<p>Dead code elimination has removed the dead <code>Jump</code> statement and also the value <code>2.0</code> from the Φ expression. Afterwards constant folding replaced the Φ expression with its one constant value. Then another iteration of constant folding replaced the <code>Add</code> expression with the constant value <code>4.0</code>. Afterwards copy propagation has put the result into the <code>Return</code> statement and voilá.</p>
<div align="center"><a href="http://blog.joa-ebert.com/wp-content/images/taas/graph3.png" target="_blank" rel="lightbox[383]"><img src="http://blog.joa-ebert.com/wp-content/images/taas/graph3.png"/></a></div>
<p>This result may have seemed quite obvious from the beginning and you may ask who writes such code. Probably nobody. But once you start inlining methods this makes a lot of sense. A lot of preconditions are known in that case and unnecessary branches can be removed. Since inlining methods bloats up the code it is very important to compact it afterwards as much as possible. I hope you see now how interesting all of this might be in the future.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2009/06/23/a-simple-method-and-taas/" size="standard" count="true"></div></div> <p><a href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=383&amp;md5=2d7090cfd0521f370ee4d6688b15fe60" title="Flattr" target="_blank"><img src="http://blog.joa-ebert.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2009/06/23/a-simple-method-and-taas/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<atom:link rel="payment" href="http://blog.joa-ebert.com/?flattrss_redirect&amp;id=383&amp;md5=2d7090cfd0521f370ee4d6688b15fe60" type="text/html" />
	</item>
	</channel>
</rss>

