From cf26d48c9b3f9097bc36509c82cbba9aa5166674 Mon Sep 17 00:00:00 2001 From: Jonathan G Rennison Date: Sat, 18 Jun 2016 13:22:59 +0100 Subject: [PATCH] Add a "SoftClamp" function which tolerates min > max, use for DrawTrainEngine. --- src/core/math_func.hpp | 23 +++++++++++++++++++++++ src/train_cmd.cpp | 2 +- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/core/math_func.hpp b/src/core/math_func.hpp index df9142462b..0124476217 100644 --- a/src/core/math_func.hpp +++ b/src/core/math_func.hpp @@ -144,6 +144,29 @@ static inline T Clamp(const T a, const T min, const T max) return a; } +/** + * Clamp a value between an interval. + * + * This function returns a value which is between the given interval of + * min and max. If the given value is in this interval the value itself + * is returned otherwise the border of the interval is returned, according + * which side of the interval was 'left'. + * + * @note If the min value is greater than the return value is the average of the min and max. + * @param a The value to clamp/truncate. + * @param min The minimum of the interval. + * @param max the maximum of the interval. + * @returns A value between min and max which is closest to a. + */ +template +static inline T SoftClamp(const T a, const T min, const T max) +{ + if (min > max) return (min + max) / 2; + if (a <= min) return min; + if (a >= max) return max; + return a; +} + /** * Clamp an integer between an interval. * diff --git a/src/train_cmd.cpp b/src/train_cmd.cpp index 61f0b7335e..5653484332 100644 --- a/src/train_cmd.cpp +++ b/src/train_cmd.cpp @@ -600,7 +600,7 @@ void DrawTrainEngine(int left, int right, int preferred_x, int y, EngineID engin const Sprite *real_spritef = GetSprite(spritef, ST_NORMAL); const Sprite *real_spriter = GetSprite(spriter, ST_NORMAL); - preferred_x = Clamp(preferred_x, + preferred_x = SoftClamp(preferred_x, left - UnScaleGUI(real_spritef->x_offs) + ScaleGUITrad(14), right - UnScaleGUI(real_spriter->width) - UnScaleGUI(real_spriter->x_offs) - ScaleGUITrad(15));