1 #ifndef MSP_GEOMETRY_HYPERSPHERE_H_
2 #define MSP_GEOMETRY_HYPERSPHERE_H_
6 #include <msp/linal/vector.h>
10 #include "surfacepoint.h"
16 A shape consisting of the points within a specific distance from the origin.
17 Two- and three-dimensional cases are Circle and Sphere, respectively.
19 template<typename T, unsigned D>
20 class HyperSphere: public Shape<T, D>
26 HyperSphere(): radius(1) { }
27 explicit HyperSphere(T);
29 virtual HyperSphere *clone() const;
31 T get_radius() const { return radius; }
33 virtual HyperBox<T, D> get_axis_aligned_bounding_box() const;
34 virtual bool contains(const LinAl::Vector<T, D> &) const;
35 virtual bool check_intersection(const Ray<T, D> &) const;
36 virtual unsigned get_max_ray_intersections() const { return 2; }
37 virtual unsigned get_intersections(const Ray<T, D> &, SurfacePoint<T, D> *, unsigned) const;
40 template<typename T, unsigned D>
41 inline HyperSphere<T, D>::HyperSphere(T r):
45 throw std::invalid_argument("HyperSphere::HyperShpere");
48 template<typename T, unsigned D>
49 inline HyperSphere<T, D> *HyperSphere<T, D>::clone() const
51 return new HyperSphere<T, D>(radius);
54 template<typename T, unsigned D>
55 inline HyperBox<T, D> HyperSphere<T, D>::get_axis_aligned_bounding_box() const
57 LinAl::Vector<T, D> dimensions;
58 for(unsigned i=0; i<D; ++i)
59 dimensions[i] = radius;
60 return HyperBox<T, D>(dimensions);
63 template<typename T, unsigned D>
64 inline bool HyperSphere<T, D>::contains(const LinAl::Vector<T, D> &point) const
66 return inner_product(point, point)<=radius*radius;
69 template<typename T, unsigned D>
70 inline bool HyperSphere<T, D>::check_intersection(const Ray<T, D> &ray) const
72 T x = inner_product(ray.get_direction(), ray.get_start());
74 return contains(ray.get_start());
76 return contains(ray.get_start()-ray.get_direction()*x);
79 template<typename T, unsigned D>
80 inline unsigned HyperSphere<T, D>::get_intersections(const Ray<T, D> &ray, SurfacePoint<T, D> *points, unsigned size) const
84 T mid = -inner_product(ray.get_direction(), ray.get_start());
85 LinAl::Vector<T, D> nearest = ray.get_start()+ray.get_direction()*mid;
86 T offset_sq = radius*radius-inner_product(nearest, nearest);
89 T offset = sqrt(offset_sq);
92 for(int i=-1; i<=1; i+=2)
95 if(ray.check_limits(x) && n<size)
99 points[n].position = ray.get_start()+ray.get_direction()*x;
100 points[n].normal = normalize(points[n].position);
101 points[n].distance = x;
113 } // namespace Geometry