#include <iostream>
/*
Simple 2D point structure
*/
struct fPoint {
float x, y;
};
/*
edgeOrientation(p1, p2, p3)
---------------------------
Computes the 2D cross product of vectors:
(p1 - p3) × (p2 - p3)
The sign of this value tells us whether p1 lies to the left or right
of the directed edge p3 → p2.
This is the core of the "same-side" triangle test.
*/
float edgeOrientation(fPoint p1, fPoint p2, fPoint p3) {
return (p1.x - p3.x) * (p2.y - p3.y)
- (p2.x - p3.x) * (p1.y - p3.y);
}
/*
PointInTriangle(pt, v1, v2, v3)
--------------------------------
Uses the same-side method:
A point is inside the triangle if it lies on the same side of all
three edges. If the signs of the three cross products are all
non-negative or all non-positive, the point is inside or on the edge.
If the signs mix (some positive, some negative), the point is outside.
*/
bool PointInTriangle(fPoint pt, fPoint v1, fPoint v2, fPoint v3) {
float d1 = edgeOrientation(pt, v1, v2);
float d2 = edgeOrientation(pt, v2, v3);
float d3 = edgeOrientation(pt, v3, v1);
bool has_negative = (d1 < 0) || (d2 < 0) || (d3 < 0);
bool has_positive = (d1 > 0) || (d2 > 0) || (d3 > 0);
// Inside if NOT both negative and positive signs
return !(has_negative && has_positive);
}
int main() {
// Triangle vertices
fPoint A{0.0f, 0.0f};
fPoint B{5.0f, 0.0f};
fPoint C{2.5f, 5.0f};
// Test point
fPoint P{2.5f, 2.0f};
bool inside = PointInTriangle(P, A, B, C);
std::cout << "Point (" << P.x << ", " << P.y << ") is "
<< (inside ? "inside" : "outside")
<< " the triangle.\n";
}
/*
run:
Point (2.5, 2) is inside the triangle.
*/