euv_core/game/ecs/impl.rs
1use super::*;
2
3/// Default identity transform at world origin.
4impl Default for EntityTransform {
5 /// Creates an identity `EntityTransform` at `(0, 0)` with unit scale.
6 ///
7 /// # Returns
8 ///
9 /// - `Self` - Identity transform.
10 fn default() -> Self {
11 Self {
12 position: Point::new(0.0, 0.0),
13 rotation_rad: 0.0,
14 scale: Size::new(1.0, 1.0),
15 }
16 }
17}
18
19/// Convenience constructors for `RigidBody2D`.
20impl RigidBody2D {
21 /// Creates a dynamic rigid body with `mass`, `restitution`, and `linear_drag`.
22 ///
23 /// # Arguments
24 ///
25 /// - `f32` - Positive mass in kilograms.
26 /// - `f32` - Restitution bounciness in `[0.0, 1.0]`.
27 /// - `f32` - Linear velocity drag per second.
28 ///
29 /// # Returns
30 ///
31 /// - `Self` - Dynamic rigid body component.
32 #[must_use]
33 pub fn dynamic(mass: f32, restitution: f32, linear_drag: f32) -> Self {
34 Self {
35 kind: BodyKind::Dynamic,
36 inv_mass: 1.0 / mass.max(0.001),
37 restitution: restitution.clamp(0.0, 1.0),
38 linear_drag: linear_drag.max(0.0),
39 gravity_scale: 1.0,
40 }
41 }
42
43 /// Creates an immovable static body with zero inverse mass.
44 ///
45 /// # Arguments
46 ///
47 /// - `f32` - Surface restitution bounciness in `[0.0, 1.0]`.
48 ///
49 /// # Returns
50 ///
51 /// - `Self` - Static rigid body component.
52 #[must_use]
53 pub fn static_body(restitution: f32) -> Self {
54 Self {
55 kind: BodyKind::Static,
56 inv_mass: 0.0,
57 restitution: restitution.clamp(0.0, 1.0),
58 linear_drag: 0.0,
59 gravity_scale: 0.0,
60 }
61 }
62
63 /// Creates a kinematic body driven directly by velocity without impulse reaction.
64 ///
65 /// # Returns
66 ///
67 /// - `Self` - Kinematic rigid body component.
68 #[must_use]
69 pub fn kinematic() -> Self {
70 Self {
71 kind: BodyKind::Kinematic,
72 inv_mass: 0.0,
73 restitution: 0.5,
74 linear_drag: 0.0,
75 gravity_scale: 0.0,
76 }
77 }
78}
79
80/// World-space bounding box queries for `Collider2D`.
81impl Collider2D {
82 /// Creates a solid circle collider on layer `layer` colliding with `mask`.
83 ///
84 /// # Arguments
85 ///
86 /// - `f32` - Circle radius in world units.
87 /// - `u32` - Collision layer bitmask.
88 /// - `u32` - Interaction mask.
89 /// - `bool` - Whether this collider acts as a trigger volume.
90 ///
91 /// # Returns
92 ///
93 /// - `Self` - Configured circle collider.
94 #[must_use]
95 pub fn circle(radius: f32, layer: u32, mask: u32, is_trigger: bool) -> Self {
96 Self {
97 shape: ColliderShape::Circle {
98 radius: radius.max(0.5),
99 },
100 layer,
101 mask,
102 is_trigger,
103 }
104 }
105
106 /// Creates an axis-aligned box collider on layer `layer` colliding with `mask`.
107 ///
108 /// # Arguments
109 ///
110 /// - `f32` - Full box width in world units.
111 /// - `f32` - Full box height in world units.
112 /// - `u32` - Collision layer bitmask.
113 /// - `u32` - Interaction mask.
114 /// - `bool` - Whether this collider acts as a trigger volume.
115 ///
116 /// # Returns
117 ///
118 /// - `Self` - Configured AABB collider.
119 #[must_use]
120 pub fn aabb(width: f32, height: f32, layer: u32, mask: u32, is_trigger: bool) -> Self {
121 Self {
122 shape: ColliderShape::Aabb {
123 width: width.max(1.0),
124 height: height.max(1.0),
125 },
126 layer,
127 mask,
128 is_trigger,
129 }
130 }
131
132 /// Computes the world-space axis-aligned bounding rectangle of this collider centered at `center`.
133 ///
134 /// # Arguments
135 ///
136 /// - `&Self` - Collider reference.
137 /// - `Point` - Entity world center position.
138 ///
139 /// # Returns
140 ///
141 /// - `Rect` - World-space AABB rectangle.
142 #[must_use]
143 pub fn world_aabb(&self, center: Point) -> Rect {
144 match self.get_shape() {
145 ColliderShape::Aabb { width, height } => Rect::new(
146 center.get_x() - width * 0.5,
147 center.get_y() - height * 0.5,
148 width,
149 height,
150 ),
151 ColliderShape::Circle { radius } => Rect::new(
152 center.get_x() - radius,
153 center.get_y() - radius,
154 radius * 2.0,
155 radius * 2.0,
156 ),
157 }
158 }
159}
160
161/// Optional component accessors for `EntityRecord`.
162impl EntityRecord {
163 /// Returns the attached `RigidBody2D` component if present.
164 ///
165 /// # Arguments
166 ///
167 /// - `&Self` - Entity record reference.
168 ///
169 /// # Returns
170 ///
171 /// - `Option<RigidBody2D>` - Rigid-body component value.
172 #[must_use]
173 pub fn body_component(&self) -> Option<RigidBody2D> {
174 let Self { body, .. } = self;
175 *body
176 }
177
178 /// Returns the attached `Collider2D` component if present.
179 ///
180 /// # Arguments
181 ///
182 /// - `&Self` - Entity record reference.
183 ///
184 /// # Returns
185 ///
186 /// - `Option<Collider2D>` - Collider component value.
187 #[must_use]
188 pub fn collider_component(&self) -> Option<Collider2D> {
189 let Self { collider, .. } = self;
190 *collider
191 }
192
193 /// Returns the attached `Sprite2D` component if present.
194 ///
195 /// # Arguments
196 ///
197 /// - `&Self` - Entity record reference.
198 ///
199 /// # Returns
200 ///
201 /// - `Option<Sprite2D>` - Sprite component value.
202 #[must_use]
203 pub fn sprite_component(&self) -> Option<Sprite2D> {
204 let Self { sprite, .. } = self;
205 *sprite
206 }
207
208 /// Returns remaining lifetime in seconds if the entity is time-limited.
209 ///
210 /// # Arguments
211 ///
212 /// - `&Self` - Entity record reference.
213 ///
214 /// # Returns
215 ///
216 /// - `Option<f32>` - Remaining TTL seconds.
217 #[must_use]
218 pub fn ttl_value(&self) -> Option<f32> {
219 let Self { ttl_secs, .. } = self;
220 *ttl_secs
221 }
222
223 /// Computes the world-space visual bounding box of this entity.
224 ///
225 /// # Arguments
226 ///
227 /// - `&Self` - Entity record reference.
228 ///
229 /// # Returns
230 ///
231 /// - `Rect` - World-space bounding rectangle.
232 #[must_use]
233 pub fn world_bounds(&self) -> Rect {
234 let pos: Point = self.get_transform().get_position();
235 if let Some(sp) = self.sprite_component() {
236 let w: f32 = sp.get_size().get_width() * self.get_transform().get_scale().get_width();
237 let h: f32 = sp.get_size().get_height() * self.get_transform().get_scale().get_height();
238 Rect::new(pos.get_x() - w * 0.5, pos.get_y() - h * 0.5, w, h)
239 } else if let Some(col) = self.collider_component() {
240 col.world_aabb(pos)
241 } else {
242 Rect::new(pos.get_x(), pos.get_y(), 1.0, 1.0)
243 }
244 }
245}
246
247/// Entity spawning, recycling, querying, and lifetime ticking for `GameWorld`.
248impl GameWorld {
249 /// Allocates a `GameWorld` pre-sized for `capacity` entities with zero initial allocations during play.
250 ///
251 /// # Arguments
252 ///
253 /// - `usize` - Initial entity slot capacity.
254 ///
255 /// # Returns
256 ///
257 /// - `Self` - Pre-allocated game world.
258 #[must_use]
259 pub fn with_capacity(capacity: usize) -> Self {
260 Self {
261 entities: Vec::with_capacity(capacity),
262 free_list: Vec::with_capacity(capacity / 4),
263 live_count: 0,
264 tick: 0,
265 }
266 }
267
268 /// Spawns a new entity at `position` with `tag` and returns its generational `EntityId`.
269 ///
270 /// # Arguments
271 ///
272 /// - `&Self` - Mutable game world.
273 /// - `EntityTag` - Semantic gameplay tag.
274 /// - `Point` - Initial world-space position.
275 ///
276 /// # Returns
277 ///
278 /// - `EntityId` - Generation-checked entity handle.
279 pub fn spawn(&mut self, tag: EntityTag, position: Point) -> EntityId {
280 let transform: EntityTransform = EntityTransform::new(position, 0.0, Size::new(1.0, 1.0));
281 let id: EntityId = if let Some(index) = self.get_mut_free_list().pop() {
282 let slot: &mut EntityRecord = &mut self.get_mut_entities()[index as usize];
283 let next_gen: u32 = slot.get_id().get_generation().wrapping_add(1).max(1);
284 let next_id: EntityId = EntityId::new(index, next_gen);
285 *slot = EntityRecord {
286 id: next_id,
287 alive: true,
288 tag,
289 transform,
290 velocity: Velocity2D::default(),
291 body: None,
292 collider: None,
293 sprite: None,
294 health: 100.0,
295 max_health: 100.0,
296 ttl_secs: None,
297 user_data: 0,
298 };
299 next_id
300 } else {
301 let index: u32 = self.get_entities().len() as u32;
302 let next_id: EntityId = EntityId::new(index, 1);
303 self.get_mut_entities().push(EntityRecord {
304 id: next_id,
305 alive: true,
306 tag,
307 transform,
308 velocity: Velocity2D::default(),
309 body: None,
310 collider: None,
311 sprite: None,
312 health: 100.0,
313 max_health: 100.0,
314 ttl_secs: None,
315 user_data: 0,
316 });
317 next_id
318 };
319 let next_live: usize = self.get_live_count().saturating_add(1);
320 self.set_live_count(next_live);
321 id
322 }
323
324 /// Despawns `id` in O(1), invalidating stale handles and recycling its arena slot.
325 ///
326 /// # Arguments
327 ///
328 /// - `&Self` - Mutable game world.
329 /// - `EntityId` - Target entity handle.
330 ///
331 /// # Returns
332 ///
333 /// - `bool` - `true` if the entity was alive and removed.
334 pub fn despawn(&mut self, id: EntityId) -> bool {
335 let idx: usize = id.get_index() as usize;
336 let removed: bool = match self.get_mut_entities().get_mut(idx) {
337 Some(slot) if slot.get_alive() && slot.get_id() == id => {
338 slot.set_alive(false);
339 true
340 }
341 _ => false,
342 };
343 if removed {
344 self.get_mut_free_list().push(id.get_index());
345 let next_live: usize = self.get_live_count().saturating_sub(1);
346 self.set_live_count(next_live);
347 }
348 removed
349 }
350
351 /// Returns `true` when `id` refers to a currently alive entity.
352 ///
353 /// # Arguments
354 ///
355 /// - `&Self` - Game world reference.
356 /// - `EntityId` - Entity handle to validate.
357 ///
358 /// # Returns
359 ///
360 /// - `bool` - Live status.
361 #[must_use]
362 pub fn is_alive(&self, id: EntityId) -> bool {
363 self.get_entity(id).is_some()
364 }
365
366 /// Returns an immutable reference to the live entity matching `id`.
367 ///
368 /// # Arguments
369 ///
370 /// - `&Self` - Game world reference.
371 /// - `EntityId` - Entity handle.
372 ///
373 /// # Returns
374 ///
375 /// - `Option<&EntityRecord>` - Live entity reference.
376 #[must_use]
377 pub fn get_entity(&self, id: EntityId) -> Option<&EntityRecord> {
378 let slot: &EntityRecord = self.get_entities().get(id.get_index() as usize)?;
379 if slot.get_alive() && slot.get_id() == id {
380 Some(slot)
381 } else {
382 None
383 }
384 }
385
386 /// Returns a mutable reference to the live entity matching `id`.
387 ///
388 /// # Arguments
389 ///
390 /// - `&Self` - Mutable game world.
391 /// - `EntityId` - Entity handle.
392 ///
393 /// # Returns
394 ///
395 /// - `Option<&mut EntityRecord>` - Mutable live entity reference.
396 pub fn get_entity_mut(&mut self, id: EntityId) -> Option<&mut EntityRecord> {
397 let slot: &mut EntityRecord = self.get_mut_entities().get_mut(id.get_index() as usize)?;
398 if slot.get_alive() && slot.get_id() == id {
399 Some(slot)
400 } else {
401 None
402 }
403 }
404
405 /// Decrements `ttl_secs` across all time-limited entities and despawns expired ones.
406 ///
407 /// # Arguments
408 ///
409 /// - `&Self` - Mutable game world.
410 /// - `f32` - Elapsed timestep in seconds.
411 ///
412 /// # Returns
413 ///
414 /// - `usize` - Number of entities expired and despawned.
415 pub fn tick_lifetimes(&mut self, dt_secs: f32) -> usize {
416 let mut expired: Vec<EntityId> = Vec::new();
417 for slot in self.get_mut_entities().iter_mut() {
418 if !slot.get_alive() {
419 continue;
420 }
421 if let Some(rem) = slot.ttl_value() {
422 let next: f32 = rem - dt_secs;
423 if next <= 0.0 {
424 expired.push(slot.get_id());
425 } else {
426 slot.set_ttl_secs(Some(next));
427 }
428 }
429 }
430 let mut removed: usize = 0;
431 for id in expired.into_iter() {
432 if self.despawn(id) {
433 removed += 1;
434 }
435 }
436 let next_tick: u64 = self.get_tick().wrapping_add(1);
437 self.set_tick(next_tick);
438 removed
439 }
440
441 /// Clears all entities while retaining arena backing allocations.
442 ///
443 /// # Arguments
444 ///
445 /// - `&Self` - Mutable game world.
446 pub fn clear(&mut self) {
447 self.get_mut_entities().clear();
448 self.get_mut_free_list().clear();
449 self.set_live_count(0);
450 }
451
452 /// Counts all live entities matching `tag`.
453 ///
454 /// # Arguments
455 ///
456 /// - `&Self` - Game world reference.
457 /// - `EntityTag` - Target gameplay tag.
458 ///
459 /// # Returns
460 ///
461 /// - `usize` - Live entity count matching `tag`.
462 #[must_use]
463 pub fn count_by_tag(&self, tag: EntityTag) -> usize {
464 self.get_entities()
465 .iter()
466 .filter(|e: &&EntityRecord| e.get_alive() && e.get_tag() == tag)
467 .count()
468 }
469}