<?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>Music To Make Games By...</title>
	<atom:link href="http://www.musictomakegamesby.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.musictomakegamesby.com</link>
	<description></description>
	<lastBuildDate>Thu, 29 Jul 2010 06:45:17 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>British Gamedev History: Master of Manic Miner?</title>
		<link>http://www.musictomakegamesby.com/2010/07/28/british-gamedev-history-master-of-manic-miner/</link>
		<comments>http://www.musictomakegamesby.com/2010/07/28/british-gamedev-history-master-of-manic-miner/#comments</comments>
		<pubDate>Wed, 28 Jul 2010 18:47:31 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[Life]]></category>
		<category><![CDATA[British Game Development]]></category>
		<category><![CDATA[Magnetic Scrolls]]></category>
		<category><![CDATA[Manic Miner]]></category>
		<category><![CDATA[Masters Of Doom]]></category>
		<category><![CDATA[Matthew Smith]]></category>
		<category><![CDATA[SmartBomb]]></category>

		<guid isPermaLink="false">http://www.musictomakegamesby.com/?p=666</guid>
		<description><![CDATA[I&#8217;ve always been fascinated with game industry stories. From the first day I started in the business, I&#8217;ve always been eager to hear anecdotes from other people that had seen and heard so much. Many years on now, I&#8217;ve some of my own stories. Some of which I&#8217;m actually part of myself. It&#8217;s kind of [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><img class="size-full wp-image-669  aligncenter" title="Masters Of Doom" src="http://www.musictomakegamesby.com/wp-content/uploads/2010/07/mod.jpg" alt="Masters Of Doom" width="312" height="314" /></p>
<p>I&#8217;ve always been fascinated with game industry stories. From the first day I started in the business, I&#8217;ve always been eager to hear anecdotes from other people that had seen and heard so much. Many years on now, I&#8217;ve some of my own stories. Some of which I&#8217;m actually part of myself. It&#8217;s kind of surreal to feel like I&#8217;m on that other side of the fence now.</p>
<p>Recently I picked up this book again: <a href="http://www.amazon.com/gp/product/0812972155?ie=UTF8&amp;tag=mutomagaby-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0812972155" target="_blank">&#8220;Masters of Doom&#8221;, by David Kushner</a>. It&#8217;s the third time I&#8217;ve read through it. Nuts eh? I don&#8217;t think I&#8217;ve ever read any kind of book that many times over. It&#8217;s just a very well told account of <a href="http://en.wikipedia.org/wiki/Id_Software" target="_blank">id Software</a>&#8216;s birthing, and what happened to the key employees up until around 2003. I&#8217;ve recommended it to several people over the past couple of years, since I first picked it up. In fact it was suggested to me in the first place by a coder colleague here at Neversoft.</p>
<p><span id="more-666"></span>I think what had me going back to it again, was how inspiring a story it is. From being a kid who downloaded the Wolf3D shareware originally from a BBS, and picked up the Doom the same way. The stories in the early half of the book are amazing to me. These people created their own genre, they created groundbreaking tech. To a kid fascinated with videogames, and computer programming these people were my gods!</p>
<p>As someone now who&#8217;s all grown-up, and has coming up to a decade of time in the industry under my belt. These stories still resonate with me, they&#8217;re extremely inspiring, and make you believe that there&#8217;s still room for innovation in the future. I think these days with conservative big-time publishers, you only see that innovation in the indie scene. I really can see something very special coming out of that section of the industry soon.<br />
<br />&nbsp;</p>
<h2>What else is out there?</h2>
<p>Well, that&#8217;s what prompted this post really. There really isn&#8217;t anything that comes close to this book right now. There&#8217;s a real gaping hole here for this stuff. You might say that people interested in the inner workings of the games industry are a very small group. But really, I don&#8217;t think this is the case. Even if you remove the gaming part completely, it&#8217;s a great account of a technical-led success story. I&#8217;m sure books about Steve Jobs and Bill Gates fly off the shelves. I can&#8217;t see why the same can&#8217;t be true about this material either.</p>
<p>There are a couple that I managed to find that I thought could be good reads. The first one looked initially very promising, but on reading the Amazon reviews I was greatly turned off. The book in question being: <a href="http://www.amazon.com/gp/product/B0030ILW9W?ie=UTF8&amp;tag=mutomagaby-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=B0030ILW9" target="_blank">Rogue Leaders: The Story of LucasArts</a>. I adored playing the old point-and-click LucasArts adventure games, so reading about these seemed a real treat. The reviews however mention that these games are only discussed very briefly, and in no sort of detail at all. So not my cup of tea, I&#8217;m not much of a Star Wars fan.</p>
<p style="text-align: center;"><a href="http://www.amazon.com/gp/product/1565125452?ie=UTF8&#038;tag=mutomagaby-20&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=1565125452" target="_new"><img class="size-full wp-image-674 aligncenter" title="SmartBomb" src="http://www.musictomakegamesby.com/wp-content/uploads/2010/07/smartbomb.jpg" alt="SmartBomb" width="196" height="300" /></a></p>
<p>The second book I actually did pick up, and have got just over halfway through. It&#8217;s <a href="http://www.amazon.com/gp/product/1565125452?ie=UTF8&amp;tag=mutomagaby-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=1565125452" target="_blank">SmartBomb</a>. It&#8217;s been a bit of a slog and I think I&#8217;m going to give up on it now. The story about how Atari started was a high-point, interesting stuff that I&#8217;ve not heard about before. But on the other hand you have a poorly-researched version of how <em>id Software</em> got big, and lots of fluff about gaming tournaments and CliffyB&#8217;s visits to trade shows.</p>
<p>The <em>id </em>mistakes were odd. They mentioned their key titles which &#8220;started it all&#8221; were &#8220;Return to Castle Wolfenstein, Doom, and Quake&#8221;&#8230; Doh! To spare their blushes though, they do refer to the correct name &#8220;Wolfenstein 3D&#8221; later on in the chapter. The other doozy I remember was saying that they were told to &#8220;make three games, we&#8217;ll give away the first two for free and sell the third&#8221;. They then referred to that as being Shareware. That&#8217;s probably how my mum would try and describe how Shareware works, if in some bizarro-world she was researching a book like this.</p>
<p>The CliffyB stuff could have been so much better if they had talked some about how he got into the industry in the first place. I still have no idea if he ever wrote code himself. I mean take <a href="http://en.wikipedia.org/wiki/Sid_Meier" target="_blank">Sid Meier</a>, he actually <a href="http://www.mobygames.com/game/dos/sid-meiers-civilization/credits" target="_blank">coded Civilization</a> as well as designing it. Not that it takes away from his designer skills if he&#8217;s not a coder. I&#8217;m just curious, I enjoyed &#8216;Jack Jackrabbit&#8217; back in the day. In the book his early days are relegated to one sentence that mentions he sent off a floppy disk in a ziploc bag. MobyGames actually says he did some games before Jack, but his role isn&#8217;t clear. <a href="http://www.mobygames.com/game/win3x/dare-to-dream-volume-one-in-a-darkened-room/credits" target="_blank">At least one</a> seems to indicate he did the whole thing himself. Anyway, <strong><a href="http://gamingisstupid.com/2007/12/17/the-chair-story-original/" target="_blank"><b>this</b></a> </strong>is a far more entertaining CliffyB story. Even though it is completely made up. <img src='http://www.musictomakegamesby.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
<br />&nbsp;</p>
<h2>Engerlund, Engerlund!</h2>
<p>As I tend to do when I write these blog posts, I&#8217;m going off track. The real point of this post, and the namesake of the post itself is about <strong>British </strong>game developers. Why is there absolutely nothing written about them in books? I also feel whenever I read any sort of modern game website about the &#8216;good old days&#8217;; it&#8217;s always just Atari, Nintendo and the Apple II. There was another golden-age of gaming, from the mid 80&#8242;s through to the early 90&#8242;s. This one occurred and originated in Britain. Take the Spectrum, the C64 (and the <a href="http://www.musictomakegamesby.com/2010/05/21/xnacpc-an-amstrad-cpc-emulator-for-the-xbox-360/" target="_blank">Amstrad</a>!). Then you&#8217;ve got the Amiga, and in turn some PC and console conversions of the same games. There&#8217;s so many good games for those systems. Nowadays though whenever a modern site like Kotaku gets misty-eyed, it&#8217;s like these games never existed.</p>
<p>Elite? I don&#8217;t think I&#8217;ve met an American who knows what that game is. Manic Miner? No chance.</p>
<p><a href="http://en.wikipedia.org/wiki/Manic_Miner" target="_blank">Manic Miner</a> is a good one to pick up on. It pre-dates &#8220;Super Mario Bros.&#8221; on the NES by almost two years. Whilst it&#8217;s missing the scrolling element of Mario, it was at the time a revelation in the British home computer market. The author, <a href="http://en.wikipedia.org/wiki/Matthew_Smith_%28games_programmer%29" target="_blank">Matthew Smith</a> famously dropped off the face of the planet after the follow-up: &#8220;Jet Set Willy&#8221;. He apparently joined a commune in The Netherlands, and stayed there for a number of years. Take a gander at this <a href="http://www.youtube.com/watch?v=FWmmMZlhcqU" target="_blank">YouTube</a> clip for some nostalgia. The gangly-guy on the new &#8220;Doctor Who?&#8221; is <strong>the </strong>Matt Smith eh? No, Mr. Manic Miner is <strong>the </strong>Matt Smith, and always will be. <img src='http://www.musictomakegamesby.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
<center><br />
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="480" height="385" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/FWmmMZlhcqU&amp;hl=en_US&amp;fs=1" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="480" height="385" src="http://www.youtube.com/v/FWmmMZlhcqU&amp;hl=en_US&amp;fs=1" allowscriptaccess="always" allowfullscreen="true"></embed></object> <br /><em>&#8220;our really sad friends even wrote their own&#8221;</em></center><br />
Seriously though, how is Matt&#8217;s story <em>not </em>interesting? If you can&#8217;t fill up a whole book with it (which really is questionable), why not add some other figures from the same era?<br />
<br />
Take &#8216;Magnetic Scrolls&#8217;. A company which funnily enough was just a short drive from where I grew up. Nestled alongside what was the first &#8216;Special Reserve&#8217; game shop in the country. I remember passing by it as a youngster and really wanting to go in that office. My own personal nostalgia aside, they made some great games. Text-adventures, a lost artform but at the time were hugely popular. (I was also a great fan of &#8216;Level 9&#8242;, another British text-adventure company).<br />
<br />
Magnetic Scrolls had connections with Infocom and Douglas Adams. Douglas Adams being of &#8220;Hitchhikers Guide to the Galaxy&#8221; fame. They were actually at one point working on the <a href="http://waxy.org/2008/04/milliways_infocoms_unreleased_sequel_to_hitchhikers_guide_to_the_galax/" target="_blank">sequel to that game</a>. Seems that some people working there were <a href="http://msmemorial.if-legends.org/games.htm/guild.php" target="_blank">good friends with Adams</a>. You just need to skim the link about the sequel to Hitchhikers to realize that there&#8217;s a hell of a lot to that story, and in turn the story of Magnetic Scrolls.<br />
<br />
That&#8217;s just a couple of examples. Here&#8217;s a few more I can think of:<br />
<br />&nbsp;</p>
<ul>
<li>Elite. Just mentioning this one again. Braben has his own company now, curious as to why Ian Bell didn&#8217;t join him. The game itself was a groundbreaking use of procedurally-generated worlds on a huge scale.</li>
<li>Mythos Games. Laser Squad, Lords of Chaos, and the X-COM/UFO games of course. Turn-based strategy joy.</li>
<li>Imagine. No really outstanding games I remember, but there&#8217;s a very interesting backstory about how piracy killed the company.</li>
<li>Codemasters. The Darling brothers, and the Oliver twins. Redefined the pricing model for games at the time, selling (mostly) quality newly developed games at budget prices.
<li>The Bitmap Brothers. Speedball and The Chaos Engine. Outstanding art-style. Best looking games out at the time.</li>
<li>Psygnosis. Nuff said. They are now SCEE Liverpool.</li>
<li>Rare. Killer Instinct, Goldeneye 64, Donkey Kong Country. They used to be &#8216;Ultimate: Play The Game&#8217;. Sure there&#8217;s a good story there. Throw in some &#8216;Mr. Pants&#8217; and it&#8217;s gold.</li>
<li>Molyneux and Bullfrog; Syndicate, Populous, Dungeon Keeper, Magic Carpet. All groundbreaking, classic games.</li>
<li>The GTA guys up at Rockstar North. Tie in the <a href="http://www.youtube.com/watch?v=f14k2j9V33Q" target="_blank">DMA design</a> days too, and you&#8217;ve quite a story. Lemmings is an all-time great.</li>
</ul>
<p>Anyway, just some food for thought. There&#8217;s a gap in the market here for someone willing to put in the research time. Can&#8217;t see why it wouldn&#8217;t sell well. The GTA stuff would probably sell it in the States! <img src='http://www.musictomakegamesby.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.musictomakegamesby.com/2010/07/28/british-gamedev-history-master-of-manic-miner/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>XNACPC &#8211; An Amstrad CPC Emulator for the Xbox 360</title>
		<link>http://www.musictomakegamesby.com/2010/05/21/xnacpc-an-amstrad-cpc-emulator-for-the-xbox-360/</link>
		<comments>http://www.musictomakegamesby.com/2010/05/21/xnacpc-an-amstrad-cpc-emulator-for-the-xbox-360/#comments</comments>
		<pubDate>Fri, 21 May 2010 17:17:58 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[Life]]></category>
		<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[amstrad]]></category>
		<category><![CDATA[amstrad cpc]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[emulator]]></category>
		<category><![CDATA[Xbox]]></category>
		<category><![CDATA[Xbox 360]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.musictomakegamesby.com/?p=621</guid>
		<description><![CDATA[A few weeks ago I mentioned on twitter that I was working on an Amstrad CPC emulator, written in XNA. There are plenty of the things for the PC and various other consoles, but not one for the Xbox 360 yet. So it seemed a cool little exercise to undertake. A long time ago, I [...]]]></description>
			<content:encoded><![CDATA[<p align=center><img src="http://www.musictomakegamesby.com/wp-content/uploads/2010/05/cpcemulator.jpg" alt="" title="CPC464" width="529" height="322" class="aligncenter size-full wp-image-630" /></p>
<p>A few weeks ago I mentioned on <a href="http://twitter.com/gavin_pugh" target="_new">twitter</a> that I was working on an <a href="http://en.wikipedia.org/wiki/Amstrad_CPC" target="_new">Amstrad CPC</a> emulator, written in XNA. There are plenty of the things for the PC and various other consoles, but not one for the Xbox 360 yet. So it seemed a cool little exercise to undertake.</p>
<p>A long time ago, I wrote one of my own for the PC. The website I setup for it is still live, <a href="http://www.angelfire.com/retro2/cpc3d/" target="_new">here</a>. I developed it initially around 1997. Back then I’d pretty much just gotten it to be able to boot, and be able to type things on the keyboard. I revisited it a few years later when I needed something flashy for my portfolio, around the time I was trying to break into the games industry. With that version I managed to get a handful of games running nicely.</p>
<p><span id="more-621"></span></p>
<h3>Little bit of history</h3>
<p>I used to be really into the emulation scene back in the day. The first one I stumbled upon was on a <a href="http://en.wikipedia.org/wiki/Bulletin_board_system" target="_new">BBS</a>, some random BBS I found in the pages of <a href="http://www.computershopper.co.uk/" target="_new">Computer Shopper</a> (wow, that mag is still going!). My father used to go to his work to wash his car on the odd weekend here and there. I used to use his Apple Mac computer when he was doing that, was one of the old Mac Quadras. This would have been around 1993 I think, so I’d have been a spritely twelve or thirteen years old at the time!</p>
<p>Anyhow, I’d use some terminal software on the Mac, downloading various interesting programming bits and bobs via the trusty <a href="http://en.wikipedia.org/wiki/ZMODEM" target="_new">ZMODEM</a> protocol. One weekend I was stunned to see something called CPCEMU. This was the first Amstrad emulator ever to see the light of day. I didn’t even know such a thing was possible at the time; I’d pretty much figured that it could well be a joke download. So after copying my weekend’s haul to a floppy as per-usual, I was excited to give it a try.</p>
<p>This software and much of the rest of the stuff I downloaded was PC-only. I didn’t have a PC at home at the time; I’d just use the ones at my school during lunchtimes. It was really cool to see the emulator fire up on that PC at school. Unfortunately though the Amstrad ROM wasn’t included in the package, so all that worked out of the box was a single sample game written to interface directly with the hardware. That year I remember my ‘big’ Christmas present was a 3.5” disc drive for the Amstrad, primarily so I could dump the ROMs from the machine so I could get the emulator working! What a nerd. <img src='http://www.musictomakegamesby.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Around the time I’d also written in to the only remaining Amstrad CPC magazine in production: Amstrad Action. They had some feature where they asked readers to write in with any sort of Amstrad-related article, and they’d print them up in some sort of ‘readers articles’ feature. This never actually happened though unfortunately; they never did run any reader articles. I’d written one in about CPCEMU, whilst it never appeared I did get a mention in the magazine. After a little googling, I managed to find it:</p>
<div align=center><b><i><br />
<a href="http://www.musictomakegamesby.com/wp-content/uploads/2010/05/aa104-08.jpg"><img src="http://www.musictomakegamesby.com/wp-content/uploads/2010/05/aa104-08-212x300.jpg" alt="" title="aa104-08" width="212" height="300" class="size-medium wp-image-632" /></a> <br />Amstrad Action – #104 – May 1994 (click for larger image)<br /></b></i></div>
<p>&nbsp;</p>
<p>Brought a smile to my face seeing it after all these years!</p>
<h3>Other emulators</h3>
<p>There were a number of other emulators I ‘followed’ back in the day too. <a href="http://www.zophar.net/genesis/genem.html" target="_new">GenEm</a>; the first SEGA Genesis / Megadrive emulator out there, was one in particular. Was really something to see it improve over time. From humble beginnings where only a handful of early-era games are only playable. Through to audio emulation working (the Genesis/MD has a second processor; a Z80 funnily enough, which is primarily used for audio in games). Around this time was an explosion in emulators in general, for all sorts of other videogame systems of similar eras. There was a bit of a race between coders to get their emulator to be the most fully featured, with the highest game-compatibility rate. Competition drives technology, I guess?</p>
<p>Some other ones I remember too were <a href="http://www.zophar.net/genesis/kgen.html" target="_new">KGEN</a> and <a href="http://www.zophar.net/genesis.html" target="_new">DGEN</a>. But the real leap at the time I recall was <a href="http://bloodlust.zophar.net/gen/genecyst.html" target="_new">Genecyst</a>. It was really leaps and bounds above the other ones out at the time. The same guy (or group) that coded it also wrote the impressive <a href="http://bloodlust.zophar.net/Callus/callus.html" target="_new">Callus</a>, and <a href="http://bloodlust.zophar.net/NESticle/nes.html" target="_new">NESticle</a>. Both landmarks at the time, particularly Callus which I think was the first Capcom arcade emulator that ran at a playable speed.  </p>
<div align=center><b><i><br />
<img src="http://www.musictomakegamesby.com/wp-content/uploads/2010/05/Genecyst.jpg" alt="" title="Genecyst" width="250" height="219" class="alignnone size-full wp-image-644" /><br />The UI for Genecyst, all emulators for the era were in DOS. Unlike most, this one had a GUI too<br /></b></i></div>
<p>&nbsp;</p>
<p>I also remember <a href="http://en.wikipedia.org/wiki/Executor_%28software%29" target="_new">Executor</a> well too, an Apple Mac emulator. This one took an interesting approach of not making use of any System ROMs at all. They essentially reverse-engineered the Mac. The emulation effectively emulated the services/OS calls that the system ROM would have provided. This I think was more of a legal choice than a practical one, but it must have been an interesting technical challenge. They updated it pretty often, it seemed like every week there was a new one to try that had a new slate of improvements. Unfortunately it was a paid-for emulator. I think it had a time restriction on it, it worked for ten minutes and then quit out. That was a rarity back then in the emulator scene.</p>
<div align=center><b><i><br />
<img src="http://www.musictomakegamesby.com/wp-content/uploads/2010/05/Executor_emu.jpg" alt="" title="Executor_emu" width="350" height="274" class="alignnone size-full wp-image-647" /><br />Screenshot of Executor in action<br /></b></i></div>
<p>&nbsp;</p>
<p>As I was looking for stuff for this article, I was surprised to see that it’s now open-source. I think now there’s probably several other Mac emulators which take the more traditional approach, and have a near 100% compatibility with a real 68k-era Mac. I wonder how well it sold throughout its lifetime?</p>
<h3>An XNA CPC Emulator</h3>
<p>Christ; I do go on like an old woman, don’t I? <img src='http://www.musictomakegamesby.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>The point of this article was meant to be about the Xbox 360 version of the emulator I’m working on. I did most of the work for it over a weekend, about a month ago. The missus was away for work, and I had a nice block of time to tackle it. I essentially just used my previous emulator I wrote a few years prior, in plain C. I rewrote it in C#, in a much more OO-way.</p>
<p>It was as a pretty straightforward process. As I’d done with my older emulator, I took the Z80 CPU emulation from an existing source. Someone has already coded a ZX Spectrum emulator in C#, so I took the CPU code from there. The <a href="http://zx360.codeplex.com/" target="_new">Zx360 project</a>. I had to make a few modifications though. One was based on how memory is accessed on the CPC, to handle the ROM and RAM banking. The other was for the way interrupts are handled. I know very little about the Spectrum, but it seems like they do behave pretty differently in that regard.</p>
<p>So, dusting off the cobwebby corners of my mind, I got to implementing all the various bits of hardware of the machine. Using both my old source, and the <a href="http://cpctech.cpc-live.com/" target="_new">Unofficial Amstrad WWW Resource</a> for reference. The code quality was like night and day compared to my old plain-C implementation. That’s I guess what thirteen years experience will help you out a bit with! It a joy to debug too; all the little components of the machine browsable in the Visual Studio debugger, in a nice OO-d tree!</p>
<p>I worked on the actual XNA-specific parts last. Getting the screen drawn, and getting input working that is. It’s just as cool as I remember when you get that startup screen rendering the very first time. This old thing:</p>
<div align=center><b><i><br />
<img src="http://www.musictomakegamesby.com/wp-content/uploads/2010/05/boot.jpg" alt="" title="XNACPC Boot" width="500" height="375" class="alignnone size-full wp-image-649" /><br />XNACPC bootup, the Amstrad CPC 464 startup screen<br /></b></i></div>
<p>&nbsp;</p>
<p> I then went on to get snapshot (.SNA) support working so I could load up memory snapshots of games. That was awesome to see as well. It had the exact same level of compatibility as my older emulator. I was a little worried the new Z80 core code could have some bugs or issues, but it seems solid now. So anyway, the same games that ran fine worked fine on this too. But of course the same ones with issues, also had issues on my new emulator too. Once I’d played a few games on the Xbox itself, I took a break from the project for a while.</p>
<div align=center><b><i><br />
<img src="http://www.musictomakegamesby.com/wp-content/uploads/2010/05/rointime.jpg" alt="" title="XNACPC Roland In Time" width="500" height="375" class="alignnone size-full wp-image-651" /><br />The classic ‘Roland in Time’ running on XNACPC, on an Xbox 360<br /></b></i></div>
<p>&nbsp;</p>
<h3>A bit later on</h3>
<p>What I really wanted to add was proper audio support. I dabbled for a while using XACT; playing a sound and messing with the pitch and volume of it. But it had pretty hideous results. It was encouraging to hear the tunes in there somewhere, but it really didn’t work well at all. What led me to stop bothering with this method was news that XNA 4.0 has nicer audio support. Specifically the class <a href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.audio.dynamicsoundeffectinstance%28XNAGameStudio.40%29.aspx" target="_new">DynamicSoundEffectInstance</a>. This class allows playback of raw audio data, not just samples. Exactly what an emulator needs.</p>
<p>The other avenue I wanted to make improvements on was to how I emulate the video hardware. My older emulator took a very naïve approach. It didn’t make any effort to emulate vsync, hsync or tie in the CPU interrupts with any of it. Over the past few weeks I’ve had some time here and there to mess with this stuff, and attempt to get something better working. I’m pretty pleased with the results. I managed to get split-screen working. Which means ‘Sorcery’, one of the classic CPC titles is now fully playable and looks just like the original.</p>
<div align=center><b><i><br />
<img src="http://www.musictomakegamesby.com/wp-content/uploads/2010/05/sorcery.jpg" alt="" title="XNACPC Sorcery" width="500" height="375" class="alignnone size-full wp-image-652" /><br />Sorcery on XNACPC &#8211; A CRTC-splitscreen game<br /></b></i></div>
<p>&nbsp;</p>
<p>I’ve still a way to go though. My CRTC and video emulation isn’t quite up to par with some of the more accomplished emulators already out on PC. Well, that’s an understatement; it’s truly awful compared to most of those emulators! But it’s something I can improve at my leisure. <img src='http://www.musictomakegamesby.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>I plan to release the source code for the emulator, specifically once I’ve got my video code a little more stable. Whether that’s a matter of weeks or months, I don’t know. I’m pretty busy at the moment with <a href="http://www.neversoft.com" target="_new">work</a>, so it may take a fair while. I’d probably expect it to be after XNA 4.0 is released too, since I’d probably get some crude level of audio support in once it’s out. I’d dabble with the <a href="http://creators.xna.com/en-US/downloads" target="_new">CTP version</a> that’s out now, but I’m really targeting Xbox which is not supported just yet. Yes, I could write the code on PC. But I really like firing up the emulator on the Xbox, and seeing the cool stuff running on there first. I can be patient&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.musictomakegamesby.com/2010/05/21/xnacpc-an-amstrad-cpc-emulator-for-the-xbox-360/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>XNA/C# &#8211; Thread.CurrentThread is slow on Xbox 360</title>
		<link>http://www.musictomakegamesby.com/2010/04/30/xnac-thread-currentthread-is-slow-on-xbox-360/</link>
		<comments>http://www.musictomakegamesby.com/2010/04/30/xnac-thread-currentthread-is-slow-on-xbox-360/#comments</comments>
		<pubDate>Fri, 30 Apr 2010 17:01:46 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CurrentThread]]></category>
		<category><![CDATA[CurrentThreadLite]]></category>
		<category><![CDATA[StringBuilder]]></category>
		<category><![CDATA[Thread]]></category>
		<category><![CDATA[Thread.CurrentThread]]></category>
		<category><![CDATA[Xbox]]></category>
		<category><![CDATA[Xbox 360]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.musictomakegamesby.com/?p=538</guid>
		<description><![CDATA[I’ve still a few more XNA articles I’ve been planning to write. The next one was to involve some threading code, and in the process of creating the article I hit upon something that I found concerning. The title of this article pretty much gives it away before I can casually introduce it; the property [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><img class="size-full wp-image-283  aligncenter" title="ThreadStatic XNA" src="http://www.musictomakegamesby.com/wp-content/uploads/2010/03/threadpic.jpg" alt="ThreadStatic XNA" width="250" height="250" /></p>
<p>I’ve still a few more XNA articles I’ve been planning to write. The next one was to involve some threading code, and in the process of creating the article I hit upon something that I found concerning. </p>
<p>The title of this article pretty much gives it away before I can casually introduce it; the property method <strong>Thread.CurrentThread</strong> is slow on the Xbox. Specifically it’s slow compared to running the same code on a Windows PC. I’d imagine the same applies to the other Compact Framework platforms too; the Zune and Windows 7 Phones. But I can’t say for sure.<br />
<span id="more-538"></span></p>
<h3>Bone-headed code</h3>
<p>I stumbled upon this whilst trying to profile some of my code for a future threading article. I had two different techniques I was comparing, and I couldn’t for the life of me understand why one was an order of magnitude slower than the other. It just didn’t make any sense. </p>
<p>What I’d done in one of them was to assume that <strong>Thread.CurrentThread</strong> is cheap, and simply returns some kind of easy to grab variable. This isn’t the case. I can illustrate by showing you the exact piece of code that was slow:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span> <span style="color: #FF0000;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> MAX_THREADS<span style="color: #008000;">;</span> i<span style="color: #008000;">++</span> <span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span> m_data<span style="color: #000000;">&#91;</span>i<span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">m_thread_id</span> <span style="color: #008000;">==</span> Thread.<span style="color: #0000FF;">CurrentThread</span> <span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> m_data<span style="color: #000000;">&#91;</span>i<span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">m_data</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Then I changed my slower technique to ‘match’ the faster one, by prefetching the current thread:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Thread thread_id <span style="color: #008000;">=</span> Thread.<span style="color: #0000FF;">CurrentThread</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span> <span style="color: #FF0000;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> MAX_THREADS<span style="color: #008000;">;</span> i<span style="color: #008000;">++</span> <span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span> m_data<span style="color: #000000;">&#91;</span>i<span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">m_thread_id</span> <span style="color: #008000;">==</span> thread_id <span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> m_data<span style="color: #000000;">&#91;</span>i<span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">m_data</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Yes, seems a no-brainer doesn’t it? In most cases it does make sense to prefetch variables like that, but I’d been a little silly and assumed there would be negligible difference from not doing so. I’d had some harebrained ideal that the optimizing compiler and the JIT-er would effectively make these two bits of code the same. On my Windows PC build they actually do execute in almost the same amount of time, certainly not different to the same degree as on Xbox.</p>
<p>It makes total sense that it doesn’t get optimized on either platform though. If you look at <strong>Thread.CurrentThread </strong>in the <a href="http://www.red-gate.com/products/reflector/" target="_new">.NET Reflector</a>, it calls an external DLL function. The compiler (or JIT-er) can’t be expected to think that the return value of that function will be the same for each iteration of the loop.</p>
<h3>So, how slow is it?</h3>
<p>My first port of call after I realized the big timesink, was to directly compare the performance between the Windows PC build and the Xbox 360 build. My test code was as follows, a loop accessing Thread.CurrentThread a million times:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Thread thread <span style="color: #008000;">=</span> null<span style="color: #008000;">;</span>
<span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span> <span style="color: #FF0000;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> <span style="color: #FF0000;">1000000</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span> <span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    thread <span style="color: #008000;">=</span> Thread.<span style="color: #0000FF;">CurrentThread</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Here’s how long it took on each platform:</p>
<table>
<tr>
<td width=100px></td>
<td width=300px>
<strong> Windows PC Release Build</strong><br />
<strong>Not in debugger, JIT-ed </strong> </td>
<td>0.0088s
</td>
</tr>
<tr height=15px>
<td width=100px></td>
<td width=300px></td>
<td>
</td>
</tr>
<tr>
<td width=100px></td>
<td width=300px>
<strong> Xbox 360 Release Build</strong><br />
<strong>Not in debugger, JIT-ed </strong> </td>
<td>4.95s
</td>
</tr>
</table>
<p>&nbsp;</p>
<p>Calling Thread.CurrentThread on the Xbox 360 is over five hundred (500!) times slower than on PC. That’s not good! The PC I’m using is nothing special, it’s a three year old Core Duo ‘1’ laptop. So I’m not running some ridiculous PC rig to see these large differences in speeds.</p>
<p>For the code I was working on, I modified it to call Thread.CurrentThread once at the start of my worker thread. I then pass this Thread object through to the other methods that I used, which are called often within that worker thread. So where these methods used to call CurrentThread multiple times themselves before, they no longer needed to. The Thread object for this worker thread was simply passed around instead. The code doesn’t look quite as nice of course, but it’s hardly a disaster.</p>
<p>The particular test I was doing with that worker thread code ran over one hundred times faster with that change made. This was still a bit of a micro-benchmark though, calling some small pieces of code a ridiculous number of times… Regardless, I was just trying to battle-test something that I’d want to use in practice. Using Thread.CurrentThread was an integral part of that.</p>
<p>What I ended up doing was having the facility to optionally pass in a Thread object if the user has one. If they didn’t, it would end up resorting to the slow Thread.CurrentThread instead. This seemed like an ideal solution.</p>
<h3>CurrentThreadLite</h3>
<p>When looking at the CurrentThread property accessor in <a href="http://www.red-gate.com/products/reflector/" target="_new">.NET Reflector</a>, I traced through to the DLL function which is ultimately called:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> Thread CurrentThread
<span style="color: #000000;">&#123;</span>
    get
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> PAL.<span style="color: #0000FF;">Threading_Thread_CurrentThread</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #000000;">&#91;</span>DllImport<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;mscoree&quot;</span>, EntryPoint<span style="color: #008000;">=</span><span style="color: #666666;">&quot;#210&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">extern</span> Thread Threading_Thread_CurrentThread<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Listed alongside this particular function was this other similarly-named one; CurrentThreadLite:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>DllImport<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;mscoree&quot;</span>, EntryPoint<span style="color: #008000;">=</span><span style="color: #666666;">&quot;#211&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">extern</span> IntPtr Threading_Thread_CurrentThreadLite<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>That’s interesting. It returns a different type, an integer pointer a opposed to a Thread object. But for my purposes I just wanted to uniquely identify a thread. If it’s faster, then it&#8217;s ideal for what I need. The suffix &#8216;lite&#8217; sounds promising!</p>
<p>I tried to see what .NET code actually uses it, it’s these methods:</p>
<p><img class="alignnone size-full wp-image-556" title="CurrentThreadLite" src="http://www.musictomakegamesby.com/wp-content/uploads/2010/04/CurrentThreadLite.png" alt="CurrentThreadLite" width="440" height="170" /></p>
<p>At least within the .NET executable that I was inspecting. There are probably other .NET library methods that make use of it. I’m not too experienced with the reflector, so I’m totally unsure of a good way of finding them.</p>
<p><strong> </strong></p>
<h4>Lite execution</h4>
<p>So I was curious about whether this ‘lite’ version was faster than the ‘full’ version on Xbox 360. A google search yielded an extremely small number of results for CurrentThreadLite, and variations of it. I figured as part of this small article I may as well have a little go at seeing if it does perform better. It may help someone else out in future who stumbles upon this page.</p>
<p>The main problem though is that there’s no direct accessor to it. Nothing at all. The StringBuilder object makes use of it to maintain thread-safety on its mutable strings, which I’ve touched on in previous articles. Using the same method I described in <a href="http://www.musictomakegamesby.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/" target="_new">this article</a>, I can grab the private member that stores the ‘IntPtr’ thread.</p>
<p>This does mean that I’ll be adding the overhead of both reflection, and likely some allocations within StringBuilder too. Given the limited set of methods I have to play with, I doubt I’ll end up with anything workable within a game. This really is purely a bit of an educational investigation now, unfortunately there&#8217;s not going to be anything that I&#8217;d consider usable.</p>
<h4>A crude performance test</h4>
<p>I picked out one StringBuilder method which calls CurrentThreadLite: <strong>Append(String)</strong>. You can see the source to this method here:</p>
<p><a href="http://labs.developerfusion.co.uk/SourceViewer/view/SSCLI/System.Text/StringBuilder/" target="_new">http://labs.developerfusion.co.uk/SourceViewer/view/SSCLI/System.Text/StringBuilder/</a></p>
<p>The .NET library code though calls a method with a different name than the reflector tells us. The prototype of which is:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>MethodImplAttribute<span style="color: #000000;">&#40;</span>MethodImplOptions.<span style="color: #0000FF;">InternalCall</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">static</span> <span style="color: #0600FF;">internal</span> <span style="color: #0600FF;">extern</span> IntPtr InternalGetCurrentThread<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>I think I can safely assume this just calls through to <b>CurrentThreadLite</b>.</p>
<p>Anyway, if I pass ‘String.Empty’ as a parameter to Append() it’ll end up doing very little work. But <strong>CurrentThreadLite</strong> will be ran though, so it’d be a good indicator as to whether it’s faster to execute than the ‘full’ one.</p>
<p>Here’s the code I’m testing with, same one million-times loop as before:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">StringBuilder string_builder <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StringBuilder<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span> <span style="color: #FF0000;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> <span style="color: #FF0000;">1000000</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span> <span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    string_builder.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span> <span style="color: #FF0000;">String</span>.<span style="color: #0000FF;">Empty</span> <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Here’s the results:</p>
<table>
<tr>
<td width=100px></td>
<td width=300px>
<strong> Xbox 360 Release Build</strong><br />
<strong>Not in debugger, JIT-ed </strong> </td>
<td>0.407s
</td>
</tr>
</table>
<p>&nbsp;</p>
<p>So it’s over ten times faster than the ‘full’ CurrentThread property accessor, the one I tested further up this article. That’s pretty cool! It makes sense that StringBuilder would use this over CurrentThread, if it were available. If they didn’t, any mutable change to a string would be ten times slower than it is now. That said, it still lags a lot behind PC; being around fifty times slower than that platform.</p>
<p>To reiterate though; unfortunately there&#8217;s no exposed direct access to <b>CurrentThreadLite</b>. As far as I can tell there&#8217;s no workable way of making use of it. I&#8217;d love someone to tell me otherwise though, it&#8217;d be awesome if I could use it.</p>
<h3>StringBuilder though is still pretty slow on Xbox 360</h3>
<p>In a <a href="http://www.musictomakegamesby.com/2010/04/05/xnac-a-garbage-free-stringbuilder-format-method/" target="_new">previous article</a>, I profiled some string manipulation code I’d written. Even though I was implementing alternate methods to what StringBuilder provides, in the end I still called their <strong>Append()</strong>. So I’d be incurring the hit from calling CurrentThreadLite too. It probably explains why the Xbox was running over ten times slower than PC.</p>
<p>I wonder if I can use reflection to grab the raw char[] data, and the string length. Then as long as I keep my code thread-safe by other means, I could work directly on the char[] buffer and concatenate strings myself. This would effectively do away with the overhead of checking what the current thread is, which is within all the existing StringBuilder mutable methods. Even though <b>CurrentThreadLite</b> is seemingly no slouch, it&#8217;s still not exactly cheap.</p>
<p>Something to think about… If it brings performance of StringBuilder in line with PC, then it certainly seems worth it. Whether it&#8217;s worth it for an XNA game though is arguable. Still, I found it interesting looking into this corner of C#.</p>
<h3>References</h3>
<ul>
<li><a href="http://labs.developerfusion.co.uk/SourceViewer/view/SSCLI/System.Threading/Thread/" target="_blank">http://labs.developerfusion.co.uk/SourceViewer/view/SSCLI/System.Threading/Thread/</a></li>
<li><a href="http://labs.developerfusion.co.uk/SourceViewer/view/SSCLI/System.Text/StringBuilder/" target="_blank">http://labs.developerfusion.co.uk/SourceViewer/view/SSCLI/System.Text/StringBuilder/</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.currentthread.aspx" target="_blank">http://msdn.microsoft.com/en-us/library/system.threading.thread.currentthread.aspx</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.musictomakegamesby.com/2010/04/30/xnac-thread-currentthread-is-slow-on-xbox-360/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>XNA/C# &#8211; A garbage-free StringBuilder Format() method</title>
		<link>http://www.musictomakegamesby.com/2010/04/05/xnac-a-garbage-free-stringbuilder-format-method/</link>
		<comments>http://www.musictomakegamesby.com/2010/04/05/xnac-a-garbage-free-stringbuilder-format-method/#comments</comments>
		<pubDate>Mon, 05 Apr 2010 16:42:38 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[360]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[format]]></category>
		<category><![CDATA[garbage]]></category>
		<category><![CDATA[StringBuilder]]></category>
		<category><![CDATA[Xbox]]></category>
		<category><![CDATA[Xbox 360]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.musictomakegamesby.com/?p=472</guid>
		<description><![CDATA[So, another entry in this StringBuilder and garbage series… This time I’m exploring the Format() method, and implementing a new alternative that does not generate any garbage. The existing AppendFormat() method on StringBuilder generates a significant amount of garbage. So in what way does the .NET one generate garbage? Well, the parameter type is ‘object’, [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><img class="size-full wp-image-475 aligncenter" title="27garbage_600" src="http://www.musictomakegamesby.com/wp-content/uploads/2010/03/27garbage_600.jpg" alt="" width="600" height="280" /></p>
<p>So, another entry in this StringBuilder and garbage series… This time I’m exploring the Format() method, and implementing a new alternative that does not generate any garbage. The existing AppendFormat() method on StringBuilder generates a significant amount of garbage.</p>
<p>So in what way does the .NET one generate garbage? Well, the parameter type is ‘object’, so you’ll get boxing and unboxing of value types. Since integers and floats are pretty oft-used with Format(), that’s not good news. With CLRProfiler I also see temporary allocations made in ‘String::ToCharArray()’, and ‘String::CtorCharArrayStartLength()’. There’s also more garbage if you use more than three arguments; for that it requires a temporary array to be created.</p>
<p>All in all, it’s not a pretty picture if you want to avoid garbage collections in your game.</p>
<p><span id="more-472"></span></p>
<h3>Variable arguments</h3>
<p>The AppendFormat() method takes a string parameter, then a series of parameter arguments. The amount of these can vary, and they can be of a different types too. So how best pass these in? Well, there are a number of different methods. Take a look at the ones StringBuilder provides as standard:<strong> </strong></p>
<ul>
<li>StringBuilder AppendFormat( string format, params object[] args );</li>
<li>StringBuilder AppendFormat( IFormatProvider provider, string format, params object[] args );</li>
<li>StringBuilder AppendFormat( string format, object arg0 );</li>
<li>StringBuilder AppendFormat( string format, object arg0, object arg1 );</li>
<li>StringBuilder AppendFormat( string format, object arg0, object arg1, object arg2 );</li>
</ul>
<p>Each of these uses object params. Object params are subject to boxing and unboxing with value types. Since I’d want to pass integers and floats through, this isn’t good. The other thing I noticed was that array parameters using the ‘params’ keyword cause a temporary allocation too. Even without using the object type, take this simplified example:<strong> </strong></p>
<p><strong>public void TestMethod( params int[] args );</strong></p>
<p>Any call to this method generates garbage. The ‘params’ keyword essentially converts any params you might specify into an array. The array of integers in this case is allocated as a temporary and then destroyed. The same thing happens when using class types too, not just value types. A different tact is required here.</p>
<p>There were two approaches I explored to support a variable set of arguments, without generating garbage. One of these I went with and will explain now, the other one I explain later on this article in the ‘Things to try’ section. The approach I chose uses generics, and unfortunately a method is required to be implemented for each number of parameters I’d want to support. Other than that though, it’s a really good fit for this problem.</p>
<h3>The implementation</h3>
<p>So, there are two main problems to solve here:</p>
<ul>
<li> Support a variable number of arguments of arbitrary types</li>
<li> Be able to use these types, perform any conversion required and concatenate them onto a StringBuilder</li>
</ul>
<p>For the former, I&#8217;m just using generics. For each number of parameters I need to support, I&#8217;ll need to write a new method. This multiple versions of the same method, but with a different number of parameters isn’t too pretty. It reminds me of C++ template abuse, stuff like the <a href="http://sigslot.sourceforge.net/" target="_blank">sig_slot library</a>.</p>
<p>But here it gets the job done, and it’s kind of your classic C# stuff in a way. There’s no support for default parameters in C#. So for different arguments you generally have to have wrapper methods to support different sets of parameters.</p>
<p>Casting generics is not like C++. My first thought was something like:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">static</span> <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> FormatArgument<span style="color: #000000;">&#40;</span> StringBuilder string_builder, T arg <span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span> arg.<span style="color: #0000FF;">GetType</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">==</span> <span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #FF0000;">int</span> int_arg <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span><span style="color: #000000;">&#41;</span>arg<span style="color: #008000;">;</span>
        string_builder.<span style="color: #0000FF;">Concat</span><span style="color: #000000;">&#40;</span> int_arg <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>But the straight casting like this is not allowed. There does seem to be a couple of methods to convert types though. At least these were the two I found, both these examples are with integers:</p>
<ul>
<li><strong>Convert.ToInt32( arg )</strong></li>
<li><strong>Arg.ToInt32( System.Globalization.NumberFormatInfo.CurrentInfo )</strong></li>
</ul>
<p>Both have their downfalls. Convert.ToInt32() generates garbage, which makes it unusable for my purpose. The latter one though doesn’t generate garbage, but it is only available on types that implement <strong>IConvertible</strong>. Fortunately all the types I wanted to use (string, int, float) all implement IConvertible. However some other types that would be nice to support, such as Math.Vector don’t. I went with this method, and in turn had to limit the arguments to IConvertibles using the ‘where’ keyword.</p>
<p>That’s about it for the nitty-gritty on some of my decisions. The rest of the code is just a classic char-by-char over the formatted string. It’ll look for the ‘{‘ open curly bracket character and then use the Concat() methods from my previous article to push in the parameters. So, here’s the code:</p>
<p><a href="http://www.musictomakegamesby.com/source/StringBuilderExtFormat.zip"><br />
<img class="alignleft size-full wp-image-437" style="vertical-align: middle;" title="zip_file" src="http://www.musictomakegamesby.com/wp-content/uploads/2010/04/zip_file.png" alt="Zip File" width="48" height="52" /><strong> StringBuilderExtFormat.zip</strong></a></p>
<h3>Performance</h3>
<p>I was definitely curious as to how my code performs. There&#8217;s certainly more scope for optimization, but I&#8217;m not keen on spending time on it unless it&#8217;s something to worry about. Using the <strong>Stopwatch</strong> class I measured the runtime of this piece of code:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">string_builder.<span style="color: #0000FF;">ConcatFormat</span><span style="color: #000000;">&#40;</span>
    <span style="color: #666666;">&quot;Test {0:0.0000} Test {1:X} Test {2} {3}&quot;</span>,
    3.45111111f, 0xBEEF, <span style="color: #FF0000;">12345678</span>, <span style="color: #666666;">&quot;Hello World&quot;</span> <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>A nice taxing formatted string with varied parameters. Here’s a table of the performance figures, they are measured from a loop calling this method 1,000,000 times.</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="162" valign="top"></td>
<td colspan="2" width="231" valign="top"><strong>Windows   PC</strong></td>
<td colspan="2" width="245" valign="top"><strong>Xbox   360</strong></td>
</tr>
<tr>
<td width="162" valign="top"></td>
<td width="120" valign="top">.NET’s</td>
<td width="111" valign="top">Mine</td>
<td width="126" valign="top">.NET’s</td>
<td width="118" valign="top">Mine</td>
</tr>
<tr>
<td width="162" valign="top">Unoptimized build<br />
- In debugger</td>
<td width="120" valign="top">2.43s</td>
<td width="111" valign="top">3.23s</td>
<td width="126" valign="top">27.57s</td>
<td width="118" valign="top">32.03s</td>
</tr>
<tr>
<td width="162" valign="top">Optimized build<br />
- In debugger</td>
<td width="120" valign="top">2.43s</td>
<td width="111" valign="top">2.61s</td>
<td width="126" valign="top">27.57s</td>
<td width="118" valign="top">28.43s</td>
</tr>
<tr>
<td width="162" valign="top">Optimized build<br />
- No debugger, jit-ed</td>
<td width="120" valign="top">2.38s</td>
<td width="111" valign="top"><strong>1.84s</strong></td>
<td width="126" valign="top">20.33s</td>
<td width="118" valign="top"><strong>18.03s</strong></td>
</tr>
<tr>
<td width="162" valign="top">Garbage generated</td>
<td width="120" valign="top">284MB</td>
<td width="111" valign="top"><strong>0 bytes</strong></td>
<td width="126" valign="top">381MB</td>
<td width="118" valign="top"><strong>0 bytes</strong></td>
</tr>
</tbody>
</table>
<p>&nbsp;<br />
For both times and garbage, smaller is better! <img src='http://www.musictomakegamesby.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>The notable thing is that the native AppendFormat() performs the same when optimized or not. I’m not entirely familiar with the in’s and out’s of .NET assemblies just yet. But I do wonder if I could put these routines in a separate library. Then whether I can set things up so that they are jit-ed, regardless of whether my main code module is ran in the debugger or not. Not something I’m too interested in right now, but just throwing it out there. I’m sure google is my friend on this one!</p>
<p>Anyhow, I’m happy that on the final build of the game I’ll have better performance than the stock .NET method. Also with significantly less garbage of course. There’s plenty of scope for optimization on my methods too, they’re pretty much a naïve first-go in all cases. With a little time and effort I think a good chunk could come off these times. Knowing it performs well though is good enough for me right now, I’ll give it more attention down the road if I need to.</p>
<h3>Things to try</h3>
<h4>A Format() that does everything?</h4>
<p>Obviously the version I’ve written doesn’t offer anywhere near the same fully-featured functionality as the stock .NET Format(). I don’t envision myself needing any more features for a game though to be honest. If I did come across something I wanted it wouldn’t be too much of a pain to implement I’m sure. But, take a look at the .NET docs, and the AppendFormat() source code:</p>
<p><a href="http://labs.developerfusion.co.uk/SourceViewer/view/SSCLI/System.Text/StringBuilder/" target="_blank">http://labs.developerfusion.co.uk/SourceViewer/view/SSCLI/System.Text/StringBuilder/</a></p>
<p>The AppendFormat() in StringBuilder is the one that is also used by System.String and I’d assume the rest of the .NET code. Using this source and any documentation for the formatting specifiers, it’d be possible to implement the same level of functionality but using my techniques to avoid garbage. Quite a task though I’d think!<br />
&nbsp;</p>
<h4>Supporting arbitrary parameter types</h4>
<p>Another thing to give a go, is a second method of variable arguments I played around with. A method that doesn’t use generics, but instead uses a base class. For an example, here’s a method prototype with two arguments:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> StringBuilder ConcatFormat<span style="color: #000000;">&#40;</span> <span style="color: #0600FF;">this</span> StringBuilder string_builder,
    <span style="color: #FF0000;">String</span> format_string, FormatArgument arg1, FormatArgument arg2 <span style="color: #000000;">&#41;</span></pre></div></div>

<p>The ‘FormatArgument’ class is an abstract base class. What you’d do is implement subclasses for each supported type, i.e.:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> FormatArgumentInt <span style="color: #008000;">:</span> FormatArgument</pre></div></div>

<p>Then have a virtual method for appending the type into the StringBuilder. The crux of this whole technique is in the use of implicit constructors. So that depending on the argument you specify to ConcatFormat(), you’ll get it converted into a new FormatArgument type. Here’s an example:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">implicit</span> <span style="color: #0600FF;">operator</span> FormatArgument<span style="color: #000000;">&#40;</span> <span style="color: #FF0000;">int</span> value <span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    FormatArgumentInt arg <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> FormatArgumentInt<span style="color: #000000;">&#40;</span> value <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">return</span> arg<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Hey, this example allocates a temporary class therefore generates garbage when used? Indeed it does, but you can use a pool container to deal with this. Pre-allocating all of these and dealing out pool items when they’re created solves the garbage issue. You’ll also need to manually dispose of them and add them back to the pool.</p>
<p>It’s a lot of work. The big upside is that you can support any types, such as Math.Matrix and Vector. It’d be cool to be able to use those if you’re using Format() for debugging. In my experiments though, performance wasn’t too hot, it was in the region of 1.5-2 times slower than the generics method I detailed earlier. The code also becomes a lot more unwieldy; the generics method looked like a work of art by comparison!</p>
<p>Maybe there’s a way of using the generics method on arbitrary non-IConvertible types? Without incurring garbage on the conversions too of course.<br />
&nbsp;</p>
<h4>Printf</h4>
<p>I like the positional arguments of C#’s Format. C/C++’s printf() stipulates that the argument list has to be used in the same order that the params are specified in the formatting string. This makes the .NET way useful for localizations particularly, where something like:</p>
<p><strong>Player {0} got {1} points!</strong></p>
<p>Could become:</p>
<p><strong>Allez {1} punts spiele {0}!  </strong> &lt;&lt; Just a made-up foreign language</strong></p>
<p>Essentially the translation requires those parameters to appear in a different order. With printf() it’s painful to do this correctly.</p>
<p>That said though if you’ve used printf() for over a decade like I have, switching to Format() might not be quite as fun. So why not implement printf() in C#? It’s really only a minor modification over the code I provide above. I was a little tempted myself, but I really want to stick with doing things the C# way for now. <img src='http://www.musictomakegamesby.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h3>References</h3>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.iconvertible.aspx" target="_blank">http://msdn.microsoft.com/en-us/library/system.iconvertible.aspx</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.convert%28VS.71%29.aspx" target="_blank">http://msdn.microsoft.com/en-us/library/system.convert%28VS.71%29.aspx</a></li>
<li><a href="http://blog.stevex.net/string-formatting-in-csharp/" target="_blank">http://blog.stevex.net/string-formatting-in-csharp/</a></li>
<li><a href="http://www.codeproject.com/KB/cs/Csharp_implicit_operator.aspx" target="_blank">http://www.codeproject.com/KB/cs/Csharp_implicit_operator.aspx</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.musictomakegamesby.com/2010/04/05/xnac-a-garbage-free-stringbuilder-format-method/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>XNA/C# &#8211; Avoiding garbage when working with StringBuilder</title>
		<link>http://www.musictomakegamesby.com/2010/04/01/xnac-avoiding-garbage-when-working-with-stringbuilder/</link>
		<comments>http://www.musictomakegamesby.com/2010/04/01/xnac-avoiding-garbage-when-working-with-stringbuilder/#comments</comments>
		<pubDate>Thu, 01 Apr 2010 15:23:54 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[360]]></category>
		<category><![CDATA[append]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[concat]]></category>
		<category><![CDATA[float]]></category>
		<category><![CDATA[garbage]]></category>
		<category><![CDATA[integer]]></category>
		<category><![CDATA[itoa]]></category>
		<category><![CDATA[StringBuilder]]></category>
		<category><![CDATA[Xbox]]></category>
		<category><![CDATA[Xbox 360]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.musictomakegamesby.com/?p=392</guid>
		<description><![CDATA[In my previous coding post, I spoke about some issues with converting a mutable StringBuilder string back to a regular ‘string’ object without generating garbage. Well, specifically without requiring an unnecessary heap allocation. One thing I hinted at was that StringBuilder has a number of other methods which generate garbage too. In fact, there are [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><img class="aligncenter size-full wp-image-418" title="Garbage" src="http://www.musictomakegamesby.com/wp-content/uploads/2010/03/garbage.jpg" alt="Garbage" width="620" height="300" /></p>
<p>In my <a href="http://www.musictomakegamesby.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/" target="_blank">previous coding post</a>, I spoke about some issues with converting a mutable StringBuilder string back to a regular ‘string’ object without generating garbage. Well, specifically without requiring an unnecessary heap allocation. One thing I hinted at was that StringBuilder has a number of other methods which generate garbage too. In fact, there are a lot of important fundamental methods which do, which are difficult to live without.</p>
<p>As I&#8217;ve mentioned before, worrying about this sort of thing may not be necessary for the game you&#8217;re working on. It&#8217;s much more of a concern on Xbox 360 than PC, due to the poorly performing garbage collector on 360. If your game isn&#8217;t something that&#8217;s going to remotely push the hardware, or be impacted by dropped frames, then you really don&#8217;t need to worry. This article is just for those who may see this as an issue, and want to explore ways to eliminate this particular method of generating garbage.<br />
<span id="more-392"></span></p>
<h3>Problem StringBuilder methods</h3>
<p>So, here&#8217;s a table of all the methods StringBuilder has. My test case used a StringBuilder constructed with an initial capacity of 1024 characters. This is plenty for anything I threw at it, so any garbage I found with <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=a362781c-3870-43be-8926-862b40aa0cd0&amp;displaylang=en" target="_blank">CLRProfiler</a> was not something associated with reallocating the StringBuilder internal string. In the cases where there&#8217;s garbage generated I&#8217;ve commented with the most interesting or appropriate function in the callstack. In many cases it&#8217;s just exactly the same method, but with the function signature reported by CLRProfiler.</p>
<table border="0" cellspacing="0" cellpadding="0" width="661">
<col width="331"></col>
<col width="71"></col>
<col width="259"></col>
<tbody>
<tr height="20">
<td width="331" height="20"></td>
<td width="71"><span style="text-decoration: underline;"><strong>Garbage</strong></span></td>
<td width="259"><span style="text-decoration: underline;"><strong>Pertinent Allocation / Notes<br />
</strong></span></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(bool value);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(byte value);</td>
<td><strong>Yes</strong></td>
<td>Append(unsigned int8)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(char value);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(char[] value);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(decimal value);</td>
<td><strong>Yes</strong></td>
<td>Append(System.Decimal)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(double value);</td>
<td><strong>Yes</strong></td>
<td>Append(float64)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(float value);</td>
<td><strong>Yes</strong></td>
<td>Append(float32)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(int value);</td>
<td><strong>Yes</strong></td>
<td>Append(int32)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(long value);</td>
<td><strong>Yes</strong></td>
<td>Append(int64)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(object value);</td>
<td><strong>Yes</strong></td>
<td>object::ToString()</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(sbyte value);</td>
<td><strong>Yes</strong></td>
<td>Append(int8)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(short value);</td>
<td><strong>Yes</strong></td>
<td>Append(int16)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(string value);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(uint value);</td>
<td><strong>Yes</strong></td>
<td>Append(unsigned int32)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(ulong value);</td>
<td><strong>Yes</strong></td>
<td>Append(unsigned int64)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(ushort value);</td>
<td><strong>Yes</strong></td>
<td>Append(unsigned int16)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(char value, int   repeatCount);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(char[] value, &#8230;);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Append(string value, &#8230;);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20"></td>
<td></td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder AppendFormat(&#8230;); <em>(all   five)</em></td>
<td><strong>Yes</strong></td>
<td>In all cases, even without args</td>
</tr>
<tr height="20">
<td height="20"></td>
<td></td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder AppendLine();</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder AppendLine(string value);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20"></td>
<td></td>
<td></td>
</tr>
<tr height="20">
<td height="20">void CopyTo(&#8230;);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20"></td>
<td></td>
<td></td>
</tr>
<tr height="20">
<td height="20">int EnsureCapacity(int capacity);</td>
<td><strong>Yes</strong></td>
<td>If capacity param &gt; current capacity</td>
</tr>
<tr height="20">
<td height="20"></td>
<td></td>
<td></td>
</tr>
<tr height="20">
<td height="20">bool Equals(StringBuilder sb);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20"></td>
<td></td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, bool   value);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, byte   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, unsigned int8)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, char   value);</td>
<td><strong>Yes</strong></td>
<td>String::CtorCharCount()</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, char[]   value);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, decimal   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, System.Decimal)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, double   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, float64)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, float   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, float32)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, int   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, int32)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, long   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, int64)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, object   value);</td>
<td><strong>Yes</strong></td>
<td>object::ToString()</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, sbyte   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, int8)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, short   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, int16)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, string   value);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, uint   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, unsigned int32)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, ulong   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, unsigned int64)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, ushort   value);</td>
<td><strong>Yes</strong></td>
<td>Insert(int32, unsigned int16)</td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, string   value, &#8230;);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Insert(int index, char[]   value, &#8230;);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20"></td>
<td></td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Remove(int startIndex, int   length);</td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20"></td>
<td></td>
<td></td>
</tr>
<tr height="20">
<td height="20">StringBuilder Replace(&#8230;); <em>(all four)</em></td>
<td>No</td>
<td></td>
</tr>
<tr height="20">
<td height="20"></td>
<td></td>
<td></td>
</tr>
<tr height="20">
<td height="20">override string ToString();</td>
<td><strong>Yes*</strong></td>
<td>See my <a href="http://www.musictomakegamesby.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/" target="_blank">previous article</a></td>
</tr>
<tr height="20">
<td height="20">string ToString(int startIndex, int   length);</td>
<td><strong>Yes*</strong></td>
<td>String::InternalSubString()</td>
</tr>
</tbody>
</table>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden;">
<table style="border-collapse: collapse; width: 495pt;" border="0" cellspacing="0" cellpadding="0" width="661">
<col style="width: 248pt;" width="331"></col>
<col style="width: 53pt;" width="71"></col>
<col style="width: 194pt;" width="259"></col>
<tbody>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt; width: 248pt;" width="331" height="20"></td>
<td class="xl65" style="width: 53pt;" width="71">Garbage</td>
<td class="xl65" style="width: 194pt;" width="259">Pertient Allocation</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(bool value);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(byte value);</td>
<td class="xl66">Yes</td>
<td>Append(unsigned int8)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(char value);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(char[] value);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(decimal value);</td>
<td class="xl66">Yes</td>
<td>Append(System.Decimal)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(double value);</td>
<td class="xl66">Yes</td>
<td>Append(float64)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(float value);</td>
<td class="xl66">Yes</td>
<td>Append(float32)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(int value);</td>
<td class="xl66">Yes</td>
<td>Append(int32)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(long value);</td>
<td class="xl66">Yes</td>
<td>Append(int64)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(object value);</td>
<td class="xl66">Yes</td>
<td>ToString()</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(sbyte value);</td>
<td class="xl66">Yes</td>
<td>Append(int8)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(short value);</td>
<td class="xl66">Yes</td>
<td>Append(int16)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(string value);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(uint value);</td>
<td class="xl66">Yes</td>
<td>Append(unsigned int32)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(ulong value);</td>
<td class="xl66">Yes</td>
<td>Append(unsigned int64)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(ushort value);</td>
<td class="xl66">Yes</td>
<td>Append(unsigned int16)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(char value, int   repeatCount);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(char[] value, &#8230;);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Append(string value, &#8230;);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20"></td>
<td></td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder AppendFormat(&#8230;); (all   five)</td>
<td class="xl66">Yes</td>
<td>String::ToCharArray(), even without args</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20"></td>
<td></td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder AppendLine();</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder AppendLine(string value);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20"></td>
<td></td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">void CopyTo(&#8230;); (all)</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20"></td>
<td></td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">int EnsureCapacity(int capacity);</td>
<td class="xl66">Yes, if capacity param &gt; current capacity</td>
<td>StringBuilder::GetNewString()</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20"></td>
<td></td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">bool Equals(StringBuilder sb);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20"></td>
<td></td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, bool   value);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, byte   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, unsigned int8)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, char   value);</td>
<td class="xl66">Yes</td>
<td>String::CtorCharCount()</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, char[]   value);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, decimal   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, System.Decimal)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, double   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, float64)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, float   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, float32)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, int   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, int32)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, long   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, int64)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, object   value);</td>
<td class="xl66">Yes</td>
<td>ToString()</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, sbyte   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, int8)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, short   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, int16)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, string   value);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, uint   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, unsigned int32)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, ulong   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, unsigned int64)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, ushort   value);</td>
<td class="xl66">Yes</td>
<td>Insert(int32, unsigned int16)</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, string   value, &#8230;);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Insert(int index, char[]   value, &#8230;);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20"></td>
<td></td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Remove(int startIndex, int   length);</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20"></td>
<td></td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">StringBuilder Replace(&#8230;); (all four)</td>
<td class="xl67">No</td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20"></td>
<td class="xl67"></td>
<td></td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">override string ToString();</td>
<td class="xl66">Yes</td>
<td>String::InternalCopy()</td>
</tr>
<tr style="height: 15pt;" height="20">
<td style="height: 15pt;" height="20">string ToString(int startIndex, int   length);</td>
<td class="xl66">Yes</td>
<td>String::InternalSubString()</td>
</tr>
</tbody>
</table>
</div>
<h6><em>* Technically you could describe these as not generating garbage, simply allocating a new string for the client to use. Certainly for the latter of these it makes sense, the term garbage is a little incorrect. But for the former, hence my previous article, it&#8217;s unnecessary and can be avoided with a little work.</em></h6>
<p><em><br />
</em></p>
<p>The common theme for garbage here is type-conversion. Anything that isn&#8217;t a string or char type is pretty much guaranteed to generate it.  &#8216;<strong>bool</strong>&#8216; is an oddball I think probably because it inserts string literals: &#8216;false&#8217; and &#8216;true&#8217;, so no conversion is needed. The other peculiar one is the <strong>Insert( int, char )</strong> one, it generates garbage when logically it doesn&#8217;t really need to. Oddly the .NET library source code says it calls Char.ToString() on the char parameter. Possibly just an oversight in the library?</p>
<p>The reasoning for the type conversions generating garbage, is that they return a temporary string converting that type to a string. This string is then fed into the StringBuilder, and then discarded. Whilst it could have been done in-place, I think the reason why it isn&#8217;t is to support <a href="http://www.musictomakegamesby.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/" target="_blank">CultureInfo</a> modifiers on the conversion. Where that conversion could take place in a different way based on the passed in CultureInfo. StringBuilder internally uses CultureInfo.CurrentCulture.</p>
<p>I think the implementation chosen was for simplicity and clarity of the type conversions. Writing a system to perform these type conversions in-place <strong>and</strong> have the flexibility of what CultureInfo offers, would have likely made the code significantly more complex. I can understand their reasoning completely.</p>
<h3>Appending numeric types without generating garbage</h3>
<p>For this article I specifically wanted to detail a replacement for those type conversion methods. These are ones you&#8217;d definitely need for a game, for at least your HUD readouts. Since these could be updated every frame, using the garbage-churning .NET library methods isn&#8217;t going to be pretty.</p>
<p>The replacement methodology I used was pretty simple; a number of methods don&#8217;t generate garbage, so use those to build up the string. This effectively means implementing an <a href="http://en.wikipedia.org/wiki/Itoa" target="_blank">itoa()</a> in C#, a conversion of an integer into string form. Floating point numbers too being handled in much the same way. My implementation is via C#&#8217;s extension methods. So the new garbage-free versions of Append() can be called directly on a StringBuilder object, as if they came with the original framework.</p>
<p>Here&#8217;s the code for download:<br />
<a href="http://www.musictomakegamesby.com/source/StringBuilderExtNumeric.cs"><br />
<img class="alignleft size-full wp-image-437" style="vertical-align: middle;" title="cs_file" src="http://www.musictomakegamesby.com/wp-content/uploads/2010/03/cs_file.png" alt="C# File" width="48" height="52" /><strong>StringBuilderExtNumeric.cs</strong></a></p>
<p>Since Append() is already taken, I chose Concat() as my alternative. There&#8217;s additional functionality over what&#8217;s offered by default in StringBuilder, to aid formatting of text. For floats you&#8217;re able to specify the amount of decimal places. For all numeric types you can specify the amount of padding, and the padding character used (most likely zero or space). Lastly, integers can be output with a specific base value, so your code could output hex, binary and octal if so desired.</p>
<p>Here&#8217;s a short made-up example of it&#8217;s usage:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">StringBuilder m_hud_health_string <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StringBuilder<span style="color: #000000;">&#40;</span> <span style="color: #FF0000;">64</span>, <span style="color: #FF0000;">64</span> <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
StringBuilder m_hud_ammo_string <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StringBuilder<span style="color: #000000;">&#40;</span> <span style="color: #FF0000;">64</span>, <span style="color: #FF0000;">64</span> <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> UpdateHUDStrings<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// Note: It's sensible to create a wrapper for Concat( string ), which just calls</span>
    <span style="color: #008080; font-style: italic;">// Append() to avoid mixing these method names. When JIT-ing, it would be inlined.</span>
