This repository has been archived by the owner on Aug 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
voronoi.go
85 lines (68 loc) · 2.11 KB
/
voronoi.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
package pixelutils
import (
"github.com/faiface/pixel"
"github.com/pzsz/voronoi"
)
// This is an pixel-conversion interface for https://github.com/pzsz/voronoi
type voronoiMap map[interface{}]voronoi.Vertex
type VoronoiCellMap map[interface{}]VoronoiCell
type VoronoiCell struct {
ID interface{}
Site pixel.Vec
Halfedges []pixel.Line
}
type Voronoi struct {
siteMap voronoiMap
sites []voronoi.Vertex
}
// helper to convert voronoi's vertex to pixel.Vec
func convertVVertex(vertex voronoi.Vertex) pixel.Vec {
return pixel.V(vertex.X, vertex.Y)
}
// Creates and returns a new pixel-compatible Voronoi
func NewVoronoi() (v *Voronoi) {
v = &Voronoi{}
v.siteMap = make(voronoiMap)
v.sites = make([]voronoi.Vertex, 0)
return
}
// Inserts the vector into the voronoi list with the given identifier
func (v *Voronoi) Insert(id interface{}, pos pixel.Vec) {
vert := voronoi.Vertex{
X: pos.X,
Y: pos.Y,
}
v.sites = append(v.sites, vert)
v.siteMap[id] = vert
}
// Computes the voronoi diagram, constrained by the given bounding box, from the nodes inserted into the list
// If closeCells == true, edges from bounding box will be included in the diagram.
func (v *Voronoi) Compute(boundingBox pixel.Rect, closeCells bool) VoronoiCellMap {
bb := voronoi.NewBBox(boundingBox.Min.X, boundingBox.Max.X, boundingBox.Min.Y, boundingBox.Max.Y)
diagram := voronoi.ComputeDiagram(v.sites, bb, closeCells)
return v.convert(diagram)
}
// helper function to conver the internal voronoi diagram to a pixel-compatible one
func (v *Voronoi) convert(diagram *voronoi.Diagram) VoronoiCellMap {
cells := make(VoronoiCellMap)
var ID interface{}
for _, vCell := range diagram.Cells {
ID = -1
for id, v := range v.siteMap {
if v.X == vCell.Site.X && v.Y == vCell.Site.Y {
ID = id
break
}
}
cell := VoronoiCell{
ID: ID,
Site: convertVVertex(vCell.Site),
}
cell.Halfedges = make([]pixel.Line, 0)
for _, edge := range vCell.Halfedges {
cell.Halfedges = append(cell.Halfedges, pixel.L(convertVVertex(edge.GetStartpoint()), convertVVertex(edge.GetEndpoint())))
}
cells[ID] = cell
}
return cells
}