Personal SFML Website Updated

A bit late, but better late than never: Happy New Year to everyone!

So the past few days I’ve been working on a new front- and back-end for my small personal website, targeted towards anything related to SFML. Active SFML developers and/or SFML forum readers might already know that I’ve been providing SFML Nightly Builds for a handful of compiler, up to now the downloads were provided through a small self written PHP file and linked in the static HTML download section. Now they’ve got a dedicated place and user-friendlier URLs.

Now let me talk a bit about the two frameworks, which currently power the new website. Both of them were fairly new to me and thus I had a lot to learn and read.

As for the front-end I used Twitter Bootstrap, the evermore popular collection of CSS and JavaScript assets, that give your site with a very simple HTML skeleton a somewhat standardized look and feel, which a many find quite intuitive and appealing to work with. The small SFML website wasn’t the first project with which I got myself introduced to Twitter Bootstrap, but it had recently refactored an older database-project, I had made for a friend of mine a few years back. The simplicity and powerfulness of the framework really surprised me and with the help of the online documentation working on a nice HTML site is a very easy task.

The decision for a proper back-end was a bit harder, since there are so many different ones and each of them provide again different features, which might sound genius, but can have a huge learning-curve, so you’d end up digging through tutorials and documentations for hours. The first framework I’ve had in mind was Symfony 2. It is a well-known and respected PHP framework and one can do any kind of web application with it. But because it’s so loosely coupled and generalized the learning curve is quite big. Although they provide some nice introduction tutorials, I’ve never gotten a good overview and never really understood how one would get to write a simple application with it.
In the search for something less clumsy and complex I went to Wikipedia’s web framework list and clicked me through one after the other, until I reached CodeIgniter. Looking at the short feature list on their website, I was immediately hooked and was pleasantly surprised as I switched to the documentation, which is structured cleanly and lets you choose on how deep you want to go, but builds up your knowledge about the basics step by step. Within a few minutes I had a running back-end with custom URL routing. The only problem I ran into was the correct mod_rewrite routing and I could only resolve it with some googling. So in case someone would by accident find my blog, here’s the correct routing I use to abstract the index.php away:

RewriteEngine on
RewriteBase /
RewriteCond $1 !^(index.php|img|css|js|robots.txt)
RewriteRule ^(.*)$ /index.php?/$1 [L,QSA]

That way one gets a nice URL like https://my-gate.net/about/ which will get redirected automatically to the index.php.

Anyways I’m quite happy with the combination of Twitter Bootstrap and CodeIgniter and will most certainly use them further for different projects. I’m here specially thinking about SFMLUploads, which has as back-end only a few very hackish PHP files and thus is constantly failing and very hard to maintain.

Do you have any experience with CodeIgniter, Boostrap or any other framework you want to drop a line in the comment section?

yEd – A simple and nice diagram tool

How often do you find yourself, trying to put some information graphically into sense, but fail to do, because the software you’re using isn’t really nice to use?

Maybe you’ve never experienced that or have never needed to do so, but I have on multiple occasion and it has never been fun.
Being a fan of open source and free software I quickly found my way to Dia, but seriously this software is not fun to work with. The interface seems to be quite buggy and you can get tired by clicking and searching through the menus and then there you’ve all that mess with your objects…
Next up being a Windows user and student I can get a copy of Microsoft’s Visio for free. Well the interface seems quite familiar and the functionalities are fitting… but it just doesn’t feel like the solution, in fact the chaos still remains.

Today, I was browsing again through my RSS feeds and found that a friend of mine (Stefan Schindler aka Tank) has published his first tutorial/article about Game Development Design (it’s very interesting and should definitely read it!) and he was using some nice and fancy diagrams. So mentioning the diagrams on IRC he immediately pointed me towards the software he used: yEd.
Here’s the solution to my initial problem:

diag

And for all the lazy people that don’t want to check out the site, here’s a YouTube video:

Stay tuned for more updates on my projects!

SFMLUploads.org – Relaunch

So I’ve taken ownership of the project SFMLUploads.org which is basically a file and image hoster made specially for developers who are using the SFMLibrary. Below you’ll find the announcement text I wrote for the official SFML forum.

