Christian Vucossa programming blog

game programming, daily troubles and solutions

The Evil NHibernate’s NonUniqueObjectException !

Posted by Christian on November 4, 2009

Today I faced this ancient evil… and it almost destroyed me.

This exception comes out when you try to save or update an object with the same id of another object that is already in the scope of  the NHibernate session.

My scenario was this: I had to save the instance of an object. Well, I have to choose if use a Insert or an Update. To do so, I query the db in search of an object with the id of mine and act accordingly.

BUT, the query keeps in the session the instance of the object and the next Update operation fails with the NonUniqueObjectException. What to do? Well, in this case you have to send in update the same object the GetByID returns to you.

So:

1) Query the db and keep the instance of the object A it returns (if any)

2) Update A with the data you store in the original updated object B

3) Save A instead of directly save B

and you’ll defeat the Evil NonUniqueObjectException!

Posted in exception solving | Leave a Comment »

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 »

Visual Studio .NET 2003 lib path limit

Posted by Christian on May 22, 2009

Yes, it is. The include lib path in Visual Studio .NET 2003 (C++) has a lenght limit, something about 2k (I haven’t measured precisely). So, if you run into the ugly LNK1104 fatal error and there is nothing wrong on your settings, maybe you have a too long lib list.

Now, far from me the will to debate if this is a silly limitation, after all one could say that a more than 2k lenght lib path list is far more silly too.

Posted in exception solving | Tagged: | Leave a Comment »

ASP.Net Repeater updated with Ajax

Posted by Christian on March 21, 2009

Here is a simple method to update an aspnet Repeater calling a server method via ajax… here we go!

We make the ajax call with the favourite js framework or none at all. I use prototype anyway.

In our server method we do something like this:

List<Item> tobound = myDao.GetItems();

myRepeater.DataSource = tobound;

myRepeater.DataBind();

// and now the magic

// first of all we instance some usefull objects:

MemoryStream stream = new MemoryStream();

StreamWriter sw = new StreamWriter(stream);

HtmlTextWriter htw = new HtmlTextWriter(sw);

// then, we call the repeater’s own render method to render on our stream:

myRepeater.RenderControl(htw);

sw.Flush();

// ok, now we swap the stream in a byte array

Byte[] content = new Byte[stream.Length];

stream.Position = 0;

stream.Read(content, 0, stream.Length);

// and finally we transform the byte array in a string

string strContent = new System.Text.ASCIIEncoding().GetString(content);

// now strContent contains all the xhtml code that renders our repeater.

// Simply put it in the response and let it be consumed by the javascript callback

Page.Response.Write(strContent);

And our client code in the callback will look like this:

$(‘myrepeaterdiv’).update(transport.responseText);

Here we have a very simple method which doesn’t make use of any server side ajax component, just the old plain asp:Repeater and a good javascript ajax library.

Bye!

Posted in various | 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 »

DataGridView Cell’s editing: handle user’s input

Posted by Christian on January 27, 2009

Today I faced an issue that stole me a couple of hours of lazy work… My need was to intercept all the ‘.’ chars inputed by the user on a DataGridView cell and replace them with commas. With my big surprise, I have not found any suitable event of method.

After a coffebreak, I returned with clear mind and restored energies at the problem and I found this event on the DataGridView object:

EditingControlShowing

Neither the name nor the help tooltip of the intellisense help me so much understanding its behavior, but I registered to it and took a try.

Its DataGridViewEditingControlShowingEventArgs provide me with a Control object that is exactly the control used by the cell to handle input, a TextBox in my case. And now the magic.

I tried to treat the control as a normal TextBox, registering to its KeyPress event and it works!

myGrid.EditingControlShowing+=new DataGridViewEditingControlShowingEventHandler(myGrid_EditingControlShowing);

private void myGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) {
if (e.Control is TextBox) {
((TextBox)e.Control).KeyPress +=new KeyPressEventHandler(HandleKeyPress);
}
}

private void HandleKeyPress(object sender, KeyPressEventArgs e) {
// My stuff here…
}

Another day at work, another .NET  trick learned…

Posted in exception solving, various | 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 »

The float to int conversion’s big mystery

Posted by Christian on December 31, 2008

Someone must explain me this thing… I was working on my roguelike, namely the wall collision, when I came across one of the strangest things seen recently. My issue was to convert space coordinate of my @ into 2d matrix coordinate of the map, a bi-dimensional array. My space2map function perform some calculation and give me a x,y values, quite straight.

It seemed to work, but after a bit of testing things began to go wrong… when I was expecting a 2 I get a 1 instead, or the like. For some debugging hours I was sure I was wrong, but in the end I found myself in front of a thing like this:

(0.2 + 0.3) / 0.5 = 0

It was enough to make me think that yes, math is an opinion. A compiler opinion, at least.

After a while google gave me the answer: there is something on the float to int conversion. A really magic function came with the answer, this:

int iround(float x)
{
return (int)floor(x + 0.5);
}

where floor() is the math.h C function.

I tried with this and it works. Then, I wrote a simple program to test this mystery, and this is the result:

The float to int test

The float to int test

For the record, this happens on GCC for Ubuntu 8.04.

Posted in exception solving | Tagged: | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.