From 859727c1d3b63edd74afc7e24501a5aef9dd2bb0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20M=C3=BCller?= Date: Fri, 10 Nov 2023 17:11:22 +0100 Subject: [PATCH] Fix inaccurate envelope point value rounding Round to nearest integer instead of truncating in `f2fx` to ensure correct round-trip with `fx2f`. Add test to ensure correct round-trip with maximum `0.0005f` absolute error. --- CMakeLists.txt | 1 + src/base/math.h | 2 +- src/test/math.cpp | 14 ++++++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 src/test/math.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 59ad00543..85ed0f03a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2744,6 +2744,7 @@ if(GTEST_FOUND OR DOWNLOAD_GTEST) jsonwriter.cpp linereader.cpp mapbugs.cpp + math.cpp name_ban.cpp net.cpp netaddr.cpp diff --git a/src/base/math.h b/src/base/math.h index 1a6692ea0..b4b553bbc 100644 --- a/src/base/math.h +++ b/src/base/math.h @@ -66,7 +66,7 @@ constexpr int fxpscale = 1 << 10; // float to fixed constexpr inline int f2fx(float v) { - return (int)(v * fxpscale); + return round_to_int(v * fxpscale); } constexpr inline float fx2f(int v) { diff --git a/src/test/math.cpp b/src/test/math.cpp new file mode 100644 index 000000000..66f2ec79a --- /dev/null +++ b/src/test/math.cpp @@ -0,0 +1,14 @@ +#include "test.h" +#include + +#include + +TEST(Math, FixedPointRoundtrip) +{ + for(int i = 0; i < 100000; ++i) + { + const float Number = i / 1000.0f; + EXPECT_NEAR(Number, fx2f(f2fx(Number)), 0.0005f); + EXPECT_EQ(i, f2fx(fx2f(i))); + } +}