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

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