判断线段是否相交的函数和求直线交点的函数

来源:互联网 发布:网络棋牌有作弊器吗 编辑:程序博客网 时间:2024/05/19 03:18

// ToLineCrossPofloat.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"


#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

struct POINT
{
 int x;
 int y;
};
/*
判断两条线段是否相交(有交点)
*/
bool IsLineSegmentCross(POINT pFirst1, POINT pFirst2, POINT pSecond1, POINT pSecond2)
{
 //每个线段的两点都在另一个线段的左右不同侧,则能断定线段相交
 //公式对于向量(x1,y1)->(x2,y2),判断点(x3,y3)在向量的左边,右边,还是线上.
 //p=x1(y3-y2)+x2(y1-y3)+x3(y2-y1).p<0 左侧, p=0 线上, p>0 右侧
 long Linep1,Linep2;
 //判断pSecond1和pSecond2是否在pFirst1->pFirst2两侧
 Linep1 = pFirst1.x * (pSecond1.y - pFirst2.y) +
  pFirst2.x * (pFirst1.y - pSecond1.y) +
  pSecond1.x * (pFirst2.y - pFirst1.y);
 Linep2 = pFirst1.x * (pSecond2.y - pFirst2.y) +
  pFirst2.x * (pFirst1.y - pSecond2.y) +
  pSecond2.x * (pFirst2.y - pFirst1.y);
 if ( ((Linep1 ^ Linep2) >= 0 ) && !(Linep1==0 && Linep2==0))//符号位异或为0:pSecond1和pSecond2在pFirst1->pFirst2同侧
 {
  return false;
 }
 //判断pFirst1和pFirst2是否在pSecond1->pSecond2两侧
 Linep1 = pSecond1.x * (pFirst1.y - pSecond2.y) +
  pSecond2.x * (pSecond1.y - pFirst1.y) +
  pFirst1.x * (pSecond2.y - pSecond1.y);
 Linep2 = pSecond1.x * (pFirst2.y - pSecond2.y) +
  pSecond2.x * (pSecond1.y - pFirst2.y) +
  pFirst2.x * (pSecond2.y - pSecond1.y);
 if ( ((Linep1 ^ Linep2) >= 0 ) && !(Linep1==0 && Linep2==0))//符号位异或为0:pFirst1和pFirst2在pSecond1->pSecond2同侧
 {
  return false;
 }
 //否则判为相交
 return true;
}
/*
求两直线交点,前提是两条直线必须有交点
在相交的情况下,可以应付各种情况(垂直、系数等)
*/
POINT GetCrossPoint(POINT p1, POINT p2, POINT q1, POINT q2)
{
 //必须相交求出的才是线段的交点,但是下面的程序段是通用的
 assert(IsLineSegmentCross(p1,p2,q1,q2));
 /*根据两点式化为标准式,进而求线性方程组*/
 POINT crossPoint;
 long tempLeft,tempRight;
 //求x坐标
 tempLeft = (q2.x - q1.x) * (p1.y - p2.y) - (p2.x - p1.x) * (q1.y - q2.y);
 tempRight = (p1.y - q1.y) * (p2.x - p1.x) * (q2.x - q1.x) + q1.x * (q2.y - q1.y) * (p2.x - p1.x) - p1.x * (p2.y - p1.y) * (q2.x - q1.x);
 crossPoint.x =(int)( (double)tempRight / (double)tempLeft );
 //求y坐标 
 tempLeft = (p1.x - p2.x) * (q2.y - q1.y) - (p2.y - p1.y) * (q1.x - q2.x);
 tempRight = p2.y * (p1.x - p2.x) * (q2.y - q1.y) + (q2.x- p2.x) * (q2.y - q1.y) * (p1.y - p2.y) - q2.y * (q1.x - q2.x) * (p2.y - p1.y);
 crossPoint.y =(int)( (double)tempRight / (double)tempLeft );
 return crossPoint;
}
int main(void)
{
 POINT pointA,pointB,pointC,pointD;
 POINT pointCross;
 bool bCross(false);
 pointA.x = 0;pointA.y = 0;
 pointB.x = 0;pointB.y = 100;

 pointC.x = 350;pointC.y = 10;
 pointD.x = -10;pointD.y = 10;
 bCross = IsLineSegmentCross(pointA,pointB,pointC,pointD);
 if (bCross)
 {
  pointCross = GetCrossPoint(pointA,pointB,pointC,pointD);
  printf("交点坐标x=%d,y=%d/n",pointCross.x,pointCross.y);
 }
 else
 {
  printf("They are not crossed!");
 }
 return 0;
}