From 3aea707982c72982cd99b12b5f0668bbd27c37fd Mon Sep 17 00:00:00 2001 From: David Date: Fri, 20 Aug 2021 23:43:44 +0200 Subject: [PATCH] Small optimization on sphere --- main.cpp | 11 ++++++----- vec3.hpp | 8 +++++++- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/main.cpp b/main.cpp index ea83b32..3f69801 100644 --- a/main.cpp +++ b/main.cpp @@ -25,14 +25,15 @@ color ray_color(const ray& r) double hit_sphere(const point3& center, double radius, const ray& r) { vec3 oc = r.origin - center; - double a = dot(r.direction, r.direction); - double b = 2.0 * dot(oc, r.direction); - double c = dot(oc,oc) - radius*radius; - double discriminant = b*b - 4*a*c; + double a = r.direction.length_squared(); + double half_b = dot(oc, r.direction); + double c = oc.length_squared() - radius*radius; + double discriminant = half_b*half_b - a*c; + if (discriminant < 0) return -1; else - return (-b - sqrt(discriminant)) / (2.0*a); + return (-half_b - sqrt(discriminant)) / a; } int main() diff --git a/vec3.hpp b/vec3.hpp index 81b9450..a841b0d 100644 --- a/vec3.hpp +++ b/vec3.hpp @@ -58,7 +58,13 @@ struct vec3 { double length() const { return sqrt(x*x + y*y + z*z); - } + } + + // Length squared, useful for some calculations + double length_squared() const + { + return x*x + y*y + z*z; + } }; /* Type aliases */