From 85d20c4f4cf3656fbf7c27b6b8bbf9536e3ae04d Mon Sep 17 00:00:00 2001 From: metamuffin Date: Wed, 7 Dec 2022 17:16:40 +0100 Subject: refactor, matrix math --- evc/src/helpers/vector.rs | 92 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 evc/src/helpers/vector.rs (limited to 'evc/src/helpers/vector.rs') diff --git a/evc/src/helpers/vector.rs b/evc/src/helpers/vector.rs new file mode 100644 index 0000000..9e7369e --- /dev/null +++ b/evc/src/helpers/vector.rs @@ -0,0 +1,92 @@ +use crate::ser::{Ser, Sink, Source}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Vec2 { + pub x: T, + pub y: T, +} + +impl Vec2 { + pub const ZERO: Vec2 = Vec2 { x: 0, y: 0 }; + pub const UP: Vec2 = Vec2 { x: 0, y: -1 }; + pub const LEFT: Vec2 = Vec2 { x: -1, y: 0 }; +} +impl Vec2 { + pub const ZERO: Vec2 = Vec2 { x: 0.0, y: 0.0 }; + pub const UP: Vec2 = Vec2 { x: 0.0, y: -1.0 }; + pub const LEFT: Vec2 = Vec2 { x: -1.0, y: 0.0 }; +} + +impl + Copy> Vec2 { + pub fn downscale(&self, f: T) -> Self { + Self { + x: self.x / f, + y: self.y / f, + } + } +} + +impl Ser for Vec2 { + 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 { + let (x, y) = source.get()?; + Ok(Vec2 { x, y }) + } +} + +pub struct Small(pub T); +impl Ser for Small> { + 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 { + let (x, y): (i8, i8) = source.get()?; + Ok(Small(Vec2 { + x: x as isize, + y: y as isize, + })) + } +} + +impl std::ops::Add for Vec2 { + type Output = Vec2; + #[inline] + fn add(self, rhs: Self) -> Self::Output { + Vec2 { + x: self.x + rhs.x, + y: self.y + rhs.y, + } + } +} +impl std::ops::Sub for Vec2 { + type Output = Vec2; + #[inline] + fn sub(self, rhs: Self) -> Self::Output { + Vec2 { + x: self.x - rhs.x, + y: self.y - rhs.y, + } + } +} +impl std::ops::Mul for Vec2 { + type Output = Vec2; + #[inline] + fn mul(self, rhs: Self) -> Self::Output { + Vec2 { + x: self.x * rhs.x, + y: self.y * rhs.y, + } + } +} + +impl From<(T, T)> for Vec2 { + #[inline] + fn from((x, y): (T, T)) -> Self { + Vec2 { x, y } + } +} + -- cgit v1.2.3-70-g09d2