refactor: Triangle

This commit is contained in:
Syntriax 2024-01-23 19:15:43 +03:00
parent dcda78b010
commit 6a5d10980a
1 changed files with 29 additions and 39 deletions

View File

@ -6,49 +6,39 @@ namespace Syntriax.Engine.Physics2D.Primitives;
public record Triangle(Vector2D A, Vector2D B, Vector2D C)
{
public float Area => MathF.Abs((
A.X * (B.Y - C.Y) +
B.X * (C.Y - A.Y) +
C.X * (A.Y - B.Y)
) * .5f);
public float Area
=> .5f * MathF.Abs(
A.X * (B.Y - C.Y) +
B.X * (C.Y - A.Y) +
C.X * (A.Y - B.Y)
);
public Circle CircumCircle
public static Circle GetCircumCircle(Triangle triangle)
{
get
Vector2D midAB = (triangle.A + triangle.B) / 2f;
Vector2D midBC = (triangle.B + triangle.C) / 2f;
float slopeAB = (triangle.B.Y - triangle.A.Y) / (triangle.B.X - triangle.A.X);
float slopeBC = (triangle.C.Y - triangle.B.Y) / (triangle.C.X - triangle.B.X);
Vector2D center;
if (MathF.Abs(slopeAB - slopeBC) > float.Epsilon)
{
Vector2D midAB = (A + B) / 2;
Vector2D midBC = (B + C) / 2;
float slopeAB = (B.Y - A.Y) / (B.X - A.X);
float slopeBC = (C.Y - B.Y) / (C.X - B.X);
Vector2D center;
if (MathF.Abs(slopeAB - slopeBC) > float.Epsilon)
{
float x = (slopeAB * slopeBC * (A.Y - C.Y) + slopeBC * (A.X + B.X) - slopeAB * (B.X + C.X)) / (2 * (slopeBC - slopeAB));
float y = -(x - (A.X + B.X) / 2) / slopeAB + (A.Y + B.Y) / 2;
center = new Vector2D(x, y);
}
else
center = (midAB + midBC) * .5f;
return new(center, Vector2D.Distance(center, A));
float x = (slopeAB * slopeBC * (triangle.A.Y - triangle.C.Y) + slopeBC * (triangle.A.X + triangle.B.X) - slopeAB * (triangle.B.X + triangle.C.X)) / (2f * (slopeBC - slopeAB));
float y = -(x - (triangle.A.X + triangle.B.X) / 2f) / slopeAB + (triangle.A.Y + triangle.B.Y) / 2f;
center = new Vector2D(x, y);
}
else
center = (midAB + midBC) * .5f;
return new(center, Vector2D.Distance(center, triangle.A));
}
public bool Overlaps(Vector2D point)
{
float originalTriangleArea = Area;
float pointTriangleArea1 = new Triangle(point, B, C).Area;
float pointTriangleArea2 = new Triangle(A, point, C).Area;
float pointTriangleArea3 = new Triangle(A, B, point).Area;
float pointTriangleAreasSum = pointTriangleArea1 + pointTriangleArea2 + pointTriangleArea3;
return originalTriangleArea.ApproximatelyEquals(pointTriangleAreasSum, float.Epsilon * 3f);
}
public bool ApproximatelyEquals(Triangle other)
=> A.ApproximatelyEquals(other.A) && B.ApproximatelyEquals(other.B) && C.ApproximatelyEquals(other.C);
public static bool ApproximatelyEquals(Triangle left, Triangle right)
=> left.A.ApproximatelyEquals(right.A) && left.B.ApproximatelyEquals(right.B) && left.C.ApproximatelyEquals(right.C);
}
public static class TriangleExtensions
{
public static bool ApproximatelyEquals(this Triangle left, Triangle right) => Triangle.ApproximatelyEquals(left, right);
}