Actions Tutorial

Welcome to the tutorial about the Events module. Here, you will learn how to build up an object-oriented event system. From SFML, you know the procedural way of event handling, namely polling:

while (window.PollEvent(event))
{
    // switch on event type
}

However, this approach has a few drawbacks. You have to differentiate the types explicitly, and your code reacting to the events is gathered in one place. The single events are hardwired as compile-time constants after each case mark. That makes it complicated to change controls according to the user's request.

The Action system of Thor's Events module has been designed with the following thoughts in mind:

Actions

The class thor::Action represents an action. It can be used in the following situations:

We say that an action is active if the event or input state specified in the constructor has been triggered. In the following example, we define some actions. The comments explain when each action is active.

thor::Action a(sf::Keyboard::X, thor::Action::PressOnce); // Key X is pressed once
thor::Action b(sf::Mouse::Left, thor::Action::Realtime);  // Left mouse button is currently held down
thor::Action c(sf::Event::Closed);                        // SFML Window is closed
We can even combine multiple actions! The following creates an action which is active when both a and b are active:
thor::Action both = a && b;
The same works if at least one of them must be active in order to activate the combined action:
thor::Action atLeastOne = a || b;
Of course, you can build arbitrary complex expressions using the overloaded AND and OR operators.

Action maps

Now we have defined some actions, but how can we use them? Here, the class template thor::ActionMap comes into play.

This class template maps IDs to actions. IDs can be of any comparable type, for example std::string or a user-defined enumeration. This type is specified in the template parameter. When we initialize an action map object, we have to pass the window that is used for event generation:

sf::Window window(...);
thor::ActionMap<std::string> map(window);

We have defined an action map that stores std::string identifiers associated with thor::Action instances. Now let's introduce meaningful IDs and associate them with the actions above:

map["run"] = a;
map["shoot"] = b;
map["quit"] = c;
Now the action map knows our actions. We can check if an action is currently active by writing
if (map.IsActive("run"))
     // React to "run" action
if (map.IsActive("shoot"))
     // React to "shoot" action
if (map.IsActive("quit"))
     // React to "quit" action
How does the action map know if an action is active? In order to make this possible, we need to feed it with the SFML events occurred every frame. This is automatically done if we call the thor::ActionMap::Update() method. Here is an example of a main loop:
while (window.IsOpened())
{
    // Poll the window for new events, update actions
    map.Update();

    // React to different action types
    if (map.IsActive("quit"))
        window.Close();

    // Update window
    window.Display();
}

As an alternative to Update(), thor::ActionMap provides the methods PushEvent() to add an SFML event and ClearEvents() to remove old events. These methods exist for more flexibility, if you want to poll the window yourself and decide which events are forwarded to the action map. Using this approach, you can write the following code:

while (window.IsOpened())
{
    // Clear events from last frame
    map.ClearEvents();

    // Forward all events to the action map
    sf::Event event;
    while (window.PollEvent(event))
        map.PushEvent(event);

    // React to different action types
    if (map.IsActive("quit"))
        window.Close();

    // Update window
    window.Display();
}     

Connecting callbacks

Actions can act as triggers for function invocations. Let’s call the functions associated to the different event types “listeners” (other terms are “callbacks”, “slots”, “event handlers” or “observers”).

What we need now are the listeners that are invoked if an action is active. Listener functions return void and take a parameter of type thor::ActionContext with your ID type as template argument. This parameter contains information about the context in which an action was fired (for example the original sf::Event that triggered the action).

Define a listener for actions with the ID"shoot":

void OnShoot(thor::ActionContext<MyAction> context)
{
    // context.Window is a pointer to the sf::Window passed to the thor::ActionMap constructor. It can
    // be used for mouse input relative to a window, as follows:
    sf::Vector2i mousePosition = sf::Mouse::GetPosition(*context.Window);

    // Do something with the mouse position...
}

Using the class template thor::EventSystem, you can associate different action types with different functions. thor::ActionMap contains a member typedef CallbackSystem for the correct type. Let's instantiate such a callback system and connect the ID "shoot"with the just defined callback OnShoot():

thor::ActionMap<std::string>::CallbackSystem system;
system.Connect("shoot", &OnShoot);

The callback system is ready to call the correct functions if an action is triggered. We only need to forward the actions from thor::ActionMap to the CallbackSystem. We can do this in the main loop, instead of the IsActive() calls:

map.InvokeCallbacks(system);

The callback mechanism is quite powerful. The second parameter of Connect() can not only be a pointer to function like in the above example, rather any compatible callable is allowed. That is, you can also pass function objects, especially instances of std::tr1::function. Besides, you are able to connect any number of listeners to one action type, just invoke Connect()once for each listener.

Another example is a listener that moves a sprite when the player is running:

void MoveSprite(sf::Sprite& sprite)
{
    sprite.Move(10.f, 0.f);
}

Here, we can’t register MoveSprite() directly at the event system, because the parameter list doesn’t match (sf::Sprite& vs.thor::ActionContext<std::string>). But we can build a function object:

struct SpriteMover
{
    explicit SpriteMover(sf::Sprite& sprite)
    : sprite(sprite)
    {
    }

    void operator() (thor::ActionContext<std::string>)
    {
        // ignore parameter
        sprite.Move(10.f, 0.f);
    }

    sf::Sprite& sprite;
};

Then the registration looks like this:

sf::Sprite playerSprite;
system.Connect("run", SpriteMover(playerSprite));

Binders [advanced]

This is a chapter that requires rather advanced C++ knowledge, so depending on your skills, you might want to skip it. You can use the whole functionality of the event systems in Thor without binders, however they can simplify things a lot.

You may think, the functor SpriteMover needs quite a lot code to achieve a single-line functionality. You are right. Fortunately, C++ offers other ways, namely binders. The library Boost.Bind (which has made it into TR1) contains a bunch of tools to compose new functions on-the-fly. If you are unfamiliar to binders, you should have a look at the Boost documentation – you don’t need Boost though, the TR1 is enough. First, we write a line to simplify the usage of the TR1 namespaces:


namespace tr1 = std::tr1;
Using the global function MoveSprite() from above, the registration looks like the following. You need tr1::ref to pass the sprite as reference.
sf::Sprite playerSprite;
system.Connect("run", tr1::bind(&MoveSprite, tr1::ref(playerSprite)));

We got rid of the class and all the constructor/member/initialization stuff. But honestly, that annoying function does nothing more than forwarding a call to a member. Since binders support member functions, why not use them to call sf::Sprite::Move() directly?

sf::Sprite playerSprite;
system.Connect("run", tr1::bind(&sf::Sprite::Move, &playerSprite, 10.f, 0.f));

Now all the functionality is contained in a single line, and we are relieved from writing boilerplate code.

Disconnecting callbacks

With the function thor::EventSystem::Connect(), you have the possibility to add event-listener connections. But you don't know how to remove them from the system as soon as they aren’t needed anymore. The member function Connect() returns an object of type thor::Connection which exists exactly for this purpose. You can store it and call its method Disconnect() later to disconnect the listener from the event.

thor::Connection connection = system.Connect("shoot", &OnShoot);
connection.Disconnect();

A connection automatically becomes invalid when the referenced listener is disconnected, so you can’t disconnect a listener accidentally more than once. To disconnect all listeners associated with a given event type, call thor::EventSystem::ClearConnections().