1 package edu.berkeley.qfat;
4 import java.awt.event.*;
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;
12 public class Mesh implements Iterable<Mesh.T> {
14 public static final float EPSILON = (float)0.0001;
15 public static final Random random = new Random();
17 private PointSet<Vert> pointset = new PointSet<Vert>();
18 public int size() { return pointset.size(); }
19 public Iterable<Vert> vertices() { return pointset; }
21 public Iterable<E> edges() {
24 public Iterator<E> iterator() {
26 HashSet<E> hse = new HashSet<E>();
27 for(T t : Mesh.this) {
35 return hse.iterator();
39 public Iterator<T> iterator() {
41 for(Vert v : pointset)
42 if (v.e != null && v.e.t != null)
43 return new FaceIterator(v);
44 return new FaceIterator();
49 public HashSet<T> ts = new HashSet<T>();
50 public RTree<T> tris = new RTree<T>();
52 public Mesh score_against = null;
53 public double score = 0;
54 public float score() { return (float)score; }
56 public int numedges = 0;
57 public float avgedge = 0;
59 public void rebindPoints() {
61 for(Mesh.T t : this) {
66 // ask edges to re-implement their bindings
67 for(Mesh.T t : this) {
74 public void unApplyQuadricToNeighborAll() {
75 HashSet<Vert> done = new HashSet<Vert>();
77 for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() }) {
78 if (done.contains(p)) continue;
80 p.unApplyQuadricToNeighbor();
83 public void recomputeAllFundamentalQuadrics() {
84 HashSet<Vert> done = new HashSet<Vert>();
86 for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() }) {
87 if (done.contains(p)) continue;
89 p.recomputeFundamentalQuadric();
92 public float applyQuadricToNeighborAll() {
95 HashSet<Vert> done = new HashSet<Vert>();
97 for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() }) {
98 if (done.contains(p)) continue;
100 p.applyQuadricToNeighbor();
103 return (float)(dist/num);
106 public void transform(Matrix m) {
107 ArrayList<Vert> set = new ArrayList<Vert>();
108 for (Vert v : pointset)
110 for(Vert v : set) v.transform(m);
113 public float volume() {
116 double area = t.area();
117 Vec origin_to_centroid = new Vec(new Point(0, 0, 0), t.centroid());
118 boolean facingAway = t.norm().dot(origin_to_centroid) > 0;
119 double height = Math.abs(t.norm().dot(origin_to_centroid));
120 total += ((facingAway ? 1 : -1) * area * height) / 3.0;
125 public void rebuildPointSet() { /*pointset.rebuild();*/ }
126 public Vec diagonal() { return pointset.diagonal(); }
127 public Point centroid() { return pointset.centroid(); }
128 public Vert nearest(Point p) { return pointset.nearest(p); }
130 public final class Vert extends HasPoint {
131 public String toString() { return p.toString(); }
133 E e; // some edge *leaving* this point
135 /** the nearest vertex in the "score_against" mesh */
136 Vert nearest_in_other_mesh;
137 /** the number of vertices in the other mesh for which this is the nearest_in_other_mesh */
139 /** the total error quadric (contributions from all vertices in other mesh for which this is nearest) */
140 Matrix quadric = Matrix.ZERO;
142 Vert bound_to = this;
143 Matrix binding = Matrix.ONE;
145 boolean quadricStale = false;
147 public Matrix errorQuadric() { return quadric; }
148 public Point getPoint() { return p; }
149 public float score() { return oldscore; }
151 private Matrix fundamentalQuadric = null;
152 public Matrix fundamentalQuadric() {
153 if (fundamentalQuadric == null) recomputeFundamentalQuadric();
154 return fundamentalQuadric;
157 private Vert(Point p) {
159 if (pointset.get(p) != null) throw new Error();
163 private void glNormal(GL gl) {
165 gl.glNormal3f(norm.x, norm.y, norm.z);
168 public void recomputeFundamentalQuadric() {
169 //if (!quadricStale && fundamentalQuadric != null) return;
170 quadricStale = false;
171 unApplyQuadricToNeighbor();
172 Matrix m = Matrix.ZERO;
177 m = m.plus(t.norm().fundamentalQuadric(t.centroid()));
180 } while(e != this.e);
181 fundamentalQuadric = m.times(1/(float)count);
182 applyQuadricToNeighbor();
185 public void unApplyQuadricToNeighbor() {
186 if (nearest_in_other_mesh == null) return;
187 if (fundamentalQuadric == null) return;
188 nearest_in_other_mesh.unComputeError();
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.computeError();
194 nearest_in_other_mesh = null;
197 public void applyQuadricToNeighbor() {
198 if (score_against == null) return;
200 Vert new_nearest = score_against.nearest(p);
201 if (nearest_in_other_mesh != null && new_nearest == nearest_in_other_mesh) return;
203 if (nearest_in_other_mesh != null) unApplyQuadricToNeighbor();
204 if (nearest_in_other_mesh != null) throw new Error();
206 nearest_in_other_mesh = new_nearest;
208 // don't attract to vertices that face the other way
209 if (nearest_in_other_mesh.e == null || nearest_in_other_mesh.norm().dot(norm()) < 0) {
210 nearest_in_other_mesh = null;
212 nearest_in_other_mesh.unComputeError();
213 nearest_in_other_mesh.quadric = nearest_in_other_mesh.quadric.plus(fundamentalQuadric());
214 nearest_in_other_mesh.quadric_count++;
215 nearest_in_other_mesh.computeError();
220 public void reComputeErrorAround() {
222 if (nearest_in_other_mesh != null) nearest_in_other_mesh.reComputeError();
225 e.p2.reComputeError();
227 } while (e != this.e);
229 public void reComputeError() {
233 public void unComputeError() {
237 public void computeError() {
238 if (quadric_count == 0) {
241 else if (nearest_in_other_mesh == null) {
242 if (score_against != null) {
243 Vert ne = score_against.nearest(p);
244 oldscore = ne.fundamentalQuadric().preAndPostMultiply(p) * 100 * 10;
249 oldscore = nearest_in_other_mesh.fundamentalQuadric().preAndPostMultiply(p) * 100 * 10;
252 oldscore = (quadric.preAndPostMultiply(p) * 100) / quadric_count;
261 //double ang = Math.abs(e.crossAngle());
262 double ang = Math.abs(e.crossAngle());
263 if (ang > Math.PI) throw new Error();
267 aspects += e.t.aspect()*e.t.aspect();
271 float minangle = (float)(Math.PI * 0.8);
273 oldscore += (ang - minangle);
276 } while (e != this.e);
277 if (numaspects > 0) oldscore += (aspects / numaspects);
279 //System.out.println(oldscore);
280 //oldscore = oldscore*oldscore;
284 private void removeTrianglesFromRTree() {
287 if (e.t != null) e.t.removeFromRTree();
289 } while(e != this.e);
291 private void addTrianglesToRTree() {
294 if (e.t != null) e.t.addToRTree();
296 } while(e != this.e);
299 /** does NOT update bound pairs! */
300 public boolean transform(Matrix m) {
301 unApplyQuadricToNeighbor();
304 if (pointset.get(this.p)==null) throw new Error();
305 pointset.remove(this);
306 removeTrianglesFromRTree();
307 float newx = m.a*p.x + m.b*p.y + m.c*p.z + m.d;
308 float newy = m.e*p.x + m.f*p.y + m.g*p.z + m.h;
309 float newz = m.i*p.x + m.j*p.y + m.k*p.z + m.l;
310 this.p = new Point(newx, newy, newz);
311 addTrianglesToRTree();
313 } catch (Exception e) {
314 throw new RuntimeException(e);
316 applyQuadricToNeighbor();
318 // FIXME: intersection test needed?
321 // should recompute fundamental quadrics of all vertices sharing a face, but we defer...
325 if (Math.abs(e.crossAngle()) > (Math.PI * 0.9) ||
326 Math.abs(e.next.crossAngle()) > (Math.PI * 0.9)) {
329 if (e.t.aspect() < 0.1) {
333 e.p2.quadricStale = true;
335 } while(e != this.e);
338 if (!ignorecollision && good) {
340 tris.range(new Segment(oldp, this.p),
342 public void visit(T t) {
346 if (!t.has(e.p1) && !t.has(e.p2) && e.intersects(t)) { good = false; }
348 if (!e.t.has(t.e1().p1) && !e.t.has(t.e1().p2) && t.e1().intersects(e.t)) { good = false; }
349 if (!e.t.has(t.e2().p1) && !e.t.has(t.e2().p2) && t.e2().intersects(e.t)) { good = false; }
350 if (!e.t.has(t.e3().p1) && !e.t.has(t.e3().p2) && t.e3().intersects(e.t)) { good = false; }
353 } while(e != Vert.this.e);
358 for(T t : Mesh.this) {
362 if (!t.has(e.p1) && !t.has(e.p2) && e.intersects(t)) { good = false; break; }
364 if (!e.t.has(t.e1().p1) && !e.t.has(t.e1().p2) && t.e1().intersects(e.t)) { good = false; break; }
365 if (!e.t.has(t.e2().p1) && !e.t.has(t.e2().p2) && t.e2().intersects(e.t)) { good = false; break; }
366 if (!e.t.has(t.e3().p1) && !e.t.has(t.e3().p2) && t.e3().intersects(e.t)) { good = false; break; }
369 } while(e != this.e);
375 reComputeErrorAround();
378 private boolean good;
380 public boolean move(Vec v) {
381 Matrix m = Matrix.translate(v);
385 good &= p.transform(m);
391 public E getFreeIncident() {
392 E ret = getFreeIncident(e, e);
393 if (ret != null) return ret;
394 ret = getFreeIncident(e.pair.next, e.pair.next);
398 System.out.println(ex + " " + ex.t);
401 throw new Error("unable to find free incident to " + this);
406 public E getFreeIncident(E start, E before) {
409 if (e.pair.p2 == this && e.pair.t == null && e.pair.next.t == null) return e.pair;
411 } while(e != before);
415 public E getE(Point p2) {
416 Vert v = pointset.get(p2);
417 if (v==null) return null;
420 public E getE(Vert p2) {
423 if (e==null) return null;
424 if (e.p1 == this && e.p2 == p2) return e;
431 Vec norm = new Vec(0, 0, 0);
434 if (e.t != null) norm = norm.plus(e.t.norm().times((float)e.prev.angle()));
436 } while(e != this.e);
440 public boolean isBoundTo(Vert p) {
443 if (px==this) return true;
448 public void unbind() { bound_to = this; binding = Matrix.ONE; }
449 public void bind(Vert p) { bind(p, Matrix.ONE); }
450 public void bind(Vert p, Matrix binding) {
451 if (isBoundTo(p)) return;
452 Vert temp_bound_to = p.bound_to;
453 Matrix temp_binding = p.binding;
454 p.bound_to = this.bound_to;
455 p.binding = binding.times(this.binding); // FIXME: may have order wrong here
456 this.bound_to = temp_bound_to;
457 this.binding = temp_binding.times(temp_binding); // FIXME: may have order wrong here
461 public class BindingGroup {
462 private HashSet<E> set = new HashSet<E>();
463 public BindingGroup bind_others;
464 public BindingGroup other() { return bind_others; }
465 public BindingGroup(BindingGroup bind_others) { this.bind_others = bind_others; }
466 public BindingGroup() { this.bind_others = new BindingGroup(this); }
467 public BindingGroup(E e) { this(); set.add(e); }
468 public void add(E e) {
469 if (set.contains(e)) return;
471 BindingGroup e_bind_peers = e.bind_peers;
472 BindingGroup e_bind_to = e.bind_to;
474 e.bind_to = bind_others;
475 for (E epeer : e_bind_peers.set) add(epeer);
476 for (E eother : e_bind_to.set) bind_others.add(eother);
478 for(E eother : bind_others.set) {
479 if (e.next.bind_to.set.contains(eother.prev)) {
480 e.next.next.bindEdge(eother.prev.prev);
482 if (e.prev.bind_to.set.contains(eother.next)) {
483 e.prev.prev.bindEdge(eother.next.next);
488 public void dobind(E e) {
489 for(E ebound : set) {
490 e.p1.bind(ebound.p2);
491 e.p2.bind(ebound.p1);
494 public void shatter(BindingGroup bg1, BindingGroup bg2) {
496 e.shatter(e.midpoint(), bg1, bg2);
501 /** [UNIQUE] an edge */
502 public final class E implements Comparable<E> {
504 public final Vert p1, p2;
505 T t; // triangle to our "left"
506 E prev; // previous half-edge
507 E next; // next half-edge
508 E pair; // partner half-edge
509 public BindingGroup bind_peers = new BindingGroup(this);
510 public BindingGroup bind_to = bind_peers.other();
511 boolean shattered = false;
513 public float comparator() {
514 Vert nearest = score_against.nearest(midpoint());
515 //if (t==null) return length();
517 double ang = Math.abs(crossAngle());
518 float minangle = (float)(Math.PI * 0.9);
523 if ((length() * length()) / t.area() > 10)
524 return (float)(length()*Math.sqrt(t.area()));
525 return length()*t.area();
527 return (float)Math.max(length(), midpoint().distance(nearest.p));
530 public int compareTo(E e) {
531 return e.comparator() > comparator() ? 1 : -1;
533 public void bindEdge(E e) { bind_to.add(e); }
534 public void dobind() { bind_to.dobind(this); }
536 public Point shatter() { return shatter(midpoint(), null, null); }
537 public Point shatter(Point mid, BindingGroup bg1, BindingGroup bg2) {
538 if (shattered || destroyed) return mid;
545 int old_colorclass = t==null ? 0 : t.colorclass;
546 if (bg1==null) bg1 = new BindingGroup();
547 if (bg2==null) bg2 = new BindingGroup();
548 BindingGroup old_bind_to = bind_to;
549 bind_peers.shatter(bg1, bg2);
550 old_bind_to.shatter(bg2.other(), bg1.other());
554 newT(r.p, p1.p, mid, null, old_colorclass);
555 newT(r.p, mid, p2.p, null, old_colorclass);
556 bg1.add(p1.getE(mid));
557 bg2.add(p2.getE(mid).pair);
561 public boolean destroyed = false;
562 public void destroy() {
563 if (destroyed) return;
565 pair.destroyed = true;
567 if (t != null) t.destroy();
570 if (pair.t != null) pair.t.destroy();
573 if (next.t != null) next.t.destroy();
574 if (prev.t != null) prev.t.destroy();
578 if (pair.next.t != null) pair.next.t.destroy();
579 if (pair.prev.t != null) pair.next.t.destroy();
585 this.bind_peers = null;
586 pair.bind_peers = null;
587 pair.prev.next = next;
588 next.prev = pair.prev;
589 prev.next = pair.next;
591 if (p1.e == this) p1.e = prev.next;
592 if (pair.p1.e == pair) pair.p1.e = pair.prev.next;
593 avgedge -= this.length();
594 avgedge -= pair.length();
599 private void sync() {
600 this.prev.next = this;
601 this.next.prev = this;
602 this.pair.pair = this;
603 bind_peers.add(this);
604 if (this.next.p1 != p2) throw new Error();
605 if (this.prev.p2 != p1) throw new Error();
606 if (this.p1.e == null) this.p1.e = this;
613 private boolean added = false;
615 public T makeT(int colorclass) { return t==null ? (t = new T(this, colorclass)) : t; }
617 public double crossAngle() {
618 Vec v1 = t.norm().times(-1);
619 Vec v2 = pair.t.norm().times(-1);
620 return Math.acos(v1.norm().dot(v2.norm()));
623 /** angle between this half-edge and the next */
624 public double angle() {
625 Vec v1 = next.p2.p.minus(p2.p);
626 Vec v2 = this.p1.p.minus(p2.p);
627 return Math.acos(v1.norm().dot(v2.norm()));
630 public void makeAdjacent(E e) {
631 if (this.next == e) return;
632 if (p2 != e.p1) throw new Error("cannot make adjacent -- no shared vertex");
633 if (t != null || e.t != null) throw new Error("cannot make adjacent -- edges not both free");
635 E freeIncident = p2.getFreeIncident(e, this);
637 e.prev.next = freeIncident.next;
638 freeIncident.next.prev = e.prev;
640 freeIncident.next = this.next;
641 this.next.prev = freeIncident;
650 /** creates an isolated edge out in the middle of space */
651 public E(Point p1, Point p2) {
652 if (pointset.get(p1) != null) throw new Error();
653 if (pointset.get(p2) != null) throw new Error();
654 this.p1 = new Vert(p1);
655 this.p2 = new Vert(p2);
656 this.prev = this.next = this.pair = new E(this, this, this);
658 this.p2.e = this.pair;
662 /** adds a new half-edge from prev.p2 to p2 */
663 public E(E prev, Point p) {
665 p2 = pointset.get(p);
666 if (p2 == null) p2 = new Vert(p);
670 if (p2.getE(p1) != null) throw new Error();
672 this.next = this.pair = new E(this, this, prev.next);
674 E q = p2.getFreeIncident();
676 this.next.prev = this;
678 this.prev.next = this;
679 this.pair = new E(q, this, z);
681 if (p2.e==null) p2.e = this.pair;
685 /** adds a new half-edge to the mesh with a given predecessor, successor, and pair */
686 public E(E prev, E pair, E next) {
694 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); }
695 public boolean has(Vert v) { return v==p1 || v==p2; }
696 public float length() { return p1.p.minus(p2.p).mag(); }
697 public String toString() { return p1+"->"+p2; }
699 public boolean intersects(T t) {
700 double A0=t.v1().p.x, A1=t.v1().p.y, A2=t.v1().p.z;
701 double B0=t.v2().p.x, B1=t.v2().p.y, B2=t.v2().p.z;
702 double C0=t.v3().p.x, C1=t.v3().p.y, C2=t.v3().p.z;
703 double j0=p1.p.x, j1=p1.p.y, j2=p1.p.z;
704 double k0=p2.p.x, k1=p2.p.y, k2=p2.p.z;
712 double R00, R01, R02, R03,
726 /* c = a × b */
727 c0 = a1 * b2 - a2 * b1;
728 c1 = a2 * b0 - a0 * b2;
729 c2 = a0 * b1 - a1 * b0;
731 /* M^(-1) = (1/det(M)) * adj(M) */
732 in_det = 1 / (c0 * c0 + c1 * c1 + c2 * c2);
733 R00 = (b1 * c2 - b2 * c1) * in_det;
734 R01 = (b2 * c0 - b0 * c2) * in_det;
735 R02 = (b0 * c1 - b1 * c0) * in_det;
736 R10 = (c1 * a2 - c2 * a1) * in_det;
737 R11 = (c2 * a0 - c0 * a2) * in_det;
738 R12 = (c0 * a1 - c1 * a0) * in_det;
744 R03 = -(R00 * A0 + R01 * A1 + R02 * A2);
745 R13 = -(R10 * A0 + R11 * A1 + R12 * A2);
746 R23 = -(R20 * A0 + R21 * A1 + R22 * A2);
748 /* fill in last row of 4x4 matrix */
752 J2 = R20 * j0 + R21 * j1 + R22 * j2 + R23;
753 K2 = R20 * k0 + R21 * k1 + R22 * k2 + R23;
754 if (J2 * K2 >= 0) return false;
756 J0 = R00 * j0 + R01 * j1 + R02 * j2 + R03;
757 K0 = R00 * k0 + R01 * k1 + R02 * k2 + R03;
758 i0 = J0 + J2 * ((K0 - J0) / (J2 - K2));
759 if (i0 < 0 || i0 > 1) return false;
761 J1 = R10 * j0 + R11 * j1 + R12 * j2 + R13;
762 K1 = R10 * k0 + R11 * k1 + R12 * k2 + R13;
763 i1 = J1 + J2 * ((K1 - J1) / (J2 - K2));
764 if (i1 < 0 || i1 > 1 || i0 + i1 > 1) return false;
770 public E makeE(Point p1, Point p2) {
771 Vert v1 = pointset.get(p1);
772 Vert v2 = pointset.get(p2);
773 if (v1 != null && v2 != null) {
775 if (e != null) return e;
777 if (e != null) return e;
779 if (v1 != null) return new E(v1.getFreeIncident(), p2);
780 if (v2 != null) return new E(v2.getFreeIncident(), p1).pair;
781 return new E(p1, p2);
783 public T newT(Point p1, Point p2, Point p3, Vec norm, int colorclass) {
785 Vec norm2 = p3.minus(p1).cross(p2.minus(p1));
786 float dot = norm.dot(norm2);
787 //if (Math.abs(dot) < EPointSILON) throw new Error("dot products within evertsilon of each other: "+norm+" "+norm2);
788 if (dot < 0) { Point p = p1; p1=p2; p2 = p; }
790 E e12 = makeE(p1, p2);
791 E e23 = makeE(p2, p3);
792 E e31 = makeE(p3, p1);
793 while(e12.next != e23 || e23.next != e31 || e31.next != e12) {
794 e12.makeAdjacent(e23);
795 e23.makeAdjacent(e31);
796 e31.makeAdjacent(e12);
798 T ret = e12.makeT(colorclass);
799 if (e12.t == null) throw new Error();
800 if (e23.t == null) throw new Error();
801 if (e31.t == null) throw new Error();
806 public class FaceIterator implements Iterator<T> {
807 private HashSet<T> visited = new HashSet<T>();
808 private LinkedList<T> next = new LinkedList<T>();
809 public FaceIterator() { }
810 public FaceIterator(Vert v) { next.addFirst(v.e.t); }
811 public boolean hasNext() { return next.peek()!=null; }
812 public void remove() { throw new Error(); }
814 T ret = next.removeFirst();
815 if (ret == null) return null;
817 T t1 = ret.e1().pair.t;
818 T t2 = ret.e2().pair.t;
819 T t3 = ret.e3().pair.t;
820 if (t1 != null && !visited.contains(t1)) next.addFirst(t1);
821 if (t2 != null && !visited.contains(t2)) next.addFirst(t2);
822 if (t3 != null && !visited.contains(t3)) next.addFirst(t3);
827 /** [UNIQUE] a triangle (face) */
828 public final class T extends Triangle {
830 public final int color;
831 public final int colorclass;
833 public void removeFromRTree() { tris.remove(this); }
834 public void addToRTree() { tris.insert(this); }
836 public void destroy() {
841 T(E e1, int colorclass) {
845 if (e1==e2 || e1==e3) throw new Error();
846 if (e3.next!=e1) throw new Error();
847 if (e1.t!=null || e2.t!=null || e3.t!=null) throw new Error("non-manifold surface or disagreeing normals");
850 e1.next.next.t = this;
852 // FIXME: check for sealed/watertight surface once construction is complete (and infer normal(s)?)
854 int color = Math.abs(random.nextInt());
857 if (e1().pair.t != null && color == e1().pair.t.color) { color++; continue; }
858 if (e2().pair.t != null && color == e2().pair.t.color) { color++; continue; }
859 if (e3().pair.t != null && color == e3().pair.t.color) { color++; continue; }
863 this.colorclass = colorclass;
867 public E e1() { return e1; }
868 public E e2() { return e1.next; }
869 public E e3() { return e1.prev; }
870 public Vert v1() { return e1.p1; }
871 public Vert v2() { return e1.p2; }
872 public Vert v3() { return e1.next.p2; }
873 public Point p1() { return e1.p1.p; }
874 public Point p2() { return e1.p2.p; }
875 public Point p3() { return e1.next.p2.p; }
876 public boolean hasE(E e) { return e1==e || e1.next==e || e1.prev==e; }
877 public boolean has(Vert v) { return v1()==v || v2()==v || v3()==v; }
879 public void glVertices(GL gl) {
881 if (e1().bind_to.set.size() == 0) return;
882 if (e2().bind_to.set.size() == 0) return;
883 if (e3().bind_to.set.size() == 0) return;
891 public boolean tilemesh = false;
892 public boolean ignorecollision = false;