Detect inside of sphere
authorLukas Jiriste <ljiriste@student.42prague.com>
Fri, 3 Jan 2025 13:13:33 +0000 (14:13 +0100)
committerLukas Jiriste <ljiriste@student.42prague.com>
Fri, 3 Jan 2025 13:13:33 +0000 (14:13 +0100)
The sphere detection only ever considered the "closer" intersection
point. This only works for ray that originate outside the sphere.

src/scene.c

index 38e2203f24a96d0054f4abef12f37e118c2b0bdd..290b404f384ca9aee7b27cd11ba06fc677069092 100644 (file)
@@ -172,19 +172,19 @@ double    get_intersection_arg_cylinder
 double get_intersection_arg_sphere(const t_ray *ray, const t_sphere *sphere)
 {
        t_vec3  start;
-       double  a;
-       double  b;
-       double  c;
-       double  det;
+       t_pair  intersection_args;
 
        start = vec_diff(ray->start, sphere->center);
-       a = vec_scalar_mul(ray->direction, ray->direction);
-       b = 2 * vec_scalar_mul(ray->direction, start);
-       c = vec_scalar_mul(start, start) - sphere->radius * sphere->radius;
-       det = b * b - 4 * a * c;
-       if (det < 0)
+       intersection_args = solve_quadratic(
+               vec_scalar_mul(ray->direction, ray->direction),
+               2 * vec_scalar_mul(ray->direction, start),
+               vec_scalar_mul(start, start) - sphere->radius * sphere->radius);
+       if (intersection_args.first > 0)
+               return (intersection_args.first);
+       else if (intersection_args.second > 0)
+               return (intersection_args.second);
+       else
                return (NAN);
-       return ((-b - sqrt(det)) / (2 * a));
 }
 
 double get_intersection_arg_bounded(const t_ray *ray, const t_object *object)