From 6037fe2802621b0d449e440bcffe3da674d24ae1 Mon Sep 17 00:00:00 2001 From: Ishan Jain Date: Tue, 2 Mar 2021 18:29:01 +0530 Subject: [PATCH] Added checkered texture --- src/demo.rs | 7 +++++-- src/materials/lambertian.rs | 5 ++++- src/texture/checker.rs | 24 ++++++++++++++++++++++++ src/texture/mod.rs | 4 +++- src/texture/solid.rs | 4 ++-- 5 files changed, 38 insertions(+), 6 deletions(-) create mode 100644 src/texture/checker.rs diff --git a/src/demo.rs b/src/demo.rs index 36c8b46..4b29897 100644 --- a/src/demo.rs +++ b/src/demo.rs @@ -1,7 +1,7 @@ use crate::{ materials::{Dielectric, Lambertian, Metal}, shapes::{MovingSphere, Sphere}, - texture::Solid, + texture::{Checker, Solid}, types::{Ray, Vec3}, BvhNode, Camera, Hitable, HORIZONTAL_PARTITION, VERTICAL_PARTITION, }; @@ -55,7 +55,10 @@ impl Demo { world.push(Arc::new(Sphere::new( Vec3::new(0.0, -1000.0, 0.0), 1000.0, - Lambertian::new(Solid::new(Vec3::new(0.5, 0.5, 0.5))), + Lambertian::new(Checker::new( + Solid::new(Vec3::new(0.2, 0.3, 0.1)), + Solid::new(Vec3::new(0.9, 0.9, 0.9)), + )), ))); let radius = 0.2; diff --git a/src/materials/lambertian.rs b/src/materials/lambertian.rs index a304011..9645e0d 100644 --- a/src/materials/lambertian.rs +++ b/src/materials/lambertian.rs @@ -21,6 +21,9 @@ impl Material for Lambertian { let scatter_direction = hit_rec.normal + random_point_in_unit_sphere(rng); let scattered_ray = Ray::new(hit_rec.p, scatter_direction, ray.time()); - (self.albedo.value(hit_rec.u, hit_rec.v), Some(scattered_ray)) + let mut p = hit_rec.p; + self.albedo.value(hit_rec.u, hit_rec.v, &mut p); + + (p, Some(scattered_ray)) } } diff --git a/src/texture/checker.rs b/src/texture/checker.rs new file mode 100644 index 0000000..2741449 --- /dev/null +++ b/src/texture/checker.rs @@ -0,0 +1,24 @@ +use crate::{types::Vec3, Texture}; + +pub struct Checker { + odd: T, + even: T, +} + +impl Checker { + pub fn new(even: T, odd: T) -> Self { + Self { odd, even } + } +} + +impl Texture for Checker { + fn value(&self, u: f64, v: f64, p: &mut Vec3) { + let sine_wave = f64::sin(10.0 * p.x()) * f64::sin(10.0 * p.y()) * f64::sin(10.0 * p.z()); + + if sine_wave < 0.0 { + self.odd.value(u, v, p) + } else { + self.even.value(u, v, p) + } + } +} diff --git a/src/texture/mod.rs b/src/texture/mod.rs index d3ded52..f3dba8e 100644 --- a/src/texture/mod.rs +++ b/src/texture/mod.rs @@ -1,9 +1,11 @@ +mod checker; mod solid; +pub use checker::Checker; pub use solid::Solid; use crate::types::Vec3; pub trait Texture { - fn value(&self, u: f64, v: f64) -> Vec3; + fn value(&self, u: f64, v: f64, p: &mut Vec3); } diff --git a/src/texture/solid.rs b/src/texture/solid.rs index 48d7438..7d8f04e 100644 --- a/src/texture/solid.rs +++ b/src/texture/solid.rs @@ -11,7 +11,7 @@ impl Solid { } impl Texture for Solid { - fn value(&self, _u: f64, _v: f64) -> Vec3 { - self.color + fn value(&self, _u: f64, _v: f64, p: &mut Vec3) { + *p = self.color } }