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