From 185791eddb16258d93932ee16861c6194c2ec077 Mon Sep 17 00:00:00 2001 From: Ishan Jain Date: Wed, 31 May 2023 16:53:02 +0530 Subject: [PATCH] optimize random_point_in_unit_sphere --- src/materials/mod.rs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/materials/mod.rs b/src/materials/mod.rs index 9904cd0..0d88041 100644 --- a/src/materials/mod.rs +++ b/src/materials/mod.rs @@ -58,11 +58,19 @@ fn refract(incident: Vec3, normal: Vec3, ni_over_nt: f64) -> Option { } fn random_point_in_unit_sphere(rng: &mut R) -> Vec3 { - let mut point = Vec3::random(rng) * 2.0 - Vec3::splat(1.0); - while point.sq_len() >= 1.0 { - point = Vec3::random(rng) * 2.0 - Vec3::splat(1.0); - } - point + let u: f64 = rng.gen(); + let v: f64 = rng.gen(); + + let theta = u * 2.0 * std::f64::consts::PI; + let phi = (2.0 * v - 1.0).acos(); + + let radius = rng.gen::().cbrt(); + + let x = radius * phi.sin() * theta.cos(); + let y = radius * phi.sin() * theta.sin(); + let z = radius * phi.cos(); + + Vec3::new(x, y, z) } pub trait MaterialBuilder {