MinMaxBounds.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Unity's Bounds struct is represented as (center, extents).
  2. // HistoryBounds make heavy use of .Encapsulate(), which has to convert
  3. // Unity's (center, extents) to (min, max) every time, and then convert back.
  4. //
  5. // It's faster to use a (min, max) representation directly instead.
  6. using System;
  7. using System.Runtime.CompilerServices;
  8. using UnityEngine;
  9. namespace Mirror
  10. {
  11. public struct MinMaxBounds: IEquatable<Bounds>
  12. {
  13. public Vector3 min;
  14. public Vector3 max;
  15. // encapsulate a single point
  16. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  17. public void Encapsulate(Vector3 point)
  18. {
  19. min = Vector3.Min(this.min, point);
  20. max = Vector3.Max(this.max, point);
  21. }
  22. // encapsulate another bounds
  23. public void Encapsulate(MinMaxBounds bounds)
  24. {
  25. Encapsulate(bounds.min);
  26. Encapsulate(bounds.max);
  27. }
  28. // convenience comparison with Unity's bounds, for unit tests etc.
  29. public static bool operator ==(MinMaxBounds lhs, Bounds rhs) =>
  30. lhs.min == rhs.min &&
  31. lhs.max == rhs.max;
  32. public static bool operator !=(MinMaxBounds lhs, Bounds rhs) =>
  33. !(lhs == rhs);
  34. public override bool Equals(object obj) =>
  35. obj is MinMaxBounds other &&
  36. min == other.min &&
  37. max == other.max;
  38. public bool Equals(MinMaxBounds other) =>
  39. min.Equals(other.min) && max.Equals(other.max);
  40. public bool Equals(Bounds other) =>
  41. min.Equals(other.min) && max.Equals(other.max);
  42. #if UNITY_2021_3_OR_NEWER
  43. // Unity 2019/2020 don't have HashCode.Combine yet.
  44. // this is only to avoid reflection. without defining, it works too.
  45. // default generated by rider
  46. public override int GetHashCode() => HashCode.Combine(min, max);
  47. #else
  48. public override int GetHashCode()
  49. {
  50. // return HashCode.Combine(min, max); without using .Combine for older Unity versions
  51. unchecked
  52. {
  53. int hash = 17;
  54. hash = hash * 23 + min.GetHashCode();
  55. hash = hash * 23 + max.GetHashCode();
  56. return hash;
  57. }
  58. }
  59. #endif
  60. // tostring
  61. public override string ToString() => $"({min}, {max})";
  62. }
  63. }