【计算几何】线段相交

1.快速排斥实验。

2.跨立实验。

3.计算交点。

 1 typedef struct Point
2 {
3     int x;
4     int y;
5 }Point;
6 //排斥实验
7 bool IsRectCross(const Point &p1,const Point &p2,const Point &q1,const Point &q2)
8 {
9     bool ret = min(p1.x,p2.x) <= max(q1.x,q2.x)    &&
10                 min(q1.x,q2.x) <= max(p1.x,p2.x) &&
11                 min(p1.y,p2.y) <= max(q1.y,q2.y) &&
12                 min(q1.y,q2.y) <= max(p1.y,p2.y);
13     return ret;
14 }
15 //跨立判断
16 bool IsLineSegmentCross(const Point &pFirst1,const Point &pFirst2,const Point &pSecond1,const Point &pSecond2)
17 {
18     long line1,line2;
19     line1 = pFirst1.x * (pSecond1.y - pFirst2.y) +
20         pFirst2.x * (pFirst1.y - pSecond1.y) +
21         pSecond1.x * (pFirst2.y - pFirst1.y);
22     line2 = pFirst1.x * (pSecond2.y - pFirst2.y) +
23         pFirst2.x * (pFirst1.y - pSecond2.y) +
24         pSecond2.x * (pFirst2.y - pFirst1.y);
25     if (((line1 ^ line2) >= 0) && !(line1 == 0 && line2 == 0))
26         return false;
27
28     line1 = pSecond1.x * (pFirst1.y - pSecond2.y) +
29         pSecond2.x * (pSecond1.y - pFirst1.y) +
30         pFirst1.x * (pSecond2.y - pSecond1.y);
31     line2 = pSecond1.x * (pFirst2.y - pSecond2.y) +
32         pSecond2.x * (pSecond1.y - pFirst2.y) +
33         pFirst2.x * (pSecond2.y - pSecond1.y);
34     if (((line1 ^ line2) >= 0) && !(line1 == 0 && line2 == 0))
35         return false;
36     return true;
37 }
38
39 bool GetCrossPoint(const Point &p1,const Point &p2,const Point &q1,const Point &q2,long &x,long &y)
40 {
41     if(IsRectCross(p1,p2,q1,q2))
42     {
43         if (IsLineSegmentCross(p1,p2,q1,q2))
44         {
45             //求交点
46             long tmpLeft,tmpRight;
47             tmpLeft = (q2.x - q1.x) * (p1.y - p2.y) - (p2.x - p1.x) * (q1.y - q2.y);
48             tmpRight = (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);
49
50             x = (int)((double)tmpRight/(double)tmpLeft);
51
52             tmpLeft = (p1.x - p2.x) * (q2.y - q1.y) - (p2.y - p1.y) * (q1.x - q2.x);
53             tmpRight = 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);
54             y = (int)((double)tmpRight/(double)tmpLeft);
55             return true;
56         }
57     }
58     return false;
59 }

posted @ 2013-08-01 17:09  一点心青  阅读(12771)  评论(0编辑  收藏