2019-07-20 19:12:31 +02:00
|
|
|
/// A 2D vector.
|
2022-08-17 16:09:25 +02:00
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
2019-11-05 03:16:46 +01:00
|
|
|
pub struct Vector<T = f32> {
|
2019-11-18 07:16:19 +01:00
|
|
|
/// The X component of the [`Vector`]
|
2019-11-05 03:16:46 +01:00
|
|
|
pub x: T,
|
2019-11-18 07:16:19 +01:00
|
|
|
|
|
|
|
|
/// The Y component of the [`Vector`]
|
2019-11-05 03:16:46 +01:00
|
|
|
pub y: T,
|
2019-08-31 04:31:13 +02:00
|
|
|
}
|
|
|
|
|
|
2019-11-05 03:16:46 +01:00
|
|
|
impl<T> Vector<T> {
|
2019-08-31 04:31:13 +02:00
|
|
|
/// Creates a new [`Vector`] with the given components.
|
2019-11-29 21:24:52 -05:00
|
|
|
pub const fn new(x: T, y: T) -> Self {
|
2019-08-31 04:31:13 +02:00
|
|
|
Self { x, y }
|
|
|
|
|
}
|
|
|
|
|
}
|
2019-11-05 03:16:46 +01:00
|
|
|
|
2023-01-30 05:01:28 +01:00
|
|
|
impl Vector {
|
|
|
|
|
/// The zero [`Vector`].
|
|
|
|
|
pub const ZERO: Self = Self::new(0.0, 0.0);
|
|
|
|
|
}
|
|
|
|
|
|
2024-05-10 18:50:10 -03:00
|
|
|
impl<T> std::ops::Neg for Vector<T>
|
|
|
|
|
where
|
|
|
|
|
T: std::ops::Neg<Output = T>,
|
|
|
|
|
{
|
|
|
|
|
type Output = Self;
|
|
|
|
|
|
|
|
|
|
fn neg(self) -> Self::Output {
|
|
|
|
|
Self::new(-self.x, -self.y)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-11-05 03:16:46 +01:00
|
|
|
impl<T> std::ops::Add for Vector<T>
|
|
|
|
|
where
|
|
|
|
|
T: std::ops::Add<Output = T>,
|
|
|
|
|
{
|
|
|
|
|
type Output = Self;
|
|
|
|
|
|
|
|
|
|
fn add(self, b: Self) -> Self {
|
|
|
|
|
Self::new(self.x + b.x, self.y + b.y)
|
|
|
|
|
}
|
|
|
|
|
}
|
2020-01-05 19:29:12 +01:00
|
|
|
|
2020-03-07 23:45:54 +01:00
|
|
|
impl<T> std::ops::Sub for Vector<T>
|
|
|
|
|
where
|
|
|
|
|
T: std::ops::Sub<Output = T>,
|
|
|
|
|
{
|
|
|
|
|
type Output = Self;
|
|
|
|
|
|
|
|
|
|
fn sub(self, b: Self) -> Self {
|
|
|
|
|
Self::new(self.x - b.x, self.y - b.y)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-05-01 04:32:56 +02:00
|
|
|
impl<T> std::ops::Mul<T> for Vector<T>
|
|
|
|
|
where
|
|
|
|
|
T: std::ops::Mul<Output = T> + Copy,
|
|
|
|
|
{
|
|
|
|
|
type Output = Self;
|
|
|
|
|
|
|
|
|
|
fn mul(self, scale: T) -> Self {
|
|
|
|
|
Self::new(self.x * scale, self.y * scale)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-01-05 19:29:12 +01:00
|
|
|
impl<T> Default for Vector<T>
|
|
|
|
|
where
|
|
|
|
|
T: Default,
|
|
|
|
|
{
|
|
|
|
|
fn default() -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
x: T::default(),
|
|
|
|
|
y: T::default(),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2020-10-28 02:36:49 +01:00
|
|
|
|
|
|
|
|
impl<T> From<[T; 2]> for Vector<T> {
|
|
|
|
|
fn from([x, y]: [T; 2]) -> Self {
|
|
|
|
|
Self::new(x, y)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<T> From<Vector<T>> for [T; 2]
|
|
|
|
|
where
|
|
|
|
|
T: Copy,
|
|
|
|
|
{
|
|
|
|
|
fn from(other: Vector<T>) -> Self {
|
|
|
|
|
[other.x, other.y]
|
|
|
|
|
}
|
|
|
|
|
}
|