source: GTP/trunk/Lib/Vis/Preprocessing/src/AxisAlignedBox3.h @ 2691

Revision 2691, 18.5 KB checked in by mattausch, 16 years ago (diff)

fixed several errors

Line 
1#ifndef _AxisAlignedBox3_H__
2#define _AxisAlignedBox3_H__
3
4#include "Rectangle3.h"
5#include "Matrix4x4.h"
6#include "Vector3.h"
7#include "Plane3.h"
8#include "Containers.h"
9
10namespace GtpVisibilityPreprocessor {
11
12class Ray;
13class Polygon3;
14class Mesh;
15class VssRay;
16struct Triangle3;
17
18/**
19        CAABox class.
20        This is a box in 3-space, defined by min and max
21        corner vectors.  Many useful operations are defined
22        on this
23*/
24class AxisAlignedBox3
25{
26protected:
27        Vector3 mMin, mMax;
28public:
29  // Constructors.
30  AxisAlignedBox3() { }
31 
32  AxisAlignedBox3(const Vector3 &nMin, const Vector3 &nMax)
33  {
34    mMin = nMin; mMax = nMax;
35  }
36
37  /** initialization to the non existing bounding box
38  */
39  void Initialize();
40
41  /** The center of the box
42  */
43  Vector3 Center() const;
44 
45  /** The diagonal of the box
46  */
47  Vector3 Diagonal() const;
48
49  float Center(const int axis) const;
50
51  float Min(const int axis) const;
52
53  float Max(const int axis) const;
54
55  float Size(const int axis) const;
56
57  // Read-only const access tomMin and max vectors using references
58  const Vector3& Min() const;
59  const Vector3& Max() const;
60
61  void Enlarge (const Vector3 &v);
62
63  void EnlargeToMinSize();
64 
65  void SetMin(const Vector3 &v);
66
67  void SetMax(const Vector3 &v);
68
69  void SetMin(int axis, const float value);
70
71  void SetMax(int axis, const float value);
72
73  // Decrease box by given splitting plane
74  void Reduce(int axis, int right, float value);
75 
76  bool Intersects(const Vector3 &lStart, const Vector3 &lEnd) const;
77
78  // the size of the box along all the axes
79  Vector3 Size() const;
80  float Radius() const { return 0.5f*Magnitude(Size()); }
81  float SqrRadius() const { return 0.5f*SqrMagnitude(Size()); }
82 
83  /** Clamps the point to the box.
84  */
85  void ClampToBox(Vector3 &pt) const;
86
87  // Return whether the box is unbounded.  Unbounded boxes appear
88  // when unbounded objects such as quadric surfaces are included.
89  bool Unbounded() const;
90
91  // Expand the axis-aligned box to include the given object.
92  void Include(const Vector3 &newpt);
93  void Include(const Polygon3 &newpoly);
94  void Include(const AxisAlignedBox3 &bbox);
95  void Include (const PolygonContainer &polys);
96  void Include(Mesh *mesh);
97
98  /** Expand the axis-aligned box to include given values in particular axis.
99  */
100  void Include(const int &axis, const float &newBound);
101
102  int Side(const Plane3 &plane) const;
103
104  // Overlap returns 1 if the two axis-aligned boxes overlap .. even weakly
105  friend inline bool Overlap(const AxisAlignedBox3 &, const AxisAlignedBox3 &);
106
107  // Overlap returns 1 if the two axis-aligned boxes overlap .. only strongly
108  friend inline bool OverlapS(const AxisAlignedBox3 &,const AxisAlignedBox3 &);
109
110  /** Overlap returns 1 if the two axis-aligned boxes overlap for a given
111          epsilon. If eps > 0.0, then the boxes has to have the real intersection
112          box, if eps < 0.0, then the boxes need not intersect really, they
113          can be at eps distance in the projection.
114          */
115  friend inline bool Overlap(const AxisAlignedBox3 &,
116                                                         const AxisAlignedBox3 &,
117                                                         float eps);
118
119  /** Returns 'factor' of overlap of first box with the second box. i.e., a number
120        between 0 (no overlap) and 1 (same box).
121  */
122  friend inline float RatioOfOverlap(const AxisAlignedBox3 &, const AxisAlignedBox3 &);
123
124  /** Includes returns true if a includes b (completely)
125  */
126  bool Includes(const AxisAlignedBox3 &b) const;
127
128  /** Returns true if this point is inside box.
129  */
130  virtual int IsInside(const Vector3 &v) const;
131 
132  /** Returns true if start and endpoint of the ray is inside box.
133  */
134  virtual int IsInside(const VssRay &v) const;
135
136  /** Test if the box makes sense.
137  */
138  virtual bool IsCorrect();
139
140  /** To answer true requires the box of real volume of non-zero value.
141  */
142  bool IsSingularOrIncorrect() const;
143
144  /** When the box is not of non-zero or negative surface area.
145  */
146  bool IsCorrectAndNotPoint() const;
147
148  /** Returns true when the box degenerates to a point.
149  */
150  bool IsPoint() const;
151
152  /** Scales the box with the factor.
153  */
154  void Scale(const float scale);
155
156  void Scale(const Vector3 &scale);
157       
158  /** Translates the box with the factor.
159  */
160  void Translate(const Vector3 &shift);
161
162  /** Returns the square of the minimal and maximal distance to
163        a point on the box.
164        */
165  void
166  GetSqrDistances(const Vector3 &point,
167                  float &minDistance,
168                  float &maxDistance
169                  ) const;
170
171  // returns true, when the sphere specified by the origin and radius
172  // fully contains the box
173  bool IsFullyContainedInSphere(const Vector3 &center, float radius) const;
174
175  // returns true, when the volume of the sphere and volume of the
176  // axis aligned box has no intersection
177  bool HasNoIntersectionWithSphere(const Vector3 &center,
178                                   float radius) const;
179
180
181  // Given a sphere described by the center and radius,
182  // the fullowing function returns:
183  //   -1 ... the sphere and the box are completely separate
184  //    0 ... the sphere and the box only partially overlap
185  //    1 ... the sphere contains fully the box
186  //  Note: the case when box fully contains the sphere is not reported
187  //        since it was not required.
188  int MutualPositionWithSphere(const Vector3 &center, float radius) const;
189
190  // Given a cube described by the center and half-size (radius),
191  // the following function returns:
192  //   -1 ... the cube and the box are completely separate
193  //    0 ... the cube and the box only partially overlap
194  //    1 ... the cube contains fully the box
195  int MutualPositionWithCube(const Vector3 &center, float halfSize) const;
196
197
198  Vector3 GetRandomPoint(const Vector3 &r) const;
199  Vector3 GetRandomPoint() const;
200  Vector3 GetRandomSurfacePoint() const;
201  Vector3 GetUniformRandomSurfacePoint() const;
202
203  void GetRandomEdgePoint(Vector3 &point, Vector3 &normal);
204
205  Vector3 GetPoint(const Vector3 &p) const {
206    return mMin + p*Size();
207  }
208
209  // Returns the smallest axis-aligned box that includes all points
210  // inside the two given boxes.
211  friend inline AxisAlignedBox3 Union(const AxisAlignedBox3 &x,
212                             const AxisAlignedBox3 &y);
213
214  // Returns the intersection of two axis-aligned boxes.
215  friend inline AxisAlignedBox3 Intersect(const AxisAlignedBox3 &x,
216                                                                                  const AxisAlignedBox3 &y);
217
218  // Given 4x4 matrix, transform the current box to new one.
219  friend inline AxisAlignedBox3 Transform(const AxisAlignedBox3 &box,
220                                                                                  const Matrix4x4 &tform);
221
222 
223  // returns true when two boxes are completely equal
224  friend inline int operator== (const AxisAlignedBox3 &A,
225                                                                const AxisAlignedBox3 &B);
226 
227  virtual float SurfaceArea() const;
228  virtual float GetVolume() const
229  {
230          return (mMax.x - mMin.x) * (mMax.y - mMin.y) * (mMax.z - mMin.z);
231  }
232
233  // Six faces are distuinguished by their name.
234  enum EFaces {ID_Back = 0,
235                           ID_Left = 1,
236                           ID_Bottom = 2,
237                           ID_Front = 3,
238                           ID_Right = 4,
239                           ID_Top = 5};
240 
241  int  ComputeMinMaxT(const Vector3 &origin,
242                      const Vector3 &direction,
243                      float *tmin,
244                      float *tmax) const;
245       
246  // Compute tmin and tmax for a ray, whenever required .. need not pierce box
247  int ComputeMinMaxT(const Ray &ray, float *tmin, float *tmax) const;
248
249  // Compute tmin and tmax for a ray, whenever required .. need not pierce box
250  int ComputeMinMaxT(const Ray &ray,
251                     float *tmin,
252                     float *tmax,
253                     EFaces &entryFace,
254                     EFaces &exitFace) const;
255 
256  // If a ray pierces the box .. returns 1, otherwise 0.
257  // Computes the signed distances for case: tmin < tmax and tmax > 0
258  int GetMinMaxT(const Ray &ray, float *tmin, float *tmax) const;
259  // computes the signed distances for case: tmin < tmax and tmax > 0
260  int GetMinMaxT(const Ray &ray, float *tmin, float *tmax,
261                 EFaces &entryFace, EFaces &exitFace) const;
262 
263  // Writes a brief description of the object, indenting by the given
264  // number of spaces first.
265  virtual void Describe(std::ostream& app, int ind) const;
266
267  // For edge .. number <0..11> returns two incident vertices
268  void GetEdge(const int edge, Vector3 *a, Vector3 *b) const;
269
270  // Compute the coordinates of one vertex of the box for 0/1 in each axis
271  // 0 .. smaller coordinates, 1 .. large coordinates
272  Vector3 GetVertex(int xAxis, int yAxis, int zAxis) const;
273
274  // Compute the vertex for number N=<0..7>, N = 4*x + 2*y + z, where
275  // x,y,z are either 0 or 1; (0 .. lower coordinate, 1 .. large coordinate)
276  // (xmin,ymin, zmin) .. N = 0, (xmax, ymax, zmax) .. N= 7
277  void GetVertex(const int N, Vector3 &vertex) const;
278
279  Vector3 GetVertex(const int N) const {
280    Vector3 v;
281    GetVertex(N, v);
282    return v;
283  }
284
285  // Returns 1, if the box includes on arbitrary face a given box
286  int IsPiercedByBox(const AxisAlignedBox3 &box, int &axis) const;
287
288
289  int GetFaceVisibilityMask(const Vector3 &position) const;
290  int GetFaceVisibilityMask(const Rectangle3 &rectangle) const;
291
292  Rectangle3 GetFace(const int face) const;
293 
294  /** Extracts plane of bounding box.
295  */
296  Plane3 GetPlane(const int face) const;
297 
298  // For a given point returns the region, where the point is located
299  // there are 27 regions (0..26) .. determined by the planes embedding in the
300  // sides of the bounding box (0 .. lower the position of the box,
301  // 1 .. inside the box, 2 .. greater than box). The region number is given as
302  // R = 9*x + 3*y + z  ; e.g. region .. inside the box is 13.
303  int GetRegionID(const Vector3 &point) const;
304 
305  // Set the corner point of rectangle on the face of bounding box
306  // given by the index number and the rectangle lying on this face
307  //  void GetFaceRectCorner(const CRectLeaf2D *rect, EFaces faceIndx,
308  //                     const int &cornerIndx, Vector3 &cornerPoint);
309
310  // Project the box to a plane given a normal vector of this plane. Computes
311  // the surface area of projected silhouettes for parallel projection.
312  float ProjectToPlaneSA(const Vector3 &normal) const;
313
314  // Computes projected surface area of the box to a given viewing plane
315  // given a viewpoint. This corresponds the probability, the box will
316  // be hit by the ray .. moreover returns .. the region number (0-26).
317  // the function supposes all the points lie of the box lies in the viewing
318  // frustrum !!! The positive halfspace of viewplane has to contain
319  // viewpoint. "projectionType" == 0 .. perspective projection,
320  // == 1 .. parallel projection.
321  float ProjectToPlaneSA(const Plane3 &viewplane,
322                         const Vector3 &viewpoint,
323                         int *tcase,
324                         const float &maxSA,
325                         int projectionType) const;
326
327  // Computes projected surface area of the box to a given viewing plane
328  // and viewpoint. It clipps the area by all the planes given .. they should
329  // define the viewing frustrum. Variable tclip defines, which planes are
330  // used for clipping, parameter 31 is the most general, clip all the plane.
331  // 1 .. clip left, 2 .. clip top, 4 .. clip right, 8 .. clip bottom,
332  // 16 .. clip supporting plane(its normal towards the viewing frustrum).
333  // "typeProjection" == 0 .. perspective projection,
334  // == 1 .. parallel projection
335  float ProjectToPlaneSA(const Plane3 &viewplane,
336                         const Vector3 &viewpoint,
337                         int *tcase, int &tclip,
338                         const Plane3 &leftPlane,
339                         const Plane3 &topPlane,
340                         const Plane3 &rightPlane,
341                         const Plane3 &bottomPlane,
342                         const Plane3 &suppPlane,
343                         const float &maxSA,
344                         int typeProjection) const;
345
346  // Projects the box to a unit sphere enclosing a given viewpoint and
347  // returns the solid angle of the box projected to a unit sphere
348  float ProjectToSphereSA(const Vector3 &viewpoint, int *tcase) const;
349
350  /** Returns vertex indices of edge.
351  */
352  void GetEdge(const int edge, int  &aIdx, int &bIdx) const;
353
354  /** Computes cross section of plane with box (i.e., bounds box).
355          @returns the cross section
356  */
357  Polygon3 *CrossSection(const Plane3 &plane) const;
358
359  /** Computes minimal and maximal t of ray, including the object intersections.
360          @returns true if ray hits the bounding box.
361  */
362  bool GetRaySegment(const Ray &ray, float &minT, float &maxT) const;
363
364  /** If the boxes are intersecting on a common face, this function
365          returns the face intersection, false otherwise.
366   
367          @param neighbour the neighbouring box intersecting with this box.
368  */
369  bool GetIntersectionFace(Rectangle3 &face,
370                                                   const AxisAlignedBox3 &neighbour) const;
371
372  /** Includes the box faces to the mesh description
373  */
374  friend void IncludeBoxInMesh(const AxisAlignedBox3 &box, Mesh &mesh);
375
376  /** Box faces are turned into polygons.
377  */
378  void ExtractPolys(PolygonContainer &polys) const;
379
380  /** Returns true if the mesh intersects the bounding box.
381  */
382  bool Intersects(const Mesh &mesh) const;
383   /** Returns true if the triangle intersects the bounding box.
384  */
385  bool Intersects(const Triangle3 &tri) const;
386  /** Splits the box into two separate boxes with respect to the split plane
387  */
388  void Split(const int axis,
389                         const float value,
390                         AxisAlignedBox3 &left,
391                         AxisAlignedBox3 &right) const;
392
393#define __EXTENT_HACK
394  // get the extent of face
395  float GetExtent(const int &face) const {
396#if defined(__EXTENT_HACK) && defined(__VECTOR_HACK)
397    return mMin[face];
398#else
399    if (face < 3)
400      return mMin[face];
401    else
402      return mMax[face-3];
403#endif
404  }
405
406  // The vertices that form boundaries of the projected bounding box
407  // for all the regions possible, number of regions is 3^3 = 27,
408  // since two parallel sides of bbox forms three disjoint spaces
409  // the vertices are given in anti-clockwise order .. stopped by -1 elem.
410  static const int bvertices[27][9];
411
412  // The list of all faces visible from a given region (except region 13)
413  // the faces are identified by triple: (axis, min-vertex, max-vertex),
414  // that is maximaly three triples are defined. axis = 0 (x-axis),
415  // axis = 1 (y-axis), axis = 2 (z-axis), -1 .. terminator. Is is always
416  // true that: min-vertex < max-vertex for all coordinates excluding axis
417  static const int bfaces[27][10];
418 
419  // The correct corners indexed starting from entry face to exit face
420  // first index determines entry face, second index exit face, and
421  // the two numbers (indx, inc) determines: ind = the index on the exit
422  // face, when starting from the vertex 0 on entry face, 'inc' is
423  // the increment when we go on entry face in order 0,1,2,3 to create
424  // convex shaft with the rectangle on exit face. That is, inc = -1 or 1.
425  static const int pairFaceRects[6][6][2];
426
427  // The vertices that form CLOSEST points with respect to the region
428  // for all the regions possible, number of regions is 3^3 = 27,
429  // since two parallel sides of bbox forms three disjoint spaces.
430  // The vertices are given in anti-clockwise order, stopped by -1 elem,
431  // at most 8 points, at least 1 point.
432  static const int cvertices[27][9];
433  static const int csvertices[27][6];
434
435  // The vertices that form FARTHEST points with respect to the region
436  // for all the regions possible, number of regions is 3^3 = 27,
437  // since two parallel sides of bbox forms three disjoint spaces.
438  // The vertices are given in anti-clockwise order, stopped by -1 elem,
439  // at most 8 points, at least 1 point.
440  static const int fvertices[27][9]; 
441  static const int fsvertices[27][9];
442
443  // input and output operator with stream
444  friend std::ostream& operator<<(std::ostream &s, const AxisAlignedBox3 &A);
445  friend std::istream& operator>>(std::istream &s, AxisAlignedBox3 &A);
446
447protected:
448  // definition of friend functions
449  friend class Ray;
450};
451
452// --------------------------------------------------------------------------
453// Implementation of inline (member) functions
454 
455inline bool
456Overlap(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y)
457{
458  if (x.mMax.x < y.mMin.x ||
459      x.mMin.x > y.mMax.x ||
460      x.mMax.y < y.mMin.y ||
461      x.mMin.y > y.mMax.y ||
462      x.mMax.z < y.mMin.z ||
463      x.mMin.z > y.mMax.z) {
464    return false;
465  }
466  return true;
467}
468
469inline bool
470OverlapS(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y)
471{
472  if (x.mMax.x <= y.mMin.x ||
473      x.mMin.x >= y.mMax.x ||
474      x.mMax.y <= y.mMin.y ||
475      x.mMin.y >= y.mMax.y ||
476      x.mMax.z <= y.mMin.z ||
477      x.mMin.z >= y.mMax.z) {
478    return false;
479  }
480  return true;
481}
482
483inline bool
484Overlap(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y, float eps)
485{
486  if ( (x.mMax.x - eps) < y.mMin.x ||
487       (x.mMin.x + eps) > y.mMax.x ||
488       (x.mMax.y - eps) < y.mMin.y ||
489       (x.mMin.y + eps) > y.mMax.y ||
490       (x.mMax.z - eps) < y.mMin.z ||
491       (x.mMin.z + eps) > y.mMax.z ) {
492    return false;
493  }
494  return true;
495}
496
497inline AxisAlignedBox3
498Intersect(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y)
499{
500  if (x.Unbounded())
501    return y;
502  else
503    if (y.Unbounded())
504      return x;
505  AxisAlignedBox3 ret = x;
506  if (Overlap(ret, y)) {
507    Maximize(ret.mMin, y.mMin);
508    Minimize(ret.mMax, y.mMax);
509    return ret;
510  }
511  else      // Null intersection.
512    return AxisAlignedBox3(Vector3(0), Vector3(0));
513  // return AxisAlignedBox3(Vector3(0), Vector3(-1));
514}
515
516inline AxisAlignedBox3
517Union(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y)
518{
519  Vector3 min = x.mMin;
520  Vector3 max = x.mMax;
521  Minimize(min, y.mMin);
522  Maximize(max, y.mMax);
523  return AxisAlignedBox3(min, max);
524}
525
526inline AxisAlignedBox3
527Transform(const AxisAlignedBox3 &box, const Matrix4x4 &tform)
528{
529  Vector3 mmin(MAXFLOAT);
530  Vector3 mmax(-MAXFLOAT);
531
532  AxisAlignedBox3 ret(mmin, mmax);
533  ret.Include(tform * Vector3(box.mMin.x, box.mMin.y, box.mMin.z));
534  ret.Include(tform * Vector3(box.mMin.x, box.mMin.y, box.mMax.z));
535  ret.Include(tform * Vector3(box.mMin.x, box.mMax.y, box.mMin.z));
536  ret.Include(tform * Vector3(box.mMin.x, box.mMax.y, box.mMax.z));
537  ret.Include(tform * Vector3(box.mMax.x, box.mMin.y, box.mMin.z));
538  ret.Include(tform * Vector3(box.mMax.x, box.mMin.y, box.mMax.z));
539  ret.Include(tform * Vector3(box.mMax.x, box.mMax.y, box.mMin.z));
540  ret.Include(tform * Vector3(box.mMax.x, box.mMax.y, box.mMax.z));
541  return ret;
542}
543
544inline float RatioOfOverlap(const AxisAlignedBox3 &box1, const AxisAlignedBox3 &box2)
545{
546        // return ratio of intersection to union
547        const AxisAlignedBox3 bisect = Intersect(box1, box2);
548        const AxisAlignedBox3 bunion = Union(box1, box2);
549
550        return bisect.GetVolume() / bunion.GetVolume();
551}
552
553inline int operator==(const AxisAlignedBox3 &A, const AxisAlignedBox3 &B)
554{
555  return (A.mMin == B.mMin) && (A.mMax == B.mMax);
556}
557
558 
559}
560
561
562#endif
Note: See TracBrowser for help on using the repository browser.