tile38/pkg/index/rtree/rtree.go

78 lines
2.0 KiB
Go
Raw Normal View History

2016-03-05 02:08:16 +03:00
package rtree
import "github.com/tidwall/tile38/pkg/index/rtreebase"
2017-08-11 03:32:40 +03:00
2016-03-05 02:08:16 +03:00
// Item is an rtree item
type Item interface {
2016-10-03 21:37:16 +03:00
Rect() (minX, minY, minZ, maxX, maxY, maxZ float64)
2016-03-05 02:08:16 +03:00
}
// Rect is a rectangle
type Rect struct {
2016-10-03 21:37:16 +03:00
MinX, MinY, MinZ, MaxX, MaxY, MaxZ float64
2016-03-05 02:08:16 +03:00
}
// Rect returns the rectangle
2016-10-03 21:37:16 +03:00
func (item *Rect) Rect() (minX, minY, minZ, maxX, maxY, maxZ float64) {
return item.MinX, item.MinY, item.MinZ, item.MaxX, item.MaxY, item.MaxZ
2016-03-05 02:08:16 +03:00
}
// RTree is an implementation of an rtree
type RTree struct {
2017-08-11 03:32:40 +03:00
tr *rtreebase.RTree
2016-03-05 02:08:16 +03:00
}
// New creates a new RTree
func New() *RTree {
2016-10-03 03:28:23 +03:00
return &RTree{
2017-08-11 03:32:40 +03:00
tr: rtreebase.New(),
2016-10-03 03:28:23 +03:00
}
2016-03-05 02:08:16 +03:00
}
// Insert inserts item into rtree
func (tr *RTree) Insert(item Item) {
2017-08-11 03:32:40 +03:00
minX, minY, _, maxX, maxY, _ := item.Rect()
tr.tr.Insert([2]float64{minX, minY}, [2]float64{maxX, maxY}, item)
2016-03-05 02:08:16 +03:00
}
// Remove removes item from rtree
func (tr *RTree) Remove(item Item) {
2017-08-11 03:32:40 +03:00
minX, minY, _, maxX, maxY, _ := item.Rect()
tr.tr.Remove([2]float64{minX, minY}, [2]float64{maxX, maxY}, item)
2016-03-05 02:08:16 +03:00
}
// Search finds all items in bounding box.
2017-08-11 03:32:40 +03:00
func (tr *RTree) Search(minX, minY, minZ, maxX, maxY, maxZ float64, iterator func(data interface{}) bool) {
// start := time.Now()
// var count int
tr.tr.Search([2]float64{minX, minY}, [2]float64{maxX, maxY}, func(data interface{}) bool {
// count++
return iterator(data)
2016-10-03 03:28:23 +03:00
})
2017-08-11 03:32:40 +03:00
// dur := time.Since(start)
// fmt.Printf("%s %d\n", dur, count)
2016-03-05 02:08:16 +03:00
}
// Count return the number of items in rtree.
func (tr *RTree) Count() int {
2016-10-03 03:28:23 +03:00
return tr.tr.Count()
2016-03-05 02:08:16 +03:00
}
// RemoveAll removes all items from rtree.
func (tr *RTree) RemoveAll() {
2017-08-11 03:32:40 +03:00
tr.tr = rtreebase.New()
2016-03-05 02:08:16 +03:00
}
2017-08-11 03:32:40 +03:00
// Bounds returns the bounds of the R-tree
func (tr *RTree) Bounds() (minX, minY, maxX, maxY float64) {
min, max := tr.tr.Bounds()
return min[0], min[1], max[0], max[1]
}
// NearestNeighbors gets the closest Spatials to the Point.
func (tr *RTree) NearestNeighbors(x, y float64, iter func(item interface{}, dist float64) bool) bool {
return tr.tr.KNN([2]float64{x, y}, [2]float64{x, y}, true, func(item interface{}, dist float64) bool {
return iter(item, dist)
})
2016-08-19 18:04:18 +03:00
}