MoonTools.Bonk/Bonk/AABB3D.cs

80 lines
2.2 KiB
C#

using System;
using System.Collections.Generic;
using System.Numerics;
using MoonTools.Structs;
namespace MoonTools.Bonk
{
/// <summary>
/// Axis-aligned bounding box in 3 dimensions.
/// </summary>
public struct AABB3D : IEquatable<AABB3D>
{
public Vector3 Min { get; private set; }
public Vector3 Max { get; private set; }
public float Width { get { return Max.X - Min.X; } }
public float Height { get { return Max.Y - Min.Y; } }
public float Depth { get { return Max.Z - Min.Z; } }
public AABB3D(float minX, float minY, float minZ, float maxX, float maxY, float maxZ)
{
Min = new Vector3(minX, minY, minZ);
Max = new Vector3(maxX, maxY, maxZ);
}
public AABB3D(Vector3 min, Vector3 max)
{
Min = min;
Max = max;
}
public static bool TestOverlap(AABB3D a, AABB3D b)
{
return
a.Min.X <= b.Max.X &&
a.Max.X >= b.Min.X &&
a.Min.Y <= b.Max.Y &&
a.Max.Y >= b.Min.Y &&
a.Min.Z <= b.Max.Z &&
a.Max.Z >= b.Min.Z;
}
public AABB3D Merge(AABB3D other)
{
return new AABB3D(
Vector3.Min(Min, other.Min),
Vector3.Max(Max, other.Max)
);
}
public IEnumerable<Vector3> AABBCorners()
{
yield return Min;
yield return new Vector3(Min.X, Min.Y, Max.Z);
yield return new Vector3(Min.X, Max.Y, Min.Z);
yield return new Vector3(Max.X, Min.Y, Min.Z);
yield return new Vector3(Min.X, Max.Y, Max.Z);
yield return new Vector3(Max.X, Min.Y, Max.Z);
yield return new Vector3(Max.X, Max.Y, Min.Z);
yield return Max;
}
public override bool Equals(object obj)
{
return obj is AABB3D d && Equals(d);
}
public override int GetHashCode()
{
return HashCode.Combine(Min, Max);
}
public bool Equals(AABB3D other)
{
return Min == other.Min && Max == other.Max;
}
}
}