Christian Vucossa programming blog

game programming, daily troubles and solutions

Archive for the ‘game programming’ Category

S.A.D.: a space project

Posted by Christian on June 20, 2009

Just a couple of screenshot from my latest project, S.A.D. (Seek And Destroy), a 3D shooter in which you are a rookie that have to shoot down the vicious spy-satellites of an unknow alien force.

This is the first time I face moving free across an empty 3d space… it’s not as simple as it sounds!

But, well, here are the pictures:

Models are self made and these are also my really first non-cube models! I used Blender for them, but I have not textured and also lights are turn off, so I render them as wireframe (for the player ship) or plain solid (the sat and the terrain).

I’m also using FTGL for the text rendering, I found it very simple and immediate (and pretty fast).

a spy sat in sight

a spy sat in sight

Posted in game programming | Tagged: | Leave a Comment »

Finite State Machine: a C++ implementation

Posted by Christian on May 29, 2009

For those who don’t know what a FSM is, here is a summary.

I think FSM are well used in game development, from purposes like AI to game state management.

You know, you have to deal with splash screens, menus, dialogs and so forth, and you need a way to decide what to put on screen at each loop. You can arrange your code into the BUS (aka Big Ugly Switch) and check for a state flag. This works, and I used it many times. Sure, it is not beauty nor elegant (after all, it’s Big and Ugly!) and, if you plan to add features (states) later, you must put other case statement. It is Big because it grows fast.

But there is another way to do the same. If you model your software in a sequence of states, each of them can receive input and generate output, and something catch this output and put on the field another appropriate state which can continue the work, well, you have an OO solution to your problem. Which means that it’s elegant. Which means that you can speak of it with your friends. Which is cool. Well, which is not the Big Ugly Switch…

FSM are this solution. I implemented a really basic version in C++. I have two classes:

  1. FSMState, which is a single state in my machine
  2. FSMManager, which handle the states and make them work together.

In addition, I put a couple of enums which are application-related… you can get rid of them and use simple int values.

So, here are my definitions (fsm.h)

class FSMManager;

enum RawInputType
{
RIT_ESC, RIT_SPACE, RIT_AKEY
};

enum HighInputType
{
HIT_IDLE=0, HIT_EXIT_GAME, HIT_SKIP_SPLASH
};

enum StateId
{
// application states
SID_IDLE=0, SID_SPLASH, SID_MENU, SID_BRIEFING, SID_PLAY, SID_PAUSE,
SID_EXIT, SID_QUIT
};

class FSMState
{
friend class FSMManager;

public:
FSMState(int iId);

// methods to program the state
void addInputPair(RawInputType, HighInputType);
void addTransition(HighInputType, int);

// run the execution
virtual void run();

protected:
void sendInput(RawInputType);
int getOutput();

private:
int m_iId;
HighInputType m_lastInput;
std::map<RawInputType, HighInputType> m_inputTable;
std::map<HighInputType, int> m_transitionTable;

};

class FSMManager
{
public:
FSMManager();

void addState(FSMState*, bool current = false);
void sendInput(RawInputType);
FSMState* getCurrentState();

private:
std::map<int, FSMState*> m_stateTable;
FSMState* m_pCurrentState;
};

The RawInpuType and HighInputType enums are filled with some sample values. The first maps a physical input, such the ESC key press. The second maps a logic input, application-related, such as “Player want to exit”.

FSMState has three public methods, one of them virtual:

  1. addInputPair simply maps physical inputs with logic inputs, in a way that is coherent with the state logic (ESC key may means “Exit from game” in the menu screen, but may means “Go to menu” while playing).
  2. addTransition maps the relative state to which go after a logic input is triggered. Each state has an ID which identify it (in this case it follows the StateId enums, but I used an int cause I plan to use this design to implement some AI too).
  3. run is virtual because real states will inherit from this class and reimplement. For test purposes I left it virtual and not pure virtual, but you can think of it as a pure virtual if you want.

The FSMManager class has a collection of states (pushed in via the addState method), but only one of them is the current state. Current state receive the raw input (which comes from another component, not present in this design) and produces an output (a new state if there is a transition, or itself) which updates the current state itself. This way a single input catching routine can pass the input through the FSMManager to the actual state, which has been programmed to give a result and maybe do a transition. At every loop the run method is called for the current state, which can perform drawings or just some logic (update of other object’s state or… what else you need).

