From 4c851311aae6e895fe8009e2a5afb47d049be416 Mon Sep 17 00:00:00 2001 From: dengqn <434500374@qq.com> Date: Thu, 31 Jul 2025 19:18:18 +0800 Subject: [PATCH] 4.1.The ray Class --- src/main.rs | 8 +++++++- src/point.rs | 4 ++++ src/ray.rs | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 src/point.rs create mode 100644 src/ray.rs diff --git a/src/main.rs b/src/main.rs index 7f010b4..52f7674 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,10 +1,14 @@ use write_file_util::{write_image}; use image::{gen_gradient_ppm_p3, Color}; use vec3::{Vec3}; +use point::{Point}; +use ray::{Ray}; mod image; mod write_file_util; mod vec3; +mod point; +mod ray; fn main() { let ppm_content = gen_gradient_ppm_p3(400, 225); @@ -16,8 +20,10 @@ fn main() { println!("v: {:#} + {:#} => {:#}", v1, v2, v1 - v2); println!("v: {:#} + {:#} => {:#}", v1, v2, v1.dot(v2)); println!("v: {:#} + {:#} => {:#}", v1, v2, v1.cross(v2)); - println!("color: {:#}", Color::new(0.3, 0.4, 1.0).to_color()); + println!("point: {:#}", Point::new(1.0, 1.0, 1.0)); + let ray = Ray::new(Point::new(1.0, 1.0, 1.0), Vec3 { x: 0.0, y: 1.0, z: 0.0 }); + println!("Ray: {:#} => {:#}", ray, ray.at(2.0)); write_image(ppm_content, "./target/test.ppm".to_string()) } diff --git a/src/point.rs b/src/point.rs new file mode 100644 index 0000000..c3e4956 --- /dev/null +++ b/src/point.rs @@ -0,0 +1,4 @@ +use crate::vec3; + +pub type Point = vec3::Vec3; + diff --git a/src/ray.rs b/src/ray.rs new file mode 100644 index 0000000..f187f2e --- /dev/null +++ b/src/ray.rs @@ -0,0 +1,35 @@ +use std::fmt; +use std::fmt::{Display}; + +use crate::{point::Point, vec3::Vec3}; + + +/* +fn: P(t) = t*b +*/ +#[derive(Debug)] +pub struct Ray { + point: Point, + direction: Vec3 +} + +impl Ray { + pub fn new(p: Point, direction: Vec3) -> Ray { + Ray { point: p, direction: direction } + } + + pub fn at(&self, t: f32) -> Point { + Point { + x: self.point.x + t * self.direction.x, + y: self.point.y + t * self.direction.y, + z: self.point.z + t * self.direction.z, + } + } +} + + +impl Display for Ray { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "O{}x{}", self.point, self.direction) + } +} \ No newline at end of file