Coding
The Game Developer’s Bookshelf
by George on Jul.23, 2010, under Coding, Reviews
Obtaining a Fix
Some Great Books
The Art of Game Design : A Book of Lenses
by Jesse SchellBeginning iPhone 3 Development: Exploring the iPhone SDK
by Dave Mark and Jeff LaMarcheUser Interface Design for Programmers
by Joel SpolskyGame Engine Architecture
by Jason GregoryThe Pragmatic Programmer: From Journeyman to Master
by Andrew HuntMy Name is George
Tuning Your Game Made Easy
by George on Jul.09, 2010, under Coding, Game Design
Some days it’s hard to think of something to write about, and other days something just falls in your lap. Happily this week it was the latter. It all started with Miguel (as these things often do) – a.k.a. @mysterycoconut on Twitter – posting this article about connecting to an iDevice via telnet while running your App. Using this technique it becomes possible to rapidly tweak parameters on the fly or in fact do all sorts of crazy stuff.
Needless to say I jumped on this idea to aid in tuning my current game prototype. I’ve just reached the stage where rapid tweaking of variables is going to help focus and refine the game play. Miguel suggests hooking a Lua scripting engine into your code, but I thought it would be fun to create my own, plus most of my code is C++ (rather than Objective-C) and I’ve found binding Lua to C++ to be a fiddly process in the past.
The corresponding code for this article can be found here. Note that the DebugServer code comes from Miguel’s article, and the AsyncSocket code comes from here. I’ve added a minimal amount to Miguel’s code to pass received commands on to the DebugUtils functions found in Debug.[h|mm]. I haven’t had time to create a complete sample project, but the code provided should drop into any existing code base with minimal fuss. If the coding style looks a little strange, you may want to also read this and this.
So, let’s start at the end and work backwards, which I often find to be an effective technique. When tuning a game we spend a lot of time tweaking variables and constants – maximum speed, rate of fire, gravity, item prices, animation durations etc. Wouldn’t it be nice to open up a telnet session to your App and enter a command like “gravity = -8”? Alternatively, maybe there’s a set pattern of enemies that causes a rare bug. Wouldn’t it be nice to enter a “SetupWeirdEnemyPattern” command for easy testing?
So, we have two common scenarios – tweaking a variable and executing a function that alters the game state in a slightly more involved way. The code below allows us to do this. Variables and functions can be “registered” and given a name, which we can then use to adjust values or execute functions via our telnet connection. To make it simple to pass in parameters to these functions, we pass in a set of text parameters using argc and argv, just like the main() function of a C++ program.
Let’s have a look at the public interface to this code:
typedef bool (*DebugCommandFunc)(int argc, char *argv[]);
namespace DebugUtils
{
void Initialise();
bool ProcessCommand(const char *command);
bool RegisterCommand(const char *commandName, DebugCommandFunc commandFunc);
bool RegisterVariable(const char *variableName, bool *var);
bool RegisterVariable(const char *variableName, int *var);
bool RegisterVariable(const char *variableName, float *var);
}
Not much there, is there? The guts of it is in the ProcessCommand() function, where we pass in a string, and magic happens. Or, to provide an example:
bool ResetGameCommand(int argc, char *argv[])
{
// Do stuff here to reset the game state
}
DebugUtils::RegisterCommand(“ResetGame”, ResetGameCommand);
And later, through a telnet connection, we enter “ResetGame”, which in turn calls:
DebugUtils::ProcessCommand(“ResetGame”);
And, just like magic, we reset the game state.
Or as another example, we could register a game variable, say…
DebugUtils::RegisterVariable(“gold”, &gameState.pileOfDubloons);
And then, through the telnet connection, we can tweak this value mid-game, by entering:
“gold = 10000”, or “gold *= 2.0”
I’ve intentionally kept this system as simple as possible, but there’s a lot of power here. It’s very simple to register variables or add short pieces of code that can be run as needed. Just a few examples – turning on debug drawing to see bounding boxes of physics objects, changing the value of gravity or a jump pack’s thrust, loading an arbitrary level, turning off collision detection – the sky’s the limit.
The key thing here is to let you spend as much time as possible refining and tuning your game, because as Jesse Schell describes in his excellent book The Art of Game Design: A book of lenses:
The Rule of the Loop: The more times you test and improve your design, the better your game will be.
In other words, by removing the code-compile-run stage from tuning our game, we can create a better game in less time. Hopefully this code, combined with Miguel’s will provide a simple way to help you refine and debug your game. Happy tuning!
P.S. I was planning to include a description of how I used TDD (Test Driven Development), but figured this post was long enough. If it’s something you’re interested in though, leave a comment or drop me a note on Twitter (@GeorgeSealy) and I’ll put together an article.
P.P.S. Yes, there’s a few things that could be added to this code to make it even more useful. At the moment it’s not possible to pass a parameter that’s a string with spaces or new lines in it. To do this, you just extend the tokenizing code to respect quoted parameters like “This is a string”.
P.P.S. I’ve resisted the temptation to allow more complex calculations such as “percentComplete = 100 * itemsFound / totalItems”. Most of the time all you want to do is tweak values. If you need this much power, hook in Lua as Miguel suggests, don’t roll your own as it becomes increasingly difficult to maintain as a project matures.
P.P.P.S. I’ve also just realised one of the more useful things I’ve left out – if you just supply the name of a variable on its own, then the variable’s value should be either returned via telnet or printed out using NSLog or similar. There’s nothing worse than finding the perfect value for something and then being unable to see what it is!
P.P.P.P.S. The observant amongst you may have noticed that the link to Jesse Schell’s book is an Amazon Affiliate link, meaning if you follow that link and subsequently purchase something I may get a small commission. I will only ever put such links to books that I have bought myself or at least read cover to cover and would recommend.
The Things I Learn From Twitter Amaze Me
by George on Jul.02, 2010, under Coding
If you’re an iPhone Dev, and you’re not using Twitter, you really should be.
Whatever else Twitter may be, it is a wonderful, anarchic repository for random bits of incredibly useful information. A good habit to get into is marking useful tidbits as favourites so that you can come back to them later. (As an aside, the first person who comes up with an easy way to sync up favourites on Twitter, bookmarks from various browsers on different machines and favourites in Google’s RSS reader will do very well for themselves.)
In celebration of the randomness of twitter, here’s a few really handy iPhone-related tips I’ve picked up lately:
Managing double size graphics for the iPhone 4 (link)
With the release of the iPhone 4, developers now have the tricky problem of dealing with multiple resolutions. There seems to be a consensus amongst many iPhone devs that the best way to handle this is with 2 sets of graphics, one for each resolution. So this means you have to deal with two sets of filenames through out your code, right? Well actually no.
It turns out that when you call:
[UIImage imageNamed:@"myImage.png"]; (or contentsOfFile:)
on the iPhone 4, it will actually first attempt to load an image called myImage@2x.png first. So simply ensure that both sets of images have the same file names (with @2x added to the iPhone 4 set), and the Sdk will take care of things for you.
Update: It turns out that the ‘@’ symbol can cause havoc with Subversion (SVN). If you use SVN, you’d better read this before you start creating all those double resolution graphics. Once again, I learned this from Twitter also.
Clear the colour buffer for faster rendering (link via @majicDave)
Because of the way iOS handles OpenGL rendering, it’s possible to get a speed boost by ensuring you make a call to clear the colour buffer before rendering. This is actually faster than not making the call at all, which seems counter-intuitive. @majicDave reported a significant improvement in frame rate when he tried this.
Hot loading levels on the device (link)
If you have a chance, read @SnappyTouch’s article in Game Programming Gems 6 : Stay in the Game: Asset Hotloading for Fast Iteration. The idea is to allow assets (textures, levels, shaders, AI scripts etc) to be re-loaded in game.
By doing this, it becomes possible to rapidly tweak and refine your game without the need to recompile. One obvious benefit is that refining assets becomes far quicker without the necessary compile – and the faster you can iterate, the better your result will be. A second benefit is that it becomes possible for artists and designers to tinker with the look and game play of the App without needing to involve a programmer.
Hot loading assets on an iPhone / iPod is a little more involved, as we don’t get easy access to the device’s file system via another computer. Miguel’s article demonstrates a good way to do this. This was also the article that kicked off the idea of #iDevBlogADay.
Getting old firmware versions (link)
So you realize that you need to test an odd bug in OS 3.13 but you’ve just upgraded your testing device to OS 4.0? This tweet give you all you need to know to revert your device to an earlier OS version. Just remember to ensure you back up everything important!
There’s HOW many sizes of icons? (link)
‘Nuff said.
Tracking your day to day sales on the App Store? (link)
Admittedly Apple emailed all developers about this one, but I heard it first via Twitter.
How to handle special characters in URLs (link)
So you’re dealing with URLs and want to get rid of all those pesky escape characters like ‘%20’ (a space)? Don’t do this by hand, it’s messy, error prone and just not needed. Apple have given us stringByReplacingPercentEscapes to take care of this for us. This is the kind of thing that can be found in documentation if you know to look for it. Often a quick question asked on Twitter can gain valuable insight.
Physics calculations are tricky (link)
Fortunately there’s clever people out there who can help us avoid the most common errors. By fixing the time step at which you run your simulation, many problems can be avoided. Additionally, there can be many advantages to separating the render and simulation time steps. http://gafferongames.com provides a wealth of useful information here.
I’ve been surprised by Twitter, I was worried it was just another social networking Web 2.0 buzz annoyance, but I was lucky to find a vibrant, fun group of intelligent people with a common interest. If you’re not sure about Twitter, give it a go. I’m @GeorgeSealy, feel free to say hi – I promise to keep my tweets to mainly iPhone Dev related topics!
Trying Something New
by George on Jun.26, 2010, under Coding, Uncategorized
This site has been quiet for too long. That’s why I’ve got involved with the #iDevBlogADay initiative. There’s a bunch of great indie developers contributing as part of a regular roster. If you want to follow all of us just subscribe to this feed.
Any good programmer is always looking for new tools and ideas to improve the code they write and to become more productive. For myself, fifteen years after I began coding professionally, this is truer than ever.
So when Noel Llopis started dropping odd comments on Twitter about ‘no classes’, ‘plain old data structures’ and ‘no singletons’ I was intrigued. How did this work? Where did this style come from? Did it lead to simple, effective code? Was it a style that would work for me? Is it a style that will work for you?
If you haven’t already read Noel’s article from yesterday describing his current coding style, then go ahead and read it now.
Take your time, I’ll wait.
It’s definitely an unusual style, and flies in the face of ‘traditional’ wisdom. So what’s life like in a world without objects? Pretty cool, actually. I’ve been experimenting with it for the last couple of weeks, and here are a few observations that might encourage you to give this style a go.
The ‘Rules’
It’s hard to change style so dramatically, so a few rules of thumb are useful to help keep on track. This style is sufficiently different that it takes time to get your head around it. Prepare to spend some time writing (and re-writing) your first code this way.
- No classes.
- Use simple structs to store data / state information, making everything visible.
- Avoid dynamic memory allocation and pointers in general.
- Nothing is global – all data is passed as needed to functions that require it.
- Functions have a single purpose – for a given set of input data, generate an output, avoiding any side effects.
- Use TDD for everything.
TDD Becomes Much Easier
Test Driven Development (TDD) has always appealed to me, but to be honest my history with TDD is a bit like my attempts to build a model railway – plenty of well intentioned starts but no completed projects. Sooner or later I’d always give up on TDD because it just didn’t fit the way I’m used to coding.
But in a world of simple data and functions with a single purpose, TDD comes into it’s own. The tests you write drive the code to be as simple as possible with none of the cruft that typically accumulates in class definitions. And constructing tests is simple – create some simple test data, pass it into a function and check the resulting outputs. All tests follow this simple formula, with not a single pesky mock object in sight.
Lean Code And A Sense Of Progress
The resulting code feels resistant to bloat. Nothing is hidden, and every function has a clear purpose with no unexpected side effects. Time will tell if this pattern persists as the code matures. I’m constantly surprised by the way the code evolves down unexpected avenues.
Every test, every function has a purpose that is clearly defined. This simplicity has a huge appeal. A test and the code that goes with it can be written fairly quickly, and each additional test provides visible progress.
Struct Is The New Interface
I’m used to relying heavily on interfaces or abstract classes in my coding, and the lack of such an option concerned me somewhat. It still does – I miss the option to have a collection of ‘game objects’ and know that I can call Update() on all of them no matter what they are – Crates, Zombies or Flying Quesadillas.
What did surprise me was that rather than accumulating everything into a single class, the data naturally falls into a collection of several parts more in keeping with the idea of components in an OO system (composition over inheritance). For example, when I was writing a leaf particle system the resulting code combined the following bits of data – a mesh, an array of (generic) particles, an array of leaf specific particle data and a free-list for deleting and creating particles from a statically allocated array.
This fragmentation may seem unfortunate, but in fact it’s a strength. The functions that deal with a mesh are applicable to all meshes, not just rendering particles. The free-list struct and functions can be used anywhere that elements in an array need to be frequently created and destroyed. Where in an OO design you carry around an entire object to each method or function call, with this approach you only pass around the ‘part’ of the object that is directly relevant.
Coding Is Fun Again
Ultimately this is the most important point for me. I’m enjoying coding this way. Progress is rapid, and through the use of unit testing, progress is very visible. My free time for game programming is extremely limited, so the ability to write code in small, manageable chunks is a big win. Refactoring can be undertaken with confidence, knowing that the unit tests and the basic structure of the code give some protection against unintended side effects.
This style won’t suit everyone, and it will absolutely terrify the Architecture Astronauts, but if you’re interested then give it a go and let me know how you get on!
Some thoughts on writing cross-platform code
by George on Apr.25, 2010, under Coding
Regardless of whether you consider Apple to be Good or Evil (or perhaps just a business who wants to make money?), the latest changes to the iPhone Developers agreement make most developers wonder what their back up plan is.
One of our goals at Acorn Heroes has always been to keep our code as portable as possible. By doing this, if/when we find ourselves needing to move code over to another platform (for whatever reason), the process is not too cumbersome. As such, C++ makes a natural, portable choice, right?
Well, sorta. We write a collection of C++ code that we can carry over to, say, the PC. The problem here is that so much useful code for the iPhone ( loading images, accelerometer, touch screen, geo-location etc) is based in Objective-C. Objective-C code isn’t supported on many platforms at all. So despite being able to write hybrid C++/Obj-C code we’re pretty much screwed, right?
Not really. The key realization to make is that, on any platform, even if we use the same language, we’ll end up re-writing most of our code that interacts with the OS anyway – things like getting the system time, creating windows and loading files will always be specific to our chosen platform.
What we don’t want though, is for these platform changes to affect the rest of our code base. Here’s how it can be done:
Make all your header files pure C++.
It’s that simple. As an example, consider a class that wraps an OpenGL texture. We create an instance of this class, supplying the filename of the texture as a parameter to the constructor. The class may have enable / disable methods, and perhaps a few other bits and pieces like making the texture wrap, or perhaps looking up pixel data. The header here is pure C++.
The implementation however, is most likely to be heavily littered with Objective-C for things such as getting a system path to our data folder, loading the file and binding a PVRTC texture. And that’s OK.
So why is this such a great way to do things?
- We’ve implemented our code in a way that’s best suited for a given platform. It’s simpler to code and is probably more efficient or optimal than a generic, cross-platform solution.
- Our code isn’t littered with #ifdefs supplying different code paths for different operating systems.
- The bulk of our code, especially the all important game logic, is completely portable – at least as portable as any other language out there (yes Java, I’m looking at you).
- We haven’t wasted large amounts of effort writing a code base that can be cross-compiled for multiple platforms. Doing this needs to be tackled early in a project, meaning it sucks away our time at a stage when we should be concentrating on defining our game play.
- When we sell 1,000,000+ copies and have the urge to go cross-platform, we take the existing code base pull out a well defined set of implementation files and recode them for the new platform. Easy, and we would need to re-write that code anyway.
- Code your interfaces between files in straight C/C++.
- Write your game (as opposed to engine) code in C/C++.
- Write specific parts of your engine that touch the operating system in whatever way you like.
- Spend more time righting game code, and less time worrying about a cross-platform future that may never come to pass.
Dynamic Lighting Experiments
by George on Mar.19, 2010, under Coding
We’re currently prototyping some ideas for our next game. This time round we’re looking to do something fun with light and dark. Unfortunately the fixed OpenGL pipeline has a fairly standard look to it, and we can’t move to using shaders in OpenGL 2 without alienating a large number of people (including ourselves – our personal devices are both iPod Touches).
So as well as game play ideas, we’ve been prototyping the tech we’ll need to bring our world to life. The game will be 2d, but we really want to find a good way to render lights and shadows to create a dark, threatening experience.
After some Google-ing I found a good starting point over on GameDev.net. The basic idea is that each light is rendered into a buffer (the alpha buffer in this case), and then any shadows are rendered on top, blacking out the light. The alpha buffer is then combined with the scene geometry to add colour to the scene.
Fairly quickly I was able to get the basic algorithm up and running. The problem though is that each light requires rendering a screen’s worth of data, and frame rates drop drastically after adding more than 2 or 3 lights. So I started looking around for other options.
One idea that appealed was to render all the lights into a single buffer, and then use a single pass to lay this back over the scene. The problem here is that we can’t just render each light’s shadows into the buffer as black.
The answer here is to calculate the shadows for a light and incorporate them into the mesh used to render the light – i.e. instead of, say, a circular triangle fan for a light source, we generate a mesh for the circular fan minus the shadows.
So, after a few false starts I managed to get the basic algorithm working, and you can see its development in the screen shots on this page. The good news is that we can have large (double digit) numbers of lights in a scene, all casting shadows and all able to be moved or turned on and off dynamically each frame. Currently performance is about 45fps on a 2nd gen iPod Touch, but I’m fairly confident that can be drastically improved with some basic optimisation.
Once I’ve got the code properly under control, I’ll write an article covering the technique in some depth, if people are interested.
The last screen shot here shows the algorithm working at the moment. I still need to add spot lights rather than point light sources, but that should be a fairly simple thing to add. There’s a couple of bugs still to iron out too, but I think it proves the concept well enough to let us move onto prototyping other parts of the game. The addition of textures makes a huge difference too. While this is still very rough, I think there’s some real promise here, and can’t wait to start building the game that makes the most of it!
Rapid Prototyping Rule #9
by George on Nov.23, 2009, under Coding
Beg. Borrow. Steal.
Got an existing game, and you feel comfortable with the code? Take a copy, rip out the guts of it, and start prototyping. Need to perform a Fourier transform? Do a Google search and mash the code you find into your prototype. Know that a friend has solved a given problem before? Ask them if they can send you the relevant code.
So you’ve found some useful code, but it doesn’t represent vectors the same way you do? Don’t go through the borrowed code doing a search/replace – it’ll take too long and may introduce errors. Instead, simply convert vector data on the way in and out with a simple piece of wrapper code. Remember, CPU and memory are free.
Rapid prototyping is about getting results fast. Sometimes the fastest way to get a result is to use working code from somewhere else.
Rapid Prototyping Rule #8
by George on Oct.14, 2009, under Coding
Have a plan. Refer to it frequently. Update it as needed.
I don’t know how I managed to get to Rule #8 without mentioning this one before. If you’re going to spend, say, 1-5 days putting together a prototype, do yourself a favour and sit down with pen and paper and plan out what you want to do.
Writing tasks down and then ticking them off as you go is a powerful motivator. Keep it simple, a list of 5-10 tasks is fine. Try to make the tasks well defined and achievable in less than a couple of hours. Crossing items off a list is good for the soul, so make sure you can do it frequently!
Making a plan is great. Sticking to it is even better. But the real key to success is to revisit and refine a plan on a regular basis. Keep in mind your goal and add, delete or re-prioritise your list of tasks once or twice a day. And always, ask yourself “What’s the minimal set of things I can do to get the prototype working?”.
Rapid Prototyping Rule #7
by George on Oct.06, 2009, under Coding
Iteration is instant.
Thanks to Noel Llopis for this one. Anything that slows you down is your enemy. The faster you can iterate through the think – code – test cycle the more effective you’ll be. Complex / slow build steps (e.g. converting png images to PVRTC format), preprocessing data files and asset generation have no place here, it’s all about code turn around.
Rapid Prototyping Rule #6
by George on Oct.03, 2009, under Coding
Notepad and Photoshop make great level editors.
[edit] : See the comments below – there’s a good argument for not even going this far. Defining these things directly in code is a viable, and useful option.
One area where you often want a lot of flexibility, even during prototyping, is the ability to quickly tweak add a new elevator to the cafeteria level or make the slurpo-bot twice as fast. Text, XML or image files make great data file formats for this sort of prototyping.
There’s plenty of standard code out there for loading text configuration files, XML data or pixel values from images. And what’s more, your data is represented in a human readable form and comes with powerful tools for editing – including the IDE you are editing code in – how convenient is that?





