use std::ops::{Add, Div, Mul, Rem, Sub}; pub type Point = Vec2; impl Point { pub const ZERO: Self = Point::new(0, 0); pub fn usize(self) -> Vec2 { Vec2::new(self.x as usize, self.y as usize) } } #[derive(Copy, Clone, Debug, PartialEq)] pub struct Vec2 { pub x: T, pub y: T, } impl Vec2 { pub const fn new(x: T, y: T) -> Self { Self { x, y } } } impl Vec2 where T: Add, T: Mul, T: Div, T: Rem, { pub fn xy(idx: T, width: T) -> Self { Self { x: idx % width, y: idx / width, } } pub fn idx(self, width: T) -> T { self.y * width + self.x } } impl From for Vec2 { fn from(p: Point) -> Self { Self::new(p.x as usize, p.y as usize) } } impl> Add for Vec2 { type Output = Vec2; fn add(self, rhs: Self) -> Self::Output { Self::new(self.x + rhs.x, self.y + rhs.y) } } impl> Sub for Vec2 { type Output = Vec2; fn sub(self, rhs: Self) -> Self::Output { Self::new(self.x - rhs.x, self.y - rhs.y) } } impl> Sub for Vec2 { type Output = Vec2; fn sub(self, rhs: T) -> Self::Output { Self::new(self.x - rhs, self.y - rhs) } } impl> Mul for Vec2 { type Output = Vec2; fn mul(self, rhs: Self) -> Self::Output { Self::new(self.x * rhs.x, self.y * rhs.y) } } impl> Mul for Vec2 { type Output = Vec2; fn mul(self, rhs: T) -> Self::Output { Self::new(self.x * rhs, self.y * rhs) } } impl> Div for Vec2 { type Output = Vec2; fn div(self, rhs: T) -> Self::Output { Self::new(self.x / rhs, self.y / rhs) } } #[inline(always)] pub fn greay32(k: u8) -> u32 { k as u32 | (k as u32) << 8 | (k as u32) << 16 } #[inline(always)] pub fn color32(r: u8, g: u8, b: u8) -> u32 { b as u32 | (g as u32) << 8 | (r as u32) << 16 } impl Vec2 { pub fn signed(self) -> Vec2 { Vec2::new(self.x.signed(), self.y.signed()) } } impl Vec2 { pub fn unsigned(self) -> Vec2 { Vec2::new(self.x.unsigned(), self.y.unsigned()) } } pub trait AsSigned { type Output; fn signed(self) -> Self::Output; } pub trait AsUnsigned { type Output; fn unsigned(self) -> Self::Output; } macro_rules! impl_num { (+$unsigned:ty, -$signed:ty) => { impl AsSigned for $unsigned { type Output = $signed; fn signed(self) -> Self::Output { self.cast_signed() } } impl AsUnsigned for $signed { type Output = $unsigned; fn unsigned(self) -> Self::Output { self.cast_unsigned() } } }; } impl_num!(+u8, -i8); impl_num!(+u16, -i16); impl_num!(+u32, -i32); impl_num!(+u64, -i64); impl_num!(+usize, -isize);