CRandomGenerator.cpp 1.9 KB

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