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