Tweaks for EventHook.
continuous-integration/drone/push Build is passing Details

This commit is contained in:
Deukhoofd 2020-07-31 19:52:12 +02:00
parent c3de280ebb
commit fa5184ad77
Signed by: Deukhoofd
GPG Key ID: ADF2E9256009EDCE
3 changed files with 28 additions and 5 deletions

View File

@ -3,9 +3,9 @@
#include <functional>
#include <vector>
#include "../../Library/Exceptions/CreatureException.hpp"
#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.
@ -17,13 +17,20 @@ namespace CreatureLib::Battling {
std::vector<EventHookFunc> _listeners;
size_t _position;
size_t _capacity;
uint8_t* _memory;
uint8_t* _memory = nullptr;
// 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() : _position(0), _capacity(defaultSize), _memory(static_cast<uint8_t*>(malloc(defaultSize))) {
if (_memory == nullptr) {
THROW_CREATURE("Out of memory.");
}
}
EventHook(const EventHook&) = delete;
EventHook& operator=(const EventHook&) = delete;
~EventHook() { free(_memory); }
size_t GetPosition() const noexcept { return _position; }
@ -32,9 +39,12 @@ namespace CreatureLib::Battling {
template <class T, class... parameters> void Trigger(parameters... args) {
if (_listeners.size() == 0)
return;
if (_position + sizeof(T) > _capacity) {
if (_position + sizeof(T) >= _capacity) {
_capacity += defaultSize;
_memory = static_cast<uint8_t*>(realloc(_memory, _capacity));
if (_memory == nullptr) {
THROW_CREATURE("Out of memory.");
}
}
uint8_t* ptr = _memory + _position;
T* event = new (ptr) T(args...);

View File

@ -27,7 +27,7 @@ namespace CreatureLib::Battling {
std::unique_ptr<ChoiceQueue> _currentTurnQueue = nullptr;
bool _hasEnded = false;
BattleResult _battleResult = BattleResult::Empty();
EventHook _eventHook = EventHook();
EventHook _eventHook;
uint32_t _currentTurn = 0;
ScriptSet _volatile;

View File

@ -27,4 +27,17 @@ TEST_CASE("Build and use event hook a lot", "[Battling]") {
REQUIRE(events.size() == 10000);
}
TEST_CASE("Build and use event hook with different types", "[Battling]") {
auto eventHook = EventHook();
std::vector<const EventData*> events;
eventHook.RegisterListener([&](const EventData* evt) mutable -> void { events.push_back(evt); });
eventHook.Trigger<DamageEvent>(nullptr, DamageSource::AttackDamage, 0, 0);
eventHook.Trigger<FaintEvent>(nullptr);
eventHook.Trigger<DamageEvent>(nullptr, DamageSource::AttackDamage, 0, 0);
eventHook.Trigger<FaintEvent>(nullptr);
eventHook.Trigger<DamageEvent>(nullptr, DamageSource::AttackDamage, 0, 0);
eventHook.Trigger<FaintEvent>(nullptr);
eventHook.Trigger<DamageEvent>(nullptr, DamageSource::AttackDamage, 0, 0);
eventHook.Trigger<FaintEvent>(nullptr);
}
#endif