From e0699c15b6697895d855a8732d940ae7d377fe20 Mon Sep 17 00:00:00 2001 From: Jonathan G Rennison Date: Fri, 26 Jan 2024 18:23:53 +0000 Subject: [PATCH] Add function to turn a percentage into a quantity scaling factor --- src/economy.cpp | 26 ++++++++++++++++++++++++++ src/economy_func.h | 2 ++ 2 files changed, 28 insertions(+) diff --git a/src/economy.cpp b/src/economy.cpp index 6b9c2a8a20..07c1621fad 100644 --- a/src/economy.cpp +++ b/src/economy.cpp @@ -2697,6 +2697,32 @@ uint ScaleQuantity(uint amount, int cf, int fine, bool allow_trunc) return amount; } +int PercentageToScaleQuantityFactor(uint percentage) +{ + const uint32_t adj[11] = {65536, 70239, 75281, 80684, 86475, 92681, 99334, 106463, 114104, 122294, 65536 * 2}; + + const uint64_t base = (((uint64_t)1) << 32); + uint64_t scale = CeilDivT(base, 100) * percentage; + const uint8_t first_bit = FindLastBit(scale); + if (first_bit >= 16) { + scale >>= (first_bit - 16); + } else { + scale <<= (16 - first_bit); + } + + uint32_t best_distance = INT32_MAX; + int best = 0; + for (int i = 0; i < 11; i++) { + uint32_t distance = Delta((uint32_t)scale, adj[i]); + if (distance < best_distance) { + best = i; + best_distance = distance; + } + } + + return ((((int)first_bit) - 32) * 10) + best; +} + uint CargoScaler::ScaleAllowTrunc(uint num) { return this->ScaleWithBias(num, Random() & 0xFFFF); diff --git a/src/economy_func.h b/src/economy_func.h index 33a53b87e5..213be385a7 100644 --- a/src/economy_func.h +++ b/src/economy_func.h @@ -56,6 +56,8 @@ inline bool EconomyIsInRecession() uint ScaleQuantity(uint amount, int scale_factor, bool allow_trunc = false); uint ScaleQuantity(uint amount, int cf, int fine, bool allow_trunc = false); +int PercentageToScaleQuantityFactor(uint percentage); + void UpdateCargoScalers(); #endif /* ECONOMY_FUNC_H */