+void PcgRandom::seed(u64 state, u64 seq)
+{
+ m_state = 0U;
+ m_inc = (seq << 1u) | 1u;
+ next();
+ m_state += state;
+ next();
+}
+
+
+u32 PcgRandom::next()
+{
+ u64 oldstate = m_state;
+ m_state = oldstate * 6364136223846793005ULL + m_inc;
+
+ u32 xorshifted = ((oldstate >> 18u) ^ oldstate) >> 27u;
+ u32 rot = oldstate >> 59u;
+ return (xorshifted >> rot) | (xorshifted << ((-rot) & 31));
+}
+
+
+u32 PcgRandom::range(u32 bound)
+{
+ // If the bound is 0, we cover the whole RNG's range
+ if (bound == 0)
+ return next();
+
+ /*
+ This is an optimization of the expression:
+ 0x100000000ull % bound
+ since 64-bit modulo operations typically much slower than 32.
+ */
+ u32 threshold = -bound % bound;
+ u32 r;
+
+ /*
+ If the bound is not a multiple of the RNG's range, it may cause bias,
+ e.g. a RNG has a range from 0 to 3 and we take want a number 0 to 2.
+ Using rand() % 3, the number 0 would be twice as likely to appear.
+ With a very large RNG range, the effect becomes less prevalent but
+ still present.
+
+ This can be solved by modifying the range of the RNG to become a
+ multiple of bound by dropping values above the a threshold.
+
+ In our example, threshold == 4 % 3 == 1, so reject values < 1
+ (that is, 0), thus making the range == 3 with no bias.
+
+ This loop may look dangerous, but will always terminate due to the
+ RNG's property of uniformity.
+ */
+ while ((r = next()) < threshold)
+ ;
+
+ return r % bound;
+}
+
+
+s32 PcgRandom::range(s32 min, s32 max)
+{
+ if (max < min)
+ throw PrngException("Invalid range (max < min)");
+
+ // We have to cast to s64 because otherwise this could overflow,
+ // and signed overflow is undefined behavior.
+ u32 bound = (s64)max - (s64)min + 1;
+ return range(bound) + min;
+}
+
+
+void PcgRandom::bytes(void *out, size_t len)
+{
+ u8 *outb = (u8 *)out;
+ int bytes_left = 0;
+ u32 r;
+
+ while (len--) {
+ if (bytes_left == 0) {
+ bytes_left = sizeof(u32);
+ r = next();
+ }
+
+ *outb = r & 0xFF;
+ outb++;
+ bytes_left--;
+ r >>= CHAR_BIT;
+ }
+}
+
+
+s32 PcgRandom::randNormalDist(s32 min, s32 max, int num_trials)
+{
+ s32 accum = 0;
+ for (int i = 0; i != num_trials; i++)
+ accum += range(min, max);
+ return myround((float)accum / num_trials);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+float noise2d(int x, int y, s32 seed)
+{
+ unsigned int n = (NOISE_MAGIC_X * x + NOISE_MAGIC_Y * y