After quite a few ups and even more downs SFMLUploads is finally back online!
SFMLUploads.org was originally created by the user Haikarainen back in May 2011 but due to server issues the project had experienced some hiccups in the early days and then went offline in July 2012. As quite a few things have been uploaded to that site and linked to in this forum, I felt it was wrong to lead the project drop dead, thus I contacted Haikarainen and convinced him to let me host and maintain the website. So here we are with the relaunch of SFMLUploads!

All the files and user accounts have been successfully transferred over to the new host, thus you’ll be able to log into your old account again to get access to your files. If you don’t remember your password you can contact me and I’ll give you the opportunity to re-register.

SFMLUploads logo

SFMLUploads is aimed at developers using the SFML library, and it’s main purpose is to serve those users with bandwidth for:

  • Project archives, allowed extensions are: .rar, .zip, .tar, .tar.gz, .tgz, .deb, .rpm, .7z, .xz, and .ace.
  • Code-snippets, syntax-highlighted code with support for 100+ languages, "fork"-able, meaning users can create other versions of it. Useful with debugging etc. Kind of like Pastebin.
  • Screenshots/images, allowed extensions are .jpg, .jpeg and .png. Primarily for screenshots, but other picture are allowed as well.

The main rule is: It HAS to have something to do with SFML, either if it’s for a forum post where you seek help for debugging a problem related to/which uses SFML, or if it’s download links for your awesome game on your personal blog or something, etc. You can read the full terms here.

I hope you like it – signup and enjoy! 🙂

PS: This service is 100% free, if you feel like donating for the hosting cost then you can do this here. Thanks!

The disappointment from Microsoft: Visual Studio 2012

With the announcement on the 1th of August for Visual Studio 2012‘s final build shouldn’t I as developer with Visual Studio be thrilled rather than disappointed? Yes the new version brings quite a lot of new and/or improved features, but it seems like Microsoft has lost their focus on what should really matter. I guess it’s not the first time the company from Redmond has gotten caught up in their own little world and totally forgot about everyone else.

So let me finally get to the point: Visual Studio 2012 or rather the compiler (MSVC) will support only about three new C++11 core features which gets us to a count of 18 supported core features of 40 (source). Some may now argue that 18 features are a lot specially since the new standard isn’t even a year old, but for those I can only add that many possibly features were obvious to come with the new standard and that the open source projects like GCC and Clang already support way more features and some of those for quite a while now (source).

When I said that Microsoft has lost their focus, this wasn’t taken out of the blue. It’s based on different facts and intuitions:

  • Fact is that Microsoft at first wanted to release the Express version of VS12 with support only for their Modern UI (formerly called Metro) Style Apps, so the development of native C++ applications would’ve then only been possible for people who pay (or pirate) Visual Studio 2012.
  • With the constant and heavy development on their own home-brew language C#, they kind of make their priorities clear…
  • Stephan T. Lavavej (aka STL) stated in a comment to the first source link from above: “Since January 2007 (when I moved from Outlook Search to VC Libraries), I’ve been the only MS dev working on the STL.” – From such a big company you’d clearly think that they’d put more people on such a task; now you can only guess how many people work on the compiler itself… (Also note that the STL itself isn’t even that far behind regarding C++11.)

As I’ve written on my other blog C++11 is a new and better language, it’s the language of the future and it’s kind of sad seeing such a big company like Microsoft failing to keep up with the development for one of their core applications.

Since I don’t want to miss to the C++11 train that starts to roll faster and faster with every passing week, I’ll probably have to leave Visual Studio behind me and start looking out for better alternatives like QtCreator, KDevelop or just plain Vim in connection with GCC or Clang. Since those tools are the most powerful in their right context, i.e. a *nix based OS, and since I’ve gotten more and more used to the so called GNU-tools, I’m seriously considering the move to Debian. For those who know me better, this step would be quite a big one for me and I won’t go and just abandon Windows but there’s no really good reason to code and develop on Windows anymore.

While writing this blog post on another PC, Debian is getting installed on my main one… So we’ll see how things develop and my hope is that Microsoft gets their things together and very soon release a service pack/update with new core features.

