rand.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. //
  2. // rand.h
  3. // cocos2d_libs
  4. //
  5. // Created by 徐俊杰 on 2020/5/25.
  6. //
  7. #ifndef rand_h
  8. #define rand_h
  9. #include "rparticle/Macros/RParticleMacros.h"
  10. /*
  11. Some random generator timings:
  12. MacBook Pro w/ Core 2 Duo 2.4GHz. Times are for gcc 4.0.1 (OS X 10.6.2) / VS2008 SP1 (Win XP SP3),
  13. in milliseconds for this loop (4915200 calls):
  14. for (int j = 0; j < 100; ++j)
  15. for (int i = 0; i < 128*128*3; ++i)
  16. data[i] = (rnd.get() & 0x3) << 6;
  17. gcc vs2008 Size
  18. C's rand(): 57.0 109.3 ms 1
  19. Mersenne Twister: 56.0 37.4 ms 2500
  20. Unity 2.x LCG: 11.1 9.2 ms 4
  21. Xorshift 128: 15.0 17.8 ms 16
  22. Xorshift 32: 20.6 10.7 ms 4
  23. WELL 512: 43.6 55.1 ms 68
  24. */
  25. NS_RRP_BEGIN
  26. // Xorshift 128 implementation
  27. // Xorshift paper: http://www.jstatsoft.org/v08/i14/paper
  28. // Wikipedia: http://en.wikipedia.org/wiki/Xorshift
  29. class Rand {
  30. public:
  31. Rand (UInt32 seed = 0)
  32. {
  33. SetSeed (seed);
  34. }
  35. UInt32 Get ()
  36. {
  37. UInt32 t;
  38. t = x ^ (x << 11);
  39. x = y; y = z; z = w;
  40. return w = (w ^ (w >> 19)) ^ (t ^ (t >> 8));
  41. }
  42. inline static float GetFloatFromInt (UInt32 value)
  43. {
  44. // take 23 bits of integer, and divide by 2^23-1
  45. return float(value & 0x007FFFFF) * (1.0f / 8388607.0f);
  46. }
  47. inline static UInt8 GetByteFromInt (UInt32 value)
  48. {
  49. // take the most significant byte from the 23-bit value
  50. return UInt8(value >> (23 - 8));
  51. }
  52. // random number between 0.0 and 1.0
  53. float GetFloat ()
  54. {
  55. return GetFloatFromInt (Get ());
  56. }
  57. // random number between -1.0 and 1.0
  58. float GetSignedFloat ()
  59. {
  60. return GetFloat() * 2.0f - 1.0f;
  61. }
  62. void SetSeed (UInt32 seed)
  63. {
  64. x = seed;
  65. y = x * 1812433253U + 1;
  66. z = y * 1812433253U + 1;
  67. w = z * 1812433253U + 1;
  68. }
  69. UInt32 GetSeed () const { return x; }
  70. private:
  71. UInt32 x, y, z, w;
  72. };
  73. NS_RRP_END
  74. #endif /* rand_h */