1 package org.lcsim.spacegeom;
2
3
4
5
6
7
8
9
10
11 public class TwoSegment
12 {
13 private TwoSpacePoint _a;
14 private TwoSpacePoint _b;
15 private double _length;
16
17
18
19
20
21
22
23 public TwoSegment(TwoSpacePoint a, TwoSpacePoint b)
24 {
25 _a = a;
26 _b = b;
27 _length = TwoSpacePoint.distance(_a,_b);
28 }
29
30
31
32
33
34
35
36 public TwoSpacePoint startPoint()
37 {
38 return _a;
39 }
40
41
42
43
44
45
46
47 public TwoSpacePoint endPoint()
48 {
49 return _b;
50 }
51
52
53
54
55
56
57
58 public double length()
59 {
60 return _length;
61 }
62
63
64
65
66
67
68
69
70 public double minimumDistance(TwoSpacePoint p)
71 {
72 double u = ( ( ( p.x() - _a.x() ) * ( _b.x() - _a.x() ) ) +
73 ( ( p.y() - _a.y() ) * ( _b.y() - _a.y() ) ) )/(_length*_length);
74 double xint = ( _a.x() + u * (_b.x() - _a.x()) ) - p.x();
75 double yint = ( _a.y() + u * (_b.y() - _a.y()) ) - p.y();
76 double dist = Math.sqrt( xint*xint + yint*yint );
77 return dist;
78 }
79
80
81
82
83
84
85
86
87
88
89
90 public static TwoSpacePoint intersection(TwoSegment a, TwoSegment b)
91 {
92
93 double x1 = a.startPoint().x();
94 double y1 = a.startPoint().y();
95 double x2 = a.endPoint().x();
96 double y2 = a.endPoint().y();
97 double x3 = b.startPoint().x();
98 double y3 = b.startPoint().y();
99 double x4 = b.endPoint().x();
100 double y4 = b.endPoint().y();
101
102 double denom = (y4-y3)*(x2-x1)-(x4-x3)*(y2-y1);
103
104 if(denom==0) return null;
105
106 double numa = (x4-x3)*(y1-y3)-(y4-y3)*(x1-x3);
107
108 if(numa==0) return null;
109
110 double ua = numa/denom;
111
112 if(ua<0 || ua >1.) return null;
113
114 double numb = (x2-x1)*(y1-y3)-(y2-y1)*(x1-x3);
115 double ub = numb/denom;
116 if(ub<0 || ub >1.) return null;
117
118
119 double xend = x3+ub*(x4-x3);
120 double yend = y3+ub*(y4-y3);
121
122 return new CartesianTwoPoint(xend, yend);
123
124 }
125
126
127
128
129
130
131
132 public String toString()
133 {
134 return "TwoSegment from "+_a+" \n to "+_b +" \n length: "+_length;
135 }
136
137 }