<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Waldheinz</title>
	<atom:link href="http://waldheinz.de/feed/" rel="self" type="application/rss+xml" />
	<link>http://waldheinz.de</link>
	<description>first things first, but not necessarily in that order</description>
	<lastBuildDate>Fri, 02 Sep 2011 13:38:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Fractal Image Compression</title>
		<link>http://waldheinz.de/2011/09/fractal-image-compression/</link>
		<comments>http://waldheinz.de/2011/09/fractal-image-compression/#comments</comments>
		<pubDate>Fri, 02 Sep 2011 13:38:44 +0000</pubDate>
		<dc:creator>Waldheinz</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[fractal]]></category>
		<category><![CDATA[graphics]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://waldheinz.de/?p=1328</guid>
		<description><![CDATA[Just for the fun of it, I spent some time implementing a fractal image compression scheme in JavaScript. Because this is really just an experiment and in no way intended for everyday use, it can only deal with square images of power-of-two dimensions. But besides this (admittedly big) limitation, it actually works. Play with it [...]]]></description>
			<content:encoded><![CDATA[<p>Just for the fun of it, I spent some time implementing a <a href="http://en.wikipedia.org/wiki/Fractal_compression" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Fractal_compression?referer=');">fractal image compression</a> scheme in JavaScript. Because this is really just an experiment and in no way intended for everyday use, it can only deal with square images of power-of-two dimensions. But besides this (admittedly big) limitation, it actually works. </p>
<h2>Play with it</h2>
<p>I have set up a <a href="http://waldheinz.de/experiments/fic/" target="fic">separate page</a> where you can play with the compression. If you have trouble figuring out how to use it or what it&#8217;s about at all, please read the rest of this post as it might help to get started.</p>
<h2>How it works</h2>
<p>The mathematically inclined might want to refer to the Wikipedia article linked above on <em>why</em> fractal compression works at all, here I&#8217;ll only outline <em>how</em> I implemented it. As already said, we start with the square power-of-two image we want to find a fractal representation for. This image is subdivided into non overlapping <em>domains</em> of let&#8217;s say 16px² (one reason for the square &#038; POT restriction is to make this possible without ugly corner cases). We also perform another subdivision of the image into <em>ranges</em>. The only real requirement for those ranges is that they must be strictly larger than the domains. In this implementation, the image is subdivided using a quadtree scheme, starting with the whole image and going down to ranges which are twice the size of the domains. These get scaled down to the domain size (using bilinear interpolation).</p>
<p>Now we have a rather big pool of range images, and the real work starts: We do an exhaustive search for range images which cover our domains as good as possible. We use the mean squared error to determine the similarity here. To improve the quality of our matches, two additional operations are performed on the ranges:</p>
<ul>
<li>The range images may be transformed to match the domains. The algorithm tries all <a href="http://www.math.csusb.edu/notes/advanced/algebra/d4/d4.html" onclick="pageTracker._trackPageview('/outgoing/www.math.csusb.edu/notes/advanced/algebra/d4/d4.html?referer=');">eight symmetries of the square</a> and chooses the best. This is the main reason for the &#8220;only squares&#8221; restriction.</li>
<li>Also, we apply a brightness/contrast adjustment to our source (range) image. The nice thing about this step is, that by doing a linear regression analysis we get both, the optimal coefficients <em>and</em> the resulting error by looping over the pixel values only once.</li>
<li>The heart of the encoding algorithm works only on gray-scale images. To support color images, their color information is converted from RGB to YUV color space, and the three resulting grey-scale channels are encoded in terms of each other.</li>
</ul>
<p>Using this scheme, the pixel colors of every domain block are reduced to a block like this (in JSON notation):</p>
<pre>
{
   "pos": [3, 3, 2],
   "channel": 0,
   "transform": 6,
   "brightness": 80.87387183475751,
   "contrast": -0.837734338904282,
}
</pre>
<p>The meaning of these properties is as follows:</p>
<ul>
<li><strong>pos</strong> defines the position of the range block in the source image, where an empty list means the whole source image is used for this domain block, [0] would mean the upper left quarter is used, [0,3] means the lower right quarter of the upper left quarter is used, and so on.</li>
<li><strong>channel</strong> is only really used for color images, and specifies the source channel where to extract from</li>
<li><strong>transform</strong> is in the range [0..7] and specifies which of the eight transformations to apply to this source image and finally</li>
<li><strong>brightness</strong> and <strong>contrast</strong> specify the value adjustment for the source image</li>
</ul>
<p>You&#8217;re still reading&#8230; just <a href="http://waldheinz.de/experiments/fic/" target="fic">start playing</a> with the damn thing and if you care just post a questing in the comments section below.</p>
]]></content:encoded>
			<wfw:commentRss>http://waldheinz.de/2011/09/fractal-image-compression/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Menger Sponge</title>
		<link>http://waldheinz.de/2011/03/menger-sponge/</link>
		<comments>http://waldheinz.de/2011/03/menger-sponge/#comments</comments>
		<pubDate>Tue, 08 Mar 2011 19:10:35 +0000</pubDate>
		<dc:creator>Waldheinz</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[graphics]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[raytracing]]></category>

		<guid isPermaLink="false">http://waldheinz.de/?p=1275</guid>
		<description><![CDATA[Last weekend I found some time to tie together some loose ends of my Haskell ray-tracing project. The new functionality was first put into use to render the inevitable Menger Sponge as you can see below. Here&#8217;s a quick rundown of what&#8217;s new with this iteration: added support for triangles (and meshes thereof); indeed everything [...]]]></description>
			<content:encoded><![CDATA[<p>Last weekend I found some time to tie together some loose ends of my Haskell ray-tracing project. The new functionality was first put into use to render the inevitable <a href="http://en.wikipedia.org/wiki/Menger_sponge" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Menger_sponge?referer=');">Menger Sponge</a> as you can see below.</p>
<p><a href="http://waldheinz.de/wp/wp-content/uploads/2011/03/menger_sponge.png"><img src="http://waldheinz.de/wp/wp-content/uploads/2011/03/menger_sponge-300x225.png" alt="A Menger Sponge" title="Menger Sponge" width="300" height="225" class="aligncenter size-medium wp-image-1276" /></a></p>
<p>Here&#8217;s a quick rundown of what&#8217;s new with this iteration:</p>
<ul>
<li>added support for triangles (and meshes thereof); indeed everything visible in the above scene consists solely of triangles</li>
<li>implemented a simple BVH for intersection acceleration; the performance still leaves something to desire, but at least it makes rendering scenes with more than like 15 primitives bearable</li>
<li>there were several cleanups and simplifications all around, but it&#8217;s been a while and I don&#8217;t remember exactly&#8230;</li>
</ul>
<p>And here&#8217;s a level 3 Menger Sponge on a &#8220;brushed metal&#8221; ground, which take ages to render, mainly because of the inefficient sampling of the glossiness:</p>
<p><a href="http://waldheinz.de/wp/wp-content/uploads/2011/03/Blue-Menger.png"><img src="http://waldheinz.de/wp/wp-content/uploads/2011/03/Blue-Menger-300x225.png" alt="Blue Menger Sponge" title="Blue Menger" width="300" height="225" class="aligncenter size-medium wp-image-1300" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://waldheinz.de/2011/03/menger-sponge/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Cleaning up Resources with Guice</title>
		<link>http://waldheinz.de/2011/01/cleaning-up-resources-with-guice/</link>
		<comments>http://waldheinz.de/2011/01/cleaning-up-resources-with-guice/#comments</comments>
		<pubDate>Mon, 10 Jan 2011 13:13:00 +0000</pubDate>
		<dc:creator>Waldheinz</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[guice]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://waldheinz.de/?p=1246</guid>
		<description><![CDATA[Building on my last post about implementing a custom Scope in Guice I&#8217;d like to go a little further with that and extend it so it handles automatic releasing of resources as well. For this we first define an interface for everything the must be disposed at the end of usage, which is congruously called [...]]]></description>
			<content:encoded><![CDATA[<p>Building on my <a href="http://waldheinz.de/2010/07/universal-custom-scope-for-guice/">last post</a> about implementing a custom Scope in Guice I&#8217;d like to go a little further with that and extend it so it handles automatic releasing of resources as well. For this we first define an interface for everything the must be disposed at the end of usage, which is congruously called <tt>Disposable</tt>:</p>
<pre>
/**
 * An interface for objects that need to be disposed after usage. This
 * somehow adds a life cycle to objects which are created, in use and after
 * usage must be "disposed" (and should not be used beyond this point).
 *
 * @author Matthias Treydte &lt;waldheinz at gmail.com&gt;
 */
public interface Disposable {

    /**
     * Disposes this object. The general contract is that no instance methods
     * should be invoked on this object after disposal, unless stated otherwise
     * in the method's description.
     */
    public void dispose();
}
</pre>
<p>The idea is that every Object that has some cleaning up to be done after usage implements this interface and does the clean up in its <tt>dispose</tt> implementation. With this, we can just roll an <tt>AttributeHolder</tt> implementation which itself has an defined end-of-life (implements <tt>Disposable</tt>) and disposes all its contained attributes when this method is called. An straight-forward implementation might look like this:</p>
<pre>
/**
 * An abstract base class for implementing the {@link AttributeHolder}
 * interface which has a implementations of the attribute related methods and
 * forwards calls to its {@link #dispose()} method to all contained
 * {@link Disposable} instances.
 *
 * @author Matthias Treydte &lt;waldheinz at gmail.com&gt;
 */
public abstract class AbstractAttributeHolder
        implements AttributeHolder, Disposable {

    private final Object lock = new Object();
    private transient Map&lt;Object, Object&gt; attributes;

    public AbstractAttributeHolder() {
        this.attributes = new HashMap&lt;Object, Object&gt;();
    }

    public void replaceAttributes(Map&lt;Object, Object&gt; newAttr) {
        synchronized (getAttributeLock()){
            this.attributes = newAttr;
        }
    }

    @Override
    public Object getAttributeLock() {
        return this.lock;
    }

    @Override
    public final void putAttribute(Object key, Object value) {
        synchronized (getAttributeLock()) {
            attributes.put(key, value);
        }
    }

    @Override
    public final boolean hasAttribute(Object key) {
        synchronized (getAttributeLock()) {
            return attributes.containsKey(key);
        }
    }

    @Override
    public final Object getAttribute(Object key) {
        synchronized (getAttributeLock()) {
            return attributes.get(key);
        }
    }

    @Override
    public final Set&lt;Object> getAttributes() {
        synchronized (getAttributeLock()) {
            return Collections.unmodifiableSet(
                    new HashSet&lt;Object&gt;(this.attributes.values()));
        }
    }

    @Override
    public void dispose() {
        synchronized (this.getAttributeLock()) {
            for (Object o : this.attributes.values()) {
                if (o instanceof Disposable) {
                    final Disposable d = (Disposable) o;
                    d.dispose();
                }
            }

            this.attributes.clear();
        }
    }
}
</pre>
<p>The interesting stuff happens in the <tt>dispose</tt> method where the contained map is scanned for instances of <tt>Disposable</tt> whose <tt>dispose</tt> method is then called in turn. This way concrete subclasses of <tt>AbstractAttributeHolder</tt> can be nested and when the outer scope is dispose, so are all nested scope and all the contained <tt>Disposable</tt> attributes.</p>
<h2>Synchronization</h2>
<p>The solution proposed in here is suitable for use in an multi-threaded environment, and like to elaborate on why I think it is so. The <tt>AttributeHolderScope</tt> basically binds some <tt>AttributeHolder</tt> to the current thread by the means of a <tt>ThreadLocal</tt> variable. But there is nothing that prevents any given <tt>AttributeHolder</tt> instance from being used by multiple threads concurrently. This is where the <tt>attributeLock()</tt> enters the stage. It is used to establish synchronization for modifying the <tt>HashMap</tt> which is the working horse of the <tt>AbstractAttributeHolder</tt>. Similarly, it also ensures the happens-before relation when reading from the map in the <tt>AttributeHolderScope.scope(..)</tt> method in case the map was modified by some other thread while the current thread is in the scope. Honestly, there is still some investigation needed here because I&#8217;m not entirely sure that this synchronization is sufficient when Guice has to build objects with a dependency tree with a depth &gt; 1. So far it behaves nicely, though&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://waldheinz.de/2011/01/cleaning-up-resources-with-guice/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Reading the Skype Chat Log</title>
		<link>http://waldheinz.de/2010/10/reading-the-skype-chat-log/</link>
		<comments>http://waldheinz.de/2010/10/reading-the-skype-chat-log/#comments</comments>
		<pubDate>Thu, 14 Oct 2010 20:40:13 +0000</pubDate>
		<dc:creator>Waldheinz</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[skype]]></category>

		<guid isPermaLink="false">http://waldheinz.de/?p=1193</guid>
		<description><![CDATA[I don&#8217;t use Skype that often, but as it seems sometimes you just have to&#8230; If you think it would be nice to read your Skype&#8217;s chat log without starting up the Skype software, now you can. I hacked a python script that will read the chat log from the Skype user data folder and [...]]]></description>
			<content:encoded><![CDATA[<p>I don&#8217;t use Skype that often, but as it seems sometimes you just have to&#8230; If you think it would be nice to read your Skype&#8217;s chat log without starting up the Skype software, now you can. I hacked a python script that will read the chat log from the Skype user data folder and print it to the console so you can rediscover long-lost treasures:</p>
<pre>
Sonium - 2006-10-24 18:25:30 : someone speak python here?
lucky - 2006-10-24 18:25:53 : HHHHHSSSSSHSSS
lucky - 2006-10-24 18:26:08 : SSSSS
Sonium - 2006-10-24 18:26:16 : the programming language
</pre>
<p>The script was written using the <a href="http://dmytry.pandromeda.com/texts/skype_chatlogs_friday_13.html" onclick="pageTracker._trackPageview('/outgoing/dmytry.pandromeda.com/texts/skype_chatlogs_friday_13.html?referer=');">storage format</a> analysis by Dmytry Lavrov. It works across at least Skype version 2.1.0.81 on Linux and some not-so-recent Windows version (don&#8217;t know exactly, sorry). The only command line parameter is the path to the directory where it will find the <tt>chatmsg*.dbb</tt> files and extract the relevant information. The main benefits of this script are</p>
<ul>
<li>that it decodes the obscure date/time format in the database (?) files, and</li>
<li>uses this information to sort the log entries before printing them out, so you can follow conversations</li>
</ul>
<p>Otherwise you can simply look at these files using your favorite hex editor as the messages themselves are stored in plain text format. You can <a href='http://waldheinz.de/wp/wp-content/uploads/2010/10/skype_chat_log.py'>download</a> the script or copy-and-paste it from below.</p>
<pre>
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from datetime import datetime

workDir = sys.argv[1]

sizes = [256, 512, 1024, 2048, 4096]

def readString(data, offset):
  result=''
  while (data[offset] != '\x00'):
    result += str(data[offset])
    offset += 1
  return result

class Message:
  def __init__(self, time, sender, message):
    self.time = time
    self.sender = sender
    self.message = message

  def __cmp__(self, other):
    return cmp(self.time, other.time)

  def __str__(self):
    return self.sender + " - " + str(self.time) +  " : " + self.message

def decodeTime(data, tsOffset):
  ts = ((ord(data[tsOffset+2]) &#038; ~0x80) << 0) | \
    ((ord(data[tsOffset+3]) &#038; ~0x80) << 7) | \
    ((ord(data[tsOffset+4]) &#038; ~0x80) << 14) | \
    ((ord(data[tsOffset+5]) &#038; ~0x80) << 21) | \
    ((ord(data[tsOffset+6]) &#038; 0x0f) << 28)

  return datetime.fromtimestamp(ts)

allMessages = []

for size in sizes:
  try:
    f = open(workDir + '/chatmsg' + str(size) + '.dbb', 'rb')
    data = f.read()
    f.close()
  except IOError:
    continue

  pos=0
  while (1):
    membersOffset = data.find('\xe0\x03\x23', pos)

    if (membersOffset == -1): break
    # ignore member names (until ";")

    tsOffset = data.find('\xe5\x03', membersOffset)
    if (tsOffset == -1): break
    time = decodeTime(data, tsOffset)

    senderOffset = data.find('\xe8\x03', membersOffset + 4)
    if (senderOffset == -1): break
    sender = readString(data, senderOffset+2)

    msgOffset = data.find('\xfc\x03', senderOffset + 2 + len(sender))
    if (msgOffset == -1): break
    msg = readString(data, msgOffset + 2)

    allMessages.append(Message(time, sender, msg))

    pos=senderOffset

allMessages.sort()

for msg in allMessages:
  print msg
</pre>
]]></content:encoded>
			<wfw:commentRss>http://waldheinz.de/2010/10/reading-the-skype-chat-log/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Animated Fractal Flame</title>
		<link>http://waldheinz.de/2010/07/animated-fractal-flame/</link>
		<comments>http://waldheinz.de/2010/07/animated-fractal-flame/#comments</comments>
		<pubDate>Tue, 27 Jul 2010 14:13:37 +0000</pubDate>
		<dc:creator>Waldheinz</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[graphics]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://waldheinz.de/?p=870</guid>
		<description><![CDATA[Last evening I was playing around with genetic algorithms to do something you could call fractal image compression. I did so becaue I stumbled upon this cool page and wanted to play with something similar, unfortunately with limited success so far. But meanwhile I can show off an animated iterated function system (aka fractal flame). [...]]]></description>
			<content:encoded><![CDATA[<p>
Last evening I was playing around with genetic algorithms to do something you could call fractal image compression. I did so becaue I stumbled upon <a href="http://alteredqualia.com/visualization/evolve/" onclick="pageTracker._trackPageview('/outgoing/alteredqualia.com/visualization/evolve/?referer=');">this cool page</a> and wanted to play with something similar, unfortunately with limited success so far. But meanwhile I can show off an animated iterated function system (aka fractal flame).
</p><p>
It works like this: the two smaller images are the endpoints of the animation, and when you press "start" the larger view gets interpolated between the two. If you click any of the small images it gets replaced with a fresh, random flame.
</p>

<table style="width:auto; margin: 0 auto;">
   <tr><td>
      <canvas id="leftCanvas" width="150" height="100"
         onclick="ifsLeft = randomIfs(fCount); init(); return false;"></canvas>
   </td><td rowspan="2">
      <canvas id="animation" width="300" height="200" ></canvas>
   </td></tr><tr><td>
      <canvas id="rightCanvas" width="150" height="100"
         onclick="ifsRight = randomIfs(fCount); init(); return false;"></canvas>
   </td></tr>
   <tr><td colspan="2">
<form name="controls" action="" style="text-align: center; vertical-align:middle;">
<div id="fps" style="float:left">-- fps</div>
<div style="float:right;">
<select name="qsel" size="1" 
   onchange="setQuality(this.form.qsel.options[this.form.qsel.selectedIndex].value)">
      <option value="5">Woo - Hoo</option>
      <option value="20" selected>Good</option>
      <option value="40">Fair</option>
      <option value="60">So - So</option>
</select>&nbsp;quality
</div>
<input type="button" value=" start " onclick="doStart()" >
<input type="button" value=" stop " onclick="doStop()" >
</form>
   </td></tr>
</table>

<p>
This thing works with current Chromium and Firefox but there's something wrong with Opera <del datetime="2010-07-27T20:56:26+00:00">that I'm not willing to investigate</del>. See below. <del datetime="2010-07-27T15:19:09+00:00">Internet Explorer fails as usual.</del> Thanks to pinetree it works with IE 9 beta now. Just for the record: I get around 10 fps for "Good" quality using Chromium 5.0.375.99 on my Core 2 Duo E8400 @ 3 GHz.
</p><p>
<em>Update</em> I checked what's up with Opera, and as it turns out Opera does not implement the createImageData method. But then, it supports the getImageData method, and I can paint the pixels black by myself. There is a page about the <a href="http://dev.opera.com/articles/view/html-5-canvas-the-basics/#pixelbasedmanipulation" onclick="pageTracker._trackPageview('/outgoing/dev.opera.com/articles/view/html-5-canvas-the-basics/_pixelbasedmanipulation?referer=');">HTML 5 canvas</a> at the Opera dev center. It states:
</p>
<blockquote>
Note: not all browsers implement createImageData. On such browsers, you need to obtain your ImageData object using the getImageData method.
</blockquote>
<p>
Well guys, just fix it and you can remove that ambiguous note. Geeez... And there is still trouble ahead: Opera does not saturate the color values you put in that ImageData object. That means whenever the accumulated value for a pixel gets bigger than 255 freaky colors appear. I could check for that in the JavaScript, but I do not want to sacrifice performance for other browsers.
</p>
<script type="text/javascript">

var fCount = 40;
var quality = 20;
var iterations = 0;

var running = false;
var startTime = null;
var updateCounter = 0;

var ifsLeft = randomIfs(fCount);
var ifsRight = randomIfs(fCount);
var ifs = randomIfs(fCount);

var anim = document.getElementById("animation");
var left = document.getElementById("leftCanvas");
var right = document.getElementById("rightCanvas");
var fpsElem = document.getElementById("fps");

var t = 0;
var dt = 0.01;

function setQuality(newQuality) {
   quality = newQuality;
   iterations = fCount / (quality);
   draw(ifsLeft, left);
   draw(ifsRight, right);   
   draw(ifs, anim);
}

function doStop() {
   running = false;
   fpsElem.innerHTML = "-- fps";
}

function init() {
   interpolate(ifs, ifsLeft, ifsRight, t);
   setQuality(quality);
}

function interpolate(ifs, left, right, t) {
   for (var i=0; i < ifs.length; i++) {
      for (var j=0; j < ifs[i].length; j++) {
         ifs[i][j] = t * right[i][j] + (1-t) * left[i][j];
      }
   }
}

function doStart() {
   if (running) return;
   
   running = true;
   startTime = timeStamp();
   updateCounter = 0;
   setTimeout(step, 50);
}

function timeStamp() {
    return 0.001 * (new Date).getTime();
}

function step() {
   if (!running) return;
   t += dt;
   if (t > 0.5) dt -= 0.0002;
   else dt += 0.0002;

   interpolate(ifs, ifsLeft, ifsRight, t);
   draw(ifs, anim);

   updateCounter++;
   if (updateCounter % 20 == 0) {
        var mutsec = (updateCounter)/(timeStamp() - startTime);
        fpsElem.innerHTML = mutsec.toFixed(1) + " fps";
        updateCounter = 0;
        startTime = timeStamp();
    }
   
   setTimeout(step, 1);
}

function randomIfs(funcs) {
   var ifs = Array();
   var s = 0.15 * Math.sqrt(fCount);

   for (var i=0; i < funcs; i++) {
      var func = Array();
      for (var j=0; j < 6; j++) {
         func.push((Math.random() - 0.5) * s);
      }
      ifs.push(func);
   }
   return ifs;
}

function draw(ifs, canvas) {
   var ctx = canvas.getContext("2d");
   var w = canvas.width;
   var h = canvas.height;         
   var dx = w / 2;
   var dy = h / 2;
   var cdata = null;
   if (ctx.createImageData) {
      cdata = ctx.createImageData(w, h);
   } else {
      cdata = ctx.getImageData(0, 0, w, h);
      for (var i=0; i < 4*w*h; i++) {
          cdata.data[i] = 0;
      }
   }
   var data = cdata.data;
   var x = 0;
   var y = 0;
   
   for (var i=0; i < iterations * w * h; i++) {
      var func = ifs[Math.floor(Math.random() * ifs.length)];
      var o = 0;
      var tx = func[o++] * x + func[o++] * y + func[o++];
      y = func[o++] * x + func[o++] * y + func[o++];
      x = tx;

      if (i < 100) continue;

      var px = Math.floor(x * w + dx);
      var py = Math.floor(y * h + dy);

      if (px >= 0 && px < w && py >= 0 && py < h) {
         var off = (px + py * w) * 4;
         data[off + 0] += 3 * quality;
         data[off + 1] += 2 * quality;
         data[off + 2] += 1 * quality;
      }
   }

   for (var i=0; i < w * h; i++) {
      data[i * 4 + 3] = 255;
   }

   ctx.putImageData(cdata, 0, 0);
}

setTimeout(init, 10);

</script>]]></content:encoded>
			<wfw:commentRss>http://waldheinz.de/2010/07/animated-fractal-flame/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Universal custom Scope for Guice</title>
		<link>http://waldheinz.de/2010/07/universal-custom-scope-for-guice/</link>
		<comments>http://waldheinz.de/2010/07/universal-custom-scope-for-guice/#comments</comments>
		<pubDate>Fri, 23 Jul 2010 19:52:17 +0000</pubDate>
		<dc:creator>Waldheinz</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[guice]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://waldheinz.de/?p=740</guid>
		<description><![CDATA[Guice is a dependency injection (DI) framework by Google I've been using for some time now and I'm starting to get a grasp on recently. Compared to Spring it is very lightweight and most importantly comes without that XML bloat, so I can recommend using it even for the smallest projects. I won't talk about [...]]]></description>
			<content:encoded><![CDATA[<a href="http://code.google.com/p/google-guice/" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/google-guice/?referer=');">Guice</a> is a dependency injection (DI) framework by Google I've been using for some time now and I'm starting to get a grasp on recently. Compared to Spring it is very lightweight and most importantly comes without that XML bloat, so I can recommend using it even for the smallest projects. I won't talk about DI in general here, besides mentioning that in my experience it makes life a whole lot easier when it comes to code maintenance and refactoring and that I don't want to go without it any more.

<h1>The Attribute Holder Scope</h1>

In Guice, a <a href="http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/Scope.html" onclick="pageTracker._trackPageview('/outgoing/google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/Scope.html?referer=');">Scope</a> acts as some kind of "memory" for created instances. Surprisingly, Guice (sans the Servlet extension) ships with only one implementation of the Scope interface, which is the <a href="http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/Singleton.html" onclick="pageTracker._trackPageview('/outgoing/google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/Singleton.html?referer=');">Singleton</a> scope. Given that, we are left with two choices for our bindings:
<ul>
<li>either we do not scope them at all (meaning the objects will be created again every time you require an instance)</li>
<li>or they are singletons (which live forever within an given Injector).</li>
</ul>

For some time I was trying to get along with these, discerning a <em>custom Scope</em> as something deeply magical that I'm not willing to deal with. This was largely due to the fact that I could not dig a non-trivial example for a Scope implementation. I'm trying to improve on that situation here. :-)

After some days (weeks?) of pain and sorrow, working around the lack of proper scopes with obscure "Manager" classes and lengthy Provider implementations, I finally found my happiness by decoupling the actual "memory" from the Scope implementation. The memory part is defined by the AttributeHolder interface which is pretty much an stripped-down Map&lt;Object, Object&gt;, as given below:

<pre>
/**
 * Implementors of this interface can serve as the backing store for
 * Objects that are scoped within an (subclass of) {@link AttributeHolderScope}.
 *
 * @author Matthias Treydte &lt;waldheinz at gmail.com&gt;
 */
public interface AttributeHolder {

    /**
     * Extracts the {@code Object} memorized for the specified key from this
     * {@code AttributeHolder}.
     *
     * @param key the identifier for the attribute to extract
     * @return the {@code Object} stored for the specified key, or {@code null}
     *      if either the {@code null} value was stored for this key or there
     *      is no attribute stored for the key
     * @see #hasAttribute(java.lang.Object) to discriminate the two reasons
     *      this method may return {@code null}
     */
    public Object getAttribute(Object key);

    /**
     * Decides if this {@code AttributeHolder} has an association for the
     * specified key.
     *
     * @param key the key to check if it's known to this {@code AttributeHolder}
     * @return if this key is known
     */
    public boolean hasAttribute(Object key);

    /**
     * Stores a new value in this {@code AttributeHolder}.
     *
     * @param key the key to identify the new attribute
     * @param value the new attribute
     */
    public void putAttribute(Object key, Object value);

    /**
     * Returns all values currently stored in this {@code AttributeHolder}. The
     * returned set can not be modified.
     *
     * @return all attributes of this holder
     */
    public Set&lt;Object&gt; getAttributes();

    /**
     * Returns an object on which to lock when access to multiple methods of
     * the {@code AttributeHolder} are to be made atomic.
     *
     * @return the {@code Object} to synchronize on
     */
    public Object getAttributeLock();
    
}
</pre>

All this interface does is to allow to associate objects with objects (plus some synchronization semantics). I suppose it is as general as it can get... The general rule is that (some of) your business objects (or entities; the stuff you read from a database or create because of user interaction) implement this interface. If you do, they can be used by Guice as a container to hold the scoped objects of the application logic. The only missing piece is the actual Scope implementation that allows Guice to make use of the attributes, which is the AttributeHolderScope:

<pre>
/**
 * A {@code Scope} that uses an {@link AttributeHolder} as the backing store
 * for it's scoped objects.
 * 
 * @author Matthias Treydte &lt;waldheinz at gmail.com&gt;
 */
public class AttributeHolderScope&lt;AHT extends AttributeHolder&gt;
        implements Scope, Provider&lt;AHT&gt; {
    
    private final ThreadLocal&lt;AHT&gt; holder;

    /**
     * Creates a new instance of {@code AttributeHolderScope}.
     */
    public AttributeHolderScope() {
        this.holder = new ThreadLocal&lt;AHT&gt;();
    }

    /**
     * Lets the current {@code Thread} enter this {@code Scope}.
     *
     * @param holder the {@link AttributeHolder} instance for the {@code Scope}
     * @throws IllegalStateException if the current {@code Thread} is already
     *      in this {@code Scope}
     */
    public void enter(AHT holder) throws IllegalStateException {
        if (holder == null)
            throw new NullPointerException();

        if (this.holder.get() != null)
            throw new IllegalStateException(
                    "already in " + getClass().getSimpleName() + " scope");
            
        this.holder.set(holder);
    }

    /**
     * Lets the current {@code Thread} leave this {@code Scope}.
     *
     * @throws OutOfScopeException if the current thread is not in
     *      this {@code Scope}
     */
    public void exit() throws OutOfScopeException {
        assertInScope();
        this.holder.remove();
    }

    /**
     * {@inheritDoc}
     *
     * @return {@docRoot}
     * @throws OutOfScopeException if the current thread is not in
     *      this {@code Scope}
     */
    @Override
    public AHT get() throws OutOfScopeException {
        assertInScope();
        return this.holder.get();
    }
    
    @Override
    public final &lt;T&gt; Provider&lt;T&gt; scope(
            final Key&lt;T&gt; key, final Provider&lt;T&gt; outer) {
        
        return new Provider&lt;T&gt;() {

            @Override
            public T get() {
                assertInScope();
                
                final AttributeHolder ah = holder.get();
                
                synchronized (ah.getAttributeLock()) {
                    T current = (T) ah.getAttribute(key);

                    if ((current == null) && !ah.hasAttribute(key)) {
                        current = outer.get();
                        ah.putAttribute(key, current);
                    }

                    return current;
                }
            }

            @Override
            public String toString() {
                return "Provider [scope=" + //NOI18N
                        AttributeHolderScope.this.getClass().getSimpleName() +
                        ", outer=" + outer.toString() + "]"; //NOI18N
            }
            
        };
    }

    private void assertInScope() throws OutOfScopeException {
        if (holder.get() == null) {
            throw new OutOfScopeException(
                    "not in " + getClass().getSimpleName()); //NOI18N
        }
    }
}
</pre>

In addition to the obvious Scope interface, the AttributeHolderScope also acts as an Provider for the AttributeHolder class it is working on. This way the holder can act as some kind of "root" for the Objects we are about to put into it's Scope.

<h1>How to use it</h1>

Let's assume we're writing a feed reader application (a very <a href="http://www.google.de/trends?q=%22feed+reader%22" onclick="pageTracker._trackPageview('/outgoing/www.google.de/trends?q=_22feed+reader_22&amp;referer=');">2006</a> example, by the way). We would need some means to store the feeds that the user has subscribed to. Therefore the Feed is our first entity, along with it's accompanying FeedScoped annotation and finally the FeedScope itself:

<pre>
public final class Feed implements AttributeHolder {
    private final URL feedUrl;
    private final Map&lt;Object, Object&gt; attributes;

    public Feed(URL feedUrl) {
        this.feedUrl = feedUrl;
        this.attributes = new HashMap&lt;Object, Object&gt;();
    }
   
    public URL getFeedUrl() {
        return this.feedUrl;
    }
    
    public Object getAttributeLock() {
        return this.attributes;
    }

    /* the rest of the AttributeHolder implementation delegates
     * to this.attributes and is omitted
     */
}

@Target({ TYPE, METHOD }) @Retention(RUNTIME) @ScopeAnnotation
public @interface FeedScoped {
    /* nothing */
}

public final class FeedScope extends AttributeHolderScope&lt;Feed&gt; {
    /* nothing */
}
</pre>

Because we don't want to fetch the feeds from the net over and over again as the user wants to read a post, we have a cache for the posts we have already retrieved for a feed (the details of the Post class are omitted for brevity):

<pre>
public interface PostCache {
    public List&lt;Post&gt; getPosts();
    public void putPost(Post newPost);
}

public class TransientPostCache implements PostCache {
    private final List&lt;Post&gt; posts;
    /* implement the PostCache methods using this.posts */
}
</pre>

The beauty of programming against the PostCache interface is that you stay focused and it's easy to swap in a more advanced implementation later (which stores the fetched articles in some form of persistent storage and does other fancy stuff).

Now we can start to profit from our work and implement the first code that actually gets something from our scope injected:

<pre>
public class FeedFetcher {
    @Inject
    public FeedFetcher(URL feedUrl, PostCache cache) {
        /* remember the parameters, ... */
    }

    public void doFetch() throws IOException {
        /* fetch the feed and add the posts to the cache */
    }
}
</pre>

And deep down in the plumbing layer we have a timer that occasionally kicks in and fetches the posts for the feed we have subscribed to:

<pre>
Injector inj = ...;
FeedScope fs = ...;

for (Feed feed : feedList) {
    fs.enter(feed);
    try {
        final FeedFetcher ff = inj.getInstance(FeedFetcher.class);
        ff.doFetch();
    } catch (IOException ex) {
        /* log the error, try again, whatever... */
    } finally {
        fs.exit();
    }
}
</pre>

This assumes we have the list of feeds and the Injector at hand. Then it iterates over the feeds we know of, entering the FeedScope for each of them. Inside the scope we ask the Injector for an FeedFetcher instance which will get the correct URL and PostCache injected and is ready to do it's best to fetch the new posts from the feed. It is important to make sure that every time we enter the FeedScope we have a matching exit(), so we put that into a finally block. All there is left to do is to wire everything up in a Module:

<pre>
public final class FeedModule extends AbstractModule {
    protected void configure() {
        /* initialize the Feed scope */
        final FeedScope fScope = new FeedScope();
        bindScope(FeedScoped.class, fScope);
        bind(Feed.class).toProvider(fScope);
        bind(FeedScope.class).toInstance(fScope);

        bind(PostCache.class).
            to(TransientPostCache.class).
            in(FeedScoped.class);

        bind(FeedFetcher.class);
    }

    @Provides
    @FeedScoped
    URL provideUrl(Feed feed) {
        return feed.getFeedUrl();
    }
}
</pre>

So this would be the outline of a feed reader application that makes use of a custom scope, which is the AttributeHolderScope in this case. 

<h2>Was it worth all the trouble?</h2>

For what we have seen in this example, surely not. But in a real-world application, this is just the beginning (its always just the beginning...). And there's interesting stuff to come! After having these classes up and running you would strive for a more advanced PostCache implementation very soon. Possibly a FilePostCache which stores the posts in files in some directory. But which directory on the file system is the right one? Or a DatabasePostCache which uses some JPA implementation to store the posts. But that would need access to some persistence manager or Database connection. And which is the right Database?

It's surely preferable to get these dependencies <em>magically</em> injected by Guice than to wire everything up by hand, and this is where I see strength of the Guice.]]></content:encoded>
			<wfw:commentRss>http://waldheinz.de/2010/07/universal-custom-scope-for-guice/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>WebKit leaks data URIs</title>
		<link>http://waldheinz.de/2010/06/webkit-leaks-data-uris/</link>
		<comments>http://waldheinz.de/2010/06/webkit-leaks-data-uris/#comments</comments>
		<pubDate>Wed, 23 Jun 2010 12:37:54 +0000</pubDate>
		<dc:creator>Waldheinz</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[webkit]]></category>

		<guid isPermaLink="false">http://waldheinz.de/?p=673</guid>
		<description><![CDATA[The Problem At work we have a web application where data URIs containing JPEG image data are generated on the server, transferred to the client and there the images are displayed by using these URIs as image sources. This approach works and it even performs nicely and all. Sadly, when trying this approach in WebKit [...]]]></description>
			<content:encoded><![CDATA[<h2>The Problem</h2>
<p>
At work we have a web application where data URIs containing JPEG image data are generated on the server, transferred to the client and there the images are displayed by using these URIs as image sources. This approach works and it even performs nicely and all. Sadly, when trying this approach in WebKit based browsers (hello iPad...), we hit a bad memory leak.
</p><p>
As it turns out, all you have to do to trigger this is setting the "source" property of an image. Every time you do this, the image gets updated as expected, but as it seems the memory occupied by the last image that was displayed is never freed. I hacked a small demonstration of this so you can try yourself. But please be aware that this might <strong>crash your browser</strong>.
</p>

<img id="theImage" src="http://waldheinz.de/wp/wp-content/uploads/2010/06/press-start.png" alt="" title="Press start..." width="400" height="300" class="aligncenter size-full" />


<script type="text/javascript">
var image = document.getElementById("theImage");
var running = false;

function startPainting() {
   if (!running) {
      running = true;
      scheduleUpdate();
   }
}

function scheduleUpdate() {
   setTimeout(updateImage, 500);
}

function updateImage() {
   var buffer = [];

   // data URI preamble
   buffer.push("data:image/bmp;base64,");

   // BMP file header
   buffer.push("Qk12fgUAAAAAADYAAAAoAAAAkAEAACwBAAABABgAAAAAAEB+BQATCwAAEwsAAAAAAAAAAAAA");
   
   // 400*300 random pixels
   for (var i=0; i < 400*300; i++) {
      if (Math.random() > 0.5) {
         buffer.push("////"); // white
      } else {
         buffer.push("AAAA"); // black
      }
   }
   
   image.src = buffer.join("");

   if (running) {
      scheduleUpdate();
   }
}

function stopPainting() {
   running = false;
}

</script>


<form name="controls" action="" style="text-align: center; padding-top: 0.5em;">
<input type="button" value=" start " onclick="startPainting()" >
<input type="button" value=" stop " onclick="stopPainting()" >
</form>

<p>
When you hit the "start" button the script will try to update the image every 50ms with a fresh, randomly-generated data URI which should result in an animated white noise (like your TV when not tuned to a station). And when using a current WebKit based browser, you will see the browsers unbounded memory usage. I highly recommend hitting "stop" before your OS starts swapping.
</p><p>
This bug is <a href="http://code.google.com/p/chromium/issues/detail?id=36142" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/chromium/issues/detail?id=36142&amp;referer=');">already known</a> on the chromium issue tracker, but currently unresolved.
</p>

<h2>Affected Browsers</h2>
<p>
Here are some browsers that I tested. If you dare to, post your test results to the comments section and I'll update this list.
</p>
<ul>
<li>Chrome 6 (Windows, 32 bit) : leaks</li>
<li>Chromium 5.0.375.70 (Linux, 64 bit) : leaks</li>
<li>Firefox 3.6.3 (Linux, 64 bit) : <strong>OK</strong></li>
<li>Firefox 3.6.3 (Windows, 32 bit) : <strong>OK</strong></li>
<li>Firefox 3.7a5 (Windows, 32 bit) : <strong>OK</strong></li>
<li>IE 8 (Windows, 32 bit): leaks</li>
<li>IE 9 (Windows, 32 bit): <strong>OK</strong></li>
<li>iPhone 3.1 : leaks (most probably; crash)</li>
<li>iPhone 4 : leaks (like 3.1)</li>
<li>Konqueror 4.3.5 : leaks</li>
<li>Opera 10.10 (Linux, 64 bit) : leaks</li>
<li>Opera 10.* (Windows, 32 bit) : leaks</li>
<li>Safari 5 (Windows, 32 bit) : leaks</li>
</ul>
<p>
To cut it short: Firefox works, all others fail in one or another way.
</p>

<h2>Workaround</h2>
<p>
Welcome to the world of canvas and manual pixel manipulation using JavaScript. Using canvas' capability to draw images is of no use here, as obviously you have to initialize the image-to-be-drawn using an... URI. *yuck*
</p>]]></content:encoded>
			<wfw:commentRss>http://waldheinz.de/2010/06/webkit-leaks-data-uris/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Glass</title>
		<link>http://waldheinz.de/2010/05/glass/</link>
		<comments>http://waldheinz.de/2010/05/glass/#comments</comments>
		<pubDate>Mon, 10 May 2010 15:52:16 +0000</pubDate>
		<dc:creator>Waldheinz</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[graphics]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[raytracing]]></category>

		<guid isPermaLink="false">http://waldheinz.de/?p=622</guid>
		<description><![CDATA[In an utter attempt to ignore the shortcomings of classic pathtracing I recently added a quite pleasing glass material to the ray tracer. It uses specular reflection and refraction, stresses Fresnel's equations for dielectrics to figure out the amount of reflected light and it even handles total internal reflection. I really like the depth in [...]]]></description>
			<content:encoded><![CDATA[In an utter attempt to ignore the shortcomings of classic pathtracing I recently added a quite pleasing glass material to the ray tracer. It uses specular reflection and refraction, stresses <a href="http://www.graphics.cornell.edu/~westin/misc/fresnel.html" onclick="pageTracker._trackPageview('/outgoing/www.graphics.cornell.edu/_westin/misc/fresnel.html?referer=');">Fresnel's equations</a> for dielectrics to figure out the amount of reflected light and it even handles total internal reflection. I really like the depth in the left part of the sphere.

<a href="http://waldheinz.de/wp/wp-content/uploads/2010/05/glass-sphere.png"><img src="http://waldheinz.de/wp/wp-content/uploads/2010/05/glass-sphere-300x225.png" alt="" title="glass-sphere" width="300" height="225" class="aligncenter size-medium wp-image-614" /></a>

Sadly, a simple path tracer has a hard time finding the caustic paths, which leads to an area of noise where parts of the caustic are supposed to be. This was an over night render, and I did not dare to wait a week for the noise to vanish.]]></content:encoded>
			<wfw:commentRss>http://waldheinz.de/2010/05/glass/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Convergence</title>
		<link>http://waldheinz.de/2010/04/convergence/</link>
		<comments>http://waldheinz.de/2010/04/convergence/#comments</comments>
		<pubDate>Wed, 28 Apr 2010 15:01:12 +0000</pubDate>
		<dc:creator>Waldheinz</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[graphics]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[raytracing]]></category>

		<guid isPermaLink="false">http://waldheinz.de/?p=544</guid>
		<description><![CDATA[As we all know the Internet is in desperate need for another sketchy ray tracer. So I kept on digging with mine and added some exciting new features, namely specular reflections, that "graph paper"-esque texture you see in so many test renders, gamma-corrected image output and something I call "incremental rendering" The images below show [...]]]></description>
			<content:encoded><![CDATA[As we all know the Internet is in desperate need for another sketchy ray tracer. So I kept on digging with mine and added some exciting new features, namely
<ul>
<li>specular reflections,</li>
<li>that "graph paper"-esque texture you see in so many test renders,</li>
<li>gamma-corrected image output and</li>
<li>something I call "incremental rendering"</li>
</ul>

The images below show the incremental rendering in action. From left to right there have been more samples taken; move the mouse over the images to see the numbers.

<table><tr>
   <td><a href="http://waldheinz.de/wp/wp-content/uploads/2010/04/pass-00001.png"><img src="http://waldheinz.de/wp/wp-content/uploads/2010/04/pass-00001-150x150.png" alt="4 spp" title="4 spp" width="150" height="150" class="aligncenter size-thumbnail" /></a></td>
   <td><a href="http://waldheinz.de/wp/wp-content/uploads/2010/04/pass-00004.png"><img src="http://waldheinz.de/wp/wp-content/uploads/2010/04/pass-00004-150x150.png" alt="16 spp" title="16 spp" width="150" height="150" class="aligncenter size-thumbnail" /></a></td>
<td><a href="http://waldheinz.de/wp/wp-content/uploads/2010/04/pass-00030.png"><img src="http://waldheinz.de/wp/wp-content/uploads/2010/04/pass-00030-150x150.png" alt="120 spp" title="120 spp" width="150" height="150" class="aligncenter size-thumbnail wp-image-550" /></a></td>
</tr></table>

The idea to enable incremetal rendering is dead simple. You simple keep the image in memory and throw samples at it, from top-left to bottom-right (or in any order you desire). When you reach the bottom-left corner you write out what you've got so far and start over from the top-left again. Here is the main rendering "loop" which does the trick:

<pre>
render :: Int -> Image -> Scene -> Camera -> Integrator -> IO ()
render pass img scene cam int = do
   prng <- newStdGen
   img' <- return $! fromRand $ runRand prng (onePass img scene cam int)
   writeFile ("pass-" ++ (printf "%05d" pass) ++ ".ppm") (imageToPpm img')
   render (pass + 1) img' scene cam int
</pre>

I think this is pretty concise, but when I first tried to run it I was faced with <em>excessive</em> memory consumption, swapping and evil. With some profiling I could spot the reason for that: Haskell is a lazy language. This means that my Image (using a not-unboxed array to hold the pixel values at that time) did not really hold the colour values I wanted to store there -- it contained only thunks for them. You can think of a thunk as an "recipe" describing how to compute that value in case it is needed later on. While this laziness allows to do some cool tricks with Haskel, in this particular case it was shooting my foot. I'm pretty sure I need all that pixel values when writing the image to a file.

Moving to "unboxed" arrays (the getPixel and putPixel functions below were needed for that because only some simple data types can be stored in such an array) did not really resolve the problem: While an Image is just two Ints (width and heigth) and a bunch of Floats (the colour values) now, Haskell came up with another neat idea to get me: You never know if the Image as a whole is needed later on, so why bother with rendering it? I resolved that by throwing a good amount of "seq" statements at random places, until it was finally running in constant space. I think when Haskell's language designers wanted to create a lazy language they really <em>meant</em> it. After all that fuzz, below is the Image module in it's current state. It's missing the accompanying "Color" module which I'll post once I got that RGB, XYZ, Spectrum color space conversion stuff straight.

<pre>
module Image(
   Image, ImageSample(..), 
   imageWidth, imageHeight, 
   imageToPpm, makeImage, addSample) where

import Data.Array.Diff

import Color

-- | places a @WeightedSpectrum@ in an @Image@
data ImageSample = ImageSample {
   samplePosX :: ! Float,
   samplePosY :: ! Float,
   sampleSpectrum :: ! WeightedSpectrum
   } deriving Show

-- | an image has a width, a height and some pixels
data Image = Image {
   imageWidth :: Int,
   imageHeight :: Int,
   _imagePixels :: (DiffUArray Int Float)
   }
   
-- | extracts the pixel at the specified offset from an Image
getPixel :: Image -> Int -> WeightedSpectrum
getPixel (Image _ _ p) o = (p ! o', s) where
   s = fromXyz (p ! (o' + 1), p ! (o' + 2), p ! (o' + 3))
   o' = o * 4
   
-- | puts an pixel to the specified offset in an Image
putPixel :: Image -> Int -> WeightedSpectrum -> Image
putPixel (Image w h p) o (sw, s) = seq p' Image w h p' where
   (sx, sy, sz) = toXyz s
   p' = p // [ (o', sw), (o' + 1, sx), (o' + 2, sy), (o' + 3, sz) ]
   o' = o * 4
   
-- | converts an image to ppm format
imageToPpm :: Image -> String
imageToPpm i@(Image w h _) = header ++ spixels 0
   where
      header = "P3\n" ++ show w ++ " " ++ show h ++ "\n255\n"
      spixels pos
         | pos == (w*h) = []
         | otherwise = (ppmPixel $ getPixel i pos) ++ spixels (pos + 1)

-- | applies gamma correction to an RGB triple
gamma :: Float -> (Float, Float, Float) -> (Float, Float, Float)
gamma x (r, g, b) = (r ** x', g ** x', b ** x') where
   x' = 1 / x

-- | converts a Float in [0..1] to an Int in [0..255], clamping values outside [0..1]
clamp :: Float -> Int
clamp v = round ( (min 1 (max 0 v)) * 255 )

-- | converts a @WeightedSpectrum@ into what's expected to be found in a ppm file
ppmPixel :: WeightedSpectrum -> String
ppmPixel ws = (toString . (gamma 2.2) .toRgb . mulWeight) ws
   where
      toString (r, g, b) = show (clamp r) ++ " " ++
         show (clamp g) ++ " " ++ show (clamp b) ++ " "

-- | converts a weighted spectrum to a plain spectrum by dividing out the weight
mulWeight :: WeightedSpectrum -> Spectrum
mulWeight (0, _) = black
mulWeight (w, s) = sScale s (1.0 / w)

-- | adds an sample to the specified image and returns the updated image
addSample :: Image -> ImageSample -> Image
addSample img@(Image w h _) (ImageSample sx sy (sw, ss))
   | isx > maxX || isy > maxY = img
   | otherwise = seq img' img'
   where
      img' = seq img seq newPixel putPixel img offset newPixel
      isx = floor sx
      isy = floor sy
      maxX = w - 1
      maxY = h - 1
      offset = isy * w + isx
      (oldW, oldS) = getPixel img offset
      newPixel = (oldW + sw, oldS + ss)

-- | creates a new all-black image of the specified width and height
makeImage :: Int -> Int -> Image
makeImage w h = Image w h pixels where
    pixels = listArray (0, pxCount - 1) (repeat 0.0)
    pxCount = w * h * 4 :: Int
</pre>

PS: Yeah, it's amusing how I mix the british "Colour" and the american "Color" spellings, I know that. :-)]]></content:encoded>
			<wfw:commentRss>http://waldheinz.de/2010/04/convergence/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Point of View</title>
		<link>http://waldheinz.de/2010/04/point-of-view/</link>
		<comments>http://waldheinz.de/2010/04/point-of-view/#comments</comments>
		<pubDate>Thu, 22 Apr 2010 19:09:31 +0000</pubDate>
		<dc:creator>Waldheinz</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[graphics]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[raytracing]]></category>

		<guid isPermaLink="false">http://waldheinz.de/?p=511</guid>
		<description><![CDATA[Noticed the previous renders all looked very similar? That's because I did not really have a notion of "view" or camera implemented. There was a hard-coded thing sitting at (0, 0, -4) and firing rays down the z-axis. I just fixed that and came up with a pinhole camera, which is really the least one [...]]]></description>
			<content:encoded><![CDATA[Noticed the previous renders all looked very similar? That's because I did not really have a notion of "view" or camera implemented. There was a hard-coded thing sitting at (0, 0, -4) and firing rays down the z-axis. I just fixed that and came up with a pinhole camera, which is really the least one can expect from a raytracer. This enables really <em>dramatic</em> renderings. Well, as dramatic as it gets if all you have are spheres and planes... :-)

<a href="http://waldheinz.de/wp/wp-content/uploads/2010/04/test9.png"><img src="http://waldheinz.de/wp/wp-content/uploads/2010/04/test9-300x225.png" alt="Three spheres in a dramatic setup" title="Three spheres in a dramatic setup" width="300" height="225" class="aligncenter size-medium wp-image-530" /></a>

<pre>
data Ray = Ray {
   rayOrigin :: Point,
   rayDir :: Normal,
   rayMin :: Float,
   rayMax :: Float
   } deriving Show

type Camera = (Float, Float) -> Ray

-- | defines the view for projective camera models
data View = View {
   viewPos :: Point, -- ^ the position of the camera in world space
   viewLookAt :: Point, -- ^ the "look-at" point world space
   viewUp :: Normal, -- ^ the "up" vector
   viewFocalLength :: Float, -- ^ focal length
   viewAspect :: Float -- ^ aspect ratio of image plane
   }
   
-- | computes a point on the image plane
viewPoint :: View -> (Float, Float) -> Point
viewPoint (View pos la up dist aspect) (u, v) = \
      center `add` (scalMul right u') `add` (scalMul up' v') where
   center = pos `add` (scalMul dir dist)
   right =  normalize $ up `cross` dir
   up' = cross right dir
   dir = normalize $ sub la pos
   u' = u * aspect - 0.5
   v' = v - 0.5

-- | a simple "pinhole" camera
pinHoleCamera :: View -> Camera
pinHoleCamera view uv = Ray pv rd 0 infinity where
   rd = normalize $ sub pv $ viewPos view
   pv = viewPoint view uv
</pre>

So, the code above is all there is about the camera abstraction I currently have. I think it is pretty self-explanatory, besides that magical <code>(Float, Float)</code> going into the Camera function. These are "normalized device coordinates"--numbers in [0, 1] which allow to sample image plane without knowing the size (in pixels) of the image that is being rendered.

Sure, it would be pretty easy to add a camera doing a thin lens approximation at this point. And depth of field is nice and all... But look at the noise in the image above! These are 100 samples per pixel, rendering took almost 150 minutes--and I doubt adding another level of randomness from sampling the lens would do any good here. So before adding that "cool" stuff I'll have to go for a better sampling scheme.

PS: I'm sorry the red sphere in the image above looks so ultra-boring.]]></content:encoded>
			<wfw:commentRss>http://waldheinz.de/2010/04/point-of-view/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

