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