您的位置:首页 > 其它

基于boost实现点到线段的投影

2016-05-31 16:06 465 查看
该算法实现于boos中t的geomertry中,在distance算法函数中,其中的求点到线段的距离中用到了投影计算

其核心思想是:三角形的相似性,通过向量点乘,得到两个相似三角形的边的比值

/*
*brief: project one point onto a segment
*parma1: the point to be projected
*param2: the start point of segment
*param3: the end point of segment
*parma4: the projected point on the segment
*/
bool point_project_on_segment(point_t const & p, point_t const & p1, point_t const & p2, point_t & p_prj)
{
/*
Algorithm [p: (px,py), p1: (x1,y1), p2: (x2,y2)]
VECTOR v(x2 - x1, y2 - y1)
VECTOR w(px - x1, py - y1)
c1 = w . v
c2 = v . v
b = c1 / c2
RETURN POINT(x1 + b * vx, y1 + b * vy)
*/
point_t w, v, projected;
bg::convert(p2, v);
bg::convert(p, w);
bg::convert(p1, projected);

bg::subtract_point(v, projected);
bg::subtract_point(w, projected);

double const zero = 0;
double c1 = bg::dot_product(w, v);
if (c1 <= zero) {
return false;
}

double c2 = bg::dot_product(v, v);
if (c2 < c1) {
return false;
}

double b = c1 / c2;
bg::multiply_value(v, b);
bg::add_point(projected, v);

p_prj = projected;
return true;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: