Skip to main content

euv_core/game/physics/
impl.rs

1use super::*;
2
3/// Default zero-gravity top-down 2D physics configuration.
4impl Default for PhysicsConfig {
5    /// Creates a default zero-gravity `PhysicsConfig` with `64px` spatial-hash cells.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default physics configuration.
10    fn default() -> Self {
11        Self {
12            gravity: Point::new(0.0, 0.0),
13            cell_size: DEFAULT_SPATIAL_CELL_SIZE,
14            position_correction: 0.8,
15            arena_bounds: None,
16        }
17    }
18}
19
20/// Default empty 2D physics world.
21impl Default for PhysicsWorld2D {
22    /// Creates a `PhysicsWorld2D` using `PhysicsConfig::default()`.
23    ///
24    /// # Returns
25    ///
26    /// - `Self` - Ready physics world.
27    fn default() -> Self {
28        Self::with_config(PhysicsConfig::default())
29    }
30}
31
32/// Fluent query builder for `RaycastQuery2D`.
33impl RaycastQuery2D {
34    /// Creates a 2D raycast query from `origin` along `direction` with default `1000.0` distance and all layers enabled.
35    ///
36    /// # Arguments
37    ///
38    /// - `Point` - Ray origin.
39    /// - `Point` - Ray direction vector.
40    ///
41    /// # Returns
42    ///
43    /// - `Self` - Ready raycast query.
44    #[must_use]
45    pub const fn new(origin: Point, direction: Point) -> Self {
46        Self {
47            origin,
48            direction,
49            max_distance: 1000.0,
50            layer_mask: u32::MAX,
51        }
52    }
53
54    /// Sets maximum travel distance for the raycast.
55    ///
56    /// # Arguments
57    ///
58    /// - `Self` - Source query.
59    /// - `f32` - Maximum distance in world units.
60    ///
61    /// # Returns
62    ///
63    /// - `Self` - Updated query.
64    #[must_use]
65    pub fn with_max_distance(mut self, max_distance: f32) -> Self {
66        self.set_max_distance(max_distance.max(0.0));
67        self
68    }
69
70    /// Sets the collision layer filter bitmask for the raycast.
71    ///
72    /// # Arguments
73    ///
74    /// - `Self` - Source query.
75    /// - `u32` - Collision layer bitmask.
76    ///
77    /// # Returns
78    ///
79    /// - `Self` - Updated query.
80    #[must_use]
81    pub fn with_layer_mask(mut self, layer_mask: u32) -> Self {
82        self.set_layer_mask(layer_mask);
83        self
84    }
85}
86
87/// Broad-phase flat spatial grid, narrow-phase contact resolution, and raycasting for `PhysicsWorld2D`.
88impl PhysicsWorld2D {
89    /// Creates a `PhysicsWorld2D` configured with `config`.
90    ///
91    /// # Arguments
92    ///
93    /// - `PhysicsConfig` - Physics simulation parameters.
94    ///
95    /// # Returns
96    ///
97    /// - `Self` - Configured 2D physics solver.
98    #[must_use]
99    pub fn with_config(config: PhysicsConfig) -> Self {
100        Self {
101            config,
102            body_bounds: Vec::new(),
103            cell_counts: Vec::new(),
104            cell_offsets: Vec::new(),
105            cell_cursors: Vec::new(),
106            cell_items: Vec::new(),
107            active_cells: Vec::new(),
108            sparse_table: Vec::new(),
109            sparse_nodes: Vec::new(),
110            sparse_active: Vec::new(),
111            sparse_bucket_scratch: Vec::new(),
112            last_stats: PhysicsStepStats::default(),
113        }
114    }
115
116    /// Packs `(cx, cy)` integer coordinates into a unique 64-bit hash key reserving `u64::MAX` for empty slots.
117    ///
118    /// # Arguments
119    ///
120    /// - `i32` - Grid cell X coordinate.
121    /// - `i32` - Grid cell Y coordinate.
122    ///
123    /// # Returns
124    ///
125    /// - `u64` - Unique cell key in `0..u64::MAX`.
126    #[inline(always)]
127    #[must_use]
128    fn pack_cell_key(cx: i32, cy: i32) -> u64 {
129        let raw: u64 = ((cx as u32 as u64) << 32) | (cy as u32 as u64);
130        if raw == u64::MAX { u64::MAX - 1 } else { raw }
131    }
132
133    /// Evaluates narrow-phase contact and applies Baumgarte separation and impulse response for one deduplicated entity pair.
134    ///
135    /// # Arguments
136    ///
137    /// - `&mut [EntityRecord]` - Mutable ECS entity slice.
138    /// - `usize` - First entity arena index.
139    /// - `usize` - Second entity arena index.
140    /// - `f32` - Baumgarte positional correction factor.
141    /// - `&mut Vec<CollisionEvent>` - Output contact event buffer.
142    #[inline]
143    fn resolve_pair(
144        entities: &mut [EntityRecord],
145        ia: usize,
146        ib: usize,
147        pos_corr: f32,
148        events: &mut Vec<CollisionEvent>,
149    ) {
150        let (id_a, pos_a, vel_a, body_a, col_a): (
151            EntityId,
152            Point,
153            Velocity2D,
154            RigidBody2D,
155            Collider2D,
156        ) = {
157            let ent: &EntityRecord = &entities[ia];
158            let Some(col) = ent.collider_component() else {
159                return;
160            };
161            (
162                ent.get_id(),
163                ent.get_transform().get_position(),
164                ent.get_velocity(),
165                ent.body_component()
166                    .unwrap_or_else(|| RigidBody2D::static_body(0.5)),
167                col,
168            )
169        };
170        let (id_b, pos_b, vel_b, body_b, col_b): (
171            EntityId,
172            Point,
173            Velocity2D,
174            RigidBody2D,
175            Collider2D,
176        ) = {
177            let ent: &EntityRecord = &entities[ib];
178            let Some(col) = ent.collider_component() else {
179                return;
180            };
181            (
182                ent.get_id(),
183                ent.get_transform().get_position(),
184                ent.get_velocity(),
185                ent.body_component()
186                    .unwrap_or_else(|| RigidBody2D::static_body(0.5)),
187                col,
188            )
189        };
190        let Some((normal, penetration)) =
191            Self::narrow_phase(pos_a, col_a.get_shape(), pos_b, col_b.get_shape())
192        else {
193            return;
194        };
195        let is_trigger: bool = col_a.get_is_trigger() || col_b.get_is_trigger();
196        events.push(CollisionEvent::new(
197            id_a,
198            id_b,
199            normal,
200            penetration,
201            is_trigger,
202        ));
203        if is_trigger {
204            return;
205        }
206        let inv_a: f32 = body_a.get_inv_mass();
207        let inv_b: f32 = body_b.get_inv_mass();
208        let inv_sum: f32 = inv_a + inv_b;
209        if inv_sum <= 0.0 {
210            return;
211        }
212        let corr_mag: f32 = (penetration / inv_sum) * pos_corr;
213        let nx_n: f32 = normal.get_x();
214        let ny_n: f32 = normal.get_y();
215        let corr_x: f32 = nx_n * corr_mag;
216        let corr_y: f32 = ny_n * corr_mag;
217        let next_pos_a: Point = Point::new(
218            pos_a.get_x() - corr_x * inv_a,
219            pos_a.get_y() - corr_y * inv_a,
220        );
221        let next_pos_b: Point = Point::new(
222            pos_b.get_x() + corr_x * inv_b,
223            pos_b.get_y() + corr_y * inv_b,
224        );
225        let rvx: f32 = vel_b.get_vx() - vel_a.get_vx();
226        let rvy: f32 = vel_b.get_vy() - vel_a.get_vy();
227        let vel_along_normal: f32 = rvx * nx_n + rvy * ny_n;
228        let mut next_vel_a: Velocity2D = vel_a;
229        let mut next_vel_b: Velocity2D = vel_b;
230        if vel_along_normal < 0.0 {
231            let e: f32 = body_a.get_restitution().min(body_b.get_restitution());
232            let j: f32 = -(1.0 + e) * vel_along_normal / inv_sum;
233            let imp_x: f32 = j * nx_n;
234            let imp_y: f32 = j * ny_n;
235            next_vel_a.set_vx(vel_a.get_vx() - imp_x * inv_a);
236            next_vel_a.set_vy(vel_a.get_vy() - imp_y * inv_a);
237            next_vel_b.set_vx(vel_b.get_vx() + imp_x * inv_b);
238            next_vel_b.set_vy(vel_b.get_vy() + imp_y * inv_b);
239        }
240        entities[ia].get_mut_transform().set_position(next_pos_a);
241        entities[ia].set_velocity(next_vel_a);
242        entities[ib].get_mut_transform().set_position(next_pos_b);
243        entities[ib].set_velocity(next_vel_b);
244    }
245
246    /// Integrates velocities/positions, resolves flat spatial-grid collisions and arena bounds with zero per-step grid allocations, and returns contact events.
247    ///
248    /// # Arguments
249    ///
250    /// - `&Self` - Mutable physics world.
251    /// - `&mut GameWorld` - Mutable ECS world containing entities and colliders.
252    /// - `f32` - Fixed physics timestep in seconds.
253    ///
254    /// # Returns
255    ///
256    /// - `Vec<CollisionEvent>` - All solid and trigger contacts detected this step.
257    pub fn step(&mut self, world: &mut GameWorld, dt_secs: f32) -> Vec<CollisionEvent> {
258        let cfg: PhysicsConfig = self.get_config();
259        let gx_dt: f32 = cfg.get_gravity().get_x() * dt_secs;
260        let gy_dt: f32 = cfg.get_gravity().get_y() * dt_secs;
261        let pos_corr: f32 = cfg.get_position_correction();
262        let inv_cell: f32 = 1.0 / cfg.get_cell_size().max(8.0);
263        let arena_opt: Option<Rect> = {
264            let PhysicsConfig { arena_bounds, .. } = cfg;
265            arena_bounds
266        };
267        let Self {
268            body_bounds,
269            cell_counts,
270            cell_offsets,
271            cell_cursors,
272            cell_items,
273            active_cells,
274            sparse_table,
275            sparse_nodes,
276            sparse_active,
277            sparse_bucket_scratch,
278            ..
279        } = self;
280        body_bounds.clear();
281        let mut integrated: usize = 0;
282        let mut grid_min_cx: i32 = i32::MAX;
283        let mut grid_max_cx: i32 = i32::MIN;
284        let mut grid_min_cy: i32 = i32::MAX;
285        let mut grid_max_cy: i32 = i32::MIN;
286        let mut total_cell_refs: usize = 0;
287        let entities: &mut [EntityRecord] = world.get_mut_entities().as_mut_slice();
288        for (idx, ent) in entities.iter_mut().enumerate() {
289            if !ent.get_alive() {
290                continue;
291            }
292            if let Some(body) = ent.body_component() {
293                match body.get_kind() {
294                    BodyKind::Static => {}
295                    BodyKind::Kinematic => {
296                        let vel: Velocity2D = ent.get_velocity();
297                        let pos: Point = ent.get_transform().get_position();
298                        let next_pos: Point = Point::new(
299                            pos.get_x() + vel.get_vx() * dt_secs,
300                            pos.get_y() + vel.get_vy() * dt_secs,
301                        );
302                        let next_rot: f32 =
303                            ent.get_transform().get_rotation_rad() + vel.get_angular() * dt_secs;
304                        ent.get_mut_transform().set_position(next_pos);
305                        ent.get_mut_transform().set_rotation_rad(next_rot);
306                        integrated += 1;
307                    }
308                    BodyKind::Dynamic => {
309                        let mut vel: Velocity2D = ent.get_velocity();
310                        let g_scale: f32 = body.get_gravity_scale();
311                        let damp: f32 = (1.0 - body.get_linear_drag() * dt_secs).clamp(0.0, 1.0);
312                        vel.set_vx((vel.get_vx() + gx_dt * g_scale) * damp);
313                        vel.set_vy((vel.get_vy() + gy_dt * g_scale) * damp);
314                        let pos: Point = ent.get_transform().get_position();
315                        let mut nx: f32 = pos.get_x() + vel.get_vx() * dt_secs;
316                        let mut ny: f32 = pos.get_y() + vel.get_vy() * dt_secs;
317                        if let Some(arena) = arena_opt {
318                            let (half_w, half_h): (f32, f32) = match ent.collider_component() {
319                                Some(col) => match col.get_shape() {
320                                    ColliderShape::Circle { radius } => (radius, radius),
321                                    ColliderShape::Aabb { width, height } => {
322                                        (width * 0.5, height * 0.5)
323                                    }
324                                },
325                                None => (0.0, 0.0),
326                            };
327                            let rest: f32 = body.get_restitution();
328                            let min_x: f32 = arena.get_x() + half_w;
329                            let max_x: f32 = arena.right() - half_w;
330                            let min_y: f32 = arena.get_y() + half_h;
331                            let max_y: f32 = arena.bottom() - half_h;
332                            if nx < min_x {
333                                nx = min_x;
334                                vel.set_vx(vel.get_vx().abs() * rest);
335                            } else if nx > max_x {
336                                nx = max_x;
337                                vel.set_vx(-vel.get_vx().abs() * rest);
338                            }
339                            if ny < min_y {
340                                ny = min_y;
341                                vel.set_vy(vel.get_vy().abs() * rest);
342                            } else if ny > max_y {
343                                ny = max_y;
344                                vel.set_vy(-vel.get_vy().abs() * rest);
345                            }
346                        }
347                        let next_rot: f32 =
348                            ent.get_transform().get_rotation_rad() + vel.get_angular() * dt_secs;
349                        ent.set_velocity(vel);
350                        ent.get_mut_transform().set_position(Point::new(nx, ny));
351                        ent.get_mut_transform().set_rotation_rad(next_rot);
352                        integrated += 1;
353                    }
354                }
355            }
356            if let Some(col) = ent.collider_component() {
357                let aabb: Rect = col.world_aabb(ent.get_transform().get_position());
358                let min_cx: i32 = (aabb.get_x() * inv_cell).floor() as i32;
359                let max_cx: i32 = (aabb.right() * inv_cell).floor() as i32;
360                let min_cy: i32 = (aabb.get_y() * inv_cell).floor() as i32;
361                let max_cy: i32 = (aabb.bottom() * inv_cell).floor() as i32;
362                grid_min_cx = grid_min_cx.min(min_cx);
363                grid_max_cx = grid_max_cx.max(max_cx);
364                grid_min_cy = grid_min_cy.min(min_cy);
365                grid_max_cy = grid_max_cy.max(max_cy);
366                let span_x: usize = ((max_cx as i64) - (min_cx as i64) + 1).max(1) as usize;
367                let span_y: usize = ((max_cy as i64) - (min_cy as i64) + 1).max(1) as usize;
368                total_cell_refs = total_cell_refs.saturating_add(span_x.saturating_mul(span_y));
369                body_bounds.push(BodyGridBounds {
370                    entity_idx: idx as u32,
371                    min_cx,
372                    max_cx,
373                    min_cy,
374                    max_cy,
375                    layer: col.get_layer(),
376                    mask: col.get_mask(),
377                });
378            }
379        }
380        let mut broad_count: usize = 0;
381        let mut events: Vec<CollisionEvent> = Vec::new();
382        if body_bounds.len() >= 2 {
383            let span_x_i64: i64 = (grid_max_cx as i64) - (grid_min_cx as i64) + 1;
384            let span_y_i64: i64 = (grid_max_cy as i64) - (grid_min_cy as i64) + 1;
385            let use_dense: bool = span_x_i64 > 0
386                && span_y_i64 > 0
387                && span_x_i64 <= FLAT_GRID_MAX_AXIS
388                && span_y_i64 <= FLAT_GRID_MAX_AXIS
389                && ((span_x_i64 * span_y_i64) as usize) <= FLAT_GRID_MAX_CELLS;
390            if use_dense {
391                let grid_w: usize = span_x_i64 as usize;
392                let grid_h: usize = span_y_i64 as usize;
393                let grid_cells: usize = grid_w * grid_h;
394                cell_counts.resize(grid_cells, 0);
395                cell_counts.fill(0);
396                for b in body_bounds.iter() {
397                    let rx0: usize = (b.min_cx - grid_min_cx) as usize;
398                    let rx1: usize = (b.max_cx - grid_min_cx) as usize;
399                    let ry0: usize = (b.min_cy - grid_min_cy) as usize;
400                    let ry1: usize = (b.max_cy - grid_min_cy) as usize;
401                    for ry in ry0..=ry1 {
402                        let row_off: usize = ry * grid_w;
403                        for rx in rx0..=rx1 {
404                            cell_counts[row_off + rx] += 1;
405                        }
406                    }
407                }
408                cell_offsets.resize(grid_cells, 0);
409                cell_cursors.resize(grid_cells, 0);
410                active_cells.clear();
411                let mut running: u32 = 0;
412                for ry in 0..grid_h {
413                    let cy: i32 = grid_min_cy + (ry as i32);
414                    let row_off: usize = ry * grid_w;
415                    for rx in 0..grid_w {
416                        let cidx: usize = row_off + rx;
417                        let cnt: u32 = cell_counts[cidx];
418                        cell_offsets[cidx] = running;
419                        cell_cursors[cidx] = running;
420                        running += cnt;
421                        if cnt >= 2 {
422                            active_cells.push((cidx, grid_min_cx + (rx as i32), cy));
423                        }
424                    }
425                }
426                cell_items.resize(running as usize, 0);
427                for (slot_idx, b) in body_bounds.iter().enumerate() {
428                    let slot_u32: u32 = slot_idx as u32;
429                    let rx0: usize = (b.min_cx - grid_min_cx) as usize;
430                    let rx1: usize = (b.max_cx - grid_min_cx) as usize;
431                    let ry0: usize = (b.min_cy - grid_min_cy) as usize;
432                    let ry1: usize = (b.max_cy - grid_min_cy) as usize;
433                    for ry in ry0..=ry1 {
434                        let row_off: usize = ry * grid_w;
435                        for rx in rx0..=rx1 {
436                            let cidx: usize = row_off + rx;
437                            let dst: usize = cell_cursors[cidx] as usize;
438                            cell_items[dst] = slot_u32;
439                            cell_cursors[cidx] = (dst + 1) as u32;
440                        }
441                    }
442                }
443                for &(cidx, cx, cy) in active_cells.iter() {
444                    let start: usize = cell_offsets[cidx] as usize;
445                    let end: usize = cell_cursors[cidx] as usize;
446                    let bucket: &[u32] = &cell_items[start..end];
447                    let n: usize = bucket.len();
448                    for i in 0..n {
449                        let ba: BodyGridBounds = body_bounds[bucket[i] as usize];
450                        for &sb_u32 in &bucket[(i + 1)..] {
451                            let bb: BodyGridBounds = body_bounds[sb_u32 as usize];
452                            if ba.min_cx.max(bb.min_cx) == cx && ba.min_cy.max(bb.min_cy) == cy {
453                                broad_count += 1;
454                                if (ba.layer & bb.mask) != 0 && (bb.layer & ba.mask) != 0 {
455                                    Self::resolve_pair(
456                                        entities,
457                                        ba.entity_idx as usize,
458                                        bb.entity_idx as usize,
459                                        pos_corr,
460                                        &mut events,
461                                    );
462                                }
463                            }
464                        }
465                    }
466                }
467            } else {
468                let needed_cap: usize = (total_cell_refs.saturating_mul(2).max(64))
469                    .next_power_of_two()
470                    .max(64);
471                let empty_cell: SparseGridCell = SparseGridCell {
472                    key: u64::MAX,
473                    cx: 0,
474                    cy: 0,
475                    head: u32::MAX,
476                    count: 0,
477                };
478                if sparse_table.len() < needed_cap {
479                    sparse_table.resize(needed_cap, empty_cell);
480                }
481                let cap: usize = sparse_table.len();
482                let mask: usize = cap - 1;
483                sparse_table.fill(empty_cell);
484                sparse_nodes.clear();
485                sparse_active.clear();
486                for (slot_idx, b) in body_bounds.iter().enumerate() {
487                    let slot_u32: u32 = slot_idx as u32;
488                    for cy in b.min_cy..=b.max_cy {
489                        for cx in b.min_cx..=b.max_cx {
490                            let key: u64 = Self::pack_cell_key(cx, cy);
491                            let mut h: usize =
492                                (key.wrapping_mul(SPARSE_GRID_HASH_MULT) >> 32) as usize & mask;
493                            loop {
494                                let cell: &mut SparseGridCell = &mut sparse_table[h];
495                                if cell.key == u64::MAX {
496                                    cell.key = key;
497                                    cell.cx = cx;
498                                    cell.cy = cy;
499                                    let node_idx: u32 = sparse_nodes.len() as u32;
500                                    sparse_nodes.push(SparseGridNode {
501                                        body_slot: slot_u32,
502                                        next: u32::MAX,
503                                    });
504                                    cell.head = node_idx;
505                                    cell.count = 1;
506                                    break;
507                                } else if cell.key == key {
508                                    let prev_head: u32 = cell.head;
509                                    let node_idx: u32 = sparse_nodes.len() as u32;
510                                    sparse_nodes.push(SparseGridNode {
511                                        body_slot: slot_u32,
512                                        next: prev_head,
513                                    });
514                                    cell.head = node_idx;
515                                    cell.count += 1;
516                                    if cell.count == 2 {
517                                        sparse_active.push(h);
518                                    }
519                                    break;
520                                }
521                                h = (h + 1) & mask;
522                            }
523                        }
524                    }
525                }
526                for &table_idx in sparse_active.iter() {
527                    let cell: SparseGridCell = sparse_table[table_idx];
528                    sparse_bucket_scratch.clear();
529                    let mut cur: u32 = cell.head;
530                    while cur != u32::MAX {
531                        let node: SparseGridNode = sparse_nodes[cur as usize];
532                        sparse_bucket_scratch.push(node.body_slot);
533                        cur = node.next;
534                    }
535                    sparse_bucket_scratch.reverse();
536                    let n: usize = sparse_bucket_scratch.len();
537                    for i in 0..n {
538                        let ba: BodyGridBounds = body_bounds[sparse_bucket_scratch[i] as usize];
539                        for &sb_u32 in &sparse_bucket_scratch[(i + 1)..] {
540                            let bb: BodyGridBounds = body_bounds[sb_u32 as usize];
541                            if ba.min_cx.max(bb.min_cx) == cell.cx
542                                && ba.min_cy.max(bb.min_cy) == cell.cy
543                            {
544                                broad_count += 1;
545                                if (ba.layer & bb.mask) != 0 && (bb.layer & ba.mask) != 0 {
546                                    Self::resolve_pair(
547                                        entities,
548                                        ba.entity_idx as usize,
549                                        bb.entity_idx as usize,
550                                        pos_corr,
551                                        &mut events,
552                                    );
553                                }
554                            }
555                        }
556                    }
557                }
558            }
559        }
560        self.set_last_stats(PhysicsStepStats::new(integrated, broad_count, events.len()));
561        events
562    }
563
564    /// Casts a 2D ray from `origin` along normalized `direction` up to `max_distance` against colliders matching `layer_mask`.
565    ///
566    /// # Arguments
567    ///
568    /// - `&GameWorld` - Game world to query.
569    /// - `Point` - Ray origin in world units.
570    /// - `Point` - Ray direction vector (normalized automatically).
571    /// - `f32` - Maximum ray distance.
572    /// - `u32` - Layer bitmask filter.
573    ///
574    /// # Returns
575    ///
576    /// - `Option<RaycastHit>` - Closest ray intersection hit, if any.
577    #[must_use]
578    pub fn raycast(
579        world: &GameWorld,
580        origin: Point,
581        direction: Point,
582        max_distance: f32,
583        layer_mask: u32,
584    ) -> Option<RaycastHit> {
585        let len: f32 =
586            (direction.get_x() * direction.get_x() + direction.get_y() * direction.get_y()).sqrt();
587        if len <= 1e-6 || max_distance <= 0.0 {
588            return None;
589        }
590        let dx: f32 = direction.get_x() / len;
591        let dy: f32 = direction.get_y() / len;
592        let mut closest: Option<RaycastHit> = None;
593        let mut best_t: f32 = max_distance;
594        for ent in world.get_entities().iter() {
595            if !ent.get_alive() {
596                continue;
597            }
598            let Some(col) = ent.collider_component() else {
599                continue;
600            };
601            if (col.get_layer() & layer_mask) == 0 {
602                continue;
603            }
604            let pos: Point = ent.get_transform().get_position();
605            let hit_opt: Option<(f32, Point)> = match col.get_shape() {
606                ColliderShape::Circle { radius } => {
607                    Self::ray_vs_circle(origin, (dx, dy), pos, radius, best_t)
608                }
609                ColliderShape::Aabb { width, height } => Self::ray_vs_aabb(
610                    origin,
611                    (dx, dy),
612                    Rect::new(
613                        pos.get_x() - width * 0.5,
614                        pos.get_y() - height * 0.5,
615                        width,
616                        height,
617                    ),
618                    best_t,
619                ),
620            };
621            if let Some((t, normal)) = hit_opt
622                && t < best_t
623            {
624                best_t = t;
625                let hit_pt: Point = Point::new(origin.get_x() + dx * t, origin.get_y() + dy * t);
626                closest = Some(RaycastHit::new(ent.get_id(), hit_pt, normal, t));
627            }
628        }
629        closest
630    }
631
632    /// Casts a 2D ray defined by a fluent `RaycastQuery2D` against `world`.
633    ///
634    /// # Arguments
635    ///
636    /// - `&GameWorld` - Game world to query.
637    /// - `&RaycastQuery2D` - Raycast query descriptor.
638    ///
639    /// # Returns
640    ///
641    /// - `Option<RaycastHit>` - Closest ray intersection hit, if any.
642    #[must_use]
643    pub fn raycast_query(world: &GameWorld, query: &RaycastQuery2D) -> Option<RaycastHit> {
644        Self::raycast(
645            world,
646            query.get_origin(),
647            query.get_direction(),
648            query.get_max_distance(),
649            query.get_layer_mask(),
650        )
651    }
652
653    /// Evaluates narrow-phase overlap between two shapes returning `(normal_a_to_b, penetration)`.
654    ///
655    /// # Arguments
656    ///
657    /// - `Point` - Center of shape A.
658    /// - `ColliderShape` - Geometry of shape A.
659    /// - `Point` - Center of shape B.
660    /// - `ColliderShape` - Geometry of shape B.
661    ///
662    /// # Returns
663    ///
664    /// - `Option<(Point, f32)>` - Contact normal and positive penetration depth if overlapping.
665    fn narrow_phase(
666        pos_a: Point,
667        shape_a: ColliderShape,
668        pos_b: Point,
669        shape_b: ColliderShape,
670    ) -> Option<(Point, f32)> {
671        match (shape_a, shape_b) {
672            (ColliderShape::Circle { radius: ra }, ColliderShape::Circle { radius: rb }) => {
673                let dx: f32 = pos_b.get_x() - pos_a.get_x();
674                let dy: f32 = pos_b.get_y() - pos_a.get_y();
675                let r_sum: f32 = ra + rb;
676                let dist_sq: f32 = dx * dx + dy * dy;
677                if dist_sq >= r_sum * r_sum {
678                    return None;
679                }
680                let dist: f32 = dist_sq.sqrt();
681                if dist <= 1e-5 {
682                    Some((Point::new(1.0, 0.0), r_sum))
683                } else {
684                    let inv_dist: f32 = 1.0 / dist;
685                    Some((Point::new(dx * inv_dist, dy * inv_dist), r_sum - dist))
686                }
687            }
688            (
689                ColliderShape::Aabb {
690                    width: wa,
691                    height: ha,
692                },
693                ColliderShape::Aabb {
694                    width: wb,
695                    height: hb,
696                },
697            ) => {
698                let dx: f32 = pos_b.get_x() - pos_a.get_x();
699                let dy: f32 = pos_b.get_y() - pos_a.get_y();
700                let ox: f32 = (wa + wb) * 0.5 - dx.abs();
701                if ox <= 0.0 {
702                    return None;
703                }
704                let oy: f32 = (ha + hb) * 0.5 - dy.abs();
705                if oy <= 0.0 {
706                    return None;
707                }
708                if ox < oy {
709                    let nx: f32 = if dx < 0.0 { -1.0 } else { 1.0 };
710                    Some((Point::new(nx, 0.0), ox))
711                } else {
712                    let ny: f32 = if dy < 0.0 { -1.0 } else { 1.0 };
713                    Some((Point::new(0.0, ny), oy))
714                }
715            }
716            (ColliderShape::Circle { radius }, ColliderShape::Aabb { width, height }) => {
717                Self::circle_vs_aabb(pos_a, radius, pos_b, width, height)
718            }
719            (ColliderShape::Aabb { width, height }, ColliderShape::Circle { radius }) => {
720                Self::circle_vs_aabb(pos_b, radius, pos_a, width, height)
721                    .map(|(n, pen): (Point, f32)| (Point::new(-n.get_x(), -n.get_y()), pen))
722            }
723        }
724    }
725
726    /// Narrow-phase Circle-vs-AABB overlap test returning normal pointing from circle to box.
727    ///
728    /// # Arguments
729    ///
730    /// - `Point` - Circle center.
731    /// - `f32` - Circle radius.
732    /// - `Point` - AABB center.
733    /// - `f32` - AABB full width.
734    /// - `f32` - AABB full height.
735    ///
736    /// # Returns
737    ///
738    /// - `Option<(Point, f32)>` - Contact normal and penetration depth.
739    fn circle_vs_aabb(
740        c_pos: Point,
741        radius: f32,
742        b_pos: Point,
743        bw: f32,
744        bh: f32,
745    ) -> Option<(Point, f32)> {
746        let half_w: f32 = bw * 0.5;
747        let half_h: f32 = bh * 0.5;
748        let rel_x: f32 = c_pos.get_x() - b_pos.get_x();
749        let rel_y: f32 = c_pos.get_y() - b_pos.get_y();
750        let closest_x: f32 = rel_x.clamp(-half_w, half_w);
751        let closest_y: f32 = rel_y.clamp(-half_h, half_h);
752        let dx: f32 = rel_x - closest_x;
753        let dy: f32 = rel_y - closest_y;
754        let dist_sq: f32 = dx * dx + dy * dy;
755        if dist_sq >= radius * radius {
756            return None;
757        }
758        let dist: f32 = dist_sq.sqrt();
759        if dist <= 1e-5 {
760            let ox: f32 = half_w - rel_x.abs();
761            let oy: f32 = half_h - rel_y.abs();
762            if ox < oy {
763                let nx: f32 = if rel_x < 0.0 { 1.0 } else { -1.0 };
764                Some((Point::new(nx, 0.0), ox + radius))
765            } else {
766                let ny: f32 = if rel_y < 0.0 { 1.0 } else { -1.0 };
767                Some((Point::new(0.0, ny), oy + radius))
768            }
769        } else {
770            Some((Point::new(-dx / dist, -dy / dist), radius - dist))
771        }
772    }
773
774    /// Ray-vs-circle analytic intersection test.
775    ///
776    /// # Arguments
777    ///
778    /// - `Point` - Ray origin.
779    /// - `(f32, f32)` - Normalized ray direction.
780    /// - `Point` - Circle center.
781    /// - `f32` - Circle radius.
782    /// - `f32` - Maximum distance.
783    ///
784    /// # Returns
785    ///
786    /// - `Option<(f32, Point)>` - Hit distance and outward surface normal.
787    fn ray_vs_circle(
788        origin: Point,
789        dir: (f32, f32),
790        center: Point,
791        radius: f32,
792        max_dist: f32,
793    ) -> Option<(f32, Point)> {
794        let oc_x: f32 = origin.get_x() - center.get_x();
795        let oc_y: f32 = origin.get_y() - center.get_y();
796        let b: f32 = oc_x * dir.0 + oc_y * dir.1;
797        let c: f32 = oc_x * oc_x + oc_y * oc_y - radius * radius;
798        let disc: f32 = b * b - c;
799        if disc < 0.0 {
800            return None;
801        }
802        let t: f32 = -b - disc.sqrt();
803        if t < 0.0 || t > max_dist {
804            return None;
805        }
806        let hx: f32 = origin.get_x() + dir.0 * t;
807        let hy: f32 = origin.get_y() + dir.1 * t;
808        let inv_r: f32 = 1.0 / radius.max(1e-5);
809        Some((
810            t,
811            Point::new((hx - center.get_x()) * inv_r, (hy - center.get_y()) * inv_r),
812        ))
813    }
814
815    /// Ray-vs-AABB slab intersection test.
816    ///
817    /// # Arguments
818    ///
819    /// - `Point` - Ray origin.
820    /// - `(f32, f32)` - Normalized ray direction.
821    /// - `Rect` - Axis-aligned box rectangle.
822    /// - `f32` - Maximum distance.
823    ///
824    /// # Returns
825    ///
826    /// - `Option<(f32, Point)>` - Hit distance and outward surface normal.
827    fn ray_vs_aabb(
828        origin: Point,
829        dir: (f32, f32),
830        rect: Rect,
831        max_dist: f32,
832    ) -> Option<(f32, Point)> {
833        let mut t_min: f32 = 0.0;
834        let mut t_max: f32 = max_dist;
835        let mut normal: Point = Point::new(0.0, 0.0);
836        if dir.0.abs() < 1e-6 {
837            if origin.get_x() < rect.get_x() || origin.get_x() > rect.right() {
838                return None;
839            }
840        } else {
841            let inv: f32 = 1.0 / dir.0;
842            let mut t1: f32 = (rect.get_x() - origin.get_x()) * inv;
843            let mut t2: f32 = (rect.right() - origin.get_x()) * inv;
844            let mut nx: f32 = -1.0;
845            if t1 > t2 {
846                swap(&mut t1, &mut t2);
847                nx = 1.0;
848            }
849            if t1 > t_min {
850                t_min = t1;
851                normal = Point::new(nx, 0.0);
852            }
853            t_max = t_max.min(t2);
854            if t_min > t_max {
855                return None;
856            }
857        }
858        if dir.1.abs() < 1e-6 {
859            if origin.get_y() < rect.get_y() || origin.get_y() > rect.bottom() {
860                return None;
861            }
862        } else {
863            let inv: f32 = 1.0 / dir.1;
864            let mut t1: f32 = (rect.get_y() - origin.get_y()) * inv;
865            let mut t2: f32 = (rect.bottom() - origin.get_y()) * inv;
866            let mut ny: f32 = -1.0;
867            if t1 > t2 {
868                swap(&mut t1, &mut t2);
869                ny = 1.0;
870            }
871            if t1 > t_min {
872                t_min = t1;
873                normal = Point::new(0.0, ny);
874            }
875            t_max = t_max.min(t2);
876            if t_min > t_max {
877                return None;
878            }
879        }
880        Some((t_min, normal))
881    }
882}