A SmallGameEngine or State Machine

introFrom a question ask in the official SFML forum which linked to a tutorial by Anthony Lewis at GameDevGeek.com I took the challenge up on me and converted that small game engine or maybe it would be better just called a state machine from SDL to SFML. In the near future I also hope to rewrite the original tutorial but of course inserting my insights and explain the additional changes I made. Also I’d like to get some more or less official approval that I’m allowed to copy bits and pieces from Tony’s text but unfortunately he didn’t reply to my e-mail (via the contact form) yet. So here a few things about it.

For all those that don’t understand what a state machine is, here a quick definition:

It is conceived as an abstract machine that can be in one of a finite number of states. The machine is in only one state at a time; the state it is in at any given time is called the current state. It can change from one state to another when initiated by a triggering event or condition, this is called a transition. – Wikipedia

So there you have it; we have a finite number of states of a game, like the menu, the splash screen, the game and the credits screen. The machine is running as long as there’s an active state and only one state can be active. (More details in the upcoming/original tutorial.)

So since the code is completely based on that tutorial it also uses the same states, namely IntroState, MenuState and PlayState. You start off with the IntroState and then by pressing any key you’ll proceed to the PlayState from which you can either invoke the MenuState or exit the application. From the MenuState you can only switch back to the PlayState.

After some thinking I’ve changed actually quite a lot of the GameEngine class and how states get created, paused, resumed and destroyed. I’ve also decided to use a few nice language features (e.g. RAII or std::unique_ptr<T>) so the code can now get described as C++ code rather than C with classes code.
Those changes, next to the ‘artistic’ advantages, give you more flexibility in using the states, as you can reset a state by just recreating it and it ensures that all three functions HandelEvents(), Update() and Draw() get called before a new state gets started, thus minimizing possible strange behaviors.

So overall it’s a nice little demo for a state machine and I might just as well use it in some future project. So feel free to literally check-it-out (or better git pull) on GitHub. If you got any questions then just put them in the comments, if you have any suggestions or bug reports use the issue tracking system of GitHub.

SmallGameEngine

TileMapCreator – Update 02

Nearly two month have passed since the last update on the TileMapCreator and I kind of feel bad about it. For my excuse I’m studying for my upcoming big exam.

Last time I was talking about the grid and how I want it to improve; I’ve spend quite some time thinking and trying out things, but haven’t gotten the best solution implemented yet. In addition I’ve looked more into how to use Git and opened a new project over at GitHub, check it out:

TileMapCreator on GitHub

If you clone the repository you’ll need SFML, SFGUI and Thor and you’ll have to create a make or project file on your own. Once I get the time I’ll dig deeper into the whole CMake thingy, you’ll be able to just use CMake to build TMC.
So if you’d indeed get it to compile and run you will only see the GUI, that’s because I’m in the process of refactoring everything and getting more into TDD (Test Driven Development), which means I’ve removed the grid temporarily, added a separated GUI class and implemented different tests. Since the last push this evening I’ve already decided to split the GUI class again into two classes and put them into their own namespace.

So how does the future look like? I decided to first concentrate more on the GUI and loading tiles into the GUI, rather than playing around with a grid that is just somehow plugged into the project but doesn’t connect with the other parts and probably needs to get rewritten later to fit with them…

That sums it up for now! If you want to keep a close look at the project make sure to watch the GitHub project!

Using sf::View

I’ve been using SFML now for more than a year but I never really understood how sf::View really works, until now. So I feel like sharing this enlightenment and I’ll also create a tutorial in the wiki section on GitHub.

What can a sf::View do?

This question is not that complicated to answer and I would’ve already been able to do so a few weeks back but I never really understood how sf::View works. The answer would be a description, so here you go:

A sf::View is basically a 2D camera i.e. you can move freely in two dimensions, you can rotate the whole scene clockwise or counterclockwise and you can zoom in and out but there’s no tilting or panning. Furthermore zooming really means enlarging the existing picture rather than closing in on something. In short terms there’s no 3D interaction.

Examples

initial

So if you now want to move a sprite around without altering its coordinates but instead moving the 2D camera, you could do this easily by calling:

