56 lines
2.4 KiB
C#

using System;
namespace Syntriax.Engine.Core;
[System.Diagnostics.DebuggerDisplay("A: {A.ToString(), nq}, B: {B.ToString(), nq}, B: {C.ToString(), nq}")]
public readonly struct Triangle(Vector2D A, Vector2D B, Vector2D C)
{
public readonly Vector2D A { get; init; } = A;
public readonly Vector2D B { get; init; } = B;
public readonly Vector2D C { get; init; } = C;
public readonly float Area
=> .5f * MathF.Abs(
A.X * (B.Y - C.Y) +
B.X * (C.Y - A.Y) +
C.X * (A.Y - B.Y)
);
public static Circle GetCircumCircle(Triangle triangle)
{
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)
{
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));
}
/// <summary>
/// Determines whether two <see cref="Triangle"/>s are approximately equal.
/// </summary>
/// <param name="left">The first <see cref="Triangle"/> to compare.</param>
/// <param name="right">The second <see cref="Triangle"/> to compare.</param>
/// <param name="epsilon">The epsilon range.</param>
/// <returns><c>true</c> if the <see cref="Triangle"/>s are approximately equal; otherwise, <c>false</c>.</returns>
public static bool ApproximatelyEquals(Triangle left, Triangle right, float epsilon = float.Epsilon)
=> left.A.ApproximatelyEquals(right.A, epsilon) && left.B.ApproximatelyEquals(right.B, epsilon) && left.C.ApproximatelyEquals(right.C, epsilon);
}
public static class TriangleExtensions
{
/// <inheritdoc cref="Triangle.ApproximatelyEquals(Triangle, Triangle, float)" />
public static bool ApproximatelyEquals(this Triangle left, Triangle right, float epsilon = float.Epsilon) => Triangle.ApproximatelyEquals(left, right, epsilon);
}