From 3558859cc691e627c177ae8fba9b1708bfdf31b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vladim=C3=ADr=20Vondru=C5=A1?= Date: Sun, 26 Aug 2012 03:19:08 +0200 Subject: [PATCH] Utility function for clamping value in given limits. --- src/Math/Math.h | 6 ++++++ src/Math/Test/MathTest.cpp | 7 +++++++ src/Math/Test/MathTest.h | 1 + 3 files changed, 14 insertions(+) diff --git a/src/Math/Math.h b/src/Math/Math.h index aa9d77723..8c37df308 100644 --- a/src/Math/Math.h +++ b/src/Math/Math.h @@ -19,6 +19,7 @@ #include #include #include +#include #include "magnumVisibility.h" @@ -129,6 +130,11 @@ template inline constexpr typename std::ena FloatingPoint(value*std::numeric_limits::min())); } +/** @brief Clamp value */ +template inline T clamp(T value, T min, T max) { + return std::min(std::max(value, min), max); +} + /** @brief Angle in degrees diff --git a/src/Math/Test/MathTest.cpp b/src/Math/Test/MathTest.cpp index 9d76e9535..cfdc49243 100644 --- a/src/Math/Test/MathTest.cpp +++ b/src/Math/Test/MathTest.cpp @@ -28,6 +28,7 @@ MathTest::MathTest() { &MathTest::degrad, &MathTest::normalize, &MathTest::denormalize, + &MathTest::clamp, &MathTest::pow, &MathTest::log); } @@ -96,6 +97,12 @@ void MathTest::denormalize() { } } +void MathTest::clamp() { + CORRADE_COMPARE(Math::clamp(0.5f, -1.0f, 5.0f), 0.5f); + CORRADE_COMPARE(Math::clamp(-1.6f, -1.0f, 5.0f), -1.0f); + CORRADE_COMPARE(Math::clamp(9.5f, -1.0f, 5.0f), 5.0f); +} + void MathTest::pow() { CORRADE_COMPARE(Math::pow<10>(2ul), 1024ul); CORRADE_COMPARE(Math::pow<0>(3ul), 1ul); diff --git a/src/Math/Test/MathTest.h b/src/Math/Test/MathTest.h index 3bb32c5ea..568c0b148 100644 --- a/src/Math/Test/MathTest.h +++ b/src/Math/Test/MathTest.h @@ -27,6 +27,7 @@ class MathTest: public Corrade::TestSuite::Tester { void degrad(); void normalize(); void denormalize(); + void clamp(); void pow(); void log(); };