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
//! [`Point`] represents x, y coordinates.

/// Auxiliary struct representing 2D coordinates.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Point(pub f64, pub f64);

impl Point {
    pub fn from_angle(angle: f64) -> Point {
        Point(angle.cos(), angle.sin())
    }

    pub fn dot(&self, rhs: &Self) -> f64 {
        self.0 * rhs.0 + self.1 * rhs.1
    }

    pub fn lerp(self, rhs: Self, v: f64) -> Self {
        self * (1.0 - v) + rhs * v
    }

    pub fn norm(self) -> f64 {
        self.0.hypot(self.1)
    }

    pub fn atan2(self) -> f64 {
        self.1.atan2(self.0)
    }

    pub fn rotate(self, angle: f64) -> Self {
        let (sin, cos) = angle.sin_cos();
        Point(self.0 * cos - self.1 * sin, self.0 * sin + self.1 * cos)
    }

    pub fn unit(self) -> Point {
        self / self.0.hypot(self.1)
    }
}

impl std::ops::Add for Point {
    type Output = Self;
    fn add(self, rhs: Self) -> Self {
        Point(self.0 + rhs.0, self.1 + rhs.1)
    }
}

impl std::ops::Sub for Point {
    type Output = Self;
    fn sub(self, rhs: Self) -> Self {
        Point(self.0 - rhs.0, self.1 - rhs.1)
    }
}

impl std::ops::Mul<f64> for Point {
    type Output = Self;
    fn mul(self, rhs: f64) -> Self {
        Point(self.0 * rhs, self.1 * rhs)
    }
}

impl std::ops::Div<f64> for Point {
    type Output = Self;
    fn div(self, rhs: f64) -> Self {
        Point(self.0 / rhs, self.1 / rhs)
    }
}

impl<T: Into<f64>> From<(T, T)> for Point {
    fn from(tuple: (T, T)) -> Point {
        Point(tuple.0.into(), tuple.1.into())
    }
}

impl From<Point> for (f64, f64) {
    fn from(point: Point) -> (f64, f64) {
        (point.0, point.1)
    }
}