In a previous post I have showed how to implement a hack to have transactions and authorization around Catalyst model classes. I am now proud to say that after some uploads and a fix in MooseX::Method::Signatures (this post requires at least version 0.31 of that module), you can now write very elegant model classes.

The requirement is simple, you usually need your model methods to be enclosed in transactions and to be subject to some kind of authorization mechanism. Now the code looks like:

Following posts 1, 2, 3, 4, 5 and 6 on the subject of writing games in Perl, now we are going to add support for maps.

At this moment, the initial ball position, as well as the walls are being defined in Perl code, during the controller initialization. What we are going to do now is creating a serialization format that describes our simulated universe, then have a set of maps in a directory navigating through them as the goals in each map are achieved.

The Map Format

There are several options to serialize and deserialize data, some are easier to use, others provide more introspection and others are better performant. I've read once a good advice in game development, which is: keep your map format accessible to art people.

A lot of people hate XML, I'm not of that club, I do like XML a lot, specially because it allows introspection and validation via XML Schema. And after the advent of XML::Compile::Schema, it's very simple to handle XML in Perl. Basically, once you have a XML Schema, you can think just in Perl data structures that will be serialized/deserialized from/to XML with associated validation.

That being said, let's proceed to our map format, which is going to be expressed as a XML Schema Definition:

At this point, the game is fully functional with the original map, now we can proceed to the next point.

Map cycling

We already have a goal in each map, so we need to react when the goal is reached so the next map is loaded. As you might have noticed, the InGame controller is completely tied to each map, so what we need to do is replace the controller instance by one with the new map.

There's one important point in the way our ball.pl script handles the main loop, it is not fully delegated to the controller, but it tries to handle the global events before it sends it to the controller.

What this means is that we can use an User SDL event to signal the main application that the goal for this controller instance was already achieved and that it should initialize the next controller.

So, first we're going to fire the event in the InGame controller as soon as the ball reaches the goal:

We're not doing putting any additional data in the event because this is the only user event we have in the game, we could use the event_code and the two pointers for data in the SDL::Event if we wanted to have a better qualification of the event.

Now we just need to handle that event. First, we're going to get the list of available maps in the beggining of ball.pl:

