diff --git a/SDL2pp/Point.cc b/SDL2pp/Point.cc index 6f66298..8fe2505 100644 --- a/SDL2pp/Point.cc +++ b/SDL2pp/Point.cc @@ -21,6 +21,8 @@ #include +#include + namespace SDL2pp { Point::Point() { @@ -108,4 +110,22 @@ Point& Point::operator*=(int value) { return *this; } +Point Point::GetClamped(const Rect& rect) const { + Point p = *this; + p.Clamp(rect); + return p; +} + +Point& Point::Clamp(const Rect& rect) { + if (x < rect.x) + x = rect.x; + if (x > rect.GetX2()) + x = rect.GetX2(); + if (y < rect.y) + y = rect.y; + if (y > rect.GetY2()) + y = rect.GetY2(); + return *this; +} + } diff --git a/SDL2pp/Point.hh b/SDL2pp/Point.hh index bf883be..5ea6a63 100644 --- a/SDL2pp/Point.hh +++ b/SDL2pp/Point.hh @@ -26,6 +26,8 @@ namespace SDL2pp { +class Rect; + //////////////////////////////////////////////////////////// /// \brief 2D point /// @@ -231,6 +233,26 @@ public: /// //////////////////////////////////////////////////////////// Point& operator*=(int value); + + //////////////////////////////////////////////////////////// + /// \brief Get a point with coordinates modified so it fits into a given rect + /// + /// \param[in] rect Rectangle to clamp with + /// + /// \returns Clamped point + /// + //////////////////////////////////////////////////////////// + Point GetClamped(const Rect& rect) const; + + //////////////////////////////////////////////////////////// + /// \brief Clamp point coordinates to make it fit into a given rect + /// + /// \param[in] rect Rectangle to clamp with + /// + /// \returns Reference to self + /// + //////////////////////////////////////////////////////////// + Point& Clamp(const Rect& rect); }; } diff --git a/tests/test_pointrect.cc b/tests/test_pointrect.cc index ae4f9b6..00884a1 100644 --- a/tests/test_pointrect.cc +++ b/tests/test_pointrect.cc @@ -269,4 +269,14 @@ BEGIN_TEST() EXPECT_TRUE(Rect(0, 2, 3, 4) != sdlrect); EXPECT_TRUE(Point(0, 7) != sdlpoint); } + + { + // clamp + Rect rect(1, 2, 3, 4); + EXPECT_TRUE(Point(0, 0).GetClamped(rect) == Point(1, 2)); + EXPECT_TRUE(Point(0, 0).Clamp(rect) == Point(1, 2)); + + EXPECT_TRUE(Point(10, 10).GetClamped(rect) == Point(3, 5)); + EXPECT_TRUE(Point(10, 10).Clamp(rect) == Point(3, 5)); + } END_TEST()