/
objectSet.go
executable file
·135 lines (120 loc) · 2.54 KB
/
objectSet.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package img
import (
"bytes"
"fmt"
"image/color"
"image/draw"
"sync"
)
//objectSet is the list of objects inside an image map[idObj]obj
type objectSet struct {
objs map[int]*object
mtx sync.RWMutex
}
func newObjectset() *objectSet {
return &objectSet{objs: make(map[int]*object)}
}
//objectsInLastRow obtains the objectSet which contains a list of objects in the last row
func (os *objectSet) objectsInLastRow(row int) (o *objectSet) {
o = newObjectset()
os.mtx.RLock()
defer os.mtx.RUnlock()
for id, obj := range os.objs {
points := obj.get(row - 1)
if points != nil {
o.set(id, obj)
}
}
return
}
func (os *objectSet) add(toAdd *object) {
os.mtx.Lock()
defer os.mtx.Unlock()
id := len(os.objs)
for os.objs[id] != nil {
id += 2
}
toAdd.id = id
os.objs[id] = toAdd
}
func (os *objectSet) drop(toDrop ...int) {
os.mtx.Lock()
defer os.mtx.Unlock()
for _, obj := range toDrop {
delete(os.objs, obj)
}
}
func (os *objectSet) append(toAppend *objectSet) {
toAppend.mtx.RLock()
defer toAppend.mtx.RUnlock()
for _, obj := range toAppend.objs {
os.add(obj)
}
}
func (os *objectSet) update(changes *objectSet) {
os.mtx.Lock()
defer os.mtx.Unlock()
for id, obj := range changes.objs {
os.objs[id] = obj
}
}
func (os *objectSet) groupObjects(dest int, toBeAppened *object) {
os.mtx.Lock()
defer os.mtx.Unlock()
original := os.objs[dest]
for row, points := range toBeAppened.points {
newpoints := append(original.get(row), points...)
original.set(row, newpoints)
}
os.objs[original.id] = original
}
func (os *objectSet) String() string {
os.mtx.RLock()
defer os.mtx.RUnlock()
buf := new(bytes.Buffer)
for id := range os.objs {
fmt.Fprintf(buf, "%d\t", id)
//fmt.Fprintf(buf, "%s \n\n", obj.String())
}
return buf.String()
}
func (os *objectSet) filter(minSize int) (s *objectSet) {
os.mtx.RLock()
defer os.mtx.RUnlock()
s = newObjectset()
for id, obj := range os.objs {
if obj.len() >= minSize {
s.objs[id] = obj
}
}
return
}
func (os *objectSet) draw(img draw.Image) {
os.mtx.RLock()
defer os.mtx.RUnlock()
colors := randColors(len(os.objs))
idx := 0
for _, o := range os.objs {
o.draw(img, colors[idx])
idx++
}
}
func (os *objectSet) drawWithColor(img draw.Image, color color.Color) {
os.mtx.RLock()
defer os.mtx.RUnlock()
idx := 0
for _, o := range os.objs {
o.draw(img, color)
idx++
}
}
func (os *objectSet) get(i int) *object {
os.mtx.RLock()
defer os.mtx.RUnlock()
return os.objs[i]
}
func (os *objectSet) set(i int, o *object) {
os.mtx.Lock()
defer os.mtx.Unlock()
os.objs[i] = o
}