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