c057f3319c5b9ebebb6dc1b0bb8b4e43a15e52d0
[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.wlu.cs.levy.CG.KDTree;
10 import edu.berkeley.qfat.geom.Point;
11
12 public class Mesh implements Iterable<Mesh.T> {
13
14     public static final float EPSILON = (float)0.0001;
15     public static final Random random = new Random();
16
17     private RTree<T> tris = new RTree<T>();
18     private PointSet<Vertex> vertices = new PointSet<Vertex>();
19
20     public boolean tilemesh = false;
21     public boolean ignorecollision = false;
22     public Mesh score_against = null;
23     public double score = 0;
24     public float score() { return (float)score; }
25
26     public int size() { return vertices.size(); }
27     public Iterable<Vertex> vertices() { return vertices; }
28
29     public Iterator<T> iterator() {
30         return tris.iterator();
31     }
32
33     public void rebindPoints() {
34         // unbind all points
35         for(Mesh.T t : this) {
36             t.v1().unbind();
37             t.v2().unbind();
38             t.v3().unbind();
39         }
40         // ask edges to re-implement their bindings
41         for(Mesh.T t : this) {
42             t.e1().dobind();
43             t.e2().dobind();
44             t.e3().dobind();
45         }
46     }
47
48     public void unApplyQuadricToNeighborAll() {
49         HashSet<Vertex> done = new HashSet<Vertex>();
50         for(T t : this)
51             for(Vertex p : new Vertex[] { t.v1(), t.v2(), t.v3() }) {
52                 if (done.contains(p)) continue;
53                 done.add(p);
54                 p.unApplyQuadricToNeighbor();
55             }
56     }
57     public void recomputeAllFundamentalQuadrics() {
58         HashSet<Vertex> done = new HashSet<Vertex>();
59         for(T t : this)
60             for(Vertex p : new Vertex[] { t.v1(), t.v2(), t.v3() }) {
61                 if (done.contains(p)) continue;
62                 done.add(p);
63                 p.recomputeFundamentalQuadric();
64             }
65     }
66     public float applyQuadricToNeighborAll() {
67         int num = 0;
68         double dist = 0;
69         HashSet<Vertex> done = new HashSet<Vertex>();
70         for(T t : this)
71             for(Vertex p : new Vertex[] { t.v1(), t.v2(), t.v3() }) {
72                 if (done.contains(p)) continue;
73                 done.add(p);
74                 p.applyQuadricToNeighbor();
75                 
76             }
77         return (float)(dist/num);
78     }
79
80     public void transform(Matrix m) {
81         ArrayList<Vertex> set = new ArrayList<Vertex>();
82         for(Vertex v : vertices) set.add(v);
83         for(Vertex v : set) v.transform(m);
84     }
85
86     public void rebuild() { /*vertices.rebuild();*/ }
87     public Vec diagonal() { return vertices.diagonal(); }
88     public Point centroid() { return vertices.centroid(); }
89     public Vertex nearest(Point p) { return vertices.nearest(p); }
90
91     /** compute the volume of the mesh */
92     public float volume() {
93         double total = 0;
94         for(T t : this) {
95             double area = t.area();
96             Vec origin_to_centroid = new Vec(new Point(0, 0, 0), t.centroid());
97             boolean facingAway = t.norm().dot(origin_to_centroid) > 0;
98             double height = Math.abs(t.norm().dot(origin_to_centroid));
99             total += ((facingAway ? 1 : -1) * area * height) / 3.0;
100         }
101         return (float)total;
102     }
103
104
105     // Vertexices //////////////////////////////////////////////////////////////////////////////
106
107     public final class Vertex extends HasPoint {
108         public String toString() { return p.toString(); }
109         public Point p;
110         E e;                // some edge *leaving* this point
111
112         /** the nearest vertex in the "score_against" mesh */
113         Vertex   nearest_in_other_mesh;
114         /** the number of vertices in the other mesh for which this is the nearest_in_other_mesh */
115         int    quadric_count;
116         /** the total error quadric (contributions from all vertices in other mesh for which this is nearest) */
117         Matrix quadric = Matrix.ZERO;
118
119         Vertex bound_to = this;
120         Matrix binding = Matrix.ONE;
121         float oldscore = 0;
122         boolean quadricStale = false;
123
124         public Matrix errorQuadric() { return quadric; }
125         public Point getPoint() { return p; }
126         public float score() { return oldscore; }
127
128         private Matrix fundamentalQuadric = null;
129         public Matrix fundamentalQuadric() {
130             if (fundamentalQuadric == null) recomputeFundamentalQuadric();
131             return fundamentalQuadric;
132         }
133
134         private Vertex(Point p) {
135             this.p = p;
136             if (vertices.get(p) != null) throw new Error();
137             vertices.add(this);
138         }
139
140         private void glNormal(GL gl) {
141             Vec norm = norm();
142             gl.glNormal3f(norm.x, norm.y, norm.z);
143         }
144
145         public void recomputeFundamentalQuadric() {
146             //if (!quadricStale && fundamentalQuadric != null) return;
147             quadricStale = false;
148             unApplyQuadricToNeighbor();
149             Matrix m = Matrix.ZERO;
150             E e = this.e;
151             int count = 0;
152             do {
153                 T t = e.t;
154                 m = m.plus(t.norm().fundamentalQuadric(t.centroid()));
155                 count++;
156                 e = e.pair.next;
157             } while(e != this.e);
158             fundamentalQuadric = m.times(1/(float)count);
159             applyQuadricToNeighbor();
160         }
161
162         public void unApplyQuadricToNeighbor() {
163             if (nearest_in_other_mesh == null) return;
164             if (fundamentalQuadric == null) return;
165             nearest_in_other_mesh.unComputeError();
166             nearest_in_other_mesh.quadric = nearest_in_other_mesh.quadric.minus(fundamentalQuadric);
167             nearest_in_other_mesh.quadric_count--;
168             if (nearest_in_other_mesh.quadric_count==0)
169                 nearest_in_other_mesh.quadric = Matrix.ZERO;
170             nearest_in_other_mesh.computeError();
171             nearest_in_other_mesh = null;
172         }
173
174         public void applyQuadricToNeighbor() {
175             if (score_against == null) return;
176
177             Vertex new_nearest = score_against.nearest(p);
178             if (nearest_in_other_mesh != null && new_nearest == nearest_in_other_mesh) return;
179
180             if (nearest_in_other_mesh != null) unApplyQuadricToNeighbor();
181             if (nearest_in_other_mesh != null) throw new Error();
182
183             nearest_in_other_mesh = new_nearest;
184                 
185             // don't attract to vertices that face the other way
186             if (nearest_in_other_mesh.e == null || nearest_in_other_mesh.norm().dot(norm()) < 0) {
187                 nearest_in_other_mesh = null;
188             } else {
189                 nearest_in_other_mesh.unComputeError();
190                 nearest_in_other_mesh.quadric = nearest_in_other_mesh.quadric.plus(fundamentalQuadric());
191                 nearest_in_other_mesh.quadric_count++;
192                 nearest_in_other_mesh.computeError();
193             }
194             reComputeError();
195         }
196
197         public void reComputeErrorAround() {
198             reComputeError();
199             if (nearest_in_other_mesh != null) nearest_in_other_mesh.reComputeError();
200             E e = this.e;
201             do {
202                 e.p2.reComputeError();
203                 e = e.pair.next;
204             } while (e != this.e);
205         }
206         public void reComputeError() {
207             unComputeError();
208             computeError();
209         }
210         public void unComputeError() {
211             score -= oldscore;
212             oldscore = 0;
213         }
214         public void computeError() {
215             if (quadric_count == 0) {
216                 if (!tilemesh) {
217                 } else if (nearest_in_other_mesh == null) {
218                     if (score_against != null) {
219                         Vertex ne = score_against.nearest(p);
220                         oldscore = ne.fundamentalQuadric().preAndPostMultiply(p) * 100 * 10;
221                     } else {
222                         oldscore = 0;
223                     }
224                 } else {
225                     oldscore = nearest_in_other_mesh.fundamentalQuadric().preAndPostMultiply(p) * 100 * 10;
226                 }
227             } else {
228                 oldscore = (quadric.preAndPostMultiply(p) * 100) / quadric_count;
229             }
230
231             oldscore = oldscore;
232
233             int numaspects = 0;
234             float aspects = 0;
235             E e = this.e;
236             do {
237                 //double ang = Math.abs(e.crossAngle());
238                 double ang = Math.abs(e.crossAngle());
239                 if (ang > Math.PI) throw new Error();
240                 /*
241                 if (e.t != null) {
242                     numaspects++;
243                     aspects += e.t.aspect()*e.t.aspect();
244                 }
245                 */
246
247                 float minangle = (float)(Math.PI * 0.8);
248                 if (ang > minangle)
249                     oldscore += (ang - minangle);
250
251                 e = e.pair.next;
252             } while (e != this.e);
253             if (numaspects > 0) oldscore += (aspects / numaspects);
254
255             //System.out.println(oldscore);
256             //oldscore = oldscore*oldscore;
257             score += oldscore;
258         }
259
260         private void removeTrianglesFromRTree() {
261             E e = this.e;
262             do {
263                 if (e.t != null) e.t.removeFromRTree();
264                 e = e.pair.next;
265             } while(e != this.e);
266         }
267         private void addTrianglesToRTree() {
268             E e = this.e;
269             do {
270                 if (e.t != null) e.t.addToRTree();
271                 e = e.pair.next;
272             } while(e != this.e);
273         }
274
275         /** does NOT update bound pairs! */
276         public boolean transform(Matrix m) {
277             unApplyQuadricToNeighbor();
278             Point oldp = this.p;
279             try {
280                 if (vertices.get(this.p)==null) throw new Error();
281                 vertices.remove(this);
282                 removeTrianglesFromRTree();
283                 float newx = m.a*p.x + m.b*p.y + m.c*p.z + m.d;
284                 float newy = m.e*p.x + m.f*p.y + m.g*p.z + m.h;
285                 float newz = m.i*p.x + m.j*p.y + m.k*p.z + m.l;
286                 this.p = new Point(newx, newy, newz);
287                 addTrianglesToRTree();
288                 vertices.add(this);
289             } catch (Exception e) {
290                 throw new RuntimeException(e);
291             }
292             applyQuadricToNeighbor();
293
294             // FIXME: intersection test needed?
295             good = true;
296
297             // should recompute fundamental quadrics of all vertices sharing a face, but we defer...
298             E e = this.e;
299             do {
300                 /*
301                 if (Math.abs(e.crossAngle()) > (Math.PI * 0.9) ||
302                     Math.abs(e.next.crossAngle()) > (Math.PI * 0.9)) {
303                     good = false;
304                 }
305                 if (e.t.aspect() < 0.1) {
306                     good = false;
307                 }
308                 */
309                 e.p2.quadricStale = true;
310                 e = e.pair.next;
311             } while(e != this.e);
312
313
314             if (!ignorecollision && good) {
315
316                 tris.range(new Segment(oldp, this.p),
317                             new Visitor<T>() {
318                                 public void visit(T t) {
319                                     if (!good) return;
320                                     E e = Vertex.this.e;
321                                     do {
322                                         if (!t.has(e.p1) && !t.has(e.p2) && e.intersects(t)) { good = false; }
323                                         if (e.t != null) {
324                                             if (!e.t.has(t.e1().p1) && !e.t.has(t.e1().p2) && t.e1().intersects(e.t)) { good = false; }
325                                             if (!e.t.has(t.e2().p1) && !e.t.has(t.e2().p2) && t.e2().intersects(e.t)) { good = false; }
326                                             if (!e.t.has(t.e3().p1) && !e.t.has(t.e3().p2) && t.e3().intersects(e.t)) { good = false; }
327                                         }
328                                         e = e.pair.next;
329                                     } while(e != Vertex.this.e);
330                                 }
331                             });
332
333                 /*
334                 for(T t : Mesh.this) {
335                     if (!good) break;
336                     e = this.e;
337                     do {
338                         if (!t.has(e.p1) && !t.has(e.p2) && e.intersects(t)) { good = false; break; }
339                         if (e.t != null) {
340                             if (!e.t.has(t.e1().p1) && !e.t.has(t.e1().p2) && t.e1().intersects(e.t)) { good = false; break; }
341                             if (!e.t.has(t.e2().p1) && !e.t.has(t.e2().p2) && t.e2().intersects(e.t)) { good = false; break; }
342                             if (!e.t.has(t.e3().p1) && !e.t.has(t.e3().p2) && t.e3().intersects(e.t)) { good = false; break; }
343                         }
344                         e = e.pair.next;
345                     } while(e != this.e);
346                 }
347                 */
348             }
349
350
351             reComputeErrorAround();
352             return good;
353         }
354         private boolean good;
355
356         public boolean move(Vec v) {
357             Matrix m = Matrix.translate(v);
358             Vertex p = this;
359             boolean good = true;
360             do {
361                 good &= p.transform(m);
362                 p = p.bound_to;
363             } while (p != this);
364             return good;
365         }
366
367         public E getFreeIncident() {
368             E ret = getFreeIncident(e, e);
369             if (ret != null) return ret;
370             ret = getFreeIncident(e.pair.next, e.pair.next);
371             if (ret == null) {
372                 E ex = e;
373                 do {
374                     System.out.println(ex + " " + ex.t);
375                     ex = ex.pair.next;
376                 } while (ex != e);
377                 throw new Error("unable to find free incident to " + this);
378             }
379             return ret;
380         }
381
382         public E getFreeIncident(E start, E before) {
383             E e = start;
384             do {
385                 if (e.pair.p2 == this && e.pair.t == null && e.pair.next.t == null) return e.pair;
386                 e = e.pair.next;
387             } while(e != before);
388             return null;
389         }
390
391         public E getE(Point p2) {
392             Vertex v = vertices.get(p2);
393             if (v==null) return null;
394             return getE(v);
395         }
396         public E getE(Vertex p2) {
397             E e = this.e;
398             do {
399                 if (e==null) return null;
400                 if (e.p1 == this && e.p2 == p2) return e;
401                 e = e.pair.next;
402             } while (e!=this.e);
403             return null;
404         }
405
406         public Vec norm() {
407             Vec norm = new Vec(0, 0, 0);
408             E e = this.e;
409             do {
410                 if (e.t != null) norm = norm.plus(e.t.norm().times((float)e.prev.angle()));
411                 e = e.pair.next;
412             } while(e != this.e);
413             return norm.norm();
414         }
415
416         public boolean isBoundTo(Vertex p) {
417             Vertex px = p;
418             do {
419                 if (px==this) return true;
420                 px = px.bound_to;
421             } while(px != p);
422             return false;
423         }
424         public void unbind() { bound_to = this; binding = Matrix.ONE; }
425         public void bind(Vertex p) { bind(p, Matrix.ONE); }
426         public void bind(Vertex p, Matrix binding) {
427             if (isBoundTo(p)) return;
428             Vertex temp_bound_to = p.bound_to;
429             Matrix temp_binding = p.binding;
430             p.bound_to = this.bound_to;
431             p.binding = binding.times(this.binding); // FIXME: may have order wrong here
432             this.bound_to = temp_bound_to;
433             this.binding = temp_binding.times(temp_binding); // FIXME: may have order wrong here
434         }
435     }
436
437     public class BindingGroup {
438         private HashSet<E> set = new HashSet<E>();
439         public BindingGroup bind_others;
440         public BindingGroup other() { return bind_others; }
441         public BindingGroup(BindingGroup bind_others) { this.bind_others = bind_others; }
442         public BindingGroup() { this.bind_others = new BindingGroup(this); }
443         public BindingGroup(E e) { this(); set.add(e); }
444         public void add(E e) {
445             if (set.contains(e)) return;
446             set.add(e);
447             BindingGroup e_bind_peers = e.bind_peers;
448             BindingGroup e_bind_to    = e.bind_to;
449             e.bind_peers = this;
450             e.bind_to    = bind_others;
451             for (E epeer  : e_bind_peers.set) add(epeer);
452             for (E eother : e_bind_to.set)    bind_others.add(eother);
453
454             for(E eother : bind_others.set) {
455                 if (e.next.bind_to.set.contains(eother.prev)) {
456                     e.next.next.bindEdge(eother.prev.prev);
457                 }
458                 if (e.prev.bind_to.set.contains(eother.next)) {
459                     e.prev.prev.bindEdge(eother.next.next);
460                 }
461             }
462
463         }
464         public void dobind(E e) {
465             for(E ebound : set) {
466                 e.p1.bind(ebound.p2);
467                 e.p2.bind(ebound.p1);
468             }
469         }
470         public void shatter(BindingGroup bg1, BindingGroup bg2) {
471             for(E e : set) {
472                 e.shatter(e.midpoint(), bg1, bg2);
473             }
474         }
475     }
476
477     /** [UNIQUE] an edge */
478     public final class E implements Comparable<E> {
479
480         public final Vertex p1, p2;
481         T t;     // triangle to our "left"
482         E prev;  // previous half-edge
483         E next;  // next half-edge
484         E pair;  // partner half-edge
485         public BindingGroup bind_peers  = new BindingGroup(this);
486         public BindingGroup bind_to     = bind_peers.other();
487         boolean shattered = false;
488
489         public boolean intersects(T t) { return t.intersects(p1.p, p2.p); }
490         public float comparator() {
491             Vertex nearest = score_against.nearest(midpoint());
492             //if (t==null) return length();
493             /*
494             double ang = Math.abs(crossAngle());
495             float minangle = (float)(Math.PI * 0.9);
496             if (ang > minangle)
497                 return 300;
498             */
499             /*
500             if ((length() * length()) / t.area() > 10)
501                 return (float)(length()*Math.sqrt(t.area()));
502             return length()*t.area();
503             */
504             return (float)Math.max(length(), midpoint().distance(nearest.p));
505             //return length();
506         }
507         public int compareTo(E e) {
508             return e.comparator() > comparator() ? 1 : -1;
509         }
510         public void bindEdge(E e) { bind_to.add(e); }
511         public void dobind() { bind_to.dobind(this); }
512
513         public Point shatter() { return shatter(midpoint(), null, null); }
514         public Point shatter(Point mid, BindingGroup bg1, BindingGroup bg2) {
515             if (shattered || destroyed) return mid;
516             shattered = true;
517
518             Vertex r = next.p2;
519             E next = this.next;
520             E prev = this.prev;
521
522             int old_colorclass = t==null ? 0 : t.colorclass;
523             if (bg1==null) bg1 = new BindingGroup();
524             if (bg2==null) bg2 = new BindingGroup();
525             BindingGroup old_bind_to = bind_to;
526             bind_peers.shatter(bg1, bg2);
527             old_bind_to.shatter(bg2.other(), bg1.other());
528             pair.shatter();
529             destroy();
530
531             newT(r.p, p1.p, mid, null, old_colorclass);
532             newT(r.p, mid, p2.p, null, old_colorclass);
533             bg1.add(p1.getE(mid));
534             bg2.add(p2.getE(mid).pair);
535             return mid;
536         }
537
538         public boolean destroyed = false;
539         public void destroy() {
540             if (destroyed) return;
541             destroyed = true;
542             pair.destroyed = true;
543
544             if (t != null) t.destroy();
545             t = null;
546
547             if (pair.t != null) pair.t.destroy();
548             pair.t = null;
549
550             if (next.t != null) next.t.destroy();
551             if (prev.t != null) prev.t.destroy();
552             next.t = null;
553             prev.t = null;
554
555             if (pair.next.t != null) pair.next.t.destroy();
556             if (pair.prev.t != null) pair.next.t.destroy();
557             pair.next.t = null;
558             pair.prev.t = null;
559
560             this.bind_to = null;
561             pair.bind_to = null;
562             this.bind_peers = null;
563             pair.bind_peers = null;
564             pair.prev.next = next;
565             next.prev = pair.prev;
566             prev.next = pair.next;
567             pair.next = prev;
568             if (p1.e == this) p1.e = prev.next;
569             if (pair.p1.e == pair) pair.p1.e = pair.prev.next;
570         }
571
572         private void sync() {
573             this.prev.next = this;
574             this.next.prev = this;
575             this.pair.pair = this;
576             bind_peers.add(this);
577             if (this.next.p1 != p2) throw new Error();
578             if (this.prev.p2 != p1) throw new Error();
579             if (this.p1.e == null) this.p1.e = this;
580             if (!added) added = true;
581         }
582         private boolean added = false;
583
584         public T makeT(int colorclass) { return t==null ? (t = new T(this, colorclass)) : t; }
585
586         public double crossAngle() {
587             Vec v1 = t.norm().times(-1);
588             Vec v2 = pair.t.norm().times(-1);
589             return Math.acos(v1.norm().dot(v2.norm()));
590         }
591
592         /** angle between this half-edge and the next */
593         public double angle() {
594             Vec v1 = next.p2.p.minus(p2.p);
595             Vec v2 = this.p1.p.minus(p2.p);
596             return Math.acos(v1.norm().dot(v2.norm()));
597         }
598
599         public void makeAdjacent(E e) {
600             if (this.next == e) return;
601             if (p2 != e.p1) throw new Error("cannot make adjacent -- no shared vertex");
602             if (t != null || e.t != null) throw new Error("cannot make adjacent -- edges not both free");
603
604             E freeIncident = p2.getFreeIncident(e, this);
605
606             e.prev.next = freeIncident.next;
607             freeIncident.next.prev = e.prev;
608
609             freeIncident.next = this.next;
610             this.next.prev = freeIncident;
611             
612             this.next = e;
613             e.prev = this;
614
615             sync();
616             freeIncident.sync();
617         }
618
619         /** creates an isolated edge out in the middle of space */
620         public E(Point p1, Point p2) {
621             if (vertices.get(p1) != null) throw new Error();
622             if (vertices.get(p2) != null) throw new Error();
623             this.p1 = new Vertex(p1);
624             this.p2 = new Vertex(p2);
625             this.prev = this.next = this.pair = new E(this, this, this);
626             this.p1.e = this;
627             this.p2.e = this.pair;
628             sync();
629         }
630
631         /** adds a new half-edge from prev.p2 to p2 */
632         public E(E prev, Point p) {
633             Vertex p2;
634             p2 = vertices.get(p);
635             if (p2 == null) p2 = new Vertex(p);
636             this.p1 = prev.p2;
637             this.p2 = p2;
638             this.prev = prev;
639             if (p2.getE(p1) != null) throw new Error();
640             if (p2.e==null) {
641                 this.next = this.pair = new E(this, this, prev.next);
642             } else {
643                 E q = p2.getFreeIncident();
644                 this.next = q.next;
645                 this.next.prev = this;
646                 E z = prev.next;
647                 this.prev.next = this;
648                 this.pair = new E(q, this, z);
649             }
650             if (p2.e==null) p2.e = this.pair;
651             sync();
652         }
653
654         /** adds a new half-edge to the mesh with a given predecessor, successor, and pair */
655         public E(E prev, E pair, E next) {
656             this.p1 = prev.p2;
657             this.p2 = next.p1;
658             this.prev = prev;
659             this.next = next;
660             this.pair = pair;
661             sync();
662         }
663         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); }
664         public boolean has(Vertex v) { return v==p1 || v==p2; }
665         public float length() { return p1.p.minus(p2.p).mag(); }
666         public String toString() { return p1+"->"+p2; }
667
668     }
669
670     public E makeE(Point p1, Point p2) {
671         Vertex v1 = vertices.get(p1);
672         Vertex v2 = vertices.get(p2);
673         if (v1 != null && v2 != null) {
674             E e = v1.getE(v2);
675             if (e != null) return e;
676             e = v2.getE(v1);
677             if (e != null) return e;
678         }
679         if (v1 != null) return new E(v1.getFreeIncident(), p2);
680         if (v2 != null) return new E(v2.getFreeIncident(), p1).pair;
681         return new E(p1, p2);
682     }
683     public T newT(Point p1, Point p2, Point p3, Vec norm, int colorclass) {
684         if (norm != null) {
685             Vec norm2 = p3.minus(p1).cross(p2.minus(p1));
686             float dot = norm.dot(norm2);
687             //if (Math.abs(dot) < EPointSILON) throw new Error("dot products within evertsilon of each other: "+norm+" "+norm2);
688             if (dot < 0) { Point p = p1; p1=p2; p2 = p; }
689         }
690         E e12 = makeE(p1, p2);
691         E e23 = makeE(p2, p3);
692         E e31 = makeE(p3, p1);
693         while(e12.next != e23 || e23.next != e31 || e31.next != e12) {
694             e12.makeAdjacent(e23);
695             e23.makeAdjacent(e31);
696             e31.makeAdjacent(e12);
697         }
698         T ret = e12.makeT(colorclass);
699         if (e12.t == null) throw new Error();
700         if (e23.t == null) throw new Error();
701         if (e31.t == null) throw new Error();
702         return ret;
703     }
704
705
706     /** [UNIQUE] a triangle (face) */
707     public final class T extends Triangle {
708         public final E e1;
709         public final int color;
710         public final int colorclass;
711
712         public void removeFromRTree() { tris.remove(this); }
713         public void addToRTree() { tris.insert(this); }
714
715         public void destroy() { tris.remove(this); }
716
717         T(E e1, int colorclass) {
718             this.e1 = e1;
719             E e2 = e1.next;
720             E e3 = e2.next;
721             if (e1==e2 || e1==e3) throw new Error();
722             if (e3.next!=e1) throw new Error();
723             if (e1.t!=null || e2.t!=null || e3.t!=null) throw new Error("non-manifold surface or disagreeing normals");
724             e1.t = this;
725             e1.next.t = this;
726             e1.next.next.t = this;
727
728             // FIXME: check for sealed/watertight surface once construction is complete (and infer normal(s)?)
729
730             int color = Math.abs(random.nextInt());
731             while(true) {
732                 color = color % 4;
733                 if (e1().pair.t != null && color == e1().pair.t.color) { color++; continue; }
734                 if (e2().pair.t != null && color == e2().pair.t.color) { color++; continue; }
735                 if (e3().pair.t != null && color == e3().pair.t.color) { color++; continue; }
736                 break;
737             }
738             this.color = color;
739             this.colorclass = colorclass;
740             tris.add(this);
741         }
742         public E e1() { return e1; }
743         public E e2() { return e1.next; }
744         public E e3() { return e1.prev; }
745         public Vertex v1() { return e1.p1; }
746         public Vertex v2() { return e1.p2; }
747         public Vertex v3() { return e1.next.p2; }
748         public Point p1() { return e1.p1.p; }
749         public Point p2() { return e1.p2.p; }
750         public Point p3() { return e1.next.p2.p; }
751         public boolean hasE(E e) { return e1==e || e1.next==e || e1.prev==e; }
752         public boolean has(Vertex v) { return v1()==v || v2()==v || v3()==v; }
753
754         public boolean shouldBeDrawn() {
755             if (e1().bind_to.set.size() == 0) return false;
756             if (e2().bind_to.set.size() == 0) return false;
757             if (e3().bind_to.set.size() == 0) return false;
758             return true;
759         }
760
761     }
762 }