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