checkpoint autogen tile
[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 merge(BindingGroup<T> bg, Matrix m) {
20         if (bg==this) throw new Error();
21         for(HasBindingGroup hbg : bg.matrices.keySet()) {
22             matrices.put((T)hbg, bg.matrices.get(hbg).times(m));
23             hbg.bindingGroup = this;
24         }
25         HashSet<HasBindingGroup> stuff = new HashSet<HasBindingGroup>();
26         for(HasBindingGroup hbg : bg.matrices.keySet())
27             stuff.add(hbg);
28         bg.matrices.clear();
29         bg.master = null;
30         for(HasBindingGroup hbg : stuff)
31             hbg.bindingGroupChanged(this);
32     }
33
34     public T getMaster() { return master; }
35     public Matrix getMatrix(T t) { return matrices.get(t); }
36
37     public Iterator<T> iterator() { return matrices.keySet().iterator(); }
38
39     /** t1 = getMatrix(t1, t2) * t2 */
40     public Matrix getMatrix(T t1, T t2) {
41         //                    t1 = getMatrix(t1) * master
42         // getMatrix(t2)^-1 * t2 =                 master
43         //                    t1 = getMatrix(t1) * getMatrix(t2)^-1 * t2
44         return getMatrix(t1).times(getMatrix(t2).inverse());
45     }
46
47     public void unbind(T trem) {
48         if (trem != master) {
49             matrices.remove(trem);
50             return;
51         }
52         if (matrices.size()==1) {
53             master = null;
54             matrices.remove(trem);
55             return;
56         }
57         Iterator<T> it = iterator();
58         T newmaster = it.next();
59         if (newmaster==trem) newmaster = it.next();
60         if (newmaster==trem) throw new Error();
61         HashMap<T,Matrix> newmatrices = new HashMap<T,Matrix>();
62         for(T t : matrices.keySet()) {
63             if (t==trem) continue;
64             newmatrices.put(t, getMatrix(t, newmaster));
65         }
66         master = newmaster;
67         matrices = newmatrices;
68     }
69
70     public boolean contains(HasBindingGroup t) {
71         return matrices.get((T)t) != null;
72     }
73 }