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