From be4baf0f188c69bdcf7b049d2f6d2b85eb8574c5 Mon Sep 17 00:00:00 2001 From: aUniqueUser <55301516+aUniqueUser@users.noreply.github.com> Date: Mon, 19 Oct 2020 16:11:07 -0400 Subject: [PATCH] Make randoms not depend on rand() (#1135) * Make randoms not depend on rand() Changed UniformRandomInt and RandFloatRange to not depend on rand, because this can cause little to no randomness depending on system. --- src/helpers.cpp | 29 +++++++---------------------- 1 file changed, 7 insertions(+), 22 deletions(-) diff --git a/src/helpers.cpp b/src/helpers.cpp index b76d8327..d3ee9fd8 100644 --- a/src/helpers.cpp +++ b/src/helpers.cpp @@ -962,34 +962,19 @@ bool AmbassadorCanHeadshot() return true; } +static std::random_device random_device; +static std::mt19937 engine{random_device()}; + float RandFloatRange(float min, float max) { - return (min + 1) + (((float) rand()) / (float) RAND_MAX) * (max - (min + 1)); + std::uniform_real_distribution random(min, max); + return random(engine); } int UniformRandomInt(int min, int max) { - uint32_t bound, len, r, result = 0; - /* Protect from random stupidity */ - if (min > max) - std::swap(min, max); - - len = max - min + 1; - /* RAND_MAX is implementation dependent. - * It's guaranteed that this value is at least 32767. - * glibc's RAND_MAX is 2^31 - 1 exactly. Since source games hard - * depend on glibc, we will do so as well - */ - while (len) - { - bound = (1U + RAND_MAX) % len; - while ((r = rand()) < bound) - ; - result *= 1U + RAND_MAX; - result += r % len; - len -= len > RAND_MAX ? RAND_MAX : len; - } - return int(result) + min; + std::uniform_int_distribution random(min, max); + return random(engine); } bool IsEntityVisible(CachedEntity *entity, int hb)