<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Metaphysical Developer</title>
	<atom:link href="http://metaphysicaldeveloper.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://metaphysicaldeveloper.wordpress.com</link>
	<description>Thoughts on Software Development</description>
	<lastBuildDate>Tue, 21 May 2013 04:04:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='metaphysicaldeveloper.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Metaphysical Developer</title>
		<link>http://metaphysicaldeveloper.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://metaphysicaldeveloper.wordpress.com/osd.xml" title="Metaphysical Developer" />
	<atom:link rel='hub' href='http://metaphysicaldeveloper.wordpress.com/?pushpress=hub'/>
		<item>
		<title>WebGL breaking into the real world</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2013/04/23/webgl-breaking-into-the-real-world/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2013/04/23/webgl-breaking-into-the-real-world/#comments</comments>
		<pubDate>Tue, 23 Apr 2013 17:56:41 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[WebGL]]></category>
		<category><![CDATA[webgl]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/?p=606</guid>
		<description><![CDATA[A few weeks ago I attended the Khronos WebGL Meetup during GCD week. It was a pleasure to see how much amazing real companies got real work got done, many in just one year. Here are some of the highlights: Shadertoy A place to share and explore shaders created by many people. Kinda like Github, [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=606&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>A few weeks ago I attended the <a href="http://www.meetup.com/WebGL-Developers-Meetup/events/109291272/?_af_eid=109291272&amp;a=uc1_te&amp;_af=event">Khronos WebGL Meetup</a> during GCD week. It was a pleasure to see how much amazing real companies got real work got done, many in just one year. Here are some of the highlights:</p>
<h2>Shadertoy</h2>
<p><a href="https://www.shadertoy.com/view/XslGRr"><img title="" alt="" src="http://i.imgur.com/ApsmK4R.png" width="80%" height="80%" /></a></p>
<p>A place to share and explore <a href="http://en.wikipedia.org/wiki/Shader">shaders</a> created by many people. Kinda like Github, but for shaders.</p>
<h2>Verold Studio</h2>
<p><a href="http://studio.verold.com/projects/513b2f59daf24d0200000316"><img title="" alt="" src="http://i.imgur.com/W5LzTt5.jpg" width="80%" height="80%" /></a></p>
<p><a href="http://studio.verold.com/projects/filter/featured">Verold</a> is similar to Shadertoy, but for full 3D models.</p>
<h2>Fractured: Fractal Att Studio</h2>
<p><a href="http://fract.ured.me/"><img title="" alt="" src="http://i.imgur.com/S2YQ0dO.png" width="80%" height="80%" /></a></p>
<p>Amazing GPU accelerated fractal exploration tool. More on <a href="http://webcl.nokiaresearch.com/demos.html">their post</a></p>
<h2>Cesium</h2>
<p><a href="http://cesium.agi.com/LotsOfSatellites/"><img title="" alt="" src="http://i.imgur.com/ifiEtYw.jpg" width="80%" height="80%" /></a></p>
<p><a href="http://cesium.agi.com/demos.html">Cesium</a> is an open source virtual globe and map engine (source on <a href="https://github.com/AnalyticalGraphicsInc/cesium">GitHub</a>). They also have an <a href="http://cesium.agi.com/Cesium/Apps/Sandcastle/index.html?src=Animations.html">online InstaREPL</a> like tool.</p>
<h2>Goo Engine</h2>
<p><a href="http://goodemos.com/demos/pb/index.html"><img title="" alt="" src="http://i.imgur.com/6hzpIYY.png" width="80%" height="80%" /></a></p>
<p>Goo engine (which showcases some pretty <a href="http://www.goodemos.com/">good demos</a>) is both an 3D Game Engine in WebGL and a distribution mechanism.</p>
<h2>Play Canvas</h2>
<p><a href="http://apps.playcanvas.com/will/doom3/gangnamstyle"><img title="" alt="" src="http://i.imgur.com/qpKW574.jpg" width="80%" height="80%" /></a></p>
<p><a href="http://playcanvas.com/demos/">Play Canvas</a> is also a 3D Game Engine in WebGL. Their amazing <a href="http://www.crackajack.de/2013/01/09/doom-3-doing-gangnam-style-in-webgl/">Doom 3 Gangnam-Style</a> animation got a lot of attention recently.</p>
<h2>Mozilla running Unreal Engine 3 on WebGL</h2>
<p><a href="https://blog.mozilla.org/blog/2013/03/27/mozilla-is-unlocking-the-power-of-the-web-as-a-platform-for-gaming/"><img title="" alt="" src="http://i.imgur.com/e71D2De.png" width="90%" height="90%" /></a></p>
<p>Mozilla outdoing themselves again. After their great work with <a href="https://developer.cdn.mozilla.net/media/uploads/demos/a/z/azakai/3baf4ad7e600cbda06ec46efec5ec3b8/bananabread_1365612639_demo_package/index.html">Banana Bread shooting game</a>, they, alongside Epic Games, ported <a href="https://en.wikipedia.org/wiki/Unreal_Engine#Unreal_Engine_3_2">Unreal Engine 3</a> to WebGL. Well, WebGL and Emscripten optmized to be compiled to their also recently launched <a href="https://blog.mozilla.org/luke/2013/03/21/asm-js-in-firefox-nightly/">asm.js</a>. It was announced a few days earlier, but the Mozilla team was showcasing some new impressive demos.</p>
<p><strong>Moving towards more widespread adoption</strong><br />
At the end I got to chat with <a href="https://github.com/toji">Brandon</a>, who did some amazing <a href="http://media.tojicode.com/q3bsp">work</a> with <a href="http://blog.tojicode.com/p/demos.html">webgl</a>, and currently works on Google Chrome GPU team helping with WebGL development.</p>
<p>We talked about many things, including ASM.js which had just been announced. I also asked him what was the thing that was impeding WebGL to get more traction, and he shared his two cents: getting gigantic asset deployment is a pain. Most 3d applications have gigabytes of assets, and, comparitevely when you are downloading 2GB assets from Steam, you can go to work, leave your computer at home doing the work, come back, and you are done. Storing the assets and running these long requests on the browser is not yet as frictionless as it could be, and that adds barriers to developers going into WebGL.</p>
<h2>Finally</h2>
<p>If this is not enough, Florian Boesch recently wrote a great post on <a href="http://codeflow.org/entries/2013/feb/02/why-you-should-use-webgl/"><em>Why you should use WebGL</em></a></p>
<br /> Tagged: <a href='http://metaphysicaldeveloper.wordpress.com/tag/webgl-2/'>webgl</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/606/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/606/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=606&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2013/04/23/webgl-breaking-into-the-real-world/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>

		<media:content url="http://i.imgur.com/ApsmK4R.png" medium="image" />

		<media:content url="http://i.imgur.com/W5LzTt5.jpg" medium="image" />

		<media:content url="http://i.imgur.com/S2YQ0dO.png" medium="image" />

		<media:content url="http://i.imgur.com/ifiEtYw.jpg" medium="image" />

		<media:content url="http://i.imgur.com/6hzpIYY.png" medium="image" />

		<media:content url="http://i.imgur.com/qpKW574.jpg" medium="image" />

		<media:content url="http://i.imgur.com/e71D2De.png" medium="image" />
	</item>
		<item>
		<title>Navigating Git Branch History</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2012/10/19/navigating-git-branch-history/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2012/10/19/navigating-git-branch-history/#comments</comments>
		<pubDate>Fri, 19 Oct 2012 17:56:54 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/?p=581</guid>
		<description><![CDATA[In last years I&#8217;ve been collaborating in very large projects using git. More recently, one thing that started annoying me was branch switching, as git shell completion started requiring a lot of cycling over similar named branches. Worse: most of the time I just needed to cycle among a few branches at a time (usually [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=581&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In last years I&#8217;ve been collaborating in very large projects using git. More recently, one thing that started annoying me was branch switching, as <a href="https://github.com/git/git/blob/master/contrib/completion/git-completion.bash">git shell completion</a> started requiring a lot of cycling over similar named branches. Worse: most of the time I just needed to cycle among a few branches at a time (usually one branch I&#8217;m fixing, master for quick experiments on what is in production, and finally my working <a href="http://martinfowler.com/bliki/FeatureBranch.html">feature branch</a>).</p>
<p><a href="http://metaphysicaldeveloper.files.wordpress.com/2012/10/screen-shot-2012-10-19-at-12-31-21-am.png"><img class="aligncenter size-medium wp-image-587" title="Git branch" alt="" src="http://metaphysicaldeveloper.files.wordpress.com/2012/10/screen-shot-2012-10-19-at-12-31-21-am.png?w=300&#038;h=191" height="191" width="300" /></a></p>
<p>Git <a href="http://gitfu.wordpress.com/2008/04/06/git-reflog-no-commits-left-behind/">reflog</a> exposes out a quick way to do this, using the shorthand HEAD@{0}, HEAD@{1}. Unfortunately, this is a bit too fine grained, as commits are recorded into the reflog.</p>
<p>After learning a bit about <a href="http://git-scm.com/docs/githooks">git&#8217;s hooks</a>, I wrote a simple utility called <a href="https://gist.github.com/3904234">git-nav</a> to help me. A sample usage (just put the git-nav script in your path to install):</p>
<pre class="brush: bash; title: ; notranslate">
$ git nav
Creating post-checkout hook...
Already on 'master'
....
$ git commit c1
$ git checkout -b cool-feature
...
$ git commit c2
$ git nav l
Navigation History: (use 'git nav [number]' to go to that point )

1        master
$ git nav
Switched to branch 'master'
...
$ git commit c3
$ git checkout merge cool-feature
....
$ git commit c4
$ git checkout 4e6bc147ee9074998ac0406c1a646d5d3bbeaced
$ git checkout -b quick-fix
$ git-nav
Switched to branch 'master'
$ git nav l
Navigation History: (use 'git nav [number]' to go to that point )

4        master
3        cool-feature
2        master
1        4e6bc147ee9074998ac0406c1a646d5d3bbeaced

$ git nav 3
Switched to branch 'cool-feature'
</pre>
<p>So, it is pretty simple:</p>
<pre>git-nav l : Lists your navigation history.

git-nav [number] : Goes back to your navigation history by number steps.

git-nav : Goes back to last branch. Same as git-nav 1.</pre>
<p>If you think it may help you as well, you can grab it <a href="https://gist.github.com/3904234">here</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/581/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/581/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=581&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2012/10/19/navigating-git-branch-history/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2012/10/screen-shot-2012-10-19-at-12-31-21-am.png?w=300" medium="image">
			<media:title type="html">Git branch</media:title>
		</media:content>
	</item>
		<item>
		<title>Conjcraft: A Minecraft Mod implemented in Clojure</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2012/04/20/conjcraft-a-minecraft-mod-implemented-in-clojure/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2012/04/20/conjcraft-a-minecraft-mod-implemented-in-clojure/#comments</comments>
		<pubDate>Fri, 20 Apr 2012 18:37:59 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[hacking]]></category>
		<category><![CDATA[Languages]]></category>
		<category><![CDATA[Minecraft]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[gaming]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[minecraft]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/?p=516</guid>
		<description><![CDATA[When you don&#8217;t create things, you become defined by your tastes rather than ability. Your tastes only narrow &#38; exclude people. So create. &#8211; why the lucky stiff TL;DR:  Source here, and here a video of the mod in action: Conjcraft Conjcraft is a simple and extensible Mod for Minecraft written in Clojure (and some Java). [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=516&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p style="padding-left:30px;"><em>When you don&#8217;t create things, you become defined by your tastes rather than ability. Your tastes only narrow &amp; exclude people. So create.</em></p>
<p style="padding-left:30px;">&#8211; <a href="http://favstar.fm/users/_why/status/881768089">why the lucky stiff</a></p>
<p>TL;DR:  Source <a href="http://github.com/danielribeiro/conjcraft">here</a>, and here a video of the mod in action:</p>
<span class='embed-youtube' style='text-align:center; display: block;'><iframe class='youtube-player' type='text/html' width='720' height='435' src='http://www.youtube.com/embed/boCbh1jcUgE?version=3&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;showinfo=1&#038;iv_load_policy=1&#038;wmode=transparent' frameborder='0'></iframe></span>
<h2>Conjcraft</h2>
<p><a href="http://github.com/danielribeiro/conjcraft">Conjcraft</a> is a simple and extensible Mod for <a title="Hacking a Gnuplot into Minecraft" href="http://metaphysicaldeveloper.wordpress.com/2011/07/31/hacking-a-gnuplot-into-minecraft/">Minecraft</a> written in <a href="http://clojure.org/">Clojure</a> (and some Java). Besides introducing two new blocks (Clojure and Github, which is hosting the source <a href="http://github.com/danielribeiro/conjcraft">here</a>), it brings an extremely simple and <a href="http://www.manning.com/ghosh/">small DSL</a> for writing Minecraft recipes.</p>
<p><a href="http://metaphysicaldeveloper.files.wordpress.com/2012/04/2012-04-18_02-58-48.png"><img class="aligncenter size-full wp-image-541" title="2012-04-18_02.58.48" alt="" src="http://metaphysicaldeveloper.files.wordpress.com/2012/04/2012-04-18_02-58-48.png?w=720"   /></a></p>
<p>The recipe DSL cleans up on on Minecrafts original one (which is alredy terse for a Java DSL). Compare these simple ones:</p>
<pre class="brush: java; title: ; wrap-lines: false; notranslate">
addRecipe(new ItemStack(Block.rail, 16), new Object[]
                {
                    &quot;X X&quot;, &quot;X#X&quot;, &quot;X X&quot;, 'X', Item.ingotIron, '#', Item.stick
                });
</pre>
<pre class="brush: clojure; title: ; wrap-lines: false; notranslate">
(recipe-dsl {\X :ingotIron \# :stick}
  &quot;X X
   X#X
   X X&quot; 'rail 16)
</pre>
<p>Small explanation: the Clojure version is essentially the ascii art of this <a href="http://www.minecraftwiki.net/wiki/Rail">recipe</a>:</p>
<p><a href="http://metaphysicaldeveloper.files.wordpress.com/2012/04/screen-shot-2012-04-19-at-1-37-29-am.png"><img class="aligncenter size-full wp-image-544" title="Screen Shot 2012-04-19 at 1.37.29 AM" alt="" src="http://metaphysicaldeveloper.files.wordpress.com/2012/04/screen-shot-2012-04-19-at-1-37-29-am.png?w=720"   /></a></p>
<p><strong>Disclaimer: </strong>I&#8217;ll not try to teach Clojure here (besides saying it is a <a href="http://en.wikipedia.org/wiki/Lisp_(programming_language)">Lisp</a>). If you need more info, there are <a href="http://learn-clojure.com">great resources</a> on the <a href="http://www.elangocheran.com/blog/2012/03/the-newbies-guide-learning-clojure">web</a>.</p>
<p>This gain in expressiveness (which is come from the fact that Clojure is extremely more expressive than Java) is compounded in multiple recipes, specially after defining a <a href="http://github.com/danielribeiro/conjcraft/blob/master/recipes.clj#L3">consistent</a> character to block/item mapping:</p>
<pre class="brush: clojure; title: ; wrap-lines: false; notranslate">
(def char-block (create-input-char-binding
                  '(
                     d dirt
                     o cobblestone
                     g github
                     c clojure
                     r redstone
                     )))
</pre>
<p>Many <a href="http://github.com/danielribeiro/conjcraft/blob/master/recipes.clj#L35">recipes</a> can use them:</p>
<pre class="brush: clojure; title: ; wrap-lines: false; notranslate">
(defn recipes []
  (recipe-dsl char-block
     &quot;d
      d&quot; 'github

     &quot;o
      o&quot; 'clojure

     &quot;c
      c
      c&quot; 'swordGold

     &quot;c c
      c c&quot; 'bootsGold

     &quot;cgc
      cgc&quot; 'bootsDiamond

     &quot;ccc
      c c
      c c&quot; 'legsGold

     &quot;ccc
      cgc
      cgc&quot; 'legsDiamond
    ))
</pre>
<p>And finally, all of this is encoded in plain text Clojure files, stored in the conjcraft directory inside  <a href="http://www.mindspring.com/~mgrand/java-system-properties.htm"> user.home</a> (which on Linux and Mac OS it is usually the user&#8217;s home directory, aka ~).</p>
<p>This way Conjcraft is <em>very extensible</em>, as it allows <em>the users</em> to add blocks and recipes, without requiring Eclipse or MCP, or to recompile and obfuscate the de-obfuscated Java code.</p>
<p>Such simplicity, though, did not come easily&#8230;</p>
<h2>Origins</h2>
<p>One of the things that has always amazed me about Minecraft is how simple its concept is. I believe this simplicity is actually paramount to its success: by giving you very solid and small building blocks (no pun intended), the game steps away and let the user create its own goals and be shine on its own.</p>
<p>This simplicity also lets other developers step in and create a <a href="http://www.minecraftdl.com/">huge variety of amazing mods</a> (out of which, one my personal favorites is the <a href="http://www.youtube.com/watch?v=86kXJ73q3q0">Aether mod</a>, for being a very ambitious project, and showing how much great content you can create on top of such a simple and powerful platform).</p>
<span class='embed-youtube' style='text-align:center; display: block;'><iframe class='youtube-player' type='text/html' width='720' height='435' src='http://www.youtube.com/embed/cl3_OLFfbfg?version=3&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;showinfo=1&#038;iv_load_policy=1&#038;wmode=transparent' frameborder='0'></iframe></span>
<p><a href="http://blip.tv/clojure/stuart-halloway-simplicity-ain-t-easy-4842694">&#8220;Simplicity Ain&#8217;t Easy&#8221;</a>: <a href="http://thinkrelevance.com/team/members/stuart-halloway">Stuart Halloway</a> masterfully made this argument, exploring what simple is (one of the key points being that <em>simple</em> is <em>&#8220;not compound”</em>), its importance, and how Clojure is a simple language, which actually makes it very powerful. Inspired on the simplicity and power of both Clojure and Minecraft (and <a title="Implementing Minecraft in WebGL" href="http://metaphysicaldeveloper.wordpress.com/2011/12/20/implementing-minecraft-in-webgl/">continuing</a> my <a title="Hacking a Gnuplot into Minecraft" href="http://metaphysicaldeveloper.wordpress.com/2011/07/31/hacking-a-gnuplot-into-minecraft/">healthy</a>(?) obsession with Minecraft and <a title="ClojureScript vs Coffeescript" href="http://metaphysicaldeveloper.wordpress.com/2011/08/28/clojurescript-vs-coffeescript/">Clojure</a>) it seemed only natural for me to set to create a simple mod on top of both platforms (natural because both of them run on top of JVM).</p>
<p>Modding Minecraft with Java is quite straightforward with the help of <a href="http://mcp.ocean-labs.de/index.php/Main_Page">Minecraft Coder Pack</a> (aka MCP) and <a href="http://www.minecraftdl.com/modloader-risugami-downloads/">ModLoader</a>. Calling clojure from Java is also <a href="http://blog.jayfields.com/2011/12/clojure-java-interop.html">very straightforward</a>, to the point that you basically need a Java class like this:</p>
<pre class="brush: java; title: ; wrap-lines: false; notranslate">
public class mod_Conjcraft extends BaseMod {
    public void load() {
        try {
            File file = new File(new File(System.getProperty(&quot;user.home&quot;), &quot;conjcraft&quot;), &quot;conjcraft_main.clj&quot;);
            System.out.println(&quot;Loading clojure mod files from &quot; + file.getAbsolutePath());
            clojure.lang.Compiler.loadFile(file.getAbsolutePath());
            clojure.lang.RT.var(&quot;conjcraft&quot;, &quot;call&quot;).invoke();
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }
}
</pre>
<p>And then I was able to create a very small function, in 5 lines of Clojure, to add a recipe that would take one block off dirt and output 7 blocks of dirt:</p>
<pre class="brush: clojure; title: ; wrap-lines: false; notranslate">
(ns conjcraft)
(import '(net.minecraft.src Block ModLoader ItemStack))
(defn call []
  (let [dirt Block/dirt]
    (ModLoader/addRecipe (ItemStack. dirt 7) (to-array [&quot;#&quot; \# dirt]))))
</pre>
<p>This actually works pretty well when using Eclipse, or the recompile.sh script that comes with MCP. The fun really began when I started preparing to release it&#8230;</p>
<h2>The 1st rule of the Obfuscator Club is:</h2>
<p><a href="http://metaphysicaldeveloper.files.wordpress.com/2012/04/alicedown.jpeg"><img class="aligncenter size-medium wp-image-552" title="alicedown" alt="" src="http://metaphysicaldeveloper.files.wordpress.com/2012/04/alicedown.jpeg?w=300&#038;h=268" width="300" height="268" /></a></p>
<p><em>You can&#8217;t defeat the obfuscator</em>. This is actually really important. Minecraft is obfuscated in its original distribution, which makes a lot of sense for a proprietary and commercial game. MCP tools de-obfuscate the original java code from its original form, giving methods and classes names very straightforward and sensible names.</p>
<p>The problem is that, in general, gamers will need your mod in the obfuscate code, as they game expects classes to use the obfuscated names. Therefore you absolutely must obfuscate your mod.</p>
<h2>The 2nd rule of the Obfuscator Club is:</h2>
<p><em>You <strong>can&#8217;t</strong> defeat the obfuscator</em>.</p>
<p><a href="http://metaphysicaldeveloper.files.wordpress.com/2012/04/obfuscate.jpg"><img class="aligncenter size-medium wp-image-553" title="obfuscate" alt="" src="http://metaphysicaldeveloper.files.wordpress.com/2012/04/obfuscate.jpg?w=240&#038;h=300" width="240" height="300" /></a></p>
<p>Clojure does have the capability of generating .class files with its <a href="http://clojure.org/compilation">Ahead of Time</a> (AOT) compiler.  Since the obfuscator does not operate on java source code, but on .class files, this could have helped. But it doesn&#8217;t. Other languages that run on JVM like <a href="http://www.scala-lang.org/">Scala</a> (which compiles to pretty Java-like bytecode) and <a href="http://www.mirah.org/">Mirah</a> (which can even compile to Java source code) can actually get around the obfuscator this way, as long as you don&#8217;t use features that require <a href="http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29">reflection</a>.</p>
<p>To understand why it doesn&#8217;t work with Clojure, let me show you what this simple AOT example:</p>
<pre class="brush: clojure; title: ; wrap-lines: false; notranslate">
(ns core
  (:gen-class :main true))

(defn -main []
  (println &quot;Hello World!&quot;))
</pre>
<p>With some help of <a href="http://java.decompiler.free.fr/?q=jdgui">JD-GUI</a> we can see the equivalent Java code of the generated class files, in particular:</p>
<pre class="brush: java; title: ; wrap-lines: false; notranslate">
public class core
{
  private static final Var main__var = Var.internPrivate(&quot;core&quot;, &quot;-main&quot;);
  private static final Var equals__var = Var.internPrivate(&quot;core&quot;, &quot;-equals&quot;);
  private static final Var toString__var = Var.internPrivate(&quot;core&quot;, &quot;-toString&quot;);
  private static final Var hashCode__var = Var.internPrivate(&quot;core&quot;, &quot;-hashCode&quot;);
  private static final Var clone__var = Var.internPrivate(&quot;core&quot;, &quot;-clone&quot;);
</pre>
<p>These seemly innocuous lines actually break in runtime. This happens because the obfuscator has another very important property: it puts everything on top level namespace (no packages). Note that the package &#8220;core&#8221; is written as a literal string, which the obfuscator will <em>not</em> touch. And currently there is no way to use AOT with <em>empty</em> namespaces</p>
<p>You could change the Clojure <a href="http://github.com/clojure/clojure">compiler</a>, or use tools to <a href="http://www.csg.ci.i.u-tokyo.ac.jp/~chiba/javassist/">manipulate</a> the byte code on the class files, but there is actually a much simpler solution:</p>
<h2>Breaking the rules: Defeating the Obfuscator</h2>
<p>Clojure is famous for supporting one of the most powerful types of <a href="http://en.wikipedia.org/wiki/Metaprogramming">metaprogramming</a>: <a href="http://en.wikipedia.org/wiki/Metaprogramming#Macro_systems">template macros</a>. I have not exploited it on the project because macros can be very hard to understand (think of them as functions that take code in its raw <a href="http://en.wikipedia.org/wiki/Abstract_Syntax_Tree">Abstract Syntax Tree</a> form, and output another raw <a href="http://en.wikipedia.org/wiki/Abstract_Syntax_Tree">Abstract Syntax Tree</a>), and I wanted to keep the project very accessible.</p>
<p><img class="aligncenter" alt="" src="http://upload.wikimedia.org/wikipedia/en/b/ba/DrawingHands.jpg" width="325" height="281" /></p>
<p>The point is that I used Clojure to generate Java source code, on compile time (the type of metaprogramming you always have the option to use, no matter the platform or base language you are based on).</p>
<p>This is done by the <a href="http://github.com/danielribeiro/conjcraft/blob/master/create_constants.clj">create_constants.clj</a> script, which actually imports the de-obfuscated code and generates a Java file mapping all block, item and material names to their actual objects (the result cannot be published without breaking both Minecraft and MCP licenses, but reading the code you can get an idea of what the result looks like).</p>
<p>Using the property highlighted before, that the literal strings will not be obfuscated, and knowing that the obfuscator will not obfuscate the attribute names of classes you create (only make stripe their package), this static maps are available to be used directly by <em>interpreted</em> Clojure code.</p>
<p>The final element of defeating the obfuscator is the <a href="http://github.com/danielribeiro/conjcraft/blob/master/java/ExtendableBlock.java">ExtendableBlock</a> class. It essentially takes Clojure functions (clojure.lang.IFn interface), and delegate methods to them (some methods have to be re-exposed even when public, as the original public method names will be obfuscated).</p>
<h2>Conclusions</h2>
<p>Modding Minecraft is extremely fun, and it gets a lot more enjoying when doing it in languages that that are fun to use. I&#8217;ve used Clojure here, but there are <a href="http://en.wikipedia.org/wiki/List_of_JVM_languages">many other</a> languages that could have been used. So have fun, and create.</p>
<h2>Thanks</h2>
<p>Thanks <a href="http://notch.tumblr.com/">Notch</a> for making Minecraft and supporting the modding community. Thanks for all the presenters at <a href="http://clojurewest.org/">ClojureWest</a> for inspiring me to bring Clojure to new places. Thanks <a href="http://twitter.com/#!/x2robbie2x">Robert</a> for making one of the best Minecraft modding <a href="http://www.youtube.com/watch?v=Hdm1gVPdaVA">tutorials</a> out there. And finally thanks to all the creators of <a href="http://mcp.ocean-labs.de/index.php/The_MCP_Team">MCP</a> and ModLoader for making modding a simpler and pleasant experience.</p>
<br /> Tagged: <a href='http://metaphysicaldeveloper.wordpress.com/tag/clojure/'>clojure</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/gaming/'>gaming</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/github/'>github</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/minecraft-2/'>minecraft</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/516/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/516/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=516&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2012/04/20/conjcraft-a-minecraft-mod-implemented-in-clojure/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2012/04/2012-04-18_02-58-48.png" medium="image">
			<media:title type="html">2012-04-18_02.58.48</media:title>
		</media:content>

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2012/04/screen-shot-2012-04-19-at-1-37-29-am.png" medium="image">
			<media:title type="html">Screen Shot 2012-04-19 at 1.37.29 AM</media:title>
		</media:content>

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2012/04/alicedown.jpeg?w=300" medium="image">
			<media:title type="html">alicedown</media:title>
		</media:content>

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2012/04/obfuscate.jpg?w=240" medium="image">
			<media:title type="html">obfuscate</media:title>
		</media:content>

		<media:content url="http://upload.wikimedia.org/wikipedia/en/b/ba/DrawingHands.jpg" medium="image" />
	</item>
		<item>
		<title>Implementing Minecraft in WebGL</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2011/12/20/implementing-minecraft-in-webgl/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2011/12/20/implementing-minecraft-in-webgl/#comments</comments>
		<pubDate>Tue, 20 Dec 2011 12:17:22 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[hacking]]></category>
		<category><![CDATA[Minecraft]]></category>
		<category><![CDATA[computational geometry]]></category>
		<category><![CDATA[hacker news]]></category>
		<category><![CDATA[team fortress 2]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/?p=447</guid>
		<description><![CDATA[TL;DR: Source here, live demo here. WebGL is an amazing piece of technology that enables browsers to natively render hardware accelerated 3d creations (yay, no o3d plugin needed!). I&#8217;ve always been specially amazed by what Mr Doob has been doing with his Three.js framework for quite a while (in particular his participation on the ROME project, [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=447&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>TL;DR: Source <a href="https://github.com/danielribeiro/WebGLCraft">here</a>, live demo <a href="http://danielribeiro.github.com/WebGLCraft/">here</a>.</p>
<div id="attachment_462" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.ro.me/" target="_blank"><img class=" wp-image-462    " title="ROME project" alt="ROME project" src="http://metaphysicaldeveloper.files.wordpress.com/2011/12/romeair.jpg?w=300&#038;h=130" height="130" width="300" /></a><p class="wp-caption-text">ROME project</p></div>
<p><a href="http://learningwebgl.com/blog/?page_id=1217">WebGL</a> is an amazing piece of technology that enables browsers to natively render hardware accelerated 3d creations (yay, no <a href="http://code.google.com/p/o3d/">o3d plugin</a> needed!). I&#8217;ve always been specially amazed by what <a href="http://mrdoob.com/">Mr Doob</a> has been doing with his <a href="https://github.com/mrdoob/three.js/">Three.js</a> framework for quite a while (in particular his participation on the <a href="http://www.ro.me/">ROME</a> project, which <a title="ClojureScript vs Coffeescript" href="http://metaphysicaldeveloper.wordpress.com/2011/08/28/clojurescript-vs-coffeescript/">I briefly talked about recently</a>). Nonetheless, there are some other amazing WebGL creations around, such as those featured on <a href="http://www.chromeexperiments.com/">Chrome Experiments</a>, those crafted by <a href="http://oos.moxiecode.com/blog/experiments/javascript-webgl/">OOS</a> and the projects recently presented on <a href="http://blog.thejit.org/2011/12/09/webglcamp/">WebGLCamp</a> (not to mention the amazing <a href="http://blog.tojicode.com/2011/10/source-engine-levels-in-webgl-video.html">Team Fortress 2</a> level vizualizer).</p>
<p>One thing that has bothered me though, throughout all the examples, is the lack of interactivity (one glaring exception was <a href="http://www.glge.org/">GLGE</a>&#8216;s <a href="http://www.glge.org/vehicle-physics-in-webgl-using-glge-and-jiglibjs/">car demo</a>) .</p>
<span class='embed-youtube' style='text-align:center; display: block;'><iframe class='youtube-player' type='text/html' width='720' height='435' src='http://www.youtube.com/embed/r_gIAjVD4Dc?version=3&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;showinfo=1&#038;iv_load_policy=1&#038;wmode=transparent' frameborder='0'></iframe></span>
<p>This seemed to be from the fact the 3d collision is quite a bit more involved than 2d (MIT&#8217;s lecture <a href="http://ocw.mit.edu/courses/mechanical-engineering/2-158j-computational-geometry-spring-2003/lecture-notes/lecnotes10.pdf">notes on Computational Geometry</a>, and even on Doom 3&#8242;s recently released <a href="https://github.com/TTimo/doom3.gpl/blob/master/neo/game/physics/Physics_RigidBody.cpp">source code</a>, can give you an idea of how much involved it can get). And since <a href="http://www.smashinglabs.pl/what-do-we-need-for-html5-games-to-be-awesome">this is considered</a> to be one of the important things  that 3d games need, I was not happy with my hands off <a href="http://news.ycombinator.com/item?id=3037014">answer of this topic</a> on Hacker News. Thus I took the challenge of making a a 3d game in WebGL with collision detection.</p>
<p>Implementing Minecraft Classic (which is <a href="http://www.minecraft.net/classic/play">playable online</a> for free) seemed like a good candidate for such project, as its mechanics are simple, and yet meaningful (not to mention that I am <a title="Hacking a Gnuplot into Minecraft" href="http://metaphysicaldeveloper.wordpress.com/2011/07/31/hacking-a-gnuplot-into-minecraft/">big fan</a> of Notch&#8217;s creation). If you don&#8217;t know anything about Minecraft, I wrote a small <a title="Hacking a Gnuplot into Minecraft" href="http://metaphysicaldeveloper.wordpress.com/2011/07/31/hacking-a-gnuplot-into-minecraft/">intro</a> about it a few months ago.</p>
<p style="text-align:center;"><a href="http://www.youtube.com/watch?v=kn2-d5a3r94" target="_blank"><img class="size-medium wp-image-471 aligncenter" title="minecraftenterprise" alt="Enterprise created in Minecraft" src="http://metaphysicaldeveloper.files.wordpress.com/2011/12/minecraftenterprise1.jpg?w=300&#038;h=168" height="168" width="300" /></a></p>
<p>Three.js was selected as the rendering lib not only because I really like Mr Doob&#8217;s work, but also because it has is quite mature, is open source, has lots of examples and provides a very <a href="http://mrdoob.github.com/three.js/examples/webgl_geometry_minecraft_ao.html">promising starting point</a>: a visualization of a Minecraft world, which includes a <a href="http://mrdoob.github.com/three.js/examples/js/ImprovedNoise.js">noise function</a> for generating it.</p>
<p style="text-align:center;"><a href="http://mrdoob.github.com/three.js/examples/webgl_geometry_minecraft_ao.html" target="_blank"><img class="aligncenter" alt="" src="http://mrdoob.github.com/three.js/assets/examples/webgl_geometry_minecraft.png" /></a></p>
<p>So all that was left was <em>just</em> adding Collision Detection. Well&#8230; this is where things started getting interesting.</p>
<h2>Minecraft Collision Detection Attempt 1: JigLibJS</h2>
<p><a href="http://www.jiglibjs.org/">Jiglibjs</a> is a port of <a href="http://www.jiglibflash.com/blog/">Jiglibflash</a>, which in itself is a port of <a href="http://www.rowlhouse.co.uk/jiglib/">Jiglib</a> for c++. It seemed pretty promising, since there was <a href="http://timothypoon.com/blog/2011/03/08/using-three-js-and-jiglibjs-together/">some people</a> using it (along with three.js), and I had <a title="ClojureScript vs Coffeescript" href="http://metaphysicaldeveloper.wordpress.com/2011/08/28/clojurescript-vs-coffeescript/">great success</a> with using physics libs in the past for 2d games, so it seemed like a natural choice.</p>
<p>After getting it to work with a prototype of the game, it became clear that some things were very wrong. The amazing demos were too simple for Minecraft, and the rotation would get really wrong when walking on simple plane surfaces (something I speculate happening due to some <a href="http://en.wikipedia.org/wiki/Numerical_stability">numerical stability</a> differences from ActionScript and Javascript, alongside with some AS3-&gt; Flash compiler bugs).</p>
<div id="attachment_484" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.jiglibjs.org/demos_official/collisions_similar.htm" target="_blank"><img class="size-medium wp-image-484 " title="Screen Shot 2011-12-19 at 11.32.35 PM" alt="" src="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-19-at-11-32-35-pm.png?w=300&#038;h=133" height="133" width="300" /></a><p class="wp-caption-text">JigLibJS demo</p></div>
<p>After some fun 4 dimension <a href="https://github.com/danielribeiro/WebGLCraft/commit/eb78fbb0a8d2cdaeffefeb5868d65c3cd76f6087#L0L8">matrix hacking</a>, and failing to get around the bugs, I was ready to move on. Thankfully I found another port of JigLibJS which seemed to correct such issues&#8230;</p>
<h2>Minecraft Collision Detection Attempt 2: JigLibJS2</h2>
<p>The fact that someone tried to make a more complex example on JigLibJS, failed, but was tenacious enough to write its own AS3 -&gt; JS compiler to make another port (which worked!) made a very positive impression.</p>
<div class="wp-caption aligncenter" style="width: 352px"><a href="http://www.brokstuk.com/jiglibjs2/" target="_blank"><img class=" " alt="" src="http://www.brokstuk.com/jiglibjs2/screenshot.png" height="269" width="342" /></a><p class="wp-caption-text">JigLibJS2 Vehicle Physics Demo</p></div>
<p>It was also very positive the fact that the interface was almost the same to JigLibJS, making the change to the existing code very small. The problems started to come when trying to make the player cube jump: the cube would not always collide with the bottom plane. This was solved by making <a href="https://github.com/danielribeiro/WebGLCraft/blob/021a83783d6c6ddce86141d76b828a34402f3903/lib/coffee/minecraft.coffee#L201">more collision iterations</a>. Soon enough another problem came up: when trying to move inside an adjacent static cube (even when both the player and the cube were in the same height), sometimes the player would get a rotation. Trying to set it to no rotation every iteration did not actually help, as the player would still sometimes get a vertical velocity when trying to penetrate the block.</p>
<p>Still, rolling my own Physics Engine seemed a bit daunting, and I decided to try out another lib:</p>
<h2>Minecraft Collision Detection Attempt 3:  Ammo.js</h2>
<p><a href="http://granular.cs.umu.se/browserphysics/?p=349">Ammo.js</a> is a port of the C++ physics engine <a href="http://bulletphysics.org/wordpress/">BulletPhysics</a>, that runs on top of the <a href="http://llvm.org/">LLVM</a>&#8216;s Javascript port, aka <a href="https://github.com/kripken/emscripten">Emscripten</a>. Everything looked amazing this time: the <a href="http://granular.cs.umu.se/ammo/Demos/index.html">demos</a> not only looked great, but were very hackable, and had no problems that I previously had.</p>
<div class="wp-caption aligncenter" style="width: 251px"><a href="http://granular.cs.umu.se/ammo/Demos/BoxDemo/index.html" target="_blank"><img alt="" src="http://granular.cs.umu.se/ammo/Demos/BoxDemo/thumb.png" height="241" width="241" /></a><p class="wp-caption-text">Ammo.js Demo</p></div>
<p>But then it came the time to try to get to more Minecrafty world dimensions. It was a bit disappointing when mere 400 cubes made the physics engine go to a crawl (even when using static cubes). It became clear that I needed O(1) collision algorithms, which is very doable for Minecraft Classic, as only the player can move, and there is always a constant amount of cubes the player can collide with at any given time. And now there were no more libs left to evaluate.</p>
<h2>Minecraft Collision Detection Attempt 4:  Rays!</h2>
<p><a href="https://github.com/mrdoob/three.js/issues/424">Rays</a> are the standard way of detecting line/Object collision in Three.js. A very simple interactive <a href="http://oos.moxiecode.com/js_webgl/ray_collision/index.html">demo</a> by OOS seemed like it could do the trick. It had the advantage of being very simple, and constant time (given that I selected the possible blocks to collide with, as the traditional <a href="https://github.com/mrdoob/three.js/blob/master/src/core/Ray.js#L16">Ray.intersectObjects</a> actually tries to intersect all objects on the Scene).</p>
<div id="attachment_491" class="wp-caption aligncenter" style="width: 310px"><a href="http://oos.moxiecode.com/js_webgl/ray_collision/index.html"><img class="size-medium wp-image-491" title="Screen Shot 2011-12-20 at 1.27.12 AM" alt="" src="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-20-at-1-27-12-am1.png?w=300&#038;h=157" height="157" width="300" /></a><p class="wp-caption-text">Ray Collision Demo</p></div>
<p>The OOS example had some issues (like trapping the player cube when jumping up and down, while hodling the forward key). This was solvable by using 12 rays correspoding to the edges of the cube that represented the player. Actually, this did not help all the time, as some rays would not collide with the world blocks if the ray&#8217;s origin inside a blocks&#8217;s face. This is a <a href="https://github.com/mrdoob/three.js/issues/759#issuecomment-2743974">bug</a> yet to be solved, but I got around it by using 24 rays (two directions for every edge of the player cube).</p>
<p>Things were going well enough that I finally moved into adding textures to the game. However, after making the player cuboid have size dimensions to Minecraft&#8217;s, instead of having the same size of the world&#8217;s cube (which was what I was experimenting with so far), I noticed that the ray would give false positives depending on the height position of the cube. This only happened when the numbers were all too exact, instead of with minor deltas, as you&#8217;d expect from using rays cast from the mouse pointer (as it is <a href="http://mrdoob.github.com/three.js/examples/canvas_interactive_cubes.html">usually</a> used on Three.js&#8217; demos).</p>
<p>This, and the fact that collision was taking about half the time of every tick (which was constant, due the improved collision algorithm) made me move on to&#8230;</p>
<h2>Minecraft Collision Detection Attempt 5: Cube Projection</h2>
<p>Up until now I had hopes that I would be able to eventually rotate the player <a href="http://en.wikipedia.org/wiki/Cuboid">cuboid</a> according to its camera. After having so many troubles with so many collision systems, I simplified the problem: collision of unrotated cuboids. This is a really simple problem: from the <a href="http://en.wikipedia.org/wiki/Separating_axis_theorem">Separating Plane Theorem</a>, it is easy to see that  I only need to see if the orthogonal projections of the cuboids, which, from the <a href="http://en.wikipedia.org/wiki/Separating_axis_theorem">Separating Axis Theorem</a>, means I only need to check out if the unrotated rectangles from the projected faces collide, which finally means I only need to check if the projected intervals collide. All of this amounts to <a href="https://github.com/danielribeiro/WebGLCraft/blob/master/lib/collision.coffee">13 lines of Coffeescript</a>:</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
CollisionUtils =
    # The two intervals are [s1, f1] and [s2, f2]
    testIntervalCollision: (s1, f1, s2, f2) -&gt; !(s2 &gt; f1 || s1 &gt; f2)

    #Cubes are objects with vmax, vmin (the vertices with greatest/smallest values)
    #properties. Assumes unrotated cubes.
    testCubeCollision: (cube1, cube2) -&gt;
        fcol = CollisionUtils.testIntervalCollision
        for axis in ['x', 'y', 'z']
            collides = fcol cube1.vmin[axis], cube1.vmax[axis]
            , cube2.vmin[axis], cube2.vmax[axis]
            return false unless collides
        return true

window.CollisionUtils = CollisionUtils
</pre>
<p>Which in retrospect is what I should have tried in the first place. At least I learned some stuff in the process.</p>
<h1>Not quite finished yet: Camera</h1>
<p><a href="http://paulirish.com/">Paul Irish</a> did a pretty amazing job with the Three.js <a href="https://github.com/mrdoob/three.js/blob/f32962f393dc3dd47f9dffaafe5899ca05c5e5ea/src/extras/controls/FirstPersonControls.js">FirstPersonControls.js</a>, which is the one that powers the Three.js Minecraft visualizer. The problem with this camera is that it makes hard to actually play Minecraft, as its default mode is to be always moving, making hard to place/remove blocks. Real Minecraft uses first person shooter camera which cannot be achieved with current browsers, as there is no <a href="https://www.w3.org/Bugs/Public/show_bug.cgi?id=9557">way to trap</a> the user&#8217;s mouse. Nevertheless, Minecraft on Android uses a touch and drag camera that can easily be implemented in JS. This camera works they same way as the one on <a href="http://blog.tojicode.com/">Brandon</a> Jones&#8217; <a href="http://media.tojicode.com/q3bsp/?mobile=1">Quake 3 WebGL</a> implementation.</p>
<div id="attachment_498" class="wp-caption aligncenter" style="width: 310px"><a href="http://media.tojicode.com/q3touch/" target="_blank"><img class="size-medium wp-image-498 " title="Screen Shot 2011-12-20 at 12.49.07 AM" alt="" src="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-20-at-12-49-07-am.png?w=300&#038;h=168" height="168" width="300" /></a><p class="wp-caption-text">Quake 3 demo</p></div>
<p>Therefore I refactored, and <a href="http://js2coffee.org/">converted</a> to Coffeescript, the FirstPersonControls to work as a click and drag camera. The resulting 86 lines of code can be seen <a href="https://github.com/danielribeiro/WebGLCraft/blob/master/lib/camera.coffee">here</a>.</p>
<h1>Adding/Removing Blocks</h1>
<p>This is where Rays worked really well. In fact, Mr. Doob even have a <a href="http://mrdoob.com/projects/voxels/">voxel</a> editor example which shows really well how to make an app that adds/removes cubes on a 3d grid:</p>
<p style="text-align:center;"><a href="http://mrdoob.com/projects/voxels" target="_blank"><img class="   aligncenter" alt="" src="http://metaphysicaldeveloper.files.wordpress.com/2012/11/voxel.png?w=720" /></a></p>
<p>The only issue I&#8217;ve found was that my floor plane was too big, which messed up the Ray/plane collision in certain angles. So I coded this intersection directly:</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
    getCubeOnFloorPosition: (ray) -&gt;
        return null if ray.direction.y &gt;= 0
        ret = vec()
        o = ray.origin
        v = ray.direction
        t = (-o.y) / v.y
        ret.y = 0
        ret.x = o.x + t * v.x
        ret.z = o.z + t * v.z
        return @addHalfCube ret
</pre>
<div id="LC395">
<h1>Conclusions</h1>
<p>I felt the result was quite satifying (the live <a href="http://danielribeiro.github.com/WebGLCraft/">demo</a>, and the <a href="https://github.com/danielribeiro/WebGLCraft">MIT licensed source</a>, can both be found on Github):</p>
<div style="display:inline-block;margin-right:5px;">
<div id="attachment_502" class="wp-caption alignnone" style="width: 250px"><a href="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-17-at-3-00-58-am.png"><img class=" wp-image-502 " title="Screen Shot 2011-12-17 at 3.00.58 AM" alt="" src="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-17-at-3-00-58-am.png?w=240&#038;h=146" height="146" width="240" /></a><p class="wp-caption-text">Minecraft Brick Pyramid</p></div>
</div>
<div style="display:inline-block;">
<div id="attachment_504" class="wp-caption alignright" style="width: 250px"><a href="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-17-at-6-44-36-pm.png"><img class=" wp-image-504 " title="Screen Shot 2011-12-17 at 6.44.36 PM" alt="" src="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-17-at-6-44-36-pm.png?w=240&#038;h=130" height="130" width="240" /></a><p class="wp-caption-text">WebGL Brick Pyramid</p></div>
</div>
</div>
<p>Granted, it starts skipping frames quite often as you add more blocks. The original example from Dr. Doob&#8217;s  didn&#8217;t because he created a single Mesh (aka object scene) composed of all blocks. Doing such would make adding/removing blocks a lot more involved (or force me to handle some area loading/unloading), which is a project in itself. Note that the rendering, and not the collision system, is the real bottleneck at this point.</p>
<p>All of this made me admire Notch&#8217;s work on Minecraft a lot more, as Minecraft <a href="http://www.minecraftwiki.net/wiki/Chunks">can handle over</a> 21&#215;21 loaded chunks of 16x16x128 (over 14 million blocks!) in any given time. The Three.js community had some <a href="https://github.com/mrdoob/three.js/issues/720#issuecomment-2613570">great insights</a> on how to achieve such performance over WebGL, which requires the use of <a href="http://en.wikipedia.org/wiki/Shader">shaders</a>, which are quite low level (even if you use the respective <a href="http://code.google.com/p/threedlibrary/">TDL Google Library</a> for this, or <a href="http://www.haskell.org/haskellwiki/GPipe">GPipe</a> to write the shaders in Haskell), and would probably require a lot of collision code to be also written in also a very low level language (slash GPipe&#8217;s Haskell). I found it also interesting that shaders can be used in <a href="http://granular.cs.umu.se/browserphysics/?p=237">some clever ways</a> to improve JS performance.</p>
<p>And finally, it is important to note that a lot of very people a lot smarter than me have been doing <a href="http://www.khronos.org/webgl/wiki/User_Contributions">some great work</a> to make working with WebGL and making 3d games much simpler.</p>
<p>There are also other renderer libraries besides Three.js: <a href="http://scenejs.org/">Scene.js</a>, <a href="http://senchalabs.github.com/philogl/">PhiloGL</a>, <a href="http://aerotwist.com/a3/">A3</a> (recently presented on the <a href="http://blog.thejit.org/2011/12/09/webglcamp/">WebGL Camp</a>), <a href="http://www.ambiera.com/coppercube/">Coppercube</a> (which is not open source, but can use flash for 3d rendering as well) and <a href="http://www.glge.org/">GLGE</a>.</p>
<p><em><a href="http://news.ycombinator.com/item?id=3376620"><img title="hacker news" alt="" src="http://1.gravatar.com/blavatar/96c849b03aefaf7ef9d30158754f0019?s=20" height="20" width="20" />Hacker News Comments</a></em></p>
<br /> Tagged: <a href='http://metaphysicaldeveloper.wordpress.com/tag/computational-geometry/'>computational geometry</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/hacker-news/'>hacker news</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/team-fortress-2/'>team fortress 2</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/447/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/447/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=447&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2011/12/20/implementing-minecraft-in-webgl/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2011/12/romeair.jpg?w=300" medium="image">
			<media:title type="html">ROME project</media:title>
		</media:content>

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2011/12/minecraftenterprise1.jpg?w=300" medium="image">
			<media:title type="html">minecraftenterprise</media:title>
		</media:content>

		<media:content url="http://mrdoob.github.com/three.js/assets/examples/webgl_geometry_minecraft.png" medium="image" />

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-19-at-11-32-35-pm.png?w=300" medium="image">
			<media:title type="html">Screen Shot 2011-12-19 at 11.32.35 PM</media:title>
		</media:content>

		<media:content url="http://www.brokstuk.com/jiglibjs2/screenshot.png" medium="image" />

		<media:content url="http://granular.cs.umu.se/ammo/Demos/BoxDemo/thumb.png" medium="image" />

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-20-at-1-27-12-am1.png?w=300" medium="image">
			<media:title type="html">Screen Shot 2011-12-20 at 1.27.12 AM</media:title>
		</media:content>

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-20-at-12-49-07-am.png?w=300" medium="image">
			<media:title type="html">Screen Shot 2011-12-20 at 12.49.07 AM</media:title>
		</media:content>

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2012/11/voxel.png" medium="image" />

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-17-at-3-00-58-am.png?w=300" medium="image">
			<media:title type="html">Screen Shot 2011-12-17 at 3.00.58 AM</media:title>
		</media:content>

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2011/12/screen-shot-2011-12-17-at-6-44-36-pm.png?w=300" medium="image">
			<media:title type="html">Screen Shot 2011-12-17 at 6.44.36 PM</media:title>
		</media:content>

		<media:content url="http://1.gravatar.com/blavatar/96c849b03aefaf7ef9d30158754f0019?s=20" medium="image">
			<media:title type="html">hacker news</media:title>
		</media:content>
	</item>
		<item>
		<title>ClojureScript vs Coffeescript</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2011/08/28/clojurescript-vs-coffeescript/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2011/08/28/clojurescript-vs-coffeescript/#comments</comments>
		<pubDate>Sun, 28 Aug 2011 20:16:48 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[hacking]]></category>
		<category><![CDATA[Languages]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[coffeescript]]></category>
		<category><![CDATA[html5]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/?p=420</guid>
		<description><![CDATA[A language that doesn&#8217;t affect the way you think about programming, is not worth knowing &#8211; Alan J. Perlis In the past few years Javascript has gained a lot of attention and ubiquity: HTML5 technologies leverage a lot of Javascript, which enables people to create amazing dream worlds (like the in the ROME project) with [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=420&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p style="padding-left:30px;"><em>A language that doesn&#8217;t affect the way you think about programming, is not worth knowing </em></p>
<p style="padding-left:30px;">&#8211; <a href="http://www-pu.informatik.uni-tuebingen.de/users/klaeren/epigrams.html">Alan J. Perlis</a></p>
<p>In the past few years Javascript has gained a lot of attention and ubiquity: HTML5 technologies leverage a lot of Javascript, which enables people to create amazing <a href="http://googlecode.blogspot.com/2011/05/dreams-in-3d-webgl-experience-for.html">dream worlds</a> (like the in the <a href="http://www.ro.me/tech/">ROME</a> project) with WebGL, V8 brings a lot of <a href="http://en.wikipedia.org/wiki/Just-in-time_compilation">JIT</a> techniques to a JavaScript Virtual Machine which helps Google Chrome be a very fast browser, and powers <a href="http://nodejs.org/">NodeJS</a> (allowing people to create a web page in a single programming language).</p>
<p style="text-align:center;"><a href="http://www.ro.me/" target="_blank"><img class="aligncenter size-full wp-image-429" title="Rome project" src="http://metaphysicaldeveloper.files.wordpress.com/2011/08/rome.png?w=720" alt=""   /></a></p>
<p>Javascript also powers queries in NoSQL databases like <a href="http://www.mongodb.org/display/DOCS/MapReduce#MapReduce-Overview">Mongo</a> and <a href="http://couchdb.apache.org/">CouchDB</a>, and it can be used when making <a href="http://doc.qt.nokia.com/4.7-snapshot/qdeclarativejavascript.html">QT</a> applications, 3d Games in <a href="http://www.unity-tutorials.com/forum/viewtopic.php?p=108">Unity</a> and even mobile apps with frameworks like <a href="http://www.webmynd.com/html5/">WebMynd</a> and <a href="http://www.phonegap.com/">PhoneGap</a>. It has been a long way from the old days when it was confined to the browser, and mostly used for form validation.</p>
<p>In spite of all of this attention, Javascript has been so misunderstood that attention to its <a href="http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742">Good Parts</a> had to drawn. It doesn&#8217;t help that its prototype based OO was first introduced by the rather unknown language <a href="http://en.wikipedia.org/wiki/Self_%28programming_language%29">Self</a>, despite the several advantages it has when compared to traditional class based OO (the paper <a href="http://labs.oracle.com/self/papers/organizing-programs.html"><em>Organizing Programs Without Classes</em></a>, written by Google&#8217;s Senior VP of Operations <a href="http://research.google.com/pubs/author79.html">Urs Hölzle</a>, who, among other things, also contributed to key JIT techniques like <a href="http://en.wikipedia.org/wiki/Inline_caching#cite_note-HCU-1">polymorphic inline caching</a>).</p>
<p>Therefore it is not surprising that there are <a href="https://github.com/jashkenas/coffee-script/wiki/List-of-languages-that-compile-to-JS">many projects that</a> compile existing languages to Javascript. Many of these were too focused on the web platform (like <a href="http://code.google.com/webtoolkit/">Google Web Toolkit</a> and the amazing <a href="http://cappuccino.org/">Cappuccino</a>&#8216;s Objective-j). On more recent years languages are targeting the whole JS ecosystem (which makes a very poignant argument that <a href="http://www.hanselman.com/blog/JavaScriptIsAssemblyLanguageForTheWebPart2MadnessOrJustInsanity.aspx"><em>JavaScript is Assembly Language for the Web</em></a>). <a href="http://jashkenas.github.com/coffee-script/">Coffeescript</a> is one of such languages, which very fond (I&#8217;ve <a href="http://metaphysicaldeveloper.wordpress.com/2011/03/31/354/">written</a> about it recently).</p>
<p>About a month ago <a href="http://github.com/clojure/clojurescript">ClojureScript</a> was <a href="http://clojure.com/blog/2011/07/22/introducing-clojurescript.html">released</a>, porting the <a href="http://clojure.org/">Clojure</a> language from Java ecosystem to the JS. Clojure is quite an amazing effort of engineering, not only for being a very successful Lisp on the JVM, but also for its novel approach of handling time and state (which its creator, Rich Hickey, <a href="http://www.infoq.com/presentations/Value-Identity-State-Rich-Hickey">explains</a> really well).</p>
<p>I was really excited to see the examples, but I was a bit bummed out that the most interesting example was a <a href="http://pragprog.com/magazines/2011-08/hello-clojurescript">Twitter visualization</a> tool (which feels a bit too much like a 2010 app). Since both CoffeeScript and Clojure are fun languages, and I wanted to see how ClojureScript would compare to CoffeeScript, I took the challenge and crafted a simple game HTML5 physics based game on both languages, using <a href="http://code.google.com/p/box2dweb/">Box2dWeb</a>, a js port of Box2D (the physics engine, created by Erin Catto, that is behind <a href="http://www.geek.com/articles/mobile/box2d-creator-asks-rovio-for-angry-birds-credit-at-gdc-2011032/">Angry birds</a>).</p>
<p style="text-align:center;"><a href="http://danielribeiro.github.com/ClojureCoffeeScriptGame/" target="_blank"><img class="aligncenter size-medium wp-image-431" title="Game" src="http://metaphysicaldeveloper.files.wordpress.com/2011/08/game.png?w=300&#038;h=260" alt="" width="300" height="260" /></a></p>
<p>The <a href="http://danielribeiro.github.com/ClojureCoffeeScriptGame/">game</a> consists of clicking on the objects to destroy them, so that they don&#8217;t reach the top of the canvas (and, in another very Tetris like fashion, the elements pop out faster the more you play). It really sticks to the bare minimum of <a href="http://www.kocca.kr/knowledge/report/__icsFiles/afieldfile/2010/05/02/69912.pdf"><em>Terrano&#8217;s Hierarchy of Gamer Needs</em></a>. All the code is open source and can be found on <a href="http://github.com/danielribeiro/ClojureCoffeeScriptGame">Github</a>. The <a href="http://github.com/danielribeiro/ClojureCoffeeScriptGame/blob/master/coffee/src/game.coffee">CoffeeScript</a>&#8216;s version source can be found here, and the <a href="http://github.com/danielribeiro/ClojureCoffeeScriptGame/blob/master/clojure/game.clj">ClojureScript</a>&#8216;s here.</p>
<h3>Lessons Learned</h3>
<p><em>Disclaimer</em><em>:</em> ClojureScript is pretty much in alpha status, so many things are likely to improve in the future.</p>
<p><strong>Compiling:</strong> The first thing that really pops up is how fast Coffeescript compiles down to JS. The watch behavior allows you to fire the compilation process and forget it. ClojureScript takes me about 5 seconds to compile a single file. Granted it gives warning about unused/undefined variables, but I&#8217;d really prefer it to compile instantly and let the browser tell me this on runtime.</p>
<p><strong>Namespaces:</strong> Clojure&#8217;s namespace are implemented as global variables, which are shadowed by local variables with the same name. For instance, if you are in a namespace called <em>game</em>, don&#8217;t use local variables and arguments named <em>game</em>. This is really important, as ClojureScript will use the global namespace for every single function defined in that namespace, so shadowing it is likely to give all sorts of errors.</p>
<p><strong>ClojureScript is not Clojure: </strong>Fogus wrote an interesting <a href="http://blog.fogus.me/2011/07/29/compiling-clojure-to-javascript-pt-2-why-no-eval/">piece</a> on the lack of eval on ClojureScript. Even though I find it might make sense for some web pages, when making WebGL games, or even Canvas 2d games, the assets size can easily overshadow then entire library&#8217;s size. Which is not a big deal if you use HTML5&#8242;s <a href="http://diveintohtml5.org/offline.html">Cache manifest</a>. In the end, it felt very much like the opposite of the Lisp spirit (epitomized by Paul Graham on his <span style="color:#000000;"><a href="http://news.ycombinator.com/item?id=2822177"><em>Five Questions about Language Design</em></a>: <em>&#8220;Give the Programmer as Much Control as Possible</em>&#8220;).</span></p>
<p>The documentation is <a href="http://github.com/clojure/clojurescript/wiki/Differences-from-Clojure">quite clear</a> that eval is not supported. What it is not clear, is that this argument against eval permeates many other functions: <a href="http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/resolve">resolve</a> is not implemented (neither ns-resolve, or the *ns* definition). Without both of them, there is no way to transform a string into a function. For people more used to OO languages, like Javascript, Ruby and Python, this essentially means that ClojureScript doesn&#8217;t have any reflection APIs. On the game:</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
createElement: -&gt;
  randomY = (0.2 + 0.4 * Math.random())*  H / @scale
  randomX = (Math.random() * (W - 50) + 25) / @scale
  type = @objectList[randomInt(@objectList.length)]
  @[&quot;create#{type}&quot;] randomX, randomY, Math.random() + 1
</pre>
<p>The last line of the Coffeescript version uses reflection to get the correct method name (to decide to invoke createTriangle, createCircle or createSquare ). The ClojureScript version had to be translated into:</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
(defn- create-element [game]
  (let [randomY (/ (* H (+ 0.2 (* 0.4 (rand)))) scale)
        randomX (/ (+ 25 (* (rand) (- W 50))) scale)
        type (rand-nth [:circle :square :triangle])
        method (keyword (str &quot;create-&quot; (name type)))]
    ((@game method) game randomX randomY (inc (rand)))
    )
  )
</pre>
<p>Which is possible because the game has the respective functions as keyword attributes, which can be easily converted from string interpolation.</p>
<p><strong>User Macros are not supported</strong>: At the moment at least (support for it is likely to come on following updates). This makes the situation above much harder to take. But this is mostly due to ClojureScript&#8217;s alpha status. This does make the code a bit longer (the CoffeeScript version has 236 lines, while the ClojureScript has 301 lines). In order to circumvent what I consider that would be one of the ugliest bits caused by lack of macros (several <em>(set! (. obj attr) value)</em> calls), I defined a js-set function:</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
(defn- js-set
  &quot;Sets an attribute name to a value on a javascript object
Returns the original object&quot;
  ([jsobject attr value]
    (do (native-set-wrapper jsobject attr value)
      jsobject))
  ([jsobject &amp; values]
    (do (doseq [[attr value] (apply hash-map values)]
          (native-set-wrapper jsobject attr value))
      jsobject)))
</pre>
<p>This is actually really against Clojure&#8217;s spirit, as Clojure really promotes immutable code. However Javascript libraries, in particular Box2dWeb, really expect mutable state. Therfore handling native js objects require such functions (note that converting them to clojure and keeping it on clojure land can be easily done with the nice undocumented function <em>js-&gt;clj</em> function, which is actually used on <a href="http://github.com/clojure/clojurescript/blob/master/samples/twitterbuzz/src/twitterbuzz/core.cljs">TwitterBuz</a>).</p>
<p>Therefore we can write functions this way</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
(defn- create-fixture
  ([shape] (js-set (b2FixtureDef.)
  :density 3
  :friction 0.3
  :restitution 0.9
  :shape shape
))
([] (create-fixture nil))
)

</pre>
<p>Instead of:</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
(defn- create-fixture
  ([shape] (let [f (b2FixtureDef.)]
  (set! (. f density) 3)
  (set! (. f friction) 0.3)
  (set! (. f restitution) 0.9)
  (set! (. f shape) shape)
))
([] (create-fixture nil)))
</pre>
<p>Which makes it look a lot like assoc function for creating maps with updated values. This version inspired me to refactor the Coffeescript version using a similar assoc function:</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
createFixture = (shape) -&gt;
f = new b2FixtureDef
f.density = 3.0
f.friction = .3
f.restitution = .9
f.shape = shape if shape?
return f
</pre>
<p>became:</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
assoc = (o, i) -&gt; o[k] = v for k, v of i; o

createFixture = (shape) -&gt;
assoc new b2FixtureDef,
density: 3
friction: .3
restitution: .9
shape: shape
</pre>
<p>Which is quite similar to ClojureScript&#8217;s version (the colons are on the right instead of the left, and it requires a comma). Which reduces the amount of <a href="http://blog.jayfields.com/2011/02/impact-of-accidental-complexity-on.html">accidental complexity</a> to a minimum.</p>
<p><em>Edit:</em> Thanks everybody for pointing out that you can use macros with Clojurescript. However, at the moment, the are clojure macros (so no js), and they require you hacking your clojurescript to add the macro files in the classpath. <a href="http://github.com/teropa/hiccups">Hiccups</a> and <a href="http://github.com/lynaghk/cljs-d3">cljs-3d</a> are two projects that do this, so you can see on their build files how they do this. Even then, you still need to use <a href="http://github.com/clojure/clojurescript/wiki/Differences-from-Clojure"><code>require-macros</code></a>. All of this makes macros less of a native feature on Clojurescript, and it makes a lot harder to share code seamlessly.</p>
<p><strong>IDE support:</strong> Clojure&#8217;s IDE support is really nice. Intellij&#8217;s <a href="http://plugins.intellij.net/plugin/?id=4050">La Clojure</a> (avaiable on its free Community Version) does a lot more than mere syntax highlight: minimal refactoring support, rainbow parenthesis, smart parenthesis, syntax highlighted repl, great autocomplete support, awesome code navigation, autocomplete for java classes and live templates. And it works pretty well for ClojureScript as well. Other <a href="http://dev.clojure.org/display/doc/Getting+Started">IDEs are also great</a>, even though Emacs support can be a bit more intense on its setup (which is not something emacs users are unfamiliar with).</p>
<p>Even though I am really happy with Github&#8217;s founder Chris Wanstrath work on the <a href="http://github.com/defunkt/coffee-mode">Emacs mode for Coffeescript</a>, it doesn&#8217;t have the same support that Clojure does. It is getting more and <a href="http://github.com/jashkenas/coffee-script/wiki/Text-editor-plugins">more support</a>, but nowadays Clojure has the upper hand.</p>
<p><strong>Debugging support:</strong> Browser support for debugging languages that compile down to javascript is <a href="http://www.infoq.com/news/2011/08/debug-languages-on-javascript-vm">coming</a>, but at the moment Cofffeescript compiles down to such a readable JS that it not a big problem. This is a <a href="http://groups.google.com/forum/#!topic/clojure/USoSFlNrMwM">known</a> issue with ClojureScript at the moment. Even on pretty print compile mode.</p>
<h3>Conclusions</h3>
<p>Since Javascript on the web has a much more simple <a href="http://ejohn.org/blog/how-javascript-timers-work/">execution model</a> than Java, Clojure&#8217;s amazing concurrency control mechanisms are not as shining. Nevertheless ClojureScript is a delight to work with. As it moves out of its Alpha status, many of the issues are likely to be gone. I also expect it to support the full Clojure language (including things like resolve, letfn, macros and eval), as writing web apps in a single language on client and server is a really nice feature. This would also make ClojureScript even more interesting, as it would allow developers do leverage all the power of existing Clojure libraries into their Javascript work (and possibly use it on a more polyglot environment).</p>
<p>Coffeescript is more suitable for production apps right now, but it is nice to see all these developer efforts to allow people to be more productive and happy with their work on Javascript platforms (this way we don&#8217;t have to wait for Google&#8217;s <a href="http://chrome.blogspot.com/2011/08/building-better-web-apps-with-new.html">NaCl</a> and <a href="http://nativeclient.googlecode.com/svn/data/site/pnacl.pdf">PNaCL</a>, which promise to bring even more languages to the environment).</p>
<br /> Tagged: <a href='http://metaphysicaldeveloper.wordpress.com/tag/clojure/'>clojure</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/coffeescript/'>coffeescript</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/html5/'>html5</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/420/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/420/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=420&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2011/08/28/clojurescript-vs-coffeescript/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2011/08/rome.png" medium="image">
			<media:title type="html">Rome project</media:title>
		</media:content>

		<media:content url="http://metaphysicaldeveloper.files.wordpress.com/2011/08/game.png?w=300" medium="image">
			<media:title type="html">Game</media:title>
		</media:content>
	</item>
		<item>
		<title>Hacking a Gnuplot into Minecraft</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2011/07/31/hacking-a-gnuplot-into-minecraft/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2011/07/31/hacking-a-gnuplot-into-minecraft/#comments</comments>
		<pubDate>Mon, 01 Aug 2011 02:58:44 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[hacking]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/?p=386</guid>
		<description><![CDATA[For those who don&#8217;t know, Minecraft is an inspiring indie game that places the gamer into a sandbox 3d world, where everything is made of blocks. Blocks can also be crafted into other blocks through recipes. Besides having over 10 million users and being feature on Techcrunch, what makes it quite unique is what the [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=386&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>For those who don&#8217;t know, <a href="http://www.minecraft.net/">Minecraft</a> is an inspiring indie game that places the gamer into a sandbox 3d world, where everything is made of blocks. Blocks can also be crafted into other blocks through recipes. Besides having over <a href="http://notch.tumblr.com/post/7128013309/10m">10 million</a> users and being feature on <a href="http://techcrunch.com/2011/01/15/a-brief-explanation-of-why-minecraft-matters/">Techcrunch</a>, what makes it quite unique is what the users have created with it: from a 3d block replica of <a href="http://www.youtube.com/watch?v=kn2-d5a3r94">the enterprise</a>, to <a href="http://www.youtube.com/watch?v=yKEbBX21igc">giant spaceships</a> and entire <a href="http://www.youtube.com/watch?v=yxAmphwLPDY">8 bit CPUs</a>. Users even created a real time <a href="http://www.youtube.com/watch?v=x2mCDkqXki0">kinetic world</a> terraformer, a tool that lets you use a <a href="http://minecraftprint.com/">3d printer</a> to bring to physical world creations from minecraft, and tools to import good old fashioned <a href="//www.patrickmin.com/minecraft/">3d models</a> into minecraft.</p>
<p>As expected, Minecraft has its <a href="http://www.minecraftwiki.net/wiki/Programs_and_editors">tools</a> and <a href="http://www.minecraftwiki.net/wiki/Mods">mods</a>. And even though there are several libs for view the world of a save file, I found that, in spite of its vibrant community, there were no libs for editing the world. Note that <a href="http://davidvierra.com/mcedit.html">MCEdit</a> allows some  hacking, but it is mostly a GUI editor (and a very good one in my opinion).</p>
<p>So I hacked together a simple library for manipulating the world files called <a href="https://github.com/danielribeiro/RubyCraft">RubyCraft</a>. To illustrate the simplicity it enables, turning the first chunk completely into gold is a simple one line:</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
Region.fromFile(filename).chunk(0, 0).block_map { :gold }
</pre>
<p>And making all blocks into orange wool is as simple as</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
Region.fromFile(filename).chunk(0, 0).each do |b|
  b.name = :wool
  b.color = :orange
end
</pre>
<p>The result:</p>
<p style="text-align:center;"><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/orangeTower.png"><img class="aligncenter" title="orange tower" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/orangeTower.png" alt="" width="426" height="324" /></a></p>
<p>The issue with this Api is that it leaks a bit the Minecraft abstraction of how the world is divided. In a nutshell, the world is divided into <em>region</em> files, each one is divided into a 32 x 32 matrix of <em>chunks</em>, which is nothing more than a 16x16x128 cube of blocks. To manipulate the chunks inside a region file, you can request a <a href="https://github.com/danielribeiro/RubyCraft/blob/master/lib/rubycraft/region.rb#L112">cube</a>, giving its initial point, width, length and height. The same code above could be written ignoring the chunk abstraction like this:</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
r = Region.fromFile(filename)
c = r.cube(0, 0, 0, :width =&gt; 16, :length =&gt; 16, :height =&gt; 128)
c.each do |block, z, x, y|
  block.name = :wool
  block.color = :orange
end
</pre>
<p>A cube can span several chunks, but at the moment it can&#8217;t span several regions. It might not be a big issue, as a Region is a pretty large area (it contains <em>over</em> 33 million blocks), and it can take a while to save an entire region (the time it takes to save a Region is proportional to the changed chunks), even in <a href="http://www.jruby.org/">JRuby</a> (which I found to be 3 times as fast than MRI for this particular task).</p>
<h3><span style="text-decoration:underline;">A Gnuplot in my Minecraft</span></h3>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/plottingOverview.png"><img class="aligncenter" title="overview" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/plottingOverview.png" alt="" width="426" height="324" /></a></p>
<p><em>Edit</em>: The save file for the resulting world can be found <a href="http://dl.dropbox.com/u/37205964/PlottedLowDirt.zip">here</a>.</p>
<p>After turning Minecraft world file into a 3d matrix, making a two real function plotter quite simple. The <a href="https://github.com/danielribeiro/RubyCraft/blob/master/examples/plotting_example.rb#L73">plotting_example.rb</a> mostly contains code that decide the area where the graph will be plotted, centering the function on the xz axis, and more importantly, it plots f(x, y) for a given f:</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
def plot(function, fillFunction)
cube = getCube
middlePointX = length / 2
middlePointZ = width / 2
centeredF = proc do |x, z|
function.call(x - middlePointX, z - middlePointZ).ceil
end
points = Set.new
yzraster(centeredF, points)
yxraster(centeredF, points)
modifyBlocks(cube, centeredF, fillFunction, points)
end
</pre>
<p>Quite straightforward. The functions yxraster and yzraster have a mild subtlety: just plotting the points of f(x, y) can prevent a look from looking continuous. In general plotting algorithms you have to find a plane or another elementary surface to approximate a small region. As minecraft only contains blocks, I&#8217;ve joined all points by discrete line segments, using <a href="http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm">Bresenham&#8217;s line algorithm</a> (source <a href="https://github.com/danielribeiro/RubyCraft/blob/master/examples/example_helpers.rb#L22">here</a>). This is done by transversing the plotting cube with xy planes, and then with zy planes (therefore only the 2d version of Bresenham algorithm is needed).</p>
<p>Also note that f(x, y) is coerced into integer values by taking the ceil. This is because Bresenham&#8217;s algorithm expects points defined on Z x Z, but is expected, as the resulting points would have to be coerced into a integer y coordinate anyway because of the Minecraft world definition.</p>
<p>With all of  this, the following <a href="https://github.com/danielribeiro/RubyCraft/blob/master/examples/plotting_example.rb#L6">examples</a> are easy to create:</p>
<p>Diamond Cone:</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
plotWith :diamond_block do |x, z|
   sqrt((x** 2 + z ** 2) / 3) * 5 + 20
end
</pre>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/cone.png"><img class="aligncenter" title="cone" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/cone.png" alt="" width="426" height="324" /></a></p>
<p>Water Hyperbolic Paraboloid</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
    plotWith :water do |x, z|
      (x** 2 - z ** 2) / 3 + 50
    end
</pre>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/hyperbolicParaboloid.png"><img class="aligncenter" title="hyperbolicParaboloid" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/hyperbolicParaboloid.png" alt="" width="426" height="324" /></a></p>
<p>Lava <a href="http://gnuplot.sourceforge.net/demo_4.4/surface1.10.png">Surface 10 of Gnuplot examples</a></p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
    plotWith :lava do |x, z|
      log(x ** 4 * z ** 2 + 2) + 20
    end
</pre>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/gnuplotSurface10.png"><img class="aligncenter" title="gnuplotSurface10" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/gnuplotSurface10.png" alt="" width="426" height="324" /></a></p>
<p>Netherrack <a href="http://gnuplot.sourceforge.net/demo_4.4/surface1.15.png">Surface15 of Gnuplot examples</a></p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
    plotWith :netherrack do |x, z|
      (sin(sqrt(z ** 2 + z ** 2)) / sqrt(x ** 2 + z ** 2)) * 30 + 30
    end
</pre>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/gnuplotSurface15.png"><img class="aligncenter" title="gnuplotSurface15" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/gnuplotSurface15.png" alt="" width="426" height="324" /></a></p>
<p>Golden rotated Sine</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
    plotWith :gold do |x, z|
      sin(sqrt((x** 2 + z ** 2)) / 2) * 10 + 30
    end
</pre>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/rotatedSine.png"><img class="aligncenter" title="rotatedSine" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/rotatedSine.png" alt="" width="426" height="324" /></a></p>
<p>Ice Sphere (half sphere actually)</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
    plotWith :ice do |x, z|
      sqrt(18**2 - x**2 - z **2) + 30
    end
</pre>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/halfSphere.png"><img class="aligncenter" title="halfSphere" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/halfSphere.png" alt="" width="426" height="324" /></a></p>
<p>Wooden Polynomial</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
    plotWith :log do |x, z|
      x /= 5
      z /= 5
      (x + z) ** 5 + x**3 + z**2 + 30
    end
</pre>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/polynomial.png"><img class="aligncenter" title="polynomial" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/polynomial.png" alt="" width="426" height="324" /></a></p>
<p>Obysidan Polynomial Quotient</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
    plotWith :obsidian do |x, z|
      p1 = (x + z) ** 6 - x ** 3 + z **2 + 50
      p2 = x ** 7 + 6* z ** 6 - x **4 - z**2 + 30
      p1 / p2 + 10
    end
</pre>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/polynomialQuotient.png"><img class="aligncenter" title="polynomialQuotient" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/polynomialQuotient.png" alt="" width="426" height="324" /></a></p>
<p>Colorful Paraboloid</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
    plot(proc {|x, z| (x** 2 + z ** 2) / 3}, proc do |b, z, x, y|
        b.name = :wool; b.data = OrderedColors[y * 16 / 128].data
      end)
</pre>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/paraboloid.png"><img class="aligncenter" title="paraboloid" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/paraboloid.png" alt="" width="426" height="324" /></a></p>
<p>The Ordered Colors of the Colorful Paraboloid are the <a href="http://www.minecraftwiki.net/wiki/Data_values#Wool">Wool Colors</a> of minecraft sorted by distance to the black color. The distance <a href="http://www.orderofevents.com/MineCraft/Phase3/processImages.py">definition</a> is the same as the one from the <a href="http://www.orderofevents.com/MineCraft/KinectInfo.htm">kinetic experiment</a>.</p>
<p>The <a href="https://github.com/danielribeiro/RubyCraft/blob/master/examples/plotting_example.rb#L73">plotting class</a> cannot plot parametric surfaces at the moment. However, since the graphs are real minecraft objects, they can be manipulated as any other minecraf object. For instance, it is possible to turn the golden rotated sine into a roller coaster (<a href="https://github.com/danielribeiro/RubyCraft/blob/master/examples/roller_coaster.rb">source here</a>):<br />
<a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/goldSineRollerCoaster.png"><img class="aligncenter" title="goldSineRollerCoaster" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/goldSineRollerCoaster.png" alt="" width="426" height="324" /></a></p>
<p><a href="https://github.com/danielribeiro/RubyCraft/raw/master/images/onthesineRollerCoaster.png"><img class="aligncenter" title="onthesineRollerCoaster" src="https://github.com/danielribeiro/RubyCraft/raw/master/images/onthesineRollerCoaster.png" alt="" width="426" height="324" /></a></p>
<p>All the code is open source and can be fount on <a href="https://github.com/danielribeiro/RubyCraft">Github</a>.</p>
<h3>Acknowledgements</h3>
<p>The examples use an edited version of the <a href="http://www.minecraftforum.net/topic/121011-creation-tykens-test-world-v181-15-updates/">Low Dirt Tyken</a>&#8216;s test world. The screenshots were take while flying using <a href="http://www.minecraftforum.net/topic/94310-173-single-player-commands-v210-2">Single Player Commands mod</a>. The algorithm for parsing the region file was based on <a href="http://clockworkcodex.blogspot.com/2011/06/minecraft-mapping-reading-minecraft.html">Weeble&#8217;s work</a>. Parsing the nbt binary is done through <a href="https://github.com/mental/nbtfile">NbtFile</a> gem.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/386/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/386/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=386&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2011/07/31/hacking-a-gnuplot-into-minecraft/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/orangeTower.png" medium="image">
			<media:title type="html">orange tower</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/plottingOverview.png" medium="image">
			<media:title type="html">overview</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/cone.png" medium="image">
			<media:title type="html">cone</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/hyperbolicParaboloid.png" medium="image">
			<media:title type="html">hyperbolicParaboloid</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/gnuplotSurface10.png" medium="image">
			<media:title type="html">gnuplotSurface10</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/gnuplotSurface15.png" medium="image">
			<media:title type="html">gnuplotSurface15</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/rotatedSine.png" medium="image">
			<media:title type="html">rotatedSine</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/halfSphere.png" medium="image">
			<media:title type="html">halfSphere</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/polynomial.png" medium="image">
			<media:title type="html">polynomial</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/polynomialQuotient.png" medium="image">
			<media:title type="html">polynomialQuotient</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/paraboloid.png" medium="image">
			<media:title type="html">paraboloid</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/goldSineRollerCoaster.png" medium="image">
			<media:title type="html">goldSineRollerCoaster</media:title>
		</media:content>

		<media:content url="https://github.com/danielribeiro/RubyCraft/raw/master/images/onthesineRollerCoaster.png" medium="image">
			<media:title type="html">onthesineRollerCoaster</media:title>
		</media:content>
	</item>
		<item>
		<title>Peter Norvig&#8217;s Spelling Corrector in 21 Lines of Coffeescript</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2011/03/31/354/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2011/03/31/354/#comments</comments>
		<pubDate>Thu, 31 Mar 2011 04:14:03 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[Languages]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/?p=354</guid>
		<description><![CDATA[Coffeescript is a very nice (and relatively new) language that compiles down to javascript, making web programming (and making firefox plugins, nodejs apps, and so forth) much more joyful. Its object model is the same as javascript (one of coffeescript&#8217;s motto is Unfancy JavaScript), and its compiled js form is quite easy to read and [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=354&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://jashkenas.github.com/coffee-script/">Coffeescript</a> is a very nice (and relatively new) language that compiles down to javascript, making web programming (and making firefox plugins, nodejs apps, and so forth) much <a href="http://amix.dk/blog/post/19612">more joyful</a>. Its object model is the same as javascript (one of coffeescript&#8217;s <a href="https://github.com/jashkenas/coffee-script">motto</a> is <em>Unfancy JavaScript</em>), and its compiled js form is quite easy to read and debug. It has many <a href="http://jashkenas.github.com/coffee-script/#overview">niceties</a>, including <a href="http://jashkenas.github.com/coffee-script/#classes">classes</a> (effectively making the <a href="http://mckoss.com/jscript/object.htm">prototype chain</a> a first class citizen of the language) and <a href="http://jashkenas.github.com/coffee-script/#loops">array/object comprehensions</a> (heavily influenced by python&#8217;s <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions">list comprehensions</a>).</p>
<p>Ruby also has a influence on the language, such as <a href="http://jashkenas.github.com/coffee-script/#language">optional parenthesis</a> on method/function invocation. In fact, the original version of Coffeescript compiler was <a href="http://www.rubyinside.com/coffeescript-a-new-language-with-a-pure-ruby-compiler-2921.html">written in Ruby</a> (but nowadays coffeescript is a <a href="http://en.wikipedia.org/wiki/Bootstrapping_(compilers)">self-hosting</a> language).</p>
<p>Coffeescript has been used by several <a href="http://jashkenas.github.com/coffee-script/#resources">projects</a>, including a <a href="http://thinkvitamin.com/mobile/new-rails-like-framework-from-37signals-for-html5-mobile-apps/">mobile framework</a> written by Rail&#8217;s creator <a href="http://37signals.com/">37 signals</a>. I&#8217;ve been using for about one year (including some open source <a href="https://github.com/danielribeiro/EaselBugTracker/blob/master/lib/easelbugtracker.coffee">work</a> using a HTML 5 Canvas framework called <a href="http://easeljs.com/">EaselJs</a>, a port of <a href="https://github.com/danielribeiro/rbcoffee/blob/master/rbcoffee.coffee">ruby functionalities</a> and even a <a href="https://github.com/danielribeiro/powerhistory">Firefox plugin</a>).</p>
<p>Because of all the Ruby and Python influence on the language, and the fact that Coffeescript can convey beautiful and concise code, I had a hunch that it could get a really good position on <a href="http://norvig.com/spell-correct.html">Peter Norvig&#8217;s Spelling Corrector</a> implementation collection (Javascript&#8217;s <a href="http://astithas.blogspot.com/2009/08/spell-checking-in-javascript.html">version</a> currently has 53 lines, which is a lot more than <a href="http://norvig.com/spell.py">python</a>&#8216;s 21). With some work, I managed to implement it in 21 lines as well:</p>
<pre class="brush: ruby; title: ; wrap-lines: false; notranslate">
words = (text) -&gt; (t for t in text.toLowerCase().split(/[^a-z]+/) when t.length &gt; 0)
Array::or = (arrayFunc) -&gt; if @length &gt; 0 then @ else arrayFunc()
Array::flat = -&gt; if @length == 0 then @ else @[0].concat(@[1..].flat())
train = (features) -&gt;
 model = {}
 (model[f] = if model[f] then model[f] +1 else 2) for f in features
 return model
NWORDS = train(words(require('fs').readFileSync('./lib/big.txt', 'utf8')))
alphabet = 'abcdefghijklmnopqrstuvwxyz'.split &quot;&quot;
edits1 = (word) -&gt;
 s = ([word.substring(0, i), word.substring(i)] for i in [0..word.length])
 deletes = (a.concat b[1..] for [a, b] in s when b.length &gt; 0)
 transposes = (a + b[1] + b[0] + b.substring(2) for [a, b] in s when b.length &gt; 1)
 replaces = (a + c + b.substring(1) for c in alphabet for [a, b] in s when b.length &gt; 0)
 inserts = (a + c + b for c in alphabet for [a, b] in s)
 return deletes.concat transposes.concat replaces.flat().concat inserts.flat()
known_edits2 = (word) -&gt; ((e2 for e2 in edits1(e1) when NWORDS[e2]? for e1 in edits1(word)).flat())
known = (words) -&gt; (w for w in words when NWORDS[w])
correct = (word) -&gt;
 candidates = known([word]).or -&gt; known(edits1(word)).or -&gt; known_edits2(word).or -&gt; [word]
 ({k: w, v: NWORDS[w] or 1} for w in candidates).sort((a, b)-&gt; b.v  - a.v)[0].k
</pre>
<p>All the code is hosted on <a href="https://github.com/danielribeiro/Coffeescript-Spelling-Corrector">github</a>. The code above can be seen in a more readable version <a href="https://github.com/danielribeiro/Coffeescript-Spelling-Corrector/blob/master/lib/spellCheck.coffee">here</a> (after line 21 it also contains a full test, using a fixture generated by a <a href="https://github.com/danielribeiro/Coffeescript-Spelling-Corrector/blob/master/python/spell.py">slightly modified version</a> of Peter Norvig&#8217;s original implementation). There is a more <a href="https://github.com/danielribeiro/Coffeescript-Spelling-Corrector/blob/master/lib/testableSpellCheck.coffee">testable</a> version, along with <a href="http://pivotal.github.com/jasmine/">Jasmine</a> BDD <a href="https://github.com/danielribeiro/Coffeescript-Spelling-Corrector/blob/master/spec/coffee/spellCheckSpec.coffee">tests</a> (which look a lot like Rspec&#8217;s in Coffeescript), which run headless on NodeJs, but work just fine in the browsers.</p>
<h3>Considerations</h3>
<p>Findall regex doesn&#8217;t exists natively in Javascript, however it is equivalent to spiting by the complementary regex (line 1)</p>
<p>Array::or (line 2) was needed to be implemented, because Python&#8217;s truthfulness allows a collection to be true (actually, any iterable) as long as it is not empty. Array::flat (line 3) has to be implemented because Coffeescript&#8217;s loop comprehension is a bit different from python&#8217;s: double loops (example: <em>x + y for y in col1 for z in col2</em>) return array of arrays instead of a single array.</p>
<p>Also note that loop comprehension&#8217;s order is inverted (<em>x + y for x for y</em> in python is translated as <em>x + y for y for x</em>).</p>
<p>Granted, this version runs really fast on NodeJs 0.4.1, and I was quite happy with how the resulting code looked. I was even happier that I did not have to write the compiled <a href="https://github.com/danielribeiro/Coffeescript-Spelling-Corrector/blob/master/libjs/spellCheck.js">Javascript</a> file and its whooping 147 lines of Spelling Corrector.</p>
<p>To see the reason why this work, check out Peter Norvig&#8217;s<a href="http://norvig.com/spell-correct.html"> original post</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/354/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/354/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=354&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2011/03/31/354/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>
	</item>
		<item>
		<title>High Level Concurrency with JRuby and Akka Actors</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2010/12/16/high-level-concurrency-with-jruby-and-akka-actors/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2010/12/16/high-level-concurrency-with-jruby-and-akka-actors/#comments</comments>
		<pubDate>Fri, 17 Dec 2010 01:46:21 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[Systems]]></category>
		<category><![CDATA[actors]]></category>
		<category><![CDATA[akka]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/?p=300</guid>
		<description><![CDATA[Many developers are used to low-level concurrency primitives, such as locks, monitors and semaphores. Java also has higher level concurrency utilities such as Atomic Objects and Fork/Join framework. Such primitives still require a lot of attention to shared variables, and are very easy to get wrong. Ilya Grigorik recently discussed other models of concurrency on [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=300&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Many developers are  used to low-level <a href="http://en.wikipedia.org/wiki/Concurrency_%28computer_science%29">concurrency</a> primitives, such as <a href="http://en.wikipedia.org/wiki/Mutual_exclusion">locks</a>, <a href="http://en.wikipedia.org/wiki/Monitor_%28synchronization%29">monitors</a> and <a href="http://en.wikipedia.org/wiki/Semaphore_%28programming%29">semaphores</a>. Java also has higher level concurrency utilities such as <a href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/package-summary.html">Atomic Objects</a> and <a href="http://gee.cs.oswego.edu/dl/papers/fj.pdf">Fork/Join</a> framework. Such primitives still require a lot of attention to shared variables, and are very easy to get wrong.  Ilya Grigorik recently discussed other models of concurrency on his recent post <em><a href="http://www.igvita.com/2010/12/02/concurrency-with-actors-goroutines-ruby/?utm_source=feedburner&amp;utm_campaign=Feed%3A+igvita+%28igvita.com%29&amp;utm_content=feed">Concurrency with Actors, Goroutines &amp; Ruby</a></em>, where he even introduced a ruby port of <a href="http://golang.org/">Go</a>&#8216;s concurrency mechanism. These models attempt to make concurrent programming easier.</p>
<p>The <a href="http://en.wikipedia.org/wiki/Actor_model">actor model</a> is another very simple high level concurrency model: actors can&#8217;t respond to more than one message at a time (messages are queued into mailboxes) and can only communicate by sending messages, not sharing variables. As long as the messages are <a href="http://doc.akkasource.org/untyped-actors-java#Actors%20%28Java%29-Messages%20and%20immutability">immutable</a> data structures (which is always true in Erlang, but has to be a convention in languages without means of ensuring this property), everything is thread-safe, without need for any other mechanism. This is very similar to request cycle found in web development MVC frameworks.</p>
<p><a title="Scala: The Successor to the Throne" href="http://metaphysicaldeveloper.wordpress.com/2009/07/29/scala-the-successor-to-the-throne/">Scala</a> is famous for coming with an Actor library built-in. However, using Scala libraries in Ruby is not easy[1]. <a href="http://akkasource.org/">Akka</a> is another great project that implements Actors, however it has a <a href="http://doc.akkasource.org/untyped-actors-java">java Api</a>, which makes the JRuby integration easier. Why JRuby? Not only to access Akka&#8217;s actor library, but also because JRuby is one of the few ruby implementations that doesn&#8217;t have the <a href="http://www.igvita.com/2008/11/13/concurrency-is-a-myth-in-ruby/">GIL</a>, therefore it allows true concurrency for all types of applications (IO bounded or not).</p>
<h4><span style="text-decoration:underline;"><strong>Integrating Akka with JRuby</strong></span></h4>
<p>For starters, let&#8217;s first create a simple actor in Java:</p>
<pre class="brush: java; title: ; notranslate">
public class PingActor extends UntypedActor {
	public void onReceive(Object message) throws Exception {
	    if (message instanceof String) {
	    	System.out.println(&quot;!!! Acted on: &quot; + message);
	    }
	    else throw new IllegalArgumentException(&quot;Unknown message:&quot; + message);
	}
}
</pre>
<p>This simple actor will just output any message it receives prefixed with &#8220;!!! Acted on: &#8220;, and will throw exception on any message that is not a string. This example show how simple it is to define an actor: just define a onReceive method that is called whenever a message is sent.</p>
<p>To see this actor working, we need four lines:</p>
<pre class="brush: java; title: ; notranslate">
		ActorRef actor = actorOf(PingActor.class).start();
		actor.sendOneWay(&quot;hello actor world&quot;);
		TimeUnit.SECONDS.sleep(1);
		ActorRegistry.shutdownAll();
</pre>
<p>The first gets an actor reference and starts it. It is important to note that you cannot create an actor just by invoking new. Not in java or scala (we can solve this in Ruby). This is because there is a lot of AOP going on the background[2]. The second line just sends the message to the actor asynchronously. There two other ways of sending messages, which I&#8217;ll not cover, but you can <a href="http://doc.akkasource.org/untyped-actors-java#Actors%20%28Java%29-Send%20messages">read more</a> in Akka&#8217;s documentation.</p>
<p>The last two lines just give time to the message reach the actor (remember, the sendOneWay method is non-blocking), and stops all actors on the system. Pretty simple right? Let&#8217;s see how we can do the same in JRuby. Setting up the stage:</p>
<pre class="brush: ruby; title: ; notranslate">
require 'java'
module Akka
  include_package 'se.scalablesolutions.akka.actor'
end
</pre>
<p>These lines enable java and make a ruby module with all the classes of se.scalablesolutions.akka.actor package. Basic JRuby setup. Now on to defining the actor:</p>
<pre class="brush: ruby; title: ; notranslate">class PingActor &lt; Akka::UntypedActor
  def self.create(*args)
    self.new(*args)
  end

  def onReceive(message)
    puts &quot;!!! Acted on: #{message}&quot;
  end
end
</pre>
<p>Here we have our first differences. The onReceive is just a cleaner version of the Java one. No type annotations, no type checking and a simpler string output. However, we have to define a <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/wont_work_without_create.rb">classmethod called create</a>, which just invokes new. This method seems to be created by the AOP part of Akka, which doesn&#8217;t seem to work on Ruby subclasses of UntypedActor. However, we can defined it ourselves. Now to actually using the actor:</p>
<pre class="brush: ruby; title: ; notranslate">
actor = Akka::UntypedActor.actorOf(PingActor).start
actor.sendOneWay &quot;hello actor world&quot;
sleep 1
Akka::ActorRegistry.shutdownAll
</pre>
<p>Pretty much the same four lines as on the Java version, with a little less parenthesis, and a terser sleep method. The ruby code can be found on <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/basic_example.rb">this page</a>, and Java code <a href="https://github.com/danielribeiro/RubyOnAkka/tree/master/java/helloakka">here</a>.</p>
<h4><span style="text-decoration:underline;"><strong><strong>Fixing the Ruby Interface</strong></strong></span></h4>
<p>Much of the code in the former example is infrastructure, but we can work around the static nature of Java classes in ruby. As factored out in <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/akka.rb">akka.rb</a>,  we can gather this functionalities into a base class, and rewrite the first example in <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/fixxed_basic_example.rb">8 lines</a>:</p>
<pre class="brush: ruby; title: ; notranslate">require 'akka'
class PingActor &lt; Actors::Base
  def onReceive(message)
    puts &quot;!!! Acted on: #{message}&quot;
  end
end
PingActor.spawn.sendOneWay &quot;hello actor world&quot;
Actors.delayedShutdown 1
</pre>
<p>Using closures we can even enhance our JRuby api with some ideas from the Scala api, making it <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/proc_basic_example.rb">down to 3 lines</a>:</p>
<pre class="brush: ruby; title: ; notranslate">require 'akka'
Actors.spawn { |m| puts &quot;!!! Acted on: #{m}&quot; }.sendOneWay &quot;hello actor world&quot;
Actors.delayedShutdown 1
</pre>
<p>In this example spawn takes a block, and creates an actor that executes it every time it receives a message. As in the Scala API, spawn starts the actor as well as creating it.</p>
<h4><span style="text-decoration:underline;"><strong><strong>But every Object is an Actor!</strong></strong></span></h4>
<p>Alan Kay, the inventor of Smalltak and of the <a href="http://c2.com/cgi/wiki?AlanKayOnObjects">term OO</a>, once <a href="http://c2.com/cgi/wiki?AlanKayOnMessaging">said</a>:</p>
<p style="padding-left:30px;"><em>I&#8217;m sorry that I long ago coined the term &#8220;objects&#8221; for this topic because it gets many people to focus on the lesser idea. The big idea is &#8220;messaging&#8221;.</em></p>
<p>This is one of the reasons that Erlang with its actors form an object oriented language[3]</p>
<p>If we look into the resemblance of sendOneWay and the reflective method invocation, which in Ruby is made through <a href="http://ruby-doc.org/core-1.8.7/classes/Object.html#M000606">send</a> or __send__, it is quite easy to adapt the ruby method invocation to Actor message sending. We start with a simple <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/akka.rb#L35">delegator</a>:</p>
<pre class="brush: ruby; title: ; notranslate">MethodParameters = Struct.new :name, :args, :block

class DelegatorActor &lt; Base
    def self.new(target)
      ret = super()
      ret.instance_variable_set(:@target, target)
      return ret
    end

    def onReceive(message)
      param = message
      @target.__send__ param.name, *param.args, &amp;param.block
    end
  end
</pre>
<p>The important part is the onRecieve message, which takes a MethodParameters object and invoke on the target. The caveat here is that we need to override the new method, because, for some reason, ruby subclasses of Akka UntypedActors will not invoke the initialize method with the arguments passed[4]. However, by turning any object into an actor, this can be the only place such hack is needed.</p>
<p>Now, the next step: <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/akka.rb#L52">adapting the actorRefs</a> to make the ruby method invocation a actor sendOneWay:</p>
<pre class="brush: ruby; title: ; notranslate">class ActorRefHandler
    public_instance_methods.each do |m|
      undef_method m unless m =~ /^__/ or m == 'to_s'
    end

    def initialize(actorRef)
      @actorRef = actorRef
    end

    def method_missing(name, *args, &amp;block)
      @actorRef.sendOneWay MethodParameters.new name, args, block
    end
  end
</pre>
<p>Which is a pretty standard implementation of message forwarding in ruby: remove all instance methods (except the really private ones, such as __send__), making sure all method calls are forwarded to method_missing.</p>
<p>With all of this we can write a simple example of <a href="//github.com/danielribeiro/RubyOnAkka/blob/master/lib/everything_is_an_actor.rb">making any object an actor</a>:</p>
<pre class="brush: ruby; title: ; notranslate">require 'akka'
class HelloWord
  def hi
    puts &quot;hello actor world&quot;
  end
end
Actors.actorOf(HelloWord.new).hi
Actors.delayedShutdown 1
</pre>
<h4><span style="text-decoration:underline;"><strong><strong><strong><strong>Making it faster</strong></strong></strong></strong></span></h4>
<p>In the heart of all of this lies the problem: making code runs faster by using the machine&#8217;s cores more effectively. Here we build the good old canonical <a href="http://hadoop.apache.org/common/docs/r0.20.2/mapred_tutorial.html#Example%3A+WordCount+v1.0">map-reduce example: word count</a>. We will count 5.4 MB of <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/shakespeare.txt">Shakespeare</a>&#8216;s texts. The example consists of 3 types of actors: a producer, mappers, and one reducer. The producer generates the chunks of lines to the mappers, which count the words on each chunk and generate a hash of word:count pairs, which the reducer aggregates into a hash of its own.</p>
<pre class="brush: ruby; title: ; notranslate">require 'akka'
require 'regular_word_count'
include Actors
module AkkaDispatcher
  include_package 'se.scalablesolutions.akka.dispatch'
  def self.workStealer(name)
    Dispatchers.newExecutorBasedEventDrivenWorkStealingDispatcher 'mappers'
  end
end

file = File.join(File.dirname(__FILE__), 'shakespeare.txt')
input = IO.readlines(file).each_slice(500).map &amp;:join
</pre>
<p>This code setups up the code to later define WorkStealer, so that our map actors can share the same message queue. We also load the file in memory, split into 500 lines chunks. If the chunks are too small, the mappers will receive too many messages, which makes the code go slow. If the chunks are too big, the job will not be split evenly among the mappers[5].</p>
<pre class="brush: ruby; title: ; notranslate">start = nil
values = Hash.new 0
linesToRead = input.size
reduceActor = actor do |message|
  linesToRead -= 1
  hash = message
  hash.each do |key, value|
    values[key] += value
  end
  if linesToRead == 0
    puts &quot;&gt;&gt; All over: Just to say we used any computed value: #{values['shakespeare']}&quot;
    finish = Time.now
    puts &quot;&gt;&gt; Total time: #{finish - start}s&quot;
    Akka::ActorRegistry.shutdownAll()
  end
end
</pre>
<p>The reducer actor is pretty straightforward. When all chunks are read, he shutdowns all actors and outputs the result and the time it took for the whole map-reduce chain to take place.</p>
<pre class="brush: ruby; title: ; notranslate">mapActorsSize = 2
mapActors = []
wordCount = WordCount.new
workStealer = AkkaDispatcher.workStealer 'mappers'
mapActorsSize.times do
  mapActor = actor do |message|
    reduceActor.sendOneWay wordCount.count message
  end
  mapActor.setDispatcher workStealer
  mapActors.push mapActor
end
</pre>
<p>The mappers delegate the actual work to an immutable <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/regular_word_count.rb">WordCount class</a>. The important part is the one that sets the same dispatcher on the actors. More on how this work on <a href="http://doc.akkasource.org/dispatchers-java#Dispatchers%20%28Java%29-Types%20of%20dispatchers-Work-stealing%20event-based">Akka&#8217;s documentation</a>.</p>
<pre class="brush: ruby; title: ; notranslate">
mapActor = mapActors.first
producer = actor do |message|
  for line in input
    mapActor.sendOneWay line
  end
end

allActors = [reduceActor, producer] + mapActors
allActors.each do |a|
  a.start
end
start = Time.now
producer.sendOneWay :start
</pre>
<p>These lines define the producer, start all actors, set the start time, and send the producer actor a message, which begins the map-reduce chain. It is important to note that the program&#8217;s main thread finishes on the last line. <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/await_done.rb">This example</a> shows how It is possible to make it wait for the result and then resume the main thread (it requires using the other types of message sending methods, thus I&#8217;ll not cover it in detail).</p>
<p><em>Results:</em> The <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/regular_word_count.rb">sequential version</a> runs on my machine (which has 2 cores) in about 4 seconds. This one with map-reduce actors take about 3 seconds, which yields a 25% improvement[6].</p>
<h4><span style="text-decoration:underline;"><strong><strong><strong><strong>Conclusion</strong></strong></strong></strong></span></h4>
<p>This post showed how it is easy to use Akka actors with JRuby and that they can easily enable thread-safe and easy to reason multicore programming. The <a href="http://akkasource.org/">Akka</a> project has many other tools to help with distributed/parallel programming, such as <a href="http://doc.akkasource.org/remote-actors-java">remote actors</a>, <a href="http://doc.akkasource.org/stm-java">software transactional memory</a>, and integrations with all sorts of persistence/queue systems. This post barely scratches the surface.</p>
<p>All the code on this blog post can be found on <a href="https://github.com/danielribeiro/RubyOnAkka/">github</a>, where all dependencies are easily available, and instructions on how to easily run the code. Give it a try, and see if you agree (<a href="http://codemonkeyism.com/actor-myths/?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+stephansblog+%28Code+Monkeyism+|+Stephans+Blog%29">or not</a>) with <a href="http://beust.com/weblog/2010/08/19/clojure-concurrency-and-silver-bullets/?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed%3A+beust%2FOtakuXml+%28Otaku%2C+Cedric%27s+weblog%29#comment-8472">others</a> that writing parallel code can be much easier and fun.</p>
<h4><span style="text-decoration:underline;"><strong><strong><strong><strong><strong><strong><strong><strong>Footnotes</strong></strong></strong></strong></strong></strong></strong></strong></span></h4>
<p>[1] As Daniel Spiewak showed it on his <em><a href="http://www.codecommit.com/blog/ruby/integrating-scala-into-jruby">Integrating Scala into JRuby</a></em> post.</p>
<p>[2] Incidentally Akka was started by <a href="http://jonasboner.com/">Jonas Bonér</a>, who is also one of the creators of  the java AOP tool <a href="http://aspectwerkz.codehaus.org/">AspectWerkz</a>, which is included in <a href="http://eclipse.org/aspectj/">Aspectj</a> nowadays.</p>
<p>[3] From a <a href="http://www.infoq.com/interviews/functional-langs">interview with</a> Joe Armstrong, the creator of Erlang:</p>
<p><em>Actually  it’s a kind of 180 degree turn because I wrote a blog article that said  &#8220;Why object-oriented programming is silly&#8221; or &#8220;Why it sucks&#8221;. I wrote  that years ago and I sort of believed that for years. Then, my thesis  supervisor, Seif Haridi, stopped me one day and he said &#8220;You’re wrong!  Erlang is object oriented!&#8221;</em></p>
<p>[4] In general, you need to create a <a href="http://doc.akkasource.org/untyped-actors-java#Actors%20%28Java%29--Creating%20Actors%20with%20non-default%20constructor">UntypedActorFactory</a> to pass arguments to the constructor, which we <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/akka.rb#L14">already do</a> (implicitly, using <a href="http://kenai.com/projects/jruby/pages/CallingJavaFromJRuby#Closure_conversion">JRuby&#8217;s closure to interface</a> coercion), but even then Ruby&#8217;s Actors <a href="https://github.com/danielribeiro/RubyOnAkka/blob/master/lib/wont_work_if_class_new_is_not_redefined.rb">will not work</a>. This could be worked around by changing the Actors module and invoking another hook method that is not initialize.</p>
<p>[5] Thanks to the Akka committers Viktor Klang and Peter Veentjer for <a href="http://groups.google.com/group/akka-user/browse_thread/thread/d37d03b9f028f8df">the hint.</a></p>
<p>[6] This is not a real benchmark. Making a real one requires a <a href="http://news.ycombinator.com/item?id=1982844">lot more attention to details</a> like jvm warm-up, jiting from ruby to java, jiting on java bytecode, and so on.</p>
<br /> Tagged: <a href='http://metaphysicaldeveloper.wordpress.com/tag/actors/'>actors</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/akka/'>akka</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/concurrency/'>concurrency</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/ruby/'>Ruby</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/scala/'>scala</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/300/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=300&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2010/12/16/high-level-concurrency-with-jruby-and-akka-actors/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>
	</item>
		<item>
		<title>RubyUnderscore: A bit of Arc and Scala in Ruby</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2010/10/31/rubyunderscore-a-bit-of-arc-and-scala-in-ruby/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2010/10/31/rubyunderscore-a-bit-of-arc-and-scala-in-ruby/#comments</comments>
		<pubDate>Mon, 01 Nov 2010 01:17:46 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Closures]]></category>
		<category><![CDATA[Implementation]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/?p=271</guid>
		<description><![CDATA[A few months ago I&#8217;ve mentioned one thing that bothered me in ruby was &#8220;No way to create simple blocks&#8221;. This is in contrast to other languages, such as Scala, Clojure and Groovy&#8217;s underscore, percent and &#8220;it&#8221;, respectively, shortcut notations. There are other languages with equivalent mechanisms as well. Even newer languages like Coffeescript have [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=271&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>A <a href="../../../../../2010/03/31/improving-ruby/">few months ago</a> I&#8217;ve mentioned one thing that bothered me in ruby was   <em>&#8220;</em><em>No way to create simple blocks&#8221;</em><em>. </em>This is in contrast to other languages, such as Scala, Clojure and Groovy&#8217;s underscore, percent and &#8220;it&#8221;, respectively, shortcut notations. There <a href="http://github.com/jashkenas/coffee-script/issues/issue/739/#issue/739">are other languages </a>with equivalent mechanisms as well. Even newer languages like <a href="http://jashkenas.github.com/coffee-script/">Coffeescript</a> have <a href="http://github.com/jashkenas/coffee-script/issues/issue/739/#comment_450208">considered</a> adding it. As James Iry <a href="http://james-iry.blogspot.com/2010/03/robert-fischer-finally-admits-that.html">mentioned</a>, such constructs are in fact related to <a href="http://okmij.org/ftp/gengo/#Scala-trace">delimited continuations</a>.</p>
<p>However ruby has <a href="http://en.wikipedia.org/wiki/Abstract_syntax_tree">Syntax Tree</a> manipulation (via <a href="http://parsetree.rubyforge.org/">Parse Tree</a> gem). Using it I created the <a href="http://github.com/danielribeiro/RubyUnderscore">RubyUnderscore</a> project, which brings this ruby, using the underscore symbol (just like <a href="http://www.scala-lang.org/">Scala</a> and <a href="http://arclanguage.org/">Arc</a>). With it, it is possible to refactor the following:</p>
<pre><strong><code>    classes.reject { |c| c.subclasses.include?(Enumerable) }</code>
<code>    dates.select { |d| d.greater_than(old_date) }</code>
<code>    collection.map { |x| x.invoke }</code></strong></pre>
<p>into:</p>
<pre><strong><code>    classes.reject _.subclasses.include? Enumerable</code>
<code>    dates.select _.greater_than old_date</code>
<code>    collection.map _.invoke</code></strong></pre>
<p>The last case can also use symbol to proc coercion (appending &amp; to symbol):</p>
<pre><strong><code>     collection.map &amp;:invoke</code></strong></pre>
<p>However, the proc coercion is not flexible enough to allow arguments or invoke a method chain. Which I think brings a small increase in readability and <a href="../../../../../wp-admin/post.php?post=46&amp;action=edit">code quality</a>, not to mention that by making closures easier to declare, it fosters them to be used more. I find this to be a <a href="../../../../../wp-admin/post.php?post=64&amp;action=edit">good thing</a>, specially when you start to refactor your loops into <a href="http://ruby-doc.org/core-1.8.7/classes/Enumerable.html#M001146">maps</a>, <a href="http://ruby-doc.org/core-1.8.7/classes/Enumerable.html#M001143">selects</a>, <a href="http://ruby-doc.org/core-1.8.7/classes/Enumerable.html#M001144">rejects</a>, <a href="http://ruby-doc.org/core-1.8.7/classes/Enumerable.html#M001150">group_bys</a> and <a href="http://ruby-doc.org/core-1.8.7/classes/Enumerable.html#M001148">reduces</a></p>
<p>This also highlights another issue I mentioned in <a href="../../../../../2010/03/31/improving-ruby/">Improving Ruby</a>: that Syntax Tree manipulation is too important to be supported only on MRI, and not throughout the implementations, like JRuby and Rubinius. Python has this built in into its standard library (through <a href="http://docs.python.org/library/ast.html">ast</a> module and <a href="http://docs.python.org/library/inspect.html#inspect.getsource">inspect.getsource</a>), and Lisp can also do syntax tree manipulation with its <a href="http://stackoverflow.com/questions/1988/how-far-can-lisp-macros-go">macro system</a>. The importance of such capability was <a href="http://www.paulgraham.com/ilc03.html">mentioned</a> by <a href="../../../../../2010/04/30/scrapbooking-startup-essays/">Paul Graham</a> (one of the creators of Arc, which is a dialect of Lisp):</p>
<p><em>Letting people rewrite your language is a good idea. You, as the language designer, can&#8217;t possibly anticipate all the things programmers are going to want to do with it. To the extent they can rewrite the language, you don&#8217;t have to.</em></p>
<p>However, syntax tree manipulation in ruby is not only unsupported in most implementations, but it is also poorly documented (even though <a href="http://www.postrank.com/">PostRank&#8217;s</a> founder <a href="http://twitter.com/#%21/igrigorik">Ilya Grigorik</a>&#8216;s post on the <a href="http://www.igvita.com/2008/12/11/ruby-ast-for-fun-and-profit/?utm_source=feedburner&amp;utm_campaign=Feed:+igvita+%28igvita.com%29&amp;utm_content=feed">subject is a very good introduction</a>) and a bit awkward to use: the <a href="http://en.wikipedia.org/wiki/Visitor_pattern">visitor</a> from <a href="http://rubygems.org/gems/sexp_processor">sexp-processor gem</a> embraces side effect (mutating all the tree nodes while processing them) and the tree nodes are just arrays, unlike Python&#8217;s modules where there is a class for every node type. It is important to note that if you are willing to pre-process your ruby code, you can use <a href="http://seattlerb.rubyforge.org/ruby2ruby/">ruby2ruby</a> to generate the equivalent and regular ruby code, which will work all over.</p>
<p>These techniques are expected to be fixed as more people realize the gains they bring, and these improvements find their way into YARV and eventually other ruby implementations. Ruby is a very nice, clean, productive and elegant language, and it would be shame if we stopped making it even better.</p>
<br /> Tagged: <a href='http://metaphysicaldeveloper.wordpress.com/tag/closures/'>Closures</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/implementation/'>Implementation</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/ruby/'>Ruby</a>, <a href='http://metaphysicaldeveloper.wordpress.com/tag/scala/'>scala</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/271/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=271&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2010/10/31/rubyunderscore-a-bit-of-arc-and-scala-in-ruby/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>
	</item>
		<item>
		<title>The Issue with Static Typing</title>
		<link>http://metaphysicaldeveloper.wordpress.com/2010/06/30/the-issue-with-static-typing/</link>
		<comments>http://metaphysicaldeveloper.wordpress.com/2010/06/30/the-issue-with-static-typing/#comments</comments>
		<pubDate>Thu, 01 Jul 2010 02:53:07 +0000</pubDate>
		<dc:creator>Daniel Ribeiro</dc:creator>
				<category><![CDATA[Languages]]></category>

		<guid isPermaLink="false">http://metaphysicaldeveloper.wordpress.com/?p=212</guid>
		<description><![CDATA[&#8220;Shouldn&#8217;t we use Scala?&#8221; is a recurring question my peers make me. I think it is fair, since I have advocated in the past that Scala has a lot of strong points compared to Java. Furthermore, this question is usually made in contrast to dynamic languages, usually Ruby or Python. Since I don&#8217;t want to [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=212&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>&#8220;Shouldn&#8217;t we use Scala?&#8221; is a recurring question my peers make me. I think it is fair, since I have <a href="http://metaphysicaldeveloper.wordpress.com/2009/07/29/scala-the-successor-to-the-throne/">advocated in the past </a>that Scala has a lot of strong points compared to Java. Furthermore, this question is usually made in contrast to dynamic languages, usually Ruby or Python.</p>
<p>Since I don&#8217;t want to discuss that common confusion of  strong with static typing, I&#8217;ll try to be very clear about what I&#8217;m talking about. By static type I mean that the types of all data must be known at <em>compile time</em>. By dynamic I mean that the types may not be known until runtime. Of course, this ignores languages that have mixed typing, such as Groovy, Objective-C and C#4.0 (as it includes the <a href="http://stackoverflow.com/questions/244302/what-do-you-think-of-the-new-c-40-dynamic-keyword">dynamic keyword</a>), but for argument&#8217;s sake, these can be ignored as the issues of static typing will apply to these as well whenever you are using it, and will not whenever you aren&#8217;t. The common examples of languages are Smalltalk, Clojure, Erlang, Ruby, Python, Lisp, Lua, Javascript, for dynamically typed, and Java, Haskell, Scala, C#, C++ for statically typed.</p>
<p>Statically typed languages have as usual <em>claimed</em> benefits that they are faster than dynamic languages, their types provide documentation of the methods and functions, static analysis tools can be more comprehensive and yield better results, and automated refactoring is a lot easier to accomplish and can also give better results. All of these reflect more the current state of implementation and tooling of such languages than of intrinsic property of the type  of the language. Steve Yegge <a href="http://steve-yegge.blogspot.com/2008/05/dynamic-languages-strike-back.html">has argued</a> this about the speed property, but one can argue for dynamic language that its tooling could use type information from runtime sources, such as unit-testing, to yield similar results .</p>
<p>But some hidden complexities take place when using static typing, which may overthrow any possible benefits coming from it:</p>
<ul>
<li>The biggest one is <em>type coupling</em>. For instance, in dynamic languages, renaming an interface is trivial as most interfaces are not even declared, just  documented (such as &#8220;this must implement less than&#8221;). <a href="http://codemonkeyism.com/scala-goodness-structural-typing/">Structural typing</a> can ease this, so can <a href="http://dcsobral.blogspot.com/2010/06/implicit-tricks-type-class-pattern.html">type classes</a>. However, even languages that support these can have problems with other refactorings, such as adding methods to an interface. Paul Graham comments about this a little (on the essay <a href="http://paulgraham.com/hp.html">Hackers and Painters</a>):</li>
</ul>
<blockquote><p>Everyone by now presumably knows about the danger of premature optimization. I think we should be just as worried about premature design&#8211; deciding too early what a program should do.</p>
<p>The right tools can help us avoid this danger. A good programming language should, like oil paint, make it easy to change your mind. Dynamic typing is a win here because you <strong>don&#8217;t have to commit to specific data representations up front</strong>. But the key to flexibility, I think, is to make the language very <a href="http://www.paulgraham.com/power.html" target="_blank">abstract</a>.</p></blockquote>
<ul>
<li><em>Some DSLs can&#8217;t be built</em>. A common example is the <a href="http://www.codecommit.com/blog/ruby/xmlbuilder-a-ruby-dsl-case-study">XML DSL</a>. This is because you can&#8217;t have in a pure statically typed language a type that accepts any single method call, returning any single possible return value, given any amount of any arguments of any type. In fact, if you do have this type, you in fact have the <em>dynamic</em> type from C#. Dynamic languages usually support this through a mechanism called <a href="http://www.google.com/url?sa=t&amp;source=web&amp;cd=2&amp;ved=0CBsQFjAB&amp;url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.91.1021%26rep%3Drep1%26type%3Dpdf&amp;rct=j&amp;q=method+lookup+alteration+and+interception&amp;ei=ZSEsTMTYC4KJuAfw2p3CCQ&amp;usg=AFQjCNH7dktUqD_4vSjR5aHidE9U4Y3sIg&amp;sig2=bHOpRznFWe0WqxTJxx9D9w">method lookup  alteration and interception</a>, such as those provided by Smalltalk’s <em>doesNotUnderstand, </em>Ruby’s <em>missing_method</em> and Python&#8217;s <em>__gettattr__</em> method.</li>
<li><em>Natural complexity</em>. By this I mean that every statically typed languages is a proper superset of a dynamic language of itself. This is easy to see from the theory behind types, as the untyped lambda calculus is just the typed lambda calculus with one type (the brave ones can find more about this on <a href="http://math.ucr.edu/home/baez/rosetta.pdf" target="_blank">Physics,  Topology, Logic and Computation A Rosetta Stone</a>).</li>
<li><em>False sense of safety</em>. The types do not guarantee that the implementations maintain the invariants of a type (such as <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle">those described by Baraba Liskov</a>). The common example is a <a href="http://java.sun.com/javase/6/docs/api/">comparator interface</a> in Java. Just because a class implements the interface, it doesn&#8217;t mean that the compare method is transitive, as required by the documentation. James Iry <a href="http://james-iry.blogspot.com/2010/05/types-la-chart.html">recently commented</a> on languages with more complex type systems (he actually said a lot more about type systems in general), that contain theorem provers in their compilers, such <a href="http://en.wikipedia.org/wiki/Agda_%28theorem_prover%29">Agda</a> and <a href="http://en.wikipedia.org/wiki/Epigram_%28programming_language%29">Epigram</a>, which can solve this issue. However such languages have other limitations, such as not being <a href="http://en.wikipedia.org/wiki/Turing_Complete">Turing Complete</a>. This essentially means that testing practices are still as needed as for static languages (even if you have theorem provers, you cannot be sure without some form of acceptance tests that the problem you are trying to solve is actually the one the customer had in his mind).</li>
<li><em><a href="http://www.scala-lang.org/node/129">Type variances</a></em>. This is actually two problems: if your languages does not support them, you have to fall back to <a href="http://en.wikipedia.org/wiki/Cast_%28computer_science%29">type casting</a>, which actually violates type-saftey and static typing in general. If your language supports it, you have to know one more concept, and when to apply it. It may not be always clear when a type should be co-variant or contravariant. This is further complicated by the fact that types with side effects (such as mutable objects) have special rules about this (further about this can be found under <em><a href="http://programming-scala.labs.oreilly.com/ch12.html">Variance of Mutable Types</a></em>, from Programming Scala). Also this concept is so common that functions are naturally covariant on the return value and contravariant on the parameters. Scala&#8217;s <a href="http://www.scala-lang.org/docu/files/api/scala/Function2.html">two argument function</a> documentation shows this explicitly.</li>
</ul>
<p>The last two issues are very diminished for languages without <a href="http://en.wikipedia.org/wiki/Subtype">subtyping</a>, but these have deeper problems as, in order to relinquish subtyping, you also have to give up on any possibility of code reuse possibility from <a href="http://en.wikipedia.org/wiki/Ad-hoc_polymorphism">ad-hoc polymorphism</a>.</p>
<p>It might seem that some points were left out, but these are usually the problem of a particular language, which are commonly and mistakenly considered to be a problem of static typing in general:</p>
<ul>
<li><em>Lack of metaprogramming support</em>.  Of course C++ has templates, which means that most people know that this is false for all statically typed languages. However, a variant of this issue is: <em>type safe safe metaprogramming</em>. This is also not true. Haskell, for instance, has a <a href="http://intoverflow.wordpress.com/2010/06/30/haskell-features-id-like-to-see-in-other-languages/">type-safe macro system</a>. Note that you cannot make type-safe runtime metaprogramming in general. For instance: even though some languages allow you to create interfaces that do not exist on compile time, the only way to invoke methods from these is through non type-safe ways (such as reflection).</li>
<li><em>Verbosity</em>. Scala is the canonical counter-example (Scala can be as terse as Clojure <a href="http://news.ycombinator.com/item?id=1467153">in some ways</a>). The more type-inference you have, the less type annotation you have to write. This doesn&#8217;t necessarily make reading it easier, but IDEs can help here. On the other hand, it will never be harder to read than dynamic languages.</li>
</ul>
<p>Going back to the question that originated this discussion: static types can come in handy, and they do have better tools these days. But they do bring complexities way beyond having to type a few extra characters. And these should not be taken lightly when considering to express code in a statically typed language.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/metaphysicaldeveloper.wordpress.com/212/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/metaphysicaldeveloper.wordpress.com/212/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=metaphysicaldeveloper.wordpress.com&#038;blog=7215623&#038;post=212&#038;subd=metaphysicaldeveloper&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://metaphysicaldeveloper.wordpress.com/2010/06/30/the-issue-with-static-typing/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/a509816d7a285952021a2ea5243612af?s=96&#38;d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">Daniel Ribeiro</media:title>
		</media:content>
	</item>
	</channel>
</rss>
