Created
December 20, 2016 19:19
-
-
Save fogleman/8b1e45e174f7c3a03de25643d11eb9d9 to your computer and use it in GitHub Desktop.
Simple Spatial Hash in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package path | |
type SpatialHash struct { | |
CellSize float64 | |
Cells map[SpatialHashKey][]interface{} | |
} | |
type SpatialHashKey struct { | |
X, Y int | |
} | |
func NewSpatialHash(cellSize float64) *SpatialHash { | |
cells := make(map[SpatialHashKey][]interface{}) | |
return &SpatialHash{cellSize, cells} | |
} | |
func (h *SpatialHash) KeyForPoint(point Vector) SpatialHashKey { | |
x := Round(point.X / h.CellSize) | |
y := Round(point.Y / h.CellSize) | |
return SpatialHashKey{x, y} | |
} | |
func (h *SpatialHash) Add(point Vector, data interface{}) { | |
key := h.KeyForPoint(point) | |
h.Cells[key] = append(h.Cells[key], data) | |
} | |
func (h *SpatialHash) Nearby(point Vector) []interface{} { | |
var result []interface{} | |
key := h.KeyForPoint(point) | |
for dx := -1; dx <= 1; dx++ { | |
for dy := -1; dy <= 1; dy++ { | |
k := SpatialHashKey{key.X + dx, key.Y + dy} | |
result = append(result, h.Cells[k]...) | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment