naev
0.12.5
src
quadtree.h
1
/*
2
* This code was initially authored by the Stackoverflow user dragon-energy and
3
* posted under following page:
4
* https://stackoverflow.com/questions/41946007/efficient-and-well-explained-implementation-of-a-quadtree-for-2d-collision-det
5
*
6
* As for the license, the author has kindly noted:
7
*
8
* "Oh and feel free to use this code I post however you want, even for
9
* commercial projects. I would really love it if people let me know if they
10
* find it useful, but do as you wish."
11
*
12
* And generally all Stackoverflow-posted code is by default licensed with CC
13
* BY-SA 4.0: https://creativecommons.org/licenses/by-sa/4.0/
14
*/
15
#pragma once
16
17
#include "intlist.h"
18
19
typedef
struct
Quadtree
Quadtree
;
20
21
struct
Quadtree
{
22
// Stores all the nodes in the quadtree. The first node in this
23
// sequence is always the root.
24
IntList
nodes;
25
26
// Stores all the elements in the quadtree.
27
IntList
elts;
28
29
// Stores all the element nodes in the quadtree.
30
IntList
enodes;
31
32
// Stores the quadtree extents.
33
int
root_mx, root_my, root_sx, root_sy;
34
35
// Maximum allowed elements in a leaf before the leaf is subdivided/split
36
// unless the leaf is at the maximum allowed tree depth.
37
int
max_elements;
38
39
// Stores the maximum depth allowed for the quadtree.
40
int
max_depth;
41
42
// Temporary buffer used for queries.
43
44
char
*temp;
45
46
// Stores the size of the temporary buffer.
47
int
temp_size;
48
};
49
50
// Function signature used for traversing a tree node.
51
typedef
void
QtNodeFunc(
Quadtree
*qt,
void
*user_data,
int
node,
int
depth,
52
int
mx,
int
my,
int
sx,
int
sy );
53
54
// Creates a quadtree with the requested extents, maximum elements per leaf, and
55
// maximum tree depth.
56
void
qt_create(
Quadtree
*qt,
int
x1,
int
y1,
int
x2,
int
y2,
int
max_elements,
57
int
max_depth );
58
59
// Destroys the quadtree.
60
void
qt_destroy(
Quadtree
*qt );
61
62
// Clears the quadtree making it empty.
63
void
qt_clear(
Quadtree
*qt );
64
65
// Inserts a new element to the tree.
66
// Returns an index to the new element.
67
int
qt_insert(
Quadtree
*qt,
int
id
,
int
x1,
int
y1,
int
x2,
int
y2 );
68
69
// Removes the specified element from the tree.
70
void
qt_remove(
Quadtree
*qt,
int
element );
71
72
// Cleans up the tree, removing empty leaves.
73
void
qt_cleanup(
Quadtree
*qt );
74
75
// Outputs a list of elements found in the specified rectangle.
76
void
qt_query(
Quadtree
*qt,
IntList
*out,
int
x1,
int
y1,
int
x2,
int
y2 );
77
78
// Traverses all the nodes in the tree, calling 'branch' for branch nodes and
79
// 'leaf' for leaf nodes.
80
void
qt_traverse(
Quadtree
*qt,
void
*user_data, QtNodeFunc *branch,
81
QtNodeFunc *leaf );
IntList
Definition
intlist.h:20
Quadtree
Definition
quadtree.h:21
Generated by
1.14.0