]> git.itanic.dy.fi Git - sdl-planets/blob - quadtree.h
quadtree.c: Compare vectors, not quadtrees
[sdl-planets] / quadtree.h
1 #ifndef _QUADTREE_H_
2 #define _QUADTREE_H_
3
4 #include <string.h>
5
6 #include "utils.h"
7 #include "vector.h"
8
9 struct quadtree {
10         struct vector pos;
11         struct quadtree *child[4];
12         struct quadtree *parent;
13
14         /* statistics */
15         long int children;      /* The total number of children */
16         long int depth;         /* The deepest subtree branch */
17 };
18
19 struct quadtree_ops {
20         /*
21          * Calculates required statistical information for a node
22          */
23         void (*recalculate_stats)(struct quadtree *node);
24 };
25
26 static inline void init_quadtree(struct quadtree *t)
27 {
28         memset(t, 0, sizeof(*t));
29 }
30
31 #define QUADTREE_UPLEFT         0x1
32 #define QUADTREE_UPRIGHT        0x2
33 #define QUADTREE_DOWNLEFT       0x4
34 #define QUADTREE_DOWNRIGHT      0x8
35 #define QUADTREE_SELF           0x10
36
37 struct quadtree_iterator {
38         struct quadtree *head;
39         void *ptr;
40
41         int (*direction)(struct quadtree *head, struct quadtree_iterator *it);
42         void (*callback)(struct quadtree *head, struct quadtree_iterator *it);
43 };
44
45 struct quadtree *quadtree_add(struct quadtree *parent, struct quadtree *new,
46                               struct quadtree_ops *ops);
47
48 struct quadtree *quadtree_del(struct quadtree *node, struct quadtree_ops *ops);
49
50 int walk_quadtree(const struct quadtree_iterator *iterator);
51
52
53 /* quadtree_find_parent - return the highest parent of the node */
54 static inline struct quadtree *quadtree_find_parent(const struct quadtree *node)
55 {
56         struct quadtree *t = (struct quadtree *)node;
57         while (t->parent)
58                 t = t->parent;
59
60         return t;
61 }
62
63 /*
64  * Recursively walk through the tree and propagate changes made to the
65  * given node up until the highest parent.
66  */
67 static inline void quadtree_recalculate_parent_stats(struct quadtree *node,
68                                                      struct quadtree_ops *ops)
69 {
70         int i;
71
72         while (node) {
73                 node->depth = 0;
74                 node->children = 0;
75
76                 for (i = 0; i < 4; i++) {
77                         if (!node->child[i])
78                                 continue;
79
80                         node->depth = MAX(node->depth,
81                                           node->child[i]->depth + 1);
82                         node->children += node->child[i]->children + 1;
83                 }
84
85                 if (ops->recalculate_stats)
86                         ops->recalculate_stats(node);
87
88                 node = node->parent;
89         }
90 }
91
92 #endif