Add UniformRandomInt RNG

Simple uniform RNG that depends on rand() as randomness source
Init random in hack.cpp
This commit is contained in:
Unnamed 2019-01-26 01:29:25 +00:00
parent 26ba1b6b1b
commit 66301c1970
3 changed files with 42 additions and 2 deletions

View File

@ -164,6 +164,7 @@ bool IsEntityVisiblePenetration(CachedEntity *entity, int hb);
// void EndPrediction(); // void EndPrediction();
float RandFloatRange(float min, float max); float RandFloatRange(float min, float max);
int UniformRandomInt(int min, int max);
bool Developer(CachedEntity *ent); bool Developer(CachedEntity *ent);

View File

@ -143,6 +143,22 @@ void critical_error_handler(int signum)
::raise(SIGABRT); ::raise(SIGABRT);
} }
static void InitRandom()
{
int rand_seed;
FILE *rnd = fopen("/dev/urandom", "rb");
if (!rnd || fread(&rand_seed, sizeof(rand_seed), 1, rnd) < 1)
{
logging::Info("Warning!!! Failed read from /dev/urandom (%s). Randomness is going to be weak", strerror(errno));
timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
rand_seed = t.tv_nsec ^ t.tv_sec & getpid();
}
srand(rand_seed);
if (rnd)
fclose(rnd);
}
void hack::Initialize() void hack::Initialize()
{ {
::signal(SIGSEGV, &critical_error_handler); ::signal(SIGSEGV, &critical_error_handler);
@ -178,9 +194,8 @@ free(logname);*/
} }
#endif /* TEXTMODE */ #endif /* TEXTMODE */
logging::Info("Initializing..."); logging::Info("Initializing...");
srand(time(0)); InitRandom();
sharedobj::LoadAllSharedObjects(); sharedobj::LoadAllSharedObjects();
CreateInterfaces(); CreateInterfaces();
CDumper dumper; CDumper dumper;

View File

@ -801,6 +801,30 @@ float RandFloatRange(float min, float max)
return (min + 1) + (((float) rand()) / (float) RAND_MAX) * (max - (min + 1)); return (min + 1) + (((float) rand()) / (float) RAND_MAX) * (max - (min + 1));
} }
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;
}
bool IsEntityVisible(CachedEntity *entity, int hb) bool IsEntityVisible(CachedEntity *entity, int hb)
{ {
if (g_Settings.bInvalid) if (g_Settings.bInvalid)