Implementation of these methods are quite straight and boring. I put only the sendInput of the FSMManager, which actually performs the inner state transition:

void FSMManager::sendInput(RawInputType raw)
{
if(m_pCurrentState != 0)
{
m_pCurrentState->sendInput(raw);

int output = m_pCurrentState->getOutput();
map<int, FSMState*>::iterator imap = m_stateTable.find(output);
if(imap != m_stateTable.end())
{
m_pCurrentState = imap->second;
}
else
{
// no state change
}
}
}

That’s all, bye.

Posted in game programming | Tagged: , | Leave a Comment »

Death and rebirth: my own roguelike reloaded

Posted by Christian on February 11, 2009

Hi there! Time to spend some words on what my Xarr project has been.

Project is dead, but it was not a death without a sense. It teached me a lot on OpenGL, but my goal was to make a roguelike, and so I switched to the classic ASCII style, embracing the *curses libraries, because graphic issues was becoming overwhelming and my interests was in the game not in the graphics mechanics this time.

Xarr is ended with my @ wandering in a maze and with a couple of S randomly moving all around. Good enough to end a demo.

The new project is something more… mature. Its codename is Dunia. I have a couple of great ideas, but I don’t want to tell about them now because of the fear of can’t accomplish them.

Up to now, Dunia comes with a @ exploring a loaded map. I said “exploring”, not “wandering”, because a field of view algorithm has been implemented, as written here.

Also, a “look” command has been implemented, as well as a “grab” command, a “drop” command and a “view inventory” one.

Oh, and there is also an “open” command! @ can move in all directions and collisions are rightfully detected.

The map features plain walkable squares, walls, doors (opened and closed) and furnitures. I defined “furnitures” all the items the player cannot grab, such as statues, but that are sensible to the look command. A nice feature a suppose.

By now I have only one kind of item: food. What else?!?

The look command in action

The look command in action


The inventory screen and the drop command

The inventory screen and the drop command

Posted in game programming | Tagged: | Leave a Comment »

Line of Sight algorithm: Bresenham

Posted by Christian on January 20, 2009

While I was working at my roguelike I faced the issue of what player can see.

This issue is known as Field of View. In a roguelike, player lives in a grid-world. His field of view are the tile he can see all around, given a certain range (influenced tipically by lighting). One of the possible methods to resolve this is using a line of sight algorithm, usefull also in other circumstances.

The plot is simple. Can player see from his position A to position B? If a rect line can be traced from A to B without passing through an obstruction (wall or whatever) he can.

Calling this for every end point of the area around the player results in the field of view. Sound simple, but it’s a bit tricky to implement.

I started with a couple of implementation of mine, based on the rect-between-two-points equation, that sounds like this:

(y – y0)(x1 – x0) = (x – x0)(y1 – y0)

and I reached a quite good result. In my game, player has a sight of 6, which means he can see at 6 cells, or tiles, around him. With this, almost the full area was correctly filled but some cells did not obey rightly.

After a bit of headache I opted for google and found this nice article on Bresenham line drawing alg.

Copy/paste on my routine, made some little edit and the result is pretty good. If you are looking for a line of sight algorithm I suggest it. It worked for me.

Bye.

Posted in game programming | Tagged: , , , | 1 Comment »

My Own Roguelike Part 3: Loading/Saving

Posted by Christian on January 1, 2009

I made some progress and archived part 2. Now the camera follow player in a correct way (thanx Tristam! :) ) and I haven’t the blinking problem yet. I’ve added a “tell me what I’m doing” feature to the message handling component, so that now a green writing serves as narrating voice at every action the player performs (walking, up to now). Collision detection with walls is also active, and a “Ouch!” message appears when it happens.

I positioned the camera higher and more distant, in order to haven’t to rotate the view to see the hero when a wall is between.

Now I have to make the loading/saving routines. I already made a load function that loads a map of arbitrary dimension and it works great. Screenshot shows this feature in a 15×21 map.

I’m very excited because, after the save method, I will enter in the real domain of the project: monsters and interaction! Bye!

the load map feature

the load map feature

Posted in game programming | Tagged: | Leave a Comment »

My Own Roguelike: part 2

Posted by Christian on December 22, 2008

A little update on development of my roguelike.

A first attempt in creating the floor

A first attempt in creating the floor

