diff --git a/X10D/src/RandomExtensions/RandomExtensions.Numerics.cs b/X10D/src/RandomExtensions/RandomExtensions.Numerics.cs index abb9603..c23bfde 100644 --- a/X10D/src/RandomExtensions/RandomExtensions.Numerics.cs +++ b/X10D/src/RandomExtensions/RandomExtensions.Numerics.cs @@ -33,6 +33,37 @@ namespace X10D.RandomExtensions return Quaternion.CreateFromYawPitchRoll(y, x, z); } + /// + /// Returns a randomly generated rotation with uniform distribution. + /// + /// The instance. + /// A constructed with uniform distribution. + /// is . + public static Quaternion NextRotationUniform(this Random random) + { + if (random is null) + { + throw new ArgumentNullException(nameof(random)); + } + + var seed = random.Next(); + var seededRandom = new Random(seed); + float normal, w, x, y, z; + + do + { + w = seededRandom.NextSingle(-1f, 1f); + x = seededRandom.NextSingle(-1f, 1f); + y = seededRandom.NextSingle(-1f, 1f); + z = seededRandom.NextSingle(-1f, 1f); + normal = w * w + x * x + y * y + z * z; + } + while (normal > 1f || normal == 0f); + + normal = MathF.Sqrt(normal); + return new Quaternion(x / normal, y / normal, z / normal, w / normal); + } + /// /// Returns a with magnitude 1 whose components indicate a random point on the unit circle. ///