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 public class BindingGroup<T extends HasBindingGroup> implements Iterable<T> {
6
7     public Matrix krank = Matrix.ONE;
8
9     private T                  master   = null;
10     private HashMap<T,Matrix>  matrices = new HashMap<T,Matrix>();
11
12     public BindingGroup(T master) {
13         this.master = master;
14         matrices.put(master, Matrix.ONE);
15     }
16
17     public int size() { return matrices.size(); }
18
19     public void setKrank(Matrix k) { krank = krank.times(k); }
20     public void merge(BindingGroup<T> bg, Matrix m) {
21         if (bg==this) throw new Error();
22         for(HasBindingGroup hbg : bg.matrices.keySet()) {
23             matrices.put((T)hbg, bg.matrices.get(hbg).times(m));
24             hbg.bindingGroup = this;
25         }
26
27         Matrix v = getMatrix(bg.master, master);
28         //krank = krank.times(v.inverse().times(bg.krank).times(v));
29
30         HashSet<HasBindingGroup> stuff = new HashSet<HasBindingGroup>();
31         for(HasBindingGroup hbg : bg.matrices.keySet())
32             stuff.add(hbg);
33         bg.matrices.clear();
34         bg.master = null;
35         for(HasBindingGroup hbg : stuff)
36             hbg.bindingGroupChanged(this);
37     }
38
39     public T getMaster() { return master; }
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 }