In Part 2 I have to deal with the map. First, I started drawing something under my character. I defined my map as the most simple thing: a matrix of uint. I implemented the matrix not as array of arrays but as vector of vectors, using the plain good old STL. After that, I have filled my matrix with 0s and then, in the draw() method, drawed a red square of given width cicling my matrix.

Next, I opened blender and modeled a cube (well, it was pretty easy since a cube is the default mesh as you open blender…). After a bit of UV mapping a texture was applied to my cube.

I decided to maintain the old tile method, but using 3D tiles instead of 2D ones, and so a cube in place of a square. Quite straight, isn’t it? :)

So I went up with my textured cube. I placed some 1s on my matrix and coded a routine that draws the cube in the right position according to the position of 1 on the matrix.

first blocks of terrain in my world. @ is not alone now!

first blocks of terrain in my world. @ is not alone now!

Ok, shame on me for my graphic skills in doing the texture, but it works. Ah, I also coded the routine to load texture and UV coords from .X files. If someone need of it… maybe I’ll do a post for it.

It’s been a little issue to define a unit of measure in order to make all the same size: the @’s steps and the tiles I mean. In the end I calculated the minx and maxx for the blocks and it gave me their length. After a bit of attempts I came with a correct @ position and step.

Next, It was the time to apply a texture to the floor. Not only: the floor has become made of tiles too. I modeled a simple little plane, scaled it as the blocks and textured. Now, when processing the matrix values I place a floor tile for 0s and a block tile for 1s.

To make possible exploring the map I wrote a routine for the camera to follow the @. But here I have a question: I used the gluLookAt, but in order to appreciate changes I have to switch everytime to projection matrix and call glLoadIdentity on it. This give me an annoying blink effect I would like to avoid, but at the moment I don’t know how.

an entire level textured

an entire level textured

Next, to complete step 2, I have to deal with wall collision detection, but this is very simple. Since it’s turn based and movements are steps of predefined lenghts, I can simply use the 2D method: look at the terrain matrix and its 0s or 1s values. I think I’ll do a little refactor after that, ’cause my code is becoming messy in some points.

Posted in game programming | Tagged: , | 2 Comments »

My Own Roguelike: part 1

Posted by Christian on December 20, 2008

So I decided to write my own roguelike.

Fine. In this article on roguelikedevelopment.com I found an interesting starting point.

The author lists 15 steps to develop this type of game. Shortly:

  1. Decide to write a game
  2. Hello World!
  3. It’s a boy!
  4. The map
  5. Saving/Loading
  6. It’s alive! Alive!
  7. Interaction
  8. Data files
  9. Items
  10. Magic
  11. Simple game
  12. Levels
  13. Experience
  14. Citizens
  15. Free at last

Step 1 is rather easy and yet completed. My roguelike will be something about a bad guy named Xarr hidden in the deeper level of his ultra deeper dungeon, the Kingdom of Evil.., and a good guy must reach and defeat him. Sounds original, uh? :)

Step 2 is quite simple too. I opened my code::blocks, created a new project and imported libraries from Pong to create an OpenGL graphic context with SDL and manage some basic input. Compile, run et voila, my Hello World works without surprises.

Step 3 is the first real milestone. I have to display something on screen, and this something is no less than the player. Yes, the good guy of my plot. The hero. Well, in most modern games this will require a beautiful textured mesh, but in Roguelikes the hero is simply a @, which really simplify life. But, as said in previous post, I want to make this game something between classic ASCII roguelike and modern 3D RPG. So I opened Blender, modeled a @ and exported. Now I have my beauty 3D version of the hero.

Author of the article seems to follow a XP way, because he repeat more than one time to not troubles about planning everything or write the best code from the beginning. Implement only what serves at the moment seems to be the rule, and so I do.

Player class is born, featuring a draw() and move() methods.

The last issue is text. After a bit headache I opted for a temporary solution: using SDL_ttf library. Probably I will look for some other solutions, maybe FTGL.

It’s all for now. Next I will face the map.

The Hero wandering in the empty world

The Hero wandering in the empty world

Posted in game programming | Tagged: | Leave a Comment »

What about a Roguelike?

Posted by Christian on December 18, 2008

Next project as I have in mind to deal with is a roguelike.

Yes I know, this is a huge amount of work, and probably it will not end as good as Pong… but I really want to try.

