1998b4b0c551f66aaf12bb4e1e384c3bcadf5a11
[anneal.git] / src / edu / berkeley / qfat / Mesh.java
1 package edu.berkeley.qfat;
2 import java.awt.*;
3 import java.util.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6 import javax.media.opengl.*;
7 import javax.media.opengl.glu.*;
8 import edu.berkeley.qfat.geom.*;
9 import edu.berkeley.qfat.geom.HasBindingGroup;
10 import edu.wlu.cs.levy.CG.KDTree;
11 import edu.berkeley.qfat.geom.Point;
12 import com.infomatiq.jsi.IntProcedure;
13
14 // EDGES RUN COUNTER-CLOCKWISE
15
16 public class Mesh implements Iterable<Mesh.T> {
17
18     public static final float EPSILON = (float)0.0001;
19     public static final Random random = new Random();
20
21     private RTree<T>         triangles = new RTree<T>();
22     private PointSet<Vertex> vertices  = new PointSet<Vertex>();
23
24     public boolean option_wireframe    = false;
25     public boolean option_errorNormals = false;
26     public boolean option_selectable   = true;
27
28     public void render(GL gl, Matrix m) {
29         if (option_wireframe) {
30             gl.glDisable(GL.GL_LIGHTING);
31             gl.glBegin(GL.GL_LINES);
32             gl.glColor3f(1, 1, 1);
33             for (T t : this) {
34                 m.times(t.e1().p1.goodp).glVertex(gl);
35                 m.times(t.e1().p2.goodp).glVertex(gl);
36                 m.times(t.e2().p1.goodp).glVertex(gl);
37                 m.times(t.e2().p2.goodp).glVertex(gl);
38                 m.times(t.e3().p1.goodp).glVertex(gl);
39                 m.times(t.e3().p2.goodp).glVertex(gl);
40             }
41             gl.glEnd();
42             gl.glEnable(GL.GL_LIGHTING);
43             return;
44         }
45         for(T t : this) {
46             gl.glColor4f((float)(0.25+(0.05*t.color)),
47                          (float)(0.25+(0.05*t.color)),
48                          (float)(0.75+(0.05*t.color)),
49                          (float)0.3); 
50             /*
51             if (t.red) {
52             gl.glColor4f((float)(0.75+(0.05*t.color)),
53                          (float)(0.25+(0.05*t.color)),
54                          (float)(0.25+(0.05*t.color)),
55                          (float)0.3); 
56             }
57             */
58             t.glTriangle(gl, m);
59         }
60         if (option_errorNormals)
61             for(T t : this)
62                 for(Mesh.Vertex p : new Mesh.Vertex[] { t.v1(), t.v2(), t.v3() }) {
63                     if (p.ok) {
64                         gl.glBegin(GL.GL_LINES);
65                         gl.glColor3f(1, 1, 1);
66                         p.p.glVertex(gl);
67                         p.p.plus(p.norm().times((float)p.error()*10)).glVertex(gl);
68                         gl.glEnd();
69                     }
70                 }
71     }
72
73     public boolean immutableVertices;
74     public Mesh    error_against      = null;
75     public double  error              = 0;
76
77     public Mesh(boolean immutableVertices) { this.immutableVertices = immutableVertices; }
78
79     public void makeVerticesImmutable() { this.immutableVertices = true; }
80     public float error() { return (float)error; }
81
82     public int size() { return vertices.size(); }
83     public Iterable<Vertex> vertices() { return vertices; }
84     public Iterator<T> iterator() { return triangles.iterator(); }
85
86     public void rebindPoints() {
87         // unbind all points
88         for(Mesh.T t : this) {
89             t.v1().unbind();
90             t.v2().unbind();
91             t.v3().unbind();
92         }
93         // ask edges to re-implement their bindings
94         for(Mesh.T t : this) {
95             t.e1().dobind();
96             t.e2().dobind();
97             t.e3().dobind();
98         }
99         System.out.println("rebound!");
100     }
101
102     public void transform(Matrix m) {
103         ArrayList<Vertex> set = new ArrayList<Vertex>();
104         for(Vertex v : vertices) set.add(v);
105         for(Vertex v : set) v.transform(m.times(v.p), true, null);
106         for(Vertex v : set) v.goodp = v.p;
107     }
108
109     public void rebuild() { /*vertices.rebuild();*/ }
110     public Vec diagonal() { return vertices.diagonal(); }
111     public Point centroid() { return vertices.centroid(); }
112     public Vertex nearest(Point p) { return vertices.nearest(p); }
113
114     /** compute the volume of the mesh */
115     public float volume() {
116         double total = 0;
117         for(T t : this) {
118             double area = t.area();
119             Vec origin_to_centroid = new Vec(new Point(0, 0, 0), t.centroid());
120             boolean facingAway = t.norm().dot(origin_to_centroid) > 0;
121             double height = Math.abs(t.norm().dot(origin_to_centroid));
122             total += ((facingAway ? 1 : -1) * area * height) / 3.0;
123         }
124         return (float)total;
125     }
126
127
128     public void subdivide() {
129         for (Vertex v : vertices()) v.original = true;
130         HashSet<E> edges = new HashSet<E>();
131         HashSet<E> flip = new HashSet<E>();
132         HashSet<T> tris = new HashSet<T>();
133         int count = 0;
134         for (T t : this) {
135             tris.add(t);
136             edges.add(t.e1());
137             edges.add(t.e2());
138             edges.add(t.e3());
139             count++;
140         }
141         System.out.println("triangles="+count);
142         count = 0;
143         for(E e : edges) {
144             if (e.destroyed || e.shattered) continue;
145             e.shatter().edge = true;
146             for(E ex : (Iterable<E>)e.getBoundPeers()) {
147                 Vertex m = nearest(ex.midpoint());
148                 m.edge = true;
149                 E e3 = ex.p1.getE(m).next;
150                 if (e3.p2.original)
151                     flip.add(e3);
152             }
153         }
154
155         int i=0;
156
157         for(E e : flip) {
158             e.flip();
159             System.out.println("flip!");
160             i++;
161             //if (i>2) break;
162         }
163
164         System.out.println("count="+count);
165
166         /*
167         tris.clear();
168         for (T t : this) if (t.v1().edge && t.v2().edge && t.v3().edge) tris.add(t);
169         for (T t : tris)
170             t.shatter();
171         */
172
173         /*
174         for(Vertex v : verts) {
175             if (!v.face) continue;
176             v.move(v.recenter().minus(v.getPoint()), false);
177         }
178         */
179         /*
180         Queue<T> q = new LinkedList<T>();
181         OUTER: while(true) {
182             for (T t : this) {
183                 if (t.old) { t.shatter(); continue OUTER; }
184             }
185             break;
186         }
187         */
188
189         rebindPoints();
190         HashSet<Vertex> verts = new HashSet<Vertex>();
191         for(Vertex v : vertices()) verts.add(v);
192         for (Vertex v : verts)
193             v.clearWish();
194         for (Vertex v : verts) {
195             if (v.edge) {
196                 for(E e = v.e; e!=null; e=e.pair.next==v.e?null:e.pair.next) {
197                     if (e.p2.original) {
198                         v.wish(e.p2);
199                         v.wish(e.p2);
200                         v.wish(e.p2);
201                         v.wish(e.p2);
202                     }
203                 }
204                 for(E e = v.e; e!=null; e=e.pair.next==v.e?null:e.pair.next) {
205                     for(E e2 = e.p2.e; e2!=null; e2=e2.pair.next==e.p2.e?null:e2.pair.next) {
206                         if (e2.p2.original) {
207                             v.wish(e.p2);
208                         }
209                     }
210                 }
211             }
212         }
213         for (Vertex v : verts)
214             v.grantWish();
215
216     }
217
218     // Vertexices //////////////////////////////////////////////////////////////////////////////
219
220     /** a vertex in the mesh */
221     public final class Vertex extends HasQuadric implements Visitor {
222         public Point p, goodp;
223         public Point oldp;
224         E e;                // some edge *leaving* this point
225
226         public boolean original = false;
227         public boolean edge = false;
228         public boolean face = false;
229
230         private int wishes = 0;
231         private Point wish = Point.ZERO;
232         public void clearWish() { wishes = 0; wish = Point.ZERO; }
233         public void wish(HasPoint hp) {
234             Point p = hp.getPoint();
235             wishes++;
236             wish = new Point(wish.x+p.x, wish.y+p.y, wish.z+p.z);
237         }
238         public void grantWish() {
239             for(Vertex v : (Iterable<Vertex>)getBoundPeers()) {
240                 if (v==this) continue;
241                 Point p = this.getBindingMatrix(v).times(v.wish.minus(Point.ZERO).div(v.wishes).plus(Point.ZERO));
242                 wish = p.minus(Point.ZERO).times(v.wishes).plus(wish);
243                 wishes += v.wishes;
244                 v.clearWish();
245             }
246             if (wishes==0) return;
247             Vec d = wish.minus(Point.ZERO).div(wishes).plus(Point.ZERO).minus(getPoint());
248             move(d, false);
249             clearWish();
250         }
251
252         private boolean illegal = false;
253
254         public boolean visible = false;
255
256         public Point getPoint() { return p; }
257         public float error() { return olderror; }
258
259         private Vertex(Point p) {
260             this.p = p;
261             this.goodp = p;
262             this.oldp = p;
263             if (vertices.get(p) != null) throw new Error();
264             vertices.add(this);
265         }
266
267         public void reinsert() {
268             vertices.remove(this);
269             vertices.add(this);
270             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) e.t.reinsert();
271         }
272
273         // the average of all adjacent points
274         public Point recenter() {
275             int count = 0;
276             Vec vec = Vec.ZERO;
277             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
278                 vec = vec.plus(e.getOther(this).getPoint().minus(Point.ZERO));
279                 count++;
280             }
281             return Point.ZERO.plus(vec.div(count));
282         }
283
284         public float olderror = 0;
285         public void setError(float nerror) {
286             error -= olderror;
287             olderror = nerror;
288             error += olderror;
289         }
290
291         /*
292         public Vertex hack(GL gl, Point mouse) {
293             double dist = Double.MAX_VALUE;
294             Vertex cur = null;
295             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
296                 Vertex v = e.getOther(this);
297                 double dist2 = v.getPoint().glProject(gl).distance(mouse);
298                 if ((cur==null || dist2 < dist) && v.visible) {
299                     dist = dist2;
300                     cur = v;
301                 }
302             }
303             return cur;
304         }
305         */
306
307         public float averageTriangleArea() {
308             int count = 0;
309             float ret = 0;
310             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
311                 ret += e.t.area();
312                 count++;
313             }
314             return ret/count;
315         }
316         public float averageEdgeLength() {
317             int count = 0;
318             float ret = 0;
319             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
320                 ret += e.length();
321                 count++;
322             }
323             return ret/count;
324         }
325
326         public Matrix _recomputeFundamentalQuadric() {
327             Matrix m = Matrix.ZERO;
328             int count = 0;
329             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
330                 m = m.plus(e.t.norm().fundamentalQuadric(e.t.centroid()));
331                 count++;
332             }
333             if (count > 0) {
334                 m = m.plus(norm().fundamentalQuadric(this.p).times(count));
335                 count *= 2;
336             }
337             return m.times(1/(float)count);
338         }
339
340         public HasQuadric nearest() { return error_against==null ? null : error_against.vertices.nearest(p, this); }
341         public void computeError() {
342             if (error_against==null) return;
343             if (nearest_in_other_mesh == null && nearest()==null) return;
344             float nerror =
345                 nearest_in_other_mesh != null
346                 ? nearest_in_other_mesh.fundamentalQuadric().preAndPostMultiply(p)
347                 : nearest().fundamentalQuadric().preAndPostMultiply(p);
348             if (quadric_count != 0)
349                 nerror = (nerror + quadric.preAndPostMultiply(p))/(quadric_count+1);
350
351             if (!immutableVertices && quadric_count == 0) {
352                 //nerror = Math.max(nerror, 0.4f);
353                 //nerror *= 2;
354             }
355             //System.out.println(nerror);
356             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
357                 double ang = e.dihedralAngle();
358                 if (ang > Math.PI) throw new Error();
359                 if (ang < -Math.PI) throw new Error();
360                 float minangle = (float)(Math.PI * 0.8);
361                 //nerror += ((ang / Math.PI)*(ang/Math.PI)) * e.length() * 0.05;
362
363                 nerror += (1-e.t.quality())*0.0001;
364                 if (ang > minangle) nerror += (ang - minangle);
365
366                 //System.out.println(((ang / Math.PI)*(ang/Math.PI)) * 0.000001);
367                 /*
368                 if (e.t.aspect() < 0.2) {
369                     nerror += (0.2-e.t.aspect()) * 10;
370                 }
371                 */
372             }
373             if (!immutableVertices) {
374                 Vertex n = (Vertex)nearest();
375                 float d = norm().dot(n.norm());
376                 if (d > 1 || d < -1) throw new Error();
377                 if (d >= 0) {
378                     nerror *= (2.0f - d);
379                 } else {
380                     nerror += 0.0003 * (2.0f + d);
381                     nerror *= (2.0f + d);
382                 }
383             }
384
385             setError(nerror);
386         }
387
388         public boolean move(Vec vv, boolean ignoreProblems) {
389
390             boolean good = true;
391
392             //     t1' = M * t1
393             //     t2' = t2.getMatrix(t1) * t1'
394             //     t2' = t2.getMatrix(t1) * M * t1
395             //     t1 =     t1.getMatrix(t2) * t2
396             // M * t1 = M * t1.getMatrix(t2) * t2
397
398             if (bindingGroup!=null && this != bindingGroup.getMaster()) {
399                 Matrix m2 = getBindingMatrix(bindingGroup.getMaster());
400                 Vec v2 = m2.times(vv.plus(getPoint())).minus(m2.times(getPoint()));
401                 return ((Vertex)bindingGroup.getMaster()).move(v2, ignoreProblems);
402             }
403
404             Point op = this.p;
405             Point pp = vv.plus(getPoint());
406             if (bindingGroup != null) {
407                 /*
408                 for(int i=0; i<20 ; i++) {
409                     Point p2 = getConstraint().times(pp);
410                     pp = pp.midpoint(p2);
411                     //System.out.println(m.minus(m2));
412                 }
413             */
414                 //pp = getConstraint().times(pp);
415             }
416             //pp = pp.minus(op).norm().times(vv.mag()).plus(op);
417             ok = false;
418             Point pt = pp;
419             for(Vertex v : (Iterable<Vertex>)getBoundPeers()) {
420                 Point pt2 = v.getBindingMatrix(this).times(pt);
421                 /*
422                 if (Math.abs( v.p.minus(pt2).mag() / pt.minus(op).mag() ) > 5)
423                     throw new Error(v.p+" "+pt2+"\n"+op+" "+pt+"\n"+v.getBindingMatrix(this));
424                 if (Math.abs( v.p.minus(pt2).mag() / pt.minus(op).mag() ) < 1/5) throw new Error();
425                 */
426                 good &= v.transform(pt2, ignoreProblems, v.getBindingMatrix(this));
427             }
428
429             if (!good && !ignoreProblems) {
430                 for(Vertex v : (Iterable<Vertex>)getBoundPeers()) 
431                     v.transform(v.oldp, true, null);
432             }
433
434             for(Vertex v : (Iterable<Vertex>)getBoundPeers())
435                 v.recomputeFundamentalQuadricIfNeighborChanged();
436             for(Vertex v : (Iterable<Vertex>)getBoundPeers())
437                 v.reComputeErrorAround();
438             ok = true;
439             return good;
440         }
441         public boolean ok = true;
442
443         /** does NOT update bound pairs! */
444         private boolean transform(Point newp, boolean ignoreProblems, Matrix yes) {
445             this.oldp = this.p;
446             if (immutableVertices) throw new Error();
447
448             unApplyQuadricToNeighbor();
449
450             boolean illegalbefore = illegal;
451             illegal = false;
452             /*
453             if (this.p.minus(newp).mag() > 0.1 && !ignoreProblems) {
454                 try {
455                     throw new Exception(""+this.p.minus(newp).mag()+" "+ignoreProblems+" "+yes);
456                 } catch(Exception e) {
457                     e.printStackTrace();
458                 }
459                 illegal = true;
460             }
461             */
462
463             this.p = newp;
464             reinsert();
465             applyQuadricToNeighbor();
466
467             if (!ignoreProblems) {
468                 checkLegality();
469             }
470             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next)
471                 e.p2.quadricStale = true;
472             return !illegal || (illegalbefore && illegal);
473         } 
474
475         public void checkLegality() {
476             /*
477             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
478                 if (Math.abs(e.dihedralAngle()) > (Math.PI * 0.9) ||
479                     Math.abs(e.next.dihedralAngle()) > (Math.PI * 0.9)) illegal = true;
480                 if (e.t.aspect() < 0.2) illegal = true;
481             }
482             */
483             if (!illegal) triangles.range(oldp, this.p, (Visitor<T>)this);
484         }
485
486         public void reComputeErrorAround() {
487             reComputeError();
488             if (nearest_in_other_mesh != null)
489                 nearest_in_other_mesh.reComputeError();
490             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next)
491                 e.p2.reComputeError();
492         }
493
494         public boolean visit(Object o) {
495             if (o instanceof Vertex)
496                 return ((Vertex)o).e != null && ((Vertex)o).norm().dot(Vertex.this.norm()) >= 0;
497             T t = (T)o;
498             if (illegal) return false;
499             for(E e = Vertex.this.e; e!=null; e=e.pair.next==Vertex.this.e?null:e.pair.next) {
500                 if (!t.has(e.p1) && !t.has(e.p2) && e.intersects(t)) { illegal = true; }
501                 if (e.t != null) {
502                     if (!e.t.has(t.e1().p1) && !e.t.has(t.e1().p2) && t.e1().intersects(e.t)) { illegal = true; }
503                     if (!e.t.has(t.e2().p1) && !e.t.has(t.e2().p2) && t.e2().intersects(e.t)) { illegal = true; }
504                     if (!e.t.has(t.e3().p1) && !e.t.has(t.e3().p2) && t.e3().intersects(e.t)) { illegal = true; }
505                 }
506             }
507             return !illegal;
508         }
509
510         public E getEdge() { return e; }
511         public E getFreeIncident() {
512             E ret = getFreeIncident(e, e);
513             if (ret != null) return ret;
514             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next)
515                 System.out.println(e + " " + e.t);
516             throw new Error("unable to find free incident to " + this);
517         }
518
519         public E getFreeIncident(E start, E before) {
520             for(E e = start; e!=null; e=e.pair.next==before?null:e.pair.next)
521                 if (e.pair.p2 == this && e.pair.t == null && e.pair.next.t == null)
522                     return e.pair;
523             return null;
524         }
525
526         public E getE(Point p2) {
527             Vertex v = vertices.get(p2);
528             if (v==null) return null;
529             return getE(v);
530         }
531         public E getE(Vertex p2) {
532             if (this.e!=null && this!=this.e.p1 && this!=this.e.p2) throw new RuntimeException();
533             int i=0;
534             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next) {
535                 if (e.p1 == this && e.p2 == p2) return e;
536                 i++;
537                 e.sanity();
538                 if (e.destroyed) throw new RuntimeException("fark " + i + " " + e.prev + " " + (e.prev.next==e) + " " + e.prev.destroyed);
539             }
540             return null;
541         }
542
543         private void glNormal(GL gl) {
544             Vec norm = norm();
545             gl.glNormal3f(norm.x, norm.y, norm.z);
546         }
547         public Vec norm() {
548             Vec norm = new Vec(0, 0, 0);
549             for(E e = this.e; e!=null; e=e.pair.next==this.e?null:e.pair.next)
550                 if (e.t != null)
551                     norm = norm.plus(e.t.norm().times((float)e.prev.angle()));
552             return norm.norm();
553         }
554
555         public void bindTo(Vertex p) { bindTo(Matrix.ONE, p); }
556     }
557
558
559     /** [UNIQUE] an edge */
560     public final class E extends HasBindingGroup implements Comparable<E> {
561
562         public void sanity() {
563             if (destroyed) return;
564             if (pair!=null && (pair.p1!=p2 || pair.p2!=p1)) throw new RuntimeException();
565             if (next!=null && next.p1!=p2) throw new RuntimeException();
566             if (prev!=null && prev.p2!=p1) throw new RuntimeException();
567         }
568
569         public final Vertex p1, p2;
570         T t;     // triangle to our "left"
571         E prev;  // previous half-edge
572         E next;  // next half-edge
573         E pair;  // partner half-edge
574         boolean shattered = false;
575
576         public boolean intersects(T t) { return t.intersects(p1.p, p2.p); }
577
578         public Segment getSegment() { return new Segment(p1.getPoint(), p2.getPoint()); }
579
580         public void flip() {
581             // FIXME: coplanarity check needed
582             if (destroyed) return;
583             for (E e : (Iterable<E>)getBoundPeers()) {
584                 if (!e.pair.isBoundTo(pair)) throw new RuntimeException("cannot flip!");
585             }
586             Vertex v1 = t.getOtherVertex(this);
587             Vertex v2 = pair.t.getOtherVertex(pair);
588             destroy();
589             pair.destroy();
590             T t1 = newT(v1, v2, p2);
591             T t2 = newT(v2, v1, p1);
592             t1.e1().sanity();
593             t1.e2().sanity();
594             t1.e3().sanity();
595             t2.e1().sanity();
596             t2.e2().sanity();
597             t2.e3().sanity();
598
599             for (E e : (Iterable<E>)getBoundPeers()) {
600                 if (e==this) continue;
601                 if (e.destroyed) continue;
602                 Vertex v1e = e.t.getOtherVertex(e);
603                 Vertex v2e = e.pair.t.getOtherVertex(e.pair);
604                 e.destroy();
605                 e.pair.destroy();
606                 if (v1e.getE(v2e)!=null) throw new RuntimeException();
607                 newT(v1e, v2e, e.p2).red = true;
608                 newT(v2e, v1e, e.p1).red = true;
609                 v2e.getE(v1e).bindTo(e.getBindingMatrix(this), v1.getE(v2));
610                 v1e.getE(v2e).bindTo(e.pair.getBindingMatrix(this.pair), v2.getE(v1));
611             }
612
613         }
614
615         public void bindingGroupChanged(edu.berkeley.qfat.geom.BindingGroup newBindingGroup_) {
616
617             edu.berkeley.qfat.geom.BindingGroup<E> newBindingGroup =
618                 (edu.berkeley.qfat.geom.BindingGroup<E>)newBindingGroup_;
619             if (newBindingGroup==null) return;
620             if (this==newBindingGroup.getMaster()) return;
621             HashSet<E> nbg = new HashSet<E>();
622             for(E eother : (Iterable<E>)newBindingGroup) nbg.add(eother);
623             for(E eother : nbg) {
624                 if (next==null || prev==null) continue;
625                 if (eother.next==null || eother.prev==null) continue;
626
627                 if (next.isBoundTo(eother.pair.prev.pair) && !prev.isBoundTo(eother.pair.next.pair))
628                     prev.bindTo(next.getBindingMatrix(eother.pair.prev.pair), eother.pair.next.pair);
629                 if (!next.isBoundTo(eother.pair.prev.pair) && prev.isBoundTo(eother.pair.next.pair))
630                     next.bindTo(prev.getBindingMatrix(eother.pair.next.pair), eother.pair.prev.pair);
631
632                 /*
633                 if (next.isBoundTo(eother.prev) && !prev.isBoundTo(eother.next))
634                     prev.bindTo(next.getBindingMatrix(eother.prev), eother.next);
635                 if (!next.isBoundTo(eother.prev) && prev.isBoundTo(eother.next))
636                     next.bindTo(prev.getBindingMatrix(eother.next), eother.prev);
637                 */
638                 if (next.isBoundTo(eother.next) && !prev.isBoundTo(eother.prev))
639                     prev.bindTo(next.getBindingMatrix(eother.next), eother.prev);
640                 if (!next.isBoundTo(eother.next) && prev.isBoundTo(eother.prev))
641                     next.bindTo(prev.getBindingMatrix(eother.prev), eother.next);
642             }
643
644         }
645
646         public float stretchRatio() {
647             Vertex nearest = error_against.nearest(midpoint());
648             float nearest_distance = midpoint().distance(nearest.p);
649             float other_distance =
650                 (p1.p.distance(error_against.nearest(p1.p).p)+
651                  p2.p.distance(error_against.nearest(p2.p).p))/2;
652             return nearest_distance/other_distance;
653         }
654         public float comparator() {
655             return length();
656         }
657         public int compareTo(E e) {
658             return e.comparator() > comparator() ? 1 : -1;
659         }
660         public void bindEdge(E e, Matrix m) {
661             _bindEdge(e, m);
662             pair._bindEdge(e.pair, m);
663         }
664         public void _bindEdge(E e, Matrix m) {
665             e = e.pair;
666             /*
667             //assumes edges are identical length at binding time
668             Vec reflectionPlaneNormal = e.p2.p.minus(e.p1.p).norm();
669             float a = reflectionPlaneNormal.x;
670             float b = reflectionPlaneNormal.y;
671             float c = reflectionPlaneNormal.z;
672             Matrix reflectionMatrix =
673                 new Matrix( 1-2*a*a,  -2*a*b,  -2*a*c, 0,
674                             -2*a*b,  1-2*b*b,  -2*b*c, 0,
675                             -2*a*c,   -2*b*c, 1-2*c*c, 0,
676                             0,       0,       0,       1);
677             m = m.times(Matrix.translate(e.midpoint().minus(Point.ORIGIN))
678                         .times(reflectionMatrix)
679                         .times(Matrix.translate(Point.ORIGIN.minus(e.midpoint()))));
680             System.out.println(reflectionPlaneNormal);
681             System.out.println("  " + p1.p + " " + m.times(e.p1.p));
682             System.out.println("  " + p2.p + " " + m.times(e.p2.p));
683             */
684             /*
685             if (m.times(e.p1.p).minus(p1.p).mag() > EPSILON) throw new Error();
686             if (m.times(e.p2.p).minus(p2.p).mag() > EPSILON) throw new Error();
687             */
688             this.bindTo(m, e);
689         }
690         
691         public void dobind() {
692             for(E e : (Iterable<E>)getBoundPeers()) {
693                 if (e==this) continue;
694                 p1.bindTo(getBindingMatrix(e), e.p1);
695                 p2.bindTo(getBindingMatrix(e), e.p2);
696                 e.p1.setConstraint(getConstraint());
697                 e.p2.setConstraint(getConstraint());
698             }
699         }
700
701         public Vertex shatter() {
702             if (shattered || destroyed) return nearest(midpoint());
703             shattered = true;
704             E first = null;
705             E firste = null;
706             E firstx = null;
707             E firstq = null;
708             for(E e : (Iterable<E>)getBoundPeers()) {
709                 E enext = e.next;
710                 E eprev = e.prev;
711                 E pnext = e.pair.next;
712                 E pprev = e.pair.prev;
713                 Point mid = e.midpoint();
714                 Vertex r = e.next.p2;
715                 Vertex l = e.pair.next.p2;
716                 if (!e.destroyed) {
717                     e.destroy();
718                     e.pair.destroy();
719                     newT(r.p, e.p1.p, mid,    null, 0);
720                     newT(r.p, mid,    e.p2.p, null, 0);
721                     newT(l.p, mid,    e.p1.p, null, 0);
722                     newT(l.p, e.p2.p, mid,    null, 0);
723                 }
724             }
725             for(E e : (Iterable<E>)getBoundPeers()) {
726                 Point mid = e.midpoint();
727                 if (first==null) {
728                     first = e.p1.getE(mid);
729                     firste = e;
730                     firstx = e.pair;
731                     firstq = e.p2.getE(mid).pair;
732                     continue;
733                 }
734                 e.p1.getE(mid).          bindTo(e.getBindingMatrix(firste), first);
735                 e.p1.getE(mid).pair.     bindTo(e.getBindingMatrix(firste), first.pair);
736                 e.p2.getE(mid).pair.     bindTo(e.getBindingMatrix(firste), firstq);
737                 e.p2.getE(mid).pair.pair.bindTo(e.getBindingMatrix(firste), firstq.pair);
738             }
739             /*
740             first.setConstraint(firste.getConstraint());
741             firstq.setConstraint(firste.getConstraint());
742             */
743             return nearest(midpoint());
744         }
745
746         public boolean destroyed = false;
747         public void destroy() {
748             if (destroyed) return;
749             destroyed = true;
750             pair.destroyed = true;
751
752             if (t != null) t.destroy();
753             t = null;
754
755             if (pair.t != null) pair.t.destroy();
756             pair.t = null;
757
758             if (next.t != null) next.t.destroy();
759             if (prev.t != null) prev.t.destroy();
760             next.t = null;
761             prev.t = null;
762
763             if (pair.next.t != null) pair.next.t.destroy();
764             if (pair.prev.t != null) pair.next.t.destroy();
765             pair.next.t = null;
766             pair.prev.t = null;
767
768             pair.prev.next = next;
769             next.prev = pair.prev;
770             prev.next = pair.next;
771             pair.next.prev = prev;
772
773             if (p1.e == this) p1.e = pair.next;
774             if (pair.p1.e == pair) pair.p1.e = next;
775
776             if (p2.e == this) throw new RuntimeException();
777             if (pair.p2.e == pair) throw new RuntimeException();
778
779             /*
780             next = pair;
781             prev = pair;
782             pair.next = this;
783             pair.prev = this;
784             */
785
786             /*
787             pair.prev = null;
788             pair.next = null;
789             next = null;
790             prev = null;
791             */
792
793             /*
794             sanity();
795             next.sanity();
796             prev.sanity();
797             pair.sanity();
798             */
799         }
800
801         private void sync() {
802             this.prev.next = this;
803             this.next.prev = this;
804             this.pair.pair = this;
805             if (this.next.p1 != p2) throw new Error();
806             if (this.prev.p2 != p1) throw new Error();
807             if (this.p1.e == null) this.p1.e = this;
808             if (!added) added = true;
809         }
810         private boolean added = false;
811
812         public T makeT(int colorclass) { return t==null ? (t = new T(this, colorclass)) : t; }
813
814         public double dihedralAngle() {
815             Vec v1 = t.norm().times(-1);
816             Vec v2 = pair.t.norm().times(-1);
817             double prod = v1.norm().dot(v2.norm());
818             prod = Math.min(1,prod);
819             prod = Math.max(-1,prod);
820             double ret = Math.acos(prod);
821             if (Double.isNaN(ret)) throw new Error("nan! " + prod);
822             return ret;
823         }
824
825         /** angle between this half-edge and the next */
826         public double angle() {
827             Vec v1 = next.p2.p.minus(p2.p);
828             Vec v2 = this.p1.p.minus(p2.p);
829             return Math.acos(v1.norm().dot(v2.norm()));
830         }
831
832         public Vertex getOther(Vertex v) {
833             if (this.p1 == v) return p2;
834             if (this.p2 == v) return p1;
835             throw new Error();
836         }
837
838         public void makeAdjacent(E e) {
839             if (this.next == e) return;
840             if (p2 != e.p1) throw new Error("cannot make adjacent -- no shared vertex: " + this + " " + e);
841             if (t != null || e.t != null) throw new Error("cannot make adjacent -- edges not both free " + t + " " + e.t);
842
843             E freeIncident = p2.getFreeIncident(e, this);
844
845             e.prev.next = freeIncident.next;
846             freeIncident.next.prev = e.prev;
847
848             freeIncident.next = this.next;
849             this.next.prev = freeIncident;
850             
851             this.next = e;
852             e.prev = this;
853
854             sync();
855             freeIncident.sync();
856         }
857
858         /** creates an isolated edge out in the middle of space */
859         public E(Point p1, Point p2) {
860             if (vertices.get(p1) != null) throw new Error();
861             if (vertices.get(p2) != null) throw new Error();
862             this.p1 = new Vertex(p1);
863             this.p2 = new Vertex(p2);
864             this.prev = this.next = this.pair = new E(this, this, this);
865             this.p1.e = this;
866             this.p2.e = this.pair;
867             sync();
868         }
869
870         /** adds a new half-edge from prev.p2 to p2 */
871         public E(E prev, Point p) {
872             Vertex p2;
873             p2 = vertices.get(p);
874             if (p2 == null) p2 = new Vertex(p);
875             this.p1 = prev.p2;
876             this.p2 = p2;
877             this.prev = prev;
878             if (prev.destroyed) throw new RuntimeException();
879             if (p2.getE(p1) != null) throw new Error();
880             if (p2.e==null) {
881                 this.next = this.pair = new E(this, this, prev.next);
882             } else {
883                 E q = p2.getFreeIncident();
884                 this.next = q.next;
885                 this.next.prev = this;
886                 E z = prev.next;
887                 this.prev.next = this;
888                 this.pair = new E(q, this, z);
889             }
890             if (p2.e==null) p2.e = this.pair;
891             sync();
892         }
893
894         /** adds a new half-edge to the mesh with a given predecessor, successor, and pair */
895         public E(E prev, E pair, E next) {
896             this.p1 = prev.p2;
897             this.p2 = next.p1;
898             if (prev.destroyed) throw new RuntimeException();
899             this.prev = prev;
900             this.next = next;
901             this.pair = pair;
902             sync();
903         }
904         public Point midpoint() { return new Point((p1.p.x+p2.p.x)/2, (p1.p.y+p2.p.y)/2, (p1.p.z+p2.p.z)/2); }
905         public boolean has(Vertex v) { return v==p1 || v==p2; }
906         public float length() { return p1.p.minus(p2.p).mag(); }
907         public String toString() { return p1+"->"+p2; }
908
909     }
910
911     public E makeE(Point p1, Point p2) {
912         Vertex v1 = vertices.get(p1);
913         Vertex v2 = vertices.get(p2);
914         if (v1 != null && v2 != null) {
915             E e = v1.getE(v2);
916             if (e != null) return e;
917             e = v2.getE(v1);
918             if (e != null) return e;
919         }
920         if (v1 != null) return new E(v1.getFreeIncident(), p2);
921         if (v2 != null) return new E(v2.getFreeIncident(), p1).pair;
922         return new E(p1, p2);
923     }
924     public boolean coalesce = false;
925     private static float round(float f) {
926         return Math.round(f*1000)/1000f;
927     }
928     public T newT(HasPoint p1, HasPoint p2, HasPoint p3) {
929         return newT(p1.getPoint(), p2.getPoint(), p3.getPoint(), null, 0);
930     }
931     public T newT(Point p1, Point p2, Point p3, Vec norm, int colorclass) {
932         if (coalesce) {
933
934             for(Vertex v : vertices) { if (p1.distance(v.p) < EPSILON) { p1 = v.p; break; } }
935             for(Vertex v : vertices) { if (p2.distance(v.p) < EPSILON) { p2 = v.p; break; } }
936             for(Vertex v : vertices) { if (p3.distance(v.p) < EPSILON) { p3 = v.p; break; } }
937             /*
938             p1 = new Point(round(p1.x), round(p1.y), round(p1.z));
939             p2 = new Point(round(p2.x), round(p2.y), round(p2.z));
940             p3 = new Point(round(p3.x), round(p3.y), round(p3.z));
941             */
942         }
943         if (norm != null) {
944             Vec norm2 = p3.minus(p1).cross(p2.minus(p1));
945             float dot = norm.dot(norm2);
946             //if (Math.abs(dot) < EPointSILON) throw new Error("dot products within evertsilon of each other: "+norm+" "+norm2);
947             if (dot < 0) { Point p = p1; p1=p2; p2 = p; }
948         }
949         E e12 = makeE(p1, p2);
950         E e23 = makeE(p2, p3);
951         E e31 = makeE(p3, p1);
952         while(e12.next != e23 || e23.next != e31 || e31.next != e12) {
953             e12.makeAdjacent(e23);
954             e23.makeAdjacent(e31);
955             e31.makeAdjacent(e12);
956         }
957         T ret = e12.makeT(colorclass);
958         if (e12.t == null) throw new Error();
959         if (e23.t == null) throw new Error();
960         if (e31.t == null) throw new Error();
961         return ret;
962     }
963
964     private int max_serial = 0;
965     /** [UNIQUE] a triangle (face) */
966     public final class T extends Triangle {
967         public final E e1;
968         public final int color;
969         public final int colorclass;
970
971         public boolean red = false;
972         public boolean old = false;
973
974         public final int serial = max_serial++;
975         public boolean occluded;
976
977         public Point shatter() {
978             if (destroyed) return null;
979             E e = e1();
980             
981             HashSet<E> forward = new HashSet<E>();
982             HashSet<E> backward = new HashSet<E>();
983             HashSet<E> both = new HashSet<E>();
984
985             for(E eb : (Iterable<E>)e.getBoundPeers()) {
986                 if (eb==e) continue;
987                 if (eb.next.isBoundTo(e.next) && eb.prev.isBoundTo(e.prev)) {
988                     forward.add(eb);
989                     both.add(eb);
990                 }
991                 if (eb.pair.next.pair.isBoundTo(e.prev) && eb.pair.prev.pair.isBoundTo(e.next)) {
992                     backward.add(eb.pair);
993                     both.add(eb.pair);
994                 }
995             }
996
997             Vertex v1 = e.t.v1();
998             Vertex v2 = e.t.v2();
999             Vertex v3 = e.t.v3();
1000             Point c = e.t.centroid();
1001             E e_next = e.next;
1002             E e_prev = e.prev;
1003             e.t.destroy();
1004             newT(v1, v2, c);
1005             newT(c,  v2, v3);
1006             newT(v3, v1, c);
1007
1008             // FIXME: forward too
1009             for(E ex : backward) {
1010                 Vertex v1x = ex.t.v1();
1011                 Vertex v2x = ex.t.v2();
1012                 Vertex v3x = ex.t.v3();
1013                 Point cx = ex.t.centroid();
1014                 E ex_next = ex.next;
1015                 E ex_prev = ex.prev;
1016                 ex.t.destroy();
1017                 newT(v1x, v2x, cx);
1018                 newT(cx,  v2x, v3x);
1019                 newT(v3x, v1x, cx);
1020
1021                 // FIXME: i have no idea if this is right
1022                 e.next.bindTo(e.getBindingMatrix(ex.pair), ex.prev);
1023                 e.prev.bindTo(e.getBindingMatrix(ex.pair), ex.next);
1024                 e.next.pair.bindTo(e.getBindingMatrix(ex.pair), ex.prev.pair);
1025                 e.prev.pair.bindTo(e.getBindingMatrix(ex.pair), ex.next.pair);
1026
1027                 e_next.next.bindTo(e_next.getBindingMatrix(ex_prev.pair), ex_prev.prev.pair);
1028                 e_next.prev.bindTo(e_next.getBindingMatrix(ex_prev.pair), ex_prev.next.pair);
1029
1030                 e_prev.next.bindTo(e_prev.getBindingMatrix(ex_next.pair), ex_next.prev.pair);
1031                 e_prev.prev.bindTo(e_prev.getBindingMatrix(ex_next.pair), ex_next.next.pair);
1032             }
1033
1034             /*
1035
1036             E first = null;
1037             E firste = null;
1038             E firstx = null;
1039             E firstq = null;
1040             for(E e : (Iterable<E>)getBoundPeers()) {
1041                 E enext = e.next;
1042                 E eprev = e.prev;
1043                 E pnext = e.pair.next;
1044                 E pprev = e.pair.prev;
1045                 Point mid = e.midpoint();
1046                 Vertex r = e.next.p2;
1047                 Vertex l = e.pair.next.p2;
1048                 if (!e.destroyed) {
1049                     e.destroy();
1050                     e.pair.destroy();
1051                     newT(r.p, e.p1.p, mid,    null, 0);
1052                     newT(r.p, mid,    e.p2.p, null, 0);
1053                     newT(l.p, mid,    e.p1.p, null, 0);
1054                     newT(l.p, e.p2.p, mid,    null, 0);
1055                 }
1056             }
1057             for(E e : (Iterable<E>)getBoundPeers()) {
1058                 Point mid = e.midpoint();
1059                 if (first==null) {
1060                     first = e.p1.getE(mid);
1061                     firste = e;
1062                     firstx = e.pair;
1063                     firstq = e.p2.getE(mid).pair;
1064                     continue;
1065                 }
1066                 e.p1.getE(mid).          bindTo(e.getBindingMatrix(firste), first);
1067                 e.p1.getE(mid).pair.     bindTo(e.getBindingMatrix(firste), first.pair);
1068                 e.p2.getE(mid).pair.     bindTo(e.getBindingMatrix(firste), firstq);
1069                 e.p2.getE(mid).pair.pair.bindTo(e.getBindingMatrix(firste), firstq.pair);
1070             }
1071             */
1072             /*
1073             first.setConstraint(firste.getConstraint());
1074             firstq.setConstraint(firste.getConstraint());
1075             */
1076             return null;
1077         }
1078
1079
1080         T(E e1, int colorclass) {
1081             this.e1 = e1;
1082             E e2 = e1.next;
1083             E e3 = e2.next;
1084             if (e1==e2 || e1==e3) throw new Error();
1085             if (e3.next!=e1) throw new Error();
1086             if (e1.t!=null || e2.t!=null || e3.t!=null) throw new Error("non-manifold surface or disagreeing normals");
1087             e1.t = this;
1088             e1.next.t = this;
1089             e1.next.next.t = this;
1090
1091             // FIXME: check for sealed/watertight surface once construction is complete (and infer normal(s)?)
1092
1093             int color = Math.abs(random.nextInt());
1094             while(true) {
1095                 color = color % 4;
1096                 if (e1().pair.t != null && color == e1().pair.t.color) { color++; continue; }
1097                 if (e2().pair.t != null && color == e2().pair.t.color) { color++; continue; }
1098                 if (e3().pair.t != null && color == e3().pair.t.color) { color++; continue; }
1099                 break;
1100             }
1101             this.color = color;
1102             this.colorclass = colorclass;
1103             triangles.add(this);
1104         }
1105         public E e1() { return e1; }
1106         public E e2() { return e1.next; }
1107         public E e3() { return e1.prev; }
1108         public Vertex v1() { return e1.p1; }
1109         public Vertex v2() { return e1.p2; }
1110         public Vertex v3() { return e1.next.p2; }
1111         public Point p1() { return e1.p1.p; }
1112         public Point p2() { return e1.p2.p; }
1113         public Point p3() { return e1.next.p2.p; }
1114         public boolean hasE(E e) { return e1==e || e1.next==e || e1.prev==e; }
1115         public boolean has(Vertex v) { return v1()==v || v2()==v || v3()==v; }
1116
1117         public Vertex getOtherVertex(E e) {
1118             if (!hasE(e)) throw new RuntimeException();
1119             if (!e.has(v1())) return v1();
1120             if (!e.has(v2())) return v2();
1121             if (!e.has(v3())) return v3();
1122             throw new RuntimeException();
1123         }
1124
1125         public void removeFromRTree() { triangles.remove(this); }
1126         public void addToRTree() { triangles.insert(this); }
1127         public void destroy() {
1128             if (e1 != null) {
1129                 e1.t = null;
1130                 e1.next.t = null;
1131                 e1.prev.t = null;
1132             }
1133             triangles.remove(this);
1134             destroyed = true;
1135         }
1136         public void reinsert() { triangles.remove(this); triangles.add(this); }
1137
1138         private boolean destroyed = false;
1139         public boolean destroyed() { return destroyed; }
1140
1141         public boolean shouldBeDrawn() {
1142
1143             if (e1().bindingGroupSize() <= 1) return false;
1144             if (e2().bindingGroupSize() <= 1) return false;
1145             if (e3().bindingGroupSize() <= 1) return false;
1146
1147             return true;
1148         }
1149
1150         public void glTriangle(GL gl, Matrix m) {
1151             gl.glPushName(serial);
1152             gl.glBegin(GL.GL_TRIANGLES);
1153             glVertices(gl, m);
1154             gl.glEnd();
1155             gl.glPopName();
1156         }
1157
1158         /** issue gl.glVertex() for each of the triangle's points */
1159         public void glVertices(GL gl, Matrix m) {
1160             if (!shouldBeDrawn()) return;
1161             super.glVertices(gl, m);
1162         }
1163     }
1164 }