isPointInTriangle static method

bool isPointInTriangle(
  1. GPoint point,
  2. GPoint a,
  3. GPoint b,
  4. GPoint c,
)

Determines whether a given point is inside a triangle defined by three other points (a, b, c).

Implementation

static bool isPointInTriangle(GPoint point, GPoint a, GPoint b, GPoint c) {
  // This algorithm is described well in this article:
  // http://www.blackpawn.com/texts/pointinpoly/default.html
  var v0x = c.x - a.x;
  var v0y = c.y - a.y;
  var v1x = b.x - a.x;
  var v1y = b.y - a.y;
  var v2x = point.x - a.x;
  var v2y = point.y - a.y;

  var dot00 = v0x * v0x + v0y * v0y;
  var dot01 = v0x * v1x + v0y * v1y;
  var dot02 = v0x * v2x + v0y * v2y;
  var dot11 = v1x * v1x + v1y * v1y;
  var dot12 = v1x * v2x + v1y * v2y;

  final invDen = 1.0 / (dot00 * dot11 - dot01 * dot01);
  final u = (dot11 * dot02 - dot01 * dot12) * invDen;
  final v = (dot00 * dot12 - dot01 * dot02) * invDen;
  return (u >= 0) && (v >= 0) && (u + v < 1);
}