Merge pull request #26737 from MidZik/rng-seed-fix

Fixed get_seed() not returning the correct seed.
This commit is contained in:
Rémi Verschelde 2019-03-07 11:18:18 +01:00 committed by GitHub
commit eb4a6a8147
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 15 deletions

View file

@ -32,24 +32,24 @@
#include "core/os/os.h"
RandomPCG::RandomPCG(uint64_t seed, uint64_t inc) :
RandomPCG::RandomPCG(uint64_t p_seed, uint64_t p_inc) :
pcg() {
pcg.state = seed;
pcg.inc = inc;
pcg.inc = p_inc;
seed(p_seed);
}
void RandomPCG::randomize() {
seed(OS::get_singleton()->get_ticks_usec() * pcg.state + PCG_DEFAULT_INC_64);
}
double RandomPCG::random(double from, double to) {
double RandomPCG::random(double p_from, double p_to) {
unsigned int r = rand();
double ret = (double)r / (double)RANDOM_MAX;
return (ret) * (to - from) + from;
return (ret) * (p_to - p_from) + p_from;
}
float RandomPCG::random(float from, float to) {
float RandomPCG::random(float p_from, float p_to) {
unsigned int r = rand();
float ret = (float)r / (float)RANDOM_MAX;
return (ret) * (to - from) + from;
return (ret) * (p_to - p_from) + p_from;
}

View file

@ -37,28 +37,33 @@
class RandomPCG {
pcg32_random_t pcg;
uint64_t current_seed = DEFAULT_SEED; // seed with this to get the same state
public:
static const uint64_t DEFAULT_SEED = 12047754176567800795U;
static const uint64_t DEFAULT_INC = PCG_DEFAULT_INC_64;
static const uint64_t RANDOM_MAX = 0xFFFFFFFF;
RandomPCG(uint64_t seed = DEFAULT_SEED, uint64_t inc = PCG_DEFAULT_INC_64);
RandomPCG(uint64_t p_seed = DEFAULT_SEED, uint64_t p_inc = PCG_DEFAULT_INC_64);
_FORCE_INLINE_ void seed(uint64_t seed) {
pcg.state = seed;
_FORCE_INLINE_ void seed(uint64_t p_seed) {
current_seed = p_seed;
pcg.state = p_seed;
pcg32_random_r(&pcg); // Force changing internal state to avoid initial 0
}
_FORCE_INLINE_ uint64_t get_seed() { return pcg.state; }
_FORCE_INLINE_ uint64_t get_seed() { return current_seed; }
void randomize();
_FORCE_INLINE_ uint32_t rand() { return pcg32_random_r(&pcg); }
_FORCE_INLINE_ uint32_t rand() {
current_seed = pcg.state;
return pcg32_random_r(&pcg);
}
_FORCE_INLINE_ double randd() { return (double)rand() / (double)RANDOM_MAX; }
_FORCE_INLINE_ float randf() { return (float)rand() / (float)RANDOM_MAX; }
double random(double from, double to);
float random(float from, float to);
real_t random(int from, int to) { return (real_t)random((real_t)from, (real_t)to); }
double random(double p_from, double p_to);
float random(float p_from, float p_to);
real_t random(int p_from, int p_to) { return (real_t)random((real_t)p_from, (real_t)p_to); }
};
#endif // RANDOM_PCG_H