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/// Render-time continuous interpolation helpers for `EntityTransform`.
20impl EntityTransform {
21 /// Linearly interpolates position, scale, and shortest-arc rotation between `self` and `other`.
22 ///
23 /// # Arguments
24 ///
25 /// - `Self` - Previous fixed-step transform.
26 /// - `Self` - Current fixed-step transform.
27 /// - `f32` - Normalized interpolation factor in `[0.0, 1.0]`.
28 ///
29 /// # Returns
30 ///
31 /// - `Self` - Interpolated 2D transform.
32 #[must_use]
33 pub fn lerp(self, other: Self, alpha: f32) -> Self {
34 let entry_index: f32 = alpha.clamp(0.0, 1.0);
35 let p0: Point = self.get_position();
36 let p1: Point = other.get_position();
37 let s0: Size = self.get_scale();
38 let s1: Size = other.get_scale();
39 let raw_delta: f32 = (other.get_rotation_rad() - self.get_rotation_rad()).rem_euclid(TAU);
40 let shortest_delta: f32 = if raw_delta > PI {
41 raw_delta - TAU
42 } else {
43 raw_delta
44 };
45 Self {
46 position: Point::new(
47 p0.get_x() + (p1.get_x() - p0.get_x()) * entry_index,
48 p0.get_y() + (p1.get_y() - p0.get_y()) * entry_index,
49 ),
50 rotation_rad: self.get_rotation_rad() + shortest_delta * entry_index,
51 scale: Size::new(
52 s0.get_width() + (s1.get_width() - s0.get_width()) * entry_index,
53 s0.get_height() + (s1.get_height() - s0.get_height()) * entry_index,
54 ),
55 }
56 }
57}
58
59/// Convenience constructors for `RigidBody2D`.
60impl RigidBody2D {
61 /// Creates a dynamic rigid body with `mass`, `restitution`, and `linear_drag`.
62 ///
63 /// # Arguments
64 ///
65 /// - `f32` - Positive mass in kilograms.
66 /// - `f32` - Restitution bounciness in `[0.0, 1.0]`.
67 /// - `f32` - Linear velocity drag per second.
68 ///
69 /// # Returns
70 ///
71 /// - `Self` - Dynamic rigid body component.
72 #[must_use]
73 pub fn dynamic(mass: f32, restitution: f32, linear_drag: f32) -> Self {
74 Self {
75 kind: BodyKind::Dynamic,
76 inv_mass: 1.0 / mass.max(0.001),
77 restitution: restitution.clamp(0.0, 1.0),
78 linear_drag: linear_drag.max(0.0),
79 gravity_scale: 1.0,
80 }
81 }
82
83 /// Creates an immovable static body with zero inverse mass.
84 ///
85 /// # Arguments
86 ///
87 /// - `f32` - Surface restitution bounciness in `[0.0, 1.0]`.
88 ///
89 /// # Returns
90 ///
91 /// - `Self` - Static rigid body component.
92 #[must_use]
93 pub fn static_body(restitution: f32) -> Self {
94 Self {
95 kind: BodyKind::Static,
96 inv_mass: 0.0,
97 restitution: restitution.clamp(0.0, 1.0),
98 linear_drag: 0.0,
99 gravity_scale: 0.0,
100 }
101 }
102
103 /// Creates a kinematic body driven directly by velocity without impulse reaction.
104 ///
105 /// # Returns
106 ///
107 /// - `Self` - Kinematic rigid body component.
108 #[must_use]
109 pub fn kinematic() -> Self {
110 Self {
111 kind: BodyKind::Kinematic,
112 inv_mass: 0.0,
113 restitution: 0.5,
114 linear_drag: 0.0,
115 gravity_scale: 0.0,
116 }
117 }
118}
119
120/// World-space bounding box queries for `Collider2D`.
121impl Collider2D {
122 /// Creates a solid circle collider on layer `layer` colliding with `mask`.
123 ///
124 /// # Arguments
125 ///
126 /// - `f32` - Circle radius in world units.
127 /// - `u32` - Collision layer bitmask.
128 /// - `u32` - Interaction mask.
129 /// - `bool` - Whether this collider acts as a trigger volume.
130 ///
131 /// # Returns
132 ///
133 /// - `Self` - Configured circle collider.
134 #[must_use]
135 pub fn circle(radius: f32, layer: u32, mask: u32, is_trigger: bool) -> Self {
136 Self {
137 shape: ColliderShape::Circle {
138 radius: radius.max(0.5),
139 },
140 layer,
141 mask,
142 is_trigger,
143 }
144 }
145
146 /// Creates an axis-aligned box collider on layer `layer` colliding with `mask`.
147 ///
148 /// # Arguments
149 ///
150 /// - `f32` - Full box width in world units.
151 /// - `f32` - Full box height in world units.
152 /// - `u32` - Collision layer bitmask.
153 /// - `u32` - Interaction mask.
154 /// - `bool` - Whether this collider acts as a trigger volume.
155 ///
156 /// # Returns
157 ///
158 /// - `Self` - Configured axis-aligned bounding box collider.
159 #[must_use]
160 pub fn axis_aligned_box(
161 width: f32,
162 height: f32,
163 layer: u32,
164 mask: u32,
165 is_trigger: bool,
166 ) -> Self {
167 Self {
168 shape: ColliderShape::AxisAlignedBox {
169 width: width.max(1.0),
170 height: height.max(1.0),
171 },
172 layer,
173 mask,
174 is_trigger,
175 }
176 }
177
178 /// Computes the world-space axis-aligned bounding rectangle of this collider centered at `center`.
179 ///
180 /// # Arguments
181 ///
182 /// - `&Self` - Collider reference.
183 /// - `Point` - Entity world center position.
184 ///
185 /// # Returns
186 ///
187 /// - `Rect` - World-space axis-aligned bounding box rectangle.
188 #[must_use]
189 pub fn world_bounds(&self, center: Point) -> Rect {
190 match self.get_shape() {
191 ColliderShape::AxisAlignedBox { width, height } => Rect::new(
192 center.get_x() - width * 0.5,
193 center.get_y() - height * 0.5,
194 width,
195 height,
196 ),
197 ColliderShape::Circle { radius } => Rect::new(
198 center.get_x() - radius,
199 center.get_y() - radius,
200 radius * 2.0,
201 radius * 2.0,
202 ),
203 }
204 }
205}
206
207/// Optional component accessors for `EntityRecord`.
208impl EntityRecord {
209 /// Returns the attached `RigidBody2D` component if present.
210 ///
211 /// # Arguments
212 ///
213 /// - `&Self` - Entity record reference.
214 ///
215 /// # Returns
216 ///
217 /// - `Option<RigidBody2D>` - Rigid-body component value.
218 #[must_use]
219 pub fn body_component(&self) -> Option<RigidBody2D> {
220 let Self { body, .. } = self;
221 *body
222 }
223
224 /// Returns the attached `Collider2D` component if present.
225 ///
226 /// # Arguments
227 ///
228 /// - `&Self` - Entity record reference.
229 ///
230 /// # Returns
231 ///
232 /// - `Option<Collider2D>` - Collider component value.
233 #[must_use]
234 pub fn collider_component(&self) -> Option<Collider2D> {
235 let Self { collider, .. } = self;
236 *collider
237 }
238
239 /// Returns the attached `Sprite2D` component if present.
240 ///
241 /// # Arguments
242 ///
243 /// - `&Self` - Entity record reference.
244 ///
245 /// # Returns
246 ///
247 /// - `Option<Sprite2D>` - Sprite component value.
248 #[must_use]
249 pub fn sprite_component(&self) -> Option<Sprite2D> {
250 let Self { sprite, .. } = self;
251 *sprite
252 }
253
254 /// Returns remaining lifetime in seconds if the entity is time-limited.
255 ///
256 /// # Arguments
257 ///
258 /// - `&Self` - Entity record reference.
259 ///
260 /// # Returns
261 ///
262 /// - `Option<f32>` - Remaining TTL seconds.
263 #[must_use]
264 pub fn ttl_value(&self) -> Option<f32> {
265 let Self { ttl_secs, .. } = self;
266 *ttl_secs
267 }
268
269 /// Computes the world-space visual bounding box of this entity.
270 ///
271 /// # Arguments
272 ///
273 /// - `&Self` - Entity record reference.
274 ///
275 /// # Returns
276 ///
277 /// - `Rect` - World-space bounding rectangle.
278 #[must_use]
279 pub fn world_bounds(&self) -> Rect {
280 let pos: Point = self.get_transform().get_position();
281 if let Some(sp) = self.sprite_component() {
282 let width_val: f32 =
283 sp.get_size().get_width() * self.get_transform().get_scale().get_width();
284 let height_val: f32 =
285 sp.get_size().get_height() * self.get_transform().get_scale().get_height();
286 Rect::new(
287 pos.get_x() - width_val * 0.5,
288 pos.get_y() - height_val * 0.5,
289 width_val,
290 height_val,
291 )
292 } else if let Some(col) = self.collider_component() {
293 col.world_bounds(pos)
294 } else {
295 Rect::new(pos.get_x(), pos.get_y(), 1.0, 1.0)
296 }
297 }
298}
299
300/// Entity spawning, recycling, Structure-of-Arrays synchronization, querying, and lifetime ticking for `GameWorld`.
301impl GameWorld {
302 /// Allocates a `GameWorld` pre-sized for `capacity` entities with zero initial allocations during play.
303 ///
304 /// # Arguments
305 ///
306 /// - `usize` - Initial entity slot capacity.
307 ///
308 /// # Returns
309 ///
310 /// - `Self` - Pre-allocated game world.
311 #[must_use]
312 pub fn with_capacity(capacity: usize) -> Self {
313 Self {
314 entities: Vec::with_capacity(capacity),
315 transforms: Vec::with_capacity(capacity),
316 velocities: Vec::with_capacity(capacity),
317 cold_meta: Vec::with_capacity(capacity),
318 free_list: Vec::with_capacity(capacity / 4),
319 live_count: 0,
320 tick: 0,
321 }
322 }
323
324 /// Synchronizes the dense SoA `transforms`, `velocities`, and `cold_meta` arrays from `entities`.
325 ///
326 /// # Arguments
327 ///
328 /// - `&Self` - Mutable game world.
329 pub fn sync_soa_from_entities(&mut self) {
330 let Self {
331 entities,
332 transforms,
333 velocities,
334 cold_meta,
335 ..
336 } = self;
337 let len: usize = entities.len();
338 transforms.resize(len, EntityTransform::default());
339 velocities.resize(len, Velocity2D::default());
340 cold_meta.resize(
341 len,
342 EntityColdMeta {
343 id: EntityId::default(),
344 alive: false,
345 tag: EntityTag::Generic,
346 health: 0.0,
347 max_health: 0.0,
348 ttl_secs: None,
349 user_data: 0,
350 teleport_epoch: 0,
351 spawn_tick: 0,
352 },
353 );
354 for (idx, ent) in entities.iter().enumerate() {
355 transforms[idx] = ent.get_transform();
356 velocities[idx] = ent.get_velocity();
357 cold_meta[idx] = EntityColdMeta {
358 id: ent.get_id(),
359 alive: ent.get_alive(),
360 tag: ent.get_tag(),
361 health: ent.get_health(),
362 max_health: ent.get_max_health(),
363 ttl_secs: ent.ttl_value(),
364 user_data: ent.get_user_data(),
365 teleport_epoch: ent.get_teleport_epoch(),
366 spawn_tick: ent.get_spawn_tick(),
367 };
368 }
369 }
370
371 /// Writes updated SoA `transforms` and `velocities` back into the `entities` mirror.
372 ///
373 /// # Arguments
374 ///
375 /// - `&Self` - Mutable game world.
376 pub fn sync_entities_from_soa(&mut self) {
377 let Self {
378 entities,
379 transforms,
380 velocities,
381 ..
382 } = self;
383 let count: usize = entities.len().min(transforms.len()).min(velocities.len());
384 for idx in 0..count {
385 entities[idx].set_transform(transforms[idx]);
386 entities[idx].set_velocity(velocities[idx]);
387 }
388 }
389
390 /// Spawns a new entity at `position` with `tag` and returns its generational `EntityId`.
391 ///
392 /// # Arguments
393 ///
394 /// - `&Self` - Mutable game world.
395 /// - `EntityTag` - Semantic gameplay tag.
396 /// - `Point` - Initial world-space position.
397 ///
398 /// # Returns
399 ///
400 /// - `EntityId` - Generation-checked entity handle.
401 pub fn spawn(&mut self, tag: EntityTag, position: Point) -> EntityId {
402 let transform: EntityTransform = EntityTransform::new(position, 0.0, Size::new(1.0, 1.0));
403 let spawn_tick: u64 = self.get_tick();
404 let id: EntityId = if let Some(index) = self.get_mut_free_list().pop() {
405 let slot_idx: usize = index as usize;
406 let next_gen: u32 = self.get_entities()[slot_idx]
407 .get_id()
408 .get_generation()
409 .wrapping_add(1)
410 .max(1);
411 let next_id: EntityId = EntityId::new(index, next_gen);
412 let meta: EntityColdMeta = EntityColdMeta {
413 id: next_id,
414 alive: true,
415 tag,
416 health: 100.0,
417 max_health: 100.0,
418 ttl_secs: None,
419 user_data: 0,
420 teleport_epoch: 0,
421 spawn_tick,
422 };
423 self.get_mut_entities()[slot_idx] = EntityRecord {
424 id: next_id,
425 alive: true,
426 tag,
427 transform,
428 velocity: Velocity2D::default(),
429 body: None,
430 collider: None,
431 sprite: None,
432 health: 100.0,
433 max_health: 100.0,
434 ttl_secs: None,
435 user_data: 0,
436 teleport_epoch: 0,
437 spawn_tick,
438 };
439 if slot_idx < self.get_transforms().len() {
440 self.get_mut_transforms()[slot_idx] = transform;
441 self.get_mut_velocities()[slot_idx] = Velocity2D::default();
442 self.get_mut_cold_meta()[slot_idx] = meta;
443 }
444 next_id
445 } else {
446 let index: u32 = self.get_entities().len() as u32;
447 let next_id: EntityId = EntityId::new(index, 1);
448 let meta: EntityColdMeta = EntityColdMeta {
449 id: next_id,
450 alive: true,
451 tag,
452 health: 100.0,
453 max_health: 100.0,
454 ttl_secs: None,
455 user_data: 0,
456 teleport_epoch: 0,
457 spawn_tick,
458 };
459 self.get_mut_entities().push(EntityRecord {
460 id: next_id,
461 alive: true,
462 tag,
463 transform,
464 velocity: Velocity2D::default(),
465 body: None,
466 collider: None,
467 sprite: None,
468 health: 100.0,
469 max_health: 100.0,
470 ttl_secs: None,
471 user_data: 0,
472 teleport_epoch: 0,
473 spawn_tick,
474 });
475 self.get_mut_transforms().push(transform);
476 self.get_mut_velocities().push(Velocity2D::default());
477 self.get_mut_cold_meta().push(meta);
478 next_id
479 };
480 let next_live: usize = self.get_live_count().saturating_add(1);
481 self.set_live_count(next_live);
482 id
483 }
484
485 /// Teleports a live entity directly to `position`, incrementing `teleport_epoch` so snapshot interpolation snaps cleanly.
486 ///
487 /// # Arguments
488 ///
489 /// - `&Self` - Mutable game world.
490 /// - `EntityId` - Target entity handle.
491 /// - `Point` - Destination world coordinates.
492 ///
493 /// # Returns
494 ///
495 /// - `bool` - `true` when the entity was alive and teleported.
496 pub fn teleport_entity(&mut self, id: EntityId, position: Point) -> bool {
497 let idx: usize = id.get_index() as usize;
498 let Some(ent) = self.get_entity_mut(id) else {
499 return false;
500 };
501 let mut transform_val: EntityTransform = ent.get_transform();
502 transform_val.set_position(position);
503 ent.set_transform(transform_val);
504 let next_epoch: u32 = ent.get_teleport_epoch().wrapping_add(1);
505 ent.set_teleport_epoch(next_epoch);
506 if idx < self.get_transforms().len() {
507 self.get_mut_transforms()[idx] = transform_val;
508 self.get_mut_cold_meta()[idx].set_teleport_epoch(next_epoch);
509 }
510 true
511 }
512
513 /// Despawns `id` in O(1), invalidating stale handles and recycling its arena slot.
514 ///
515 /// # Arguments
516 ///
517 /// - `&Self` - Mutable game world.
518 /// - `EntityId` - Target entity handle.
519 ///
520 /// # Returns
521 ///
522 /// - `bool` - `true` if the entity was alive and removed.
523 pub fn despawn(&mut self, id: EntityId) -> bool {
524 let idx: usize = id.get_index() as usize;
525 let removed: bool = match self.get_mut_entities().get_mut(idx) {
526 Some(slot) if slot.get_alive() && slot.get_id() == id => {
527 slot.set_alive(false);
528 true
529 }
530 _ => false,
531 };
532 if removed {
533 if idx < self.get_cold_meta().len() {
534 self.get_mut_cold_meta()[idx].set_alive(false);
535 }
536 self.get_mut_free_list().push(id.get_index());
537 let next_live: usize = self.get_live_count().saturating_sub(1);
538 self.set_live_count(next_live);
539 }
540 removed
541 }
542
543 /// Returns `true` when `id` refers to a currently alive entity.
544 ///
545 /// # Arguments
546 ///
547 /// - `&Self` - Game world reference.
548 /// - `EntityId` - Entity handle to validate.
549 ///
550 /// # Returns
551 ///
552 /// - `bool` - Live status.
553 #[must_use]
554 pub fn is_alive(&self, id: EntityId) -> bool {
555 self.get_entity(id).is_some()
556 }
557
558 /// Returns an immutable reference to the live entity matching `id`.
559 ///
560 /// # Arguments
561 ///
562 /// - `&Self` - Game world reference.
563 /// - `EntityId` - Entity handle.
564 ///
565 /// # Returns
566 ///
567 /// - `Option<&EntityRecord>` - Live entity reference.
568 #[must_use]
569 pub fn get_entity(&self, id: EntityId) -> Option<&EntityRecord> {
570 let slot: &EntityRecord = self.get_entities().get(id.get_index() as usize)?;
571 if slot.get_alive() && slot.get_id() == id {
572 Some(slot)
573 } else {
574 None
575 }
576 }
577
578 /// Returns a mutable reference to the live entity matching `id`.
579 ///
580 /// # Arguments
581 ///
582 /// - `&Self` - Mutable game world.
583 /// - `EntityId` - Entity handle.
584 ///
585 /// # Returns
586 ///
587 /// - `Option<&mut EntityRecord>` - Mutable live entity reference.
588 pub fn get_entity_mut(&mut self, id: EntityId) -> Option<&mut EntityRecord> {
589 let slot: &mut EntityRecord = self.get_mut_entities().get_mut(id.get_index() as usize)?;
590 if slot.get_alive() && slot.get_id() == id {
591 Some(slot)
592 } else {
593 None
594 }
595 }
596
597 /// Decrements `ttl_secs` across all time-limited entities and despawns expired ones in-place without heap allocation.
598 ///
599 /// # Arguments
600 ///
601 /// - `&Self` - Mutable game world.
602 /// - `f32` - Elapsed timestep in seconds.
603 ///
604 /// # Returns
605 ///
606 /// - `usize` - Number of entities expired and despawned.
607 pub fn tick_lifetimes(&mut self, dt_secs: f32) -> usize {
608 let Self {
609 entities,
610 cold_meta,
611 free_list,
612 live_count,
613 tick,
614 ..
615 } = self;
616 let mut removed: usize = 0;
617 for (idx, slot) in entities.iter_mut().enumerate() {
618 if !slot.get_alive() {
619 continue;
620 }
621 if let Some(rem) = slot.ttl_value() {
622 let next: f32 = rem - dt_secs;
623 if next <= 0.0 {
624 slot.set_alive(false);
625 if idx < cold_meta.len() {
626 cold_meta[idx].set_alive(false);
627 }
628 free_list.push(idx as u32);
629 removed += 1;
630 } else {
631 slot.set_ttl_secs(Some(next));
632 if idx < cold_meta.len() {
633 cold_meta[idx].set_ttl_secs(Some(next));
634 }
635 }
636 }
637 }
638 *live_count = live_count.saturating_sub(removed);
639 *tick = tick.wrapping_add(1);
640 removed
641 }
642
643 /// Clears all entities while retaining arena backing allocations.
644 ///
645 /// # Arguments
646 ///
647 /// - `&Self` - Mutable game world.
648 pub fn clear(&mut self) {
649 self.get_mut_entities().clear();
650 self.get_mut_transforms().clear();
651 self.get_mut_velocities().clear();
652 self.get_mut_cold_meta().clear();
653 self.get_mut_free_list().clear();
654 self.set_live_count(0);
655 }
656
657 /// Counts all live entities matching `tag`.
658 ///
659 /// # Arguments
660 ///
661 /// - `&Self` - Game world reference.
662 /// - `EntityTag` - Target gameplay tag.
663 ///
664 /// # Returns
665 ///
666 /// - `usize` - Live entity count matching `tag`.
667 #[must_use]
668 pub fn count_by_tag(&self, tag: EntityTag) -> usize {
669 if self.get_cold_meta().len() == self.get_entities().len() {
670 self.get_cold_meta()
671 .iter()
672 .filter(|matrix_elems: &&EntityColdMeta| {
673 matrix_elems.get_alive() && matrix_elems.get_tag() == tag
674 })
675 .count()
676 } else {
677 self.get_entities()
678 .iter()
679 .filter(|event_ref: &&EntityRecord| {
680 event_ref.get_alive() && event_ref.get_tag() == tag
681 })
682 .count()
683 }
684 }
685}