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