2024-01-24 12:46:31 +03:00
|
|
|
using System.Collections.Generic;
|
|
|
|
|
2024-01-23 18:39:25 +03:00
|
|
|
using Syntriax.Engine.Core;
|
|
|
|
|
|
|
|
namespace Syntriax.Engine.Physics2D.Primitives;
|
|
|
|
|
|
|
|
public record AABB(Vector2D LowerBoundary, Vector2D UpperBoundary)
|
|
|
|
{
|
2024-01-24 18:37:43 +03:00
|
|
|
public Vector2D Center => (LowerBoundary + UpperBoundary) * .5f;
|
|
|
|
public Vector2D Size => LowerBoundary.FromTo(UpperBoundary).Abs();
|
|
|
|
public Vector2D SizeHalf => Size * .5f;
|
|
|
|
|
2024-01-24 12:58:51 +03:00
|
|
|
public static AABB FromVectors(IEnumerable<Vector2D> vectors)
|
2024-01-24 12:46:31 +03:00
|
|
|
{
|
2024-01-24 12:58:51 +03:00
|
|
|
int counter = 0;
|
2024-01-24 12:46:31 +03:00
|
|
|
|
2024-01-24 12:58:51 +03:00
|
|
|
Vector2D lowerBoundary = new(float.MaxValue, float.MaxValue);
|
|
|
|
Vector2D upperBoundary = new(float.MinValue, float.MinValue);
|
2024-01-24 12:46:31 +03:00
|
|
|
|
2024-01-24 12:58:51 +03:00
|
|
|
foreach (Vector2D vector in vectors)
|
2024-01-24 12:46:31 +03:00
|
|
|
{
|
|
|
|
lowerBoundary = Vector2D.Min(lowerBoundary, vector);
|
|
|
|
upperBoundary = Vector2D.Max(upperBoundary, vector);
|
2024-01-24 12:58:51 +03:00
|
|
|
counter++;
|
2024-01-24 12:46:31 +03:00
|
|
|
}
|
|
|
|
|
2024-01-24 12:58:51 +03:00
|
|
|
if (counter < 2)
|
|
|
|
throw new System.ArgumentException($"Parameter {nameof(vectors)} must have at least 2 items.");
|
|
|
|
|
2024-01-24 12:46:31 +03:00
|
|
|
return new(lowerBoundary, upperBoundary);
|
|
|
|
}
|
|
|
|
|
2024-01-23 19:13:51 +03:00
|
|
|
public static bool ApproximatelyEquals(AABB left, AABB right)
|
|
|
|
=> left.LowerBoundary.ApproximatelyEquals(right.LowerBoundary) && left.UpperBoundary.ApproximatelyEquals(right.UpperBoundary);
|
|
|
|
}
|
2024-01-23 18:39:25 +03:00
|
|
|
|
2024-01-23 19:13:51 +03:00
|
|
|
public static class AABBExtensions
|
|
|
|
{
|
2024-01-24 12:58:51 +03:00
|
|
|
public static AABB ToAABB(this IEnumerable<Vector2D> vectors) => AABB.FromVectors(vectors);
|
2024-01-24 12:46:31 +03:00
|
|
|
|
2024-01-23 19:13:51 +03:00
|
|
|
public static bool ApproximatelyEquals(this AABB left, AABB right) => AABB.ApproximatelyEquals(left, right);
|
2024-01-23 18:39:25 +03:00
|
|
|
}
|