namespace Syntriax.Engine.Physics2D.Primitives;
///
/// Represents a range of values along a single axis.
///
/// The minimum value of the projection.
/// The maximum value of the projection.
///
/// Initializes a new instance of the struct with the specified minimum and maximum values.
///
[System.Diagnostics.DebuggerDisplay("Min: {Min}, Max: {Max}")]
public readonly struct Projection(float min, float max)
{
///
/// Gets the minimum value of the projection.
///
public readonly float Min = min;
///
/// Gets the maximum value of the projection.
///
public readonly float Max = max;
///
/// Checks if two projections overlap.
///
/// The first projection to check.
/// The second projection to check.
/// if the projections overlap; otherwise, .
public static bool Overlaps(Projection left, Projection right) => Overlaps(left, right, out var _);
///
/// Checks if two projections overlap and calculates the depth of the overlap.
///
/// The first projection to check.
/// The second projection to check.
/// The depth of the overlap, if any.
/// if the projections overlap; otherwise, .
public static bool Overlaps(Projection left, Projection right, out float depth)
{
// TODO Try to improve this
bool rightMinInLeft = right.Min > left.Min && right.Min < left.Max;
if (rightMinInLeft)
{
depth = left.Max - right.Min;
return true;
}
bool rightMaxInLeft = right.Max < left.Max && right.Max > left.Min;
if (rightMaxInLeft)
{
depth = left.Min - right.Max;
return true;
}
bool leftMinInRight = left.Min > right.Min && left.Min < right.Max;
if (leftMinInRight)
{
depth = right.Max - left.Min;
return true;
}
bool leftMaxInRight = left.Max < right.Max && left.Max > right.Min;
if (leftMaxInRight)
{
depth = right.Min - left.Max;
return true;
}
depth = 0f;
return false;
}
}
///
/// Provides extension methods for the struct.
///
public static class ProjectionExtensions
{
///
/// Checks if two projections overlap.
///
/// The first projection to check.
/// The second projection to check.
/// if the projections overlap; otherwise, .
public static bool Overlaps(this Projection left, Projection right) => Projection.Overlaps(left, right);
///
/// Checks if two projections overlap and calculates the depth of the overlap.
///
/// The first projection to check.
/// The second projection to check.
/// The depth of the overlap, if any.
/// if the projections overlap; otherwise, .
public static bool Overlaps(this Projection left, Projection right, out float depth) => Projection.Overlaps(left, right, out depth);
}