checkpoint
[anneal.git] / src / edu / berkeley / qfat / geom / BindingGroup.java
1 package edu.berkeley.qfat.geom;
2 import javax.media.opengl.*;
3 import java.util.*;
4
5 /** tracks an equivalence class of geometric objects which are related to each other by transformation matrices */
6 public class BindingGroup<T extends HasBindingGroup> implements Iterable<T> {
7
8     public Matrix krank = Matrix.ONE;
9
10     private T                  master   = null;
11     private HashMap<T,Matrix>  matrices = new HashMap<T,Matrix>();
12
13     public BindingGroup(T master) {
14         this.master = master;
15         matrices.put(master, Matrix.ONE);
16     }
17
18     public int size() { return matrices.size(); }
19
20     public void setKrank(Matrix k) { krank = krank.times(k); }
21     public void merge(BindingGroup<T> bg, Matrix m) {
22         if (bg==this) throw new Error();
23         for(HasBindingGroup hbg : bg.matrices.keySet()) {
24             matrices.put((T)hbg, bg.matrices.get(hbg).times(m));
25             hbg.bindingGroup = this;
26         }
27
28         Matrix v = getMatrix(bg.master, master);
29         //krank = krank.times(v.inverse().times(bg.krank).times(v));
30
31         HashSet<HasBindingGroup> stuff = new HashSet<HasBindingGroup>();
32         for(HasBindingGroup hbg : bg.matrices.keySet())
33             stuff.add(hbg);
34         bg.matrices.clear();
35         bg.master = null;
36         for(HasBindingGroup hbg : stuff)
37             hbg.bindingGroupChanged(this);
38     }
39
40     public Matrix getMatrix(T t) { return matrices.get(t); }
41
42     public Iterator<T> iterator() { return matrices.keySet().iterator(); }
43
44     /** t1 = getMatrix(t1, t2) * t2 */
45     public Matrix getMatrix(T t1, T t2) {
46         //                    t1 = getMatrix(t1) * master
47         // getMatrix(t2)^-1 * t2 =                 master
48         //                    t1 = getMatrix(t1) * getMatrix(t2)^-1 * t2
49         return getMatrix(t1).times(getMatrix(t2).inverse());
50     }
51
52     public void unbind(T trem) {
53         if (trem != master) {
54             matrices.remove(trem);
55             return;
56         }
57         if (matrices.size()==1) {
58             master = null;
59             matrices.remove(trem);
60             return;
61         }
62         Iterator<T> it = iterator();
63         T newmaster = it.next();
64         if (newmaster==trem) newmaster = it.next();
65         if (newmaster==trem) throw new Error();
66         HashMap<T,Matrix> newmatrices = new HashMap<T,Matrix>();
67         for(T t : matrices.keySet()) {
68             if (t==trem) continue;
69             newmatrices.put(t, getMatrix(t, newmaster));
70         }
71         master = newmaster;
72         matrices = newmatrices;
73     }
74
75     public boolean contains(HasBindingGroup t) {
76         return matrices.get((T)t) != null;
77     }
78 }