ray-trace-w1/src/vec3.rs

112 lines
2.3 KiB
Rust

use std::{fmt::Display, ops::{Add, AddAssign, Div, Mul, MulAssign, Sub}};
use std::fmt;
use crate::types_defined::Vec3;
impl Display for Vec3 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {}, {})", self.x, self.y, self.z)
}
}
impl Vec3 {
pub fn new(x: f32, y: f32, z: f32) -> Self {
Vec3 { x, y, z }
}
/// 点积运算
pub fn dot(self, other: Vec3) -> f32 {
self.x * other.x + self.y * other.y + self.z * other.z
}
/// 叉积运算
pub fn cross(self, other: Vec3) -> Vec3 {
Vec3 {
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 length_squared(self) -> f32 {
return self.x * self.x + self.y * self.y + self.z * self.z;
}
pub fn length(self) -> f32 {
return self.length_squared().sqrt();
}
}
impl Add for Vec3 {
type Output = Self;
fn add(self, other: Self) -> Self {
Vec3 { x: self.x + other.x, y: self.y + other.y, z: self.z + other.z }
}
}
// 向量减法: Vec3 - Vec3
impl Sub for Vec3 {
type Output = Self;
fn sub(self, other: Self) -> Self {
Vec3 {
x: self.x - other.x,
y: self.y - other.y,
z: self.z - other.z,
}
}
}
// 标量乘法: Vec3 * f32
impl Mul<f32> for Vec3 {
type Output = Self;
fn mul(self, scalar: f32) -> Self {
Vec3 {
x: self.x * scalar,
y: self.y * scalar,
z: self.z * scalar,
}
}
}
// 标量乘法: f32 * Vec3 (反向操作)
impl Mul<Vec3> for f32 {
type Output = Vec3;
fn mul(self, vec: Vec3) -> Vec3 {
vec * self
}
}
// 标量除法: Vec3 / f32
impl Div<f32> for Vec3 {
type Output = Self;
fn div(self, scalar: f32) -> Self {
if scalar == 0.0 {
panic!("Division by zero");
}
Vec3 {
x: self.x / scalar,
y: self.y / scalar,
z: self.z / scalar,
}
}
}
// 加法赋值: Vec3 += Vec3
impl AddAssign for Vec3 {
fn add_assign(&mut self, other: Self) {
*self = *self + other;
}
}
// 标量乘法赋值: Vec3 *= f32
impl MulAssign<f32> for Vec3 {
fn mul_assign(&mut self, scalar: f32) {
*self = *self * scalar;
}
}