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 RTree<T> tris = new RTree<T>();
18 private PointSet<Vert> vertices = new PointSet<Vert>();
20 public boolean tilemesh = false;
21 public boolean ignorecollision = false;
22 public Mesh score_against = null;
23 public double score = 0;
24 public float score() { return (float)score; }
25 public int numedges = 0;
26 public float avgedge = 0;
28 public int size() { return vertices.size(); }
29 public Iterable<Vert> vertices() { return vertices; }
31 public Iterator<T> iterator() {
32 return tris.iterator();
35 public void rebindPoints() {
37 for(Mesh.T t : this) {
42 // ask edges to re-implement their bindings
43 for(Mesh.T t : this) {
50 public void unApplyQuadricToNeighborAll() {
51 HashSet<Vert> done = new HashSet<Vert>();
53 for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() }) {
54 if (done.contains(p)) continue;
56 p.unApplyQuadricToNeighbor();
59 public void recomputeAllFundamentalQuadrics() {
60 HashSet<Vert> done = new HashSet<Vert>();
62 for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() }) {
63 if (done.contains(p)) continue;
65 p.recomputeFundamentalQuadric();
68 public float applyQuadricToNeighborAll() {
71 HashSet<Vert> done = new HashSet<Vert>();
73 for(Vert p : new Vert[] { t.v1(), t.v2(), t.v3() }) {
74 if (done.contains(p)) continue;
76 p.applyQuadricToNeighbor();
79 return (float)(dist/num);
82 public void transform(Matrix m) {
83 ArrayList<Vert> set = new ArrayList<Vert>();
84 for (Vert v : vertices)
86 for(Vert v : set) v.transform(m);
89 public float volume() {
92 double area = t.area();
93 Vec origin_to_centroid = new Vec(new Point(0, 0, 0), t.centroid());
94 boolean facingAway = t.norm().dot(origin_to_centroid) > 0;
95 double height = Math.abs(t.norm().dot(origin_to_centroid));
96 total += ((facingAway ? 1 : -1) * area * height) / 3.0;
101 public void rebuild() { /*vertices.rebuild();*/ }
102 public Vec diagonal() { return vertices.diagonal(); }
103 public Point centroid() { return vertices.centroid(); }
104 public Vert nearest(Point p) { return vertices.nearest(p); }
106 public final class Vert extends HasPoint {
107 public String toString() { return p.toString(); }
109 E e; // some edge *leaving* this point
111 /** the nearest vertex in the "score_against" mesh */
112 Vert nearest_in_other_mesh;
113 /** the number of vertices in the other mesh for which this is the nearest_in_other_mesh */
115 /** the total error quadric (contributions from all vertices in other mesh for which this is nearest) */
116 Matrix quadric = Matrix.ZERO;
118 Vert bound_to = this;
119 Matrix binding = Matrix.ONE;
121 boolean quadricStale = false;
123 public Matrix errorQuadric() { return quadric; }
124 public Point getPoint() { return p; }
125 public float score() { return oldscore; }
127 private Matrix fundamentalQuadric = null;
128 public Matrix fundamentalQuadric() {
129 if (fundamentalQuadric == null) recomputeFundamentalQuadric();
130 return fundamentalQuadric;
133 private Vert(Point p) {
135 if (vertices.get(p) != null) throw new Error();
139 private void glNormal(GL gl) {
141 gl.glNormal3f(norm.x, norm.y, norm.z);
144 public void recomputeFundamentalQuadric() {
145 //if (!quadricStale && fundamentalQuadric != null) return;
146 quadricStale = false;
147 unApplyQuadricToNeighbor();
148 Matrix m = Matrix.ZERO;
153 m = m.plus(t.norm().fundamentalQuadric(t.centroid()));
156 } while(e != this.e);
157 fundamentalQuadric = m.times(1/(float)count);
158 applyQuadricToNeighbor();
161 public void unApplyQuadricToNeighbor() {
162 if (nearest_in_other_mesh == null) return;
163 if (fundamentalQuadric == null) return;
164 nearest_in_other_mesh.unComputeError();
165 nearest_in_other_mesh.quadric = nearest_in_other_mesh.quadric.minus(fundamentalQuadric);
166 nearest_in_other_mesh.quadric_count--;
167 if (nearest_in_other_mesh.quadric_count==0)
168 nearest_in_other_mesh.quadric = Matrix.ZERO;
169 nearest_in_other_mesh.computeError();
170 nearest_in_other_mesh = null;
173 public void applyQuadricToNeighbor() {
174 if (score_against == null) return;
176 Vert new_nearest = score_against.nearest(p);
177 if (nearest_in_other_mesh != null && new_nearest == nearest_in_other_mesh) return;
179 if (nearest_in_other_mesh != null) unApplyQuadricToNeighbor();
180 if (nearest_in_other_mesh != null) throw new Error();
182 nearest_in_other_mesh = new_nearest;
184 // don't attract to vertices that face the other way
185 if (nearest_in_other_mesh.e == null || nearest_in_other_mesh.norm().dot(norm()) < 0) {
186 nearest_in_other_mesh = null;
188 nearest_in_other_mesh.unComputeError();
189 nearest_in_other_mesh.quadric = nearest_in_other_mesh.quadric.plus(fundamentalQuadric());
190 nearest_in_other_mesh.quadric_count++;
191 nearest_in_other_mesh.computeError();
196 public void reComputeErrorAround() {
198 if (nearest_in_other_mesh != null) nearest_in_other_mesh.reComputeError();
201 e.p2.reComputeError();
203 } while (e != this.e);
205 public void reComputeError() {
209 public void unComputeError() {
213 public void computeError() {
214 if (quadric_count == 0) {
217 else if (nearest_in_other_mesh == null) {
218 if (score_against != null) {
219 Vert ne = score_against.nearest(p);
220 oldscore = ne.fundamentalQuadric().preAndPostMultiply(p) * 100 * 10;
225 oldscore = nearest_in_other_mesh.fundamentalQuadric().preAndPostMultiply(p) * 100 * 10;
228 oldscore = (quadric.preAndPostMultiply(p) * 100) / quadric_count;
237 //double ang = Math.abs(e.crossAngle());
238 double ang = Math.abs(e.crossAngle());
239 if (ang > Math.PI) throw new Error();
243 aspects += e.t.aspect()*e.t.aspect();
247 float minangle = (float)(Math.PI * 0.8);
249 oldscore += (ang - minangle);
252 } while (e != this.e);
253 if (numaspects > 0) oldscore += (aspects / numaspects);
255 //System.out.println(oldscore);
256 //oldscore = oldscore*oldscore;
260 private void removeTrianglesFromRTree() {
263 if (e.t != null) e.t.removeFromRTree();
265 } while(e != this.e);
267 private void addTrianglesToRTree() {
270 if (e.t != null) e.t.addToRTree();
272 } while(e != this.e);
275 /** does NOT update bound pairs! */
276 public boolean transform(Matrix m) {
277 unApplyQuadricToNeighbor();
280 if (vertices.get(this.p)==null) throw new Error();
281 vertices.remove(this);
282 removeTrianglesFromRTree();
283 float newx = m.a*p.x + m.b*p.y + m.c*p.z + m.d;
284 float newy = m.e*p.x + m.f*p.y + m.g*p.z + m.h;
285 float newz = m.i*p.x + m.j*p.y + m.k*p.z + m.l;
286 this.p = new Point(newx, newy, newz);
287 addTrianglesToRTree();
289 } catch (Exception e) {
290 throw new RuntimeException(e);
292 applyQuadricToNeighbor();
294 // FIXME: intersection test needed?
297 // should recompute fundamental quadrics of all vertices sharing a face, but we defer...
301 if (Math.abs(e.crossAngle()) > (Math.PI * 0.9) ||
302 Math.abs(e.next.crossAngle()) > (Math.PI * 0.9)) {
305 if (e.t.aspect() < 0.1) {
309 e.p2.quadricStale = true;
311 } while(e != this.e);
314 if (!ignorecollision && good) {
316 tris.range(new Segment(oldp, this.p),
318 public void visit(T t) {
322 if (!t.has(e.p1) && !t.has(e.p2) && e.intersects(t)) { good = false; }
324 if (!e.t.has(t.e1().p1) && !e.t.has(t.e1().p2) && t.e1().intersects(e.t)) { good = false; }
325 if (!e.t.has(t.e2().p1) && !e.t.has(t.e2().p2) && t.e2().intersects(e.t)) { good = false; }
326 if (!e.t.has(t.e3().p1) && !e.t.has(t.e3().p2) && t.e3().intersects(e.t)) { good = false; }
329 } while(e != Vert.this.e);
334 for(T t : Mesh.this) {
338 if (!t.has(e.p1) && !t.has(e.p2) && e.intersects(t)) { good = false; break; }
340 if (!e.t.has(t.e1().p1) && !e.t.has(t.e1().p2) && t.e1().intersects(e.t)) { good = false; break; }
341 if (!e.t.has(t.e2().p1) && !e.t.has(t.e2().p2) && t.e2().intersects(e.t)) { good = false; break; }
342 if (!e.t.has(t.e3().p1) && !e.t.has(t.e3().p2) && t.e3().intersects(e.t)) { good = false; break; }
345 } while(e != this.e);
351 reComputeErrorAround();
354 private boolean good;
356 public boolean move(Vec v) {
357 Matrix m = Matrix.translate(v);
361 good &= p.transform(m);
367 public E getFreeIncident() {
368 E ret = getFreeIncident(e, e);
369 if (ret != null) return ret;
370 ret = getFreeIncident(e.pair.next, e.pair.next);
374 System.out.println(ex + " " + ex.t);
377 throw new Error("unable to find free incident to " + this);
382 public E getFreeIncident(E start, E before) {
385 if (e.pair.p2 == this && e.pair.t == null && e.pair.next.t == null) return e.pair;
387 } while(e != before);
391 public E getE(Point p2) {
392 Vert v = vertices.get(p2);
393 if (v==null) return null;
396 public E getE(Vert p2) {
399 if (e==null) return null;
400 if (e.p1 == this && e.p2 == p2) return e;
407 Vec norm = new Vec(0, 0, 0);
410 if (e.t != null) norm = norm.plus(e.t.norm().times((float)e.prev.angle()));
412 } while(e != this.e);
416 public boolean isBoundTo(Vert p) {
419 if (px==this) return true;
424 public void unbind() { bound_to = this; binding = Matrix.ONE; }
425 public void bind(Vert p) { bind(p, Matrix.ONE); }
426 public void bind(Vert p, Matrix binding) {
427 if (isBoundTo(p)) return;
428 Vert temp_bound_to = p.bound_to;
429 Matrix temp_binding = p.binding;
430 p.bound_to = this.bound_to;
431 p.binding = binding.times(this.binding); // FIXME: may have order wrong here
432 this.bound_to = temp_bound_to;
433 this.binding = temp_binding.times(temp_binding); // FIXME: may have order wrong here
437 public class BindingGroup {
438 private HashSet<E> set = new HashSet<E>();
439 public BindingGroup bind_others;
440 public BindingGroup other() { return bind_others; }
441 public BindingGroup(BindingGroup bind_others) { this.bind_others = bind_others; }
442 public BindingGroup() { this.bind_others = new BindingGroup(this); }
443 public BindingGroup(E e) { this(); set.add(e); }
444 public void add(E e) {
445 if (set.contains(e)) return;
447 BindingGroup e_bind_peers = e.bind_peers;
448 BindingGroup e_bind_to = e.bind_to;
450 e.bind_to = bind_others;
451 for (E epeer : e_bind_peers.set) add(epeer);
452 for (E eother : e_bind_to.set) bind_others.add(eother);
454 for(E eother : bind_others.set) {
455 if (e.next.bind_to.set.contains(eother.prev)) {
456 e.next.next.bindEdge(eother.prev.prev);
458 if (e.prev.bind_to.set.contains(eother.next)) {
459 e.prev.prev.bindEdge(eother.next.next);
464 public void dobind(E e) {
465 for(E ebound : set) {
466 e.p1.bind(ebound.p2);
467 e.p2.bind(ebound.p1);
470 public void shatter(BindingGroup bg1, BindingGroup bg2) {
472 e.shatter(e.midpoint(), bg1, bg2);
477 /** [UNIQUE] an edge */
478 public final class E implements Comparable<E> {
480 public final Vert p1, p2;
481 T t; // triangle to our "left"
482 E prev; // previous half-edge
483 E next; // next half-edge
484 E pair; // partner half-edge
485 public BindingGroup bind_peers = new BindingGroup(this);
486 public BindingGroup bind_to = bind_peers.other();
487 boolean shattered = false;
489 public boolean intersects(T t) { return t.intersects(p1.p, p2.p); }
490 public float comparator() {
491 Vert nearest = score_against.nearest(midpoint());
492 //if (t==null) return length();
494 double ang = Math.abs(crossAngle());
495 float minangle = (float)(Math.PI * 0.9);
500 if ((length() * length()) / t.area() > 10)
501 return (float)(length()*Math.sqrt(t.area()));
502 return length()*t.area();
504 return (float)Math.max(length(), midpoint().distance(nearest.p));
507 public int compareTo(E e) {
508 return e.comparator() > comparator() ? 1 : -1;
510 public void bindEdge(E e) { bind_to.add(e); }
511 public void dobind() { bind_to.dobind(this); }
513 public Point shatter() { return shatter(midpoint(), null, null); }
514 public Point shatter(Point mid, BindingGroup bg1, BindingGroup bg2) {
515 if (shattered || destroyed) return mid;
522 int old_colorclass = t==null ? 0 : t.colorclass;
523 if (bg1==null) bg1 = new BindingGroup();
524 if (bg2==null) bg2 = new BindingGroup();
525 BindingGroup old_bind_to = bind_to;
526 bind_peers.shatter(bg1, bg2);
527 old_bind_to.shatter(bg2.other(), bg1.other());
531 newT(r.p, p1.p, mid, null, old_colorclass);
532 newT(r.p, mid, p2.p, null, old_colorclass);
533 bg1.add(p1.getE(mid));
534 bg2.add(p2.getE(mid).pair);
538 public boolean destroyed = false;
539 public void destroy() {
540 if (destroyed) return;
542 pair.destroyed = true;
544 if (t != null) t.destroy();
547 if (pair.t != null) pair.t.destroy();
550 if (next.t != null) next.t.destroy();
551 if (prev.t != null) prev.t.destroy();
555 if (pair.next.t != null) pair.next.t.destroy();
556 if (pair.prev.t != null) pair.next.t.destroy();
562 this.bind_peers = null;
563 pair.bind_peers = null;
564 pair.prev.next = next;
565 next.prev = pair.prev;
566 prev.next = pair.next;
568 if (p1.e == this) p1.e = prev.next;
569 if (pair.p1.e == pair) pair.p1.e = pair.prev.next;
570 avgedge -= this.length();
571 avgedge -= pair.length();
576 private void sync() {
577 this.prev.next = this;
578 this.next.prev = this;
579 this.pair.pair = this;
580 bind_peers.add(this);
581 if (this.next.p1 != p2) throw new Error();
582 if (this.prev.p2 != p1) throw new Error();
583 if (this.p1.e == null) this.p1.e = this;
590 private boolean added = false;
592 public T makeT(int colorclass) { return t==null ? (t = new T(this, colorclass)) : t; }
594 public double crossAngle() {
595 Vec v1 = t.norm().times(-1);
596 Vec v2 = pair.t.norm().times(-1);
597 return Math.acos(v1.norm().dot(v2.norm()));
600 /** angle between this half-edge and the next */
601 public double angle() {
602 Vec v1 = next.p2.p.minus(p2.p);
603 Vec v2 = this.p1.p.minus(p2.p);
604 return Math.acos(v1.norm().dot(v2.norm()));
607 public void makeAdjacent(E e) {
608 if (this.next == e) return;
609 if (p2 != e.p1) throw new Error("cannot make adjacent -- no shared vertex");
610 if (t != null || e.t != null) throw new Error("cannot make adjacent -- edges not both free");
612 E freeIncident = p2.getFreeIncident(e, this);
614 e.prev.next = freeIncident.next;
615 freeIncident.next.prev = e.prev;
617 freeIncident.next = this.next;
618 this.next.prev = freeIncident;
627 /** creates an isolated edge out in the middle of space */
628 public E(Point p1, Point p2) {
629 if (vertices.get(p1) != null) throw new Error();
630 if (vertices.get(p2) != null) throw new Error();
631 this.p1 = new Vert(p1);
632 this.p2 = new Vert(p2);
633 this.prev = this.next = this.pair = new E(this, this, this);
635 this.p2.e = this.pair;
639 /** adds a new half-edge from prev.p2 to p2 */
640 public E(E prev, Point p) {
642 p2 = vertices.get(p);
643 if (p2 == null) p2 = new Vert(p);
647 if (p2.getE(p1) != null) throw new Error();
649 this.next = this.pair = new E(this, this, prev.next);
651 E q = p2.getFreeIncident();
653 this.next.prev = this;
655 this.prev.next = this;
656 this.pair = new E(q, this, z);
658 if (p2.e==null) p2.e = this.pair;
662 /** adds a new half-edge to the mesh with a given predecessor, successor, and pair */
663 public E(E prev, E pair, E next) {
671 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); }
672 public boolean has(Vert v) { return v==p1 || v==p2; }
673 public float length() { return p1.p.minus(p2.p).mag(); }
674 public String toString() { return p1+"->"+p2; }
678 public E makeE(Point p1, Point p2) {
679 Vert v1 = vertices.get(p1);
680 Vert v2 = vertices.get(p2);
681 if (v1 != null && v2 != null) {
683 if (e != null) return e;
685 if (e != null) return e;
687 if (v1 != null) return new E(v1.getFreeIncident(), p2);
688 if (v2 != null) return new E(v2.getFreeIncident(), p1).pair;
689 return new E(p1, p2);
691 public T newT(Point p1, Point p2, Point p3, Vec norm, int colorclass) {
693 Vec norm2 = p3.minus(p1).cross(p2.minus(p1));
694 float dot = norm.dot(norm2);
695 //if (Math.abs(dot) < EPointSILON) throw new Error("dot products within evertsilon of each other: "+norm+" "+norm2);
696 if (dot < 0) { Point p = p1; p1=p2; p2 = p; }
698 E e12 = makeE(p1, p2);
699 E e23 = makeE(p2, p3);
700 E e31 = makeE(p3, p1);
701 while(e12.next != e23 || e23.next != e31 || e31.next != e12) {
702 e12.makeAdjacent(e23);
703 e23.makeAdjacent(e31);
704 e31.makeAdjacent(e12);
706 T ret = e12.makeT(colorclass);
707 if (e12.t == null) throw new Error();
708 if (e23.t == null) throw new Error();
709 if (e31.t == null) throw new Error();
714 /** [UNIQUE] a triangle (face) */
715 public final class T extends Triangle {
717 public final int color;
718 public final int colorclass;
720 public void removeFromRTree() { tris.remove(this); }
721 public void addToRTree() { tris.insert(this); }
723 public void destroy() { tris.remove(this); }
725 T(E e1, int colorclass) {
729 if (e1==e2 || e1==e3) throw new Error();
730 if (e3.next!=e1) throw new Error();
731 if (e1.t!=null || e2.t!=null || e3.t!=null) throw new Error("non-manifold surface or disagreeing normals");
734 e1.next.next.t = this;
736 // FIXME: check for sealed/watertight surface once construction is complete (and infer normal(s)?)
738 int color = Math.abs(random.nextInt());
741 if (e1().pair.t != null && color == e1().pair.t.color) { color++; continue; }
742 if (e2().pair.t != null && color == e2().pair.t.color) { color++; continue; }
743 if (e3().pair.t != null && color == e3().pair.t.color) { color++; continue; }
747 this.colorclass = colorclass;
750 public E e1() { return e1; }
751 public E e2() { return e1.next; }
752 public E e3() { return e1.prev; }
753 public Vert v1() { return e1.p1; }
754 public Vert v2() { return e1.p2; }
755 public Vert v3() { return e1.next.p2; }
756 public Point p1() { return e1.p1.p; }
757 public Point p2() { return e1.p2.p; }
758 public Point p3() { return e1.next.p2.p; }
759 public boolean hasE(E e) { return e1==e || e1.next==e || e1.prev==e; }
760 public boolean has(Vert v) { return v1()==v || v2()==v || v3()==v; }
762 public boolean shouldBeDrawn() {
763 if (e1().bind_to.set.size() == 0) return false;
764 if (e2().bind_to.set.size() == 0) return false;
765 if (e3().bind_to.set.size() == 0) return false;