1: <?php
2:
3: namespace Quadtree\Geometry;
4:
5: 6: 7:
8: class Bounds implements \Quadtree\Insertable
9: {
10:
11: private $width;
12:
13:
14: private $height;
15:
16:
17: private $left;
18:
19:
20: private $top;
21:
22: 23: 24: 25: 26: 27:
28: public function __construct($width, $height, $left = 0, $top = 0)
29: {
30: if (
31: !is_numeric($width)
32: || !is_numeric($height)
33: || !is_numeric($left)
34: || !is_numeric($top)
35: ) {
36: throw new \InvalidArgumentException('Input must be numeric');
37: }
38: $this->width = (float)$width;
39: $this->height = (float)$height;
40: $this->left = (float)$left;
41: $this->top = (float)$top;
42: }
43:
44: 45: 46:
47: function getWidth()
48: {
49: return $this->width;
50: }
51:
52: 53: 54:
55: function getHeight()
56: {
57: return $this->height;
58: }
59:
60: 61: 62:
63: function getLeft()
64: {
65: return $this->left;
66: }
67:
68: 69: 70:
71: function getTop()
72: {
73: return $this->top;
74: }
75:
76: 77: 78: 79: 80:
81: public function containsPoint(Point $point)
82: {
83: $leftIn = $point->getLeft() >= $this->left && $point->getLeft() < ($this->left + $this->width);
84: $topIn = $point->getTop() >= $this->top && $point->getTop() < ($this->top + $this->height);
85: return $leftIn && $topIn;
86: }
87:
88: 89: 90: 91:
92: public function getCenter()
93: {
94: $left = $this->left + ($this->width / 2);
95: $top = $this->top + ($this->height / 2);
96: return new Point($left, $top);
97: }
98:
99: 100: 101: 102: 103:
104: public function intersects(Bounds $other)
105: {
106: return $this->left <= $other->getLeft() + $other->getWidth()
107: && $other->getLeft() <= $this->left + $this->width
108: && $this->top <= $other->getTop() + $other->getHeight()
109: && $other->getTop() <= $this->top + $this->height;
110: }
111:
112: 113: 114: 115: 116:
117: public function intersection(Bounds $other)
118: {
119: $x0 = max($this->left, $other->getLeft());
120: $x1 = min($this->left + $this->width, $other->getLeft() + $other->getWidth());
121: if ($x0 <= $x1) {
122: $y0 = max($this->top, $other->getTop());
123: $y1 = min($this->top + $this->height, $other->getTop() + $other->getHeight());
124: if ($y0 <= $y1) {
125: return new static($x1 - $x0, $y1 - $y0, $x0, $y0);
126: }
127: }
128: return NULL;
129: }
130:
131:
132: 133: 134: 135:
136: public function getBounds()
137: {
138: return $this;
139: }
140:
141: 142: 143: 144:
145: public function getArea()
146: {
147: return $this->width * $this->height;
148: }
149:
150: 151: 152: 153: 154:
155: public function equals(Bounds $other)
156: {
157: return $this->width === $other->getWidth()
158: && $this->height === $other->getHeight()
159: && $this->left === $other->getLeft()
160: && $this->top === $other->getTop();
161: }
162: }