CRandomGenerator.cpp 1.8 KB

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