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