diff options
Diffstat (limited to 'src/sphere.cpp')
| -rw-r--r-- | src/sphere.cpp | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/src/sphere.cpp b/src/sphere.cpp new file mode 100644 index 0000000..31915a2 --- /dev/null +++ b/src/sphere.cpp @@ -0,0 +1,37 @@ +#include "sphere.hpp" + +sphere::sphere(point3 center, double radius) : center(center), radius(radius) +{} + +bool sphere::hit(const ray& r, double t_min, double t_max, struct hit_info& info) const { + // Vector from the ray origin to sphere position + vec3 origin_center = r.origin - center; + + double a = r.direction.dot(r.direction); + double half_b = r.direction.dot(origin_center); + double c = origin_center.dot(origin_center) - radius * radius; + double discriminant = half_b * half_b - a * c; + + if (discriminant < 0) { + return false; + } + + double sq_discriminant = sqrt(discriminant); + double t = (-half_b - sq_discriminant) / a ; + + if (t_min > t || t_max < t) { + t = (-half_b + sq_discriminant) / a ; + + if (t_min > t || t_max < t) { + return false; + } + } + + info.t = t; + info.point = r.at(t); + + vec3 out_normal = (info.point - center).unit(); + info.set_face_normal(r, out_normal); + + return true; +} |
