Skip to content

Commit 469272a

Browse files
committed
fix(simplifier): prevent near zero denominator
1 parent 4f96b62 commit 469272a

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

Runtime/MeshSimplifier.cs

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ public sealed class MeshSimplifier
6363
private const int TriangleEdgeCount = 3;
6464
private const int TriangleVertexCount = 3;
6565
private const double DoubleEpsilon = 1.0E-3;
66+
private const double DenomEpilson = 0.00000001;
6667
private static readonly int UVChannelCount = MeshUtils.UVChannelCount;
6768
#endregion
6869

@@ -574,17 +575,24 @@ private double CalculateError(ref Vertex vert0, ref Vertex vert1, out Vector3d r
574575
#region Calculate Barycentric Coordinates
575576
private static void CalculateBarycentricCoords(ref Vector3d point, ref Vector3d a, ref Vector3d b, ref Vector3d c, out Vector3 result)
576577
{
577-
Vector3 v0 = (Vector3)(b - a), v1 = (Vector3)(c - a), v2 = (Vector3)(point - a);
578-
float d00 = Vector3.Dot(v0, v0);
579-
float d01 = Vector3.Dot(v0, v1);
580-
float d11 = Vector3.Dot(v1, v1);
581-
float d20 = Vector3.Dot(v2, v0);
582-
float d21 = Vector3.Dot(v2, v1);
583-
float denom = d00 * d11 - d01 * d01;
584-
float v = (d11 * d20 - d01 * d21) / denom;
585-
float w = (d00 * d21 - d01 * d20) / denom;
586-
float u = 1f - v - w;
587-
result = new Vector3(u, v, w);
578+
Vector3d v0 = (b - a), v1 = (c - a), v2 = (point - a);
579+
double d00 = Vector3d.Dot(ref v0, ref v0);
580+
double d01 = Vector3d.Dot(ref v0, ref v1);
581+
double d11 = Vector3d.Dot(ref v1, ref v1);
582+
double d20 = Vector3d.Dot(ref v2, ref v0);
583+
double d21 = Vector3d.Dot(ref v2, ref v1);
584+
double denom = d00 * d11 - d01 * d01;
585+
586+
// Make sure the denominator is not too small to cause math problems
587+
if (Math.Abs(denom) < DenomEpilson)
588+
{
589+
denom = DenomEpilson;
590+
}
591+
592+
double v = (d11 * d20 - d01 * d21) / denom;
593+
double w = (d00 * d21 - d01 * d20) / denom;
594+
double u = 1.0 - v - w;
595+
result = new Vector3((float)u, (float)v, (float)w);
588596
}
589597
#endregion
590598

0 commit comments

Comments
 (0)