2
0

CRandomGenerator.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * CRandomGenerator.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CRandomGenerator.h"
  12. VCMI_LIB_NAMESPACE_BEGIN
  13. boost::thread_specific_ptr<CRandomGenerator> CRandomGenerator::defaultRand;
  14. CRandomGenerator::CRandomGenerator()
  15. {
  16. resetSeed();
  17. }
  18. void CRandomGenerator::setSeed(int seed)
  19. {
  20. rand.seed(seed);
  21. }
  22. void CRandomGenerator::resetSeed()
  23. {
  24. boost::hash<std::string> stringHash;
  25. auto threadIdHash = stringHash(boost::lexical_cast<std::string>(boost::this_thread::get_id()));
  26. setSeed(static_cast<int>(threadIdHash * std::time(nullptr)));
  27. }
  28. TRandI CRandomGenerator::getIntRange(int lower, int upper)
  29. {
  30. return std::bind(TIntDist(lower, upper), std::ref(rand));
  31. }
  32. vstd::TRandI64 CRandomGenerator::getInt64Range(int64_t lower, int64_t upper)
  33. {
  34. return std::bind(TInt64Dist(lower, upper), std::ref(rand));
  35. }
  36. int CRandomGenerator::nextInt(int upper)
  37. {
  38. return getIntRange(0, upper)();
  39. }
  40. int CRandomGenerator::nextInt(int lower, int upper)
  41. {
  42. return getIntRange(lower, upper)();
  43. }
  44. int CRandomGenerator::nextInt()
  45. {
  46. return TIntDist()(rand);
  47. }
  48. vstd::TRand CRandomGenerator::getDoubleRange(double lower, double upper)
  49. {
  50. return std::bind(TRealDist(lower, upper), std::ref(rand));
  51. }
  52. double CRandomGenerator::nextDouble(double upper)
  53. {
  54. return getDoubleRange(0, upper)();
  55. }
  56. double CRandomGenerator::nextDouble(double lower, double upper)
  57. {
  58. return getDoubleRange(lower, upper)();
  59. }
  60. double CRandomGenerator::nextDouble()
  61. {
  62. return TRealDist()(rand);
  63. }
  64. CRandomGenerator & CRandomGenerator::getDefault()
  65. {
  66. if(!defaultRand.get())
  67. {
  68. defaultRand.reset(new CRandomGenerator());
  69. }
  70. return *defaultRand;
  71. }
  72. TGenerator & CRandomGenerator::getStdGenerator()
  73. {
  74. return rand;
  75. }
  76. VCMI_LIB_NAMESPACE_END