1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.util.geometry;
16
17
18
19
20
21
22 public class Line2D implements Shape2D {
23
24 private final double startX_;
25 private final double startY_;
26 private final double endX_;
27 private final double endY_;
28 private final boolean isVertical_;
29
30 private final double slope_;
31 private final double yIntercept_;
32
33
34
35
36
37
38
39 public Line2D(final Point2D start, final Point2D end) {
40 this(start.getX(), start.getY(), end.getX(), end.getY());
41 }
42
43
44
45
46
47
48
49
50
51 public Line2D(final double x1, final double y1, final double x2, final double y2) {
52 startX_ = x1;
53 startY_ = y1;
54 endX_ = x2;
55 endY_ = y2;
56
57 isVertical_ = Math.abs(startX_ - endX_) < EPSILON;
58 if (isVertical_) {
59 slope_ = Double.NaN;
60 yIntercept_ = Double.NaN;
61 }
62 else {
63
64 slope_ = (endY_ - startY_) / (endX_ - startX_);
65 yIntercept_ = startY_ - slope_ * startX_;
66 }
67 }
68
69
70
71
72
73
74
75
76 public Point2D intersect(final Line2D line) {
77 if (isVertical_ && line.isVertical_) {
78 return null;
79 }
80
81 if (isVertical_ && !line.isVertical_) {
82 final double intersectY = line.slope_ * startX_ + line.yIntercept_;
83 return new Point2D(startX_, intersectY);
84 }
85
86 if (!isVertical_ && line.isVertical_) {
87 final double intersectY = slope_ * line.startX_ + yIntercept_;
88 return new Point2D(line.startX_, intersectY);
89 }
90
91
92 if (Math.abs(slope_ - line.slope_) < EPSILON) {
93 return null;
94 }
95
96
97 final double intersectX = (line.yIntercept_ - yIntercept_) / (slope_ - line.slope_);
98
99 final double intersectY = slope_ * intersectX + yIntercept_;
100 return new Point2D(intersectX, intersectY);
101 }
102
103
104
105
106 @Override
107 public boolean contains(final double x, final double y) {
108 if (isVertical_) {
109 if (Math.abs(startX_ - x) > EPSILON) {
110 return false;
111 }
112 }
113 else {
114 final double testY = slope_ * x + yIntercept_;
115 if (Math.abs(y - testY) > EPSILON) {
116 return false;
117 }
118
119 if (x < startX_ && x < endX_
120 || (x > startX_ && x > endX_)) {
121 return false;
122 }
123 }
124
125 if (y < startY_ && y < endY_
126 || (y > startY_ && y > endY_)) {
127 return false;
128 }
129
130 return true;
131 }
132
133
134
135
136 @Override
137 public boolean isEmpty() {
138 return Math.abs(startX_ - endX_) < EPSILON && Math.abs(startY_ - endY_) < EPSILON;
139 }
140
141 @Override
142 public String toString() {
143 return "Line2D [ (" + startX_ + ", " + startY_ + "), (" + endX_ + ", " + endY_
144 + "), " + (isVertical_ ? "isVertical" : "y = " + slope_ + "*x + " + yIntercept_ + "]");
145 }
146 }