<?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; Jason-Swearingen</title>
	<atom:link href="http://www.altdevblogaday.com/author/jason-swearingen/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>Getting started with Google App Engine (for .NET developers)</title>
		<link>http://www.altdevblogaday.com/2012/03/14/getting-started-with-google-app-engine-for-net-developers/</link>
		<comments>http://www.altdevblogaday.com/2012/03/14/getting-started-with-google-app-engine-for-net-developers/#comments</comments>
		<pubDate>Wed, 14 Mar 2012 04:49:09 +0000</pubDate>
		<dc:creator>Jason-Swearingen</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[google app engine]]></category>
		<category><![CDATA[intellij]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=24941</guid>
		<description><![CDATA[<p>Here at Novaleaf, we make consumer apps in addition to games. Our first web app is a <a href="http://www.cheap.co.th/" target="_blank">Thai specific computer hardware eCommerce web app</a> built on Google App Engine (GAE), using Java.</p>
<p><a href="http://www.altdevblogaday.com/2012/03/14/getting-started-with-google-app-engine-for-net-developers/" class="more-link">Read more on Getting started with Google App Engine (for .NET developers)&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Here at Novaleaf, we make consumer apps in addition to games. Our first web app is a <a href="http://www.cheap.co.th/" target="_blank">Thai specific computer hardware eCommerce web app</a> built on Google App Engine (GAE), using Java.</p>
<p>I&#8217;m historically (and well, currently) a .NET developer, but find the idea of a GAE based game server platform intriguing. But hey, I&#8217;m pretty much a 1 trick pony: &#8220;C# or nuthin.&#8221; (I can write C++ but hate it), so how do I get into the world of &#8220;weird&#8221; java buzzwords like servlets and WAR, in addition to the platform specific knowledge that makes up GAE?</p>
<p>One way would be to force one of Novaleaf&#8217;s webdevs to sit down and teach me. I might just do that, but&#8230; after I give it a try myself.   Here&#8217;s the steps I took to learn GAE&#8217;s basics, and get a &#8220;hello world&#8221; app running. I hope it&#8217;s useful for other .NET developers looking to expand their skills in a relatively painless way.</p>
<h2><strong>First: Get a high-level picture.</strong></h2>
<p><strong></strong><br />
I skimmed <a href="http://code.google.com/appengine/docs/" target="_blank">Google&#8217;s online resources about GAE and it&#8217;s various features</a>. and learned from a high-level what GAE can and can not do, and what it will be able to do in the near future.  I prefer to do this high-level overview first to frame the capabilities of the platform, so later when doing in-depth tutorials I can frame the knowledge in context to how it&#8217;d fit into my project&#8217;s needs.</p>
<p>I was a bit surprised about how well described it is, at least relative to <a href="http://www.oracle.com/technetwork/java/index.html" target="_blank">Sun&#8217;s Java/Javadoc references</a>. I am sure that for Java developers, the documentation is perfectly fine&#8230; but for people starting out, it&#8217;s a bit painful to figure out the difference between J2SE, J2EE, that Java &#8220;2&#8243; is actually v1.2, etc etc&#8230;  Anyway, no need to go into that here, right ;)</p>
<h2><strong>Second:  will GAE do what I need?</strong></h2>
<p>Once I understand the general capabilities of GAE, I ask myself if it will do what I need?   Well, I have a ton of ideas floating in my head, but to put this in perspective for a &#8220;simple game server&#8221; here&#8217;s some key points:</p>
<ol>
<li>GAE scales very well with multiple users (each request is on a separate thread)</li>
<li>Storing intra-gamestate will be too expensive (GAE stores all state in database, so high-frequency read/writes will be monetarily expensive)</li>
<li>Storing macro-level metagame information (low-frequency user information and matchmaking data) seems to be a good match for GAE&#8217;s feature set</li>
<li>Per-user server polling is the only viable option for GAE right now  (<a href="http://code.google.com/appengine/docs/features.html" target="_blank">a socket api is in development</a> but not yet ready)</li>
<li>Threading is not supported right now (in development) so no multithreaded fancyness is available.</li>
<li>Supports <a href="http://code.google.com/appengine/docs/java/xmpp/overview.html" target="_blank">XMPP</a> based chat protocol</li>
<li>To summarize, GAE seems suitable for synchronizing with users every few minutes, so for savegame, matchmaking, topscores, achievements, etc.    but not for high-frequency use .</li>
</ol>
<div></div>
<div>So this is all fine by me.   Current GAE features seems to restrict my game-use to matchmaking services only, though if I want to get creative with the XMPP functionality, it may be possible to introduce a high-latency gamestate server, though the adding of sockets to GAE in the future also looks promising.</div>
<div></div>
<h2><strong>Third: Find a good book.</strong></h2>
<p><strong></strong><br />
I searched amazon for the highest rated books on the matter, and settled with &#8220;<a href="http://www.amazon.com/Programming-Google-App-Engine-Infrastructure/dp/059652272X/ref=sr_1_1?ie=UTF8&amp;qid=1331610310&amp;sr=8-1" target="_blank">Programming Google App Engine</a>&#8220;.</p>
<p><img class="alignnone" src="http://ecx.images-amazon.com/images/I/51nR64klqWL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA300_SH20_OU01_.jpg" alt="" width="180" height="180" /></p>
<p>I am currently on chapter 2 of this book, following the tutorials to put together a &#8220;hello world&#8221;.  Seems good, however their explanations detail using <a href="http://www.eclipse.org/" target="_blank">Eclipse</a>,  which is nice and all (and free) but not realy that user friendly to .NET developers comfortable with Visual Studio.</p>
<h2><strong>Fourth: Setting up the right tools</strong></h2>
<p>I did some research as to the most visual-studio-like java IDE, and came up with <a href="http://www.jetbrains.com/idea/" target="_blank">IntelliJ</a>.  Their Ultimate Edition also comes with GAE and <a href="http://code.google.com/webtoolkit/" target="_blank">Google Web Toolkit</a> integration, so seems great to me.     I&#8217;ll quickly summarize the steps I take to get the tools setup:</p>
<ol>
<li>Install Java6 JDK from Sun&#8217;s website (J2SE x64 is what I used) <a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html">http://www.oracle.com/technetwork/java/javase/downloads/index.html</a>  Note that you must use v6.x with GAE</li>
<li>Install IntelliJ Ultimate (11.x is what i used)</li>
<li>Download and extract the GAE SDK to some reference folder on your HD:   <a href="http://code.google.com/appengine/downloads.html#Google_App_Engine_SDK_for_Java">http://code.google.com/appengine/downloads.html#Google_App_Engine_SDK_for_Java</a></li>
</ol>
<div></div>
<p>Run IntelliJ and create a new project with the following options:</p>
<ol>
<li>Setup a new project (Java Module)</li>
<li>Under technologies, choose &#8220;Google App Engine&#8221;, choose the right SDK dir that you extracted the GAE SDK to.</li>
<li>If not set, point JDK dir to the <strong>program files\java\jdk1.6.x</strong> dir  (File&#8211;&gt;Project Structure&#8211;&gt;Project)</li>
<li>Add J2EE servlet references:  File&#8211;&gt;ProjectStructure&#8211;&gt;Libraries&#8211;&gt;AppEngine API&#8211;&gt;Classes-&gt;Attach Directory:   “<strong>%PATH_TO_APP_ENGINE_API%\lib\shared</strong>”  also add <strong>\lib\orm\</strong> and <strong>\lib\user\</strong> and <strong>\lib\</strong></li>
<li>Add GAE Javadocs for inline documentation:   File&#8211;&gt;ProjectStructure&#8211;&gt;Libraries&#8211;&gt;AppEngine API&#8211;&gt;Specify Documentation URL&#8211;&gt;“<a href="http://code.google.com/appengine/docs/java/javadoc/">http://code.google.com/appengine/docs/java/javadoc/</a>” also add “<a href="http://docs.oracle.com/cd/E17410_01/javaee/6/api/">http://docs.oracle.com/cd/E17410_01/javaee/6/api/</a>” for the shared library stuff, as GAE ships with parts of J2EE, but without the docs of it, so you have to point to Sun&#8217;s docs instead.</li>
<li>Reconfigure Intellij for non-case-sensitive autocomplete: File&#8211;&gt;Settings&#8211;&gt;Editor&#8211;&gt;Code Completion&#8211;&gt;Case Sensitive completion&#8211;&gt;None</li>
<li>seems that the basic dir layout isn&#8217;t compatible with GAE.  move the META-INF dir to be under the src dir</li>
<li>For JPA persistence to work (needed for the book&#8217;s tutorials) you must change some settings:   File&#8211;&gt;Project Structure&#8211;&gt;Modules&#8211;&gt;Web&#8211;&gt;GAE.  Check &#8220;Run Enhancer&#8221; and set the persistence options to JPA.</li>
</ol>
<p>After that, you should be able to follow the tutorials as shown in the Book I mentioned earlier, or get started with <a href="http://code.google.com/appengine/docs/java/gettingstarted/creating.html" target="_blank">google&#8217;s own tutorials</a>.</p>
<h2><strong>Summary:  Pretty easy!</strong></h2>
<p>In total, I spent about 3 days figuring out these details and finish up my first &#8220;hello world&#8221; app and getting it published on GAE.   If this information proves useful (or not), please leave a comment.  I&#8217;d love to hear.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2012/03/14/getting-started-with-google-app-engine-for-net-developers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Architect a Worker Thread subsystem, step-by-step (C#)</title>
		<link>http://www.altdevblogaday.com/2011/09/22/how-to-architect-a-worker-thread-subsystem-step-by-step-csharp/</link>
		<comments>http://www.altdevblogaday.com/2011/09/22/how-to-architect-a-worker-thread-subsystem-step-by-step-csharp/#comments</comments>
		<pubDate>Thu, 22 Sep 2011 16:21:49 +0000</pubDate>
		<dc:creator>Jason-Swearingen</dc:creator>
				<category><![CDATA[#gamedev]]></category>
		<category><![CDATA[Education]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[multithreading]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://altdevblogaday.com/?p=16550</guid>
		<description><![CDATA[<p><strong>Introduction</strong><br />
I have just completed rewriting of our &#8220;worker thread&#8221; execution subsystem, fixing some obscure race conditions, and wanted to share the solution in a &#8220;step by step&#8221; approach.</p>
<p><strong>Primary Aim: <em>(education)</em></strong><br />
to provide practical knowledge to those recently entered into the &#8220;system parallelization&#8221; field. I will describe the multithread relevent design process that went into the design and development of <a href="http://www.novaleaf.com">Novaleaf</a>&#8216;s new WorkerThread subsystem.<br />
<span id="more-16550"></span></p>
<p><a href="http://www.altdevblogaday.com/2011/09/22/how-to-architect-a-worker-thread-subsystem-step-by-step-csharp/" class="more-link">Read more on How to Architect a Worker Thread subsystem, step-by-step (C#)&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong><br />
I have just completed rewriting of our &#8220;worker thread&#8221; execution subsystem, fixing some obscure race conditions, and wanted to share the solution in a &#8220;step by step&#8221; approach.</p>
<p><strong>Primary Aim: <em>(education)</em></strong><br />
to provide practical knowledge to those recently entered into the &#8220;system parallelization&#8221; field. I will describe the multithread relevent design process that went into the design and development of <a href="http://www.novaleaf.com">Novaleaf</a>&#8216;s new WorkerThread subsystem.<br />
<span id="more-16550"></span></p>
<p><strong>First step, what&#8217;s the goal? <em>(use case scenario)</em></strong><br />
it&#8217;s very important for any development (not just multithreading) to fully understand your &#8220;functional objectives&#8221; before starting to architect, and then to architect your system (high-level design) before you code.</p>
<p><em>Here is my scenario:</em><br />
Synchronization between a &#8220;main engine thread&#8221; and a reusable &#8220;worker thread&#8221; subsystem. main and worker threads should execute loops at a 1:1 frequency, with the start/end of the worker thread&#8217;s loop tied to a specific part of the engine&#8217;s loop code.</p>
<p><em>illustration of the scenario:</em><br />
<a href="http://altdevblogaday.com/wp-content/uploads/2011/09/altDevdiagramworkerthread.png"><img class="alignnone size-full wp-image-16564" src="http://altdevblogaday.com/wp-content/uploads/2011/09/altDevdiagramworkerthread.png" alt="Worker Thread Workflow Diagram" width="563" height="759" /></a></p>
<p><strong>High level design:</strong></p>
<ol>
<li>&#8220;engine wait for worker&#8221;: need main thread sync-point to wait for worker to finish</li>
<li>&#8220;worker wait for engine&#8221;: need worker to wait until main thread resumes worker (starts next loop)</li>
<li>&#8220;others wait for worker&#8221; also need other systems to be able to wait for worker to finish. an example is if there is a shared resource that multiple threads access.</li>
<li>Worker owns it&#8217;s own thread:  The worker runs in an infinite loop, pausing when waiting for the engine (<em>Design point #2</em>).</li>
<li>Keep it stupid simple!  There are many ways I could sexify (complicate) this setup, but there are three reasons why i do not:
<ol>
<li>Educational purposes</li>
<li>Complex thread synchronization has bugs (race conditions)</li>
<li>&#8220;I use this in real life&#8221; (it works)</li>
</ol>
</li>
</ol>
<p><strong>Implementation Phase 1: <em>(identify existing solutions)</em></strong></p>
<p><em>Design point #2</em>,<br />
&#8220;worker wait for engine&#8221; shows that to fulfill this functionality, only 1 thread (worker) needs to wait for the main engine thread. In this case, the <a href="http://en.wikipedia.org/wiki/Base_Class_Library" target="_blank">.NET BCL</a> class <a href="http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx" target="_blank">AutoResetEvent </a>works nicely because it will allow a single waiter (the worker) through when the main thread says it&#8217;s ready (signals).</p>
<blockquote><p><code><br />
//**worker loop, (full workflow)**<br />
while(true){<br />
//wait for engine to allow this worker to start it's next loop<br />
waitForEngine_AutoResetEvent.WaitOne();</p>
<p>//do fancy asynchronous work here!</p>
<p>//worker informs engine that it is finished<br />
waitForWorker_ManualResetEvent.Set();<br />
}</code></p></blockquote>
<p>Above is the worker thread&#8217;s loop. it waits for the engine to signal it to proceed, does work, then informs the engine that it&#8217;s finished.</p>
<p>Now for what the engine&#8217;s code (partially) looks like:</p>
<blockquote><p><code>//**engine thread**<br />
//allow 1 waiting thread through,<br />
//or if none are waiting, exactly 1 future caller through<br />
//then automatically (instantly) resets to blocking.<br />
waitForEngine_AutoResetEvent.Set();</code></p></blockquote>
<p>We can not use ManualResetEvent because we need to call .Set() and .Reset() independently:</p>
<blockquote><p><code>//**engine thread with race condition (bad)**<br />
//allow waiting code through<br />
waitForEngine_ManualResetEvent.Set();<br />
//set to blocking<br />
waitForEngine_ManualResetEvent.Reset();</code></p></blockquote>
<p>This doesn&#8217;t work because of the situation when worker has called <code>waitForWorker_ManualResetEvent.Set();</code> but has not yet looped back and made the <code>.WaitOne()</code> call. the worker&#8217;s execution may be suspended between those two lines, and thus the engine may itself .Set() and .Reset() before the worker even gets to the next line. It sounds unlikely, and it is, but it is not safe (it may fail 1 out of 1 million times).</p>
<p><em>Design point #1</em>,<br />
&#8220;engine wait for worker&#8221;: we could get by with the design point #2 solution &#8220;AutoResetEvent&#8221; stated above, however we need to consider <em>Design point #3</em>.</p>
<p><em>Design point #3</em>,<br />
&#8220;others wait for worker&#8221;: because of this, the AutoResetEvent solution doesn&#8217;t work.</p>
<blockquote><p><code>//fails because only the first waiter will be allowed through<br />
//multiple systems may wait on the worker thread completing.<br />
waitForWorker_AutoResetEvent.WaitOne();</code></p></blockquote>
<p>however we also can not use the <em>ManualResetEvent</em>, because of the problem already outlined above in Design point#2.<br />
If you look at the other classes in the .NET BCL System.Threading namespace, none of those seem to be a good fit for this problem. So looks like we need to write our own synchronization primitive!</p>
<p><strong>Implementation Phase 2: <em>(rethinking the problem)</em></strong></p>
<p>To recap, we need a synchronization primitive similar to AutoResetEvent, however needs to only reset (block future calles) after the main engine thread finishes waiting. All threads, including the engine, should unblock once the worker thread&#8217;s loop completes.</p>
<p>After thinking through the problem, it turns out we actually DO NOT need anything more complex than ManualResetEvent for the engine-wait-on-worker. here&#8217;s why:</p>
<ol>
<li>if our worker calls <code>waitForWorker_ManualResetEvent.Set()</code> then all waiting threads will clear, and all future waits will clear</li>
<li>if the engine calls <code>waitForWorker_ManualResetEvent.Reset()</code> after waiting for the worker to finish but <em>before</em> launching the worker&#8217;s next loop, then the engine&#8217;s target workflow is preserved.</li>
<li><strong>Here&#8217;s the kicker:</strong> if other threads wait on the worker, they will suffer race conditions (example: worker&#8217;s next loop starts before the other thread&#8217;s call to .WaitOne() even finishes). <em>Thus this workflow is unsupported. Other threads must synchronize with main, not with workers.</em></li>
</ol>
<p><strong>Implementation Phase 3: <em>(Final take away)</em></strong><br />
Please pay special attention to my &#8220;<strong>Here&#8217;s the kicker</strong>&#8221; list-item above. This shows that while my initial thoughts were to allow any &#8220;other thread&#8221; to synchronize with the worker thread, this requirement would have resulted in the construction of a custom (and complex) synchronization primitive. Also, on closer inspection this seems to be a significantly troubling <a href="http://en.wikipedia.org/wiki/Anti-pattern" target="_blank">anti-pattern</a> which should consciously be avoided.</p>
<blockquote><p><code><br />
//**main thread, (full workflow)**<br />
void Engine_UpdateTheWorker(float time)<br />
{<br />
//wait for worker's previous loop to finish<br />
waitForWorker_manualResetEvent.WaitOne();<br />
//reset our worker's waitEvent back to blocking<br />
waitForWorker_manualResetEvent.Reset();</p>
<p>//do data synchronization<br />
workerLoopTime=time;</p>
<p>//signal our worker to start it's next loop<br />
waitForEngine_autoResetEvent.Set();<br />
}</code></p></blockquote>
<p>Above is the full implementation of the engine&#8217;s synchronization code.  This and the worker&#8217;s loop code further above is copy-paste-programmer friendly for those looking to quickly utilize the architecture I have provided.</p>
<p><strong>Conclusion: <em>really really try not to re-invent the wheel.</em></strong><br />
There certainly will be times where the base synchronization primitives will not be enough to get the job done, but with the .NET 4.0 BCL System.Threading additions, those will (should) be few and far between. I hope that this step-by-step on the process I went through for re-designing Novaleaf&#8217;s WorkerThread subsystem helps illustrate this point.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/09/22/how-to-architect-a-worker-thread-subsystem-step-by-step-csharp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MapFold: Simplifying Inter-Thread Communication.</title>
		<link>http://www.altdevblogaday.com/2011/04/22/mapfold-simplifying-inter-thread-communication/</link>
		<comments>http://www.altdevblogaday.com/2011/04/22/mapfold-simplifying-inter-thread-communication/#comments</comments>
		<pubDate>Fri, 22 Apr 2011 01:05:05 +0000</pubDate>
		<dc:creator>Jason-Swearingen</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=4433</guid>
		<description><![CDATA[<p>Being Novaleaf&#8217;s core engine architect, I try to identify problematic workflows and figure out an existing design pattern to apply, or construct a new one.</p>
<p>Since we&#8217;ve been parallelizing our engine, one problem I keep seeing pop up is how to manage inter-thread communications: everyone does it differently, and in doing so, has to rewrite the basic data workflow and synchronization (and do so in their own unique way)  Due to the subtle nature of race-conditions, this is especially dangerous.</p>
<p><a href="http://www.altdevblogaday.com/2011/04/22/mapfold-simplifying-inter-thread-communication/" class="more-link">Read more on MapFold: Simplifying Inter-Thread Communication&#8230;.</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Being Novaleaf&#8217;s core engine architect, I try to identify problematic workflows and figure out an existing design pattern to apply, or construct a new one.</p>
<p>Since we&#8217;ve been parallelizing our engine, one problem I keep seeing pop up is how to manage inter-thread communications: everyone does it differently, and in doing so, has to rewrite the basic data workflow and synchronization (and do so in their own unique way)  Due to the subtle nature of race-conditions, this is especially dangerous.</p>
<p>So, I set about designing a solution.  My original solution was called &#8220;PushProcess&#8221; but after doing some searches on wikipedia for naming conventions, I have renamed it to &#8220;MapFold&#8221; (not to be confused with Google&#8217;s <a href="http://en.wikipedia.org/wiki/MapReduce" target="_blank">MapReduce</a>).</p>
<p><strong>Workflow Diagram</strong></p>
<p>&nbsp;</p>
<p><a href="http://altdevblogaday.com/wp-content/uploads/2011/04/MapFold-Workflow-1.png"><img class="alignnone size-full wp-image-4465" src="http://altdevblogaday.com/wp-content/uploads/2011/04/MapFold-Workflow-1.png" alt="Novaleaf's MapFold Workflow" width="891" height="633" /></a></p>
<p><strong>Data Transformation</strong></p>
<p><em><strong>MapFold </strong></em>is an abstract class, thus derived classes are required to add their own custom Map and Fold computational algorithm, giving clear mechanisms for data transformation.</p>
<ul>
<li><strong><a href="http://en.wikipedia.org/wiki/Map_(higher-order_function)" target="_blank">Map()</a></strong> allows data being input from the User threads to be transformed immediately (on the same thread).</li>
<li><strong><a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)" target="_blank">Fold()</a></strong> allows enqueued data to be transformed by the Owner thread before or during consumption.</li>
</ul>
<p>The primary benefit of all of this is encapsulation of all this data transformation logic in a single location (the derived class) and providing an obvious extensibility point for performing these transformations.</p>
<p>Another major benefit of <em><strong>MapFold </strong></em>is the encapsulation and reuse of enqueue/dequeue/synchronization logic.</p>
<p><strong>Source Code (C#)</strong></p>
<p>&nbsp;</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// Design Pattern for Multithread data synchronization/communication</span>
<span style="color: #008080; font-style: italic;">/// &lt;para&gt;this base class provides the workflow for enqueueing data (&lt;see cref=&quot;TInput&quot;/&gt;) from multiple threads, </span>
<span style="color: #008080; font-style: italic;">/// and preparing (transforming to &lt;see cref=&quot;TIntermediate&quot;/&gt; via the Map method) it for use by this class's owner </span>
<span style="color: #008080; font-style: italic;">/// (usually a system on a &lt;see cref=&quot;WorkerThread&quot;/&gt; but not required). &lt;/para&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;para&gt;the data can be transformed at 2 positions: </span>
<span style="color: #008080; font-style: italic;">/// &lt;para&gt;&lt;see cref=&quot;TInput&quot;/&gt; --&gt; &lt;see cref=&quot;TIntermediate&quot;/&gt;:  first by the &lt;see cref=&quot;Map&quot;/&gt; method </span>
<span style="color: #008080; font-style: italic;">/// (which occurs immediatly upon invocation on the same thread as the caller)&lt;/para&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;para&gt;&lt;see cref=&quot;TIntermediate&quot;/&gt; --&gt; output (custom): second, </span>
<span style="color: #008080; font-style: italic;">/// when the &lt;see cref=&quot;Fold&quot;/&gt;() method is invoked (by the owner), </span>
<span style="color: #008080; font-style: italic;">/// additional data transformations may occur. </span>
<span style="color: #008080; font-style: italic;">/// the output data from this &lt;see cref=&quot;Fold&quot;/&gt;() method depends on the descendant </span>
<span style="color: #008080; font-style: italic;">/// class overriding this abstract method. &lt;/para&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;para&gt; See the &lt;see cref=&quot;FrameState&quot;/&gt; class for an example usage (enqueing framestate changes every frame to worker threads)&lt;/para&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;typeparam name=&quot;TInput&quot;&gt;&lt;/typeparam&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;typeparam name=&quot;TIntermediate&quot;&gt;intermediate data type written by &lt;see cref=&quot;Map&quot;/&gt;() and processed by &lt;see cref=&quot;Fold&quot;/&gt;()&lt;/typeparam&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;remarks&gt;&lt;/remarks&gt;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> abstract <span style="color: #6666cc; font-weight: bold;">class</span> MapFold_Example<span style="color: #008000;">&lt;</span>TInput, TIntermediate<span style="color: #008000;">&gt;</span>
<span style="color: #008000;">&#123;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// for internal thread safety use only.</span>
	<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
	<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">object</span> _lock <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// calls to the &lt;see cref=&quot;Map&quot;/&gt;() method enqueue to this.  (locked so threadsafe)</span>
	<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
	<span style="color: #0600FF; font-weight: bold;">private</span> Queue<span style="color: #008000;">&lt;</span>TIntermediate<span style="color: #008000;">&gt;</span> mapQueue <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Queue<span style="color: #008000;">&lt;</span>TIntermediate<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// calls to &lt;see cref=&quot;Fold&quot;/&gt;() consume this.  (we swap-buffer with &lt;see cref=&quot;mapQueue&quot;/&gt; every call so this is threadsafe consumption)</span>
	<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
	<span style="color: #0600FF; font-weight: bold;">private</span> Queue<span style="color: #008000;">&lt;</span>TIntermediate<span style="color: #008000;">&gt;</span> foldQueue <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Queue<span style="color: #008000;">&lt;</span>TIntermediate<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// thread-safe enqueue &lt;see cref=&quot;TInput&quot;/&gt; for consumption by this object owner.</span>
	<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;input&quot;&gt;&lt;/param&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;remarks&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;para&gt;input will be transformed to &lt;see cref=&quot;TIntermediate&quot;/&gt; during this method call.&lt;/para&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;para&gt;http://en.wikipedia.org/wiki/Map_(higher-order_function)&lt;/para&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;/remarks&gt;</span>
	<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Map<span style="color: #008000;">&#40;</span>TInput input<span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		TIntermediate intermediate<span style="color: #008000;">;</span>
		Map<span style="color: #008000;">&#40;</span>input, <span style="color: #0600FF; font-weight: bold;">out</span> intermediate<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #0600FF; font-weight: bold;">lock</span> <span style="color: #008000;">&#40;</span>_lock<span style="color: #008000;">&#41;</span>
		<span style="color: #008000;">&#123;</span>
			<span style="color: #008080; font-style: italic;">//only the actual enqueue is inside the lock to minimize waits by multiple threads</span>
			mapQueue<span style="color: #008000;">.</span><span style="color: #0000FF;">Enqueue</span><span style="color: #008000;">&#40;</span>intermediate<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #008000;">&#125;</span>
	<span style="color: #008000;">&#125;</span>
&nbsp;
	<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// override this method to transform &lt;see cref=&quot;input&quot;/&gt; --&gt; &lt;see cref=&quot;intermediate&quot;/&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;input&quot;&gt;&lt;/param&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;intermediate&quot;&gt;&lt;/param&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;remarks&gt;this work occurs on the user's thread (the &quot;external&quot; execution calling &lt;see cref=&quot;Map&quot;/&gt;)&lt;/remarks&gt;</span>
	<span style="color: #0600FF; font-weight: bold;">protected</span> abstract <span style="color: #6666cc; font-weight: bold;">void</span> Map<span style="color: #008000;">&#40;</span>TInput input, <span style="color: #0600FF; font-weight: bold;">out</span> TIntermediate intermediate<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Fold<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		Fold<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">default</span><span style="color: #008000;">&#40;</span>Action<span style="color: #008000;">&lt;</span>Queue<span style="color: #008000;">&lt;</span>TIntermediate<span style="color: #008000;">&gt;&gt;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #008000;">&#125;</span>
&nbsp;
	<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// start computations on all currently enqueued &lt;see cref=&quot;TIntermediate&quot;/&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;para&gt;this should be invoked by this object's 'owner', probably once per frame.&lt;/para&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;foldDelegate&quot;&gt;if you pass a delegate, this will be executed first, before the internal Fold implementation (if any)&lt;/param&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;remarks&gt;http://en.wikipedia.org/wiki/Fold_(higher-order_function)&lt;/remarks&gt;</span>
	<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Fold<span style="color: #008000;">&#40;</span>Action<span style="color: #008000;">&lt;</span>Queue<span style="color: #008000;">&lt;</span>TIntermediate<span style="color: #008000;">&gt;&gt;</span> foldDelegate<span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
&nbsp;
		<span style="color: #0600FF; font-weight: bold;">lock</span> <span style="color: #008000;">&#40;</span>_lock<span style="color: #008000;">&#41;</span>
		<span style="color: #008000;">&#123;</span>
			var temp <span style="color: #008000;">=</span> foldQueue<span style="color: #008000;">;</span>
			foldQueue <span style="color: #008000;">=</span> mapQueue<span style="color: #008000;">;</span>
			mapQueue <span style="color: #008000;">=</span> temp<span style="color: #008000;">;</span>
		<span style="color: #008000;">&#125;</span>
		<span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>foldDelegate <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
		<span style="color: #008000;">&#123;</span>
			foldDelegate<span style="color: #008000;">&#40;</span>foldQueue<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #008000;">&#125;</span>
		Fold<span style="color: #008000;">&#40;</span>foldQueue<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
		foldQueue<span style="color: #008000;">.</span><span style="color: #0000FF;">Clear</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #008000;">&#125;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// override this method to specify implementation for the &lt;see cref=&quot;Fold&quot;/&gt;() method.</span>
	<span style="color: #008080; font-style: italic;">/// &lt;para&gt; start computations on all currently enqueued &lt;see cref=&quot;TIntermediate&quot;/&gt;&lt;/para&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;para&gt;this should be invoked by this object's 'owner', probably once per frame.&lt;/para&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;intermediateQueue&quot;&gt;all currently enqueued values sent via the &lt;see cref=&quot;Map&quot;/&gt;() method (after being transformed &lt;see cref=&quot;TInput&quot;/&gt; --&gt; &lt;see cref=&quot;TIntermediate&quot;/&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;para&gt;usage note: this queue will automatically be cleared after this method completes&lt;/para&gt;&lt;/param&gt;</span>
	<span style="color: #0600FF; font-weight: bold;">protected</span> abstract <span style="color: #6666cc; font-weight: bold;">void</span> Fold<span style="color: #008000;">&#40;</span>Queue<span style="color: #008000;">&lt;</span>TIntermediate<span style="color: #008000;">&gt;</span> intermediateQueue<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// an &quot;easy to use&quot; concrete class that allows the min-workflow of MapFold </span>
<span style="color: #008080; font-style: italic;">/// without the need to create your own custom class</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;typeparam name=&quot;TValue&quot;&gt;&lt;/typeparam&gt;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> MapFold_Example<span style="color: #008000;">&lt;</span>TValue<span style="color: #008000;">&gt;</span> <span style="color: #008000;">:</span> MapFold_Example<span style="color: #008000;">&lt;</span>TValue, TValue<span style="color: #008000;">&gt;</span>
<span style="color: #008000;">&#123;</span>
	<span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">override</span> <span style="color: #6666cc; font-weight: bold;">void</span> Fold<span style="color: #008000;">&#40;</span>Queue<span style="color: #008000;">&lt;</span>TValue<span style="color: #008000;">&gt;</span> intermediateQueue<span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #008080; font-style: italic;">//no op (owner class can interact with the intermediateQueue through the value returned by the base class's .Fold() method.</span>
	<span style="color: #008000;">&#125;</span>
	<span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">override</span> <span style="color: #6666cc; font-weight: bold;">void</span> Map<span style="color: #008000;">&#40;</span>TValue input, <span style="color: #0600FF; font-weight: bold;">out</span> TValue intermediate<span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #008080; font-style: italic;">//no work: intermediate is of same type/value as enqueued via the original call to the base class's .Map() method</span>
		intermediate <span style="color: #008000;">=</span> input<span style="color: #008000;">;</span>
	<span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>&nbsp;</p>
<p><strong>An Example</strong></p>
<p>Instead of explaining why this is better than continuously &#8220;rolling your own&#8221;, I&#8217;ll give an example system using this <em><strong>MapFold </strong></em>workflow:</p>
<p>&nbsp;</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// This example shows a straight forward and simple way to synchronize </span>
<span style="color: #008080; font-style: italic;">/// multithread communication to a render system.</span>
<span style="color: #008080; font-style: italic;">/// &lt;para&gt;For the sake of simplicity, some optimizations were omitted </span>
<span style="color: #008080; font-style: italic;">/// (such as reduction of value-type copies, etc).&lt;/para&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> RenderManager_Example
<span style="color: #008000;">&#123;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// intermediate data type</span>
	<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
	<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">struct</span> RenderTransaction
	<span style="color: #008000;">&#123;</span>
		<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">enum</span> TransactionStatus
		<span style="color: #008000;">&#123;</span>
			Alloc,
			Free,
			Modify,
		<span style="color: #008000;">&#125;</span>
&nbsp;
		<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
		<span style="color: #008080; font-style: italic;">/// transaction being done</span>
		<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
		<span style="color: #0600FF; font-weight: bold;">public</span> TransactionStatus transaction<span style="color: #008000;">;</span>
		<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
		<span style="color: #008080; font-style: italic;">/// object reference for internal render tracking and external coordination.</span>
		<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
		<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> objectId<span style="color: #008000;">;</span>
		<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
		<span style="color: #008080; font-style: italic;">/// world transform</span>
		<span style="color: #008080; font-style: italic;">/// &lt;para&gt;set when transaction==Alloc|Modify&lt;/para&gt;</span>
		<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
		<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">object</span> xform<span style="color: #008000;">;</span>
		<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
		<span style="color: #008080; font-style: italic;">/// asset used by this object.</span>
		<span style="color: #008080; font-style: italic;">/// &lt;para&gt;set when transaction==Alloc&lt;/para&gt;</span>
		<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
		<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> assetId<span style="color: #008000;">;</span>
	<span style="color: #008000;">&#125;</span>
&nbsp;
	<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// an instance of our mapFold for this renderManager</span>
	<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
	<span style="color: #0600FF; font-weight: bold;">private</span> MapFold_Example<span style="color: #008000;">&lt;</span>RenderTransaction<span style="color: #008000;">&gt;</span> mapFold<span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF; font-weight: bold;">public</span> RenderManager_Example<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		mapFold <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> MapFold_Example<span style="color: #008000;">&lt;</span>RenderTransaction<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #008000;">&#125;</span>
&nbsp;
	<span style="color: #008080;">#region public (thread safe) methods</span>
	<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// allocate space in our render system for a new object</span>
	<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;assetId&quot;&gt;asset this object uses&lt;/param&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;objectId&quot;&gt;id for our object&lt;/param&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;xform&quot;&gt;starting world transform&lt;/param&gt;</span>
	<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Alloc<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> assetId, <span style="color: #6666cc; font-weight: bold;">int</span> objectId, <span style="color: #6666cc; font-weight: bold;">object</span> xform<span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #008080; font-style: italic;">//invoke our base class's mapFold.Map() which does a thread-safe FIFO enqueue</span>
		mapFold<span style="color: #008000;">.</span><span style="color: #0000FF;">Map</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> RenderTransaction<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
			<span style="color: #008000;">&#123;</span>
				assetId <span style="color: #008000;">=</span> assetId,
				objectId <span style="color: #008000;">=</span> objectId,
				xform <span style="color: #008000;">=</span> xform,
				transaction <span style="color: #008000;">=</span> RenderTransaction<span style="color: #008000;">.</span><span style="color: #0000FF;">TransactionStatus</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Alloc</span>
			<span style="color: #008000;">&#125;</span>
								<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #008000;">&#125;</span>
&nbsp;
	<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// remove the object from rendering</span>
	<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;objectId&quot;&gt;&lt;/param&gt;</span>
	<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Free<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> objectId<span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #008080; font-style: italic;">//invoke our base class's mapFold.Map() which does a thread-safe FIFO enqueue</span>
		mapFold<span style="color: #008000;">.</span><span style="color: #0000FF;">Map</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> RenderTransaction<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
			<span style="color: #008000;">&#123;</span>
				objectId <span style="color: #008000;">=</span> objectId,
				transaction <span style="color: #008000;">=</span> RenderTransaction<span style="color: #008000;">.</span><span style="color: #0000FF;">TransactionStatus</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Free</span>
			<span style="color: #008000;">&#125;</span>
			<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #008000;">&#125;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// change this object's runtime render properties</span>
	<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;objectId&quot;&gt;&lt;/param&gt;</span>
	<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;xform&quot;&gt;&lt;/param&gt;</span>
	<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Modify<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> objectId, <span style="color: #6666cc; font-weight: bold;">object</span> newXform<span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #008080; font-style: italic;">//invoke our base class's mapFold.Map() which does a thread-safe FIFO enqueue</span>
		mapFold<span style="color: #008000;">.</span><span style="color: #0000FF;">Map</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> RenderTransaction<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
		<span style="color: #008000;">&#123;</span>
			objectId <span style="color: #008000;">=</span> objectId,
			xform <span style="color: #008000;">=</span> newXform,
			transaction <span style="color: #008000;">=</span> RenderTransaction<span style="color: #008000;">.</span><span style="color: #0000FF;">TransactionStatus</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Modify</span>
		<span style="color: #008000;">&#125;</span>
		<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #008000;">&#125;</span>
&nbsp;
	<span style="color: #008080;">#endregion</span>
&nbsp;
	<span style="color: #008080;">#region private worker methods (execute during the RenderManger's .Update(), which is assumed to execute on it's own thread)</span>
&nbsp;
	<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> Owner_ProcessTransactions<span style="color: #008000;">&#40;</span>Queue<span style="color: #008000;">&lt;</span>RenderTransaction<span style="color: #008000;">&gt;</span> toProcess<span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #008080; font-style: italic;">//does a FIFO enumeration of enqueued data (from .Map()</span>
		<span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>var renderTransaction <span style="color: #0600FF; font-weight: bold;">in</span> toProcess<span style="color: #008000;">&#41;</span>
		<span style="color: #008000;">&#123;</span>
			<span style="color: #0600FF; font-weight: bold;">switch</span> <span style="color: #008000;">&#40;</span>renderTransaction<span style="color: #008000;">.</span><span style="color: #0000FF;">transaction</span><span style="color: #008000;">&#41;</span>
			<span style="color: #008000;">&#123;</span>
				<span style="color: #0600FF; font-weight: bold;">case</span> RenderTransaction<span style="color: #008000;">.</span><span style="color: #0000FF;">TransactionStatus</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Alloc</span><span style="color: #008000;">:</span>
					Owner_Alloc<span style="color: #008000;">&#40;</span>renderTransaction<span style="color: #008000;">.</span><span style="color: #0000FF;">assetId</span>, renderTransaction<span style="color: #008000;">.</span><span style="color: #0000FF;">objectId</span>, renderTransaction<span style="color: #008000;">.</span><span style="color: #0000FF;">xform</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
					<span style="color: #0600FF; font-weight: bold;">break</span><span style="color: #008000;">;</span>
				<span style="color: #0600FF; font-weight: bold;">case</span> RenderTransaction<span style="color: #008000;">.</span><span style="color: #0000FF;">TransactionStatus</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Free</span><span style="color: #008000;">:</span>
					Owner_Free<span style="color: #008000;">&#40;</span>renderTransaction<span style="color: #008000;">.</span><span style="color: #0000FF;">objectId</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
					<span style="color: #0600FF; font-weight: bold;">break</span><span style="color: #008000;">;</span>
				<span style="color: #0600FF; font-weight: bold;">case</span> RenderTransaction<span style="color: #008000;">.</span><span style="color: #0000FF;">TransactionStatus</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Modify</span><span style="color: #008000;">:</span>
					Owner_Modify<span style="color: #008000;">&#40;</span>renderTransaction<span style="color: #008000;">.</span><span style="color: #0000FF;">objectId</span>, renderTransaction<span style="color: #008000;">.</span><span style="color: #0000FF;">xform</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
					<span style="color: #0600FF; font-weight: bold;">break</span><span style="color: #008000;">;</span>
				<span style="color: #0600FF; font-weight: bold;">default</span><span style="color: #008000;">:</span>
					<span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> NotSupportedException<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
			<span style="color: #008000;">&#125;</span>
		<span style="color: #008000;">&#125;</span>
	<span style="color: #008000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> Owner_Alloc<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> assetId, <span style="color: #6666cc; font-weight: bold;">int</span> objectId, <span style="color: #6666cc; font-weight: bold;">object</span> xform<span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #008080; font-style: italic;">//allocate a slot in our render system</span>
	<span style="color: #008000;">&#125;</span>
	<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> Owner_Free<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> objectId<span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #008080; font-style: italic;">//delete the object from our render system</span>
	<span style="color: #008000;">&#125;</span>
	<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> Owner_Modify<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> objectId, <span style="color: #6666cc; font-weight: bold;">object</span> xform<span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #008080; font-style: italic;">//modify position of existing object in our render system</span>
	<span style="color: #008000;">&#125;</span>
	<span style="color: #008080;">#endregion</span>
&nbsp;
	<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
	<span style="color: #008080; font-style: italic;">/// this .Update() method is meant to be executed in our render thread</span>
	<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
	<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Update<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #008080; font-style: italic;">//FIFO execution of enqueued .Map() data (Alloc,Modify,Free)</span>
		mapFold<span style="color: #008000;">.</span><span style="color: #0000FF;">Fold</span><span style="color: #008000;">&#40;</span>Owner_ProcessTransactions<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
		<span style="color: #008080; font-style: italic;">//draw goes here</span>
	<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>&nbsp;</p>
<p>&nbsp;</p>
<p><strong>So is this unique?</strong></p>
<p>I am under the impression that while this workflow is certainly not unique, few encapsulate this pattern into a discrete object.  What about you?  Do you do something similar?  Lets discuss in the comments!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/04/22/mapfold-simplifying-inter-thread-communication/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Lock-Free Queue</title>
		<link>http://www.altdevblogaday.com/2011/03/09/lock-free-queue/</link>
		<comments>http://www.altdevblogaday.com/2011/03/09/lock-free-queue/#comments</comments>
		<pubDate>Wed, 09 Mar 2011 08:02:08 +0000</pubDate>
		<dc:creator>Jason-Swearingen</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=1639</guid>
		<description><![CDATA[<p>Multithreading is hard, and unless you have years of experience (and/or lots of patience debugging) <a href="http://www.parlezuml.com/blog/?postid=715">you should NEVER write your own synchronization primitives</a>.</p>
<p>So to help out all the &#8220;async noobs&#8221;, here is my C#  implementation of an <a href="http://www.research.ibm.com/people/m/michael/podc-1996.pdf">excellent lock-free queue paper</a>.</p>
<p><a href="http://www.altdevblogaday.com/2011/03/09/lock-free-queue/" class="more-link">Read more on Lock-Free Queue&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Multithreading is hard, and unless you have years of experience (and/or lots of patience debugging) <a href="http://www.parlezuml.com/blog/?postid=715">you should NEVER write your own synchronization primitives</a>.</p>
<p>So to help out all the &#8220;async noobs&#8221;, here is my C#  implementation of an <a href="http://www.research.ibm.com/people/m/michael/podc-1996.pdf">excellent lock-free queue paper</a>.</p>
<p>If you don&#8217;t know what a &#8220;lock-free&#8221; algorithm is, this code is really not for your consumption, as it is going to be a bit too advanced.  If you are an &#8216;asynchronous beginner&#8217; or even an expert, the best book on the subject I&#8217;ve seen is &#8220;<a href="http://www.amazon.com/Art-Multiprocessor-Programming-Maurice-Herlihy/dp/0123705916/ref=pd_sim_b_1">The Art of Multiprocessor Programming</a>&#8221; so give that a read.</p>
<p>And yes, this is in C#.  If you are a C/C++ developer, weep your bitter tears  :)</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">	<span style="color: #008080; font-style: italic;">///</span>
	<span style="color: #008080; font-style: italic;">/// A lock-free queue.</span>
	<span style="color: #008080; font-style: italic;">///</span>
Usage Note<span style="color: #008000;">:</span> thread safe, fast performance
	<span style="color: #008080; font-style: italic;">///</span>
	<span style="color: #008080; font-style: italic;">/// by jason swearingen, copyright novaleaf software.  all rights reserved.</span>
	<span style="color: #008080; font-style: italic;">///</span>
Released under the MSPL<span style="color: #008000;">:</span> http<span style="color: #008000;">:</span><span style="color: #008080; font-style: italic;">//www.opensource.org/licenses/ms-pl</span>
	<span style="color: #008080; font-style: italic;">///</span>
idea <span style="color: #008000;">/</span> core algorithm taken <span style="color: #0600FF; font-weight: bold;">from</span> http<span style="color: #008000;">:</span><span style="color: #008080; font-style: italic;">//www.research.ibm.com/people/m/michael/podc-1996.pdf</span>
	<span style="color: #008080; font-style: italic;">/// inline comments are direct transcriptions of this paper's psudocode (thus this queue is virtually a 1:1 implementation of this awesome paper)</span>
	<span style="color: #008080; font-style: italic;">///</span>
	<span style="color: #008080; font-style: italic;">///</span>
	<span style="color: #008000;">&#91;</span>ThreadSafe<span style="color: #008000;">&#93;</span>
	<span style="color: #008000;">&#91;</span>DebuggerStepThrough<span style="color: #008000;">&#93;</span>
	<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> SafeQueue
	<span style="color: #008000;">&#123;</span>
		<span style="color: #008080; font-style: italic;">//structure pointer t fptr: pointer to node t, count: unsigned integerg</span>
		<span style="color: #008080; font-style: italic;">//structure node t fvalue: data type, next: pointer tg</span>
		<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">class</span> Node
		<span style="color: #008000;">&#123;</span>
			<span style="color: #0600FF; font-weight: bold;">public</span> Node next<span style="color: #008000;">;</span>
			<span style="color: #0600FF; font-weight: bold;">public</span> T value<span style="color: #008000;">;</span>
		<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #008080;">#if DEBUG</span>
		<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">int</span> Count
		<span style="color: #008000;">&#123;</span>
			get
			<span style="color: #008000;">&#123;</span>
&nbsp;
				<span style="color: #0600FF; font-weight: bold;">return</span> _count<span style="color: #008000;">;</span>
&nbsp;
			<span style="color: #008000;">&#125;</span>
		<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #008080;">#endif</span>
&nbsp;
		<span style="color: #008080; font-style: italic;">//structure queue t fHead: pointer t, Tail: pointer tg</span>
		<span style="color: #0600FF; font-weight: bold;">private</span> Node _head, _tail<span style="color: #008000;">;</span>
&nbsp;
		<span style="color: #0600FF; font-weight: bold;">public</span> SafeQueue<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
		<span style="color: #008000;">&#123;</span>
			<span style="color: #008080; font-style: italic;">//initialize(Q: pointer to queue t)</span>
			<span style="color: #008080; font-style: italic;">//node = new node() # Allocate a free node</span>
			<span style="color: #008080; font-style: italic;">//node–&gt;next.ptr = NULL # Make it the only node in the linked list</span>
			<span style="color: #008080; font-style: italic;">//Q–&gt;Head = Q–&gt;Tail = node # Both Head and Tail point to it</span>
			_head <span style="color: #008000;">=</span> _tail <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Node<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #008000;">&#125;</span>
&nbsp;
		<span style="color: #0600FF; font-weight: bold;">private</span> volatile <span style="color: #6666cc; font-weight: bold;">int</span> _count <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
&nbsp;
		<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">bool</span> IsEmpty
		<span style="color: #008000;">&#123;</span>
			get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> _count <span style="color: #008000;">==</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
		<span style="color: #008000;">&#125;</span>
&nbsp;
		<span style="color: #008080; font-style: italic;">//enqueue(Q: pointer to queue t, value: data type)</span>
&nbsp;
		<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">virtual</span> <span style="color: #6666cc; font-weight: bold;">void</span> Enqueue<span style="color: #008000;">&#40;</span>T value<span style="color: #008000;">&#41;</span>
		<span style="color: #008000;">&#123;</span>
			Enqueue<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">ref</span> value<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #008000;">&#125;</span>
&nbsp;
		<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">virtual</span> <span style="color: #6666cc; font-weight: bold;">void</span> Enqueue<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">ref</span> T value<span style="color: #008000;">&#41;</span>
		<span style="color: #008000;">&#123;</span>
&nbsp;
			<span style="color: #008080; font-style: italic;">//E1: node = new node() # Allocate a new node from the free list</span>
			<span style="color: #008080; font-style: italic;">//E2: node–&gt;value = value # Copy enqueued value into node</span>
			<span style="color: #008080; font-style: italic;">//E3: node–&gt;next.ptr = NULL # SafeSet next pointer of node to NULL</span>
			Node toAdd <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Node<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
			toAdd<span style="color: #008000;">.</span><span style="color: #0000FF;">value</span> <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span>
			Node tail <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">;</span>
			Node temp<span style="color: #008000;">;</span>
&nbsp;
			<span style="color: #008080; font-style: italic;">//E4: loop # Keep trying until Enqueue is done</span>
			<span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">&#41;</span>
			<span style="color: #008000;">&#123;</span>
				<span style="color: #008080; font-style: italic;">//E5: tail = Q–&gt;Tail # Read Tail.ptr and Tail.count together</span>
				<span style="color: #008080; font-style: italic;">//E6: next = tail.ptr–&gt;next # Read next ptr and count fields together</span>
				tail <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span>_tail<span style="color: #008000;">;</span>
				Node next <span style="color: #008000;">=</span> tail<span style="color: #008000;">.</span><span style="color: #0000FF;">next</span><span style="color: #008000;">;</span>
&nbsp;
				<span style="color: #008080; font-style: italic;">//E7: if tail == Q–&gt;Tail # Are tail and next consistent?</span>
				<span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>Node<span style="color: #008000;">.</span><span style="color: #0000FF;">ReferenceEquals</span><span style="color: #008000;">&#40;</span>tail, <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span>_tail<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
				<span style="color: #008000;">&#123;</span>
					<span style="color: #008080; font-style: italic;">//E8: if next.ptr == NULL # Was Tail pointing to the last node?</span>
					<span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>next <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
					<span style="color: #008000;">&#123;</span>
						<span style="color: #008080; font-style: italic;">//E9: if CAS(&amp;tail.ptr–&gt;next, next, ) # Try to link node at the end of the linked list</span>
						temp <span style="color: #008000;">=</span> Interlocked<span style="color: #008000;">.</span><span style="color: #0000FF;">CompareExchange</span><span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">ref</span> tail<span style="color: #008000;">.</span><span style="color: #0000FF;">next</span>, toAdd, next<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
						<span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>Node<span style="color: #008000;">.</span><span style="color: #0000FF;">ReferenceEquals</span><span style="color: #008000;">&#40;</span>temp, next<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
						<span style="color: #008000;">&#123;</span>
							<span style="color: #008080; font-style: italic;">//E10: break # Enqueue is done. Exit loop</span>
							<span style="color: #0600FF; font-weight: bold;">break</span><span style="color: #008000;">;</span>
							<span style="color: #008080; font-style: italic;">//E11: endif</span>
						<span style="color: #008000;">&#125;</span>
&nbsp;
					<span style="color: #008000;">&#125;</span><span style="color: #008080; font-style: italic;">//E12: else # Tail was not pointing to the last node</span>
					<span style="color: #0600FF; font-weight: bold;">else</span>
					<span style="color: #008000;">&#123;</span>
						<span style="color: #008080; font-style: italic;">//E13: CAS(&amp;Q–&gt;Tail, tail, ) # Try to swing Tail to the next node for try again</span>
						Interlocked<span style="color: #008000;">.</span><span style="color: #0000FF;">CompareExchange</span><span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">ref</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span>_tail, next, tail<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
						<span style="color: #008080; font-style: italic;">//E14: endif</span>
					<span style="color: #008000;">&#125;</span>
					<span style="color: #008080; font-style: italic;">//E15: endif</span>
				<span style="color: #008000;">&#125;</span>
				<span style="color: #008080; font-style: italic;">//E16: endloop</span>
			<span style="color: #008000;">&#125;</span>
			<span style="color: #008080; font-style: italic;">//E17: CAS(&amp;Q–&gt;Tail, tail, ) # Enqueue is done. Try to swing Tail to the inserted node</span>
			Interlocked<span style="color: #008000;">.</span><span style="color: #0000FF;">CompareExchange</span><span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">ref</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span>_tail, toAdd, tail<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
			Interlocked<span style="color: #008000;">.</span><span style="color: #0000FF;">Increment</span><span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">ref</span> _count<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
		<span style="color: #008000;">&#125;</span>
&nbsp;
		<span style="color: #008080; font-style: italic;">//dequeue(Q: pointer to queue t, pvalue: pointer to data type): boolean</span>
		<span style="color: #008080; font-style: italic;">///</span>
		<span style="color: #008080; font-style: italic;">///</span>
		<span style="color: #008080; font-style: italic;">///</span>
		<span style="color: #008080; font-style: italic;">///</span>
&nbsp;
		<span style="color: #008080; font-style: italic;">/// false if unable to dequeue</span>
		<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">virtual</span> <span style="color: #6666cc; font-weight: bold;">bool</span> Dequeue<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">out</span> T value<span style="color: #008000;">&#41;</span>
		<span style="color: #008000;">&#123;</span>
&nbsp;
			<span style="color: #008080; font-style: italic;">//D1: loop # Keep trying until Dequeue is done</span>
			<span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">&#41;</span>
			<span style="color: #008000;">&#123;</span>
				<span style="color: #008080; font-style: italic;">//D2: head = Q–&gt;Head # Read Head</span>
				<span style="color: #008080; font-style: italic;">//D3: tail = Q–&gt;Tail # Read Tail</span>
				<span style="color: #008080; font-style: italic;">//D4: next = head–&gt;next # Read Head.ptr–&gt;next</span>
				Node head <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span>_head<span style="color: #008000;">;</span>
				Node tail <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span>_tail<span style="color: #008000;">;</span>
				Node next <span style="color: #008000;">=</span> head<span style="color: #008000;">.</span><span style="color: #0000FF;">next</span><span style="color: #008000;">;</span>
				Node temp<span style="color: #008000;">;</span>
&nbsp;
				<span style="color: #008080; font-style: italic;">//D5: if head == Q–&gt;Head # Are head, tail, and next consistent?</span>
				<span style="color: #008080; font-style: italic;">//if (Node.ReferenceEquals(head, this._head))</span>
				<span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>head <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span>_head<span style="color: #008000;">&#41;</span>
				<span style="color: #008000;">&#123;</span>
					<span style="color: #008080; font-style: italic;">//D6: if head.ptr == tail.ptr # Is queue empty or Tail falling behind?</span>
					<span style="color: #008080; font-style: italic;">//if (Node.ReferenceEquals(head, tail))</span>
					<span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>head <span style="color: #008000;">==</span> tail<span style="color: #008000;">&#41;</span>
					<span style="color: #008000;">&#123;</span>
						<span style="color: #008080; font-style: italic;">//D7: if next.ptr == NULL # Is queue empty?</span>
						<span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>next <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
						<span style="color: #008000;">&#123;</span>
							<span style="color: #008080; font-style: italic;">//D8: return FALSE # Queue is empty, couldn’t dequeue</span>
							value <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">default</span><span style="color: #008000;">&#40;</span>T<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
							<span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">;</span>
							<span style="color: #008080; font-style: italic;">//D9: endif</span>
						<span style="color: #008000;">&#125;</span>
						<span style="color: #008080; font-style: italic;">//D10: CAS(&amp;Q–&gt;Tail, tail, ) # Tail is falling behind. Try to advance it</span>
						Interlocked<span style="color: #008000;">.</span><span style="color: #0000FF;">CompareExchange</span><span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">ref</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span>_tail, next, tail<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
						<span style="color: #008080; font-style: italic;">//D11: else # No need to deal with Tail</span>
					<span style="color: #008000;">&#125;</span>
					<span style="color: #0600FF; font-weight: bold;">else</span>
					<span style="color: #008000;">&#123;</span>
						<span style="color: #008080; font-style: italic;">//# Read value before CAS, otherwise another dequeue might free the next node</span>
						<span style="color: #008080; font-style: italic;">//D12: *pvalue = next.ptr–&gt;value</span>
						value <span style="color: #008000;">=</span> next<span style="color: #008000;">.</span><span style="color: #0000FF;">value</span><span style="color: #008000;">;</span>
						<span style="color: #008080; font-style: italic;">//D13: if CAS(&amp;Q–&gt;Head, head, ) # Try to swing Head to the next node</span>
						temp <span style="color: #008000;">=</span> Interlocked<span style="color: #008000;">.</span><span style="color: #0000FF;">CompareExchange</span><span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">ref</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span>_head, next, head<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
						<span style="color: #008080; font-style: italic;">//if (Node.ReferenceEquals(temp, head))</span>
						<span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>temp <span style="color: #008000;">==</span> head<span style="color: #008000;">&#41;</span>
						<span style="color: #008000;">&#123;</span>
							<span style="color: #008080; font-style: italic;">//D14: break # Dequeue is done. Exit loop</span>
							<span style="color: #0600FF; font-weight: bold;">break</span><span style="color: #008000;">;</span>
							<span style="color: #008080; font-style: italic;">//D15: endif</span>
						<span style="color: #008000;">&#125;</span>
&nbsp;
						<span style="color: #008080; font-style: italic;">//D16: endif</span>
					<span style="color: #008000;">&#125;</span>
					<span style="color: #008080; font-style: italic;">//D17: endif</span>
				<span style="color: #008000;">&#125;</span>
				<span style="color: #008080; font-style: italic;">//D18: endloop</span>
			<span style="color: #008000;">&#125;</span>
&nbsp;
			Interlocked<span style="color: #008000;">.</span><span style="color: #0000FF;">Decrement</span><span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">ref</span> _count<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
			<span style="color: #008080; font-style: italic;">//D19: free(head.ptr) # It is safe now to free the old dummy node</span>
			<span style="color: #008080; font-style: italic;">//D20: return TRUE # Queue was not empty, dequeue succeeded</span>
			<span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">;</span>
&nbsp;
		<span style="color: #008000;">&#125;</span>
&nbsp;
	<span style="color: #008000;">&#125;</span></pre></div></div>

<p>If you are using .NET 4.0, you probably don&#8217;t need this, as<a href="http://msdn.microsoft.com/en-us/library/dd460693.aspx"> TPF has a lot of great (new) synchronization primitives.</a> But if you don&#8217;t use .NET 4, or if you really want to learn how to create a great lock-free algorithm, this is my contribution to you :)</p>
<h3>alright!  Ending, I have an appology.</h3>
<p>I&#8217;ve been busy the last 2 weeks on <a href="http://www.game-connection.com/">GC</a> demos and<a href="http://dreambuildplay.com/"> DBP</a> entry designs.  So my part 2 of <a href="http://altdevblogaday.com/2011/02/21/spatial-partitioning-part-1-survey-of-spatial-partitioning-solutions/">Spatial Partitions</a> will have to wait for my next post.  Hope you enjoy<a href="http://en.wikipedia.org/wiki/Thread_safety"> thread-safety</a> and thus can forgive me :)</p>
<h3>Got any questions/concerns/complains!  COMMENT BELOW!</h3>
<h4><span style="color: #808080">About the author:</span></h4>
<p><span style="color: #808080">Jason Swearingen is Technical Director at <a title="Novaleaf Game Studios" href="http://www.novaleaf.com/">Novaleaf Game Studios</a> (in Bangkok Thailand).<br />
You can reach Jason via email (<strong>jasons </strong>aat <strong>novaleaf </strong>doot coom), or twitter (<strong>@jasons_novaleaf</strong>).</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/03/09/lock-free-queue/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Spatial Partitioning. Part 1: Survey of spatial partitioning solutions</title>
		<link>http://www.altdevblogaday.com/2011/02/21/spatial-partitioning-part-1-survey-of-spatial-partitioning-solutions/</link>
		<comments>http://www.altdevblogaday.com/2011/02/21/spatial-partitioning-part-1-survey-of-spatial-partitioning-solutions/#comments</comments>
		<pubDate>Mon, 21 Feb 2011 16:49:36 +0000</pubDate>
		<dc:creator>Jason-Swearingen</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=984</guid>
		<description><![CDATA[<p><strong>A quick note:</strong></p>
<p>Being my second post here at #AltDevBlogADay, I was going to write about the commercial viability of XNA.  However I&#8217;m just finishing up the architecture of our new spatial partitioning system, so I&#8217;ll be doing this series first, while it&#8217;s still in my head :)</p>
<p><a href="http://www.altdevblogaday.com/2011/02/21/spatial-partitioning-part-1-survey-of-spatial-partitioning-solutions/" class="more-link">Read more on Spatial Partitioning. Part 1: Survey of spatial partitioning solutions&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p><strong>A quick note:</strong></p>
<p>Being my second post here at #AltDevBlogADay, I was going to write about the commercial viability of XNA.  However I&#8217;m just finishing up the architecture of our new spatial partitioning system, so I&#8217;ll be doing this series first, while it&#8217;s still in my head :)</p>
<h2>Spatial Partitioning Series!</h2>
<p>I&#8217;ll be spending the next two (or more) posts on spatial partitioning.  Starting this post is a quick survey of the spatial partitioning solutions I know most about.  If you have a favorite that I don&#8217;t mention, please do let me know in the comments!</p>
<h2>What&#8217;s spatial partitioning?</h2>
<p>For those of you who are not familiar with the subject, you are forgiven.  Spatial partitioning (quad trees and the such)  are not really known for being the sexiest part of game development, that honor goes towards rendering or perhaps AI.  However without a proper spatial partitioning choice, that awesome &#8220;moar bloom&#8221; being thrown at the screen runs into a brick wall trying to figure out what game objects are in the camera vs what is not.  That&#8217;s ultimately what spatial partitioning is all about:  reducing the cost of  finding objects you care about by storing objects in some sort of database that is easy to query by location.   Instead of going on-and-on about it, I&#8217;d refer the beginners to <a href="http://en.wikipedia.org/wiki/Space_partitioning">wikipedia </a>or perhaps the excellent &#8220;<a href="http://realtimecollisiondetection.net/">Real time collision detection</a>&#8221; book on the market (chapter 2 and 7 specifically).</p>
<h2>A Survey of the solutions</h2>
<p>Here&#8217;s a list of the various spatial partitioning systems that I happen to know about.  I consider myself fairly well versed in the subject, so if some guru&#8217;s happen to know of a gaping hole in my knowledge, please fill me in via the comments!</p>
<h3>Grid</h3>
<p>Perhaps the simplest solution, this is usually implemented via a 2 dimensional array.  3d grids are of course possible, but given that most 3d games have a generally 2d distribution, and the fact that 3d grids quickly eat your systems RAM, 2d is much, much more common.</p>
<p><strong>Usage Characteristics</strong></p>
<p>There are generally 2 ways of using grids:   Either each cell contains the objects who&#8217;s bounding volumes (usually sphere or box) are center positions are located in the cell, or contain all objects that touch the cell.   for the former case, the actual objects (and/or metadata) may be stored in the cell directly (allocated inline), or reference pointers are stored that point to the objects actual location.  For the Later case of each cell storing all intersections, you are restricted to the reference pointer case.</p>
<p><strong>Benefits / Drawbacks</strong></p>
<p>The greatest benefit of grids is their simplicity, and virtually 1:1 mapping to simple 2d arrays.  If you have a homogeneous or static world, grids may be a very excellent choice.</p>
<p>The greatest drawback is the inability to handle heterogeneous data: objects of various sizes and/or clumped distributions are huge problems that quickly ruin the elegance and performance of grids.</p>
<p>Benefits of cell inline allocation of objects is cache coherency, but since you have fixed cells allocated for the entire size of your world, you run the risk of each cell&#8217;s allocations being both too big and too small if your world&#8217;s objects are heterogeneously distributed.</p>
<p>A more exotic grid solutions include virtual grids, who&#8217;s backing database is a hashtable.  this reduces memory use but greatly increases the cost of queries, as multiple hash lookups need to made to find neighboring cells, plus memory fragmentation.</p>
<p>Grids also give good performance with dynamic objects, as due to it&#8217;s fixed-space nature, there is no re-partitioning needed (which is not true with most other solutions!)</p>
<h3>Quad Trees</h3>
<p><img class="thumbimage" src="http://upload.wikimedia.org/wikipedia/commons/thumb/8/8b/Point_quadtree.svg/300px-Point_quadtree.svg.png" alt="" width="300" height="300" /></p>
<p><a href="http://en.wikipedia.org/wiki/Quadtree">Quad trees</a> are one of the most natural extensions of grids, and are primarily designed to overcome grid&#8217;s biggest problems: heterogeneous sizes and distributions.   In the classical case, cells are replaced with &#8220;Nodes&#8221; (cells, but reference based, not fixed allocations/alignments), and nodes with two or more objects are sub-divided until only 1 object is in each of the &#8220;leaf&#8221; nodes.</p>
<p><strong>Usage Characteristics</strong></p>
<p>To enable elegant node sub-division, the center position of objects are used when determining ownership.   The simple case keeps dividing down to 1 object per node, but this is not strictly necessary, and is easily customizable, though if it is more efficient for you to query against 1000 objects in 1 node or 1000 nodes, is an exercise for the reader or perhaps someone else&#8217;s #AltDevBlogADay entry =D</p>
<p><strong>Benefits / Drawbacks</strong></p>
<p>Narrowly targeted queries are quite elegant, as walking from the root, you may reject large branches of the tree upon the parent failing to meet the query parameters.   Broad queries however, offer fairly poor performance, of requiring deep traversals of nodes.  For programming environments with a <a href="http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)">garbage collector</a> like .<a href="http://en.wikipedia.org/wiki/.NET_Framework">NET</a> or <a href="http://en.wikipedia.org/wiki/Java_(software_platform)">Java</a>, the reference-class overhead of the nodes is substantial and can be problematic (gc stalls when running a game is not good!).</p>
<p>As mentioned, the nodes are partitioned based on object centers, which is quite a large problem due to &#8220;external&#8221; objects that may potentially overlap your node-of-interest when performing collision detection.  Some exotic solutions such as storing pointers to neighboring nodes exist, but generally it&#8217;s a pain in the ass and quite weak performance for dynamic objects.  Another big weakness of trees are the need to repartition when dynamic objects move, the overhead of which can cripple highly dynamic simulations.</p>
<p>One potential benefit of trees is using the varied node sizes (nodes are cut in 4 each level) to bucket objects based on size.  This also helps reduce the complexity of handling overlapping nodes, but it&#8217;s still not a simple decision on how to handle this problem.  some choices push the objects up to the first node that entirely contains them, but unfortunately this tends to push a large number of objects all the way up to the root, due to objects overlapping the partition boundaries (as an example, consider an object at (0,0) in the picture shown above)</p>
<p>Often cited as a solution are &#8220;loose&#8221; quad trees, but I dislike these for the same reason I dislike the seemingly cool<a href="http://www.gamedev.net/topic/200191-sphere-tree/">sphere-tre</a>e: maintenance is a complicated mess and it&#8217;s not so obvious how to customize the &#8216;looseyness&#8217; to optimize performance in any given situation.</p>
<p>Another big caveat for quad trees is that they should not be used for heterogeneous distributions, as you will effectively have a cache-poor, pointer-based grid at the lowest level and a required tree-traversal on top.  Generally for heterogeneous distributions, you are better served by a grid.</p>
<p>Though I mention many drawbacks, trees aren&#8217;t that bad.  their memory savings compared to grids under &#8220;clustered distribution&#8221; situations is considerable, while offering fast coarse-granularity partitioning, and it&#8217;s darn <a href="http://digitseven.com/QuadTree.aspx">simple to implement</a>.</p>
<h3>Hierarchy Grids</h3>
<p>A cross between grids and a quad tree, think of it as pre-allocating all the nodes of a tree (whether they have objects in them or not).  So with the respect of  the two, they share the strengths and weaknesses of grids/trees based on these choices.  I won&#8217;t repeat them, you can simply read them above :)</p>
<p><strong>Benefits / Drawbacks</strong></p>
<p>Overall, I much prefer hierarchy grids over grids/trees, because the platforms I work on can afford the extra memory overhead, and it&#8217;s actually quite advantageous to pre-allocate for my platform of choice (<a href="http://en.wikipedia.org/wiki/Microsoft_XNA">XNA</a>/.NET) which reduces garbage collection pressure.</p>
<p>The biggest drawback to this is the expensive cost of querying empty cells.</p>
<h3>Kd Trees</h3>
<p><img class="thumbimage" src="http://upload.wikimedia.org/wikipedia/en/thumb/b/bf/Kdtree_2d.svg/300px-Kdtree_2d.svg.png" alt="" width="300" height="298" /></p>
<p><a href="http://en.wikipedia.org/wiki/K-d_tree">kd-trees</a> are kind of  the uber-spatial-optimization of quad trees, where instead of sub-dividing the world into fixed sized cells, the spaces are sized based on the objects located inside (at least where they were at time 0).</p>
<p><strong>Usage Characteristics</strong></p>
<p>Much the same as quad trees, except &#8220;faster&#8221; queries.  However special care has to be made on modifications, as fragmentation occurs and the tree will need to be rebalanced to maintain high performance.   Generally these are useful for offline pre-computation of static environments.</p>
<p><strong>Benefits / Drawbacks</strong></p>
<p>good for static environments (better than quad trees for localized, ray queries), but not the most trivial to implement, and is not a good choice for highly dynamic environments due to the additional costs of repartitioning.</p>
<p>Overall, the performance (and logic) is fairly close to quad trees. I dislike this choice because of the high repartitioning cost, and unlike a grid or quad tree, is a bit more difficult to debug.</p>
<h3>Zones/Rooms</h3>
<p>Some-what a &#8216;super partition&#8217;  strategy is to subdivide the world by &#8220;room&#8221;, often the dimensions of which are left up to content creators, and the connection of rooms performed by portals in addition to the potential for coordinate-system locality. A fairly well known example of this is the game <a href="http://www.google.com/search?q=the+continuous+world+of+dungeon+siege">dungeon siege</a>.</p>
<p><strong>Usage Characteristics</strong></p>
<p>While I have not personally experimented with this approach, it seems interesting.  Perhaps not the way as described in dungeon siege, but I could say this approach being useful for &#8220;zones&#8221; in the world-of-warcraft sense of the word: allowing each zone to be subdivided by it&#8217;s own partitioning system.</p>
<p>Also noted by the dungeon siege article is that there is a certain benefit to allowing artists to author the rooms, but also there is an incredible amount of complex infrastructure and toolsets that need to be developed to undertake their approach.    I would consider this to be fairly risky, and costly, and puts an emphasis on hand-tailored content, which is a luxury none but the most AAA projects can afford.</p>
<h3>Offset Hierarchy Grid (OHG)</h3>
<p>The OHG is what I just finished architecting for <a href="http://www.novaleaf.com/">Novaleaf&#8217;</a>s use.  It&#8217;s a hierarchy grid, with each level offset from the previous, to allow the benefits of &#8220;loosey&#8221; grids/trees without their unpredictable nature and maintenance overhead.</p>
<p>Usage-wise it&#8217;s &#8220;just a grid&#8221;, so gives the same benefits and tradeoffs.  However obviously since I just architected Novaleaf&#8217;s solution around the OHG, there must be some reason we went this approach, right?   well if you are reading this far, I&#8217;m sorry to disappoint, but this will be the subject of my next blog post(s)    Complain in the comments!!!</p>
<h4><span style="color: #999999">About the author:</span></h4>
<p><span style="color: #999999">Jason Swearingen is Technical Director at <a title="Novaleaf Game Studios" href="http://www.novaleaf.com/">Novaleaf Game Studios</a>.<br />
You can reach Jason via email (<strong>jasons </strong>aat <strong>novaleaf </strong>doot coom), or twitter (<strong>@jasons_novaleaf</strong>).</span></p>
<p><span style="color: #999999">PS: images courtesy of wikipedia</span></p>
<p><span style="color: #000000"><strong>PPS: anything you want to know about in detail?  again, let me know in the comments!!!</strong></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/02/21/spatial-partitioning-part-1-survey-of-spatial-partitioning-solutions/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Nobody Gives a Shit:  Introspections of a start-up indie studio’s dealings with publishers.</title>
		<link>http://www.altdevblogaday.com/2011/01/22/nobody-gives-a-shit-introspections-of-a-start-up-indie-studios-dealings-with-publishers/</link>
		<comments>http://www.altdevblogaday.com/2011/01/22/nobody-gives-a-shit-introspections-of-a-start-up-indie-studios-dealings-with-publishers/#comments</comments>
		<pubDate>Sat, 22 Jan 2011 07:47:08 +0000</pubDate>
		<dc:creator>Jason-Swearingen</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/2011/01/22/nobody-gives-a-shit-introspections-of-a-start-up-indie-studios-dealings-with-publishers/</guid>
		<description><![CDATA[<h2>Background: JasonS@ Novaleaf</h2>
<div>About 3 years ago, I was one of the founders of <a href="http://www.novaleaf.com" title="Novaleaf Game Studios">Novaleaf Game Studios</a>, a small (approx 10 members in the production team) studio in Bangkok Thailand, focusing on using <a href="http://en.wikipedia.org/wiki/Microsoft_XNA" title="XNA">XNA</a>&#160;as the development platform.</div>
<p><a href="http://www.altdevblogaday.com/2011/01/22/nobody-gives-a-shit-introspections-of-a-start-up-indie-studios-dealings-with-publishers/" class="more-link">Read more on Nobody Gives a Shit:  Introspections of a start-up indie studio’s dealings with publishers&#8230;.</a></p>
]]></description>
			<content:encoded><![CDATA[<h2>Background: JasonS@ Novaleaf</h2>
<div>About 3 years ago, I was one of the founders of <a href="http://www.novaleaf.com" title="Novaleaf Game Studios">Novaleaf Game Studios</a>, a small (approx 10 members in the production team) studio in Bangkok Thailand, focusing on using <a href="http://en.wikipedia.org/wiki/Microsoft_XNA" title="XNA">XNA</a>&nbsp;as the development platform.</div>
<p />
<div>Over time, our BizDev team has attended business matching events like <a href="http://www.game-connection.com/" title="Game Connection">Game Connection</a> and <a href="http://www.gamesconvention.com/" title="Games Convention">Games Convention</a>, in the USA, France, Germany, and Singapore, &nbsp;with me in attendance as the technical/design staff member. &nbsp;</div>
<p />
<div>So through my experiences, I have come to realize that dealing with publishers isn&#8217;t quite what you might expect, reading some common Game Project Management books on the market (or worse, reading what people ramble in online forums). &nbsp;Not that they get it &#8220;wrong&#8221; per-say, but the prioritization of tasks is incorrect. &nbsp;The closest I&#8217;ve seen to correct from a &#8220;what matters&#8221; perspective is the book <a href="http://www.amazon.com/Secrets-Game-Business-2nd-Ed/dp/1584503998/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1295674555&amp;sr=1-1" title="Secrets of the Game Business">Secrets of the Game Business</a>&#8216;s Chapter 2.1 list of <em>&#8220;Top 10 Misconceptions New Game Developers Have about Publishers&#8221;. &nbsp;</em>If you have a chance, get this book as it&#8217;s quite good.</div>
<h4>Before I go further, A bit of a disclaimer: &nbsp;</h4>
<div>My experiences and expectations are certainly colored by the types of games Novaleaf is developing (XBLA sized experiences for core gamers). &nbsp;Also, please keep in mind that when I say &#8220;startup indie studio&#8221; I really do mean&nbsp;<span style="text-decoration: underline;">STARTUP</span>&nbsp;and <span style="text-decoration: underline;">INDIE</span> in caps. &nbsp;Prior to Novaleaf I was a <a href="http://en.wikipedia.org/wiki/Rights_Management_Services" title="DRM">DRM</a>&nbsp;developer at Microsoft, and so without the support network of game-industry peers, I&#8217;m sure we had it rougher than others!</div>
<h2>Nobody gives a shit!</h2>
<div>Back to the title of this post: When dealing with publishers, you have to assume that nobody gives a shit, about anything/everything you do. &nbsp;Not that this is patently true, but I feel that if you make this assumption a key part of your strategic plan, you will be better prepared to actually achieve something meaningful from your publisher discussions.</div>
<p />
<div>What this really means, is putting much greater focus on the things that, in the immortal words of some former nation leaders, will <a href="http://en.wikipedia.org/wiki/Shock_and_awe" title="SHOCK AND AWE">SHOCK AND AWE</a> them into accepting that your little studio is worth, dare I say, an advance on development costs.</div>
<p />
<div>So, the remainder of this entry will be me describing as best I can, some of the musings I have learned over the last few years, especially when trying to determine the priority of what to do, at what point in a project.</div>
<h2>My Introspections, in no particular order:</h2>
<h4>Having industry connections help. &nbsp;</h4>
<div>While it&#8217;s the job of publisher agents to search for talent, people are lazy, and would rather color their perceptions of any potential partner by their existing knowledge. &nbsp;Being unknown is added risk, and publishers are (unfortunately) very risk adverse.</p>
<h4>Your game pitch doc doesn&#8217;t matter. &nbsp;</h4>
<div>Now this might get me flamed for saying it, but to get your foot in the door, really, your pitch documents don&#8217;t matter. &nbsp;Imagine this: &nbsp;you come up with the equivalent of a &#8220;Mass Effect 3&#8243; pitch document. &nbsp;If you are a small studio, instantly (and without bothering to read a word of your slick and pretty document) the publisher will doubt whether you have the resources to accomplish such a task. &nbsp;If you design a nice pitch doc describing a title that your team could realistically accomplish in 1 year, then (maybe if you are lucky) after they skim your docs, they will ask to see a playable demo before they commit to anything. &nbsp;So really, regardless of whatever any books / resources say on the matter, &nbsp;I strongly feel that your game pitch docs do not matter AT ALL, at least not at the &#8220;foot in the door&#8221; point. &nbsp;Again this gets back to &#8220;SHOCK AND AWE&#8221;: &nbsp;what really matters is the playable demo.</div>
<p></p>
<div>I think a lot of game business / design resources neglect this point a lot, because when you have established relationships with a publisher, and the publisher knows of your studio, yes I think the formula is different (and in that case, most likely the initial pitch doc has more significance). &nbsp;My main point is that when you are a total unknown to the publisher, the significance of any/everything drops relative to a playable demo that &#8220;proves the fun&#8221;.</div>
<h4>Create a compelling playable demo as the only priority.</h4>
<div>The key words here are &#8220;compelling&#8221;, and &#8220;only priority&#8221;. &nbsp;For more than a year, we focused on generating pitch docs, tech-demos, and simple gameplay sandboxes, all on the misguided thought that publishers would spend the time to review these materials and carefully consider the merits. &nbsp;In hindsight, this was absolutely the wrong approach, and honestly we wasted more than a year&#8217;s worth of our studio&#8217;s productivity jumping through publisher hoops that ultimately didn&#8217;t matter.</div>
<p></p>
<div>Instead, focus on creating a compelling playable demo. &nbsp;This doesn&#8217;t mean &#8220;don&#8217;t create a game design&#8221;, it just means do the minimal game designing needed to create this compelling demo. &nbsp;To be compelling, the demo has to show it&#8217;s fun. &nbsp;I&#8217;m not so sure how much of an impact art quality is on the demo&#8217;s perceived quality, but it most likely depends on the type of experience your title gives.</div>
<p></p>
<div>Once you have that demo and it&#8217;s awesome, it won&#8217;t take you much more time to generate the additional docs needed for a pitch, but even that, I think is unnecessary until you receive publisher interest. &nbsp;One important reason why a small studio should consider skipping it: &nbsp;doing pretty graphic design work needed for a pitch is a pretty specialized skill set, and most small studio&#8217;s won&#8217;t have someone able to create truly professional documentation. &nbsp;So better to present what your studio&#8217;s strengths are (hopefully that&#8217;s creating games) and then once you find genuine publisher interest, invest in the time/money needed to create sexy documentation.</div>
<h4>Submit a video/screenshots first.</h4>
</div>
<div>When you submit your game for consideration to publishers, start with a youtube link to your gameplay video, and maybe a few screenshots of your game. &nbsp;If they are interested, follow up by sending your playable demo. &nbsp;It of course helps if the video is sexy, but really what matters is you show a compelling gameplay experience. &nbsp;As described above, it doesn&#8217;t help to submit 20 page pitch docs at this point. &nbsp;It requires too much effort to obtain meaningful information from a pitch doc at this stage, and really what matters is if the gameplay experience is compelling, which a video can describe much better than a document ever could.</div>
<div>
<h4>Never ever submit a finished game to publishers.</h4>
<div>Firstly, it puts you at a severe financial disadvantage. &nbsp;(All production risks have already been incurred and resolved). &nbsp;But secondly, and most importantly, you will greatly increase the &#8220;Noise ratio&#8221; when soliciting publishers. &nbsp;Almost no publisher would say no to publishing a finished game (it doesn&#8217;t cost them anything) but not so many would actually believe in the title to actually invest in it&#8217;s development. &nbsp;It comes back to the compelling playable demo. &nbsp;If you create this, and it does not gain you call-backs from publishers interested in pursuing, that&#8217;s telling you you should re-think your game idea.</div>
<h4>Research your publisher:</h4>
</div>
<div>Research, as best you can, who you deal with, before you make a deal. &nbsp;As a &#8220;noob&#8221; in the game bizdev world, this may be very hard, so it pays to shop around (after all, until you sign at the bottom line, there is no commitment)</div>
<p />
<div>If dealing with small publishers, make sure you negotiate a minimum per-unit royalties, otherwise you can rather rudely find out that your game has been given away for free (such as to a magazine for distro on an included CD), for next to nothing in the way of commission to you. &nbsp;&nbsp;</div>
<p />
<div>Part of this gets to a major point about publisher ethics: if they demand you to translate your game to a certain language (such as Russian) but know that estimated sales in that region won&#8217;t even come close to recouping your localization costs, and yet don&#8217;t inform you of this: &nbsp;walk away and never talk to that publisher again. &nbsp;(and yes, unfortunately Novaleaf found this out the hard way). &nbsp;</div>
<h4>Business Matching Events:</h4>
<div>If you plan on attending business matching events like Games Connection @ GDC, submit your awesome demo video a few months in advance. &nbsp;In the followups you can mention your attendance at these events and solicit a meeting. &nbsp; This is especially important for international studios that are not near the &#8220;regional game dev hubs&#8221;, though if you are near a publisher&#8217;s office, you should really try to schedule a meeting with them NOT at GDC, as they will all be busy with other things/big clients around that time-frame, so may not have time to talk with &#8220;small potatoes&#8221; like you.</div>
<h2>Conclusions</h2>
<p>So in summary: &nbsp;Most publishers are narcissistic ruthless cutthroats, only interested in reducing risk and making money. &nbsp;A fact we already know, right?
<p /></p>
<h4><span style="color: #808080;">About the author:</span></h4>
<p><span style="color: #808080;">Jason Swearingen is Technical Director at <a href="http://www.novaleaf.com" title="Novaleaf Game Studios">Novaleaf Game Studios</a>. </span><br /><span style="color: #808080;">You can reach Jason via email (<strong>jasons </strong>aat <strong>novaleaf </strong>doot coom), or twitter (<strong>@jasons_novaleaf</strong>). </span><br /><span style="color: #808080;">Additional Novaleaf blogs team can be found <a href="http://blogs.novaleaf.com/" title="here">here</a>. </span></p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/01/22/nobody-gives-a-shit-introspections-of-a-start-up-indie-studios-dealings-with-publishers/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

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