Skip to content

Commit c77f755

Browse files
committed
improved quadtree, kdtree tests and benchmarks
1 parent 4f3b135 commit c77f755

File tree

10 files changed

+1173
-96
lines changed

10 files changed

+1173
-96
lines changed

kdtree.go

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package sketchy
22

3-
import "github.com/tdewolff/canvas"
3+
import (
4+
"container/heap"
5+
"github.com/tdewolff/canvas"
6+
)
47

58
type KDTree struct {
69
point *Point
@@ -67,6 +70,27 @@ func (k *KDTree) Query(r Rect) []Point {
6770
return results
6871
}
6972

73+
func (k *KDTree) NearestNeighbors(point Point, s int) []Point {
74+
var result []Point
75+
if s <= 0 {
76+
return result
77+
}
78+
ph := &PointHeap{
79+
size: s,
80+
points: []MetricPoint{},
81+
}
82+
heap.Init(ph)
83+
k.pushOnHeap(point, ph)
84+
result = ph.Report()
85+
return result
86+
}
87+
88+
func (k *KDTree) Clear() {
89+
k.point = nil
90+
k.left = nil
91+
k.right = nil
92+
}
93+
7094
func (k *KDTree) Size() int {
7195
count := 1
7296
if k.left != nil {
@@ -86,12 +110,6 @@ func (k *KDTree) DrawWithPoints(s float64, ctx *canvas.Context) {
86110
k.draw(ctx, 0, s)
87111
}
88112

89-
func (k *KDTree) Clear() {
90-
k.point = nil
91-
k.left = nil
92-
k.right = nil
93-
}
94-
95113
func (k *KDTree) insert(p Point, d int) {
96114
if k.point == nil {
97115
k.point = &p
@@ -188,3 +206,18 @@ func (k *KDTree) draw(ctx *canvas.Context, depth int, pointSize float64) {
188206
k.right.draw(ctx, depth+1, pointSize)
189207
}
190208
}
209+
210+
func (k *KDTree) pushOnHeap(target Point, h *PointHeap) {
211+
if k.point != nil {
212+
heap.Push(h, MetricPoint{
213+
Metric: SquaredDistance(target, *k.point),
214+
Point: *k.point,
215+
})
216+
}
217+
if k.left != nil {
218+
k.left.pushOnHeap(target, h)
219+
}
220+
if k.right != nil {
221+
k.right.pushOnHeap(target, h)
222+
}
223+
}

0 commit comments

Comments
 (0)