From 9e7d16b0a9727d9fd62274f0d98eb0dd0df13a4f Mon Sep 17 00:00:00 2001 From: Evan Hemsley <2342303+ehemsley@users.noreply.github.com> Date: Sun, 29 Dec 2019 22:54:21 -0800 Subject: [PATCH] optimize rectangle support function --- Bonk/Shapes/Rectangle.cs | 41 +++++++++++++++++++++++++++------------- 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/Bonk/Shapes/Rectangle.cs b/Bonk/Shapes/Rectangle.cs index ebf9a98..5433ecc 100644 --- a/Bonk/Shapes/Rectangle.cs +++ b/Bonk/Shapes/Rectangle.cs @@ -38,21 +38,36 @@ namespace MoonTools.Core.Bonk AABB = new AABB(minX, minY, maxX, maxY); } + private Vector2 Support(Vector2 direction) + { + if (direction.X >= 0 && direction.Y >= 0) + { + return new Vector2(MaxX, MaxY); + } + else if (direction.X >= 0 && direction.Y < 0) + { + return new Vector2(MaxX, MinY); + } + else if (direction.X < 0 && direction.Y >= 0) + { + return new Vector2(MinX, MaxY); + } + else if (direction.X < 0 && direction.Y < 0) + { + return new Vector2(MinX, MinY); + } + else + { + throw new ArgumentException("Support vector direction cannot be zero."); + } + } + public Vector2 Support(Vector2 direction, Transform2D transform) { - var maxDotProduct = float.NegativeInfinity; - var maxVertex = new Vector2(MinX, MinY); - foreach (var vertex in Vertices) - { - var transformed = Vector2.Transform(vertex, transform.TransformMatrix); - var dot = Vector2.Dot(transformed, direction); - if (dot > maxDotProduct) - { - maxVertex = transformed; - maxDotProduct = dot; - } - } - return maxVertex; + Matrix4x4 inverseTransform; + Matrix4x4.Invert(transform.TransformMatrix, out inverseTransform); + var inverseDirection = Vector2.TransformNormal(direction, inverseTransform); + return Vector2.Transform(Support(inverseDirection), transform.TransformMatrix); } public AABB TransformedAABB(Transform2D transform)