view.move(360.f, 360.f);

move

Next you maybe want to get a closer look at something, so you can use:

view.zoom(0.1f);

zoom

Or you want to rotate everything:

view.rotate(20.f);

rotate

Now you get the idea what the camera can do and you’d probably be even able to program something with it, but do you understand how it works? Do you know what the center of the sf::View is?

So let’s get a bit more technical.

How does sf::View work?

So lets see what the documentation of SFML says about this:

A view is composed of a source rectangle, which defines what part of the 2D scene is shown, and a target viewport, which defines where the contents of the source rectangle will be displayed on the render target (window or texture).

The viewport allows to map the scene to a custom part of the render target, and can be used for split-screen or for displaying a minimap, for example. If the source rectangle has not the same size as the viewport, its contents will be stretched to fit in.

If you’ve understood everything then congrats! I didn’t (at first) and although it’s a good, short and precise description it’s not very intuitive.

From the text above we can extract that there are two different rectangle defining the sf::View: a source and a viewport. What we also have, although not ‘physically’, is the render coordinate system, i.e. the coordinates you use to draw sprites etc.

At first I’ll explain how the source rectangle and the render coordinate system work together, then talk about the size and the constructor, furthermore show you how to use the viewport to create different layouts like a split-screen or a mini-map, as suggest in the description and at the end get a bit away from the direct manipulation of the sf::View and look at the convertCoords(…) function of a sf::RenderTarget.

At the bottom of the post you’ll find a ZIP file which holds a fully working example, demonstrating everything you’ll learn in this post.

The source rectangle

Since I don’t want to talk about the viewport yet but I’ll let it have its defaults value, which means that it will cover the whole window i.e. the whole scene will be rendered 1:1 onto the window.

In the example above I’ve already moved the view to the point, where I’m rendering the separate sprite of Link. Link’s position in pixel is (1056, 640) but to get him centered, respectively the top left corner of him, I can’t just use what might seem intuitively:

view.setCenter(1056, 640);

(Of course you can set the view center to (0, 0) and then move to to (1056, 640) but we’re trying to understand what the center of the view is.)

Since I’m assuming that you’ve already some knowledge with SFML, I’ll also assume that you know SFML is using a Cartesian coordinate system with a flipped Y axis. So the point (0, 0) can normally be found in the top left corner and then maximum x and y value can be found in the bottom right corner. If you’re working with images you’ll soon get comfortable with this system.

But now comes the center of view, which is in fact defined from the middle point of the display area. The view uses a Cartesian coordinate system too but this time the X axis gets flipped. In the end we have the point (0, 0) (also known as origin) in middle of the view, the maximum x and y values are in the top left corner and the minimal and negative x and y values are in the bottom right corner. What you’re now actually can set with setCenter is the where origin of the rendering coordinate system is put in the coordinate system of the view. I hope the following images will clarify the situation a bit.

The black square should represent the window and since we set the viewport to a fixed value the origin of the sf::View coordinate system will always be in the middle of the window. Here are the two separated coordinate systems:

coord-render

coord-view

If we combine them we get for example something like:

coord-comb

Then we have our two operations rotate() and zoom(). The last picture combines the two transformation:

coord-comb-rot

coord-comb-zoom

coord-comb-zoom-rot

I think it’s nearly impossible to explain this even better.

Note that in the images above, I’ve moved the rendering coordinate system around to get a few different variations. I guess most of the time it’s better to use the move() function since you won’t need to deal with where to place the origin point. On the other hand you really need to understand how sf::View works to use rotate() and zoom() because it’s not obvious that those transformation will happen around the sf::View origin i.e. the middle of the view.

You should keep in mind the introduced concept doesn’t just hold for a window it’ll work with any render target including sf::RenderTexture.

The size and the constructor

Before we take a closer look at the viewport we need to understand what the size of the view is and which parameters the constructor takes.

