RandomUtil.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //---------------------------------------------------------------------------------------------------------------------
  2. // UnitTests.cs
  3. //
  4. // Microsoft XNA Community Game Platform
  5. // Copyright (C) Microsoft Corporation. All rights reserved.
  6. //---------------------------------------------------------------------------------------------------------------------
  7. using System;
  8. using Microsoft.Xna.Framework;
  9. namespace UnitTests
  10. {
  11. /// <summary>
  12. /// Utility functions for creating uniform random vectors and orientations.
  13. /// </summary>
  14. public static class RandomUtil
  15. {
  16. public static float NextFloat(this Random random, float min, float max)
  17. {
  18. return (float)random.NextDouble() * (max - min) + min;
  19. }
  20. public static Vector3 PointInCube(this Random random)
  21. {
  22. return new Vector3
  23. {
  24. X = random.NextFloat(-1, 1),
  25. Y = random.NextFloat(-1, 1),
  26. Z = random.NextFloat(-1, 1)
  27. };
  28. }
  29. public static Vector3 PointInSphere(this Random random)
  30. {
  31. for (; ; )
  32. {
  33. Vector3 p = random.PointInCube();
  34. if (p.LengthSquared() <= 1.0f)
  35. {
  36. p.Normalize();
  37. return p;
  38. }
  39. }
  40. }
  41. public static Quaternion Orientation(this Random random)
  42. {
  43. for (; ; )
  44. {
  45. // Pick a random point uniformly inside the 4-sphere, then normalize
  46. Quaternion q = new Quaternion
  47. {
  48. X = random.NextFloat(-1,1),
  49. Y = random.NextFloat(-1,1),
  50. Z = random.NextFloat(-1,1),
  51. W = random.NextFloat(-1,1)
  52. };
  53. if (q.LengthSquared() <= 1.0f)
  54. {
  55. q.Normalize();
  56. return q;
  57. }
  58. }
  59. }
  60. }
  61. }