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