Oxygine  1
2g game engine
OBBox.h
1 #pragma once
2 #include "oxygine-include.h"
3 #include "Vector2.h"
4 #include "Rect.h"
5 
6 namespace oxygine
7 {
8  class OBBox
9  {
10  private:
12  Vector2 corner[4];
13 
15  Vector2 axis[2];
16 
18  float origin[2];
19 
21  bool overlaps1Way(const OBBox& other) const
22  {
23  for (int a = 0; a < 2; ++a)
24  {
25 
26  float t = other.corner[0].dot(axis[a]);
27 
28  // Find the extent of box 2 on axis a
29  float tMin = t;
30  float tMax = t;
31 
32  for (int c = 1; c < 4; ++c)
33  {
34  t = other.corner[c].dot(axis[a]);
35 
36  if (t < tMin)
37  {
38  tMin = t;
39  }
40  else if (t > tMax)
41  {
42  tMax = t;
43  }
44  }
45 
46  // We have to subtract off the origin
47 
48  // See if [tMin, tMax] intersects [0, 1]
49  if ((tMin > 1 + origin[a]) || (tMax < origin[a]))
50  {
51  // There was no intersection along this dimension;
52  // the boxes cannot possibly overlap.
53  return false;
54  }
55  }
56 
57  // There was no dimension along which there is no intersection.
58  // Therefore the boxes overlap.
59  return true;
60  }
61 
62 
65  void computeAxes()
66  {
67  axis[0] = corner[1] - corner[0];
68  axis[1] = corner[3] - corner[0];
69 
70  // Make the length of each axis 1/edge length so we know any
71  // dot product must be less than 1 to fall within the edge.
72 
73  for (int a = 0; a < 2; ++a)
74  {
75  axis[a] /= axis[a].sqlength();
76  origin[a] = corner[0].dot(axis[a]);
77  }
78  }
79 
80  public:
81 
82  OBBox(const RectF& rect, const AffineTransform& tr)
83  {
84  corner[0] = tr.transform(rect.getLeftTop());
85  corner[1] = tr.transform(rect.getRightTop());
86  corner[2] = tr.transform(rect.getRightBottom());
87  corner[3] = tr.transform(rect.getLeftBottom());
88 
89  computeAxes();
90  }
91 
93  bool overlaps(const OBBox& other) const
94  {
95  return overlaps1Way(other) && other.overlaps1Way(*this);
96  }
97 
98  RectF aabbox() const
99  {
100  RectF rect(corner[0], Vector2(0, 0));
101  rect.unite(corner[1]);
102  rect.unite(corner[2]);
103  rect.unite(corner[3]);
104  return rect;
105  }
106 
107  };
108 
109 }
Definition: OBBox.h:8
–oxgl-end–!
Definition: Actor.h:14
bool overlaps(const OBBox &other) const
Definition: OBBox.h:93