From f39ff66c94f0791ad32fc97cd9cf7b0dde275ad3 Mon Sep 17 00:00:00 2001 From: Nigel Date: Sat, 4 Mar 2023 19:15:27 +0100 Subject: [PATCH] Simple sphere with normals --- src/program.cpp | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/program.cpp b/src/program.cpp index 263130f..8db45fb 100644 --- a/src/program.cpp +++ b/src/program.cpp @@ -4,9 +4,27 @@ #include +double hit_sphere (const point3& center, double radius, const ray& r) { + vec3 oc = r.origin() - center; + auto a = dot(r.direction(), r.direction()); + auto b = 2.0 * dot(oc, r.direction()); + auto c = dot(oc, oc) - radius*radius; + auto discriminant = b*b - 4*a*c; + if ( discriminant < 0) { + return -1.0; + }else{ + return (-b - sqrt(discriminant) ) / (2.0*a); + } +} + color ray_color(const ray& r){ + auto t = hit_sphere(point3(0,0,-1), 0.5, r); + if(t > 0.0){ + vec3 N = unit_vector(r.at(t) - vec3(0,0,-1)); + return 0.5*color(N.x()+1, N.y()+1, N.z()+1); + } vec3 unit_direction = unit_vector(r.direction()); - auto t = 0.5*(unit_direction.y() + 1.0); + t = 0.5*(unit_direction.y() + 1.0); return (1.0-t)*color(1.0, 1.0, 1.0) + t*color(0.5,0.7,1.0); }