r-type  0.0.0
R-Type main
Loading...
Searching...
No Matches
EntityManager.hpp
Go to the documentation of this file.
1///
2/// @file EntityManager.hpp
3/// @brief Centralized entity lifecycle management system for R-Type server
4/// @details This file contains the EntityManager class which provides a complete entity
5/// management system for the R-Type game server. It handles creation, destruction,
6/// tracking, and synchronization of all game entities including players, enemies,
7/// projectiles, and powerups. The manager maintains network IDs for entity
8/// synchronization and provides factory methods for entity creation with proper
9/// component initialization.
10/// @namespace gme
11/// @author R-Type Team
12/// @date 2025
13///
14
15#pragma once
16
17#include "ECS/Component.hpp"
18#include "ECS/Entity.hpp"
19#include "ECS/Registry.hpp"
21#include <memory>
22#include <unordered_map>
23#include <unordered_set>
24#include <vector>
25
26namespace gme
27{
28 ///
29 /// @enum ServerEntityType
30 /// @brief Enumeration of entity types managed by the server
31 /// @details Categorizes entities for proper handling, network synchronization,
32 /// and behavior assignment. Each type has specific properties and behaviors.
33 ///
34 enum class ServerEntityType : uint8_t
35 {
36 PLAYER = 0, ///< Player-controlled entity
37 ENEMY_BASIC = 1, ///< Basic enemy type (simple behavior)
38 ENEMY_ADVANCED = 2, ///< Advanced enemy type (complex behavior)
39 BOSS = 3, ///< Boss enemy (high health, special patterns)
40 PROJECTILE_PLAYER = 4, ///< Player-fired projectile
41 PROJECTILE_ENEMY = 5, ///< Enemy-fired projectile
42 POWERUP = 6 ///< Collectible powerup item
43 };
44
45 ///
46 /// @struct EntityMetadata
47 /// @brief Metadata structure for tracking entity lifecycle and properties
48 /// @details Stores additional information about entities beyond ECS components,
49 /// including network synchronization data, lifetime management, and ownership.
50 ///
52 {
53 ecs::Entity entity; ///< ECS entity handle
54 ServerEntityType type; ///< Entity type classification
55 std::uint32_t networkId; ///< Unique ID used in network synchronization packets
56 bool isActive; ///< Whether entity is currently active
57 float lifetime; ///< Maximum lifetime in seconds (-1 for infinite)
58 float currentLife; ///< Elapsed lifetime counter in seconds
59 std::uint32_t ownerId; ///< Owner entity ID (for projectiles, the spawner)
60 };
61
62 ///
63 /// @class EntityManager
64 /// @brief Central entity lifecycle manager for the R-Type game server
65 /// @details This class provides comprehensive entity management including:
66 /// - Entity creation with proper component initialization
67 /// - Entity destruction and cleanup
68 /// - Network ID assignment and tracking
69 /// - Lifetime management for temporary entities
70 /// - Player score tracking
71 /// - Network state synchronization
72 /// - Reverse lookups (entity <-> network ID)
73 ///
74 /// The manager maintains separate containers for different entity types and ensures
75 /// proper cleanup of destroyed entities. All entities are assigned unique network IDs
76 /// for client-server synchronization.
77 ///
78 /// @namespace gme
79 ///
81 {
82 public:
83 ///
84 /// @brief Constructor
85 /// @param registry Reference to the ECS registry
86 /// @details Initializes the entity manager with a reference to the game's ECS registry
87 ///
88 explicit EntityManager(ecs::Registry &registry);
89
90 ///
91 /// @brief Destructor
92 ///
93 ~EntityManager() = default;
94
95 /// @brief Deleted copy constructor (non-copyable)
96 EntityManager(const EntityManager &) = delete;
97 /// @brief Deleted copy assignment operator (non-copyable)
99 /// @brief Deleted move constructor (non-movable)
101 /// @brief Deleted move assignment operator (non-movable)
103
104 // ========== Player Management ==========
105
106 ///
107 /// @brief Create a new player entity
108 /// @param sessionId Network session ID of the player
109 /// @param x Initial X position
110 /// @param y Initial Y position
111 /// @return Created player entity handle
112 /// @details Creates a player entity with all required components (Transform, Velocity,
113 /// Health, Hitbox, NetworkId) and registers it for tracking
114 ///
115 ecs::Entity createPlayer(std::uint32_t sessionId, float x, float y);
116
117 ///
118 /// @brief Destroy a player entity
119 /// @param sessionId Network session ID of the player to destroy
120 /// @details Removes player from tracking and queues entity for destruction
121 ///
122 void destroyPlayer(std::uint32_t sessionId);
123
124 ///
125 /// @brief Get player entity by session ID
126 /// @param sessionId Network session ID
127 /// @return Player entity handle (may be invalid if player doesn't exist)
128 ///
129 ecs::Entity getPlayer(std::uint32_t sessionId);
130
131 ///
132 /// @brief Get player entity by session ID (const version)
133 /// @param sessionId Network session ID
134 /// @return Player entity handle
135 ///
136 ecs::Entity getPlayerEntity(std::uint32_t sessionId) const;
137
138 ///
139 /// @brief Check if player exists
140 /// @param sessionId Network session ID
141 /// @return True if player exists and is registered
142 ///
143 bool hasPlayer(std::uint32_t sessionId) const;
144
145 ///
146 /// @brief Mark a player as dead without destroying the entity
147 /// @param sessionId Network session ID
148 /// @details Adds player to dead players set, useful for game over detection
149 ///
150 void markPlayerAsDead(std::uint32_t sessionId);
151
152 ///
153 /// @brief Get count of alive players
154 /// @return Number of players not marked as dead
155 ///
156 std::uint32_t getAlivePlayerCount() const;
157
158 ///
159 /// @brief Get all player entities
160 /// @return Const reference to map of session ID to player entity
161 ///
162 const std::unordered_map<std::uint32_t, ecs::Entity> &getPlayers() const { return m_playerEntities; }
163
164 ///
165 /// @brief Add points to a player's score
166 /// @param sessionId Network session ID of the player
167 /// @param points Points to add (can be negative)
168 ///
169 void addScore(std::uint32_t sessionId, int points);
170
171 ///
172 /// @brief Get player's current score
173 /// @param sessionId Network session ID
174 /// @return Current score (0 if player not found)
175 ///
176 int getScore(std::uint32_t sessionId) const;
177
178 ///
179 /// @brief Reset player's score to zero
180 /// @param sessionId Network session ID
181 ///
182 void resetScore(std::uint32_t sessionId);
183
184 ///
185 /// @brief Create a basic enemy entity
186 /// @param x Spawn X position
187 /// @param y Spawn Y position
188 /// @param health Initial health (default: 50.0)
189 /// @return Created enemy entity handle
190 /// @details Creates basic enemy with simple AI behavior
191 ///
192 ecs::Entity createBasicEnemy(float x, float y, float health = 50.0f);
193
194 ///
195 /// @brief Create an advanced enemy entity
196 /// @param x Spawn X position
197 /// @param y Spawn Y position
198 /// @param health Initial health (default: 100.0)
199 /// @return Created enemy entity handle
200 /// @details Creates advanced enemy with complex AI behavior
201 ///
202 ecs::Entity createAdvancedEnemy(float x, float y, float health = 100.0f);
203
204 ///
205 /// @brief Create a boss enemy entity
206 /// @param x Spawn X position
207 /// @param y Spawn Y position
208 /// @param health Initial health (default: 1000.0)
209 /// @return Created boss entity handle
210 /// @details Creates boss with special AI and high durability
211 ///
212 ecs::Entity createBoss(float x, float y, float health = 1000.0f);
213
214 ///
215 /// @brief Destroy an enemy entity
216 /// @param enemyId Network ID of the enemy
217 ///
218 void destroyEnemy(std::uint32_t enemyId);
219
220 ///
221 /// @brief Get enemy entity by network ID
222 /// @param enemyId Network ID of the enemy
223 /// @return Enemy entity handle
224 ///
225 ecs::Entity getEnemy(std::uint32_t enemyId);
226
227 ///
228 /// @brief Get all enemy entities
229 /// @return Const reference to map of network ID to enemy entity
230 ///
231 const std::unordered_map<std::uint32_t, ecs::Entity> &getEnemies() const { return m_enemyEntities; }
232
233 ///
234 /// @brief Create a player projectile entity
235 /// @param playerId Session ID of the player who fired
236 /// @param x Initial X position
237 /// @param y Initial Y position
238 /// @param vx X velocity
239 /// @param vy Y velocity
240 /// @param isSupercharged Whether this is a powered-up shot (default: false)
241 /// @return Created projectile entity handle
242 ///
243 ecs::Entity createPlayerProjectile(std::uint32_t playerId, float x, float y, float vx, float vy,
244 bool isSupercharged = false);
245
246 ///
247 /// @brief Create an enemy projectile entity
248 /// @param enemyId Network ID of the enemy who fired
249 /// @param x Initial X position
250 /// @param y Initial Y position
251 /// @param vx X velocity
252 /// @param vy Y velocity
253 /// @return Created projectile entity handle
254 ///
255 ecs::Entity createEnemyProjectile(std::uint32_t enemyId, float x, float y, float vx, float vy);
256
257 ///
258 /// @brief Destroy a projectile entity
259 /// @param projectileId Network ID of the projectile
260 ///
261 void destroyProjectile(std::uint32_t projectileId);
262
263 ///
264 /// @brief Get projectile entity by network ID
265 /// @param projectileId Network ID of the projectile
266 /// @return Projectile entity handle
267 ///
268 ecs::Entity getProjectile(std::uint32_t projectileId);
269
270 ///
271 /// @brief Get all projectile entities
272 /// @return Const reference to map of network ID to projectile entity
273 ///
274 const std::unordered_map<std::uint32_t, ecs::Entity> &getProjectiles() const
275 {
277 }
278
279 ///
280 /// @brief Create a powerup entity
281 /// @param x Spawn X position
282 /// @param y Spawn Y position
283 /// @param powerupType Type of powerup (0-255)
284 /// @return Created powerup entity handle
285 ///
286 ecs::Entity createPowerup(float x, float y, uint8_t powerupType);
287
288 ///
289 /// @brief Destroy a powerup entity
290 /// @param powerupId Network ID of the powerup
291 ///
292 void destroyPowerup(std::uint32_t powerupId);
293
294 ///
295 /// @brief Update lifetime counters for temporary entities
296 /// @param deltaTime Time elapsed since last frame (seconds)
297 /// @details Increments currentLife for entities with limited lifetime and destroys
298 /// entities that have exceeded their lifetime
299 ///
300 void updateLifetimes(float deltaTime);
301
302 ///
303 /// @brief Process destruction queue and remove destroyed entities
304 /// @details Should be called after all systems have updated to safely remove entities
305 ///
307
308 ///
309 /// @brief Get entity metadata by network ID
310 /// @param networkId Network ID of the entity
311 /// @return Pointer to metadata (nullptr if not found)
312 ///
313 EntityMetadata *getEntityMetadata(std::uint32_t networkId);
314
315 ///
316 /// @brief Get entity metadata by network ID (const version)
317 /// @param networkId Network ID of the entity
318 /// @return Const pointer to metadata (nullptr if not found)
319 ///
320 const EntityMetadata *getEntityMetadata(std::uint32_t networkId) const;
321
322 ///
323 /// @brief Get network ID for an entity handle
324 /// @param entity ECS entity handle
325 /// @return Network ID (0 if not found)
326 ///
327 std::uint32_t getNetworkIdForEntity(ecs::Entity entity) const;
328
329 ///
330 /// @brief Get network state for all entities
331 /// @return Vector of EntityState structures for network transmission
332 /// @details Creates snapshot of all entity positions, velocities, and states
333 /// for synchronization with clients
334 ///
335 std::vector<rnp::EntityState> getAllEntityStates() const;
336
337 ///
338 /// @brief Convert server entity type to network protocol entity type
339 /// @param type Server entity type
340 /// @return Corresponding network protocol entity type
341 ///
343
344 ///
345 /// @brief Clear all entities and reset manager state
346 /// @details Destroys all entities and resets ID generators
347 ///
348 void clear();
349
350 ///
351 /// @brief Get total count of all managed entities
352 /// @return Total number of active entities
353 ///
354 size_t getTotalEntityCount() const;
355
356 private:
357 ecs::Registry &m_registry; ///< Reference to ECS registry
358
359 // Entity containers (networkId -> Entity)
360 std::unordered_map<std::uint32_t, ecs::Entity> m_playerEntities; ///< Player entities by session ID
361 std::unordered_map<std::uint32_t, ecs::Entity> m_enemyEntities; ///< Enemy entities by network ID
362 std::unordered_map<std::uint32_t, ecs::Entity> m_projectileEntities; ///< Projectile entities by network ID
363 std::unordered_map<std::uint32_t, ecs::Entity> m_powerupEntities; ///< Powerup entities by network ID
364
365 // Metadata tracking (networkId -> Metadata)
366 std::unordered_map<std::uint32_t, EntityMetadata> m_entityMetadata; ///< Entity metadata by network ID
367
368 // Dead players tracking
369 std::unordered_set<std::uint32_t> m_deadPlayers; ///< Set of dead player session IDs
370
371 // Score tracking (sessionId -> score)
372 std::unordered_map<std::uint32_t, int> m_playerScores; ///< Player scores by session ID
373
374 // Reverse lookup (Entity -> networkId)
375 std::unordered_map<ecs::Entity, std::uint32_t> m_entityToNetworkId; ///< Reverse lookup map
376
377 // ID generators
378 std::uint32_t m_nextEnemyId = 2000; ///< Next available enemy network ID
379 std::uint32_t m_nextProjectileId = 1000; ///< Next available projectile network ID
380 std::uint32_t m_nextPowerupId = 5000; ///< Next available powerup network ID
381
382 // Destruction queue (to avoid modifying containers during iteration)
383 std::vector<std::uint32_t> m_destroyQueue; ///< Queue of network IDs pending destruction
384
385 ///
386 /// @brief Register a new entity with the manager
387 /// @param entity ECS entity handle
388 /// @param type Entity type classification
389 /// @param networkId Network ID for synchronization
390 /// @param lifetime Maximum lifetime in seconds (-1.0 for infinite)
391 /// @param ownerId Owner entity ID (for projectiles)
392 ///
393 void registerEntity(ecs::Entity entity, ServerEntityType type, std::uint32_t networkId,
394 float lifetime = -1.0f, std::uint32_t ownerId = 0);
395
396 ///
397 /// @brief Unregister an entity from the manager
398 /// @param networkId Network ID of the entity to unregister
399 ///
400 void unregisterEntity(std::uint32_t networkId);
401
402 ///
403 /// @brief Process pending entity destructions from queue
404 /// @details Safely removes entities that were queued for destruction
405 ///
406 void processDestroyQueue();
407 };
408
409} // namespace gme
This file contains the component definitions.
This file contains the entity definitions.
This file contains the network protocol.
This file contains the Registry class declaration.
Class for managing entities and their components.
Definition Registry.hpp:25
Central entity lifecycle manager for the R-Type game server.
ecs::Entity getPlayer(std::uint32_t sessionId)
Get player entity by session ID.
std::unordered_map< std::uint32_t, EntityMetadata > m_entityMetadata
Entity metadata by network ID.
ecs::Entity getProjectile(std::uint32_t projectileId)
Get projectile entity by network ID.
void addScore(std::uint32_t sessionId, int points)
Add points to a player's score.
std::uint32_t m_nextEnemyId
Next available enemy network ID.
bool hasPlayer(std::uint32_t sessionId) const
Check if player exists.
void cleanupDestroyedEntities()
Process destruction queue and remove destroyed entities.
void markPlayerAsDead(std::uint32_t sessionId)
Mark a player as dead without destroying the entity.
void destroyPlayer(std::uint32_t sessionId)
Destroy a player entity.
ecs::Entity createPlayerProjectile(std::uint32_t playerId, float x, float y, float vx, float vy, bool isSupercharged=false)
Create a player projectile entity.
void updateLifetimes(float deltaTime)
Update lifetime counters for temporary entities.
EntityManager(ecs::Registry &registry)
Constructor.
std::unordered_map< std::uint32_t, ecs::Entity > m_powerupEntities
Powerup entities by network ID.
const std::unordered_map< std::uint32_t, ecs::Entity > & getEnemies() const
Get all enemy entities.
EntityManager(const EntityManager &)=delete
Deleted copy constructor (non-copyable)
std::vector< std::uint32_t > m_destroyQueue
Queue of network IDs pending destruction.
std::uint32_t getNetworkIdForEntity(ecs::Entity entity) const
Get network ID for an entity handle.
rnp::EntityType getNetworkEntityType(ServerEntityType type) const
Convert server entity type to network protocol entity type.
std::unordered_set< std::uint32_t > m_deadPlayers
Set of dead player session IDs.
ecs::Entity createBoss(float x, float y, float health=1000.0f)
Create a boss enemy entity.
void processDestroyQueue()
Process pending entity destructions from queue.
ecs::Entity createPowerup(float x, float y, uint8_t powerupType)
Create a powerup entity.
ecs::Entity getPlayerEntity(std::uint32_t sessionId) const
Get player entity by session ID (const version)
~EntityManager()=default
Destructor.
int getScore(std::uint32_t sessionId) const
Get player's current score.
ecs::Entity createAdvancedEnemy(float x, float y, float health=100.0f)
Create an advanced enemy entity.
std::unordered_map< ecs::Entity, std::uint32_t > m_entityToNetworkId
Reverse lookup map.
std::uint32_t m_nextPowerupId
Next available powerup network ID.
std::unordered_map< std::uint32_t, ecs::Entity > m_projectileEntities
Projectile entities by network ID.
ecs::Entity createPlayer(std::uint32_t sessionId, float x, float y)
Create a new player entity.
std::unordered_map< std::uint32_t, ecs::Entity > m_playerEntities
Player entities by session ID.
EntityMetadata * getEntityMetadata(std::uint32_t networkId)
Get entity metadata by network ID.
const std::unordered_map< std::uint32_t, ecs::Entity > & getPlayers() const
Get all player entities.
void destroyProjectile(std::uint32_t projectileId)
Destroy a projectile entity.
std::vector< rnp::EntityState > getAllEntityStates() const
Get network state for all entities.
ecs::Registry & m_registry
Reference to ECS registry.
void clear()
Clear all entities and reset manager state.
void destroyEnemy(std::uint32_t enemyId)
Destroy an enemy entity.
size_t getTotalEntityCount() const
Get total count of all managed entities.
const std::unordered_map< std::uint32_t, ecs::Entity > & getProjectiles() const
Get all projectile entities.
std::unordered_map< std::uint32_t, ecs::Entity > m_enemyEntities
Enemy entities by network ID.
EntityManager(EntityManager &&)=delete
Deleted move constructor (non-movable)
std::uint32_t getAlivePlayerCount() const
Get count of alive players.
ecs::Entity createBasicEnemy(float x, float y, float health=50.0f)
Create a basic enemy entity.
std::uint32_t m_nextProjectileId
Next available projectile network ID.
ecs::Entity createEnemyProjectile(std::uint32_t enemyId, float x, float y, float vx, float vy)
Create an enemy projectile entity.
void registerEntity(ecs::Entity entity, ServerEntityType type, std::uint32_t networkId, float lifetime=-1.0f, std::uint32_t ownerId=0)
Register a new entity with the manager.
std::unordered_map< std::uint32_t, int > m_playerScores
Player scores by session ID.
EntityManager & operator=(const EntityManager &)=delete
Deleted copy assignment operator (non-copyable)
void destroyPowerup(std::uint32_t powerupId)
Destroy a powerup entity.
void resetScore(std::uint32_t sessionId)
Reset player's score to zero.
EntityManager & operator=(EntityManager &&)=delete
Deleted move assignment operator (non-movable)
void unregisterEntity(std::uint32_t networkId)
Unregister an entity from the manager.
ecs::Entity getEnemy(std::uint32_t enemyId)
Get enemy entity by network ID.
std::uint32_t Entity
Definition Entity.hpp:13
ServerEntityType
Enumeration of entity types managed by the server.
@ ENEMY_ADVANCED
Advanced enemy type (complex behavior)
@ PLAYER
Player-controlled entity.
@ PROJECTILE_PLAYER
Player-fired projectile.
@ ENEMY_BASIC
Basic enemy type (simple behavior)
@ PROJECTILE_ENEMY
Enemy-fired projectile.
@ POWERUP
Collectible powerup item.
@ BOSS
Boss enemy (high health, special patterns)
EntityType
Entity types for world state.
Definition Protocol.hpp:106
Metadata structure for tracking entity lifecycle and properties.
ecs::Entity entity
ECS entity handle.
float lifetime
Maximum lifetime in seconds (-1 for infinite)
float currentLife
Elapsed lifetime counter in seconds.
ServerEntityType type
Entity type classification.
std::uint32_t ownerId
Owner entity ID (for projectiles, the spawner)
bool isActive
Whether entity is currently active.
std::uint32_t networkId
Unique ID used in network synchronization packets.