aboutsummaryrefslogtreecommitdiffstats
path: root/src/sphere.cpp
diff options
context:
space:
mode:
authorladevieq <ladevie.quentin@gmail.com>2020-12-20 21:59:33 +0100
committerladevieq <ladevie.quentin@gmail.com>2020-12-20 21:59:33 +0100
commitc7c4f8f82c66cfe89b72d176ee51dab8bd30dc95 (patch)
treed0c2caeccda953d86806cb7c7b27c8941e0ef845 /src/sphere.cpp
parentfc601fd503ec1ebd08e4daffeb9aa0812aff2b71 (diff)
Add hittable interface and hit infos on hit
Diffstat (limited to 'src/sphere.cpp')
-rw-r--r--src/sphere.cpp37
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;
+}