a4dd2a09b5eb2e5bad23f30603ac68b7c77eb8d9
[anneal.git] / src / edu / berkeley / qfat / geom / Line.java
1 package edu.berkeley.qfat.geom;
2 import javax.media.opengl.*;
3
4 /** an infinitely long line in 3-space */
5 public class Line implements AffineConstraint {
6
7     // y=mx+c
8     // z=nx+d
9     public final float m, n, c, d;
10
11     /** the line passing through two points */
12     public Line(Point p1, Point p2) {
13         this.m = (p2.y-p1.y)/(p2.x-p1.x);
14         this.n = (p2.z-p1.z)/(p2.x-p1.x);
15         this.c = p1.y - m * p1.x;
16         this.d = p1.z - n * p1.x;
17     }
18
19     public int hashCode() {
20         return
21             Float.floatToIntBits(m) ^
22             Float.floatToIntBits(n) ^
23             Float.floatToIntBits(c) ^
24             Float.floatToIntBits(d);
25     }
26     public boolean equals(Object o) {
27         if (o==null || !(o instanceof Line)) return false;
28         Line line = (Line)o;
29         return line.m==m && line.n==n && line.c==c && line.d==d;
30     }
31
32     public String toString() {
33         return "[line: y="+m+"x+"+c+" z="+n+"x+"+d+"]";
34     }
35
36     public double distance(Point p) { return getProjection(p).distance(p); }
37
38     public Vec getUnit() {
39         Point p1 = new Point(0, c,   d);
40         Point p2 = new Point(1, m+c, n+d);
41         return p2.minus(p1).norm();
42     }
43
44     /** returns the point on this line which is closest to p */
45     public Point getProjection(Point p) {
46         /*
47         Point p1 = new Point(0, c,   d);
48         Point p2 = new Point(1, m+c, n+d);
49         Vec w = p.minus(p1);
50         return getUnit().times(w.dot(getUnit()));
51         */
52         throw new RuntimeException("test this before using; may not be correct");
53     }
54
55     public AffineConstraint intersect(AffineConstraint con, float epsilon) {
56         if (!(con instanceof Line)) return con.intersect(this, epsilon);
57         Line line = (Line)con;
58         if (Math.abs(this.m-line.m) <= epsilon &&
59             Math.abs(this.n-line.n) <= epsilon &&
60             Math.abs(this.c-line.c) <= epsilon &&
61             Math.abs(this.d-line.d) <= epsilon)
62             return this;
63         float x = (line.c-this.c)/(this.m-line.m);
64         if (Math.abs( (m*x+c)-(line.m*x+line.c) ) > epsilon ) return null;
65         if (Math.abs( (n*x+d)-(line.n*x+line.d) ) > epsilon ) return null;
66         return new Point(x, m*x+c, n*x+d);
67     }
68
69     public AffineConstraint multiply(Matrix m) {
70         throw new RuntimeException("not yet implemented");
71     }
72
73 }