X48 2010

Posted in Code, Contest, XNA on March 8th, 2010 by Andrew

This year I again entered Microsoft’s X48 programming contest, taking the spot of a programmer who dropped out of  a group at the last minuet, this time around, Birmingham City University hosted the 27 hour long coding marathon.

Not being with my usual team that enters such events (veterans of last years X48, the Last.fm Hack Day and D24 (Derby Unis’ own, XNA contest)) was a good experience getting use to a different team dynamic very fast. I was the main coder of the team, as I’m in the final year and the other two programmers are in the second year, our artist was also a replacement, a poor soul dragged out of bed at half-7 in the morning after a mere 4 hours sleep to replace the original artist that had to drop out due to illness. Having had half our team replaced in the week before the event, we thought our team name was an obvious choice, ‘Plan B’ would work furiously with XNA to create the best game they could.

Each X48 even has a theme to code to, that is only revealed in the introduction talks at the even, this time around the theme was ‘discovery’ apparently chosen to be deliberately vague.

We had the advantage that one of the programmers in the team is more of a game designer than a programmer, so we came up with lots of ideas, all trying to get away from the obvious space-based gameplay.

Eventually we decided that you should play in a dream-world and be tasked with discovering this world you find yourself in, we thought that just having the player walking around didn’t sound like much of a game, so we had the idea to cover the world in a black fog, similar to the fog in RTS games (once you’ve revealed a place it stays revealed). This seemed like a half-decent game, but we thought that we were not making the most of the game mechanic, so we added a creature, aptly called ‘figment’, figment is the one that actually lights up the level, and usually hovers around the player as you make your way through the level. Figment also really loves berries, which the player has an infinite supply of (which is most likely what attracted figment to our hero in the first place) you can throw these berries, and figment will chase after them to eat them, lighting up the level as he/she/it goes (we never did decide on gender).

The one level we designed had a number of puzzles that made use of this mechanic (although unfortunately we didn’t have time to program most of them) sometimes you had to throw berries to light the way over a pit that would surely lead to doom, other times you would use them to send figment to help you in other ways, by pushing a switch or picking up a key that figment would keep hold of until you sent him off to unlock a door.

The technical aspect of programming the game provided a few challenges, pretty early on we settled on making it a tile-based game, being the fastest way to make a platforming game that we know of. At the last X48 we decided on a platformer too, I made the call to hand-make the level, which took 6 solid hours of staring at comma separated numbers, (I had foolishly decided that hand-editing would take less time than making a level-editor) this time, learning from the mistake, I set about making the level-editor as one of my first tasks.

It took about 5 hours to make, which isn’t too bad, it was made with artists/designers in mind, since the designer would be the one making the level this time around. The interface was a bit iffy, but you could switch from game-play mode to editor mode at the touch of a button, ‘paint’ on the tiles you desire and save with ease, then switch back to game-play mode to see how the new level played. This saved a huge amount of time, I lost count of how many iterations the level eventually went through, and it ended up being much bigger than we could have ever done by hand, not to mention that the tile-set was huge with our artist industriously cranking out over 60 different 32×32 tiles to make the game look really nice.

The darkness and revealing the map was taken care of by the other main programmer, not being familiar with shaders, she crafted a solution that used several black textures, and adjusted the alpha as figment passed by to get a very nice looking per-pixel effect (we had previously toyed with the idea of revealing a tile at a time, however, with 32×32 pixel tiles that seemed to us like it would be too harsh).

Unfortunately we didn’t win any of the top-three prizes, a very well deserved first place went to a game called ‘dot’ which asked the player to discover how to play the game in a variety of ingenious ways, we did, however, pick up the Innovation prize for our game, which I’m very happy with (and we won awesome kites).

You can find out more about what everyone at the event got up to (and see some of the other games) on the X48 Blog and Flikcr. Bring on next years X48!

XNABlackjack

Posted in Code, Portfolio, Uni, XNA on January 10th, 2010 by Andrew

This blackjack game, created using XNA was produced for the Network Programming module of the final year. It allows multiple players on the same network (sorry, no Internet play at the moment) to create or connect to a server. Once connected to a server players are able to chat to each other and challenge up to five other players to a game of (simplified) blackjack.

