CRandomGenerator.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. CRandomGenerator::CRandomGenerator()
  14. {
  15. resetSeed();
  16. }
  17. CRandomGenerator::CRandomGenerator(int seed)
  18. {
  19. setSeed(seed);
  20. }
  21. void CRandomGenerator::setSeed(int seed)
  22. {
  23. rand.seed(seed);
  24. }
  25. void CRandomGenerator::resetSeed()
  26. {
  27. boost::hash<std::string> stringHash;
  28. auto threadIdHash = stringHash(boost::lexical_cast<std::string>(boost::this_thread::get_id()));
  29. setSeed(static_cast<int>(threadIdHash * std::time(nullptr)));
  30. }
  31. TRandI CRandomGenerator::getIntRange(int lower, int upper)
  32. {
  33. assert(lower <= upper);
  34. return std::bind(TIntDist(lower, upper), std::ref(rand));
  35. }
  36. vstd::TRandI64 CRandomGenerator::getInt64Range(int64_t lower, int64_t upper)
  37. {
  38. assert(lower <= upper);
  39. return std::bind(TInt64Dist(lower, upper), std::ref(rand));
  40. }
  41. int CRandomGenerator::nextInt(int upper)
  42. {
  43. assert(0 <= upper);
  44. return getIntRange(0, upper)();
  45. }
  46. int CRandomGenerator::nextInt(int lower, int upper)
  47. {
  48. assert(lower <= upper);
  49. return getIntRange(lower, upper)();
  50. }
  51. int CRandomGenerator::nextInt()
  52. {
  53. return TIntDist()(rand);
  54. }
  55. vstd::TRand CRandomGenerator::getDoubleRange(double lower, double upper)
  56. {
  57. assert(lower <= upper);
  58. return std::bind(TRealDist(lower, upper), std::ref(rand));
  59. }
  60. double CRandomGenerator::nextDouble(double upper)
  61. {
  62. assert(0 <= upper);
  63. return getDoubleRange(0, upper)();
  64. }
  65. double CRandomGenerator::nextDouble(double lower, double upper)
  66. {
  67. assert(lower <= upper);
  68. return getDoubleRange(lower, upper)();
  69. }
  70. double CRandomGenerator::nextDouble()
  71. {
  72. return TRealDist()(rand);
  73. }
  74. CRandomGenerator & CRandomGenerator::getDefault()
  75. {
  76. static thread_local CRandomGenerator defaultRand;
  77. return defaultRand;
  78. }
  79. TGenerator & CRandomGenerator::getStdGenerator()
  80. {
  81. return rand;
  82. }
  83. VCMI_LIB_NAMESPACE_END