| 1 |
using System; |
| 2 |
using System.Collections.Generic; |
| 3 |
|
| 4 |
namespace Oni |
| 5 |
{ |
| 6 |
internal struct BoundingSphere : IEquatable<BoundingSphere> |
| 7 |
{ |
| 8 |
public Vector3 Center; |
| 9 |
public float Radius; |
| 10 |
|
| 11 |
public BoundingSphere(Vector3 center, float radius) |
| 12 |
{ |
| 13 |
Center = center; |
| 14 |
Radius = radius; |
| 15 |
} |
| 16 |
|
| 17 |
public static BoundingSphere CreateFromBoundingBox(BoundingBox bbox) |
| 18 |
{ |
| 19 |
BoundingSphere r; |
| 20 |
r.Center = (bbox.Min + bbox.Max) * 0.5f; |
| 21 |
r.Radius = Vector3.Distance(r.Center, bbox.Min); |
| 22 |
return r; |
| 23 |
} |
| 24 |
|
| 25 |
public static BoundingSphere CreateFromPoints(IEnumerable<Vector3> points) |
| 26 |
{ |
| 27 |
var center = Vector3.Zero; |
| 28 |
int count = 0; |
| 29 |
|
| 30 |
foreach (var point in points) |
| 31 |
{ |
| 32 |
center += point; |
| 33 |
count++; |
| 34 |
} |
| 35 |
|
| 36 |
center /= count; |
| 37 |
|
| 38 |
float radius = 0.0f; |
| 39 |
|
| 40 |
foreach (var point in points) |
| 41 |
{ |
| 42 |
float distance = Vector3.DistanceSquared(center, point); |
| 43 |
|
| 44 |
if (distance > radius) |
| 45 |
radius = distance; |
| 46 |
} |
| 47 |
|
| 48 |
radius = FMath.Sqrt(radius); |
| 49 |
|
| 50 |
return new BoundingSphere(center, radius); |
| 51 |
} |
| 52 |
|
| 53 |
public static bool operator ==(BoundingSphere s1, BoundingSphere s2) => s1.Radius == s2.Radius && s1.Center == s2.Center; |
| 54 |
public static bool operator !=(BoundingSphere s1, BoundingSphere s2) => s1.Radius != s2.Radius || s1.Center != s2.Center; |
| 55 |
|
| 56 |
public bool Equals(BoundingSphere other) => other.Radius == Radius && other.Center == Center; |
| 57 |
|
| 58 |
public override bool Equals(object obj) => obj is BoundingSphere && Equals((BoundingSphere)obj); |
| 59 |
public override int GetHashCode() => Radius.GetHashCode() ^ Center.GetHashCode(); |
| 60 |
|
| 61 |
public override string ToString() => $"{{{Center} {Radius}}}"; |
| 62 |
} |
| 63 |
} |