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

<channel>
	<title>#AltDevBlogADay &#187; Aras Pranckevičius</title>
	<atom:link href="http://www.altdevblogaday.com/author/aras-pranckevicius/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.altdevblogaday.com</link>
	<description>Each day a little more #gamedev love</description>
	<lastBuildDate>Thu, 17 May 2012 03:06:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Testing Graphics Code, 4 years later</title>
		<link>http://www.altdevblogaday.com/2011/06/17/testing-graphics-code-4-years-later/</link>
		<comments>http://www.altdevblogaday.com/2011/06/17/testing-graphics-code-4-years-later/#comments</comments>
		<pubDate>Fri, 17 Jun 2011 04:45:33 +0000</pubDate>
		<dc:creator>Aras Pranckevičius</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=8792</guid>
		<description><![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 <a href="http://unity3d.com/">Unity</a>. Recent <a href="http://altdevblogaday.com/2011/06/13/definition-of-done-1/">Francesco&#8217;s article</a> made me revisit it&#8230; 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><a href="http://www.altdevblogaday.com/2011/06/17/testing-graphics-code-4-years-later/" class="more-link">Read more on Testing Graphics Code, 4 years later&#8230;</a></p>
]]></description>
			<content:encoded><![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 <a href="http://unity3d.com/">Unity</a>. Recent <a href="http://altdevblogaday.com/2011/06/13/definition-of-done-1/">Francesco&#8217;s article</a> made me revisit it&#8230; 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.<br />
<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:<br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/06/092-FogModes.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/06/092-FogModes.png" alt="" width="400" height="300" class="alignnone size-full wp-image-770" /></a><br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/06/017-Fog.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/06/017-Fog.png" alt="" width="400" height="300" class="alignnone size-full wp-image-771" /></a></p>
<p>Another example, tests for various corner cases of Deferred Lighting:<br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/06/118-DeferredLMCases.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/06/118-DeferredLMCases.png" alt="" width="400" height="300" class="alignnone size-full wp-image-774" /></a><br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/06/134-DefLightShapes.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/06/134-DefLightShapes.png" alt="" width="400" height="300" class="alignnone size-full wp-image-775" /></a><br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/06/143-DefLargeCoords.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/06/143-DefLargeCoords.png" alt="" width="400" height="300" class="alignnone size-full wp-image-776" /></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:<br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/06/teamcity-gfx-tests.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/06/teamcity-gfx-tests.png" alt="" width="445" height="362" class="alignnone size-full wp-image-778" /></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 <i>fully</i> deterministic it seems.</p>
<p>So you have this bunch of &#8220;this is the golden truth&#8221; images for all the tests:<br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/06/some-gfx-tests.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/06/some-gfx-tests-300x148.png" alt="" width="300" height="148" class="alignnone size-medium wp-image-8801" /></a></p>
<p>And each platform automatically tested on TeamCity has it&#8217;s own set:<br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/06/gfx-test-platforms.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/06/gfx-test-platforms.png" alt="" width="187" height="181" class="alignnone size-full wp-image-782" /></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:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/06/17/testing-graphics-code-4-years-later/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Notes on Native Client &amp; Pepper Plugin API</title>
		<link>http://www.altdevblogaday.com/2011/06/02/notes-on-native-client-pepper-plugin-api/</link>
		<comments>http://www.altdevblogaday.com/2011/06/02/notes-on-native-client-pepper-plugin-api/#comments</comments>
		<pubDate>Thu, 02 Jun 2011 08:23:58 +0000</pubDate>
		<dc:creator>Aras Pranckevičius</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=7283</guid>
		<description><![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><a href="http://www.altdevblogaday.com/2011/06/02/notes-on-native-client-pepper-plugin-api/" class="more-link">Read more on Notes on Native Client &#38; Pepper Plugin API&#8230;</a></p>
]]></description>
			<content:encoded><![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 <a href="http://msdn.microsoft.com/en-us/library/bb219685(v=vs.85).aspx"><tt>Direct3DCreate9</tt></a> and run with it, while keeping the promise of &#8220;it&#8217;s secure&#8221;? Or a more extreme case, <tt>FILE* f = fopen("/etc/passwd", "rt");</tt>?!</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 (<tt><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></tt>) &#8211; similar to what you&#8217;d use EGL on other platforms for &#8211; and beyond that you just include <tt>GLES2/gl2.h, GLES2/gl2ext.h</tt> 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 &#8212; 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 <tt><a href="http://src.chromium.org/viewvc/chrome/trunk/src/ppapi/cpp/audio_config.h?view=markup">ppapi/cpp/audio_config.h</a></tt> and <tt><a href="http://src.chromium.org/viewvc/chrome/trunk/src/ppapi/cpp/audio.h?view=markup">ppapi/cpp/audio.h</a></tt>. 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 <tt>pp::Instance</tt>) 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"><tt>PPInputEvent</tt> 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 <tt><a href="http://src.chromium.org/viewvc/chrome/trunk/src/ppapi/cpp/url_loader.h?view=markup">ppapi/cpp/url_loader.h</a></tt> and friends.</p>
<p>Timer &amp; time queries via <tt><a href="http://src.chromium.org/viewvc/chrome/trunk/src/ppapi/cpp/core.h?view=markup">ppapi/cpp/core.h</a></tt> (e.g. <tt>pp::Module::Get()-&gt;core()-&gt;CallOnMainThread(...)</tt>).</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 &#8211; or almost everything &#8211; 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 &#8211; especially considering how it came into existence &#8211; 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 &#8212; 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:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/06/02/notes-on-native-client-pepper-plugin-api/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>A way to visualize mip levels</title>
		<link>http://www.altdevblogaday.com/2011/05/03/a-way-to-visualize-mip-levels/</link>
		<comments>http://www.altdevblogaday.com/2011/05/03/a-way-to-visualize-mip-levels/#comments</comments>
		<pubDate>Tue, 03 May 2011 16:41:50 +0000</pubDate>
		<dc:creator>Aras Pranckevičius</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=5066</guid>
		<description><![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><a href="http://www.altdevblogaday.com/2011/05/03/a-way-to-visualize-mip-levels/" class="more-link">Read more on A way to visualize mip levels&#8230;</a></p>
]]></description>
			<content:encoded><![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:<br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/05/BootcampNormal.jpg"><img src="http://altdevblogaday.com/wp-content/uploads/2011/05/BootcampNormal-300x170.jpg" alt="" width="300" height="170" class="alignnone size-medium wp-image-5068" /></a><br />
We provide a &#8220;mipmaps&#8221; visualization mode that renders it like this:<a href="http://altdevblogaday.com/wp-content/uploads/2011/05/BootcampMips.jpg"><img src="http://altdevblogaday.com/wp-content/uploads/2011/05/BootcampMips-300x170.jpg" alt="" width="300" height="170" class="alignnone size-medium wp-image-5067" /></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:<br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/05/PlatformerSizes.jpg"><img src="http://altdevblogaday.com/wp-content/uploads/2011/05/PlatformerSizes-300x114.jpg" alt="" width="300" height="114" class="alignnone size-medium wp-image-5070" /></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.<br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/05/FloorCeiling.jpg"><img src="http://altdevblogaday.com/wp-content/uploads/2011/05/FloorCeiling-300x190.jpg" alt="" width="300" height="190" class="alignnone size-medium wp-image-5069" /></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>
<pre>struct v2f {
    float4 pos : SV_POSITION;
    float2 uv : TEXCOORD0;
    float2 mipuv : TEXCOORD1;
};
<b>float2 mainTextureSize</b>;
v2f vert (float4 vertex : POSITION, float2 uv : TEXCOORD0)
{
    v2f o;
    o.pos = mul (matrix_mvp, vertex);
    o.uv = uv;
    o.mipuv = <b>uv * mainTextureSize / 8.0</b>;
    return o;
}
half4 frag (v2f i) : COLOR0
{
    half4 col = tex2D (mainTexture, i.uv);
    half4 mip = tex2D (mipColorsTexture, i.mipuv);
    half4 res;
    res.rgb = lerp (col.rgb, mip.rgb, mip.a);
    res.a = col.a;
    return res;
}
</pre>
<p>The <tt>mainTextureSize</tt> 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 <tt>mipColorsTexture</tt> that has different colors in each mip level.</p>
<p>Let&#8217;s say we would create a 32&#215;32 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: <tt>newUV = uv * 256 / 32</tt> or in a more generic way, <tt>newUV = uv * textureSize / mipTextureSize</tt>.</p>
<p>Why there&#8217;s <tt>8.0</tt> in the shader then, if we create the mip texture at 32&#215;32 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 32&#215;32 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>
<p><span style="font-size: 75%"><em>(this post is also on my blog at <a href="http://aras-p.info/blog/2011/05/03/a-way-to-visualize-mip-levels/">http://aras-p.info/blog/2011/05/03/a-way-to-visualize-mip-levels/</a></em>)</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/05/03/a-way-to-visualize-mip-levels/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Mercurial/Kiln experience so far</title>
		<link>http://www.altdevblogaday.com/2011/04/18/mercurialkiln-experience-so-far/</link>
		<comments>http://www.altdevblogaday.com/2011/04/18/mercurialkiln-experience-so-far/#comments</comments>
		<pubDate>Mon, 18 Apr 2011 07:15:17 +0000</pubDate>
		<dc:creator>Aras Pranckevičius</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=4313</guid>
		<description><![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.com/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><em>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!<br />
</em></p>
<p><a href="http://www.altdevblogaday.com/2011/04/18/mercurialkiln-experience-so-far/" class="more-link">Read more on Mercurial/Kiln experience so far&#8230;</a></p>
]]></description>
			<content:encoded><![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.com/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><em>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!<br />
</em></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 &#8212; an import from CVS &#8212; 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://altdevblogaday.com/wp-content/uploads/2011/04/hg-branches.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/04/hg-branches-150x150.png" alt="" width="150" height="150" class="alignright size-thumbnail wp-image-4314" /></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>Subversion: update, commit.
<ul>
<li>Since merges don&#8217;t really work: branch, switch &amp; merge are rarely used by mere mortals.</li>
</ul>
</li>
<li>Mercurial: pull, update or merge, commit, push.
<ul>
<li>And you might find you have two heads now!</li>
</ul>
<ul>
<li>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> ;)</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 datetime="whoops, wrong terminology!">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 <tt>hg status</tt>) 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:<br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/04/kiln-overview.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/04/kiln-overview-300x173.png" alt="" width="300" height="173" class="alignnone size-medium wp-image-4317" /></a></p>
<p>And shows the overview of any particular repository:<br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/04/kiln-repo.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/04/kiln-repo-300x167.png" alt="" width="300" height="167" class="alignnone size-medium wp-image-4318" /></a></p>
<p>And of course diff view of any particular commit:<br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/04/kiln-diff.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/04/kiln-diff-300x104.png" alt="" width="300" height="104" class="alignnone size-medium wp-image-4315" /></a></p>
<p>My largest complaints about Kiln&#8217;s web interface are: 1) speed and 2) merge spiderwebs.</p>
<p><b><em>Speed</em></b>: 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://altdevblogaday.com/wp-content/uploads/2011/04/kiln-merge-spiderweb.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/04/kiln-merge-spiderweb-150x150.png" alt="" width="150" height="150" class="alignright size-thumbnail wp-image-687" /></a><b><em>Merge spiderwebs</em></b>: 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:<br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/04/kiln-reviewrequest.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/04/kiln-reviewrequest-300x138.png" alt="" width="300" height="138" class="alignnone size-medium wp-image-4320" /></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:<br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/04/kiln-review.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/04/kiln-review-300x199.png" alt="" width="300" height="199" class="alignnone size-medium wp-image-4319" /></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 &#8212; 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>
<p><span style="font-size: 85%"><em>This post is also on my blog at <a href="http://aras-p.info/blog/2011/04/18/mercurialkiln-experience-so-far/">http://aras-p.info/blog/2011/04/18/mercurialkiln-experience-so-far/</a></em></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/04/18/mercurialkiln-experience-so-far/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Stories of Universities</title>
		<link>http://www.altdevblogaday.com/2011/04/01/stories-of-universities/</link>
		<comments>http://www.altdevblogaday.com/2011/04/01/stories-of-universities/#comments</comments>
		<pubDate>Fri, 01 Apr 2011 18:59:34 +0000</pubDate>
		<dc:creator>Aras Pranckevičius</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=3009</guid>
		<description><![CDATA[<p>I was doing a talk and a Q&#38;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><a href="http://www.altdevblogaday.com/2011/04/01/stories-of-universities/" class="more-link">Read more on Stories of Universities&#8230;</a></p>
]]></description>
			<content:encoded><![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>Mumble mumble&#8230; weeelll&#8230; something something mumble. This was the majority&#8217;s opinion.</li>
<li>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.</li>
<li>Without OOP there&#8217;s no way to separate things out; everything becomes a mess.</li>
<li>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;</li>
<li><em>I forget if there was anything else really.</em></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://altdevblogaday.com/wp-content/uploads/2011/04/pifloat.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/04/pifloat.png" alt="" width="342" height="51" class="alignnone size-full wp-image-3010" /></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>
<p><span style="font-size:80%"><em>This post is also on my blog at <a href="http://aras-p.info/blog/2011/04/01/stories-of-universities/">http://aras-p.info/blog/2011/04/01/stories-of-universities</a></em></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/04/01/stories-of-universities/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Mobile graphics API wishlist: some features</title>
		<link>http://www.altdevblogaday.com/2011/03/19/mobile-graphics-api-wishlist-some-features/</link>
		<comments>http://www.altdevblogaday.com/2011/03/19/mobile-graphics-api-wishlist-some-features/#comments</comments>
		<pubDate>Sat, 19 Mar 2011 13:53:09 +0000</pubDate>
		<dc:creator>Aras Pranckevičius</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=2131</guid>
		<description><![CDATA[<p>In my <a href="http://altdevblogaday.com/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><a href="http://www.altdevblogaday.com/2011/03/19/mobile-graphics-api-wishlist-some-features/" class="more-link">Read more on Mobile graphics API wishlist: some features&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://altdevblogaday.com/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 &#8211; 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 &#8211; 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 &#8211; <a href="http://www.khronos.org/registry/gles/extensions/QCOM/QCOM_tiled_rendering.txt">QCOM_tiled_rendering</a> &#8211; 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>
<p><em>This is a cross-post from my blog: http://aras-p.info/blog/2011/03/19/mobile-graphics-api-wishlist-some-features/</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/03/19/mobile-graphics-api-wishlist-some-features/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Mobile graphics API wishlist: performance</title>
		<link>http://www.altdevblogaday.com/2011/03/04/mobile-graphics-api-wishlist-performance/</link>
		<comments>http://www.altdevblogaday.com/2011/03/04/mobile-graphics-api-wishlist-performance/#comments</comments>
		<pubDate>Fri, 04 Mar 2011 06:30:06 +0000</pubDate>
		<dc:creator>Aras Pranckevičius</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=1507</guid>
		<description><![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><a href="http://www.altdevblogaday.com/2011/03/04/mobile-graphics-api-wishlist-performance/" class="more-link">Read more on Mobile graphics API wishlist: performance&#8230;</a></p>
]]></description>
			<content:encoded><![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><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 &#8211; 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 &#8211; 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>
<p><em>This is a cross-post from my blog: <a href="http://aras-p.info/blog/2011/03/04/mobile-graphics-api-wishlist-performance/">http://aras-p.info/blog/2011/03/04/mobile-graphics-api-wishlist-performance/</a></em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/03/04/mobile-graphics-api-wishlist-performance/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>A Non-Uniform Work Distribution</title>
		<link>http://www.altdevblogaday.com/2011/02/16/a-non-uniform-work-distribution/</link>
		<comments>http://www.altdevblogaday.com/2011/02/16/a-non-uniform-work-distribution/#comments</comments>
		<pubDate>Wed, 16 Feb 2011 15:48:24 +0000</pubDate>
		<dc:creator>Aras Pranckevičius</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=790</guid>
		<description><![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><a href="http://www.altdevblogaday.com/2011/02/16/a-non-uniform-work-distribution/" class="more-link">Read more on A Non-Uniform Work Distribution&#8230;</a></p>
]]></description>
			<content:encoded><![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:<br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/02/graphbugs.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/02/graphbugs-300x247.png" alt="" width="300" height="247" class="alignnone size-medium wp-image-791" /></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.<br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/02/svntimeline.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/02/svntimeline-300x145.png" alt="" width="300" height="145" class="alignnone size-medium wp-image-793" /></a></p>
<p>Or putting the same into &#8220;commits by developer&#8221;:<br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/02/svnauthor.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/02/svnauthor-300x161.png" alt="" width="300" height="161" class="alignnone size-medium wp-image-794" /></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.<br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/02/svntroll.png"><img src="http://altdevblogaday.com/wp-content/uploads/2011/02/svntroll.png" alt="" width="330" height="108" class="alignnone size-full wp-image-795" /></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:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/02/16/a-non-uniform-work-distribution/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>The Virtual and No-Virtual</title>
		<link>http://www.altdevblogaday.com/2011/02/01/the-virtual-and-no-virtual/</link>
		<comments>http://www.altdevblogaday.com/2011/02/01/the-virtual-and-no-virtual/#comments</comments>
		<pubDate>Tue, 01 Feb 2011 10:21:00 +0000</pubDate>
		<dc:creator>Aras Pranckevičius</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/2011/02/01/the-virtual-and-no-virtual/</guid>
		<description><![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;&#160;<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 &#38; 2.0 ones and so on.</p>
<p><a href="http://www.altdevblogaday.com/2011/02/01/the-virtual-and-no-virtual/" class="more-link">Read more on The Virtual and No-Virtual&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>You are writing some system where different implementations have to be used for different platforms. To keep things real, let&rsquo;s say it&rsquo;s a rendering system which we&rsquo;ll call &ldquo;GfxDevice&rdquo;&nbsp;<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&rsquo;s say our GfxDevice interface needs to do this&nbsp;<em>(in real world it would need to do much more)</em>:</p>
<div class="code">
<pre>void SetShader (ShaderType type, ShaderID shader);
void SetTexture (int unit, TextureID texture);
void SetGeometry (VertexBufferID vb, IndexBufferID ib);
void Draw (PrimitiveType prim, int primCount);</pre>
</div>
<p>How this can be done?</p>
<p><span id="more-262"></span><br />
<h3>Approach #1: virtual interface!</h3>
<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&rsquo;s what you would have been taught at the university in various software design courses. Here we go:</p>
<div class="code">
<pre>class GfxDevice {
public:
    virtual ~GfxDevice();
    virtual void SetShader (ShaderType type, ShaderID shader) = 0;
    virtual void SetTexture (int unit, TextureID texture) = 0;
    virtual void SetGeometry (VertexBufferID vb, IndexBufferID ib) = 0;
    virtual void Draw (PrimitiveType prim, int primCount) = 0;
};
// and then we have:
class GfxDeviceD3D9 : public GfxDevice {
    // ...
};
class GfxDeviceGLES20 : public GfxDevice {
    // ...
};
class GfxDeviceGCM : public GfxDevice {
    // ...
};
// and so on</pre>
</div>
<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>
<p>Side note: <em>of course</em> the cost of a virtual function call is not something that stands out immediately. It&rsquo;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 &ldquo;a heavy bottleneck&rdquo;. 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>
<p>If we want to get rid of virtual functions on platforms where they are useless, what can we do?</p>
<h3>Approach #2: preprocessor to the rescue</h3>
<p>We just have to take out the &#8220;virtual&#8221; bit from the interface, and the &#8220;= 0&#8243; abstract function bit. With a bit of preprocessor we can:</p>
<div class="code">
<pre>#define GFX_DEVICE_VIRTUAL (PLATFORM_WINDOWS || PLATFORM_MOBILE_UNIVERSAL || SOMETHING_ELSE)
#if GFX_DEVICE_VIRTUAL
    #define GFX_API virtual
    #define GFX_PURE = 0
#else
    #define GFX_API
    #define GFX_PURE
#endif
class GfxDevice {
public:
    GFX_API ~GfxDevice();
    GFX_API void SetShader (ShaderType type, ShaderID shader) GFX_PURE;
    GFX_API void SetTexture (int unit, TextureID texture) GFX_PURE;
    GFX_API void SetGeometry (VertexBufferID vb, IndexBufferID ib) GFX_PURE;
    GFX_API void Draw (PrimitiveType prim, int primCount) GFX_PURE;
};</pre>
</div>
<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>
<h3>Let&#8217;s think about what virtual functions actually are</h3>
<p>How virtual functions work? Usually they work like this: each object gets a &ldquo;pointer to a virtual function table&rdquo; as it&rsquo;s first hidden member. The virtual function table (vtable) is then just pointers to where the functions are in the code. Something like this:<br /> <img class="alignnone size-full wp-image-615" src="http://aras-p.info/blog/wp-content/uploads/2011/02/vtable1.png" height="371" alt="" style="padding: 0px" /></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>
<div class="code">
<pre>device-&gt;Draw (kPrimTriangles, 1337);</pre>
</div>
<p>it will generate something like the following pseudo-assembly:</p>
<div class="CodeRay">
<div class="code">
<pre>vtable = load pointer from [device] address
drawlocation = vtable + 3*PointerSize ; since Draw is at index [3] in vtable
drawfunction = load pointer from [drawlocation] address
pass device pointer, kPrimTriangles and 1337 as arguments
call into code at [drawfunction] address</pre>
</div>
</div>
<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&rsquo;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>
<div class="CodeRay">
<div class="code">
<pre>vtable = load pointer from [device] address
; wait 500 cycles until the pointer arrives
drawlocation = vtable + 3*PointerSize
drawfunction = load pointer from [drawlocation] address
; wait 500 cycles until the pointer arrives
pass device pointer, kPrimTriangles and 1337 as arguments
call into code at [drawfunction] address
; wait 500 cycles until code at that address is loaded</pre>
</div>
</div>
<h3>Can we do better?</h3>
<p>Look at the picture in the previous paragraph and remember the &ldquo;wait 500 cycles&rdquo; 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>
<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.<br /> If we&rsquo;d move all function pointers into objects themselves, we&rsquo;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>
<p>However, how many GfxDevice object instances do we&nbsp;<em>really</em>&nbsp;have? Most often&hellip;&nbsp;<em>exactly one</em>.</p>
<h3>Approach #3: function pointers</h3>
<p>If we move function pointers to the object itself, we&rsquo;d have something like this:<br /><img class="alignnone size-full wp-image-621" src="http://aras-p.info/blog/wp-content/uploads/2011/02/novtable2.png" height="356" alt="" width="337" style="padding: 0px" /></p>
<p>There&rsquo;s no built-in language support for implementing this in C++ however, so that would have to be done manually. Something like:</p>
<div class="CodeRay">
<div class="code">
<pre>struct GfxDeviceFunctions {
    SetShaderFunc SetShader;
    SetTextureFunc SetTexture;
    SetGeometryFunc SetGeometry;
    DrawFunc Draw;
};
class GfxDeviceGLES20 : public GfxDeviceFunctions {
    // ...
};</pre>
</div>
</div>
<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 &ldquo;this&rdquo; parameter; it&rsquo;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 &ldquo;this&rdquo; parameter directly:</p>
<div class="CodeRay">
<div class="code">
<pre>class GfxDeviceGLES20 : public GfxDeviceFunctions {
    // ...
    static void DrawImpl (GfxDevice* self, PrimitiveType prim, int primCount);
    // ...
};</pre>
</div>
</div>
<p>Code that uses it would look like this then:</p>
<div class="CodeRay">
<div class="code">
<pre>device-&gt;Draw (device, kPrimTriangles, 1337);</pre>
</div>
</div>
<p>and it would generate the following pseudo-assembly:</p>
<div class="CodeRay">
<div class="code">
<pre>drawlocation = device + 3*PointerSize
drawfunction = load pointer from [drawlocation] address
; wait 500 cycles until the pointer arrives
pass device pointer, kPrimTriangles and 1337 as arguments
call into code at [drawfunction] address
; wait 500 cycles until code at that address is loaded</pre>
</div>
</div>
<p>Look at that, one of &ldquo;wait 500 cycles&rdquo; is gone!</p>
<h3>More C style</h3>
<p>We could move function pointers outside of GfxDevice if we want to, and just make them global:<br /><img class="alignnone size-full wp-image-624" src="http://aras-p.info/blog/wp-content/uploads/2011/02/globalfuncs.png" height="358" alt="" style="padding: 0px" /></p>
<p>In GLES1.1 case, that global GfxDevice funcs block would point to different pieces of code. And the pseudocode for this:</p>
<div class="CodeRay">
<div class="code">
<pre>// global variables!
SetShaderFunc GfxSetShader;
SetTextureFunc GfxSetTexture;
SetGeometryFunc GfxSetGeometry;
DrawFunc GfxDraw;
// GLES2.0 implementation:
void GfxDrawGLES20 (GfxDevice* self, PrimitiveType prim, int primCount) { /*...*/ }</pre>
</div>
</div>
<p>Code that uses it:</p>
<div class="CodeRay">
<div class="code">
<pre>GfxDraw (device, kPrimTriangles, 1337);</pre>
</div>
</div>
<p>and the pseudo-assembly:</p>
<div class="CodeRay">
<div class="code">
<pre>drawfunction = load pointer from [GfxDraw variable] address
; wait 500 cycles until the pointer arrives
pass device pointer, kPrimTriangles and 1337 as arguments
call into code at [drawfunction] address
; wait 500 cycles until code at that address is loaded</pre>
</div>
</div>
<h3>Is it worth it?</h3>
<p>I can hear some saying, &ldquo;what? throwing away C++ OOP and implementing the same in almost raw C?! you&rsquo;re crazy!&rdquo;</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 &ldquo;wait 500 cycles&rdquo; 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&rsquo;ll know one of the many possible alternatives, right?</p>
<p>And yeah, another alternative that&rsquo;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&nbsp;<em>very</em>&nbsp;similar to the last approach of &ldquo;store function pointer table globally&rdquo;, except you&rsquo;d get some compiler syntax sugar to make it easier; and you wouldn&rsquo;t even need to load the code that is not going to be used.</p>
<p><em>This is a cross-post from my blog: <a href="http://aras-p.info/blog/2011/02/01/the-virtual-and-no-virtual/">http://aras-p.info/blog/2011/02/01/the-virtual-and-no-virtual/</a></em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/02/01/the-virtual-and-no-virtual/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>iOS shader tricks, or it’s 2001 all over again</title>
		<link>http://www.altdevblogaday.com/2011/01/18/ios-shader-tricks-or-its-2001-all-over-again/</link>
		<comments>http://www.altdevblogaday.com/2011/01/18/ios-shader-tricks-or-its-2001-all-over-again/#comments</comments>
		<pubDate>Tue, 18 Jan 2011 00:25:00 +0000</pubDate>
		<dc:creator>Aras Pranckevičius</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/2011/01/18/ios-shader-tricks-or-its-2001-all-over-again/</guid>
		<description><![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><a href="http://www.altdevblogaday.com/2011/01/18/ios-shader-tricks-or-its-2001-all-over-again/" class="more-link">Read more on iOS shader tricks, or it’s 2001 all over again&#8230;</a></p>
]]></description>
			<content:encoded><![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:<br />
<span id="more-303"></span><img src="http://altdevblogaday.com/wp-content/uploads/2011/01/1-200x300.jpg" alt="" width="200" height="300" /></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 naïve shader version:</p>
<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>
<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&#8242;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">https://gist.github.com/783703/05e78340b12739e853ce031bd0388430ea95f2a6</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">https://gist.github.com/783703/1e4fd0daa384d308d125a748985e8e203e49625a</a></p>
<p>15 milliseconds! But&#8230; the rendering is wrong; everything turned white near the bottom of the screen:</p>
<div><img src="http://altdevblogaday.com/wp-content/uploads/2011/01/3-200x300.jpg" alt="" width="200" height="300" /></div>
<p>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">https://gist.github.com/783703/591eb83dacaae3840cc4e4d3d8b95a4fc3abdd65</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">https://gist.github.com/783703/6360c2912b860aa30415e5120ef147169274cd71</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 128&#215;128 RGBA lookup texture and use that: <a href="https://gist.github.com/783703/87f1cf5529d644cab16123550e809e9f7598f4f3">https://gist.github.com/783703/87f1cf5529d644cab16123550e809e9f7598f4f3</a></p>
<p>A fast &amp; not super efficient code to create the lighting lookup texture for Blinn-Phong:</p>
<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>
<p><strong>9.1</strong> milliseconds! We lost some precision in the specular though (it&#8217;s dimmer):</p>
<div><img src="http://altdevblogaday.com/wp-content/uploads/2011/01/6-200x300.jpg" alt="" width="200" height="300" /></div>
<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">https://gist.github.com/783703/e24a2475fded83d2196372c8092a0d8de80a98eb</a></p>
<p>This is 8.3 milliseconds, or <strong>7.6</strong> milliseconds if we reduce our lighting texture resolution to 32&#215;128.</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>
<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>
<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 my blog: <a href="http://aras-p.info/blog/2011/02/01/ios-shader-tricks-or-its-2001-all-over-again/">http://aras-p.info/blog/2011/02/01/ios-shader-tricks-or-its-2001-all-over-again/</a></em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/01/18/ios-shader-tricks-or-its-2001-all-over-again/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 1.658 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2012-05-17 03:32:21 -->
<!-- Compression = gzip -->
