4.1.The ray Class

This commit is contained in:
dengqn 2025-07-31 19:18:18 +08:00
parent 0c7ef49a35
commit 4c851311aa
3 changed files with 46 additions and 1 deletions

View File

@ -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())
}

4
src/point.rs Normal file
View File

@ -0,0 +1,4 @@
use crate::vec3;
pub type Point = vec3::Vec3;

35
src/ray.rs Normal file
View File

@ -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)
}
}