From 64f35c0e3190f3b56a1c17e81c775966bd0a2251 Mon Sep 17 00:00:00 2001
From: vaxerski <43317083+vaxerski@users.noreply.github.com>
Date: Fri, 3 Mar 2023 13:33:52 +0000
Subject: [PATCH] Bezier: Fix incorrect binary search in bezier approx

---
 src/helpers/BezierCurve.cpp | 21 ++++++++++++---------
 1 file changed, 12 insertions(+), 9 deletions(-)

diff --git a/src/helpers/BezierCurve.cpp b/src/helpers/BezierCurve.cpp
index 440a87c08..e018811ca 100644
--- a/src/helpers/BezierCurve.cpp
+++ b/src/helpers/BezierCurve.cpp
@@ -45,24 +45,27 @@ float CBezierCurve::getXForT(float t) {
 
 // Todo: this probably can be done better and faster
 float CBezierCurve::getYForPoint(float x) {
-    // binary search for the range UPDOWN X
-    float upperT = 1;
-    float lowerT = 0;
-    float mid    = 0.5;
+    if (x >= 1.0)
+        return 1.0;
 
-    while (std::abs(upperT - lowerT) > INVBAKEDPOINTS) {
-        if (m_aPointsBaked[((int)(mid * (float)BAKEDPOINTS))].x > x) {
+    // binary search for the range UPDOWN X
+    int upperT = BAKEDPOINTS - 1;
+    int lowerT = 0;
+    int mid    = upperT / 2;
+
+    while (std::abs(upperT - lowerT) > 1) {
+        if (m_aPointsBaked[mid].x > x) {
             upperT = mid;
         } else {
             lowerT = mid;
         }
 
-        mid = (upperT + lowerT) / 2.f;
+        mid = (upperT + lowerT) / 2;
     }
 
     // in the name of performance i shall make a hack
-    const auto LOWERPOINT = &m_aPointsBaked[std::clamp((int)((float)BAKEDPOINTS * lowerT), 0, BAKEDPOINTS - 1)];
-    const auto UPPERPOINT = &m_aPointsBaked[std::clamp((int)((float)BAKEDPOINTS * upperT), 0, BAKEDPOINTS - 1)];
+    const auto LOWERPOINT = &m_aPointsBaked[std::clamp(lowerT, 0, BAKEDPOINTS - 1)];
+    const auto UPPERPOINT = &m_aPointsBaked[std::clamp(upperT, 0, BAKEDPOINTS - 1)];
 
     const auto PERCINDELTA = (x - LOWERPOINT->x) / (UPPERPOINT->x - LOWERPOINT->x);