add vector clamp

This commit is contained in:
Matthew 2025-12-29 14:14:23 +11:00
parent 6af1c3e126
commit e77c1790f7

28
math.d
View File

@ -6,6 +6,7 @@ import dlib.util;
import dlibincludes; import dlibincludes;
import core.stdc.math : tanf, cosf, sinf, sqrtf, fabsf; import core.stdc.math : tanf, cosf, sinf, sqrtf, fabsf;
import std.algorithm.comparison : clamp;
import std.math; import std.math;
import std.math.algebraic; 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); 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 version(DLIB_TEST) unittest
{ {
enum FLOAT_MAX = f32.max; enum FLOAT_MAX = f32.max;
@ -1164,5 +1179,18 @@ version(DLIB_TEST) unittest
Transform(&vec, &mat, 1.0); Transform(&vec, &mat, 1.0);
assert(vec == Vec3(18.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);
} }
} }