checkpoint i think it works!
[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 public class BindingGroup<T extends HasBindingGroup> implements Iterable<T> {
6
7     private T                  master   = null;
8     private HashMap<T,Matrix>  matrices = new HashMap<T,Matrix>();
9
10     public BindingGroup(T master) {
11         this.master = master;
12         matrices.put(master, Matrix.ONE);
13     }
14
15     public int size() { return matrices.size(); }
16
17     public void merge(BindingGroup<T> bg, Matrix m) {
18         if (bg==this) throw new Error();
19         for(HasBindingGroup hbg : bg.matrices.keySet()) {
20             matrices.put((T)hbg, bg.matrices.get(hbg).times(m));
21             hbg.bindingGroup = this;
22         }
23         for(HasBindingGroup hbg : bg.matrices.keySet())
24             hbg.bindingGroupChanged(this);
25         bg.matrices.clear();
26         bg.master = null;
27     }
28
29     public T getMaster() { return master; }
30     public Matrix getMatrix(T t) { return matrices.get(t); }
31
32     public Iterator<T> iterator() { return matrices.keySet().iterator(); }
33
34     /** t1 = getMatrix(t1, t2) * t2 */
35     public Matrix getMatrix(T t1, T t2) {
36         //                    t1 = getMatrix(t1) * master
37         // getMatrix(t2)^-1 * t2 =                 master
38         //                    t1 = getMatrix(t1) * getMatrix(t2)^-1 * t2
39         return getMatrix(t1).times(getMatrix(t2).inverse());
40     }
41
42     public void unbind(T trem) {
43         if (trem != master) {
44             matrices.remove(trem);
45             return;
46         }
47         if (matrices.size()==1) {
48             master = null;
49             matrices.remove(trem);
50             return;
51         }
52         Iterator<T> it = iterator();
53         T newmaster = it.next();
54         if (newmaster==trem) newmaster = it.next();
55         if (newmaster==trem) throw new Error();
56         HashMap<T,Matrix> newmatrices = new HashMap<T,Matrix>();
57         for(T t : matrices.keySet()) {
58             if (t==trem) continue;
59             newmatrices.put(t, getMatrix(t, newmaster));
60         }
61         master = newmaster;
62         matrices = newmatrices;
63     }
64
65     public boolean contains(HasBindingGroup t) {
66         return matrices.get((T)t) != null;
67     }
68 }