5ba7404022c20b24bab3ee207ed2604e9774047d
[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         for(Vert v : pointset)
41             if (v.e != null && v.e.t != null)
42                 return new FaceIterator(v);
43         return new FaceIterator();
44     }
45
46     public Mesh score_against = null;
47     public double score = 0;
48     public float score() { return (float)score; }
49
50     public int numedges = 0;
51     public float avgedge = 0;
52
53     public void rebindPoints() {
54         // unbind all points
55         for(Mesh.T t : this) {
56             t.v1().unbind();
57             t.v2().unbind();
58             t.v3().unbind();
59         }
60         // ask edges to re-implement their bindings
61         for(Mesh.T t : this) {
62             t.e1().dobind();
63             t.e2().dobind();
64             t.e3().dobind();
65         }
66     }
67
68     public void unscore() {
69         HashSet<Vert> done = new HashSet<Vert>();
70         for(T t : this)
71             for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() }) {
72                 if (done.contains(p)) continue;
73                 done.add(p);
74                 p.unscore();
75             }
76     }
77     public void recomputeAllFundamentalQuadrics() {
78         HashSet<Vert> done = new HashSet<Vert>();
79         for(T t : this)
80             for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() }) {
81                 if (done.contains(p)) continue;
82                 done.add(p);
83                 p.recomputeFundamentalQuadric();
84             }
85     }
86     public float rescore() {
87         int num = 0;
88         double dist = 0;
89         HashSet<Vert> done = new HashSet<Vert>();
90         for(T t : this)
91             for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() }) {
92                 if (done.contains(p)) continue;
93                 done.add(p);
94                 p.rescore();
95                 
96             }
97         return (float)(dist/num);
98     }
99
100     public void transform(Matrix m) {
101         ArrayList<Vert> set = new ArrayList<Vert>();
102         for (Vert v : pointset)
103             set.add(v);
104         for(Vert v : set) v.transform(m);
105     }
106
107     public float volume() {
108         double total = 0;
109         for(T t : this) {
110             double area = t.area();
111             Vec origin_to_centroid = new Vec(new Point(0, 0, 0), t.centroid());
112             boolean facingAway = t.norm().dot(origin_to_centroid) > 0;
113             double height = Math.abs(t.norm().dot(origin_to_centroid));
114             total += ((facingAway ? 1 : -1) * area * height) / 3.0;
115         }
116         return (float)total;
117     }
118
119     public class BindingGroup {
120         public HashSet<E> es = new HashSet<E>();
121         public BindingGroup() { }
122         public BindingGroup(E e) {
123             es.add(e);
124         }
125         public void add(E e) {
126             if (e.bg != null) { merge(e.bg); return; }
127             es.add(e);
128             e.bg = this;
129         }
130         public void merge(BindingGroup bg) {
131             for(E e : bg.es) {
132                 e.bg = null;
133                 add(e);
134             }
135         }
136     }
137
138     public Vec diagonal() { return pointset.diagonal(); }
139     public Point centroid() { return pointset.centroid(); }
140     public Vert nearest(Point p) { return pointset.nearest(p); }
141
142     public final class Vert extends HasPoint {
143         public Point p;
144         E e;                // some edge *leaving* this point
145
146         /** the nearest vertex in the "score_against" mesh */
147         Vert   nearest_in_other_mesh;
148         /** the number of vertices in the other mesh for which this is the nearest_in_other_mesh */
149         int    quadric_count;
150         /** the total error quadric (contributions from all vertices in other mesh for which this is nearest) */
151         Matrix quadric = Matrix.ZERO;
152
153         Vert bound_to = this;
154         Matrix binding = new Matrix();
155         float oldscore = 0;
156
157         public Matrix errorQuadric() { return quadric; }
158         public Point getPoint() { return p; }
159         public float score() { return oldscore; }
160
161         private Matrix fundamentalQuadric = null;
162         public Matrix fundamentalQuadric() {
163             if (fundamentalQuadric == null) recomputeFundamentalQuadric();
164             return fundamentalQuadric;
165         }
166
167         private Vert(Point p) {
168             this.p = p;
169             if (pointset.get(p) != null) throw new Error();
170             pointset.add(this);
171         }
172
173         public void recomputeFundamentalQuadric() {
174             unscore();
175             Matrix m = Matrix.ZERO;
176             E e = this.e;
177             do {
178                 T t = e.t;
179                 m = m.plus(t.norm().fundamentalQuadric(t.centroid()));
180                 e = e.pair.next;
181             } while(e != this.e);
182             fundamentalQuadric = m;
183             rescore();
184         }
185
186         public void unscore() {
187             if (nearest_in_other_mesh == null) return;
188             if (fundamentalQuadric == null) return;
189             nearest_in_other_mesh.quadric = nearest_in_other_mesh.quadric.minus(fundamentalQuadric);
190             nearest_in_other_mesh.quadric_count--;
191             if (nearest_in_other_mesh.quadric_count==0)
192                 nearest_in_other_mesh.quadric = Matrix.ZERO;
193             nearest_in_other_mesh = null;
194         }
195
196         public void rescore() {
197             if (score_against == null) return;
198
199             score -= oldscore;
200             oldscore = 0;
201
202             if (nearest_in_other_mesh != null) unscore();
203             if (nearest_in_other_mesh == null) {
204                 nearest_in_other_mesh = score_against.nearest(p);
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.quadric = nearest_in_other_mesh.quadric.plus(fundamentalQuadric());
211                     nearest_in_other_mesh.quadric_count++;
212                 }
213             }
214
215             oldscore = quadric_count == 0 ? 0 : (quadric.preAndPostMultiply(p) / quadric_count);
216             score += oldscore;
217         }
218
219         /** does NOT update bound pairs! */
220         public boolean transform(Matrix m) {
221             unscore();
222             try {
223                 if (pointset.get(this.p)==null) throw new Error();
224                 pointset.remove(this);
225                 float newx = m.a*p.x + m.b*p.y + m.c*p.z + m.d;
226                 float newy = m.e*p.x + m.f*p.y + m.g*p.z + m.h;
227                 float newz = m.i*p.x + m.j*p.y + m.k*p.z + m.l;
228                 this.p = new Point(newx, newy, newz);
229                 pointset.add(this);
230             } catch (Exception e) {
231                 throw new RuntimeException(e);
232             }
233             rescore();
234
235             // should recompute fundamental quadrics of all vertices sharing a face, but we defer...
236             // FIXME: intersection test needed?
237             return true;
238         }
239
240         public boolean move(Vec v) {
241             Matrix m = new Matrix(v);
242             Vert p = this;
243             boolean good = true;
244             do {
245                 good &= p.transform(m);
246                 p = p.bound_to;
247             } while (p != this);
248             return good;
249         }
250
251         public E getFreeIncident() {
252             E ret = getFreeIncident(e, e);
253             if (ret != null) return ret;
254             ret = getFreeIncident(e.pair.next, e.pair.next);
255             if (ret == null) throw new Error("unable to find free incident to " + this);
256             return ret;
257         }
258
259         public E getFreeIncident(E start, E before) {
260             E e = start;
261             do {
262                 if (e.pair.p2 == this && e.pair.t == null && e.pair.next.t == null) return e.pair;
263                 e = e.pair.next;
264             } while(e != before);
265             return null;
266         }
267
268         public E getE(Point p2) {
269             Vert v = pointset.get(p2);
270             if (v==null) return null;
271             return getE(v);
272         }
273         public E getE(Vert p2) {
274             E e = this.e;
275             do {
276                 if (e==null) return null;
277                 if (e.p1 == this && e.p2 == p2) return e;
278                 e = e.pair.next;
279             } while (e!=this.e);
280             return null;
281         }
282
283         public Vec norm() {
284             Vec norm = new Vec(0, 0, 0);
285             E e = this.e;
286             do {
287                 if (e.t != null) norm = norm.plus(e.t.norm().times((float)e.prev.angle()));
288                 e = e.pair.next;
289             } while(e != this.e);
290             return norm.norm();
291         }
292
293         public boolean isBoundTo(Vert p) {
294             Vert px = p;
295             do {
296                 if (px==this) return true;
297                 px = px.bound_to;
298             } while(px != p);
299             return false;
300         }
301         public void unbind() { bound_to = this; binding = new Matrix(); }
302         public void bind(Vert p) { bind(p, new Matrix()); }
303         public void bind(Vert p, Matrix binding) {
304             if (isBoundTo(p)) return;
305             Vert temp_bound_to = p.bound_to;
306             Matrix temp_binding = p.binding;
307             p.bound_to = this.bound_to;
308             p.binding = binding.times(this.binding); // FIXME: may have order wrong here
309             this.bound_to = temp_bound_to;
310             this.binding = temp_binding.times(temp_binding); // FIXME: may have order wrong here
311         }
312     }
313
314     /** [UNIQUE] an edge */
315     public final class E implements Comparable<E> {
316
317         public final Vert p1, p2;
318         T t;     // triangle to our "left"
319         E prev;  // previous half-edge
320         E next;  // next half-edge
321         E pair;  // partner half-edge
322         public BindingGroup bg = new BindingGroup(this);
323         boolean shattered = false;
324
325         public int compareTo(E e) { return e.length() > length() ? 1 : -1; }
326
327         public void bind(E e) { bind(e, new Matrix()); }
328         public void bind(E e, Matrix m) { e.bg.add(this); }
329
330         public void dobind() {
331             if (bg==null) return;
332             for(E ex : bg.es) {
333                 if (ex==this) continue;
334                 p1.bind(ex.p1);
335                 p2.bind(ex.p2);
336             }
337         }
338
339         public Point shatter() { return shatter(midpoint(), null, null); }
340         public Point shatter(Point mid, BindingGroup bg1, BindingGroup bg2) {
341             if (shattered) return mid;
342             shattered = true;
343
344             Vert r = next.p2;
345             E next = this.next;
346             E prev = this.prev;
347
348             if (bg1==null) bg1 = new BindingGroup();
349             if (bg2==null) bg2 = new BindingGroup();
350             for(E e : bg.es) e.shatter(e.midpoint(), bg1, bg2);
351             pair.shatter();
352             destroy();
353
354             newT(r.p, p1.p, mid, null);
355             newT(r.p, mid, p2.p, null);
356             bg1.add(p1.getE(mid));
357             bg2.add(p2.getE(mid).pair);
358             return mid;
359         }
360
361         public boolean destroyed = false;
362         public void destroy() {
363             if (destroyed) return;
364             destroyed = true;
365             pair.destroyed = true;
366             if (next.t != null) next.t.destroy();
367             if (prev.t != null) prev.t.destroy();
368             next.t = null;
369             prev.t = null;
370             pair.next.t = null;
371             pair.prev.t = null;
372             this.bg = null;
373             pair.bg = null;
374             pair.prev.next = next;
375             next.prev = pair.prev;
376             prev.next = pair.next;
377             pair.next = prev;
378             if (p1.e == this) p1.e = prev.next;
379             if (pair.p1.e == pair) pair.p1.e = pair.prev.next;
380             avgedge -= this.length();
381             avgedge -= pair.length();
382             numedges--;
383             numedges--;
384         }
385
386         private void sync() {
387             this.prev.next = this;
388             this.next.prev = this;
389             this.pair.pair = this;
390             if (this.next.p1 != p2) throw new Error();
391             if (this.prev.p2 != p1) throw new Error();
392             if (this.p1.e == null) this.p1.e = this;
393             if (!added) {
394                 added = true;
395                 numedges++;
396                 avgedge += length();
397             }
398         }
399         private boolean added = false;
400
401         public T makeT() { return t==null ? (t = new T(this)) : t; }
402
403         /** angle between this half-edge and the next */
404         public double angle() {
405             Vec v1 = next.p2.p.minus(p2.p);
406             Vec v2 = this.p1.p.minus(p2.p);
407             return Math.acos(v1.norm().dot(v2.norm()));
408         }
409
410         public void makeAdjacent(E e) {
411             if (this.next == e) return;
412             if (p2 != e.p1) throw new Error("cannot make adjacent -- no shared vertex");
413             if (t != null || e.t != null) throw new Error("cannot make adjacent -- edges not both free");
414
415             E freeIncident = p2.getFreeIncident(e, this);
416
417             e.prev.next = freeIncident.next;
418             freeIncident.next.prev = e.prev;
419
420             freeIncident.next = this.next;
421             this.next.prev = freeIncident;
422             
423             this.next = e;
424             e.prev = this;
425
426             sync();
427             freeIncident.sync();
428         }
429
430         /** creates an isolated edge out in the middle of space */
431         public E(Point p1, Point p2) {
432             if (pointset.get(p1) != null) throw new Error();
433             if (pointset.get(p2) != null) throw new Error();
434             this.p1 = new Vert(p1);
435             this.p2 = new Vert(p2);
436             this.prev = this.next = this.pair = new E(this, this, this);
437             this.p1.e = this;
438             this.p2.e = this.pair;
439             sync();
440         }
441
442         /** adds a new half-edge from prev.p2 to p2 */
443         public E(E prev, Point p) {
444             Vert p2;
445             p2 = pointset.get(p);
446             if (p2 == null) p2 = new Vert(p);
447             this.p1 = prev.p2;
448             this.p2 = p2;
449             this.prev = prev;
450             if (p2.getE(p1) != null) throw new Error();
451             if (p2.e==null) {
452                 this.next = this.pair = new E(this, this, prev.next);
453             } else {
454                 E q = p2.getFreeIncident();
455                 this.next = q.next;
456                 this.next.prev = this;
457                 E z = prev.next;
458                 this.prev.next = this;
459                 this.pair = new E(q, this, z);
460             }
461             if (p2.e==null) p2.e = this.pair;
462             sync();
463         }
464
465         /** adds a new half-edge to the mesh with a given predecessor, successor, and pair */
466         public E(E prev, E pair, E next) {
467             this.p1 = prev.p2;
468             this.p2 = next.p1;
469             this.prev = prev;
470             this.next = next;
471             this.pair = pair;
472             sync();
473         }
474         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); }
475         public boolean has(Vert v) { return v==p1 || v==p2; }
476         public float length() { return p1.p.minus(p2.p).mag(); }
477         public String toString() { return p1+"->"+p2; }
478
479         public boolean intersects(T t) {
480             double A0=t.v1().p.x, A1=t.v1().p.y, A2=t.v1().p.z;
481             double B0=t.v2().p.x, B1=t.v2().p.y, B2=t.v2().p.z;
482             double C0=t.v3().p.x, C1=t.v3().p.y, C2=t.v3().p.z;
483             double j0=p1.p.x, j1=p1.p.y, j2=p1.p.z;
484             double k0=p2.p.x, k1=p2.p.y, k2=p2.p.z;
485             double J0, J1, J2;
486             double K0, K1, K2;
487             double i0, i1, i2;
488             double a0, a1, a2;
489             double b0, b1, b2;
490             double c0, c1, c2;
491             double in_det;
492             double R00, R01, R02, R03,
493                 R10, R11, R12, R13,
494                 R20, R21, R22, R23,
495                 R30, R31, R32, R33;
496
497
498             /* a = B - A */
499             a0 = B0 - A0; 
500             a1 = B1 - A1; 
501             a2 = B2 - A2;
502             /* b = C - B */
503             b0 = C0 - A0;
504             b1 = C1 - A1;
505             b2 = C2 - A2;
506             /* c = a &times; b */
507             c0 = a1 * b2 - a2 * b1;
508             c1 = a2 * b0 - a0 * b2;
509             c2 = a0 * b1 - a1 * b0;
510  
511             /* M^(-1) = (1/det(M)) * adj(M) */
512             in_det = 1 / (c0 * c0 + c1 * c1 + c2 * c2);
513             R00 = (b1 * c2 - b2 * c1) * in_det;
514             R01 = (b2 * c0 - b0 * c2) * in_det;
515             R02 = (b0 * c1 - b1 * c0) * in_det;
516             R10 = (c1 * a2 - c2 * a1) * in_det;
517             R11 = (c2 * a0 - c0 * a2) * in_det;
518             R12 = (c0 * a1 - c1 * a0) * in_det;
519             R20 = (c0) * in_det;
520             R21 = (c1) * in_det;
521             R22 = (c2) * in_det;
522   
523             /* O = M^(-1) * A */
524             R03 = -(R00 * A0 + R01 * A1 + R02 * A2);
525             R13 = -(R10 * A0 + R11 * A1 + R12 * A2);
526             R23 = -(R20 * A0 + R21 * A1 + R22 * A2);
527  
528             /* fill in last row of 4x4 matrix */
529             R30 = R31 = R32 = 0;
530             R33 = 1;
531   
532             J2 = R20 * j0 + R21 * j1 + R22 * j2 + R23;
533             K2 = R20 * k0 + R21 * k1 + R22 * k2 + R23;
534             if (J2 * K2 >= 0) return false;
535
536             J0 = R00 * j0 + R01 * j1 + R02 * j2 + R03;
537             K0 = R00 * k0 + R01 * k1 + R02 * k2 + R03;
538             i0 = J0 + J2 * ((K0 - J0) / (J2 - K2));
539             if (i0 < 0 || i0 > 1) return false;
540   
541             J1 = R10 * j0 + R11 * j1 + R12 * j2 + R13;
542             K1 = R10 * k0 + R11 * k1 + R12 * k2 + R13;
543             i1 = J1 + J2 * ((K1 - J1) / (J2 - K2));
544             if (i1 < 0 || i1 > 1 || i0 + i1 > 1) return false;
545
546             return true;            
547         }
548     }
549
550     public E makeE(Point p1, Point p2) {
551         Vert v1 = pointset.get(p1);
552         Vert v2 = pointset.get(p2);
553         if (v1 != null && v2 != null) {
554             E e = v1.getE(v2);
555             if (e != null) return e;
556             e = v2.getE(v1);
557             if (e != null) return e;
558         }
559         if (v1 != null) return new E(v1.getFreeIncident(), p2);
560         if (v2 != null) return new E(v2.getFreeIncident(), p1).pair;
561         return new E(p1, p2);
562     }
563     public T newT(Point p1, Point p2, Point p3, Vec norm) {
564         if (norm != null) {
565             Vec norm2 = p3.minus(p1).cross(p2.minus(p1));
566             float dot = norm.dot(norm2);
567             //if (Math.abs(dot) < EPointSILON) throw new Error("dot products within evertsilon of each other: "+norm+" "+norm2);
568             if (dot < 0) { Point p = p1; p1=p2; p2 = p; }
569         }
570         E e12 = makeE(p1, p2);
571         E e23 = makeE(p2, p3);
572         E e31 = makeE(p3, p1);
573         while(e12.next != e23 || e23.next != e31 || e31.next != e12) {
574             e12.makeAdjacent(e23);
575             e23.makeAdjacent(e31);
576             e31.makeAdjacent(e12);
577         }
578         T ret = e12.makeT();
579         if (e12.t == null) throw new Error();
580         if (e23.t == null) throw new Error();
581         if (e31.t == null) throw new Error();
582         return ret;
583     }
584
585
586     public class FaceIterator implements Iterator<T> {
587         private HashSet<T> visited = new HashSet<T>();
588         private LinkedList<T> next = new LinkedList<T>();
589         public FaceIterator() { }
590         public FaceIterator(Vert v) { next.addFirst(v.e.t); }
591         public boolean hasNext() { return next.peek()!=null; }
592         public void remove() { throw new Error(); }
593         public T next() {
594             T ret = next.removeFirst();
595             if (ret == null) return null;
596             visited.add(ret);
597             T t1 = ret.e1().pair.t;
598             T t2 = ret.e2().pair.t;
599             T t3 = ret.e3().pair.t;
600             if (t1 != null && !visited.contains(t1)) next.addFirst(t1);
601             if (t2 != null && !visited.contains(t2)) next.addFirst(t2);
602             if (t3 != null && !visited.contains(t3)) next.addFirst(t3);
603             return ret;
604         }
605     }
606
607     /** [UNIQUE] a triangle (face) */
608     public final class T extends Triangle {
609         public final E e1;
610         public final int color;
611
612         public void destroy() {
613         }
614
615         T(E e1) {
616             this.e1 = e1;
617             E e2 = e1.next;
618             E e3 = e2.next;
619             if (e1==e2 || e1==e3) throw new Error();
620             if (e3.next!=e1) throw new Error();
621             if (e1.t!=null || e2.t!=null || e3.t!=null) throw new Error("non-manifold surface or disagreeing normals");
622             e1.t = this;
623             e1.next.t = this;
624             e1.next.next.t = this;
625
626             // FIXME: check for sealed/watertight surface once construction is complete (and infer normal(s)?)
627
628             int color = Math.abs(random.nextInt());
629             while(true) {
630                 color = color % 4;
631                 if (e1().pair.t != null && color == e1().pair.t.color) { color++; continue; }
632                 if (e2().pair.t != null && color == e2().pair.t.color) { color++; continue; }
633                 if (e3().pair.t != null && color == e3().pair.t.color) { color++; continue; }
634                 break;
635             }
636             this.color = color;
637         }
638         public E e1() { return e1; }
639         public E e2() { return e1.next; }
640         public E e3() { return e1.prev; }
641         public Vert v1() { return e1.p1; }
642         public Vert v2() { return e1.p2; }
643         public Vert v3() { return e1.next.p2; }
644         public Point p1() { return e1.p1.p; }
645         public Point p2() { return e1.p2.p; }
646         public Point p3() { return e1.next.p2.p; }
647         public boolean hasE(E e) { return e1==e || e1.next==e || e1.prev==e; }
648         public boolean has(Vert v) { return v1()==v || v2()==v || v3()==v; }
649     }
650
651 }