]> git.tdb.fi Git - libs/math.git/blob - source/geometry/halfspace.h
Implement bounding boxes with a separate class
[libs/math.git] / source / geometry / halfspace.h
1 #ifndef MSP_GEOMETRY_HALFSPACE_H_
2 #define MSP_GEOMETRY_HALFSPACE_H_
3
4 #include "boundingbox.h"
5 #include "shape.h"
6
7 namespace Msp {
8 namespace Geometry {
9
10 /**
11 An infinite shape consisting of the space on one side of a plane.  Mostly
12 useful when composited with other shapes.
13 */
14 template<typename T, unsigned D>
15 class HalfSpace: public Shape<T, D>
16 {
17 private:
18         LinAl::Vector<T, D> normal;
19
20 public:
21         HalfSpace();
22         HalfSpace(const LinAl::Vector<T, D> &);
23
24         virtual HalfSpace *clone() const;
25
26         const LinAl::Vector<T, D> &get_normal() const { return normal; }
27
28         virtual BoundingBox<T, D> get_axis_aligned_bounding_box() const;
29         virtual bool contains(const LinAl::Vector<T, D> &) const;
30         virtual unsigned get_max_ray_intersections() const { return 1; }
31         virtual unsigned get_intersections(const Ray<T, D> &, SurfacePoint<T, D> *, unsigned) const;
32 };
33
34 template<typename T, unsigned D>
35 inline HalfSpace<T, D>::HalfSpace()
36 {
37         normal[0] = 1;
38 }
39
40 template<typename T, unsigned D>
41 inline HalfSpace<T, D>::HalfSpace(const LinAl::Vector<T, D> &n):
42         normal(normalize(n))
43 { }
44
45 template<typename T, unsigned D>
46 inline HalfSpace<T, D> *HalfSpace<T, D>::clone() const
47 {
48         return new HalfSpace<T, D>(normal);
49 }
50
51 template<typename T, unsigned D>
52 inline BoundingBox<T, D> HalfSpace<T, D>::get_axis_aligned_bounding_box() const
53 {
54         // XXX If the normal is aligned to an axis, should the bounding box reflect that?
55         return ~BoundingBox<T, D>();
56 }
57
58 template<typename T, unsigned D>
59 inline bool HalfSpace<T, D>::contains(const LinAl::Vector<T, D> &point) const
60 {
61         return inner_product(point, normal)<=0;
62 }
63
64 template<typename T, unsigned D>
65 inline unsigned HalfSpace<T, D>::get_intersections(const Ray<T, D> &ray, SurfacePoint<T, D> *points, unsigned size) const
66 {
67         T x = -inner_product(ray.get_start(), normal)/inner_product(ray.get_direction(), normal);
68         if(ray.check_limits(x))
69         {
70                 if(points && size>0)
71                 {
72                         points[0].position = ray.get_start()+ray.get_direction()*x;
73                         points[0].normal = normal;
74                         points[0].distance = x;
75                 }
76
77                 return 1;
78         }
79
80         return 0;
81 }
82
83 } // namespace Geometry
84 } // namespace Msp
85
86 #endif