Files
Cubed/include/entt/entity/group.hpp
zhenyan121 236e7c0433 feature: creature (#38)
* build(deps): add assimp library as dependency

* feat(render): add model loading and rendering pipeline

* refactor(render): rename depth player shaders to depth model and clean up

* build: add EnTT library

* feat(entity): add ECS-based entity rendering

* feat(render): add shadow pass for entity models

* refactor(render): unify model and player rendering with single shader pipeline

* refactor(collision): convert AABB to center-half representation and migrate player data to ECS

* refactor(gameplay): add base classes Chunk and World for shared logic

* feat(gameplay): implement entity movement system with collision detection

- Add Velocity and HitBoxes components to entity
- Introduce HitboxManager for loading per-entity collision AABBs from JSON
- Create MoveSystem with per-axis collision handling
- Move get_block_aabb to base World class and add virtual get_per_tick_time
- Remove static get_block_aabb from ClientWorld; use member m_per_tick_time for tick duration

* fix(gameplay): correct hitbox insertion in HitboxManager::load

* build: remove entt library

* refactor(gameplay): replace entt components with SparseVector for player data

Refactor client world to use a custom SparseVector for player data instead of entt registry. Consolidate Transform, ViewAngles, and related structs into Position, Orientation, WalkPose. Introduce PlayerData and PlayerRenderData. Remove the unused move_system.cpp. Unify player render and shadow render into a single function.

* feat(render): add model ID system with concurrent lookup and namespace-based loading

- Extract `ModelID` and `Model` struct to new `model.hpp`
- Replace `std::unordered_map` with `tbb::concurrent_hash_map` for thread safety
- Add `get_model(ModelID)`, `get_model_id`, `get_model_name` methods
- Parse model names in `namespace:name` format to construct asset paths
- Update `load_model` to accept `string_view` and use ID-based management

* refactor(gameplay): extract movement, gravity, orientation, and walk pose into structs

* refactor(gameplay): extract Entity base class from ClientPlayer

Move position, walk pose, velocity, orientation, movement, and gravity
fields and their accessors into a new Entity base class. ClientPlayer now
inherits from Entity, removing duplicated members. Also update velocity
handling to use 3D vector per axis and adjust related logic.

* feat(player): split max speed into horizontal/vertical, set spawn pos

* refactor: move movement logic into SpeedSystem and Entity components

* refactor(gameplay): extract physics and collision from ClientPlayer into PhysicalSystem

Move per-axis collision detection and move distance calculation to new
PhysicalSystem. Move SpeedSystem implementation from inline header to
separate .cpp file. Add const accessors to Entity. Replace inline AABB
helper with HitboxManager registration of player hitbox using new
PLAYER_SIZE constant. Remove obsolete members and functions from
ClientPlayer.

* refactor(gameplay): integrate model and hitbox ID system into Entity

- Introduce HitboxID, EntityID, and ModelID types for safer ID-based lookups
- Replace AABB struct with Hitbox (includes HitboxID)
- Convert ModelManager and HitboxManager to singletons with Handle structs
- Update Entity to store IDs for model and hitbox, removing direct references
- Reorganize creature model assets into subdirectories per entity type
- Add player model (player.glb) and collision data for pig
- Remove ModelManager dependency from App and Renderer
- Add namespace parsing utility for asset paths
- Mark sparse_vector::insert() with [[nodiscard]]

* build: add entt library

* refactor(gameplay): rename ClientPlayer to LocalPlayer

* refactor(gameplay): separate player logic into manager and ECS components

* feat(gameplay): add entity managers and refactor to ECS components

* refactor(gameplay): replace client thread with timer-based system and add entity manager

* feat(gameplay): implement entity system with concurrent task handling and fix model loading

* feat(gameplay): add entity destruction support

* feat(entity): add client-to-server entity creation and destruction requests

Extend the network protocol with `C2SEntityCreateRequest` and `C2SEntityDestoryRequest` packets. Refactor entity managers to split public client-facing create/destroy methods that send requests over the network, from internal handlers that process received packets. Add utility functions for converting protobuf Vec3 to glm::vec3.

* feat(gameplay): implement entity update packets

Add S2CEntityUpdate to sync entity positions from server to client, including update handling in the client entity manager and server-side AI updates.

* feat(ai): add wander AI system with move boost

Add AIBase and WanderAITag components, a WanderAISystem, and a MoveBoost component to control wandering behavior. Replace the old MoveState with MoveBoost and include a horizontal random direction helper.

* refactor(ecs): move entity physics to tick-based systems

Update PhysicalSystem and SpeedSystem to operate on entt::registry
instead of individual components. Add TickVelocity for server creatures
so movement is calculated per tick without frame delta time. LocalPlayer
now implements its own client-side physics with collision detection.

* feat(gameplay): add server-side entity movement and AI

Refactor LocalPlayer::update_physical to operate on a passed position, and run speed, physical, and wander AI systems in ServerEntityManager.

* feat(gameplay): add pig wander AI and refine speed physics

* feat(server): send entity position updates to all sessions

* fix: correct velocity clamping and hitbox loading

Preserve sign when clamping velocity; negative velocities now clamp to zero instead of flipping direction. Support loading hitbox definitions from JSON arrays and objects. Tune pig entity movement, spawn height, and wander probabilities.

* feat(creatures): refine pig movement physics

Add movement constants for pigs and switch deceleration to per-axis friction so creatures stop naturally. Extend wander boost duration for smoother behavior.

* feat(physics): implement step-up for horizontal collisions

* feat: sync entity direction and rotate models accordingly

Move direction into the transform component and include it in server-to-client entity updates. Client now sets transform direction from the network message and uses it to compute yaw for model rotation, so entities visually face their movement direction. Refactor net_utils to support arbitrary Vec3 fields.

* feat(render): interpolate entity transforms for rendering

Add RenderTransform component to smooth position/direction updates
and use it in entity and shadow passes.

* fix(server_world): send time before entity updates

* build: replace nlohmann json with rapidjson

* refactor(json): migrate from nlohmann to rapidjson

Replace nlohmann::json with rapidjson across localization, hitbox manager, server world, and sensitive filter. Add json_utils helper for converting rapidjson documents to maps, and improve parse error handling.

* feat(item): add item manager with JSON asset loading

Implement ItemManager to load and query item definitions from assets/item JSON files. Add ItemData struct, item asset metadata, CMake source registration, and initialize the manager during app startup. Also add AGENTS.md repository guidelines.

* refactor(item): decouple items from block types

The item system now supports an ItemKind and property, allowing item JSON to declare a type instead of assuming every item is a block. BlockManager was moved to its own header, redesigned around concurrent hash maps, and exposes id_from_name(). Texture and UI code now key items by ItemID, while block placement resolves the block type from the item registry.

* fix(gameplay): use inline const for static EMPTY members

Use inline const for static EMPTY members to avoid ODR and linker issues.
Add missing block_manager.hpp includes in gameplay sources.

* fix: stabilize block item registration and display

Store item names as owned strings in ItemManager, set block type
property for block items, validate item kind before placement, and
handle items without textures gracefully in inventory UI.

* feat: add pig spawn egg item

Add pig spawn egg asset and texture, parse spawn egg item kind and creature property, and spawn the configured entity when used on an empty block. Also fix item texture loading to use actual image dimensions and update selected item UI sizing.

* refactor(gameplay): update systems per entity with chunk check

Refactor server entity update flow to process entities individually,
skipping those whose chunk is not loaded. System update methods now
accept a single entity instead of iterating the full registry view,
and `ServerWorld::get_chunk_ref_count` is added to determine if an
entity's chunk is active.

* perf(render): skip entities outside loaded chunks

* feat: add --direct-enter option to skip to world scene

Support a new CLI flag that launches the app directly into the world scene. If no IP is provided, it starts a local server on the specified port and connects to 127.0.0.1; otherwise it connects to the given IP. With this flag enabled, a port must be specified via -p. Also expose SceneManager::push as public so scenes can be pushed immediately when bypassing the normal menu flow.

* refactor(localization): switch block translations to item naming

Remove the `name_key` field from block definitions and use item-based
localization keys (`item.*.name`) for inventory display. Item data now
stores the localized name at load time.

* feat(gameplay): spawn creatures during chunk generation

Add creature spawning to chunk generation with a configurable
SpawnConfig, including a default pig spawn. Spawning occurs in
the final generation phase and registers entities through the
server world's entity manager.

Also destroy entities when their chunk is unloaded to prevent
orphaned entities and expose the entity manager from ServerWorld.

* feat(gameplay): add run mode based thread pool config

Introduce RunMode enum and thread pool sizing helpers for client,
server, and hybrid modes. Add compute pool to server world and pass
mode through server/client initialization.

* perf(server): parallelize entity update loop

Use parallel_do to process entities concurrently via the compute
pool. Switch get_all_session to a thread-safe
tbb::concurrent_vector and make ChunkEntity's ref_count atomic to
avoid data races. Also remove the debug pig spawn from world init.

* feat(creatures): animate creature walk cycles

Add a Gait component synchronized over the network and procedural animation for model nodes. Load animation parameters from assets/model/creature/pig/animation.json and apply leg swing, body bob, and head motion based on gait. Refactor Gait into its own header for reuse.

* fix(gameplay): make entity interpolation frame-rate independent

* perf(render): batch model rendering with instancing

Replaces per-entity draw calls with instanced rendering for both main and shadow passes. Each model's node hierarchy is flattened once and instance matrices are updated per frame, reducing draw calls and CPU overhead.

* refactor(render): build entity instance buffers once per frame

Move instance matrix upload into build_vertices and use a precomputed
instance data map for both shadow and color passes, avoiding duplicate
GPU buffer updates.

* perf(gameplay): batch entity updates into single packet

Aggregate per-entity update messages into S2CEntityUpdateBatch and
broadcast once per tick. Reuse serialized packets in several broadcast
loops to avoid repeated make_packet calls.

* fix: correct thread count and shadow projection uniform

- Add reserved client thread count to client threads in server generation calculation.
- Set projection matrix uniform only for non-shadow rendering.

* feat(ecs): add entity type separation and creature limits

Replace generic entity creation with typed creatures and items. Rename `add_entity` to `add_creature`, enforce per-player creature cap, and track entity/creature totals for metrics. Expose run mode to dev panel and show new counts.

* perf(render): frustum cull entities before instance building

Add frustum culling to entity instance data collection using AABB vs camera frustum planes. Pass renderer into get_instances_data_map to compute MVP and extract planes. Also add "Rendered Entities" debug counter for visibility.

* feat(audio): add ambient pig sounds

Add pig call audio with randomized timing, triggered by proximity to the player as 3D positional sound.

* feat(client-entity): use snapshot history for entity interpolation

Replace exponential smoothing with a buffered snapshot system. Each entity keeps a deque of position/direction snapshots with timestamps; the render transform is interpolated at a fixed 100 ms render delay to hide network jitter. Snapshots are capped to 16 entries.

* refactor(hitbox): move player hitbox definition to JSON asset

* feat(client_player): use snapshot interpolation for remote players

Replace exponential position smoothing with snapshot interpolation. Remote player transforms are rendered from a delayed snapshot history, using linear interpolation for position and shortest-path interpolation for yaw/pitch. A 100 ms render delay compensates for network tick rate.
2026-08-07 10:19:49 +08:00

1053 lines
39 KiB
C++

#ifndef ENTT_ENTITY_GROUP_HPP
#define ENTT_ENTITY_GROUP_HPP
#include "../config/config.h"
#include "../core/algorithm.hpp"
#include "../core/fwd.hpp"
#include "../core/iterator.hpp"
#include "../core/type_info.hpp"
#include "../core/type_traits.hpp"
#include "../stl/array.hpp"
#include "../stl/concepts.hpp"
#include "../stl/cstddef.hpp"
#include "../stl/iterator.hpp"
#include "../stl/tuple.hpp"
#include "../stl/type_traits.hpp"
#include "../stl/utility.hpp"
#include "entity.hpp"
#include "fwd.hpp"
namespace entt {
/*! @cond ENTT_INTERNAL */
namespace internal {
template<typename, typename, typename>
class extended_group_iterator;
template<typename It, typename... Owned, typename... Get>
class extended_group_iterator<It, owned_t<Owned...>, get_t<Get...>> {
template<typename Type>
[[nodiscard]] auto index_to_element([[maybe_unused]] Type &cpool) const {
if constexpr(stl::is_void_v<typename Type::value_type>) {
return stl::make_tuple();
} else {
return stl::forward_as_tuple(cpool.rbegin()[it.index()]);
}
}
public:
using iterator_type = It;
using value_type = decltype(stl::tuple_cat(stl::make_tuple(*stl::declval<It>()), stl::declval<Owned>().get_as_tuple({})..., stl::declval<Get>().get_as_tuple({})...));
using pointer = input_iterator_pointer<value_type>;
using reference = value_type;
using difference_type = stl::ptrdiff_t;
using iterator_category = stl::input_iterator_tag;
using iterator_concept = stl::forward_iterator_tag;
constexpr extended_group_iterator()
: it{},
pools{} {}
extended_group_iterator(iterator_type from, stl::tuple<Owned *..., Get *...> cpools)
: it{from},
pools{stl::move(cpools)} {}
extended_group_iterator &operator++() noexcept {
return ++it, *this;
}
extended_group_iterator operator++(int) noexcept {
const extended_group_iterator orig = *this;
return ++(*this), orig;
}
[[nodiscard]] reference operator*() const noexcept {
return stl::tuple_cat(stl::make_tuple(*it), index_to_element(*stl::get<Owned *>(pools))..., stl::get<Get *>(pools)->get_as_tuple(*it)...);
}
[[nodiscard]] pointer operator->() const noexcept {
return operator*();
}
[[nodiscard]] constexpr iterator_type base() const noexcept {
return it;
}
template<typename... Args>
[[nodiscard]] constexpr bool operator==(const extended_group_iterator<Args...> &other) const noexcept {
return it == other.it;
}
private:
It it;
stl::tuple<Owned *..., Get *...> pools;
};
struct group_descriptor {
using size_type = stl::size_t;
virtual ~group_descriptor() = default;
[[nodiscard]] virtual bool owned(const id_type) const noexcept {
return false;
}
};
template<typename Type, stl::size_t Owned, stl::size_t Get, stl::size_t Exclude>
class group_handler final: public group_descriptor {
using entity_type = Type::entity_type;
void swap_elements(const stl::size_t pos, const entity_type entt) {
for(size_type next{}; next < Owned; ++next) {
pools[next]->swap_elements((*pools[next])[pos], entt);
}
}
void push_on_construct(const entity_type entt) {
if(stl::apply([entt, pos = len](auto *cpool, auto *...other) { return cpool->contains(entt) && !(cpool->index(entt) < pos) && (other->contains(entt) && ...); }, pools)
&& stl::apply([entt](auto *...cpool) { return (!cpool->contains(entt) && ...); }, filter)) {
swap_elements(len++, entt);
}
}
void push_on_destroy(const entity_type entt) {
if(stl::apply([entt, pos = len](auto *cpool, auto *...other) { return cpool->contains(entt) && !(cpool->index(entt) < pos) && (other->contains(entt) && ...); }, pools)
&& stl::apply([entt](auto *...cpool) { return (0u + ... + cpool->contains(entt)) == 1u; }, filter)) {
swap_elements(len++, entt);
}
}
void remove_if(const entity_type entt) {
if(pools[0u]->contains(entt) && (pools[0u]->index(entt) < len)) {
swap_elements(--len, entt);
}
}
void common_setup() {
// we cannot iterate backwards because we want to leave behind valid entities in case of owned types
for(auto first = pools[0u]->rbegin(), last = first + static_cast<decltype(pools)::difference_type>(pools[0u]->size()); first != last; ++first) {
push_on_construct(*first);
}
}
public:
using common_type = Type;
using size_type = Type::size_type;
template<typename... OGType, typename... EType>
group_handler(stl::tuple<OGType &...> ogpool, stl::tuple<EType &...> epool)
: pools{stl::apply([](auto &&...cpool) { return stl::array<common_type *, (Owned + Get)>{&cpool...}; }, ogpool)},
filter{stl::apply([](auto &&...cpool) { return stl::array<common_type *, Exclude>{&cpool...}; }, epool)} {
stl::apply([this](auto &...cpool) { ((cpool.on_construct().template connect<&group_handler::push_on_construct>(*this), cpool.on_destroy().template connect<&group_handler::remove_if>(*this)), ...); }, ogpool);
stl::apply([this](auto &...cpool) { ((cpool.on_construct().template connect<&group_handler::remove_if>(*this), cpool.on_destroy().template connect<&group_handler::push_on_destroy>(*this)), ...); }, epool);
common_setup();
}
[[nodiscard]] bool owned(const id_type hash) const noexcept override {
for(size_type pos{}; pos < Owned; ++pos) {
if(pools[pos]->info().hash() == hash) {
return true;
}
}
return false;
}
[[nodiscard]] size_type length() const noexcept {
return len;
}
template<stl::size_t Index>
[[nodiscard]] common_type *storage() const noexcept {
if constexpr(Index < (Owned + Get)) {
return pools[Index];
} else {
return filter[Index - (Owned + Get)];
}
}
private:
stl::array<common_type *, (Owned + Get)> pools;
stl::array<common_type *, Exclude> filter;
stl::size_t len{};
};
template<typename Type, stl::size_t Get, stl::size_t Exclude>
class group_handler<Type, 0u, Get, Exclude> final: public group_descriptor {
using entity_type = Type::entity_type;
void push_on_construct(const entity_type entt) {
if(!elem.contains(entt)
&& stl::apply([entt](auto *...cpool) { return (cpool->contains(entt) && ...); }, pools)
&& stl::apply([entt](auto *...cpool) { return (!cpool->contains(entt) && ...); }, filter)) {
elem.push(entt);
}
}
void push_on_destroy(const entity_type entt) {
if(!elem.contains(entt)
&& stl::apply([entt](auto *...cpool) { return (cpool->contains(entt) && ...); }, pools)
&& stl::apply([entt](auto *...cpool) { return (0u + ... + cpool->contains(entt)) == 1u; }, filter)) {
elem.push(entt);
}
}
void remove_if(const entity_type entt) {
elem.remove(entt);
}
void common_setup() {
for(const auto entity: *pools[0u]) {
push_on_construct(entity);
}
}
public:
using common_type = Type;
template<typename Allocator, typename... GType, typename... EType>
group_handler(const Allocator &allocator, stl::tuple<GType &...> gpool, stl::tuple<EType &...> epool)
: pools{stl::apply([](auto &&...cpool) { return stl::array<common_type *, Get>{&cpool...}; }, gpool)},
filter{stl::apply([](auto &&...cpool) { return stl::array<common_type *, Exclude>{&cpool...}; }, epool)},
elem{allocator} {
stl::apply([this](auto &...cpool) { ((cpool.on_construct().template connect<&group_handler::push_on_construct>(*this), cpool.on_destroy().template connect<&group_handler::remove_if>(*this)), ...); }, gpool);
stl::apply([this](auto &...cpool) { ((cpool.on_construct().template connect<&group_handler::remove_if>(*this), cpool.on_destroy().template connect<&group_handler::push_on_destroy>(*this)), ...); }, epool);
common_setup();
}
[[nodiscard]] common_type &handle() noexcept {
return elem;
}
[[nodiscard]] const common_type &handle() const noexcept {
return elem;
}
template<stl::size_t Index>
[[nodiscard]] common_type *storage() const noexcept {
if constexpr(Index < Get) {
return pools[Index];
} else {
return filter[Index - Get];
}
}
private:
stl::array<common_type *, Get> pools;
stl::array<common_type *, Exclude> filter;
common_type elem;
};
} // namespace internal
/*! @endcond */
/**
* @brief Group.
*
* Primary template isn't defined on purpose. All the specializations give a
* compile-time error, but for a few reasonable cases.
*/
template<typename, typename, typename>
class basic_group;
/**
* @brief Non-owning group.
*
* A non-owning group returns all entities and only the entities that are at
* least in the given storage. Moreover, it's guaranteed that the entity list is
* tightly packed in memory for fast iterations.
*
* @b Important
*
* Iterators aren't invalidated if:
*
* * New elements are added to the storage.
* * The entity currently pointed is modified (for example, elements are added
* or removed from it).
* * The entity currently pointed is destroyed.
*
* In all other cases, modifying the pools iterated by the group in any way
* invalidates all the iterators.
*
* @tparam Get Types of storage _observed_ by the group.
* @tparam Exclude Types of storage used to filter the group.
*/
template<typename... Get, typename... Exclude>
class basic_group<owned_t<>, get_t<Get...>, exclude_t<Exclude...>> {
using base_type = stl::common_type_t<typename Get::base_type..., typename Exclude::base_type...>;
using underlying_type = base_type::entity_type;
template<typename Type>
static constexpr stl::size_t index_of = type_list_index_v<stl::remove_const_t<Type>, type_list<typename Get::element_type..., typename Exclude::element_type...>>;
template<stl::size_t... Index>
[[nodiscard]] auto pools_for(stl::index_sequence<Index...>) const noexcept {
using return_type = stl::tuple<Get *...>;
return descriptor ? return_type{static_cast<Get *>(descriptor->template storage<Index>())...} : return_type{};
}
public:
/*! @brief Underlying entity identifier. */
using entity_type = underlying_type;
/*! @brief Unsigned integer type. */
using size_type = stl::size_t;
/*! @brief Signed integer type. */
using difference_type = stl::ptrdiff_t;
/*! @brief Common type among all storage types. */
using common_type = base_type;
/*! @brief Random access iterator type. */
using iterator = common_type::iterator;
/*! @brief Reverse iterator type. */
using reverse_iterator = common_type::reverse_iterator;
/*! @brief Iterable group type. */
using iterable = iterable_adaptor<internal::extended_group_iterator<iterator, owned_t<>, get_t<Get...>>>;
/*! @brief Group handler type. */
using handler = internal::group_handler<common_type, 0u, sizeof...(Get), sizeof...(Exclude)>;
/**
* @brief Group opaque identifier.
* @return Group opaque identifier.
*/
static id_type group_id() noexcept {
return type_hash<basic_group<owned_t<>, get_t<stl::remove_const_t<Get>...>, exclude_t<stl::remove_const_t<Exclude>...>>>::value();
}
/*! @brief Default constructor to use to create empty, invalid groups. */
basic_group() noexcept
: descriptor{} {}
/**
* @brief Constructs a group from a set of storage classes.
* @param ref A reference to a group handler.
*/
basic_group(handler &ref) noexcept
: descriptor{&ref} {}
/**
* @brief Returns the leading storage of a group.
* @return The leading storage of the group.
*/
[[nodiscard]] const common_type &handle() const noexcept {
return descriptor->handle();
}
/**
* @brief Returns the storage for a given element type, if any.
* @tparam Type Type of element of which to return the storage.
* @return The storage for the given element type.
*/
template<typename Type>
[[nodiscard]] auto *storage() const noexcept {
return storage<index_of<Type>>();
}
/**
* @brief Returns the storage for a given index, if any.
* @tparam Index Index of the storage to return.
* @return The storage for the given index.
*/
template<stl::size_t Index>
[[nodiscard]] auto *storage() const noexcept {
using type = type_list_element_t<Index, type_list<Get..., Exclude...>>;
return *this ? static_cast<type *>(descriptor->template storage<Index>()) : nullptr;
}
/**
* @brief Returns the number of entities that are part of the group.
* @return Number of entities that are part of the group.
*/
[[nodiscard]] size_type size() const noexcept {
return *this ? handle().size() : size_type{};
}
/**
* @brief Returns the number of elements that a group has currently
* allocated space for.
* @return Capacity of the group.
*/
[[nodiscard]] size_type capacity() const noexcept {
return *this ? handle().capacity() : size_type{};
}
/*! @brief Requests the removal of unused capacity. */
void shrink_to_fit() {
if(*this) {
descriptor->handle().shrink_to_fit();
}
}
/**
* @brief Checks whether a group is empty.
* @return True if the group is empty, false otherwise.
*/
[[nodiscard]] bool empty() const noexcept {
return !*this || handle().empty();
}
/**
* @brief Returns an iterator to the first entity of the group.
*
* If the group is empty, the returned iterator will be equal to `end()`.
*
* @return An iterator to the first entity of the group.
*/
[[nodiscard]] iterator begin() const noexcept {
return *this ? handle().begin() : iterator{};
}
/**
* @brief Returns an iterator that is past the last entity of the group.
* @return An iterator to the entity following the last entity of the
* group.
*/
[[nodiscard]] iterator end() const noexcept {
return *this ? handle().end() : iterator{};
}
/**
* @brief Returns an iterator to the first entity of the reversed group.
*
* If the group is empty, the returned iterator will be equal to `rend()`.
*
* @return An iterator to the first entity of the reversed group.
*/
[[nodiscard]] reverse_iterator rbegin() const noexcept {
return *this ? handle().rbegin() : reverse_iterator{};
}
/**
* @brief Returns an iterator that is past the last entity of the reversed
* group.
* @return An iterator to the entity following the last entity of the
* reversed group.
*/
[[nodiscard]] reverse_iterator rend() const noexcept {
return *this ? handle().rend() : reverse_iterator{};
}
/**
* @brief Returns the first entity of the group, if any.
* @return The first entity of the group if one exists, the null entity
* otherwise.
*/
[[nodiscard]] entity_type front() const noexcept {
const auto it = begin();
return it != end() ? *it : null;
}
/**
* @brief Returns the last entity of the group, if any.
* @return The last entity of the group if one exists, the null entity
* otherwise.
*/
[[nodiscard]] entity_type back() const noexcept {
const auto it = rbegin();
return it != rend() ? *it : null;
}
/**
* @brief Finds an entity.
* @param entt A valid identifier.
* @return An iterator to the given entity if it's found, past the end
* iterator otherwise.
*/
[[nodiscard]] iterator find(const entity_type entt) const noexcept {
return *this ? handle().find(entt) : iterator{};
}
/**
* @brief Returns the identifier that occupies the given position.
* @param pos Position of the element to return.
* @return The identifier that occupies the given position.
*/
[[nodiscard]] entity_type operator[](const size_type pos) const {
return begin()[static_cast<difference_type>(pos)];
}
/**
* @brief Checks if a group is properly initialized.
* @return True if the group is properly initialized, false otherwise.
*/
[[nodiscard]] explicit operator bool() const noexcept {
return descriptor != nullptr;
}
/**
* @brief Checks if a group contains an entity.
* @param entt A valid identifier.
* @return True if the group contains the given entity, false otherwise.
*/
[[nodiscard]] bool contains(const entity_type entt) const noexcept {
return *this && handle().contains(entt);
}
/**
* @brief Returns the elements assigned to the given entity.
* @tparam Type Type of the element to get.
* @tparam Other Other types of elements to get.
* @param entt A valid identifier.
* @return The elements assigned to the entity.
*/
template<typename Type, typename... Other>
[[nodiscard]] decltype(auto) get(const entity_type entt) const {
return get<index_of<Type>, index_of<Other>...>(entt);
}
/**
* @brief Returns the elements assigned to the given entity.
* @tparam Index Indexes of the elements to get.
* @param entt A valid identifier.
* @return The elements assigned to the entity.
*/
template<stl::size_t... Index>
[[nodiscard]] decltype(auto) get(const entity_type entt) const {
const auto cpools = pools_for(stl::index_sequence_for<Get...>{});
if constexpr(sizeof...(Index) == 0) {
return stl::apply([entt](auto *...curr) { return stl::tuple_cat(curr->get_as_tuple(entt)...); }, cpools);
} else if constexpr(sizeof...(Index) == 1) {
return (stl::get<Index>(cpools)->get(entt), ...);
} else {
return stl::tuple_cat(stl::get<Index>(cpools)->get_as_tuple(entt)...);
}
}
/**
* @brief Iterates entities and elements and applies the given function
* object to them.
*
* The function object is invoked for each entity. It is provided with the
* entity itself and a set of references to non-empty elements. The
* _constness_ of the elements is as requested.<br/>
* The signature of the function must be equivalent to one of the following
* forms:
*
* @code{.cpp}
* void(const entity_type, Type &...);
* void(Type &...);
* @endcode
*
* @note
* Empty types aren't explicitly instantiated and therefore they are never
* returned during iterations.
*
* @tparam Func Type of the function object to invoke.
* @param func A valid function object.
*/
template<typename Func>
void each(Func func) const {
for(const auto entt: *this) {
if constexpr(is_applicable_v<Func, decltype(stl::tuple_cat(stl::tuple<entity_type>{}, stl::declval<basic_group>().get({})))>) {
stl::apply(func, stl::tuple_cat(stl::make_tuple(entt), get(entt)));
} else {
stl::apply(func, get(entt));
}
}
}
/**
* @brief Returns an iterable object to use to _visit_ a group.
*
* The iterable object returns tuples that contain the current entity and a
* set of references to its non-empty elements. The _constness_ of the
* elements is as requested.
*
* @note
* Empty types aren't explicitly instantiated and therefore they are never
* returned during iterations.
*
* @return An iterable object to use to _visit_ the group.
*/
[[nodiscard]] iterable each() const noexcept {
const auto cpools = pools_for(stl::index_sequence_for<Get...>{});
return iterable{{begin(), cpools}, {end(), cpools}};
}
/**
* @brief Sort a group according to the given comparison function.
*
* The comparison function object must return `true` if the first element
* is _less_ than the second one, `false` otherwise. The signature of the
* comparison function should be equivalent to one of the following:
*
* @code{.cpp}
* bool(stl::tuple<Type &...>, stl::tuple<Type &...>);
* bool(const Type &..., const Type &...);
* bool(const Entity, const Entity);
* @endcode
*
* Where `Type` are such that they are iterated by the group.<br/>
* Moreover, the comparison function object shall induce a
* _strict weak ordering_ on the values.
*
* The sort function object must offer a member function template
* `operator()` that accepts three arguments:
*
* * An iterator to the first element of the range to sort.
* * An iterator past the last element of the range to sort.
* * A comparison function to use to compare the elements.
*
* @tparam Type Optional type of element to compare.
* @tparam Other Other optional types of elements to compare.
* @tparam Compare Type of comparison function object.
* @tparam Sort Type of sort function object.
* @tparam Args Types of arguments to forward to the sort function object.
* @param compare A valid comparison function object.
* @param algo A valid sort function object.
* @param args Arguments to forward to the sort function object, if any.
*/
template<typename Type, typename... Other, typename Compare, typename Sort = std_sort, typename... Args>
void sort(Compare compare, Sort algo = Sort{}, Args &&...args) {
sort<index_of<Type>, index_of<Other>...>(stl::move(compare), stl::move(algo), stl::forward<Args>(args)...);
}
/**
* @brief Sort a group according to the given comparison function.
*
* @sa sort
*
* @tparam Index Optional indexes of elements to compare.
* @tparam Compare Type of comparison function object.
* @tparam Sort Type of sort function object.
* @tparam Args Types of arguments to forward to the sort function object.
* @param compare A valid comparison function object.
* @param algo A valid sort function object.
* @param args Arguments to forward to the sort function object, if any.
*/
template<stl::size_t... Index, typename Compare, typename Sort = std_sort, typename... Args>
void sort(Compare compare, Sort algo = Sort{}, Args &&...args) {
if(*this) {
if constexpr(sizeof...(Index) == 0) {
static_assert(stl::is_invocable_v<Compare, const entity_type, const entity_type>, "Invalid comparison function");
descriptor->handle().sort(stl::move(compare), stl::move(algo), stl::forward<Args>(args)...);
} else {
auto comp = [&compare, cpools = pools_for(stl::index_sequence_for<Get...>{})](const entity_type lhs, const entity_type rhs) {
if constexpr(sizeof...(Index) == 1) {
return compare((stl::get<Index>(cpools)->get(lhs), ...), (stl::get<Index>(cpools)->get(rhs), ...));
} else {
return compare(stl::forward_as_tuple(stl::get<Index>(cpools)->get(lhs)...), stl::forward_as_tuple(stl::get<Index>(cpools)->get(rhs)...));
}
};
descriptor->handle().sort(stl::move(comp), stl::move(algo), stl::forward<Args>(args)...);
}
}
}
/**
* @brief Sort entities according to their order in a range.
*
* The shared pool of entities and thus its order is affected by the changes
* to each and every pool that it tracks.
*
* @param first An iterator to the first element of the range of entities.
* @param last An iterator past the last element of the range of entities.
*/
void sort_as(stl::input_iterator auto first, stl::input_iterator auto last) const {
if(*this) {
descriptor->handle().sort_as(first, last);
}
}
private:
handler *descriptor;
};
/**
* @brief Owning group.
*
* Owning groups returns all entities and only the entities that are at
* least in the given storage. Moreover:
*
* * It's guaranteed that the entity list is tightly packed in memory for fast
* iterations.
* * It's guaranteed that all elements in the owned storage are tightly packed
* in memory for even faster iterations and to allow direct access.
* * They stay true to the order of the owned storage and all instances have the
* same order in memory.
*
* The more types of storage are owned, the faster it is to iterate a group.
*
* @b Important
*
* Iterators aren't invalidated if:
*
* * New elements are added to the storage.
* * The entity currently pointed is modified (for example, elements are added
* or removed from it).
* * The entity currently pointed is destroyed.
*
* In all other cases, modifying the pools iterated by the group in any way
* invalidates all the iterators.
*
* @tparam Owned Types of storage _owned_ by the group.
* @tparam Get Types of storage _observed_ by the group.
* @tparam Exclude Types of storage used to filter the group.
*/
template<typename... Owned, typename... Get, typename... Exclude>
class basic_group<owned_t<Owned...>, get_t<Get...>, exclude_t<Exclude...>> {
static_assert(((Owned::storage_policy != deletion_policy::in_place) && ...), "Groups do not support in-place delete");
using base_type = stl::common_type_t<typename Owned::base_type..., typename Get::base_type..., typename Exclude::base_type...>;
using underlying_type = base_type::entity_type;
template<typename Type>
static constexpr stl::size_t index_of = type_list_index_v<stl::remove_const_t<Type>, type_list<typename Owned::element_type..., typename Get::element_type..., typename Exclude::element_type...>>;
template<stl::size_t... Index, stl::size_t... Other>
[[nodiscard]] auto pools_for(stl::index_sequence<Index...>, stl::index_sequence<Other...>) const noexcept {
using return_type = stl::tuple<Owned *..., Get *...>;
return descriptor ? return_type{static_cast<Owned *>(descriptor->template storage<Index>())..., static_cast<Get *>(descriptor->template storage<sizeof...(Owned) + Other>())...} : return_type{};
}
public:
/*! @brief Underlying entity identifier. */
using entity_type = underlying_type;
/*! @brief Unsigned integer type. */
using size_type = stl::size_t;
/*! @brief Signed integer type. */
using difference_type = stl::ptrdiff_t;
/*! @brief Common type among all storage types. */
using common_type = base_type;
/*! @brief Random access iterator type. */
using iterator = common_type::iterator;
/*! @brief Reverse iterator type. */
using reverse_iterator = common_type::reverse_iterator;
/*! @brief Iterable group type. */
using iterable = iterable_adaptor<internal::extended_group_iterator<iterator, owned_t<Owned...>, get_t<Get...>>>;
/*! @brief Group handler type. */
using handler = internal::group_handler<common_type, sizeof...(Owned), sizeof...(Get), sizeof...(Exclude)>;
/**
* @brief Group opaque identifier.
* @return Group opaque identifier.
*/
static id_type group_id() noexcept {
return type_hash<basic_group<owned_t<stl::remove_const_t<Owned>...>, get_t<stl::remove_const_t<Get>...>, exclude_t<stl::remove_const_t<Exclude>...>>>::value();
}
/*! @brief Default constructor to use to create empty, invalid groups. */
basic_group() noexcept
: descriptor{} {}
/**
* @brief Constructs a group from a set of storage classes.
* @param ref A reference to a group handler.
*/
basic_group(handler &ref) noexcept
: descriptor{&ref} {}
/**
* @brief Returns the leading storage of a group.
* @return The leading storage of the group.
*/
[[nodiscard]] const common_type &handle() const noexcept {
return *storage<0>();
}
/**
* @brief Returns the storage for a given element type, if any.
* @tparam Type Type of element of which to return the storage.
* @return The storage for the given element type.
*/
template<typename Type>
[[nodiscard]] auto *storage() const noexcept {
return storage<index_of<Type>>();
}
/**
* @brief Returns the storage for a given index, if any.
* @tparam Index Index of the storage to return.
* @return The storage for the given index.
*/
template<stl::size_t Index>
[[nodiscard]] auto *storage() const noexcept {
using type = type_list_element_t<Index, type_list<Owned..., Get..., Exclude...>>;
return *this ? static_cast<type *>(descriptor->template storage<Index>()) : nullptr;
}
/**
* @brief Returns the number of entities that that are part of the group.
* @return Number of entities that that are part of the group.
*/
[[nodiscard]] size_type size() const noexcept {
return *this ? descriptor->length() : size_type{};
}
/**
* @brief Checks whether a group is empty.
* @return True if the group is empty, false otherwise.
*/
[[nodiscard]] bool empty() const noexcept {
return !*this || !descriptor->length();
}
/**
* @brief Returns an iterator to the first entity of the group.
*
* If the group is empty, the returned iterator will be equal to `end()`.
*
* @return An iterator to the first entity of the group.
*/
[[nodiscard]] iterator begin() const noexcept {
return *this ? (handle().end() - static_cast<difference_type>(descriptor->length())) : iterator{};
}
/**
* @brief Returns an iterator that is past the last entity of the group.
* @return An iterator to the entity following the last entity of the
* group.
*/
[[nodiscard]] iterator end() const noexcept {
return *this ? handle().end() : iterator{};
}
/**
* @brief Returns an iterator to the first entity of the reversed group.
*
* If the group is empty, the returned iterator will be equal to `rend()`.
*
* @return An iterator to the first entity of the reversed group.
*/
[[nodiscard]] reverse_iterator rbegin() const noexcept {
return *this ? handle().rbegin() : reverse_iterator{};
}
/**
* @brief Returns an iterator that is past the last entity of the reversed
* group.
* @return An iterator to the entity following the last entity of the
* reversed group.
*/
[[nodiscard]] reverse_iterator rend() const noexcept {
return *this ? (handle().rbegin() + static_cast<difference_type>(descriptor->length())) : reverse_iterator{};
}
/**
* @brief Returns the first entity of the group, if any.
* @return The first entity of the group if one exists, the null entity
* otherwise.
*/
[[nodiscard]] entity_type front() const noexcept {
const auto it = begin();
return it != end() ? *it : null;
}
/**
* @brief Returns the last entity of the group, if any.
* @return The last entity of the group if one exists, the null entity
* otherwise.
*/
[[nodiscard]] entity_type back() const noexcept {
const auto it = rbegin();
return it != rend() ? *it : null;
}
/**
* @brief Finds an entity.
* @param entt A valid identifier.
* @return An iterator to the given entity if it's found, past the end
* iterator otherwise.
*/
[[nodiscard]] iterator find(const entity_type entt) const noexcept {
const auto it = *this ? handle().find(entt) : iterator{};
return it >= begin() ? it : iterator{};
}
/**
* @brief Returns the identifier that occupies the given position.
* @param pos Position of the element to return.
* @return The identifier that occupies the given position.
*/
[[nodiscard]] entity_type operator[](const size_type pos) const {
return begin()[static_cast<difference_type>(pos)];
}
/**
* @brief Checks if a group is properly initialized.
* @return True if the group is properly initialized, false otherwise.
*/
[[nodiscard]] explicit operator bool() const noexcept {
return descriptor != nullptr;
}
/**
* @brief Checks if a group contains an entity.
* @param entt A valid identifier.
* @return True if the group contains the given entity, false otherwise.
*/
[[nodiscard]] bool contains(const entity_type entt) const noexcept {
return *this && handle().contains(entt) && (handle().index(entt) < (descriptor->length()));
}
/**
* @brief Returns the elements assigned to the given entity.
* @tparam Type Type of the element to get.
* @tparam Other Other types of elements to get.
* @param entt A valid identifier.
* @return The elements assigned to the entity.
*/
template<typename Type, typename... Other>
[[nodiscard]] decltype(auto) get(const entity_type entt) const {
return get<index_of<Type>, index_of<Other>...>(entt);
}
/**
* @brief Returns the elements assigned to the given entity.
* @tparam Index Indexes of the elements to get.
* @param entt A valid identifier.
* @return The elements assigned to the entity.
*/
template<stl::size_t... Index>
[[nodiscard]] decltype(auto) get(const entity_type entt) const {
const auto cpools = pools_for(stl::index_sequence_for<Owned...>{}, stl::index_sequence_for<Get...>{});
if constexpr(sizeof...(Index) == 0) {
return stl::apply([entt](auto *...curr) { return stl::tuple_cat(curr->get_as_tuple(entt)...); }, cpools);
} else if constexpr(sizeof...(Index) == 1) {
return (stl::get<Index>(cpools)->get(entt), ...);
} else {
return stl::tuple_cat(stl::get<Index>(cpools)->get_as_tuple(entt)...);
}
}
/**
* @brief Iterates entities and elements and applies the given function
* object to them.
*
* The function object is invoked for each entity. It is provided with the
* entity itself and a set of references to non-empty elements. The
* _constness_ of the elements is as requested.<br/>
* The signature of the function must be equivalent to one of the following
* forms:
*
* @code{.cpp}
* void(const entity_type, Type &...);
* void(Type &...);
* @endcode
*
* @note
* Empty types aren't explicitly instantiated and therefore they are never
* returned during iterations.
*
* @tparam Func Type of the function object to invoke.
* @param func A valid function object.
*/
template<typename Func>
void each(Func func) const {
for(auto args: each()) {
if constexpr(is_applicable_v<Func, decltype(stl::tuple_cat(stl::tuple<entity_type>{}, stl::declval<basic_group>().get({})))>) {
stl::apply(func, args);
} else {
stl::apply([&func](auto, auto &&...less) { func(stl::forward<decltype(less)>(less)...); }, args);
}
}
}
/**
* @brief Returns an iterable object to use to _visit_ a group.
*
* The iterable object returns tuples that contain the current entity and a
* set of references to its non-empty elements. The _constness_ of the
* elements is as requested.
*
* @note
* Empty types aren't explicitly instantiated and therefore they are never
* returned during iterations.
*
* @return An iterable object to use to _visit_ the group.
*/
[[nodiscard]] iterable each() const noexcept {
const auto cpools = pools_for(stl::index_sequence_for<Owned...>{}, stl::index_sequence_for<Get...>{});
return iterable{{begin(), cpools}, {end(), cpools}};
}
/**
* @brief Sort a group according to the given comparison function.
*
* The comparison function object must return `true` if the first element
* is _less_ than the second one, `false` otherwise. The signature of the
* comparison function should be equivalent to one of the following:
*
* @code{.cpp}
* bool(stl::tuple<Type &...>, stl::tuple<Type &...>);
* bool(const Type &, const Type &);
* bool(const Entity, const Entity);
* @endcode
*
* Where `Type` are either owned types or not but still such that they are
* iterated by the group.<br/>
* Moreover, the comparison function object shall induce a
* _strict weak ordering_ on the values.
*
* The sort function object must offer a member function template
* `operator()` that accepts three arguments:
*
* * An iterator to the first element of the range to sort.
* * An iterator past the last element of the range to sort.
* * A comparison function to use to compare the elements.
*
* @tparam Type Optional type of element to compare.
* @tparam Other Other optional types of elements to compare.
* @tparam Compare Type of comparison function object.
* @tparam Sort Type of sort function object.
* @tparam Args Types of arguments to forward to the sort function object.
* @param compare A valid comparison function object.
* @param algo A valid sort function object.
* @param args Arguments to forward to the sort function object, if any.
*/
template<typename Type, typename... Other, typename Compare, typename Sort = std_sort, typename... Args>
void sort(Compare compare, Sort algo = Sort{}, Args &&...args) const {
sort<index_of<Type>, index_of<Other>...>(stl::move(compare), stl::move(algo), stl::forward<Args>(args)...);
}
/**
* @brief Sort a group according to the given comparison function.
*
* @sa sort
*
* @tparam Index Optional indexes of elements to compare.
* @tparam Compare Type of comparison function object.
* @tparam Sort Type of sort function object.
* @tparam Args Types of arguments to forward to the sort function object.
* @param compare A valid comparison function object.
* @param algo A valid sort function object.
* @param args Arguments to forward to the sort function object, if any.
*/
template<stl::size_t... Index, typename Compare, typename Sort = std_sort, typename... Args>
void sort(Compare compare, Sort algo = Sort{}, Args &&...args) const {
const auto cpools = pools_for(stl::index_sequence_for<Owned...>{}, stl::index_sequence_for<Get...>{});
if constexpr(sizeof...(Index) == 0) {
static_assert(stl::is_invocable_v<Compare, const entity_type, const entity_type>, "Invalid comparison function");
storage<0>()->sort_n(descriptor->length(), stl::move(compare), stl::move(algo), stl::forward<Args>(args)...);
} else {
auto comp = [&compare, &cpools](const entity_type lhs, const entity_type rhs) {
if constexpr(sizeof...(Index) == 1) {
return compare((stl::get<Index>(cpools)->get(lhs), ...), (stl::get<Index>(cpools)->get(rhs), ...));
} else {
return compare(stl::forward_as_tuple(stl::get<Index>(cpools)->get(lhs)...), stl::forward_as_tuple(stl::get<Index>(cpools)->get(rhs)...));
}
};
storage<0>()->sort_n(descriptor->length(), stl::move(comp), stl::move(algo), stl::forward<Args>(args)...);
}
auto cb = [this](auto *head, auto *...other) {
for(auto next = descriptor->length(); next; --next) {
const auto pos = next - 1;
[[maybe_unused]] const auto entt = head->data()[pos];
(other->swap_elements(other->data()[pos], entt), ...);
}
};
stl::apply(cb, cpools);
}
private:
handler *descriptor;
};
} // namespace entt
#endif