Advertisement

Barycentric Coordinate Calculation gives divide by zero

Started by January 07, 2015 07:55 AM
2 comments, last by Paradigm Shifter 10 years, 1 month ago

I just started reading through Real Time Collision Detection, and just got to the section on Barycentric Coordinates. I struggled a bit with getting the first the first example code for calculating the barycentric coordinates for u, v, and w, as my inputs for the method kept causing divide by zero errors, when both pairs of numbers on the Vector2s were the same number.

For example:

(1,1), (2,2), (3, 3), with (10, 10) being tested against.

I kept getting 0 for the denominator from the three Vector2s making up the triangle, for all the combinations I tried of Vector2s using the same number for both coordinates, and any Vector2 being tested against. It works perfectly in the unit tests for Vector2s that don't share the same values for their x and y coordinates.

How might I go about finding the denominator, in this case?


public static void Barycentric(Vector2 a, Vector2 b, Vector2 c,
Vector2 p, out float u, out float v, out float w)
{
    Vector2 v0 = b - a, v1 = c - a, v2 = p - a;
    float d00 = Vector2.Dot(v0, v0);
    float d01 = Vector2.Dot(v0, v1);
    float d11 = Vector2.Dot(v1, v1);
    float d20 = Vector2.Dot(v2, v0);
    float d21 = Vector2.Dot(v2, v1);
    float denom = d00 * d11 - d01 * d01;

    v = (d11 * d20 - d01 * d21) / denom;
    w = (d00 * d21 - d01 * d20) / denom;
    u = 1.0f - v - w;
}

You are getting zero in the denominator because the triangle is degenerate (it is a segment..).
Advertisement

Thanks, that was helpful. I wasn't visualizing those points correctly in my head. So, I'd pop a test in at the start of the method checking if the points make a line segment. What would I want to set them to in that case?

You should remove degenerate triangles from your triangle collision data when you export the data. If you need collision against lines have a separate container for them and do line vs. collision object tests as different functions.
"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

This topic is closed to new replies.

Advertisement