/* * CS5600 University of Utah * Charles McGarvey * mcgarvey@eng.utah.edu */ #ifndef _SPHERE_HH_ #define _SPHERE_HH_ #include "color.hh" #include "element.hh" namespace rt { /* * A class for a sphere object. */ class sphere : public element { public: color_t material; vec_t origin; scal_t radius; sphere(vec_t o, scal_t r = S(1.0), color_t color = COLOR_WHITE) : origin(o), radius(r), material(color) {} virtual ~sphere() {} virtual bool intersect(ray_t ray, contact_t& hit) const { vec_t b = vec_sub(origin, ray.o); scal_t z = vec_dot(b, ray.d); // check if the sphere is behind the ray if (z < S(0.0)) { return false; } scal_t d2 = vec_dot(b, b) - z * z; scal_t r2 = radius * radius; // check for an intersection if (r2 < d2) { return false; } hit.d = z - std::sqrt(r2 - d2); if (hit.d < S(0.0)) { return false; } hit.p = ray_solve(ray, hit.d); hit.n = vec_sub(hit.p, origin); return true; } virtual color_t color(vec_t point) const { return material; } }; /* * Destroy a new'd sphere, releasing its memory. */ INLINE_MAYBE void sphere_destroy(sphere* s) { delete s; } } // namespace rt #endif // _SPHERE_HH_