e2d3bc55e4ce6e43ca05ea9806eed137a4ad241e
[anneal.git] / src / edu / berkeley / qfat / geom / Polygon.java
1 package edu.berkeley.qfat.geom;
2 import javax.media.opengl.*;
3 import java.util.*;
4 import edu.berkeley.qfat.Mesh;
5
6 // FIXME: numerical stability issues galore
7 /** a planar, convex, possibly infinite/open polygon */
8 public final class Polygon {
9
10     public final Plane plane;
11     
12     private final HalfSpace[] halfSpaces;
13
14     public Polygon(Plane plane) { this(plane, new HalfSpace[0]); }
15
16     public Polygon(Plane plane, HalfSpace[] halfSpaces) {
17         this.plane = plane;
18         this.halfSpaces = halfSpaces;
19     }
20
21     public Polygon intersect(HalfSpace hs) {
22         HalfSpace[] newHalfSpaces = new HalfSpace[halfSpaces.length+1];
23         System.arraycopy(halfSpaces, 0, newHalfSpaces, 0, halfSpaces.length);
24         newHalfSpaces[newHalfSpaces.length-1] = hs;
25         return new Polygon(plane, newHalfSpaces);
26     }
27
28     public Triangle[] tesselate(Mesh mesh) {
29         // FIXME: check for closedness
30         // find a starting point
31         HashSet<Segment> segments = new HashSet<Segment>();
32         int i;
33         for(i=0; i<halfSpaces.length; i++) {
34             Point p1=null, p2=null;
35             for(int j=0; j<halfSpaces.length; j++) {
36                 if (i==j) continue;
37                 Point p = plane.intersect(halfSpaces[i], halfSpaces[j]);
38                 if (p==null) continue;
39                 for(int k=0; k<halfSpaces.length; k++) {
40                     if (i==k || j==k) continue;
41                     //if (!halfSpaces[k].contains(p)) { p = null; break; }
42                 }
43                 if (p!=null) {
44                     if (p1==null) p1 = p;
45                     else if (p2==null) { if (!p.equals(p1)) p2 = p; }
46                     else throw new Error();
47                 }
48             }
49             if (p1!=null && p2!=null) {
50                 System.out.println("new segment: " + p1 + " " + p2);
51                 segments.add(new Segment(p1, p2));
52             }
53         }
54         Vec cen = new Vec(0,0,0);
55         for(Segment s : segments)
56             cen = cen.plus(s.p1.minus(Point.ORIGIN)).plus(s.p2.minus(Point.ORIGIN));
57         Point centroid = Point.ORIGIN.plus(cen.times(1f/(2*segments.size())));
58         for(Segment s : segments) {
59             System.out.println("newt! " + s.p1 + " " + centroid + " " + s.p2 + " " + plane.norm.times(-1));
60             mesh.newT(s.p1, centroid, s.p2, plane.norm.times(-1), 0);
61         }
62         System.out.println("done");
63         return null;
64     }
65
66 }