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

Revision 2575, 18.3 KB checked in by bittner, 17 years ago (diff)

big merge: preparation for havran ray caster, check if everything works

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