diff --git a/math.d b/math.d index 0784d69..1d71656 100644 --- a/math.d +++ b/math.d @@ -6,6 +6,7 @@ import dlib.util; import dlibincludes; import core.stdc.math : tanf, cosf, sinf, sqrtf, fabsf; +import std.algorithm.comparison : clamp; import std.math; import std.math.algebraic; @@ -956,6 +957,20 @@ Remap(f32 v, f32 in_min, f32 in_max, f32 out_min, f32 out_max) return Lerp(out_min, out_max, t); } +template +IsVector(T) +{ + import std.traits : isInstanceOf; + enum bool IsVector = isInstanceOf!(Vector, T); +} + +T +Clamp(T)(T value, T low, T high) if(IsVector!(T)) +{ + mixin(GenerateLoop!("value.v[@] = clamp(value.v[@], low.v[@], high.v[@]);", T.v.length)); + return value; +} + version(DLIB_TEST) unittest { enum FLOAT_MAX = f32.max; @@ -1164,5 +1179,18 @@ version(DLIB_TEST) unittest Transform(&vec, &mat, 1.0); assert(vec == Vec3(18.0)); + + Vec4 low = Vec4(-5.0); + Vec4 high = Vec4(+5.0); + Vec4 test = Vec4(-500.0); + + test = Clamp(test, low, high); + + assert(test == low); + + test = Vec4(+500.0); + test = Clamp(test, low, high); + + assert(test == high); } }