I have an idea about the interface. I would like to keep using OpenGL and the little framework builded for Pong, and so using a graphical user interface instead of text. But I love text-only roguelike, I found them … poetic, while tile-based are often nothing more than… 80ish (maybe because tilesets are always the same in all games, since about 20 years i think!).

But my roguelike will use 3d graphics in a nice way. I’ll keep the classical @ and other symbols, but they’ll wander in a 3d dungeon with textured walls and floors.

This is my Colombo’s Egg. I always wanted to develop an RPG but 3d modeling or even 2d graphics always represented a big obstacle. Maybe this time I’ll be able to move some more steps into this dream!

Posted in game programming | Tagged: , | Leave a Comment »

3D Pong collision detection: the simple way

Posted by Christian on December 12, 2008

As said in previous posts I’m actually working on a Pong clone in OpenGL, SDL and C++.

Topic of this post is Pong’s collision detection.

In a 2D environment this is quite easy and deserve of a very poor math, since we have a defined screen resolution, defined objects size and a perfect 1 to 1 relationship between units and pixels. We simple need of some x,y calculations.

But what in a 3D env? First, we don’t have relationship between pixels and units. Second, object can be translated and scaled, which means their size can change.

There are quite a few algorithms for 3D collision detection, I know of their existance but I master only one of them at the moment: Bounding Spheres.

Anyway, I tried with bounding spheres (which probably will be topic for another post) but I realize this is not the best suitable alg for the cause. In Pong we have to deal mostly with stretched cubes, and a sphere is not the best geometric figure to surround them. What we need is probably a Bounding Box version of the algorithm but… wait a moment.

Maybe what we really need is only a 3d adaption of our old, plain 2D algorithm.

Sure, we can’t tell how long or how fat is our racket or our ball, but we can calculate where object is on the 3D space, and with a little effort we can tell which vertex is the more up, the more right, the more left and the more bottom.

We can do that simply passing through all our object’s vertexes and locate the one with the higher y value, which will be the most up, then the one with the lowest y, the most bottom and so on with the x values.

At the end we have 4 vertexes for every object in the scene describing their borders.

But the ball is moving, and the rackets too. We need to keep update this borders with the object’s translations. But this is simple: if object translate up (0,1,0) we translate up all 4 border vertexes by the same values. Vertexes follow the object movements, of course.

And if the object scales? Well, we scale the borders too in the same way.

So, here we are with our vertexes. And now? Eheh, now the easy part. Each loop we only have to  check ball borders with rackets and field opposite borders in order to detect collisions.

For example: if ball’s right border is major or equal to player 2 racket’s left border (assuming player 2 is the one on the right) we have a collision.

if( ball.maxX() >= player2.minX() ){

ball.collideRight();

}

Easy, isn’t it?

Posted in game programming | Tagged: , , | Leave a Comment »

SDL: SDL_KeyboardEvent too slow?

Posted by Christian on December 11, 2008

Once again my OpenGL Pong clone gave me a chance to dig more into the common game programming issues.

This time the problem is SDL and its way to manage user keyboard input: SDL_KeyboardEvent.

The scenario is the following: I have my ball bouncing from one side of the game field to the other and my racket that should move up and down according to some key press events. Really simple. But…

The racket moves too later. I press the key, wait for about a second, and then that white rectangle of pixels decide to obey. Too, too too late.

So what? SDL is slow? No, once again computer is right and I’m wrong.

The issue is on my fps. Scene is rendered too speedy, more than 900 times per second. My handleInput() routine is placed at the very beginning on the game loop and no one knows when exactly the “key pressed” event is fired and catched. I have to tell the truth: I don’t know exactly why this happens, but happens. And I found the trick that solve it.

Delay.

Simply reduce in an artificial way the loop speed and the magic will happens: the keyboard response becomes immediate.

How to do that? Using SDL_Delay and SDL_GetTicks to force the fps below to a maximum rate.

At the beginning of the loop you take the current number of ticks and at the end do the same. Then check the difference with a costant of your choice and delay the loop of the difference. Something like that:

Uint32 start = SDL_GetTicks();

/* do graphic stuff and all the game loop logic */

Uint32 end = SDL_GetTicks();

if(end – start < MAX_FPS_RATE){

SDL_Delay(MAX_FPS_RATE – (end – start));

}

I’ve used 33 as MAX_FPS_RATE to have about 30 fps and all the inputs works great.

Posted in game programming | Tagged: , , | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.