my @maps = sort <maps/*.xml>;

Then we're going to replace the hard-coded map selection with the first map in that array.

Simplifying the Deployment of Catalyst Perl Applications in Shared Hosting

Deploying Perl in shared hosting environments used to be an unpleasant experience, since most hosting providers would refuse to install and keep up-to-date CPAN modules. Fortunally this is no longer the case, since the advent of local::lib, which allows the build and installing of modules in a private directory. But this still required the user to have shell access to the machine, in order to bootstrap the local::lib and install all the dependencies.

The most problematic is not just requiring shell access, but actually requiring the compiler toolkit as well as the development headers for libraries such as libpq-dev (for the DBD::Pg module) or libxml2-dev (for the XML::LibXML module). This would certainly be a problem for a lot of hosting providers.

The last time I started building a local::lib bootstrap I came to the following realization. The machine I'm using is a Debian Lenny, the machine in the hosting provider is a Debian Lenny, so all I need to do is bootstrap the local::lib in my own machine (actually doing it inside a fresh debootstrapped chroot, to actually installing every non-core module by cpan). Then I just created a tarball with it and sent to the server and voilà, it just worked.

Of course my chroot required all the development headers as well as the compiler toolchain, but when I move the local::lib dir to the server, everything is already compiled, so I just need to make sure the postgresql client library is installed (which was already the case) as well as the libxml2 package (which was also the case).

So I realized this image can be re-used in any hosting provider using Debian-Lenny- i386. As I wouldn't like to have my blog shutdown due to excess traffic, I've uploaded the file to rapidshare, feel free to take it to a more convenient place (please tell me the link so I can add it here) -- I have removed the manpages in order to reduce the file size (reduced about 50%).

How to use it?

Simply unpack it into your user's account, it will create a "perl5" directory, if your hosting provider doesn't allow shell access, simply unpack it anywhere into your local machine and use the ftp client to send all the files (remember to set binary mode, since there will be binary files in there).

Then you need to include that path into your Perl's include directory, you can:

set the PERL5LIB environment directory with /home/youruser/perl5/lib/perl5:/home/youruser/perl5/lib/perl5/i486-linux-gnu-thread-multi

add -I/home/youruser/perl5/lib/perl5 -I/home/youruser/perl5/lib/perl5/i486-linux-gnu-thread-multi in the #!/usr/bin/perl line

If more people think this is a good idea, we might eventually start having different prebuilt images, since that is completely OS-Version specific. The image I built is intended for use ONLY on Debian Lenny i386 machines, it will fail and segfault miserably if you try to use it in other OS and/or version.

Following posts 1, 2, 3, 4 and 5 on the subject of writing games in Perl, now we are going to fix the math in the game.

In the first post, I used a very naive simplification of the movement calculation. I simply considered that the velocity was constant during the time of the frame and recalculated the final velocity after the frame so it would affect the next calculation.

I have to confess that I didn't do it just for the simplification of the code. I did it because of my lack of good understanding of math. Some people have noticed that I should've used a Runge-Kutta method to solve the problem, but, honestly, the math language is something that really requires a level of practice I simply don't have (I've been working on Information Systems for 12 years, now it's the first time I really miss calculus knowledge).

The problem I was trying to solve is: Considering I have a ball that is falling at a speed of 3 m/s with a gravity of 9.8 m/s², how far would it fall after 25 miliseconds (about 40 FPS). I'm strongly visually-oriented, so let me try to represent in some ascii-art what I was trying to find out.

I was considering I had defined the position I (initial) and I wanted to know which was the position F (final).

It was only after I shared the problem with Edilson (a colleague that works in the same place as I do), and after he present me a sheet full of math calculations which I simply ignored, since I couldn't understand, and then he said me: "You're looking at the wrong graphic, this graphic is derived from another graphic, which is velocity vs time".

This was a very important realization for me, bear with me: Let's simplify the problem a bit, let's consider we have a constant velocity. The graphic of velocity vs time would be something like:

Wait, that's a rectangle, its width is Δt and it's height is v, so the distance travelled is the area of the rectangle.

WAIT! That's the definition of Integral I've been reading in math books for a while and that never really meant anything to me because of all the math blabbering that really require consistent math practice to actually understand anything.

So now that I feel a lot less dumb, let's proceed to the problem at hand. The velocity in our game is lineary-variable, which means that its graphic over time will look like:

The intial grahic on the position over time at the beggining of this post is derived from this graphic -- and this is actually the meaning of derivative -- so the distance travelled in a given time frame is the area of the trapezoid representing that time frame:

So, the answer to my initial question is just a matter of calculating that area:

Δs = ((vI + vF) * Δt)/2

It looks pretty easy now, and, in fact, I feel quite dumb for taking so long to realize that. But anyway, that is probably all the required math for a lot of games. I hope I wasn't the only one who had a hard time understading all that, and, anyway, now I can start to understand more complex integral and derivative calculations.

So, let's apply that to the code in our game, which happens to be at the Ball.pm file.

Following posts 1, 2, 3 and 4 on the subject of writing games in Perl, now we are going to add a goal to our game.

Currently we have a bouncing ball with that collides in walls and have a camera following it. Now we are about to add a goal to the game. The idea is that you should get the ball to hit some specific point, considering the gravity and the 100% efficient bounce, making the ball go through some small places might be an interesting challenge.

The first thing we're going to do is change the walls configuration, so we make a more challenging setup, currently we have a box with a wall of half the height in the middle, let's make it a bit more interesting, let's change the walls initialization code to the following.

This creates two small passages in the middle of two vertical walls, not really hard, but kinda entertaining to get the ball to go through those. But in order to make it actually hard, let's add another wall:

Rect->new({ x => 9.2,
y => 11,
h => 1,
w => 1.6 }), # chamber

Now we have a small chamber created between the two vertical lines. It's kinda tricky to get the ball in there, I personally took some minutes.

But while I was testing this map, a bug appeared, and this is actually an important bug. Since the collision was pretty simplified to handle just one wall at the beginning, I was inadvertedly positioning the ball at the target destination after it bounced. This was ok when I had just one wall, but when I have more, and more importantly, when they are really close to each other, I might position the ball over another wall when detecting a collision, and that just, well, you have a ball inside a wall, unless you're watching the X Files, this can't be good.

The problem, as you might have noticed, happens when I calculate the target position after the bounce, so what we're going to do is simply stop trying to guess that. We're going to position the ball in the exactly spot before the collision with the bouncing velocities and recalculate the whole frame from that instant on.

This will actually mean a simplification of the code, that will look like:

Now, to add a goal, we're going to add another set of objects, the goal itself, which is simply a point, and the view, which I'm also going to reuse the filled rect view. First I'm going to create a Point object akin to the Rect I have created earlier.

Following posts 1, 2 and 3 on the subject of writing games in Perl, now we are going to add a camera.

Up to this point, we've been coupling the positional information in our simulated universe with the screen position. This is very easy to do, but very limiting as well, how can we represent off-screen elements that way?

Our next step is to implement a camera. The idea is quite simple, instead of asking for each model object to render itself, We're going to:

Initialize a view object for each of the model objects.

Detect which model objects are in the current view sight of the camera.

Send to the view objects the positional information of the model objects.

Ask the view objects to draw themselves.

At this point you might have noticed that I'm using the terms "model" and "view" as a direct reference to the Model-View-Controller architecture, and that's precisely my intention. The basic idea is: The model is only responsible for managing the simulation of our universe, while the view is only responsible for turning that simulation visible to the user. The Controller here is the code that implements the main loop, receiving the user events, and coordinating the FPS management.

I could list several reasons on why having the model and the view as separated objects is a good idea, but I'd like two point just two of them, since these are going to be future topics in this tutorial:

You can apply "themes" to the visualization, like "hi-res" and "low-res" simply by changing the initialization of the view, adding support for zoom and rotation is also very simple.

You can have the calculations on the simulation side in a different thread then the rendering of the objects, enabling our game to take advantage on multi-core systems.

Code Layout

The first thing I'm going to do is reorganize our current module layout. Up to this point our code had:

ball.pl

lib/Ball.pm

lib/Wall.pm

lib/Util.pm

But now we're going to need a different layout, here is our target organization:

ball.pl

This is still going to be our main script, but we're going to have less code in it.

lib/BouncingBall/Model/Ball.pm

Yes, I named our game BouncingBall, and the first model class is the ball itself, it will look much like the current code, but the "get_rect" and the "draw" methods won't be there.

lib/BouncingBall/Model/Wall.pm

This looks like our current Wall code, but as with the ball, "get_rect" and "draw" won't be there.

lib/BouncingBall/Controller/InGame.pm

At this point we're only going to have one controller, but the general idea is that we're going to have one controller for each of the main states of the game, like "MainMenu", "Paused", "InGame", "GameOver" etc. The InGame controller will implement the code that is currently inside the main loop of ball.pl

lib/BouncingBall/View.pm

This defines the types for the things that implement draw.

lib/BouncingBall/View/Plane.pm

This implements the background.

lib/BouncingBall/View/FilledRect.pm

Currently, our ball and our wall are just filled rectangles, so we're going to preserve that for now. This is interesting to make the view vs model point even more clear. The view doesn't need to be aware of what it is representing, as long as it knows how to do it. In our case, it doesn't need to know if it is representing a Ball or a Wall, it simply needs to know where it is and what color to paint.

lib/BouncingBall/View/MainSurface.pm

This class represents the main application surface, it is special because it needs to configure the video mode, but it is also a dependency for the FilledRect view, since it needs to blit itself somewhere.

lib/BouncingBall/View/Camera.pm

This is the view class that will implement the mapping of coordinates from the simulated universe to the MainSurface, the FilledRect also depends on this class.

lib/BouncingBall/Event/RectMoved.pm

Typed event that describes the movement of some object represented by its enclosing rect.

lib/BouncingBall/Event/Rect.pm

Object describing a simple rect (using floating-point instead of integer), to be used by RectMoved.

lib/BouncingBall/Event/MovingRectObservable.pm

Moose role that implements the logic for being a class that can be observed.

lib/BouncingBall/Event/MovingRectObserver.pm

Moose role that defines the type of the observer class.

General flow

ball.pl initializes the BouncingBall module.

BouncingBall initializes the MainSurface view, as this view is special and is preserved during the entire application lifetime, independent of the controller in charge right now.

As we don't implement game menu or any other fancy stuff, we go directly to the game. That means we'll initialize the InGame Controller.

The connection between the views and the models is defined by the controller, so it needs to initialize the models, the views and connect them together.

After the initialization, we're ready for the game loop, which is, at this point, entirely handled by the InGame controller.

The case for Observers

A naive implementation of the connection between the models and the views would be, at each step, to fetch the relevant information from the model and set it into the view. Or possibly have the view itself fetch the data from the model. But there's one important point to consider, if the model and the view ends in a different thread, accessing each other's data would become significantly complicated.

That being said, a different mechanism for view-model integration is necessary. If we go to the way GUI toolkits work, we'll notice a pattern called "The Observer Pattern", basically, one object registers itself as "observing" the other. When that specific type of event happens, a pre-defined method is called in the observing object.

So what we're going to do is to preserve a local cache of the information that view needs from the model, use it directly and get it updated using the observer pattern. That way we have the model and the view decoupled in terms of threading.

To the code

The first thing we need to do is porting our Ball and Wall into proper model objects, at first, simply removing the "get_rect" and "draw" methods. I'm not going to put all its code again here, but renaming the modules and removing that methods is the only thing I'm doing right now. The time_lapse is also simplfied to remove the automatic bounce, we're going to put extra walls to enclose the ball.

Now we need to step-by-step get to the final code layout presented earlier, let's start by the view classes, and in that case, let's get the most important view class, the MainSurface.

Here we use Moose object initialization to initialize the SDL Video subsystem and get a new surface for the required videomode. This is a bit different then what we were doing in the original ball.pl, but not much. The most important difference is that we're now using double hardware buffering, which is more efficient then doing individual updates.

Now we need the Camera view, which is going to implement the logic on translating the coordinates from each object to the current visualization. This is a very important decoupling in our logic, because it is here that we relativize the points from the simulated universe to the screen. And this is going to be done by setting a camera position which is going to serve as pivot in the coordinate translation.

This is going to be implemented through three methods in our camera, one that converts a distance in meters to pixels, other that converts a coordinate to the screen and finally one that checks if a coordinate is visible at that moment.

Ok, now that we have the Model and the View classes, we can implement the observer pattern, so the view can be updated as the model changes.

One important aspect on how the MVC model works is that the controller should have just a limited control on the interaction between the model and the view, otherwise you'll get a very complicated code in the controller. Ideally you should have the same level of abstraction in the model as you have in the view, so you have componentization of your application.

That being said, we need to plan the communication pattern between the view and the model. It is important that they should be mostly unaware of each other, in the sense that the view doesn't need to know that it's a ball being modelled, but just that it has a point describing its position and a rect describing its measures - We can even keep only the rect for our current purposes.

That is our RectMoved event class and the Rect class which is used by it:

Now we need to make our Ball model class fire that event whenever its position or size attributes are changed. So we're goint to add the following modifiers to the attributes. At first we're not going to support the old_rect attribute of the event, so we're just sending the new_rect.

Following posts 1 and 2 on the subject of writing games in Perl, now we are going to add colision.

The idea is quite simple, we are going to add another square to the game, and when the ball hits it, it will change direction. Following the way we were working, I'm going to add another object, called Wall.

The first thing is modelling our wall, which will be a rectangle, so it has the following attributes.

Now we need to add our wall to the game, that will mean a simple change in our main code, first we need to load the Wall module, then initialize the Wall just after initializing the ball, and finally calling the draw method just after calling the same method on ball.

use Wall;

my $wall = Wall->new;

$wall->draw($app, $height, $width);

If you tried to run the code at this point, you'll notice you won't see any wall. That happens because the application is only updating the screen where the ball is passing. The Wall needs to be drawn a first time, and the screen needs to be updated at that position. This prevents us from re-updating the wall rect everytime, which is pointless, since the wall is static - that code goes right before the main loop.

Now we need to check for a collision. This should happen in the place of the time_lapse call. Note that while I neglected math in the movement part, here it's more complicated because I need to react in a reasonable manner depending on how the collision happened. But as we're working in Perl and we have CPAN, I can just use Collision::2D (zpmorgan++ for working on this and pointing me in the correct direction)

If you don't have the Collision::2D module installed, just call

# cpan Collision::2D

If you're not sure wether you have it or not, just try installing it anyway, it will suceed if the module is already installed.

I assumed an API that wasn't currently implemented in our Ball object, so I changed the ball so that pos_v, pos_h, width and height return the bounding dimensions for the ball I won't put the code in the post, but you can check at the github repo.

Okay, now it's time to check for collisions and act accordingly. Again, we'll assume an 100% efficient collision, so the code looks like:

In the case we have a collision, Collision::2D tells us when and how it happened. In order to implement the bouncing, I also calculate how far they would have been proceeded before and after the collision.

The method that describes how the collision happened is "axis". If it was a purely horizontal colision, it will return 'x', if it was purely vertical, it will return 'y', if it was mixed, it will return a vector that describes it. In the case of a bug, it will return undef.

In the case of perfect horizontal or vertical collision (or bug), we reposition the ball by first calculating where it would be at the time of the collision and then bounce it away - depending on how the collision occurred.

I'm working for some time in a concept on what I've been calling Null CMS, which would be simply a content repository with metadata support and authorization. The interface would simply be a search and an edit screen. The data would be stored in Plain Old Semantic HTML (POSH), tags and categorization would be made with HTML META tags, microformats would also be used to allow structuring other types of data. Media files could be stored with an associated html file describing it.

In order to make it fast, I'd use KinoSearch to index all of that, including inexing known microformats and other patterns that could be defined in code. The other requisite for that is supporting UNIX-style permissions (ugo+rwx) so I could have three sets of indices - 1 for each user, 1 for each group and 1 for others.

In the end, this is going to be presented as a Catalyst Model, that will then be used to implement web sites in an easy and clean way - using a specialized cat front-end for sites is very straight forward, I had experience front-ending wordpress which, besides it's weird data modelling (and "weird" is putting it in a nice way), and it was pretty nice.

This could easily be solved with a XML database, such as Sedna, eXist or even bdbxml, but they require an extra level of control of the operating system that would make this project pointless (If I have this kind of control, I'd use Alfresco which already implements everything I need).

Conceptually, something as simple as storing everything in a tar file would solve it, but then we have concurrent access and it fails.

I was wondering about KiokuDB, but I'd still need a storage for kinosearch indexes, maybe it's possible to create a store class for kinosearch that stores it in a relational database.

In summary, I need a solution that could be used in a regular cheap shared hosting (which probably means only MySQL).

The other alternative is using Amazon services, but that would make me too depedant on them - although it would probably be a minor problem, since it's all encapsulated in a model class...

I'm usually not thrilled by competitions, but I must admit this one has taken me. I refer to the Google AI Challenge promoted by the University of Waterloo Computer Science Club. This is a simple bot competition where you play in a one-to-one tron game with another bot from the competition in one of a set of maps.

The deadline for bot submission is 26th february, but don't wait untill there. The example bots are nothing close to the competition bots... You can follow my status here.

Following the first post on the subject of writing games in Perl, where we created a bouncing ball (I know, it is a rectangle, but I trust your imagination), this post is going to add something very important when dealing with games: input.

Silveira Neto suggested that I should include more specific instructions on how to start the game (and maybe a video), so I recalled that I didn't mention that all the sources for this posts (including the text) is currently hosted at a github repository (if you plan to contribute, please just ask me for commit permissions instead of forking the repo).

So if you want to run the codes posted here, you first need to:

$ git clone http://github.com/ruoso/games-perl.git

You can check for updates by calling

$ git pull origin master

from inside the games-perl directory. Each directory inside games-perl starts with the number of the post. The first post is inside the 1-bouncing-ball directory and the second is in 2-controlling. To run the the first code just get inside the first directory and call:

$ perl ball.pl

The second example code is based on the first, so the script name is the same, so just get into the other directory and run the same line. If you get an error like:

It means you probably don't have the newest SDL, take a look at the first post to see how to get the newest redesigned SDL.

Controlling the Ball

Enough for the introduction, let's get to the actual code. The first thing we need is understanding SDL Events. If you ever programmed GUI applications or even if you wrote some javascript you are aware of how an event framework looks like. SDL is no exception, you need to wait (or poll) for the events, and each event will contain the information you need to figure out what happened.

In our case, we want to apply additional acceleration to the ball whenever the arrow keys are pressed. But if we have an event-based system, the way to figure out which of those four keys is currently pressed is keeping a state mask and update it when you receive keydown and keyup events.

So what we're going to do is to manipulate the acc_h and acc_v ball attributes depending on the keydown and keyup events. It might look complicated, but the only change we need is (this is inside ball.pl main loop):