欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

点-线,线-线

程序员文章站 2024-03-15 10:52:11
...

直线的参数表示 P=p+t*v

///直线相交,求两条直线的交点
///调用前需保证两直线有唯一的交点,且不重合
Vector GetLineIntersection(Point p,Vector v,Point q,Vector w)
{
    Vector u=p-q;
    double t=Cross(w,u)/Cross(v,w);
    return p+v*t;
}
///点到直线的距离
///用叉积求三角形面积
double  DistanceToLine(Point p,Point a,Point b)
{
    Vector v1=b-a;
    Vector v2=p-a;
    return fabs(Cross(v1,v2))/Length(v1);
}

///点到线段的最短距离,注意分情况
double DistanceToSegment(Point p,Point a,Point b)
{
    if(a==b) return Length(p-a);
    Vector v1=b-a,v2=p-a,v3=p-b;
    if(dcmp(Dot(v1,v2))<0) return Length(v2);
    if(dcmp(Dot(v1,v3))>0) return Length(v3);
    return fabs(Cross(v1,v2))/Length(v1);

}
///求点在直线上的投影点坐标
Point GetLine(Point p,Point a,Point b)
{
    Vector v=b-a;
    return a+v*(Dot(v,p-a)/Dot(v,v));
}
///判断线段相交
///充要条件:每条线段的端点都在另一条线段的两侧(叉积符号不同)
bool SegmentProperIntersection(Point a1,Point a2,Point b1,Point b2)
{
    double c1=Cross(a2-a1,b1-a1),c2=Cross(a2-a1,b2-a1);
    double c3=Cross(b2-b1,a1-b1),c4=Cross(b2-b1,a2-b1);
    return dcmp(c1)*dcmp(c2)<0&&dcmp(c3)*dcmp(c4)<0;
}
///判断点是否在线段上
bool OnSegment(Point p,Point a1,Point a2)
{
    return dcmp(Cross(a1-p,a2-p))==0&&dcmp(Dot(a1-p,a2-p))<0;
}
///求多边形面积
double PolyArea(Point *p,int n)
{
    double area=0;
    for(int i=1; i<n-1; i++)
        area+=Cross(p[i]-p[0],p[i+1]-p[0]);
    return area/2;
}