StevEngine
StevEngine is a customizable C++ game engine.
Loading...
Searching...
No Matches
EventSystem.hpp
1#pragma once
2#include "utilities/ID.hpp"
3#include <functional>
4#include <string>
5#include <unordered_map>
6#include <vector>
7
8namespace StevEngine {
12 class Event {
13 public:
18 virtual const std::string GetEventType() const = 0;
19 };
20
22 template<typename EventType> using EventFunction = std::function<void(const EventType& e)>;
23
28 public:
33 virtual void Execute(const Event& e) = 0;
34
39 Utilities::ID GetType() const { return handlerType; }
40
41 virtual ~EventHandlerBase() {}
42
44 };
45
49 template<typename EventType>
51 public:
56 explicit EventHandler(const EventFunction<EventType>& handler) : handler(handler) {};
57
58 void Execute(const Event& event) override
59 {
60 if (event.GetEventType() == EventType::GetStaticEventType()) {
61 handler(static_cast<const EventType&>(event));
62 }
63 }
64
65 ~EventHandler() {}
66
67 private:
68 EventFunction<EventType> handler;
69 };
70
75 public:
82 template<typename EventType> Utilities::ID Subscribe(EventFunction<EventType> handler) {
83 return Subscribe(EventType::GetStaticEventType(), new EventHandler<EventType>(handler));
84 }
85
91 void Unsubscribe(const std::string eventId, const Utilities::ID handler);
92
97 void Publish(const Event& event);
98
99 private:
106 Utilities::ID Subscribe(const std::string eventId, EventHandlerBase* handler);
107
109 std::unordered_map<std::string, std::vector<EventHandlerBase*>> subscribers;
110 };
111}
Base class for event handlers.
Definition EventSystem.hpp:27
const Utilities::ID handlerType
Unique handler identifier.
Definition EventSystem.hpp:43
Utilities::ID GetType() const
Get handler type ID.
Definition EventSystem.hpp:39
virtual void Execute(const Event &e)=0
Execute handler with event.
Typed event handler implementation.
Definition EventSystem.hpp:50
void Execute(const Event &event) override
Execute handler with event.
Definition EventSystem.hpp:58
EventHandler(const EventFunction< EventType > &handler)
Create new event handler.
Definition EventSystem.hpp:56
Manages event subscriptions and publishing.
Definition EventSystem.hpp:74
void Publish(const Event &event)
Publish event to subscribers.
Definition EventSystem.cpp:28
void Unsubscribe(const std::string eventId, const Utilities::ID handler)
Unsubscribe from event.
Definition EventSystem.cpp:17
Utilities::ID Subscribe(EventFunction< EventType > handler)
Subscribe to event type.
Definition EventSystem.hpp:82
Base class for all engine events.
Definition EventSystem.hpp:12
virtual const std::string GetEventType() const =0
Get type identifier for this event.
UUID-based unique identifier.
Definition ID.hpp:13