Skip to content

Commit

Permalink
Add lerp and inverseLerp helper functions
Browse files Browse the repository at this point in the history
  • Loading branch information
tehKaiN committed Sep 18, 2022
1 parent 64185ca commit 793ef1b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
15 changes: 14 additions & 1 deletion libs/common/include/helpers/mathFuncs.h
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ constexpr U clamp(T val, U min, U max) noexcept
// Here all values are positive or have the same signedness
return static_cast<U>(clamp(static_cast<Common>(val), static_cast<Common>(min), static_cast<Common>(max)));
}
// Linear interpolation between [startVal, endVal]. Difference between those 2 and elapsedTime should be smallish
/// Linear interpolation between [startVal, endVal]. Difference between those 2 and elapsedTime should be smallish
template<typename T, typename U, typename V>
constexpr T interpolate(const T startVal, const T endVal, const U elapsedTime, const V duration) noexcept
{
Expand All @@ -66,4 +66,17 @@ constexpr T interpolate(const T startVal, const T endVal, const U elapsedTime, c
else // Special case for unsigned values
return static_cast<T>(startVal - ((startVal - endVal) * elapsedTime) / duration);
}

/// Linear interpolation, similar to C++20's std::lerp()
constexpr float lerp(const float startVal, const float endVal, const float ratio) noexcept
{
return startVal + ratio * (endVal - startVal);
}

/// Inverse function to lerp(): Returns the ratio of value in [startVal, endVal]
template<typename T>
constexpr T inverseLerp(const T startVal, const T endVal, const T value) noexcept
{
return (value - startVal) / (endVal - startVal);
}
} // namespace helpers
22 changes: 22 additions & 0 deletions tests/common/testMathHelpers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -188,4 +188,26 @@ BOOST_AUTO_TEST_CASE_TEMPLATE(Interpolate, T, TimeTypes)
}
}

BOOST_AUTO_TEST_CASE(Lerp)
{
const auto startVal = 5.0f;
const auto endVal = 10.0f;
BOOST_TEST(helpers::lerp(startVal, endVal, .0f) == startVal);
BOOST_TEST(helpers::lerp(startVal, endVal, 1.0f) == endVal);
BOOST_TEST(helpers::lerp(startVal, endVal, .5f) == 7.5f);
BOOST_TEST(helpers::lerp(startVal, endVal, 2.0f) == 15.0f);
BOOST_TEST(helpers::lerp(startVal, endVal, -.5f) == 2.5f);
}

BOOST_AUTO_TEST_CASE(InverseLerp)
{
const auto startVal = 5.0f;
const auto endVal = 10.0f;
BOOST_TEST(helpers::inverseLerp(startVal, endVal, startVal) == .0f);
BOOST_TEST(helpers::inverseLerp(startVal, endVal, endVal) == 1.0f);
BOOST_TEST(helpers::inverseLerp(startVal, endVal, 7.5f) == .5f);
BOOST_TEST(helpers::inverseLerp(startVal, endVal, 15.0f) == 2.0f);
BOOST_TEST(helpers::inverseLerp(startVal, endVal, 2.5f) == -.5f);
}

BOOST_AUTO_TEST_SUITE_END()

0 comments on commit 793ef1b

Please sign in to comment.