#pragma once #include "matrices.h" #include "materials.h" #include "shapes.h" #include "rays.h" #include "intersections.h" inline static struct shape sphere() { return (struct shape){ mat4x4_identity(), material(), SHAPE_SPHERE, }; } inline static struct tuple sphere_normal_at(struct tuple local_point) { return tuple_sub(local_point, point(0.0f, 0.0f, 0.0f)); } inline static void sphere_intersect(struct shape const * const s, struct ray local_ray, struct intersections * intersections) { struct tuple sphere_to_ray = tuple_sub(local_ray.origin, point(0.0f, 0.0f, 0.0f)); float a = tuple_dot(local_ray.direction, local_ray.direction); float b = 2 * tuple_dot(local_ray.direction, sphere_to_ray); float c = tuple_dot(sphere_to_ray, sphere_to_ray) - 1; float discriminant = b * b - 4 * a * c; if (discriminant < 0) { return; } else { float root = sqrtf(discriminant); float t1 = (-b - root) / (2 * a); float t2 = (-b + root) / (2 * a); intersections->i[intersections->count++] = intersection(t1, s); intersections->i[intersections->count++] = intersection(t2, s); return; } }