<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Aras' website]]></title>
  <link href="http://aras-p.info/atom.xml" rel="self"/>
  <link href="http://aras-p.info/"/>
  <updated>2013-06-11T12:00:17+03:00</updated>
  <id>http://aras-p.info/</id>
  <author>
    <name><![CDATA[Aras Pranckevičius]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Mobile Hardware Stats (and more)]]></title>
    <link href="http://aras-p.info/blog/2013/04/07/mobile-hardware-stats-and-more/"/>
    <updated>2013-04-07T16:06:00+03:00</updated>
    <id>http://aras-p.info/blog/2013/04/07/mobile-hardware-stats-and-more</id>
    <content type="html"><![CDATA[<p><img class="right" src="http://aras-p.info/img/blog/2013-04/hwstats.png"></p>

<p>Short summary: Unity&#8217;s <a href="http://stats.unity3d.com/"><strong>hardware stats page</strong></a> now has a &#8220;mobile&#8221; section. Which is exactly what it says, hardware statistics of people playing Unity games on iOS &amp; Android. Go to <a href="http://stats.unity3d.com/">stats.unity3d.com</a> and enjoy.</p>

<p><em>Some interesting bits:</em></p>

<p><strong>Operating systems</strong></p>

<p><a href="http://stats.unity3d.com/mobile/os-ios.html">iOS uptake</a> is crazy high: 98% of the market has iOS version that&#8217;s not much older than one year (iOS 5.1 was released in 2012 March). You&#8217;d be quite okay targetting just 5.1 and up!</p>

<p><a href="http://stats.unity3d.com/mobile/os.html">Android uptake</a> is&#8230; slightly different. 25% of the market is still on Android 2.3, which is almost two and a half years old (2010 December). Note that for all practical reasons Android 3.x does not exist ;)</p>

<p><a href="http://stats.unity3d.com/web/os.html">Windows XP</a> in the Web Player is making a comeback at 48% of the market. Most likely explained by &#8220;Asia&#8221;, see geography below.</p>

<ul>
<li>Windows Vista could be soon dropped, almost no one is using it anymore. XP&#8230; not dropping that just yet :(</li>
<li>64 bit Windows is still <em>not</em> the norm.</li>
</ul>


<p><strong> Geography </strong></p>

<p> <a href="http://stats.unity3d.com/mobile/os.html">Android</a> is big in United States (18%), China (13%), Korea (12%), Japan (6%), Russia (4%), Taiwan (4%) &#8211; mostly Asia.</p>

<p> <a href="http://stats.unity3d.com/mobile/os-ios.html">iOS</a> is big in United States (30%), United Kingdom (10%), China (7%), Russia (4%), Canada (4%), Germany (4%) &#8211; mostly &#8220;western world&#8221;.</p>

<p> Looking at <a href="http://stats.unity3d.com/web/os.html">Web Player</a>, China is 28% while US is only 12%!</p>

<p><strong> GPU </strong></p>

<p><a href="http://stats.unity3d.com/mobile/gpu.html">GPU makers</a> on Android: Qualcomm 37%, ARM 32%, Imagination 22%, NVIDIA 6%.</p>

<ul>
<li>You wouldn&#8217;t guess NVIDIA is in the distant 4th place, would you?</li>
<li>ARM share is almost entirely Mali 400. Strangely enough, almost no latest generation (Mali T6xx) devices.</li>
<li>OpenGL ES 3.0 capable devices are 4% right now, almost exclusively pulled forward by Qualcomm Adreno 320.</li>
<li>On iOS, Imagination is 100% of course&#8230;</li>
</ul>


<p>No big changes <a href="http://stats.unity3d.com/web/gpu.html">on the PC</a>:</p>

<ul>
<li>Intel slowly rising, NVIDIA &amp; AMD flat, others that used to exist (S3 &amp; SIS) don&#8217;t exist anymore.</li>
<li>GPU capabilities increasing, though shader model 5.0 uptake seems slower than SM4.0 was.</li>
<li>Due to rise of Windows XP, &#8220;can actually use DX10+&#8221; is <em>decreasing</em> :(</li>
</ul>


<p><strong> Devices </strong></p>

<p>On Android, <a href="http://stats.unity3d.com/mobile/device.html">Samsung is king</a> with 55% of the market. No wonder it takes majority of the Android profits I guess. The rest is split by umpteen vendors (Sony, LG, HTC, Amazon etc.).</p>

<p>Most popular devices are various Galaxy models. Out of non-Samsung ones, Kindle Fire (4.3%), Nexus 7 (1.5%) and then it goes into <em>&#8220;WAT? I guess Asia&#8221;</em> territory with Xiaomi MI-One (1.2%) and so on.</p>

<p>On iOS, <a href="http://stats.unity3d.com/mobile/device-ios.html">Apple has 100% share</a> <em>(shocking right?)</em>. There&#8217;s no clear leader in device model; iPhone 4S (18%), iPhone 5 (16%), iPad 2 (16%), iPhone 4 (14%), iPod Touch 4 (10%).</p>

<p>Interesting that first iPad can be pretty much ignored now (1.5%), whereas iPad 2 is still more popular than any of the later iPad models.</p>

<p><strong> CPU </strong></p>

<p>Single core CPUs are about 27% on both Android &amp; iOS. The <a href="http://stats.unity3d.com/mobile/cpu-ios.html">rest on iOS</a> is all dual-core CPUs, whereas almost a <a href="http://stats.unity3d.com/mobile/cpu.html">quarter of Androids</a> have four cores!</p>

<p>ARMv6 can be quite safely ignored. Good.</p>

<p>On PC, the &#8220;lots and lots of cores!&#8221; future <a href="http://stats.unity3d.com/web/cpu.html">did not happen</a> - majority are dual core, and 4 core CPU growth seemingly stopped at 23% (though again, maybe explained by rise of Asia?).</p>

<p><strong> FAQ </strong></p>

<blockquote><p>How big is this data set exactly?</p></blockquote>

<p>Millions and millions. We track the data at quarterly granularity, and in the last quarter mobile has been about 200 million devices <em>(yes really!)</em>; whereas web player has been 36 million machines.</p>

<blockquote><p>Why no &#8220;All&#8221; section in mobile pages, with both Android &amp; iOS?</p></blockquote>

<p>We&#8217;ve added hardware stats tracking on Android earlier, so there are more Unity games made with it out there. Would be totally unfair &#8220;market share&#8221; - right now, 250 million Android devices and &#8220;only&#8221; 4 million iOS devices are represented in the stats. As more developers move to more recent Unity versions, the market share will level out and then we&#8217;ll add &#8220;All&#8221; section.</p>

<blockquote><p>Nice charts, what did you use?</p></blockquote>

<p><a href="http://www.flotcharts.org/">Flot</a>. It is nice! I added &#8221;<a href="https://github.com/flot/flot/pull/867">track by area</a>&#8221; option to it.</p>

<blockquote><p>How often is stats.unity3d.com page updated?</p></blockquote>

<p>Roughly once a month.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA["Parallel for" in Apple's GCD]]></title>
    <link href="http://aras-p.info/blog/2013/02/03/parallel-for-in-apples-gcd/"/>
    <updated>2013-02-03T12:25:00+02:00</updated>
    <id>http://aras-p.info/blog/2013/02/03/parallel-for-in-apples-gcd</id>
    <content type="html"><![CDATA[<p>I was checking out <a href="http://graphics.pixar.com/opensubdiv/">OpenSubdiv</a> and noticed that on a Mac it&#8217;s not exactly &#8220;massively parallel&#8221;. Neither of OpenGL backends work (transform feedback one requires GL 4.2, and compute shader one requires GL 4.3 - but Macs right now can only do GL 3.2), OpenCL backend is much slower than the CPU one (OS X 10.7, GeForce GT 330M) for some reason, I don&#8217;t have CUDA installed so didn&#8217;t check that one, and OpenMP isn&#8217;t exactly supported by Apple&#8217;s compilers (yet?). Which leaves OpenSubdiv doing simple single threaded CPU subdivision.</p>

<p><em>This isn&#8217;t <del>webscale</del> multicorescale! Something must be done!</em></p>

<p>Apple platforms might not support <a href="http://en.wikipedia.org/wiki/OpenMP">OpenMP</a>, but they do have something called <a href="http://en.wikipedia.org/wiki/Grand_Central_Dispatch">Grand Central Dispatch</a> (GCD). Which is supposedly a fancy technology to make multicore programming very easy &#8211; here&#8217;s the <a href="http://www.youtube.com/watch?v=Nx7v815bYUw">original GCD unveiling</a>. Seeing how easy it is, I decided to try it out.</p>

<p>As a baseline, single threaded &#8220;CPU&#8221; subdivision kernel takes 33 milliseconds to compute 4th subdivision level of a &#8220;Car&#8221; model:</p>

<p><img src="http://aras-p.info/img/blog/2013-02/osd-car4cpu.png"></p>

<p><strong> OpenMP dispatcher in OpenSubdiv </strong></p>

<p>Subdivision in OpenSubdiv is computed by running several loops over data: loop to compute new edge positions, new face positions, new vertex positions etc. Fairly standard stuff. Each loop iteration is completely independent from others, for example:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='c'><span class='line'><span class="kt">void</span> <span class="nf">OsdCpuComputeEdge</span><span class="p">(</span><span class="cm">/*...*/</span> <span class="kt">int</span> <span class="n">start</span><span class="p">,</span> <span class="kt">int</span> <span class="n">end</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="n">start</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">end</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>      <span class="c1">// compute i-th edge, completely independent of all other edges</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>So of course OpenMP version just trivially says &#8220;hey, this loop is parallel!&#8221;:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='c'><span class='line'><span class="kt">void</span> <span class="nf">OsdOmpComputeEdge</span><span class="p">(</span><span class="cm">/*...*/</span> <span class="kt">int</span> <span class="n">start</span><span class="p">,</span> <span class="kt">int</span> <span class="n">end</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="cp">#pragma omp parallel for </span><span class="c1">//&lt;-- only this line is different!</span>
</span><span class='line'>    <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="n">start</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">end</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>      <span class="c1">// compute i-th edge</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>And then OpenMP-aware compiler and runtime will decide how to run this loop best over multiple CPU cores available. For example, it might split the loop into as many subsets as there are CPU cores, run these subsets (&#8220;jobs&#8221;) on its worker threads for these cores, and wait until all of them are done. Or it might split it up into more jobs, so that if the job lenghts will end up being different, it will still have some jobs to process on the other cores. This is all up to the OpenMP runtime to decide, but generally for large completely parallel loops it does a pretty good job.</p>

<p><em>Except, well, OpenMP doesn&#8217;t work on current Xcode 4.5 compiler (clang).</em></p>

<p><strong> Initial parallel loop using GCD </strong></p>

<p>GCD documentation suggests using <code>dispatch_apply</code> to submit a number of jobs at once; see <a href="http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html#//apple_ref/doc/uid/TP40008091-CH102-SW23">Performing Loop Operations Concurrently</a> section. This is easy to do:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='c'><span class='line'><span class="kt">void</span> <span class="nf">OsdGcdComputeEdge</span><span class="p">(</span><span class="cm">/*...*/</span> <span class="kt">int</span> <span class="n">start</span><span class="p">,</span> <span class="kt">int</span> <span class="n">end</span><span class="p">,</span> <span class="n">dispatch_queue_t</span> <span class="n">gcdq</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="c1">// replace for loop with:</span>
</span><span class='line'>  <span class="n">dispatch_apply</span><span class="p">(</span><span class="n">end</span><span class="o">-</span><span class="n">start</span><span class="p">,</span> <span class="n">gcdq</span><span class="p">,</span> <span class="o">^</span><span class="p">(</span><span class="kt">size_t</span> <span class="n">blockIdx</span><span class="p">){</span>
</span><span class='line'>      <span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="n">start</span><span class="o">+</span><span class="n">blockIdx</span><span class="p">;</span>
</span><span class='line'>      <span class="c1">// compute i-th edge</span>
</span><span class='line'>    <span class="p">});</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>See <a href="https://github.com/aras-p/OpenSubdiv/commit/b556e9d6cd#diff-3">full commit here</a>. That was easy. <em>And <strong>slower</strong> than single threaded</em>: 47ms with GCD, compared to 33ms single threaded. <em>Not good.</em></p>

<p>OpenMP looks at the whole loop and hopefully partitions it into sensible count of subsets for parallel execution. Whereas GCD&#8217;s <code>dispatch_apply</code> submits <em>each iteration</em> of the loop to be executed in parallel. This &#8220;submit stuff to be executed on my worker threads&#8221; is naturally not a free operation and incurs some overhead. In our case, each iteration of the loop is fairly simple, it pretty much does weighted average of some vertices. Dispatch overhead here is probably higher than the actual work that we&#8217;re trying to do!</p>

<p><strong> Better parallel loop using GCD </strong></p>

<p>Of course the solution here is to batch up work items. Imagine that this loop processes, for example, 16 items (vertices, edges, &#8230;), then goes to next 16, and so on. These &#8220;packets of 16 items&#8221; would be what we dispatch to GCD. At the end of the loop, we might need to handle the remaining ones, if the number of iterations was not a multiple of 16. In fact, this is exactly what GCD documentation suggests in <a href="http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/ThreadMigration/ThreadMigration.html#//apple_ref/doc/uid/TP40008091-CH105-SW2">Improving on Loop Code</a>.</p>

<p>All OpenSubdiv CPU kernels take &#8220;start&#8221; and &#8220;end&#8221; parameters that are essentially indices into an array of where to do the processing. So from our GCD blocks we can just call the regular CPU functions (see <a href="https://github.com/aras-p/OpenSubdiv/commit/c4b463668a">full commit</a>):</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
</pre></td><td class='code'><pre><code class='c'><span class='line'><span class="k">const</span> <span class="kt">int</span> <span class="n">GCD_WORK_STRIDE</span> <span class="o">=</span> <span class="mi">16</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="kt">void</span> <span class="nf">OsdGcdComputeEdge</span><span class="p">(</span><span class="cm">/*...*/</span> <span class="kt">int</span> <span class="n">start</span><span class="p">,</span> <span class="kt">int</span> <span class="n">end</span><span class="p">,</span> <span class="n">dispatch_queue_t</span> <span class="n">gcdq</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="c1">// submit work to GCD in parallel</span>
</span><span class='line'>    <span class="k">const</span> <span class="kt">int</span> <span class="n">workSize</span> <span class="o">=</span> <span class="n">end</span><span class="o">-</span><span class="n">start</span><span class="p">;</span>
</span><span class='line'>    <span class="n">dispatch_apply</span><span class="p">(</span><span class="n">workSize</span><span class="o">/</span><span class="n">GCD_WORK_STRIDE</span><span class="p">,</span> <span class="n">gcdq</span><span class="p">,</span> <span class="o">^</span><span class="p">(</span><span class="kt">size_t</span> <span class="n">blockIdx</span><span class="p">){</span>
</span><span class='line'>        <span class="k">const</span> <span class="kt">int</span> <span class="n">start_i</span> <span class="o">=</span> <span class="n">start</span> <span class="o">+</span> <span class="n">blockIdx</span><span class="o">*</span><span class="n">GCD_WORK_STRIDE</span><span class="p">;</span>
</span><span class='line'>        <span class="k">const</span> <span class="kt">int</span> <span class="n">end_i</span> <span class="o">=</span> <span class="n">start_i</span> <span class="o">+</span> <span class="n">GCD_WORK_STRIDE</span><span class="p">;</span>
</span><span class='line'>        <span class="n">OsdCpuComputeFace</span><span class="p">(</span><span class="cm">/*...*/</span><span class="p">,</span> <span class="n">start_i</span><span class="p">,</span> <span class="n">end_i</span><span class="p">);</span>
</span><span class='line'>    <span class="p">});</span>
</span><span class='line'>    <span class="c1">// do trailing block that&#39;s less than our batch size</span>
</span><span class='line'>    <span class="k">const</span> <span class="kt">int</span> <span class="n">start_e</span> <span class="o">=</span> <span class="n">end</span> <span class="o">-</span> <span class="n">workSize</span><span class="o">%</span><span class="n">GCD_WORK_STRIDE</span><span class="p">;</span>
</span><span class='line'>    <span class="k">const</span> <span class="kt">int</span> <span class="n">end_e</span> <span class="o">=</span> <span class="n">end</span><span class="p">;</span>
</span><span class='line'>    <span class="k">if</span> <span class="p">(</span><span class="n">start_e</span> <span class="o">&lt;</span> <span class="n">end_e</span><span class="p">)</span>
</span><span class='line'>        <span class="n">OsdCpuComputeFace</span><span class="p">(</span><span class="cm">/*...*/</span><span class="p">,</span> <span class="n">start_e</span><span class="p">,</span> <span class="n">end_e</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>This makes 4th subdivision level of the car model be computed in 15ms:</p>

<p><img src="http://aras-p.info/img/blog/2013-02/osd-car4gcd.png"></p>

<p>So that&#8217;s twice as fast as single threaded implementation. Is that good enough or not? My machine is a dual core (4 thread) one, so it is within my ballpark of expectations. Maybe it could go higher, but for that I&#8217;d need to do some profiling.</p>

<p>But you know what? Take a look at the other numbers - 62 milliseconds are spent on &#8220;CPU Draw&#8221;, so clearly that takes way more time than actual subdivision now. Fixing that one will have to be for another time, but suffice to say that reading data from GPU vertex buffers back into system memory each frame might not be a recipe for efficiency.</p>

<p>There&#8217;s at least one place in the above &#8220;GCD loop pattern&#8221; <em>(<a href="http://realtimecollisiondetection.net/blog/?p=44">hi Christer!</a>)</em> that might be improved: dispatch_apply waits until all submitted jobs are done. But to compute the trailing block we don&#8217;t need to wait for the other ones. The trailing block could be incorporated into the dispatch_apply loop, with better computation of end_i variable. Some other day!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Adventures in 3D Printing]]></title>
    <link href="http://aras-p.info/blog/2012/12/14/adventures-in-3d-printing/"/>
    <updated>2012-12-14T17:18:00+02:00</updated>
    <id>http://aras-p.info/blog/2012/12/14/adventures-in-3d-printing</id>
    <content type="html"><![CDATA[<p>I shamelessly stole whole idea from <a href="http://robert.cupisz.eu/">Robert Cupisz</a>
and did some 3D printed earrings. TL;DR: raymarching, marching cubes, MeshLab.</p>

<p><em>Now for the longer version&#8230;</em></p>

<p><strong>Step 1: pick a Quaternion Julia fractal</strong></p>

<p>As always, <a href="http://www.iquilezles.org/www/articles/juliasets3d/juliasets3d.htm">Iñigo Quilez&#8217; work</a> is a definitive
resource. There&#8217;s a ready-made GLSL shader for raymarching this fractal in <a href="http://www.iquilezles.org/apps/shadertoy/">ShaderToy</a> (named &#8220;Quaternion&#8221;), however current state of WebGL doesn&#8217;t allow loops with dynamic number of iterations, so it does not quite work in the browser. The
shader is good otherwise!</p>

<p><strong>Step 2: realtime tweaking with raymarching</strong></p>

<p>With some massaging I&#8217;ve brought the shader into Unity.</p>

<p><img src="http://aras-p.info/img/blog/2012-12/QuatRaymarch.png"></p>

<p>Here, some experimentation with parameters for the fractal (picked 7.45 for &#8220;time value&#8221;), as well as extending the distance function to have a little torus for the earring hook, etc.</p>

<p>Keep in mind that while a fractal might look nice, it might not be printable fine because of too thin walls. All materials have a minimum &#8220;wall thickness&#8221;, and for example <a href="http://www.shapeways.com/materials/silver">silver printed at Shapeways</a> has a minimum thickness of 0.6-0.8mm.
So I had to make the hape somewhat less interesting.</p>

<p>Now this leaves us with a signed distance field function (in a form of a GPU shader).
This needs to be turned into an actual 3D model.</p>

<p><strong>Step 3: marching cubes</strong></p>

<p>Welcome old friend,  <a href="http://en.wikipedia.org/wiki/Marching_cubes">Marching Cubes</a>! I couldn&#8217;t
find anything out of the box that would do &#8220;here&#8217;s my distance field function, do marching cubes on it&#8221;, so I wrote some quick-n-dirty code myself. Started with classic
<a href="http://paulbourke.net/geometry/polygonise/">Paul Bourke&#8217;s code</a> and made it print everything into an .OBJ file.</p>

<p>Here&#8217;s a non-final version of the distance field, gone through marching cubes, and brought back into Unity:</p>

<p><a href="http://aras-p.info/img/blog/2012-12/QuatMarched.jpg"><img src="http://aras-p.info/img/blog/2012-12/QuatMarched-600.jpg"></a></p>

<p>At this point I realized that the output will be quite noisy and some sort of &#8220;smoothing&#8221;
will have to be done. Did a quick try at doing <em>something</em> with 3dsmax, but it is really no
good at dealing with more than a million vertices at a time. Just doing a vertex weld on a million vertex model was taking two hours (?!).</p>

<p><strong>Step 4: filtering in MeshLab</strong></p>

<p>Some googling leads to <a href="http://meshlab.sourceforge.net/">MeshLab</a> which is all kinds of awesome.
And open source (which means the UI is not the most polished one, but hey it works).</p>

<p>Here&#8217;s my final model, as produced by marching cubes, loaded in MeshLab:</p>

<p><a href="http://aras-p.info/img/blog/2012-12/QuatRaw.png"><img src="http://aras-p.info/img/blog/2012-12/QuatRaw-600.jpg"></a></p>

<p>It&#8217;s still quite noisy, has several thin features and possibly sharp edges. Here&#8217;s what I did in
MeshLab:</p>

<ul>
<li>Remove duplicate vertices</li>
<li>Filters -> Remeshing, Simplification and Reconstruction -> Surface Reconstruction: Poisson. Entered 8 as octree depth, left others at default (solver divide: 6, sample per node: 1, surface offsetting: 1).</li>
<li>Scale the model to be about 26mm in length. Scale tool, measure geometric properties filter, freeze matrix.</li>
</ul>


<p><a href="http://aras-p.info/img/blog/2012-12/QuatFinal.png"><img src="http://aras-p.info/img/blog/2012-12/QuatFinal-600.jpg"></a></p>

<p>Did I say MeshLab is awesome? It is.</p>

<p><strong> Step 5: print it!</strong></p>

<p>Export smoothed model from MeshLab, upload the file to a 3D printing service and&#8230; done!
I used <a href="http://www.shapeways.com/creator/">Shapeways</a>, but there&#8217;s also <a href="http://i.materialise.com/">i.materialize</a> and others.</p>

<p>Here is the real actual printed thing!</p>

<p><a href="http://aras-p.info/img/blog/2012-12/QuatPhoto1.jpg"><img src="http://aras-p.info/img/blog/2012-12/QuatPhoto1-600.jpg"></a></p>

<p><a href="http://aras-p.info/img/blog/2012-12/QuatPhoto2.jpg"><img src="http://aras-p.info/img/blog/2012-12/QuatPhoto2-600.jpg"></a></p>

<p>I&#8217;ve been doing computer graphics since, well, last millenium. And this is probably
the first time when this &#8220;graphics work&#8221; directly ends up in a real actual <em>thing</em>.
Feels nice ;)</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Non Power of Two Textures]]></title>
    <link href="http://aras-p.info/blog/2012/10/17/non-power-of-two-textures/"/>
    <updated>2012-10-17T09:15:00+03:00</updated>
    <id>http://aras-p.info/blog/2012/10/17/non-power-of-two-textures</id>
    <content type="html"><![CDATA[<p>Support for non power of two (&#8220;NPOT&#8221;, i.e. arbitrary sized) textures has been in GPUs for quite a while, but the state of support can be confusing. Recent question from <a href="http://twitter.com/rygorous">@rygorous</a>:</p>

<blockquote><p>Lazyweb, &lt;&#8230;> GL question: &lt;&#8230;> ARB NPOT textures is fairly demanding, and texture rectangle
are awkward. Is there an equivalent to ES2-style semantics in regular GL? Bonus Q: Is there something
like the Unity HW survey, but listing supported GL extensions? :)</p></blockquote>

<p>There are generally three big types of texture size support:</p>

<ul>
<li>Full support for arbitrary texture sizes. This includes mipmaps, all texture wrap &amp; filtering modes, and most often compressed texture formats as well.</li>
<li>&#8220;Limited&#8221; support for non-power-of-two sizes. No mipmaps, texture wrap mode has to be Clamp, but does allow texture filtering. This makes such textures not generally useful in 3D space, but just good enough for anything in screen space (UI, 2D, postprocessing).</li>
<li>No support, texture sizes have to be powers of two (16,32,64,128,&#8230;). If you&#8217;re running on really, <em>really</em> old GPU then textures might also need to be square (width = height).</li>
</ul>


<p><strong> Direct3D 9 </strong></p>

<p>Things are quite simple here. <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb172513.aspx">D3DCAPS9.TextureCaps</a> has capability bits, <code>D3DPTEXTURECAPS_POW2</code> and <code>D3DPTEXTURECAPS_NONPOW2CONDITIONAL</code> both being <em>off</em> indicates full support for NPOT texture sizes. When both <code>D3DPTEXTURECAPS_POW2</code> and <code>D3DPTEXTURECAPS_NONPOW2CONDITIONAL</code> bits are <em>on</em>, then you have limited NPOT support.</p>

<p><em>I&#8217;ve no idea what would it mean if NONPOW2CONDITIONAL bit is set, but POW2 bit is not.</em></p>

<p>Hardware wise, limited NPOT has been generally available since 2002-2004, and full NPOT since 2006 or so.</p>

<p><strong> Direct3D 11 </strong></p>

<p>Very simple; feature level 10_0 and up has full support for NPOT sizes; while feature level 9_x has limited support for NPOT. <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ff476876.aspx">MSDN link</a>.</p>

<p><strong> OpenGL </strong></p>

<p>Support for NPOT textures has been a core OpenGL feature since 2.0; promoted from earlier <a href="http://www.opengl.org/registry/specs/ARB/texture_non_power_of_two.txt">ARB_texture_non_power_of_two</a> extension. The extension specifies &#8220;full&#8221; support for NPOT, including mipmaps &amp; wrapping modes. There&#8217;s no practical way to detect hardware that can only do &#8220;limited&#8221; NPOT textures.</p>

<p>However, in traditional OpenGL spirit, presence of something in the API does not mean it can run on the GPU&#8230; E.g. Mac OS X with <a href="https://developer.apple.com/graphicsimaging/opengl/capabilities/">Radeon X1600 GPU is an OpenGL 2.1+</a> system, and as such pretends there&#8217;s full support for NPOT textures. In practice, as soon as you have NPOT size with mipmaps or a non-clamp wrap mode, you drop into software rendering. <em>Ouch.</em></p>

<p>A rule of thumb that seems to work: try to detect &#8220;DX10+&#8221; level GPU, and in that case assume full NPOT support is <em>actually</em> there. Otherwise, in GL2.0+ or when <code>ARB_texture_non_power_of_two</code> is present, only assume <em>limited</em> NPOT support.</p>

<p>Then the question of course is, how to detect DX10+ level GPU in OpenGL? If you&#8217;re using OpenGL 3+, then you are on DX10+ GPU. In earlier GL versions, you&#8217;d have to use some heuristics. For example, if you have <code>ARB_fragment_program</code> and <code>GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB</code> is less than 4096 is a pretty good indicator of pre-DX10 hardware, on Mac OS X at least. Likewise, you could query <code>MAX_TEXTURE_SIZE</code>, lower than 8192 is a good indicator for pre-DX10.</p>

<p><strong> OpenGL ES </strong></p>

<p>OpenGL ES 3.0 has full NPOT support in core; ES 2.0 has limited NPOT support (no mipmaps, no Repeat wrap mode) in core; and ES 1.1 has no NPOT support.</p>

<p>For ES 1.1 and 2.0, full NPOT support comes with <code>GL_ARB_texture_non_power_of_two</code> or <code>GL_OES_texture_npot</code> extension. In practice, iOS devices don&#8217;t support this; and on Android side there&#8217;s support on Qualcomm Adreno and ARM Mali. Possibly some others.</p>

<p>For ES 1.1, limited NPOT support comes with <code>GL_APPLE_texture_2D_limited_npot</code> (all iOS devices) or <code>GL_IMG_texture_npot</code> (some ImgTec Android devices I guess).</p>

<p>WebGL and Native Client currently are pretty much OpenGL ES 2.0, and thus support limited NPOT textures.</p>

<p><strong> Flash Stage3D </strong></p>

<p>Sad situation here; current version of Stage3D (as of Flash Player 11.4) has no NPOT support whatsoever. Not even for render targets.</p>

<p><strong> Consoles </strong></p>

<p>I wouldn&#8217;t be allowed to say anything about them, now would I? :) Check documentation that comes with your developer access on each console.</p>

<p><strong> Is there something like the Unity HW survey, but listing supported GL extensions? </strong></p>

<p>Not a single good resource, but there are various bits and pieces:</p>

<ul>
<li><a href="http://unity3d.com/webplayer/hardware-stats">Unity Web Player hardware stats</a> - no GL extensions, but we do map GPUs to &#8220;DX-like&#8221; levels and from there you can sort of infer things.</li>
<li><a href="http://store.steampowered.com/hwsurvey">Steam Hardware Survey</a> - likewise.</li>
<li><a href="https://developer.apple.com/graphicsimaging/opengl/capabilities/">Apple OpenGL Capabilities</a> - tables of detailed GL info for recent OS X versions and all GPUs supported by Apple. Excellent resource for Mac programmers! Apple does remove pages of old OS X versions from there, you&#8217;d have to use <a href="http://archive.org/">archive.org</a> to get them back.</li>
<li><a href="http://www.glbenchmark.com/result.jsp">GLBenchmark Results</a> - results database of GLBenchmark, has list of OpenGL ES extensions and some caps bits for each result (&#8220;GL config.&#8221; tab).</li>
<li><a href="http://www.realtech-vr.com/">Realtech VR GLView</a> - OpenGL &amp; OpenGL ES extensions and capabilities viewer, for Windows, Mac, iOS &amp; Android.</li>
<li><a href="http://update.omnigroup.com/">Omni Software Update Statistics</a> - Mac specific, but does list some OpenGL stats from &#8220;Graphics&#8221; dropdown.</li>
<li><a href="http://kludx.com/">KluDX</a> - Windows app that shows information about GPU; also has reports of submitted data.</li>
<li><a href="http://feedback.wildfiregames.com/report/opengl/">0 A.D. OpenGL capabilities database</a> - OpenGL capabilities submitted by players of 0 A.D. game.</li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Cross Platform Shaders in 2012]]></title>
    <link href="http://aras-p.info/blog/2012/10/01/cross-platform-shaders-in-2012/"/>
    <updated>2012-10-01T13:53:00+03:00</updated>
    <id>http://aras-p.info/blog/2012/10/01/cross-platform-shaders-in-2012</id>
    <content type="html"><![CDATA[<p>Since about 2002 to 2009 the de facto shader language for games was HLSL. Everyone on PCs was targeting Windows through Direct3D, Xbox 360 uses HLSL as well, and Playstation 3 uses Cg, which for all practical purposes is the same as HLSL. There were very few people targeting Mac OS X or Linux, or using OpenGL on Windows. One shader language ruled the world, and everything was rosy. You could close your eyes and pretend OpenGL with it&#8217;s GLSL language just did not exist.</p>

<p>Then a series of events happened, and all of a sudden OpenGL is needed again! iOS and Android are too big to be ignored (which means OpenGL ES + GLSL), and making games for Mac OS X or Linux isn&#8217;t a crazy idea either. This little WebGL thing that excites many hackers uses a variant of GLSL as well.</p>

<p><strong>Now we have a problem; we have two similar but subtly different shading languages to deal with</strong>. I wrote about how we <a href="http://aras-p.info/blog/2010/05/21/compiling-hlsl-into-glsl-in-2010/">deal with this at Unity</a>, and not much has changed since 2010. The &#8220;recommended way&#8221; is still writing HLSL/Cg, and we cross-compile into GLSL for platforms that need it.</p>

<p>But what about the future?</p>

<p><em>It could happen that importance of HLSL (and Direct3D) will decrease over time; this largely depends on what Microsoft is going to do. But just like OpenGL became important again just as it seemed to become irrelevant, so could Direct3D. Or something completely new. I&#8217;ll assume that for several years into the future, we&#8217;ll need to deal with at least two shading languages.</em></p>

<p>There are several approaches at handling the problem, and several solutions in that space, at varying levels of completeness.</p>

<p><strong> #1. Do it all by hand! </strong></p>

<p>&#8220;Just write all shaders twice&#8221;. Ugh. That&#8217;s not &#8220;web scale&#8221; so we&#8217;ll just discard this approach.</p>

<p>Slightly related approach is to have a library of preprocessor macros &amp; function definitions, and use them in places where HLSL &amp; GLSL are different. This is certainly doable, take a look at <a href="http://timothylottes.blogspot.com/2011/07/fxaa-311-released.html">FXAA</a> for a good example. Downsides are, you really need to know all the tiny differences between languages. HLSL&#8217;s <code>fmod()</code> and GLSL&#8217;s <code>mod()</code> sound like they do the same thing, but are subtly different - and there are many more places like this.</p>

<p><strong> #2. Don&#8217;t use HLSL nor GLSL: treat them as shader backends </strong></p>

<p>You could go for fully graphical based shader authoring. Drag some nodes around, connect them, and have shader &#8220;baking&#8221; code that can spit out HLSL, GLSL, or anything else that is needed. This is a big enough topic by iself; graphical shader editing has a lot more uses at &#8220;describing material properties&#8221; level than it has at lower level (who&#8217;d want to write a deferred rendering light pass shader using nodes &amp; lines?).</p>

<p>You could also use a completely different language that compiles down to HLSL or GLSL. I&#8217;m not aware of any big uses in realtime graphics, but recent examples could be <a href="https://github.com/imageworks/OpenShadingLanguage/">Open Shading Language</a> (in film) or <a href="http://www.cdl.uni-saarland.de/projects/anysl/">AnySL</a> (in research).</p>

<p><strong> #3. Cross-compile HLSL source into GLSL or vice versa </strong></p>

<p>Parse shader source in one language, produce some intermediate representation, massage / verify that representation as needed, &#8220;print&#8221; it into another language. Some solutions exist here, for example:</p>

<ul>
<li><a href="https://github.com/aras-p/hlsl2glslfork">hlsl2glslfork</a> does DX9 HLSL -> GLSL 1.10 / ES 1.00 translation. Used by Unity, and judging from pull requests and pokes I get, in several dozen other game development shops.</li>
<li><a href="http://code.google.com/p/angleproject/">ANGLE</a> does GLSL ES 1.00 -> DX9 HLSL. Used by WebGL implementation in Chrome and Firefox.</li>
<li><a href="http://developer.nvidia.com/cg-toolkit">Cg</a> compiles Cg (&#8220;almost the same as HLSL&#8221;) into various backends, including D3D9 shader assembly and various versions of GLSL, with mixed success. No support for compiling into D3D10+ shader bytecode as far as I can tell.</li>
</ul>


<p>Big limitation of two libraries above, is that they only do &#8220;DX9 level&#8221; shaders, so to speak. No support for DX10/11 style HLSL syntax (which Microsoft has changed <em>a lot</em>), and no support for correspondingly higher GLSL versions (GLSL 3.30+, GLSL ES 3.00). At least right now.</p>

<blockquote><p><strong> Call to action! </strong>
There seems to be a need for source level translation libraries for DX10/GL3+ style language syntax &amp; feature sets.
I&#8217;m not sure if it makes sense to extend the above libraries, or to start from scratch&#8230; But we need a good quality, open source
with liberal license, well maintained &amp; tested package to do this. It shouldn&#8217;t be hard, and it probably doesn&#8217;t make sense for everyone
to try to roll their own. <strong>github &amp; bitbucket makes collaboration a snap, let&#8217;s do it</strong>.</p></blockquote>

<p>If anyone at Microsoft is reading this: it would <em>really help</em> to have formal grammar of HLSL available. &#8220;Reference for HLSL&#8221; on MSDN has tiny bits and pieces scattered around, but that seems both incomplete and hard to assemble into a single grammar.</p>

<p>A building block could be <a href="http://cgit.freedesktop.org/mesa/mesa">Mesa</a> or its smaller fork, <a href="https://github.com/aras-p/glsl-optimizer">GLSL Optimizer</a> (see related <a href="http://aras-p.info/blog/2010/09/29/glsl-optimizer/">blog post</a>). It has a decent intermediate representation (IR) for shaders, a bunch of cleanup/optimization/lowering passes, a GLSL parser and GLSL printer (in GLSL Optimizer). Could be extended to parse HLSL and/or print HLSL. Currently lacking most of DX11/GL4 features, and some DX10/GL3 features in the IR. But under active development, so will get those soon I hope.</p>

<p><a href="http://icculus.org/mojoshader/">MojoShader</a> also has an in-progress HLSL parser and translator to GLSL.</p>

<p><strong> #4. Translate compiled shader bytecode into GLSL </strong></p>

<p>Take HLSL, compile it down to bytecode, parse that bytecode and generate corresponding &#8220;low level&#8221; GLSL. Right now this would only go one way, as GLSL does not have a cross platform &#8220;compiled shader&#8221; representation. <em>Though with recent <a href="http://www.khronos.org/news/permalink/khronos-spir-1.0-specification-for-opencl-now-available">OpenCL getting SPIR</a>, maybe there&#8217;s hope in OpenGL getting something similar in the future?</em></p>

<p>This is a lot simpler to do than parsing full high level language, and a ton of platform differences go away (the ones that are handled purely at syntax level, e.g. function overloading, type promotion etc.). A possible downside is that HLSL bytecode might be &#8220;too optimized&#8221; - all the hard work about register packing &amp; allocation, loop unrolling etc. is not that much needed here. Any conventions like whether your matrices are column-major or row-major is also &#8220;baked into&#8221; the resulting shader, so your D3D and GL rendering code better match there.</p>

<p>Several existing libraries in this space:</p>

<ul>
<li><a href="http://icculus.org/mojoshader/">MojoShader</a> translates DX9 shader model 1.1 to 3.0 into GLSL or ARB assembly programs. Used in many Linux game ports and probably somewhere else.</li>
<li><a href="https://github.com/James-Jones/HLSLCrossCompiler">James Jones&#8217; HLSLCrossCompiler</a>, a recent project on github that translates DX10/11 shader model 4/5 to GLSL 3.30. Seems like in active development, a <a href="http://jamesjonesdeveloper.com/wordpress/?p=25">blog post about it here</a>.</li>
<li><a href="http://code.google.com/p/fxdis-d3d1x/">Rich Geldreich&#8217;s fxdis-d3d1x</a>, a shader model 4/5 bytecode disassembler. Based on Mesa&#8217;s <a href="http://cgit.freedesktop.org/mesa/mesa/commit/?id=92617aeac109481258f0c3863d09c1b8903d438b">D3D11 state tracker</a>.</li>
</ul>


<p><strong> What now? </strong></p>

<p>Go and make solutions to the approaches above, especially #3 and #4! Cross-platform shader developers all around the world will thank you. <em>All twenty of them, or something ;)</em></p>

<p>If you&#8217;re a student looking for an entry into the industry as a programmer: <em>this is a perfect example of a freetime / university project</em>! It&#8217;s self-contained, it has clear goals, and above all, it&#8217;s <em>actually useful</em> for the real world. A non-crappy implementation of a library like this would almost certainly land you a job at <a href="http://unity3d.com/company/jobs/overview">Unity</a> and I guess many other places.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Careful with That Initializer, Eugene]]></title>
    <link href="http://aras-p.info/blog/2012/07/09/careful-with-that-initializer/"/>
    <updated>2012-07-09T22:04:00+03:00</updated>
    <id>http://aras-p.info/blog/2012/07/09/careful-with-that-initializer</id>
    <content type="html"><![CDATA[<p>I was profiling something, and noticed that <code>HighestBit()</code> was taking suspiciously large amount of time. So I looked at the code.
It had some platform specific implementations, but the cross-platform fallback was this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
</pre></td><td class='code'><pre><code class='c'><span class='line'><span class="c1">// index of the highest bit set, or -1 if input is zero</span>
</span><span class='line'><span class="kr">inline</span> <span class="kt">int</span> <span class="nf">HighestBitRef</span> <span class="p">(</span><span class="n">UInt32</span> <span class="n">mask</span><span class="p">)</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>  <span class="kt">int</span> <span class="n">base</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span><span class='line'>  <span class="k">if</span> <span class="p">(</span> <span class="n">mask</span> <span class="o">&amp;</span> <span class="mh">0xffff0000</span> <span class="p">)</span>
</span><span class='line'>  <span class="p">{</span>
</span><span class='line'>      <span class="n">base</span> <span class="o">=</span> <span class="mi">16</span><span class="p">;</span>
</span><span class='line'>      <span class="n">mask</span> <span class="o">&gt;&gt;=</span> <span class="mi">16</span><span class="p">;</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>  <span class="k">if</span> <span class="p">(</span> <span class="n">mask</span> <span class="o">&amp;</span> <span class="mh">0x0000ff00</span> <span class="p">)</span>
</span><span class='line'>  <span class="p">{</span>
</span><span class='line'>      <span class="n">base</span> <span class="o">+=</span> <span class="mi">8</span><span class="p">;</span>
</span><span class='line'>      <span class="n">mask</span> <span class="o">&gt;&gt;=</span> <span class="mi">8</span><span class="p">;</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>  <span class="k">if</span> <span class="p">(</span> <span class="n">mask</span> <span class="o">&amp;</span> <span class="mh">0x000000f0</span> <span class="p">)</span>
</span><span class='line'>  <span class="p">{</span>
</span><span class='line'>      <span class="n">base</span> <span class="o">+=</span> <span class="mi">4</span><span class="p">;</span>
</span><span class='line'>      <span class="n">mask</span> <span class="o">&gt;&gt;=</span> <span class="mi">4</span><span class="p">;</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>  <span class="k">const</span> <span class="kt">int</span> <span class="n">lut</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">};</span>
</span><span class='line'>  <span class="k">return</span> <span class="n">base</span> <span class="o">+</span> <span class="n">lut</span><span class="p">[</span> <span class="n">mask</span> <span class="p">];</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Not the best implementation of the functionality, but probably not the worst either. Takes three branches, and then a small look-up table.</p>

<p><em>Notice anything suspicious?</em></p>

<p>Let&#8217;s take a look at the assembly (MSVC 2010, x86).</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
<span class='line-number'>40</span>
<span class='line-number'>41</span>
<span class='line-number'>42</span>
<span class='line-number'>43</span>
<span class='line-number'>44</span>
<span class='line-number'>45</span>
<span class='line-number'>46</span>
<span class='line-number'>47</span>
<span class='line-number'>48</span>
<span class='line-number'>49</span>
<span class='line-number'>50</span>
<span class='line-number'>51</span>
<span class='line-number'>52</span>
<span class='line-number'>53</span>
<span class='line-number'>54</span>
<span class='line-number'>55</span>
</pre></td><td class='code'><pre><code class='nasm'><span class='line'><span class="c1">; int HighestBitRef (UInt32 mask)</span>
</span><span class='line'><span class="nf">push</span>        <span class="nb">ebp</span>
</span><span class='line'><span class="nf">mov</span>         <span class="nb">ebp</span><span class="p">,</span><span class="nb">esp</span>
</span><span class='line'><span class="nf">sub</span>         <span class="nb">esp</span><span class="p">,</span><span class="mh">44h</span>
</span><span class='line'><span class="nf">mov</span>         <span class="nb">eax</span><span class="p">,</span><span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nv">___security_cookie</span><span class="p">]</span> <span class="c1">; MSVC stack-smashing protection</span>
</span><span class='line'><span class="nf">xor</span>         <span class="nb">eax</span><span class="p">,</span><span class="nb">ebp</span>
</span><span class='line'><span class="nf">mov</span>         <span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">-</span><span class="mi">4</span><span class="p">],</span><span class="nb">eax</span>
</span><span class='line'><span class="c1">; int base = 0;</span>
</span><span class='line'><span class="nf">mov</span>         <span class="nb">ecx</span><span class="p">,</span><span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">+</span><span class="mi">8</span><span class="p">]</span>
</span><span class='line'><span class="nf">xor</span>         <span class="nb">edx</span><span class="p">,</span><span class="nb">edx</span>
</span><span class='line'><span class="c1">; if ( mask &amp; 0xffff0000 )</span>
</span><span class='line'><span class="nf">test</span>        <span class="nb">ecx</span><span class="p">,</span><span class="mh">0FFFF0000h</span>
</span><span class='line'><span class="nf">je</span>          <span class="nv">_lbl1</span>
</span><span class='line'><span class="nf">mov</span>         <span class="nb">edx</span><span class="p">,</span><span class="mh">10h</span>  <span class="c1">; base = 16;</span>
</span><span class='line'><span class="nf">shr</span>         <span class="nb">ecx</span><span class="p">,</span><span class="mh">10h</span>  <span class="c1">; mask &gt;&gt;= 16;</span>
</span><span class='line'><span class="nl">_lbl1:</span> <span class="c1">; if ( mask &amp; 0x0000ff00 )</span>
</span><span class='line'><span class="nf">test</span>        <span class="nb">ecx</span><span class="p">,</span><span class="mh">0FF00h</span>
</span><span class='line'><span class="nf">je</span>          <span class="nv">_lbl2</span>
</span><span class='line'><span class="nf">add</span>         <span class="nb">edx</span><span class="p">,</span><span class="mi">8</span>  <span class="c1">; base += 8;</span>
</span><span class='line'><span class="nf">shr</span>         <span class="nb">ecx</span><span class="p">,</span><span class="mi">8</span>  <span class="c1">; mask &gt;&gt;= 8;</span>
</span><span class='line'><span class="nl">_lbl2:</span> <span class="c1">; if ( mask &amp; 0x000000f0 )</span>
</span><span class='line'><span class="nf">test</span>        <span class="nb">cl</span><span class="p">,</span><span class="mh">0F0h</span>
</span><span class='line'><span class="nf">je</span>          <span class="nv">_lbl3</span>
</span><span class='line'><span class="nf">add</span>         <span class="nb">edx</span><span class="p">,</span><span class="mi">4</span>  <span class="c1">; base += 4;</span>
</span><span class='line'><span class="nf">shr</span>         <span class="nb">ecx</span><span class="p">,</span><span class="mi">4</span>  <span class="c1">; mask &gt;&gt;= 4;</span>
</span><span class='line'><span class="nl">_lbl3:</span>
</span><span class='line'><span class="c1">; const int lut[] = {-1,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3};</span>
</span><span class='line'><span class="nf">mov</span>         <span class="nb">eax</span><span class="p">,</span><span class="mi">1</span>
</span><span class='line'><span class="nf">mov</span>         <span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">-</span><span class="mh">3Ch</span><span class="p">],</span><span class="nb">eax</span>
</span><span class='line'><span class="nf">mov</span>         <span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">-</span><span class="mh">38h</span><span class="p">],</span><span class="nb">eax</span>
</span><span class='line'><span class="nf">mov</span>         <span class="nb">eax</span><span class="p">,</span><span class="mi">2</span>
</span><span class='line'><span class="nf">mov</span>         <span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">-</span><span class="mh">34h</span><span class="p">],</span><span class="nb">eax</span>
</span><span class='line'><span class="nf">mov</span>         <span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">-</span><span class="mh">30h</span><span class="p">],</span><span class="nb">eax</span>
</span><span class='line'><span class="nf">mov</span>         <span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">-</span><span class="mh">2Ch</span><span class="p">],</span><span class="nb">eax</span>
</span><span class='line'><span class="nf">mov</span>         <span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">-</span><span class="mh">28h</span><span class="p">],</span><span class="nb">eax</span>
</span><span class='line'><span class="nf">mov</span>         <span class="nb">eax</span><span class="p">,</span><span class="mi">3</span>
</span><span class='line'><span class="nf">mov</span>         <span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">-</span><span class="mh">24h</span><span class="p">],</span><span class="nb">eax</span>
</span><span class='line'><span class="nf">mov</span>         <span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">-</span><span class="mh">20h</span><span class="p">],</span><span class="nb">eax</span>
</span><span class='line'><span class="nf">mov</span>         <span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">-</span><span class="mh">1Ch</span><span class="p">],</span><span class="nb">eax</span>
</span><span class='line'><span class="nf">mov</span>         <span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">-</span><span class="mh">18h</span><span class="p">],</span><span class="nb">eax</span>
</span><span class='line'><span class="nf">mov</span>         <span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">-</span><span class="mh">14h</span><span class="p">],</span><span class="nb">eax</span>
</span><span class='line'><span class="nf">mov</span>         <span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">-</span><span class="mh">10h</span><span class="p">],</span><span class="nb">eax</span>
</span><span class='line'><span class="nf">mov</span>         <span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">-</span><span class="mh">0Ch</span><span class="p">],</span><span class="nb">eax</span>
</span><span class='line'><span class="nf">mov</span>         <span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">-</span><span class="mi">8</span><span class="p">],</span><span class="nb">eax</span>
</span><span class='line'><span class="nf">mov</span>         <span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">-</span><span class="mh">44h</span><span class="p">],</span><span class="mh">0FFFFFFFFh</span>
</span><span class='line'><span class="nf">mov</span>         <span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">-</span><span class="mh">40h</span><span class="p">],</span><span class="mi">0</span>
</span><span class='line'><span class="c1">; return base + lut[ mask ];</span>
</span><span class='line'><span class="nf">mov</span>         <span class="nb">eax</span><span class="p">,</span><span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">+</span><span class="nb">ecx</span><span class="o">*</span><span class="mi">4</span><span class="o">-</span><span class="mh">44h</span><span class="p">]</span>
</span><span class='line'><span class="nf">mov</span>         <span class="nb">ecx</span><span class="p">,</span><span class="kt">dword</span> <span class="nv">ptr</span> <span class="p">[</span><span class="nb">ebp</span><span class="o">-</span><span class="mi">4</span><span class="p">]</span>
</span><span class='line'><span class="nf">xor</span>         <span class="nb">ecx</span><span class="p">,</span><span class="nb">ebp</span>
</span><span class='line'><span class="nf">add</span>         <span class="nb">eax</span><span class="p">,</span><span class="nb">edx</span>
</span><span class='line'><span class="nf">call</span>        <span class="nv">functionSearch</span><span class="o">+</span><span class="mi">1</span> <span class="c1">; MSVC stack-smashing protection</span>
</span><span class='line'><span class="nf">mov</span>         <span class="nb">esp</span><span class="p">,</span><span class="nb">ebp</span>
</span><span class='line'><span class="nf">pop</span>         <span class="nb">ebp</span>
</span><span class='line'><span class="nf">ret</span>
</span></code></pre></td></tr></table></div></figure>


<p>Ouch. <strong>It is creating that look-up table</strong>. Each. And. Every. Time.</p>

<p>Well, the code asked for that: <code>const int lut[] = {-1,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3}</code>, so the compiler does exactly what it was told.
Could the compiler be smarter, notice that the table is actually always constant, and put that into the data segment?
<em>&#8220;I would if I was a compiler, and I&#8217;m not even smart!&#8221;</em> The compiler could do this, I guess, but it does not <em>have to</em>. More often
than not, <strong>if you&#8217;re expecting the compiler to &#8220;be smart&#8221;, it will do the opposite</strong>.</p>

<p>So the above code, it fills the table. This makes the function long enough that the compiler decides to not inline it. And since it&#8217;s
filling up some table on the stack, MSVC&#8217;s &#8220;stack protection&#8221; code bits come into play (which are on by default), making the code even longer.</p>

<p>I&#8217;ve done a quick test and timed how long does this take: <code>for (int i = 0; i &lt; 100000000; ++i) sum += HighestBitRef(i);</code> on a
Core i7-2600K @ 3.4GHz&#8230; <strong>565 milliseconds</strong>.</p>

<p>The fix? Do not initialize the lookup table each time!</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='c'><span class='line'><span class="k">const</span> <span class="kt">int</span> <span class="n">kHighestBitLUT</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="kr">inline</span> <span class="kt">int</span> <span class="nf">HighestBitRef</span> <span class="p">(</span><span class="n">UInt32</span> <span class="n">mask</span><span class="p">)</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>  <span class="c1">// ...</span>
</span><span class='line'>  <span class="k">return</span> <span class="n">base</span> <span class="o">+</span> <span class="n">kHighestBitLUT</span><span class="p">[</span> <span class="n">mask</span> <span class="p">];</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Note: I could have just put in a <code>static const int lut[]</code> in the original function code. But that <em>sounds</em> like this might not be thread-safe
(at least similar initialization of more complex objects isn&#8217;t; not sure about array initializers). A quick test with MSVC2010 reveals that it is thread-safe, but I wouldn&#8217;t want to rely on that.</p>

<p>How much faster now? 298 milliseconds if explicitly non-inlined, <strong>110 ms</strong> when inlined. <strong>Five times faster</strong> by moving one line up!
For completeness sake, using MSVC <code>_BitScanReverse</code> intrinsic (<code>__builtin_clz</code> in gcc), which compiles down to x86 <code>BSR</code> instruction, takes 94 ms in the same test.</p>

<p>So&#8230; yeah. Careful with those initializers.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Tiled Forward Shading links]]></title>
    <link href="http://aras-p.info/blog/2012/03/27/tiled-forward-shading-links/"/>
    <updated>2012-03-27T17:35:46+03:00</updated>
    <id>http://aras-p.info/blog/2012/03/27/tiled-forward-shading-links</id>
    <content type="html"><![CDATA[<p>Main idea of my <a href="http://aras-p.info/blog/2012/03/02/2012-theory-for-forward-rendering/">previous post</a> was roughly this: in forward rendering, there&#8217;s no reason why we still have to use per-object light lists. We can apply roughly the same ideas as those of tiled deferred shading.</p>

<p>Really nice to see that other people have thought about this before or about the same time; here are some links:</p>

<ul>
<li><p><a href="http://www.cse.chalmers.se/~olaolss/main_frame.php?contents=publication&amp;id=tiled_shading">Tiled Shading</a> by Ola Olsson and Ulf Assarsson; Journal of Graphics Tools. PDF, source code and comparisons between tiled forward &amp; tiled deferred. <em>Update:</em> &#8220;clustered shading&#8221; was published since then, see next item.</p></li>
<li><p><a href="http://www.cse.chalmers.se/~olaolss/main_frame.php?contents=publication&amp;id=clustered_shading">Clustered Deferred and Forward Shading</a> by Ola Olsson , Markus Billeter and Ulf Assarsson. Takes ideas from tiled shading and brings them to the next level.</p></li>
<li><p><a href="http://developer.amd.com/gpu_assets/AMD_Demos_LeoDemoGDC2012.ppsx">Forward+: Bringing Deferred Lighting to the Next Level</a> by Takahiro Hirada, Jay McKee, Jason C. Yang; GDC 2012. This describes AMD&#8217;s Leo demo. There&#8217;s an incomplete Eurographics 2012 <a href="https://sites.google.com/site/takahiroharada/">paper here</a>.</p></li>
<li><p><a href="http://www.pjblewis.com/articles/tile-based-forward-rendering/">Tile-Based Forward Rendering</a> by Peter J. B. Lewis. Implementation without using a Compute Shader (but uses other DX11 features like UAVs).</p></li>
<li><p><a href="http://mynameismjp.wordpress.com/2012/03/31/light-indexed-deferred-rendering/">Light Indexed Deferred Rendering</a>; new implementation by Matt &#8220;MJP&#8221; Pettineo. Includes performance comparisons with tiled deferred rendering.</p></li>
<li><p>Very similar in approach is of course <a href="http://code.google.com/p/lightindexed-deferredrender/">Light Indexed Deferred Rendering</a> by Damian Trebilco.</p></li>
</ul>


<p>As <a href="http://portfolio.punkuser.net/">Andrew Lauritzen</a> points out in the <a href="http://aras-p.info/blog/2012/03/02/2012-theory-for-forward-rendering/#comment-179964">comments of my previous post</a>, claiming &#8220;but deferred will need super-fat G-buffers!&#8221; is an over-simplification. You could just as well store material indices plus data for sampling textures (UVs + derivatives); and going &#8220;deferred&#8221; you have more choices in how you schedule your computations.</p>

<p>There&#8217;s no principal difference between &#8220;forward&#8221; and &#8220;deferred&#8221; these days. As soon as you have a Z-prepass you already are caching/deferring <em>something</em>, and then it&#8217;s a whole spectrum of options what and how to cache or &#8220;defer&#8221; for later computation.</p>

<p>Ultimately of course, the best approach depends on a million of factors. The only lesson to learn from this post is that &#8220;forward rendering does not have to use per-object light lists&#8221;.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[2012 Theory for Forward Rendering]]></title>
    <link href="http://aras-p.info/blog/2012/03/02/2012-theory-for-forward-rendering/"/>
    <updated>2012-03-02T10:16:30+02:00</updated>
    <id>http://aras-p.info/blog/2012/03/02/2012-theory-for-forward-rendering</id>
    <content type="html"><![CDATA[<p>Good question in a <a href="https://twitter.com/ivanassen/statuses/175350571044311042">tweet</a> by <a href="https://twitter.com/#!/ivanassen">@ivanassen</a>:</p>

<blockquote><p>So what is the 2012 theory on lights in a forward renderer?</p></blockquote>

<p>Hard to answer that in 140 characters, so here goes raw brain dump <em>(warning: not checked in practice!)</em>.</p>

<p><strong>Short answer</strong></p>

<p>A modern forward renderer for DX11-class hardware would probably be something like <a href="http://developer.amd.com/samples/demos/pages/AMDRadeonHD7900SeriesGraphicsReal-TimeDemos.aspx">AMD&#8217;s Leo demo</a>.</p>

<p>They seem to be doing light culling in a compute shader, and the result is per-pixel / tile linked lists of lights. Then scene is rendered normally in forward rendering, fetching the light lists and computing shading. Advantages are many; arbitrary shading models with many parameters that would be hard to store in a G-buffer; semitransparent objects; hardware MSAA support; much smaller memory requirements compared to some fat G-buffer layout.</p>

<p>Disadvantages would be storing linked lists, I guess. Potentially unbounded memory usage here, though I guess various schemes similar to <a href="http://software.intel.com/en-us/articles/adaptive-transparency/">Adaptive Transparency</a> could be used to cap the maximum number of lights per pixel/tile.</p>

<p><strong>Deferred == Caching</strong></p>

<p>All the deferred lighting/shading approaches are essentially caching schemes. We cache some amount of surface information, in screen space, in order to avoid fetching or computing the same information over and over again, while applying lights one by one in traditional forward rendering.</p>

<p>Now, the &#8220;cache in screenspace&#8221; leads to disadvantages like &#8220;it&#8217;s really hard to do transparencies&#8221; - since with transparencies you do not have one point in space mapping to one pixel on screen anymore. There&#8217;s no reason why caching should be done in screen space however; lighting could also just as well be computed in texture space (like some skin rendering techniques, but they do it for a different reason), world space (voxels?), etc.</p>

<p><strong>Does &#8220;modern&#8221; forward rendering still need caching?</strong></p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2012/03/ShaderParams.png"><img class="right" src="http://aras-p.info/blog/wp-content/uploads/2012/03/ShaderParams-238x500.png"></a>
Caching information was important since in DX9 / Shader Model 3 times, it was hard to do forward rendering that could almost arbitrarily apply variable number of lights - with good efficiency - in one pass. That led to either shader combination explosion, or inefficient multipass rendering, or both. But now we have DX11, compute, structured buffers and unordered access views, so maybe we can actually do better?</p>

<p>Because at some point we will want to have BRDFs with more parameters than it is viable to store in a G-buffer (side image: this is <em>half</em> of parameters for a material). We will want many semitransparent objects. And then we&#8217;re back to square one; we can not efficiently do this in a traditional &#8220;deferred&#8221; way where we cache N numbers per pixel.</p>

<p>AMD&#8217;s Leo goes in that direction. It seems to be a blend of <a href="http://software.intel.com/en-us/articles/deferred-rendering-for-current-and-future-rendering-pipelines/">tiled deferred approaches</a> to light culling, applied to forward rendering.</p>

<p><strong>I imagine it doing something like:</strong></p>

<ol>
<li><p>Z-prepass:</p>

<ol>
<li>Render Z prepass of opaque objects to fill in depth buffer.</li>
<li>Store that away (copy into another depth buffer).</li>
<li>Continue Z prepass of transparent objects; writing to depth.</li>
<li>Now we have two Z buffers, and for any pixel we know the Z-extents of anything interesting in it (from closest transparent object up to closest opaque surface)</li>
</ol>
</li>
<li><p>Shadowmaps, as usual. Would need to keep all shadowmaps for all lights in memory, which can be a problem!</p></li>
<li><p>Light culling, very similar to what you&#8217;d do in tiled deferred case!</p>

<ol>
<li>Have all lights stored in a buffer. Light types, positions/directions/ranges/angles, colors etc.</li>
<li>From the two depth buffers above, we can compute Z ranges per pixel/tile in order to do better light culling.</li>
<li>Run a compute shader that does light culling. Could do this per pixel or per small tiles (e.g. 8x8 ). Result is buffer(s) / lists per pixel or tile, with lights that affect said pixel or tile.</li>
</ol>
</li>
<li><p>Render objects in forward rendering:</p>

<ol>
<li>Z-buffer is already pre-filled in 1.1.</li>
<li>Each shader would have to do &#8220;apply all lights that affect this pixel/tile&#8221; computation. So that would involve fetching those arbitrary light informations, looping over lights etc.</li>
<li>Otherwise, each object is free to use as many shader parameters as it wants, or use any BRDF it wants.</li>
<li>Rendering order is like usual forward rendering; batch-friendly order (since Z is prefilled already) for opaque, per-object or per-triangle back-to-front order for semitransparent objects.</li>
</ol>
</li>
<li><p><em>Profit!</em></p></li>
</ol>


<p>Now, I have hand-waved over some potentially problematic details.</p>

<p>For example, &#8220;two depth buffers&#8221; is not robust for cases where there&#8217;s <em>no</em> opaque objects in some area; we&#8217;d need to track minimum <em>and</em> maximum depths of semitransparent stuff, or accept worse light culling for those tiles. Likewise, copying the depth buffer might lose some hardware Hi-Z information, so in practice it could be better to track semitransparent depths using another approach (min/max blending of a float texture etc.).</p>

<p>4.b. bit about &#8220;let&#8217;s apply all lights&#8221; assumes there is <em>some</em> way to do that efficiently, while supporting complicated things like each light having a different cookie/gobo texture, or a different shadowmap etc. Texture arrays could almost certainly be used here, but since this just a brain dump without verification in practice, it&#8217;s hard to say how would this work.</p>

<p><strong>Update</strong>: other papers came out describing almost the same idea, with actual implementations &amp; measurements. <a href="http://aras-p.info/blog/2012/03/27/tiled-forward-shading-links/">Check them out here!</a></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Prophets and duct-tapers or: useful programmer traits]]></title>
    <link href="http://aras-p.info/blog/2011/09/09/prophets-and-duct-tapers-or-useful-programmer-traits/"/>
    <updated>2011-09-09T18:52:38+03:00</updated>
    <id>http://aras-p.info/blog/2011/09/09/prophets-and-duct-tapers-or-useful-programmer-traits</id>
    <content type="html"><![CDATA[<p>I liked Pierre&#8217;s <a href="http://www.codercorner.com/blog/?p=502">The Prophet Programmer</a> post. Go read it now.</p>

<p>Now <em>of course</em> that post is a rant. It exaggerates. It puts everything into one bit grayscale colors. There&#8217;s never one person completely like this &#8220;prophet programmer&#8221; and another like the idolized &#8220;best programmer&#8230; not afraid of anything!!1&#8221;.</p>

<p>But it does highlight at least this thing: some aspects of programmer&#8217;s behavior are either useful or not.</p>

<p>Obsessing over latest hypes, &#8220;the proper ways&#8221;, following books by the letter just by itself <em>is not useful</em>. Sure, sometimes a dash of &#8220;proper ways&#8221; or recommendations is good, but the benefits of doing that are really, really tiny. Hence it&#8217;s not worth thinking/arguing much about.</p>

<p><strong>Here&#8217;s some actually useful programmer traits</strong> instead.** I&#8217;m thinking about real actual people I&#8217;m working with here, even if I&#8217;m not telling names.</p>

<p>He <em>feels what needs to be done</em> to get the solution, in the big picture. Sometimes these are unusual ideas that probably no one is doing - because everyone has always been seeing the problem in the standard way. The solutions seem obvious once you see them, but require some sort of step function in thinking to get there. Zero iteration way of hooking up touchscreen device input to test the game is to play the game on PC, stream images into the device and stream inputs back. Least hassle free asset pipeline is when there is no &#8220;export/import asset&#8221; step. Or a more famous outside example, tablets <a href="http://aras-p.info/blog/wp-content/uploads/2011/09/tablets-before-and-after-ipad.jpeg">before and after</a> the iPad. You rarely, if ever, can do things like that by doing user surveys or improving on existing solutions; you need someone who can see through and find what&#8217;s the <em>actual</em> problem you want to solve. This guy is worth gold.</p>

<p>She can <em>cut things</em>. &#8220;Perfection is achieved, not when there is nothing more to add, but when there is nothing left to cut away&#8221;, quoth Saint-Exupéry. To be good at doing anything you (both you and your team) need to focus, which means cutting things. Let go of bad ideas and blind alleys. If your justification for doing it is &#8220;but we already spent so much time on it&#8221;, just don&#8217;t - it will only get worse. Cut features that aren&#8217;t quite ready by the deadlines. Remove old things that aren&#8217;t useful anymore. Doing that can and will make some people upset; it&#8217;s really, <em>really</em> hard to postpone or even completely abandon a thing that someone put a lot of effort into. But it needs to be done; and you need her on the team to make these hard decisions.</p>

<p>That other guy is <em>freaking fast</em>. And not in a sense of &#8220;types tons of code real fast and then sometimes it works, and two weeks after someone else has to clean it up&#8221;. No - he&#8217;s cranking out good, solid, tested, working code at incredible speeds. Got ten bugs; they are fixed by next day. Got a new feature to do; commits with everything implemented (and working!) are pushed in a few days. When he goes on vacation your burndown chart changes slope. How he does it? I don&#8217;t know. But by all means, keep onto him!</p>

<p>The other girl can figure out any <em>complex problem real fast</em>. Be it a tricky bug, unexpected behavior, really weird interaction with other systems - others could be spending hours, if not days, trying to figure out what&#8217;s going on. She, on the other hand, checks just a handful of things and goes &#8220;ha! the problem&#8217;s right there&#8221;. As if applying binary search to the whole problem space, except to everyone else the space seems unsorted and they don&#8217;t even know what they&#8217;re looking for!</p>

<p>This dude can keep <em>a ton of context in his head</em> while doing anything. How will this feature interact with dozens or even hundreds of other features; he&#8217;s able to think about all of them and majority of corner cases and get everything right in one go. Would take dozens of roundtrips between coding &amp; QA for someone else to get right. When estimating effort for new things, he can immediately list all the tricky work that will need to be done; whereas others would go &#8220;sounds easy&#8221; only to find out it&#8217;s a month of work.</p>

<p>She&#8217;s <em>not satisfied with the status quo</em>. No this isn&#8217;t good enough, she says; and let me show you where &amp; how spectacularly it breaks. And it does not matter if everyone else is doing it this way; here&#8217;s why putting that stuff into uniform grid isn&#8217;t good. A lot of times you need this extra bump to snap out of your own &#8220;this is good enough, no one will care&#8221; thoughts.</p>

<p>He&#8217;s doing a lot of <em>boring work to get others more productive</em>. There&#8217;s <em>a ton</em> of boring work on even the most exciting projects, and someone has to do it. He&#8217;s often the unsung hero, quietly working on infrastructure, build times, fixing annoyances in the tools, processes and workflows; all just so that others can be better at doing <em>exciting</em> things. You could call him a janitor or a plumber if you wish, but any place gets rotten and broken real fast without those people.</p>

<p>&#8230;and the list could go on. Unlike obsessing over irrelevant details, <strong>these make a difference</strong>. Makes your team run circles around others. Helps you solve <em>hard</em> problems, invent things, moves you forward at enormous velocity.</p>

<p>You need people with those traits and attitudes.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Fast Mobile Shaders or, I did a talk at SIGGRAPH!]]></title>
    <link href="http://aras-p.info/blog/2011/08/17/fast-mobile-shaders-or-i-did-a-talk-at-siggraph/"/>
    <updated>2011-08-17T21:22:05+03:00</updated>
    <id>http://aras-p.info/blog/2011/08/17/fast-mobile-shaders-or-i-did-a-talk-at-siggraph</id>
    <content type="html"><![CDATA[<p>Finally after many years of dreaming I made it to <a href="http://www.siggraph.org/s2011/">SIGGRAPH</a>! And not only that, I also did a talk/course with <a href="http://twitter.com/#!/__ReJ__">ReJ</a> for 1.5 hours. This was the first time Unity had real presence at SIGGRAPH and I hope we&#8217;ll be more active &amp; visible next time around.</p>

<p>Here it is, 100+ slides with notes: <a href="http://aras-p.info/texts/files/FastMobileShaders_siggraph2011.pdf"><strong>Fast Mobile Shaders</strong></a> (17MB pdf). This isn&#8217;t strictly about shaders; there&#8217;s info about mobile GPU architectures, general performance, hidden surface removal and so on. Also, graphs with logarithmic scales; can&#8217;t go wrong with that!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Testing Graphics Code, 4 years later]]></title>
    <link href="http://aras-p.info/blog/2011/06/17/testing-graphics-code-4-years-later/"/>
    <updated>2011-06-17T06:44:46+03:00</updated>
    <id>http://aras-p.info/blog/2011/06/17/testing-graphics-code-4-years-later</id>
    <content type="html"><![CDATA[<p>Almost four years ago <a href="http://aras-p.info/blog/2007/07/31/testing-graphics-code/">I wrote how we test rendering code</a> at Unity. Did it stand the test of time and more importantly, growing the company from less than 10 people to more than 100 people?</p>

<p><em>I&#8217;m happy to say it did! That&#8217;s it, move on to read the rest of the internets.</em></p>

<p>The earlier post was more focused on hardware compatibility area (differences between platforms, GPUs, driver versions, driver bugs and their workarounds etc.). In addition to that, we do regression tests on a bunch of <a href="http://blogs.unity3d.com/2010/01/12/on-web-player-regression-testing/">actual Unity made games</a>. All that is good and works, let&#8217;s talk about what tests the rendering team at Unity is using in the daily lives instead.</p>

<p><strong>Graphics Feature &amp; Regression Testing</strong></p>

<p>In daily life of a graphics programmer, you care about two things related to testing:</p>

<p><strong>1.</strong> Whether a new feature you are adding, more or less, works.
<strong>2.</strong> Whether something new you added or something you refactored broke or changed any existing features.</p>

<p>Now, &#8220;works&#8221; is a vague term. Definitions can range from equally vague</p>

<blockquote><p>Works For Me!</p></blockquote>

<p>to something like</p>

<blockquote><p>It has been battle tested on thousands of use cases, hundreds of shipped games, dozens of platforms, thousands of platform configurations and within each and every one of them there&#8217;s not a single wrong pixel, not a single wasted memory byte and not a single wasted nanosecond! <em>No kittehs were harmed either!</em></p></blockquote>

<p>In ideal world we&#8217;d only consider the latter as &#8220;works&#8221;, however that&#8217;s quite hard to achieve.</p>

<p>So instead we settle for small &#8220;functional tests&#8221;, where each feature has a small scene setup that exercises said feature (very much like talked about in <a href="http://aras-p.info/blog/2007/07/31/testing-graphics-code/">previous post</a>). It&#8217;s graphics programmer&#8217;s responsibility to add tests like that for his stuff.</p>

<p>For example, Fog handling might be tested by a couple scenes like this:</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/06/092-FogModes.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/06/092-FogModes.png" alt="" /></a>
<a href="http://aras-p.info/blog/wp-content/uploads/2011/06/017-Fog.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/06/017-Fog.png" alt="" /></a></p>

<p>Another example, tests for various corner cases of Deferred Lighting:</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/06/118-DeferredLMCases.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/06/118-DeferredLMCases.png" alt="" /></a>
<a href="http://aras-p.info/blog/wp-content/uploads/2011/06/134-DefLightShapes.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/06/134-DefLightShapes.png" alt="" /></a>
<a href="http://aras-p.info/blog/wp-content/uploads/2011/06/143-DefLargeCoords.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/06/143-DefLargeCoords.png" alt="" /></a></p>

<p>So that&#8217;s basic testing for &#8220;it works&#8221; that the graphics programmers themselves do. Beyond that, features are tested by QA and a large beta testing group, tried, profiled and optimized on real actual game projects and so on.</p>

<p>The good thing is, doing these basic tests also provides you with point 2 (did I break or change something?) automatically. If after your changes, all the graphics tests still pass, there&#8217;s a pretty good chance you did not break anything. Of course this testing is not exhaustive, but any time a regression is spotted by QA, beta testers or reported by users, you can add a new graphics test to check for that situation.</p>

<p><strong>How do we actually do it?</strong></p>

<p>We use <a href="http://www.jetbrains.com/teamcity/">TeamCity</a> for the build/test farm. It has several build machines set up as graphics test agents (unlike most other build machines, they need an actual GPU, or a iOS device connected to them, or a console devkit etc.) that run graphics test configurations for all branches automatically. Each branch has it&#8217;s graphics tests run daily, and branches with &#8220;high graphics code activity&#8221; (i.e. branches that the rendering team is actually working on) have them run more often. You can always initiate the tests manually by clicking a button of course. What you want to see at any time is this:</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/06/teamcity-gfx-tests.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/06/teamcity-gfx-tests.png" alt="" /></a></p>

<p>The basic approach is the same as <a href="http://aras-p.info/blog/2007/07/31/testing-graphics-code/">4 years ago</a>: a &#8220;game level&#8221; (&#8220;scene&#8221; in Unity speak) for each test, runs for defined number of frames, run everything at fixed timestep, take a screenshot at end of each frame. Compare each screenshot with &#8220;known good&#8221; image for that platform; any differences equals &#8220;FAIL&#8221;. On many platforms you have to allow a couple of wrong pixels because many consumer GPUs are not <em>fully</em> deterministic it seems.</p>

<p>So you have this bunch of &#8220;this is the golden truth&#8221; images for all the tests:</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/06/some-gfx-tests.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/06/some-gfx-tests-500x247.png" alt="" /></a></p>

<p>And each platform automatically tested on TeamCity has it&#8217;s own set:</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/06/gfx-test-platforms.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/06/gfx-test-platforms.png" alt="" /></a></p>

<p>Since the &#8220;test controller&#8221; can run on a different device than actual tests (the case for iOS, Xbox 360 etc.), the test executable opens a socket connection to transfer the screenshots. The test controller is a relatively simple C# application that listens on a socket, fetches the screenshots and compares them with the template ones. The result of it is output that TeamCity can understand; along with &#8220;build artifacts&#8221; that consist of failed tests (for each failed test: expected image, failed image, difference image with increased contrast).</p>

<p>That&#8217;s pretty much it! And of course, automated tests are nice and all, but that should not get too much into the way of actual <a href="http://programming-motherfucker.com/">programming manifesto</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Notes on Native Client & Pepper Plugin API]]></title>
    <link href="http://aras-p.info/blog/2011/06/02/notes-on-native-client-pepper-plugin-api/"/>
    <updated>2011-06-02T10:24:48+03:00</updated>
    <id>http://aras-p.info/blog/2011/06/02/notes-on-native-client-pepper-plugin-api</id>
    <content type="html"><![CDATA[<p>Google&#8217;s <a href="http://code.google.com/p/nativeclient/">Native Client</a> (NaCl) is a brilliant idea. <a href="http://en.wikipedia.org/wiki/Wikipedia:Too_long;_didn%27t_read">TL;DR</a>: it allows <em>native</em> code to be run <em>securely</em> in the browser.</p>

<p><strong>But is it secure?</strong></p>

<p><em>&#8220;Bububut, waitaminnit! Native code is not secure by definition&#8221;</em> you say. Turns out, that isn&#8217;t necessarily true. With a specially massaged compiler, some runtime support and careful native code validation it is possible to ensure native code, when ran in the browser, can&#8217;t cause harm to user&#8217;s machine. I suggest taking a look at the original <a href="http://src.chromium.org/viewvc/native_client/data/docs_tarball/nacl/googleclient/native_client/documentation/nacl_paper.pdf">NaCl for x86 paper</a> and more recently, how similar techniques would apply to <a href="http://www.chromium.org/nativeclient/reference/arm-overview">ARM CPUs</a>.</p>

<p><strong>But what can you do with it?</strong></p>

<p>So that&#8217;s great. It means it is possible to take C/C++ code, compile it with NaCl SDK (a gcc derived toolchain) and have it run in the browser. We can make a loop in C that multiplies a ton of floating point numbers, and it will run at native speed. That&#8217;s wonderful, except you can&#8217;t really do much interesting stuff with your own C code in isolation&#8230;</p>

<p>You need access to the hardware and/or OS. As game developers, we need pixels to appear on the screen. Preferably lots of them, with the help of something like a <a href="http://en.wikipedia.org/wiki/Graphics_processing_unit">GPU</a>. Audio waves to come out of the speakers. Mouse moves and keyboard presses to translate to some fancy actions. Post a high score to the internets. And so on.</p>

<p>NaCl surely can&#8217;t just allow my C code to call <code>Direct3DCreate9</code> and run with it, while keeping the promise of &#8220;it&#8217;s secure&#8221;? Or a more extreme case, <code>FILE* f = fopen("/etc/passwd", "rt");</code>?!</p>

<p>And that&#8217;s true; NaCl does not allow you to use completely arbitrary APIs. It has it&#8217;s own set of APIs to interface with &#8220;the system&#8221;.</p>

<p><strong>Ok, how do I interface with the system?</strong></p>

<p>&#8230;and that&#8217;s where the current state of NaCl gets a bit confusing.</p>

<p>Initially Google developed an improved &#8220;browser plugin model&#8221; and called it Pepper. This Pepper thing would then take care of actually putting your code <em>into the browser</em>. Starting it up, tearing it down, controlling repaints, processing events and so on. But then apparently they realized that building on top of a decade-old Netscape plugin API (<a href="http://en.wikipedia.org/wiki/NPAPI">NPAPI</a>) isn&#8217;t going to really work, so they developed Pepper2 or PPAPI (Pepper Plugin API) which ditches NPAPI completely. To write a native client plugin, you only interface with PPAPI.</p>

<p>So some of the pages on the internets reference the &#8220;old API&#8221; (which is gone as far as I can see), and some others reference the new one. It does not help that Native Client&#8217;s own documentation are scattered around in <a href="http://www.chromium.org/nativeclient">Chromium</a>, <a href="http://code.google.com/p/nativeclient/">NaCl</a>, <a href="http://code.google.com/p/nativeclient-sdk/">NaCl SDK</a> and <a href="http://code.google.com/p/ppapi/">PPAPI</a> sites. Seriously, <em>it&#8217;s a mess</em>, with seemingly no high level, up to date &#8220;introduction&#8221; page that tells what exactly PPAPI can and can&#8217;t do. <em>Edit</em>: I&#8217;m told that the definitive entry point to NaCl right now is this page: <a href="http://code.google.com/chrome/nativeclient/"><strong>http://code.google.com/chrome/nativeclient/</strong></a> which clears up some mess.</p>

<p><strong>Here&#8217;s what I think it can do</strong></p>

<p><em>Note: At <a href="http://unity3d.com/">work</a> we have an in-progress Unity NaCl port using this PPAPI. However, I am not working on it, so my knowledge may or may not be true. Take everything with a grain of NaCl ;)</em></p>

<p>Most of things below found by poking around at <a href="http://src.chromium.org/viewvc/chrome/trunk/src/ppapi/">PPAPI source tree</a>, and by looking into Unity&#8217;s NaCl platform dependent bits.</p>

<p><em><strong>Graphics</strong></em></p>

<p>PPAPI provides an OpenGL ES 2.0 implementation for your 3D needs. You need to setup the context and initial surfaces via PPAPI (<a href="http://src.chromium.org/viewvc/chrome/trunk/src/ppapi/cpp/dev/context_3d_dev.h?view=markup">ppapi/cpp/dev/context_3d_dev.h</a>, <a href="http://src.chromium.org/viewvc/chrome/trunk/src/ppapi/cpp/dev/surface_3d_dev.h?view=markup">ppapi/cpp/dev/surface_3d_dev.h</a>) - similar to what you&#8217;d use EGL on other platforms for - and beyond that you just include <code>GLES2/gl2.h</code>, <code>GLES2/gl2ext.h</code> and call ye olde GLES2.0 functions.</p>

<p>Behind the scenes, all your GLES2.0 calls will be put into a <a href="http://src.chromium.org/viewvc/chrome/trunk/src/gpu/command_buffer/">command buffer</a> and transferred to actual &#8220;3D server&#8221; process for consuming them. Chrome splits up itself into various processes like that for security reasons &#8211; so that each process has the minimum set of privileges, and a crash or a security exploit in one of them can&#8217;t easily transfer over to other parts of the browser.</p>

<p><em><strong>Audio</strong></em></p>

<p>For audio needs, PPAPI provides a simple buffer based API in <a href="http://src.chromium.org/viewvc/chrome/trunk/src/ppapi/cpp/audio_config.h?view=markup">ppapi/cpp/audio_config.h</a> and <a href="http://src.chromium.org/viewvc/chrome/trunk/src/ppapi/cpp/audio.h?view=markup">ppapi/cpp/audio.h</a>. Your own callback will be called whenever audio buffer needs to be filled with new samples. That means you do all sound mixing yourself and just fill in the final buffer.</p>

<p><em><strong>Input</strong></em></p>

<p>Your plugin instance (subclass of <code>pp::Instance</code>) will get input events via HandleInputEvent virtual function override. Each event is a simple <a href="http://src.chromium.org/viewvc/chrome/trunk/src/ppapi/c/pp_input_event.h?view=markup">PPInputEvent struct</a> and can represent keyboard &amp; mouse. No support for gamepads or touch input so far, it seems.</p>

<p><em><strong>Other stuff</strong></em></p>

<p>Doing WWW requests is possible via <a href="http://src.chromium.org/viewvc/chrome/trunk/src/ppapi/cpp/url_loader.h?view=markup">ppapi/cpp/url_loader.h</a> and friends.</p>

<p>Timer &amp; time queries via <a href="http://src.chromium.org/viewvc/chrome/trunk/src/ppapi/cpp/core.h?view=markup">ppapi/cpp/core.h</a> (e.g. <code>pp::Module::Get()-&gt;core()-&gt;CallOnMainThread(...)</code>).</p>

<p>And, well, a bunch of other stuff is there, like ability to rasterize blocks of text into bitmaps, pop up file selection dialogs, use the browser to decode video streams and so on. Everything - or almost everything - is there to make it possible to do games on it.</p>

<p><strong>Summary</strong></p>

<p>Like <a href="http://chadaustin.me/2011/01/in-defense-of-language-democracy/">Chad says</a>, it would be good to end <em>&#8220;thou shalt only use Javascript&#8221;</em> on the web. Javascript is a very nice language - especially considering how it came into existence - but <em>forcing</em> it on everyone is quite silly. And no matter how hard V8/JägerMonkey/Nitro folks are trying, it is very, very hard to <a href="http://chadaustin.me/2011/01/digging-into-javascript-performance/">beat performance</a> of a simple, static, compiled language (like C) that has direct access to memory and the programmer is in almost full control of both the code flow and the memory layout. Steve rightly <a href="http://twitter.com/#!/stevestreeting/status/76216985888882688">points out</a> that even if for some tasks a super-optimized Javascript engine will approach the speed of C, it will burn much more energy to do so &#8211; a very important aspect in the increasingly mobile world.</p>

<p>Native Client does give some hope that there will be a way to run native code, at native speeds, in the browser, without compromising on security. Let it happen.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A way to visualize mip levels]]></title>
    <link href="http://aras-p.info/blog/2011/05/03/a-way-to-visualize-mip-levels/"/>
    <updated>2011-05-03T18:41:59+03:00</updated>
    <id>http://aras-p.info/blog/2011/05/03/a-way-to-visualize-mip-levels</id>
    <content type="html"><![CDATA[<p>Recently a <a href="http://twitter.com/#!/aras_p/status/63538509952200705">discussion</a> on Twitter about folks using 2048 textures on a pair of dice spawned this post. How do artists know if the textures are too high or too low resolution? Here&#8217;s what we do in Unity, which may or may not work elsewhere.</p>

<p>When you have a game scene that, for example, looks like this:</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/05/BootcampNormal.jpg"><img src="http://aras-p.info/blog/wp-content/uploads/2011/05/BootcampNormal-500x283.jpg" alt="" /></a></p>

<p>We provide a &#8220;mipmaps&#8221; visualization mode that renders it like this:</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/05/BootcampMips.jpg"><img src="http://aras-p.info/blog/wp-content/uploads/2011/05/BootcampMips-500x283.jpg" alt="" /></a></p>

<p>Original texture colors mean it&#8217;s a perfect match (1:1 texels to pixels ratio); more red = too much texture detail; more blue = too little texture detail.</p>

<p><em>That&#8217;s it, end of story, move along!</em></p>

<p>Now of course it&#8217;s not that simple. You can just go and resize all textures that were used on the red stuff. The player might walk over to those red objects, and <em>then</em> they would need more detail!</p>

<p>Also, the amount of texture detail needed very much depends on the screen resolution the game will be running at:</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/05/PlatformerSizes.jpg"><img src="http://aras-p.info/blog/wp-content/uploads/2011/05/PlatformerSizes-500x190.jpg" alt="" /></a></p>

<p>Still, even with varying resolution sizes and the fact that the same objects in 3D can be near &amp; far from the viewer, this view can answer the question of &#8220;does something have a too high/too low texture detail?&#8221;, mostly by looking at colorization mismatch between nearby objects.</p>

<p>In the picture above, the railings have too little texture detail (blue), while the lamp posts have too much (red). The little extruded things on the floating pads have too much detail as well.</p>

<p>The image below reveals that floor and ceiling have mismatching texture densities: floor has too little, while ceiling has too much. Probably should be the other way around, in a platform you&#8217;d more often be looking at the floor.</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/05/FloorCeiling1.jpg"><img src="http://aras-p.info/blog/wp-content/uploads/2011/05/FloorCeiling1-500x318.jpg" alt="" /></a></p>

<p><strong>How to do this?</strong></p>

<p>In the mipmap view shader, we display the original texture mixed with a special &#8220;colored mip levels&#8221; texture. The regular texture is sampled with original UVs, while the color coded texture is sampled with more dense ones, to allow visualization of &#8220;too little texture detail&#8221;. In shader code <em>(HLSL, shader model 2.0 compatible)</em>:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>struct v2f {
</span><span class='line'>    float4 pos : SV_POSITION;
</span><span class='line'>    float2 uv : TEXCOORD0;
</span><span class='line'>    float2 mipuv : TEXCOORD1;
</span><span class='line'>};
</span><span class='line'>float2 mainTextureSize;
</span><span class='line'>v2f vert (float4 vertex : POSITION, float2 uv : TEXCOORD0)
</span><span class='line'>{
</span><span class='line'>    v2f o;
</span><span class='line'>    o.pos = mul (matrix_mvp, vertex);
</span><span class='line'>    o.uv = uv;
</span><span class='line'>    o.mipuv = uv * mainTextureSize / 8.0;
</span><span class='line'>    return o;
</span><span class='line'>}
</span><span class='line'>half4 frag (v2f i) : COLOR0
</span><span class='line'>{
</span><span class='line'>    half4 col = tex2D (mainTexture, i.uv);
</span><span class='line'>    half4 mip = tex2D (mipColorsTexture, i.mipuv);
</span><span class='line'>    half4 res;
</span><span class='line'>    res.rgb = lerp (col.rgb, mip.rgb, mip.a);
</span><span class='line'>    res.a = col.a;
</span><span class='line'>    return res;    
</span><span class='line'>}</span></code></pre></td></tr></table></div></figure>


<p>The <code>mainTextureSize</code> above is the pixel size of the main texture, for example (256,256). Division by eight might seem a bit weird, but it really isn&#8217;t!</p>

<p>To show the colored mip levels, we need to create mipColorsTexture that has different colors in each mip level.</p>

<p>Let&#8217;s say we would create a 32x32 size texture for this, and the largest mip level would be used to display &#8220;ideal texel to pixel density&#8221;. If the original texture was 256 pixels in size and we want to sample a 32 pixels texture at exactly the same texel density as the original one, we have to use more dense UVs: <code>newUV = uv * 256 / 32</code> or in a more generic way, <code>newUV = uv * textureSize / mipTextureSize</code>.</p>

<p>Why there&#8217;s 8.0 in the shader then, if we create the mip texture at 32x32 size? That&#8217;s because we don&#8217;t want the largest mip level to indicate &#8220;ideal texel to pixel&#8221; density. We also want a way to visualize &#8220;not enough texel density&#8221;. So we push the ideal mip level two levels down, which means it&#8217;s four times UV difference. That&#8217;s how 32 becomes 8 in the shader.</p>

<p>The actual colors we use for this 32x32 mipmaps visualization texture are, in RGBA: (0.0,0.0,1.0,0.8); (0.0,0.5,1.0,0.4); (1.0,1.0,1.0,0.0); (1.0,0.7,0.0,0.2); (1.0,0.3,0.0,0.6); (1.0,0.0,0.0,0.8). Alpha channel controls how much to interpolate between the original color and the tinted color. Our 3rd mip level has zero alpha so it displays unmodified color.</p>

<p><em>Now, step 2 is somehow forcing artists to actually use this ;)</em></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Mercurial/Kiln experience so far]]></title>
    <link href="http://aras-p.info/blog/2011/04/18/mercurialkiln-experience-so-far/"/>
    <updated>2011-04-18T09:14:33+03:00</updated>
    <id>http://aras-p.info/blog/2011/04/18/mercurialkiln-experience-so-far</id>
    <content type="html"><![CDATA[<p>At <a href="http://unity3d.com/">work</a> we switched to <a href="http://mercurial.selenic.com/">Mercurial</a> almost two months ago. Like <a href="http://altdevblogaday.org/2011/03/09/its-time-to-stop-using-subversion/">Richard says</a>, it was time to stop using Subversion. Here are my impressions so far.</p>

<p>_Preemptive warning: I&#8217;ve only ever used CVS, SourceSafe, Subversion, git and Mercurial as source contro systems (never used Perforce). I never really used a code review tool before Kiln. Everything below might be non-issues in other tools/systems, or not suitable for different setups/workflows!
_</p>

<p><strong>The Story</strong></p>

<p>At Unity we used <a href="http://subversion.apache.org/">Subversion</a> for source code versioning as long as I remember. svn revision 1 &#8211; an import from CVS &#8211; happened in 2005. We don&#8217;t talk about CVS. Nor about SourceSafe. Subversion was fine while the number of developers was small; we had a saying that CVS scales up to 5 people, and experimentally found out that svn scales up to about 50.</p>

<p>Since merging branches in subversion does not <em>really</em> work well, everyone was mostly working on one trunk, <em>carefully</em>. We would do an occasional branch for &#8220;this will surely break everything&#8221; features; and would branch off trunk sometime before each Unity release, but that&#8217;s about it. Having something like 50 people and 10 platforms on a single branch in version control does get a bit uneasy.</p>

<p>So we looked at various options, like <a href="http://git-scm.com/">git</a>, <a href="http://mercurial.selenic.com/">Mercurial</a>, <a href="http://www.perforce.com/">Perforce</a> and so on. I don&#8217;t know why exactly we ended up with Mercurial (someone made a decision I guess&#8230;). It <em>felt</em> like distributed versioning systems are <em>teh future</em> and unlike most game developers we don&#8217;t need to version hundreds of gigabytes of binary assets (hence no big need for Perforce).</p>

<p>So while some people were at GDC, we did a big switch to several things at once: 1) replace Subversion with Mercurial, 2) replace &#8220;everyone works on the same trunk&#8221; workflow with &#8220;teams work on their own topic branches&#8221;, 3) introduce a bit more formal code reviews via <a href="http://www.fogcreek.com/kiln/">Kiln</a>.</p>

<p>In hindsight, maybe switching three things at once wasn&#8217;t the brightest idea; there&#8217;s only so much change a person can absorb per unit of time. On the other hand, everyone experienced a large initial shock but now that the debris is setting down they just continue working with no big shocks predicted in the near future.</p>

<p><strong>Our Setup</strong></p>

<p>We use Fogcreek&#8217;s Kiln and host it on <a href="http://www.fogcreek.com/kiln/for-your-server.html">our own servers</a>. This is mostly for legal reasons I think (in our source code we have 3rd party bits which are under strict NDAs). Advantage of hosting ourselves is that we&#8217;re under complete control. Disadvantage is that we have to do some work; and we only get Kiln updates each couple of months (so for example everyone who lets Fogcreek host Kiln is on Kiln 2.4.x right now, while we&#8217;re still on 2.3.x).</p>

<p>Our source tree is about 12000 files amounting to about 600MB. Mercurial&#8217;s history (60000 revisions imported from svn) adds another 200MB. Additionally, we pull almost 1GB of binary files (see below for binary file versioning) into the source tree.</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/04/hg-branches.png"><img class="right" src="http://aras-p.info/blog/wp-content/uploads/2011/04/hg-branches-150x150.png"></a>Each &#8220;team&#8221; (core, editor, graphics, ios, android, &#8230;) has it&#8217;s own &#8220;branch&#8221; (actually, a separate repository clone) of the codebase, and merge back and forth between &#8220;trunk&#8221; repository. The trunk is supposed to be stable and shippable at almost any time (in theory&#8230; :)); unfinished, unreviewed code or code that has any failing tests can&#8217;t be pushed into trunk. Additionally, long-lasting features get their own &#8220;feature branches&#8221; (again, actually full clones of the repository). So right now we have more than 40 of those team+feature branches.</p>

<p>We have almost 50 developers committing to the source tree. Additionally, there is a build farm of 30 machines building most of those branches and running automated test suites. All this <em>does</em> put some pressure on the Kiln server ;) Everything below describes usage of Kiln 2.3.x with Mercurial 1.7.x; with more recent versions anything might have changed.</p>

<p><strong>Mercurial, or: I Have Two Heads!</strong></p>

<p>Probably the hardest thing to grok is the whole centralized-to-distributed versioning transition. Not everyone has github as their start page yet, and DVCS is actually more complex than a simple centralized model that Subversion has.</p>

<p>Things like this:</p>

<blockquote><p>OMG it says I have two heads now, what do I do?!</p></blockquote>

<p>just do not happen in centralized systems. <em>It&#8217;s not easy for a developer to accept he has two heads now, either. Or where this extra head came from&#8230;</em></p>

<p>And the benefits of distributed source control system are not immediately obvious to someone who&#8217;s never used one. The initial reaction is that suddenly everything got more complex for no good reason. Compare operations that you would use daily:</p>

<ul>
<li><p>Subversion: update, commit.</p>

<ul>
<li>Since merges don&#8217;t really work: branch, switch &amp; merge are rarely used by mere mortals.</li>
</ul>
</li>
<li><p>Mercurial: pull, update or merge, commit, push.</p>

<ul>
<li><p>And you might find you have two heads now!</p></li>
<li><p>You should also see their faces when you go &#8220;well, let me tell you about rebase&#8230;&#8221;. You might just as well explain everything with <a href="http://tartley.com/?p=1267">easy to understand spatial analogies</a> ;)</p></li>
</ul>
</li>
</ul>


<p>Thankfully, there&#8217;s this thing called the intertubes, which often has <a href="http://hginit.com/">helpful tutorials</a>.</p>

<p>Myself, I think <em>maybe</em> switching to git would have been a smaller overall shock. Mercurial is easier to get into, but it kind of pretends to work like ye olde versioning system, while underneath it is very different. Git, on the other hand, does not even try to look similar; it says &#8220;I&#8217;ll fuck with your brain&#8221; immediately after initial &#8220;hi how are you&#8221;. So it&#8217;s a larger initial shock, but maybe that <em>forces</em> people to get into this different mindset faster.</p>

<p><strong>Versioning large binary files</strong></p>

<p>Even if we <em>mostly</em> version only the code, there are occasional binaries. In our case it&#8217;s mostly 3rd party SDKs that are linked into Unity. For example, PhysX, Mono, FMOD, D3DX, Cg etc. We do have the source code for most of them, but we don&#8217;t need each developer to have 30000 files of Mono&#8217;s source code for example. So we build them separately, and version the prebuilt headers/libraries/DLLs in the regular source tree. Some of those prebuilt things can get quite large though (think couple hundred megabytes).</p>

<p>Most distributed version control systems (including git and mercurial) have trouble with this. <em>Every</em> version of <em>every</em> file is stored in your own local <del>checkout</del>clone. Try having 50 versions of whole Mono build in there and you&#8217;ll wonder where the precious SSD space on your laptop did go!</p>

<p>Luckily, Kiln has a solution for this: <a href="http://kiln.stackexchange.com/questions/1873">kbfiles</a> extension. For each file marked as &#8220;large binary file&#8221;, only it&#8217;s &#8220;stand in&#8221; SHA1 hash is versioned, and the file itself is fetched from a central server into your local machine on demand. Think of it as a centralized versioning model for those special binary files. kbfiles itself is based on <a href="http://mercurial.selenic.com/wiki/BfilesExtension">bfiles extension</a>, with a tighter integration into Mercurial.</p>

<p>So the good news, with Kiln large binary files are handled easy and with no pain. You can globally set &#8220;large size&#8221; threshold, filename patterns etc. that are turned into &#8220;big files&#8221; automatically; or manually indicate &#8220;big file&#8221; when adding new files. And then continue using Mercurial as usual.</p>

<p>The bad news, however, is that kbfiles still has occasional bugs. Of course they will be fixed eventually, but for example right now <a href="http://blog.bitquabit.com/2008/11/25/rebasing-mercurial/">rebasing</a> with an incoming bigfiles commit will result in the wrong bigfile version in the end. Or, presence of kbfiles extension makes various Mercurial operations (like hg status) be <em>much</em> <a href="http://kiln.stackexchange.com/questions/3319">slower than usual</a>.</p>

<p><strong>Kiln as Web Interface</strong></p>

<p>Kiln itself is the server hosting Mercurial repositories, a web interface to view/admin them, and a code review tool. It&#8217;s fairly nice and does all the standard stuff, like show overview of all activity happening in a group of repositories:</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/04/kiln-overview.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/04/kiln-overview-500x288.png" alt="" /></a></p>

<p>And shows the overview of any particular repository:</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/04/kiln-repo.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/04/kiln-repo-500x279.png" alt="" /></a></p>

<p>And of course diff view of any particular commit:</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/04/kiln-diff.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/04/kiln-diff-500x173.png" alt="" /></a></p>

<p>My largest complaints about Kiln&#8217;s web interface are: 1) speed and 2) merge spiderwebs.</p>

<p><strong><em>Speed</em></strong>: like oh so many modern fancy-web systems, Kiln sometimes feels sluggish. Sometimes, in a time taken for Kiln to display a diff, Crysis 2 <em>would have rendered New York fifty times</em>. We did various things to boost up our server&#8217;s <em>oomph</em>, but it still does not feel fast enough. Maybe we don&#8217;t know how to setup our servers right; or maybe Kiln is actually quite slow; or maybe our repository size + branch count + number of people hitting it are exceeding whatever limits Kiln was designed for. That said, this is not unique of Kiln, <em>lots</em> of web systems are slow for sometimes no good reasons. If you are a web developer, however, keep this in mind: latency of any user operation is super important.</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/04/kiln-merge-spiderweb.png"><img class="right" src="http://aras-p.info/blog/wp-content/uploads/2011/04/kiln-merge-spiderweb-150x150.png"></a><strong><em>Merge spiderwebs</em></strong>: distributed version control makes merges reliable and easy. However, merges happen all the time and can make it hard to see what was <em>actually</em> going on in the code. You can&#8217;t see the actual changes through the merge spiderwebs.</p>

<p>The change history is littered with &#8220;merge&#8221;, &#8220;merge remote repo&#8221;, &#8220;merge again&#8221; commits. The branch graph goes crazy and starts taking half of the page width. Not good! Now of course, this is where <a href="http://blog.bitquabit.com/2008/11/25/rebasing-mercurial/">rebasing</a> would help, however right now we&#8217;re not very keen on using it because of Kiln&#8217;s bigfiles bug mentioned above.</p>

<p><strong>Kiln as Code Review Tool</strong></p>

<p>Reviewing code is fairly easy: there&#8217;s a Review button that shows up when hovering over any commit. Each commit also shows how many reviews it has pending or accepted. So you just click on something, and voilà, you can request a code review:</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/04/kiln-reviewrequest.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/04/kiln-reviewrequest-500x230.png" alt="" /></a></p>

<p>Within each review you see the diffs, send comments back and forth between people, and highlight code snippets to be attached with each comment:</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/04/kiln-review.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/04/kiln-review-500x332.png" alt="" /></a></p>

<p>In Kiln 2.3.x (which is what we use at the moment) the reviews still have a sort of &#8220;unfinished&#8221; feeling. For example, if you want multiple people to review a change, Kiln actually creates multiple reviews that are only very loosely coupled. The good news is that in Kiln 2.4 they have <a href="http://blog.fogcreek.com/rethinking-reviews/">improved this</a>, and I&#8217;m quite sure more improvements will come in the future.</p>

<p>Another option that I&#8217;m missing right now: in the repository views, filter out all approved commits. As an occasional &#8220;merge master&#8221;, I need to see if my big merge had any unreviewed or pending-review commits &#8211; something that&#8217;s quite hard to see with a merge-heavy history.</p>

<p><strong>Summary</strong></p>

<p>I&#8217;m quite happy with how switch to Mercurial + Kiln turned out to be so far. With each team working on their own repository, it does feel like we&#8217;re much less stepping on each other&#8217;s toes. That said, we haven&#8217;t shipped any Unity release from Mercurial yet; doing that will be a future exercise.</p>

<p><a href="http://www.fogcreek.com/kiln/">Kiln</a> is promising. It has some very good ideas (integrated code reviews &amp; versioning of big files in Mercurial), but it still has quite a lot of rough edges. I&#8217;m not totally happy with the web side performance of it either. That said, Fogcreek&#8217;s support for us has been fantastic; we got some bugfixes in the matter of days and they&#8217;ve been really helpful with setup/workflow/optimization issues. So it seems like it has a good future. Fogcreek guys, if you&#8217;re reading this: <a href="http://farm1.static.flickr.com/225/524768428_e20c722cc0.jpg">keep up wrk</a>!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Stories of Universities]]></title>
    <link href="http://aras-p.info/blog/2011/04/01/stories-of-universities/"/>
    <updated>2011-04-01T20:55:26+03:00</updated>
    <id>http://aras-p.info/blog/2011/04/01/stories-of-universities</id>
    <content type="html"><![CDATA[<p>I was doing a talk and a Q&amp;A session at a local university. Unaware of the consequences, one guy asked about the usefulness of the programming courses they have in real work&#8230;</p>

<p>Oh boy. Do you really want to go there?</p>

<blockquote><p>Now before I go ranting full steam, let me tell that there were really good courses and really bright teachers at my (otherwise unspectacular) university. Most of the math, physics and related fundamental sciences courses were good &amp; taught by people who know their stuff. Even some of the computer science / programming courses were good!</p></blockquote>

<p>With that aside, let&#8217;s bet back to ranting.</p>

<p><strong>What is OOP?</strong></p>

<p>Somehow conversation drifted to the topics of code design, architecture and whatnot. I asked the audience, for example, what do they think are the benefits of object oriented programming (OOP)? The answers were the following:</p>

<ul>
<li><p>Mumble mumble&#8230; weeelll&#8230; something something mumble. This was the majority&#8217;s opinion.</p></li>
<li><p>OOP makes it very easy for a new guy to start at work, because everything nicely separated and he can just work on this one file without knowing anything else.</p></li>
<li><p>Without OOP there&#8217;s no way to separate things out; everything becomes a mess.</p></li>
<li><p>OOP uses classes, and they are nicer than not using classes. Because a class lets you&#8230; uhm&#8230; well I don&#8217;t know, but classes are nicer than no classes. I think it had something to do with something being in separate files. Or maybe in one file. I don&#8217;t actually know&#8230;</p></li>
<li><p><em>I forget if there was anything else really.</em></p></li>
</ul>


<p>Let me tell you how easy it is for a guy to start at work. You come to new place all inspired and excited. You&#8217;re being put into some unholy codebase that grew in a chaotic way over last N years and being assigned to do some random feature or fix some bugs. When you encounter anything smelly in the codebase (this happens fairly often), the answer to &#8220;WTF is this?&#8221; is most often &#8220;it came from the past, yeah, we don&#8217;t like it either&#8221; or &#8220;I dunno, this guy who left last year wrote it&#8221; or &#8220;yeah, I wrote it but it was ages ago, I don&#8217;t remember anything about it&#8230; wow! this is idiotic code indeed! just be careful, touching it might break everything&#8221;. All this is totally independent of whether the codebase used OOP or not.</p>

<p>I am exaggerating of course; the codebase doesn&#8217;t have to be that bad. But still; whether it&#8217;s good or not, or whether it&#8217;s easy for a new guy to start there is really not related to it being OOP.</p>

<p>Interesting!</p>

<p>Clearly they have no frigging clue what OOP is, besides of whatever they&#8217;ve been told by the teacher. And the teacher in turn knows about OOP based on what he read in one or two books. And the author of the books&#8230; well, we don&#8217;t know; depends on the book I guess. But this is at least a second-order disconnect from reality, if not more!</p>

<p>Why is that?</p>

<p>I guess part of the problem is teachers having no real actual work experience except by reading books. This can work for math. For a lot of programming courses&#8230; not so much. Another part is students learning in a vacuum, trying to <em>kind of</em> get what the lectures are about and pass the tests.</p>

<p>In both cases it&#8217;s totally separated from doing some real actual work and trying to apply what you&#8217;re trying to learn. Which leads to some funny things like&#8230;</p>

<p><strong>How are floating point numbers stored?</strong></p>

<p>I saw this about 11 years ago in one lecture of a C++ course. The teacher quickly explained how various types are stored in memory. He got over the integer types without trouble and started explaining floats.</p>

<blockquote><p>So there&#8217;s one bit for the sign. Then come the digits before the decimal point. Since there are 10 possible choices for each digit, you need four bits of memory for each digit. Then comes one bit for the decimal point. After the decimal point, again you have four bits per digit. Done!</p></blockquote>

<p>ORLY? This was awesome, especially trying to imagine how to store the decimal point.</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/04/pifloat.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/04/pifloat.png" alt="" /></a></p>

<p>See that decimal digit bit, haha! <em>You see, it&#8217;s one bit and you can&#8217;t&#8230; what do you mean you don&#8217;t get it? And not only that; this needs variable length and&#8230; really? You&#8217;re going to a party instead?</em> I wasn&#8217;t very popular.</p>

<p>Funny or not, this is not exactly telling a correct story on how floats are stored in memory on 101% of the architectures you&#8217;d ever care about.</p>

<p>I could tell a ton of other examples of little disconnects with reality, which I think are caused by not ever having to put your knowledge into practice.</p>

<p><strong>Where do we go from here?</strong></p>

<p>Now of course, the university I went to is not something that would be considered &#8220;good&#8221; by world standards. I went to several lectures by <a href="http://graphics.ucsd.edu/~henrik/">Henrik Wann Jensen</a> at DTU at that was like night and day! But how many of these not-too-good-only-passable universities are around the world? I&#8217;d imagine certainly more than one, and certainly less than the number of MITs, Stanfords et al combined.</p>

<p>As a student, I <em>somehow</em> figured I should take a lot of things with a grain of <del>salt</del> doubt. And in a lot of cases, trying to do something for real trumps lab work / tests / exams in how much you&#8217;ll be able to learn. Go make a techdemo, a small game, play around with some techniques, try to implement that clever sounding paper from siggraph and observe it burst in flames, team up with friends while doing any of the above. <a href="http://www.youtube.com/watch?v=u6ALySsPXt0">Do it</a>!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Mobile graphics API wishlist: some features]]></title>
    <link href="http://aras-p.info/blog/2011/03/19/mobile-graphics-api-wishlist-some-features/"/>
    <updated>2011-03-19T15:50:15+02:00</updated>
    <id>http://aras-p.info/blog/2011/03/19/mobile-graphics-api-wishlist-some-features</id>
    <content type="html"><![CDATA[<p>In my <a href="http://aras-p.info/blog/2011/03/04/mobile-graphics-api-wishlist-performance/">previous post</a> I talked about things I&#8217;d want from OpenGL ES 2.0 in the performance area. Now it&#8217;s time to look at what extra features it might expose with an extension here or there.</p>

<p><em>Note that I’m focusing on, in my limited understanding, low-hanging fruits. The features I want already exist in the current GPUs or platforms; or could be easily made available. Of course more radical new architectures would bring more &amp; fancier features, but that&#8217;s a topic for another story.</em></p>

<p><strong>Programmable blending</strong></p>

<p>At least two out of three big current mobile GPU families (PVR SGX, Adreno, Tegra 2) support programmable blending in the hardware. Maybe all of them do this and I just don&#8217;t have enough data. By &#8220;support it in the hardware&#8221; I mean either: 1) the GPU has no blending hardware, the drivers add &#8220;read current pixel &amp; blend&#8221; instructions to the shaders or 2) has blending hardware for commonly used modes, but fancier modes use shader patching with no severe performance penalties.</p>

<p>Programmable blending is useful for various things; from deferred-style decals (blending normals is hard in fixed function!) to fancier Photoshop-like blend modes to potentially faster single-pixel image postprocessing effects (like color correction).</p>

<p>Currently only NVIDIA exposes this capability via <a href="http://developer.download.nvidia.com/tegra/docs/tegra_gles2_development.pdf">NV_shader_framebuffer_fetch</a> extension.</p>

<p><em>Suggestion</em>: expose it on other hardware that can do this! It&#8217;s fine to not handle hard edge cases (for example, what happens when multisampling is used?), we can live with the limitations.</p>

<p><strong>Direct, fast access to frame buffer on the CPU</strong></p>

<p>Most (all?) mobile platforms use unified memory approach, where there&#8217;s no physical distinction between &#8220;system memory&#8221; and &#8220;video memory&#8221;. Some of those platforms are slightly unbalanced, e.g. a strong GPU coupled with a weak CPU or vice versa. More and more of those systems will have multicore CPUs. It might make sense to do similar approaches that PS3 guys are doing these days - offload some of the GPU work to the CPU(s).</p>

<p>Image processing, deferred lighting and similar things could be done more efficiently on a general purpose CPU, where you aren&#8217;t limited to &#8220;one pixel at a time&#8221; model of current mobile GPUs.</p>

<p><em>Suggestion</em>: can haz get a pointer to framebuffer memory perhaps? Of course this is grossly oversimplifying all the synchronization &amp; security issues, but <em>something</em> should be possible to do in order to exploit the unified memory model. Right now it just sits there largely unused, with GLES2.0 still pretending CPU is talking to a GPU over a ten meter high concrete wall.</p>

<p><strong>Expose Tile Based GPU capabilities</strong></p>

<p>PowerVR GPUs found in all iOS and some Android devices are so called &#8220;tile based&#8221; architectures. So is, to some extent, Qualcomm Adreno family.</p>

<p>Currently this capability is mostly sitting behind a black box. On PowerVR GPUs the programmer does know that &#8220;overdraw of opaque objects does not matter&#8221;, or that &#8220;alpha testing is really slow&#8221; but that&#8217;s about it. There&#8217;s no control over the whole rendering process, even if some of the things could benefit from having more control over the whole tiling thing.</p>

<p>Take, for example, deferred lighting/shading. The cool folks are doing it tile-based already on <a href="http://www.slideshare.net/DICEStudio/directx-11-rendering-in-battlefield-3?from=ss_embed">DirectX 11</a> or <a href="http://www.slideshare.net/DICEStudio/spubased-deferred-shading-in-battlefield-3-for-playstation-3?from=ss_embed">PS3</a>.</p>

<p>On a tile-based GPU, all rendering is <em>already</em> happening in tiles, so what if we could say &#8220;now, you work on this tile, render this, render that; now we go this this tile&#8221;? Maybe that way we could achieve two things at once: 1) better light culling because it&#8217;s at tile level, and 2) most of the data could stay on this super-fast on-chip memory, without having to be written into system memory &amp; later read again. Memory bandwidth is very often a limiting factor in mobile graphics performance, and ability to keep deferred lighting buffers on-chip through the whole process could cut down bandwidth requirements a lot.</p>

<p><em>Suggestion</em>: somehow <em>(I&#8217;m feeling very hand-wavy today)</em> expose more control over tiled rendering. For example, explicitly say that rendering will only happen to the given tiles; and these textures are very likely to be read just after they are rendered into - so don&#8217;t resolve them to memory if they fit into on-chip one.</p>

<p>There&#8217;s already a Qualcomm extension of something towards that area - <a href="http://www.khronos.org/registry/gles/extensions/QCOM/QCOM_tiled_rendering.txt">QCOM_tiled_rendering</a> - though it seems to be more concerned about where does rendering happen. More control is needed on how to mark FBO textures as &#8220;keep in on-chip memory for sampling as a texture plz&#8221;.</p>

<p><strong>OpenCL</strong></p>

<p>Current mobile GPUs already are, or very soon will be, OpenCL capable. Also OpenCL can be implemented on the CPU, nicely SIMDified via NEON, and use multicore. <em>DO WANT!</em> (and while you&#8217;re at it, everything that&#8217;s doable to make interop between CL &amp; GL faster)</p>

<p>This can be used for a ton of things; skinning, culling, particles, procedural animations, image postprocessing and so on. And with a much less restrictive programming model, it&#8217;s easier to reuse computation results across draw calls or frames.</p>

<p>Couple this with &#8220;direct access to memory on the CPU&#8221; and OpenCL could be used for more things than graphics (again I&#8217;m grossly oversimplifying here and ignoring the whole synchronization/latency/security elephant&#8230;).</p>

<p><strong>MOAR?</strong></p>

<p>Now of course there are more things I&#8217;d want to see, but for today I&#8217;ll take just those above, thank you. Have a nice day!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Mobile graphics API wishlist: performance]]></title>
    <link href="http://aras-p.info/blog/2011/03/04/mobile-graphics-api-wishlist-performance/"/>
    <updated>2011-03-04T08:24:49+02:00</updated>
    <id>http://aras-p.info/blog/2011/03/04/mobile-graphics-api-wishlist-performance</id>
    <content type="html"><![CDATA[<p>Most mobile platforms currently are based on OpenGL ES 2.0. While it is <em>much</em> better than traditional OpenGL, there are ways where it limits performance or does not expose some interesting hardware features. So here&#8217;s an unorganized wishlist for GLES2.0 performance part!</p>

<p><em>Note that I&#8217;m focusing on, in my limited understanding, short term low-hanging fruits how to extend/patch existing GLES2.0 API. A pipe dream would be starting from scratch, getting rid of all OpenGL baggage and hopefully come up with a much cleaner, leaner &amp; better API, especially if it&#8217;s designed to only support some particular platform. But I digress, back to GLES2.0 for now.</em></p>

<p><strong>No guarantees when something expensive might happen.</strong></p>

<p>Due to some flexibility in GLES2.0, there might be expensive things happening at almost any point in your frame. For example, binding a texture with a different format might cause a driver to recompile a shader at the draw call time. I&#8217;ve seen <a href="http://twitter.com/#!/aras_p/status/34628257294852096">60 milliseconds</a> on iPhone 3Gs at first draw call with a relatively simple shader, all spent inside shader compiler backend. <em>60 milliseconds!</em> There are various things that can cause performance hiccups like this: texture formats, blending modes, vertex layout, non power of two textures and so on.</p>

<p><em>Suggestion</em>: work with GPU vendors and agree on an API that could make guarantees on when the expensive resource creation / patching work can happen, and when it can&#8217;t. For example, <em>somehow</em> guarantee that a draw call or a state set will not cause any object recreation / shader patching in the driver. I don&#8217;t have much experience with D3D10/11, but my impression is that this was one of the things it got right, no?</p>

<p><strong>Offline shader compilation.</strong></p>

<p>GLES2.0 has the functionality to load binary shaders, but it&#8217;s not mandatory. Some of the big platforms (iOS, I&#8217;m looking at you) just don&#8217;t support it.</p>

<p>Now of course, a single platform (like iOS or Android) can have multiple different GPUs, so you can&#8217;t fully compile a shader offline into final optimized GPU microcode. But <em>some</em> of the full compilation cost could very well be done offline, without being specific to any particular GPU.</p>

<p><em>Suggestion</em>: come up with a platform independent binary shader format. Something like D3D9 shader assembly is probably too low level (it assumes a vector4-based GPU, limited number of registers and so on), but something higher level should be possible. All of the shader lexing, parsing and common optimizations (constant folding, arithmetic simplifications, dead code removal etc.) can be done offline. It won&#8217;t speed up shader loading by an order of magnitude, but even if it&#8217;s possible to cut it by 20%, it&#8217;s worth it. And it would remove a very big bug surface area too!</p>

<p><strong>Texture loading.</strong></p>

<p>A lot (all?) of mobile platforms have unified CPU &amp; GPU memories, however to actually load the texture we have to read or memory map it from disk and then copy into OpenGL via glTexture2D and similar functions. Then, depending on the format, the driver would internally do swizzling and alignment of texture data.</p>

<p><em>Suggestion</em>: can&#8217;t most of this cost be removed? If for some formats it&#8217;s perfectly, statically known what layout and swizzling the GPU expects&#8230; can&#8217;t we just point the API to the data we already loaded or memory mapped? We could still need to implement the glTexture2D case for when (if ever) a totally new strange GPU comes that needs the data in a different order, but why not provide a faster path for the current GPUs?</p>

<p><strong>Vertex declarations.</strong></p>

<p>In unextended GLES2.0 you have to do <em>a ton</em> of calls just to setup vertex data. <a href="http://www.khronos.org/registry/gles/extensions/OES/OES_vertex_array_object.txt">OES_vertex_array_object</a> is a step in the right direction, providing the ability to create sets of vertex data bindings (&#8220;vertex declarations&#8221; in D3D speak). However, it builds upon an existing API, resulting in something that feels quite messy. Somehow it feels that by starting from scratch it could result in something much cleaner. Like&#8230; vertex declarations that existed in D3D since forever maybe?</p>

<p><em>Suggestion</em>: clean up that shit! It would probably need to be tied to a vertex shader input signature (just like in D3D10/11) to guarantee there would be no shader patching, but we&#8217;d be fine with that.</p>

<p><strong>Shader uniforms are per shader program.</strong></p>

<p>What it says - shader uniforms (&#8220;constants&#8221; in D3D speak) are not global; they are tied to a specific shader program. I don&#8217;t quite understand why, and I don&#8217;t think any GPU works that way. This is causing complexities and/or performance loss in the driver (it either has to save &amp; restore all uniform values on each shader change, or have dirty tracking on which uniforms have changed etc.). It also causes unneeded uniform sets on the client side - instead of having, for example, view*projection matrix set just once per frame it has to be set for each shader program that we use.</p>

<p><em>Suggestion</em>: just get rid of that? If you need to not break the existing spec, how about adding an extension to make all uniforms global? I propose <code>glCanHaz(GL_OES_GLOBAL_UNIFORMS_PLZ)</code></p>

<p><strong>Next up:</strong></p>

<p>Next time, I&#8217;ll take a look at my unorganized wishlist for mobile graphics features!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A Non-Uniform Work Distribution]]></title>
    <link href="http://aras-p.info/blog/2011/02/16/a-non-uniform-work-distribution/"/>
    <updated>2011-02-16T17:47:57+02:00</updated>
    <id>http://aras-p.info/blog/2011/02/16/a-non-uniform-work-distribution</id>
    <content type="html"><![CDATA[<p><em>Warning: a post with stupid questions and no answers whatsoever!</em></p>

<p>You need to do ten thousand things for the gold master / release / ShipIt(tm) moment. And you have 40 people who do the actual work&#8230; this means each of them <em>only</em> has to do 10000/40=250 things, which is not that bad. Right?</p>

<p>Meanwhile in the real world&#8230; it does not actually work like that. And that&#8217;s something that has been on my mind for a long time. I don&#8217;t know how much of this is truth vs. perception, or what to do about it. But here&#8217;s my feeling, simplified:</p>

<p><strong>20 percent of the people are responsible for getting 80 percent of the work done</strong></p>

<p>I am somewhat exaggerating just to keep it consistent with the <a href="http://en.wikipedia.org/wiki/Pareto_principle">Pareto principle</a>. But my feeling is that &#8220;work done&#8221; distribution is highly non uniform everywhere I worked where the team was more than a handful of people.</p>

<p>Here are some stupid statistics to illustrate my point (with graphs, and everyone loves graphs!):</p>

<p>Graph of bugs fixed per developer, over one week during the bug fixing phase. Red/yellow/green corresponds to priority 1,2,3 issues:</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/02/graphbugs.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/02/graphbugs.png" alt="" /></a></p>

<p>The distribution of bugs fixes is, shall we say, <em>somewhat</em> non uniform.</p>

<p>Is it a valid measure of &#8220;productivity&#8221;? Absolutely not. Some people probably haven&#8217;t been fixing bugs at all that week. Some bugs are <em>way</em> harder to fix than others. Some people could have made major part of the fix, but the finishing touches &amp; the act of actually resolving the bug was made by someone else. So yes, this statistics is absolutely flawed, but do we have anything else?</p>

<p>We could be checking version control commits.</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/02/svntimeline.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/02/svntimeline-500x243.png" alt="" /></a></p>

<p>Or putting the same into &#8220;commits by developer&#8221;:</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/02/svnauthor.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/02/svnauthor-500x269.png" alt="" /></a></p>

<p>Of course this is even easier to game than resolving bugs. <em>&#8220;Moving buttons to the left&#8221;, &#8220;Whoops, that was wrong, moving them to the right again&#8221;</em> anyone? And people will be trolling statistics just because they can.</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/02/svntroll.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/02/svntroll.png" alt="" /></a></p>

<p>However, there is still this highly subjective &#8220;feeling&#8221; that some folks are way, <em>way</em> faster than others. And not in just &#8220;can do some mess real fast&#8221; way, but in the &#8220;gets actual work done, and done well&#8221; way.</p>

<p>Or is it just my experience? How is it in your company? What can be done about it? Should something be done about it? I don&#8217;t know the answers&#8230;</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Virtual and No-Virtual]]></title>
    <link href="http://aras-p.info/blog/2011/02/01/the-virtual-and-no-virtual/"/>
    <updated>2011-02-01T12:28:03+02:00</updated>
    <id>http://aras-p.info/blog/2011/02/01/the-virtual-and-no-virtual</id>
    <content type="html"><![CDATA[<p>You are writing some system where different implementations have to be used for different platforms. To keep things real, let&#8217;s say it&#8217;s a rendering system which we&#8217;ll call &#8220;GfxDevice&#8221; <em>(based on a true story!)</em>. For example, on Windows there could be a Direct3D 9, Direct3D 11 or OpenGL implementations; on iOS/Android there could be OpenGL ES 1.1 &amp; 2.0 ones and so on.</p>

<p>For sake of simplicity, let&#8217;s say our GfxDevice interface needs to do this <em>(in real world it would need to do much more)</em>:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>void SetShader (ShaderType type, ShaderID shader);
</span><span class='line'>void SetTexture (int unit, TextureID texture);
</span><span class='line'>void SetGeometry (VertexBufferID vb, IndexBufferID ib);
</span><span class='line'>void Draw (PrimitiveType prim, int primCount);</span></code></pre></td></tr></table></div></figure>


<p>How this can be done?</p>

<p><strong>Approach #1: virtual interface!</strong></p>

<p>Many a programmer would think like this: why of course, GfxDevice is an interface with virtual functions, and then we have multiple implementations of it. Sounds good, and that&#8217;s what you would have been taught at the university in various software design courses. Here we go:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>class GfxDevice {
</span><span class='line'>public:
</span><span class='line'>    virtual ~GfxDevice();
</span><span class='line'>    virtual void SetShader (ShaderType type, ShaderID shader) = 0;
</span><span class='line'>    virtual void SetTexture (int unit, TextureID texture) = 0;
</span><span class='line'>    virtual void SetGeometry (VertexBufferID vb, IndexBufferID ib) = 0;
</span><span class='line'>    virtual void Draw (PrimitiveType prim, int primCount) = 0;
</span><span class='line'>};
</span><span class='line'>// and then we have:
</span><span class='line'>class GfxDeviceD3D9 : public GfxDevice {
</span><span class='line'>    // ...
</span><span class='line'>};
</span><span class='line'>class GfxDeviceGLES20 : public GfxDevice {
</span><span class='line'>    // ...
</span><span class='line'>};
</span><span class='line'>class GfxDeviceGCM : public GfxDevice {
</span><span class='line'>    // ...
</span><span class='line'>};
</span><span class='line'>// and so on</span></code></pre></td></tr></table></div></figure>


<p>And then based on platform (or something else) you create the right GfxDevice implementation, and the rest of the code uses that. This is all good and it works.</p>

<p>But then&#8230; hey! Some platforms <em>can only ever have one</em> GfxDevice implementation. On PS3 you will <em>always</em> end up using GfxDeviceGCM. Does it really make sense to have virtual functions on that platform?</p>

<blockquote><p>Side note: <em>of course</em> the cost of a virtual function call is not something that stands out immediately. It&#8217;s much less than, for example, doing a network request to get the leaderboards or parsing that XML file that ended up in your game for reasons no one can remember. Virtual function calls will not show up in the profiler as &#8220;a heavy bottleneck&#8221;. However, they are not free and their cost will be scattered around in a million places that is very hard to eradicate. You can end up having death by a thousand paper cuts.</p></blockquote>

<p>If we want to get rid of virtual functions on platforms where they are useless, what can we do?</p>

<p><strong>Approach #2: preprocessor to the rescue</strong></p>

<p>We just have to take out the &#8220;virtual&#8221; bit from the interface, and the &#8220;= 0&#8221; abstract function bit. With a bit of preprocessor we can:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>#define GFX_DEVICE_VIRTUAL (PLATFORM_WINDOWS || PLATFORM_MOBILE_UNIVERSAL || SOMETHING_ELSE)
</span><span class='line'>#if GFX_DEVICE_VIRTUAL
</span><span class='line'>    #define GFX_API virtual
</span><span class='line'>    #define GFX_PURE = 0
</span><span class='line'>#else
</span><span class='line'>    #define GFX_API
</span><span class='line'>    #define GFX_PURE
</span><span class='line'>#endif
</span><span class='line'>class GfxDevice {
</span><span class='line'>public:
</span><span class='line'>    GFX_API ~GfxDevice();
</span><span class='line'>    GFX_API void SetShader (ShaderType type, ShaderID shader) GFX_PURE;
</span><span class='line'>    GFX_API void SetTexture (int unit, TextureID texture) GFX_PURE;
</span><span class='line'>    GFX_API void SetGeometry (VertexBufferID vb, IndexBufferID ib) GFX_PURE;
</span><span class='line'>    GFX_API void Draw (PrimitiveType prim, int primCount) GFX_PURE;
</span><span class='line'>};</span></code></pre></td></tr></table></div></figure>


<p>And then there&#8217;s no separate class called GfxDeviceGCM for PS3; it&#8217;s just GfxDevice class implementing non-virtual methods. You have to make sure you don&#8217;t try to compile multiple GfxDevice class implementations on PS3 of course.</p>

<p>Ta-da! Virtual functions are gone on some platforms and life is good.</p>

<p>But we still have the other platforms, where there can be more than one GfxDevice implementation, and the decision for which one to use is made at runtime. Like our good old friend the PC: you could use Direct3D 9 or Direct3D 11 or OpenGL, based on the OS, GPU capabilities or user&#8217;s preference. Or a mobile platform where you don&#8217;t know whether OpenGL ES 2.0 will be available and you&#8217;d have to fallback to OpenGL ES 1.1.</p>

<p><strong>Let&#8217;s think about what virtual functions actually are</strong></p>

<p>How virtual functions work? Usually they work like this: each object gets a &#8220;pointer to a virtual function table&#8221; as it&#8217;s first hidden member. The virtual function table (vtable) is then just pointers to where the functions are in the code. Something like this:</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/02/vtable1.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/02/vtable1.png" alt="" /></a></p>

<p>The key points are: 1) each object&#8217;s data starts with a vtable pointer, and 2) vtable layout for classes implementing the same interface is the same.</p>

<p>When the compiler generates code for something like this:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>device-&gt;Draw (kPrimTriangles, 1337);</span></code></pre></td></tr></table></div></figure>


<p>it will generate something like the following pseudo-assembly:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>vtable = load pointer from [device] address
</span><span class='line'>drawlocation = vtable + 3*PointerSize ; since Draw is at index [3] in vtable
</span><span class='line'>drawfunction = load pointer from [drawlocation] address
</span><span class='line'>pass device pointer, kPrimTriangles and 1337 as arguments
</span><span class='line'>call into code at [drawfunction] address</span></code></pre></td></tr></table></div></figure>


<p>This code will work no matter if device is of GfxDeviceGLES20 or GfxDeviceGLES11 kind. For both cases, the first pointer in the object will point to the appropriate vtable, and the fourth pointer in the vtable will point to the appropriate Draw function.</p>

<p>By the way, the above illustrates the overhead of a virtual function call. If we&#8217;d assume a platform where we have an in-order CPU and reading from memory takes 500 CPU cycles (which is not far from truth for current consoles), then if nothing we need is in the CPU cache yet, this is what actually happens:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>vtable = load pointer from [device] address
</span><span class='line'>; *wait 500 cycles* until the pointer arrives
</span><span class='line'>drawlocation = vtable + 3*PointerSize
</span><span class='line'>drawfunction = load pointer from [drawlocation] address
</span><span class='line'>; *wait 500 cycles* until the pointer arrives
</span><span class='line'>pass device pointer, kPrimTriangles and 1337 as arguments
</span><span class='line'>call into code at [drawfunction] address
</span><span class='line'>; *wait 500 cycles* until code at that address is loaded</span></code></pre></td></tr></table></div></figure>


<p><strong>Can we do better?</strong></p>

<p>Look at the picture in the previous paragraph and remember the &#8220;wait 500 cycles&#8221; for each pointer we are chasing. Can we reduce the number of pointer chases? Of course we can: why not ditch the vtable altogether, and just put function pointers directly into the GfxDevice object?</p>

<blockquote><p>Virtual tables are implemented in this way mostly to save space. If we had 10000 objects of some class that has 20 virtual methods, we only pay one pointer overhead per object (40000 bytes on 32 bit architecture) and we store the vtable (20*4=80 bytes on 32 bit arch) just once, in total 39.14 kilobytes.</p>

<p>If we&#8217;d move all function pointers into objects themselves, we&#8217;d need to store 20 function pointers in each object. Which would be 781.25 kilobytes! Clearly this approach does not scale with increasing object instance counts.</p></blockquote>

<p>However, how many GfxDevice object instances do we <em>really</em> have? Most often&#8230; <em>exactly one</em>.</p>

<p><strong>Approach #3: function pointers</strong></p>

<p>If we move function pointers to the object itself, we&#8217;d have something like this:</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/02/novtable2.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/02/novtable2.png" alt="" /></a></p>

<p>There&#8217;s no built-in language support for implementing this in C++ however, so that would have to be done manually. Something like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>struct GfxDeviceFunctions {
</span><span class='line'>    SetShaderFunc SetShader;
</span><span class='line'>    SetTextureFunc SetTexture;
</span><span class='line'>    SetGeometryFunc SetGeometry;
</span><span class='line'>    DrawFunc Draw;
</span><span class='line'>};
</span><span class='line'>class GfxDeviceGLES20 : public GfxDeviceFunctions {
</span><span class='line'>    // ...
</span><span class='line'>};</span></code></pre></td></tr></table></div></figure>


<p>And then when creating a particular GfxDevice, you have to fill in the function pointers yourself. And the functions were member functions which magically take &#8220;this&#8221; parameter; it&#8217;s hard to just use them as function pointers without going to clumsy C++ member function pointer syntax and related issues.</p>

<p>We can be more explicit, C style, and instead just have the functions be static, taking &#8220;this&#8221; parameter directly:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>class GfxDeviceGLES20 : public GfxDeviceFunctions {
</span><span class='line'>    // ...
</span><span class='line'>    static void DrawImpl (GfxDevice* self, PrimitiveType prim, int primCount);
</span><span class='line'>    // ...
</span><span class='line'>};</span></code></pre></td></tr></table></div></figure>


<p>Code that uses it would look like this then:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>device-&gt;Draw (device, kPrimTriangles, 1337);</span></code></pre></td></tr></table></div></figure>


<p>and it would generate the following pseudo-assembly:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>drawlocation = device + 3*PointerSize
</span><span class='line'>drawfunction = load pointer from [drawlocation] address
</span><span class='line'>; *wait 500 cycles* until the pointer arrives
</span><span class='line'>pass device pointer, kPrimTriangles and 1337 as arguments
</span><span class='line'>call into code at [drawfunction] address
</span><span class='line'>; *wait 500 cycles* until code at that address is loaded</span></code></pre></td></tr></table></div></figure>


<p>Look at that, one of &#8220;wait 500 cycles&#8221; is gone!</p>

<p><strong>More C style</strong></p>

<p>We could move function pointers outside of GfxDevice if we want to, and just make them global:</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/02/globalfuncs.png"><img src="http://aras-p.info/blog/wp-content/uploads/2011/02/globalfuncs.png" alt="" /></a></p>

<p>In GLES1.1 case, that global GfxDevice funcs block would point to different pieces of code. And the pseudocode for this:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>// global variables!
</span><span class='line'>SetShaderFunc GfxSetShader;
</span><span class='line'>SetTextureFunc GfxSetTexture;
</span><span class='line'>SetGeometryFunc GfxSetGeometry;
</span><span class='line'>DrawFunc GfxDraw;
</span><span class='line'>// GLES2.0 implementation:
</span><span class='line'>void GfxDrawGLES20 (GfxDevice* self, PrimitiveType prim, int primCount) { /* ... */ }</span></code></pre></td></tr></table></div></figure>


<p>Code that uses it:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>GfxDraw (device, kPrimTriangles, 1337);</span></code></pre></td></tr></table></div></figure>


<p>and the pseudo-assembly:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>drawfunction = load pointer from [GfxDraw variable] address
</span><span class='line'>; wait 500 cycles until the pointer arrives
</span><span class='line'>pass device pointer, kPrimTriangles and 1337 as arguments
</span><span class='line'>call into code at [drawfunction] address
</span><span class='line'>; wait 500 cycles until code at that address is loaded</span></code></pre></td></tr></table></div></figure>


<p><strong>Is it worth it?</strong></p>

<p>I can hear some saying, &#8220;what? throwing away C++ OOP and implementing the same in almost raw C?! you&#8217;re crazy!&#8221;</p>

<p>Whether going the above route is better or worse is mostly a matter of programming style and preferences. It does get rid of one &#8220;wait 500 cycles&#8221; in the worst case for sure. And yes, to get that you do lose some of automagic syntax sugar in C++.</p>

<p>Is it worth it? Like always, depends on a lot of things. But if you do find yourself pondering the virtual function overhead for singleton-like objects, or especially if you do see that your profiler reports cache misses when calling into them, at least you&#8217;ll know one of the many possible alternatives, right?</p>

<p>And yeah, another alternative that&#8217;s easy to do on some platforms? Just put different GfxDevice implementations into dynamically loaded libraries, exposing the same set of functions. Which would end up being <em>very</em> similar to the last approach of &#8220;store function pointer table globally&#8221;, except you&#8217;d get some compiler syntax sugar to make it easier; and you wouldn&#8217;t even need to load the code that is not going to be used.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[iOS shader tricks, or it's 2001 all over again]]></title>
    <link href="http://aras-p.info/blog/2011/02/01/ios-shader-tricks-or-its-2001-all-over-again/"/>
    <updated>2011-02-01T09:43:57+02:00</updated>
    <id>http://aras-p.info/blog/2011/02/01/ios-shader-tricks-or-its-2001-all-over-again</id>
    <content type="html"><![CDATA[<p>I was recently optimizing some OpenGL ES 2.0 shaders for iOS/Android, and it was funny to see how performance tricks that were cool in 2001 are having their revenge again. Here&#8217;s a small example of starting with a normalmapped Blinn-Phong shader and optimizing it to run several times faster. Most of the clever stuff below was actually done by <a href="http://twitter.com/#!/__ReJ__">ReJ</a>, props to him!</p>

<p>Here&#8217;s a small test I&#8217;ll be working on: just a single plane with albedo and normal map textures:</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/02/iosbump1.jpg"><img src="http://aras-p.info/blog/wp-content/uploads/2011/02/iosbump1-150x150.jpg" alt="" /></a></p>

<p>I&#8217;ll be testing on iPhone 3Gs with iOS 4.2.1. Timer is started before glClear() and stopped after glFinish() that I added just after drawing the mesh.</p>

<p>Let&#8217;s start with an initial naive shader version:</p>

<div><script src='https://gist.github.com/783784.js?file='></script>
<noscript><pre><code>#ifdef VERTEX
attribute vec4 a_position;
attribute vec2 a_uv;
attribute vec3 a_normal;
attribute vec4 a_tangent;

uniform mat4 u_mvp;
uniform mat4 u_world2object;
uniform vec4 u_worldlightdir;
uniform vec4 u_worldcampos;

varying vec2 v_uv;
varying vec3 v_lightdir;
varying vec3 v_viewdir;

void main()
{
    gl_Position = u_mvp * a_position;
    v_uv = a_uv;
    
    vec3 bitan = cross (a_normal.xyz, a_tangent.xyz) * a_tangent.w;
    mat3 tsprotation = mat3 (
        a_tangent.x, bitan.x, a_normal.x,
        a_tangent.y, bitan.y, a_normal.y,
        a_tangent.z, bitan.z, a_normal.z);
    
    vec3 objLightDir = (u_world2object * u_worldlightdir).xyz;
    vec3 objCamPos = (u_world2object * u_worldcampos).xyz;
    vec3 objViewDir = objCamPos - a_position.xyz;
    
    v_lightdir = tsprotation * objLightDir;
    v_viewdir = tsprotation * objViewDir;
}
#endif


#ifdef FRAGMENT
precision highp float;

uniform vec4 u_lightcolor;
uniform vec4 u_matcolor;
uniform float u_spec;

varying vec2 v_uv;
varying vec3 v_lightdir;
varying vec3 v_viewdir;

uniform sampler2D u_texcolor;
uniform sampler2D u_texnormal;

void main()
{
    vec4 albedo = texture2D (u_texcolor, v_uv) * u_matcolor;
    vec3 normal = texture2D (u_texnormal, v_uv).rgb * 2.0 - 1.0;
    
    vec3 halfdir = normalize (normalize(v_lightdir) + normalize(v_viewdir));
    
    float diff = max (0.0, dot (normal, v_lightdir));
    float nh = max (0.0, dot (normal, halfdir));
    float spec = pow (nh, u_spec);
    
    vec4 c = albedo * u_lightcolor * diff + u_lightcolor * spec;
    
    gl_FragColor = c;
}
#endif
</code></pre></noscript></div>


<p>Should be pretty self-explanatory to anyone who&#8217;s familiar with tangent space normal mapping and Blinn-Phong BRDF. Running time: <strong>24.5 milliseconds</strong>. On iPhone 4&#8217;s Retina resolution, this would be about 4x slower!</p>

<p>What can we do next? On mobile platforms using appropriate precision of variables is often very important, especially in a fragment shader. So let&#8217;s go and add highp/mediump/lowp qualifiers to the fragment shader: <a href="https://gist.github.com/783703/05e78340b12739e853ce031bd0388430ea95f2a6">shader source</a></p>

<p>Still the same running time! Alas, iOS does not have low level shader analysis tools, so we can&#8217;t really tell why that is happening. We could be limited by something else (e.g. normalizing vectors and computing pow() being the bottlenecks that run in parallel with all low precision stuff), or the driver might be promoting most of our computations to higher precision because it feels like it. It&#8217;s a magic box!</p>

<p>Let&#8217;s start approximating instead. How about computing normalized view direction per vertex, and interpolating that for the fragment shader? It won&#8217;t be entirely &#8220;correct&#8221;, but hey, it&#8217;s a phone we&#8217;re talking about. <a href="https://gist.github.com/783703/1e4fd0daa384d308d125a748985e8e203e49625a">shader source</a></p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/02/iosbump3.jpg"><img class="right" src="http://aras-p.info/blog/wp-content/uploads/2011/02/iosbump3-150x150.jpg"></a>
15 milliseconds! But&#8230; the rendering is wrong; everything turned white near the bottom of the screen. Turns out PowerVR SGX (the GPU in all current iOS devices) is really meaning &#8220;low precision&#8221; when we want to add two lowp vectors and normalize the result. Let&#8217;s try promoting one of them to medium precision with a &#8220;varying mediump vec3 v_viewdir&#8221;: <a href="https://gist.github.com/783703/591eb83dacaae3840cc4e4d3d8b95a4fc3abdd65">shader source</a></p>

<p>That fixed rendering, but we&#8217;re back to 24.5 milliseconds. <em>Sad shader writers are sad&#8230; oh shader performance analysis tools, where art thou?</em></p>

<p>Let&#8217;s try approximating some more: compute half-vector in the vertex shader, and interpolate normalized value. This would get rid of all normalizations in the fragment shader. <a href="https://gist.github.com/783703/6360c2912b860aa30415e5120ef147169274cd71">shader source</a></p>

<p><strong>16.3</strong> milliseconds, not too bad! We still have pow() computed in the fragment shader, and that one is probably not the fastest operation there&#8230;</p>

<p>Almost a decade ago, a very common trick was to use a lookup texture to do the lighting. For example, a 2D texture indexed by (N.L, N.H). Since all lighting data would be &#8220;baked&#8221; into the texture, it does not necessarily have to be Blinn-Phong even; we can prepare faux-anisotropic, metallic, toon-shading or other fancy BRDFs there, as long as they can be expressed in terms of N.L and N.H. So let&#8217;s try creating 128x128 RGBA lookup texture and use that: <a href="https://gist.github.com/783703/87f1cf5529d644cab16123550e809e9f7598f4f3">shader source</a></p>

<p>A fast &amp; not super efficient code to create the lighting lookup texture for Blinn-Phong:</p>

<div><script src='https://gist.github.com/783759.js?file='></script>
<noscript><pre><code>// lr,lg,lb - light color
// spec = specular power
int idx = 0;
for (int y = 0; y &lt; height; ++y)
{
    for (int x = 0; x &lt; width; ++x, idx+=4)
    {
        float vx = float(x) / width;
        float vy = float(y) / height;
        float nl = vx;
        float nh = vy;
        float s = powf (nh, spec);
        data[idx+0] = nl * lr * 255.0f;
        data[idx+1] = nl * lg * 255.0f;
        data[idx+2] = nl * lb * 255.0f;
        data[idx+3] = s * 255.0f;
    }
}
</code></pre></noscript></div>


<p><strong>9.1</strong> milliseconds! We lost some precision in the specular though (it&#8217;s dimmer):</p>

<p><a href="http://aras-p.info/blog/wp-content/uploads/2011/02/iosbump6.jpg"><img src="http://aras-p.info/blog/wp-content/uploads/2011/02/iosbump6-150x150.jpg" alt="" /></a></p>

<p>What else can be done? Notice that we clamp N.L and N.H values in the fragment shader, but this could be done just as well by the texture sampler, if we set texture&#8217;s addressing mode to CLAMP_TO_EDGE. Let&#8217;s get rid of the clamps: <a href="https://gist.github.com/783703/e24a2475fded83d2196372c8092a0d8de80a98eb">shader source</a></p>

<p>This is 8.3 milliseconds, or <strong>7.6</strong> milliseconds if we reduce our lighting texture resolution to 32x128.</p>

<p>Should we stop there? Not necessarily. For example, the shader is still multiplying albedo with a per-material color. Maybe that&#8217;s not very useful and can be let go. Maybe we can also make specular be always white?</p>

<div><script src='https://gist.github.com/783703.js?file='></script>
<noscript><pre><code>// Final for now...
// iPhone 3Gs: 5.9ms

#ifdef VERTEX
attribute vec4 a_position;
attribute vec2 a_uv;
attribute vec3 a_normal;
attribute vec4 a_tangent;

uniform mat4 u_mvp;
uniform mat4 u_world2object;
uniform vec4 u_worldlightdir;
uniform vec4 u_worldcampos;

varying vec2 v_uv;
varying vec3 v_lightdir;
varying vec3 v_halfdir;

void main()
{
    gl_Position = u_mvp * a_position;
    v_uv = a_uv;
    
    vec3 bitan = cross (a_normal.xyz, a_tangent.xyz) * a_tangent.w;
    mat3 tsprotation = mat3 (
        a_tangent.x, bitan.x, a_normal.x,
        a_tangent.y, bitan.y, a_normal.y,
        a_tangent.z, bitan.z, a_normal.z);
    
    vec3 objLightDir = (u_world2object * u_worldlightdir).xyz;
    vec3 objCamPos = (u_world2object * u_worldcampos).xyz;
    vec3 objViewDir = objCamPos - a_position.xyz;
    
    v_lightdir = tsprotation * objLightDir;
    vec3 viewdir = normalize(tsprotation * objViewDir);
    v_halfdir = normalize (v_lightdir + viewdir);
}
#endif


#ifdef FRAGMENT
uniform lowp vec4 u_lightcolor;
uniform lowp vec4 u_matcolor;
uniform mediump float u_spec;

varying mediump vec2 v_uv;
varying lowp vec3 v_lightdir;
varying lowp vec3 v_halfdir;

uniform sampler2D u_texcolor;
uniform sampler2D u_texnormal;
uniform sampler2D u_texLUT;

void main()
{
    lowp vec4 albedo = texture2D (u_texcolor, v_uv);
    lowp vec3 normal = texture2D (u_texnormal, v_uv).rgb * 2.0 - 1.0;
    
    lowp float diff = dot (normal, v_lightdir);
    lowp float nh = dot (normal, v_halfdir);
    lowp vec2 luv = vec2(diff,nh);
    lowp vec4 l = texture2D (u_texLUT, luv);
    
    lowp vec4 c = albedo * l + l.a;
    gl_FragColor = c;
}
#endif
</code></pre></noscript></div>


<p>How fast is this? <strong>5.9 milliseconds</strong>, or over <strong>4 times</strong> faster than our original shader.</p>

<p>Could it be made faster? Maybe; that&#8217;s an exercise for the reader :) I tried computing just the RGB color channels and setting alpha to zero, but that got slightly slower. Without real shader analysis tools it&#8217;s hard to see where or if additional cycles could be squeezed out.</p>

<p>I&#8217;m adding <a href="http://aras-p.info/blog/wp-content/uploads/2011/02/iOSShaderPerf.zip">Xcode project with sources, textures and shaders of this experiment</a>. Notes about it: only tested on iPhone 3Gs (probably will crash on iPhone 3G, and iPad will have wrong aspect ratio). Might not work at all! Shader is read from Resources/Shaders/shader.txt, next to it are shader versions of the steps of this experiment. Enjoy!</p>

<p><em>This is a cross post from altdevblogaday: <a href="http://altdevblogaday.com/ios-shader-tricks-or-its-2001-all-over-again">http://altdevblogaday.com/ios-shader-tricks-or-its-2001-all-over-again</a></em></p>
]]></content>
  </entry>
  
</feed>
