算法描述,参考链接:
[https://blackpawn.com/texts/pointinpoly/default.html]
代码实现,C++:
// Is the point within the face?
// Adapted from http://www.blackpawn.com/texts/pointinpoly/default.html
bool is_inside(const Vec2& point, const Face* f) {
Vec3 bary = get_barycentric_coords(point, f);
//printf("UV: %f, %f\n", u, v);
// Check if point is in triangle
// 10*epsilon: want to be robust for borders
return ((bary[0] >= -10*EPSILON) && (bary[1] >= -10*EPSILON) && (bary[2] >= -100*EPSILON));
}
Vec3 get_barycentric_coords(const Vec2& point, const Face* f) {
// Compute vectors
Vec2 v0 = f->v[0]->u - f->v[2]->u;
Vec2 v1 = f->v[1]->u - f->v[2]->u;
Vec2 v2 = point - f->v[2]->u;
// Compute dot products
double dot00 = dot(v0, v0);
double dot01 = dot(v0, v1);
double dot02 = dot(v0, v2);
double dot11 = dot(v1, v1);
double dot12 = dot(v1, v2);
// Compute barycentric coordinates
double invDenom = 1.f / (dot00 * dot11 - dot01 * dot01);
double u = (dot11 * dot02 - dot01 * dot12) * invDenom;
double v = (dot00 * dot12 - dot01 * dot02) * invDenom;
return Vec3(u,v,1-u-v);
}
什么是重心坐标,参考:
重心坐标(Barycentric coordinates)