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