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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#[cfg(feature="ncollide2d")] use ncollide2d::shape::Ball;
use crate::geom::{about_equal, Scalar, Vector};
use std::{
    cmp::{Eq, PartialEq},
};

#[derive(Clone, Copy, Default, Debug, Deserialize, Serialize)]
///A circle with a center and a radius
pub struct Circle {
    /// The position of the center of the circle
    pub pos: Vector,
    /// The radius of the circle
    pub radius: f32,
}

impl Circle {
    /// Create a circle with the center as a vector
    pub fn new(center: impl Into<Vector>, radius: impl Scalar) -> Circle {
        Circle {
            pos:    center.into(),
            radius: radius.float()
        }
    }

    ///Construct a circle from a center and a Ball
    #[cfg(feature="ncollide2d")]
    pub fn from_ball(center: impl Into<Vector>, ball: Ball<f32>) -> Circle {
        Circle::new(center.into(), ball.radius())
    }

    ///Convert the circle into an ncollide Ball
    #[cfg(feature="ncollide2d")]
    pub fn into_ball(self) -> Ball<f32> {
        Ball::new(self.radius)
    }
}

impl PartialEq for Circle {
    fn eq(&self, other: &Circle) -> bool {
        return about_equal(self.pos.x, other.pos.x)
            && about_equal(self.pos.y, other.pos.y)
            && about_equal(self.radius, other.radius)
    }
}

impl Eq for Circle {}

#[cfg(test)]
mod tests {
    use crate::geom::*;

    #[test]
    fn construction() {
        let circ = Circle::new((0f32, 1f32), 2f32);
        assert_eq!(circ.pos.x, 0f32);
        assert_eq!(circ.pos.y, 1f32);
        assert_eq!(circ.radius, 2f32);
    }

    #[test]
    fn contains() {
        let circ = Circle::new((0, 0), 10);
        let vec1 = Vector::new(0, 0);
        let vec2 = Vector::new(11, 11);
        assert!(circ.contains(vec1));
        assert!(!circ.contains(vec2));
    }

    #[test]
    fn overlap() {
        let a = &Circle::new((0, 0), 16);
        let b = &Circle::new((5, 5), 4);
        let c = &Circle::new((50, 50), 5);
        let d = &Rectangle::new((10, 10), (10, 10));
        assert!(a.overlaps(b));
        assert!(!a.overlaps(c));
        assert!(a.overlaps(d));
        assert!(!c.overlaps(d));
    }

    #[test]
    fn rect_overlap() {
        let circ = &Circle::new((0, 0), 5);
        let rec1 = &Rectangle::new_sized((2, 2));
        let rec2 = &Rectangle::new((5, 5), (4, 4));
        assert!(circ.overlaps(rec1));
        assert!(rec1.overlaps(circ));
        assert!(!circ.overlaps(rec2));
        assert!(!rec2.overlaps(circ));
    }

    #[test]
    fn translate() {
        let circ = Circle::new((0, 0), 16);
        let translate = Vector::new(4, 4);
        assert_eq!(circ.center() + translate, circ.translate(translate).center());
    }

}