Game rules are simple, closest score to 21 without going over wins, blackjack beats anything, no five-card-trick etc. (Part of the assignement spec was that the game is secondary to the actual networking implementation). The first player to win 5 rounds wins the game.

XNABlackjack

A two-player game of blackjack in progress

The GUI is made with the Neoforce Controls library, a brilliant and free GUI library for XNA that supports both PC and 360 applications.

The networking code doesn’t use XNAs’ built-in networking code, as that was banned (for obvious reasons) but rather the sockets implementation for C#.

Both the Source and Executable are available.

Culling Demo

Posted in Code, DirectX, Portfolio, Uni on January 10th, 2010 by Andrew

This was the third of three mini-projects that comprised the practical part of the Advanced 3D Programming module for the final year, (and purposefully the easiest one of the three, to help spread the load across the year).

It is built upon Frank Lunas DirectX 9 framework. The demo starts by generating a terrain and placing 5000 trees randomly around the scene (Hence the large loading time) it then uses a variety of techniques to attempt to cull the most trees possible, hoping to increase the frame-rate (Not always  successfully).

Culling Demo

5000 randomly placed trees on a generated terrain

First on the optimising techniques is the classic octree, the terrain and trees are slit into nodes which are culled by the camera before rendering, which usually results in a large boost to frame-rate (which you can see by pressing the ‘T’ key to toggle between using the octree or ‘whole’ where the terrain is not split and the camera culling is not performed)

Next is occlusion culling, which is a bit of a double edged sword. Firstly all the trees bounding boxes are rendered to a texture, then, one by one the trees are rendered again, this time querying how many pixels were actually rendered, trees that do have some pixels rendered in that pass, then have their actual meshes rendered to the back-buffer. Due to the slowness of querying the graphics card to discover the number of pixels drawn for each tree, I actually use the result from a few frames back. The steps are as follows:

  • If the tree’s query is finished, start a new one and render the tree
  • If not, use the result from the last successful query

This works well as a optimisation when the scene is running at a high frame-rate, however at low frame-rates if you move the camera quickly you can see the ‘popping’ caused by the occlusion results being a few frames behind.

Even with that optimisation the occlusion culling is still slower than not using it, but implementing it was considered more of an academic exercise. (Toggle occlusion culling with the ‘O’ key)

Last up is LODding, when the tree mesh is loaded, I create several versions of the mesh with different numbers of faces and store them in an array, I then calculate the distance from each tree to the player and use this distance squared to choose a mesh so that trees near the player are rendered with the ‘normal’ mesh, and trees further away are rendered with the meshes that have less triangles.

Feel free to Download the executable.

Software Renderer

Posted in Code, Portfolio on January 8th, 2010 by Andrew

This software renderer started off as an assignment for uni, but I re-did it from scratch after finishing that year to show off as a portfolio piece (It’s just took a while for me to get around to uploading it to this version of the site). The code is really quite bad by my current standards (amazing the difference and year and a half makes) but it was a brilliant learning experience to be in total control of everything from loading the file to transforming the verts to finally drawing the polygons on the screen.

ACTRenderer

ACTRenderer

Currently the renderer features:

  • Several Drawing modes
    • Point
    • Wireframe
    • Flat Shaded
    • GDI+ Flat Shaded
    • Gouraud Shaded
    • Debug Texture
    • Textured
    • Textured Flat Lit
    • Texture Gouraud Lit
  • Support for animations
  • Should open any MD2 model and PCX texture
  • Ambient, Directional and Point light types
  • Supports ambient, diffuse and specular lighting
  • Several Effects
    • Negative
    • Static
    • Greyscale
    • Tint
    • Night-vision
    • Emboss
    • Colour Emboss
    • Blur

Download the Executable or Source (Warning, the source code is dire)

Squad Based Emergent Behaviour

Posted in Code, OpenGL, Portfolio, Uni on January 4th, 2010 by Andrew

For our AI Assignments we had to pick a paper describing an AI technique to recreate, this made for a really fun module with everyone doing different things, all of which were cool.

