Skip to content

Commit

Permalink
Add listener structure directly to component caches.
Browse files Browse the repository at this point in the history
  • Loading branch information
linuscu committed Oct 29, 2024
1 parent f3fa660 commit 92a03ec
Showing 1 changed file with 47 additions and 2 deletions.
49 changes: 47 additions & 2 deletions packages/ecs/include/ecs/entityecs/ECSExt.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<class T>
int32_t registerListener(std::function<void(const T&)> listener) {
if constexpr (std::is_same<T, Events::OnComponentAssigned2>){
mEventListenersAssign.push_back({ mIdEnumerator, listener });
}
else if constexpr (std::is_same<T, Events::OnComponentRemoved2>){
mEventListenersRemove.push_back({ mIdEnumerator, listener });
}
else {
return -1;
}
return mIdEnumerator++;
}

template<class T>
void unregisterListener(int32_t id) {
if constexpr (std::is_same<T, Events::OnComponentAssigned2>){
std::erase_if(mEventListenersAssign, [cid = id](auto& listener) {
if (listener.first == cid) {
return true;
}
return false;
});
}
else if constexpr (std::is_same<T, Events::OnComponentRemoved2>){
std::erase_if(mEventListenersRemove, [cid = id](auto& listener) {
if (listener.first == cid) {
return true;
}
return false;
});
}
}
protected:

std::vector<std::tuple<Entity*, ComponentHandle<Types>...>> mComponents;
std::map<Entity*, std::tuple<ComponentHandle<Types>...>> mComponentMap;

int32_t mIdEnumerator = 0;
std::vector<std::pair<int32_t, std::function<void(const Events::OnComponentAssigned2&)>>> mEventListenersAssign;
std::vector<std::pair<int32_t, std::function<void(const Events::OnComponentRemoved2&)>>> mEventListenersRemove;
};

class EntitySystem2 : public l::ecs::EntitySystem
Expand Down

0 comments on commit 92a03ec

Please sign in to comment.