Skip to content
This repository was archived by the owner on Oct 11, 2020. It is now read-only.

Commit 6a1e4d6

Browse files
koraaa-teammate
authored andcommitted
Refactor rnd/rndscale/dtrnd to be proper functions
Before this they were macros. Macros are evil.
1 parent d100d3d commit 6a1e4d6

2 files changed

Lines changed: 33 additions & 6 deletions

File tree

inexor/shared/tools.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
#include <unistd.h>
66
#endif
77

8+
#include <cstdlib>
9+
#include <limits>
10+
811
////////////////////////// strings ////////////////////////////////////////
912

1013
static string tmpstr[4];
@@ -57,6 +60,20 @@ uint randomMT()
5760
return y;
5861
}
5962

63+
int rnd(const int x) {
64+
return abs((int)randomMT()) % x;
65+
}
66+
67+
float rndscale(const double x) {
68+
double int_max = std::numeric_limits<int>::max();
69+
return abs((int)randomMT()) * x / int_max;
70+
}
71+
72+
int detrnd(const uint seed, const int x) {
73+
return ( (seed*1103515245 + 12345) >>16) %x;
74+
}
75+
76+
6077
///////////////////////// network ///////////////////////
6178

6279
// all network traffic is in 32bit ints, which are then compressed using the following simple scheme (assumes that most values are small).

inexor/shared/tools.h

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -67,12 +67,22 @@ static inline int bitscan(uint mask)
6767
#endif
6868
#endif
6969

70-
extern void seedMT(uint seed);
71-
extern uint randomMT();
72-
#define rnd(x) ((int)(randomMT()&0x7FFFFFFF)%(x))
73-
#define rndscale(x) (float((randomMT()&0x7FFFFFFF)*double(x)/double(0x7FFFFFFF)))
74-
#define detrnd(s, x) ((int)(((((uint)(s))*1103515245+12345)>>16)%(x)))
75-
70+
/// Generate a random integer between 0 and x, excluding x
71+
///
72+
/// ```rnd(2) // can producd 0 and 1```
73+
extern int rnd(const int x);
74+
75+
/// Generate a random float between 0 and x
76+
///
77+
/// ```rndscale(1) // min: 0, max: 0.99...```
78+
extern float rndscale(const double x);
79+
80+
/// Generate a deterministic pseudo-random number
81+
///
82+
/// This means, that given the same seed and the same
83+
/// maximum value (`x`) this function will always return the
84+
/// same.
85+
extern int detrnd(const uint seed, const int x);
7686

7787
/// "for"-loop macro definitions
7888
/// DEPRECATED: Use c++ range based loops instead

0 commit comments

Comments
 (0)