The paper I chose can be found in AI Game Programming Wisdom; Squad Tactics: Team AI and Emergent Behaviours by William van der Sterren. It involves squads of units that hold an internal knowledge representation of the world that is gathered both first-hand (From what they can see) and second-hand, using messages that are sent from the other squad members, this gives entities an imperfect knowledge of the world, leading to more realistic behaviour. Squad members, when moving, use a number of different weights to decide on the best spot to move to, all of which can be changed whilst the simulation is running.

The result is pretty cool, I think, although my implementation is lacking some features, the article talks about threats including grenades, however I didn’t have time to implement it, there’s also a few bugs, the entities sometimes go a bit crazy rotating a lot and sometimes they don’t face in the correct direction (Bugs that, regrettably I didn’t have time to fix) but you can still see the effect.

The assignment also requred some for of user input, so the demo includes the ability to edit levels and place units (Go easy on the number of walls and units, the line-of-sight checking is rather unoptimal)

So, after such a build-up, here’s a pic to wet your appitaite and a download link so you can try it out.

Squad Based Emergent Behaviour

Squad Based Emergent Behaviour

Download

D3DXCreateZombie

Posted in Uncategorized on November 30th, 2009 by Andrew

DirectX has utility functions for creating spheres and boxes and the like, but we thought that we would give developers something truely useful, so I present D3DXCreateZombie().

D3DXCreateZombie

Uses a left-handed coordinate system to create a mesh containing a zombie.

