Add Rect intersection and union methods

This commit is contained in:
Dmitry Marakasov 2014-12-30 00:14:14 +03:00
parent 837772dac0
commit c584b1a005
2 changed files with 57 additions and 0 deletions

View File

@ -19,6 +19,8 @@
3. This notice may not be removed or altered from any source distribution.
*/
#include <algorithm>
#include <SDL2pp/Point.hh>
#include <SDL2pp/Rect.hh>
@ -150,6 +152,31 @@ bool Rect::Contains(const Rect& rect) const {
return rect.x >= x && rect.y >= y && rect.GetX2() <= GetX2() && rect.GetY2() <= GetY2();
}
bool Rect::Intersects(const Rect& rect) const {
return !(rect.GetX2() < x || rect.GetY2() < y || rect.x > GetX2() || rect.y > GetY2());
}
Rect Rect::GetUnion(const Rect& rect) const {
return Rect::FromCorners(
std::min(x, rect.x),
std::min(y, rect.y),
std::max(GetX2(), rect.GetX2()),
std::max(GetY2(), rect.GetY2())
);
}
Optional<Rect> Rect::GetIntersection(const Rect& rect) const {
if (!Intersects(rect))
return NullOpt;
return Rect::FromCorners(
std::max(x, rect.x),
std::max(y, rect.y),
std::min(GetX2(), rect.GetX2()),
std::min(GetY2(), rect.GetY2())
);
}
Rect Rect::operator+(const Point& offset) const {
return Rect(x + offset.x, y + offset.y, w, h);
}

View File

@ -301,6 +301,36 @@ public:
////////////////////////////////////////////////////////////
bool Contains(const Rect& rect) const;
////////////////////////////////////////////////////////////
/// \brief Check whether the rect intersects another rect
///
/// \param rect Rect to check
///
/// \returns True if the rects intersect
///
////////////////////////////////////////////////////////////
bool Intersects(const Rect& rect) const;
////////////////////////////////////////////////////////////
/// \brief Calculate union with another rect
///
/// \param rect Rect to union with
///
/// \returns Rect representing intersection area or NullOpt if there was no intersection
///
////////////////////////////////////////////////////////////
Rect GetUnion(const Rect& rect) const;
////////////////////////////////////////////////////////////
/// \brief Calculate intersection with another rect
///
/// \param rect Rect to intersect with
///
/// \returns Rect representing intersection area or NullOpt if there was no intersection
///
////////////////////////////////////////////////////////////
Optional<Rect> GetIntersection(const Rect& rect) const;
////////////////////////////////////////////////////////////
/// \brief Get rectangle moved by a given offset
///