EARandom.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // Copyright (c) Electronic Arts Inc. All rights reserved.
  3. ///////////////////////////////////////////////////////////////////////////////
  4. ///////////////////////////////////////////////////////////////////////////////
  5. // This file implements a basic set of random number generators suitable for game
  6. // development usage.
  7. /////////////////////////////////////////////////////////////////////////////////////
  8. #include <EAStdC/internal/Config.h>
  9. #include <EAStdC/EARandom.h>
  10. #include <EAStdC/EARandomDistribution.h>
  11. #include <EAStdC/EAStopwatch.h>
  12. #include <string.h>
  13. #include <EAAssert/eaassert.h>
  14. #if defined(EASTDC_EASTOPWATCH_H)
  15. #define EARandomGetCPUCycle EA::StdC::Stopwatch::GetCPUCycle
  16. #elif EASTDC_TIME_H_AVAILABLE
  17. #include <time.h>
  18. static inline uint64_t EARandomGetCPUCycle()
  19. {
  20. return (uint64_t)clock();
  21. }
  22. #else
  23. #error Must define a way to get some pseudorandom bits with EARandomGetCPUCycle.
  24. #endif
  25. namespace EA
  26. {
  27. namespace StdC
  28. {
  29. namespace Internal
  30. {
  31. // this constant is designed to produce a maximum double value that when cast to a float does not fall outside the
  32. // valid range of [0..1).
  33. static const float_t RAND_FLOAT_MAX = 1.0f - 1.0f / 1048576.0f; // 1 - 2^-20
  34. }
  35. EASTDC_API void GetRandomSeed(void* pSeed, size_t nLength)
  36. {
  37. // We get a 64 bit value to work with and copy it repeatedly into
  38. // the bytes of the seed.
  39. const uint64_t nSeed64 = EARandomGetCPUCycle();
  40. for(size_t i = 0; i < nLength; i++)
  41. ((unsigned char*)pSeed)[i] = (unsigned char)(nSeed64 >> ((i % sizeof(uint64_t)) * sizeof(uint64_t)));
  42. }
  43. ///////////////////////////////////////////////////////////////////////////////
  44. // RandomLinearCongruential
  45. ///////////////////////////////////////////////////////////////////////////////
  46. void RandomLinearCongruential::SetSeed(uint32_t nSeed)
  47. {
  48. if(nSeed == 0xffffffff)
  49. nSeed = (uint32_t)(EARandomGetCPUCycle() & 0xffffffff);
  50. else if(nSeed == 0) // Test for seed == 0 because that's an illegal value for us.
  51. nSeed = 0xaaaaaaaa; // Convert it to some other constant. The actual value of the constant doesn't matter much.
  52. mnSeed = nSeed;
  53. }
  54. uint32_t RandomLinearCongruential::RandomUint32Uniform(uint32_t nLimit)
  55. {
  56. return EA::StdC::RandomLimit(*this, nLimit);
  57. }
  58. double RandomLinearCongruential::RandomDoubleUniform()
  59. {
  60. // All powers of two (such as this) are exact in floating point
  61. static const double kDoubleUniformScaleFactor = 2.32830643653870e-10f; // = (1 / 4294967296)
  62. // Unsigned conversions to float are often slow in due to store-to-load
  63. // mismatch stalls (well, at least on some architectures), so we do a
  64. // signed conversion.
  65. int32_t randInt = int32_t(RandomUint32Uniform());
  66. double dResult = (kDoubleUniformScaleFactor * randInt) + 0.5;
  67. if(dResult > Internal::RAND_FLOAT_MAX) // Due to precision issues, we need to clamp this.
  68. dResult = Internal::RAND_FLOAT_MAX;
  69. return dResult;
  70. }
  71. ///////////////////////////////////////////////////////////////////////////////
  72. // RandomTaus
  73. ///////////////////////////////////////////////////////////////////////////////
  74. ///////////////////////////////////////////////////////////////////////////////
  75. // P. L'Ecuyer, "Maximally Equidistributed Combined Tausworthe Generators",
  76. // Mathematics of Computation, 65, 213 (1996), 203-213.
  77. //
  78. // This generator has a period of approximately 2^88. This should be
  79. // preferred over simple linear congruential generators which fail to
  80. // produce uniformly distributed k-tuplets of numbers.
  81. //
  82. // Approved for EA use by EA Legal:
  83. // http://easites.ea.com/legal/Lists/OpenSourceDealSheet/DispForm.aspx?ID=589
  84. ///////////////////////////////////////////////////////////////////////////////
  85. const uint32_t kTausSeed0 = UINT32_C(3719485138);
  86. const uint32_t kTausSeed1 = UINT32_C(840184915);
  87. const uint32_t kTausSeed2 = UINT32_C(2586639250);
  88. uint32_t RandomTaus::GetSeed() const
  89. {
  90. return (mState[0] ^ kTausSeed0);
  91. }
  92. void RandomTaus::SetSeed(uint32_t nSeed)
  93. {
  94. if(nSeed == 0xffffffff)
  95. nSeed = (uint32_t)(EARandomGetCPUCycle() & 0xffffffff);
  96. const uint32_t newState[3] = { kTausSeed0 ^ nSeed, kTausSeed1 ^ nSeed, kTausSeed2 ^ nSeed };
  97. SetSeed(newState);
  98. }
  99. void RandomTaus::SetSeed(const uint32_t* pSeedArray)
  100. {
  101. if(pSeedArray)
  102. {
  103. mState[0] = pSeedArray[0];
  104. mState[1] = pSeedArray[1];
  105. mState[2] = pSeedArray[2];
  106. if (mState[0] < 2)
  107. mState[0] += kTausSeed0; // bad seed -- fix it
  108. if (mState[1] < 8)
  109. mState[1] += kTausSeed1; // bad seed -- fix it
  110. if (mState[2] < 16)
  111. mState[2] += kTausSeed2; // bad seed -- fix it
  112. }
  113. else
  114. SetSeed(0xffffffff); // Set seed automatically.
  115. }
  116. uint32_t RandomTaus::RandomUint32Uniform()
  117. {
  118. mState[0] = ((mState[0] & 0xfffffffe) << 12) ^ (((mState[0] << 13) ^ mState[0]) >> 19);
  119. mState[1] = ((mState[1] & 0xfffffff8) << 4) ^ (((mState[1] << 2) ^ mState[1]) >> 25);
  120. mState[2] = ((mState[2] & 0xfffffff0) << 17) ^ (((mState[2] << 3) ^ mState[2]) >> 11);
  121. return (mState[0] ^ mState[1] ^ mState[2]);
  122. }
  123. uint32_t RandomTaus::RandomUint32Uniform(uint32_t nLimit)
  124. {
  125. return EA::StdC::RandomLimit(*this, nLimit);
  126. }
  127. double RandomTaus::RandomDoubleUniform()
  128. {
  129. const uint32_t nRandNoLimit = RandomUint32Uniform();
  130. // All powers of two (such as this) are exact in floating point
  131. static const float kDoubleUniformScaleFactor = 2.32830643653870e-10f;
  132. // Unsigned conversions to float are often slow in due to store-to-load
  133. // mismatch stalls (well, at least on some architectures), so we do a
  134. // signed conversion.
  135. double dResult = (kDoubleUniformScaleFactor * (int32_t)nRandNoLimit) + 0.5;
  136. if(dResult > Internal::RAND_FLOAT_MAX) // Due to precision issues, we need to clamp this.
  137. dResult = Internal::RAND_FLOAT_MAX;
  138. return dResult;
  139. }
  140. double RandomTaus::RandomDoubleUniform(double limit)
  141. {
  142. EA_ASSERT(limit > 0);
  143. const uint32_t nRandNoLimit = RandomUint32Uniform();
  144. // All powers of two (such as this) are exact in floating point
  145. static const float kDoubleUniformScaleFactor = 2.32830643653870e-10f;
  146. // Unsigned conversions to float are often slow in due to store-to-load
  147. // mismatch stalls (well, at least on some architectures), so we do a
  148. // signed conversion.
  149. double dResult = (kDoubleUniformScaleFactor * limit * (int32_t)nRandNoLimit) + 0.5;
  150. if(dResult > Internal::RAND_FLOAT_MAX) // Due to precision issues, we need to clamp this.
  151. dResult = Internal::RAND_FLOAT_MAX;
  152. return dResult;
  153. }
  154. ///////////////////////////////////////////////////////////////////////////////
  155. // RandomMersenneTwister
  156. ///////////////////////////////////////////////////////////////////////////////
  157. RandomMersenneTwister::RandomMersenneTwister(uint32_t nSeed)
  158. {
  159. mpNextState = NULL;
  160. mnCountRemaining = kStateCount;
  161. SetSeed(nSeed);
  162. }
  163. RandomMersenneTwister::RandomMersenneTwister(const uint32_t seedArray[], unsigned nSeedArraySize)
  164. {
  165. mpNextState = NULL;
  166. mnCountRemaining = kStateCount;
  167. SetSeed(seedArray, nSeedArraySize);
  168. }
  169. RandomMersenneTwister& RandomMersenneTwister::operator=(const RandomMersenneTwister& randomMT)
  170. {
  171. ::memcpy(mState, randomMT.mState, sizeof(mState));
  172. mpNextState = &mState[0] + (randomMT.mpNextState - randomMT.mState);
  173. mnCountRemaining = randomMT.mnCountRemaining;
  174. return *this;
  175. }
  176. #define LOCAL_MIN(x, y) (x) < (y) ? (x) : (y)
  177. unsigned RandomMersenneTwister::GetSeed(uint32_t seedArray[], unsigned nSeedArraySize) const
  178. {
  179. if(nSeedArraySize >= 1)
  180. {
  181. // Get mnCountRemaining
  182. seedArray[0] = (uint32_t)mnCountRemaining;
  183. // Get mState
  184. unsigned i, copyCount = LOCAL_MIN((unsigned)kStateCount, nSeedArraySize - 1);
  185. for(i = 0; i < copyCount; i++)
  186. seedArray[i + 1] = mState[i];
  187. for(i = copyCount; i < (nSeedArraySize - 1); i++)
  188. seedArray[i + 1] = 0;
  189. return copyCount + 1;
  190. }
  191. return 0;
  192. }
  193. void RandomMersenneTwister::SetSeed(const uint32_t seedArray[], unsigned nSeedArraySize)
  194. {
  195. if(nSeedArraySize >= 1)
  196. {
  197. // Set mnCountRemaining
  198. mnCountRemaining = (int32_t)seedArray[0];
  199. if(mnCountRemaining > kStateCount)
  200. mnCountRemaining = kStateCount;
  201. // Set mpNextState
  202. mpNextState = mState + (kStateCount - mnCountRemaining);
  203. // Set mState
  204. const uint32_t* pStateInput = seedArray + 1; // +1 because seedArray[0] stores mnCountRemaining.
  205. uint32_t* pStateOutput = &mState[0];
  206. uint32_t* pStateOutputEnd = pStateOutput + kStateCount;
  207. while(pStateOutput < pStateOutputEnd)
  208. {
  209. if(pStateInput >= (seedArray + 1 + nSeedArraySize))
  210. pStateInput = (seedArray + 1); // Go back to the beginning.
  211. *pStateOutput++ = *pStateInput++;
  212. }
  213. }
  214. }
  215. void RandomMersenneTwister::SetSeed(uint32_t nSeed)
  216. {
  217. uint32_t* pState = &mState[0];
  218. int i = kStateCount;
  219. if(nSeed == 0xffffffff)
  220. nSeed = (uint32_t)(EARandomGetCPUCycle() & 0xffffffff);
  221. // Even seeds for the Mersenne Twister are known to be bad,
  222. // where bad means a non-maximal period and striping.
  223. nSeed |= 1;
  224. while(i--)
  225. {
  226. *pState = nSeed & 0xffff0000;
  227. *pState |= ((nSeed *= 69069)++ & 0xffff0000) >> 16;
  228. pState++;
  229. (nSeed *= 69069)++;
  230. }
  231. Reload();
  232. }
  233. uint32_t RandomMersenneTwister::RandomUint32Uniform()
  234. {
  235. uint32_t nValue;
  236. if(--mnCountRemaining < 0)
  237. {
  238. Reload();
  239. --mnCountRemaining;
  240. }
  241. nValue = *mpNextState++;
  242. nValue ^= (nValue >> 11);
  243. nValue ^= (nValue << 7) & 0x9d2c5680;
  244. nValue ^= (nValue << 15) & 0xefc60000;
  245. return nValue ^ (nValue >> 18);
  246. }
  247. uint32_t RandomMersenneTwister::RandomUint32Uniform(uint32_t nLimit)
  248. {
  249. return EA::StdC::RandomLimit(*this, nLimit);
  250. }
  251. double RandomMersenneTwister::RandomDoubleUniform()
  252. {
  253. double dResult = (int32_t)RandomUint32Uniform() * 2.3283064365386963e-10 + 0.5;
  254. if(dResult > Internal::RAND_FLOAT_MAX) // Due to precision issues, we need to clamp this.
  255. dResult = Internal::RAND_FLOAT_MAX;
  256. return dResult;
  257. }
  258. static inline uint32_t LoBit(uint32_t n)
  259. {
  260. return (n & 0x00000001);
  261. }
  262. static inline uint32_t MixBits(uint32_t n, uint32_t m)
  263. {
  264. return ((n & 0x80000000) | (m & 0x7FFFFFFF));
  265. }
  266. void RandomMersenneTwister::Reload()
  267. {
  268. const uint32_t kMagicNumber = 0x9908b0df; // Needs to be used as unsigned.
  269. const int kPeriodValue = 397;
  270. uint32_t *p0 = &mState[0], *p2 = &mState[1], *pM = &mState[kPeriodValue];
  271. uint32_t s0 = mState[0], s1 = mState[1];
  272. int i;
  273. for(i = kStateCount - kPeriodValue; i--; s0 = s1, s1 = *++p2)
  274. *p0++ = *pM++ ^ (MixBits(s0, s1) >> 1) ^ (LoBit(s1) ? kMagicNumber : 0);
  275. for(pM = &mState[0], i = kPeriodValue; --i; s0 = s1, s1 = *++p2 )
  276. *p0++ = *pM++ ^ (MixBits(s0, s1) >> 1) ^ (LoBit(s1) ? kMagicNumber : 0);
  277. s1 = mState[0];
  278. *p0 = *pM ^ (MixBits(s0, s1) >> 1) ^ (LoBit(s1) ? kMagicNumber : 0);
  279. mnCountRemaining = kStateCount;
  280. mpNextState = &mState[0];
  281. }
  282. uint32_t RandomMersenneTwister::Hash(int t, int c)
  283. {
  284. static uint32_t nIncrementor = 0;
  285. uint32_t h1 = 0;
  286. uint32_t h2 = 0;
  287. unsigned char* p = (unsigned char*)&t;
  288. unsigned i;
  289. for(i=0; i < sizeof(t); ++i)
  290. {
  291. h1 *= UINT8_MAX + 2;
  292. h1 += p[i];
  293. }
  294. p = (unsigned char*)&c;
  295. for(i=0; i < sizeof(c); ++i)
  296. {
  297. h2 *= UINT8_MAX + 2;
  298. h2 += p[i];
  299. }
  300. return (h1 + nIncrementor++) ^ h2;
  301. }
  302. // For unity build friendliness, undef all local #defines.
  303. #undef EARandomGetCPUCycle
  304. #undef LOCAL_MIN
  305. } // namespace StdC
  306. } // namespace EA