From 92a03ecdb962b0b210c9df8d7dc38ab9d1ed9233 Mon Sep 17 00:00:00 2001 From: lnd3 Date: Tue, 29 Oct 2024 17:25:33 +0100 Subject: [PATCH] Add listener structure directly to component caches. --- packages/ecs/include/ecs/entityecs/ECSExt.h | 49 ++++++++++++++++++++- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/packages/ecs/include/ecs/entityecs/ECSExt.h b/packages/ecs/include/ecs/entityecs/ECSExt.h index 0fe68f7..601811f 100644 --- a/packages/ecs/include/ecs/entityecs/ECSExt.h +++ b/packages/ecs/include/ecs/entityecs/ECSExt.h @@ -182,17 +182,62 @@ namespace l::ecs { } virtual void receive(World*, const Events::OnComponentAssigned2& event) { - tryAdd(event.entity); + if (tryAdd(event.entity)) { + for (auto& listener : mEventListenersAssign) { + listener.second(event); + } + } } virtual void receive(World*, const Events::OnComponentRemoved2& event) { - tryRemove(event.entity); + if (tryRemove(event.entity)) { + for (auto& listener : mEventListenersRemove) { + listener.second(event); + } + } + } + + template + int32_t registerListener(std::function listener) { + if constexpr (std::is_same){ + mEventListenersAssign.push_back({ mIdEnumerator, listener }); + } + else if constexpr (std::is_same){ + mEventListenersRemove.push_back({ mIdEnumerator, listener }); + } + else { + return -1; + } + return mIdEnumerator++; } + template + void unregisterListener(int32_t id) { + if constexpr (std::is_same){ + std::erase_if(mEventListenersAssign, [cid = id](auto& listener) { + if (listener.first == cid) { + return true; + } + return false; + }); + } + else if constexpr (std::is_same){ + std::erase_if(mEventListenersRemove, [cid = id](auto& listener) { + if (listener.first == cid) { + return true; + } + return false; + }); + } + } protected: std::vector...>> mComponents; std::map...>> mComponentMap; + + int32_t mIdEnumerator = 0; + std::vector>> mEventListenersAssign; + std::vector>> mEventListenersRemove; }; class EntitySystem2 : public l::ecs::EntitySystem