Skip to content

Avoid 0/0 in get_barycentric_ratio when every weight is zeroed - #17

Merged
komietty merged 1 commit into
komietty:mainfrom
joseph-x-li:fix-barycentric-nan
Oct 22, 2026
Merged

komietty merged 1 commit into
komietty:mainfrom
joseph-x-li:fix-barycentric-nan

Conversation

@joseph-x-li

Copy link
Copy Markdown
Contributor

Fixes #15.

When the weights' sum is zero or not finite, fall back to the nearest corner (weight 1
there, 0 elsewhere). That is still a valid interpolation (non-negative weights summing
to one), it's exact for values that are constant over the triangle, and for a point
that close to all three edges the triangle is effectively degenerate around it anyway.
Every other path is unchanged.

Adds a_point_near_all_three_edges_of_a_thin_triangle_gets_finite_weights to
src/values.rs, which returns NaN weights on main and passes with this change.

Diff (src/values.rs):

-        uvw /= uvw[0] + uvw[1] + uvw[2];
-        uvw
+        // Within `tol` of all three edge lines (a thin triangle at a coarse tolerance)
+        // every weight is zero; dividing would make every value NaN. Take the nearest
+        // corner instead, still a valid interpolation.
+        let sum = uvw[0] + uvw[1] + uvw[2];
+        if sum.abs() > Real::MIN_POSITIVE && sum.is_finite() {
+            uvw /= sum;
+            return uvw;
+        }
+        let d = [0, 1, 2].map(|i| (*v - pos[i]).length_squared());
+        let near = if d[0] <= d[1] && d[0] <= d[2] { 0 } else if d[1] <= d[2] { 1 } else { 2 };
+        uvw = Vec3::ZERO;
+        uvw[near] = 1.;
+        uvw

🤖 Generated with Claude Code

Each weight is zeroed when the point is within tol of that edge's line,
then the weights are divided by their sum. On a thin triangle a point can
be within tol of all three, so the sum is zero and every interpolated
value became NaN. Fall back to the nearest corner, still a valid
interpolation. Adds a unit test with such a triangle.

Fixes komietty#15

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@komietty

Copy link
Copy Markdown
Owner

LGTM.

@komietty
komietty merged commit 54fee6b into komietty:main Oct 22, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Interpolated vertex values become NaN when a point is within tol of all three edges of a thin triangle

2 participants