For now we’ve used the same size for the view as for the render target, this gives us a 1:1 projection. But what if we’d divide the size of both sides by two? From the observer perspective such a change would equal to using view.zoom(0.5f) but from the programmer perspective it’s something completely different. As we’ll learn in the next paragraph we can use the viewport to map the rendering stuff to a certain area on the window. Now if’ we’d apply the scene with the same size as before everything would get shrinked and eventually stretched if the ratio of the side isn’t the same anymore. This can create some wanted effects but mostly it would defeat the purpose. With setting a specific size, we’re telling the sf::View how big the view should get drawn while not making any visible transformations on the rendering part.

With that in mind it’s now easy to understand how to use the constructor.

sf::View view(origin.x, origin.y, size.width, size.height);

Where origin relates to a 2D vector of the origin in the rendering coordinate system and size relates to the sf::View size as discussed above.

The viewport rectangle

After we’ve seen most of the things sf::View can do, we want to generalize this even further. For now we’ve assumed we were using a window and rendered 1:1 onto it’s surface, but what if we wanted to display my stuff only on the lower right corner or use only the half left side? That’s where the viewport comes in.

The default values are sf::FloatRect(0, 0, 1, 1) which means the view covers 100% of the render target. So we got another rectangle which holds percentage values of the size of the render target. The first two values describe the position of the upper left corner and the last two values the lower right corner.

If you want to split the screen you’d need two different views for the left and the right side. Before you then draw to one side you’ll have to change the view on the render target first. To draw something to the other side, just set the second view and you’re good to go. This could look like this:

sf::View viewLeft(sf::FloatRect(0, 0, window.getSize().x/2, window.getSize().y));
viewLeft.setViewport(sf::FloatRect(0, 0, 0.5, 1));
sf::View viewRight(sf::FloatRect(0, 0, window.getSize().x/2, window.getSize().y));
viewRight.setViewport(sf::FloatRect(0.5, 0, 0.5, 1));
// ...
window.setView(viewLeft);
window.draw(leftSprite);
window.setView(viewRight);
window.draw(rightSprite);

With all the knowledge provided above you should now have a good understanding of why we divide the window width by two or why viewRight is defined with 0.5 as first argument.

split

Another example I promised to show is how to create a mini-map i.e. a scaled down overview of the whole map. In practice it’s often better to construct it’s own mini-map rather than just scaling down the original one, since the quality can get fairly poor. But let us first test how it will really look like.

If you’re working with more dynamic data you’d probably need to render everything to a sf::RenderTexture and then extract the texture and render it twice. In this example we ignore those facts and just assume we’ve got a sprite with the Zelda map texture thus we can reduce the code to a few lines.

sf::View standard = window.getView();
unsigned int size = 100;
sf::View minimap(sf::FloatRect(standard.getCenter().x, standard.getCenter().y, size, window.getSize().y*size/window.getSize().x));
minimap.setViewport(sf::FloatRect(1.f-(1.f*minimap.getSize().x)/window.getSize().x-0.02f, 1.f-(1.f*minimap.getSize().y)/window.getSize().y-0.02f, (1.f*minimap.getSize().x)/window.getSize().x, (1.f*minimap.getSize().y)/window.getSize().y));
minimap.zoom(4.f);
// ...
window.setView(standard);
window.draw(map);
window.setView(minimap);
window.draw(map);

minimap

The convertCoords(…) function

As we’ve seen in the paragraph with the source rectangle it’s not very intuitive to work with those two coordinate system. It’s also pretty hard to determine by hand at which position for instance your mouse cursor is located relative to the view underneath. But why would you want to do this by hand, since SFML has already a build in function that will do the heavy lifting for you, namely convertCoords(…)?

There are two ways to use this function:

  1. Determine the relative position on the render target of the point P to the current view of the render target.
  2. Determine the relative position on the render target of the point P to a specified view.

This function can be very useful, e.g. you’ve moved around your view and now the user click on a point on the window. Just call convertCoords(…) and you’ll instantly know where on the moved view he clicked.

Complete demonstration

I’ve created a small application which packs up every introduced concept. The code isn’t the prettiest but contains a lot of more or less useful comments. I also provide a package that contains just the images presented in this blog post and since maybe some people want both, I’ve created one that contains everything.

If you have any questions/suggestions or found any mistakes/bugs/errors just let me know in the comment section!

