39 lines
812 B
Rust
39 lines
812 B
Rust
#[derive(Debug, Clone, Copy)]
|
|
pub struct Vec3 {
|
|
pub x: f32,
|
|
pub y: f32,
|
|
pub z: f32,
|
|
}
|
|
|
|
impl Vec3 {
|
|
pub fn new(x: f32, y: f32, z: f32) -> Self {
|
|
Vec3 { x, y, z }
|
|
}
|
|
|
|
pub fn squared_length(&self) -> f32 {
|
|
self.x * self.x + self.y * self.y + self.z * self.z
|
|
}
|
|
|
|
pub fn length(&self) -> f32 {
|
|
self.squared_length().sqrt()
|
|
}
|
|
|
|
pub fn normalize(&self) -> Vec3 {
|
|
let len = self.length();
|
|
if len != 0.0 {
|
|
Vec3 {
|
|
x: self.x / len,
|
|
y: self.y / len,
|
|
z: self.z / len,
|
|
}
|
|
} else {
|
|
// Return zero vector if length is zero to avoid NaNs
|
|
Vec3 {
|
|
x: 0.0,
|
|
y: 0.0,
|
|
z: 0.0,
|
|
}
|
|
}
|
|
}
|
|
}
|