<?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>Paradice Software &#187; Code</title>
	<atom:link href="http://www.paradicesoftware.com/blog/index.php/tag/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.paradicesoftware.com/blog</link>
	<description>Developing a role-playing game since 1981</description>
	<lastBuildDate>Tue, 22 Jun 2010 08:23:04 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>3rd Party Code</title>
		<link>http://www.paradicesoftware.com/blog/index.php/2010/03/3rd-party-code/</link>
		<comments>http://www.paradicesoftware.com/blog/index.php/2010/03/3rd-party-code/#comments</comments>
		<pubDate>Sat, 06 Mar 2010 22:46:42 +0000</pubDate>
		<dc:creator>Lawrence</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Good coding guidelines]]></category>
		<category><![CDATA[3rd party]]></category>
		<category><![CDATA[libraries]]></category>

		<guid isPermaLink="false">http://www.paradicesoftware.com/blog/?p=203</guid>
		<description><![CDATA[As a general rule, I like to write all of the code used by my games/programs myself. Not because I think I am the best programmer in the world, but because &#8211; for me &#8211; one of the main reasons I program is to learn more about how software functions on the very lowest levels, [...]]]></description>
			<content:encoded><![CDATA[<p>As a general rule, I like to write all of the code used by my games/programs myself. Not because I think I am the best programmer in the world, but because &#8211; for me &#8211; one of the main reasons I program is to learn more about how software functions on the very lowest levels, and if I used extensive 3rd party code (like Unreal Engine for my game, for example) a lot of that stuff that I *want* to learn about would be abstracted away, or worse: still present but obscured and intermingled with the 3rd party code itself.</p>
<p>Coincidentally, this is the same reason I don&#8217;t use managed languages like C#. I quite like knowing about things that managed code wants to hide! The increase in development time is not that important to me, I have no external deadlines to meet.</p>
<p>However, there are points beyond which it&#8217;s not practical for me to write the code myself, because it&#8217;s either A) incredibly complex, B) boring, C) proprietary, or D) so ubiquitous that it really doesn&#8217;t need reinventing. e.g.: writing code to decode an MP3 file into raw audio. I could *potentially* do this, but as it belongs to all four categories, I&#8217;m really comfortable with not doing it myself!</p>
<p>Currently in my Freepascal development I am using three 3rd Party Code libraries every day. And they are all excellent, both in terms of features and being easy enough that I can &#8216;plug them in&#8217; to my own lx7 game engine with very little work. Here they are:</p>
<h3>DirectX &#8211; by Clootie</h3>
<p>No, not DirectX itself (that deserves a whole separate subject!), but a port of all the headers/structures/glue code necessary to use DirectX in Freepascal. This gives me low level access to every function and interface used by DirectX itself, and the port is so perfect I was able to build my own graphics engine on top of Direct3D just by studying the (C++) DirectX SDK. Nothing is missing! Everything works! You probably won&#8217;t appreciate how rare this is if you normally use C++.<br />
<a href="http://www.clootie.ru/">http://www.clootie.ru/</a></p>
<h3>BASSfpc</h3>
<p>BASS is an Audio Library that makes it *dead easy* to play sound and music files of many different types. BASSfpc is the FPC port of this. BASS handles MP3s, WAVs, OGGs, and about a million other sound types, and it does it efficiently and with the bare minimum of code needed (literally about 4 lines of code to init the library and start playing an MP3!).<br />
<a href="http://www.un4seen.com/">http://www.un4seen.com/</a></p>
<h3>LNet</h3>
<p>The newest addition to my Libs folder. LNet provides a set of classes to implement networking, at the very lowest level, without adding any additional features or complexity. That&#8217;s exactly what I needed, because I want to add my own features and complexity! There are many many network libraries out there, but (for Freepascal at least) LNet definately gets my vote, for being simple, class-based, and extremely elegant.<br />
<a href="http://lnet.wordpress.com/">http://lnet.wordpress.com/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.paradicesoftware.com/blog/index.php/2010/03/3rd-party-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Icefall UI Evolution</title>
		<link>http://www.paradicesoftware.com/blog/index.php/2009/11/icefall-ui-evolution/</link>
		<comments>http://www.paradicesoftware.com/blog/index.php/2009/11/icefall-ui-evolution/#comments</comments>
		<pubDate>Fri, 20 Nov 2009 23:25:57 +0000</pubDate>
		<dc:creator>Lawrence</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Icefall]]></category>
		<category><![CDATA[Decision]]></category>

		<guid isPermaLink="false">http://www.paradicesoftware.com/blog/?p=170</guid>
		<description><![CDATA[Taking a break from coding topics, today&#8217;s post explores how Icefall&#8217;s dialog User Interface (UI) has evolved over the course of it&#8217;s development. My automatic-backup tool keeps every version of Icefall available, so I fired up a few old versions and took some screenshots to illustrate the process.
Original Design

This screenshot is actually from the realtime Icefall [...]]]></description>
			<content:encoded><![CDATA[<p>Taking a break from coding topics, today&#8217;s post explores how Icefall&#8217;s dialog User Interface (UI) has evolved over the course of it&#8217;s development. My automatic-backup tool keeps every version of Icefall available, so I fired up a few old versions and took some screenshots to illustrate the process.</p>
<h3>Original Design</h3>
<p><img class="aligncenter size-medium wp-image-166" title="UI Dialog: Original" src="http://www.paradicesoftware.com/blog/wp-content/uploads/2009/11/Stage1-300x239.jpg" alt="UI Dialog: Original" width="300" height="239" /></p>
<p>This screenshot is actually from the realtime Icefall prototype. I needed a quick way to change screen resolutions for testing, so this is it. Some interesting features: The green background would slowly sway while the dialog was open, and there was a shimmering gold border around whichever element had keyboard focus.</p>
<h3>Revision</h3>
<p><img class="aligncenter size-medium wp-image-167" title="Icefall: Revision" src="http://www.paradicesoftware.com/blog/wp-content/uploads/2009/11/Stage2-300x266.jpg" alt="Icefall: Revision" width="300" height="266" /></p>
<p>Fast forward to the turn-based rewrite of Icefall, and this is the original Video Options dialog. Some big changes: the background texture is more subdued, there is a panel on the left to select what <strong>type </strong>of options to view, and the gold-edge focus indicator has gone (now, the focused element is just highlighted a little more). Buttons and checkboxes have also had a minor makeover, e.g. the buttons are now rounded.</p>
<h3>Revision 2</h3>
<p><img class="aligncenter size-medium wp-image-168" title="UI Dialog: Revision 2" src="http://www.paradicesoftware.com/blog/wp-content/uploads/2009/11/Stage3-300x248.jpg" alt="UI Dialog: Revision 2" width="300" height="248" /></p>
<p>What changed here? The window frame! Gone is the &#8216;rusted steel&#8217; frame from the top and bottom of the window, replaced with an ice-blue frame that encloses all four sides. I wanted to get more &#8220;ice theme&#8221; into the UI for the game, and at the same time I needed a UI frame that covered the left and right too, because not all UI elements use the slate background (the spellbook, for example, uses a &#8216;book&#8217; background, and it looked a little strange with no enclosing frame). I also think this looks better than the previous one.</p>
<h3>Current Design</h3>
<p><img class="aligncenter size-medium wp-image-169" title="UI Design: Final" src="http://www.paradicesoftware.com/blog/wp-content/uploads/2009/11/Stage4-300x248.jpg" alt="UI Design: Final" width="300" height="248" /></p>
<p>Good, the rate-of-change of the dialog is slowing down, which means we&#8217;re getting closer to completion! The only change here is to the background of the listbox. The &#8216;green waves&#8217; looked ok in the original version, but as the look and feel of the rest of the dialog evolved, it began to look more and more out of place. When the dialog frames turned ice-blue, it was a good opportunity to build on that existing colourspace and again lend more of an &#8216;icey&#8217; theme to things by using a dark, ice-blue texture. This is what this dialog looks like in current builds. Hopefully, you agree with me that it&#8217;s the best looking of them all?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.paradicesoftware.com/blog/index.php/2009/11/icefall-ui-evolution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>More Textures than Memory</title>
		<link>http://www.paradicesoftware.com/blog/index.php/2009/11/more-textures-than-memory/</link>
		<comments>http://www.paradicesoftware.com/blog/index.php/2009/11/more-textures-than-memory/#comments</comments>
		<pubDate>Wed, 18 Nov 2009 05:10:19 +0000</pubDate>
		<dc:creator>Lawrence</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Good coding guidelines]]></category>
		<category><![CDATA[Icefall]]></category>
		<category><![CDATA[DirectX]]></category>
		<category><![CDATA[Freepascal]]></category>

		<guid isPermaLink="false">http://www.paradicesoftware.com/blog/?p=155</guid>
		<description><![CDATA[Icefall uses literally dozens of textures&#8230; (and it will probably be &#8216;hundreds&#8217; by the time the game is completed).
Textures are used for everything, from the mouse cursor, menus, fonts, buttons, to the game world itself, spells/action icons, monsters, equipment&#8230; everything.
Although my own main PC has 512MB of video (texture) RAM, not everyone does! And
following on [...]]]></description>
			<content:encoded><![CDATA[<p>Icefall uses literally dozens of textures&#8230; (and it will probably be &#8216;hundreds&#8217; by the time the game is completed).</p>
<p>Textures are used for everything, from the mouse cursor, menus, fonts, buttons, to the game world itself, spells/action icons, monsters, equipment&#8230; everything.</p>
<p>Although my own main PC has 512MB of video (texture) RAM, not everyone does! And<br />
following on from my <a href="http://www.paradicesoftware.com/blog/index.php/2009/11/minimum-requirements/">minimum requirements</a> post, I don&#8217;t really want someone&#8217;s video card memory size to be a limiting factor if everything else meets the requirements, so Icefall needs a way to manage things when there are more textures than there is video memory.</p>
<p>I don&#8217;t want each bit of code that uses textures to worry about whether they&#8217;re loaded or not, so the logical choice is to encapsulate all of the texture handling into one place: I call the class that handles this the <em>TContentManager</em> (&#8221;content&#8221; because it also handles sounds, fonts, music, etc.).</p>
<p>When the game code asks the <em>TContentManager</em> for a texture: the first thing it does is look to see if that texture is already available in video memory: if so, it just hands out a reference. Easy! If not, it retrieves the filename for that texture from Icefall&#8217;s <em>ResourceDatabase</em>, and attempts to load the texture from disk. If that fails, it looks at <strong>why</strong> it failed: if it&#8217;s <em>D3DERR_OUTOFVIDEOMEMORY</em>, the next step is to unload some other texture and try again, repeating until the load succeeds or we have no loaded textures left. (If it still doesn&#8217;t load, or if the texture load fails for some other reason, it&#8217;s goodbye Icefall).</p>
<p>Programmatically:</p>
<blockquote><pre>
function TContentManager.GetTexture(ID: TTextureID): TLXTexture;
var
   HRes: HRESULT;
   NewTexture: TLXTexture;
   FileName: String;
begin
   if TextureLoaded(ID) then
      exit(Texture[ID]);

   FileName := ResourceManager.Textures[ID].FileName;
   repeat
      HRes := LXLoadTexture(FileName,NewTexture);
      case HRes of
         D3D_OK:
            Texture[ID] := NewTexture;
         D3DERR_OUTOFVIDEOMEMORY:
            UnloadTexture(0);
      else
         // Fatal error!
      end;
   until TextureLoaded(ID);
   result := Texture[ID];
end function;
</pre>
</blockquote>
<p><em>UnloadTexture</em> is a method that unloads a texture. It takes a <em>TTextureID</em> as a parameter, but passing 0 in this case tells the method we want it to choose a texture to unload itself. This is where it gets interesting.</p>
<p>Before I got to this, I originally had set up a few states so that they explicitly called <em>TContentManager.UnloadTexture</em> to release textures when the game left that state (e.g. the game would unload the &#8216;Option-selection&#8217; texture when the player closed the Options dialog). However, this turned out to be sub-optimal for several reasons:</p>
<ul>
<li>Players might well leave and re-enter states (like Options) several times to accomplish whatever it is they&#8217;re trying to do.</li>
<li>It doesn&#8217;t make use of extra video memory: it keeps loading from disk (or the disk-cache anyway) while the extra video memory stays idle.</li>
<li>I had to explicitly declare what textures I was done with. Not a problem really but &#8216;just another thing&#8217; that I had to do when changing states.</li>
</ul>
<p>So now I no longer explicitly release anything. <em>UnloadTexture</em> always chooses the texture to unload that was least-recently used (a linked list makes this a very fast and efficient check &#8211; no timers or array scanning involved). In practise &#8220;least recently used&#8221; turns out to be about 97% optimal (when simulated against a 100% optimal algorithm which is permitted to see the future when deciding what to unload) so it&#8217;s virtually perfect &#8211; substantially better than my explicit declarations were. </p>
<p>If for some crazy reason the user doesn&#8217;t want Icefall consuming all of their video RAM*, I can chuck in a call to <em>IDirect3DDevice9.GetAvailableTextureMem</em> and trigger <em>UnloadTexture</em> if it&#8217;s below some specific amount. Alternatively, I could keep a sum of the amount of texture memory I&#8217;m using, and trigger <em>UnloadTexture</em> if that amount threatens to exceed 32MB or whatever (I haven&#8217;t decided yet).</p>
<p>The point is, if you find yourself manually balancing resources, it&#8217;s probably an excellent idea to profile your resource usage and see if you can find a pattern that will let you just automate the whole thing**. You&#8217;ll save yourself much time and your code will be cleaner and more flexible.</p>
<p>*Note: this only actually matters on Vista or Windows 7. Under the Windows XP model, multiple applications can&#8217;t share texture memory anyway. As soon as an application takes focus, DirectX invalidates all texture resources belonging to everything else (forcing them to reload from system-memory or disk when they get restored). The WDDM (Windows Display Driver Model) in Vista &#8220;understands&#8221; video memory, and can share it amongst applications. This is one of the reasons DirectX 10+ can&#8217;t be backported to XP: XP has no concept of video card resources.</p>
<p>**If you&#8217;re creating a game frame-rate locked or just frame-rate dependent, you might still need to explicitly acquire and release resources (e.g. between levels), because a 10ms pause at an unexpected point in your game could be noticeable or detrimental. Either that, or move the resource acquistion to another thread and have low-quality &#8216;emergency&#8217; textures to display while the real ones load&#8230; this is a very common technique for FPS games. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.paradicesoftware.com/blog/index.php/2009/11/more-textures-than-memory/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scary Windows development stories</title>
		<link>http://www.paradicesoftware.com/blog/index.php/2009/11/scary-windows-development-stories/</link>
		<comments>http://www.paradicesoftware.com/blog/index.php/2009/11/scary-windows-development-stories/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 08:44:20 +0000</pubDate>
		<dc:creator>Lawrence</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Good coding guidelines]]></category>
		<category><![CDATA[Taxes]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.paradicesoftware.com/blog/?p=148</guid>
		<description><![CDATA[I&#8217;m currently reading a book about the evolution of Windows. One of the most interesting things I keep finding is how stupid some 3rd party application developers must have been&#8230;. for example, it seems to have been common practice that if you wanted your app to grab a particular Windows setting (let&#8217;s say the Fonts [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m currently reading a book about the evolution of Windows. One of the most interesting things I keep finding is how stupid some 3rd party application developers must have been&#8230;. for example, it seems to have been common practice that if you wanted your app to grab a particular Windows setting (let&#8217;s say the Fonts directory), instead of a quick MSDN search, which turns up both the <em>SHGetFolderPath</em> and <em>SHGetKnownFolderPath</em> functions (either of which is exactly what you want), these programmers fired up RegEdit and searched for the path of their own Fonts folder&#8230; the first key they found, they used as the parameter for a call to  <em>RegOpenKeyEx</em> and they read the value that way.</p>
<p>To me, that is not only a frighteningly ignorant and dangerous way to develop software (you&#8217;re not going to discover caveats &#038; usage notes by browsing RegEdit!) but <strong>of course</strong> this is not the supported way to do it (how could any sane developer think otherwise?), and <strong>of course</strong> that app would have broken immediately on any new of Windows had MS not added a compatibility shim to watch for that program checking that buggy key, and substituting in a quick call to obtain the real value&#8230;</p>
<p>This isn&#8217;t backyard programmers writing in VBA in Excel to accomplish some one-off business task, either.. it&#8217;s commercial software that did this, written by professional developers and sold to unsuspecting customers for big cash. Scary stuff.</p>
<p>The only question worth pondering here is: was this &#8216;grab something promising out of the Registry&#8217; technique better or worse than just hard-coding &#8220;C:\Windows\Fonts\&#8221; into the application? (I&#8217;m not 100% sure but it seems very likely there&#8217;s a shim out there for programs that did that, too.) </p>
]]></content:encoded>
			<wfw:commentRss>http://www.paradicesoftware.com/blog/index.php/2009/11/scary-windows-development-stories/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Game Golden Rule #1: Support Windowed-mode</title>
		<link>http://www.paradicesoftware.com/blog/index.php/2009/11/game-golden-rule-1-support-windowed-mode/</link>
		<comments>http://www.paradicesoftware.com/blog/index.php/2009/11/game-golden-rule-1-support-windowed-mode/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 06:50:43 +0000</pubDate>
		<dc:creator>Lawrence</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Game Golden Rules]]></category>
		<category><![CDATA[DirectX]]></category>
		<category><![CDATA[Taxes]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.paradicesoftware.com/blog/?p=141</guid>
		<description><![CDATA[I thought I&#8217;d cover this rule first, because I listed it as number one and also because it&#8217;s probably one of the most controversial. Let&#8217;s begin: a simple Why/Why Not argument should suffice for this one:
Why Allow Windowed-mode:
It&#8217;s more convenient for your users. Some users multitask (gasp!), even while playing games. This is much harder [...]]]></description>
			<content:encoded><![CDATA[<p>I thought I&#8217;d cover this rule first, because I listed it as number one and also because it&#8217;s probably one of the most controversial. Let&#8217;s begin: a simple Why/Why Not argument should suffice for this one:</p>
<h3>Why Allow Windowed-mode:</h3>
<p><strong>It&#8217;s more convenient for your users.</strong> Some users multitask (gasp!), even while playing games. This is much harder to do when your game is Fullscreen. I suspect this is a part of why games like Minesweeper and Solitaire get so much play-time. They&#8217;re built into the OS, sure, but you can also fire them up and play while you&#8217;re waiting for something to download/compile/whatever. Very handy!</p>
<p><strong>It&#8217;s more convenient for you.</strong> Debugging is hard, and debugging fullscreen is harder! My own game engine (in debug builds) has a feature to throw a debugging/log window up so I can watch internal game messages etc: you can&#8217;t do this if your game is always fullscreen. Not only that, but if your game crashes at some Direct3D stuff (which can happen in early builds, before you lock down your video interface code), it&#8217;s very tricky to find a cause when you&#8217;re staring at a blank screen. A blank window on the desktop gives you more context and options.</p>
<p><strong>It makes paying certain Windows taxes more obvious.</strong> If you&#8217;re running in Windowed mode while developing, you&#8217;re going to be hitting the titlebar close button, you&#8217;ll be minimising/maximising your game Window, or maybe just clicking other apps, stealing your game&#8217;s focus. Because you&#8217;re doing these things, you&#8217;re much more likely to take the time to ensure your game handles them correctly. Fullscreen games are required to handle these situations too, you know: but some of them never get around to it! (Civilization 3, which is always &#8220;fullscreen&#8221;, can experience a rather ugly crash if I dare to click something on my second monitor while I&#8217;m playing).</p>
<p><strong>It&#8217;s future proof.</strong> You might think your fullscreen game is pretty cool, what with it supporting resolutions right up to 1920&#215;1080, but who knows what the future holds? How well will your fullscreen game look on some giant desktop running 12,000&#215;12,000 pixels? Or do you just expect no one will be playing it then? (if you don&#8217;t, then code this way: you&#8217;re sure to be correct). Windowed mode doesn&#8217;t solve this completely, but it gives your users more options.</p>
<p>Ok, hopefully you can that there are always scenarios where that option would be valuable, but you might not be convinced to allow it in <strong>your</strong> game. Let&#8217;s take a look at some reasons why not:</p>
<h3>Why NOT allow Windowed-mode:</h3>
<p><strong>It&#8217;s hard to code.</strong> Oh no, now all of your video code has two scenarios to account for! Well, actually, no it doesn&#8217;t. Once you&#8217;ve initialised Direct3D correctly, none of your other code even needs to *know* it&#8217;s drawing to a windowed area of the desktop. And initialising Direct3D to support either Windowed or Fullscreen mode is <strong>easy</strong>! I&#8217;ll bet you $5 that the sum total of video code required to support this option is LESS than the amount of code required to present the option to the user and store the result.</p>
<p><strong>Fullscreen is more atmospheric. Atmosphere is important in my game!</strong> By all means then, make fullscreen the default. Plenty of games do. I&#8217;m just asking for the <strong>option!</strong></p>
<p><strong>But I want to retain control.</strong> Fuck off! The user is in control: it&#8217;s their computer. Besides, if the user really wants to window you, they can do it: they can fire up a virtual machine and lock you inside it: good luck getting into fullscreen mode then. Of course, if it&#8217;s that important to them, they&#8217;re more likely to just uninstall you and go play something with a windowed option.</p>
<p>And there you have it. Why I believe every game should support Windowed-mode!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.paradicesoftware.com/blog/index.php/2009/11/game-golden-rule-1-support-windowed-mode/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Paying your Windows Taxes</title>
		<link>http://www.paradicesoftware.com/blog/index.php/2009/11/paying-your-windows-taxes/</link>
		<comments>http://www.paradicesoftware.com/blog/index.php/2009/11/paying-your-windows-taxes/#comments</comments>
		<pubDate>Wed, 11 Nov 2009 05:09:57 +0000</pubDate>
		<dc:creator>Lawrence</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Game Golden Rules]]></category>
		<category><![CDATA[Taxes]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.paradicesoftware.com/blog/?p=123</guid>
		<description><![CDATA[In Windows (like every operating system), when you&#8217;re writing an application or game there are certain things that your application is responsible for handling: some of them are easy, some of them take a little bit more effort. On his excellent blog, Microsoft&#8217;s Raymond Chen calls these responsibilities &#8220;Taxes&#8221;, and there are good reasons why [...]]]></description>
			<content:encoded><![CDATA[<p>In Windows (like every operating system), when you&#8217;re writing an application or game there are certain things that your application is responsible for handling: some of them are easy, some of them take a little bit more effort. On his excellent blog, Microsoft&#8217;s <a href="http://blogs.msdn.com/oldnewthing/archive/2005/08/22/454487.aspx">Raymond Chen</a> calls these responsibilities &#8220;Taxes&#8221;, and there are good reasons why you should pay them. Windows taxes include things like:</p>
<ul>
<li>Respond to Windows messages correctly</li>
<li>Respect user action (don&#8217;t silently cancel a Sleep request)</li>
<li>Non-standard installs (don&#8217;t assume C:\Windows!)</li>
<li>Run fine as a Standard User</li>
<li>Respect the user&#8217;s settings</li>
</ul>
<p>Raymond talks about more complex taxes too (internationalisation, heirarchical file systems), but I&#8217;m sticking to what I&#8217;m comfortable with!</p>
<p>Unfortunately, amongst all applications, games appear to be the worst at being good Windows citizens, there are far too many games out there (not just freeware ones either) that don&#8217;t pay <strong>any</strong> of the above taxes, and (to sustain the metaphor) some start trying &#8216;tax-fraud&#8217; schemes like:</p>
<ul>
<li>Trying to disable Alt-Tab</li>
<li>Refusing to be minimised (automatically restoring themselves after 1 sec)</li>
<li>Preventing the system from shutting down</li>
</ul>
<p>I might make this another series because there&#8217;s plenty to talk about, and most of it&#8217;s not even that difficult these days: you just have to be aware of the situation, and what the correct behaviour is. (I must admit I never gave thought to multi-monitor situations before I got my second monitor).</p>
<p>For now though, I will limit myself to a list of ten &#8216;golden rules&#8217; which I believe all games should obey, at a minimum (not all of them are Windows taxes &#8211; some of them are just treating your users properly). In fact I will expand on some of these in later posts too, because they&#8217;re worth talking about.</p>
<h3>Top ten Golden rules for Games: being a good Windows application</h3>
<ol>
<li>1. Fullscreen games: <strong>always</strong> allow an option to run in a Window.</li>
<li>2. Provide gamma and volume controls, and separate music from sound.</li>
<li>3. Always allow your game to be paused, saved and quit. At any time.</li>
<li>4. Provide a way to skip <strong>anything</strong> non-interactive: from cutscenes to credits.</li>
<li>5. Respect multi-monitor: If you were dragged to monitor 2, next time open on monitor 2.</li>
<li>6. Respect the filesystem: don&#8217;t open files in Read/Write mode if you only want to read from them.</li>
<li>7. Respect security: A game <strong>does not</strong> need an Administrator account to play!</li>
<li>8. Respect UI settings: if the user has selected &#8216;Use Large Fonts&#8217; in Windows, use larger fonts in your game!</li>
<li>9. Respect sessions: if the user logs off/hibernates/shuts down, handle it gracefully. Don&#8217;t try to block the action, and don&#8217;t lose their progress.</li>
<li>10. Adapt to a changing system: if you last opened on 1680&#215;1050, but the system now says the monitor can&#8217;t support that, open in a res it <strong>can</strong> support.</li>
</ol>
<p>I&#8217;ll talk about how to implement some of these (and why they&#8217;re so important) in future posts.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.paradicesoftware.com/blog/index.php/2009/11/paying-your-windows-taxes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Controlling Gamestate</title>
		<link>http://www.paradicesoftware.com/blog/index.php/2009/10/controlling-gamestate/</link>
		<comments>http://www.paradicesoftware.com/blog/index.php/2009/10/controlling-gamestate/#comments</comments>
		<pubDate>Fri, 30 Oct 2009 18:57:41 +0000</pubDate>
		<dc:creator>Lawrence</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Icefall]]></category>
		<category><![CDATA[Gamestate]]></category>

		<guid isPermaLink="false">http://www.paradicesoftware.com/blog/?p=90</guid>
		<description><![CDATA[Virtually all programs have this, a central &#8216;game&#8217; loop that grabs user input, updates game logic, redraws the screen. At it&#8217;s simplest possible level, it usually looks something like this:

repeat
   Input;
   Update;
   Redraw;
until Quit;

The problem mainly comes in that middle section, Update. For any game, there are a variety [...]]]></description>
			<content:encoded><![CDATA[<p>Virtually all programs have this, a central &#8216;game&#8217; loop that grabs user input, updates game logic, redraws the screen. At it&#8217;s simplest possible level, it usually looks something like this:</p>
<blockquote>
<pre>repeat
   Input;
   Update;
   Redraw;
until Quit;</pre>
</blockquote>
<p>The problem mainly comes in that middle section, <em>Update</em>. For any game, there are a variety of different states you can be in (main menu, options screen, credits, playing game) and for most games, &#8220;playing game&#8221; breaks down into a whole lot more states by itself. For my simple 500 Card Game, I had states &#8220;bidding&#8221;, &#8220;dealing&#8221;, &#8220;choosing kitty&#8221;, as well as playing. If you&#8217;re not careful, your <em>Update</em> procedure can end up looking like this:</p>
<blockquote>
<pre>Procedure Update;
begin
   case State of
      STATE_MENU:
         // wait for a menu click
      STATE_OPTIONS:
         // handle user input
      STATE_CREDITS:
         // roll some credits
      STATE_GAME:
         case GameState of
            GS_PLAYING:
               // handle user input
               // update some monsters
            // etc
         end;
      // STATE_ even more stuff:
   end;
end;</pre>
</blockquote>
<p>So far, so big and clunky. It gets worse when you have to handle nested state transitions: in my card game, someone could be playing, then go to the Menu and come back. So I had to have a variable &#8216;LastState&#8217; that remembered where they were, so they could go back to it. But it&#8217;s worse than that, because they might go to the Menu, then go to the Options screen: and when they came back, they&#8217;d still want their current game to not be lost! My card game was simple, so I managed this as simply as I could: when entering the &#8216;menu&#8217; state, the menu grabbed it&#8217;s own copy of LastState, and it restored this value when the other screens (Options, Credits etc) returned to it, so there was always a way back to the game. This was the simplest case, because every state had exactly one other state that it could be transitioned from (you couldn&#8217;t get to Options from Game without going through Menu).</p>
<p>For Icefall though, the stakes were raised. I wanted the Options screen accessible from in-game, as well as in the initial menu. And there are many more states that the game can be in, and some of them should not be returned to (e.g the &#8220;create character&#8221; screen), so rather than a gigantic and ugly Update loop, I went back to good old OOP and implemented a class-based state stack.</p>
<p>Icefall has a central &#8220;State Engine&#8221; that looks after the current state stack, handles transitions between them, and calls whichever state is &#8216;on top&#8217; during the main loop. The State class looks something like this:</p>
<blockquote>
<pre>TIceState = class (TIceClass)
   constructor Create
      (StateEngine: TIceStateEngine;
       Transition: TStateTransition);
   procedure OnEnter; virtual;
   procedure OnLeave; virtual;
   procedure Update; virtual;
   procedure Redraw;
   // other useful state methods
   destructor Destroy; override;
end;</pre>
</blockquote>
<p>Essentially, for every state the game can be in, I have a corresponding class that defines it&#8217;s specific behaviour in <em>Update</em>. I can also do other &#8216;maintenence&#8217; (e.g. ensure the right music is playing) by overriding the OnEnter and OnLeave procedures. The game can change states by constructing a new <em>TIceState</em> instance, passing it a reference to the state engine and describing the type of transition to use (e.g. whether to nest the state [for a trip to a Menu] or just progress to the new state with no way back [like a character create screen]). You can also leave a state just by destructing the class instance: the state engine will pop back to the next highest state on the state stack, or quit the game if there are no states left (e.g., you just hit &#8216;Exit&#8217; from the Main Menu). </p>
<p>The state engine takes care of nested states and transitions, and someone&#8217;s <strong>exact</strong> state in the game can be saved (if needed) by storing the entire state stack: while I&#8217;m unlikely to want the game to be saved while on the Character Create screen, it&#8217;s good to know I can safely save the game while in shops, or at any other point, without even worrying about special handling code to cover all the situations.</p>
<p>Another interesting thing I have done is move the game&#8217;s &#8220;loader&#8221; (the part that loads textures, sounds, music, fonts, databases) into it&#8217;s own state, and just made it the very first state that&#8217;s pushed onto the stack, and it takes a parameter to the state to transition to when it&#8217;s done. It takes the whole &#8216;loading&#8217; step out of the main game code, which makes that much simpler, and I can make the loader just load the resources I&#8217;m going to need right now: some other state (like the credits) can always call it again later to load specific credit-y images.</p>
<p>I can also use the the same game engine to build other tools like the Map Editor: the only difference between the map editor and the game itself is that it compiles in a different set of states: when the map editor has loaded, it launches itself into a <em>TMapEditorState</em> instead of a <em>TMainMenuState</em>.</p>
<p>Overall, having a <strong>state stack</strong> is very flexible, quite simple to use and maintain, and overall a vast improvement from the &#8216;giant case statement&#8217; I was using previously.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.paradicesoftware.com/blog/index.php/2009/10/controlling-gamestate/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>OOP Part 3: Composition</title>
		<link>http://www.paradicesoftware.com/blog/index.php/2009/10/oop-part-3-composition/</link>
		<comments>http://www.paradicesoftware.com/blog/index.php/2009/10/oop-part-3-composition/#comments</comments>
		<pubDate>Fri, 30 Oct 2009 06:05:18 +0000</pubDate>
		<dc:creator>Lawrence</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Icefall]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://www.paradicesoftware.com/blog/?p=80</guid>
		<description><![CDATA[Last time, we looked at the inheritance style of object-oriented programming in detail. Now let&#8217;s look at the alternative: composition.
We&#8217;ll use another example from Icefall to illustrate the differences. Icefall has a central &#8216;world view&#8217; that shows the player and their immediate surroundings (items, monsters, terrain, etc). The world view also shows animations (e.g. fireballs, [...]]]></description>
			<content:encoded><![CDATA[<p>Last time, we looked at the <strong>inheritance</strong> style of object-oriented programming in detail. Now let&#8217;s look at the alternative: <strong>composition</strong>.</p>
<p>We&#8217;ll use another example from Icefall to illustrate the differences. Icefall has a central &#8216;world view&#8217; that shows the player and their immediate surroundings (items, monsters, terrain, etc). The world view also shows animations (e.g. fireballs, weapons swinging, speech bubbles, etc) and it&#8217;s the animation code that we&#8217;ll be looking at in detail today.</p>
<p>I designed this feature around each animation being a class instance, with the class methods and properties making it easy for the game engine to control the details (lifetime, location, save/load etc etc). I knew I&#8217;d have several different types of animation, so my initial implementation chucked all that &#8216;management&#8217; functionality into a <em>TAnimation</em> class, and left virtual methods for  things like <em>Process</em> and <em>Draw</em> for descendents to implement. After creating a few basic animations, my class hierarchy looked like this:</p>
<blockquote>
<pre>TAnimation
   TAnimText
      TAnimSpeech
      TAnimTexturedText
   TAnimTexture
      TAnimMissile
      TAnimExplosion
      TAnimMelee</pre>
</blockquote>
<p>Animations with text (i.e. picking up an item) were a subclass, and speech bubbles (or text with a textured background) were subclasses of that. Missiles (like fireballs) were a subclass where the animation moved from one place to another (and was rotated to face the right direction), and Explosions were in one place but had a series of animation frames over time. Melee animations showed a weapon and some motion-blur, sweeping out to attack a monster/player.</p>
<p>The problem with this system, which I discovered after adding <em>TAnimTexturedText</em> (specificially to show damage-dealt as a number on a bloodsplat-graphic background) was that most of the subtypes only varied in very small ways, and the overhead of naming, constructing and using each subtype took more effort than defining the subtype itself. Also, the &#8216;event&#8217; system I was setting up for Icefall was supposed to allow for animations to be defined dynamically in response to any spell or event (and new events added in data files without recompiling the game) &#8211; but the code that supported this was going to be very complex and ugly if it had to choose between all of the different constructors each time and pass a specific set of parameters to make it happen.</p>
<p>So, I rewrote the animation subsystem to bring any functionality that I could possibly re-use into the parent class: now, all animations had a <em>Texture</em> property, a <em>Rotate</em> property, <em>Frames</em>, <em>Movement</em>, <em>Sound</em>&#8230; which could all be left at Nil or 0 if not needed. My new, composited animation hierarchy looked like this:</p>
<blockquote>
<pre>TAnimation
   TAnimText
      TAnimSpeech</pre>
</blockquote>
<p>As soon as I did this, I found that it was not only easier to manage the sources, but that features of the parent class ended up getting used more often than I anticipated: e.g. giving an explosion a random value for <em>Rotate</em> made each explosion look slightly different, and I could apply a small <em>Movement</em> value to Text to let it &#8216;float&#8217; upwards from where it first appeared: new and useful functionality essentially for &#8216;free&#8217;.</p>
<p>Note that I kept <em>AnimText</em> separate from the parent, because there is some substantially different functionality: it has text (which directly contributes to the size and position of the anim), which is also dynamic, and there is some special logic to ensure two text animations don&#8217;t overlap each other. It made sense to move this code out into a specific class where it could be closely tweaked. Speech is different again, because there is a &#8220;speaker&#8221; creature that it it linked to: the speech bubble needs to move around with it&#8217;s speaker, disappear if they die, etc.</p>
<p>In summary, now that the <em>TAnimation</em> class is composited, it&#8217;s significantly &#8216;better&#8217; code than before:</p>
<ul>
<li>Fewer types to worry about</li>
<li>Much easier to follow the logic of the code in a single class</li>
<li>Can trivially re-use functionality developed for one subtype in others</li>
<li>Much easier for other code to utilise this class effectively</li>
</ul>
<p>So, my conclusion in this small series is:</p>
<p>Use composition in your classes, unless there is substantially different behaviour, or external code needs to interact with a specific subtype in a special way (e.g. <em>TAnimation</em> itself is inherited from <em>TWorldObject</em>, because the world view needs to interact with animations in a specific way).</p>
<p>Next time, I&#8217;ll find something different to ramble on about.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.paradicesoftware.com/blog/index.php/2009/10/oop-part-3-composition/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OOP Part 2: Inheritance</title>
		<link>http://www.paradicesoftware.com/blog/index.php/2009/10/oop-part-2-inheritance/</link>
		<comments>http://www.paradicesoftware.com/blog/index.php/2009/10/oop-part-2-inheritance/#comments</comments>
		<pubDate>Wed, 28 Oct 2009 07:00:37 +0000</pubDate>
		<dc:creator>Lawrence</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Icefall]]></category>
		<category><![CDATA[Freepascal]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://www.paradicesoftware.com/blog/?p=64</guid>
		<description><![CDATA[Last time, we talked about two different approaches to designing objects for a game or application: Inheritance and Composition. It&#8217;s time to look at the pros and cons in more detail. Let&#8217;s start with inheritance.
Inheritance
When learning OOP, inheritance is what you learn! Create a common, generic ancestor-type class, and create new classes for specific game [...]]]></description>
			<content:encoded><![CDATA[<p>Last time, we talked about two different approaches to designing objects for a game or application: Inheritance and Composition. It&#8217;s time to look at the pros and cons in more detail. Let&#8217;s start with inheritance.</p>
<h3>Inheritance</h3>
<p>When learning OOP, inheritance is what you learn! Create a common, generic ancestor-type class, and create new classes for specific game objects which inherit from, override and extend the functions of the ancestor. Repeat as desired. Let&#8217;s look at the consequences of following this model:</p>
<p>Pros:</p>
<ol>
<li>It&#8217;s easy to locate all functionality belonging to each type: they&#8217;re together in the source for the child class.</li>
<li>It&#8217;s easy to write an appropriate constructor for the type; so you know the classes internal state will be consistent.</li>
<li>It&#8217;s easy to guard against the wrong type being passed to a function at compile time: If you have <em>Function AttackMonster(WithWeapon: TWeapon);</em> the compiler will prevent you passing a <em>TItem</em> that isn&#8217;t a <em>TWeapon</em>.</li>
<li>You can specify abstract methods in the parent where you know the divergent behaviour will be, and the language and compiler will help you get there and warn you if you&#8217;ve left something out.</li>
</ol>
<p>Cons:</p>
<ol>
<li>You end up with *lots* of different classes &#8211; which may be in lots of different files.</li>
<li>Some of the classes can be really, really small&#8230; e.g., a single method override.</li>
<li>When looking at the child class implementation with a call to the inherited parent, you don&#8217;t know exactly what the parent does.</li>
<li>If two different children of a common ancestor need the same functionality, you have to code it twice.</li>
<li>Code that constructs instances must take care to call the correct constructor.</li>
<li>You can&#8217;t &#8220;switch&#8221; a child to a different type; you need to destruct it and create a new instance of the other type.</li>
<li>Greater risk of circular-references if your child classes need to interact with each other.</li>
</ol>
<p>You can see the pattern forming. The <strong>Pros</strong> of this model tend to be that things are easier to setup up-front, when you&#8217;re initially coding the classes. The <strong>Cons</strong> tend to hit you later: when you&#8217;re extending functionality, or just coming back to the code after time spent elsewhere.</p>
<p>It&#8217;s also possible with this model to really make life impossible for yourself. If you come up against Con #4 and are tempted to move some of that common functionality in the parent class, congratulations: you just blasted Pro #1 and debugging and maintaining this code just became a nightmare, and now the parent needs to duplicate some child state in order to know which of these &#8220;optional-children&#8221; operations it should perform. Ick!</p>
<p>Note that this inheritance style is still arguably a gigantic code-safety and readibility improvement from old-style procedual code. The question is, can we do better? In Part 3, we&#8217;ll look at the alternative model of Composited classes.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.paradicesoftware.com/blog/index.php/2009/10/oop-part-2-inheritance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Object-oriented programming</title>
		<link>http://www.paradicesoftware.com/blog/index.php/2009/10/object-oriented-programming/</link>
		<comments>http://www.paradicesoftware.com/blog/index.php/2009/10/object-oriented-programming/#comments</comments>
		<pubDate>Sun, 25 Oct 2009 22:21:28 +0000</pubDate>
		<dc:creator>Lawrence</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Icefall]]></category>
		<category><![CDATA[Freepascal]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://www.paradicesoftware.com/blog/?p=40</guid>
		<description><![CDATA[Like almost everything else these days, Icefall is designed around object-oriented programming (OOP) principles. Specifically, Icefall uses Classes instead of objects, although the difference is not relevant for this discussion.
At any given time, the game will be operating dozens of different classes and hundreds of instances of those classes, with the majority of them representing [...]]]></description>
			<content:encoded><![CDATA[<p>Like almost everything else these days, Icefall is designed around object-oriented programming (OOP) principles. Specifically, Icefall uses Classes instead of objects, although the <a title="Freepascal: Classes" href="http://www.freepascal.org/docs-html/ref/refch6.html" target="_blank">difference</a> is not relevant for this discussion.</p>
<p>At any given time, the game will be operating dozens of different classes and hundreds of instances of those classes, with the majority of them representing either individual game objects (an item, a monster, the player) or a piece of the user interface (a button, an animation, etc). As you&#8217;d expect, many of these classes inherit from other classes (e.g. the button class is inherited from the generic UI class) but the question of exactly how much inheritance to use is something that confuses many people &#8211; and if you get it wrong, your code will suffer. So let&#8217;s take a closer look.</p>
<h3>Inheritance vs Composition</h3>
<p>Turning a program&#8217;s logic into a group of classes seems easy (hmm, my game has items, let&#8217;s make a <em>TItem</em> class!), but choosing the right combination of classes is harder than it looks. Like everything else, the more complex your application is, the harder and more important these choices will be.</p>
<p>One common choice is to do everything via inheritance. You make some ancestor classes which contain <strong>only</strong> the logic that will be common to all descendents, and you create inherited classes to cover all exceptions or additions to that logic. This style is called<em><strong> </strong></em><strong>inheritance</strong> for obvious reasons, and lots of newcomers to OOP start like this. Let&#8217;s create an example that shows this in action:</p>
<p>Icefall needs to know an item&#8217;s worth (in gold) to a shopkeeper to allow the player to buy/sell it. As items in Icefall can have randomly generated properties, we can&#8217;t define the worth of everything at compile time (and even if we could, there will be hundreds of different items in Icefall. Don&#8217;t specify things you could calculate. I&#8217;ll talk about this another time). So we need a method in the <em>TItem</em> class to calculate the item&#8217;s worth for us.</p>
<h3>Inheritance</h3>
<p>The inheritance solution might look like like this:</p>
<blockquote>
<pre>TItem = class
   function Worth: Integer; virtual;
end;

function TItem.Worth: Integer;
begin
   result := ILevel * 20; // ILevel is another property.
end;</pre>
</blockquote>
<p>Nice and easy so far. The item&#8217;s worth is calculated as being 20 times it&#8217;s <em>ILevel</em> (item-level). But what happens when we want to make some items (let&#8217;s say weapons) more valuable than others? The inheritance solution is to build on the existing code and do this:</p>
<blockquote>
<pre>TWeapon = class (TItem)
   function Worth: Integer; override;
end;

function TWeapon.Worth: Integer;
begin
   result := 100 + ILevel * 50; // Weapons are worth more
end;</pre>
</blockquote>
<p>We have overridden <em>TItem</em>&#8217;s <em>Worth</em> function with a new one just for <em>TWeapon</em>. We just have to remember that when we&#8217;re creating items, if it&#8217;s a weapon we need to construct a <em>TWeapon</em> class instead of a <em>TItem</em> class to hold it, and the right <em>Worth</em> function will be called automatically.</p>
<h3>Composition</h3>
<p>Meanwhile, another style, often referred to as <strong>composition</strong>, says to group similar functionality together, and use members or properties to determine the appropriate behaviour for each instance:</p>
<blockquote>
<pre>TItemType = (ITEMTYPE_NORMAL,ITEMTYPE_WEAPON);

TItem = class
   function Worth: Integer;
   property ItemType: TItemType;
end;

function TItem.Worth: Integer;
begin
   case ItemType of
      ITEMTYPE_WEAPON :
         result := 100 + ILevel * 50;
   else
      result := ILevel * 20;
   end;
end;</pre>
</blockquote>
<p>Already, for our tiny example, the two implementations are looking considerably different. The composited version defines a class property called <em>ItemType</em> that stores what type of item this instance represents, and the <em>Worth</em> function contains all the functionality for both item types (I used a <em>case</em> statement instead of a simple <em>if</em>, because I suspect I will end up with more than two item types).</p>
<p>p.s. Icefall, of course, takes much more into account to determine an item&#8217;s worth: it&#8217;s rarity, any enchantments, whether the shopkeeper likes the player, etc etc. But that wasn&#8217;t relevant for this discussion <img src='http://www.paradicesoftware.com/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<h3>Conclusion</h3>
<p>So which is better? What are the pros and cons of each style? Tune in next time to find out!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.paradicesoftware.com/blog/index.php/2009/10/object-oriented-programming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
