Support removing entities while iterating in util::ecs

This commit is contained in:
Nikita Lisitsa 2022-06-23 17:28:34 +03:00
parent b519391f83
commit c6f971a36f

View file

@ -93,7 +93,7 @@ namespace psemek::util
auto visit = [&](auto * ... ptrs) auto visit = [&](auto * ... ptrs)
{ {
if constexpr (std::is_invocable_v<Behavior, typename Components::data & ..., typename Behavior::context &>) if constexpr (std::is_invocable_v<Behavior, typename Components::data & ..., typename Behavior::context const &>)
{ {
behavior(*ptrs..., ctx); behavior(*ptrs..., ctx);
} }
@ -119,7 +119,10 @@ namespace psemek::util
if (*list == i) if (*list == i)
{ {
ctx.entity = i; ctx.entity = i;
ctx.remove = false;
std::apply(visit, cptrs); std::apply(visit, cptrs);
if (ctx.remove)
remove_entity(i);
} }
std::apply(increment, cptrs); std::apply(increment, cptrs);
++list; ++list;
@ -128,12 +131,15 @@ namespace psemek::util
else else
{ {
// packed // packed
std::size_t const size = entity_count(); for (std::size_t i = 0; i < entity_count(); ++i)
for (std::size_t i = 0; i < size; ++i)
{ {
ctx.entity = i; ctx.entity = i;
ctx.remove = false;
std::apply(visit, cptrs); std::apply(visit, cptrs);
std::apply(increment, cptrs); if (ctx.remove)
remove_entity(i);
else
std::apply(increment, cptrs);
} }
} }
} }
@ -323,6 +329,8 @@ namespace psemek::util
component_ptrs components; component_ptrs components;
mutable bool remove = false;
template <typename Component> template <typename Component>
Component & get() const Component & get() const
{ {