HRESULT D3DXCreateZombie(
    LPDIRECT3DDEVICE9 pDevice, 
    FLOAT DegredationLevel, 
    DWORD Type,
    LPD3DXMESH * ppMesh,
    LPD3DXBUFFER * ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device associated with the created sphere mesh.
DegredationLevel
[in] The level of degredation of the zombie, amount of flesh destroyed etc. This value should be in the range of 0.0f to 1.0f.
Type
[in] Combination of one or more flags, from the D3DXZOMBIE enumeration, specifying creation options for the mesh.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL, D3DXERR_INVALIDDATA, E_OUTOFMEMORY.

Remarks

The created zombie is centered at the origin, and its axis is aligned with the z-axis. It is also hungry for brains

This function creates a mesh with the D3DXMESH_MANAGED creation option and D3DFVF_XYZ | D3DFVF_NORMAL flexible vertex format (FVF).

Requirements

Header: Declared in D3dx9zombie.h.

Library: Use D3dx9.lib.

Event Driven FSMs

Posted in Code on October 11th, 2009 by Andrew

In AI this week we had to implement our own Finite State Machine, in the seminar before hand we talked about it and decided that the best approch, is a buffered event driven FSM, where FSMs listen for events that are generated, this gives us the advantages of event driven FSMs (Any class can interact, by the event, with any other class without even knowing if that other class exists etc) without the draw-backs (code being executed at a non-determinate time and order)

I decided to have a crack at implementing one myself, I’m not saying this is the best method for doing so, but it is a method.

What do we need? Well, we need an Event class, I’ll also use an EventType class to distinguish between instances of Events and types of Events, since FSMs will listen for events of a certain type, I’ll use an EventFactory to create the Events and EventTypes and an EventOccurance class to hold event occurrences. That’s good enough to be getting on with, so if you’re sitting comfortably, I’ll begin.

Firstly, registering a FSM (or sub-class) to listen for an EventType, for this, we’ll need to store a pointer to the FSM and a pointer to a member function on the said FSM, the first is easy, the second, not so.

Pointers to member functions can be problematic, we either can make the function static (which is a restraint I didn’t want to push on myself) or we need to know the type of class the function is a member on, the problem being we can’t cast, so a pointer to a function of the FSM class, has a different syntax to one on a DoorFSM class.

So how to store a list of these? Well for that we turn to Functors (anyone who knows functors or is afraid of templates, look away now)

I created a TemplateFunctor class, which has a ctor that takes a pointer to a class, and a function pointer to a function that’s a member of said class, the code looks like this:


template<class T, class U>
class TemplateFunctor
: public Functor
{
public:
TemplateFunctor(T* pObject, void(T::*pFunction)(U*))
{
m_pObject = pObject;
m_pFunction = pFunction;
}

virtual void operator()(void* pArg)
{
(*m_pObject.*m_pFunction)((U*)pArg);
}

private:
T*    m_pObject;
void (T::*m_pFunction)(U*);
};

As you can see, this templated class has two arguments, T is the type of class the member function belongs to, U is the type of the object passed as a parameter to the callback function, the overloaded function call operator just calls the function. The eagle-eyed of you will spot that it inherits from a bass class called Functor, this is so we can store a list of them, since every instance of this class could potentially have a different T value and thus, in reality be a different class type, we need a common parent so we can store pointers to them.

Ok, now we can store the information we need to register listeners, where will we keep this list? Well for me that’s on the EventType class, which is basically a black-magic way of doing RTTI (Runtime type identification), for this, we’ll need an EventFactory class, which you can see here:

class Empty{};
template<typename T, class P = Empty>
class EventFactory :
public P {
public:

virtual EventType* Type()
{
return TYPE;
}

EventFactory() : P()
{
}

~EventFactory()
{
}

static EventType* TYPE;

};
template </typename><typename T, class P> EventType* EventFactory<t , P>::TYPE = new EventType();

Ok, this template class also takes two parameters, T is the type of Event, P is that event types parent, which for most new classes will be Event, but defaults to the aptly named Empty.

The black magic here is the TYPE variable, which is public for good reason, it allows you to do DoorOpenEvent::TYPE to return a pointer to that classes type, the Type() method is virtual to allow an instance of a subclass of Event (DoorOpenEvent) to get a pointer to the right EventType (if you have an instance of DoorOpenEvent called pEvent, calling pEvent::TYPE would return the EventType for Event)

So why are we even creating an Event class to subclass from? I use it for the Dispatch method, which calls the Dispatch method on the EventType (By calling Type()->Dispatch()) but saves on some typing, you may also want to add other methods and state for all events to contain.

The function to register a listener is a templated function, and just creates a new TemplateFunctor with a pointer to a class and member function.

The Dispatch() method, this is pretty simple, all FSMs have an AddEventOccurance() method that takes an EventOccurance object, this is just a storage class that holds a pointer to the EventType of the event that occurred (so you can have a callback method that handles more than one type of event, and check which type of event it was by comparing that pointer to pointers returned by the TYPE variable of an Event subclass) a priority variable (just an int) and a void pointer for any other data (It’s assumed that the callback function will know what to cast that to to be useful). So all we need to do is iterate over all registered listeners, and add a new EventOccurence to them.

EventOccurances overload the less-than operator, this is used by the priority queue to sort it so that the highest priority event will be at the top.

Uni progress, week two

Posted in Uni on October 11th, 2009 by Andrew

On the third week of uni now, final year is where it all kicks off, year 2 was hard but was about getting you ready for placement, which it did wonderfully, final year is where you’re let off the leash with some really interesting projects to work with, so far these are:

Network Programming

Along-side ARP this is one of the modules that’s not CGP exclusive the assignment brief; implement a multi-player game over TCP/IP featuring a lobby with chat where players can challenge others to a game, minimum of 2 players per game however that’ll cap your grade at a C+ so the more the merrier. Add to that a dev-diary to chart your progress and a 1500 word report that’s given equal weight to the code (to help the non-coders get a leg in).

My game will be blackjack, a player can either start or join a server, servers broadcast to all possible clients, allowing a joining player to select which server they want to connect to, once they connect to the lobby they can chat to others connected to the same lobby and start a game (challenging others if they like) any player connected to a server can join any of the games available (provided the game isn’t full on players) and be dealt in next hand, when the game is over (after a set number of rounds) all players are returned to the lobby.

So far, progress is good, we can use any language we like as-long as it uses ports, so I’m using C# (mainly so I can use XNA to cut-down on time spend actually developing the game) I’ve chosen to go with UDP, since one you can get bonus marks for it and two to me it makes more sense for games (more up-to-date data is better than reliable data) I made the actual networking code as a library, so I could start testing it in a console app then move it over to the actual game without any fuss, I have a client and server done, a packet class with various read/write methods for shipping data back and fourth and a class to uniquely identify players. The plan is to have the server run a client as-well, so no extra code needs to be done for that to happen.

AI

A topic close to my heart, this module promised to be really interesting and so far, it’s not disappointed. Assignment is not out yet but if it’s the same as last year, we all pick an area to focus on and implement that to a high standard, this year we’re using the LightSpeed engine, the third incharnation of the Gamebryo engine from Emergent, which is focused on rapid development and promises to be awesome (one we get the bugs out of running it). So far we’ve  looked at finite state machines, and implemented our own. This module has a seminar rather than a lecture, where we all throw ideas around about the different ways to achieve certain things.

Implementing an FSM is something I’ve done before, so I decided to go one step further this time and go for a more sophisticated design, it’s main point is that it’s event-based, but events are dumped in a priority queue ordered by a priority value set when the event is dispatched (although it can be overridden for fixed priority events, before the state is updated, the one at the top of the queue is run, invoking the callback function associated with it, this avoids the special hell that usually plagues event-based code of code being ran at bad times and in a non-determinable order.

I’ve implemented this in a static-library, which I hope to build-up each week into something nice for the portfolio (a year of working at Strawdog has taught me to love static libraries).

Advanced 3D Graphics (A3D)

One of the ‘hardcore’ modules this year (the other being AI) this year it’s different from last year; teams of two will complete 3 mini-projects on one of a list of subjects (one per group) thankfully it was pre-arranged that me and Chris (who happens to know a fair bit about shaders) would team up. Our first project is NPR (non photo-realistic rendering) and progress goes well, Chris found a paper on a really cool water-colour shader to make everything look painted and is busy implementing that, I’m doing a cell-shader and then working on getting it running in a DirectX framework (since we’re working in Render Monkey at the moment)

This looks like it’ll be a challenging module for me, having done no previous shader work, but a good partner helps a lot and it’s something that I’m developing more and more interesting in as I work on it.

ARP (aka ‘The Dissertation’)

That should really do with some dramatic music, this year-long module is the cornerstone of our final year grade (and since the final year is worth 80% of the mark for the degree, it’s the main component for that too).

For this module you have to have a mentor to guide you through, a tutor can take a minimum of 5 students, and given the extra work involved for each one, that’s about all most of them take, and whilst we’ve got access to any tutor on the School of buisiness and computing (the area of the uni our course falls under) having one of the specialist CGP tutors is a plus, but there’s only three of them and twenty-two students this year (more than expected) so 7 will have to look else-where for a mentor.

Originally I had chosen Dynamic Difficulty in Games, a topic suggested by the course leader, John Sear. However places for him were filling up fast, and he didn’t seem to enthused by the idea, so I decided to look else where, I handed that proposal to Adam Thornett, our A3D tutor, but then e-mailed him saying that I was willing to change the topic to one more in his area of expertise if that helped, he said it would so I wrote a proposal for a study on Art-pipelines, after a talk on this subject, we decided that coming up with a decent project on it would be hard, and not very interesting to boot.

Adam mentioned that you can get marks for a code-implementation along side a report for this year, so it’s not a waste to pick a code-heavy project he also listed a few ideas he would consider fun and I tended to agree with him on most of them.

After all that, my chosen topic is ‘Alternative Input Methods for Games’ looking at all the different ways we can get the player to interact with a game, for the first part, I will take an open-source game and change it’s input method to a variety of different ones, and see how they play, currently the list of input methods include a dance-mat, webcam, 3D mice and Wiimote. I will then make my own game, and look to combine several of them to make a challenging and immersive game. It seems a fun project (not-least the fun I’ll have watching people run around on a dance-mat) but still mostly half-formed ideas at the moment.

So that’s a run-down of what this year holds, work is tough but manageable, the years placement has benefited me no-end making me a much better coder and worker, but mostly this year should be fun, all the modules hold the possibility to be really interesting and I’m really looking forward to getting stuck in with my ARP. Hopefully I’ll still be this enthusiastic come Christmas time.

Lessons I’ve learned from working in the games industry

Posted in Articles on September 3rd, 2009 by Andrew

I’m coming to the end of my year and a bit placement, so I thought I’d mention a few of the more important things I’ve learned in my time at Strawdog Studios.

You’re not expected to know everything.

You will be asked to do things that you have never done before, admitting you don’t know how to do it is not only perfectly fine, it’s also a very good idea as it will help your manager to more accurately estimate the time said task will take you. Learning how to do something is an important skill to have, some-things can’t be found with a quick google search (sacrilege I know) sometimes you will spend hours, days even researching techniques and planning out how you’ll tackle a certain problem.

There’s no such word as can’t.

More childhood advise come back to haunt me. Simply put, you should, given enough time and resources, be able to write code to do almost anything. Often, things that seem impossible turn out not to be, if you just approach them from a slightly different angle. For example you may be working on limited hardware which just doesn’t have the power to render an effect properly, there’s always a way you can fake the effect when you need to, a lot of games programming ends up being black-magic smoke and mirrors thanks to the demands of having to run at 60 or 30 fps.

Don’t get attached to your code.

You are not the code you write, I’ll say it again, you are not the code you write. Code will need to be changed, sometimes your first attempt misses something you later find out, sometimes you’ll discover something that means you have to change code, sometimes the design will change and the problem the code was solving doesn’t exist any more. You can’t take these things personally, everyone has bad days where they write code that on reflection is terrible, learn from the mistakes you make and accept that any code you write may end up never being used.

Sometimes the job will be soul destroying

Personally, I think working in the games industry is the best job in the world, it’s challenging, you get to work with a bunch of fun people who really know there stuff, you get to bring ideas to life, plus everyone else thinks your job is really cool. But sometimes, like any job, there are bad days, days when you spend 8 hours tracking down some small little bug, days when things just don’t work, no matter what you try. I’ve spent days tracking down bugs that only appear in release builds deployed to the device, debugging by displaying a square on screen that changes colour depending on where the code is. These days happen, and you have to power through them, try to relish the challenge and if you can’t, think of it as paying for all the awesome days.

Stand on the shoulders of giants.

Programmers hate to re-invent the wheel, thankfully these days it’s easy to find code snippets to draw on. Most challenges you come across will have been solved before, and probably by people with more resources and expertise than you. It’s important to know that (licences permitting) it’s ok to use these resources, provided of course, that you take the time to understand what the code is doing and how it’s doing it, if you jump ahead and just copy and paste it, the time you save you’ll pay back several times over when it breaks and you have to debug it.

Keep a notebook and pen handy.

This one might not be the same for everyone, but a lot of programmers I know (myself included) swear by it. Sometimes, in order to work out a problem, you need to step back, away from the restraints of the computer and write something down, or make a drawing to plan out your approach, in the course of my years placement I’ve filled at-least 3 notebooks and numerous sheets of paper with plans, sketches and equations that are not only helpful at the time, but are good to look back over if you need to fix previously written code, can you remember what you were thinking 2-3 months ago? No, me either.

Ask for help when you need it.

No-one will think bad of you for it, most programmers like explaining things, and as stated previously, you’re not expected to know everything. Books and internet resources are useful, but nothing can replace talking to someone who knows what they’re on about, or running a theory past someone else to get a different angle, and remember, someday you’ll be the person with the expert knowledge in some area with someone asking you for advice.

Learn when to stop.

When I was at uni, pretty much all I did all day every day was code, any time I wasn’t coding, I was thinking about it. This had it’s up-sides, uni is hard, and there’s a lot of work to be done, so there’s not much room for down-time anyway. But at work, it’s different, true the work is hard, and there’s still lots of it but you’re there for longer, day-in and day-out, you have to be able to switch off sometimes, enjoy time away from programming, away from a computer in general if you can. I think that working at Strawdog studios really helped me learn this lesson, unlike other studios we rarely do over-time and everyone understands the need to have down-time, otherwise you’ll just end up burning out, your fun job will turn into a chore and that’s just no way to live your life.

Obviously everyone will have different experiences when it comes time to work in the industry, but hopefully these will help some of you just starting out adjust better, and maybe make the experience a little less daunting. If you feel I’ve missed an important lesson you learned please leave a comment.