<?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>Game Dev Without a Cause &#187; Programming</title>
	<atom:link href="https://gamedevwithoutacause.com/?cat=9&#038;feed=rss2" rel="self" type="application/rss+xml" />
	<link>https://gamedevwithoutacause.com</link>
	<description>Rob&#039;s Thoughts on Games, Game Dev, and Design - Temporary home of Skyboy Games</description>
	<lastBuildDate>Wed, 23 Jul 2014 09:18:52 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.2.38</generator>
	<item>
		<title>Seeing the Whole Elephant</title>
		<link>https://gamedevwithoutacause.com/?p=1710</link>
		<comments>https://gamedevwithoutacause.com/?p=1710#comments</comments>
		<pubDate>Tue, 22 Jan 2013 16:12:54 +0000</pubDate>
		<dc:creator><![CDATA[Rob]]></dc:creator>
				<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://gamedevwithoutacause.com/?p=1710</guid>
		<description><![CDATA[There&#8217;s this old parable about several blind men and an elephant. There story goes something like this: Asked to describe an elephant each blind man grabs a part of the elephant then proceeds to describe what they felt. One feels &#8230; <a href="https://gamedevwithoutacause.com/?p=1710">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a href="http://gamedevwithoutacause.com/wp-content/uploads/2013/01/Blind_monks_examining_an_elephant.jpeg"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2013/01/Blind_monks_examining_an_elephant.jpeg" alt="Blind_monks_examining_an_elephant" width="800" height="580" class="aligncenter size-full wp-image-1753" /></a><br />
There&#8217;s this old parable about several blind men and an elephant.  There story goes something like this: Asked to describe an elephant each blind man grabs a part of the elephant then proceeds to describe what they felt.  One feels the elephant&#8217;s tusk and describes an elephant as a hard, bony creature.  Another feels it&#8217;s leg and describes the elephant as being stout like a tree trunk.  Yet another grabs the elephants tail and promptly describes the elephant as being like a snake.  Naturally, once they start sharing their findings, an argument ensues about what an elephant really is.</p>
<p>Each of these poor men is being totally honest in their description, but the end result ends up being divorced from reality by the limits of their own perception.  The moral of the story is for one to be aware of where their limited perception (or preconceptions) may hide information from them.  In more colloquial terms, it&#8217;s about learning to see the whole picture.<span id="more-1710"></span></p>
<p>This lesson also applies to programming, particularly when designing code.  For almost any programming problem, there are several, potentially competing, factors that play into its solutions.  It&#8217;s easy to get so locked into a single mindset that you overlook important factors that you would only have noticed from a different vantage point.</p>
<p>When I need to design a piece of code, I try to think about it from at least the following three perspectives.  Of course, these thee perspectives don&#8217;t represent the full set of potential viewpoints from which to examine a problem.  These are just the three that I&#8217;ve found to be the most useful tools for my day-to-day programming work.</p>
<p><strong>Class View</strong><br />
At this stage, I think about how I would structure my code with traditional Object-Oriented Programming techniques.  I think about the data and functions that would be a part of the core &#8220;objects&#8221; in the feature I am creating.  If things get hairy, I bust out some UML to track dependencies and ownership relations.  This views tends to make the code most easily digestible for many game programmers because most of them have been raised on OOP principles.</p>
<p><strong>Data View</strong><br />
This is where I look at the problem I need to solve in terms of data that needs to be processed.  As opposed to thinking in terms of classes which are collections of data and functions that operate on that data, I think about data processing as a pipeline.  In many cases, this sort of thought process leads me to the core update loops that will form the core of the feature I&#8217;m implementing.  This view is often about making the code easily usable for the target machine.  In many cases it&#8217;s about taking data that has been gathered and normalized so it can be processed in a minimally-complex fashion.</p>
<p><strong>User View</strong><br />
I wouldn&#8217;t be a very useful programmer if I ignored my end-users.  If my feature needs someone to author data for it (and almost every feature does in some way or another), I&#8217;d better make sure they can create that data in a reliable and reasonably error-proof fashion.  This is especially true if they have to produce a lot of data or need to iterate on that data repeatedly.</p>
<p>I don&#8217;t always use the above three views in that order, but I generally make sure to ask myself if I&#8217;ve considered my design from all three of these perspectives before I start working on any significantly large feature.  Sometimes the best thing I can do when programming is to stop and ask myself: &#8220;Have I seen the whole elephant?&#8221;</p>
]]></content:encoded>
			<wfw:commentRss>https://gamedevwithoutacause.com/?feed=rss2&#038;p=1710</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>#OneGameAMonth</title>
		<link>https://gamedevwithoutacause.com/?p=1692</link>
		<comments>https://gamedevwithoutacause.com/?p=1692#comments</comments>
		<pubDate>Tue, 01 Jan 2013 10:04:01 +0000</pubDate>
		<dc:creator><![CDATA[Rob]]></dc:creator>
				<category><![CDATA[Game Design]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://gamedevwithoutacause.com/?p=1692</guid>
		<description><![CDATA[Ah, New Year&#8217;s. The annual turn of the calendar marked by resolutions and gym membership renewals. This year, my big resolution (or, rather, personal challenge) can be summed up with a single hashtag: #OneGameAMonth One Game a Month. That&#8217;s twelve &#8230; <a href="https://gamedevwithoutacause.com/?p=1692">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a href="http://gamedevwithoutacause.com/wp-content/uploads/2013/01/logo.png"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2013/01/logo.png" alt="logo" width="768" height="80" class="aligncenter size-full wp-image-1700" /></a><br />
Ah, New Year&#8217;s. The annual turn of the calendar marked by resolutions and gym membership renewals. This year, my big resolution (or, rather, personal challenge) can be summed up with a single hashtag:</p>
<p>#OneGameAMonth<br />
<span id="more-1692"></span></p>
<p>One Game a Month.  That&#8217;s twelve games in a year.  Considering that I struggled to launch two games last year (<a href="https://itunes.apple.com/us/app/michelangelo-the-game/id500556693#" target="_blank">Michelangelo</a> and <a href="http://marketplace.xbox.com/en-US/Product/Robot-Legions/66acd000-77fe-1000-9115-d80258550c46" target="_blank">Robot Legions</a>, $1 a piece if you&#8217;re interested), this seems like a pretty tall order.  And you know what, it is.  But, I&#8217;m going to try and see how far I get.</p>
<p><a href="http://onegameamonth.com/" target="_blank">One Game A Month</a> is a motivational promotion being run by @McFunkypants.  As the name suggests, the goal is to make a game every month.  There are over 2000 developers signed-up who are ready to encourage each other to make games.  As a nice touch, the One Game A Month site has implemented a suite of typical gamification features: experience points for making games, leveling-up profiles, and achievements.</p>
<p>On one hand, it&#8217;s silly.  On the other, it&#8217;s also hugely motivating.  If you&#8217;re a game dev looking for a challenge, this may be the one for you.  If you need some more convincing, how about listening to @McFunkypant&#8217;s One Game A Month keynote speech:<br />
<iframe width="584" height="438" src="http://www.youtube.com/embed/1mjkNtfRbV8?feature=oembed" frameborder="0" allowfullscreen></iframe></p>
]]></content:encoded>
			<wfw:commentRss>https://gamedevwithoutacause.com/?feed=rss2&#038;p=1692</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An Easy Way to Break Your Save Data in XNA</title>
		<link>https://gamedevwithoutacause.com/?p=1675</link>
		<comments>https://gamedevwithoutacause.com/?p=1675#comments</comments>
		<pubDate>Tue, 25 Dec 2012 14:33:44 +0000</pubDate>
		<dc:creator><![CDATA[Rob]]></dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Robot Legions]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://gamedevwithoutacause.com/?p=1675</guid>
		<description><![CDATA[Late last week, I finally managed to pass an update for Robot Legions out onto the Xbox Live Marketplace. I wasn&#8217;t originally planning to release an update this early (I have some other features in-the-works for the &#8220;real&#8221; next update), &#8230; <a href="https://gamedevwithoutacause.com/?p=1675">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/12/broken-hard-disk.jpg"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/12/broken-hard-disk.jpg" alt="broken-hard-disk" width="449" height="300" class="aligncenter size-full wp-image-1679" /></a><br />
Late last week, I finally managed to pass an update for <a href="http://marketplace.xbox.com/en-US/Product/Robot-Legions/66acd000-77fe-1000-9115-d80258550c46" target="_blank">Robot Legions</a> out onto the Xbox Live Marketplace. I wasn&#8217;t originally planning to release an update this early (I have some other features in-the-works for the &#8220;real&#8221; next update), but&#8230; I had a bug.  A nasty save data killing bug.</p>
<p>Yuck.</p>
<p>So, in the interest of helping other XNA devs out there, let me tell you about what I screwed up and how I fixed it.<span id="more-1675"></span></p>
<p>So, let&#8217;s get to the meat.  Let me show you how I screwed up my save data handling.</p>
<p>First, this is how I read my save data:</p>
<pre class="brush: c#">
// Deserialization
XmlSerializer s = new XmlSerializer(typeof(T));
if (container.FileExists(filename))
{
    TextReader r = new StreamReader(container.OpenFile(filename, FileMode.Open));
    saveDataItem = (T)s.Deserialize(r);
    r.Close();
}
container.Dispose();

</pre>
<p>And this is how I wrote it:</p>
<pre class="brush: c#">
// Serialization
XmlSerializer s = new XmlSerializer(saveDataItem.GetType());
TextWriter w = new StreamWriter(container.OpenFile(filename, FileMode.OpenOrCreate));
s.Serialize(w, saveDataItem);
w.Close();
</pre>
<p>See the bug?  Yeah, well, neither did I.  You see, there was this little problem with how I wrote my save data.  The code above would work in most cases, but if I wrote data that was shorter than the previous file&#8217;s save data, the old save data would only be partially overwritten.  Any bytes of the old save data not explicitly overwritten by the new save data would remain appended to the end of the new save data. Thus potentially turning data like this:</p>
<pre class="brush: xml">
&lt;RobotSaveData&gt;&lt;Cash&gt;12345&lt;/Cash&gt;&lt;/RobotSaveData&gt;
</pre>
<p>Into data like this:</p>
<pre class="brush: xml">
&lt;RobotSaveData&gt;&lt;Cash&gt;123&lt;/Cash&gt;&lt;/RobotSaveData&gt;a&gt;
</pre>
<p>And totally confounding the XML deserializer.  Voila! Broken save data and unhappy customers.  To top it off, as far as I can tell, this behavior doesn&#8217;t replicate on Windows, only on the Xbox 360.  You can imagine my consternation.</p>
<p>Enough about what went wrong.  Here&#8217;s how I went about fixing it.  I changed the way I opened a file for writing my save data:</p>
<pre class="brush: c#">
// Serialization
XmlSerializer s = new XmlSerializer(saveDataItem.GetType());
TextWriter w = new StreamWriter(
    container.FileExists(filename) ?
    container.OpenFile(filename, FileMode.Truncate) :
    container.OpenFile(filename, FileMode.Create)
);
s.Serialize(w, saveDataItem);
w.Close();
</pre>
<p>This big difference here is that I use FileMode.Truncate when opening the file for writing save data.  By doing this, I&#8217;m able to dispose of the old contents and completely overwrite them with my new save data.</p>
<p><strong>EDIT:</strong> I was recently informed by one of the fine members of the XBLIG community that simply using FileMode.Create when I open a file is sufficient for my purposes since it&#8217;s behavior when a file exists is the same as FileMode.Truncate.</p>
]]></content:encoded>
			<wfw:commentRss>https://gamedevwithoutacause.com/?feed=rss2&#038;p=1675</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Code Comments and 5WH</title>
		<link>https://gamedevwithoutacause.com/?p=1660</link>
		<comments>https://gamedevwithoutacause.com/?p=1660#comments</comments>
		<pubDate>Tue, 18 Dec 2012 14:23:39 +0000</pubDate>
		<dc:creator><![CDATA[Rob]]></dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://gamedevwithoutacause.com/?p=1660</guid>
		<description><![CDATA[Comments in code, you can&#8217;t live with &#8217;em, you can&#8217;t live without &#8217;em. Depending on who you ask, comments are a crucial form of documentation without which most source code would be unusable. Others might say that code comments are, &#8230; <a href="https://gamedevwithoutacause.com/?p=1660">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/12/6a00d8348999ec69e2017ee3d5ac64970d-800wi.jpeg"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/12/6a00d8348999ec69e2017ee3d5ac64970d-800wi.jpeg" alt="" title="6a00d8348999ec69e2017ee3d5ac64970d-800wi" width="400" height="324" class="aligncenter size-full wp-image-1664" /></a><br />
Comments in code, you can&#8217;t live with &#8217;em, you can&#8217;t live without &#8217;em.  Depending on who you ask, comments are a crucial form of documentation without which most source code would be unusable.  Others might say that code comments are, at best, an administrative nuisance or, at worst, dangerously misleading as they inevitably lose sync with the source code they purport to clarify.  Reality, of course, lies across a spectrum between these extremes.  Code comments, in-and-of-themselves, are neither helpful, nor hurtful.  It&#8217;s the content of the comments themselves and how they relate to the reality of the source code itself that makes them valuable (or potentially harmful.)  </p>
<p>If you&#8217;ve attended elementary school in the States, you should be familiar with 5WH, the building blocks of questions: Who, What, When, Where, Why and How.  These six words cover the gamut of questions you can ask and provide structure to information sharing.  So, what happens when you apply these questions to comments in source code and use them to direct the information you need to share?<br />
<span id="more-1660"></span></p>
<p><strong>Who?</strong><br />
Who wrote this code?  Or, more importantly, who is responsible for this code when it breaks something?  Explicitly identifying the owner of particular bits of code is useful because subsequent readers of the code then know who to ask if they have questions.  This goes beyond just code ownership.  I actually write my name next to any code comments I make so people can ask me to clarify in case my comment didn&#8217;t make sense to them.</p>
<p>That being said, this question can also be easily answered by having decent source control.  If I find comments disagreeing with what I see from source control histories, I trust what the source control says.</p>
<p><strong>What?</strong><br />
Commenting about what source code does is absolutely <strong>useless</strong>.  People who hate comments in code usually hate them because they are answering this question.  Writing what code does is simply re-stating information presented by the source code itself only with less precision and a greater change of being incorrect.  This is also the kind of commenting you&#8217;ll get if you instate a commenting policy without addressing what questions the comments are actually supposed to answer.</p>
<p>Do we really need more &#8220;documentation&#8221; like this:</p>
<pre class="brush: c#">
	//Sets the position of this object
	void SetPosition(Vector2 position);
</pre>
<p>It&#8217;s silly.  Don&#8217;t do it.</p>
<p><strong>When?</strong><br />
Putting a time-stamp on comments is almost as useful as putting your name on comments.  This is another bit of information that replicates information provided by source control but it can help someone reading your code if they can decide, at a glance, whether a given comment is old and out-of-date.</p>
<p><strong>Where?</strong><br />
Where is the code?  The code is where the code is.  A more useful question to answer is: where should this code be used?  If the answer is not obvious, it&#8217;s probably worth mentioning.  Another useful bit of information is telling the reader where your code came from.  If you pulled the code from the net, include a link in the comments to the original material.  If you copy-pasted (shame on you) the code from someplace, mention the source in the comments.</p>
<p><strong>Why?</strong><br />
This is the BIG ONE!  How often have you found yourself reading someone else&#8217;s (or your own) code and thinking: &#8220;Why did they do that?&#8221; If you answer only one question with your comments, answer this one.  While &#8220;what&#8221; is fully captured by the code itself and &#8220;when/who&#8221; are captured by source control, &#8220;why&#8221; is pretty much invisible unless explicitly explained.  If you think something is a hack, elaborate on why that is.  If there&#8217;s some code that you think might be dangerous, explain why.  If you chose a particular implementation when another might have worked, talk about why you made that choice.  The person reading your code will thank you.</p>
<p><strong>How?</strong><br />
If your code needs some explanation in order to be used correctly or if there is some particular order in which certain functions need to be called in order to behave as expected, it&#8217;s a good idea to document that in your comments.  This is another question, like &#8220;Why&#8221;, that is not easily answered by source-control or the source code itself.</p>
<p>Programmers tend to be busy and comments are not crucial in the strictest sense of the word, but they CAN be invaluable tools to people reading code.  Comments aren&#8217;t intrinsically valuable, however.  Their value is only realized when they answer a question held by someone reading the code. Good code comments must serve the needs of the code reader, be that another programmer or your future self.</p>
]]></content:encoded>
			<wfw:commentRss>https://gamedevwithoutacause.com/?feed=rss2&#038;p=1660</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>More Fun with SpriteFonts</title>
		<link>https://gamedevwithoutacause.com/?p=1605</link>
		<comments>https://gamedevwithoutacause.com/?p=1605#comments</comments>
		<pubDate>Tue, 27 Nov 2012 14:07:55 +0000</pubDate>
		<dc:creator><![CDATA[Rob]]></dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://gamedevwithoutacause.com/?p=1605</guid>
		<description><![CDATA[A while ago, I posted about pre-rendering text to improve runtime performance when using XNA SpriteFonts. Since then, I&#8217;ve managed to complete a game (Robot Legions, currently up for peer review) using my XNA codebase and got to try out &#8230; <a href="https://gamedevwithoutacause.com/?p=1605">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/41603DS65RL._SL500_AA300_.jpeg"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/41603DS65RL._SL500_AA300_.jpeg" alt="" title="41603DS65RL._SL500_AA300_" width="300" height="300" class="aligncenter size-full wp-image-1608" /></a><br />
A while ago, I posted about pre-rendering text to improve runtime performance when using XNA SpriteFonts.  Since then, I&#8217;ve managed to complete a game (Robot Legions, currently up for <a href="http://catalog.create.msdn.com/en-US/GameDetails.aspx?catalogEntryId=f9ea114c-b564-4586-84eb-f984e62b408b&#038;type=1" target="_blank">peer review</a>) using my XNA codebase and got to try out my text pre-rendering solution in a real project.  It worked out pretty well, but there were a few features that I wished I had implemented ahead of time.  Well, while Robot Legions was being play-tested, I went ahead and implemented some of those features.  Now I&#8217;ll describe those features and share a bit of (hopefully) helpful code that will let you use them in your own games.<span id="more-1605"></span></p>
<p>The core functionality of my text pre-rendering solution is drawing a given string to a texture using a given font.  I&#8217;m then able to use that text texture anywhere in my game as I would any normal texture.  This allows me to avoid the overhead of calling DrawString() for text in my game that doesn&#8217;t have to change often.  </p>
<pre class="brush: c#">
SpriteFont demoFont = Game.Content.Load&lt;SpriteFont&gt;(&quot;TextRenderingDemo/DemoFont&quot;);
Texture2D textTexture = textWriter.CreateTextSpriteTexture(demoFont, &quot;The quick, brown fox jumped over Richter Belmont&quot;);
</pre>
<p>In addition to the core functionality, I added the following features:</p>
<p><strong>Button Guides</strong><br />
The XBLIG Creator&#8217;s site <a href="http://xbox.create.msdn.com/en-US/education/catalog/utility/controller_buttons" target="_blank">provides</a> images of the Xbox Controller&#8217;s buttons compatible with XNA&#8217;s SpriteFont for providing on-screen control instructions.  While it&#8217;s possible to combine the button images with another sprite font image and use them as one SpriteFont, I prefer to combine the button images with fonts I choose at runtime.  To do this, I prepared a version of my string rendering function with extra parameters for rendering the button image and positioning it relative to the text of my choice.</p>
<pre class="brush: c#">
SpriteFont demoFont = Game.Content.Load&lt;SpriteFont&gt;(&quot;TextRenderingDemo/DemoFont&quot;);
SpriteFont buttonFont = Game.Content.Load&lt;SpriteFont&gt;(&quot;Fonts/xboxControllerSpriteFont&quot;);
Texture2D textTexture = textWriter.CreateButtonGuideTextSpriteTexture(demoFont, buttonFont, &quot;: Do Something&quot;, &quot;&#039;&quot;, 0.5f, new Vector2(0.0f, 0.0f));
</pre>
<p><a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/textRendering011.png"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/textRendering011.png" alt="" title="textRendering01" width="949" height="531" class="aligncenter size-full wp-image-1616" /></a></p>
<p><strong>Drop Shadows</strong><br />
In a lot of cases, just rendering SpriteFonts as is tends to feel a little flat.  Drawing a darkened version of the same text offset by a couple pixels before drawing the text in question goes a long way to helping it stand out.  It&#8217;s a trick I use so often that I decided to bake drop shadows into my text pre-renderer.  With this functionality, a call like this:</p>
<pre class="brush: c#">
SpriteFont demoFont = Game.Content.Load&lt;SpriteFont&gt;(&quot;TextRenderingDemo/DemoFont&quot;);
List&lt;TextWriterDropShadow&gt; dropShadows = new List&lt;TextWriterDropShadow&gt;();
dropShadows.Add(new TextWriterDropShadow(new Vector2(2.0f, 2.0f), Color.Black));

Texture2D textTexture = textWriter.CreateTextSpriteTexture(demoFont, &quot;The quick, brown fox jumped over Richter Belmont&quot;, Color.White, dropShadows);
</pre>
<p>Can give me text that looks like this:<br />
<a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/textRendering02.png"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/textRendering02.png" alt="" title="textRendering02" width="877" height="540" class="aligncenter size-full wp-image-1618" /></a></p>
<p><strong>Text Borders</strong><br />
You&#8217;ll notice that I pass lists of drop shadows to my sprite pre-renderer.  It may seem like overkill, but being able to define a multiple drop shadows allows me to create various effects when rendering text.  For example, I can define a list of drop-shadows like this:</p>
<pre class="brush: c#">
SpriteFont demoFont = Game.Content.Load&lt;SpriteFont&gt;(&quot;TextRenderingDemo/DemoFont&quot;);
List&lt;TextWriterDropShadow&gt; dropShadows = new List&lt;TextWriterDropShadow&gt;();
dropShadows.Add(new TextWriterDropShadow(new Vector2(-1.0f, -1.0f), Color.Black));
dropShadows.Add(new TextWriterDropShadow(new Vector2(1.0f, -1.0f), Color.Black));
dropShadows.Add(new TextWriterDropShadow(new Vector2(-1.0f, 1.0f), Color.Black));
dropShadows.Add(new TextWriterDropShadow(new Vector2(1.0f, 1.0f), Color.Black));

dropShadows.Add(new TextWriterDropShadow(new Vector2(0.0f, -2.0f), Color.Black));
dropShadows.Add(new TextWriterDropShadow(new Vector2(0.0f, 2.0f), Color.Black));
dropShadows.Add(new TextWriterDropShadow(new Vector2(-2.0f, 0.0f), Color.Black));
dropShadows.Add(new TextWriterDropShadow(new Vector2(2.0f, 0.0f), Color.Black));

Texture2D textTexture = textWriter.CreateTextSpriteTexture(demoFont, &quot;The quick, brown fox jumped over Richter Belmont&quot;, Color.White, dropShadows);
</pre>
<p>To give me fancy bordered text like this:<br />
<a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/textRendering03.png"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/textRendering03.png" alt="" title="textRendering03" width="855" height="526" class="aligncenter size-full wp-image-1619" /></a></p>
<p>How&#8217;s that for pop?</p>
<p>Playing with the number of drop shadows, their offsets, and colors can allow you to produce a variety of decorations for your game&#8217;s text.  Give it a try if you&#8217;re interested. You can find the code for my text pre-renderer below:</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace EstrellaLib.Sprite
{
    public class TextWriterDropShadow
    {
        public Vector2 Offset;
        public Color Color;

        public TextWriterDropShadow(Vector2 offset, Color color)
        {
            Offset = offset;
            Color = color;
        }
    }

    public class TextTextureWriter
    {
        GraphicsDevice _graphics;
        SpriteBatch _spriteBatch;

        public TextTextureWriter(GraphicsDevice graphics)
        {
            _graphics = graphics;
            _spriteBatch = new SpriteBatch(graphics);            
        }

        public Texture2D CreateTextSpriteTexture(SpriteFont spriteFont, string textString)
        {
            return CreateTextSpriteTexture(spriteFont, textString, Color.White, null);
        }

        public Texture2D CreateTextSpriteTexture(SpriteFont spriteFont, string textString, Color textColor, List&lt;TextWriterDropShadow&gt; dropShadows)
        {
            return RenderTextTexture(spriteFont, textString, textColor, null, &quot;&quot;, 1.0f, Vector2.Zero, dropShadows);
        }

        public Texture2D CreateButtonGuideTextSpriteTexture(SpriteFont textSpriteFont, SpriteFont buttonGuideSpriteFont, string textString, string buttonGuideText, float buttonGuideScale, Vector2 buttonGuidePositionOffset)
        {
            return CreateButtonGuideTextSpriteTexture(textSpriteFont, buttonGuideSpriteFont, textString, buttonGuideText, buttonGuideScale, buttonGuidePositionOffset, Color.White, null);
        }

        public Texture2D CreateButtonGuideTextSpriteTexture(SpriteFont textSpriteFont, SpriteFont buttonGuideSpriteFont, string textString, string buttonGuideText, float buttonGuideScale, Vector2 buttonGuidePositionOffset, Color textColor, List&lt;TextWriterDropShadow&gt; dropShadows)
        {
            return RenderTextTexture(textSpriteFont, textString, textColor, buttonGuideSpriteFont, buttonGuideText, buttonGuideScale, buttonGuidePositionOffset, dropShadows);
        }

        private Texture2D RenderTextTexture(SpriteFont textSpriteFont, string textString, Color textColor, SpriteFont buttonGuideSpriteFont, string buttonGuideText, float buttonGuideScale, Vector2 buttonGuidePositionOffset, List&lt;TextWriterDropShadow&gt; dropShadows)
        {
            if (textSpriteFont != null)
            {
                Vector2 stringDimensions = textSpriteFont.MeasureString(textString);

                float buttonHorizontalShift = 0.0f;
                Vector2 buttonTextDimensions = Vector2.Zero;
                if (buttonGuideSpriteFont != null)
                {
                    buttonTextDimensions = buttonGuideSpriteFont.MeasureString(buttonGuideText);
                    buttonTextDimensions.X *= buttonGuideScale;

                    buttonTextDimensions.X += Math.Abs(buttonGuidePositionOffset.X);
                    if (buttonGuidePositionOffset.X &lt; 0.0f)
                    {
                        buttonHorizontalShift = -buttonGuidePositionOffset.X;
                    }

                    //Eliminate potential non-integral values that could result in lost pixels on texture render
                    buttonTextDimensions.X = (float)Math.Ceiling(buttonTextDimensions.X);
                }

                Vector2 dropShadowPositionAdjust = Vector2.Zero;
                Vector2 dropShadowSizeAdjust = Vector2.Zero;
                if (dropShadows != null)
                {
                    Vector2 lowestVals = Vector2.Zero;
                    Vector2 hightestVals = Vector2.Zero;
                    foreach (TextWriterDropShadow dropShadow in dropShadows)
                    {
                        if( dropShadow.Offset.X &lt; 0.0f )
                            lowestVals.X = Math.Min(lowestVals.X, dropShadow.Offset.X);

                        if (dropShadow.Offset.Y &lt; 0.0f)
                            lowestVals.Y = Math.Min(lowestVals.Y, dropShadow.Offset.Y);

                        if (dropShadow.Offset.X &gt; 0.0f)
                            hightestVals.X = Math.Max(hightestVals.X, dropShadow.Offset.X);

                        if (dropShadow.Offset.Y &gt; 0.0f)
                            hightestVals.Y = Math.Max(hightestVals.Y, dropShadow.Offset.Y);
                    }

                    dropShadowPositionAdjust.X = Math.Abs(lowestVals.X);
                    dropShadowPositionAdjust.Y = Math.Abs(lowestVals.Y);

                    dropShadowSizeAdjust.X = Math.Abs(lowestVals.X) + Math.Abs(hightestVals.X);
                    dropShadowSizeAdjust.Y = Math.Abs(lowestVals.Y) + Math.Abs(hightestVals.Y);
                }

                RenderTarget2D renderTarget = new RenderTarget2D(_graphics, (int)stringDimensions.X + (int)buttonTextDimensions.X + (int)dropShadowSizeAdjust.X, (int)stringDimensions.Y + (int)dropShadowSizeAdjust.Y);

                _graphics.SetRenderTarget(renderTarget);
                _graphics.Clear(Color.Transparent);
                _spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, null, null);
                
                if (buttonGuideSpriteFont != null)
                {
                    _spriteBatch.DrawString(buttonGuideSpriteFont, buttonGuideText, dropShadowPositionAdjust + new Vector2(buttonHorizontalShift, buttonTextDimensions.Y * -0.25f * buttonGuideScale) + buttonGuidePositionOffset, Color.White, 0.0f, Vector2.Zero, buttonGuideScale, SpriteEffects.None, 1.0f);
                }

                Vector2 textPosition = dropShadowPositionAdjust + new Vector2(buttonHorizontalShift + buttonTextDimensions.X, 0.0f);
                if (dropShadows != null)
                {
                    foreach (TextWriterDropShadow dropShadow in dropShadows)
                    {
                        _spriteBatch.DrawString(textSpriteFont, textString, textPosition + dropShadow.Offset, dropShadow.Color);
                    }
                }

                _spriteBatch.DrawString(textSpriteFont, textString, textPosition, textColor);
                
                _spriteBatch.End();
                _graphics.SetRenderTarget(null);

                return renderTarget;
            }
            return null;
        }
    }
}

/* Button Guide Mapping
Character	Image
Space       Left Thumbstick
!	        Directional Pad
&quot;	        Right Thumbstick
#	        BACK
$	        Guide
%	        START
&amp;	        X
&#039;	        A
(	        Y
)	        B
*	        Right Shoulder
+	        Right Trigger
,	        Left Trigger
-	        Left Shoulder
*/
</pre>
]]></content:encoded>
			<wfw:commentRss>https://gamedevwithoutacause.com/?feed=rss2&#038;p=1605</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using CLRProfiler to Take Out the Trash, Part 2</title>
		<link>https://gamedevwithoutacause.com/?p=1570</link>
		<comments>https://gamedevwithoutacause.com/?p=1570#comments</comments>
		<pubDate>Tue, 13 Nov 2012 14:22:39 +0000</pubDate>
		<dc:creator><![CDATA[Rob]]></dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Robot Legions]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://gamedevwithoutacause.com/?p=1570</guid>
		<description><![CDATA[In last week&#8217;s post, I described how I used CLRProfiler to identify a couple parts of my code that were producing garbage every frame. One related to equality comparisons with my ActorState struct and another involving System.Objects being produced when &#8230; <a href="https://gamedevwithoutacause.com/?p=1570">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/M-O__character_of_WALL.E_.jpg"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/M-O__character_of_WALL.E_.jpg" alt="" title="M-O_(_character_of_WALL.E_)" width="341" height="512" class="aligncenter size-full wp-image-1575" /></a><br />
In last week&#8217;s post, I described how I used CLRProfiler to identify a couple parts of my code that were producing garbage every frame. One related to equality comparisons with my ActorState struct and another involving System.Objects being produced when I called RuntimePropertyInfo.SetValue().  This time, I&#8217;ll talk about what I did to fix those two problems.<span id="more-1570"></span></p>
<p><b>Fixing Problem #1: Structs as Dictionary Keys</b><br />
So, according to the CLRProfiler, I&#8217;m creating ActorStates via Generic.ObjectEqualityComparer::Equals() during my ChooseTargetNode() function. Looking at that code, it simple looks like I&#8217;m checking against a Dictionary that uses ActorState as a key. A quick Google search turns up this <a href="http://www.xnawiki.com/index.php?title=Enumerations_as_Dictionary_Keys" target="_blank">tidbit on XNA Wikia</a>.  The article talks about how Enums cause memory allocations when used as keys in Dictionaries.  It&#8217;s fair to assume that structs would have similar behavior and cause garbage to be created when used by the Dictionary&#8217;s internal comparison functions.  Luckily, the fix for this is easy.  If a struct implements IEquatable, Dictionary won&#8217;t allocate instances of that struct during comparisons.  Since my ActorState struct already implemented comparison functions, I just needed to add IEquatable as a part of its declaration.</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EstrellaLib.Actor
{
    public struct ActorState : IEquatable&lt;ActorState&gt;
    {
        string _stateName;

        public ActorState(string stateName)
        {
            _stateName = stateName.ToUpperInvariant();
        }

        public string StateName
        {
            get
            {
                return _stateName;
            }
            set
            {
                _stateName = value.ToUpperInvariant();
            }
        }

        public override bool Equals(object obj)
        {
            if (obj is ActorState)
            {
                return this.Equals((ActorState)obj);
            }
            return false;
        }

        public bool Equals(ActorState p)
        {
            return _stateName == p._stateName;
        }

        public override int GetHashCode()
        {
            return _stateName.GetHashCode();
        }

        public static bool operator ==(ActorState lhs, ActorState rhs)
        {
            return lhs.Equals(rhs);
        }

        public static bool operator !=(ActorState lhs, ActorState rhs)
        {
            return !(lhs.Equals(rhs));
        }

        public static ActorState None = new ActorState(&quot;NONE&quot;);
    }
}
</pre>
<p>Once I did that, ActorState disappeared from my allocation list on a second CLRProfiler run.</p>
<p><b>Fixing Problem #2: Value Type Boxing with PropertyInfos</b><br />
While the boxing problem caused by my code is relatively straight-forward:</p>
<pre class="brush: c#">
        public override void ApplyToActor(Actor targetActor)
        {
            if (_targetProperty == null)
            {
                _targetProperty = targetActor.GetType().GetProperty(_targetName);
                _targetActor = targetActor;
            }
            System.Diagnostics.Debug.Assert(_targetActor == targetActor);

            //PropertyInfo.SetValue(object obj, object value, object[] index)&#039;s second parameter
            // causes any value types I pass to it to be boxed in a temporary System.Object
            _targetProperty.SetValue(targetActor, _targetValue, null);
        }
</pre>
<p>Fixing it, is not quite as easy as simply implementing a particular interface.  I need to find a way to avoid calling SetValue().  Thankfully, PropertyInfo provides a way for me to get a delegate for setting the properties value that is typed to the value I&#8217;m trying to set.  This means that, if I go through the setter delegate, I can avoid implicitly casting my value type to a System.Object and creating garbage.  With a bit of work, I modify my code and end up with something like this:</p>
<pre class="brush: c#">
        public override void ApplyToActor(Actor targetActor)
        {
            if (_targetActor == null)
            {
                PropertyInfo targetProperty = targetActor.GetType().GetProperty(_targetName);
                _targetActor = targetActor;

                MethodInfo setter = targetProperty.GetSetMethod();
                System.Diagnostics.Debug.Assert(setter != null);
                _propertySetter = (Action&lt;T&gt;)Delegate.CreateDelegate(typeof(Action&lt;T&gt;), targetActor, setter);
            }
            System.Diagnostics.Debug.Assert(_targetActor == targetActor);
            System.Diagnostics.Debug.Assert(_propertySetter != null);
            _propertySetter(_targetValue);
        }
</pre>
<p>It&#8217;s not as easy to read as the version using SetValue, but it doesn&#8217;t produce any garbage.  For a function that will be called multiple times a frame, it&#8217;s totally worth it.</p>
<p><b>Enjoying the Fruits of my Labor</b><br />
With my code changes in place, I fire up CLRProfiler again to make sure I get the expected effect.  The GC Timeline ends up looking something like this.<br />
<a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/CLRPic08.png"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/CLRPic08.png" alt="" title="CLRPic08" width="445" height="184" class="aligncenter size-full wp-image-1562" /></a></p>
<p>There we go!  A few GCs occurring when the game starts up, but once we get to the Title screen: nothing.  Just a flat plane of constant memory use.  My garbage collection problems are solved! At least in this part of the game.</p>
]]></content:encoded>
			<wfw:commentRss>https://gamedevwithoutacause.com/?feed=rss2&#038;p=1570</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using CLRProfiler to Take Out the Trash, Part 1</title>
		<link>https://gamedevwithoutacause.com/?p=1541</link>
		<comments>https://gamedevwithoutacause.com/?p=1541#comments</comments>
		<pubDate>Tue, 06 Nov 2012 14:22:26 +0000</pubDate>
		<dc:creator><![CDATA[Rob]]></dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Robot Legions]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://gamedevwithoutacause.com/?p=1541</guid>
		<description><![CDATA[As cutesy as it may be, I&#8217;m growing rather fond of my garbage collection count display. I&#8217;m especially fond of it because it helped me find garbage collections occuring in places I never expected them to happen. Such as my &#8230; <a href="https://gamedevwithoutacause.com/?p=1541">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/10/wall-e.jpeg"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/10/wall-e.jpeg" alt="" title="wall-e" width="450" height="333" class="aligncenter size-full wp-image-1542" /></a></p>
<p>As cutesy as it may be, I&#8217;m growing rather fond of my <a href="http://gamedevwithoutacause.com/?p=1523" title="Getting Cute with Performance Metrics (and Reducing Memory Usage too!)" target="_blank">garbage collection count display</a>.  I&#8217;m especially fond of it because it helped me find  garbage collections occuring in places I never expected them to happen.  Such as my title screen for example:<br />
<a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/10/RobotLegion-2012-11-02-14-05-04-39.jpg"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/10/RobotLegion-2012-11-02-14-05-04-39-1024x576.jpg" alt="" title="RobotLegion 2012-11-02 14-05-04-39" width="584" height="328" class="aligncenter size-large wp-image-1547" /></a></p>
<p>Ack!  Look at all those garbage cans, I mean recycling bins (reduce, reuse, recycle, folks!)</p>
<p>That&#8217;s a lot of garbage collections for a &#8220;static&#8221; title screen.  Now, how to find out what&#8217;s causing all that garbage to be created&#8230; That&#8217;s where Microsoft&#8217;s <a href="http://www.microsoft.com/en-us/download/details.aspx?id=16273" target="_blank">CLRProfiler</a> comes into play.<span id="more-1541"></span></p>
<p><b>Running CLRProfiler</b><br />
CLRProfiler is a great tool for profiling your XNA game&#8217;s memory usage.  It can produce graphs and tables that tell you exactly when your game is allocating what classes.  It&#8217;s also a bit rough around the edges and hard to use.  Even installing it eschews the oh-so-common installer for a zip file (a rarity in Windows tools nowadays.)</p>
<p>So, once I get my hands on the tool, the first thing I have to do is get my game running with CLRProfiler.  Pressing the Start Application button seems like a good place to start, but first I need to set my working directory or else my game won&#8217;t be able to find its data while it&#8217;s being run. To do that, I click on File->Set Parameters then set the working directory to the directory where my game&#8217;s executable lives.<br />
<a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/CLRPic01.png"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/CLRPic01.png" alt="" title="CLRPic01" width="615" height="426" class="aligncenter size-full wp-image-1548" /></a></p>
<p>Next, to make sure I get all the information I need, I enable both Allocations and Calls in the Profile section. With those settings done, I&#8217;m ready to hit the Start Application button and select my game&#8217;s executable for profiling.<br />
<a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/CLRPic02.png"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/CLRPic02.png" alt="" title="CLRPic02" width="336" height="255" class="aligncenter size-full wp-image-1549" /></a></p>
<p><b>Diagnosing the Problem</b><br />
At this point, I let my game run to the title screen so I can gather data on memory applications.  After a few seconds, I shut down my game and let CLRProfiler chew on the data and present it to me.<br />
<a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/CLRPic03.png"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/CLRPic03.png" alt="" title="CLRPic03" width="885" height="541" class="aligncenter size-full wp-image-1550" /></a></p>
<p>Since I&#8217;m worried about garbage collection, I&#8217;ll take a look at the GC Timeline.  Clicking the &#8220;Time Line&#8221; button gives me a graph of memory at various GC generations like this one:<br />
<a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/CLRPic04.png"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/CLRPic04-1024x660.png" alt="" title="CLRPic04" width="584" height="376" class="aligncenter size-large wp-image-1552" /></a></p>
<p>See that sawtooth pattern on the bottom timeline there?  Those are garbage collections.  Memory builds up until it hits a threshold then garbage collection kicks in and drops the total memory usage.  After that memory begins to build up again until it hits the threshold and triggers another collection and so on. Now that I know how I&#8217;m allocating memory, it&#8217;s time to find out what I&#8217;m allocating.  Box-selecting one of the sawtooths, I produce a report of what is in memory at that point.<br />
<a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/CLRPic05.png"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/CLRPic05-1024x667.png" alt="" title="CLRPic05" width="584" height="380" class="aligncenter size-large wp-image-1553" /></a></p>
<p>The list on the right shows me all objects instantiated during the period I box-selected. Lots of System.Objects and lots of ActorStates.  The ActorState structs are definitely being produced by my code and the System.Objects are probably being produced by the way I&#8217;m using .NET. Right-clicking on the list of allocated objects, I produce a graph of which function calls allocated which objects.<br />
<a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/CLRPic06.png"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/CLRPic06-1024x590.png" alt="" title="CLRPic06" width="584" height="336" class="aligncenter size-large wp-image-1554" /></a></p>
<p>All the way on the right are my System.Object and ActorState allocations.  Tracking back to the left, I can follow the function calls to find out where these allocations are happening.<br />
<a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/CLRPic07.png"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/11/CLRPic07-1024x594.png" alt="" title="CLRPic07" width="584" height="338" class="aligncenter size-large wp-image-1555" /></a></p>
<p>Aha, looks like ActorStates are being allocated when they are being compared.  As for the System.Objects, it looks like my calls into the .NET&#8217;s Reflection code are responsible.  Considering that RuntimePropertyInfo.SetValue() takes a System.Object as a parameter and my code is generally passing in value types, this looks like a textbook case of boxing.</p>
<p>Now, thanks to CLRProfiler, I know where my garbage collection problems are coming from. Next week, I&#8217;ll go into what I can do to fix them.</p>
]]></content:encoded>
			<wfw:commentRss>https://gamedevwithoutacause.com/?feed=rss2&#038;p=1541</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting Cute with Performance Metrics (and Reducing Memory Usage too!)</title>
		<link>https://gamedevwithoutacause.com/?p=1523</link>
		<comments>https://gamedevwithoutacause.com/?p=1523#comments</comments>
		<pubDate>Tue, 30 Oct 2012 14:05:34 +0000</pubDate>
		<dc:creator><![CDATA[Rob]]></dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Robot Legions]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://gamedevwithoutacause.com/?p=1523</guid>
		<description><![CDATA[I&#8217;ve lamented before about how unfortunate it was that my frametime display allocated memory and would cause garbage collections to occur. Well, I found a simple solution for my memory allocation problem and, if I say so myself, it&#8217;s kind &#8230; <a href="https://gamedevwithoutacause.com/?p=1523">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/10/Unify-icon-elements.png"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/10/Unify-icon-elements.png" alt="" title="Unify-icon-elements" width="369" height="362" class="aligncenter size-full wp-image-1524" /></a><br />
I&#8217;ve lamented <a href="http://gamedevwithoutacause.com/?p=1442" title="Measuring Frametime Revisited" target="_blank">before</a> about how unfortunate it was that my frametime display allocated memory and would cause garbage collections to occur.  Well, I found a simple solution for my memory allocation problem and, if I say so myself, it&#8217;s kind of&#8230; cute.<span id="more-1523"></span></p>
<p>Okay, so enough being coy, what did I actually do?  Basically, I replaced my frametime and memory displays with icons.  I retain the original text-based display as an option when I need more detail, but most of the time, I can use the icon-based display to keep me aware of my basic performance profile.  You can see the new frametime display in action in this screenshot from work-in-progress Robot Legions (upper-left corner):<br />
<a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/10/RL_PerfIcons.jpg"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/10/RL_PerfIcons-1024x576.jpg" alt="" title="RL_PerfIcons" width="584" height="328" class="aligncenter size-large wp-image-1538" /></a></p>
<p>There are 2 major elements to this new, memory-allocation-free frametime display. One is the stopwatch whose neighboring smiley face changes color and expression depending on how high the frametime is.  If my frametime grows to a level where I would start dropping frames, the face icon becomes an angry red.  The other element is the row of garbage cans (actually recycling bins because we&#8217;re eco-friendly around here) that show the number of recent garbage collections.  It&#8217;s not a lot of information but it&#8217;s just enough to let me know when I should start using my heavier-duty profiling tools to dig into a problem.</p>
<p>In case you want to use this sort of display in your own project, you can grab the icon spritesheet here.<br />
<a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/10/PerfIconSheet.png"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/10/PerfIconSheet.png" alt="" title="PerfIconSheet" width="160" height="32" class="aligncenter size-full wp-image-1535" /></a></p>
<p>The icons are originally from the public domain <a href="http://tango.freedesktop.org/Tango_Icon_Library" target="_blank">Tango Icon Library</a>.  You can go there to find icons suitable for a variety of purposes.</p>
<p>The latest code for my frametime display code is below:</p>
<pre class="brush: c#">
#if DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;


namespace EstrellaLib.Debug
{
    /// &lt;summary&gt;
    /// This is a game component that implements IUpdateable.
    /// &lt;/summary&gt;
    public class FrametimeCounterComponent : Microsoft.Xna.Framework.DrawableGameComponent
    {
        enum PerfIconType
        {
            Stopwatch,
            GarbageBin,
            HappyFace,
            NeutralFace,
            SadFace
        }

        Stopwatch FrametimeStopwatch;

        const int PERF_ICON_WIDTH = 32;
        Texture2D PerfIconSheet;
        SpriteFont FrametimeDisplayFont;
        SpriteBatch FrametimeDisplayBatch;

        bool ShowFrametimeText;

        public Vector2 FrametimeDisplayPosition;
        public Color FrametimeDisplayColor;

        const double FRAMETIME_DANGER_THRESHOLD = 1000.0f / 60.0f;      //If averaged frametime goes over this threshold...
        const float DANGER_COLOR_DISPLAY_SECONDS = 2.0f;                //... the frametime display will change color for this many seconds.
        
        float DangerTimer;
        public Color FrametimeDangerDisplayColor;
        float AveragedFrameTime;

        public bool ShowAveragedFrametime;

        WeakReference GcDetectionReference;
        long TotalMemoryKB;

        float RecentGarbageCollections;

        public FrametimeCounterComponent(Game game, bool showFrametimeText)
            : base(game)
        {
            ShowAveragedFrametime = true;
            FrametimeDisplayPosition = Vector2.One * 10.0f;
            FrametimeDisplayColor = Color.Green;
            FrametimeDangerDisplayColor = Color.Magenta;
            GcDetectionReference = new WeakReference(null);
            RecentGarbageCollections = 0;
            ShowFrametimeText = showFrametimeText;
        }

        /// &lt;summary&gt;
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// &lt;/summary&gt;
        public override void Initialize()
        {
            FrametimeStopwatch = new Stopwatch();
            FrametimeStopwatch.Start();
            base.Initialize();
        }

        protected override void LoadContent()
        {
            FrametimeDisplayBatch = new SpriteBatch(Game.GraphicsDevice);
            PerfIconSheet = Game.Content.Load&lt;Texture2D&gt;(&quot;Textures/PerfIconSheet&quot;);
            FrametimeDisplayFont = Game.Content.Load&lt;SpriteFont&gt;(&quot;Debug/Fonts/Default&quot;);
            base.LoadContent();
        }

        /// &lt;summary&gt;
        /// Allows the game component to update itself.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;gameTime&quot;&gt;Provides a snapshot of timing values.&lt;/param&gt;
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            float deltaSeconds = (float)gameTime.ElapsedGameTime.TotalSeconds;
            TimeSpan frameTime = FrametimeStopwatch.Elapsed;
            FrametimeStopwatch.Reset();
            FrametimeStopwatch.Start();

            RecentGarbageCollections = MathHelper.Max(0.0f, RecentGarbageCollections - deltaSeconds * 0.1f);        //Subtract 1 RecentGC every 10 seconds
            if (!GcDetectionReference.IsAlive)
            {
                GcDetectionReference = new WeakReference(new Object());
                TotalMemoryKB = GC.GetTotalMemory(false) / 1024;
                RecentGarbageCollections+=1.0f;
            }
           

            AveragedFrameTime = AveragedFrameTime * 0.9f + (float)frameTime.TotalMilliseconds * 0.1f;
            DangerTimer = MathHelper.Clamp(DangerTimer - deltaSeconds, 0.0f, DANGER_COLOR_DISPLAY_SECONDS);
            if (AveragedFrameTime &gt; FRAMETIME_DANGER_THRESHOLD)
            {
                DangerTimer = DANGER_COLOR_DISPLAY_SECONDS;
            }

            int displayItemCount = 0;
            FrametimeDisplayBatch.Begin();
           
            if (ShowFrametimeText)
            {
                FrametimeDisplayBatch.DrawString(FrametimeDisplayFont, &quot;Frame Time: &quot; + (ShowAveragedFrametime ? AveragedFrameTime : frameTime.TotalMilliseconds) + &quot;ms&quot;, FrametimeDisplayPosition + Vector2.UnitY * (FrametimeDisplayFont.LineSpacing * displayItemCount++), DangerTimer &gt; 0.0f ? FrametimeDangerDisplayColor : FrametimeDisplayColor);
                FrametimeDisplayBatch.DrawString(FrametimeDisplayFont, &quot;Total Memory: &quot; + TotalMemoryKB + &quot;KB&quot;, FrametimeDisplayPosition + Vector2.UnitY * (FrametimeDisplayFont.LineSpacing * displayItemCount++), FrametimeDisplayColor);
                FrametimeDisplayBatch.DrawString(FrametimeDisplayFont, &quot;Recent GCs: &quot; + (int)RecentGarbageCollections, FrametimeDisplayPosition + Vector2.UnitY * (FrametimeDisplayFont.LineSpacing * displayItemCount++), FrametimeDisplayColor);
            }

            DrawIcon(PerfIconType.Stopwatch, FrametimeDisplayPosition + Vector2.UnitY * (FrametimeDisplayFont.LineSpacing * displayItemCount));
            DrawIcon(FrametimeToPerfIcon(ShowAveragedFrametime ? AveragedFrameTime : (float)frameTime.TotalMilliseconds), FrametimeDisplayPosition + Vector2.UnitX * PERF_ICON_WIDTH + Vector2.UnitY * (FrametimeDisplayFont.LineSpacing * displayItemCount));
            displayItemCount++;

            int garbageX = 0;
            int garbageY = 0;
            for (int i = 0; i &lt; (int)RecentGarbageCollections; ++i)
            {
                DrawIcon(PerfIconType.GarbageBin, FrametimeDisplayPosition + Vector2.UnitX * PERF_ICON_WIDTH * garbageX + Vector2.UnitY * (FrametimeDisplayFont.LineSpacing * displayItemCount) + Vector2.UnitY * (FrametimeDisplayFont.LineSpacing * garbageY));
                garbageX++;
                if (garbageX &gt; 10)
                {
                    garbageY++;
                    garbageX = 0;
                }
            }
            displayItemCount++;

            FrametimeDisplayBatch.End();

            base.Draw(gameTime);
        }

        private void DrawIcon(PerfIconType iconType, Vector2 position)
        {
            FrametimeDisplayBatch.Draw(PerfIconSheet, position, new Rectangle((int)iconType * PERF_ICON_WIDTH, 0, PERF_ICON_WIDTH, PERF_ICON_WIDTH), Color.White);
        }

        private PerfIconType FrametimeToPerfIcon(float frameTime)
        {
            if (frameTime &lt; FRAMETIME_DANGER_THRESHOLD * 0.75f )
            {
                return PerfIconType.HappyFace;
            }
            else if (frameTime &lt; FRAMETIME_DANGER_THRESHOLD * 1.5f)
            {
                return PerfIconType.NeutralFace;
            }

            return PerfIconType.SadFace;
        }
    }
}
#endif
</pre>
]]></content:encoded>
			<wfw:commentRss>https://gamedevwithoutacause.com/?feed=rss2&#038;p=1523</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Improved Memory Usage Display</title>
		<link>https://gamedevwithoutacause.com/?p=1466</link>
		<comments>https://gamedevwithoutacause.com/?p=1466#comments</comments>
		<pubDate>Tue, 23 Oct 2012 14:04:24 +0000</pubDate>
		<dc:creator><![CDATA[Rob]]></dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://gamedevwithoutacause.com/?p=1466</guid>
		<description><![CDATA[In a previous post, I talked about how I added basic memory usage output to my frametime debug display. I also mentioned the major problem with that system being that the debug output I used allocated memory, causing garbage collections &#8230; <a href="https://gamedevwithoutacause.com/?p=1466">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/09/Cyberbrain.jpg"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/09/Cyberbrain.jpg" alt="" title="Cyberbrain" width="336" height="192" class="aligncenter size-full wp-image-1467" /></a><br />
In a previous post, I talked about how I added <a href="http://gamedevwithoutacause.com/?p=1442" title="v" target="_blank">basic memory usage output</a> to my frametime debug display.  I also mentioned the major problem with that system being that the debug output I used allocated memory, causing garbage collections to occur.  This constant change in memory usage naturally made the output hard to read.  As I was writing that post, I had an idea for how I could easily solve that problem which I will share with you now.<span id="more-1466"></span></p>
<p>The main issue with the memory output in my frametime debug display is that the constant memory allocations causes it to fluctuate between values several megabytes apart as temporary memory is allocated then periodically disposed by garbage collection.  This means that the memory display ticks up constantly then drops down to a threshold value from which it starts ticking again.  Naturally, this makes it hard to read the memory display and causes it to not accurately represent the memory being allocated by the game itself.</p>
<p>While I mentioned modifying the display logic to prevent memory allocations, I found an easier alternative I could implement without dramatically changing the existing code.  Basically, I opted to only update the memory value being displayed just after a garbage collection.  This means that the number displayed doesn&#8217;t change constantly as new memory is allocated, making it easier to read.  Because it&#8217;s updated after a garbage collection run, the memory usage I log will exclude memory that was allocated but waiting to be released. Now, because I miss small allocations that don&#8217;t total up enough to trigger garbage collection and garbage collection itself is not guaranteed to necessarily clean up all potentially releasable memory, this approach to memory reporting is not entirely accurate.  It&#8217;s pretty close however and the stability of the number gives me a much better reading of how much memory the various parts of my game are using relative to each other.</p>
<p>The code I use to only check memory usage after a garbage collection is below:</p>
<pre class="brush: c#">
    //In class member declarations
    WeakReference GcDetectionReference;

...

    //In component Draw() function
    if (!GcDetectionReference.IsAlive)
    {
         GcDetectionReference = new WeakReference(new Object());
         TotalMemoryKB = GC.GetTotalMemory(false) / 1024;
    }
</pre>
<p>The trick here (which I picked up from this <a href="http://blogs.msdn.com/b/shawnhar/archive/2007/10/12/monitoring-the-garbage-collector.aspx" target="_blank">post</a>) is to use a WeakReference around a dummy object as a canary for detecting garbage collections.  WeakReferences aren&#8217;t considered to be holding memory for the purpose of garbage collections so they can have memory be deleted out from under them.  In this scenario, the WeakReference GCDetectionReference is the only reference to the dummy object we allocate so it is very likely to for said object to be deleted during garbage collection.  This allows us know when a garbage collection has just occurred and thus know when to update the memory usage report.</p>
<p>I hope this bit of code proves useful to my fellow XNA game devs.  For convenience, the full code for the updated FrametimeCounterComponent follows:</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;


namespace EstrellaLib.Debug
{
    /// &lt;summary&gt;
    /// This is a game component that implements IUpdateable.
    /// &lt;/summary&gt;
    public class FrametimeCounterComponent : Microsoft.Xna.Framework.DrawableGameComponent
    {
        Stopwatch FrametimeStopwatch;
        
        SpriteFont FrametimeDisplayFont;
        SpriteBatch FrametimeDisplayBatch;

        public Vector2 FrametimeDisplayPosition;
        public Color FrametimeDisplayColor;

        const double FRAMETIME_DANGER_THRESHOLD = 1000.0f / 60.0f;      //If averaged frametime goes over this threshold...
        const float DANGER_COLOR_DISPLAY_SECONDS = 2.0f;                //... the frametime display will change color for this many seconds.
        
        float DangerTimer;
        public Color FrametimeDangerDisplayColor;
        float AveragedFrameTime;

        public bool ShowAveragedFrametime;

        WeakReference GcDetectionReference;
        long TotalMemoryKB;

        public FrametimeCounterComponent(Game game)
            : base(game)
        {
            ShowAveragedFrametime = true;
            FrametimeDisplayPosition = Vector2.One * 10.0f;
            FrametimeDisplayColor = Color.Green;
            FrametimeDangerDisplayColor = Color.Magenta;
            GcDetectionReference = new WeakReference(null);
        }

        /// &lt;summary&gt;
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// &lt;/summary&gt;
        public override void Initialize()
        {
            FrametimeStopwatch = new Stopwatch();
            FrametimeStopwatch.Start();
            base.Initialize();
        }

        protected override void LoadContent()
        {
            FrametimeDisplayBatch = new SpriteBatch(Game.GraphicsDevice);
            FrametimeDisplayFont = Game.Content.Load&lt;SpriteFont&gt;(&quot;Debug/Fonts/Default&quot;);
            base.LoadContent();
        }

        /// &lt;summary&gt;
        /// Allows the game component to update itself.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;gameTime&quot;&gt;Provides a snapshot of timing values.&lt;/param&gt;
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            TimeSpan frameTime = FrametimeStopwatch.Elapsed;
            FrametimeStopwatch.Reset();
            FrametimeStopwatch.Start();

            if (!GcDetectionReference.IsAlive)
            {
                GcDetectionReference = new WeakReference(new Object());
                TotalMemoryKB = GC.GetTotalMemory(false) / 1024;
            }

            AveragedFrameTime = AveragedFrameTime * 0.9f + (float)frameTime.TotalMilliseconds * 0.1f;
            DangerTimer = MathHelper.Clamp(DangerTimer - (float)gameTime.ElapsedGameTime.TotalSeconds, 0.0f, DANGER_COLOR_DISPLAY_SECONDS);
            if (AveragedFrameTime &gt; FRAMETIME_DANGER_THRESHOLD)
            {
                DangerTimer = DANGER_COLOR_DISPLAY_SECONDS;
            }

            FrametimeDisplayBatch.Begin();
            FrametimeDisplayBatch.DrawString(FrametimeDisplayFont, &quot;Frame Time: &quot; + (ShowAveragedFrametime ? AveragedFrameTime : frameTime.TotalMilliseconds) + &quot;ms&quot;, FrametimeDisplayPosition, DangerTimer &gt; 0.0f ? FrametimeDangerDisplayColor : FrametimeDisplayColor);
            FrametimeDisplayBatch.DrawString(FrametimeDisplayFont, &quot;Total Memory: &quot; + TotalMemoryKB + &quot;KB&quot;, FrametimeDisplayPosition + Vector2.UnitY * FrametimeDisplayFont.LineSpacing, FrametimeDisplayColor);
            FrametimeDisplayBatch.End();

            base.Draw(gameTime);
        }
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>https://gamedevwithoutacause.com/?feed=rss2&#038;p=1466</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OOP Stand Alone Complex</title>
		<link>https://gamedevwithoutacause.com/?p=1482</link>
		<comments>https://gamedevwithoutacause.com/?p=1482#comments</comments>
		<pubDate>Tue, 09 Oct 2012 14:04:24 +0000</pubDate>
		<dc:creator><![CDATA[Rob]]></dc:creator>
				<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://gamedevwithoutacause.com/?p=1482</guid>
		<description><![CDATA[Don&#8217;t get me wrong, I&#8217;m not against object-oriented programming (OOP). More often than not, it&#8217;s a valuable method for modeling data and logic in games. However, because of its near-total dominance of thinking regarding programming in games, I often find &#8230; <a href="https://gamedevwithoutacause.com/?p=1482">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a href="http://gamedevwithoutacause.com/wp-content/uploads/2012/10/Ghost-in-the-Shell-Stand-Alone-Complex-post.jpeg"><img src="http://gamedevwithoutacause.com/wp-content/uploads/2012/10/Ghost-in-the-Shell-Stand-Alone-Complex-post-1024x819.jpeg" alt="" title="Ghost-in-the-Shell-Stand-Alone-Complex-post" width="584" height="467" class="aligncenter size-large wp-image-1483" /></a><br />
Don&#8217;t get me wrong, I&#8217;m not against object-oriented programming (OOP).  More often than not, it&#8217;s a valuable method for modeling data and logic in games.  However, because of its near-total dominance of thinking regarding programming in games, I often find myself playing the anti-OOP advocate in conversations at work.</p>
<p>You see, there are times when designs that look &#8220;right&#8221; when viewed through an OOP lens turn out to be ill-suited to solving certain problems in game programming.  One of the major causes of this is the tendency of OOP to encourage thinking of problems in terms of single data objects.  Often this works because handling multiple instances of an object is a natural extension once you know how to handle a single instance.  This isn&#8217;t always the case however and it&#8217;s common for OOP-oriented programmers (OOPOP?) to overlook cases in which it would be better to think of processing data as a gestalt as opposed to as lists of stand-alone objects.</p>
<p>To clarify this idea, I&#8217;ll share a recent experience with some code at work.<span id="more-1482"></span></p>
<p>The story that follows is a familiar one.  We, the programmers, had adopted a fully-featured game engine with a suitably large codebase.  The engine&#8217;s 3D features were, as to be expected, top-notch.  The engine&#8217;s 2D feature were not quite so developed.  It mainly consisted of a set of functions to draw sprites onto a 2D HUD at particular positions, scales, rotations, etc.  It had no useful UI features like buttons or other widgets nor could it handle hierarchies of sprites.  This meant that any sort of menus beyond the simplest single-depth affairs would be impossibly clumsy to implement.</p>
<p>So, like any good programmer, one of our number set about extending the engine&#8217;s 2D HUD system with our own hierarchal sprite management system as well as some basic widgets.  Throw in some runtime tools for tweaking UI layouts and we were golden.  At least, we were until we started implementing some of the more complicated menus in the game.</p>
<p>You might not notice it at first, but most game menus actually have significant amounts of information being displayed at once.  Unchecked, these menus can result in surprisingly large numbers of sprite renders.  And that&#8217;s what we had in our project.  Lot&#8217;s of sprites being rendered at once and our framerate tanking on our menus.  Heavy menus?  I thought the game itself was supposed to be the heavy part?  What happened?</p>
<p>Well, having the hierarchal sprite system written in a scripting language didn&#8217;t help performance, but that&#8217;s a straight-forward transcription away from being solved.  More to the root of the problem was the design of the hierarchal sprite system itself.  You see, it was almost text-book OOP with &#8220;sprite&#8221; being the core object.  Sprites were independent objects capable of rendering themselves   The first thing the programmer probably did was write code to make sure a single sprite could render itself.  Then, he made sure they could be connected hierarchically, deriving their absolute screen position based on their relative offset from their parent.  </p>
<p>For the most part, that approach makes sense, until you look carefully at how sprites were actually being used.  Almost every sprite we used was the child of another sprite in a multi-level child-parent hierarchy.  We would render our root sprites and expect the render command to travel down to child sprites through the hierarchy.  So far, so good.  But, every sprite was designed to be able to calculate its own absolute screen position.  To do this, each sprite would query its parent&#8217;s absolute position and add its own relative offset.  These absolute position calculations therefore involved climbing back up the hierarchy to the root.  This operation was performed by each child and would only become more expensive as we went deeper down the hierarchy with each depth requiring longer trips back to the root to calculate screen positions.</p>
<p>&#8220;Wow&#8221;, you may say.  &#8220;That behavior is horrid.&#8221;  And you would be right.  If you&#8217;re already traveling down a hierarchy, it makes sense to calculate values like absolute screen position and propagate them downwards as you perform the traversal.  But, it was surprisingly non-obvious from the OOP perspective.  Had the programmer who implemented the sprite system thought in terms of how hierarchies of sprites should be rendered as opposed to how single sprites should render themselves, I imagine he would have written very different code. </p>
<p>Object-oriented programming has a powerful tendency to encourage thinking in terms of single objects and assuming that the handling of multiple instances of said objects is a trivial extension.  For a lot of high-level game logic, this is probably a correct assumption.  But, in cases where you need to process large amounts of data, this sort of single-instance thinking can be debilitating.  While swearing off object-oriented programming would be akin to throwing the baby out with the bathwater, it&#8217;s good practice to occasionally question your own thought process and approach problems from a different angle.</p>
]]></content:encoded>
			<wfw:commentRss>https://gamedevwithoutacause.com/?feed=rss2&#038;p=1482</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
