use rand::prelude::*; use crate::color::Color; use crate::hit::HitRecord; use crate::ray::Ray; use crate::vec::{Point3, Vec3, dot, unit_vector}; use enum_dispatch::enum_dispatch; #[enum_dispatch] pub trait Material: Send + Sync { fn scatter(&self, ray: &Ray, hit_record: &HitRecord, rng: &mut ThreadRng) -> Scatter; } #[enum_dispatch(Material)] pub enum MaterialEnum { Lambertian, Metal, Dielectric, } pub struct Scatter { pub attenuation: Color, pub scattered: Ray, } pub struct Lambertian { albedo: Color, } impl Lambertian { pub fn new(albedo: Color) -> Self { Self { albedo } } } impl Material for Lambertian { fn scatter(&self, _ray: &Ray, hit_record: &HitRecord, rng: &mut ThreadRng) -> Scatter { let mut scatter_direction = hit_record.normal + Vec3::random_unit(rng); if scatter_direction.near_zero() { scatter_direction = hit_record.normal; } Scatter { attenuation: self.albedo, scattered: Ray::new(hit_record.point, scatter_direction), } } } pub struct Metal { albedo: Color, fuzz: f64, } impl Metal { pub fn new(albedo: Color, fuzz: f64) -> Self { Self { albedo, fuzz } } } impl Material for Metal { fn scatter(&self, ray: &Ray, hit_record: &HitRecord, rng: &mut ThreadRng) -> Scatter { let reflected = Vec3::reflect(ray.direction, hit_record.normal); let reflected = unit_vector(reflected) + (self.fuzz * Vec3::random_unit(rng)); let scattered = Ray::new(hit_record.point, reflected); Scatter { attenuation: self.albedo, scattered, } } } pub struct Dielectric { refraction_index: f64, } impl Dielectric { pub fn new(refraction_index: f64) -> Self { Self { refraction_index } } /// Use Schlick's approximation for reflectance. fn reflectance(cosine: f64, refraction_index: f64) -> f64 { let r0 = (1.0 - refraction_index) / (1.0 + refraction_index); let r0 = r0 * r0; r0 + (1.0 - r0) * (1.0 - cosine).powf(5.0) } } impl Material for Dielectric { fn scatter(&self, ray: &Ray, hit_record: &HitRecord, rng: &mut ThreadRng) -> Scatter { let attenuation = Color::new(1.0, 1.0, 1.0); let refraction_index = if hit_record.front_face { 1.0 / self.refraction_index } else { self.refraction_index }; let unit_direction = unit_vector(ray.direction); let cos_theta = dot(-unit_direction, hit_record.normal).min(1.0); let sin_theta = (1.0 - cos_theta * cos_theta).sqrt(); let direction = if refraction_index * sin_theta > 1.0 || Self::reflectance(cos_theta, refraction_index) > rng.random_range(0.0..1.0) { Vec3::reflect(unit_direction, hit_record.normal) } else { Vec3::refract(unit_direction, hit_record.normal, refraction_index) }; let scattered = Ray::new(hit_record.point, direction); Scatter { attenuation, scattered, } } }