&nbsp;
    m_hud_health_string.<span style="color: #0000FF;">Length</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>                    <span style="color: #008080; font-style: italic;">//&lt; Clear the string</span>
    m_hud_health_string.<span style="color: #0000FF;">Concat</span><span style="color: #000000;">&#40;</span> GetCurrentHealth<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>   <span style="color: #008080; font-style: italic;">//&lt; This method returns an int</span>
    m_hud_health_string.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span> <span style="color: #666666;">&quot; / &quot;</span> <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    m_hud_health_string.<span style="color: #0000FF;">Concat</span><span style="color: #000000;">&#40;</span> GetMaximumHealth<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>   <span style="color: #008080; font-style: italic;">//&lt; This method returns an int</span>
&nbsp;
    m_hud_ammo_string.<span style="color: #0000FF;">Length</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>                      <span style="color: #008080; font-style: italic;">//&lt; Clear the string</span>
    m_hud_ammo_string.<span style="color: #0000FF;">Concat</span><span style="color: #000000;">&#40;</span> GetBulletsInAmmoClip<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">//&lt; This method returns an int</span>
    m_hud_ammo_string.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span> <span style="color: #666666;">&quot; ( &quot;</span> <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    m_hud_ammo_string.<span style="color: #0000FF;">Concat</span><span style="color: #000000;">&#40;</span> GetNumAmmoClips<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>      <span style="color: #008080; font-style: italic;">//&lt; This method returns an int</span>
    m_hud_ammo_string.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span> <span style="color: #666666;">&quot; )&quot;</span> <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>But, what about Format(), I hear you cry? It can sometimes be easier to format more complex strings, and can result in much cleaner code than multiple appends/concats. Well, I have a garbage-free one of those too. I&#8217;ll cover its implementation next time I write about C# here.</p>
