<?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"
	>

<channel>
	<title>Scientific Ninja</title>
	<atom:link href="http://scientificninja.com/feed" rel="self" type="application/rss+xml" />
	<link>http://scientificninja.com</link>
	<description></description>
	<pubDate>Wed, 02 Jul 2008 05:30:05 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5</generator>
	<language>en</language>
			<item>
		<title>PSPCLR: Implementing newobj</title>
		<link>http://scientificninja.com/development/pspclr-implementing-newobj</link>
		<comments>http://scientificninja.com/development/pspclr-implementing-newobj#comments</comments>
		<pubDate>Sun, 22 Jun 2008 23:59:54 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://scientificninja.com/?p=45</guid>
		<description><![CDATA[PSPCLR just recently turned five bits old. The commit that brought the repository revision to 16 was actually pretty large, in terms of files touched, but most of the changes are actually just a result of some fairly heavy refactoring I&#8217;ve been doing slowly over the last few weeks. In particular,

I got rid of the [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://pspclr.googlecode.com">PSPCLR</a> just recently turned five bits old. The commit that brought the repository revision to 16 was <a href="http://code.google.com/p/pspclr/source/detail?r=16">actually pretty large</a>, in terms of files touched, but most of the changes are actually just a result of some fairly heavy refactoring I&#8217;ve been doing slowly over the last few weeks. In particular,</p>
<ul>
<li>I got rid of the TableTool and replaced it with a real MSBuild task. I also added a task for generated opcode-related boilderplate and dispatch functions, to further decrease the amount of effort involved in implementin a new opcode in the interpreter.</li>
<li>I reorganized the project files somewhat, in particular splitting the build process projects into a <code>PspClr.Prerequisite.sln</code> and leaving the actual loader, corelib implementation, et cetera in <code>PspClr.Product.sln</code>. The motivation behind this change was to work around the assembly unload limitation that makes developing MSBuild tasks in the same solution file you call them from a painful experience.</li>
<li>I streamlined a lot of the metadata handling, especially as relates to runtime representations of the metadata &#8212; there is an actual object model that wraps the metadata row, making them much easier to work with in code.</li>
</ul>
<p>After all of that, however, the basically functionality remains about the same as last time. With one small addition: <tt>newobj</tt>.</p>
<h3>&#8220;4.21 newobj - create a new object&#8221;</h3>
<p><tt>newobj</tt> causes the CLR to create a new instance of either a reference or value type. Since nearly everything you&#8217;d ever want to work with is such an instance, it&#8217;s a fairly critical opcode to support. The only reason I was able to get away without it so far is that the assembly entry point method is static, as is <tt>System.Console.WriteLine</tt>.</p>
<p><tt>newobj</tt> is very straightforward: it&#8217;s a single-byte instruction followed by a four-byte argument, which is a metadata token (essentially an encoded index) that refers to the constructor to invoke on the created object. The reference can be to the method definition metadata or the member reference metadata table &#8212; the former is for methods that exist in the same assembly, the latter for references outside the assembly. I&#8217;m only going to discuss the former, as the process for resolving the latter is essentially the same but with the extra layer of indirection of finding the assembly in your dependency list first.</p>
<p>When you encounter a <code>newobj</code> call, that constuctor method definition is all you have available. It looks like this:</p>
<ul>
<li>A four-byte address to the start of the method&#8217;s CIL opcode stream.</li>
<li>Four bytes of flags.</li>
<li>An index into the string heap, which provides the method&#8217;s name (&#8221;<code>.ctor</code>&#8221; for constructors).</li>
<li>An index into the blob heap, which provides the method&#8217;s signature.</li>
<li>An index into another metadata table which defines the parameters of the method.</li>
</ul>
<p>Does it look like there&#8217;s anything missing? At first glance, there doesn&#8217;t appear to be any information about the type that owns the method &#8212; without knowing the type, you can&#8217;t know the size of an instance of that type, which means you can&#8217;t create that instance, which means you cannot call the constructor since it wouldn&#8217;t have anything to initialize.</p>
<p>You might try looking in the parameter list or in the signature in the blob heap to try and extract the information about the owning type, but that would not be a fruitful search. The existence of the <code>this</code> parameter is encoded with a flag, not a full parameter entry (in the interests of saving space). No, to find out who owns a method, you have to look through the <em>type list</em> until you find a type that has the desired method.</p>
<p>This isn&#8217;t as bad as it might seem at first glance &#8212; the metadata that defines a type contains an index to the first method definition for that type, and you are guaranteed that all method definitions are owned by at most a single type and that all definitions belong to a given type are contiguous in the method definition table. This makes it pretty easy to associate methods with a type &#8212; the fields of a type are stored in the same fashion, and you need to process them to create the in-memory layout for the type anyway (since you need to know how many bytes an instance of the type occupies). This is what spurred me to create a more robust object model for the runtime representations of all this metadata that the execution engine consumes.</p>
<p>At assembly load time, I iterate the type definition metadata, and produce a <code>TypeDef</code> object for each entry, which I store in the assembly. Creating a <code>TypeDef</code> object iterates the subsection of the method and field metadata tables that are owned by that type and creates <code>MethodDef</code> and <code>FieldDef</code> objects which are stored in the <code>TypeDef</code>. Methods and fields are imbued with a reference back to their owning <code>TypeDef</code>, which allows me to make the mapping between method and owning type O(1) at the expense of a small amount of storage.</p>
<p>With that object model in place, it becomes possible to implement <code>newobj</code>. Read the method reference argument, and find the appropriate <code>MethodDef</code> object (this is an O(1) lookup in an array stored in the assembly). Get the <code>TypeDef</code> for the <code>MethodDef</code> (another constant time lookup), and allocate enough space for that type on the heap. Then call the constructor.</p>
<h3>The Horizon: <code>ldfld</code> and <code>stfld</code></h3>
<p><code>newobj</code> and its supporting code changes are a pretty decent step forward for PSPCLR, but I&#8217;m still a long ways away from something useful. Next on my plate are the opcodes for loading and storing object fields &#8212; these are used when, for example, you read or write from members. Since constructors do this often, they make for a logical next step.</p>
]]></content:encoded>
			<wfw:commentRss>http://scientificninja.com/development/pspclr-implementing-newobj/feed</wfw:commentRss>
		</item>
		<item>
		<title>Developer-Player Communication, Part II</title>
		<link>http://scientificninja.com/industry/developer-player-communication-part-ii</link>
		<comments>http://scientificninja.com/industry/developer-player-communication-part-ii#comments</comments>
		<pubDate>Fri, 20 Jun 2008 05:36:40 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Industry]]></category>

		<guid isPermaLink="false">http://scientificninja.com/?p=43</guid>
		<description><![CDATA[The flow of information between developers and players &#8212; and in general the entire interaction between those two groups &#8212; is an aspect of the game development process that tends to be an afterthought. In some cases, the concept is entirely ignored. In my last post I hilighted three reasons why this may be the [...]]]></description>
			<content:encoded><![CDATA[<p>The flow of information between developers and players &#8212; and in general the <em>entire</em> interaction between those two groups &#8212; is an aspect of the game development process that tends to be an afterthought. In some cases, the concept is entirely ignored. In my last post I <a href="http://scientificninja.com/industry/developer-player-communication-part-i">hilighted three reasons why this may be the case</a>, along with some justifications. At the end of the post I admitted to playing devil&#8217;s advocate and that I didn&#8217;t really agree with the majority of those justifications, in general. Today&#8217;s post expands upon what exactly I find troublesome about those three points.</p>
<h3>Cost and Benefit — Is There an Audience?</h3>
<p>The gist of this point was that given that the majority of players are not versed in the specific technical domains that are involved in the process of developing a game, the size of the audience for &#8220;techy&#8221; updates is potentially rather small. Perhaps the audience is so small, in fact, that it&#8217;s not worth the productivity hit required to get the information out of the programmer&#8217;s brain and in to a tangible, presentable form.</p>
<p>The thing is, technical information does not have to be presented in its natural state. I&#8217;m not talking about posting your Perforce check-in logs on a website, here. I&#8217;m talking about communicating the progress of the technical aspect of the game, in consumer-friendly form. This isn&#8217;t impossible &#8212; it&#8217;s not neccessarily easy, though. It involves employing communications skills that are not neccessarily all that common among programmers. In particular, it calls for the ability to distill a technical factoid or event into bite-size chunks that can be digested by somebody with much less technical know-how. Usually this requires a fair command of metaphor and other literary or educational devices &#8212; which makes sense, because teaching is essentially what&#8217;s going on here. You will likely observe that team members who have had experience (successfully) teaching classes, speaking at conferences, and so on will likely be better people to solicit for input to a devblog.</p>
<p>The fact that what you&#8217;re essentially doing here is <em>teaching</em> your players a little about the technical magic behind the curtains is important. This is a <em>good</em> thing. The player base, as a whole, tends to get their impression of the inner workings of game development from the gaming media. But let us not kid ourselves here &#8212; the gaming press really doesn&#8217;t have a clue what&#8217;s going on, either. Is it really better for us to be letting <em>them</em> set the stage for what our industry is like? I think not.</p>
<p>Talking to the players about appropriately distilled technical progress helps improve their overall understanding of the industry. If you do it right, and maintain a spin on the presentation that focuses on the cool things the tech may enable players to see when the game ships, you can cultivate a much more trusting and pleasant relationship with your eventual playerbase &#8212; and you get a bit of a marketing push out of it, as well. Despite the fact that you&#8217;re releasing information to a wide audience, players will still get a kick out of the fact that you&#8217;re sharing &#8220;insider secrets&#8221; with them. However, this brings us to another issue.</p>
<h3>Management of Expectations</h3>
<p>If you recall, I described expectation management as the desire to limit discussion about things that might be in the game because of the possibility that those things might be cut and that players would thusly feel &#8216;cheated&#8217; of features. Of the three excuses I discussed last time, I think that this one is the most prevalent in the real world. I only mention it second because I think that a significant root cause is the aforementioned lack of real understanding on the part of the players.</p>
<p>Features get cut for lots of reasons, but almost all of those reasons boil down to a cost/benefit ratio that is not in the developer&#8217;s favor, or because they sounded cool on paper but when implemented turned out bland or tedious. This is generally a good thing for the overall health of the product &#8212; but it isn&#8217;t always seen that way by the players. Doing more to educate and inform players about the state of the game as it develops would help alleviate the misconceptions that they commonly have about whether a feature was cut for compelling technical or fun-factor reasons.</p>
<p>I think the advantages weigh in more heavily here: talking about some aspects of gameplay can stimulate discussion among the fans and make them feel more like they&#8217;re a part of the process, <em>even if</em> things only end up turning out the way they want through pure coincidence. </p>
<p>I think that it can be <a href="http://www.codinghorror.com/blog/archives/000840.html">harmful to keep information privatized</a>. Certainly some information should be, but that sort of stuff tends to be the exception rather than the rule, I think. Tranparency and openness on a topic is an <a href="http://blog.jonudell.net/2007/04/10/too-busy-to-blog-count-your-keystrokes/">investment</a> of the time and brainpower you devote to that topic, in this modern age. We&#8217;ve taken steps in the right direction with <a href="http://www.gdconf.com/">GDC</a> and other trade shows (and to some degree, with the abolition of the farce that was the old E3), but we can do better.</p>
<p>If players become better educated about what making games is really about, maybe they won&#8217;t feel quite as put-out when the game shapes up to be different upon release from what it was during the early days. What&#8217;s the worst that could <em>really</em> happen anyway? We&#8217;d be in the same position we are now, which isn&#8217;t exactly a huge risk to be taking.</p>
<h3>Publisher Mandate</h3>
<p>Publishers are generally the controlling entity in the development process: they supply the money to the developer, persuant to the developer meeting certain milestones and following certain rules. So it&#8217;s entirely concievable that a publisher might want to curtail any unnecessary discussion of any ongoing projects. </p>
<p>On this point, I&#8217;m not sure what to say &#8212; &#8220;find a better publisher,&#8221; isn&#8217;t exactly a real-world option. Fortunately, I&#8217;m not entirely convinced this is an excuse that one hears all that often &#8212; I&#8217;ve heard far more stories about publishers signing off on the release of blatantly poor-quality information (screenshots with clear animation or art asset bugs, for example) than I have stories about publishers issuing gag orders on contractually obligated studios. </p>
<h3>The End</h3>
<p>In the end, it&#8217;s obviously going to be impossible to make everybody happy, and no matter how much, or how well, you communicate with your players there will always be those players who disagree with your choices no matter how rational or necessary those choices were from your perspective. To the player, if it sounded cool and you didn&#8217;t do it, that&#8217;s usually bad.</p>
<p>But being more outgoing and chatty has advantages for both parties involved; our historical tendency to keep our lips sealed has not been to our advantage. I&#8217;m glad to see a trend towards honest rapport between developers and players emerging, and I hope it continues.</p>
]]></content:encoded>
			<wfw:commentRss>http://scientificninja.com/industry/developer-player-communication-part-ii/feed</wfw:commentRss>
		</item>
		<item>
		<title>Developer-Player Communication, Part I</title>
		<link>http://scientificninja.com/industry/developer-player-communication-part-i</link>
		<comments>http://scientificninja.com/industry/developer-player-communication-part-i#comments</comments>
		<pubDate>Fri, 30 May 2008 00:49:05 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Industry]]></category>

		<guid isPermaLink="false">http://scientificninja.com/?p=42</guid>
		<description><![CDATA[Why are some studios open and eager to talk about their upcoming projects, and others notoriously close-mouthed about the same subject? Talking about what&#8217;s in the pipeline can have a beneficial on the community surrounding a studio and a particular game, which can be a useful thing to build up during the run-up to the [...]]]></description>
			<content:encoded><![CDATA[<p>Why are some studios open and eager to talk about their upcoming projects, and others notoriously close-mouthed about the same subject? Talking about what&#8217;s in the pipeline can have a beneficial on the community surrounding a studio and a particular game, which can be a useful thing to build up during the run-up to the game&#8217;s ship date. <em>Not</em> talking can tend to irk fans, who may not have a particularly clear picture of how the game development process works and may not find the developers&#8217; explainations concerning their reticence particularly suitable. On the surface it looks like discussing the development process with fans has the clear advantage. So why is it so uncommon?</p>
<p>Not surprisingly, there&#8217;s often a fairly strong correlation between candor and size. Small companies tend to be less formal in their operation, and the sorts of communication we&#8217;re talking about here is generally considered somewhat informal in nature. Of course there are exceptions. <a href="http://spiderwebsoftware.com/">Spiderweb Software</a> is a three-man shop that produces little in the way of development-related updates beyond &#8220;we&#8217;re working on X,&#8221; &#8220;almost done X,&#8221; and &#8220;X is out, we&#8217;re moving on to Y.&#8221; </p>
<p>Bungie is one of my favorite examples; back when they were working on Marathon they were active on AOL and Usenet groups. During the development of Halo, Matt Soell would produce <a href="http://halo.bungie.org/haloupdates/">weekly developer updates</a> filled with all manner of interesting tidbits (they continued this tradition after Halo as well, but over time their community interaction has lost the style that attracted me to it originally).</p>
<p>Some other developer logs I recall fondly are those from Ambrosia projects, particularly <a href="http://www.ambrosiasw.com/forums/index.php?showtopic=34316">Escape Velocity: Nova</a> and its <a href="http://www.ambrosiasw.com/forums/index.php?showtopic=34315">Windows port</a>, and the <a href="http://www.ambrosiasw.com/forums/index.php?showtopic=112570">port of Aquaria</a>.</p>
<p>If you follow a few of those links and browse around, you&#8217;ll get a feeling for the specific type of communication I&#8217;m talking about here: discussion about the actual day-to-day process of crafting the game, venting about bugs and nerdy programmer anecdotes included. I&#8217;m not talking about more generalized community interaction concerning non-development issues &#8212; while that&#8217;s certainly an important aspect of overall relationship between development studio and players, it&#8217;s not my area expertise and I won&#8217;t comment on it too extensively, lest I look the fool.</p>
<p>With that context established, let&#8217;s consider some of the more popular reasons you don&#8217;t see more, larger, development studios actively producing developer blogs.</p>
<h3>Cost and Benefit &#8212; Is There an Audience?</h3>
<p>Producing content for public consumption involves human effort; real bodies, in real chairs, doing real writing and editing. Furthermore, although perhaps less true for smaller studios, larger companies have a certain level of professionalism they would presumably like to maintain. Part of that maintainence is making sure anything that is written as Official Company Word employs proper grammar and punctuation, doesn&#8217;t leak important trade secrets, doesn&#8217;t slander another developer &#8212; basically, make sure things look like they were written by somebody who knows what they&#8217;re doing, instead of some programmer who fancies himself a writer but who can&#8217;t even spell &#8220;maintenance.&#8221;</p>
<p>That editing, fact-checking, content review, and so on all take time out of somebody&#8217;s work day, and when you look at the bottom line you have to wonder if the returns justify the cost &#8212; that&#8217;s anybody&#8217;s guess when you&#8217;re talking about actual <i>developer log</i>-style (that is, containing some measure of technical nitty-gritty) content. Not everybody finds technical content interesting; if I had to guess I&#8217;d think that those people are the clear minority (compare the original EV Nova log, for example, to the Windows port version &#8212; the former is by and large a running checklist of &#8217;stuff we checked in to the repository&#8217; while the latter has actual narrative content with a wider appeal). Of course, you can blunt the edges of the technical mumbo-jumbo to some degree, and include commentary on other, more widely-palatable issues. Once again, Soell&#8217;s Halo updates did this really well. In fact, transforming some of the technical details about that sweet database voodoo you implemented last Thursday that makes your asset pre-build stage run twice as fast into layman&#8217;s terms can be an exciting challenge for some, and artists and designers usually enjoy taking time off from real work to stage a sexy screenshot to show off some new feature that just got added to the build.</p>
<p>But again, you ramp up the effort you put into wrangling content for your developer updates, you ramp up cost, and draw resources away from actually making the game &#8212; the real, important goal. It can escalate to the point where your team is in a mini &#8220;E3 crunch&#8221; every few weeks. The benefits in community engagement you might get back in return for that aren&#8217;t always tangible or measurable, which makes for risk &#8212; in some cases, enough risk that company&#8217;s simply adopt a blanket &#8220;we&#8217;ll talk when we&#8217;re done, thanks,&#8221; policy and forget about it.</p>
<h3>Management of Expectations</h3>
<p>People become attached easily, and often to surprisingly minor things. Everybody is different, everybody finds enjoyment in different things in a game. Most of us have an armchair game designer floating around in our soggy little brains, too, which always complicates things. My point here is that it&#8217;s often very difficult to get rid of some aspect of gameplay, even a minor one, once you&#8217;ve mentioned it. </p>
<p>Remember Guild Halls in Diablo 2? The fourth race in Rise of Legends? The deep, adaptive, immersive AI in Black and White or Oblivion? All of these were talked about, or even hyped in some cases, pre-release but vanished with barely a trace by the time the games hit shelves. The fan backlash didn&#8217;t kill the games, but a good deal of players had chips on their shoulders for some time, and blamed the developers for what they saw as an injustice. The damage wasn&#8217;t done to the games&#8217; sell-through numbers, but to the atmosphere of those games&#8217; communities, and community improvement is ostensibly what the whole developer-player communication thing is about, no?</p>
<p>It&#8217;s a fair assumption that the majority of players are non-technical (that is, they aren&#8217;t software developers themselves). It can be difficult to convince these people that cutting a feature was justified in terms of development cost, or because it wasn&#8217;t turning out to be fun. In the former case, the players tend to lack the technical acumen to grasp a completely literal explaination of the rationale, and/or such an explaination may require more background about the development history of the related aspects of the project than the studio may be willing to reveal. In the latter case, the players will have their own versions of the cut feature in their mind, almost certainly disconnected from the reality of how the feature feels in the context of the rest of the game, and can sometimes have a hard time looking past what&#8217;s in their own heads.</p>
<p>Because of this, it&#8217;s common for studios to err on the side of releasing <em>less</em> information because it doesn&#8217;t create expectations among the fan base that may be unrealistic. There&#8217;s also some measure of surprise when the game ships with a bunch of cool features nobody knew about, which can be a plus.</p>
<h3>Publisher Mandate</h3>
<p>There are a lot of studios that are owned by a publisher, and most of the rest are developing games on some other publisher&#8217;s dime via contract. Those sorts of relationships generally afford the publisher a certain measure of control over the developer, control which can manifest itself as an enforced &#8220;don&#8217;t talk about Project X,&#8221; policy.</p>
<p>Publishers, being beasts of an altogether different nature, are generally concerned more with the business ramifications (such as the effect on stock prices) that talking about projects in development have. In the interests of controlling the release of information they may deem related to some corporate strategy (investing in new intellectual property, entering into negotions to secure a license to some existing intellectual property, diversifying platforms, et cetera) or trade secret, publishers might choose to have the developer filter all related informational releases through them first, or simply ban them outright. </p>
<p>I&#8217;ve never personally been in a situation where I&#8217;ve observed this happen, as far as I know (I&#8217;m generally not involved in the details of the relationship between the studio where I work and its publisher), and I&#8217;m glad. It&#8217;s an extremely heavy-handed tactic, in my opinion, and it&#8217;s unfortunate that it happens at all.</p>
<h3>On Balance</h3>
<p>There are opposing points to be made here &#8212; I should note that I&#8217;m primarily playing devil&#8217;s advocate with this article; while I understand where studios are coming from with the above arguments, I don&#8217;t neccessarily agree with them. Next time I&#8217;ll talk about exactly how I disagree, and what I think can be done to improve things.</p>
]]></content:encoded>
			<wfw:commentRss>http://scientificninja.com/industry/developer-player-communication-part-i/feed</wfw:commentRss>
		</item>
		<item>
		<title>Choosing Tools</title>
		<link>http://scientificninja.com/advice/choosing-tools</link>
		<comments>http://scientificninja.com/advice/choosing-tools#comments</comments>
		<pubDate>Thu, 15 May 2008 04:07:32 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Advice]]></category>

		<guid isPermaLink="false">http://scientificninja.com/?p=35</guid>
		<description><![CDATA[So, you want to be like the professional game developers, do you? You&#8217;re a hot-shot hobby game developer with a great idea for the world&#8217;s next killer MMO, and to make damn sure you build the best game you can you want to make damn sure you use the best tools available. Engines, IDEs, 3D [...]]]></description>
			<content:encoded><![CDATA[<p>So, you want to be like the professional game developers, do you? You&#8217;re a hot-shot hobby game developer with a great idea for the world&#8217;s next killer MMO, and to make damn sure you build the best game you can you want to make damn sure you use the best tools available. Engines, IDEs, 3D modelling tools, audio mixers, composition software, version control and project management suites, content creation programs &#8212; you want to use the best of the best.</p>
<p>Well, that&#8217;s a waste of your time &#8212; and in many cases, a waste of quite a lot of your money, too.</p>
<p>Amateur game developers often have this sort of hero-worship attitude towards professional developers, their tools, and their products. But as I&#8217;ve touched on before, that&#8217;s not neccessarily a very productive stance to take. When it comes to tools in particular, reasoning behind the argument tends to be one of</p>
<ul>
<li>you&#8217;re considering a career in the industry and want to learn the &#8220;correct&#8221; tools, or</li>
<li>you want to use &#8220;the tools&#8221; that professionals use because you believe it will give what you produce with those tools an edge over what you might produce with some other tool.
</ul>
<p>Both of these are bad reasons.</p>
<h3>Argument The First</h3>
<p>Consider the first argument. This is the stance that <a href="http://youtube.com/watch?v=UJ-QSJmEgHU">shady trade schools</a> would like you to take, because it&#8217;s the based on the same core principle that they usually base their <a href="http://scientificninja.com/advice/on-game-schools">(usually rather weak) curriculum</a> on. That is, the idea that game development is a tool-centric process that requires particular applications of specific tools and technology. The idea that there is, for any given problem domain for which a tool can be constructed (such as creating 3D models, or building game levels), a single tool that is the &#8216;best&#8217; tool for that job. The One True Tool that all game developers are using for that task.</p>
<p>Now, <em>if</em> that assumption were true, there might be a valid argument there. But it&#8217;s not true. There is no such thing as the &#8216;best&#8217; tool for a given problem (in general); while there are usually a handful of apps that are considered to be <em>among</em> the best, each of these will have strengths and weaknesses that need to be considered. </p>
<p>This is important: the criteria professionals use to evaluate tools are very different from the criteria you should use. The tools that do get used by professionals are a result of a selection process based on that criteria, so it should be clear that you, using a different set of criteria, may arrive at a different ideal tool. As for what your criteria should be? I can&#8217;t tell you &#8212; every problem is different, and you know yours the best. The only advice I can reasonably offer you is to try to get the biggest bang (in terms of increase in your productivity) for your buck.</p>
<h3>Argument The Second</h3>
<p>The second argument is built around an assumption that is similar to the first. Where the first assumption was that the craft requires the crafter to employ specific tools, the second assumption is that the tools imbue the crafter with the ability to perform the craft. This is equally false; the tools don&#8217;t make the games. Sure, <a href="http://usa.autodesk.com/adsk/servlet/index?id=7635018&#038;siteID=123112">Maya</a> provides orders of magnitude more features, controls, and options than <a href="http://chumbalum.swissquake.ch/">Milkshape 3D</a> does &#8212; but those features don&#8217;t do anything without the artists skillful hands at the controls.</p>
<p>The skill that artist has is a core talent that comes from an understanding of the process of 3D modelling that is fundamental and application-agnostic. The understanding of how muscles interact with the skeletal structure of a bipedal humanoid to shape its movement, and how that interaction can be extroplated to create natural looking motion on a more bizzare, six-legged alien form &#8212; that doesn&#8217;t come from knowing where the Create Biped button is in the UI of a specific tool.</p>
<p>You can pick up a lot of the basic, fundamental important bits of working with a specific genre of tools by using free and/or inexpensive tools in that genre. Those skills will carry over as you migrate to other tools, even those big-name brands that you see advertised in your latest issue of <em><a href="http://www.gdmag.com">Game Developer</a></em>. In some cases you may even be able to produce more content at higher quality with simple tools, especially if you&#8217;re new to working with that specific type of content. Often the complexity of heavy-duty tools can be overwhelming.</p>
<h3>Takeaway</h3>
<p>What you should take away from this post is quite simple: you don&#8217;t need to emulate a professional game development studio, not in general, and not in terms of tool selection. Your goal is to make a killer game, right? Then focus on making a killer game. If you&#8217;re able to make your game without additional tools now, great, keep doing that. If you think you need to start using some external tools, grab some evaluation copies and give them a spin. If you can&#8217;t get an eval copy of something that you know (or think) professionals use, don&#8217;t sweat it &#8212; I assure you there is an alternative.</p>
<p>Above all, a tool is supposed to optimize the development process in some way, and this should be among your key requirements (and one of the only ones I can recommend in general, as I noted earlier). In order to be useful, a tool must make you more productive in some fashion. It should, ideally, do this as cheaply as possible. There are free tools out there for doing just about everything, most of which range from passable to excellent, so don&#8217;t be fooled into thinking that a $2,000 price tag is really getting you something. </p>
<p>Now, all of that said, you can usually get your hands on lightweight versions of some of the so-called &#8216;industry-standard&#8217; tools for free. Microsoft publishes <a href="http://www.microsoft.com/express/">Express editions of Visual Studio</a>, Softimage offers a <a href="http://www.softimage.com/products/modtool/">&#8216;mod tool&#8217; version of XSI</a>, for example. As long as these tools meet your requirements, and you can work them competently, there&#8217;s no real reason not to use them. But if they <em>don&#8217;t</em> meet your requirements or you <em>can&#8217;t</em> work them well enough to be productive, don&#8217;t use them just because they&#8217;re what you heard <code>[insert game studio here] </code>used to make <code>[insert popular title here]</code>.</p>
<p>You&#8217;re not in Rome, so who cares what the Romans are doing?</p>
]]></content:encoded>
			<wfw:commentRss>http://scientificninja.com/advice/choosing-tools/feed</wfw:commentRss>
		</item>
		<item>
		<title>Using XSLT to Generate Code</title>
		<link>http://scientificninja.com/development/using-xslt-to-generate-code</link>
		<comments>http://scientificninja.com/development/using-xslt-to-generate-code#comments</comments>
		<pubDate>Wed, 09 Apr 2008 03:44:18 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://scientificninja.com/development/using-xslt-to-generate-code</guid>
		<description><![CDATA[The last time I talked about XSLT was quite a while ago. I was using XSLT to generate wiki markup for both my personal projects and for SlimDX. It&#8217;s worth noting that we have abandoned the wiki markup documentation in SlimDX, however &#8212; it didn&#8217;t look or operate as nice as we would have liked, [...]]]></description>
			<content:encoded><![CDATA[<p>The last time I talked about XSLT was quite a while ago. I was <a href="http://scientificninja.com/development/using-xslt-to-create-wiki-markup">using XSLT to generate wiki markup</a> for both my personal projects and for SlimDX. It&#8217;s worth noting that we have abandoned the wiki markup documentation in SlimDX, however &#8212; it didn&#8217;t look or operate as nice as we would have liked, and it wasn&#8217;t available offline. Anyway, this weekend I felt like exploring the technology a little more, so I decided to see if I could craft an XSL transformation that would produce (well formatted!) C# code for an object model described by XML. </p>
<p>I already have a custom tool called <code>transformadf.exe</code> to do this. It reads <code>.adf</code> files (which describe the physical structure of in-game assets used by my code) and produces some C# source files containing the asset class and some supporting machinery. The .NET XPath query library is used to build an in-memory description of the structure from the <code>.adf</code> file, and then produces the code files based that structure and heavy use of <code>StringBuilder</code>. There are two things I don&#8217;t like about this approach:</p>
<ul>
<li>Modifying the resulting code is difficult. The boilerplate portions of the code, the &#8220;template&#8221; if you will, are all contained in string literals scattered around the file. Some characters need escaping, and a particular set of simple rules need to be obeyed with respect to line endings (not Unix / DOS / Mac, but rather whether or not you end the line via <code>StringBuilder.AppendLine</code>, or just use the <code>StringBuilder.Append</code> method, which will not include the newline). Making changes to the template is more cumbersome than it should be.</li>
<li><code>transformadf.exe</code> is part of the build process for the framework code itself (because the framework includes standard asset types), <em>and</em> the build process for the framework&#8217;s client games. The other tools in the framework are used only by the client games. This makes <code>transformadf.exe</code> unique within the framework&#8217;s build system, as it can&#8217;t use the standard set of prebuild/postbuild actions (since it&#8217;s part of those actions).</li>
</ul>
<h3>Back Into the Breach</h3>
<p>I had not really done anything with XSLT since the last time I wrote about it, so I suffered through a few false starts before I ended up with something that wasn&#8217;t entirely embarrassing. The two things I took away from this study session with the language were the <code>ancestor</code> selection axis and the <code>mode</code> attribute on templates.</p>
<h3>The <code>ancestor</code> Axis</h3>
<p>XSLT uses XPath to query for (&#8221;select&#8221;) nodes in the XML hierarchy to operate on. Part of that selection process is the notion of the axis along which you are performing the selection &#8212; you can think of this axis as a direction, but I found it easier (although less intuitive, initially) to think of the axis as specifying the set from which you will select. The default selection axis, if you don&#8217;t specify one, is the <code>child</code> axis. To specify an axis other than the default, you use the syntax <code>axis::expr</code>, where <code>axis</code> is the axis specifier and <code>expr</code> is an XPath expression. </p>
<p>The <code>ancestor</code> axis is the set of nodes between the document root and the current context node, but <em>not</em> the context node itself (use <code>ancestor-or-self</code> for that). It&#8217;s important to note that the resulting set of nodes selected from this axis is organized in <em>document order</em>: matching nodes closer to the document root appear first. This is why I suggested thinking of the axis as a set rather than a direction, since &#8220;direction&#8221; and &#8220;ancestor&#8221; put me in the mind of traversing the node tree backwards, &#8220;towards&#8221; the ancestors, and thus returning the nodes closes to the context node first. Until I shifted gears, I kept making stupid mistakes in my <code>xsl:for-each</code> operations. </p>
<h3>The <code>mode</code> Attribute</h3>
<p>For every asset description, I generate three C# class: the asset class itself, a marshaller class that handles lifetime and serialization tasks, and a reference class that allows the asset to be pointed to by other assets (and allows the asset wrangling subsystem to ensure all dependent assets are automatically loaded, if desired). This requires three passes through the source XML. My original strategy was to copy the source tree into three variables, renaming the root of each tree. Then I applied templates to each tree in turn, and the templates themselves matched nodes that were descendants of specific named roots (using the XPath selection <code>named-root//node-name</code>). </p>
<p>This let me have a template for matching <code>marshaller-class//field</code> that was different from <code>asset-class//field</code>; desirable, since I needed to do entirely different things to process fields in each of the three classes. It worked, but it felt clunky and ugly &#8212; and it was. While researching some other aspect of XSLT that had slipped my mind, I stumbled across the <code>mode</code> attribute that can be applied to templates and the <code>apply-template</code> element that allows for exactly this kind of filtering <em>without</em> the bloated triple copying of the source tree.</p>
<p>It&#8217;s quite simple: an XSL template can be given a named <code>mode</code>, and will only match when templates are being applied in that mode. Now I can simply write the appropriate templates and mark them with an appropriate mode, and <code>apply-templates</code> three times &#8212; it is <em>much</em> cleaner to look at.</p>
<h3>Results</h3>
<p>In the end, deciding whether or not to use XSLT or my hand-rolled tool was very much a &#8220;six of one, half-dozen of the other,&#8221; kind of decision. The XSLT worked, and worked well. The time I spent struggling with new parts of the language (or those I&#8217;d forgotten) was about equal to the time I spent writing the generator initially. Maintaining the generator has been expensive, but I suspect maintaining the XSLT will be equally so. I didn&#8217;t gain a lot in terms of template code expressibility in XSL, either &#8212; that is to say, it&#8217;s nearly as difficult to write or maintain the non-generated boilerplate portions of the code in XSL as it was with <code>transformadf.exe</code>. The difficult is simply elsewhere (in particular, in coping with whitespace so that the generated code is at least passably <em>clean</em>).</p>
<p>While I haven&#8217;t made up my mind completely, I&#8217;m leaning towards continuing to use the XSLT. For the most part things stay roughly the same, but it <em>does</em> provide a solution to my second problem, that of <code>transformadf.exe</code> being a special-case project. We&#8217;ll see what happens.</p>
]]></content:encoded>
			<wfw:commentRss>http://scientificninja.com/development/using-xslt-to-generate-code/feed</wfw:commentRss>
		</item>
		<item>
		<title>COM and SlimDX, Part II</title>
		<link>http://scientificninja.com/development/com-and-slimdx-part-ii</link>
		<comments>http://scientificninja.com/development/com-and-slimdx-part-ii#comments</comments>
		<pubDate>Mon, 17 Mar 2008 01:05:08 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://scientificninja.com/development/com-and-slimdx-part-ii</guid>
		<description><![CDATA[Earlier, in &#8220;COM and SlimDX, Part I,&#8221; I discussed an early design decision that was made in SlimDX that prevented us from supporting the idiomatic C# pattern for disposal of unmanaged resources. In closing, I mentioned that our new solution, while a huge leap forward, still had some problems.
Today we&#8217;ll discuss them.
SlimDX supports the ability [...]]]></description>
			<content:encoded><![CDATA[<p>Earlier, in <a href="http://scientificninja.com/development/com-and-slimdx-part-i">&#8220;COM and SlimDX, Part I,&#8221;</a> I discussed an early design decision that was made in SlimDX that prevented us from supporting the idiomatic C# pattern for disposal of unmanaged resources. In closing, I mentioned that our new solution, while a huge leap forward, still had some problems.</p>
<p>Today we&#8217;ll discuss them.</p>
<p>SlimDX supports the ability to share &#8212; in a sense &#8212; the native objects of other APIs using <code><a href="http://msdn2.microsoft.com/en-us/library/system.intptr(VS.71).aspx">System.IntPtr</a></code>, an opaque managed representation of a pointer or handle. All SlimDX COM objects expose their native pointer as an <code>IntPtr</code>. They can also be constructed from <code>IntPtr</code>s.</p>
<p>With the old SlimDX design, we only ran into two serious issues with this process. The first was that since <code>IntPtr</code>s are entirely opaque, we&#8217;d more-or-less trust the user to construct the correct type and pass the correct pointer. Sure, we performed a <code>QueryInterface()</code>, but that may not have been the best idea in retrospect &#8212; there are known scenarios (for example, see <a href="http://forums.xna.com/thread/28827.aspx">here</a> and <a href="http://www.gamedev.net/community/forums/topic.asp?topic_id=457958">here</a>) where DirectX objects don&#8217;t behave the way you might expect a COM interface to behave &#8212; and so our code might have occasionally failed in situations it should not have.</p>
<p>The second issue was that we used these <code>IntPtr</code> constructors internally, occasionally in scenarios where it was impractical to know the proper type to construct. Remember the <code>GetDevice</code> example from last time? In Direct3D10, there&#8217;s a similar method for resource views (<a href="http://msdn2.microsoft.com/en-us/library/bb173877(VS.85).aspx">GetResource()</a>) that is used to get a pointer to the resource that the view object is looking at. The method is a member of the <a href="http://msdn2.microsoft.com/en-us/library/bb173876(VS.85).aspx">ID3D10View</a> base class, so naturally we placed it in the analagous <code>SlimDX.Direct3D10.ResourceView</code> class. The implementation would have looked something like:</p>
<table>
<tr>
<td>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="c">Resource^ ResourceView::<span style="color: #202020;">GetResource</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#123;</span>
  ID3D10Resource* resource = <span style="color: #cc66cc;">0</span>;
  NativeComInterface-&gt;GetResource<span style="color: #66cc66;">&#40;</span> &amp;resource <span style="color: #66cc66;">&#41;</span>;
  <span style="color: #b1b100;">return</span> gcnew Resource<span style="color: #66cc66;">&#40;</span> IntPtr<span style="color: #66cc66;">&#40;</span> resource <span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#41;</span>; 
<span style="color: #66cc66;">&#125;</span></pre></td></tr></table></div>

</td>
<tr>
</table>
<p>The problem with this approach is that it logically &#8220;slices&#8221; the object. This is similar to <a href="http://en.wikipedia.org/wiki/Slicing">slicing in, say, C++</a> except that the underlying object is not physical destroyed, only the way you can interact with that object reference. In other words, even if the <code>ID3D10Resource*</code> returned from the native call pointed to a derived <code>ID3D10Texture2D</code>, it would be an error to downcast the managed <code>Resource</code> reference to a managed <code>Texture2D</code> reference, because we statically constructed a <code>Resource</code>, <em>not</em> a <code>Texture2D</code>. </p>
<p>A solution to this is a factory-type construction process &#8212; fortunately for us, most of the types involved here had base class methods that would indicate the actual runtime type of the object somehow &#8212; even though that would mean we&#8217;d have to push most implementation of the method lower in the class hierarchy. That was the solution we were considering, until the object table was brought up, which neatly solved the whole issue for us.</p>
<p>Almost.</p>
<p>You see, there&#8217;s one final caveat. The reason the object table eliminates the need for a factory is that it stores the native pointer as the key, and the actual runtime managed instance as the value. Thus, the aforementioned code snippet becomes a table lookup instead of a <code>gcnew</code> statement. The problem rears its ugly little head when you consider the possibility that the table lookup can <em>fail to find the key</em>. At first that might seem impossible (and thus not worth handling) because the view can&#8217;t be created with a resource, and given the existence of the object table, the only way the resource can cease to exist before the view is if the programmer intentionally disposed of it. This would be a programmer error, which is generally something we do not concern ourselves with handling gracefully (that is, we&#8217;d throw an exception indicating the programmer is a dim bulb, rather than try to bravely soldier on).</p>
<p>Unfortunately, since SlimDX can exchange native resources with other APIs via <code>IntPtr</code>, it&#8217;s possible to get into this sticky situation rather easily &#8212; simply construct a new <code>ResourceView</code> using an exposed <code>IntPtr</code>. SlimDX will correctly handle the <code>ResourceView</code>, incrementing the native reference count and placing an entry in the object table. But SlimDX won&#8217;t know about the original resource, so if you call <code>GetResource()</code> on the view, SlimDX will not find the <code>Resource</code>&#8217;s key in the table. What will happen, in that case, is that SlimDX will treat the object as a new one, increment the native reference count, and add an object table entry. This is unfortunate because the user now has to <code>Dispose()</code> of that resource, even though they didn&#8217;t explictly allocate it with new. </p>
<p>We&#8217;re currently considering this a pathological use case, and aren&#8217;t addressing the issue. Users doing that kind of advanced interop with SlimDX will simply need to be aware of the problem and the non-standard call to <code>Dispose()</code> they&#8217;ll need to make. I do believe it is a fixable issue, but the fix isn&#8217;t in the March release since it will not adversely affect the majority of our user base &#8212; you&#8217;ll have to wait for June, if we&#8217;re even able to remedy it all. In the interim, however, it&#8217;s important to be aware of the dangers that lurk in the shady corners of the API.</p>
]]></content:encoded>
			<wfw:commentRss>http://scientificninja.com/development/com-and-slimdx-part-ii/feed</wfw:commentRss>
		</item>
		<item>
		<title>C# on the PSP</title>
		<link>http://scientificninja.com/development/csharp-on-the-psp</link>
		<comments>http://scientificninja.com/development/csharp-on-the-psp#comments</comments>
		<pubDate>Sat, 08 Mar 2008 19:33:15 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://scientificninja.com/development/c-on-the-psp</guid>
		<description><![CDATA[I put some custom firmware on my PSP last week. Then I put a homebrew development environment on my PC. Then I wrote a Common Language Runtime for the PSP, and now I can run the prototypical C# Hello World program from my PSP. For the gory details, read on.
Getting the Tools
Homebrew console development is [...]]]></description>
			<content:encoded><![CDATA[<p>I put some custom firmware on my PSP last week. Then I put a homebrew development environment on my PC. Then I wrote a Common Language Runtime for the PSP, and now I can run the prototypical C# Hello World program from my PSP. For the gory details, read on.</p>
<h3>Getting the Tools</h3>
<p>Homebrew console development is typically mired in obtuse (and frequently undocumented) complexity from line zero; it&#8217;s the grim reality of working with something that is essentially a giant, constantly-evolving <em>hack</em>. When I set out to get the PSP development toolchain on to my machine, I was prepared for all sorts of mucking about with Cygwin and various other Unix tools, and I was knee deep in getting everything sorted out and configured when I stumbled across <a href="http://www.jetcube.eu/archives/2008/02/entry_71.html">this blog entry</a> by <a href="http://www.jetcube.eu/">Paulo Lopes</a> and <a href="http://forums.ps2dev.org/viewtopic.php?t=9812">this related forum thread</a>. Paulo&#8217;s SDK distribution is extremely pleasant to install, and with just one simple change (adding <code>-lstdc++</code> to the <code>LIBS</code> in the makefile) I was able to build C++ applications from within Visual Studio without any of the mess I was expecting. I haven&#8217;t had any trouble with it yet, so I highly recommend it to anybody looking to get into PSP <em>development</em> instead of PSP <em>screwing-around-with-makefiles-for-hours</em>.</p>
<h3>The Depths of the CLR</h3>
<p>Like C#, the Common Language Runtime is described in an <a href="http://www.ecma-international.org/publications/standards/Ecma-335.htm">ECMA standard</a>. Anybody looking to build themselves a CLR, or understand an existing CLR implementation, needs to have that document handy.</p>
<p>Code for the CLR is stored inside &#8220;assemblies,&#8221; which also includes resources and other modules. Assemblies are packaged up inside files in <a href="http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx">the Portable Executable format</a> (the very same format used by Windows <code>.exe</code> and <code>.dll</code> files). The PE format is well-documented and discussed at length elsewhere, so I won&#8217;t go into it too much. It&#8217;s sufficient to say that the first task for my project was to implement a PE file loader, which was a relatively straightforward task.</p>
<p>Within the PE file is the CLR metadata, which pretty much contains all the information to load and run the application. There&#8217;s a header, with the kind of information you&#8217;d expect to find in a header, and there are &#8220;heaps&#8221; of string, GUID, and binary data. The meat of the metadata, however, are the tables. The tables consist of rows of data, each row having a specific number of columns. The data in each column of a particular table is generally a fixed constant value or an index into another table or the string/GUID/binary blob heaps. Each table is identified by a eight-bit ordinal (for example, the table containing method definitions is <code>0x06</code>). Conceptually, there&#8217;s nothing too difficult here. In practice, however, there are few snags you can easily run afoul of.</p>
<h3>Table Format Woes</h3>
<p>For starters, the table columns that contain indices into other tables are not a fixed size. In the interests of saving space, all indices are two bytes in size if the table they&#8217;re indexing has less than two bytes worth of rows. Otherwise they&#8217;re four bytes. In the metadata table, you&#8217;re only given a bitfield indicating which tables exist and a series of integers specifying how many rows those tables each have. The tables are all contiguously stored in the metadata, but since the size of each table as a whole isn&#8217;t provided, you can&#8217;t just jump to any random table easily. You need to process every table definition, checking every column that&#8217;s an index against the reported size of the appropriate table, and build up a database of table row sizes at runtime. </p>
<p>The variable nature of the table sizes also means accessing them in a clean fashion is tricky, and best served by lightweight wrapper classes for each type of table row. The processing of the table definitions and implementation of the table row wrappers is rather mechanical, so it lends itself to automation by a build tool.</p>
<h3>Data Alignment</h3>
<p>On the PSP in particular, misaligned data access is a problem. The PSP&#8217;s main CPU is a MIPS chip, which has memory access alignment requirements: two-byte accesses must occur at an address divisible by two, four-byte accesses must occur at an address divisible by four, et cetera. The MIPS processor isn&#8217;t one I&#8217;m terribly familiar with; I know it has instructions supporting misaligned load/store operations, and I was able to see them generated by the compiler, but I&#8217;d still get hard crashes on the PSP when I tried to access misaligned data, so some further investigation is warranted.</p>
<p>For now, I simply use a set of wrapper routines to perform any memory IO. These routines ensure the address in question meets alignment requirements, and if it doesn&#8217;t they fetch data from the nearest aligned addresses and shift and mask the results to yeild the value I&#8217;m interested in. Misaligned access occurs quite frequently when implementing the CLR. For example, CIL opcode are a single byte, but they are occasionally followed by a four-byte argument token, which will usually be misaligned.</p>
<h3>What About Mono?</h3>
<p>The reason I embarked on this project, and in this particular fashion (rather than, say, porting <a href="http://mono-project.org">Mono</a>), was to learn more about the gritty details of the CLR. Mono&#8217;s very mature relative to my little upstart implementation, but by porting it I wouldn&#8217;t be learning as much about the CLR as I would be about Mono&#8217;s code structure and internals. I felt rather lost digging around in Mono&#8217;s code, as well, because not only did I not know their codebase, I didn&#8217;t know the domain within which their codebase was operating &#8212; and as I&#8217;ve said before, learning about that domain by <a href="http://scientificninja.com/advice/dont-read-source-code">reading their source code wouldn&#8217;t have taught me</a> as much.</p>
<p>On the other hand, while I&#8217;ve learned a lot about the CLR&#8217;s guts so far, the actual amount of PSP-specific code I&#8217;ve had to write is quite small, and other than the memory alignment crashes I haven&#8217;t run in to many problems on the PSP that didn&#8217;t also manifest themselves in my Windows build. This will likely change as I start being able to implement more and more of the standard library.</p>
<h3>Downloading the Project</h3>
<p>I have <a href="http://pspclr.googlecode.com">a Google Code page for the PSP CLR</a>, if you&#8217;d like to look around. I should warn you (if the low SVN revision numbers don&#8217;t tip you off) that this is an extremely early attempt. There are a lot of places I&#8217;m taking shortcuts, failing to check for errors, and making assumptions, and even if all of that works out, I only have support for a handful of opcodes and a single standard library function (<code>System.Console.Write(string)</code>). In other words, it doesn&#8217;t actually <em>do</em> much yet, so don&#8217;t expect too much. Nonetheless, it&#8217;s there if you want to take a look.</p>
]]></content:encoded>
			<wfw:commentRss>http://scientificninja.com/development/csharp-on-the-psp/feed</wfw:commentRss>
		</item>
		<item>
		<title>COM and SlimDX, Part I</title>
		<link>http://scientificninja.com/development/com-and-slimdx-part-i</link>
		<comments>http://scientificninja.com/development/com-and-slimdx-part-i#comments</comments>
		<pubDate>Thu, 28 Feb 2008 14:58:46 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://scientificninja.com/development/com-and-slimdx-part-i</guid>
		<description><![CDATA[The last few months have been fairly busy, and a good portion of that is due to the upcoming SlimDX March release, which we expect to package and ship shortly after the official March DirectX SDK update becomes available. Since the DirectX team changed up their release schedule, there&#8217;s been a larger-than-usual gap in between [...]]]></description>
			<content:encoded><![CDATA[<p>The last few months have been fairly busy, and a good portion of that is due to the upcoming SlimDX March release, which we expect to package and ship shortly after the official March DirectX SDK update becomes available. Since <a href="http://www.microsoft.com/downloads/details.aspx?DisplayLang=en&#038;FamilyID=529f03be-1339-48c4-bd5a-8506e5acf571#new">the DirectX team changed up their release schedule</a>, there&#8217;s been a larger-than-usual gap in between releases, and we&#8217;ve taken advantage of that extra time to make some fairly major changes to SlimDX. The <a href="http://slimdx.mdxinfo.com/wiki/index.php?title=Release_Notes">Release Notes </a>page on our wiki covers the basics, but there&#8217;s one issue of particular signifigance that I wanted to talk about in detail, since it&#8217;s important.</p>
<p>SlimDX is a managed wrapper for DirectX and other libraries. It&#8217;s written in C++/CLI, an offshoot of C++ whose niche is interoperability between managed and unmanaged code. Bridging that divide is never quite as simple as it looks, and SlimDX has certainly been no exception to that rule, even though it&#8217;s a relatively thin layer over the native APIs. One of the trickiest problems we&#8217;ve had to solve is how to to get SlimDX code to play nice on both sides of the fence: the managed side of the library needs to expose interfaces and semantics consistent with those of .NET, and the unmanaged side of the library needs to play by the COM rules that govern most of the native APIs we wrap.</p>
<p>In the COM world, the lifetime of objects are managed through reference counting. When you acquire a pointer to a COM interface, you call its <code>AddRef()</code> method, incrementing its reference count. When you&#8217;re done, you call <code>Release()</code>, which decrements the count and destroys the object if no other references exist. In languages like C++, where DirectX is most commonly used, you have rich support for <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization">the RAII pattern</a>, which leads to smart pointer implementations such as <code>CComPtr</code>.</p>
<p>But C# doesn&#8217;t support automatic, scope-based, deterministic destruction. So, while incrementing the reference count correctly is a no-brainer, correctly decrementing it when the user is done with the object is a problem. C# has finalization, which is an entirely automatic, but nondeterministic, process for cleaning up managed resources. The framework also offers the <code>IDisposable</code> pattern and an idiomatic implementation thereof, which is intended for manual cleanup of unmanaged resources the garbage collector is not aware of: file handles, GDI handles, and in our case, COM objects.</p>
<h3>Finalization and Disposal</h3>
<p>Since the COM interface represents an unmanaged resource that is beyond the control of the runtime&#8217;s garbage collector, implementing <code>IDisposable</code> is an obvious step. <a href="http://msdn2.microsoft.com/en-us/library/ms244737(VS.80).aspx">The idiom for <code>IDisposable</code> in C#</a> stipulates that a disposable object should also implement a finalizer (even though this is, strictly speaking, optional) to call <code>Dispose()</code> on the off chance the user fails to do so, ensuring that the unmanaged resources will at least get freed up <em>eventually</em> rather than leak.</p>
<p>This, however, causes trouble for SlimDX. Finalization, you see, is performed in its own thread, which means that the Direct3D runtime will emit warnings in debug mode if the underlying Direct3D device was not created with appropriate flag for enabling multithreading. Allowing those diagnostics to appear is against our design guidelines, and forcing device creation to be multithreaded is a heavy-handed and boorish solution, especially since the flag has performance implications.</p>
<p>This effectively makes finalization <em>completely</em> off-limits to SlimDX, since we can&#8217;t know at compile-time if we&#8217;re allowed to release resources from other threads. In fact, SlimDX&#8217;s finalizers do absolutely nothing.</p>
<h3>The Non-Idiomatic Solution</h3>
<p>Part of the semantics of <code>IDisposable</code> are that object creation (via <code>new</code>) and disposal should exist as a pair. Additionally, the client should only expect to have to call <code>Dispose()</code> on objects the client has explicitly created. SlimDX&#8217;s original design made that impossible; to clean up SlimDX resources correctly, you needed to call <code>Dispose()</code> on <em>every single reference</em> to an object you ever got from SlimDX.</p>
<p>Recall that in Direct3D, most resources are associated with the device object that created them, and you can at any time ask the resource to return a pointer to its device. If SlimDX implemented <code>IDisposable</code> in the traditional way, you would only need one call to <code>Dispose()</code> for the device object; ideally that call would be made from the same context that originally created the device in the first place. But, as I&#8217;ve said, SlimDX did things a bit differently &#8212; not only did you need to dispose of the original device, you also needed to dispose of the device reference given to you by the buffer&#8217;s <code>GetDevice()</code> method, <em>even though they were both references to the same object</em>. We initially chose this design because it is as similar to the <em>native</em> semantics as possible &#8212; each new reference to an object incremented the reference count, and thus required a <code>Dispose()</code> call to decrement the reference count. </p>
<p>Another annoying side-effect of this design was that SlimDX objects rarely compared equal, even if they represented the same native object. In other words, <code>foo.GetBuffer() == foo.GetBuffer()</code> was never true.</p>
<h3>A Better Way</h3>
<p>For a while, we simply lived with the strange disposal model. But as we started wrapping up open issues for the March release, it became painfully obvious we were going to have to take some drastic measures and refactor large portions of SlimDX&#8217;s internals, because the designs were making the library extremely difficult to use. </p>
<p>So, after a number of involved design discussions in #gamedev, we came up with a new design for the March release. This time around, we&#8217;d use an internal hash table to track the native objects and map them to an existing SlimDX object. When a new object is needed (for example, when <code>GetDevice()</code> is called), we first look in our hash table to see if we already know about the native object in question. If we do, we return the existing managed wrapping object, otherwise we create a new one and store the mapping in the table. </p>
<p>Additionally, we manually call <code>Release()</code> on native objects whenever the underlying DirectX API implicitly calls <code>AddRef()</code> &#8212; in effect, we ensure SlimDX&#8217;s only reference to the native object is the one stored in the hash table. You can call <code>GetDevice()</code> as many times as you like, and it will always return the same reference and the net COM reference count will remain the same after the calls as it was before. As a result, calling <code>Dispose()</code> on the object returned from <code>GetDevice()</code> is unneccessary &#8212; the only reference that needs to be disposed of is the <em>first</em>, exactly the way <code>IDisposable</code> is supposed to work.</p>
<h3>It&#8217;s Not All Perfect</h3>
<p>Unfortunately, while this new design is a huge step forward for SlimDX in terms of correctness and consistency on the managed side, there are still a handful of pitfalls. Thankfully, those pitfalls exist largely in edge cases that will affect a very small percentage of SlimDX users, as opposed to the original problem, which affected <em>every</em> SlimDX user. I&#8217;ll talk more about what those problems are next time.</p>
]]></content:encoded>
			<wfw:commentRss>http://scientificninja.com/development/com-and-slimdx-part-i/feed</wfw:commentRss>
		</item>
		<item>
		<title>Shade: Conversions</title>
		<link>http://scientificninja.com/development/shade-conversions</link>
		<comments>http://scientificninja.com/development/shade-conversions#comments</comments>
		<pubDate>Thu, 17 Jan 2008 18:23:02 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://scientificninja.com/development/shade-conversions</guid>
		<description><![CDATA[Previously, I described the type system Shade uses for connections between shader fragments. Today I&#8217;m going to discuss the process by which conversions are searched for. 
An individual conversion in Shade is a simple thing, essentially a conversion is a highly-specialized shader feature. A conversion has semantic types for input and output, as well as [...]]]></description>
			<content:encoded><![CDATA[<p>Previously, I described <a href="http://scientificninja.com/development/shade-semantic-types">the type system Shade uses </a>for connections between shader fragments. Today I&#8217;m going to discuss the process by which conversions are searched for. </p>
<p>An individual conversion in Shade is a simple thing, essentially a conversion is a highly-specialized shader feature. A conversion has semantic types for input and output, as well as a snippet of code code that will perform the conversion. Shade&#8217;s conversion search routine takes a source and target parameter, and returns a list of conversions and an integer representing the &#8220;difficulty&#8221; of the conversion. Difficulty is a heuristic. The only values with a concrete meaning are 0 (the types match exactly) and <code>int.MaxValue</code> (the conversion is impossible). Beyond that, difficulty is only useful as a relative measure &#8212; lower, of course, being better.</p>
<p>In order for a conversion to be possible at all, the source type must contain <em>at least</em> all of the trait names as the target type (but the values can, of course, be different). Conversions may not add new traits to a type, they can only change or remove them. So, for example, it is possible to convert from <code>type:float4,basis:model</code> to <code>type:float4,basis:view</code>. It is possible to convert from <code>type:float3,use:normal,basis:clip</code> to <code>type:float3,basis:world</code> (discarding the <code>use</code> trait in the process). However, it is <em>not</em> possible to convert from <code>type:float3</code> to <code>type:float2,basis:view</code> (without information about the basis the vector originates in, there&#8217;s no sane way to bring it into a defined basis). This relationship is referred to as the compatibility of the two types, and it is not a transitive relationship. It&#8217;s also not a boolean relationship - types that have more traits in common are more compatible (<code>type:float4,basis:world</code> is more compatible with <code>type:float4,basis:clip</code> than it is with just <code>type:float4</code>. <code>type:float4</code>, however, is not compatible at all with <code>type:float4,basis:world</code>).</p>
<p>The traits that exist on both the source and the target, but whose values differ, are known as the &#8220;candidate traits.&#8221; The psuedo-type that is defined by the candidate traits is checked against every conversion available to Shade. Any conversion with an input that is compatible with the source type is a potential addition to the final result set. For every potential conversion found, a temporary type is created that represents the type of the original source parameter after application of the conversion, and the conversion search routine is repeated recursively using this new parameter as the source. The stopping case is when the source and target parameters are the same (success) or no acceptable conversions exist (failure). The child conversion with the lowest difficulty is selected as the result, and returned. </p>
<p>One thorny issue is that conversions discard any trait the source has that the target lacks. This is undesirable, because it means that the deeper the graph, the more likely you are to lose a lot of the useful semantic information that improves the stability and utility of the tool. One direction I plan on exploring in the future is modifying the conversion search so that such traits are simply propagated through unchanged, to prevent this problem from occuring.</p>
]]></content:encoded>
			<wfw:commentRss>http://scientificninja.com/development/shade-conversions/feed</wfw:commentRss>
		</item>
		<item>
		<title>Shade: Semantic Types</title>
		<link>http://scientificninja.com/development/shade-semantic-types</link>
		<comments>http://scientificninja.com/development/shade-semantic-types#comments</comments>
		<pubDate>Mon, 14 Jan 2008 14:13:54 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://scientificninja.com/development/shade-semantic-types</guid>
		<description><![CDATA[Recall that when you work with Shade, you&#8217;re basically just dropping little nodes on a layout surface. Each node represents some kind of effect feature you&#8217;d like your finalized shader to exhibit, and each node has a number of input and output parameters you can connect to form a graph that defines relationships and dependancies [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://scientificninja.com/development/shade-basic-concepts">Recall</a> that when you work with Shade, you&#8217;re basically just dropping little nodes on a layout surface. Each node represents some kind of effect feature you&#8217;d like your finalized shader to exhibit, and each node has a number of input and output parameters you can connect to form a graph that defines relationships and dependancies between feature fragments.</p>
<p>Shade produces HLSL code when compiling a shader graph. Like most languages, HLSL&#8217;s type system is &#8220;simple&#8221; in the sense that it is only concerned with the <em>fundamental type</em> of a variable &#8212; this is perfectly acceptable for programming. Shade, however, requires more information to achieve its goals.</p>
<p>Take a look at the closeup of the example shader graph from the last article, below. The skinning node produces a &#8220;normal&#8221; output, containing the skinned normal. The diffuse lighting node expects a &#8220;normal&#8221; input so that it can perform the standard <em>n-dot-l</em> diffuse lighting calculation. Each shader feature is written in isolation, and generally has to make some assumptions about inputs. For example, this particular diffuse lighting feature assumes the input normal vector is in world space, because the shader global containing the light vector happens to be in world space. It would really clutter the UI to include all those assumptions on the display, and more importantly it would be exceedingly counterproductive for Shade to require the user to manually place little feature nodes to perform the appropriate conversions between coordinate spaces.</p>
<p><img class="leftbox" src="http://scientificninja.com/files/blog/shade-semantic-types-closeup.png" alt="Shade graph detail"/></p>
<p>Fortunately, by adding additional information to the parameter types, we can have Shade inject those conversions automatically. This is the basis of Shade&#8217;s semantic type system. A semantic type is just a collection of name/value pairs called &#8220;traits&#8221; that describe contextual features of the type. The only trait that is required is that describing the fundamental type. Additional traits are optional, but more information is generally better (especially when finding conversions is concerned, as will be addressed in a later article). For example, the semantic type of the skinned normal is <code>type:float3,use:normal,basis:model,range:unit</code>. The input to the diffuse lighting feature is <code>type:float3,use:normal,basis:view</code>.</p>
<p>Imbuing the parameters with this extra information requires some additional effort on the part of the programmer crafting shader features, but the result is a more reliable interface for the artist building effects with those features since there is more information for the compiler to work with &#8212; it can perform more comprehensive sanity checks and automatic boilerplate. Without the extra semantic information, Shade could still generate HLSL that was correct and compiled. After all, the fundamental types of both parameters are the same &#8212; <code>float3</code>. But the extra information allows Shade to better understand the contexts in which the parameters exist, and makes it possible to ensure the values passed through those variables are put in the proper contexts before they are used.</p>
<p>The end result is a system that is both safer and easier to use, allowing more errors to be detected while at the same time keeping the graph uncluttered and not bogging the artist down with grunt work. Although the example shader I&#8217;m presenting here is quite simple and contains fairly low-level features, the ultimate goal of the tool is to have a system that involves <em>fewer</em> feature nodes (as a result, the feature nodes will be higher-level in nature). Part of that motivation is because this kind of visual pseudo-programming can become unmanageable quickly as the number of features increases; the semantic typing system allows for a great deal of clutter to be removed.</p>
<p>Next time, I&#8217;ll take a look at how Shade actually searches for and applies conversions between semantic types.</p>
]]></content:encoded>
			<wfw:commentRss>http://scientificninja.com/development/shade-semantic-types/feed</wfw:commentRss>
		</item>
	</channel>
</rss>
