Find if a point is within a triangle.



Task

   Assume points are on a plane defined by (x, y) real number coordinates.
   Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC. 
   You may use any algorithm. 
   Bonus: explain why the algorithm you chose works.


Related tasks

   Determine_if_two_triangles_overlap


Also see

 Discussion of several methods. [[1]]
 Determine if a point is in a polygon [[2]]
 Triangle based coordinate systems [[3]]
 Wolfram entry [[4]]


func real Dot(W,X,Y,Z);         \Return the dot product of two 2D vectors
real W,X,Y,Z;                   \ (W-X) dot (Y-Z)
real WX(2), YZ(2);
[WX(0):= W(0)-X(0);  WX(1):= W(1)-X(1);
 YZ(0):= Y(0)-Z(0);  YZ(1):= Y(1)-Z(1);
return WX(0)*YZ(0) + WX(1)*YZ(1);
];
 
real A,B,C;                     \triangle
 
func PointInTri(P);             \Return 'true' if point P is inside triangle ABC
real P;
int  S0,S1,S2;          \signs
[S0:= Dot(P,A,B,A) >= 0.0;
 S1:= Dot(P,B,C,B) >= 0.0;
 S2:= Dot(P,C,A,C) >= 0.0;
return S0=S1 & S1=S2 & S2=S0;
];
 
[A:= [10.5, 6.3];  B:= [13.5, 3.6];  C:= [ 3.3, -1.6];
Text(0, if PointInTri([10.0, 3.0]) then "inside" else "outside");  CrLf(0);
Text(0, if PointInTri([-5.0,-2.2]) then "inside" else "outside");  CrLf(0);
Text(0, if PointInTri([10.5, 6.3]) then "inside" else "outside");  CrLf(0);
]