Random.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "core/utils/Random.hpp"
  2. #include <stdio.h>
  3. constexpr static int M = 7;
  4. Core::Random::Random(Seed seed) : data(), index(0) {
  5. for(size_t i = 0; i < data.getLength(); i++) {
  6. data[i] = seed;
  7. seed = seed * 7 + 31;
  8. }
  9. }
  10. void Core::Random::update() {
  11. static const Seed map[2] = {0, 0x8EBFD028};
  12. for(size_t i = 0; i < data.getLength() - M; i++) {
  13. data[i] = data[i + M] ^ (data[i] >> 1) ^ map[data[i] & 1];
  14. }
  15. for(size_t i = data.getLength() - M; i < data.getLength(); i++) {
  16. data[i] = data[i + (M - data.getLength())] ^ (data[i] >> 1) ^
  17. map[data[i] & 1];
  18. }
  19. index = 0;
  20. }
  21. Core::Random::Seed Core::Random::next() {
  22. if(index >= data.getLength()) {
  23. update();
  24. }
  25. Seed r = data[index++];
  26. r ^= (r << 7) & 0x2B5B2500;
  27. r ^= (r << 15) & 0xDB8B0000;
  28. r ^= (r >> 16);
  29. return r;
  30. }
  31. template<typename T>
  32. T limit(T value, T min, T inclusiveMax) {
  33. return min + value % (inclusiveMax - min + 1);
  34. }
  35. Core::Random::Seed Core::Random::next(Seed min, Seed inclusiveMax) {
  36. return limit(next(), min, inclusiveMax);
  37. }
  38. i32 Core::Random::nextI32() {
  39. return static_cast<i32>(next() >> 1);
  40. }
  41. i32 Core::Random::nextI32(i32 min, i32 inclusiveMax) {
  42. return limit(nextI32(), min, inclusiveMax);
  43. }
  44. size_t Core::Random::nextSize() {
  45. if constexpr(sizeof(size_t) <= sizeof(Seed)) {
  46. return static_cast<size_t>(next());
  47. } else {
  48. return static_cast<size_t>(next()) |
  49. (static_cast<size_t>(next()) >> 32);
  50. }
  51. }
  52. size_t Core::Random::nextSize(size_t min, size_t inclusiveMax) {
  53. return limit(nextSize(), min, inclusiveMax);
  54. }
  55. bool Core::Random::nextBool() {
  56. return next() & 1;
  57. }
  58. float Core::Random::nextFloat() {
  59. static constexpr i32 m = 0x7FFFFFFF;
  60. float f = static_cast<float>(next() & m) * (1.0f / static_cast<float>(m));
  61. return f >= 1.0f ? nextFloat() : f;
  62. }
  63. float Core::Random::nextFloat(float min, float exclusiveMax) {
  64. return min + nextFloat() * (exclusiveMax - min);
  65. }