-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomponent.go
293 lines (257 loc) · 7.14 KB
/
component.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
package ecs
import (
"encoding/json"
"fmt"
"reflect"
"sort"
"github.com/BurntSushi/toml"
"github.com/gabstv/container"
)
// ComponentType is a data type that has a Pkg() function.
// It is used to identify a component type.
// It must be unique per type in a world.
type ComponentType interface {
Pkg() string
}
// ComponentData holds the data T of an Entity.
type ComponentData[T ComponentType] struct {
Entity Entity
Data T
}
// IComponentStore is an interface for component stores.
type IComponentStore interface {
Contains(e Entity) bool
Remove(e Entity) bool
MergeJSONData(e Entity, jd []byte) error
dataExtract(fn func(e Entity, d interface{}))
dataImport(e Entity, d toml.Primitive, md toml.MetaData) error
dataOf(e Entity) interface{}
typeMatch(d interface{}) bool
}
// ComponentStore[T ComponentType] is a component data storage. The component data
// is stored in a slice ordered by the Entity (ID; ascending).
type ComponentStore[T ComponentType] struct {
// data is an ordered entity slice of all entities that have this component.
data []ComponentData[T]
world *World
zerov T
isptr *bool
watchers container.Set[*ComponentWatcher[T]]
}
// Apply passes a pointer of the component data to the function fn.
// This is used to read or update data in the component.
func (c *ComponentStore[T]) Apply(e Entity, fn func(*T)) bool {
index, exists := c.getIndex(e)
if !exists {
return false
}
x := &c.data[index]
fn(&x.Data)
return true
}
// Contains returns true if the entity has data of this component store.
func (c *ComponentStore[T]) Contains(e Entity) bool {
_, exists := c.getIndex(e)
return exists
}
// MergeJSONData unmarshals the data into the component type of this component store.
func (c *ComponentStore[T]) MergeJSONData(e Entity, jd []byte) error {
zv, _ := c.getCopy(e)
if err := json.Unmarshal(jd, &zv); err != nil {
return err
}
c.Replace(e, zv)
return nil
}
// Remove removes the component data from this component store. It returns true
// if the component data was found (and then removed).
func (c *ComponentStore[T]) Remove(e Entity) bool {
index, exists := c.getIndex(e)
if !exists {
return false
}
c.data = append(c.data[:index], c.data[index+1:]...)
c.watchers.Each(func(w *ComponentWatcher[T]) {
w.ComponentRemoved(e)
})
return true
}
// Replace adds or replaces the component data for the given entity.
func (c *ComponentStore[T]) Replace(e Entity, data T) {
// add to c.data
index, exists := c.getIndex(e)
if exists {
c.setDataAt(index, data)
return
}
// insert data at index
c.data = Insert(c.data, index, ComponentData[T]{e, data})
c.watchers.Each(func(w *ComponentWatcher[T]) {
w.ComponentAdded(e)
})
}
// ComponentStore[T] privates
func (c *ComponentStore[T]) all() []ComponentData[T] {
return c.data
}
func (c *ComponentStore[T]) dataExtract(fn func(e Entity, d interface{})) {
for _, v := range c.all() {
fn(v.Entity, v.Data)
}
}
func (c *ComponentStore[T]) dataImport(e Entity, d toml.Primitive, md toml.MetaData) error {
x := c.newType()
if c.isPointerType() {
if err := md.PrimitiveDecode(d, x); err != nil {
return fmt.Errorf("failed to decode component %T: %v", x, err)
}
} else {
if err := md.PrimitiveDecode(d, &x); err != nil {
return fmt.Errorf("failed to decode component %T: %v", x, err)
}
}
c.Replace(e, x)
return nil
}
func (c *ComponentStore[T]) dataOf(e Entity) interface{} {
i, exists := c.getIndex(e)
if !exists {
return nil
}
return c.data[i].Data
}
func (c *ComponentStore[T]) getCopy(e Entity) (T, bool) {
index, exists := c.getIndex(e)
if !exists {
return c.zerov, false
}
return c.data[index].Data, true
}
// getIndex does a binary search on c.data for the index of the entity
func (c *ComponentStore[T]) getIndex(e Entity) (int, bool) {
return getIndex(c.data, e)
}
func (c *ComponentStore[T]) isPointerType() bool {
if c.isptr == nil {
//TODO: consider dropping support of pointer types to avoid using
// reflect entirely.
if reflect.ValueOf(c.zerov).Kind() == reflect.Ptr {
isptr := true
c.isptr = &isptr
} else {
isptr := false
c.isptr = &isptr
}
}
return *c.isptr
}
func (c *ComponentStore[T]) newType() T {
if c.isPointerType() {
//TODO: consider dropping support of pointer types to avoid using
// reflect entirely.
return reflect.New(reflect.TypeOf(c.zerov)).Interface().(T)
}
var y T
return y
}
func (c *ComponentStore[T]) setDataAt(index int, data T) {
c.data[index].Data = data
}
func (c *ComponentStore[T]) typeMatch(d interface{}) bool {
if d == nil {
return false
}
_, ok := d.(T)
return ok
}
type ComponentIndexEntry struct {
Name string
Index int
}
type ComponentIndex []ComponentIndexEntry
func (e ComponentIndex) ToMap() map[string]int {
m := make(map[string]int)
for _, v := range e {
m[v.Name] = v.Index
}
return m
}
// static fns
// Apply updates the component data for the given entity.
func Apply[T ComponentType](w *World, e Entity, fn func(*T)) bool {
c := GetComponentStore[T](w)
return c.Apply(e, fn)
}
// Contains returns true if the given entity has the given component.
func Contains[T ComponentType](w *World, e Entity) bool {
c := GetComponentStore[T](w)
return c.Contains(e)
}
// GetComponentStore returns the component store for the given component type and
// world instance.
func GetComponentStore[T ComponentType](w *World) *ComponentStore[T] {
if w.components == nil {
w.components = make(map[string]IComponentStore)
}
var zv T
if c, ok := w.components[zv.Pkg()]; ok {
return c.(*ComponentStore[T])
}
c := &ComponentStore[T]{
data: make([]ComponentData[T], 0),
world: w,
}
w.components[zv.Pkg()] = c
return c
}
// RemoveComponent removes the component data for the given entity.
// It returns false if the component was not found.
func RemoveComponent[T ComponentType](w *World, e Entity) bool {
c := GetComponentStore[T](w)
return c.Remove(e)
}
// Set replaces or inserts the component data for the given entity.
// If you junst need to update a value, use Apply() instead.
func Set[T ComponentType](w *World, e Entity, data T) {
c := GetComponentStore[T](w)
c.Replace(e, data)
}
func componentIndexFromMap(m map[string]int) ComponentIndex {
x := make([]ComponentIndexEntry, 0, len(m))
for k, v := range m {
x = append(x, ComponentIndexEntry{
Name: k,
Index: v,
})
}
sort.SliceStable(x, func(i, j int) bool {
return x[i].Index < x[j].Index
})
return ComponentIndex(x)
}
// getEntityIndex does a binary search on an entity slice
func getEntityIndex(slc []Entity, e Entity) (int, bool) {
x := sort.Search(len(slc), func(i int) bool {
return slc[i] >= e
})
if x < len(slc) && slc[x] == e {
// x is present at data[i]
return x, true
}
// x is not present in data,
// but i is the index where it would be inserted.
return x, false
}
// getIndex does a binary search on c.data for the index of the entity
func getIndex[T ComponentType](slc []ComponentData[T], e Entity) (int, bool) {
x := sort.Search(len(slc), func(i int) bool {
return slc[i].Entity >= e
})
if x < len(slc) && slc[x].Entity == e {
// x is present at data[i]
return x, true
}
// x is not present in data,
// but i is the index where it would be inserted.
return x, false
}