<?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>#AltDevBlogADay &#187; James Podesta</title>
	<atom:link href="http://www.altdevblogaday.com/author/james-podesta/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.altdevblogaday.com</link>
	<description>Each day a little more #gamedev love</description>
	<lastBuildDate>Thu, 17 May 2012 03:06:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>RTFM &#8211; TL;DR</title>
		<link>http://www.altdevblogaday.com/2011/06/27/rtfm-tldr/</link>
		<comments>http://www.altdevblogaday.com/2011/06/27/rtfm-tldr/#comments</comments>
		<pubDate>Mon, 27 Jun 2011 23:11:45 +0000</pubDate>
		<dc:creator>James Podesta</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://altdevblogaday.org/?p=8606</guid>
		<description><![CDATA[<p>When I was young, I used to read all manuals like I read my fantasy novels. Take them into my bedroom for the weekend and read from the first page to the last, in order, skipping nothing. I would devour every piece of information in the order they chose to present it to me, and miss nothing.  By the end I would have a clear understanding of all the pieces of the puzzle and how they fit together.</p>
<p><a href="http://www.altdevblogaday.com/2011/06/27/rtfm-tldr/" class="more-link">Read more on RTFM &#8211; TL;DR&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>When I was young, I used to read all manuals like I read my fantasy novels. Take them into my bedroom for the weekend and read from the first page to the last, in order, skipping nothing. I would devour every piece of information in the order they chose to present it to me, and miss nothing.  By the end I would have a clear understanding of all the pieces of the puzzle and how they fit together.</p>
<p>&nbsp;</p>
<p>These days I just code with the knowledge I have,  guess how things might be and, when I get stuck, I jump into a reference manual or jump onto google and find the bit of information I&#8217;m missing. As a consequence, I only just found out a few days ago, purely by an accidental web link, that STL provided a bitset template.  I can see understand perfectly why I didn&#8217;t know this existed. It&#8217;s not that I haven&#8217;t had use for a bitset template in the past,  its just that its not something complex enough that I would ever needed to google for information on it.</p>
<p>&nbsp;</p>
<p>The combined knowledge of the universe is now at my finger tips, kindly indexed by keywords. I know the answer to the ultimate question of life, the universe and everything is in cyberspace, if only I can find the right question.  But does this mean I don&#8217;t need to store information in my head anymore &#8211; just retask my brain to be a master of composing the correct keywords for a problem.  Is it really ok to be crippled if I have no internet connection.</p>
<p>&nbsp;</p>
<p>And its not just knowledge that has been replaced by keyword access. When I was young, my pirate friends &#8211; not me, I would never &#8211; would trade games via mail (notice no &#8216;e&#8217; prefix) on cassettes (young readers should google this if you don&#8217;t know what a cassette is). Now you just type in a keyword into Vuze on your Mac &#8211; again, not me, I don&#8217;t even know what Vuze is &#8211; and you get a list of every song, tv show, movie or game and within minutes its yours &#8211; well, not yours, but you have it.  Actually, even googling is too much effort.  Just highlight the word in your browser and Apture will find the information for you.</p>
<p>&nbsp;</p>
<p>Admittedly, I appear to have a lot less time than I used to when I was young. I&#8217;ve done numerous experiments, including watching clocks in 70s videos, and it certainly appears that time hasn&#8217;t sped up, at least in no way I have been able to measure. Maybe its facebook, twitter, dayjob, family and nightjob &#8211; I certainly didn&#8217;t have all these when I was younger. I could just take a book into the bedroom for the weekend and emerge 3 days later a little bit smarter &#8211; yeah, it was a sad childhood really.</p>
<p>&nbsp;</p>
<p>So are our new iBrains really a good thing?  Time to put on the opinion cap.  Yes, its awesome having access to blogs and white papers and answers to everyones questions,  but we need to temper that with discipline. The most common forum post these days is &#8220;read the manual&#8221;,  because most questions are clearly answered in the manual but no-one bothers reading now. Its easier and quicker to jump on a forum and ask if anyone else knows the answer &#8211; maybe someone who has actually read the manual.  (Actually, I have no idea what the most common forum post is, I totally made that up to support my argument. ).</p>
<p>&nbsp;</p>
<p>So am I going to return to reading manuals front-to-back?  I was all ready to say &#8220;absolutely, I will make a point of always reading manuals properly from now on!&#8221;  But to be honest, I doubt it.  There&#8217;s a simple rule of the universe that all things follow the path of least resistance.  While humans are capable of using intellect to break this rule,  they generally don&#8217;t bother.  BTW, this is also a great rule to follow if your ever designing tools or interfaces that you want other people to use &#8211; make sure your stuff is the path of least resistance&#8230;</p>
<p>So what&#8217;s the morale to all this?</p>
<p>TL;DR</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/06/27/rtfm-tldr/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Learning from Others</title>
		<link>http://www.altdevblogaday.com/2011/05/14/learning-from-others/</link>
		<comments>http://www.altdevblogaday.com/2011/05/14/learning-from-others/#comments</comments>
		<pubDate>Sat, 14 May 2011 08:01:12 +0000</pubDate>
		<dc:creator>James Podesta</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=5685</guid>
		<description><![CDATA[<p>Learning from previous works is a great way to boost your learning curve.  This is as relevant to newbies as it is to old fixed-in-our-ways dinosaur coders like myself. Every piece of code and software is someone&#8217;s attempt to solve a problem. Understanding why the authors chose to solve the problem the way they did, will make your future decisions that much more informed.</p>
<p><a href="http://www.altdevblogaday.com/2011/05/14/learning-from-others/" class="more-link">Read more on Learning from Others&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Learning from previous works is a great way to boost your learning curve.  This is as relevant to newbies as it is to old fixed-in-our-ways dinosaur coders like myself. Every piece of code and software is someone&#8217;s attempt to solve a problem. Understanding why the authors chose to solve the problem the way they did, will make your future decisions that much more informed.</p>
<p>&nbsp;</p>
<h2>Learning from other code</h2>
<p>Often, through my professional career, I&#8217;m forced to work in other people&#8217;s frameworks. Most often this is very frustrating as their way to solve a problem is in contrary to how I&#8217;d prefer the problem solved. However, its important to keep a cool head and try to understand the philosophy behind their code.  In most cases, there are a few things that do work well in the framework, and often, once you understand it all, you may even be swayed over by the advantages of their technique.</p>
<p>&nbsp;</p>
<h2>Learning from other languages</h2>
<p>I recently had to code a simple utility in C#.  I don&#8217;t write utilities often and have very little experience in C#, so the process was a small learning curve.  However, by learning some of C#&#8217;s string handling interfaces, I was then inspired to add some new helper functions to my C++ codebase to make certain things easier to do, like having a simple Split function that divides strings up into arrays of smaller strings. Some languages are very cleanly designed and have some great features. You&#8217;ll often find you can duplicate those features to a reasonable extent in your own language of choice. So as well as having another language available to you, when you need it,  you also have absorbed interface design skills from that other language. It&#8217;s not just a case of every language having its use. It&#8217;s more that every language has found creative ways to solve common problems.</p>
<p>&nbsp;</p>
<h2>Learning from other engines</h2>
<p>You will have seen other articles about the importance of home projects. Your &#8220;paid&#8221; projects are generally restrictive as to how much experimentation and personal growth you can pull out of them due to design, production and time constraints.  Personal projects are also grant a great opportunity to experiment with other engines. Some of the top engines out there have very mature and well thought out pipelines and programming methodologies. Producing a game prototype in various engines is a great way of gaining insight into how your own pipeline can be improved. Always remember that the intention here is not (necessarily) to find a new engine to replace your current engine. The purpose of doing a home project in a new engine is mainly to boost your knowledge by seeing how a problem can be solved in a very different way from how you would normally solve it. Until you have completed a substantial project in another engine, you never really know how these different techniques will cope with all the bits and pieces you need to tie together to make a deliverable game.</p>
<p>&nbsp;</p>
<h2>Taking the time to learn</h2>
<p>Certainly, experience can be attained by just solving new and different problems, evolving your skillset to meet the new challenges. However, when you look at other people&#8217;s code, languages, and engines, what you are seeing is the result of those people&#8217;s already evolved skillsets. Understanding the decisions made there is a way to rapidly enhance your own ability.</p>
<p>It&#8217;s not always fun to have to learn how other people have done things, and generally we code at home because we enjoy it, so we avoid things that aren&#8217;t fun. So I like to look at it as &#8220;professional homework&#8221;. The pain of learning other peoples techniques is often because your brain is being challenged to solve problems in ways it is unfamiliar with. Like everything in life, the healthy things often taste terrible. Taking the time to do your homework will make your decisions much more well-rounded in future.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/05/14/learning-from-others/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Debugging on your Web Browser</title>
		<link>http://www.altdevblogaday.com/2011/03/15/debugging-on-your-web-browser/</link>
		<comments>http://www.altdevblogaday.com/2011/03/15/debugging-on-your-web-browser/#comments</comments>
		<pubDate>Tue, 15 Mar 2011 17:17:55 +0000</pubDate>
		<dc:creator>James Podesta</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=1998</guid>
		<description><![CDATA[<div>Some time ago, a colleague I worked with at Krome Studios, Matthew Peers, put me onto using HTTP as an interactive output for debug information. I&#8217;d never touched HTTP before and didn&#8217;t realise what an amazingly easy and convenient interface it was for getting state information out of your game. Pretty much any platform that is ping-able and supports sockets interface can provide a HTTP interface for debugging information. So far I&#8217;ve used it on X360, PS3, PC and iOS devices.</div>
<div></div>
<div>For those of you who have no experience with HTTP GET protocol, I will go through a simple overview of the code involved. But before I do that, I&#8217;d like to show you exactly what this is all about and I think a short video is the quickest way to convey that information. So here is a small video of how I am currently using the interface for my iOS game magelore. This video shows the PC version running, but it works exactly the same running it on an iDevice or pretty much any other platform.</div>
<div><!--YouTube Error: bad URL entered--></div>
<p><a href="http://www.altdevblogaday.com/2011/03/15/debugging-on-your-web-browser/" class="more-link">Read more on Debugging on your Web Browser&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<div>Some time ago, a colleague I worked with at Krome Studios, Matthew Peers, put me onto using HTTP as an interactive output for debug information. I&#8217;d never touched HTTP before and didn&#8217;t realise what an amazingly easy and convenient interface it was for getting state information out of your game. Pretty much any platform that is ping-able and supports sockets interface can provide a HTTP interface for debugging information. So far I&#8217;ve used it on X360, PS3, PC and iOS devices.</div>
<div></div>
<div>For those of you who have no experience with HTTP GET protocol, I will go through a simple overview of the code involved. But before I do that, I&#8217;d like to show you exactly what this is all about and I think a short video is the quickest way to convey that information. So here is a small video of how I am currently using the interface for my iOS game magelore. This video shows the PC version running, but it works exactly the same running it on an iDevice or pretty much any other platform.</div>
<div><!--YouTube Error: bad URL entered--></div>
<h2>So what&#8217;s it good for?</h2>
<div>Some things I&#8217;ve used my HTTP interface for so far:</div>
<div>
<ul>
<li>profile information. Gives you somewhere to dump a copy of everything in the selected players profile at any given moment.</li>
<li>a script debugger. For our custom scripting language, it allowed you to put breakpoints into any live script and also see traces of recently run script commands and their results. It&#8217;s very satisfying being able to just connect to designer&#8217;s machines and see what scripts they are currently running and how many objects they have placed &#8211; especially if they are unaware you are doing it ;)</li>
<li>sorted and filtered general entity lists and entity details</li>
<li>screenshots. If you can get a screen shot into a recognised file format, like TGA or PNG,  then you can easily transfer it via HTTP.</li>
<li>server / client entity lists. For debugging network apps it&#8217;s great for looking at what all clients on the network are seeing.</li>
<li>download csv or log files. In my flight simulator work, I capture the entire history of all entities which can be downloaded via the debug interface to see what their velocities reached, turn rates, and what sensors where doing at any time.</li>
</ul>
</div>
<div>Other suggestions:</div>
<div>
<ul>
<li>Visual event tracker.  Its often useful for designers to capture game events like player movements, deaths, and kills for level tuning purposes. Why not generate images from this information at runtime and allow them to scrutinize a QA session while its in process. Or even open a couple of them at once if its a network game.</li>
<li><a title="A Fun Hack IPad To FPGA Data passing" href="http://altdevblogaday.com/2011/02/15/a-fun-hack-ipad-to-fpga-data-passing" target="_blank">Mike Acton&#8217;s FPGA (whatever the hell that is) interface</a></li>
</ul>
</div>
<h2>How to set it up</h2>
<div>Here is a very quick overview for one possible simple way of setting up the html interface. You could do a lot more elaborate interface with support for AJAX and generating java script if you want to really spend a lot of time on it. However, a very basic interface, like I present below, still gives you a lot of freedom and can be set up in an afternoon.</div>
<div>This is the code for Win32 sockets. Other platforms can differ slightly on how to set up non-blocking sockets, but are otherwise identical. Note that I&#8217;ve removed all error-checking for the purposes of keeping it readable for this article.</div>
<div>First we create a listener TCP IP socket. It will just be waiting for GET requests from any browser trying to connect to you.</div>
<pre escaped="true" lang="c++" line="1">  SOCKET m_listener;
  SOCKET m_connection;

  SOCKET listener = socket(PF_INET, SOCK_STREAM, 6);
  u_long nonBlocking = 1;
  ioctlsocket(listener, FIONBIO, &amp;nonBlocking);

  sockaddr_in myAddr;
  myAddr.sin_family = AF_INET;
  myAddr.sin_port = htons(portNmbr);
  myAddr.sin_addr.s_addr = INADDR_ANY;
  bind(listener, (sockaddr*)&amp;myAddr, sizeof(myAddr));
  listen(listener, 16);</pre>
<div>Too easy. Now we just need to accept connections and read the GET request. From the GET request we really just want the URL since all the information about what to display will be embedded in the URL as a path and as VALUE PAIRs.</div>
<pre escaped="true" lang="c++" line="1">  SOCKET m_connection;

  m_connection = accept(m_listener, 0, 0);
  if (m_connection != INVALID_SOCKET)
  {
    const int BUFSIZE = 8096;
    char buffer[BUFSIZE+1];
    int received = recv(connection, buffer, BUFSIZE, 0);
    if (received &gt; 0)
    {
      buffer[received] = 0; // null terminate the buffer
      ProcessHTTPSpaces(buffer);  // spaces may come in a %20 so convert these back to spaces
      char* url = (char*)strchr(buffer, ' '); // string is "METHOD URL " + lots of other stuff
      if (url)
      {
        url++[0] = 0; // null terminate the method, increment pointer to url
        char* pSpaceChar = (char*)strchr(url, ' ');
        if( pSpaceChar ) pSpaceChar[0] = 0; // null terminate after the second space to ignore extra stuff
        if( url[0] == '/' ) url++;
        HandleRequest(buffer, url);
      }
      CLOSE_SOCKET(m_connection);
    }
  }</pre>
<div>The HandleRequest method has now been passed 2 parts. The first parameter will either be &#8220;GET&#8221; or &#8220;POST&#8221;.  I only support &#8220;GET&#8221; currently.</div>
<div>This method will extract the arguments from the URL and put them into a handy arguments class. For example a typical URL request to example an entity might look like:</div>
<div>
<pre escaped="true" lang="c++" line="1">  http:\\127.0.0.1:1234\ExamineEntity?id=235422;verbose=true</pre>
</div>
<div>This is interpreted as the command &#8220;ExamineEntity&#8221;  with the arguments &#8220;id=235422&#8243; specifying which entity to examine and &#8220;verbose=true&#8221; specifying that we want the verbose version. Users of the system would register an &#8220;ExamineEntity&#8221; callback which would then appear on the main HTML page (or could be hidden if it should only be reached by an internal link).</div>
<pre escaped="true" lang="c++" line="1">  HTTPServer::Instance()-&gt;RegisterCallback(SZ("ExamineEntity"), SZ("Examine an entity"), &amp;HTTPCallback_ExamineEntity, 0);</pre>
<div>And so here is the code for HandleRequest. Again it has been simplified to keep this article to a wieldable length:</div>
<pre escaped="true" lang="c++" line="1">void HTTPServer::HandleRequest(const char* method, const char* url)
{
  // we only handle GET requests - may support POST in future
  if (!DMStringEqual(method, "GET"))
    return;

  // build the command and arg list
  DMString command = GrabCommand(url);

  DMHTTPArgList args;
  const char *pArg, *pValue;
  while (GrabValuePair(url, pArg, pValue))
  {
    args.push_back(HTTPArgument(pArg, pValue));
  }

  HTTPCallbackMap::iterator it = m_callbacks.find(command);
  if (it != m_callbacks.end())
  {
    it-&gt;second.callback(it-&gt;second.pUserData, command, args);
  }
  else
  {
    HTMLBuilder builder;
    builder.WriteLn("Unkown URL Command");
    SendResponse(builder.HTMLPage());
  }
}</pre>
<div>You&#8217;ll see the HTMLBuilder class in there. Your final output needs to be in HTML format so this class just enables you to do some simple logging and formatting without worrying about that aspect.  I think convenience is very important if you want all of your team to be able to get behind this debugging method and add their own HTML pages. I also have a helper class for the generation of sortable HTML tables, which I won&#8217;t go into now.</div>
<div>The final piece of the puzzle is the SendResponse method. This sends the HTML page back to your browser and is listed below. Note that this is hardcoding the type as text/html. You may want to customise this so you can handle other content types, but I&#8217;ve kept it simple for this article.</div>
<pre escaped="true" lang="c++" line="1">void HTTPServer::SendResponse(const char* pData, const char *pDataType)
{
  const char *pHeader = "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n";
  int dataSize = strlen(pData);
  send(m_connection, pHeader, strlen(pHeader), 0);
  send(m_connection, pData, dataSize, 0);
}</pre>
<div>So that&#8217;s basically it. You now have a bunch of game-side callbacks that get called whenever someone attempts to browse your ip address. The game callbacks just need to generate a HTML page by whatever method they like and pass it to &#8220;SendResponse&#8221;.</div>
<h2>Conclusion</h2>
<div>While I&#8217;ve explained my specific server callback implementation, the real purpose of the article was just to get you thinking about the idea of using HTML as a debugging interface to your application. It is simple, convenient, cross-platform, and gives you all the power of your browser for multiple windows, multiple applications without having to code your own net client. It&#8217;s now up to you to work interesting ways for it to help your project.</div>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/03/15/debugging-on-your-web-browser/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Tips for Managing Multiple Coordinate Systems</title>
		<link>http://www.altdevblogaday.com/2011/02/28/tips-for-managing-multiple-coordinate-systems/</link>
		<comments>http://www.altdevblogaday.com/2011/02/28/tips-for-managing-multiple-coordinate-systems/#comments</comments>
		<pubDate>Mon, 28 Feb 2011 23:32:53 +0000</pubDate>
		<dc:creator>James Podesta</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=1408</guid>
		<description><![CDATA[An article giving some suggestions for helping maintain your sanity when dealing with code that delves in and out of multiple coordinate systems.]]></description>
			<content:encoded><![CDATA[<p>Most programmers with any experience in 3D will have dealt with cartesian coordinates, in what we would call World Space. Graphics programmers will certainly have had a lot experience in homogeonous coordinates as well as View space and Screen space. Anyone dealing with animation or collision will have spent a lot of time in local space. All of these are different ways that a single absolute position in space can be represented. However, these are all taken at different stages in a pipeline and have very specific uses.  Where I find it can get quite complicated is if you have multiple co-ordinate systems at the same level which only serve to show the same absolute co-ordinates from a different mathematical perspective.</p>
<p>My latest contract has me working in flight simulator territory.  This now introduces geocentric coordinates as well as lon/lat/alt co-ordinates on top of the usualy world space which is the core of the rendering pipeline. Geocentric co-ordinates are basically a typical cartesian system (X,Y,Z) but where (0,0,0) represents the centre of the planet and the Y axis points to the North Pole. Orientation also has several representations in the application.  There is a geocentric representation which is the transform from the geocentric identity as well as the render world space orientation which is the more traditional &#8220;local to world&#8221; transform in 3d applications.   All these transformations have the potential to make any code very confusing indeed, as I soon discovered coming onto the project.  I spent the next few weeks researching the co-ordinate systems and coming up with some modifications to the code base to make it readable to myself and others.</p>
<h2>Understand the co-ordinate systems you will be working in</h2>
<p>The first thing you need to do is actually understand how the co-ordinate system works.  For positional systems, this means understand exactly what (0,0,0) represents  (assuming a 3 coordinate system of course). In some coordinate systems (0,0,0) might not represent a static position in space.  Be aware of what direction positive is on each of the coordinates.</p>
<p>Some coordinates may represent curves through space.  For instance, with lat/lon/alt coordinate systems,  lattitude lines curved around the earth. This is significant if you are comparing distances between points in one space to differences between the same points in another space.</p>
<p>Understand the scale of the coordinates. Hopefully most cartesian systems will be in metres, but I&#8217;ve seen a few in centimetres. For lat/lon/alt,  it is good to have a feel for how many metres a degree of longitude is.  I see this as part of the classic mantra of &#8220;know your data&#8221;.</p>
<p>For orientation systems, understand exactly what it means to give one of your game objects an identity orientation in this coordinate system. Which direction will it face. I like to visualize the x,y,z vectors of a matrix at identity and see in which direction each axis represents with respect to an identity oriented game object.  Understand what direction pitch, yaw and roll travel in. Understand what a cross product will give in this coordinate system.  It only takes a few experiments to get data on all these and its generally not safe to assume that the maths libraries will do exactly as you expect if you didn&#8217;t write them yourself.</p>
<h2>Understand what each coordinate systems strengths are</h2>
<p>Each coordinate system is there for a reason, so learn what that reason is.  If there is NO reason,  then you would shouldn&#8217;t be using that coordinate system and complicating your code unnecessarily.  For my project,  all our coordinate systems were mandatory due to other software we were interfacing with.</p>
<p>Each coordinate system is particularly good at certain maths, and weak at others.  Geocentric is a nice simple cartesian system in metres,  but the concept of &#8220;up&#8221; varies with your location so heightmap patches are expensive to apply.  Longitude/Lattitude/Altitude is convenient for heightmaps since &#8220;up&#8221; is represented by &#8220;altitude&#8221; and 0 is at the surface of the planet. It&#8217;s weaknesses are that it is in degrees (instead of metres) and the first 2 coordinates represent curved space making distance and angle calculations very inaccurate when the points are far apart.</p>
<h2>Write simple explicit conversion routines for going between coordinate systems</h2>
<p>Invent a unique string identifier for each coordinate system. This allows you to have consistent transformation functions between each space.  While implicit transformations would be convenient and easy to implement,  it is important for code readability to see clearly when data is transformed.  For my project I have the 3 systems I need to consistently transform between. Geocentric (geo),  Lon/Lat/Alt (LLA)  and Local Open GL coordinates  (Local).  When I came onto the project,  there was no consistent and easy way to transform between coordinates.   Some transformations used methods of a class, others used static functions and others were a composite of functions. Worse still, the naming of the methods had no obvious link to the concept that you where trying to transform from one space to another.</p>
<p>I&#8217;ve now wrapped all the various transformation methods with simple consistent helper functions.</p>
<pre escaped="true" lang="c++">vector3 PositionGeoToLocal( const vector3 &amp;vectorGeo )
vectorLLA PositionGeoToLLA( const vector3 &amp;vectorGeo )
vector3 PositionLLAToGeo( const vectorLLA &amp;vectorLLA )
vector3 PositionLLAToLocal( const vectorLLA &amp;vectorLLA )
vector3 PositionLocalToGeo( const vector3 &amp;vectorLocal )
vectorLLA PositionLocalToLLA( const vector3 &amp;vectorLocal )

quaternion OrientationGeoToLocal( const quaternion &amp;orientGeo )
quaternion OrientationLocalToGeo( const quaternion &amp;orientLocal )</pre>
<h2>Use a variable naming convention for your coordinates</h2>
<p>Since you may different coordinate systems interleaved through a single block of maths,  it can help with code readability to use a naming convention that identifies the coordinate system you are using. My prefered method is a small postfix on the variables,  but a prefix would work just as well.</p>
<p>Having different classes for each representation helps the compiler spot any misuse of variables but it doesn&#8217;t help the clarity of the code.</p>
<h2>Converting Velocities Safely</h2>
<p>Velocities and directions are a little trickier to convert since they can depend on what position they are taken from.  The simple trick here is to convert the current position, and calculate and convert the current position plus the velocity.  Then if you take a difference between those positions, you get the converted velocity.</p>
<pre escaped="true" lang="C++">vectorLLA positionLLA = PositionGeoToLLA( positionGeo )
vectorLLA velocityLLA = PositionGeoToLLA( positionGeo + velocityGeo ) - positionLLA;</pre>
<p>It important to realise here that applying the same velocity in LLA space will not give you the same results as applying it in a cartesian coordinate system.</p>
<h2>Other interesting uses of curved space</h2>
<p>Something I&#8217;ve done on a couple of projects now is to use a 2d coordinate system that represents curved space. When coordinates a transformd into their cartesian counterpart for rendering,  space is effectively warped giving you a more interesting world to move in. For instance, a simple old school 2d game can bend around 3d space without complicating the actual movement or physics maths since those are done as simple x,y maths in curved space.</p>
<p>On my current game, Magelore, I use a curved coordinate system to add some noise to what would have been a very square-edged tile system. All game code is just done in a simple x,y grid,  but when transforming from grid space to cartesian space, it all gets warped somewhat.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/02/28/tips-for-managing-multiple-coordinate-systems/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>A Technique for Applying Updates to Serialized Persistent Levels</title>
		<link>http://www.altdevblogaday.com/2011/02/13/a-technique-for-applying-updates-to-serialized-persistent-levels/</link>
		<comments>http://www.altdevblogaday.com/2011/02/13/a-technique-for-applying-updates-to-serialized-persistent-levels/#comments</comments>
		<pubDate>Sun, 13 Feb 2011 11:59:00 +0000</pubDate>
		<dc:creator>James Podesta</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/?p=486</guid>
		<description><![CDATA[<p>I&#8217;m currently working on an iPad RPG.  The game is level based,  where you have a world level from which you can enter several village levels. Those in turn may lead onto other dungeons or cellars.  So it was necessary to decide on a strategy for game saves. And as an iPad app, I knew I wanted to support adding new content to levels after the game was released, but in a way that would play friendly with the state of the levels players had already saved locally.</p>
<p><a href="http://www.altdevblogaday.com/2011/02/13/a-technique-for-applying-updates-to-serialized-persistent-levels/" class="more-link">Read more on A Technique for Applying Updates to Serialized Persistent Levels&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m currently working on an iPad RPG.  The game is level based,  where you have a world level from which you can enter several village levels. Those in turn may lead onto other dungeons or cellars.  So it was necessary to decide on a strategy for game saves. And as an iPad app, I knew I wanted to support adding new content to levels after the game was released, but in a way that would play friendly with the state of the levels players had already saved locally.</p>
<p><span id="more-486"></span></p>
<p>I figured binary serialization would be a good way to go as its fairly flexible and efficient.  If you haven&#8217;t used serializers before, there is a fair bit of information on it floating about. I won&#8217;t go deeply into serializing as it is outside the scope of this article. As a quick overview,  serializing a level involves iterating over all the live objects and having them write their variables to a stream.  To reload the level,  you can load the stream, and de-serialize the objects. Often the same code can work in both directions since it merely lists which variables need serializing.  Here is a quick example of serializing a door entity from my game.  Note the &amp; symbol (which I stole from Boost syntax)  means the variable is read or written depending on the mode of the stream, so the same code works as a read as well as a write.</p>
<pre><code>void Door::Serialize( DMSerializer &amp;stream )
{
  parent::Serialize(stream);

  stream &amp; m_isLocked &amp; m_isOpen;
}
</code></pre>
<p>So this is all fine and dandy.   The big problem comes after you have published your game and you now want to add new content to a level in the next version update.  In my original plan, I would load a level file on the first visit to a level, but on subsequent visits, I would just load the serialized version.  However, that meant that once a player had seen a level,  it would never look at the level file again. If I added new NPCs or new towns, the player would never see them unless they started a clean profile.</p>
<p>This is a problem I&#8217;d never come across in my years of doing console titles.  Generally in updates we had to add new levels or extra profile information,  but never modify a level that already existed in a savegame.  I tried designing around the problem by saying that levels would always reset on entering them,  but that meant that destructible objects would reset each time which was too big an exploit.</p>
<p>After a few days of considering options, I settled on the following solution.  But before you get bored reading a lot of text and code,  here is a video showing the final result of updating a saved level.</p>
<!--YouTube Error: bad URL entered-->
<div>
<div><strong>Every Entity Gets a Unique Integer ID</strong></div>
</div>
<p>Every entity gets a unique integer ID.   This is effectively a HANDLE for your entity.   Other entities can safely reference your entity by keeping a copy of this handle. This is useful for serialization since an entity may need to save a reference another entity. You can&#8217;t serialize a pointer, but you can serialize an integer. I was previously using weak pointers to entities, but after implementing unique ID handles, the weak pointers are no longer required and have been stripped out of the codebase.</p>
<p>All UIDs are registered in a table for a quick resolve. I use a simple array of entity pointers,  since I restrict the number of UIDs to 8192 so a 32k table can hold all known UIDs.  If an array is not viable, you could use a map or hashtable, but be aware the lookup time will be much worse.</p>
<p>UID -1 is considered an INVALID HANDLE.  This is important so you can tell if a UID no longer references any entity.<br />
Split your UIDs into 3 ranges.  There 3 distinctive types of entity for this system and they each need to be isolated so you can tell what type of entity it is by looking at the UID.</p>
<ol>
<li>Entities created in code that don&#8217;t appear in a level file,  such as the player.  These entities will be statically assigned a UID. For instance, my main character always gets UID 0.  These shall be called Global UIDs</li>
<li>Entites that exist in a level file. These will have their UID listed in the level file. The UID can never change and can never be resused in a future update. If an object is deleted from the level,  that UID should never be recycled.  These shall be called Static UIDs.</li>
<li>Dynamically created entities.  These do not exist in the level file but are spawned during the cause of gameplay. For instance, a spawner might spawn a giant rat. The spawner itself would be specified in the level file, so it is a type 2 entity.  The rat is spawned dyamically so it is a type 3 entity and will be assigned a dynamic UID from the range that has been reserved.  Code for allocating, freeing and resolving entities is posted below (edit &#8211; I have updated this code following responses to this article. Note that ths code is for demonstration purposes. You will want to add range checking assertions.).</li>
</ol>
<pre><code>u16 DMSceneManager::AllocDynamicUID( DMEntity *pNewEntity )
{
  u16 newUID = m_freeUIDs[ 0 ];
  m_freeUIDS[ 0 ] = m_freeUIDs[ --m_freeUIDCount ];
  m_entityArray[ newUID ] = pNewEntity;
  return newUID;
}

DMSceneManager::FreeDynamicUID( u16 uid )
{
  m_freeUIDs[ ++m_freeUIDCount ] = uid;
  m_entityArray[ uid ] = 0;
}

DMEntity *DMSceneManager::ResolveEntity( u16 uid )
{
  return m_entityArray[ uid ];
}
</code></pre>
<h3>Saving a level</h3>
<p>As we exit a level,  or just exit the app,  we will serialize the current level to disk.  I support multiple profile slots so each level is serialized to the file  &#8221;&lt;ProfileID&gt;_&lt;levelName&gt;.sav&#8221;.   All entities of type 2 and 3 get serialized.  Entities of Type 0 get serialized to the players profile file since they are effectively global and not bound to any level and should only be restored on the initial profile load.</p>
<pre><code>void DMSceneManager::Serialize(DMSerializer &amp;stream)
{
  DMEntity *pEntity = m_pEntityList;
  while (pEntity)
  {
    u16 uid = pEntity-&gt;UID();
    if (IsUIDStatic(uid) || IsUIDDynamic(uid))
    {
      stream &lt;&lt; UID();
      stream.StartBlock();
      stream &lt;&lt; GetTemplateName();
      pEntity-&gt;Serialize(stream);
      stream.EndBlock();
    }
    pEntity = pEntity-&gt;m_pNext;
  }
  stream &lt;&lt; INVALID_ENTITY_HANDLE;
}
</code></pre>
<h3>Loading a level</h3>
<p>As we enter a level,  we will throw out all entities of type 2 and 3 from above from the previous level.  They will have been serialized and will be restored if the player returns to the old level.  If we followed this approach correctly,  then before loading a level,  no entities of type 2 ad 3 should exist.   As we load the level file, we will be creating all the type 2 objects and giving them their UID numbers which will still match what they were last time the player was in this level.</p>
<p>Finally we deserialize the stream for this level. The UID is grabbed first and we check if an object exists with that UID.</p>
<ul>
<li>If the object exists,  then we serialize over the top.  This means serialize functions must cope with the object already being initialised.</li>
<li>If the object doesn&#8217;t exist,  but is a type 2 UID,  just ignore it.  This means it was a level file object but that object has been removed from the level.</li>
<li>If the object doesn&#8217;t exist, but is a type 3 UID,  then create it and deserialize it.</li>
</ul>
<pre><code>void DMSceneManager::Deserialize(DMSerializer &amp;stream)
{
  u16 uniqueID;
  stream &gt;&gt; uniqueID;

  while (uniqueID != INVALID_ENTITY_HANDLE)
  {
    stream.StartBlock(DMString());

    DMString templateName;
    stream &gt;&gt; templateName;

    DMEntity *pEntity = ResolveEntity(uniqueID);
    if (pEntity)
    {
      // this entity was created in the level file - just just serialize over the top of its current state
      pEntity-&gt;Serialize(stream);
    }
    else if (IsUIDDynamic(uniqueID))
    {
      // dynamic entity - doesn't primed by the TileMap so we need to create it...
      pEntity = (DMEntity *)DMObjectFactory::Get()-&gt;CreateObject(templateName);
      pEntity-&gt;SetUID(uniqueID);
      pEntity-&gt;Serialize(stream);
    }

    stream.EndBlock();   // skips to the end of the block if entity didn't get deserialized

    // get next unique ID
    stream &gt;&gt; uniqueID;
  }
}
</code></pre>
<h3>What does this system allow you to update?</h3>
<p>Doing this allows you to add and remove objects to an already serialized level.  This is essential for adding new content such as quest givers or opening new areas with doors or towns.</p>
<p>You can also update anything in the entities that isn&#8217;t serialized. That is, any data you assign via the level file, but will not dynamically change  during gameplay.  This can be scripts or blocks of data defining behaviour, such as wander paths or spawn areas. As an example, I have npc&#8217;s that give a short speech when spoken to. The speech is embedded in the level file.  Since this text will not change during gameplay, it is not serialized and any modifications to the level file will not be override by saved games.</p>
<p>Another point I don&#8217;t delve into is that a serialized level has a version number that can be checked when de-serializing.  This means if you modify the variables in an entity,  you can still provide a fall back serialization routine that converts the old stream into some sensible values under the new system.  This is also relevant to being able to provide updates to a title,  but is a fairly standard technique so I haven&#8217;t gone into it in any detail here.</p>
<h3>Final Questions</h3>
<p>How do you address the issue of saving your levels?  Are you having to deal with the same issue, but have come up with a difference solution?  Please post about it in the comments below. I&#8217;d love to read about how others have tackled this problem.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/02/13/a-technique-for-applying-updates-to-serialized-persistent-levels/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Rolling an iOS Game Engine Without Breaking the Bank</title>
		<link>http://www.altdevblogaday.com/2011/01/29/rolling-an-ios-game-engine-without-breaking-the-bank/</link>
		<comments>http://www.altdevblogaday.com/2011/01/29/rolling-an-ios-game-engine-without-breaking-the-bank/#comments</comments>
		<pubDate>Sat, 29 Jan 2011 17:32:00 +0000</pubDate>
		<dc:creator>James Podesta</dc:creator>
		
		<guid isPermaLink="false">http://altdevblogaday.org/2011/01/29/rolling-an-ios-game-engine-without-breaking-the-bank/</guid>
		<description><![CDATA[<p>There are a lot of great engines out there now with very reasonable prices. Unity and Unreal being the most well known. However, for small iPhone games it is still possible to roll your own engine without getting bogged down in endless months of development. Even with the adequate 3d power of the iPhone4 and iPad,  low-tech 2D games are still topping the charts and proving that a sole developer can still make a mark in the appstore.</p>
<p><a href="http://www.altdevblogaday.com/2011/01/29/rolling-an-ios-game-engine-without-breaking-the-bank/" class="more-link">Read more on Rolling an iOS Game Engine Without Breaking the Bank&#8230;</a></p>
]]></description>
			<content:encoded><![CDATA[<p>There are a lot of great engines out there now with very reasonable prices. Unity and Unreal being the most well known. However, for small iPhone games it is still possible to roll your own engine without getting bogged down in endless months of development. Even with the adequate 3d power of the iPhone4 and iPad,  low-tech 2D games are still topping the charts and proving that a sole developer can still make a mark in the appstore.</p>
<p>Making your own engine can be a great learning experience,  and gives you complete control over any performance bottlenecks and the ability to fix any bugs and implement any obscure features your game might need.</p>
<p><span id="more-269"></span></p>
<p>I’m currently developing an RPG called Magelore.  I am using my own engine for this, which I initially wrote with Daniel Krenn for Venger,  released under the Wretched Games label.  It has been used in 4 released apps, with Magelore to be the 5th.  The engine is simple and contains the minimum set of features to streamline iOS app development without any bells and whistles.  While Venger was 3D, our subsequent games have been 2D as well as Magelore which is all 2D.</p>
<p>The most important point worth noting, is that if you don&#8217;t want to get bogged down writing an engine for months and never getting onto the game part,  it is best not to get too obsessed with optimising the engine.  A typical iOS 2D app is generally fill rate limited,  so spending too much of your precious time optimisations engine components isn&#8217;t going to pay off in the short term.   Physics and collisions are the other likely bottleneck.  Unless you’re doing your own physics system,  there is not much you can improve here from the engine side.  You simply need to adjust your design and gameplay code so as not to need so too many expensive operations per frame.</p>
<p>I&#8217;ll now go through the minimum elements you need for an engine in order to get a game onto the AppStore.  I&#8217;ll go into some of these modules in much greater detail in future blogs.  This will need to be a very brief overview or the blog would be massive.</p>
<p><span style="font-size: large">Cross Platform</span></p>
<p>It can be a huge boon for development to make your engine cross platform, and really doesn&#8217;t cost a lot.  Our engine runs on PC also, which means we can use Visual Studio which as a much superior debugger to XCode. It also means we have access to mouse and keyboard for debugging shortcuts,  easy screen shots and frapping of videos.   The PC version has been set up so it will run in 320&#215;480,  640&#215;960 or 1024&#215;768 modes in both portrait and landscape modes.  This way I can test what the game will look like on any device by changing a commandline parameter.  Since you&#8217;re using OpenGL,  to make something cross platform you mainly just need to isolate a few minor modules &#8211;  startup, sound, textures, input, and minor discrepancies between OpenGL and OpenGLES.   Our objective C OSX files are restricted to the AppDelegate, the View class, the OpenGLRenderer1 and 2 classes, SoundEngine and the Texture class.</p>
<p><span style="font-size: large">C++ versus Objective C</span></p>
<p>My engine is completely C++.  The Objective C parts are restricted to the AppDelegate,  the EAGLView class and a small OpenGLRenderer1 and OpenGLRenderer2 class. Most importantly, this means the PC version shares 99% of the code with the iOS version.</p>
<p><span style="font-size: large">File System</span></p>
<p>On most games,  you can get by with just a ReadFile and a WriteFile method. Most games do not require streaming files, and its generally more efficient to read them in one chunk and process them in memory. I always use a flat filesystem with my games. This means every resource is accessed by just a unique filename with no path. This removes a lot of possibilities for human error when managing your assets since they can be moved anywhere and still work, and can never get mixed up.  I&#8217;ve used that technique for console games with 10 gigs of assets, so there&#8217;s no scaling issue once you have worked out good file naming standards.</p>
<p>Asynchronous loading is an optional extra that will give you some power to polish UI transition between levels, but its not essential in most games.  You sound system will probably need streaming for music,  but I have used middleware for sound  (namely Apple&#8217;s SoundEngine.cpp/h)  which handles its own threading and soundbank streaming.</p>
<p><span style="font-size: large">Data File Reader</span></p>
<p>You&#8217;ll want to data drive as much content as possible,  so you&#8217;ll need to pick a data file format and stick to that standard for all your data files. I use XML and have a smaller helper object that just manages construction and destruction of TinyXML documents.  Generally the runtime hit for loading and parsing your data will not be an issue,  but if it is it generally means you need to break up your XMLs into smaller parts so they don&#8217;t need to be loaded all at once.  Supporting Auto-Refresh is very useful for development here.  That is,  your class that reads an XML should continually check if the file has changed and reload it.  This is especially good for any system that needs rapid iteration like particle systems or combat balancing,  and saves you having to spend a lot of development time implementing an editor for those data files.</p>
<p><span style="font-size: large">Maths</span></p>
<p>Good maths support is essential in any game. Vectors, trigonometry wrappers, random number generators, interpolators,  and Min, Max, Clamp templates should be there. In a 3d game you&#8217;ll need matrix and quaternion support as well.  Code for any complex routines, like quaternion maths,  are easily found on the net so no need to be a maths genius to put together a good library of maths helpers. Depending on your game design,  you will generally not need to worry about low-level optimisations of your maths library.   When choosing your vector classes, be careful not to fall into the optimising trap. The readability difference between a optimised vector library that efficiently pipelines a vector math unit,  versus a simple operator overloaded type-safe vector library is massive. However the speed improvement you might get for that payout may be insignificant as maths were not your bottleneck.</p>
<p><span style="font-size: large">Containers</span></p>
<p>You need to provide a good set of stacks, lists, maps, hashtables. I&#8217;d recommend just using STL for this but keep an eye on your object file sizes.  A common trick to avoid code bloat is to use containers of pointers,  as generally compilers can share the same code for a  std::vector&lt;classA *&gt;  and  std::vector&lt;classB *&gt;.   The are some of other advantages to using a container of pointers, so its well worth looking into.</p>
<p><span style="font-size: large">Render Framework</span></p>
<p>Of course, you&#8217;ll need to be able to render graphics and some sort of render manager class can help co-ordinate sprite systems, material systems, and models and provide an extendable framework for adding new types of rendering primitives.   I have taken a layered approach to rendering.  The scene is split into a lot of layers and each layer holds a bunch of Render Jobs.   Each layer is given a view object which determines its camera and projection matrix, thus determining if it is a 2D or 3D layer.  You can specify a sorting mode for each layer.  Each render job is added with a priority value.  In a 3D layer, that priority might be the render objects centre Z co-ordinate and you can specify that this layer gets sorted.   Other layers can be left unsorted and so the order you add render jobs becomes the order they render.  This can be useful for UI.  You can also set render targets and capture targets for each layer.   A render target specifies that this layer will render to a specific texture,  instead of the back buffer.  A capture target specifies that a copy of the backbuffer will be taken when the layer is finished and stored in a specific texture.   In practice,  capture targets are quite slow on iOS, so you&#8217;re better off sticking with render targets only.   Note that this is really only used for special effects and so you can happily skip this feature for a simple iOS game.</p>
<p>Render Jobs are an extendable callback driven rendering system.  Any engine or game module can implement their own render job.  Examples of render jobs I support are Sprites, Fonts and Primitive Rendering.  The concept is system. You tell the engine that you are creating a rendering job on a specific layer and priority and supply it with a callback function.   The engine returns a pointer to the some raw memory you can use for your job data. Once you have filled as much memory as you require you tell the engine that you are done.  At the appropriate time in the Draw pass it will invoke your callback function, passing it your render job data. You can then access OpenGL directly to implement whatever kind of rendering you need.</p>
<p><span style="font-size: large">Materials and Textures Pipeline</span></p>
<p>You&#8217;ll certainly need textures.  Support for compressed textures (PVR) is also desirable but not essential .  In 2D artwork the compression artifacts can be quite noticable. They are really better suited for 3d object textures. I&#8217;ve restricted myself to just PNGs and PVRs so as to simplify the art requirements.  It&#8217;s fairly easy to support a range of textures through middleware, but it can be best to just stick to one format that does all your needs and not end up with massive bloats of code and inconsistent resources.   Materials are currently just a simple table of information detailing what texture they use, and what blend modes and render states to activate.</p>
<p><span style="font-size: large">Fonts</span></p>
<p>You&#8217;ll need to be able to render fonts.  I use AngelCode&#8217;s excellent BMFont  utility to convert any font into a PNG with a text data file.  Font renderers will need to support all justification modes,  and it is very handy to have a render-in-box method that will word wrap text into a box area. This comes in handy for drawing requesters.  I also like to have support embedded commands like change text colours or jumping to a tab position so you can easily syntax highlight messages without having to split it into font draw calls.</p>
<p><span style="font-size: large">Sprites</span></p>
<p>Sprites are your moving, animating elements in a 2D game,  though they can be used as billboards in a 3D game also. For sprites I use PSDs as my input source.  Each sprite animation frame comes in as a separate PSD layer and hotspots can also be defined through layers. Since I do all my art creation in photoshop, this is a convenient storage format. It may also be useful to support making a sprite out of lots of single png files &#8211; which would allow you to render something animated in</p>
<p>3dsMax and bring it quickly into the game.   I only support PSDs on the PC platform,  which then dumps out a binary sprite file with all sprites quad packed into large texture pages.  This sprite file is then used by the iOS device for its textures &#8211; which saves on load times and storage size on the iPhone, with the trade off that I need to run the game on the PC to generate data for the iOS version.</p>
<p><img src="http://altdevblogaday.com/wp-content/uploads/2011/01/woah-were-halfway-there-wo-oh-livin-on-a-prayer.jpg.scaled500-300x297.jpg" alt="" width="408" height="405" /></p>
<p><span style="font-size: large">Pa</span><span style="font-size: large">rti</span><span style="font-size: large">cle</span><span style="font-size: large"> System</span></p>
<p>At some point you&#8217;ll want some explosions or sparkles or some autonomous animating effect. For Magelore,  I use a simple envelope driven sprite manager with movement defined in an XML file. This gives me a very flexible system with minimal coding effort.  If your game is heavily focussed on retro pixel based effects where you need 100s or 1000s of points,  you may want to spend a lot of time here optimising for data cache access, vectorising the updates and reducing the dynamic memory accesses during the draws.  This can bog you down for a long time and needs many iterations of profiling and testing and very low-level knowledge of the memory pipeline for your hardware. However, for a lot of game styles you can get by with just a simple flexible generic system. Fillrate is probably going to be your biggest bottleneck with particle systems.</p>
<p><span style="font-size: large">Primitive Renderer</span></p>
<p>Being able to dynamically generate and render raw textured uv&#8217;d polygons is always useful for prototyping new effects or one off effects.  I prefer to put a wrapper over OpenGL to hide any minor OpenGLES discrepancies. It also bad for someone to touch the raw render states as your material pipeline will be unaware of these changes to state.</p>
<p><span style="font-size: large">Accelerometer Input</span></p>
<p>Many iOS games will need accelerometer input. This comes to your app via the accelerometer message so you can just provide your appDelegate as the delegate for that message,  and then wrap it up and send it to your C++ input module for everything else to access.  I put an adaptive smoothing over it so the values look smoother when rendered on screen but are still responsive to fast movement.</p>
<p><span style="font-size: large">UI System</span></p>
<p>My UI System is, in most respects like a standard windowing input system &#8211; frames that have area on screen and children.  It deviates in a few areas to be more useful in a multitouch with your fingers environment like iOS devices.   Frames can be oversized and overlap. Touches will go to the frame they are most inside.  Frames can also register for multitouch,  which means while held, all future touches are captured by that frame.  An example use might be a zoom icon. When you touch zoom you can use the second finger to pinch the screen in to control the zoom.   I still expose the raw touch list to the game if they want to do something very freestyle that doesn&#8217;t map to the simple concept of buttons.</p>
<p><span style="font-size: large">Serializer</span></p>
<p>One popular way to save games is via a serializer. Some important features for a serializer are:</p>
<p>•<span> </span>endian agnostic &#8211; always serialize bytes at a time so the endian of the platform doesn&#8217;t matter. Useful if you ever make a PS3 or X360 version of your game and want data compatibility.</p>
<p>•<span> </span>bit serializing &#8211; I like to include a method that lets you serialise an int to specified number of bits.  If you use the serializer for creating network packets, you&#8217;ll want to pack them as small as possible.</p>
<p>•<span> </span>version number &#8211; important for your future upgrade path so you can add new content to your objects.</p>
<p>•<span> </span>compression &#8211; supporting gzip compression is easy and fast.  If your posting large serializations to web servers,  any reduced bandwidth is a win.</p>
<p>•<span> </span>blocks &#8211; I support a StartBlock and EndBlock serializer command.  This inserts a size into the stream for you enabling you to skip whole blocks during deserialization if that object is no longer important to your game.</p>
<p>•<span> </span>ascii output &#8211; I include an ascii serializer  (write only)  for debugging purposes. When saving my games, I run the process a second time using an ascii serializer so if anything is going wrong I can easily see what data is causing it.</p>
<p><span style="font-size: large">Scripting</span></p>
<p>Scripting language is essential for data driven games. I use a custom scripting language in my engine. When taking an off-the-shelf language like Lua or GameMonkey,  just be sure you&#8217;re not going to run into performance and memory bottlenecks. A lot of existing script languages can eat up a considerable portion of your CPU just doing garbage collection.  My script language was meant purely to automate simple tasks and has no dynamic memory usage. It is meant to be used as high level control I can embed scripts like &#8220;open door;  delay 3;  close door&#8221; into any system.   Note that some scripting languages are not designed to handle a command like &#8220;delay 3&#8243; &#8211; one that stalls the script for 3 seconds &#8211; unless they are run as co-routines or threads,  which can add unwanted complexity.</p>
<p><span style="font-size: large">Physics</span></p>
<p>I&#8217;ve not used any physics systems in any of our released games and Magelore is no exception.  Venger used a simple collision system for ray collides and custom 3d movement routines.  For a 3d physics system I&#8217;d recommend looking at Bullet or Newton Physics.  For a 2d physics system its hard to go past Box2D.  Writing your own requires very strong mathematics skills and I&#8217;ve seen many failed attempts by good programmers.</p>
<p><span style="font-size: large">Sound</span></p>
<p>For iOS sound we&#8217;ve used SoundEngine.cpp which comes with Apples sample programs. It provides simple access to playing mono and stereo caf files, and for streaming m4a files.</p>
<p><span style="font-size: large">Video Playback</span></p>
<p>Often useful. Fortunately this is extremely easy to implement on iOS through Apples MPMoviePlayerController class. You just create one of this and add its view on top of your current view. You later get a callback when the video is complete.</p>
<p><span style="font-size: large">Debugging</span></p>
<p>It&#8217;s important to support a basic suite of Asserts, Errors and Logging. Lately I&#8217;ve taken to using HTTP debugging where you can listen on port 80 and deliver game information as HTML pages on HTTP GET requests. This is great for getting debug information from remote machines like someone QA&#8217;ing your game.  On my last project, which was very script heavy, I did a full debugger for my script system via the HTTP webpage. That turned out to be a great help to the designers,  and if they really got stuck, I could just browse to their X360 web page and see what was going wrong.</p>
<p><span style="font-size: large">Scene Manager and Entity System</span></p>
<p>You&#8217;ll need some kind of object framework. Something to keep track of all your objects and call Update and Draw methods.  I&#8217;m just using a old style fat entity system for simplicity. My scene management is a simple list of entities. I can get away with this because I generally only have objects alive if they are near being visible, and I don&#8217;t have too many live objects for it to become a bottleneck.  Venger was a tunnel shooter and so we were able to just create and destroy all objects as you progressed through the tunnel,  meaning all live objects where valid for Update</p>
<p>I try to keep my hierarchies as flat as possible.  If you&#8217;re ever finding that your hierarchies are getting deep,  it’s time to switch to a component system.  However, components come with some baggage since you have extra intra-entity communication, dependency and ordering issues to deal with. So there is still some advantages to keeping with a fat entity system,  especially if you already have one working and the alternative would be to scrap it and start all over again ;)</p>
<p><span style="font-size: large">All Done</span></p>
<p>Phew&#8230; Now that I have all that off my chest, I hope to write about more focussed topics in future blogs where I&#8217;ll be able to describe in better detail with pictures, code sample and videos how aspects of the game are implemented. Areas I have ear-marked for discussion include how content is generated,  applying updates to serialized levels,  script usage in xml content,  real-time lighting system, and so forth.</p>
<p>For information on the progress of Magelore, including pictures and video,  check out   <a href="http://magelore.blogspot.com">http://magelore.blogspot.com</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.altdevblogaday.com/2011/01/29/rolling-an-ios-game-engine-without-breaking-the-bank/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

