forked from psykhi/wordclouds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspatialhashmap.go
74 lines (64 loc) · 1.53 KB
/
spatialhashmap.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
package wordclouds
import (
"github.com/satori/go.uuid"
)
type uniqueBox struct {
uuid.UUID
b *Box
}
type spatialHashMap struct {
mat [][][]*uniqueBox
rw float64
rh float64
gridSize int
}
func (s *spatialHashMap) TestCollision(b *Box, test func(a *Box, b *Box) bool) (bool, int) {
overlaps := 0
top, left, right, bottom := s.toGridCoords(b)
for i := left; i <= right; i++ {
for j := bottom; j <= top; j++ {
for _, ub := range s.mat[i][j] {
overlaps++
if test(ub.b, b) {
return true, overlaps
}
}
}
}
return false, overlaps
}
func (s *spatialHashMap) Add(b *Box) {
id := uuid.NewV4()
top, left, right, bottom := s.toGridCoords(b)
for i := left; i <= right; i++ {
for j := bottom; j <= top; j++ {
s.mat[i][j] = append(s.mat[i][j], &uniqueBox{id, b})
}
}
}
func newSpatialHashMap(windowWidth float64, windowHeight float64, gridSize int) *spatialHashMap {
rw := windowWidth / float64(gridSize)
rh := windowHeight / float64(gridSize)
mat := make([][][]*uniqueBox, gridSize)
for i := 0; i < gridSize; i++ {
mat[i] = make([][]*uniqueBox, gridSize)
for j := 0; j < gridSize; j++ {
mat[i][j] = make([]*uniqueBox, 0)
}
}
return &spatialHashMap{
mat: mat,
rw: rw,
rh: rh,
gridSize: gridSize,
}
}
func min(a int, b int) int {
if a < b {
return a
}
return b
}
func (s *spatialHashMap) toGridCoords(b *Box) (int, int, int, int) {
return min(int(b.Top/s.rh), s.gridSize-1), int(b.Left / s.rw), min(int(b.Right/s.rw), s.gridSize-1), int(b.Bottom / s.rh)
}