<h3>Some other things to try</h3>
<p>The code I’ve written <span style="text-decoration: line-through;">probably</span> (definitely) could be optimized further. In case you need to do this, or if you’re just curious and want to play around, I’ve got a few ideas of things to try:</p>
<ul>
<li> Different code for the oft-used base ten. You’re now modulo-ing and dividing by a constant, and passing one less parameter around. You can also just add characters by using ( ‘0’ + value ), instead of using the static char array. The static char array is just used since the hex ‘A-F’ don’t follow ‘9’ in the ascii table.</li>
<li> Try using a static char[] array to generate the string you’re about to append, and just call Append() once on the StringBuilder. StringBuilder keeps itself thread-safe and has other overhead on most of its members. So I think this would result in a speedup, by just making one mutable interaction with the StringBuilder.<br />
Keep in mind that you’ll want to make this array a [ThreadStatic] (thread-local store), so that you can use the code on multiple threads without issue.</li>
<li> Take a look at these two websites for some more ideas:<br />
<a href="http://www.jb.man.ac.uk/~slowe/cpp/itoa.html" target="_blank">Coverage  of some common C implementations</a>, along with some performance  comparisons.<br />
<a href="http://sourceforge.net/projects/itoa/" target="_blank">A bit of a different approach using C++</a>, potentially may throw up something applicable to C#.</li>
</ul>
<p>Another thing worth considering is to wrap up the StringBuilder into a new type. Maybe a struct is a good idea, to save making another heap allocation when creating them. The reasoning behind this is to hide away the garbage-generating methods. So all you’re exposing are the safe, garbage-free methods. It also saves you having to awkwardly come up with a different method name, such as ‘Concat()’, like I did. Another win for this methodology is that you could write operator overloads to support ‘+=’, to perform concatenations too.</p>
<h3>References</h3>
<ul>
<li><a href="http://forums.xna.com/forums/p/16395/87923.aspx" target="_blank">http://forums.xna.com/forums/p/16395/87923.aspx</a></li>
<li><a href="http://www.jb.man.ac.uk/~slowe/cpp/itoa.html" target="_blank">http://www.jb.man.ac.uk/~slowe/cpp/itoa.html</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.musictomakegamesby.com/2010/04/01/xnac-avoiding-garbage-when-working-with-stringbuilder/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Deadly Premonition – A flawed gem?</title>
		<link>http://www.musictomakegamesby.com/2010/03/24/deadly-premonition-%e2%80%93-a-flawed-gem/</link>
		<comments>http://www.musictomakegamesby.com/2010/03/24/deadly-premonition-%e2%80%93-a-flawed-gem/#comments</comments>
		<pubDate>Wed, 24 Mar 2010 20:33:01 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[New Games]]></category>

		<guid isPermaLink="false">http://www.musictomakegamesby.com/?p=338</guid>
		<description><![CDATA[Back when I last had a little spurt of writing in this blog, I really wanted to talk about ‘Pathologic’. An awesome, unique PC game certainly unlike any other game I’ve played before. Its survival horror pushed to extremes. The development house is based in Russia; Ice Pick Lodge. I’ve much respect for the game, [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><img class="size-full wp-image-339 aligncenter" title="Deadly Premonition" src="http://www.musictomakegamesby.com/wp-content/uploads/2010/03/deadly1.jpg" alt="Deadly Premonition" width="610" height="300" /></p>
<p>Back when I last had a little spurt of writing in this blog, I really wanted to talk about <a href="http://en.wikipedia.org/wiki/Pathologic" target="_blank"><strong>‘Pathologic’</strong></a>.</p>
<p>An awesome, unique PC game certainly unlike any other game I’ve played before. Its survival horror pushed to extremes. The development house is based in Russia; <a href="http://www.ice-pick.com/" target="_blank">Ice Pick Lodge</a>.</p>
<p>I’ve much respect for the game, I tip my hat to a fantastic achievement. My sole disappointment was just that only few people got to experience this gem. Maybe when I play through a second time as a different character: ‘Haruspicus’, I’ll get the gumption to write about it to convince the small readership of this blog to give it a try. <img src='http://www.musictomakegamesby.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Knowing that day will likely never come, please read this review:</p>
<p><a href="http://www.rockpapershotgun.com/2008/04/10/butchering-pathologic-part-1-the-body/" target="_blank">http://www.rockpapershotgun.com/2008/04/10/butchering-pathologic-part-1-the-body/</a></p>
<p>It’s what led me to give it a try in the first place. It’s an old game, so go easy on the graphical criticism… Speaking of which!</p>
<p><span id="more-338"></span><br />
<h3>Deadly Premonition – A ‘B Game’, as in ‘B Movie’?</h3>
<p>Aye, not the prettiest game on the eyes given we’re talking an Xbox 360 game. But really, it’s another time to ignore that. How I link this to Pathologic isn’t too direct, the games share some similar elements in how they expand the survival aspect of gameplay. They’re both very unique games, very different to the usual AAA fare.</p>
<p>The fuss over its <a href="http://www.metacritic.com/games/platforms/xbox360/deadlypremonition" target="_blank">review scores</a> is what led to me noticing the game. I suspect all the furor over it has led to it getting nice sales. Oh, by the way; did I mention that Deadly Premonition is a new release and priced at only $20? Unfortunately European guys, it’s not released out there yet and the US version is apparently region-locked. It’s quite a shame.</p>
<p>What I’m about to write about is free of spoilers. With a game like this I really wanted to avoid reading too far down into reviews. I’ll respect anyone reading this by attempting to just lure you into buying it and not ruin any of the nice surprises in the game. I haven’t got too far into the game, I’m only a little after the investigation of the crime scene. Probably only three to four hours in.</p>
<h3>First Impressions</h3>
<p>When I first fired up the game it was what I was expecting. Nice initial cutscene to set the mood. The devs have their names flash up during the opening sequence too, kind of like COD4 in a way. I was a little surprised to see that the devs are all Japanese; I didn’t remember reading that in the reviews that I skimmed. Things fall into place now; I can’t see a Western dev attempting a game like this. It’s ‘M-rated’ too. If this were a big budget game I’m sure the publishers would have them water it down to a ‘T-teen’ rating, and market it as a CSI-style game. Thank god that didn’t happen! I’m real curious as to how long the game was in development, does anyone know?</p>
<p style="text-align: center;">
<img class="aligncenter size-full wp-image-349" title="Deadly Premonition2" src="http://www.musictomakegamesby.com/wp-content/uploads/2010/03/deadly2.jpg" alt="Deadly Premonition" width="610" height="300" /></p>
<p>My first warning when picking up the game is that you will be a little frustrated with how gameplay starts out. It’s not long before you’re dealing with combat. Yes, there is combat in this game but it doesn’t seem to be the main focus of the title at all. If you get the game and give up whilst you’re in that first part of combat; you’ll be missing out for sure. Persevere.</p>
<p>Also, one big tip I can give which didn’t seem to be mentioned in the manual, nor on-screen is that holding ‘B’ and another face button together will speed up the text scrolling. You can also press start to skip any scrolling text. The game has a number of rough edges which frustrate me as a coder. The sort of things that if I were set loose on the code for a week, I’d have fixed immediately. Here’s a few that come to mind:</p>
<h4>Minor annoyances:</h4>
<ul>
<li>Animations such as opening doors begin to feel too long, and are unskippable.</li>
<li>Cutscenes can’t be paused, or at least I haven’t found a way how. The guide button doesn’t pause them unfortunately.</li>
<li>The pause menu is a little clunky and slow</li>
<li>The world map doesn’t zoom out far enough. It also doesn’t appear on the HUD during combat at all, which is frustrating.</li>
<li>Saving is a little arduous. If autosave is enabled, when I use a telephone to save the game, I shouldn’t get a bunch of confirmation UI screens.</li>
<li>Collision. A couple of times I’ve got caught on a ninety degree concave edge of a room. The player control should be a little more forgiving and push you around if you’re close to the edge.</li>
<li>They spell &#8216;Turkey Sandwich&#8217; as &#8216;Turky Sandwich&#8217;[sic] at one point in the game! Unforgivable! <img src='http://www.musictomakegamesby.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
</ul>
<p>Wow! I’m doing the game lots of favours here eh? Who’d want to play this mess? Well, the game is a breath of fresh air in 360-land. It’s awesomeness I simply do not have the superlatives for. Here are some things I think rock about this game:</p>
<h4>Premonition of greatness:</h4>
<ul>
<li>Voiceovers. These really shine. Compared to say the Bethesda games: Fallout 3 and Oblivion… There’s so much charm to it, and it really highlights how soulless the VO on those games sound sometimes (they’re great games of course, just one criticism I have of them). The game treads a fine line between comedy and horror, and the style fits it extremely well.</li>
<li>The music. It’s fantastic! It’s simple stuff and I haven’t heard many different tunes but the cues alongside the cutscenes, and the way it sometimes drowns out the dialog… It just feels right. The main protagonist is a little ‘special’, so I see it as him drifting off into la-la land when it happens.</li>
<li>The story. It’s a pretty gripping one. Despite the bat-shit insaneness where the game steps into comedy, the storyline is always intriguing. You actually care about what happens, and moreso you’re wanting to see what the slightly insane twists on what’s coming next could be.</li>
<li>Survival elements. I like that you need to make sure that your car has topped up petrol. I like that you need to sleep and stave off your hunger. Apparently too you have to change clothing as the days progress otherwise people start to think you smell. I liked the similar mechanics in <a href="http://en.wikipedia.org/wiki/Pathologic" target="_blank">Pathologic</a> too. Where on something like GTA: San Andreas they can become annoying; here these mechanics suit a survival horror game perfectly.</li>
<li>Open-world gameplay. Near the beginning of the game you’ll meet up with some locals who want you to drive them somewhere. You can leave them at any time, and when you meet up with them again later they’ll be pissed at you for leaving them waiting. The cutscene transitions during open-world gameplay are pretty cool too, big thumbs up.</li>
<li>It&#8217;s GTA meets Resident Evil, meets Maniac Mansion, meets CSI, meets Criminal Minds (unsub!), meets Spaced, meets Twin Peaks. What’s not to love about that?</li>
<li>Laughter, fun, entertainment. It&#8217;s easy to forget sometimes that games can be fun! Take some serious gruff-voiced guy, who’s built like a brick-outhouse. Navigate him through a repetitive dull environment; it&#8217;s what the kids seem to like now. The vibe of this game is different, wholly unique; it&#8217;s something I&#8217;d recommend to anyone who thinks that games are an artform.</li>
</ul>
<p style="text-align: center;">
<img class="aligncenter size-full wp-image-351" title="Deadly Premonition3" src="http://www.musictomakegamesby.com/wp-content/uploads/2010/03/deadly3.jpg" alt="Deadly Premonition" width="610" height="300" /></p>
<p>One third and final list now. From what I remember of when I skimmed  reviews, there were a number of things that were mentioned as negatives  that I really think are no big deal at all. Granted I’m only a small  portion through the game, but I have encountered and seen pretty much  all the things that have been complained about. Whether the charm lasts  is another matter, but I feel like I’ll get my money’s worth out of this  game for sure.</p>
<h4>Don’t you love journos?:</h4>
<ul>
<li>The graphics. C’mon, this is a budget title. The characters in my opinion are above the quality of most PS2 games. The outside environments probably on par with early PS2-era games, the interiors look much better. Go have a wank over the latest Final Fantasy if pretty scenery is what does it for you.</li>
<li>The combat, the camera, the controls. They take a little getting used to; by the second section of combat I was a dab hand with the FBI issue shooter. The complaints here are probably because the controls don’t match the ‘generic third-person game’ controls. Whatever; it’s not hard to get to grips with them.</li>
<li>The sparse environment. There are actually a lot of residents in Greenvale. The story though is of a town which had a boom a few decades back due to a buoyant lumber trade. The town now is relatively empty since those days. The hospital is too big for what the town needs; the hotel is almost empty. Sounds perfect for survival horror?</li>
<li>Terrible writing, terrible story, terrible voiceovers. You must have really missed the point.</li>
</ul>
<p>So there, go play it. It’s only $20!  If you don’t like it, go trade it for a grey and brown shooter; there’s plenty sitting in Gamestop. <img src='http://www.musictomakegamesby.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.musictomakegamesby.com/2010/03/24/deadly-premonition-%e2%80%93-a-flawed-gem/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XNA/C# &#8211; StringBuilder to String with no garbage</title>
		<link>http://www.musictomakegamesby.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/</link>
		<comments>http://www.musictomakegamesby.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/#comments</comments>
		<pubDate>Wed, 24 Mar 2010 05:50:32 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[360]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[garbage]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[StringBuilder]]></category>
		<category><![CDATA[Xbox]]></category>
		<category><![CDATA[Xbox 360]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.musictomakegamesby.com/?p=298</guid>
		<description><![CDATA[In my day job I’m a bit of a stickler with memory. I’m at times approaching borderline OCD I think with budgets and fragmentation. Having a good handle on memory usage on a game is very important; once you start pushing a console’s limits you can cause a lot of headaches down the road if [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><img class="size-full wp-image-299  aligncenter" title="String Garbage" src="http://www.musictomakegamesby.com/wp-content/uploads/2010/03/DrawstringGarbage.jpg" alt="String Garbage" width="233" height="226" /></p>
<p>In my day job I’m a bit of a stickler with memory. I’m at times approaching borderline OCD I think with budgets and fragmentation. <img src='http://www.musictomakegamesby.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Having a good handle on memory usage on a game is very important; once you start pushing a console’s limits you can cause a lot of headaches down the road if you’re not mindful of things like memory budgets. Forgetting about fragmentation until it’s a big problem is also a bad idea. Once you’ve started bad practices like this on a game, they tend to snowball and you’re in for a hard uphill battle once they become a problem that needs fixing.</p>
<p>With working in C# and XNA now, the big enemy on the memory front isn’t really fragmentation or running out of available memory. The Xbox 360 has plenty of memory for any project I’d try and tackle myself; coder art for the win! The problem is one of performance, more specifically the lack of performance of the garbage collection system. Garbage collection on the 360 isn’t as full featured as on the full .NET Framework on Windows. It lacks the ‘generational’ model that the full Framework offers, meaning a full collection is performed whenever the system deems it necessary to do one.</p>
<p><span id="more-298"></span>Having random CPU spikes in your game is a nightmare. More so that in the case of garbage collection on 360 there’s little control other than being able to invoke a collection yourself manually. If you’re generating garbage at runtime during gameplay, you are going to see spikes in your frame times. With just a little garbage generated, and if your game isn’t CPU-bound, you may be able to get away with not giving this any attention. However given my nature with this sort of thing, I want to run a tight ship with this being a potential future headache if I don’t do so.</p>
<p>That said, I think for any sort of menu system I’d have, I’d probably be happy to let it generate garbage and then just call GC.Collect() when we go back to gameplay. Giving it a different treatment entirely to how I&#8217;d handle the regular runtime gameplay of the game. It’s all about where it’s important to concentrate efforts to avoid garbage.</p>
<h3>Profiling</h3>
<p>For profiling any garbage my game might generate I use <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=a362781c-3870-43be-8926-862b40aa0cd0&amp;displaylang=en" target="_blank">CLRProfiler for Windows</a>. It gives a nice in-depth analysis of memory usage, it’s pretty much invaluable for dealing with garbage collection problems. It’s almost worth keeping your game always running on a Windows target just so that you can make use of it!</p>
<p>On 360 I use the ‘Remote Performance Monitor’ that comes with the Game Studio SDK. It’s nowhere near as detailed, but it does give a good indication of the severity of any garbage collection issues with your game. Discussing how I use these tools is beyond the scope of this blog post, Google is your friend. <img src='http://www.musictomakegamesby.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h3>The String and StringBuilder problem</h3>
<p>The StringBuilder class in C# is the preferred way of working with string manipulation if performance is important. You can avoid it entirely, but you’ll be very likely to end up generating garbage at runtime if you’re exclusively using the string type.</p>
<p>For example, avoid using the ‘+’ operator to concatenate strings. Strings in C# are immutable, meaning they cannot be modified. If you perform this kind of operation, your resultant string will be allocated on the heap. It’s very easy to generate lots of garbage with this sort of code. Something like this monstrosity, which could be run every frame:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">string</span> show_world_details <span style="color: #008000;">=</span> “<span style="color: #000000;">&#91;</span> FPS <span style="color: #008000;">:</span>” <span style="color: #008000;">+</span> GetFPS<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> “ P1 Health<span style="color: #008000;">:</span>” <span style="color: #008000;">+</span> GetHealth<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> “  <span style="color: #000000;">&#93;</span>”<span style="color: #008000;">;</span></pre></div></div>

<p>StringBuilder allows you to work with a mutable string. It provides functionality to concatenate other strings, and other types onto your mutable string. Many of the functions of StringBuilder are completely garbage-free. Many however are not. I’ve a future post in the works which will cover that particular problem in more detail. For now, concatenating other strings onto the StringBulder is garbage-free. So that’s the method I’ll stick to for the sake of this post.</p>
<p>What I wanted to discuss was the conversion of your built up StringBuilder to a string type. There are many functions within the .NET library which only take strings as parameters. Thankfully on the XNA side, the DrawString() rendering routines <strong>do</strong> take a StringBuilder argument natively. However other functions such as those that write debugging output to Visual Studio or the console, only take string parameters. So in walks StringBuilder.ToString()…</p>
<h3>ToString() code</h3>
<p>So does calling ToString() generate garbage? My first expectation was that of course it would, it’d just copy what the string is into a new immutable string object created on the heap. This however is not the case, or at least sometimes it isn’t the case. To avoid beating around the bush here I’ll show you the actual source code of the ToString() method:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #FF0000;">String</span> ToString<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
&nbsp;
    <span style="color: #FF0000;">String</span> currentString <span style="color: #008000;">=</span>  m_StringValue<span style="color: #008000;">;</span>
    IntPtr currentThread <span style="color: #008000;">=</span> m_currentThread<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>currentThread <span style="color: #008000;">!=</span> Thread.<span style="color: #0000FF;">InternalGetCurrentThread</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
&nbsp;
        <span style="color: #0600FF;">return</span> <span style="color: #FF0000;">String</span>.<span style="color: #0000FF;">InternalCopy</span><span style="color: #000000;">&#40;</span>currentString<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">2</span> <span style="color: #008000;">*</span>  currentString.<span style="color: #0000FF;">Length</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">&amp;</span>lt<span style="color: #008000;">;</span> currentString.<span style="color: #0000FF;">ArrayLength</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
&nbsp;
        <span style="color: #0600FF;">return</span> <span style="color: #FF0000;">String</span>.<span style="color: #0000FF;">InternalCopy</span><span style="color: #000000;">&#40;</span>currentString<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    currentString.<span style="color: #0000FF;">ClearPostNullChar</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    m_currentThread <span style="color: #008000;">=</span> IntPtr.<span style="color: #0000FF;">Zero</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">return</span>  currentString<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Bit hairy, no? InternalCopy() is the function which will allocate a copy of the string on the heap and return it. The function can actually return the internal string without making any copies. Specifically the first time it’s called, and if the string makes use of at least 50% of the StringBuilder capacity. The ‘m_currentThread’ member being set to zero will effectively mean that the next time any sort of mutable operation is performed on the StringBuilder; be it clearing the string, or appending to it. The StringBuilder will allocate a new string on the heap. Each of the mutable methods of StringBuilder check the ‘m_currentThread’ and ensure that the StringBuilder owns the particular string. The way ToString() works, it’s effectively giving away ownership of that string and will start with a fresh one on the next mutable operation.</p>
<p>The reasoning behind this thread noting, as well as keeping the String returned by ToString() completely immutable, is to keep StringBuilder thread-safe. There’s comments within the code that detail the potential race condition that could occur, which I have omitted above. You can see them in full <a href="http://labs.developerfusion.co.uk/SourceViewer/view/SSCLI/System.Text/StringBuilder/" target="_blank">here</a>.</p>
<p>The other reason for making the copy is in the case that the user is making inefficient use of memory. If we’re only using a tiny portion of the StringBuilder capacity, the .NET authors deemed that it’s more efficient to return a copy instead of making reference to the full big string.</p>
<p>If I want to re-use a StringBuilder object, say for some kind of readout I might want Visual Studio to display in the debugging output window. I’m out of luck garbage-wise. I may avoid generating a copy of the string the first time I call it, but if I’m reusing the StringBuilder, it’s going allocate a new string on the heap for me when I call the next mutable method on it.</p>
<h3>The solution</h3>
<p>What I wanted was direct access to the string that the StringBuilder works with. <span style="text-decoration: line-through;">Doing this on Windows with ‘unsafe’ code is most likely straightforward, but I want to target 360 so that’s a non-starter. On the 360 you’re bound by the shackles of the Compact Framework, if it’s not in there, you can’t use it.</span></p>
<p>Thanks to <a href="http://www.codeproject.com/KB/dotnet/strings.aspx" target="_blank">this article</a> though, I was able to track down a method to be able to access that internal string object which the StringBuilder works with. It’s effectively doing something the .NET library authors don’t want you to do, grabbing that private member (oo-er). Thankfully this also works on 360!</p>
<p>Here’s the code:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">string</span> my_string <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#41;</span>my_stringbuilder.<span style="color: #0000FF;">GetType</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GetField</span><span style="color: #000000;">&#40;</span>
    <span style="color: #666666;">&quot;m_StringValue&quot;</span>,
    <span style="color: #000000;">System.<span style="color: #0000FF;">Reflection</span></span>.<span style="color: #0000FF;">BindingFlags</span>.<span style="color: #0000FF;">NonPublic</span> <span style="color: #008000;">|</span>
    <span style="color: #000000;">System.<span style="color: #0000FF;">Reflection</span></span>.<span style="color: #0000FF;">BindingFlags</span>.<span style="color: #0000FF;">Instance</span> <span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GetValue</span><span style="color: #000000;">&#40;</span> my_stringbuilder <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Reflection isn’t too pretty, eh? But here it’s a nice devious means to an end. Reflection isn’t too hot performance-wise, so I’d recommend grabbing the internal string just the once for the StringBuilder you’ll be working with. Stash it away as a member of a class or something, and you’ll then have the string to pass along to whatever function you wish. Now we’re no longer worrying about the ToString() generating garbage for us; success!</p>
<p>Here&#8217;s a bit of sample code:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">StringBuilder my_stringbuilder <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StringBuilder<span style="color: #000000;">&#40;</span> <span style="color: #FF0000;">32</span>, <span style="color: #FF0000;">32</span> <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #FF0000;">string</span> my_string <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#41;</span>my_stringbuilder.<span style="color: #0000FF;">GetType</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GetField</span><span style="color: #000000;">&#40;</span>
	<span style="color: #666666;">&quot;m_StringValue&quot;</span>, BindingFlags.<span style="color: #0000FF;">NonPublic</span> <span style="color: #008000;">|</span> BindingFlags.<span style="color: #0000FF;">Instance</span> <span style="color: #000000;">&#41;</span>
	.<span style="color: #0000FF;">GetValue</span><span style="color: #000000;">&#40;</span> my_stringbuilder <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
my_stringbuilder.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span> <span style="color: #666666;">&quot;This &quot;</span> <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
my_stringbuilder.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span> <span style="color: #666666;">&quot;Is &quot;</span> <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
my_stringbuilder.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span> <span style="color: #666666;">&quot;A &quot;</span> <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
my_stringbuilder.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span> <span style="color: #666666;">&quot;Test!&quot;</span> <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// my string will be &quot;This Is A Test!&quot;</span>
Console.<span style="color: #0000FF;">Write</span><span style="color: #000000;">&#40;</span> my_string <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// This second append would have resulted in a new heap allocation</span>
<span style="color: #008080; font-style: italic;">// if I'd used ToString() above.</span>
my_stringbuilder.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span> <span style="color: #666666;">&quot; Yay!&quot;</span> <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
Console.<span style="color: #0000FF;">Write</span><span style="color: #000000;">&#40;</span> my_string <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>I’d advise creating your StringBuilder objects with the two integer parameters contructor. As well as preallocating the string, you’ll also be putting a cap on the capacity:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// Creates an empty StringBuilder with a minimum capacity of capacity</span>
<span style="color: #008080; font-style: italic;">// and a maximum capacity of maxCapacity.</span>
<span style="color: #0600FF;">public</span> StringBuilder<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> capacity, <span style="color: #FF0000;">int</span> maxCapacity<span style="color: #000000;">&#41;</span></pre></div></div>

<p>Meaning it’ll never grow in size, or make any more heap allocations after it’s initially constructed. If that were to happen, the string object you grabbed is no longer linked to the StringBuilder. You&#8217;d need to redo the reflection call to grab the new string that the StringBuilder owns.</p>
<p>So by using that constructor, this means if you grab the internal string you’re guaranteed to keep the reference to the StringBuilder’s mutable string forever. The one key exception here though is if you work with the StringBuilder on another thread. In that case, you’ll be subject to the same issues as before.</p>
<p>I’ll revisit StringBuilder here again in future, to cover some of it’s other shortcomings with regard to generating garbage.</p>
<h3>References</h3>
<ul>
<li><a href="http://www.codeproject.com/KB/dotnet/strings.aspx" target="_blank">http://www.codeproject.com/KB/dotnet/strings.aspx</a></li>
<li><a href="http://blogs.msdn.com/shawnhar/archive/2007/07/02/twin-paths-to-garbage-collector-nirvana.aspx" target="_blank">http://blogs.msdn.com/shawnhar/archive/2007/07/02/twin-paths-to-garbage-collector-nirvana.aspx</a></li>
<li><a href="http://blogs.msdn.com/netcfteam/archive/2006/12/22/managed-code-performance-on-xbox-360-for-xna-part-2-gc-and-tools.aspx" target="_blank">http://blogs.msdn.com/netcfteam/archive/2006/12/22/managed-code-performance-on-xbox-360-for-xna-part-2-gc-and-tools.aspx</a></li>
<li><a href="http://blogs.msdn.com/stevenpr/archive/2004/07/26/197254.aspx" target="_blank">http://blogs.msdn.com/stevenpr/archive/2004/07/26/197254.aspx</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.musictomakegamesby.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>XNA/C# &#8211; Retrieval of Date and Time a Game Was Built</title>
		<link>http://www.musictomakegamesby.com/2009/02/08/xnac-retrieval-of-date-and-time-a-game-was-built/</link>
		<comments>http://www.musictomakegamesby.com/2009/02/08/xnac-retrieval-of-date-and-time-a-game-was-built/#comments</comments>
		<pubDate>Sun, 08 Feb 2009 22:13:12 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>

		<guid isPermaLink="false">http://www.musictomakegamesby.com/?p=195</guid>
		<description><![CDATA[During development, generally your testers will be running a version of the game that could be a number of days old. By the time you&#8217;ve got back bug reports there is likely to have been significant progress on the game since. There&#8217;s every chance during interim development that bugs could have been fixed before QA [...]]]></description>
			<content:encoded><![CDATA[<p><center><img class="aligncenter size-full wp-image-196" title="datestamp" src="http://www.musictomakegamesby.com/wp-content/uploads/2009/02/datestamp.jpg" alt="datestamp" width="250" height="250" /></center></p>
<p>During development, generally your testers will be running a version of the game that could be a number of days old.</p>
<p>By the time you&#8217;ve got back bug reports there is likely to have been significant progress on the game since. There&#8217;s every chance during interim development that bugs could have been fixed before QA found them. Also, the goalposts could be moved; some aspect of the title may have been significantly changed and that bug report you got no longer makes any sense.</p>
<p>For these reasons it&#8217;s imperative that when you get back bugs, you know what version of the game they were running. There&#8217;s a number of ways you can address this:</p>
<p><span id="more-195"></span></p>
<h4>Version Numbering</h4>
<ul>
<li>Can be in various forms. Could possibly be a hard coded string, some piece of built data, or the version number built into a PC executable header.</li>
<li>Many PC applications shipped just use simple version numbering to denote their builds. You still see a lot of &#8220;beta version 2.0.1.1123&#8243; style versioning on commercial software sitting out on webpages.</li>
<li>Manually updating the minor revisions each time is an easy thing to forget. It is possible to set up most development environments to auto-increment this number. If there&#8217;s no native support, it can usually be hacked in as a pre-build step.</li>
</ul>
<h4>Source Control Revision</h4>
<ul>
<li>There&#8217;s dozens of different pieces of source control software. With the majority of them it&#8217;s possible to synchronize to an explicit revision of the source tree. The revision number a game was built from can be used to identify a build.</li>
<li>As a pre-build step it is possible to automatically embed this revision number into the game.</li>
<li>Some source control software doesn&#8217;t have any sort of global revision numbering. Visual Sourcesafe springs to mind; that one only logs revision histories on a per-file basis. A single revision number to identify a particular build of the game is not possible. For Sourcesafe though it is possible to apply a label to the whole source tree. That could be done with each significant test build, with a version number of some kind.</li>
</ul>
<h4>Date/Time Stamping</h4>
<ul>
<li>Simply the date and time at which the build was created. Similarly to the source control methods, you can easily pinpoint exactly what code and data made it into the particular build of the game.</li>
<li>It falls down a little if your source control still accepts submissions, and you have other users submitting code whilst a build is being created. When cross referencing the date and time you actually built the game, it could appear that some changes got in that actually didn&#8217;t. This is no big deal if you lock out your source control whilst making a build for testing, or if you only have one person on the project.</li>
<li>Don&#8217;t use the timestamp of the executable itself! Aside from easily being able to be overwritten (the create and modified dates could be blitzed over for example, with particular unzipping or CD burning software). On the Xbox with XNA it&#8217;s not actually possible to inspect the executable&#8217;s date using the System.IO calls.</li>
<li>It is generally possible in most development environments to embed the current date and time into code. In C# this is actually possible in a very nice, clean manner. Updated intelligently each time you build an executable.</li>
</ul>
<p>With your average XNA game you&#8217;ve got no QA department to rely on. Most testing would probably be done by the developers, and their friends and family. The easier and more transparent this identification-marking is, the better.</p>
<h3>Automatic versioning in C#</h3>
<p>C# does provide automatic versioning in the form of an implicit change to the assembly version. For a newly created XNA project you&#8217;ll have an &#8216;Assembly.cs&#8217; file. At the bottom is the version number:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// Version information for an assembly consists of the following four values:</span>
<span style="color: #008080; font-style: italic;">//</span>
<span style="color: #008080; font-style: italic;">//      Major Version</span>
<span style="color: #008080; font-style: italic;">//      Minor Version</span>
<span style="color: #008080; font-style: italic;">//      Build Number</span>
<span style="color: #008080; font-style: italic;">//      Revision</span>
<span style="color: #008080; font-style: italic;">//</span>
<span style="color: #000000;">&#91;</span>assembly<span style="color: #008000;">:</span> AssemblyVersion<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;1.0.0.0&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span></pre></div></div>

<p>If you change the line to the following instead:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>assembly<span style="color: #008000;">:</span> AssemblyVersion<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;1.0.*&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span></pre></div></div>

<p>The last two numbers in the version will now be automatically filled in when the assembly is compiled. The numbers it fills in with are based on the current system date and time. So by doing this you&#8217;re effectively able to timestamp the built date of your game into the version number of the assembly. Both PC and Xbox are able to grab this version number, so it can be displayed within the game or on any sort of &#8216;game has crashed&#8217; screen you have.</p>
<p>The first two numbers, the major and minor version can still be used for their usual purpose. If you&#8217;re so inclined.</p>
<p>The &#8216;build number&#8217; and &#8216;revision&#8217; portions of the version can be grabbed and converted to a C# DateTime class, with the following code:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">private</span> DateTime DateCompiled<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// The assembly version must have the last two numbers removed and replaced with *</span>
    <span style="color: #008080; font-style: italic;">// It should look something like this: </span>
    <span style="color: #008080; font-style: italic;">// [assembly: AssemblyVersion(&quot;1.0.*&quot;)]</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">//Build dates start from 01/01/2000</span>
    <span style="color: #000000;">System</span>.<span style="color: #0000FF;">DateTime</span> result <span style="color: #008000;">=</span> DateTime.<span style="color: #0000FF;">Parse</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;1/1/2000&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">//Retrieve the version information from the assembly from which this code is being executed</span>
    <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Version</span> version <span style="color: #008000;">=</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Reflection</span></span>.<span style="color: #0000FF;">Assembly</span>.<span style="color: #0000FF;">GetExecutingAssembly</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GetName</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Version</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">//Add the number of days (build)</span>
    result <span style="color: #008000;">=</span> result.<span style="color: #0000FF;">AddDays</span><span style="color: #000000;">&#40;</span>version.<span style="color: #0000FF;">Build</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">//Add the number of seconds since midnight (revision) multiplied by 2</span>
    result <span style="color: #008000;">=</span> result.<span style="color: #0000FF;">AddSeconds</span><span style="color: #000000;">&#40;</span>version.<span style="color: #0000FF;">Revision</span> <span style="color: #008000;">*</span> <span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">//If we're currently in daylight saving time add an extra hour</span>
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>TimeZone.<span style="color: #0000FF;">IsDaylightSavingTime</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">System</span>.<span style="color: #0000FF;">DateTime</span>.<span style="color: #0000FF;">Now</span>, 
        TimeZone.<span style="color: #0000FF;">CurrentTimeZone</span>.<span style="color: #0000FF;">GetDaylightChanges</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">System</span>.<span style="color: #0000FF;">DateTime</span>.<span style="color: #0000FF;">Now</span>.<span style="color: #0000FF;">Year</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> 
    <span style="color: #000000;">&#123;</span> 
        result <span style="color: #008000;">=</span> result.<span style="color: #0000FF;">AddHours</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> 
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">return</span> result<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p><i>Courtesy of this <a href="http://dotnetfreak.co.uk/blog/archive/2004/07/08/determining-the-build-date-of-an-assembly.aspx">post from dotnetfreak.co.uk</a> of equivalent VB.NET code.</i></p>
<p>So, this is what I&#8217;m going with to tag my game builds. It covers me for what I need, and requires zero maintenance. </p>
<h3>Note:</h3>
<p>It is mentioned on a number of webpages that the &#8216;build number&#8217; and &#8216;revision&#8217; numbers don&#8217;t update on each build. It&#8217;s said that they only update each time you actually start the Visual Studio application.</p>
<p>However, I haven&#8217;t found this to be the case with Visual Studio 2008. Both the PC and Xbox XNA projects update this just fine. I can edit any .cs file in my project, and the game gets a new timestamp. I believe that the posts about the bad behavior were with Visual Studio 2005 and 2003.</p>
<p>XNA content pipeline files though, do not affect the timestamp at all. This makes total sense though, as the binary xnb data files aren&#8217;t part of the actual executable assembly.</p>
<h3>References:</h3>
<ul>
<li><a href="http://dotnetfreak.co.uk/blog/archive/2004/07/08/determining-the-build-date-of-an-assembly.aspx">http://dotnetfreak.co.uk/blog/archive/2004/07/08/determining-the-build-date-of-an-assembly.aspx</a></li>
<li><a href="http://stackoverflow.com/questions/324245/aspnet-show-application-build-dateinfo-at-the-bottom-of-the-screen">http://stackoverflow.com/questions/324245/aspnet-show-application-build-dateinfo-at-the-bottom-of-the-screen</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.reflection.assemblyversionattribute.assemblyversionattribute.aspx">http://msdn.microsoft.com/en-us/library/system.reflection.assemblyversionattribute.assemblyversionattribute.aspx</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.musictomakegamesby.com/2009/02/08/xnac-retrieval-of-date-and-time-a-game-was-built/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>XNA/C# &#8211; An Introduction, Build Configurations&#8230;</title>
		<link>http://www.musictomakegamesby.com/2009/02/07/xnac-an-introduction-build-configurations/</link>
		<comments>http://www.musictomakegamesby.com/2009/02/07/xnac-an-introduction-build-configurations/#comments</comments>
		<pubDate>Sat, 07 Feb 2009 21:07:05 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>

		<guid isPermaLink="false">http://www.musictomakegamesby.com/?p=101</guid>
		<description><![CDATA[So, I alluded to the fact I wanted to begin writing about XNA in my last post. Over the Christmas break I began getting to grips with C# and XNA, and wrote some code to have a go at prototyping a game idea I had. I think it’s pretty cool that you can execute your [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><img class="size-medium wp-image-102 aligncenter" title="xna-logo" src="http://www.musictomakegamesby.com/wp-content/uploads/2009/02/xna-logo.png" alt="xna-logo" width="230" height="114" /></p>
<p>So, I alluded to the fact I wanted to begin writing about XNA in my last post. Over the Christmas break I began getting to grips with C# and XNA, and wrote some code to have a go at prototyping a game idea I had. I think it’s pretty cool that you can execute your code on a retail 360 as well. It’s not quite as nice as using a devkit with native code, but it’s pretty close.</p>
<p><strong>Note to Microsoft:</strong> Make it easier to launch the XNA connect app from the dashboard. I know it’s not <em>meant</em> to crash, and it doesn’t that often. But I’ve been attempting some dodgy things and I’ve had it fall over several times. It would be great if it appeared at the top of your ‘Game Library’, as the XNA apps themselves do. For the connect app I have to always scroll to the ‘community games’ section and pick it from there.</p>
<p><span id="more-101"></span></p>
<h3>Environment</h3>
<p>Anyway, I thought the best place to start would be to describe the environment I’m working with:</p>
<ul>
<li> I’m targeting both 360 and PC for the moment, but there’s every chance I might drop one platform in the future. I have no plans to write anything for the Zune.</li>
<li> I’ve setup two extra build configurations in addition to the existing ‘debug’ and ‘release’. One named ‘final’, which would be the intended executable for the final version of the game to be dished out to the public. ‘release’ is the configuration which would have optimizations enabled; but would still have some debugging code which I wouldn&#8217;t want in the final game executable. &#8216;release&#8217; would also enable assertion code, which is omitted completely in &#8216;final&#8217;. The second new configuration is ‘profile’, which is the same as ‘final’ for all intents and purposes, but compiles in profiling code. I wrote my own basic profiler, as I had nothing but trouble with nprof on PC.</li>
<li> I have the code in two portions: I have a library in which I put what I’d deem as my ‘engine’ code, the stuff in there is (relatively-speaking) clean and what I’d want to keep if I scrapped a game idea and went with something else. The other portion is the game-side code, here I’m less fussy about organization whilst I’m just prototyping some ideas. Any code samples I put on this site though will be in a simple form which just an executable target, no libraries.</li>
<li> The code I do post will be namespaced ‘Cute’. Why? Well, I’m focusing on doing a graphically primitive cutesy style game, with bright colors and simple geo. I’m no artist. Rather than come up with some other namespace for code I put here, I’ll just post the one I use.</li>
</ul>
<h3>Build Configurations</h3>
<p>So, on to the build configurations. Here&#8217;s an explanation of each, and the extra compilation symbols I define:</p>
<p><strong>Debug: </strong>Code optimization is turned off, TRACE and DEBUG are defined. The same as a new project in devstudio would be for it&#8217;s debug configuration. I also define the symbols ASSERT and PROFILE for this build. This would be the build I&#8217;d drop down to diagnose any problems that were tricky on a release build, due to the code optimizations.</p>
<p><strong>Release: </strong>The same as debug, except with code optimizations turned on. TRACE is defined only on Xbox for debug output (see later note), DEBUG is not defined on either platform. This is generally the build I work with most. It runs at a good frame rate, I have assertions and profiling. As mentioned I&#8217;d only drop down to the debug build to work more accurately with the debugger.</p>
<p><strong>Final:</strong> This is the &#8216;shipping&#8217; build. Compared to release, the ASSERT and PROFILE defines are removed. Essentially all development &#8216;fluff&#8217; is out the window; the executable is expected to behave perfectly. The frame rate should also be somewhat better than release too because of this. Though right now given the early stage of my work, there&#8217;s really no difference to see just yet.</p>
<p>I define a FINAL symbol here as well, in case I want to conditionally compile in or out pieces of code specifically for this build.</p>
<p><strong>Profile: </strong>For this build I use the same setup as final, but with the PROFILE define enabled. I lose the overhead of assert checking from the release build, so have pretty similar performance to my final build. However my profiler is usable, so this build is perfect for testing any optimizations I might perform on the game. I also enable TRACE on Xbox, which is explained a little later.</p>
<p>I&#8217;ve shoved some screenshots at the bottom of this post, for clarity too.</p>
<h3>Defined Symbols, Debug Output on 360</h3>
<p>ASSERT and PROFILE defines? I&#8217;ll post in future covering how I use those. It&#8217;s pretty straightforward what they do when turned on and off though.</p>
<p>I define the symbols just a tad differently on 360 though. The Xbox 360 only has working debug output with the TRACE or DEBUG defines turned on. Here&#8217;s a table showing the debug output functions that are available, and how they behave on the two platforms:</p>
<p style="text-align: center;"><strong>PC</strong></p>
<table border="0">
<tbody>
<tr>
<td width="250"></td>
<td width="80">No defines</td>
<td width="80">DEBUG only</td>
<td width="80">TRACE only</td>
<td width="80">Both defined</td>
</tr>
<tr>
<td><strong>System.Console.Write</strong></td>
<td>Works</td>
<td>Works</td>
<td>Works</td>
<td>Works</td>
</tr>
<tr>
<td><strong>System.Diagnostics.Debug.Write</strong></td>
<td>No Output</td>
<td>Works</td>
<td>No Output</td>
<td>Works</td>
</tr>
<tr>
<td><strong>System.Diagnostics.Trace.Write</strong></td>
<td>No Output</td>
<td>No Output</td>
<td>Works</td>
<td>Works</td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
<p style="text-align: center;"><strong>360</strong></p>
<table border="0">
<tbody>
<tr>
<td width="250"></td>
<td width="80">No defines</td>
<td width="80">DEBUG only</td>
<td width="80">TRACE only</td>
<td width="80">Both defined</td>
</tr>
<tr>
<td><strong>System.Console.Write</strong></td>
<td>No Output</td>
<td>No Output</td>
<td>No Output</td>
<td>No Output</td>
</tr>
<tr>
<td><strong>System.Diagnostics.Debug.Write</strong></td>
<td>No Output</td>
<td>Works</td>
<td>No Output</td>
<td>Works</td>
</tr>
<tr>
<td><strong>System.Diagnostics.Trace.Write</strong></td>
<td>No Output</td>
<td>No Output</td>
<td>Works</td>
<td>Works</td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
<p>So, the defines differ on my 360 build. I have TRACE enabled on my release and profile builds, so I can get output. My profiler though, I hope to eventually get to render to the screen. Instead of it just dumping captured data in text form to the debug window. So I may be able to disable TRACE on my 360 profile build at some point in future.</p>
<p>On PC I route my printouts through System.Console.Write, on XBOX through System.Diagnostics. Trace.Write. I have a locally namespaced function that behaves correctly for both platforms. Yes, I could just have TRACE defined on the appropriate builds for parity&#8230; But I just don&#8217;t trust that it has zero other detrimental effects on performance.</p>
<h3>Phew&#8230;</h3>
<p>That&#8217;s it for the moment. Dry preparation is out of the way, this is more of a primer than anything. Something I can link back to in future to explain my #ifdef madness. Somewhat more useful stuff to come next&#8230;</p>
<p>Oh, here&#8217;s those configuration screenshots I mentioned:</p>
<p style="text-align: center;"><strong>PC: Debug, release, final, profile.</strong></p>
<p style="text-align: center;"><a rel="attachment wp-att-120" href="http://www.musictomakegamesby.com/2009/02/07/xnac-an-introduction-build-configurations/pc_debug/"><img class="aligncenter size-full wp-image-120" title="pc_debug" src="http://www.musictomakegamesby.com/wp-content/uploads/2009/02/pc_debug.png" alt="pc_debug" width="648" height="232" /></a><a rel="attachment wp-att-122" href="http://www.musictomakegamesby.com/2009/02/07/xnac-an-introduction-build-configurations/pc_release/"><img class="aligncenter size-full wp-image-122" title="pc_release" src="http://www.musictomakegamesby.com/wp-content/uploads/2009/02/pc_release.png" alt="pc_release" width="648" height="233" /></a><a rel="attachment wp-att-123" href="http://www.musictomakegamesby.com/2009/02/07/xnac-an-introduction-build-configurations/pc_final/"><img class="aligncenter size-full wp-image-123" title="pc_final" src="http://www.musictomakegamesby.com/wp-content/uploads/2009/02/pc_final.png" alt="pc_final" width="648" height="232" /></a><a rel="attachment wp-att-121" href="http://www.musictomakegamesby.com/2009/02/07/xnac-an-introduction-build-configurations/pc_profile/"><img class="aligncenter size-full wp-image-121" title="pc_profile" src="http://www.musictomakegamesby.com/wp-content/uploads/2009/02/pc_profile.png" alt="pc_profile" width="648" height="232" /></a><strong></strong></p>
<p style="text-align: center;"><strong>360: Debug, release, final, profile.</strong></p>
<p style="text-align: center;"><strong><a rel="attachment wp-att-168" href="http://www.musictomakegamesby.com/2009/02/07/xnac-an-introduction-build-configurations/360_debug/"><img class="aligncenter size-full wp-image-168" title="360_debug" src="http://www.musictomakegamesby.com/wp-content/uploads/2009/02/360_debug.png" alt="360_debug" width="648" height="232" /></a><a rel="attachment wp-att-167" href="http://www.musictomakegamesby.com/2009/02/07/xnac-an-introduction-build-configurations/360_release/"><img class="aligncenter size-full wp-image-167" title="360_release" src="http://www.musictomakegamesby.com/wp-content/uploads/2009/02/360_release.png" alt="360_release" width="648" height="233" /></a><a rel="attachment wp-att-169" href="http://www.musictomakegamesby.com/2009/02/07/xnac-an-introduction-build-configurations/360_final/"><img class="aligncenter size-full wp-image-169" title="360_final" src="http://www.musictomakegamesby.com/wp-content/uploads/2009/02/360_final.png" alt="360_final" width="648" height="232" /></a><a rel="attachment wp-att-170" href="http://www.musictomakegamesby.com/2009/02/07/xnac-an-introduction-build-configurations/360_profile/"><img class="aligncenter size-full wp-image-170" title="360_profile" src="http://www.musictomakegamesby.com/wp-content/uploads/2009/02/360_profile.png" alt="360_profile" width="648" height="233" /></a><br />
</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.musictomakegamesby.com/2009/02/07/xnac-an-introduction-build-configurations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Guitar Hero : Metallica announced</title>
		<link>http://www.musictomakegamesby.com/2009/02/01/guitar-hero-metallica-announced/</link>
		<comments>http://www.musictomakegamesby.com/2009/02/01/guitar-hero-metallica-announced/#comments</comments>
		<pubDate>Sun, 01 Feb 2009 23:44:44 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[Life]]></category>
		<category><![CDATA[My Games]]></category>
		<category><![CDATA[Work]]></category>

		<guid isPermaLink="false">http://www.musictomakegamesby.com/?p=70</guid>
		<description><![CDATA[I only ever seem to write on this blog when there&#8217;s a new GH game coming out&#8230; That said, I&#8217;ve started to code a little in my free time. I got a block of time over the Christmas break and I decided to have a good go at doing some stuff with XNA and C#. [...]]]></description>
			<content:encoded><![CDATA[<p>I only ever seem to write on this blog when there&#8217;s a new GH game coming out&#8230;</p>
<p style="text-align: center;"><img class="size-full wp-image-79 aligncenter" title="metallica" src="http://www.musictomakegamesby.com/wp-content/uploads/2009/02/metallica.jpg" alt="Metallica" width="400" height="117" /></p>
<p>That said, I&#8217;ve started to code a little in my free time. I got a block of time over the Christmas break and I decided to have a good go at doing some stuff with XNA and C#. Was a good experience, I feel a lot more comfortable with C# now. I&#8217;ve learnt to live with some of the annoying differences between it and C++. I code in the latter every day for my day job; for another language that&#8217;s so close to it, it takes a bit of a leap to leave the old ways behind.</p>
<p>So, hopefully I&#8217;ll give this blog a bit of a new lease of life soon with some tidbits from my XNA adventures. I&#8217;ve got a couple of &#8216;in-progress&#8217; articles going already.</p>
<p>Anyway, Metallica&#8230; <span id="more-70"></span></p>
<p>The last time there was rumblings of a Metallica game was back in 2003:<br />
<a href="http://cube.ign.com/articles/422/422960p1.html" target="_new">http://cube.ign.com/articles/422/422960p1.html</a></p>
<p>&#8230; and I would know nothing about such a game at all of course&#8230; *whistles*</p>
<blockquote><p><em>Damage Inc. [Metallica car combat title] (PC/PS2/GC/XBOX, Climax/VU Games)*</em></p></blockquote>
<p><a href="http://www.destructoid.com/surfer-girl-is-back-with-a-cancelled-game-list-50625.phtml" target="_new">http://www.destructoid.com/surfer-girl-is-back-with-a-cancelled-game-list-50625.phtml</a><br />
Seems like a very long time ago now&#8230; I&#8217;d like to say more about it, but it&#8217;s probably not a good idea.</p>
<p>Like Aerosmith last year, my involvement is pretty minimal; I&#8217;m working on something else right now. The Metallica game is based on the World Tour engine, so all four instruments are playable. Unlike with the Aerosmith game, where you were limited to just guitar and bass.</p>
<p>As per usual, with the press-situation for these sorts of things I really can&#8217;t say anything in more detail. It looks fantastic and I think the fans are going to be dead impressed with it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.musictomakegamesby.com/2009/02/01/guitar-hero-metallica-announced/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