Tutorial: How to change your cursor?

cursorI’ve just published my first tutorial with SFML, okay it’s actually not fully my tutorial since I’ve partially rewritten one from the old section, but expanded it with in my opinion a better solution.
Although you can find the tutorial on the wiki site of SFML, I post it here again.


How to change your cursor?

The cursor is something every computer user is familiar with and in fact is constantly staring at, yet many people don’t even realize anymore that it’s there and changes its shape every so often. Next to the functionality like pointing and clicking the cursor can show many different states and indicate possible actions. For example you’ll get a selection cursor when hovering over a text or a hand shaped cursor could indicate a link etc.

Since SFML is not a framework nor a GUI system providing a native function for changing the mouse cursor doesn’t fit its purpose. Here’s where this tutorial comes in. If you’re making an application or game, you might want to be able to display a different cursor. There are two ways to change your cursor:

  1. You can hide the default cursor and draw a sprite where the cursor should be
  2. You can ask your OS to do it for you. (Windows & Linux)

This tutorial will cover both methods.

What do you need?

You’ll need SFML, an editor and a compiler (obviously these links are only suggestions).
Since I won’t go into details regarding C++ or SFML, the tutorial requires you to have some basic knowledge on both topics.

Hide and Draw

This task is fairly simple, it consists out of three required and one optional tasks:

  1. Use sf::RenderWindow::setMouseCursorVisible(bool) to hide the cursor.
  2. Set the position of the sprite to the position of the mouse.
  3. (optional) Adjust the view to get the correct render position.
  4. Draw the sprite to the screen.

Since it’s so simple there’s not more to talk about and an example shows a possible implementation:

#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow window(sf::VideoMode(800, 600), "Hidden Cursor");
    window.setMouseCursorVisible(false); // Hide cursor

    sf::View fixed = window.getView(); // Create a fixed view

    // Load image and create sprite
    sf::Texture texture;
    texture.loadFromFile("cursor.png");
    sf::Sprite sprite(texture);

    while(window.isOpen())
    {
        sf::Event event;
        while(window.pollEvent(event))
        {
            if(event.type == sf::Event::Closed)
            {
                window.close();
            }
        }

        sprite.setPosition(static_cast<sf::Vector2f>(sf::Mouse::getPosition(window))); // Set position

        window.clear();
        window.setView(fixed);
        window.draw(sprite);
        window.display();
    }

    return EXIT_SUCCESS;
}

Ask your Operation System (OS)

What are the advantages of using this method over the other?

  • The OS will not duplicate the cursor in memory, because it is a shared resource.
  • The OS will use a cursor that the user is used to. For example on windows 7 the user is not used to having an hour glass, but is familiar with some sort of an animated circle.

Class Prototype

Since we have to store the cursor differently for the Linux as for the Windows platform, we’ve introduced an preprocessor switch for the include files and the private class members.

#ifndef STANDARDCURSOR_HPP
#define STANDARDCURSOR_HPP

#include <SFML/System.hpp>
#include <SFML/Window.hpp>

#ifdef SFML_SYSTEM_WINDOWS
    #include <windows.h>
#elif defined(SFML_SYSTEM_LINUX)
    #include <X11/cursorfont.h>
    #include <X11/Xlib.h>
#else
    #error This OS is not yet supported by the cursor library.
#endif

namespace sf
{
    class StandardCursor
    {
    private:
		#ifdef SFML_SYSTEM_WINDOWS

		HCURSOR Cursor; /*Type of the Cursor with Windows*/

		#else

        XID Cursor;
        Display* display;

		#endif
    public:
        enum TYPE{ WAIT, TEXT, NORMAL, HAND /*,...*/ };
        StandardCursor(const TYPE t);
        void set(const sf::WindowHandle& aWindowHandle) const;
        ~StandardCursor();
    };
}

#endif // STANDARDCURSOR_HPP

Class Implementation

Instead of ‘breaking’ the scope with preprocessor statements we’ll define every function twice with a switch for each platform.

#include "StandardCursor.hpp"

#ifdef SFML_SYSTEM_WINDOWS

