This repository has been archived by the owner on Sep 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Line.java
74 lines (60 loc) · 1.51 KB
/
Line.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.util.*;
public class Line {
public static final double EPS = 1e-6;
double a, b, c;
Point u, v;
ArrayList<Point> junctions;
public Line(Point p1, Point p2) {
u = p1;
v = p2;
if (Math.abs(p1.x - p2.x) < EPS) {
this.a = 1;
this.b = 0.0;
this.c = -p1.x;
} else {
this.a = -(double) (p1.y - p2.y) / (p1.x - p2.x);
this.b = 1.0;
this.c = -(double) (this.a * p1.x) - p1.y;
}
}
boolean parallel(Line l) {
return Math.abs(this.a - l.a) < EPS &&
Math.abs(this.b - l.b) < EPS;
}
boolean same(Line l) {
return this.parallel(l) && Math.abs(this.c - l.c) < EPS;
}
Point intersect(Line l) {
if (this.same(l)) return new Point();
if (this.parallel(l)) return null;
Point p = new Point();
p.x = (l.b * this.c - this.b * l.c) /
(l.a * this.b - this.a * l.b);
if (Math.abs(this.b) > EPS)
p.y = -(this.a * p.x + this.c);
else
p.y = -(l.a * p.x + l.c);
return p;
}
Point intersectSeg(Line l) {
Point p = this.intersect(l);
if (p == null)
return null;
else if (p.nanpt() && this.segOverlap(l))
return p;
else if (!p.nanpt() && this.pointOnSeg(p) && l.pointOnSeg(p))
return p;
else
return null;
}
boolean segOverlap(Line l) {
return this.pointOnSeg(l.u) || this.pointOnSeg(l.v) ||
l.pointOnSeg(u) || l.pointOnSeg(v);
}
boolean pointOnSeg(Point p) {
return (u.distSq(p) + p.distSq(v)) - u.distSq(v) < EPS;
}
public String toString() {
return String.format("Line through %s and %s", u.toString(), v.toString());
}
}