use std::ops::{Add, Mul, Sub};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Vec3 {
pub x: f64,
pub y: f64,
pub z: f64,
}
impl Vec3 {
pub fn new(x: f64, y: f64, z: f64) -> Self {
Self { x, y, z }
}
pub fn from_array(array: &[f32; 3]) -> Self {
Self {
x: array[0] as f64,
y: array[1] as f64,
z: array[2] as f64,
}
}
pub fn to_array(&self) -> [f32; 3] {
return [self.x as f32, self.y as f32, self.z as f32];
}
pub fn dot(&self, other: &Self) -> f64 {
return self.x * other.x + self.y * other.y + self.z * other.z;
}
pub fn cross(&self, other: &Self) -> Self {
return Self {
x: self.y * other.z - self.z * other.y,
y: self.z * other.x - self.x * other.z,
z: self.x * other.y - self.y * other.x,
};
}
pub fn normalize(&self) -> Self {
return *self * (1.0 / self.length());
}
pub fn length_squared(&self) -> f64 {
return self.dot(self);
}
pub fn length(&self) -> f64 {
return self.length_squared().sqrt();
}
}
impl Add for Vec3 {
type Output = Self;
fn add(self, other: Self) -> Self::Output {
Self {
x: self.x + other.x,
y: self.y + other.y,
z: self.z + other.z,
}
}
}
impl Sub for Vec3 {
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
Self {
x: self.x - other.x,
y: self.y - other.y,
z: self.z - other.z,
}
}
}
impl Mul<Vec3> for f64 {
type Output = Vec3;
fn mul(self, other: Vec3) -> Self::Output {
return other * self;
}
}
impl Mul<f64> for Vec3 {
type Output = Self;
fn mul(self, scalar: f64) -> Self::Output {
Self {
x: self.x * scalar,
y: self.y * scalar,
z: self.z * scalar,
}
}
}
pub struct Vec4 {
pub x: f64,
pub y: f64,
pub z: f64,
pub w: f64,
}
impl Vec4 {
pub fn new(x: f64, y: f64, z: f64, w: f64) -> Self {
Self { x, y, z, w }
}
}
mod tests {
use super::*;
#[test]
fn test_vec3_cross_with_different_vectors() {
let a = Vec3::new(1.0, 2.0, 3.0);
let b = Vec3::new(4.0, 5.0, 6.0);
let c = a.cross(&b);
assert_eq!(c, Vec3::new(-3.0, 6.0, -3.0));
}
#[test]
fn test_vec3_cross_with_colinear_vectors() {
let a = Vec3::new(1.0, 2.0, 3.0);
let b = Vec3::new(2.0, 4.0, 6.0);
let c = a.cross(&b);
assert_eq!(c, Vec3::new(0.0, 0.0, 0.0));
}
}