sf::StandardCursor::StandardCursor(const sf::StandardCursor::TYPE t)
{
    switch(t)
    {
        case sf::StandardCursor::WAIT :
            Cursor = LoadCursor(NULL, IDC_WAIT);
        break;
        case sf::StandardCursor::HAND :
            Cursor = LoadCursor(NULL, IDC_HAND);
        break;
        case sf::StandardCursor::NORMAL :
            Cursor = LoadCursor(NULL, IDC_ARROW);
        break;
        case sf::StandardCursor::TEXT :
            Cursor = LoadCursor(NULL, IDC_IBEAM);
        break;
        //For more cursor options on Windows go here: http://msdn.microsoft.com/en-us/library/ms648391%28v=vs.85%29.aspx
    }
}

void sf::StandardCursor::set(const sf::WindowHandle& aWindowHandle) const
{
	SetClassLongPtr(aWindowHandle, GCLP_HCURSOR, reinterpret_cast<LONG_PTR>(Cursor));
}

sf::StandardCursor::~StandardCursor()
{
	// Nothing to do for destructor : no memory has been allocated (shared ressource principle)
}

#elif defined(SFML_SYSTEM_LINUX)

sf::StandardCursor::StandardCursor(const sf::StandardCursor::TYPE t)
{
    display = XOpenDisplay(NULL);

    switch(t)
    {
        case sf::StandardCursor::WAIT:
            Cursor = XCreateFontCursor(display, XC_watch);
        break;
        case sf::StandardCursor::HAND:
            Cursor = XCreateFontCursor(display, XC_hand1);
        break;
        case sf::StandardCursor::NORMAL:
            Cursor = XCreateFontCursor(display, XC_left_ptr);
        break;
        case sf::StandardCursor::TEXT:
            Cursor = XCreateFontCursor(display, XC_xterm);
        break;
        // For more cursor options on Linux go here: http://www.tronche.com/gui/x/xlib/appendix/b/
    }
}

void sf::StandardCursor::set(const sf::WindowHandle& aWindowHandle) const
{
    XDefineCursor(display, aWindowHandle, Cursor);
    XFlush(display);
}

sf::StandardCursor::~StandardCursor()
{
    XFreeCursor(display, Cursor);
    delete display;
    display = NULL;
}

#else
    #error This OS is not yet supported by the cursor library.
#endif

Cursor Demonstration

This section presents a fully functional demonstration of both cursor changing possibilities.

To get an handle to the window we will use SFML’s sf::Window::getSystemHandle() function and then we will load the cursor with the OS specific implementation.

#include <iostream>
#include <SFML/Graphics.hpp>
#include "StandardCursor.hpp"

int main()
{
	int choice = 0;
	while(choice != 1 && choice != 2)
	{
		std::cout << "t1. Hide the cursor and draw your own." << std::endl;
		std::cout << "t2. Let the OS handle the cursor." << std::endl;
		std::cout << "Choose your cursor behaviour: ";
		std::cin >> choice;
	}

    sf::RenderWindow window(sf::VideoMode(800, 600), "Cursor Demonstration");

	if(choice == 2)
    {
		sf::StandardCursor Cursor(sf::StandardCursor::HAND);
		Cursor.set(window.getSystemHandle());
	}
	else
		window.setMouseCursorVisible(false);

	sf::View fixed = window.getView();
	sf::Texture texture;
	if(!texture.loadFromFile("cursor.png"))
		return EXIT_FAILURE;
	sf::Sprite sprite(texture);

    while(window.isOpen())
    {
		sf::Event event;
		while(window.pollEvent(event))
			if(event.type == sf::Event::Closed)
				window.close();

		window.clear();

		if(choice == 1)
		{
			sprite.setPosition(static_cast<sf::Vector2f>(sf::Mouse::getPosition(window)));
			window.setView(fixed);
			window.draw(sprite);
		}

		window.display();
    }
    return EXIT_SUCCESS;
}

A *.zip file containing both, the code for StandardCursor class and the demonstration and an cursor image, can be obtained through this link: cursor.zip (2.9 KB)

TileMapCreator – Update 01

As promised here comes a small update on the TileMapCreator; screenshot first:

