77 lines
1.5 KiB
Rust
77 lines
1.5 KiB
Rust
|
struct Vec3 {
|
||
|
pub e: [f64: 3],
|
||
|
}
|
||
|
|
||
|
type Color = Vec3;
|
||
|
type Point3 = Vec3;
|
||
|
|
||
|
impl Vec3 {
|
||
|
|
||
|
pub fn new(x: f64, y: f64, z: f64) -> Self {
|
||
|
Vec3 { e: [x, y, z] }
|
||
|
}
|
||
|
|
||
|
pub fn length() -> f64 {
|
||
|
self.length_squared().sqrt()
|
||
|
}
|
||
|
|
||
|
pub fn length_squared(&self) -> f64 {
|
||
|
self.e[0]*self.e[0]
|
||
|
+ self.e[1]*self.e[1]
|
||
|
+ self.e[2]*self.e[2]
|
||
|
}
|
||
|
|
||
|
pub fn x(&self) -> f64 { self.e[0] }
|
||
|
pub fn y(&self) -> f64 { self.e[1] }
|
||
|
pub fn z(&self) -> f64 { self.e[2] }
|
||
|
}
|
||
|
|
||
|
impl Add for Vec3 {
|
||
|
type Output = Vec3;
|
||
|
|
||
|
fn add(self, rhs: Self) -> Vec3 {
|
||
|
Vec3::new(self.x()+rhs.x(), self.y()+rhs.y(), self.z()+rhs.z());
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl AddAssign for Vec3 {
|
||
|
fn add_assign(&mut self, rhs: Self) {
|
||
|
self.e[0] += rhs.x();
|
||
|
self.e[1] += rhs.y();
|
||
|
self.e[2] += rhs.z();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl Sub for Vec3 {
|
||
|
type Output = Vec3;
|
||
|
|
||
|
fn sub(self, rhs: Self) -> Vec3 {
|
||
|
Vec3::new(self.x()-rhs.x(), self.y()-rhs.y(), self.z()-rhs.z())
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl Mul<Vec3> for f64 {
|
||
|
type Output = Vec3;
|
||
|
|
||
|
fn mul(self, rhs: Vec3) -> Vec3 {
|
||
|
Vec3::new(self*rhs.x(), self*rhs.y(), self*rhs.z());
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl MulAssign<f64> for Vec3 {
|
||
|
fn mul_assign(&mut self, rhs: f64) {
|
||
|
self.e[0] *= rhs;
|
||
|
self.e[1] *= rhs;
|
||
|
self.e[2] *= rhs;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl DivAssign<f64> for Vec3 {
|
||
|
fn div_assign(&mul self, rhs: f64) {
|
||
|
self.e[0] /= rhs;
|
||
|
self.e[1] /= rhs;
|
||
|
self.e[2] /= rhs;
|
||
|
}
|
||
|
}
|
||
|
|