1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
use quadtree_rs::{area::AreaBuilder, point::Point, Quadtree};

use crate::geometry::{Rectangle, Vector};

use super::CollisionStrategy;

/// The default collision detection implemented with a QuadTree
pub struct BoundingBoxCollider {
    qt: Quadtree<u32, Rectangle>,
    padding: u32,
}

impl BoundingBoxCollider {
    /// Create a new BoundingBoxCollider instance.
    ///
    /// `max_width` is the maximum width of the surface detecting the collisions.
    ///
    /// `padding` is the spacing to use between rectangles.
    pub fn new(max_width: u32, padding: u32) -> BoundingBoxCollider {
        BoundingBoxCollider {
            qt: Quadtree::<u32, Rectangle>::new(f32::sqrt(max_width as f32) as usize),
            padding,
        }
    }
}

impl CollisionStrategy for BoundingBoxCollider {
    fn collides(&self, pos: Vector, r: &Rectangle) -> bool {
        let r = r.grow(2 * self.padding as isize).unwrap();

        let region = AreaBuilder::default()
            .anchor(Point { x: pos.0, y: pos.1 })
            .dimensions((r.size().0, r.size().1))
            .build()
            .unwrap();

        let query = self.qt.query(region);

        query.count() != 0
    }

    fn add(&mut self, pos: Vector, r: Rectangle) {
        let region = AreaBuilder::default()
            .anchor(Point {
                x: pos.0 + self.padding,
                y: pos.1 + self.padding,
            })
            .dimensions((r.size().0, r.size().1))
            .build()
            .unwrap();

        self.qt.insert(region, r);
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn collide() {
        let mut bbc = BoundingBoxCollider::new(50, 0);
        bbc.add((0, 0), Rectangle::new(0, 0, 10, 5));
        bbc.add((20, 0), Rectangle::new(20, 0, 10, 10));

        assert!(!bbc.collides((15, 5), &Rectangle::new(0, 0, 5, 3)));
        assert!(!bbc.collides((30, 5), &Rectangle::new(0, 0, 5, 3)));

        assert!(bbc.collides((15, 0), &Rectangle::new(0, 0, 10, 10)));
        assert!(bbc.collides((0, 0), &Rectangle::new(0, 0, 1, 1)));
    }
}