source: trunk/VUT/GtpVisibilityPreprocessor/src/AxisAlignedBox3.h @ 538

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