Last active
February 26, 2022 03:12
-
-
Save lcpz/cab70d24899ec482fa62907fc075f129 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
struct Point { // 2-D | |
double x, y; | |
Point(double x, double y) : x(x), y(y) {} | |
}; | |
// Barycentric method - https://stackoverflow.com/a/9755252 | |
bool isInsideTriangle(const Point& a, const Point& b, const Point& c, const Point& s) | |
{ | |
// collinearity, (a, b, c) is not a triangle | |
if (a.x == b.x == c.x || a.y == b.y == c.y) | |
return false; | |
double as_x = s.x - a.x; | |
double as_y = s.y - a.y; | |
bool s_ab = (b.x - a.x) * as_y - (b.y - a.y) * as_x > 0; | |
if ((c.x - a.x) * as_y - (c.y - a.y) * as_x > 0 == s_ab) return false; | |
if ((c.x - b.x) * (s.y - b.y) - (c.y - b.y) * (s.x - b.x) > 0 != s_ab) return false; | |
return true; | |
} | |
int main() | |
{ | |
Point origin{0, 0}; | |
Point p1{-340, 495}; | |
Point p2{-153, -910}; | |
Point p3{835, -947}; | |
std::cout << std::boolalpha << isInsideTriangle(p1, p2, p3, origin) << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment