engine/math/src/vec3.rs

120 lines
2.6 KiB
Rust
Raw Normal View History

2024-08-23 11:22:09 +00:00
use std::ops::{Add, Div, Mul, Sub};
use std::ops::{Index, IndexMut};
pub struct Vec3<T> {
pub x: T,
pub y: T,
pub z: T,
}
impl<T: Add<Output = T>> Add for Vec3<T> {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z,
}
}
}
impl<T: Sub<Output = T>> Sub for Vec3<T> {
type Output = Self;
fn sub(self, other: Self) -> Self {
Self {
x: self.x - other.x,
y: self.y - other.y,
z: self.z - other.z,
}
}
}
impl<T: Mul<U, Output = T>, U: Clone> Mul<U> for Vec3<T> {
type Output = Self;
fn mul(self, other: U) -> Self {
Self {
x: self.x * other.clone(),
y: self.y * other.clone(),
z: self.z * other.clone(),
}
}
}
impl<T: Div<U, Output = T>, U: Clone> Div<U> for Vec3<T> {
type Output = Self;
fn div(self, other: U) -> Self {
Self {
x: self.x / other.clone(),
y: self.y / other.clone(),
z: self.z / other.clone(),
}
}
}
impl<T: Mul<Output = T> + Add<Output = T>> Dot<T> for Vec3<T> {
fn dot(me: Self, other: Self) -> T {
me.x * other.x + me.y * other.y + me.z * other.z
}
}
impl<T: Clone + Mul<Output = T> + Sub<Output = T>> Cross<T> for Vec3<T> {
fn cross(me: Self, other: Self) -> Self {
Self {
x: me.y.clone() * other.z.clone() - me.z.clone() * other.y.clone(),
y: me.z.clone() * other.x.clone() - me.x.clone() * other.z.clone(),
z: me.x.clone() * other.y.clone() - me.y.clone() * other.x.clone(),
}
}
}
impl<T> Index<usize> for Vec3<T> {
type Output = T;
fn index(&self, index: usize) -> &T {
match index {
0 => &self.x,
1 => &self.y,
2 => &self.z,
_ => panic!("Index not found"),
}
}
}
impl<T> IndexMut<usize> for Vec3<T> {
fn index_mut(&mut self, index: usize) -> &mut T {
match index {
0 => &mut self.x,
1 => &mut self.y,
2 => &mut self.z,
_ => panic!("Index not found"),
}
}
}
impl<T: Clone> From<[T; 3]> for Vec3<T> {
fn from(array: [T; 3]) -> Self {
Self {
x: array[0].clone(),
y: array[1].clone(),
z: array[2].clone(),
}
}
}
impl<T> Into<[T; 3]> for Vec3<T> {
fn into(self) -> [T; 3] {
[self.x, self.y, self.z]
}
}
pub trait Dot<T> {
fn dot(me: Self, other: Self) -> T;
}
pub trait Cross<T> {
fn cross(me: Self, other: Self) -> Self;
}