1
0

PoissonDiskSampler.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. using System.Diagnostics.CodeAnalysis;
  2. using System.Numerics;
  3. using Robust.Shared.Random;
  4. using Robust.Shared.Utility;
  5. namespace Content.Server.Worldgen.Tools;
  6. /// <summary>
  7. /// An implementation of Poisson Disk Sampling, for evenly spreading points across a given area.
  8. /// </summary>
  9. public sealed class PoissonDiskSampler
  10. {
  11. public const int DefaultPointsPerIteration = 30;
  12. [Dependency] private readonly IRobustRandom _random = default!;
  13. /// <summary>
  14. /// Samples for points within the given circle.
  15. /// </summary>
  16. /// <param name="center">Center of the sample</param>
  17. /// <param name="radius">Radius of the sample</param>
  18. /// <param name="minimumDistance">Minimum distance between points. Must be above 0!</param>
  19. /// <param name="pointsPerIteration">The number of points placed per iteration of the algorithm</param>
  20. /// <returns>An enumerator of points</returns>
  21. public SampleEnumerator SampleCircle(Vector2 center, float radius, float minimumDistance,
  22. int pointsPerIteration = DefaultPointsPerIteration)
  23. {
  24. return Sample(center - new Vector2(radius, radius), center + new Vector2(radius, radius), radius,
  25. minimumDistance, pointsPerIteration);
  26. }
  27. /// <summary>
  28. /// Samples for points within the given rectangle.
  29. /// </summary>
  30. /// <param name="topLeft">The top left of the rectangle</param>
  31. /// <param name="lowerRight">The bottom right of the rectangle</param>
  32. /// <param name="minimumDistance">Minimum distance between points. Must be above 0!</param>
  33. /// <param name="pointsPerIteration">The number of points placed per iteration of the algorithm</param>
  34. /// <returns>An enumerator of points</returns>
  35. public SampleEnumerator SampleRectangle(Vector2 topLeft, Vector2 lowerRight, float minimumDistance,
  36. int pointsPerIteration = DefaultPointsPerIteration)
  37. {
  38. return Sample(topLeft, lowerRight, null, minimumDistance, pointsPerIteration);
  39. }
  40. /// <summary>
  41. /// Samples for points within the given rectangle, with an optional rejection distance.
  42. /// </summary>
  43. /// <param name="topLeft">The top left of the rectangle</param>
  44. /// <param name="lowerRight">The bottom right of the rectangle</param>
  45. /// <param name="rejectionDistance">The distance at which points will be discarded, if any</param>
  46. /// <param name="minimumDistance">Minimum distance between points. Must be above 0!</param>
  47. /// <param name="pointsPerIteration">The number of points placed per iteration of the algorithm</param>
  48. /// <returns>An enumerator of points</returns>
  49. public SampleEnumerator Sample(Vector2 topLeft, Vector2 lowerRight, float? rejectionDistance,
  50. float minimumDistance, int pointsPerIteration)
  51. {
  52. // This still doesn't guard against dangerously low but non-zero distances, but this will do for now.
  53. DebugTools.Assert(minimumDistance > 0, "Minimum distance must be above 0, or else an infinite number of points would be generated.");
  54. var settings = new SampleSettings
  55. {
  56. TopLeft = topLeft, LowerRight = lowerRight,
  57. Dimensions = lowerRight - topLeft,
  58. Center = (topLeft + lowerRight) / 2,
  59. CellSize = minimumDistance / (float) Math.Sqrt(2),
  60. MinimumDistance = minimumDistance,
  61. RejectionSqDistance = rejectionDistance * rejectionDistance
  62. };
  63. settings.GridWidth = (int) (settings.Dimensions.X / settings.CellSize) + 1;
  64. settings.GridHeight = (int) (settings.Dimensions.Y / settings.CellSize) + 1;
  65. var state = new State
  66. {
  67. Grid = new Vector2?[settings.GridWidth, settings.GridHeight],
  68. ActivePoints = new List<Vector2>()
  69. };
  70. return new SampleEnumerator(this, state, settings, pointsPerIteration);
  71. }
  72. private Vector2 AddFirstPoint(ref SampleSettings settings, ref State state)
  73. {
  74. while (true)
  75. {
  76. var d = _random.NextDouble();
  77. var xr = settings.TopLeft.X + settings.Dimensions.X * d;
  78. d = _random.NextDouble();
  79. var yr = settings.TopLeft.Y + settings.Dimensions.Y * d;
  80. var p = new Vector2((float) xr, (float) yr);
  81. if (settings.RejectionSqDistance != null &&
  82. (settings.Center - p).LengthSquared() > settings.RejectionSqDistance)
  83. continue;
  84. var index = Denormalize(p, settings.TopLeft, settings.CellSize);
  85. state.Grid[(int) index.X, (int) index.Y] = p;
  86. state.ActivePoints.Add(p);
  87. return p;
  88. }
  89. }
  90. private Vector2? AddNextPoint(Vector2 point, ref SampleSettings settings, ref State state)
  91. {
  92. var q = GenerateRandomAround(point, settings.MinimumDistance);
  93. if (q.X >= settings.TopLeft.X && q.X < settings.LowerRight.X &&
  94. q.Y > settings.TopLeft.Y && q.Y < settings.LowerRight.Y &&
  95. (settings.RejectionSqDistance == null ||
  96. (settings.Center - q).LengthSquared() <= settings.RejectionSqDistance))
  97. {
  98. var qIndex = Denormalize(q, settings.TopLeft, settings.CellSize);
  99. var tooClose = false;
  100. for (var i = (int) Math.Max(0, qIndex.X - 2);
  101. i < Math.Min(settings.GridWidth, qIndex.X + 3) && !tooClose;
  102. i++)
  103. for (var j = (int) Math.Max(0, qIndex.Y - 2);
  104. j < Math.Min(settings.GridHeight, qIndex.Y + 3) && !tooClose;
  105. j++)
  106. {
  107. if (state.Grid[i, j].HasValue && (state.Grid[i, j]!.Value - q).Length() < settings.MinimumDistance)
  108. tooClose = true;
  109. }
  110. if (!tooClose)
  111. {
  112. state.ActivePoints.Add(q);
  113. state.Grid[(int) qIndex.X, (int) qIndex.Y] = q;
  114. return q;
  115. }
  116. }
  117. return null;
  118. }
  119. private Vector2 GenerateRandomAround(Vector2 center, float minimumDistance)
  120. {
  121. var d = _random.NextDouble();
  122. var radius = minimumDistance + minimumDistance * d;
  123. d = _random.NextDouble();
  124. var angle = Math.PI * 2 * d;
  125. var newX = radius * Math.Sin(angle);
  126. var newY = radius * Math.Cos(angle);
  127. return new Vector2((float) (center.X + newX), (float) (center.Y + newY));
  128. }
  129. private static Vector2 Denormalize(Vector2 point, Vector2 origin, double cellSize)
  130. {
  131. return new Vector2((int) ((point.X - origin.X) / cellSize), (int) ((point.Y - origin.Y) / cellSize));
  132. }
  133. public struct SampleEnumerator
  134. {
  135. private PoissonDiskSampler _pds;
  136. private State _state;
  137. private SampleSettings _settings;
  138. // These variables make up the state machine.
  139. private bool _returnedFirstPoint;
  140. private int _pointsPerIteration;
  141. private int _iterationListIndex;
  142. private bool _iterationFound;
  143. private int _iterationPosition;
  144. // This has internal access because C# nested type access is being weird.
  145. internal SampleEnumerator(PoissonDiskSampler pds, State state, SampleSettings settings, int ppi)
  146. {
  147. _pds = pds;
  148. _state = state;
  149. _settings = settings;
  150. _pointsPerIteration = ppi;
  151. }
  152. public bool MoveNext([NotNullWhen(true)] out Vector2? point)
  153. {
  154. // First point is chosen via a very particular method.
  155. if (!_returnedFirstPoint)
  156. {
  157. _returnedFirstPoint = true;
  158. point = _pds.AddFirstPoint(ref _settings, ref _state);
  159. return true;
  160. }
  161. // Remaining points have to be fed out carefully.
  162. // We can be interrupted (by a successful point) mid-stream.
  163. while (_state.ActivePoints.Count != 0)
  164. {
  165. if (_iterationPosition == 0)
  166. {
  167. // First point of iteration.
  168. _iterationListIndex = _pds._random.Next(_state.ActivePoints.Count);
  169. _iterationFound = false;
  170. }
  171. var basePoint = _state.ActivePoints[_iterationListIndex];
  172. point = _pds.AddNextPoint(basePoint, ref _settings, ref _state);
  173. // Set this now, return later after processing is complete.
  174. _iterationFound |= point != null;
  175. // Iteration loop advance.
  176. _iterationPosition++;
  177. if (_iterationPosition == _pointsPerIteration)
  178. {
  179. // Reached end of this iteration.
  180. _iterationPosition = 0;
  181. if (!_iterationFound)
  182. _state.ActivePoints.RemoveAt(_iterationListIndex);
  183. }
  184. if (point != null)
  185. return true;
  186. }
  187. point = null;
  188. return false;
  189. }
  190. }
  191. internal struct State
  192. {
  193. public Vector2?[,] Grid;
  194. public List<Vector2> ActivePoints;
  195. }
  196. internal struct SampleSettings
  197. {
  198. public Vector2 TopLeft, LowerRight, Center;
  199. public Vector2 Dimensions;
  200. public float? RejectionSqDistance;
  201. public float MinimumDistance;
  202. public float CellSize;
  203. public int GridWidth, GridHeight;
  204. }
  205. }