MoonTools.Bonk/Bonk/MultiShape.cs

79 lines
2.6 KiB
C#
Raw Normal View History

2020-01-05 00:13:07 +00:00
using System.Collections.Generic;
using System.Collections.Immutable;
using MoonTools.Core.Structs;
namespace MoonTools.Core.Bonk
{
2020-01-05 07:24:36 +00:00
public struct MultiShape<TShape2D> : IHasAABB2D, ICollisionTestable<TShape2D> where TShape2D : struct, IShape2D
2020-01-05 00:13:07 +00:00
{
2020-01-05 07:24:36 +00:00
private static ImmutableArray<TransformedShape2D<TShape2D>>.Builder _builder = ImmutableArray.CreateBuilder<TransformedShape2D<TShape2D>>();
private ImmutableArray<TransformedShape2D<TShape2D>> _transformedShapes;
public IEnumerable<TransformedShape2D<TShape2D>> TransformedShapes { get { return _transformedShapes; } }
2020-01-05 00:13:07 +00:00
public AABB AABB { get; }
2020-01-05 07:24:36 +00:00
public MultiShape(ImmutableArray<(TShape2D, Transform2D)> shapeTransformPairs)
2020-01-05 00:13:07 +00:00
{
2020-01-05 07:24:36 +00:00
_builder.Clear();
foreach (var (shape, transform) in shapeTransformPairs)
{
_builder.Add(new TransformedShape2D<TShape2D>(shape, transform));
}
2020-01-05 00:13:07 +00:00
2020-01-05 07:24:36 +00:00
_transformedShapes = _builder.ToImmutable();
AABB = AABBFromShapes(_transformedShapes);
}
public MultiShape(ImmutableArray<TransformedShape2D<TShape2D>> transformedShapes)
{
_transformedShapes = transformedShapes;
AABB = AABBFromShapes(transformedShapes);
2020-01-05 00:13:07 +00:00
}
public AABB TransformedAABB(Transform2D transform)
{
return AABB.Transformed(AABB, transform);
}
2020-01-05 07:24:36 +00:00
public IEnumerable<TransformedShape2D<TShape2D>> Compose(Transform2D transform)
2020-01-05 00:13:07 +00:00
{
2020-01-05 07:24:36 +00:00
foreach (var transformedShape in TransformedShapes)
2020-01-05 00:13:07 +00:00
{
2020-01-05 07:24:36 +00:00
yield return transformedShape.Compose(transform);
2020-01-05 00:13:07 +00:00
}
}
2020-01-05 07:24:36 +00:00
private static AABB AABBFromShapes(IEnumerable<TransformedShape2D<TShape2D>> transformedShapes)
2020-01-05 00:13:07 +00:00
{
var minX = float.MaxValue;
var minY = float.MaxValue;
var maxX = float.MinValue;
var maxY = float.MinValue;
2020-01-05 07:24:36 +00:00
foreach (var transformedShape in transformedShapes)
2020-01-05 00:13:07 +00:00
{
2020-01-05 07:24:36 +00:00
var aabb = transformedShape.AABB;
2020-01-05 00:13:07 +00:00
if (aabb.Min.X < minX)
{
minX = aabb.Min.X;
}
if (aabb.Min.Y < minY)
{
minY = aabb.Min.Y;
}
if (aabb.Max.X > maxX)
{
maxX = aabb.Max.X;
}
if (aabb.Max.Y > maxY)
{
maxY = aabb.Max.Y;
}
}
return new AABB(minX, minY, maxX, maxY);
}
}
}