-
Notifications
You must be signed in to change notification settings - Fork 1
/
node.go
133 lines (104 loc) · 2.07 KB
/
node.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package quadtree
const childCount = 4
type item[T any] struct {
Value T
Rect rect
}
type node[T any] struct {
Childs []*node[T]
Items []item[T]
Rect rect
}
func makeNode[T any](r rect) *node[T] {
return &node[T]{
Rect: r,
Childs: []*node[T]{},
}
}
func (n *node[T]) Grow(max, cur int) {
if cur > max {
return
}
n.Childs = make([]*node[T], childCount)
for i, r := range n.Rect.Split() {
n.Childs[i] = makeNode[T](r)
n.Childs[i].Grow(max, cur+1)
}
}
func (n *node[T]) Insert(r rect, value T) (ok bool) {
if !n.Rect.ContainsRect(r) {
return
}
for i := 0; i < len(n.Childs); i++ {
if c := n.Childs[i]; c.Rect.ContainsRect(r) {
return c.Insert(r, value)
}
}
n.Items = append(n.Items, item[T]{Rect: r, Value: value})
return true
}
func (n *node[T]) Search(r rect, iter func(*item[T]) bool) {
if !n.Rect.Overlaps(r) {
return
}
var it *item[T]
for i := 0; i < len(n.Items); i++ {
if it = &n.Items[i]; !it.Rect.Overlaps(r) {
continue
}
if !iter(it) {
return
}
}
for i := 0; i < len(n.Childs); i++ {
switch {
case r.ContainsRect(n.Childs[i].Rect):
if !n.Childs[i].ForEach(iter) {
return
}
case n.Childs[i].Rect.Overlaps(r):
n.Childs[i].Search(r, iter)
}
}
}
func (n *node[T]) ForEach(iter func(*item[T]) bool) (next bool) {
for i := 0; i < len(n.Items); i++ {
if !iter(&n.Items[i]) {
return false
}
}
for i := 0; i < len(n.Childs); i++ {
if !n.Childs[i].ForEach(iter) {
return false
}
}
return true
}
func (n *node[T]) Size() (total int) {
total = len(n.Items)
for i := 0; i < len(n.Childs); i++ {
total += n.Childs[i].Size()
}
return total
}
func (n *node[T]) Del(x, y float64) (it item[T], ok bool) {
if !n.Rect.ContainsPoint(x, y) {
return
}
for i := 0; i < len(n.Items); i++ {
if it = n.Items[i]; it.Rect.ContainsPoint(x, y) {
last := len(n.Items) - 1
if i != last {
n.Items[i] = n.Items[last]
}
n.Items = n.Items[:last]
return it, true
}
}
for i := 0; i < len(n.Childs); i++ {
if it, ok = n.Childs[i].Del(x, y); ok {
return it, ok
}
}
return
}