remove all entity components after destroy

This commit is contained in:
2018-12-25 19:53:21 +07:00
parent 828b4ab07e
commit 64b919763d
2 changed files with 35 additions and 7 deletions

22
ecs.hpp
View File

@@ -202,8 +202,11 @@ namespace ecs_hpp
private:
template < typename T >
detail::component_storage<T>* find_storage_() const;
template < typename T >
detail::component_storage<T>& get_or_create_storage_();
std::size_t remove_all_components_impl_(const entity& ent) const noexcept;
private:
mutable std::mutex mutex_;
@@ -297,6 +300,7 @@ namespace ecs_hpp
inline bool world::destroy_entity(const entity& ent) {
std::lock_guard<std::mutex> guard(mutex_);
remove_all_components_impl_(ent);
return entities_.erase(ent) > 0u;
}
@@ -333,13 +337,7 @@ namespace ecs_hpp
inline std::size_t world::remove_all_components(const entity& ent) const noexcept {
std::lock_guard<std::mutex> guard(mutex_);
std::size_t removed_components = 0u;
for ( auto& storage_p : storages_ ) {
if ( storage_p.second->remove(ent.id()) ) {
++removed_components;
}
}
return removed_components;
return remove_all_components_impl_(ent);
}
template < typename T >
@@ -366,4 +364,14 @@ namespace ecs_hpp
return *static_cast<detail::component_storage<T>*>(
emplace_r.first->second.get());
}
inline std::size_t world::remove_all_components_impl_(const entity& ent) const noexcept {
std::size_t removed_components = 0u;
for ( auto& storage_p : storages_ ) {
if ( storage_p.second->remove(ent.id()) ) {
++removed_components;
}
}
return removed_components;
}
}

View File

@@ -119,5 +119,25 @@ TEST_CASE("world") {
REQUIRE(e1.exists_component<velocity_c>());
}
}
{
ecs::world w;
auto e1 = w.create_entity();
auto e2 = w.create_entity();
w.assign_component<position_c>(e1);
w.assign_component<velocity_c>(e1);
w.assign_component<position_c>(e2);
w.assign_component<velocity_c>(e2);
w.destroy_entity(e1);
REQUIRE_FALSE(w.exists_component<position_c>(e1));
REQUIRE_FALSE(w.exists_component<velocity_c>(e1));
REQUIRE(w.exists_component<position_c>(e2));
REQUIRE(w.exists_component<velocity_c>(e2));
}
}
}