FastRandom.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using Microsoft.Xna.Framework;
  4. namespace MonoGame.Extended
  5. {
  6. /// <summary>
  7. /// Represents a pseudo-random number generator using a linear congruential generator algorithm.
  8. /// </summary>
  9. /// <remarks>
  10. /// <para>
  11. /// This implementation uses the same constants as Microsoft Visual C++ rand() function:
  12. ///
  13. /// a=214013
  14. /// c=2531011
  15. /// m=2^31
  16. /// </para>
  17. /// <para>
  18. /// It provides high performance and speed, but comes at the price of having lower statistical quality, or true
  19. /// 'randomness' compared to modern algorithms. The algorithm is deterministic based on the initial seed
  20. /// value, making it suitable for reproducible sequences.
  21. ///</para>
  22. ///<para>
  23. /// Note: This pseudo-random number generator exhibits noticeable patterns and should not be used for
  24. /// cryptographic purposes or when a high-quality random distribution is critical. Consider using
  25. /// <see cref="System.Random"/> for better statistical properties.
  26. /// </para>
  27. /// </remarks>
  28. public class FastRandom
  29. {
  30. private readonly IFastRandomImpl _impl;
  31. /// <summary>
  32. /// Provides a thread-safe <see cref="FastRandom"/> instance that may be used concurrently from any thread.
  33. /// </summary>
  34. public static FastRandom Shared { get; } = new FastRandom(new ThreadSafeFastRandomImpl());
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="FastRandom"/> class using the default seed value.
  37. /// </summary>
  38. public FastRandom() : this(1)
  39. {
  40. }
  41. /// <summary>
  42. /// Initializes a new instance of the <see cref="FastRandom"/> class using the specified seed value.
  43. /// </summary>
  44. /// <param name="seed">A number used to calculate a starting value for the pseudo-random number sequence.</param>
  45. public FastRandom(int seed)
  46. {
  47. _impl = new LinearCongruentialGeneratorImpl(seed);
  48. }
  49. private FastRandom(IFastRandomImpl impl)
  50. {
  51. ArgumentNullException.ThrowIfNull(impl);
  52. _impl = impl;
  53. }
  54. /// <summary>
  55. /// Returns a non-negative random integer.
  56. /// </summary>
  57. /// <returns>A 32-bit signed integer that is greater than or equal to 0 and less than 32768.</returns>
  58. public int Next()
  59. {
  60. return _impl.Next();
  61. }
  62. /// <summary>
  63. /// Returns a non-negative random integer that is less than or equal to the specified maximum.
  64. /// </summary>
  65. /// <param name="max">The inclusive upper bound of the random number to be generated.</param>
  66. /// <returns>
  67. /// A 32-bit signed integer that is greater than or equal to 0 and less than or equal to <paramref name="max"/>.
  68. /// </returns>
  69. public int Next(int max)
  70. {
  71. return _impl.Next(max);
  72. }
  73. /// <summary>
  74. /// Returns a random integer that is within a specified range.
  75. /// </summary>
  76. /// <param name="min">The inclusive lower bound of the random number returned.</param>
  77. /// <param name="max">The inclusive upper bound of the random number returned.</param>
  78. /// <returns>
  79. /// A 32-bit signed integer that is greater than or equal to <paramref name="min"/> and less than or equal to
  80. /// <paramref name="max"/>.
  81. /// </returns>
  82. public int Next(int min, int max)
  83. {
  84. return _impl.Next(min, max);
  85. }
  86. /// <summary>
  87. /// Returns a random integer that is within a specified range.
  88. /// </summary>
  89. /// <param name="range">
  90. /// A range representing the inclusive lower and upper bound of the random number to return.
  91. /// </param>
  92. /// <returns>
  93. /// A 32-bit signed integer that is greater than or equal to the <see cref="Range{T}.Min"/> and less than or
  94. /// equal to the <see cref="Range{T}.Max"/> value of <paramref name="range"/>.
  95. /// </returns>
  96. public int Next(Range<int> range)
  97. {
  98. return _impl.Next(range);
  99. }
  100. /// <summary>
  101. /// Returns a random floating-point number that is greater than or equal to 0.0 and less than 1.0.
  102. /// </summary>
  103. /// <returns>
  104. /// A single-precision floating point number that is greater than or equal to 0.0 and less than 1.0.
  105. /// </returns>
  106. public float NextSingle()
  107. {
  108. return _impl.NextSingle();
  109. }
  110. /// <summary>
  111. /// Returns a random floating-point number that is greater than or equal to 0.0 and less than the
  112. /// specified maximum.
  113. /// </summary>
  114. /// <param name="max">The exclusive upper bond of the random number generated.</param>
  115. /// <returns>
  116. /// A single precision floating-point number that is greater than or equal to 0.0 and less than
  117. /// <paramref name="max"/>.
  118. /// </returns>
  119. public float NextSingle(float max)
  120. {
  121. return _impl.NextSingle(max);
  122. }
  123. /// <summary>
  124. /// Returns a random floating-point number that is within a specified range.
  125. /// </summary>
  126. /// <param name="min">The inclusive lower bound of the random number returned.</param>
  127. /// <param name="max">The exclusive upper bound of the random number returned.</param>
  128. /// <returns>
  129. /// A single-precision floating point number that is greater than or equal to <paramref name="min"/> and
  130. /// less than <paramref name="max"/>.
  131. /// </returns>
  132. public float NextSingle(float min, float max)
  133. {
  134. return _impl.NextSingle(min, max);
  135. }
  136. /// <summary>
  137. /// Returns a random floating-point number that is within a specified range.
  138. /// </summary>
  139. /// <param name="range">
  140. /// A range representing the inclusive lower and exclusive upper bound of the random number returned.
  141. /// </param>
  142. /// <returns>
  143. /// A single-precision floating point number that is greater than or equal to the <see cref="Range{T}.Min"/>
  144. /// and less than the <see cref="Range{T}.Max"/> value of <paramref name="range"/>
  145. /// </returns>
  146. public float NextSingle(Range<float> range)
  147. {
  148. return _impl.NextSingle(range);
  149. }
  150. /// <summary>
  151. /// Returns a random angle between -π and π.
  152. /// </summary>
  153. /// <returns>
  154. /// A random angle value in radians.
  155. /// </returns>
  156. public float NextAngle()
  157. {
  158. return _impl.NextAngle();
  159. }
  160. /// <summary>
  161. /// Gets a random unit vector.
  162. /// </summary>
  163. /// <param name="vector">When this method returns, contains a unit vector with a random direction.</param>
  164. public void NextUnitVector(out Vector2 vector)
  165. {
  166. _impl.NextUnitVector(out vector);
  167. }
  168. /// <summary>
  169. /// Gets a random unit vector.
  170. /// </summary>
  171. /// <param name="vector">A pointer to the Vector2 where the random unit vector will be stored.</param>
  172. public unsafe void NextUnitVector(Vector2* vector)
  173. {
  174. _impl.NextUnitVector(vector);
  175. }
  176. #region IFastRandomImplementation
  177. private interface IFastRandomImpl
  178. {
  179. int Next();
  180. int Next(int max);
  181. int Next(int min, int max);
  182. int Next(Range<int> range);
  183. float NextSingle();
  184. float NextSingle(float max);
  185. float NextSingle(float min, float max);
  186. float NextSingle(Range<float> range);
  187. float NextAngle();
  188. void NextUnitVector(out Vector2 vector);
  189. unsafe void NextUnitVector(Vector2* vector);
  190. }
  191. #endregion
  192. #region Linear Congruential Generator
  193. private sealed class LinearCongruentialGeneratorImpl : IFastRandomImpl
  194. {
  195. private const int MULTIPLIER = 214013;
  196. private const int INCREMENT = 2531011;
  197. private int _state;
  198. public LinearCongruentialGeneratorImpl() : this(1)
  199. {
  200. }
  201. public LinearCongruentialGeneratorImpl(int seed)
  202. {
  203. ArgumentOutOfRangeException.ThrowIfNegativeOrZero(seed);
  204. _state = seed;
  205. }
  206. public int Next()
  207. {
  208. _state = MULTIPLIER * _state + INCREMENT;
  209. return (_state >> 16) & 0x7FFF;
  210. }
  211. public int Next(int max)
  212. {
  213. return (int)(max * NextSingle() + 0.5f);
  214. }
  215. public int Next(int min, int max)
  216. {
  217. return (int)((max - min) * NextSingle() + 0.5f) + min;
  218. }
  219. public int Next(Range<int> range)
  220. {
  221. return Next(range.Min, range.Max);
  222. }
  223. public float NextSingle()
  224. {
  225. return Next() / (float)short.MaxValue;
  226. }
  227. public float NextSingle(float max)
  228. {
  229. return max * NextSingle();
  230. }
  231. public float NextSingle(float min, float max)
  232. {
  233. return (max - min) * NextSingle() + min;
  234. }
  235. public float NextSingle(Range<float> range)
  236. {
  237. return NextSingle(range.Min, range.Max);
  238. }
  239. public float NextAngle()
  240. {
  241. return NextSingle(-MathHelper.Pi, MathHelper.Pi);
  242. }
  243. public void NextUnitVector(out Vector2 vector)
  244. {
  245. float angle = NextAngle();
  246. vector.X = MathF.Cos(angle);
  247. vector.Y = MathF.Sin(angle);
  248. }
  249. public unsafe void NextUnitVector(Vector2* vector)
  250. {
  251. float angle = NextAngle();
  252. vector->X = MathF.Cos(angle);
  253. vector->Y = MathF.Sin(angle);
  254. }
  255. }
  256. #endregion
  257. #region ThreadSafeImpl
  258. private sealed class ThreadSafeFastRandomImpl : IFastRandomImpl
  259. {
  260. [ThreadStatic]
  261. private static LinearCongruentialGeneratorImpl t_random;
  262. private static LinearCongruentialGeneratorImpl LocalRandom => t_random ?? Create();
  263. [MethodImpl(MethodImplOptions.NoInlining)]
  264. private static LinearCongruentialGeneratorImpl Create()
  265. {
  266. t_random = new LinearCongruentialGeneratorImpl();
  267. return t_random;
  268. }
  269. public int Next()
  270. {
  271. return LocalRandom.Next();
  272. }
  273. public int Next(int max)
  274. {
  275. return LocalRandom.Next(max);
  276. }
  277. public int Next(int min, int max)
  278. {
  279. return LocalRandom.Next(min, max);
  280. }
  281. public int Next(Range<int> range)
  282. {
  283. return LocalRandom.Next(range.Min, range.Max);
  284. }
  285. public float NextSingle()
  286. {
  287. return LocalRandom.NextSingle();
  288. }
  289. public float NextSingle(float max)
  290. {
  291. return LocalRandom.NextSingle(max);
  292. }
  293. public float NextSingle(float min, float max)
  294. {
  295. return LocalRandom.NextSingle(min, max);
  296. }
  297. public float NextSingle(Range<float> range)
  298. {
  299. return LocalRandom.NextSingle(range.Min, range.Max);
  300. }
  301. public float NextAngle()
  302. {
  303. return LocalRandom.NextAngle();
  304. }
  305. public void NextUnitVector(out Vector2 vector)
  306. {
  307. LocalRandom.NextUnitVector(out vector);
  308. }
  309. public unsafe void NextUnitVector(Vector2* vector)
  310. {
  311. LocalRandom.NextUnitVector(vector);
  312. }
  313. }
  314. #endregion
  315. }
  316. }