<?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>Olhovsky &#187; c#</title>
	<atom:link href="http://www.olhovsky.com/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.olhovsky.com</link>
	<description>Programming, meet art.</description>
	<lastBuildDate>Mon, 23 Jan 2012 05:19:58 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.2</generator>
		<item>
		<title>Avoiding garbage collections on the compact CLR.</title>
		<link>http://www.olhovsky.com/2011/03/avoiding-garbage-collections-on-the-compact-clr/</link>
		<comments>http://www.olhovsky.com/2011/03/avoiding-garbage-collections-on-the-compact-clr/#comments</comments>
		<pubDate>Wed, 30 Mar 2011 17:24:32 +0000</pubDate>
		<dc:creator>olhovsky</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[DBP2011]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[xbox]]></category>

		<guid isPermaLink="false">http://www.olhovsky.com/?p=513</guid>
		<description><![CDATA[I haven&#8217;t posted in a few days because I&#8217;ve been working on almost purely programming related tasks, which don&#8217;t lead to pretty screenshots. I&#8217;ve been improving the efficiency of the spatial partitioning scheme, and terrain draw args sorting. Today though, &#8230; <a href="http://www.olhovsky.com/2011/03/avoiding-garbage-collections-on-the-compact-clr/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I haven&#8217;t posted in a few days because I&#8217;ve been working on almost purely programming related tasks, which don&#8217;t lead to pretty screenshots. I&#8217;ve been improving the efficiency of the spatial partitioning scheme, and terrain draw args sorting.</p>
<p>Today though, I (re)wrote an object pool class.</p>
<p>Garbage collections are expensive on the compact CLR, they occur whenever 1MB of garbage is created, and cause noticeable stutter in the game when they happen. For this reason, I simply try not to generate any garbage.</p>
<p>Why we can&#8217;t just choose to have collections occur every 16MB or something, I don&#8217;t know.</p>
<p>I&#8217;ve written custom pools in various places in this project, because creating an efficient generic pool is tricky. Have a look at <a href="http://swampthingtom.blogspot.com/2007/06/generic-pool-collection-class.html">swampthingtom&#8217;s generic object pool</a>. It uses a struct as a container for each pooled item and can only pool types that meet the <code>new()</code> constraint (public parameterless constructor, and no abstract classes allowed).</p>
<p>Having to write a pool for every type though is slowing me down, so I spent some time today thinking about a good design for a generic object pool.</p>
<p>Giving up abstract classes (which is what swampthingtom does with his pool) is going a little too far for me. Also, a significant performance cost is associated with the use of that pool, which makes it less than ideal if you are using it to allocate hundreds of objects or more.</p>
<p><a href="http://blog.gallusgames.com/programming/lean-mean-object-pool-in-c">Here&#8217;s another approach</a>, which is minimalist, and still uses the new() constraint. This pool is clearly faster, but offers no way to iterate over over the collection of active pooled objects, and again, no abstract classes or constructors with parameters allowed. It&#8217;s also basically just an unsafe version of <a href="http://www.google.ca/url?sa=t&amp;source=web&amp;cd=3&amp;ved=0CCMQFjAC&amp;url=http%3A%2F%2Fmsdn.microsoft.com%2Fen-us%2Flibrary%2Fsystem.collections.stack.aspx&amp;ei=x7eUTeaWO9KN0QHDq5n1Cw&amp;usg=AFQjCNHuMdTjEHpoo12GMm5bl7cr6xf07A&amp;sig2=uqPYDg2YEgFDavbGqcZMmw">Stack</a> <img src='http://www.olhovsky.com/wp/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>So I wrote a pool that partitions an array into two parts, the first part for live objects, the second for dead objects. Then I effectively do what the compact CLR does with dead objects &#8212; sweep across the dead objects once in a while, and compact them into the second part of the array. As for object initialization, I pass the pool a Func delegate that does the initialization. Delegates are a little slow, but in this case they are called rarely &#8212; in fact, they should be called never, if I pick the right pool sizes. The code is barely tested so far and might benefit from another small optimization or two, but I&#8217;ll be sure to post it soonish. As usual, I&#8217;m also not fond of the idea of posting good code this far from the competition deadline.</p>
<p>By the way, <a href="http://stackoverflow.com/questions/5486654/allowing-iteration-without-generating-any-garbage/5487374">I fought with stackoverflow</a> to try to get some discussion going about ways to iterate over the pool without generating garbage. Most people did not want to hear about avoiding garbage creation. Eventually Eric Lippert came to the rescue and defended my question.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.olhovsky.com/2011/03/avoiding-garbage-collections-on-the-compact-clr/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Sky effect and bloom filter.</title>
		<link>http://www.olhovsky.com/2011/03/sky-effect-and-bloom-filter/</link>
		<comments>http://www.olhovsky.com/2011/03/sky-effect-and-bloom-filter/#comments</comments>
		<pubDate>Sat, 26 Mar 2011 07:55:58 +0000</pubDate>
		<dc:creator>olhovsky</dc:creator>
				<category><![CDATA[DBP2011]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[dream build play]]></category>

		<guid isPermaLink="false">http://www.olhovsky.com/?p=497</guid>
		<description><![CDATA[I&#8217;ve added a bloom filter, which every big title seems to use these days. The bloom filter takes the brightest parts of the image, blurs them, and mixes the result back into the scene. This makes lights glow, softens bright &#8230; <a href="http://www.olhovsky.com/2011/03/sky-effect-and-bloom-filter/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve added a bloom filter, which every big title seems to use these days.</p>
<p>The bloom filter takes the brightest parts of the image, blurs them, and mixes the result back into the scene. This makes lights glow, softens bright edges, and generally makes things look more natural.</p>
<p>Since there&#8217;s very little light you can&#8217;t notice the bloom so much, although it&#8217;s very obvious on the bottom center bar indicator. The rest of the HUD does not have the bloom applied to it.</p>
<p><a href="http://www.olhovsky.com/wp/wp-content/uploads/2011/03/march26_bloom_and_aurora_sky.png"><img class="aligncenter size-large wp-image-498" title="March 26 bloom and Aurora Borealis sky effect." src="http://www.olhovsky.com/wp/wp-content/uploads/2011/03/march26_bloom_and_aurora_sky-1024x598.png" alt="" width="640" height="373" /></a>The blue sky effect resembles an <a href="http://en.wikipedia.org/wiki/Aurora_(astronomy)">aurora</a> somewhat, and is animated. It&#8217;s obviously more interesting to see in motion than in this still picture.</p>
<p>Compare to this aurora below (courtesy wikipedia).</p>
<p style="text-align: center;">&nbsp;</p>
<div class="wp-caption aligncenter" style="width: 609px"><img class="     " title="Aurora Australis" src="http://upload.wikimedia.org/wikipedia/commons/thumb/6/63/Aurora_australis_panorama.jpg/800px-Aurora_australis_panorama.jpg" alt="" width="599" height="142" /><p class="wp-caption-text">Aurora Australis</p></div>
]]></content:encoded>
			<wfw:commentRss>http://www.olhovsky.com/2011/03/sky-effect-and-bloom-filter/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The CPU vs GPU XBOX360 speed disparity.</title>
		<link>http://www.olhovsky.com/2011/03/the-cpu-vs-gpu-xbox360-speed-disparity/</link>
		<comments>http://www.olhovsky.com/2011/03/the-cpu-vs-gpu-xbox360-speed-disparity/#comments</comments>
		<pubDate>Sun, 20 Mar 2011 00:19:42 +0000</pubDate>
		<dc:creator>olhovsky</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[DBP2011]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[xbox]]></category>

		<guid isPermaLink="false">http://www.olhovsky.com/?p=430</guid>
		<description><![CDATA[Today and yesterday I mostly worked on class work. Actually I mostly worked on a single assignment :/ However, I did find time to write the terrain chunk drawing loop, which implicitly builds a quadtree and tests at each recursive &#8230; <a href="http://www.olhovsky.com/2011/03/the-cpu-vs-gpu-xbox360-speed-disparity/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Today and yesterday I mostly worked on class work. Actually I mostly worked on a single assignment :/</p>
<p>However, I did find time to write the terrain chunk drawing loop, which implicitly builds a quadtree and tests at each recursive level the nodes of the tree against the camera frustum.</p>
<p>I discovered quickly that testing whether every single chunk is in the camera frustum or not is <em>very</em> expensive &#8212; 8 ms, which is half the time I have to do all draw thread computation at 60 fps.</p>
<p>In my <a title="Terrain started, and quadtree vs. block based LOD." href="http://www.olhovsky.com/2011/03/terrain-started/">previous terrain</a>, where I used a quadtree for each chunk, the number of tests to see if a chunk was in the frustum was bounded, since the quadtree didn&#8217;t need to recurse all of the way, if the entire terrain was visible, since further blocks would simply be drawn larger.</p>
<p>In the new chunk LOD method, in the worst case, the entire terrain is visible and all blocks need to be drawn and tested, which takes 8 milliseconds to check, using 64&#215;64 chunks and a 1024&#215;1024 terrain heightmap.</p>
<p>On the XBOX (using only 1 core), using XNA&#8217;s BoundingSphere and BoundingFrustum classes, I can do about 40,000 sphere/frustum tests per second (600-700 per frame).</p>
<p>The GPU can test whether a triangle is in the frustum on the order of 100,000,000 times per second (over 1 million per frame).</p>
<p>The terrain chunks I&#8217;m using are 64&#215;64 = 4096 triangles each. It is actually faster to send thousands of triangles to the GPU than to perform a single intersection test on the CPU. Unless of course, you&#8217;re GPU bound and have some CPU cycles to spare.</p>
<p>Exactly how my situation will turn out is to be determined, but I thought I&#8217;d emphasize just how large the processing speed difference is for this type of operation, between the CPU and the GPU on the XBOX with XNA.</p>
<p>In an effort to minimize the chunk drawing loop CPU time, I&#8217;ve also built a ReusableMinHeap class, which is a garbage-free min heap, which sorts the chunk draw calls for me from closest to furthest &#8212; to minimize overdraw. So far, it performs roughly the same as C#&#8217;s <a href="http://msdn.microsoft.com/en-us/library/8k6e334t.aspx">Array.Sort</a>, which uses quick sort.</p>
<p>I&#8217;ll be happy to share the min heap class when the competition is over. Someone remind me.</p>
<p>By the way, here&#8217;s what the chunk-LOD terrain looks like so far:</p>
<div id="attachment_440" class="wp-caption aligncenter" style="width: 650px"><a href="http://www.olhovsky.com/wp/wp-content/uploads/2011/03/march19_chunk_lod_terrain.png"><img class="size-large wp-image-440" title="Chunk LOD Terrain March 19" src="http://www.olhovsky.com/wp/wp-content/uploads/2011/03/march19_chunk_lod_terrain-1024x598.png" alt="" width="640" height="373" /></a><p class="wp-caption-text">The current state of the terrain as of March 19, 2011. Using 64x64 chunks and a 1024x1024 heightmap.</p></div>
]]></content:encoded>
			<wfw:commentRss>http://www.olhovsky.com/2011/03/the-cpu-vs-gpu-xbox360-speed-disparity/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Fields vs. properties performance on the Xbox 360.</title>
		<link>http://www.olhovsky.com/2010/04/fields-vs-properties-performance-on-the-xbox-360/</link>
		<comments>http://www.olhovsky.com/2010/04/fields-vs-properties-performance-on-the-xbox-360/#comments</comments>
		<pubDate>Sat, 17 Apr 2010 20:32:00 +0000</pubDate>
		<dc:creator>olhovsky</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[xbox]]></category>

		<guid isPermaLink="false">http://www.olhovsky.com/?p=140</guid>
		<description><![CDATA[I took Sam Allen&#8217;s performance test and ran a similar test (below) on the Xbox 360 with XNA. static string _backing; // Backing store for property static string Property // Getter and setter { get { return _backing; } set &#8230; <a href="http://www.olhovsky.com/2010/04/fields-vs-properties-performance-on-the-xbox-360/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I took <a href="http://dotnetperls.com/property-test">Sam Allen&#8217;s performance test</a> and ran a similar test (below) on the Xbox 360 with XNA.</p>
<pre class="brush:csharp">static string _backing; // Backing store for property
static string Property  // Getter and setter
{
    get
    {
        return _backing;
    }
    set
    {
        _backing = value;
    }
}
static string Field;    // Static field

public FieldPropertyTest(Game game)
    : base(game)
{

    long[] results1 = new long[10];
    long[] results2 = new long[10];

    Property = "string";
    Field = "string";
    const int m = 1000000;
    for (int x = 0; x &lt; 10; x++) // Ten tests
    {
        Stopwatch s1 = new Stopwatch();
        s1.Start();
        for (int i = 0; i &lt; m; i++) // Test property
        {
            Property = "string";
            //if (Property == "cat")
            //{
            //}
        }
        s1.Stop();
        Stopwatch s2 = new Stopwatch();
        s2.Start();
        for (int i = 0; i &lt; m; i++) // Test field
        {
            Field = "string";
            //if (Field == "cat")
            //{
            //}
        }
        s2.Stop();
        results1[x] = s1.ElapsedMilliseconds;
        results2[x] = s2.ElapsedMilliseconds;
    }
}</pre>
<p>The results:</p>
<p><strong>Get:</strong><br />
Property: 341 ms<br />
Field: 307 ms</p>
<p><strong>Set:</strong><br />
Property: 85 ms<br />
Field: 66 ms</p>
<p>This performance difference from the more robust .NET CLR used in Allen&#8217;s tests is owing to the fact that the .NET Compact CLR (which the Xbox 360 uses) doesn&#8217;t inline functions at all &#8212; to my knowledge.</p>
<p>Of course, the small size of the numbers above is good news &#8212; it took 10 million gets on a field to produce a 34ms difference.<br />
It&#8217;s hard to imagine a scenario where using a field in place of a property would be a relatively large enough performance gain to affect your framerate.</p>
<p>There are also the usual <a href="http://blogs.msdn.com/shawnhar/archive/2009/07/14/the-perils-of-microbenchmarking.aspx">caveats with micro-benchmarks</a> like these, and the difference may be smaller (or larger) than what you see above, in real-world uses.</p>
<p>So, I&#8217;d take <a href="http://www.codinghorror.com/blog/2006/08/properties-vs-public-variables.html">Jeff Atwood&#8217;s advice</a> and simply always use (auto-)properties, unless you have a very tight performance sensitive loop that is accessing many properties.</p>
<p>Edit:<br />
The <a href="http://blogs.msdn.com/b/netcfteam/archive/2006/12/22/managed-code-performance-on-xbox-360-for-the-xna-framework-1-0.aspx?wa=wsignin1.0">NetCF team blog</a> states that getters/setters are inlined, which is probably a source of some confusion. It&#8217;s also possible that my results above are wrong, if I&#8217;ve fallen into a micro benchmarking trap. Let me know if you find some results opposing what I&#8217;ve written above.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.olhovsky.com/2010/04/fields-vs-properties-performance-on-the-xbox-360/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>ToString Garbage Creation in C#</title>
		<link>http://www.olhovsky.com/2009/09/tostring-garbage-creation-in-c/</link>
		<comments>http://www.olhovsky.com/2009/09/tostring-garbage-creation-in-c/#comments</comments>
		<pubDate>Thu, 17 Sep 2009 05:24:39 +0000</pubDate>
		<dc:creator>olhovsky</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[garbage collector]]></category>

		<guid isPermaLink="false">http://www.olhovsky.com/?p=70</guid>
		<description><![CDATA[I profiled my XNA game project today using the XNA Framework Remote Perf Monitor and discovered that I was generating about 8000 more manage objects per second than I was expecting to. It turns out that this code was generating &#8230; <a href="http://www.olhovsky.com/2009/09/tostring-garbage-creation-in-c/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I profiled my XNA game project today using the XNA Framework Remote Perf Monitor and discovered that I was generating about 8000 more manage objects per second than I was expecting to.</p>
<p>It turns out that this code was generating 7400 managed objects per second:</p>
<pre class="brush:c#">            text[0] = "FPS: " + fps.FPS.ToString();
            text[1] = "charPos: " + charPos.ToString();
            text[2] = "tLOD: " + tLOD.ToString();
            text[3] = "tTris: " + tTris.ToString();
            text[4] = "tBlocksDrawn: " + tBlocksDrawn.ToString();
            text[5] = "tBlocksCulled: " + tBlocksCulled.ToString();
            text[6] = "drawCodeTime: " + drawCodeTime.ToString();
</pre>
<p>A complicated optimization for code that isn&#8217;t even going to get compiled into the release build would be silly. The easiest fix here is to only periodically update the content of these strings (say, once per second, instead of once per frame.)<br />
Also, some of the garbage generation could be reduced by separating the arrays into one array for the static strings &#8220;drawCodeTime: &#8221; for example and then drawCodeTime.ToString() in a separate string. That would still leave thousands of objects per second created, sadly.</p>
<p>If you have a game that relies on many string conversions, your best bet is to use StringBuilder objects (which have predefined size) and replace subsections of those strings with the new string using the .Replace method that StringBuilders have built-in.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.olhovsky.com/2009/09/tostring-garbage-creation-in-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

