summaryrefslogtreecommitdiff
path: root/game_server/src/maths.rs
blob: 8844c6e9d61392cad16c94d02e657cf42ce43bf9 (plain)
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#[derive(Clone, Copy)]
pub struct Vec2 {
    pub x: f32,
    pub y: f32,
}

impl std::ops::Add for Vec2 {
    type Output = Self;
    fn add(self, other: Self) -> Self {
        Self {
            x: self.x + other.x,
            y: self.y + other.y
        }
    }
}

impl std::ops::Sub for Vec2 {
    type Output = Self;
    fn sub(self, other: Self) -> Self {
        Self {
            x: self.x - other.x,
            y: self.y - other.y
        }
    }
}

impl std::ops::Neg for Vec2 {
    type Output = Self;
    fn neg(self) -> Self {
        Self {
            x: -self.x,
            y: -self.y
        }
    }
}

impl std::cmp::PartialOrd for Vec2 {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(if self.x < other.x && self.y < other.y {
            std::cmp::Ordering::Less
        } else if self.x > other.x && self.y > other.y {
            std::cmp::Ordering::Greater
        } else {
            std::cmp::Ordering::Equal
        })
    }
}

impl std::cmp::PartialEq for Vec2 {
    fn eq(&self, other: &Self) -> bool {
        f32::abs(self.x - other.x) < 1e-8
        && f32::abs(self.y - other.y) < 1e-8
    }
}

impl std::cmp::Eq for Vec2 {}

impl Vec2 {
    pub fn distance(&self) -> f32 {
        f32::sqrt(self.distance2())
    }

    pub fn distance2(&self) -> f32 {
        self.x * self.x + self.y * self.y
    }
}

pub struct Box {
    pub pos: Vec2,
    /// the size may not be smaller than zero
    pub size: Vec2, 
}

impl std::ops::Add<Vec2> for Box {
    type Output = Self;
    fn add(self, other: Vec2) -> Self {
        Self {
            p1: self.p1 + other,
            p2: self.p2 + other,
        }
    }
}

impl std::ops::Sub<Vec2> for Box {
    type Output = Self;
    fn sub(self, other: Vec2) -> Self {
        Self {
            pos: self.pos + other,
            size: self.size + other
        }
    }
}

pub struct RBox {
    /// Point 1
    pub p1: Vec2,
    /// Point 2
    pub p2: Vec2, 
    /// Width
    pub w: f32,
}

impl std::ops::Add<Vec2> for RBox {
    type Output = Self;
    fn add(self, other: Vec2) -> Self {
        Self {
            p1: self.p1 + other,
            p2: self.p2 + other,
            w: self.w,
        }
    }
}

impl std::ops::Sub<Vec2> for RBox {
    type Output = Self;
    fn sub(self, other: Vec2) -> Self {
        Self {
            p1: self.p1 + other,
            p2: self.p2 + other,
            w: self.w,
        }
    }
}