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