Skip to content

Commit ec69aba

Browse files
MathLib: added WrapToRange function
1 parent de19e09 commit ec69aba

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

Common/interface/BasicMath.hpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2668,6 +2668,20 @@ typename std::enable_if<std::is_enum<T>::value, T>::type ExtractLSB(T& bits)
26682668
return static_cast<T>(ExtractLSB(reinterpret_cast<typename std::underlying_type<T>::type&>(bits)));
26692669
}
26702670

2671+
/// Wraps Value to the range [Min, Min + Range)
2672+
template <typename T>
2673+
T WrapToRange(T Value, T Min, T Range)
2674+
{
2675+
VERIFY_EXPR(Range >= 0);
2676+
if (Range <= 0)
2677+
return Min;
2678+
2679+
T Result = (Value - Min) % Range;
2680+
if (Result < 0)
2681+
Result += Range;
2682+
2683+
return Result + Min;
2684+
}
26712685

26722686
inline std::ostream& operator<<(std::ostream& os, const float4& vec)
26732687
{

Tests/DiligentCoreTest/src/Common/MathLibTest.cpp

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2019-2023 Diligent Graphics LLC
2+
* Copyright 2019-2024 Diligent Graphics LLC
33
* Copyright 2015-2019 Egor Yusov
44
*
55
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -2292,6 +2292,38 @@ TEST(Common_BasicMath, VectorAll)
22922292
EXPECT_FALSE(all(double4{1, 1, 1, 0}));
22932293
}
22942294

2295+
2296+
TEST(Common_BasicMath, Wrap)
2297+
{
2298+
EXPECT_EQ(WrapToRange(10, 1, 0), 1);
2299+
EXPECT_EQ(WrapToRange(10, 1, 1), 1);
2300+
EXPECT_EQ(WrapToRange(-10, 1, 0), 1);
2301+
EXPECT_EQ(WrapToRange(-10, 1, 1), 1);
2302+
2303+
EXPECT_EQ(WrapToRange(0, 200, 10), 200);
2304+
EXPECT_EQ(WrapToRange(1, 200, 10), 201);
2305+
EXPECT_EQ(WrapToRange(9, 200, 10), 209);
2306+
EXPECT_EQ(WrapToRange(10, 200, 10), 200);
2307+
2308+
EXPECT_EQ(WrapToRange(-1, 200, 10), 209);
2309+
EXPECT_EQ(WrapToRange(-9, 200, 10), 201);
2310+
EXPECT_EQ(WrapToRange(-10, 200, 10), 200);
2311+
2312+
for (int Range : {1, 2, 7, 8, 9, 10, 15, 16, 17})
2313+
{
2314+
int Min = -Range / 2;
2315+
for (int i = -2; i <= 2; ++i)
2316+
{
2317+
for (int Ref = Min; Ref < Min + Range; ++Ref)
2318+
{
2319+
int Value = i * Range + Ref;
2320+
EXPECT_EQ(WrapToRange(Value, Min, Range), Ref) << Value << " " << Min << " " << Range;
2321+
}
2322+
}
2323+
}
2324+
}
2325+
2326+
22952327
TEST(Common_AdvancedMath, IsPointInsideTriangleF)
22962328
{
22972329
{

0 commit comments

Comments
 (0)