43 lines
1.4 KiB
C#
43 lines
1.4 KiB
C#
using System.Collections.Generic;
|
|
|
|
using Syntriax.Engine.Core;
|
|
|
|
namespace Syntriax.Engine.Physics2D.Primitives;
|
|
|
|
public record AABB(Vector2D LowerBoundary, Vector2D UpperBoundary)
|
|
{
|
|
public Vector2D Center => (LowerBoundary + UpperBoundary) * .5f;
|
|
public Vector2D Size => LowerBoundary.FromTo(UpperBoundary).Abs();
|
|
public Vector2D SizeHalf => Size * .5f;
|
|
|
|
public static AABB FromVectors(IEnumerable<Vector2D> vectors)
|
|
{
|
|
int counter = 0;
|
|
|
|
Vector2D lowerBoundary = new(float.MaxValue, float.MaxValue);
|
|
Vector2D upperBoundary = new(float.MinValue, float.MinValue);
|
|
|
|
foreach (Vector2D vector in vectors)
|
|
{
|
|
lowerBoundary = Vector2D.Min(lowerBoundary, vector);
|
|
upperBoundary = Vector2D.Max(upperBoundary, vector);
|
|
counter++;
|
|
}
|
|
|
|
if (counter < 2)
|
|
throw new System.ArgumentException($"Parameter {nameof(vectors)} must have at least 2 items.");
|
|
|
|
return new(lowerBoundary, upperBoundary);
|
|
}
|
|
|
|
public static bool ApproximatelyEquals(AABB left, AABB right)
|
|
=> left.LowerBoundary.ApproximatelyEquals(right.LowerBoundary) && left.UpperBoundary.ApproximatelyEquals(right.UpperBoundary);
|
|
}
|
|
|
|
public static class AABBExtensions
|
|
{
|
|
public static AABB ToAABB(this IEnumerable<Vector2D> vectors) => AABB.FromVectors(vectors);
|
|
|
|
public static bool ApproximatelyEquals(this AABB left, AABB right) => AABB.ApproximatelyEquals(left, right);
|
|
}
|