tmc

So this must seem disappointing, nothing really changed, except maybe the gray square on the grid. But then again I’ll have to remind you that TMC is far from being useable and the biggest changes will happen in the codebase which then again don’t necessarily need to be visually present in the application. What did then change?

In the old version I just had one class Grid which handled all the selecting and highlighting decisions next to the rendering part. This ‘method’ got quickly out of hand and there was no useable way to keep track of every cell and its states. But if one ‘object’ has different states why would I want to try really hard to synchronize different vectors? Why not just use another class? So I introduced the new class Cell for which exist just one header file. One cell keeps track of the states highlighted, selected, changed and filled. Additionally if also hold a shared_ptr to the texture or nullptr if the cell doesn’t hold a tile.

For the grid rendering I also thought about for quite a bit, actually it was the first part I changed, and I’ve chosen the following render steps.

for each cell
 if the cell has changed
  draw the blank sprite to clear the cell
  if the cell is filled
   draw tile
  if the cell is selected
   draw selector
  if the cell is highlighted
   draw highlighter
  draw the grid overlay
if one cell has changed
 update the grid texture

This assumes an iteration over all cells doesn’t cost much time. Also I always clear the cell because it’s possible that the tile as some transparent pixels, rendering it on old content would produce a wrong image. This seems to work quite well.

Another approach I could think of would be using multiple render textures for different layers and then combine them at the end. But I don’t really see how it would make a difference in performance and it would probably only increase the GPU memory usage.

As you can see in the screenshot the highlighting already works (again). When ever your mouse cursor hovers over a cell it will get highlighted once and when you leave it, it will get ‘unhighlighted’ and the next cell will get highlighted.

Next up will be selection. For that I’ll have to store the selected cells in a vector or a similar data structure, to tell the grid which should be shown as selected and later to tell the events like delete or place where to work their magic.

TileMapCreator – A GUI tool

Whenever you’re thinking about creating a tile based game you end up with some hackish format for loading tiles. There’s no good way to edit the format and if you forget which number represents which image you’re lost.

Although I’ve never really come close to a functioning tile based game, I often failed at the map load and create functionalities. So I looked a bit around for existing editors and loading functions and there are quite a few like Tiled or Mappy, but they mostly don’t fit my needs or use some proprietary libraries I’m not willing to use, either because of the overhead (e.g. boost) or license (e.g. Qt). With that in mind I decided to create my own editor. I will work it out for quite specific properties and then try to open it up for further settings.

But since this is a blog about my development experience you can guess the editor is still in a very basic state. Once I’ve hardened the code a bit more, I’ll open new project on GitHub, until then you’ll just have to keep reading the updates on this blog.

The GUI concept is quite simple; on the left side there’s a grid which represents the tile map and on the right holds various GUI elements and a list of the existing tiles you can work with. As I was thinking about the GUI I’ve searched a software for fast prototyping with GUIs and ended up with Pencil, which can run as extension in the Firefox browser but you can also use it as native application. It’s a bit of overkill to create a concept image for this simple GUI but I did it anyways:

concept

For the implementation part I first though about using Qt since it provides a very nice interface but since I’d then had to figure out how to use it with SFML I decided to take a better look at SFGUI. It works pretty good but it misses many features you’d expect from a GUI system but since it’s in constant development there’s more to come in near future. I’ll probably post about SFGUI separately since there are a few words more one could talk about it.

Additionally I use the Thor library for handling my resources. Thor acts as an extension to SFML and adds many higher level feature like resource manager and particle systems. For TileMapCreator it seems to be a quite big and the since I don’t really have to share my resources the manager is actually just a easy way to load resources.

So with SFML, SFGUI and Thor I get my base onto which I can build the TileMapCreator. So far I’ve setup the GUI system and created a grid class on which I’ll have to do some tweaking.

TMC

I’ve chosen the icon package Grunge-Icons from icons.mysitemyway.com. I don’t really like them but I couldn’t find anything that does have a big enough resolution and not just 16×16, looks a bit non-standard and can be used freely. So if you have any suggestions please leave a comment!

That’s it for now but I’m sure there will be a few updates before this gets useable.