From c4369f86c920888bfaa00e46d74e3f5a1872a9ab Mon Sep 17 00:00:00 2001 From: Julian T Date: Sun, 31 Jan 2021 17:21:11 +0100 Subject: Add Scene type and Sphere intersect --- src/core/ray.rs | 5 +++-- src/core/vector3.rs | 45 +++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 44 insertions(+), 6 deletions(-) (limited to 'src/core') diff --git a/src/core/ray.rs b/src/core/ray.rs index 7d73b93..54af639 100644 --- a/src/core/ray.rs +++ b/src/core/ray.rs @@ -1,6 +1,7 @@ use crate::core::Vector3f; pub struct Ray { - origin: Vector3f, - direction: Vector3f, + pub origin: Vector3f, + pub direction: Vector3f, } + diff --git a/src/core/vector3.rs b/src/core/vector3.rs index da09ceb..e3aa9a6 100644 --- a/src/core/vector3.rs +++ b/src/core/vector3.rs @@ -1,5 +1,5 @@ use crate::{Float, Number}; -use std::ops::{Sub, Add}; +use std::ops::{Sub, Add, DivAssign}; #[derive(Clone, Copy)] pub struct Vector3 { @@ -19,7 +19,7 @@ impl Vector3 { } } - pub fn new_xy(x: T, y: T, z: T) -> Vector3 { + pub fn new_xyz(x: T, y: T, z: T) -> Vector3 { Vector3 { x, y, z} } } @@ -27,7 +27,7 @@ impl Vector3 { impl Sub for Vector3 { type Output = Self; fn sub(self, op: Self) -> Self::Output { - Self::new_xy( + Self::new_xyz( self.x - op.x, self.y - op.y, self.z - op.z, @@ -38,10 +38,47 @@ impl Sub for Vector3 { impl Add for Vector3 { type Output = Self; fn add(self, op: Self) -> Self::Output { - Self::new_xy( + Self::new_xyz( self.x + op.x, self.y + op.y, self.z + op.z, ) } } + +impl DivAssign for Vector3 { + fn div_assign(&mut self, op: T) { + self.x /= op; + self.y /= op; + self.z /= op; + } +} + +impl Vector3f { + pub fn len_squared(&self) -> Float { + self.x * self.x + self.y * self.y + self.z * self.z + } + + pub fn len(&self) -> Float { + self.len_squared().sqrt() + } + + pub fn dot(&self, op: &Self) -> Float { + self.x * op.x + self.y * op.y + self.z * op.z + } + + pub fn norm_in(&mut self) { + let len = self.len(); + if len == 0.0 { + *self = Self::new(0.0); + } + + *self /= len; + } + + pub fn norm(&self) -> Self { + let mut new = self.clone(); + new.norm_in(); + new + } +} -- cgit v1.2.3