<?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>#AltDevBlogADay &#187; Ignacio Castaño</title>
	<atom:link href="http://www.altdevblogaday.com/author/ignacio-castano/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.altdevblogaday.com</link>
	<description>Each day a little more #gamedev love</description>
	<lastBuildDate>Mon, 17 Jun 2013 14:45:09 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Seamless Cube Map Filtering</title>
		<link>http://www.altdevblogaday.com/2012/03/03/seamless-cube-map-filtering/</link>
		<comments>http://www.altdevblogaday.com/2012/03/03/seamless-cube-map-filtering/#comments</comments>
		<pubDate>Sat, 03 Mar 2012 06:53:11 +0000</pubDate>
		<dc:creator>Ignacio Castaño</dc:creator>
				<category><![CDATA[Computer Graphics]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=24628</guid>
		<description><![CDATA[<p>Modern GPUs filter seamlessly across cube map faces. This feature is enabled automatically when using Direct3D 10 and 11 and in OpenGL when using the <a href="http://www.opengl.org/registry/specs/ARB/seamless_cube_map.txt">ARB_seamless_cube_map</a> extension. However, it&#8217;s not exposed through Direct3D 9 and it&#8217;s just not available in any of the current generation consoles.</p>
<p><a href="http://www.altdevblogaday.com/2012/03/03/seamless-cube-map-filtering/" class="more-link">Read more on Seamless Cube Map Filtering&#8230;</a></p>
]]></description>
				<content:encoded><![CDATA[<p>Modern GPUs filter seamlessly across cube map faces. This feature is enabled automatically when using Direct3D 10 and 11 and in OpenGL when using the <a href="http://www.opengl.org/registry/specs/ARB/seamless_cube_map.txt">ARB_seamless_cube_map</a> extension. However, it&#8217;s not exposed through Direct3D 9 and it&#8217;s just not available in any of the current generation consoles.</p>
<p>There are several solutions for this problem. Texture borders solve it elegantly, but are not available on all hardware, and only exposed through the OpenGL API (and proprietary APIs in some consoles).</p>
<p>When textures are static a common solution is to pre-process them in an attempt to eliminate the edge seams. In a short siggraph sketch, John Isidoro <a href="http://developer.amd.com/media/gpu_assets/Isidoro-CubeMapFiltering-Sketch-SIG05.pdf">proposed averaging cube map edge texels</a> across edges and obscuring the effect of the averaging by adjusting the intensity of the nearby texels using various methods. These methods are implemented in <a href="http://developer.amd.com/archive/gpu/cubemapgen/pages/default.aspx">AMD&#8217;s CubeMapGen</a>, whose source code is now <a href="http://code.google.com/p/cubemapgen/">publicly available online</a>. While this seems like a good idea, a few minutes experimenting with CubeMapGen make it obvious that it does not always work very well!</p>
<h2>Embedded Texture Borders</h2>
<p>A very simple solution that even works for dynamic cube maps is to slightly increase the FOV of the perspective projection so that the edges of adjacent faces match up exactly. <a href="http://www.gamedev.net/blog/73/entry-2005516-seamless-filtering-across-faces-of-dynamic-cube-map/">Ysaneya shows</a> that in order to achieve that, the FOV needs to be tweaked as follows:</p>
<p><code>
<pre>
fov = 2.0 * atan(n / (n - 0.5))
</pre>
<p></code></p>
<p>where <code>n</code> is the resolution of the cube map.</p>
<p>What this is essentially doing is to scale down the face images by one texel and padding them with a border of texels that is shared between adjacent faces. Since the texels at the face edges are now identical the seams are gone. </p>
<p>In practice this is much trickier than it sounds. While the fragments at the adjacent face borders should sample the scene in the same direction, rasterization rules do not guarantee that in both cases the rasterized fragments will match.</p>
<p>However, if we take this idea to the realm of offline cube map generation, we can easily guarantee exact results. Cube maps are often used to store directional functions. Each texel has an associated uv coordinate within the cube map face, from which we derive a direction vector that is then used to sample our directional function. Examples of such functions include expensive BRDFs that we would like to precompute, or an environment map sampled using angular extent filtering.</p>
<p>Usually these uv coordinates are computed so that the resulting direction vectors point to the texel centers. For an integer texel coordinate <code>x</code> in the <code>[0,n-1]</code> range we map it to a floating point coordinate <code>u</code> in the <code>[-1, 1]</code> range as follows:</p>
<p><code>
<pre>
map_1(x) = (x + 0.5) * 2 / n - 1
</pre>
<p></code></p>
<p>We then obtain the corresponding direction vector as follows:</p>
<p><code>
<pre>
dir = normalize(faceVector + faceU * map_1(x) + faceV * map_1(y)
</pre>
<p></code></p>
<p>When doing that, the texels at the borders do not map to <code>-1</code> and <code>1</code> exactly, but to:</p>
<p><code>
<pre>
map(0) = -1 + 1/n
map(n-1) = 1 - 1/n
</pre>
<p></code></p>
<p>In our case we want the edges of each face to match up exactly to they result in the same direction vectors. That can be achieved with a function like this:</p>
<p><code>
<pre>
map_2(x) = 2 * x / (n - 1) - 1
</pre>
<p></code></p>
<p>If we use this map to sample our directional function, the resulting cube map is seamless, but the face images are scaled down uniformly. In the first case the slope of the map is:</p>
<p><code>
<pre>
map_1'(x) = 2 / n
</pre>
<p></code></p>
<p>but in the second case it is slightly different:</p>
<p><code>
<pre>
map_2'(x) = 2 / (n - 1)
</pre>
<p></code></p>
<p>This technique works very well at high resolutions. When n is sufficiently high, the change in slope between map_1 and map_2 becomes minimal. However, at low resolutions the stretching on the interior of the face can become noticeable.</p>
<p>A better solution is to stretch the image only in the proximity of the edges. That can be achieved warping the uv face coordinates with a cubic polynomial of this form:</p>
<p><img src="http://altdevblogaday.com/wp-content/uploads/2012/02/warp.png" alt="" title="warp3" width="360" height="222" class="alignright size-full wp-image-24718" /><code>
<pre>
warp3(x) = ax^3 + x
</pre>
<p></code></p>
<p>We can compose this function with our original mapping. The result around the origin is close to a linear identity, but we can adjust <code>a</code> to stretch the function closer to the face edges. In our case we want the values at <code>1-1/n</code> to produce <code>1</code> instead, so we can easily determine the value of <code>a</code> by solving:</p>
<p><code>
<pre>
warp3(1-1/n) = ax^3 + x = 1
</pre>
<p></code></p>
<p>which gives us:</p>
<p><code>
<pre>
a = n^2 / (n-1)^3
</pre>
<p></code></p>
<p>I implemented the linear stretch and cubic warping methods in <a href="http://code.google.com/p/nvidia-texture-tools/">NVTT</a> and they often produce better results than the methods available in AMD&#8217;s CubeMapGen. However, I was not entirely satisfied. While this removed the zero-order discontinuity, it introduced a first-order discontinuity that in some cases was even more noticeable than the artifacts it was intended to remove.</p>
<p>You can hover the cursor over the following image to show how the warp edge fixup method eliminates the discontinuities, but sometimes still results in visible artifacts:</p>
<style type="text/css">
img.hover {
  display:none
}
a:hover img.hover {
  display:inline
}
a:hover img.nohover {
  display:none
}
</style>
<p><a><img src="http://altdevblogaday.com/wp-content/uploads/2012/02/seamless_warp.png" alt="" title="" width="560" height="273" class="hover aligncenter size-full wp-image-24672" /><img src="http://altdevblogaday.com/wp-content/uploads/2012/02/seams.png" alt="" title="" width="560" height="273" class="nohover aligncenter size-full wp-image-24673" /></a></p>
<p>Any edge fixup method is going to force the slope of the color gradient across the edge to be zero, because it needs to duplicate the border texels. The eye seems to be very sensible to this form of discontinuity and it&#8217;s questionable whether this is better than the original artifact. Maybe other warp functions would make the discontinuity less obvious, or maybe it could be smoothed like Isidoro&#8217;s method do. At the time I implemented this I thought the remaining artifacts did not deserve more attention and moved on to other tasks.</p>
<h2>Modifed Texture Lookup</h2>
<p>However, a few days ago <a href ="https://twitter.com/#!/SebLagarde">Sebastien Lagarde</a> integrated these methods in AMD&#8217;s CubeMapGen. See <a href="http://seblagarde.wordpress.com/2012/02/26/amd-cubemapgen-for-physically-based-rendering/">this post</a> for more results and comparisons against other methods. That got me thinking again about this and then I realized that the only thing that needs to be done to avoid the seams is to modify the texture coordinates at runtime the same way we modify them during the offline cube map evaluation. At first I thought that would be impractical, because it would require projecting the texture coordinates onto the cube map faces, but turns out that the resulting math is very simple. In the case of the uniform stretch that I first suggested, the transform required at runtime is just a conditional per-component multiplication:</p>
<p><code>
<pre>
float3 fix_cube_lookup(float3 v) {
   float M = max(max(abs(v.x), abs(v.y)), abs(v.z));
   float scale = (cube_size - 1) / cube_size;
   if (abs(v.x) != M) v.x *= scale;
   if (abs(v.y) != M) v.y *= scale;
   if (abs(v.z) != M) v.z *= scale;
   return v;
}
</pre>
<p></code></p>
<p>One problem is that we need to know the size of the cube map face in advance, but every mipmap has a different size and we may not know what mipmap is going to be sampled in advance. So, this method only works when explicit LOD is used.</p>
<p>Another issue is that with trilinear filtering enabled, the hardware samples from two contiguous mipmap levels. Ideally we would have to use a different scale factor for each mipmap level. That could be achieved sampling them separately and combining the result manually, but in practice, using the same scale for both levels seems to produce fairly good results. We can easily find a scale factor that works well for fractional LODs as a function of the LOD value and the size of the top level mipmap:</p>
<p><code>
<pre>
float scale = 1 - exp2(lod) / cube_size;
if (abs(v.x) != M) v.x *= scale;
if (abs(v.y) != M) v.y *= scale;
if (abs(v.z) != M) v.z *= scale;
</pre>
<p></code></p>
<p>If you are using cube maps to store prefiltered environment maps, chances are you are computing the cube map LOD from the specular power using <code>log2(specular_power)</code>. If that&#8217;s the case, the two transcendental instructions cancel out and the scale becomes a linear function of the specular power.</p>
<p>The images below show the results using the warp filtering method (these were chosen to highlight the artifacts of the warp method). Hover the cursor over the images to visualize the results of the new approach:</p>
<p><a><img src="http://altdevblogaday.com/wp-content/uploads/2012/02/examples_warp.png" alt="" title="" width="566" height="582" class="nohover alignnone size-full wp-image-24694" /><img src="http://altdevblogaday.com/wp-content/uploads/2012/02/examples_seamless.png" alt="" title="" width="566" height="582" class="hover alignnone size-full wp-image-24693" /></a></p>
<p>I&#8217;d like to thank Sebastien Lagarde for his valuable feedback while testing these ideas and for providing the nice images accompanying this article.</p>
<p><em>Note: This article is also published at <a href="http://the-witness.net/news/2012/02/seamless-cube-map-filtering/">The Witness blog</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/03/03/seamless-cube-map-filtering/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AltDevConf Programming &#8211; John McCutchan</title>
		<link>http://www.altdevblogaday.com/2012/02/09/altdevconf-programming-john-mccutchan/</link>
		<comments>http://www.altdevblogaday.com/2012/02/09/altdevconf-programming-john-mccutchan/#comments</comments>
		<pubDate>Thu, 09 Feb 2012 22:53:47 +0000</pubDate>
		<dc:creator>Ignacio Castaño</dc:creator>
				<category><![CDATA[#AltDevConf]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Programming Track]]></category>
		<category><![CDATA[AltDevConf]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=24144</guid>
		<description><![CDATA[With <a href="http://altdevconf.org">AltDevConf</a> around the corner, we are all busy with preparations to make sure it becomes a success. In the mean time, we still have a few more talks to announce properly, next up in the pipeline is <a href="">John McCutchan</a>'s talk titled "Control, Configure, Monitor and View Your Game Engine From the Web".]]></description>
				<content:encoded><![CDATA[<p><img src="http://altdevblogaday.com/wp-content/uploads/2012/02/cutch_small.jpg" alt="" title="cutch_small" width="240" height="240" class="alignright size-full wp-image-24156" /><br />
With <a href="http://altdevconf.org">AltDevConf</a> around the corner, we are all busy with preparations to make sure it becomes a success. In the mean time, we still have a few more talks to announce properly, next up in the pipeline is <a href="">John McCutchan</a>&#8216;s talk titled &#8220;Control, Configure, Monitor and View Your Game Engine From the Web&#8221;.</p>
<p>Today I had the opportunity to catch up with John and ask him a few questions about his talk and his background. Instead of writing a formal introduction, we thought it would be a good idea to simply transcribe his answers:</p>
<p><em>Ignacio Castaño:</em> I&#8217;ve seen your name in the linux kernel and gnome mailing lists, can you explain what was your involvement in those projects?</p>
<blockquote><p>
<em>John McCutchan:</em> I got my start with Unix at a young age- when I was in elementary school I was given a book on Unix that came with 5 inch floppy disks. A couple years later my friend introduced me to Debian Linux and I started to get into C and Free Software. Many years later, after Gnome 2.0 came out, I started to use Gnome as my desktop environment. At the time if you had a CD-ROM the file manager would block it from being unmounted because it was using something called dnotify to monitor file systems for changes.  I wanted to fix it so I wrote inotify which allow for more efficient file system monitoring without blocking unmounts. In order to get inotify in the kernel I ported a bunch of user space code to use it (FAM, gnome-vfs, etc).
 </p></blockquote>
<p><em>IC:</em> What brought you to the game industry?</p>
<blockquote><p>
<em>JM:</em> During graduate school I started to become interested in real time rigid body simulations and collision detection in particular. While working on my thesis I spent my spare time writing a 3D collision detection engine and rigid body physics engine. I never released my engine to the public, but along the way I met Erwin Coumans and he hired me to work on Bullet at SCEA.
</p></blockquote>
<p><em>IC:</em> Are you still involved in any other open source project?</p>
<blockquote><p>
<em>JM:</em> No, I&#8217;ve drifted away from working on open source projects. Mostly due to limited spare time.
</p></blockquote>
<p><em>IC:</em> You are becoming a regular author at AltDevBlogADay. What motivates you to be part of this community?</p>
<blockquote><p>
<em>JM:</em> I really enjoyed many of the articles on the site and after reading an article about something I had just done, I decided that I should share some of my ideas and quit working in a vacuum. I always enjoyed working on open source projects because of all the interesting people and ideas constantly being shared. AltDevBlog has captured some of that.
</p></blockquote>
<p><em>IC:</em> In a few words, can you tell our readers what your talk is about?</p>
<blockquote><p>
<em>JM:</em> Creating an interface to your game engine that allows web applications to control, configure, monitor, and view your game over the network.
</p></blockquote>
<p><em>IC:</em> John, it was great talking to you, thanks for you time and for contributing to AltDevConf!</p>
<p>To learn more about John&#8217;s work, check out his recent <a href="http://altdevblogaday.com/author/john-mccutchan/">AltDevBlogADay articles</a> or come to his talk this Saturday at 2:00 PM (PST). Check out <a href="http://altdevblogaday.com/2012/02/02/altdevconf-schedule/">our schedule</a> or <a href="">register online now</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/02/09/altdevconf-programming-john-mccutchan/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AltDevConf Programming &#8211; Matthieu Laban, Philippe Rollin &amp; Miguel de Icaza</title>
		<link>http://www.altdevblogaday.com/2012/02/09/altdevconf-programming-laban/</link>
		<comments>http://www.altdevblogaday.com/2012/02/09/altdevconf-programming-laban/#comments</comments>
		<pubDate>Thu, 09 Feb 2012 09:52:45 +0000</pubDate>
		<dc:creator>Ignacio Castaño</dc:creator>
				<category><![CDATA[#AltDevConf]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Programming Track]]></category>
		<category><![CDATA[AltDevConf]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=24025</guid>
		<description><![CDATA[There are only 2 days to go before <a href="http://altdevconf.org">AltDevConf</a>! With the conference around the corner it's time to finish unveiling all the details of the program we have put together. Today I'm pleased to present the next three speakers in our lineup for the Programming track: Matthieu Laban, Philippe Rollin and Miguel de Icaza. Together they will present a joint talk titled "Cross Platform Development in C#: From Windows Phone to iOS with MonoTouch".]]></description>
				<content:encoded><![CDATA[<p><a href="http://altdevblogaday.com/wp-content/uploads/2012/02/all.jpg"><img src="http://altdevblogaday.com/wp-content/uploads/2012/02/all-229x300.jpg" alt="" title="all" width="229" height="300" class="alignright size-medium wp-image-24027" /></a><br />
Only 2 days to go before <a href="http://altdevconf.org">AltDevConf</a>! With the conference around the corner it&#8217;s time to finish unveiling all the details of the program we have put together. Today I&#8217;m pleased to present the next three speakers in our lineup for the Programming track: Matthieu Laban, Philippe Rollin and Miguel de Icaza. Together they will present a joint talk titled &#8220;Cross Platform Development in C#: From Windows Phone to iOS with MonoTouch&#8221;.</p>
<p>Matthieu and Philippe are the founders of <a href="http://flyingdevstudio.blogspot.com/">Flying Development Studio</a>, an independent studio focused on the development of flight simulation products for mobile platforms. Their first product, <a href="http://infinite-flight.com/">Infinite Flight</a> gained critical acclaim and commercial success on the Windows Phone store and is about to be released for iOS devices. Matthieu is a licensed pilot and can often be found flying around the bay area. Philippe is passionate about computer graphics and a flight simulation enthusiast. Both share a meticulous attention to detail and a relentless desire to create great products.</p>
<p>Miguel needs little to no presentation. He currently directs the <a href="http://www.mono-project.com/">Mono project</a>, an open source implementation of the .NET framework running on Mac, Linux, mobile devices and embedded systems. He is currently CTO for <a href="http://xamarin.com/">Xamarin</a>, a startup focused on bringing .NET to mobile devices and previously worked at Novell and Ximian, where he created both the Mono project and worked on the Linux desktop.</p>
<p>Miguel will start the session providing an overview of the mono ecosystem as it relates to game developers. He will describe some of the reasons behind mono&#8217;s popularity among game developers, and show different ways in which developers are using the mono runtime in games. He will focus on mono features that were specifically added for game development and address common fears and concerns that game developers usually have.</p>
<p>Matthieu and Philippe&#8217;s success porting Infinite Flight from Windows Phone to iOS would have not been possible without MonoTouch, but that doesn&#8217;t mean it came without challenges. In the second part of the session they will share their experiences with the Mono runtime on iOS and the challenges they faced in order to bring the simulator to market on both platforms.</p>
<p>I think that combining their different perspectives over the mono runtime will give us a unique opportunity to learn from their experiences.</p>
<p>Their talk will air next Saturday at 12:00 PM (PST), check it out in our <a href="http://altdevblogaday.com/2012/02/02/altdevconf-schedule/">schedule</a> and <a href="https://www4.gotomeeting.com/register/729719079">register now</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/02/09/altdevconf-programming-laban/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AltDevConf Programming &#8211; Alex Champandard</title>
		<link>http://www.altdevblogaday.com/2012/01/13/altdevconf-programming-alex-champandard/</link>
		<comments>http://www.altdevblogaday.com/2012/01/13/altdevconf-programming-alex-champandard/#comments</comments>
		<pubDate>Fri, 13 Jan 2012 16:26:45 +0000</pubDate>
		<dc:creator>Ignacio Castaño</dc:creator>
				<category><![CDATA[#AltDevConf]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Programming Track]]></category>
		<category><![CDATA[AltDevConf]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=23014</guid>
		<description><![CDATA[To follow up with <a href="http://altdevblogaday.com/2012/01/09/altdevconf-education-ian-schreiber/">Luke's announcement</a> and continue unveiling the program we are building for AltDevConf, allow me to introduce you to Alex Champandard, our first featured speaker of the Programming Track.]]></description>
				<content:encoded><![CDATA[<p><img src="http://files.aigamedev.com/site/AlexChampandard.icon.png" alt="Alex" class="alignright"/>To follow up with <a href="http://altdevblogaday.com/2012/01/09/altdevconf-education-ian-schreiber/">Luke&#8217;s announcement</a> and continue unveiling the program we are building for <a href="http://altdevconf.org">AltDevConf</a>, allow me to introduce you to Alex Champandard, our first featured speaker of the <a href="http://altdevconf.org/programming/">Programming Track</a>.</p>
<p>Alex is a veteran of the industry. I&#8217;ve known about him since the late 90s, when he used to write some regular columns at <a href="http://www.flipcode.com">flipcode</a> that I still have fond memories of. Later, as flipcode closed his doors he found his passion in game AI and continued writing and sharing his work at the <a href="http://ai-depot">ai-depot</a>.</p>
<p>Today, Alex has a unique perspective of recent game AI developments that draws from both his professional and academic experience. He has worked at leading game studios and continues consulting with them regularly. He has contributed to many games including Killzone 3, Killzone 2, Max Payne 3, and Rockstar Table Tennis.</p>
<p>On the academic front, he&#8217;s the editor-in-chief of <a href="AiGameDev.com">AiGameDev.com</a>, author of the <a href="http://books.google.com/books/about/AI_game_development.html?id=ZpuR8GnBSGcC">AI Game Development</a> book, and frequent speaker at the <a href="http://gameaiconf.com/">Paris Game AI Conference</a>, which he co-organizes with his wife Petra.</p>
<p>Alex has become one of the main authorities for the study and advocation of Behavior Trees in games. In his AltDevConf talk he will introduce this technique to newcomers, discuss modern trends in current games, and predict what to expect from future implementations. Here&#8217;s a description of the talk in his own words:</p>
<blockquote><p>
This presentation will provide the most comprehensive overview of the design and implementation of behavior trees to date.  Since their incremental evolution into the games industry ~8 years ago, a lot has changed and there are clear trends in their uses and applications in commercial games.  Drawing from <a href="http://AiGameDev.com">AiGameDev.com</a>&#8216;s extensive experience prototyping, teaching, consulting about behavior trees, you&#8217;ll learn the key principles behind first- and second-generation behavior trees as they are currently used in games &#8212; and what challenges and opportunities this presents for your game&#8217;s AI and scripting system.
</p></blockquote>
<p>Alex is just one of the speakers we’ll be introducing during the next few days leading to the conference. You can read more about the program we are putting together at <a href="http://altdevconf.org">AltDevConf.org</a> and remember to clear your schedule February 11th/12th to come join us!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/01/13/altdevconf-programming-alex-champandard/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Irradiance Caching &#8211; Part 1</title>
		<link>http://www.altdevblogaday.com/2011/07/14/irradiance-caching-part-1/</link>
		<comments>http://www.altdevblogaday.com/2011/07/14/irradiance-caching-part-1/#comments</comments>
		<pubDate>Thu, 14 Jul 2011 08:20:38 +0000</pubDate>
		<dc:creator>Ignacio Castaño</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[global illumination]]></category>
		<category><![CDATA[lightmaps]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=9904</guid>
		<description><![CDATA[<p>This is the first article I wanted to publish when I started writing about the technology behind <a href="http://the-witness.net">The Witness</a>. I had just spent a week or so implementing irradiance caching with rotation and translation gradients. Extending the equations of the gradient estimation to the hemicube sample distribution had proven to be tricky and had taken me a considerable amount of effort. So, I thought it would be cool to document my derivation, so that others would not have to do the same. However, for that article to make sense I first had to provide some background, hence the previous two articles:</p>
<p><a href="http://www.altdevblogaday.com/2011/07/14/irradiance-caching-part-1/" class="more-link">Read more on Irradiance Caching &#8211; Part 1&#8230;</a></p>
]]></description>
				<content:encoded><![CDATA[<p>This is the first article I wanted to publish when I started writing about the technology behind <a href="http://the-witness.net">The Witness</a>. I had just spent a week or so implementing irradiance caching with rotation and translation gradients. Extending the equations of the gradient estimation to the hemicube sample distribution had proven to be tricky and had taken me a considerable amount of effort. So, I thought it would be cool to document my derivation, so that others would not have to do the same. However, for that article to make sense I first had to provide some background, hence the previous two articles:</p>
<ul>
<li><a href="http://the-witness.net/news/?p=120">Lightmap Parameterization</a></li>
<li><a href="http://the-witness.net/news/?p=244">Hemicube Rendering and Integration</a></li>
</ul>
<p>Unfortunately, by the time I was done with these, the work I had done on the gradients was not so fresh anymore, which is why it has taken me so long to complete this article.</p>
<p><a href="http://the-witness.net/news/wp-content/uploads/2011/06/irradiance_gradients_0.jpg"><img class="aligncenter size-large wp-image-1133" src="http://the-witness.net/news/wp-content/uploads/2011/06/irradiance_gradients_0-512x288.jpg" alt="" width="512" height="288" /></a></p>
<p><span id="more-9904"></span><br />
In <a href="http://the-witness.net/news/?p=244">my previous post</a> I mentioned the need to find an algorithm that would allow us to extrapolate the irradiance to fill lightmap texels with invalid samples, to smooth the resulting lightmaps to reduce noise, and to sample the irradiance at a lower frequency to improve performance. As some avid readers suggested <em>Irradiance Caching</em> solves all these problems. However, at the time I didn&#8217;t know that, and my initial attempts at a solution were misguided.</p>
<h2>Texture Space Approaches</h2>
<p>I had some experience writing baker tools to capture normal and displacement maps from high resolution meshes. In that setting it is common to use various image filters to fill holes caused by sampling artifacts and extend sampled attributes beyond the boundaries of the mesh parameterization. <a href="http://freespace.virgin.net/hugo.elias/radiosity/radiosity.htm">Hugo Elias&#8217; popular article</a> also proposes a texture space hierarchical sampling method, and that persuaded me that working in texture space would be a good idea.</p>
<p>However, in practice texture space methods had many problems. Extrapolation filters only provide accurate estimates close to chart boundaries, and even then, they only use information from one side of the boundary, which usually results in seams. Also, the effectiveness of irregular sampling and interpolation approaches in texture space is greatly reduced by texture discontinuities and did not reduce the number of samples as much as desired.</p>
<p>After trying various approaches, it became clear that the solution was to work in object space instead. I was about to implement my own solution, when I learned that this is what irradiance caching was about.</p>
<h2>Irradiance Caching</h2>
<p>This technique has such a terrible name that I would have never learned about it if it wasn&#8217;t due to a friend&#8217;s suggestion. I think that a much more appropriate name would be adaptive irradiance sampling or irradiance interpolation. In fact, in the <a href="http://radsite.lbl.gov/radiance/papers/sg88/paper.html">paper that introduced the technique for the first time</a> Greg Ward referred to it as <em>lazy irradiance evaluation</em>, which seems to me a much more appropriate name.</p>
<p>There&#8217;s plenty of literature on the subject and I don&#8217;t want to repeat what you can learn elsewhere. So, in this article I&#8217;m only going to provide a brief overview, focus on the unique aspects of our implementation, and point you to other sources for further reference.</p>
<p>The basic idea behind irradiance caching is to sample the irradiance adaptively based on a metric that predicts changes in the irradiance due to proximity to occluders and reflectors. This metric is based on the split sphere model, which basically models the worst possible illumination conditions in order to predict the necessary distance between irradiance samples based on their distance to the surrounding geometry.</p>
<p>Interpolation between these samples is then performed using radial basis functions, the radius associated to each sample is also based on this distance. Whenever the contribution of the nearby samples falls below a certain threshold a new irradiance record needs to be generated, in our case this is done by rendering an hemicube at that location. In order to perform interpolation efficiently the irradiance records are inserted in an octree, which allows us to efficiently query the nearby records at any given point.</p>
<p>For more details, the <a href="http://cgg.mff.cuni.cz/~jaroslav/papers/2008-irradiance_caching_class/index.htm">Siggraph &#8217;08 course</a> on the topic is probably the most comprehensive reference. There&#8217;s also a book based on the materials of the course; it&#8217;s slightly augmented, but in my opinion it does not add much value to the freely available material.</p>
<p>The <a href="http://www.pbrt.org/"><em>Physically Based Rendering book</em> by Matt Pharr &amp; Greg Humphreys</a> is an excellent resource and the <a href="https://github.com/mmp/pbrt-v2">accompanying source code</a> contains a good, albeit basic implementation.</p>
<p>Finally, Rory Driscoll provides a good introduction from a programmer&#8217;s point of view: <a href="http://www.rorydriscoll.com/2009/01/18/irradiance-caching-part-1/">part 1</a>, <a href="http://www.rorydriscoll.com/2009/01/24/irradiance-caching-part-2/">part 2</a>.</p>
<p>Our implementation is fairly standard, there are however a two main differences: First, we are sampling the irradiance using hemicubes instead of a stratified Montecarlo distribution. As a result, the way the we compute the irradiance gradients for interpolation is somewhat different. Second, we use a record placement strategy more suited to our setting. In part 1 I&#8217;ll focus on the estimation of the irradiance gradients, while in part 2 I&#8217;ll write about our record placement strategies.</p>
<h2>Irradiance Gradients</h2>
<p>When interpolating our discrete irradiance samples using radial basis functions the resulting images usually have spotty or smudgy appearance. This can be mitigated by increasing the number of samples and increasing the interpolation threshold, which effectively makes them overlap and smoothes out the result. However, this also increases the number of samples significantly, which defeats the purpose of using irradiance caching.</p>
<p>One of the most effective approaches to improve the interpolation is estimating the irradiance gradients at the sampling points, which basically tell how the irradiance changes when the position and orientation of the surface changes. We cannot evaluate the irradiance gradients exactly, but we can find reasonable approximations with the information that we already have from rendering an hemicube. </p>
<p>In my previous article I explained that the irradiance integral was just a weighted sum over the radiance samples, where the contribution of each sample is the product of the radiance through each of the hemicube texels <img src='http://s0.wp.com/latex.php?latex=L_i&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='L_i' title='L_i' class='latex' />, the solid angle of the texel <img src='http://s0.wp.com/latex.php?latex=A_i&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='A_i' title='A_i' class='latex' />, and the cosine term <img src='http://s0.wp.com/latex.php?latex=%5Ccos_%7B%5Ctheta_i%7D&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;cos_{&#92;theta_i}' title='&#92;cos_{&#92;theta_i}' class='latex' />. That is, the irradiance <img src='http://s0.wp.com/latex.php?latex=E%28%5Cmathbf%7Bx%7D%29&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='E(&#92;mathbf{x})' title='E(&#92;mathbf{x})' class='latex' /> at a point <img src='http://s0.wp.com/latex.php?latex=%5Cmathbf%7Bx%7D&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;mathbf{x}' title='&#92;mathbf{x}' class='latex' /> is approximated as:</p>
<img src='http://s0.wp.com/latex.php?latex=E%28%5Cmathbf%7Bx%7D%29+%5Csimeq+%5Csum_%7Bi%3D0%7D%5EN+A_i+L_i+%5Ccos%5Ctheta_i&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='E(&#92;mathbf{x}) &#92;simeq &#92;sum_{i=0}^N A_i L_i &#92;cos&#92;theta_i' title='E(&#92;mathbf{x}) &#92;simeq &#92;sum_{i=0}^N A_i L_i &#92;cos&#92;theta_i' class='latex' />
<p>The irradiance gradients consider how each these terms change under infinitesimal rotations and translations and can be obtained by differentiating <img src='http://s0.wp.com/latex.php?latex=E%28%5Cmathbf%7Bx%7D%29&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='E(&#92;mathbf{x})' title='E(&#92;mathbf{x})' class='latex' />.</p>
<img src='http://s0.wp.com/latex.php?latex=%5Cnabla+E%28%5Cmathbf%7Bx%7D%29+%5Csimeq+%5Csum_%7Bi%3D0%7D%5EN+%5Cnabla+A_i+L_i+%5Ccos%5Ctheta_i&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;nabla E(&#92;mathbf{x}) &#92;simeq &#92;sum_{i=0}^N &#92;nabla A_i L_i &#92;cos&#92;theta_i' title='&#92;nabla E(&#92;mathbf{x}) &#92;simeq &#92;sum_{i=0}^N &#92;nabla A_i L_i &#92;cos&#92;theta_i' class='latex' />
<p>The radiance term is considered to be constant, so the equation reduces to:</p>
<img src='http://s0.wp.com/latex.php?latex=%5Cnabla+E%28%5Cmathbf%7Bx%7D%29+%5Csimeq+%5Csum_%7Bi%3D0%7D%5EN+L_i+%5Cnabla+A_i+%5Ccos%5Ctheta_i&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;nabla E(&#92;mathbf{x}) &#92;simeq &#92;sum_{i=0}^N L_i &#92;nabla A_i &#92;cos&#92;theta_i' title='&#92;nabla E(&#92;mathbf{x}) &#92;simeq &#92;sum_{i=0}^N L_i &#92;nabla A_i &#92;cos&#92;theta_i' class='latex' />
<p>In reality, the radiance is not really constant, but the goal is to estimate the gradients without using any information in addition to what we have already obtained by rendering the scene on a hemicube. So that we can improve the quality of the interpolation by only doing some additional computations while integrating the hemicube.</p>
<h3>Rotation Gradient</h3>
<p>The rotation gradient expresses how the irradiance changes as the hemicube is rotated in any direction:</p>
<img src='http://s0.wp.com/latex.php?latex=%5Cnabla_r+E%28%5Cmathbf%7Bx%7D%29+%5Csimeq+%5Csum_%7Bi%3D0%7D%5EN+L_i+%5Cnabla_r+A_i+%5Ccos%5Ctheta_i&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;nabla_r E(&#92;mathbf{x}) &#92;simeq &#92;sum_{i=0}^N L_i &#92;nabla_r A_i &#92;cos&#92;theta_i' title='&#92;nabla_r E(&#92;mathbf{x}) &#92;simeq &#92;sum_{i=0}^N L_i &#92;nabla_r A_i &#92;cos&#92;theta_i' class='latex' />
<p>The most important observation is that as the hemicube rotates, the solid angle of the texels with respect to the origin remains constant. So, the only factor that influences the gradient is the cosine term:</p>
<img src='http://s0.wp.com/latex.php?latex=%5Cnabla_r+A_i+%5Ccos%5Ctheta_i+%3D+A_i+%5Cnabla_r+%5Ccos%5Ctheta_i&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;nabla_r A_i &#92;cos&#92;theta_i = A_i &#92;nabla_r &#92;cos&#92;theta_i' title='&#92;nabla_r A_i &#92;cos&#92;theta_i = A_i &#92;nabla_r &#92;cos&#92;theta_i' class='latex' />
<p>With this in mind, the rotation gradient is simply the rotation axis scaled by the rate of change, that is, the angle gradient:</p>
<img src='http://s0.wp.com/latex.php?latex=%5Cfrac%7B%5Cpartial+%7D%7B%5Cpartial+%5Ctheta_i%7D+%5Ccos%5Ctheta_i+%3D+-%5Csin%5Ctheta_i&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;frac{&#92;partial }{&#92;partial &#92;theta_i} &#92;cos&#92;theta_i = -&#92;sin&#92;theta_i' title='&#92;frac{&#92;partial }{&#92;partial &#92;theta_i} &#92;cos&#92;theta_i = -&#92;sin&#92;theta_i' class='latex' />
<p>And the rotation axis is given by the cross product of the z axis and the texel direction <img src='http://s0.wp.com/latex.php?latex=%5Cmathbf%7Bd%7D_i&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;mathbf{d}_i' title='&#92;mathbf{d}_i' class='latex' />:</p>
<img src='http://s0.wp.com/latex.php?latex=%5Cmathbf%7Bv%7D_i+%3D+%5Cleft%7C+%5Cmathbf%7Bd%7D_i+%5Ctimes+%280%2C+0%2C+1%29+%5Cright%7C&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;mathbf{v}_i = &#92;left| &#92;mathbf{d}_i &#92;times (0, 0, 1) &#92;right|' title='&#92;mathbf{v}_i = &#92;left| &#92;mathbf{d}_i &#92;times (0, 0, 1) &#92;right|' class='latex' />
<p>Therefore:</p>
<img src='http://s0.wp.com/latex.php?latex=%5Cnabla_r+%5Ccos%5Ctheta_i+%3D+-%5Cmathbf%7Bv%7D_i+%5Csin%5Ctheta_i&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;nabla_r &#92;cos&#92;theta_i = -&#92;mathbf{v}_i &#92;sin&#92;theta_i' title='&#92;nabla_r &#92;cos&#92;theta_i = -&#92;mathbf{v}_i &#92;sin&#92;theta_i' class='latex' />
<p>This can be simplified further by noting that <img src='http://s0.wp.com/latex.php?latex=%5Csin%5Ctheta_i&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;sin&#92;theta_i' title='&#92;sin&#92;theta_i' class='latex' /> is the length of <img src='http://s0.wp.com/latex.php?latex=%5Cmathbf%7Bv%7D_i&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;mathbf{v}_i' title='&#92;mathbf{v}_i' class='latex' /> before normalization and that results in a very simple expression:</p>
<img src='http://s0.wp.com/latex.php?latex=%5Cnabla_r+%5Ccos%5Ctheta_i+%3D+%28%5Cmathbf%7Bd%7D_%7Byi%7D%2C+-%5Cmathbf%7Bd%7D_%7Bxi%7D%2C+0%29&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;nabla_r &#92;cos&#92;theta_i = (&#92;mathbf{d}_{yi}, -&#92;mathbf{d}_{xi}, 0)' title='&#92;nabla_r &#92;cos&#92;theta_i = (&#92;mathbf{d}_{yi}, -&#92;mathbf{d}_{xi}, 0)' class='latex' />
<p>Finally, the rotation gradient for the hemisphere is the sum of the gradients corresponding to each texel.</p>
<img src='http://s0.wp.com/latex.php?latex=%5Cnabla+E%28%5Cmathbf%7Bx%7D%29+%5Csimeq+%5Csum_%7Bi%3D0%7D%5EN+L_i+A_i+%28%5Cmathbf%7Bd%7D_%7Byi%7D%2C+-%5Cmathbf%7Bd%7D_%7Bxi%7D%2C+0%29&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;nabla E(&#92;mathbf{x}) &#92;simeq &#92;sum_{i=0}^N L_i A_i (&#92;mathbf{d}_{yi}, -&#92;mathbf{d}_{xi}, 0)' title='&#92;nabla E(&#92;mathbf{x}) &#92;simeq &#92;sum_{i=0}^N L_i A_i (&#92;mathbf{d}_{yi}, -&#92;mathbf{d}_{xi}, 0)' class='latex' />
<p>The resulting code is trivial:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="cpp" style="font-family:monospace;">foreach texel, color in hemicube <span style="color: #008000;">&#123;</span>
    Vector2 v <span style="color: #000080;">=</span> texel.<span style="color: #007788;">solid_angle</span> <span style="color: #000040;">*</span> Vector2<span style="color: #008000;">&#40;</span>texel.<span style="color: #007788;">dir</span>.<span style="color: #007788;">y</span>, <span style="color: #000040;">-</span>texel.<span style="color: #007788;">dir</span>.<span style="color: #007788;">x</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    rotation_gradient<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#93;</span> <span style="color: #000040;">+</span><span style="color: #000080;">=</span> v <span style="color: #000040;">*</span> color.<span style="color: #007788;">x</span><span style="color: #008080;">;</span>
    rotation_gradient<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#93;</span> <span style="color: #000040;">+</span><span style="color: #000080;">=</span> v <span style="color: #000040;">*</span> color.<span style="color: #007788;">y</span><span style="color: #008080;">;</span>
    rotation_gradient<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">2</span><span style="color: #008000;">&#93;</span> <span style="color: #000040;">+</span><span style="color: #000080;">=</span> v <span style="color: #000040;">*</span> color.<span style="color: #007788;">z</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<h3>Translation Gradients</h3>
<p>The derivation of the translation gradients is a bit more complicated than the rotation gradients because the solid angle term is not invariant under translations anymore.</p>
<p>My first approach was to simplify the expression of the solid angle term by using an approximation that is easier to differentiate. Instead of using the exact texel solid angle like I had been doing so far, I approximated it by the differential solid angle scaled by the constant area of the texel, which is a reasonable approximation if the texels are sufficiently small.</p>
<p>In general, the differential solid angle in a given direction <img src='http://s0.wp.com/latex.php?latex=%5CTheta&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;Theta' title='&#92;Theta' class='latex' /> is given by:</p>
<img src='http://s0.wp.com/latex.php?latex=d%5Comega_%5CTheta+%3D+%5Cfrac%7B%5Cmathbf%7Bn%7D%5Ccdot%5CTheta%7D%7Br%5E2%7D+da&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='d&#92;omega_&#92;Theta = &#92;frac{&#92;mathbf{n}&#92;cdot&#92;Theta}{r^2} da' title='d&#92;omega_&#92;Theta = &#92;frac{&#92;mathbf{n}&#92;cdot&#92;Theta}{r^2} da' class='latex' />
<p>For the particular case of the texels of the top face of the hemicube, <strong>n</strong> is equal to the z axis. So, the differential solid angle is:</p>
<img src='http://s0.wp.com/latex.php?latex=d%5Comega_%5CTheta+%3D+%5Cfrac%7B%5Ccos%5Ctheta%7D%7Br%5E2%7D+da&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='d&#92;omega_&#92;Theta = &#92;frac{&#92;cos&#92;theta}{r^2} da' title='d&#92;omega_&#92;Theta = &#92;frac{&#92;cos&#92;theta}{r^2} da' class='latex' />
<p>We also know that:</p>
<img src='http://s0.wp.com/latex.php?latex=%5Ccos%5Ctheta+%3D+1%2Fr&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;cos&#92;theta = 1/r' title='&#92;cos&#92;theta = 1/r' class='latex' />
<p>which simplifies the expression further:</p>
<img src='http://s0.wp.com/latex.php?latex=d%5Comega_%5CTheta+%3D+%28%5Ccos%5Ctheta%29%5E3+da&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='d&#92;omega_&#92;Theta = (&#92;cos&#92;theta)^3 da' title='d&#92;omega_&#92;Theta = (&#92;cos&#92;theta)^3 da' class='latex' />
<p>Using this result and factoring the area of the texels out of the sum we obtain the following expression for the gradient:</p>
<img src='http://s0.wp.com/latex.php?latex=%5Cnabla_t+E_z%28%5Cmathbf%7Bx%7D%29+%5Csimeq+4+%5Csum_%7Bi%3D0%7D%5EN+L_i+%5Cnabla_t+%28%5Ccos%5Ctheta_i%29%5E4&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;nabla_t E_z(&#92;mathbf{x}) &#92;simeq 4 &#92;sum_{i=0}^N L_i &#92;nabla_t (&#92;cos&#92;theta_i)^4' title='&#92;nabla_t E_z(&#92;mathbf{x}) &#92;simeq 4 &#92;sum_{i=0}^N L_i &#92;nabla_t (&#92;cos&#92;theta_i)^4' class='latex' />
<p>The remaining faces have similar expressions, slightly more complex, but still easy to differentiate along the x and y directions. We could continue along this path and we would obtain closed formulas that can be used to estimate the translation gradients. However, this simple approach did not produce satisfactory results. The problem is that these gradients assume that the only thing that changes under translation is the projected solid angle of the texels, but that ignores the parallax effect and the occlusion between neighboring texels. That is, samples that correspond to objects that are close to the origin of the hemicube should move faster than those that that are farther, and as they move they may occlude nearby samples.</p>
<p>As you can see in the following lightmap, the use of these gradients resulted in smoother results in areas that are away from occluders, but produced incorrect results whenever the occluders are nearby.</p>
<div id="attachment_727" class="wp-caption aligncenter" style="width: 610px"><img class="size-full wp-image-727" src="http://the-witness.net/news/wp-content/uploads/2011/01/translation_gradient_comparison_a.png" alt="" width="600" height="157" /><p class="wp-caption-text">Left: Reference. Middle: Irradiance caching without gradients. Right: Irradiance caching with flawed gradients</p></div>
<p>The hexagonal shape corresponds to the ceiling of a room that has walls along its sides and a window through which the light enters. The image on the left is a reference lightmap with one hemicube sample per pixel. The image on the middle is the same lightmap computed using irradiance caching taking only 2% of the samples. Note that the number of samples is artificially low to emphasize the artifacts. On the right side the same lightmap is computed using the proposed gradients. If you look closely you can notice that on the interior the lightmap looks smoother, but close to the walls the artifacts remain.</p>
<p>This is exactly the same flaw of the gradients that Krivanek et al proposed in <a href="http://cgg.mff.cuni.cz/~jaroslav/papers/tvcg2005/krivanek05radiance_caching.pdf">Radiance Caching for Efficient Global Illumination Computation</a>, but was later corrected in the followup paper <a href="http://cgg.mff.cuni.cz/~jaroslav/papers/sccg2005/sccg2005-krivanek.pdf">Improved Radiance Gradient Computation</a> by approaching the problem the same way Greg Ward did in the original <a href="http://radsite.lbl.gov/radiance/papers/erw92/paper.pdf">original <em>Irradiance Gradients</em> paper</a>.</p>
<p>I then tried follow the same approach. The basic idea is to consider the cosine term invariant under translation so that only the area term needs to be differentiated, and to express the gradient of the cell area in terms of the marginal area changes between adjacent cells. The most important observation is that the motion of the boundary between cells is always determined by the closest sample, so this approach takes occlusion into account.</p>
<p>Unfortunately we cannot directly use Greg Ward&#8217;s gradients, because they are closely tied to the stratified Montecarlo distribution and we are using a hemicube sampling distribution. However, we can still apply the same methodology to arrive to a formulation of the gradients that we can use in our setting.</p>
<p>In our case, the cells are the hemicube texels projected onto the hemisphere and the cell area is the texel solid angle. To determine the translation gradients of the texel&#8217;s solid angle is equivalent to computing the sum of the marginal gradients corresponding to each of the texel walls.</p>
<p>These marginal gradients are the wall normals projected onto the translation plane, scaled by the length of the wall, and multiplied by the rate of motion of the wall in that direction.</p>
<p>Since the hemicube uses a gnomonic projection, where lines in the plane map to great circles in the sphere, the texel boundaries of the hemicubes map to great arcs in the hemisphere. So, the length of these arcs is very easy to compute. Given the direction of the two texel corners <img src='http://s0.wp.com/latex.php?latex=%5Cmathbf%7Bd%7D_0%2C+%5Cmathbf%7Bd%7D_1&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;mathbf{d}_0, &#92;mathbf{d}_1' title='&#92;mathbf{d}_0, &#92;mathbf{d}_1' class='latex' />, the length of their hemispherical projection is:</p>
<img src='http://s0.wp.com/latex.php?latex=arclength%28%5Cmathbf%7Bd%7D_0%2C+%5Cmathbf%7Bd%7D_1%29+%3D+%5Carccos%7B%5Cmathbf%7Bd%7D_0+%5Ccdot+%5Cmathbf%7Bd%7D_1%7D&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='arclength(&#92;mathbf{d}_0, &#92;mathbf{d}_1) = &#92;arccos{&#92;mathbf{d}_0 &#92;cdot &#92;mathbf{d}_1}' title='arclength(&#92;mathbf{d}_0, &#92;mathbf{d}_1) = &#92;arccos{&#92;mathbf{d}_0 &#92;cdot &#92;mathbf{d}_1}' class='latex' />
<p>The remaining problem is to compute the rate of motion of the wall, which as Greg Ward noted has to be proportional to the minimum distance of the two samples.</p>
<p>The key observation is that we can classify all the hemicube edges in wo categories: Edges with constant longitude (<img src='http://s0.wp.com/latex.php?latex=%5Ctheta&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;theta' title='&#92;theta' class='latex' /> is invariant), and edges with constant latitude (<img src='http://s0.wp.com/latex.php?latex=%5Cphi&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;phi' title='&#92;phi' class='latex' /> is invariant).</p>
<p>In each of these cases we can estimate the rate of change of edges with respect to the normal direction by considering the analogous problem in the <a href="http://mathworld.wolfram.com/SphericalCoordinates.html">canonical hemispherical parametrization</a>:</p>
<p><img src='http://s0.wp.com/latex.php?latex=r+%3D+%5Csqrt%7Bx%5E2%2By%5E2%2Bz%5E2%7D&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='r = &#92;sqrt{x^2+y^2+z^2}' title='r = &#92;sqrt{x^2+y^2+z^2}' class='latex' /><br />
<img src='http://s0.wp.com/latex.php?latex=%5Cphi+%3D+%5Carctan%5Cfrac%7By%7D%7Bx%7D&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;phi = &#92;arctan&#92;frac{y}{x}' title='&#92;phi = &#92;arctan&#92;frac{y}{x}' class='latex' /><br />
<img src='http://s0.wp.com/latex.php?latex=%5Ctheta+%3D+%5Carccos%5Cfrac%7Bz%7D%7Br%7D&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;theta = &#92;arccos&#92;frac{z}{r}' title='&#92;theta = &#92;arccos&#92;frac{z}{r}' class='latex' /></p>
<p>For longitudinal edges we can consider how <img src='http://s0.wp.com/latex.php?latex=%5Ctheta&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;theta' title='&#92;theta' class='latex' /> changes with respect to motion along the x axis:</p>
<img src='http://s0.wp.com/latex.php?latex=%5Cfrac%7B%5Cpartial%5Ctheta%7D%7B%5Cpartial+x%7D+%3D+%5Cfrac%7B-%5Ccos%5Ctheta%7D%7Br%7D&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;frac{&#92;partial&#92;theta}{&#92;partial x} = &#92;frac{-&#92;cos&#92;theta}{r}' title='&#92;frac{&#92;partial&#92;theta}{&#92;partial x} = &#92;frac{-&#92;cos&#92;theta}{r}' class='latex' />
<p>and for latitudinal edges we can consider how <img src='http://s0.wp.com/latex.php?latex=%5Cphi&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;phi' title='&#92;phi' class='latex' /> changes with respect to motion along the y axis:</p>
<img src='http://s0.wp.com/latex.php?latex=%5Cfrac%7B%5Cpartial%5Cphi%7D%7B%5Cpartial+y%7D+%3D+%5Cfrac%7B-1%7D%7Br+%5Csin%5Ctheta%7D&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='&#92;frac{&#92;partial&#92;phi}{&#92;partial y} = &#92;frac{-1}{r &#92;sin&#92;theta}' title='&#92;frac{&#92;partial&#92;phi}{&#92;partial y} = &#92;frac{-1}{r &#92;sin&#92;theta}' class='latex' />
<p>As we noted before, the rate of the motion is dominated by the nearest edge, so <img src='http://s0.wp.com/latex.php?latex=r&#038;bg=ffffff&#038;fg=000&#038;s=0' alt='r' title='r' class='latex' /> takes the value of the minimum depth of the two samples adjacent to the edge.</p>
<p>A detailed derivation for these formulas can be found in <a href="http://zurich.disneyresearch.com/~wjarosz/publications/dissertation/">Wojciech Jarosz&#8217;s dissertation</a>, which is now publicly available online. His detailed explanation is very didactic and I highly recommend reading it to get a better understanding of how these formulas are obtained.</p>
<p>Note that these are just the same formulas used by Greg Ward and others. In practice, the only thing that changes is the layout of the cells and the length of the walls between them.</p>
<p>As can be seeing in the following picture, the new gradients produce much better results. Note that the appearance on the interior of the lightmap is practically the same, but closer to the walls the results are now much smoother. Keep in mind that artifacts are still present, because the number of samples is artificially low.</p>
<div id="attachment_1048" class="wp-caption aligncenter" style="width: 610px"><img class="size-full wp-image-1048" src="http://the-witness.net/news/wp-content/uploads/2011/06/translation_gradient_comparison.png" alt="" width="600" /><p class="wp-caption-text">Left: No gradients. Middle: Flawed translation gradients. Right: Improved translation gradients.</p></div>
<p>In order to estimate the translation gradients efficiently we precompute the direction and magnitude of the marginal gradients corresponding to each texel edge without taking the distance to the edge into account:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #666666;">// Compute the length of the edge walls multiplied by the rate of motion</span>
<span style="color: #666666;">// with respect to motion in the normal direction</span>
foreach edge in hemicube <span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">float</span> wall_length <span style="color: #000080;">=</span> <span style="color: #0000dd;">acos</span><span style="color: #008000;">&#40;</span>dot<span style="color: #008000;">&#40;</span>d0, d1<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    Vector2 projected_wall_normal <span style="color: #000080;">=</span> normalize<span style="color: #008000;">&#40;</span>cross<span style="color: #008000;">&#40;</span>d0, d1<span style="color: #008000;">&#41;</span>.<span style="color: #007788;">xy</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">float</span> motion_rate <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span>constant_altitude<span style="color: #008000;">&#40;</span>d0,d1<span style="color: #008000;">&#41;</span> <span style="color: #008080;">?</span>
        <span style="color: #000040;">-</span>cos_theta<span style="color: #008000;">&#40;</span>d0,d1<span style="color: #008000;">&#41;</span> <span style="color: #008080;">:</span>      <span style="color: #666666;">// d(theta)/dx = -cos(theta) / depth</span>
        <span style="color: #000040;">-</span><span style="color: #0000dd;">1</span> <span style="color: #000040;">/</span> sin_theta<span style="color: #008000;">&#40;</span>d0,d1<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>   <span style="color: #666666;">// d(phi)/dy = -1 / (sin(theta) * depth)</span>
&nbsp;
    edge.<span style="color: #007788;">translation_gradient</span> <span style="color: #000080;">=</span> projected_wall_normal <span style="color: #000040;">*</span> wall_length <span style="color: #000040;">*</span> motion_rate<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>Then, during integration we split the computations in two steps. First, we accumulate the marginal gradients of each of the edges scaled by the minimum edge distance:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="cpp" style="font-family:monospace;">foreach edge in hemicube <span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">float</span> depth0 <span style="color: #000080;">=</span> depth<span style="color: #008000;">&#40;</span>edge.<span style="color: #007788;">x0</span>, edge.<span style="color: #007788;">y0</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">float</span> depth1 <span style="color: #000080;">=</span> depth<span style="color: #008000;">&#40;</span>edge.<span style="color: #007788;">x1</span>, edge.<span style="color: #007788;">y1</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">float</span> min_depth <span style="color: #000080;">=</span> min<span style="color: #008000;">&#40;</span>depth0, depth1<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
    texel<span style="color: #008000;">&#91;</span>edge.<span style="color: #007788;">x0</span>, edge.<span style="color: #007788;">y0</span><span style="color: #008000;">&#93;</span>.<span style="color: #007788;">translation_gradient</span> <span style="color: #000040;">-</span><span style="color: #000080;">=</span> edge.<span style="color: #007788;">gradient</span> <span style="color: #000040;">/</span> min_depth<span style="color: #008080;">;</span>
    texel<span style="color: #008000;">&#91;</span>edge.<span style="color: #007788;">x1</span>, edge.<span style="color: #007788;">y1</span><span style="color: #008000;">&#93;</span>.<span style="color: #007788;">translation_gradient</span> <span style="color: #000040;">+</span><span style="color: #000080;">=</span> edge.<span style="color: #007788;">gradient</span> <span style="color: #000040;">/</span> min_depth<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<p>Once we have the per texel gradient, we compute the final irradiance gradient as the sum of the texel gradients weighted by the texel colors:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="cpp" style="font-family:monospace;">foreach texel, color in hemicube <span style="color: #008000;">&#123;</span>
    Vector2 translation_gradient <span style="color: #000080;">=</span> texel.<span style="color: #007788;">translation_gradient</span> <span style="color: #000040;">*</span> texel.<span style="color: #007788;">clamped_cosine</span><span style="color: #008080;">;</span>
    translation_gradient_sum<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #008000;">&#93;</span> <span style="color: #000040;">+</span><span style="color: #000080;">=</span> translation_gradient <span style="color: #000040;">*</span> color.<span style="color: #007788;">x</span><span style="color: #008080;">;</span>
    translation_gradient_sum<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#93;</span> <span style="color: #000040;">+</span><span style="color: #000080;">=</span> translation_gradient <span style="color: #000040;">*</span> color.<span style="color: #007788;">y</span><span style="color: #008080;">;</span>
    translation_gradient_sum<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">2</span><span style="color: #008000;">&#93;</span> <span style="color: #000040;">+</span><span style="color: #000080;">=</span> translation_gradient <span style="color: #000040;">*</span> color.<span style="color: #007788;">z</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div>

<h2>Conclusions</h2>
<p>Irradiance Caching provides a very significant speedup to our lightmap baker. On typical meshes we only need to render about 10 to 20% of the samples to approximate the irradiance at very high quality, and for lower quality results or fast previews we can get away with as few as 3% of the samples.</p>
<p>The use of irradiance gradients for interpolation allows reducing the number of samples significantly, or for the same number of samples produces much higher quality results. The following picture compares the results without irradiance gradients and with them, in both cases the number of samples and their location is the same, note how the picture at the bottom has much smoother lightmaps.</p>
<p><a href="http://the-witness.net/news/wp-content/uploads/2011/06/ic_comparison_1.jpg"><img class="aligncenter size-large wp-image-1139" src="http://the-witness.net/news/wp-content/uploads/2011/06/ic_comparison_1-351x384.jpg" alt="" width="351" height="384" /></a></p>
<p>I think that without irradiance caching the hemicube rendering approach to global illumination would have not been practical. That said, implementing irradiance caching robustly is tricky and a lot of tuning and tweaking is required in order to obtain good results.</p>
<p><em>Note: This article is also published at <a href="http://the-witness.net/news/2011/07/irradiance-caching-part-1/">The Witness blog</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/07/14/irradiance-caching-part-1/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 0.971 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2013-06-18 00:28:31 -->
<!-- Compression = gzip -->