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 record Triangle(Vector2D A, Vector2D B, Vector2D C)
{ {
public float Area => MathF.Abs(( public float Area
A.X * (B.Y - C.Y) + => .5f * MathF.Abs(
B.X * (C.Y - A.Y) + A.X * (B.Y - C.Y) +
C.X * (A.Y - B.Y) B.X * (C.Y - A.Y) +
) * .5f); 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; 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));
Vector2D midBC = (B + C) / 2; float y = -(x - (triangle.A.X + triangle.B.X) / 2f) / slopeAB + (triangle.A.Y + triangle.B.Y) / 2f;
center = new Vector2D(x, y);
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));
} }
else
center = (midAB + midBC) * .5f;
return new(center, Vector2D.Distance(center, triangle.A));
} }
public bool Overlaps(Vector2D point) public static bool ApproximatelyEquals(Triangle left, Triangle right)
{ => left.A.ApproximatelyEquals(right.A) && left.B.ApproximatelyEquals(right.B) && left.C.ApproximatelyEquals(right.C);
float originalTriangleArea = Area; }
float pointTriangleArea1 = new Triangle(point, B, C).Area; public static class TriangleExtensions
float pointTriangleArea2 = new Triangle(A, point, C).Area; {
float pointTriangleArea3 = new Triangle(A, B, point).Area; public static bool ApproximatelyEquals(this Triangle left, Triangle right) => Triangle.ApproximatelyEquals(left, right);
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);
} }