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.

Welcome to my development blog

Although I already maintain a blog, I always wanted to write even more about my adventures in the development section. It was actually one of the main reason I started the other blog and if you look closely you could also find quite a few few posts about programming stuff.
Now as I got deeper involved with C++ and SFML I noticed that the common language to write about it is not German but surprise, surprise English.
On the other hand "My-Gate • Blog" got more and more personal which may not be that interesting for tech guys.

The main topics will be about C++ and SFML (Simple and Fast Multimedia Library) although I’ll also write about topics that seem interesting and could be of value to others.

cppsfml

As with all blogs, I hope to contribute here on regular basis and probably will fail doing so from time to time. 🙂