MoonTools.Bonk/Bonk/Shapes/Polygon.cs

64 lines
1.9 KiB
C#
Raw Normal View History

2019-09-06 08:11:58 +00:00
using System;
using Microsoft.Xna.Framework;
using MoonTools.Core.Structs;
namespace MoonTools.Core.Bonk
{
2019-10-25 21:01:36 +00:00
/// <summary>
/// A Shape defined by an arbitrary collection of vertices. WARNING: Polygon must use an Array internally and therefore will create GC pressure.
/// </summary>
2019-09-06 08:11:58 +00:00
public struct Polygon : IShape2D, IEquatable<IShape2D>
{
public Position2D[] Vertices { get; private set; }
// vertices are local to the origin
public Polygon(params Position2D[] vertices)
{
Vertices = vertices;
}
public Vector2 Support(Vector2 direction, Transform2D transform)
{
var furthest = float.NegativeInfinity;
var furthestVertex = Vector2.Transform(Vertices[0], transform.TransformMatrix);
foreach (var vertex in Vertices)
{
2019-09-06 20:00:35 +00:00
var TransformedVertex = Vector2.Transform(vertex, transform.TransformMatrix);
var distance = Vector2.Dot(TransformedVertex, direction);
2019-09-06 08:11:58 +00:00
if (distance > furthest)
{
furthest = distance;
2019-09-06 20:00:35 +00:00
furthestVertex = TransformedVertex;
2019-09-06 08:11:58 +00:00
}
}
return furthestVertex;
}
public AABB AABB(Transform2D Transform2D)
{
2019-09-06 20:00:35 +00:00
return Bonk.AABB.FromTransformedVertices(Vertices, Transform2D);
2019-09-06 08:11:58 +00:00
}
public bool Equals(IShape2D other)
{
if (other is Polygon)
{
var otherPolygon = (Polygon)other;
if (Vertices.Length != otherPolygon.Vertices.Length) { return false; }
for (int i = 0; i < Vertices.Length; i++)
{
2019-10-25 21:01:36 +00:00
if (Vertices[i].ToVector2() != otherPolygon.Vertices[i].ToVector2()) { return false; }
2019-09-06 08:11:58 +00:00
}
return true;
}
return false;
}
}
}