<?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>gavpugh.com</title>
	<atom:link href="http://www.gavpugh.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.gavpugh.com</link>
	<description>A Videogame Programming Blog</description>
	<lastBuildDate>Fri, 23 Mar 2012 06:37:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Ludum Dare #22 &#8211; Postmortem, Journal, and Time-lapse</title>
		<link>http://www.gavpugh.com/2011/12/21/ludum-dare-22-postmortem-journal-and-timelapse/</link>
		<comments>http://www.gavpugh.com/2011/12/21/ludum-dare-22-postmortem-journal-and-timelapse/#comments</comments>
		<pubDate>Wed, 21 Dec 2011 20:20:25 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[Life]]></category>
		<category><![CDATA[My Games]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Crunch]]></category>
		<category><![CDATA[Game Jam]]></category>
		<category><![CDATA[Ludum Dare]]></category>
		<category><![CDATA[Ludum Dare 22]]></category>
		<category><![CDATA[Rapid Game Development]]></category>
		<category><![CDATA[Shining Force]]></category>
		<category><![CDATA[Unity]]></category>
		<category><![CDATA[Unity3D]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=1276</guid>
		<description><![CDATA[So, this past weekend I participated in the 22nd Ludum Dare competition. You have just 48 hours over the weekend in which to create a game. The crux of the competition is that you create all code and content within that 48 hour period. No re-used assets at all. Only engine/middleware/framework code is permitted to [...]]]></description>
			<content:encoded><![CDATA[<p align="center"><img src="http://www.gavpugh.com/wp-content/uploads/2011/12/advofone.png" alt="" title="advofone" width="450" height="334" class="alignnone size-full wp-image-1352" /></p>
<p>So, this past weekend I participated in the <a href="http://www.ludumdare.com/compo/" target="_blank">22nd Ludum Dare</a> competition. You have just 48 hours over the weekend in which to create a game. The crux of the competition is that you create all code and content within that 48 hour period. No re-used assets at all. Only engine/middleware/framework code is permitted to be prepared beforehand.</p>
<p>I wrote my game with <a href="http://unity3d.com/" target="_blank">Unity</a>. It’s the first project I’ve ever undertaken in Unity, and I had very little experience of it. I came out of the other side with a very positive impression, I really liked using it. As much as I love C/C++; given the time constraints, it seemed a good idea to go with Unity. The other big upside is that you can deploy the game to be played via a web browser. This was definitely what I wanted. I didn’t want people to have to go to the hassle of a download-and-install, just to play the little toy game I made over a weekend.</p>
<p><span id="more-1276"></span></p>
<p>I wrote a turn-based strategy RPG game. My inspiration was the “Shining Force” series of games. The theme of Ludum Dare this time was “Alone”; every game submitted had to follow this theme. This obviously doesn’t fit the team-based gameplay of Shining Force, but mine has a twist. You just play as a single character. It just takes the combat part of those RPG games, there’s no walking around and talking to villagers. There is a shop to purchase and sell items between battles, but that’s it.</p>
<p>&nbsp;</p>
<h2>The Game</h2>
<p>Here’s a link to play the finished game:</p>
<div align=center><a href="http://www.gavpugh.com/ludumdare/ld22/WebPlayer.html" target="_blank"><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/12/unity.png" alt="" title="unity" width="350" height="160" class="alignnone size-full wp-image-1354" /><br />&#8220;Adventures of One&#8221;<br /></b></i></a></div>
<p>&nbsp;</p>
<p>I was disappointed with what I ended up with, mostly due to how much work I had to squeeze into the time. In my eyes the game had two major failings:</p>
<ul>
<li>A lack of polish. The art is my placeholder art, and the GUI is the default-Unity GUI.</p>
<li>Little game balancing. The first world is decently balanced, but after that it gets way too easy. The game is completely procedurally-generated. I just didn’t have the time to playtest it.
</ul>
<p>The biggest achievement though was:</p>
<ul>
<li>I wrote a game in 48 hours, that’s actually playable; and a little bit fun! <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />
</ul>
<p>That&#8217;s my introduction out of the way. Now, onto the postmortem&#8230;</p>
<p>&nbsp;</p>
<h2>What Went Right?</h2>
<ul>
<li>Choosing an idea which I’d see through to the end. I actually lost most of the first two hours to thinking over what type of game I’d do. The theme ‘Alone’ was tricky for me, as most of the ideas I had before it was announced didn’t fit it. I ended up taking one of those ideas and simplified it. In retrospect doing a full-blown party of player characters would have been ridiculously hard to do in 48 hours. But yeah, I was excited by the idea and that helped me keep my motivation.
<li>Using a higher level language like C#. Considering the game didn’t make too much use of Unity-specific ‘scene’ features, and was mostly generated in code; I could have had similar results using something like XNA instead. Either way, this sort of rapid development lends itself to something higher-level like C#. Out of habit, I think I would have been too anal about my code if I wrote it in C++. C# just lets you throw caution to the wind that little bit easier!
<li>Enemy AI. Pretty close to “Shining Force”’s enemy AI. It slotted in well to the turn system I had set up; so it followed the same rules and states the player had. The turn system I wrote had its positives and negatives, but since I left the AI to pretty late on, I’m happy I spent the time earlier making the turn system generic.
<li>The UI. I left it to pretty late on. I hate coding UI. I’m glad though I just used the stock Unity functions and didn’t try any fancy rendering techniques. I went for the basics, and that was the right decision. I’d hoped I’d get the chance at the end during the polish phase to ‘skin’ it, but I had no polish phase.
<li>Save and load. Lost close to an hour implementing it, but it’s a pretty cool feature. It autosaves after each battle (Unity stores web-app info on your hard-drive, so it’s transparent). I also got in a crude Base64 load/save screen, to bring your save to other computers.
<li>Bug free? Well, it seems to be for me. I kept it in a pretty stable condition, considering the game’s complexity and reliance on procedural generation, and AI.
<li>Food, drink, and breaks. I think I was sensible with what I ate and drank. I took pretty regular short breaks. Even if it was to just chill on the sofa with a notepad for five minutes, and plan out my next coding session. I’m not a coffee or energy-drink guy, so just cups of tea kept me going. I’m unsure how I wasn’t totally fatigued by the end, I’m guessing it was adrenaline.
<li>The ‘all nighter’. It saved me from not finishing. I’m an optimist when it comes to scheduling time. Re-reading my <a href="http://gavpugh.com/ludumdare/ld22/log.txt" target="_blank">journal log</a>, I hardly meet any of my set goals (but to be honest I did surprise myself with getting ‘unscheduled’ stuff done really quickly). If I’d had lost say, another five hours to a second nap, there is no way I’d have had a functional game come submission time.
<li>Placeholder work. Crappy art, blocks instead of characters, a checkerboard playing area for 90% of development. These sorts of things meant I had systems playable sooner. This helps my motivation, there’s nothing worse than building up to a point, where you’ve seen nothing on screen and hoping ‘everything will work out at the end’…. And then it inevitably doesn’t. My longest blind-coding run without actually seeing anything on the screen working, was about half an hour; for the turn system. Everything was short and sweet to rapidly iterate on.
<li>The audio. I think it went well. I dropped in the sound effects just after the halfway point, which provided good battling feedback, with the lack of particles/visual effects. The music I also procedurally generated. I lucked out with some good classical piano pieces which fit the style of game well. The voiceovers by the wife I threw in at the last minute. They worked out well, but I’d have liked to try and fix the audio balance between her and the music a bit more.
<li>Not caring about the code quality. It’s awful. Terribly hacked-about stuff that reminds me of the sort of thing I’d have written in college. I however still coded pretty defensively though. I just didn’t worry about things like commenting, and whitespace/indentation being off. Fix something ‘properly’, or throw in a sure-fire hack? A no brainer. I also committed many cardinal sins with global static singletons, instead of jumping through Unity’s component hoops. My typing fingers thanked me!
<li>Stand-up desk. I have an <a href="http://adam.pra.to/content/jerker/" target="_blank">IKEA Jerker desk</a>. It’s not adjustable, but I have a high stool which I use when I need a rest. Being able to constantly switch between two was awesome. When I’d feel lethargic in the chair, I could stand. When my feet got tired of the standing, I’d be able to take a load off and sit. I probably was about 50/50 in each position, time-wise.
<li>No internet distractions. I know some people who do these completions regularly like to use Twitter and IRC extensively during the dev time. I’m a bit of a procrastinator; those sorts of things can be a big timesink. I told myself I would just check my emails on my cellphone, and do nothing more than that. It worked out well. I’m real surprised that I didn’t feed my <a href="http://www.thechaosengine.com/forum" target="_blank">Chaos Engine</a> addiction, throughout the whole 48 hours!
</ul>
<p>&nbsp;</p>
<h2>What Went Wrong?</h2>
<ul>
<li>I left some important features until way near the end. In particular the attack logic I rushed through, such that it doesn’t scale into later battles. Enemy placement and the map terrain generation I did with less than two hours to go. I should have had all the procedural-generation stuff done very early, and other risky things like the battle logic calculations too. Instead I did the bread-and-butter stuff that’s hard to get wrong first, and did the risky stuff later.
<li>Very little playtesting. It’s a slow game to play through to test leveling into later battles. I should have made leveling stats deterministic and had some way of starting myself off in the later, harder battles to test balancing.
<li>Graphics/art. I spent hardly any time at all on the graphics. I can’t draw for shit, but I can usually fudge things to look very aesthetically pleasing despite that lack of talent. I didn’t even get any time to try that.
<li>A lack of preparation. I’d planned each day during the week prior to “look at Unity tonight”. I hadn’t got around to it. So I had to learn as I went.  Some aspects like hooking up audio took a little longer than they would have, if I knew how to do it beforehand. I also found myself dropping in and out of the ‘component’ model that Unity has for objects, because it didn’t ‘click’ for me until a few hours in. I think I would have likely pen-and-paper planned out my components to be better organized, than the ad-hoc mess they ended up as.
<li>AOE (area-of-effect) magic; stuff that affects more than one tile. Probably lost a couple of hours spread over the whole period, to implementing it, and dealing with fallout from it. I envisioned it as being useful in later battles when there are tons of enemies; which drove me to add it in the first place. It’s a shame later battles are such a walkover, which kind of renders it just a time-saving device.
<li>I started working at about 11am on the Saturday, after about five hours of sleep. I took it easy in the morning, and watched some football as I coded. That time was actually pretty productive. I then carried on for well over 24 hours and worked up to the 6pm deadline the next day. I really didn’t feel too tired, but my productivity certainly slowed. I didn’t have many bugs to fix, but one in particular was niggling in the last four hours.  I only fixed it shortly before submission. I think with a fresher head, I’d probably have not caused the bug in the first place.
<li>UI and state machines. I hate coding UI. I hate coding state machines. This game had plenty of both. I’m surprised it didn’t demotivate me.  State machines always seem such a chore. So much code for what has very simple intentions. Scripting languages can make this a lot easier with their micro-threading capabilities. I remember reading something about C# and the ‘yield’ statement lending itself well to state machines, but it’s a little less straightforward to grok. I should have probably checked that out again.
<li>The scope. Too big. Too ambitious. Given my lack of preparation too, it was silly to think I could do the idea justice in less than 48 hours. I had a good stab at it, though. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />
</ul>
<div align=center><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/12/picasso.png" alt="" title="picasso" width="300" height="300" class="alignnone size-full wp-image-1289" /><br />&#8220;Picasso&#8221; &#8211; Look at that work of art!<br /></b></i></div>
<p>&nbsp;</p>
<h2>My TODO List At The End</h2>
<p>I had to prioritize the last few tasks, so I inevitably had some on the cutting room floor. Here are the features I really wanted to add:</p>
<ul>
<li>Particle effects on attacks. I’d seen some demos of particles in Unity, and they looked really simple to set up. A good bang-for-buck. Didn’t even give it a slight look.
<li>More/better character graphics. I also rushed through naming and giving stats to the enemies that did make it in. The art in the game isn’t good, and I don’t think I’d have made it that much better; but I’d have liked to added more varied enemies for sure. I think I probably spent a grand total of about twenty minutes the whole project (if that), making art.
<li>I had functionality to ‘slow’ the player movement over harsh terrain, and collision for impassable squares. I always planned to procedurally generate the terrain, but I didn’t get the chance to hook this stuff up. Impassable squares would have been tricky, in order to avoid blocking the player out of areas. ‘Slow’ terrain though wouldn’t have been much work.
<li>Healing spells for enemies. ‘Buff’ and ‘debuff’ spells for the hero player, as well as the enemies. Similar ‘buff’ and ‘debuff’ items to use as well. Some of the turn-logic for this sort of thing was in place; it would have probably taken less than an hour to add these.
<li>A better looking GUI. I’d have liked to try changing the font and colour used. I did Google search at one point, but it looked pretty involved, and would require me to go through all my UI code and hookup references to a ‘GUISkin’. Probably not much time to do at all, but every minute counted at this stage.
</ul>
<p>Of course, all of these things still fall way below ‘fixing the balancing’, and some other things mentioned in the “What went wrong” section. The Perlin-noise, colored and textured terrain was actually a wishlist item for me originally. I wonder if I’d have left that on the wishlist, I would have been able to fix the balancing?</p>
<p>&nbsp;</p>
<h2>Final Thoughts</h2>
<p>In all, I enjoyed the experience. I was disappointed that the game I was intending to be challenging and provide seemingly ‘endless hours’ of battling, only holds up for about ten minutes. But I had fun coding something that quickly under a time pressure. Sure, the code looks absolutely horrible, but it’s a thrilling experience just churning out stuff at that speed, and having it all come together.</p>
<p>I would consider doing another Ludum Dare in future, but I’d definitely want to do more preparation. I’d also certainly scope my idea much better. I think a shorter, tighter game is the way to go. Something that would be doable with two ‘sleeps’ in there as well. I’d like to get a good twelve hours of sleep next time, instead of five! </p>
<p>&nbsp;</p>
<h2>My Journal Log</h2>
<p>You’ll notice the log ends at about 2pm, four hours before my 6pm deadline. That last four hours was just a whirlwind, the time flew by ridiculously fast!</p>
<p><a href="http://gavpugh.com/ludumdare/ld22/log.txt" target="_blank"><br />
<img class="alignleft size-full wp-image-437" style="vertical-align: middle;" title="zip_file" src="http://www.gavpugh.com/wp-content/uploads/2011/11/inf-file.png" alt="Zip File" width="48" height="52" />log.txt</a></p>
<p>I found it pretty useful to keep this log. It helped with motivation, and helped me focus on what I should be doing next.</p>
<p>I also have half a dozen mini-notepads full of ramblings about movement, AI, and the turn system. Taking a break from the computer and sitting down with a pad and paper is pretty valuable. Just gives you time to refocus, so you don’t just sit there coding down a blind alley.</p>
<p>&nbsp;</p>
<h2>My Time-lapse Video</h2>
<p>~38 hours in ~4 minutes:</p>
<p><iframe width="640" height="360" src="http://www.youtube.com/embed/q_VTmWSDQ-k" frameborder="0" allowfullscreen="1"></iframe></p>
<p>The first session was about 10 hours; the second session was about 28. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2011/12/21/ludum-dare-22-postmortem-journal-and-timelapse/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Developing for the Kindle Fire, on a Windows PC</title>
		<link>http://www.gavpugh.com/2011/11/21/developing-for-the-kindle-fire-on-a-windows-pc/</link>
		<comments>http://www.gavpugh.com/2011/11/21/developing-for-the-kindle-fire-on-a-windows-pc/#comments</comments>
		<pubDate>Mon, 21 Nov 2011 18:27:04 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Adb]]></category>
		<category><![CDATA[adb_usb.ini]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Driver]]></category>
		<category><![CDATA[Kindle]]></category>
		<category><![CDATA[Kindle Fire]]></category>
		<category><![CDATA[USB]]></category>
		<category><![CDATA[USB Driver]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=1185</guid>
		<description><![CDATA[If you&#8217;re a developer and you&#8217;ve picked up the Kindle Fire this past week, you may still be in the Honeymoon period with the device. If that is starting to wear off by now, you may have the inkling to try writing code for it. If you&#8217;ve previously developed software for Android, you&#8217;ll be a [...]]]></description>
			<content:encoded><![CDATA[<p><center><img src="http://www.gavpugh.com/wp-content/uploads/2011/11/kindlefire.png" alt="" title="kindlefire" width="471" height="256" class="alignnone size-full wp-image-1280" /></center></p>
<p>If you&#8217;re a developer and you&#8217;ve picked up the Kindle Fire this past week, you may still be in the Honeymoon period with the device. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  If that is starting to wear off by now, you may have the inkling to try writing code for it. If you&#8217;ve previously developed software for Android, you&#8217;ll be a little worried when you first connect it up. Out of the box, you can&#8217;t develop with it right away.</p>
<p>Thankfully, it&#8217;s not too complex to get things working. Thanks to some <a href="http://blog.actlocalmedia.com/2011/11/developing-on-kindle-fire.html" target="_blank">existing blog posts</a>, it was hardly difficult to figure it out. I thought I&#8217;d write up my install process, for anyone specifically developing on a Windows machine. I&#8217;m sure by now though, a week after launch there&#8217;s plenty of info out there. I&#8217;m also wanting to flex my blog-writing muscle again, just to get something written and maintain my recent uptick in pace.</p>
<p><span id="more-1185"></span></p>
<p>For this blog post I&#8217;m assuming you&#8217;re using Windows 7. Earlier versions of Windows should work fine too, but the steps may be subtly different.</p>
<p>&nbsp;</p>
<h2>Unknown USB Device &#8211; Kindle</h2>
<p>The first thing to address is that there&#8217;s one &#8216;Unknown Device&#8217; when you connect the Kindle Fire to a Windows PC. I&#8217;m assuming you have the Android SDK installed, so if you haven&#8217;t got it you&#8217;ll want to <a href="http://developer.android.com/sdk/index.html" target="_blank">install it from here</a>.</p>
<div align=center><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/11/kindlefire-usb.png" alt="" title="kindlefire-usb" width="640" height="187" class="alignnone size-full wp-image-1289" /><br />Unknown Device: &#8220;Kindle&#8221;<br /></b></i></div>
<p>&nbsp;</p>
<p>Now, you&#8217;ll want driver support for this &#8216;Unknown Device&#8217; so that you can use &#8216;adb&#8217; with it. So, download this file:</p>
<p><a href="http://www.gavpugh.com/source/kindlefire_winusb.inf"><img class="alignleft size-full wp-image-437" style="vertical-align: middle;" title="zip_file" src="http://www.gavpugh.com/wp-content/uploads/2011/11/inf-file.png" alt="Zip File" width="48" height="52" /><strong> kindlefire_winusb.inf</strong></a> &#8211; <i>Right-click and choose to &#8220;Save Link as&#8230;&#8221;</i></p>
<p>You&#8217;ll want to place it at a specific location, relative to the directory the Android SDK is installed to. It should go here:</p>
<ul>
<li><b>\extras\google\usb_driver</b>
</ul>
<p>There should already be an &#8216;android_winusb.inf&#8217; file in the same directory. My &#8216;kindlefire_winusb.inf&#8217; is actually largely a copy of the contents of this other inf file; it simply has the USB hardware device IDs for the Kindle Fire listed now.</p>
<p>You can point Windows to this &#8216;usb_driver&#8217; directory, if it&#8217;s currently trying to install that &#8216;Unknown Device&#8217;. Otherwise follow these steps:</p>
<ul>
<li>Go to Control Panel -> Administrative Tools -> Computer Management.
<li>Select the &#8216;Device Manager&#8217; in the left-hand pane.
<li>Find &#8216;Kindle&#8217; under &#8216;Other Devices&#8217; (as shown in the above screenshot).
<li>Right-click on it, choose &#8216;Update Driver Software&#8217;.
<li>Tell these dialogs to locate the driver inside the same directory you copied the .inf file to: <b>\extras\google\usb_driver</b> under the Android SDK directory.
<li>That&#8217;s it. The device should now no longer appear under &#8216;Other Devices&#8217;. It ends up being &#8216;Android Phone&#8217; -> &#8216;Android Composite ADB Interface&#8217;.
</ul>
<p>&nbsp;</p>
<h2>adb: No device found when Kindle Fire is connected</h2>
<p>Though the Windows device itself is installed, this isn&#8217;t quite enough. If you attempt to deploy to it through adb, it won&#8217;t work yet.</p>
<p>The problem here is that adb doesn&#8217;t know about the Kindle Fire USB Device ID. It has to be given that ID explicitly via a .ini file. The &#8220;adb_usb.ini&#8221; file in question is located in this directory:</p>
<ul>
<li><b>c:\Users\*USERNAME*\.android</b>
</ul>
<div align=center><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/11/kindlefire-adb.png" alt="" title="kindlefire-adb" width="640" height="187" class="alignnone size-full wp-image-1298" /><br />Editing: adb_usb.ini<br /></b></i></div>
<p>&nbsp;</p>
<p>So, open up &#8220;adb_usb.ini&#8221; in Notepad. Add this one single line, as shown above:</p>
<ul>
<pre>0x1949</pre>
</ul>
<p>Almost there now! Fire up a command prompt and navigate to your Android SDK /tools directory. Type the following commands:</p>
<ul>
<li><b>adb kill-server</b>
<li><b>adb start-server</b>
<li><b>adb devices</b>
</ul>
<div align=center><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/11/kindlefire-adb-server.png" alt="" title="kindlefire-adb-server" width="546" height="339" class="alignnone size-full wp-image-1299" /><br />Restarting the adb server: The Kindle Fire lives!<br /></b></i></div>
<p>&nbsp;</p>
<p>If all went well, it should look like the above screenshot. There should be one device listed, which in this case would be your Kindle Fire.</p>
<p><b>Aside: </b>Interestingly &#8216;android update adb&#8217; as suggested in the text of &#8216;adb_usb.ini&#8217;, generates an error with the latest SDK R15 tools. &#8216;adb&#8217; isn&#8217;t an accepted parameter to &#8216;update&#8217;. My Google-fu has failed to find a more permanent solution to adding this line. All references I can find to various other Android devices, encountering the same issues as the Kindle Fire, is just the same edit to &#8216;adb_usb.ini&#8217;.</p>
<p>&nbsp;</p>
<h2>All Done</h2>
<p>That&#8217;s it! Your Kindle Fire will now behave just like any other Android device you may have developed with before.</p>
<div align=center><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/11/discon-kindlefire.jpg" alt="" title="discon-kindlefire" width="350" height="208" class="alignnone size-full wp-image-1287" /><br />File Transfer / Disconnection screen<br /></b></i></div>
<p>&nbsp;</p>
<p>One thing to note, is that big black screen which the Kindle Fire displays: &#8220;You can now transfer files from your computer to Kindle&#8221;. This is just to serve the internal storage over the USB connection, as a mounted device. You can safely press &#8216;Disconnect&#8217; and leave this screen, and still be able to debug without issue. As long as the cable remains connected, &#8216;adb&#8217; will work fine.</p>
<div align=center><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/11/sanangeles-kindlefire.jpg" alt="" title="sanangeles-kindlefire" width="500" height="464" class="alignnone size-full wp-image-1282" /><br />&#8220;San Angeles&#8221; demo running on my Kindle Fire, built by vs-android<br /></b></i></div>
<p>&nbsp;</p>
<p>Thankfully, <a href="http://code.google.com/p/vs-android/" target="_blank">vs-android</a> worked just fine. Given I&#8217;ve only ever tested my personal cellphone with it; even though there&#8217;s no reason it shouldn&#8217;t have worked, I was nonetheless relieved that the Kindle fired up &#8220;San Angeles&#8221; without issue. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>&nbsp;</p>
<h2>References</h2>
<ul>
<li><a href="http://blog.actlocalmedia.com/2011/11/developing-on-kindle-fire.html" target="_blank">Act Local Media: Developing on the Kindle Fire</a>
<li><a href="http://forum.xda-developers.com/archive/index.php/t-882105.html" target="_blank">xda-developers: [Q] Creative ZiiO doesn&#8217;t appear on adb devices list</a>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2011/11/21/developing-for-the-kindle-fire-on-a-windows-pc/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>vs-android v0.93 Released</title>
		<link>http://www.gavpugh.com/2011/11/14/vs-android-v0-93-released/</link>
		<comments>http://www.gavpugh.com/2011/11/14/vs-android-v0-93-released/#comments</comments>
		<pubDate>Mon, 14 Nov 2011 18:21:20 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[visual studio]]></category>
		<category><![CDATA[vs-android]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=1256</guid>
		<description><![CDATA[In an effort to post more often in this blog, I&#8217;m writing up a minor vs-android update. I don&#8217;t usually write here about the minor version changes, I usually just fire out a tweet when I do those. I actually started work on this one, the evening after I published XNACPC. I was going to [...]]]></description>
			<content:encoded><![CDATA[<p><center><img src="http://www.gavpugh.com/wp-content/uploads/2011/11/Android4.png" alt="" title="Android4" width="300" height="219" class="alignnone size-full wp-image-1262" /></center></p>
<p>In an effort to post more often in this blog, I&#8217;m writing up a minor vs-android update. I don&#8217;t usually write here about the minor version changes, I usually just fire out a tweet when I do those. </p>
<p>I actually started work on this one, the evening after I <a href="http://www.gavpugh.com/2011/11/11/xnacpc-xbox-360-amstrad-cpc-emulator-released/">published XNACPC</a>. I was going to fix some of the issues of vs-android, which were posted to the Google Code page. One of them was related to a new Android SDK (the Java/apk building counterpart to C++&#8217;s NDK), which caused issues when building the vs-android samples. So I went and downloaded the new SDK. I also figured I should grab the r6b NDK, which had been out a while now but I hadn&#8217;t updated to yet. To my surprise NDK r7 was out! Coincidentally it was posted up the very same day I decided to check it. Spooky.</p>
<p><span id="more-1256"></span></p>
<h2>Breaking Changes</h2>
<p>Unfortunately <a href="http://developer.android.com/sdk/ndk/index.html" target="_blank">NDK r7</a> introduced breaking changes for vs-android. Specifically the names of support libraries I was linking with, were renamed. This, along with the SDK R15 issues were a stark reminder that when Google change things like this, they are likely to break vs-android. Fortunately addressing these changes was straightforward.</p>
<p>Interestingly NDK r7 brings with it a &#8216;Cygwin-free&#8217; build method. Since the compiler and linker have always worked without Cygwin, it only seems like &#8216;make&#8217; was an issue for them. So I&#8217;d imagine the inclusion of a Win32 native make is what allows them to do this now. Glad they&#8217;ve seen sense that Cygwin isn&#8217;t at all popular with most Windows devs. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>NDK r7 also brings support for <a href="http://developer.android.com/guide/appendix/api-levels.html" target="_blank">Android 4.0: &#8220;Ice Cream Sandwich&#8221;</a>. I&#8217;m not entirely up to speed with what&#8217;s changed, but the API&#8217;s available for the NDK jumped from &#8220;android-9&#8243; to &#8220;android-14&#8243;. With nothing in between. &#8217;9&#8242; being support for Android 2.3.2, and &#8217;14&#8242; being Android 4.0. So oddly enough they skipped the 3.x releases entirely for the NDK. I guess nothing changed to anything exposed to the NDK, during that period?</p>
<h2>v0.93 Changes</h2>
<p>Here is the list of changes made in v0.93. Pretty much all just bug fixes, and support for some small additions to the new NDK:</p>
<ul>
<li>NDK r7 was a breaking change for vs-android. This version now requires r7 or newer to be installed.
<li>Fixed breaking changes to the location of STL libraries. Also fixed new linking issues introduced by STL changes.
<li>Removed support for defunct arm 4.4.0 toolset.
<li>Added support for android-14, Android API v4.0.
<li>Added support for the dynamic (shared) version of the GNU libstdc++ STL.
<li>Tested against newest JDK &#8211; jdk-7u1-windows-i586.
<li>Added support for building assembly files. &#8216;.s&#8217; and &#8216;.asm&#8217; extensions will be treated as assembly code.
<li>Correct passing of ANT_OPTS to the Ant Build step. Thanks to &#8216;mark.bozeman&#8217;.
<li>Corrected expected apk name for release builds.
<li>Added to Ant Build property page; the ability to add extra flags to the calls to adb.
<li>Fixed bug with arm arch preprocessor defines not making it onto the command line.
<li>Fixed bad quote removal on paths, in the C# code. Thanks to &#8216;hoesing@kleinbottling&#8217;.
<li>Removed stlport project from Google Code &#8211; This was an oversight by Google in the r6 NDK, prebuilt is back again.
<li>Updated sample projects to work with R15 SDK tools.
</ul>
<p>You can get the latest vs-android here:</p>
<ul>
<li><a href="http://code.google.com/p/vs-android/" target="_blank">http://code.google.com/p/vs-android/</a>
</ul>
<h2>Kindle Fire</h2>
<p>I have my second Android device arriving soon. I ordered a &#8216;Kindle Fire&#8217;; I&#8217;m yet to try using a tablet computer. At $200 the price was right for me to take the plunge.</p>
<p>I&#8217;m looking forward to coding for it. I&#8217;d imagine it will help speed the development of vs-android. I haven&#8217;t been working on my personal Android project for a while, so it has slowed how often I update it. Certainly helps to <a href="http://en.wikipedia.org/wiki/Eating_your_own_dog_food" target="_blank">&#8216;eat your own dog food&#8217;</a>. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2011/11/14/vs-android-v0-93-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XNACPC: Xbox 360 Amstrad CPC Emulator, released!</title>
		<link>http://www.gavpugh.com/2011/11/11/xnacpc-xbox-360-amstrad-cpc-emulator-released/</link>
		<comments>http://www.gavpugh.com/2011/11/11/xnacpc-xbox-360-amstrad-cpc-emulator-released/#comments</comments>
		<pubDate>Fri, 11 Nov 2011 17:44:54 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[amstrad cpc]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[compact framework]]></category>
		<category><![CDATA[emulator]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[xnacpc]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=1173</guid>
		<description><![CDATA[On and off during the last month or so, I&#8217;ve worked toward finishing a project I wrote about last year. It&#8217;s an Amstrad CPC Emulator, written in C# using the Microsoft XNA library. I&#8217;ve written plenty about the background and motivation in the previous blog post. This post is just here to announce the finished [...]]]></description>
			<content:encoded><![CDATA[<p><center><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/11/xnacpc_title.png" alt="" title="xnacpc_title" width="449" height="211" class="aligncenter size-full wp-image-1175" /><br />
</center></p>
<p>On and off during the last month or so, I&#8217;ve worked toward finishing a project I wrote about <a href="http://www.gavpugh.com/2010/05/21/xnacpc-an-amstrad-cpc-emulator-for-the-xbox-360/">last year</a>. It&#8217;s an Amstrad CPC Emulator, written in C# using the Microsoft XNA library. I&#8217;ve written plenty about the background and motivation in the  <a href="http://www.gavpugh.com/2010/05/21/xnacpc-an-amstrad-cpc-emulator-for-the-xbox-360/">previous blog post</a>. This post is just here to announce the finished product, and touch a little on the things I&#8217;ve worked on recently.</p>
<p>The picture above is from Hewson&#8217;s &#8220;Nebulus&#8221;. Now that the emulator has a pretty complete feature set; games like these are very playable now. It makes a world of difference having the audio fully working now, for example. It also is great to finally be able to play at the original, full frame rate on Xbox 360. Surprisingly the 360 had trouble emulating this seemingly primitive machine! </p>
<p>Anyway, after the jump is a video showing the emulator in action on the 360&#8230;</p>
<p><span id="more-1173"></span></p>
<p>&nbsp; </p>
<h2>XNACPC In Action</h2>
<p>Here you go! This video shows a number of games running on the emulator. It&#8217;s taken with a point-and-shoot camera, in a poorly lit room. So the quality isn&#8217;t too great, unfortunately. Some games have pretty washed out colors and bad contrast; some look fine though.</p>
<p>I guess I could have captured it from my PC, but the whole point of the emulator was to get it running on the Xbox 360. The fun part is showing it off on the real thing. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p></p>
<p><iframe width="640" height="360" src="http://www.youtube.com/embed/TfB2V1DmFs0" frameborder="0" allowfullscreen="1"></iframe></p>
<h2>CRTC &#8211; Good Timing and Accurate Video</h2>
<p>My first pass at XNACPC <a href="http://www.gavpugh.com/2010/05/21/xnacpc-an-amstrad-cpc-emulator-for-the-xbox-360/">last year</a>, used the same technique which I employed when I wrote my CPC emulator back in the 90&#8242;s. I used a pretty naive approach, that had surprisingly good results for the early crop of launch games for the CPC.</p>
<p>I fudged the interrupts simply so that they occurred at 300Hz, which they&#8217;d be at on a real CPC. I wasn&#8217;t emulating the HSYNC correctly, nor the counters which are based off the HSYNC and generate interrupts. I also had to fudge the VSYNC signal which is read from one of the PPI ports. Whilst it was a primitive approach, it worked pretty well. Even &#8216;Sorcery&#8217;; a split-screen game, looked and played like the original.</p>
<p>Fixing the CRTC to behave properly was at the top of my list. I was pleased that I managed it. The best reference I found for it was probably here:</p>
<ul>
<li><a href="http://www.grimware.org/doku.php/documentations/devices/crtc">http://www.grimware.org/doku.php/documentations/devices/crtc</a></li>
</ul>
<div align=center><b><i><br />
<a href="http://www.gavpugh.com/wp-content/uploads/2011/11/crtc_timing.png" target="_blank"><img src="http://www.gavpugh.com/wp-content/uploads/2011/11/crtc_timing-300x187.png" alt="" title="crtc_timing" width="300" height="187" class="aligncenter size-medium wp-image-1177" /></a><br />Grimware CRTC Timing Reference<br /></b></i></div>
<p>&nbsp;</p>
<p>So I threw away my old video implementation and did it the proper way. Many games which previously didn&#8217;t work, now played just fine. I also used to draw the entire screen at the end of the frame. When I switched to drawing it line-by-line after each HSYNC, it eliminated flickering artifacts in many games. &#8220;Monty on the Run&#8221; for instance, looked awful in many places when I was updating the whole screen at once.</p>
<div align=center><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/11/crtc_bug.png" alt="" title="crtc_bug" width="457" height="147" class="aligncenter size-full wp-image-1178" /><br />&#8220;Monty On The Run&#8221; &#8211; Fullscreen vs. Line-by-line<br /></b></i></div>
<p>&nbsp;</p>
<h2>Audio &#8211; Silence Isn&#8217;t Golden</h2>
<p>I actually traded off the audio work with the CRTC work. I&#8217;d switch between them when I hit a wall, to keep things interesting. When I first worked on the emulator last year it actually wasn&#8217;t possible to implement emulated audio at all. That only became possible when XNA 4.0 was released, with the addition of <a href="http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.audio.dynamicsoundeffectinstance.aspx" target="_blank">DynamicSoundEffectInstance</a>.</p>
<p>The audio on a CPC is pretty simple in it&#8217;s concept, but it did take me a little while to get the timing correct. It&#8217;s essentially based on square waves, where the audio signal is either on or off. The signal does have volume control, so it&#8217;s possible to produce pretty decent sounding music with it.</p>
<div align=center><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/11/square_wave.png" alt="" title="square_wave" width="482" height="241" class="aligncenter size-full wp-image-1179" /><br />AY8912 Audio Square Waves<br /></b></i></div>
<p>&nbsp;</p>
<p>There&#8217;s three main parts to the AY audio chip used in the CPC:</p>
<ul>
<li>Three channels of tone generators. Producing square waves at given independent periods.</li>
<li>A single noise generator. It generates random noise, which can be used by any combination of channels instead of the tone generator output.</li>
<li>A single envelope generator. This allows any combination of channels to progressively change the volume over time, in a manner that doesn&#8217;t need any CPU assistance.</li>
</ul>
<p>Of the three channels; two of them represent the left and right speakers, and the other one is mixed between each speaker.</p>
<p>That&#8217;s the gist of it. The audio was pretty satisfying to implement; since I&#8217;d never tried to get it working, back in the emulator I developed in the 90&#8242;s. Unfortunately the addition of the audio was taxing enough for the Xbox to drop under the 50fps that a CPC runs at. This meant I had to refactor the audio code somewhat, from a nice C#-style to a more brute-force C-style. </p>
<h2>Z80, PPI and Other Hardware Bugs</h2>
<p>There was a fun little period after I had the CRTC emulation all working correctly. With the last big hurdle overcome, I now had to fix bugs in my hardware implementation. This was the period where suddenly lots of other dead non-working games would spring to life.</p>
<p>Coming back to the source code after over a year was fine for the most part, but I did forget about a number of functions which I stubbed out. The PPI was a big one, I just did the basics to get the most primitive games running. So there I had to go back to the hardware documents and fill in the more obscure parts of the implementation. After doing that, a bunch more games would run.</p>
<p>One other key fix I remember was to the Z80 emulation. The HALT instruction was broken. I took the Z80 CPU emulator originally from an older <a href="http://zx360.codeplex.com/" target="_blank">C# Spectrum emulator</a>. I&#8217;d made a number of modifications to get it to play nice with the CPC; mostly around timing and interrupts. When I noticed a couple of games dying on the HALT instruction, I went back to the Z80 documentation and implemented HALT correctly. As well as getting some games to run, it also amusingly fixed the broken &#8216;pelvic thrust&#8217; animation in the intro to &#8216;Rocky Horror Picture Show&#8217;. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div align=center><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/11/rocky_horror.png" alt="" title="rocky_horror" width="420" height="156" class="aligncenter size-full wp-image-1180" /><br />&#8220;The Rocky Horror Picture Show&#8221; &#8211; Intro<br /></b></i></div>
<p>&nbsp;</p>
<h2>CRT Shader &#8211; A Bit of Polish</h2>
<p>Once I finally had the majority of the games looking pretty much perfect, I had an inkling to go a little further. I&#8217;m not much of a graphics programmer, by today&#8217;s standards. I used to be really into graphics programming back in the mid to late 90&#8242;s. Michael Abrash&#8217;s <a href="http://www.amazon.com/Zen-Graphics-Programming-Ultimate-Writing/dp/188357708X" target="_blank">&#8220;Zen of Graphics Programming&#8221;</a> was one of my favorite books. I also remember fondly working through the <a href="http://bespin.org/~qz/pc-gpe/" target="_blank">&#8216;Asphixia VGA Trainers&#8217;</a>. It&#8217;s about the last time I think I wrote more than just a handful of lines of assembly code at once. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>It&#8217;d been a few years since I last experimented with shaders, so I decided to try writing a simple shader to give the emulator a <a href="http://filthypants.blogspot.com/2011/05/more-emulator-pixel-shaders-crt-updated.html" target="_blank">&#8216;CRT effect&#8217;</a>. I only spent a small amount of time on it; it&#8217;s nothing fancy. The gist of my effect works as follows:</p>
<ul>
<li>Each CPC pixel is exactly three &#8216;XNA pixels&#8217; high. My shader uses modf() to modolo based on this, so I can do something different for each of the three rows of pixels.</li>
<li><b>Row One:</b> I leave the color alone. Sample goes straight through.</li>
<li><b>Row Two:</b> 90% of the color I take from original sampled value. 5% I actually sample from the next CPC pixel scanline. Then, 5% left out to make it darker. </li>
<li><b>Row Three:</b> 75% of the color I take from original sampled value. 15% I sample from the next scanline. Then, 10% left out to make it darker.</li>
</ul>
<p>Sampling a little of the next scanline down, introduces a little color bleeding; which seems to work well. It&#8217;s pretty decent-looking considering how simple my shader was. Here&#8217;s a zoomed picture, below. It looks it&#8217;s best though at 1:1 resolution, as you can see from the &#8220;Nebulus&#8221; shot at the very top of this blog post.</p>
<div align=center><b><i><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/11/crt_shader.png" alt="" title="crt_shader" width="640" height="388" class="aligncenter size-full wp-image-1181" /><br />&#8220;Ikari Warriors&#8221; &#8211; 2x Zoomed Shot of my CRT Shader Effect<br /></b></i></div>
<p>&nbsp;</p>
<h2>Xbox 360 &#8211; Compact Framework Creaking Under Pressure</h2>
<p>Getting the emulator running at the full frame rate of the original CPC, wasn&#8217;t much fun. On PC it was fine, no problems there. I think Task Manager shows ~2% CPU usage on my PC when it&#8217;s running. When I turned the frame-rate limiting off, I think it ran at >300fps. I&#8217;m talking specifically here about emulation of the CPC, not just drawing and updating the screen. So when I run it with the frame-limiter off, the machine runs so fast that any game is essentially unplayable.</p>
<p>Now, the Xbox 360. Some of you with experience with C# and the 360, will likely think I&#8217;ll mention garbage collection? Actually this wasn&#8217;t an issue for me. For any emulation runtime code, I made sure I wasn&#8217;t doing anything bad there. I generate absolutely no garbage when the game runs. I do allow for garbage in my &#8220;Pause Menu&#8221; code, however. But that&#8217;s really nice and easy to handle, just perform a full collection when unpausing. I like that approach for being able to write quick-and-dirty UI code, and keep the actual game clean.</p>
<p>So, not garbage? Nah, it&#8217;s just a raw CPU throughput problem. I hear someone shouting &#8220;JIT&#8221;&#8230;? Indeed; it does help a lot. The version of the emulator I&#8217;ve uploaded today runs at about half the speed of a CPC, when I have the debugger attached to the Xbox. So yeah: Release Build. No debugger attached. No garbage collection. This is as good as it gets.</p>
<p>I did a few things to drag the emulator kicking and screaming, to meet the 50fps that the CPC runs at:</p>
<ul>
<li>General optimizations which seem to benefit 360: Lookup tables seem to win over a handful of computational instructions. A general mistrust of the optimizer/JIT works well too. Cache variables yourself when doing multiple lookups from other classes, for example.</li>
<li>Changed the routine which writes screen memory out to the XNA texture, to use unsafe code.</li>
<li>Refactored my audio code to have the tone, noise and envelope generators as structs instead of classes (no vcalls). Ripped out my nice methods and just let my audio code access public members instead.</li>
<li>The biggest win by far was hand-unrolling a simple for loop. It was an inner loop inside my graphics rendering code. It was walking over eight pixels for each byte of CPC memory. Instead of looping, I copy and pasted the line over eight times. My frame rate jumped from ~40fps to ~50fps.</li>
</ul>
<p>Anyway. This was a bit of an eye-opener. I&#8217;m used to writing native code on 360, and I&#8217;m sure the thing wouldn&#8217;t break a sweat with a C++ version of my emulator. It&#8217;s odd to think that when I first worked on my emulator back in 1998, in C++; it was on a Pentium 120. That P120 ran the emulation fine, taxing the CPU at around 50% if I recall. Compare that to the ~95% I&#8217;m shipping XNACPC on the Xbox with. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>So, the Compact Framework on 360 isn&#8217;t too hot. To be honest though, I&#8217;d have no qualms with developing something like this in C# if I was targeting PC. The full .NET Framework seems to be a good performer. Of course, straight-game code is going to be a whole different kettle of fish; compared to something as ridiculous as I&#8217;ve coded here. I don&#8217;t mean to slag off the Compact Framework; I&#8217;d imagine other XNA devs don&#8217;t see the huge disparity that I did, when they&#8217;re coding their games.</p>
<h2>The Source</h2>
<p>In an ideal world I&#8217;d be able to release it on the XBLIG channel. But given both copyright (and moral) issues with distributing games that other people have worked on, it&#8217;s not a possibility. This is a shame for people interested in playing with it though, since it means your only option requires a &#8216;Creators Club&#8217; subscription. This costs $99 a year!</p>
<p>That said, I&#8217;d likely expect the few of you that actually read this blog (and the fewer that read this far down!) might be XNA coders. I&#8217;ve a zip file setup which contains the solution and project files, with the emulator ready to deploy to your Xbox. You can download it here:<br />
<a href="http://www.gavpugh.com/xnacpc/xnacpc_1_0_source.zip"><img class="alignleft size-full wp-image-437" style="vertical-align: middle;" title="zip_file" src="http://www.gavpugh.com/wp-content/uploads/2010/04/zip_file1.png" alt="Zip File" width="48" height="52" /><strong> xnacpc_1_0_source.zip</strong></a></p>
<p>If you just want to browse the code online, I&#8217;ve put it up here at Google Code too:</p>
<ul>
<li><a href="http://code.google.com/p/xnacpc/" target="_blank">Google Code &#8211; XNACPC</a></li>
</ul>
<p>If you&#8217;re interested in taking XNACPC and releasing something (legal and authorized) on XBL Indie Games, or Windows Phone 7. Please contact me about it, I&#8217;d love to work on the project!</p>
<h2>PC Version</h2>
<p>The PC version is playable without any sort of coding experience, nor requiring paying any money to Microsoft. You can download it here:<br />
<a href="http://www.gavpugh.com/xnacpc/xnacpc_1_0_pc_binaries.zip"><img class="alignleft size-full wp-image-437" style="vertical-align: middle;" title="zip_file" src="http://www.gavpugh.com/wp-content/uploads/2010/04/zip_file1.png" alt="Zip File" width="48" height="52" /><strong> xnacpc_1_0_pc_binaries.zip</strong></a></p>
<p>Just unzip it somewhere, and run &#8216;XNACPC.exe&#8217;. That&#8217;s it. There&#8217;s a number of games in the package, all setup ready to play. You may also need to download the <a href="http://www.microsoft.com/download/en/details.aspx?id=20914" target="_blank">XNA Runtime</a>, if the app complains about missing something when you run it.</p>
<h2>What&#8217;s Next?</h2>
<p>Well, I really don&#8217;t plan to do any more work on XNACPC. There&#8217;s plenty of other CPC emulators which are more complete. They emulate more features, and run pretty much any game you can throw at them. The intention wasn&#8217;t to compete with those emulators, it was just to prove it&#8217;s possible to do the same in C# with XNA. I think I&#8217;ve done that, so there&#8217;s no real motivation to continue with the project.</p>
<p>It&#8217;s been fun; but I&#8217;ve been tinkering with CPC emulators in various forms since 1998. Right now I&#8217;m happy to close the door on this, and keep working on &#8216;new&#8217; stuff instead of having one eye on the past. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Hope you enjoy poking around the <a href="http://code.google.com/p/xnacpc/" target="_blank">source code</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2011/11/11/xnacpc-xbox-360-amstrad-cpc-emulator-released/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>vs-android: Closing in on v1.0</title>
		<link>http://www.gavpugh.com/2011/07/22/vs-android-closing-in-on-v1-0/</link>
		<comments>http://www.gavpugh.com/2011/07/22/vs-android-closing-in-on-v1-0/#comments</comments>
		<pubDate>Fri, 22 Jul 2011 17:48:56 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Life]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[android ndk]]></category>
		<category><![CDATA[android visual studio]]></category>
		<category><![CDATA[microsoft visual studio]]></category>
		<category><![CDATA[msbuild]]></category>
		<category><![CDATA[ndk visual studio]]></category>
		<category><![CDATA[visual studio]]></category>
		<category><![CDATA[visual studio android]]></category>
		<category><![CDATA[vs-android]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=1047</guid>
		<description><![CDATA[So, it’s been quite a while since I last posted on this blog. I&#8217;ve been pretty busy the past few months with various things. At work we had an important milestone during that time, which thankfully passed with flying colors. Outside of work though, I actually got married a couple of months ago! My wife and I [...]]]></description>
			<content:encoded><![CDATA[<p align="center"><img class="aligncenter size-full wp-image-1145" title="ms-android" src="http://www.gavpugh.com/wp-content/uploads/2011/07/ms-android.jpg" alt="Microsoft Android" width="219" height="219" /></p>
<p>So, it’s been quite a while since I last posted on this blog. I&#8217;ve been pretty busy the past few months with various things. At work we had an important milestone during that time, which thankfully passed with flying colors. Outside of work though, I actually got married a couple of months ago! My wife and I eloped to Hawaii, just the two of us, and tied the knot. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>So it’s been quite a busy period recently for me. Starting on vs-android back in January probably wasn’t the best timing. Getting it done wasn’t too bad; it was more the follow-up support email period that was tougher to deal with. More so, given the marriage preparations and what have you, which I was going through at the time. So vs-android got left by the wayside a while, and rightfully so!</p>
<p>A couple of weeks ago though, I picked up the project again. I was determined primarily to fix the dependency issues the previous version had. After looking again at what Microsoft had done with their Win32 toolchain, I decided to massively change my approach. I went from a system that was built primarily with MSBuild, with a little C# to sanitize pathnames and switches. To a system which had almost all of it&#8217;s moving parts in C#, with MSBuild just ferrying the project data into it.</p>
<p>That was pretty much the basis for the latest iteration of vs-android. I bolted on a few other things along the way, but for the most part it was just about getting it into a stable and reliable state.</p>
<p><span id="more-1047"></span></p>
<h2>vs-android v0.9</h2>
<p>So yeah, I’ve just wrapped up a new version of vs-android. I didn’t bother posting about the last couple of version revisions I did in the past, but this one is a little different. It got a pretty major overhaul. In my eyes has moved from an experimental toy, to something people can actually write production code with. So this is why the version number jumped up to point-nine.</p>
<p>To get an idea of the extent of said overhaul, here’s a list of the changes made:</p>
<ul>
<li>Verified working with Android NDK r5b, r5c, and r6.</li>
<li>Much of vs-android functionality moved from MSBuild script to C# tasks. Similar approach now to Microsoft&#8217;s existing Win32 setup.</li>
<li>Dependency checking rewritten to use tracking log files.</li>
<li>Dependency issues fixed, dependency checking also now far quicker.</li>
<li>Android Property sheets now completely replace the Microsoft ones, no more rafts of unused sheets.</li>
<li>Property sheets populated with many options. Switches are no longer hard-coded within vs-android script.</li>
<li>STL support added. Choice between &#8216;None&#8217;, &#8216;Minimal&#8217;, &#8216;libstdc++&#8217;, and &#8216;stlport&#8217;.</li>
<li>Support for x86 compilation with r6 NDK.</li>
<li>Full support for v7-a arm architecture, as well as the existing v5.</li>
<li>Support for Android API directories other than just &#8216;android-9&#8242;.</li>
<li>Separated support for &#8216;dynamic libraries&#8217; and &#8216;applications&#8217;. Applications build to apk files.</li>
<li>Response files used in build, no more command-line length limitations.</li>
<li>Deploy and run within Visual Studio, adb is now invoked by vs-android.</li>
<li>&#8216;Echo command lines&#8217; feature fixed.</li>
<li>All support SDK/libs (NDK, SDK, Ant, JDK) are okay living in directories with spaces in them now.</li>
<li>All bugs logged within Google Code are addressed.</li>
</ul>
<div>
<p>So yeah, quite a few of ‘em&#8230;</p>
<p>I think my favorite out of the lot was fixing up the property pages.  Previously they looked like the below, with one specific page for Android’s gcc, and several other pages related to the Win32 compiler. Unfortunately while most of the Win32 settings were unused and benign, some of them (preprocessor, include paths, etc&#8230;) actually <strong>did</strong> do something. It was a little messy:</p>
<p><img src="http://www.gavpugh.com/wp-content/uploads/2011/07/old_vsa1.png" alt="" title="old_vsa" width="615" height="492" class="alignnone size-full wp-image-1155" /></p>
<p>For comparison, here are the new property pages in the next image. All the properties now pertain to the Android build, no chaff in there at all:</p>
<p><img src="http://www.gavpugh.com/wp-content/uploads/2011/07/new_vsa1.png" alt="" title="new_vsa" width="608" height="408" class="alignnone size-full wp-image-1156" /></p>
<p>So that’s a little taster of what has changed.</p>
<h2>How much faster?</h2>
<p>As a result of moving the dependency checking to using Microsoft&#8217;s tracking-log files, and also running gcc just once rather than twice to grab dependency headers. vs-android v0.9 runs significantly faster than it&#8217;s predecessor.</p>
<p>It wasn&#8217;t much of a slouch before, at least compared to the stock ndk-build scripts Google provides. In my <a href="http://www.gavpugh.com/2011/02/04/vs-android-developing-for-android-in-visual-studio/">previous blog post</a> I looked at the speed differences, here&#8217;s the comparison with the v0.9 numbers added:</p>
<p><center><i>Building 381 .cpp/.c files. The <a href="http://irrlicht.sourceforge.net/" target="_blank">Irrlicht engine</a> Android port.</i></p>
<table border=0 cellspacing="10">
<tr>
<td></td>
<td><strong>ndk-build</strong></td>
<td><strong>vs-android v0.2</strong></td>
<td><strong>vs-android v0.9</strong></td>
</tr>
<tr>
<td><strong><strong>Full Rebuild</strong></strong></td>
<td>9m14s</td>
<td>5m32</td>
<td><b>4m38</b></td>
</tr>
<tr>
<td><strong>Incremental Build (1 cpp changed)</strong></td>
<td>1m24s</td>
<td>35s</td>
<td><b>23s</b></td>
</tr>
<tr>
<td><strong>No-op build (build with nothing changed)</strong></td>
<td>1m2s</td>
<td>0s</td>
<td><b>0s</b></td>
</tr>
<tr>
<td><strong>Single cpp build, aka Ctrl-F7</strong></td>
<td>N/A</td>
<td>2s</td>
<td><b>2s</b></td>
</tr>
</table>
<p></center></p>
<h2>Download</h2>
<p>You can download the latest version of vs-android at my Google Code page, here:</p>
<ul>
<li><b><a href="http://code.google.com/p/vs-android/" target="_blank">Google Code: vs_android</a></b></li>
</ul>
<h2>What’s next for vs-android?</h2>
<p>My plan going forward will just be to focus on any bug fixes needed. I have a huge laundry list of features I&#8217;d like to add, but I have to be realistic. I’ll likely put in a few smaller additions in incremental updates before I hit v1.0. In my eyes v1.0 will have an installer, and a “New Project Wizard”; anything else I manage to add to that is icing on the cake.</p>
<p>However, for the immediate future I’ll be trying to take a break from it for a while. What I enjoy most about coding is tackling various different problems. I get a little tired working on the same area of a project for too long, and vs-android certainly isn’t a project with a varied wide scope of tasks.</p>
<p>I’d like to go finish fixing up the CRTC syncing in <a href="http://www.gavpugh.com/2010/05/21/xnacpc-an-amstrad-cpc-emulator-for-the-xbox-360/">XNACPC</a> next, I think. I also had audio functioning last time I was working on it, but my dodgy CRTC code was making it sound pretty awful. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  I’ve nothing fancy at all planned for the emulator, I just want to get the basics solid and throw up the C# source.</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2011/07/22/vs-android-closing-in-on-v1-0/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>vs-android: Developing for Android in Visual Studio</title>
		<link>http://www.gavpugh.com/2011/02/04/vs-android-developing-for-android-in-visual-studio/</link>
		<comments>http://www.gavpugh.com/2011/02/04/vs-android-developing-for-android-in-visual-studio/#comments</comments>
		<pubDate>Fri, 04 Feb 2011 17:49:59 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[android ndk]]></category>
		<category><![CDATA[android visual studio]]></category>
		<category><![CDATA[microsoft visual studio]]></category>
		<category><![CDATA[msbuild]]></category>
		<category><![CDATA[ndk visual studio]]></category>
		<category><![CDATA[visual studio]]></category>
		<category><![CDATA[visual studio android]]></category>
		<category><![CDATA[vs-android]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=1042</guid>
		<description><![CDATA[DISCLAIMER: I tend to waffle on a bit. &#8220;Skip to the end&#8221; if you just want to find out about vs-android, and where to download it. &#160; About six weeks ago I moved into that club which everyone else seemed to be part of, but not me. I joined the ranks of smartphone owners! No [...]]]></description>
			<content:encoded><![CDATA[<p><center><img src="http://www.gavpugh.com/wp-content/uploads/2011/02/vsandroid1.png" alt="Visual Studio - Android" title="vsandroid" width="389" height="175" class="aligncenter size-full wp-image-1052" /></center></p>
<table border=0 bgcolor="#DDDDDD" CELLSPACING=0 CELLPADDING=0>
<tr>
<td>
<strong>DISCLAIMER:</strong> I tend to waffle on a bit. <a href="http://www.gavpugh.com/2011/02/04/vs-android-developing-for-android-in-visual-studio/#vs-android">&#8220;Skip to the end&#8221;</a> if you just want to find out about <i>vs-android</i>, and where to download it.
</td>
</tr>
<tr>
<td bgcolor="#FFFFFF">&nbsp;</td>
</tr>
</table>
<p>About six weeks ago I moved into that club which everyone else seemed to be part of, but not me. I joined the ranks of smartphone owners! No more 90&#8242;s flip-phone; I picked up a recent-ish Android handset. I&#8217;d never really been too into the whole concept of smartphone, but was starting to feel a little left behind. I must say that after those few weeks I&#8217;m sold, these things are pretty cool.</p>
<p>So, what&#8217;s a programmer to do? I think I may have actually downloaded the Android SDK before I even received the phone. Yeah, just a little bit eager! It&#8217;s actually the second handheld device I&#8217;ve tried to code on. The first being the <a href="http://en.wikipedia.org/wiki/Tapwave_Zodiac" target="_blank">Tapwave Zodiac</a>, also with an arm processor and touchscreen. I never really got anything worthwhile going on it, my excuse being a job hunt and subsequent move to the United States. But nonetheless, it was a fun little handheld to code for. I was certainly looking forward to coding on a much more popular device.</p>
<p><span id="more-1042"></span></p>
<h2>Total Eclipse of the IDE</h2>
<p>Now if you&#8217;ve ever tried to write anything for the Android, you&#8217;ll know the preferred development environment is Eclipse. If you&#8217;re writing your stuff completely in Java, you have everything you&#8217;d ever need in Eclipse. It seems to do all the nice syntax highlighting, and intellisense-like functionality that Visual Studio offers. Of course the shortcut keys are completely wrong, and must have been setup by a madman <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> , but it does seem a pretty good IDE to develop in. Better yet, it&#8217;s free!</p>
<p>But is it for me? Nah. It&#8217;s not for me.</p>
<p>I just couldn&#8217;t get on with it. Primarily I want to write my code in C/C++ too. So I started to convince myself that I needn&#8217;t bother with Eclipse. I can get all the highlighting and quick-reference stuff in Visual Studio, and I could run batch files to build my code. After all, with C++ under Eclipse you still have to install Cygwin and effectively build from the command-line. (or setup batch/makefiles as you would with Visual Studio).</p>
<p><center><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/02/eclipse1.png" alt="eclipse" title="eclipse" width="638" height="211" class="aligncenter size-full wp-image-1089" /></center></p>
<p>&nbsp;</p>
<p>I&#8217;ve used Visual Studio for a very long time now, since it&#8217;s older guise as simply: &#8216;Visual C++&#8217;. Was <a href="http://en.wikipedia.org/wiki/Visual_C%2B%2B#32-bit_versions" target="_blank">version 4.0</a> I think that I started with, when I moved from DOS to Windows programming. Now it&#8217;s my primary coding IDE; I&#8217;ve used it at both games companies I&#8217;ve worked at in the past decade. It&#8217;s an odd one to admit, but it&#8217;s too hard to let the thing go.</p>
<h2>Makefile Project</h2>
<p>So I set off and started a &#8216;Makefile Project&#8217; in Visual Studio. I could update the system include paths under Visual Studio 2010 (something I think was trickier with earlier versions, or at least not set on a per-project basis, I forget).  This meant I&#8217;d get properly working intellisense of the Android NDK headers, the &#8216;External Dependencies&#8217; list in my solution was all completely correct too. All in all, a pretty nice setup.</p>
<p>I put together a batch file, which invoked a cygwin session running &#8216;ndk-build&#8217;. I then setup some further ones which would build the entire package using &#8216;ant&#8217;, and then install and run the application on the Android device connected to my PC. Not much to argue with here. For someone who was longing for Visual Studio back, after a few days with Eclipse. It was lovely.</p>
<p>If you want to try the makefile method, take a look at this website:</p>
<ul>
<li><a href="http://ian-ni-lewis.blogspot.com/2011/01/adventures-on-android-ndk-part-i.html" target="_blank">http://ian-ni-lewis.blogspot.com/2011/01/adventures-on-android-ndk-part-i.html</a></li>
</ul>
<p>His method is a little cleaner than the one I used, my batch/script files were hard-coded messes of experimentation. Check out the <a href="http://ian-ni-lewis.blogspot.com/2011/01/its-like-coming-home-again.html" target="_blank">debugging article</a> on his page too, he&#8217;s got a way of using WinGDB to debug Android NDK code in Visual Studio. It&#8217;s awesome.</p>
<h2>What about when it gets big?</h2>
<p>Unfortunately Android&#8217;s NDK build scripts under Cygwin on Windows, isn&#8217;t exactly the performer. When your file count gets into triple figures the initial dependency checks take an age. I also wasn&#8217;t too enamored with not knowing what was passed to my compiler. You get a limited set of proprietary settings you can change in your makefile, but it did feel like a black box.</p>
<p><center><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/02/ndk-build.png" alt="ndk-build" title="ndk-build" width="395" height="105" class="aligncenter size-full wp-image-1084" /></center></p>
<p>&nbsp;</p>
<p>Coming from a console background, I like to know what my debug and release builds actually are. I also like to setup further build variants too&#8230; Usually one specific to profiling the game, essentially release with some limited modules enabled to do the profiling. The other major one would be a variant of my debug build, with asserts on but the optimization cranked up to max. </p>
<p>So it did feel a little confining. My realization about the build slowdowns with lots of files came when I attempted to integrate third-party code&#8230; Specifically what I&#8217;m wanting to use is the <a href="http://irrlicht.sourceforge.net/" target="_blank">Irrlicht engine</a>. It&#8217;s a well-structured open source rendering engine. Very versatile, and runs on a variety of platforms. Android included, of course.</p>
<p>Runing ndk-build, the thing would sit there for well over a minute before even starting to compile files. I&#8217;ve a recent i7-based laptop too, so it&#8217;s no slouch. I had an itching to try and delve into a more integrated method of building with Visual Studio, and that tipped the balance for me.</p>
<h2>Enter MSBuild</h2>
<p>With Visual Studio 2010 Microsoft made a radical change to the way their C++ environment worked. They moved over the entire thing to use MSBuild. Having worked with a certain non-Microsoft gaming console, you could see that they had to do a little hoop-jumping in previous versions of Visual Studio. Integrating custom compilers with the older versions really appeared to be quite a task. With VS2010, it had been hinted on some preview posts from Microsoft that this would be far easier.</p>
<p>Unfortunately though when I started to look into this, I found next to no information on the web about it. Well, really I found absolutely nothing in the end. I found a couple of questions on stackoverflow.com about the same subject, but with no answers. I ended up searching through the Visual Studio directories to find the existing scripts for Microsoft&#8217;s compiler. From there I duplicated the directory layout and began tinkering with setting up a new platform.</p>
<p>I&#8217;d never used MSBuild before this. It was completely new to me, never even seen a MSBuild file before. I hear some game companies use it, but ours certainly doesn&#8217;t. I can definitely recommend it though, it&#8217;s very powerful and flexible. It does have quite a learning curve, and Google searching for documentation can lead you to very bad explanations of how it works. If you&#8217;re at all interested in it, I recommend this book:</p>
<ul>
<li><a href="http://www.amazon.com/Inside-Microsoft-Build-Engine-Foundation/dp/0735645248/mutomagaby-20" target="_blank">&#8220;Inside the Microsoft Build Engine: Using MSBuild and Team Foundation Build&#8221;</a> by Sayed Ibrahim Hashimi, William Bartholomew. </li>
</ul>
<p>As well as being a very good guide to MSBuild, it actually had a small chapter about exactly what I was trying to do! Something I couldn&#8217;t find at all with Google. Unfortunately I picked the book up after I&#8217;d done the majority of my scripting, but it at least showed me I was barking up the right tree.</p>
<p><a name="vs-android"></a> </p>
<h2>vs-android</h2>
<p><center><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/02/vsa1.png" alt="vs-android" title="vsa1" width="634" height="159" class="aligncenter size-full wp-image-1093" /><br />
</center></p>
<p>&nbsp;</p>
<p>So, <strong>vs-android</strong>. Once I&#8217;d gotten all the features I wanted, and all the bugs I could find ironed out, I decided to release it as open-source. The regular download package just consists of a collection of MSBuild scripts, which need to be copied within a certain sub-directory of your Visual Studio installation.</p>
<p>Alongside the scripts is a single DLL file. When you&#8217;re working with MSBuild, you can code up custom tasks in a .NET language, such as C#. The header dependency scanning code lives here, which invokes gcc to find all the headers that the c/cpp files would be dependent on. As well as some other command-line switch manipulation code. The full source to the C# DLL is up on my Google code page.</p>
<p><center><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2011/02/vsa2.png" alt="vs-android" title="vsa2" width="638" height="199" class="aligncenter size-full wp-image-1094" /><br />
</center><br />
&nbsp;</p>
<p>You can download vs-android here:</p>
<ul>
<li><a href="http://code.google.com/p/vs-android/" target="_blank">Google Code: vs-android</a></li>
</ul>
<p>There&#8217;s full documentation on those pages too. Along with a step-by-step example of getting Android&#8217;s &#8216;san-angeles&#8217; sample app compiling and linking. The Google Code page also contains more technical info about the implementation, if you&#8217;re interested. There&#8217;s a link on the main page to &#8216;tech notes&#8217;, which expands on some of the points I&#8217;ve touched on here.</p>
<p>One thing I&#8217;d like to mention is that you don&#8217;t need <b>Cygwin</b> at all any more, if you use vs-android. That in itself is a godsend! It&#8217;s been a few years since I last used it. It was compulsory for our build process a few years ago, when I was working in the United Kingdom. For whatever reason the install took far longer than I remember it taking, and it has a horrible long pause when the thing starts up. I&#8217;m definitely glad I don&#8217;t need to deal with it again for Android dev.</p>
<p>Finally, I&#8217;ll leave you with a comparison of the build times, versus using &#8216;ndk-build&#8217; (sans long Cygwin pause). They&#8217;re pretty good, but I think with some more work I can get the thing running even faster.</p>
<p><center><i>Building 381 .cpp/.c files. The <a href="http://irrlicht.sourceforge.net/" target="_blank">Irrlicht engine</a> Android port.</i></p>
<table border=0 cellspacing="10">
<tr>
<td></td>
<td><strong>ndk-build</strong></td>
<td><strong>vs-android</strong></td>
</tr>
<tr>
<td><strong><strong>Full Rebuild</strong></strong></td>
<td>9m14s</td>
<td>5m32</td>
</tr>
<tr>
<td><strong>Incremental Build (1 cpp changed)</strong></td>
<td>1m24s</td>
<td>35s</td>
</tr>
<tr>
<td><strong>No-op build (build with nothing changed)</strong></td>
<td>1m2s</td>
<td>0s</td>
</tr>
<tr>
<td><strong>Single cpp build, aka Ctrl-F7</strong></td>
<td>N/A</td>
<td>2s</td>
</tr>
</table>
<p></center></p>
<p>&nbsp;</p>
<h2>What&#8217;s next?</h2>
<p>I&#8217;d hope to continue updating these scripts in future. I&#8217;ve got a nice list of things I&#8217;d like to tackle already. For now though, I&#8217;m going to take a little break from the build scripts. I&#8217;m very happy that I can change gears back to writing game code again. Getting a &#8216;release&#8217; together, with all that it entails, documentation and everything is pretty draining.</p>
<p>I think the last time I put something up on the internet like this was in 1997, when I worked on an <a href="http://www.gavpugh.com/old-code/">editor for Command and Conquer: Red Alert</a>. If you do click onto the garish Geocities website, keep in mind that I was a teenager at the time. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2011/02/04/vs-android-developing-for-android-in-visual-studio/feed/</wfw:commentRss>
		<slash:comments>37</slash:comments>
		</item>
		<item>
		<title>XNA/C# &#8211; StringBuilder changes in XNA 4.0</title>
		<link>http://www.gavpugh.com/2010/12/21/xnac-stringbuilder-changes-in-xna-4-0/</link>
		<comments>http://www.gavpugh.com/2010/12/21/xnac-stringbuilder-changes-in-xna-4-0/#comments</comments>
		<pubDate>Tue, 21 Dec 2010 19:00:18 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[FieldAccessException]]></category>
		<category><![CDATA[StringBuilder]]></category>
		<category><![CDATA[System.Text.StringBuilder]]></category>
		<category><![CDATA[windows 7 phone]]></category>
		<category><![CDATA[windows phone]]></category>
		<category><![CDATA[windows phone 7]]></category>
		<category><![CDATA[Xbox]]></category>
		<category><![CDATA[Xbox 360]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=967</guid>
		<description><![CDATA[So yeah, this is another post detailing a change made in the latest version of XNA. This one was inspired by some comments on a previous blog post of mine: &#8220;StringBuilder to String with no garbage&#8221;. A developer named Matt, who was targeting Windows 7 Phones, pointed out that this particular trick with reflection was [...]]]></description>
			<content:encoded><![CDATA[<p><center><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2010/12/StringHeader.png" alt="StringBuilder" title="StringBuilder" width="450" height="283" class="aligncenter size-full wp-image-972" /><br />
</center></p>
<p>So yeah, this is another post detailing a change made in the latest version of XNA.</p>
<p>This one was inspired by some comments on a previous blog post of mine: <a href="http://www.gavpugh.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/">&#8220;StringBuilder to String with no garbage&#8221;</a>. A developer named Matt, who was targeting Windows 7 Phones, pointed out that this particular trick with reflection was not working. He&#8217;d get a &#8216;FieldAccessException&#8217; when attempting to access the internal private System.String object.</p>
<p>I&#8217;d just got round to installing the Windows Phone stuff to check this out, and indeed this is the case. I tried various different flags in the GetField() call, but had no luck in getting it to work. I tried setting up a trivial case with my own class containing a private &#8216;System.String&#8217; and had the exact same problem.</p>
<p><span id="more-967"></span></p>
<p>So for whatever reason Windows Phone&#8217;s Compact Framework doesn&#8217;t allow access to private members via the GetValue() reflection call. In my aforementioned test with my own custom class, public members worked fine. In both cases the GetField() method was all good, it was just the GetValue() that throws &#8216;FieldAccessException&#8217; in the case of private members.</p>
<p>Well&#8230; That&#8217;s a bit of a fly in the ointment right there. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<h3>Windows PC: A totally new version of StringBuilder?</h3>
<p>Upon further inspection with the new XNA, I saw that the Windows setup had changed too. The StringBuilder object contents had changed completely. </p>
<p>For reference, here&#8217;s what I&#8217;ll call &#8216;version one&#8217; of the StringBuilder. The one we&#8217;re used to from good &#8216;ol XNA 3.1:<br />
<center><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2010/12/SBPhone40.png" alt="StringBuilder_v1" title="StringBuilder_v1" width="292" height="120" class="alignnone size-full wp-image-981" /><br />
<i>StringBuilder version one</i><br />
</center></p>
<p>Here&#8217;s &#8216;version two&#8217;:<br />
<center><br />
<img src="http://www.gavpugh.com/wp-content/uploads/2010/12/SBWindows40.png" alt="StringBuilder_v2" title="StringBuilder_v2" width="295" height="171" class="alignnone size-full wp-image-982" /><br />
<i>StringBuilder version two</i><br />
</center><br />
</p>
<p>Very, very different. </p>
<p>This new version maintains a series of chunks. As chunks are added it actually ends up linking together multiple new StringBuilder objects. The member &#8216;m_ChunkPrevious&#8217; is this link.</p>
<p>From checking out the XNA 4.0 platforms, only the PC Windows build target uses this new StringBuilder. It could be argued that given that the GC performs well on PC that you need not use any tricks to grab internal strings anyway.</p>
<p>If you&#8217;re desperate though, I did come up with a crude method of grabbing the internal string without generating garbage. Be warned though, it&#8217;s far uglier than the previous &#8217;3.1&#8242; method I had.</p>
<p>Here goes:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">const</span> <span style="color: #6666cc; font-weight: bold;">int</span> MAX_STRING_SIZE <span style="color: #008000;">=</span> <span style="color: #FF0000;">64</span><span style="color: #008000;">;</span>
&nbsp;
StringBuilder my_string_builder<span style="color: #008000;">;</span>
<span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> my_char_array<span style="color: #008000;">;</span>
<span style="color: #6666cc; font-weight: bold;">string</span> my_dest_string <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">' '</span>, MAX_STRING_SIZE<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">unsafe</span> <span style="color: #6666cc; font-weight: bold;">void</span> CopyIntoString<span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">string</span> dest_string, <span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> char_buffer, <span style="color: #6666cc; font-weight: bold;">int</span> length <span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #000000;">System.<span style="color: #0000FF;">Diagnostics</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">Debug</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Assert</span><span style="color: #008000;">&#40;</span> dest_string<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span> <span style="color: #008000;">&gt;=</span> length <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">unsafe</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">fixed</span> <span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">*</span> dest_fixed <span style="color: #008000;">=</span> dest_string <span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">// Copy in the string data</span>
                <span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">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> length<span style="color: #008000;">;</span> i<span style="color: #008000;">++</span> <span style="color: #008000;">&#41;</span>
                <span style="color: #008000;">&#123;</span>
                    dest_fixed<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> char_buffer<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
                <span style="color: #008000;">&#125;</span>
&nbsp;
                <span style="color: #008080; font-style: italic;">// NULL terminate the dest string</span>
                <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span> length <span style="color: #008000;">&lt;</span> dest_string<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span> <span style="color: #008000;">&#41;</span>
                <span style="color: #008000;">&#123;</span>
                    dest_fixed<span style="color: #008000;">&#91;</span>length<span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">&#41;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
                <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> PrepareSB<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>            
    my_string_builder <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StringBuilder<span style="color: #008000;">&#40;</span>MAX_STRING_SIZE, MAX_STRING_SIZE<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Ensure this StringBuilder only has one chunk</span>
    StringBuilder sanity_check <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>StringBuilder<span style="color: #008000;">&#41;</span>my_string_builder<span style="color: #008000;">.</span><span style="color: #0000FF;">GetType</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetField</span><span style="color: #008000;">&#40;</span>
        <span style="color: #666666;">&quot;m_ChunkPrevious&quot;</span>, BindingFlags<span style="color: #008000;">.</span><span style="color: #0000FF;">NonPublic</span> <span style="color: #008000;">|</span> BindingFlags<span style="color: #008000;">.</span><span style="color: #0000FF;">Instance</span> <span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">.</span><span style="color: #0000FF;">GetValue</span><span style="color: #008000;">&#40;</span>my_string_builder<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">System.<span style="color: #0000FF;">Diagnostics</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">Debug</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Assert</span><span style="color: #008000;">&#40;</span> sanity_check <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Grab the char array from the StringBuilder</span>
    my_char_array <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span>my_string_builder<span style="color: #008000;">.</span><span style="color: #0000FF;">GetType</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetField</span><span style="color: #008000;">&#40;</span>
        <span style="color: #666666;">&quot;m_ChunkChars&quot;</span>, BindingFlags<span style="color: #008000;">.</span><span style="color: #0000FF;">NonPublic</span> <span style="color: #008000;">|</span> BindingFlags<span style="color: #008000;">.</span><span style="color: #0000FF;">Instance</span> <span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">.</span><span style="color: #0000FF;">GetValue</span><span style="color: #008000;">&#40;</span>my_string_builder<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">//! This function can be called iteratively and generates no garbage</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> TestSB<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// Put something in there</span>
    my_string_builder<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
    my_string_builder<span style="color: #008000;">.</span><span style="color: #0000FF;">Append</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Hello World!&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Copy into our dest string</span>
    CopyIntoString<span style="color: #008000;">&#40;</span>my_dest_string, my_char_array, my_string_builder<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Note this dest string is a little odd, the NULL terminator shows in the </span>
    <span style="color: #008080; font-style: italic;">// debugger with all the spaces after it.</span>
    <span style="color: #008080; font-style: italic;">// On use of the string though in code, I'm seeing the correct amount of </span>
    <span style="color: #008080; font-style: italic;">// characters used. It stops at the NULL.</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>My eyes! <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>It works&#8230; But really; I wouldn&#8217;t touch this monstrosity.<br />
&nbsp;<br />
</p>
<hr />
&nbsp;<br />
</p>
<h1>Summary by Version and Platform</h1>
<p>&nbsp;<br />
<br />
So what follows here is a summary of the version of StringBuilder used on each platform, under both XNA 3.1 and 4.0. I also note the version of &#8216;mscorlib&#8217; as listed in the project references section; this is the assembly which contains the System.Text.StringBuilder class.</p>
<h3>Visual Studio 2008, and XNA v3.1</h3>
<h4>Windows</h4>
<p><b>mscorlib v2.0.0.0, Runtime Version v2.0.50727</b><br />
Uses StringBuilder version one. The technique detailed <a href="http://www.gavpugh.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/">here</a> works fine.</p>
<h4>Xbox 360</h4>
<p><b>mscorlib v3.5.0.0, Runtime Version v2.0.50727</b><br />
Uses StringBuilder version one. The technique detailed <a href="http://www.gavpugh.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/">here</a> works fine.</p>
<h3>Visual Studio 2010, and XNA v4.0</h3>
<h4>Windows Phone 7</h4>
<p><b>mscorlib v2.0.5.0, Runtime Version v2.0.50727</b><br />
Uses StringBuilder version one. Unfortunately reflection access to the internal System.String is disallowed. You&#8217;re stuck with using ToString() and incurring garbage.</p>
<h4>Windows</h4>
<p><b>mscorlib v4.0.0.0, Runtime Version v4.0.30319</b><br />
Uses StringBuilder version <strong>two</strong>. This new implementation of StringBuilder requires a convoluted way of converting the StringBuilder to a System.String, without generating garbage. I&#8217;d say incurring the garbage hit on PC is preferable to using the hacky stuff I&#8217;ve published in this post.</p>
<h4>Xbox 360</h4>
<p><b>mscorlib v2.0.5.0, Runtime Version v2.0.50727</b><br />
Uses StringBuilder version one. The technique detailed <a href="http://www.gavpugh.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/">here</a> works fine.</p>
<p>Oddly enough the main version number dropped to v2.0.5.0, from v3.5.0.0. A little confusing. The versions though match the Windows Phone 7 assemblies exactly.</p>
<h3>Conclusions</h3>
<p>So, under XNA 4.0 you&#8217;re out of luck on Windows Phone 7 unfortunately. Please let me know though if this isn&#8217;t the case, if you find some other way of getting round it please drop a comment on this post.</p>
<p>For Xbox 360 we&#8217;re fortunately still good to use the same methods which worked under XNA 3.1.</p>
<p>It&#8217;s pretty much inevitable though that in future both Phone 7 and Xbox 360 are bumped up to the new .NET StringBuilder class, which Windows currently uses. Possibly even Xbox 360 may get the same reflection shackles that Phone 7 has now too.</p>
<p>Can only hope that when we get a new Compact Framework, it comes with a shiny new generational garbage collector implementation. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h3>References</h3>
<ul>
<li><a href="http://www.nesterovsky-bros.com/weblog/2010/08/25/StringAndStringBuilderInNET4.aspx" target="_blank">String and StringBuilder in .NET 4</a></li>
<li><a href="http://stackoverflow.com/questions/3564906/how-the-stringbuilder-class-is-implemented-does-it-internally-create-new-string" target="_blank">How the StringBuilder class is implemented? Does it internally create new string objects each time we append?</a></li>
<li><a href="http://stackoverflow.com/questions/4166155/does-stringbuilder-become-immutable-after-a-call-to-tostring" target="blank">Does StringBuilder become immutable after a call to ToString?</a></li>
<li><a href="http://www.gavpugh.com/2010/03/23/xnac-stringbuilder-to-string-with-no-garbage/" target="_blank">XNA/C# – StringBuilder to String with no garbage</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2010/12/21/xnac-stringbuilder-changes-in-xna-4-0/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>XNA/C# &#8211; Thread-local storage on Xbox 360</title>
		<link>http://www.gavpugh.com/2010/11/29/xnac-thread-local-storage-on-xbox-360/</link>
		<comments>http://www.gavpugh.com/2010/11/29/xnac-thread-local-storage-on-xbox-360/#comments</comments>
		<pubDate>Mon, 29 Nov 2010 17:48:53 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[compact framework]]></category>
		<category><![CDATA[LocalDataStoreSlot]]></category>
		<category><![CDATA[Thread-Local Storage]]></category>
		<category><![CDATA[threadlocal]]></category>
		<category><![CDATA[ThreadStatic]]></category>
		<category><![CDATA[Xbox]]></category>
		<category><![CDATA[Xbox 360]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=891</guid>
		<description><![CDATA[&#160; I initially begun writing this particular article back in April. Back then with XNA 3.1 to play with, there was actually a method of &#8216;thread-local storage&#8217; for Xbox. With the release of XNA 4.0, this last remaining native method was removed. The [ThreadLocal] attribute though was added to the Compact Framework, but it seems [...]]]></description>
			<content:encoded><![CDATA[<p><center><img class="alignnone size-full wp-image-893" title="Thread-local storage" src="http://www.gavpugh.com/wp-content/uploads/2010/11/threadlocalstore.jpg" alt="Thread-local storage" width="400" height="277" /></center></p>
<p>&nbsp;</p>
<p>I initially begun writing this particular article back in April. Back then with XNA 3.1 to play with, there was actually a method of &#8216;thread-local storage&#8217; for Xbox. With the release of XNA 4.0, this last remaining <a href="http://www.gavpugh.com/2010/11/23/xnac-changes-in-the-xbox-360-compact-framework/">native method was removed</a>. The [ThreadLocal] attribute though was added to the Compact Framework, but it seems to be a <a href="http://www.gavpugh.com/2010/11/26/xnac-%E2%80%93-threadstatic-attribute-is-broken-on-xbox-360/">stubbed non-functional attribute</a> on Xbox 360.</p>
<p>So, where does that leave us? There is various ways you can manually code up a thread-local storage solution. The whole crux of it is data-retrieval and storage on a per-thread basis. The most immediately obvious way to go is just some sort of associative container, a Dictionary<> of some sort of thread &#8216;id&#8217; mapped to the data you wish to store.</p>
<p><span id="more-891"></span></p>
<p>Just something like:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Dictionary<span style="color: #008000;">&lt;</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Threading</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">Thread</span>, MyClass <span style="color: #008000;">&gt;</span> my_tls_data<span style="color: #008000;">;</span></pre></div></div>

<p>There&#8217;s a lot of room for freedom in implementation though. Is Dictionary<> really the most suitable container? Should items be auto-created on the first access, or explicitly created by the user? Most of all I want to keep things performing well. Given some functionality performs <a href="http://www.gavpugh.com/2010/04/30/xnac-thread-currentthread-is-slow-on-xbox-360/">extremely poorly on the Xbox 360</a>, I want to be careful what I throw into my implementation.</p>
<h3>The profiling approach</h3>
<p>So, here&#8217;s how I set things up to profile changes I made throughout development:</p>
<ul>
<li>My test case sets up ten threads.</li>
<li>Each thread has TLS data which consists of one simple integer.</li>
<li>I kick off all ten threads at once, and each runs a loop 100,000 times incrementing their integer by one each time. (I verified the loop is not optimized out for the release-JIT&#8217;d builds).</li>
<li>Once I see all ten threads have finished their loops I conclude the test and take the timing.</li>
<li>I run the tests over and over and calculate a running average time. I display the results on screen, as opposed to debug output. So I can see the results on a release build which isn&#8217;t connected to the debugger. Pretty simple stuff, it just looks like this:<br />
<img src="http://www.gavpugh.com/wp-content/uploads/2010/11/profiling.png" alt="TLS Profiling" title="TLS Profiling" width="504" height="71" class="aligncenter size-full wp-image-947" />
</li>
<li>Xbox times have a steady average very quickly after just a dozen or so tests. Windows times were more erratic and I generally left them for a couple of minutes to settle down.</li>
</ul>
<h3>Implementation choices</h3>
<p>So, given the myriad of different ways this thing could be done, I broke down the choices I&#8217;d need to make. Here&#8217;s a breakdown piece-by-piece of the decisions I made along the way. Forgive the language, they&#8217;re just lifted verbatim from notes I made:</p>
<ul>
<li><strong>Array over Dictionary<></strong></li>
<ul>
<li>For both Windows and Xbox with ten test threads, using an array instead of a Dictionary<> was a little over twice as fast. 74ms versus 151ms on Xbox.</li>
<li>From additional testing on Xbox, array became a comparable speed to Dictionary<> at around 32 threads. I threw in a couple of different access patterns to test with too. Only if you&#8217;re going crazy with threads and data access, will Dictionary<> be a win.</li>
<li>See the source code for the array implementation. It&#8217;s just essentially a simple associative container of &#8216;Thread&#8217;->&#8217;Data&#8217;. Potentially the whole array needs to be searched on each access. But keeping the array size small makes this a win over Dictionary<>.</li>
</ul>
<li><strong>For vs foreach on array access</strong></li>
<ul>
<li>A for loop incrementing an integer was faster.</li>
<li>Doing the search with foreach() instead roughly doubled the times. 74ms versus 141ms.</li>
</ul>
<li><strong>Thread object vs integer thread ID (ManagedThreadId)</strong></li>
<ul>
<li>Each of these approaches were within a millisecond of one other. Something like 73.5ms versus 74ms. The integer version was the slight winner.</li>
<li>I kind of like using the object reference, it makes debugging easier. So I went with that instead of using the integer ID.</li>
</ul>
<li><strong>Call to Thread.CurrentThread on data access.</strong></li>
<ul>
<li>Cost is prohibitive on Xbox, see a blog post I wrote a while back:<br /><a href="http://www.gavpugh.com/2010/04/30/xnac-thread-currentthread-is-slow-on-xbox-360/">http://www.gavpugh.com/2010/04/30/xnac-thread-currentthread-is-slow-on-xbox-360/</a></li>
<li>This is still the case under XNA 4.0, figures haven&#8217;t changed. For the testing I was doing for these classes, calling Thread.CurrentThread on Xbox each access increases the time taken in one example from 74ms up to 7248ms. The equivalent test on Windows went from 26ms up to 32ms.</li>
<li>My class has to provide a data accessor which takes a thread object param.</li>
</ul>
<li><strong>Explicit cleanup, versus WeakReference to determine threads are done with.</strong></li>
<ul>
<li>WeakReference is slow on Xbox unfortunately too. Even worse than Thread.CurrentThread in my tests. The example case I used shot up from 74ms to over 40,000ms. Windows jumped from 26ms to 76ms.</li>
<li>I chose to use explicit cleanup. </li>
<li>Side note: To make cleanup easier on thread destruction, consider a TLS manager class. The TLS objects can register with the manager upon creation, and the manager can walk them all destroy any data associated to a specific thread.</li>
</ul>
<li><strong>Explicit construction, versus &#8216;auto&#8217; construction.</strong></li>
<ul>
<li>Auto construction isn&#8217;t too much of a performance drop. It just adds an extra branch to the code if the data access fails to find its data. Which you probably would have in there anyway to throw an Exception, or fire an assert.</li>
<li>In my tests removing auto construction from my code, dropped the reference 74ms case down to 73ms. Good tradeoff in my opinion, so I kept auto-construction.</li>
</ul>
<li><strong>Avoid thread locks for data access</strong></li>
<ul>
<li>Locks are only required for adding new array entries, or removing them. The data access function should be able to execute in the general case without a lock.</li>
<li>With auto-construction though, a new entry could be added within the accessing function. There&#8217;s a risk of a race condition if two concurrent threads try to auto-construct the data for one specific thread.</li>
<li>As long as we can be sure that threads only access their own data, everything is fine. So the GetData(Thread) version should verify that the thread matches Thread.CurrentThread.</li>
<li>The check only needs to be made after the search fails, just as it&#8217;s about to do the auto-construction. I ended up just putting this code within #if DEBUG, so I didn&#8217;t have to worry about any performance hit.</li>
</ul>
</ul>
<h3>Explicit cleanup</h3>
<p>I wasn&#8217;t too happy with requiring explicit cleanup. It means the cleanest solution would be some kind of global static function which ensured all various TLS variables are freed. Something like:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> CleanupTLS<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    Profiler<span style="color: #008000;">.</span><span style="color: #0000FF;">GetCurrentNodeStack</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">FreeData</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    Debug<span style="color: #008000;">.</span><span style="color: #0000FF;">Output</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetStringBuilder</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">FreeData</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    Renderer<span style="color: #008000;">.</span><span style="color: #0000FF;">DebugLines</span><span style="color: #008000;">.</span><span style="color: #0000FF;">FreeData</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// etc...</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Consider too that some of these variables may be initially at private scope, so they would need to be specifically exposed somehow so the freeing can occur. At best you&#8217;d need to add explicit public freeing functions to various affected modules.</p>
<p>As hinted in my notes, a global manager class which registers all TLS variables could make this a lot cleaner. As TLS data is instantiated, I will register with the manager. Where this occurs is not performance-critical. The freeing isn&#8217;t performance-critical either. The freeing though is pretty simple, the manager just walks all the TLS references it&#8217;s been given, and attempts to purge any with data for a specific thread.</p>
<p>So instead of calling the above mess, you can just call:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Core<span style="color: #008000;">.</span><span style="color: #0000FF;">ThreadLocalManager</span><span style="color: #008000;">.</span><span style="color: #0000FF;">FreeData</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Bit happier with it now. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h3>Profiling figures</h3>
<p>I explained my profiling setup earlier in this article. Here are the figures with my final implementation, compared against the existing methods of TLS. The &#8216;No param&#8217; version of my code makes a call to &#8216;Thread.CurrentThread&#8217; each time to determine what data to pass back. The &#8216;Thread param&#8217; version uses a passed in thread reference to retrieve the data instead.</p>
<p>The figures are for ten concurrent threads making 100,000 accesses each:</p>
<table border="1" cellspacing="0" cellpadding="2">
<tbody>
<tr height="20">
<td width="300" height="20"></td>
<td align="center" colspan="2"><b>Windows PC</b></td>
<td align="center"colspan="2" ><b>Xbox 360</b></td>
</tr>
<tr height="20">
<td height="20"></td>
<td width="180" align="center">Release &#8211; <br />Debugger</td>
<td width="180" align="center">Release &#8211; JIT&#8217;d</td>
<td width="180" align="center">Release &#8211; <br />Debugger</td>
<td width="180" align="center">Release &#8211; JIT&#8217;d</td>
</tr>
<tr height="20">
<td height="20"><strong>My code &#8211; No param</strong></td>
<td align="right">152.3ms</td>
<td align="right">31.2ms</td>
<td align="right"><b>*</b> 7805.9ms</td>
<td align="right"><b>*</b> 7248.8ms</td>
</tr>
<tr height="20">
<td height="20"><strong>My code &#8211; Thread param</strong></td>
<td align="right">139.4ms</td>
<td align="right">27.9ms</td>
<td align="right">456.8ms</td>
<td align="right">74.2ms</td>
</tr>
<tr height="20">
<td height="20"><strong>[ThreadStatic]</strong></td>
<td align="right">172.7ms</td>
<td align="right">45.6ms</td>
<td align="right">N/A</td>
<td align="right">N/A</td>
</tr>
<tr height="20">
<td height="20"><strong>GetData/SetData()</strong></td>
<td align="right">164.3ms</td>
<td align="right">51.1ms</td>
<td align="right"><b>**</b> 7854.1ms</td>
<td align="right"><b>**</b> 7565.3ms</td>
</tr>
</tbody>
</table>
<p>&nbsp;<br />
<i>* Using &#8216;Thread.CurrentThread&#8217; on Xbox 360 <a href="http://www.gavpugh.com/2010/04/30/xnac-thread-currentthread-is-slow-on-xbox-360/">is very slow</a>.</i><br />
<i>** The GetData/SetData() (LocalDataStoreSlot) method doesn&#8217;t work under XNA 4.0 on Xbox 360. These figures are from when I ran the same tests months ago under XNA 3.1 on 360.</i></p>
<p>Given these figures I&#8217;m happy to use my new implementation for both Windows and Xbox 360. There&#8217;s no alternatives currently for Xbox 360, so given I&#8217;ve explored many optimization possibilities it&#8217;s pretty much as good as it gets. For Windows it actually is slightly faster than even [ThreadStatic], so using the same code across both totally makes sense.</p>
<h3>Show me the code</h3>
<p>Here&#8217;s the code for download:<br />
<a href="http://www.gavpugh.com/source/ThreadLocal.cs"><br />
<img class="alignleft size-full wp-image-437" style="vertical-align: middle;" title="cs_file" src="http://www.gavpugh.com/wp-content/uploads/2010/03/cs_file1.png" alt="C# File" width="48" height="52" /><strong>ThreadLocal.cs</strong></a></p>
<p>It also includes the class for &#8216;ThreadLocalManager&#8217;, which as detailed earlier assists with easier cleanup of data from destroyed threads.</p>
<p>Here&#8217;s a quick contrived bit of code to show how these classes should be used:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> Core<span style="color: #008000;">.</span><span style="color: #0000FF;">ThreadLocal</span><span style="color: #008000;">&lt;</span>StringBuilder<span style="color: #008000;">&gt;</span> ms_tls_stringbuilder <span style="color: #008000;">=</span> 
    <span style="color: #008000;">new</span> Core<span style="color: #008000;">.</span><span style="color: #0000FF;">ThreadLocal</span><span style="color: #008000;">&lt;</span>StringBuilder<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">//! Entry function for new worker threads</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> ThreadRun<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// Grab the TLS stringbuilder</span>
    StringBuilder sb <span style="color: #008000;">=</span> ms_tls_stringbuilder<span style="color: #008000;">.</span><span style="color: #0000FF;">Data</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Do bunch of work</span>
    <span style="color: #008000;">...</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Free all TLS data associated with this thread</span>
    Core<span style="color: #008000;">.</span><span style="color: #0000FF;">ThreadLocalManager</span><span style="color: #008000;">.</span><span style="color: #0000FF;">FreeData</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The TLS data access has a function which takes a thread parameter. This should be used in performance-critical code, given my findings detailed in this article. Just note the &#8216;Thread.CurrentThread&#8217; once in your new thread, and pass it around to any performance-critical functions that require working with TLS.</p>
<h3>Value Types</h3>
<p>My implementation is currently tied to just using reference types, value types will not work with it. An alternative is to just simply wrap value types in a class, which is what I&#8217;ve been happy to do with my engine.</p>
<p>If you absolutely need a thread-local implementation which does work natively with value types, it&#8217;s not too hard to do. You&#8217;d want to set up an alternative class, with pretty much the same code in it. Change the &#8216;where&#8217; constraint to simply: <strong>&#8216;struct&#8217;</strong>. There&#8217;s a couple of different ways I could see the implementation going:</p>
<ul>
<li>Implement separate Get and Set data methods. Maybe just a single property?</li>
<li>Have a get method not return a value, but instead pass it back through a reference parameter.</li>
</ul>
<p>There&#8217;s no reason why you couldn&#8217;t have both these types of interface for it.</p>
<h3>References</h3>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/bb203915.aspx" target="_blank">MSDN: Namespaces, Types, and Members in the .NET Compact Framework for Xbox 360</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/6sby1byh%28v=VS.100%29.aspx" target="_blank">MSDN: Thread Local Storage: Thread-Relative Static Fields and Data Slots</a></li>
<li><a href="http://forums.xna.com/forums/t/18202.aspx?PageIndex=1" target="_blank">XNA Forums: possible to have an array on stack, not in heap?</a></li>
<li><a href="http://forums.xna.com/forums/p/29351/164709.aspx" target="_blank">XNA Forums: Why no ThreadStaticAttribute on XNA?</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/d5x73970.aspx" target="_blank">MSDN: Constraints on Type Parameters</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2010/11/29/xnac-thread-local-storage-on-xbox-360/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>XNA/C# – [ThreadStatic] attribute is broken on Xbox 360</title>
		<link>http://www.gavpugh.com/2010/11/26/xnac-%e2%80%93-threadstatic-attribute-is-broken-on-xbox-360/</link>
		<comments>http://www.gavpugh.com/2010/11/26/xnac-%e2%80%93-threadstatic-attribute-is-broken-on-xbox-360/#comments</comments>
		<pubDate>Sat, 27 Nov 2010 04:34:28 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[compact framework]]></category>
		<category><![CDATA[SetProcessorAffinity()]]></category>
		<category><![CDATA[ThreadStatic]]></category>
		<category><![CDATA[ThreadStaticAttribute]]></category>
		<category><![CDATA[Xbox]]></category>
		<category><![CDATA[Xbox 360]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=853</guid>
		<description><![CDATA[Continuing on from my last XNA post, I had a go at using [ThreadStatic] on the Xbox. Specifically this attribute was not available with XNA 3.1, but was introduced in the new 4.0 version. At first glace it worked fine, I threw in the same code I&#8217;d used on Windows. Unlike under 3.1 it compiles [...]]]></description>
			<content:encoded><![CDATA[<p><center><img src="http://www.gavpugh.com/wp-content/uploads/2010/11/Thread2.png" alt="[ThreadStatic]" title="[ThreadStatic]" width="400" height="241" class="alignnone size-full wp-image-871" /><br />
</center></p>
<p>Continuing on from <a href="http://http://www.gavpugh.com/2010/11/23/xnac-changes-in-the-xbox-360-compact-framework/">my last XNA post</a>, I had a go at using <a href="http://msdn.microsoft.com/en-us/library/system.threadstaticattribute%28v=VS.95%29.aspx" target="_blank">[ThreadStatic]</a> on the Xbox. Specifically this attribute was not available with XNA 3.1, but was introduced in the new 4.0 version.</p>
<p>At first glace it worked fine, I threw in the same code I&#8217;d used on Windows. Unlike under 3.1 it compiles without issue. However, the attribute appears to actually do nothing it all. It behaves just like the attribute wasn&#8217;t there, just like a regular plain static variable.</p>
<p>I found this issue from attempting to use [ThreadStatic] within some code I had written for a future article here. The code was to profile various methods of implementing <a href="http://en.wikipedia.org/wiki/Thread-local_storage" target="_blank">Thread-local storage</a> on the Xbox 360. Switching the code to add a test case for [ThreadStatic] worked fine at first, but I was seeing very odd profile numbers coming back from it. On closer inspection in the debugger I could see that the TLS values weren&#8217;t thread-specific, they were getting written to at runtime by other executing threads.</p>
<p><span id="more-853"></span></p>
<h3>Show me the code</h3>
<p>So, I spliced out some code and came up with a contrived test to check how [ThreadStatic] is working. Here&#8217;s the code:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> ThreadTest
<span style="color: #008000;">&#123;</span>
    <span style="color: #008000;">&#91;</span>ThreadStatic<span style="color: #008000;">&#93;</span> <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">int</span> m_int_counter <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">private</span> Thread m_thread<span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">int</span> m_affinity<span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">int</span> m_thread_num<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> ThreadTest<span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">int</span> thread_num, <span style="color: #6666cc; font-weight: bold;">int</span> affinity <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        m_affinity <span style="color: #008000;">=</span> affinity<span style="color: #008000;">;</span>
        m_thread_num <span style="color: #008000;">=</span> thread_num<span style="color: #008000;">;</span>
        m_thread <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #008000;">&#40;</span> Run <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Start<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        m_thread<span style="color: #008000;">.</span><span style="color: #0000FF;">Start</span><span style="color: #008000;">&#40;</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&#41;</span><span style="color: #0600FF; font-weight: bold;">this</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Run<span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">object</span> passed_obj <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        ThreadTest this_obj <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span>ThreadTest<span style="color: #008000;">&#41;</span>passed_obj<span style="color: #008000;">;</span>
&nbsp;
        Debug<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span> <span style="color: #666666;">&quot;Started thread #&quot;</span> <span style="color: #008000;">+</span>
            this_obj<span style="color: #008000;">.</span><span style="color: #0000FF;">m_thread_num</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; Affinity=&quot;</span> <span style="color: #008000;">+</span> this_obj<span style="color: #008000;">.</span><span style="color: #0000FF;">m_affinity</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080;">#if XBOX</span>
        Thread<span style="color: #008000;">.</span><span style="color: #0000FF;">CurrentThread</span><span style="color: #008000;">.</span><span style="color: #0000FF;">SetProcessorAffinity</span><span style="color: #008000;">&#40;</span> this_obj<span style="color: #008000;">.</span><span style="color: #0000FF;">m_affinity</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080;">#endif //XBOX</span>
&nbsp;
        Debug<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span> 
            <span style="color: #666666;">&quot;Thread #&quot;</span> <span style="color: #008000;">+</span> this_obj<span style="color: #008000;">.</span><span style="color: #0000FF;">m_thread_num</span> <span style="color: #008000;">+</span> 
            <span style="color: #666666;">&quot;: Before m_int_counter &quot;</span> <span style="color: #008000;">+</span> m_int_counter <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        m_int_counter<span style="color: #008000;">++;</span>
&nbsp;
        Debug<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span> 
            <span style="color: #666666;">&quot;Thread #&quot;</span> <span style="color: #008000;">+</span> this_obj<span style="color: #008000;">.</span><span style="color: #0000FF;">m_thread_num</span> <span style="color: #008000;">+</span> 
            <span style="color: #666666;">&quot;: After m_int_counter &quot;</span> <span style="color: #008000;">+</span> m_int_counter <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// The four affinities that are okay to use. See:</span>
<span style="color: #008080; font-style: italic;">// http://msdn.microsoft.com/en-us/library/microsoft.xna.net_cf.system.threading.thread.setprocessoraffinity.aspx</span>
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> <span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> m_affinities <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">&#91;</span><span style="color: #FF0000;">4</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">&#123;</span> <span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">3</span>, <span style="color: #FF0000;">4</span>, <span style="color: #FF0000;">5</span> <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">bool</span> m_started <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// Call this from anywhere, I just threw it in Update() in a new XNA game project</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Test<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span> m_started <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// Just do it once...</span>
        <span style="color: #0600FF; font-weight: bold;">return</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
    m_started <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">const</span> <span style="color: #6666cc; font-weight: bold;">int</span> NUM_THREADS <span style="color: #008000;">=</span> <span style="color: #FF0000;">10</span><span style="color: #008000;">;</span>
&nbsp;
    ThreadTest<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> threads <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ThreadTest<span style="color: #008000;">&#91;</span>NUM_THREADS<span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Create ten threads and kick them off near-enough at the same time.</span>
    <span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">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> NUM_THREADS<span style="color: #008000;">;</span> i<span style="color: #008000;">++</span> <span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #6666cc; font-weight: bold;">int</span> affinity <span style="color: #008000;">=</span> m_affinities<span style="color: #008000;">&#91;</span>i <span style="color: #008000;">%</span> <span style="color: #FF0000;">4</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
        threads<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ThreadTest<span style="color: #008000;">&#40;</span> i, affinity <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        threads<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Start</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<h3>What&#8217;s up</h3>
<p>Firstly, here&#8217;s the output under Windows. The &#8216;before&#8217; number is always zero, and the &#8216;after&#8217; is always one. The [ThreadStatic] variable is indeed unique to each thread instance.</p>
<h4>Windows</h4>
<pre>
Started thread #0 Affinity=1
Started thread #6 Affinity=4
Started thread #4 Affinity=1
Started thread #7 Affinity=5
Started thread #8 Affinity=1
Started thread #2 Affinity=4
Started thread #9 Affinity=3
Thread #7: Before m_int_counter 0
Thread #8: Before m_int_counter 0
Thread #0: Before m_int_counter 0
Thread #6: Before m_int_counter 0
Thread #4: Before m_int_counter 0
Thread #2: Before m_int_counter 0
Thread #9: Before m_int_counter 0
Thread #8: After m_int_counter 1
Thread #7: After m_int_counter 1
Thread #0: After m_int_counter 1
Thread #6: After m_int_counter 1
Thread #4: After m_int_counter 1
Thread #9: After m_int_counter 1
Thread #2: After m_int_counter 1
Started thread #5 Affinity=3
Started thread #3 Affinity=5
Started thread #1 Affinity=3
Thread #1: Before m_int_counter 0
Thread #1: After m_int_counter 1
Thread #5: Before m_int_counter 0
Thread #5: After m_int_counter 1
Thread #3: Before m_int_counter 0
Thread #3: After m_int_counter 1
</pre>
<p>&nbsp;<br />
Disregard the affinity value for Windows, it&#8217;s not used. Anyhow, here&#8217;s the Xbox output.</p>
<h4>Xbox 360</h4>
<pre>
Started thread #0 Affinity=1
Thread #5: Before m_int_counter 3
Thread #6: Before m_int_counter 3
Thread #3: Before m_int_counter 3
Thread #2: Before m_int_counter 3
Thread #7: Before m_int_counter 3
Thread #9: Before m_int_counter 3
Thread #0: Before m_int_counter 3
Thread #5: After m_int_counter 4
Thread #6: After m_int_counter 5
Thread #3: After m_int_counter 6
Thread #2: After m_int_counter 7
Thread #7: After m_int_counter 8
Thread #9: After m_int_counter 9
Thread #0: After m_int_counter 10
</pre>
<p>&nbsp;</p>
<p>The [ThreadStatic] variable is obviously not unique to each thread. It&#8217;s just behaving like a regular static. If I comment out the line which sets the thread affinity (which is Xbox-specific code), I get similar output.</p>
<p>What&#8217;s also concerning is that the &#8220;Debug.WriteLine()&#8221; function seems to be randomly failing. Each time I run it, I get different lines missed out from my expected output.</p>
<p>Perhaps on Xbox it&#8217;s implementation is not completely thread-safe? I swear it was on XNA 3.1&#8242;s Compact Framework, but maybe my memory is failing me.</p>
<h3>Solutions?</h3>
<p>I have an alternate way of implementing TLS with C#. It&#8217;s very fast as long as you&#8217;re not running a ridiculous number of threads (under a dozen is fine). When I last looked at the code under XNA 3.1 it outperformed the <a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.getdata.aspx" target="_blank">&#8216;GetData/SetData()&#8217;</a> method of TLS considerably. In fact when I tested the code under Windows and compared it to [ThreadStatic], it outperformed that too.</p>
<p>Will be the next article I post up, since I think I&#8217;ve encountered all the issues I can on the road to finishing it up.</p>
<h3>References</h3>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.threadstaticattribute%28v=VS.95%29.aspx" target="_blank">ThreadStaticAttribute Class</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/microsoft.xna.net_cf.system.threading.thread.setprocessoraffinity.aspx" target="_blank">Thread.SetProcessorAffinity Method</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2010/11/26/xnac-%e2%80%93-threadstatic-attribute-is-broken-on-xbox-360/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XNA/C# &#8211; Changes in the Xbox 360 Compact Framework</title>
		<link>http://www.gavpugh.com/2010/11/23/xnac-changes-in-the-xbox-360-compact-framework/</link>
		<comments>http://www.gavpugh.com/2010/11/23/xnac-changes-in-the-xbox-360-compact-framework/#comments</comments>
		<pubDate>Tue, 23 Nov 2010 18:03:11 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[XNA / C#]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[compact framework]]></category>
		<category><![CDATA[Thread-Local Storage]]></category>
		<category><![CDATA[ThreadStatic]]></category>
		<category><![CDATA[Xbox]]></category>
		<category><![CDATA[Xbox 360]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.gavpugh.com/?p=805</guid>
		<description><![CDATA[A few months back I was partway through an article about XNA. I was going to cover how to implement efficient &#8220;Thread Local Storage&#8221; on the Xbox 360. Back in Game Studio v3.1 I found that the [ThreadStatic] attribute was not supported on the Xbox, and the only workable methods out of the box were [...]]]></description>
			<content:encoded><![CDATA[<p><center><img src="http://www.gavpugh.com/wp-content/uploads/2010/11/compactframework.jpg" alt="Compact Framework" title="Compact Framework" width="400" height="306" class="alignnone size-full wp-image-808" /><br />
</center></p>
<p>A few months back I was partway through an article about XNA. I was going to cover how to implement efficient <a href="http://en.wikipedia.org/wiki/Thread-local_storage" target="_blank">&#8220;Thread Local Storage&#8221;</a> on the Xbox 360. Back in Game Studio v3.1 I found that the <strong>[ThreadStatic]</strong> attribute was not supported on the Xbox, and the only workable methods out of the box were the Thread.GetData(), Thread.SetData() methods. Those methods aren&#8217;t good performance-wise, so I proceeded to look at more efficient alternatives.</p>
<p>That article was going to detail the solution I came up with, and currently used in my engine. However upon revisiting the work recently and upgrading to the new v4.0 XNA, I found that I had some compile errors. Specifically <strong>&#8216;System.Threading.LocalDataStoreSlot&#8217;</strong> was now missing, it&#8217;s that slow method of TLS I was using to benchmark against. So I commented that code out. I then figured why not for the hell of it try to enable the <strong>[ThreadStatic]</strong> code, that I had #ifdef&#8217;d to the WINDOWS build. Lo and behold, it now compiled on Xbox 360!</p>
<p><span id="more-805"></span></p>
<p>No idea if it&#8217;s any better performing than the old &#8216;LocalDataStoreSlot&#8217; though, or better than the alternate method I came up with. That&#8217;s an exercise for another day.</p>
<h3>My Googling Escapades</h3>
<p>The only article I could find back when I was working on 3.1 about [ThreadStatic] on Xbox was <a href="http://forums.create.msdn.com/forums/p/18202/96386.aspx" target="_blank">this</a> one. Doing a search now, I couldn&#8217;t find anything else new. I also tried searching for information about &#8220;LocalDataStoreSlot&#8221;, the class which was removed in the 4.0 upgrade. Again, I found nothing about the removal.</p>
<p>I also had noticed in some other code I have that the &#8216;System.Diagnostics.Trace&#8217; class, and static functions therein were also removed. Now I start to scratch my head a little and wonder what else has disappeared, and what other cool things may have been added. My searches weren&#8217;t very fruitful, I just found a handful of forum posts which mentioned briefly some sort of changes to the Compact Framework (I&#8217;ve included them in my references at the bottom of this page). Nothing complete and comprehensive which listed all the differences.</p>
<p>The MSDN documentation does denote on the page for each class, type, function&#8230; which platforms it is available on. There&#8217;s also a dropdown to switch the framework version. I confess I found it a bit unwieldy to check up on. For example &#8216;ThreadStaticAttribute&#8217; shows a &#8216;Silverlight&#8217; entry in the dropdown box. On that page it denotes that it works on the Xbox 360. Where &#8216;LocalDataStoreSlot&#8217; (the one which was removed), does not have Silverlight in it&#8217;s list, but does show XNA support for the 360 on the 3.5 Framework. Which tells me that it used to work, but now is deprecated in the Silverlight-compliant Framework.</p>
<p>Anyhow, checking these things one-by-one isn&#8217;t exactly viable.</p>
<h3>Taking a dump</h3>
<p>Knowing that there was a number of changes, but not knowing exactly what those changes were; I was still a little curious. What I did was to use the <a href="http://msdn.microsoft.com/en-us/library/f7dy01k1%28VS.80%29.aspx" target="_blank">&#8216;ildasm&#8217; tool</a> to dump the types which existed in the .NET Framework DLL files.</p>
<p>For those equally curious, they reside here:<br />
<strong>C:\Program Files\Microsoft XNA\XNA Game Studio\v3.1\References\Xbox360</strong><br />
and here:<br />
<strong>C:\Program Files\Microsoft XNA\XNA Game Studio\v4.0\References\Xbox360</strong><br />
Or wherever your &#8220;\Program Files&#8221; directory lies.</p>
<p>With a little tinkering I could collate that output and determine the changes which occurred between the two versions of the Framework. I omitted the <strong>&#8220;Microsoft.Xna.Framework.Input.Touch&#8221;</strong> library from the output though, since new Xbox 360 projects do not include it as a reference. I&#8217;m unsure though as to why there is a DLL sitting in the &#8220;Xbox 360&#8243; directory. Possibly early Natal/Kinect support code? Heh, I doubt it. I&#8217;m guessing it&#8217;s just stub functionality for parity with the Windows 7 phones.</p>
<p>So anyhow, here&#8217;s the data I collected. Hopefully others may find this useful&#8230; Or possibly just point me to a website that had this information already. <img src='http://www.gavpugh.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h3>System types <strong>removed</strong> from the Xbox 360 Compact Framework</h3>
<p>These are types which used to exist in the Compact Framework for the Xbox 360, in the &#8220;XNA Game Studio&#8221; v3.1 release. But these are now missing from the new v4.0 release:</p>
<pre>
  Microsoft.Xna.Framework.BatteryChargeStatus
  Microsoft.Xna.Framework.Graphics.BasicDirectionalLight
  Microsoft.Xna.Framework.Graphics.ClipPlane
  Microsoft.Xna.Framework.Graphics.ClipPlaneCollection
  Microsoft.Xna.Framework.Graphics.Color
  Microsoft.Xna.Framework.Graphics.CompilerOptions
  Microsoft.Xna.Framework.Graphics.DepthStencilBuffer
  Microsoft.Xna.Framework.Graphics.DeviceNotSupportedException
  Microsoft.Xna.Framework.Graphics.DeviceStillDrawingException
  Microsoft.Xna.Framework.Graphics.DeviceType
  Microsoft.Xna.Framework.Graphics.DriverInternalErrorException
  Microsoft.Xna.Framework.Graphics.EffectFunction
  Microsoft.Xna.Framework.Graphics.EffectFunctionCollection
  Microsoft.Xna.Framework.Graphics.EffectParameterBlock
  Microsoft.Xna.Framework.Graphics.EffectPool
  Microsoft.Xna.Framework.Graphics.GammaRamp
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/AddressCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/BlendCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/CompareCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/CursorCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/DeclarationTypeCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/DeviceCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/DriverCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/FilterCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/LineCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/PixelShaderCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/PrimitiveCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/RasterCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/ShadingCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/StencilCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/TextureCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/VertexFormatCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/VertexProcessingCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCapabilities/VertexShaderCaps
  Microsoft.Xna.Framework.Graphics.GraphicsDeviceCreationParameters
  Microsoft.Xna.Framework.Graphics.MultiSampleType
  Microsoft.Xna.Framework.Graphics.OutOfVideoMemoryException
  Microsoft.Xna.Framework.Graphics.PackedVector.Normalized101010
  Microsoft.Xna.Framework.Graphics.PackedVector.Rgba32
  Microsoft.Xna.Framework.Graphics.PackedVector.UInt101010
  Microsoft.Xna.Framework.Graphics.PixelShader
  Microsoft.Xna.Framework.Graphics.PresentOptions
  Microsoft.Xna.Framework.Graphics.QueryUsages
  Microsoft.Xna.Framework.Graphics.RasterStatus
  Microsoft.Xna.Framework.Graphics.RenderState
  Microsoft.Xna.Framework.Graphics.RenderTarget
  Microsoft.Xna.Framework.Graphics.ResolveTexture2D
  Microsoft.Xna.Framework.Graphics.ResourceType
  Microsoft.Xna.Framework.Graphics.SaveStateMode
  Microsoft.Xna.Framework.Graphics.ShaderConstant
  Microsoft.Xna.Framework.Graphics.ShaderConstantCollection
  Microsoft.Xna.Framework.Graphics.ShaderConstantTable
  Microsoft.Xna.Framework.Graphics.ShaderProfile
  Microsoft.Xna.Framework.Graphics.ShaderRegisterSet
  Microsoft.Xna.Framework.Graphics.SpriteBlendMode
  Microsoft.Xna.Framework.Graphics.StateBlock
  Microsoft.Xna.Framework.Graphics.SwapEffect
  Microsoft.Xna.Framework.Graphics.TextureUsage
  Microsoft.Xna.Framework.Graphics.TextureWrapCoordinates
  Microsoft.Xna.Framework.Graphics.VertexElementMethod
  Microsoft.Xna.Framework.Graphics.VertexShader
  Microsoft.Xna.Framework.Graphics.VertexStream
  Microsoft.Xna.Framework.Graphics.VertexStreamCollection
  Microsoft.Xna.Framework.Net.InviteAcceptedEventArgs
  Microsoft.Xna.Framework.Net.NetworkException
  Microsoft.Xna.Framework.Net.NetworkNotAvailableException
  Microsoft.Xna.Framework.NoSuitableGraphicsDeviceException
  Microsoft.Xna.Framework.PowerLineStatus
  Microsoft.Xna.Framework.PowerStatus
  System.ApplicationException
  System.CharEnumerator
  System.Collections.ArrayList
  System.Collections.CaseInsensitiveComparer
  System.Collections.CaseInsensitiveHashCodeProvider
  System.Collections.CollectionBase
  System.Collections.Comparer
  System.Collections.Generic.SortedList`2
  System.Collections.Hashtable
  System.Collections.IHashCodeProvider
  System.Collections.Queue
  System.Collections.SortedList
  System.Collections.Specialized.BitVector32
  System.Collections.Specialized.BitVector32/Section
  System.Collections.Specialized.HybridDictionary
  System.Collections.Specialized.ListDictionary
  System.Collections.Specialized.NameObjectCollectionBase
  System.Collections.Specialized.NameObjectCollectionBase/KeysCollection
  System.Collections.Specialized.NameValueCollection
  System.Collections.Specialized.StringDictionary
  System.Collections.Stack
  System.ComponentModel.AddingNewEventArgs
  System.ComponentModel.AddingNewEventHandler
  System.ComponentModel.AttributeCollection
  System.ComponentModel.BindingList`1
  System.ComponentModel.CancelEventHandler
  System.ComponentModel.CollectionChangeAction
  System.ComponentModel.CollectionChangeEventArgs
  System.ComponentModel.CollectionChangeEventHandler
  System.ComponentModel.Component
  System.ComponentModel.ComponentResourceManager
  System.ComponentModel.Container
  System.ComponentModel.DataObjectAttribute
  System.ComponentModel.DataObjectMethodAttribute
  System.ComponentModel.DataObjectMethodType
  System.ComponentModel.DesignerCategoryAttribute
  System.ComponentModel.DesignTimeVisibleAttribute
  System.ComponentModel.EventDescriptor
  System.ComponentModel.EventDescriptorCollection
  System.ComponentModel.EventHandlerList
  System.ComponentModel.IBindingList
  System.ComponentModel.IBindingListView
  System.ComponentModel.ICancelAddNew
  System.ComponentModel.ICustomTypeDescriptor
  System.ComponentModel.IDataErrorInfo
  System.ComponentModel.IListSource
  System.ComponentModel.IRaiseItemChangedEvents
  System.ComponentModel.ISupportInitialize
  System.ComponentModel.ISupportInitializeNotification
  System.ComponentModel.ITypedList
  System.ComponentModel.ListChangedEventArgs
  System.ComponentModel.ListChangedEventHandler
  System.ComponentModel.ListChangedType
  System.ComponentModel.ListSortDescription
  System.ComponentModel.ListSortDescriptionCollection
  System.ComponentModel.MarshalByValueComponent
  System.ComponentModel.MemberDescriptor
  System.ComponentModel.PropertyDescriptorCollection
  System.ComponentModel.TypeDescriptor
  System.ComponentModel.Win32Exception
  System.Diagnostics.DefaultTraceListener
  System.Diagnostics.TextWriterTraceListener
  System.Diagnostics.Trace
  System.Diagnostics.TraceListener
  System.Diagnostics.TraceListenerCollection
  System.Globalization.CultureTypes
  System.Globalization.DaylightTime
  System.IO.Compression.CompressionMode
  System.IO.Compression.DeflateStream
  System.IO.Compression.GZipStream
  System.IO.InvalidDataException
  System.MarshalByRefObject
  System.Resources.ResourceReader
  System.Security.Policy.Evidence
  System.SerializableAttribute
  System.Text.ASCIIEncoding
  System.Text.RegularExpressions.RegexRunner
  System.Text.RegularExpressions.RegexRunnerFactory
  System.Text.UTF7Encoding
  System.Threading.EventResetMode
  System.Threading.Mutex
  System.Threading.ThreadPriority
  System.TimeZone
  System.TypedReference
  System.UriHostNameType
  System.UriPartial
  System.Xml.EntityHandling
  System.Xml.Formatting
  System.Xml.IHasXmlNode
  System.Xml.Schema.IXmlSchemaInfo
  System.Xml.Schema.ValidationEventArgs
  System.Xml.Schema.ValidationEventHandler
  System.Xml.Schema.XmlAtomicValue
  System.Xml.Schema.XmlSchemaAll
  System.Xml.Schema.XmlSchemaAnnotated
  System.Xml.Schema.XmlSchemaAnnotation
  System.Xml.Schema.XmlSchemaAny
  System.Xml.Schema.XmlSchemaAnyAttribute
  System.Xml.Schema.XmlSchemaAppInfo
  System.Xml.Schema.XmlSchemaAttribute
  System.Xml.Schema.XmlSchemaAttributeGroup
  System.Xml.Schema.XmlSchemaAttributeGroupRef
  System.Xml.Schema.XmlSchemaChoice
  System.Xml.Schema.XmlSchemaCompilationSettings
  System.Xml.Schema.XmlSchemaComplexContent
  System.Xml.Schema.XmlSchemaComplexContentExtension
  System.Xml.Schema.XmlSchemaComplexContentRestriction
  System.Xml.Schema.XmlSchemaComplexType
  System.Xml.Schema.XmlSchemaContent
  System.Xml.Schema.XmlSchemaContentModel
  System.Xml.Schema.XmlSchemaContentProcessing
  System.Xml.Schema.XmlSchemaContentType
  System.Xml.Schema.XmlSchemaDatatype
  System.Xml.Schema.XmlSchemaDatatypeVariety
  System.Xml.Schema.XmlSchemaDerivationMethod
  System.Xml.Schema.XmlSchemaDocumentation
  System.Xml.Schema.XmlSchemaElement
  System.Xml.Schema.XmlSchemaEnumerationFacet
  System.Xml.Schema.XmlSchemaException
  System.Xml.Schema.XmlSchemaExternal
  System.Xml.Schema.XmlSchemaFacet
  System.Xml.Schema.XmlSchemaFractionDigitsFacet
  System.Xml.Schema.XmlSchemaGroup
  System.Xml.Schema.XmlSchemaGroupBase
  System.Xml.Schema.XmlSchemaGroupRef
  System.Xml.Schema.XmlSchemaIdentityConstraint
  System.Xml.Schema.XmlSchemaImport
  System.Xml.Schema.XmlSchemaInclude
  System.Xml.Schema.XmlSchemaInference
  System.Xml.Schema.XmlSchemaInference/InferenceOption
  System.Xml.Schema.XmlSchemaInferenceException
  System.Xml.Schema.XmlSchemaInfo
  System.Xml.Schema.XmlSchemaKey
  System.Xml.Schema.XmlSchemaKeyref
  System.Xml.Schema.XmlSchemaLengthFacet
  System.Xml.Schema.XmlSchemaMaxExclusiveFacet
  System.Xml.Schema.XmlSchemaMaxInclusiveFacet
  System.Xml.Schema.XmlSchemaMaxLengthFacet
  System.Xml.Schema.XmlSchemaMinExclusiveFacet
  System.Xml.Schema.XmlSchemaMinInclusiveFacet
  System.Xml.Schema.XmlSchemaMinLengthFacet
  System.Xml.Schema.XmlSchemaNotation
  System.Xml.Schema.XmlSchemaNumericFacet
  System.Xml.Schema.XmlSchemaObjectCollection
  System.Xml.Schema.XmlSchemaObjectEnumerator
  System.Xml.Schema.XmlSchemaObjectTable
  System.Xml.Schema.XmlSchemaParticle
  System.Xml.Schema.XmlSchemaPatternFacet
  System.Xml.Schema.XmlSchemaRedefine
  System.Xml.Schema.XmlSchemaSequence
  System.Xml.Schema.XmlSchemaSimpleContent
  System.Xml.Schema.XmlSchemaSimpleContentExtension
  System.Xml.Schema.XmlSchemaSimpleContentRestriction
  System.Xml.Schema.XmlSchemaSimpleType
  System.Xml.Schema.XmlSchemaSimpleTypeContent
  System.Xml.Schema.XmlSchemaSimpleTypeList
  System.Xml.Schema.XmlSchemaSimpleTypeRestriction
  System.Xml.Schema.XmlSchemaSimpleTypeUnion
  System.Xml.Schema.XmlSchemaTotalDigitsFacet
  System.Xml.Schema.XmlSchemaType
  System.Xml.Schema.XmlSchemaUnique
  System.Xml.Schema.XmlSchemaUse
  System.Xml.Schema.XmlSchemaValidationException
  System.Xml.Schema.XmlSchemaValidationFlags
  System.Xml.Schema.XmlSchemaValidator
  System.Xml.Schema.XmlSchemaValidity
  System.Xml.Schema.XmlSchemaWhiteSpaceFacet
  System.Xml.Schema.XmlSchemaXPath
  System.Xml.Schema.XmlValueGetter
  System.Xml.Serialization.IXmlTextParser
  System.Xml.Serialization.SoapAttributeAttribute
  System.Xml.Serialization.SoapAttributeOverrides
  System.Xml.Serialization.SoapAttributes
  System.Xml.Serialization.SoapElementAttribute
  System.Xml.Serialization.SoapEnumAttribute
  System.Xml.Serialization.SoapIgnoreAttribute
  System.Xml.Serialization.SoapIncludeAttribute
  System.Xml.Serialization.SoapReflectionImporter
  System.Xml.Serialization.SoapTypeAttribute
  System.Xml.Serialization.UnreferencedObjectEventArgs
  System.Xml.Serialization.UnreferencedObjectEventHandler
  System.Xml.Serialization.XmlAnyAttributeAttribute
  System.Xml.Serialization.XmlAttributeEventArgs
  System.Xml.Serialization.XmlAttributeEventHandler
  System.Xml.Serialization.XmlElementEventArgs
  System.Xml.Serialization.XmlElementEventHandler
  System.Xml.Serialization.XmlNodeEventArgs
  System.Xml.Serialization.XmlNodeEventHandler
  System.Xml.ValidationType
  System.Xml.WhitespaceHandling
  System.Xml.XmlAttribute
  System.Xml.XmlAttributeCollection
  System.Xml.XmlCDataSection
  System.Xml.XmlCharacterData
  System.Xml.XmlComment
  System.Xml.XmlDeclaration
  System.Xml.XmlDocument
  System.Xml.XmlDocumentFragment
  System.Xml.XmlElement
  System.Xml.XmlEntityReference
  System.Xml.XmlImplementation
  System.Xml.XmlLinkedNode
  System.Xml.XmlNamedNodeMap
  System.Xml.XmlNode
  System.Xml.XmlNodeChangedAction
  System.Xml.XmlNodeChangedEventArgs
  System.Xml.XmlNodeChangedEventHandler
  System.Xml.XmlNodeList
  System.Xml.XmlNodeOrder
  System.Xml.XmlNodeReader
  System.Xml.XmlOutputMethod
  System.Xml.XmlProcessingInstruction
  System.Xml.XmlSignificantWhitespace
  System.Xml.XmlText
  System.Xml.XmlTextReader
  System.Xml.XmlTextWriter
  System.Xml.XmlUrlResolver
  System.Xml.XmlWhitespace
  System.Xml.XPath.XPathException
  System.Xml.XPath.XPathItem
  System.Xml.Xsl.XsltException
</pre>
<h3>System types <strong>added</strong> to the Xbox 360 Compact Framework</h3>
<p>These are types which did <strong>not</strong> exist in the Compact Framework for the Xbox 360, in the &#8220;XNA Game Studio&#8221; v3.1 release. But these are now present in the new v4.0 release:</p>
<pre>
  Microsoft.Win32.SafeHandles.SafeHandleMinusOneIsInvalid
  Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
  Microsoft.Win32.SafeHandles.SafeWaitHandle
  Microsoft.Xna.Framework.Audio.AudioChannels
  Microsoft.Xna.Framework.Audio.DynamicSoundEffectInstance
  Microsoft.Xna.Framework.Audio.Microphone
  Microsoft.Xna.Framework.Audio.MicrophoneState
  Microsoft.Xna.Framework.Audio.NoMicrophoneConnectedException
  Microsoft.Xna.Framework.Color
  Microsoft.Xna.Framework.DisplayOrientation
  Microsoft.Xna.Framework.GamerServices.Achievement
  Microsoft.Xna.Framework.GamerServices.AchievementCollection
  Microsoft.Xna.Framework.GamerServices.AvatarRendererState
  Microsoft.Xna.Framework.GamerServices.GameUpdateRequiredException
  Microsoft.Xna.Framework.GamerServices.IAvatarAnimation
  Microsoft.Xna.Framework.GamerServices.InviteAcceptedEventArgs
  Microsoft.Xna.Framework.GamerServices.LeaderboardEntry
  Microsoft.Xna.Framework.GamerServices.LeaderboardIdentity
  Microsoft.Xna.Framework.GamerServices.LeaderboardKey
  Microsoft.Xna.Framework.GamerServices.LeaderboardOutcome
  Microsoft.Xna.Framework.GamerServices.LeaderboardReader
  Microsoft.Xna.Framework.GamerServices.LeaderboardWriter
  Microsoft.Xna.Framework.GamerServices.NetworkException
  Microsoft.Xna.Framework.GamerServices.NetworkNotAvailableException
  Microsoft.Xna.Framework.GamerServices.PropertyDictionary
  Microsoft.Xna.Framework.Graphics.AlphaTestEffect
  Microsoft.Xna.Framework.Graphics.BlendState
  Microsoft.Xna.Framework.Graphics.DepthStencilState
  Microsoft.Xna.Framework.Graphics.DirectionalLight
  Microsoft.Xna.Framework.Graphics.DualTextureEffect
  Microsoft.Xna.Framework.Graphics.EffectMaterial
  Microsoft.Xna.Framework.Graphics.EnvironmentMapEffect
  Microsoft.Xna.Framework.Graphics.GraphicsProfile
  Microsoft.Xna.Framework.Graphics.IEffectFog
  Microsoft.Xna.Framework.Graphics.IEffectLights
  Microsoft.Xna.Framework.Graphics.IEffectMatrices
  Microsoft.Xna.Framework.Graphics.IVertexType
  Microsoft.Xna.Framework.Graphics.NoSuitableGraphicsDeviceException
  Microsoft.Xna.Framework.Graphics.PackedVector.Bgra4444
  Microsoft.Xna.Framework.Graphics.RasterizerState
  Microsoft.Xna.Framework.Graphics.RenderTargetBinding
  Microsoft.Xna.Framework.Graphics.SkinnedEffect
  Microsoft.Xna.Framework.Graphics.VertexBufferBinding
  Microsoft.Xna.Framework.LaunchParameters
  Microsoft.Xna.Framework.Net.WriteLeaderboardsEventArgs
  Microsoft.Xna.Framework.TitleContainer
  System.AccessViolationException
  System.AppDomainManager
  System.AppDomainSetup
  System.ComponentModel.AsyncOperation
  System.ComponentModel.AsyncOperationManager
  System.ComponentModel.BackgroundWorker
  System.ComponentModel.CategoryAttribute
  System.ComponentModel.ComponentCollection
  System.ComponentModel.DescriptionAttribute
  System.ComponentModel.DoWorkEventArgs
  System.ComponentModel.DoWorkEventHandler
  System.ComponentModel.ITypeDescriptorContext
  System.ComponentModel.ProgressChangedEventArgs
  System.ComponentModel.ProgressChangedEventHandler
  System.ComponentModel.ReadOnlyAttribute
  System.ComponentModel.RunWorkerCompletedEventArgs
  System.ComponentModel.RunWorkerCompletedEventHandler
  System.ComponentModel.TypeConverterAttribute
  System.ContextStaticAttribute
  System.DataMisalignedException
  System.DateTimeOffset
  System.Diagnostics.DebuggerBrowsableAttribute
  System.Diagnostics.DebuggerBrowsableState
  System.Diagnostics.DebuggerDisplayAttribute
  System.Diagnostics.DebuggerTypeProxyAttribute
  System.Diagnostics.StackFrame
  System.Diagnostics.StackTrace
  System.DllNotFoundException
  System.Environment/SpecialFolder
  System.ExecutionEngineException
  System.FieldAccessException
  System.FileStyleUriParser
  System.FtpStyleUriParser
  System.GenericUriParser
  System.GenericUriParserOptions
  System.Globalization.HebrewCalendar
  System.Globalization.HijriCalendar
  System.Globalization.UmAlQuraCalendar
  System.HttpStyleUriParser
  System.InvalidTimeZoneException
  System.IO.FileLoadException
  System.IO.IsolatedStorage.IsolatedStorageException
  System.IO.IsolatedStorage.IsolatedStorageFile
  System.IO.IsolatedStorage.IsolatedStorageFileStream
  System.IO.UnmanagedMemoryStream
  System.LoaderOptimization
  System.MissingFieldException
  System.NotFiniteNumberException
  System.Reflection.AssemblyFileVersionAttribute
  System.Reflection.GenericParameterAttributes
  System.Reflection.InterfaceMapping
  System.Reflection.IReflect
  System.Reflection.LocalVariableInfo
  System.Reflection.MemberFilter
  System.Reflection.ReflectionTypeLoadException
  System.Reflection.ResourceAttributes
  System.Reflection.TargetException
  System.Reflection.TypeDelegator
  System.ResolveEventArgs
  System.ResolveEventHandler
  System.Resources.UltimateResourceFallbackLocation
  System.Runtime.CompilerServices.CompilationRelaxations
  System.Runtime.CompilerServices.CompilationRelaxationsAttribute
  System.Runtime.CompilerServices.RuntimeCompatibilityAttribute
  System.Runtime.InteropServices.AllowReversePInvokeCallsAttribute
  System.Runtime.InteropServices.ClassInterfaceAttribute
  System.Runtime.InteropServices.ClassInterfaceType
  System.Runtime.InteropServices.CoClassAttribute
  System.Runtime.InteropServices.ComDefaultInterfaceAttribute
  System.Runtime.InteropServices.COMException
  System.Runtime.InteropServices.ComImportAttribute
  System.Runtime.InteropServices.ComInterfaceType
  System.Runtime.InteropServices.DispIdAttribute
  System.Runtime.InteropServices.InterfaceTypeAttribute
  System.Runtime.InteropServices.SafeHandle
  System.Runtime.Serialization.OnDeserializedAttribute
  System.Runtime.Serialization.OnDeserializingAttribute
  System.Runtime.Serialization.OnSerializedAttribute
  System.Runtime.Serialization.OnSerializingAttribute
  System.Runtime.Serialization.StreamingContext
  System.Runtime.Serialization.StreamingContextStates
  System.Runtime.Versioning.TargetFrameworkAttribute
  System.RuntimeArgumentHandle
  System.Security.Permissions.CodeAccessSecurityAttribute
  System.Security.Permissions.SecurityAttribute
  System.Security.Permissions.SecurityPermissionAttribute
  System.Security.Permissions.SecurityPermissionFlag
  System.Security.Principal.IIdentity
  System.Security.Principal.IPrincipal
  System.Security.SecurityCriticalAttribute
  System.Security.SecuritySafeCriticalAttribute
  System.Security.SecurityState
  System.Security.SecurityTransparentAttribute
  System.Security.UnverifiableCodeAttribute
  System.ServiceModel.XmlSerializerFormatAttribute
  System.StringSplitOptions
  System.Text.DecoderFallbackException
  System.Text.EncoderFallbackException
  System.Threading.IOCompletionCallback
  System.Threading.NativeOverlapped
  System.Threading.Overlapped
  System.Threading.ParameterizedThreadStart
  System.Threading.RegisteredWaitHandle
  System.Threading.SendOrPostCallback
  System.Threading.SynchronizationContext
  System.Threading.SynchronizationLockException
  System.Threading.ThreadStartException
  System.Threading.ThreadState
  System.Threading.WaitOrTimerCallback
  System.ThreadStaticAttribute
  System.TimeZoneInfo
  System.TypeInitializationException
  System.UriBuilder
  System.UriIdnScope
  System.UriParser
  System.UriTypeConverter
  System.Xml.DtdProcessing
  System.Xml.Linq.ReaderOptions
  System.Xml.NamespaceHandling
  System.Xml.Serialization.XmlMappingAccess
</pre>
<h3>Notables?</h3>
<p>A number of deprecated collections are no longer available, the classic &#8220;ArrayList&#8221; from C# 1.0 among several others. Most of these would cause big performance problems with the Xbox garbage collector, so makes total sense that they have been trimmed out.</p>
<p>Additions which piqued my interest included <strong>&#8220;DebuggerDisplayAttribute&#8221;</strong>, and <strong>&#8220;StackTrace&#8221;/ &#8220;StackFrame&#8221;</strong>. The former I have a vague recollection trying to use before, it helps <a href="http://msdn.microsoft.com/en-us/library/x810d419.aspx" target="_blank">nicely format how a type is viewed in the Debugger</a>. You can achieve the same functionality with ToString(), but if you need to use ToString() for runtime purposes and want something different shown in the debugger, it&#8217;s useful. &#8220;StackTrace&#8221; I was interested in because I believe the crash handler I&#8217;d written had a slightly different pathway between 360 and Windows. For 360 I had to throw an exception, and handle it. In the exception handling code I could pull out the callstack. With the StackTrace class you can just grab the callstack right off in the crash handler.</p>
<p><strong>&#8220;System.Threading.ThreadState&#8221;</strong> too, I think I&#8217;d had to do a different workaround for the Xbox in the past. Nice to see that it&#8217;s now available. </p>
<p>Strangely I noticed <strong>&#8220;System.LocalDataStoreSlot&#8221;</strong> is not included in my removal list. Not sure why this is the case. Maybe I missed some key parameter in &#8216;ildasm&#8217;?</p>
<h3>The Zune, or Windows 7 Phone?</h3>
<p>Sorry, but I haven&#8217;t been developing for those platforms. Given some comments about the v4.0 release wanting to &#8216;standardize&#8217; the Compact Framework to some kind of &#8220;Silverlight&#8221; API-set, I&#8217;d imagine the ones I&#8217;ve mentioned were added will probably exist for these platforms too. No idea though whether all the removed types I list apply to the Zune, many may not have even existed in the first place.</p>
<p>Er&#8230; So yeah, this is just covering the Xbox. Your mileage may vary with the other platforms.</p>
<p><b>Edit: Ah, Zune <a href="http://news.softpedia.com/news/XNA-Game-Studio-4-0-Not-for-Zune-HD-Just-Windows-Xbox-360-and-Windows-Phone-7-136999.shtml" target="_blank">isn&#8217;t even supported</a> by XNA 4.0!</b></p>
<h3>References</h3>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/2weec7k5.aspx" target="_blank">MSDN: Differences Between the .NET Compact Framework and the .NET Framework</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/bb203915.aspx" target="_blank">MSDN: Namespaces, Types, and Members in the .NET Compact Framework for Xbox 360</a></li>
<li><a href="http://forums.create.msdn.com/forums/p/60727/373621.aspx" target="_blank">Forums: XNA 4.0 RTM &#8211; Xbox Project &#8211; Serializable doesnt work</a></li>
<li><a href="http://forums.create.msdn.com/forums/p/62420/383733.aspx" target="_blank">Forums: XNA 4.0 .Net reference version for XBox</a></li>
<li><a href="http://forums.create.msdn.com/forums/p/66363/406010.aspx" target="_blank">Forums: Thread.Priority property deprecated on 360/XNA 4.0?</a></li>
<li><a href="http://blogs.msdn.com/b/shawnhar/archive/2010/03/16/breaking-changes-in-xna-game-studio-4-0.aspx?PageIndex=3" target="_blank">Shawn&#8217;s Blog: Breaking changes in XNA Game Studio 4.0</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.gavpugh.com/2010/11/23/xnac-changes-in-the-xbox-360-compact-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

