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