51 lines
1.7 KiB
C++
51 lines
1.7 KiB
C++
#ifndef CREATURELIB_EVENTHOOK_HPP
|
|
#define CREATURELIB_EVENTHOOK_HPP
|
|
|
|
#include <functional>
|
|
#include <vector>
|
|
#include "EventData.hpp"
|
|
|
|
|
|
namespace CreatureLib::Battling {
|
|
/// The Event Hook class allows users to write consumers for the battle events, for example to write User Interfaces
|
|
/// for it.
|
|
class EventHook {
|
|
public:
|
|
typedef std::function<void(const CreatureLib::Battling::EventData*)> EventHookFunc;
|
|
|
|
private:
|
|
std::vector<EventHookFunc> _listeners;
|
|
size_t _position;
|
|
size_t _capacity;
|
|
uint8_t* _memory;
|
|
|
|
// Consider tweaking this size to be in line with the normal amount of events we use.
|
|
static const size_t defaultSize = 1024;
|
|
|
|
public:
|
|
EventHook() : _position(0), _capacity(defaultSize), _memory(static_cast<uint8_t*>(malloc(defaultSize))) {}
|
|
~EventHook() { free(_memory); }
|
|
|
|
size_t GetPosition() const noexcept { return _position; }
|
|
size_t GetCapacity() const noexcept { return _capacity; }
|
|
|
|
template <class T, class... parameters> void Trigger(parameters... args) {
|
|
if (_listeners.size() == 0)
|
|
return;
|
|
if (_position + sizeof(T) > _capacity) {
|
|
_capacity += defaultSize;
|
|
_memory = static_cast<uint8_t*>(realloc(_memory, _capacity));
|
|
}
|
|
uint8_t* ptr = _memory + _position;
|
|
T* event = new (ptr) T(args...);
|
|
_position += sizeof(T);
|
|
for (auto listener : _listeners) {
|
|
listener(event);
|
|
}
|
|
}
|
|
|
|
void RegisterListener(const EventHookFunc& func) { _listeners.push_back(func); }
|
|
};
|
|
}
|
|
#endif // CREATURELIB_EVENTHOOK_HPP
|