aboutsummaryrefslogtreecommitdiff
path: root/evc/src/helpers/vector.rs
blob: 9e7369e5c6e5135aa5a94df21a7e099229af2101 (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
use crate::ser::{Ser, Sink, Source};

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Vec2<T> {
    pub x: T,
    pub y: T,
}

impl Vec2<isize> {
    pub const ZERO: Vec2<isize> = Vec2 { x: 0, y: 0 };
    pub const UP: Vec2<isize> = Vec2 { x: 0, y: -1 };
    pub const LEFT: Vec2<isize> = Vec2 { x: -1, y: 0 };
}
impl Vec2<f32> {
    pub const ZERO: Vec2<f32> = Vec2 { x: 0.0, y: 0.0 };
    pub const UP: Vec2<f32> = Vec2 { x: 0.0, y: -1.0 };
    pub const LEFT: Vec2<f32> = Vec2 { x: -1.0, y: 0.0 };
}

impl<T: std::ops::Div<Output = T> + Copy> Vec2<T> {
    pub fn downscale(&self, f: T) -> Self {
        Self {
            x: self.x / f,
            y: self.y / f,
        }
    }
}

impl Ser for Vec2<isize> {
    fn write(&self, sink: &mut impl std::io::Write) -> anyhow::Result<()> {
        sink.put((self.x, self.y))
    }

    fn read(source: &mut impl std::io::Read) -> anyhow::Result<Self> {
        let (x, y) = source.get()?;
        Ok(Vec2 { x, y })
    }
}

pub struct Small<T>(pub T);
impl Ser for Small<Vec2<isize>> {
    fn write(&self, sink: &mut impl std::io::Write) -> anyhow::Result<()> {
        sink.put((self.0.x as i8, self.0.y as i8))
    }

    fn read(source: &mut impl std::io::Read) -> anyhow::Result<Self> {
        let (x, y): (i8, i8) = source.get()?;
        Ok(Small(Vec2 {
            x: x as isize,
            y: y as isize,
        }))
    }
}

impl<T: std::ops::Add> std::ops::Add for Vec2<T> {
    type Output = Vec2<T::Output>;
    #[inline]
    fn add(self, rhs: Self) -> Self::Output {
        Vec2 {
            x: self.x + rhs.x,
            y: self.y + rhs.y,
        }
    }
}
impl<T: std::ops::Sub> std::ops::Sub for Vec2<T> {
    type Output = Vec2<T::Output>;
    #[inline]
    fn sub(self, rhs: Self) -> Self::Output {
        Vec2 {
            x: self.x - rhs.x,
            y: self.y - rhs.y,
        }
    }
}
impl<T: std::ops::Mul> std::ops::Mul for Vec2<T> {
    type Output = Vec2<T::Output>;
    #[inline]
    fn mul(self, rhs: Self) -> Self::Output {
        Vec2 {
            x: self.x * rhs.x,
            y: self.y * rhs.y,
        }
    }
}

impl<T> From<(T, T)> for Vec2<T> {
    #[inline]
    fn from((x, y): (T, T)) -> Self {
        Vec2 { x, y }
    }
}