Browse Source

min, max, clamp math

Kajetan Johannes Hammerle 2 years ago
parent
commit
1f086aa7d2
3 changed files with 55 additions and 1 deletions
  1. 1 0
      Main.cpp
  2. 29 0
      math/Math.h
  3. 25 1
      tests/MathTests.cpp

+ 1 - 0
Main.cpp

@@ -89,5 +89,6 @@ int main(int argAmount, char** args) {
     Window::run<isRunning, tick, render>(50'000'000);
     Window::close();
     GL::printError("WUSI");
+
     return 0;
 }

+ 29 - 0
math/Math.h

@@ -38,6 +38,35 @@ namespace Math {
         }
         return c;
     }
+
+    template<typename T>
+    const T& min(const T& t) {
+        return t;
+    }
+
+    template<typename T, typename... Args>
+    const T& min(const T& t, Args&&... args) {
+        const T& o = min(args...);
+        return t < o ? t : o;
+    }
+
+    template<typename T>
+    const T& max(const T& t) {
+        return t;
+    }
+
+    template<typename T, typename... Args>
+    const T& max(const T& t, Args&&... args) {
+        const T& o = max(args...);
+        return o < t ? t : o;
+    }
+
+    template<typename T>
+    const T& clamp(const T& t, const T& borderA, const T& borderB) {
+        const T& low = min(borderA, borderB);
+        const T& high = max(borderA, borderB);
+        return max(low, min(high, t));
+    }
 }
 
 #endif

+ 25 - 1
tests/MathTests.cpp

@@ -43,10 +43,34 @@ static void testRoundUpLog2(Test& test) {
     test.checkEqual(31, Math::roundUpLog2(0x7FFFFFFF), "round up log2 11");
 }
 
+static void testMin(Test& test) {
+    test.checkEqual(-5, Math::min(-5), "min 1");
+    test.checkEqual(-10, Math::min(-5, 4, 3, 2, -10), "min 2");
+    test.checkEqual(4, Math::min(5, 20, 4, 30), "min 3");
+}
+
+static void testMax(Test& test) {
+    test.checkEqual(-5, Math::max(-5), "max 1");
+    test.checkEqual(4, Math::max(-5, 4, 3, 2, -10), "max 2");
+    test.checkEqual(30, Math::max(5, 20, 4, 30), "max 3");
+}
+
+static void testClamp(Test& test) {
+    test.checkEqual(5, Math::clamp(1, 5, 10), "clamp 1");
+    test.checkEqual(7, Math::clamp(7, 5, 10), "clamp 2");
+    test.checkEqual(10, Math::clamp(20, 5, 10), "clamp 3");
+    test.checkEqual(5, Math::clamp(1, 10, 5), "clamp 4");
+    test.checkEqual(7, Math::clamp(7, 10, 5), "clamp 5");
+    test.checkEqual(10, Math::clamp(20, 10, 5), "clamp 6");
+}
+
 void MathTests::test() {
-    Test test("Utils");
+    Test test("Math");
     testInterpolate(test);
     testPopCount(test);
     testRoundUpLog2(test);
+    testMin(test);
+    testMax(test);
+    testClamp(test);
     test.finalize();
 }