diff --git a/stuff/tree/main.pde b/stuff/tree/main.pde new file mode 100644 index 0000000..bd1711a --- /dev/null +++ b/stuff/tree/main.pde @@ -0,0 +1,18 @@ + +kd_tree t; +void settings() +{ + size(512, 512); + t = new kd_tree(new Point(256,256), false); +} +void mouseReleased() +{ + Point pt = new Point(mouseX, mouseY); + ellipse(pt.x,pt.y,5,5); + t.insert(pt); +} +void draw() +{ + // println(t.left); + //println(t.right); +} \ No newline at end of file diff --git a/stuff/tree/tree.pde b/stuff/tree/tree.pde new file mode 100644 index 0000000..c4ecb2d --- /dev/null +++ b/stuff/tree/tree.pde @@ -0,0 +1,94 @@ +class Point +{ + float x,y; + public Point(float _x, float _y) + { + x = _x; + y = _y; + } +} + +class kd_tree +{ + Point loc; + kd_tree left, right; + private boolean dir;//vertical if true, horizontal if false + public kd_tree(Point p, boolean vert) + { + loc = p; + dir = vert; + } + void insert(Point p) + { + //insert by cycling through dimensions + kd_tree parent = search(p); + //print(parent + " "); + if(parent.dir == true) + { + line(p.x, 0, p.x, 512); + if(parent.loc.x > p.x) + { + parent.left = new kd_tree(p, !parent.dir); + + } + else + { + parent.right = new kd_tree(p, !parent.dir); + } + } + else + { + line(0, p.y, 512, p.y); + if(parent.loc.y < p.y) + { + parent.left = new kd_tree(p, !parent.dir); + } + else + { + parent.right = new kd_tree(p, !parent.dir); + } + } + + line(p.x, p.y, parent.loc.x, parent.loc.y); + + } + + kd_tree search(Point p) + { + //search for the cell containing this point + if(dir) + { + if(p.x < loc.x) + { + if(left!=null) + return left.search(p); + else + return this; + } + else + { + if(right!=null) + return right.search(p); + else + return this; + } + } + else + { + if(p.y < loc.y) + { + if(left!=null) + return left.search(p); + else + return this; + } + else + { + if(right!=null) + return right.search(p); + else + return this; + } + } + } +} \ No newline at end of file