-
Notifications
You must be signed in to change notification settings - Fork 0
/
world.go
349 lines (328 loc) · 8.94 KB
/
world.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package ecs
import (
"context"
"fmt"
"sync"
"sync/atomic"
"time"
)
// SystemExecWrapper is used to alter every system exec
// upon registering a system
type SystemExecWrapper func(*World, SystemExec) SystemExec
// DefaultSystemExecWrapper is called when the system is added
// to a world. It is used if the World's SystemExecWrapper is unset.
var DefaultSystemExecWrapper SystemExecWrapper = func(w *World, x SystemExec) SystemExec {
return x
}
// World is the "world" that entities, components and systems live and interact.
type World struct {
SystemExecWrapper SystemExecWrapper
// lock for nextEntity, entities, entityIndexMap
lock sync.RWMutex
nextEntity uint64
nextComponent uint64
nextView uint64
entities map[Entity]flag
components map[flag]*Component
componentNames map[string]*Component
systems []*System
systemNames map[string]*System
views []*View
globals *dict
ctxbuilder ContextBuilderFn
}
// NewWorld creates a world and initializes the internal storage (necessary).
func NewWorld() *World {
w := &World{}
w.entities = make(map[Entity]flag)
w.components = make(map[flag]*Component)
w.componentNames = make(map[string]*Component)
w.views = make([]*View, 0)
w.systems = make([]*System, 0)
w.systemNames = make(map[string]*System)
w.globals = newdict()
w.ctxbuilder = DefaultContextBuilder
return w
}
// NewWorldWithCtx creates a world and sets the context buolder
func NewWorldWithCtx(b ContextBuilderFn) *World {
w := NewWorld()
w.ctxbuilder = b
return w
}
// NewEntity creates and entity and adds it to the current world.
func (w *World) NewEntity() Entity {
nextid := atomic.AddUint64(&w.nextEntity, 1)
entity := Entity(nextid - 1)
w.lock.Lock()
defer w.lock.Unlock()
w.entities[entity] = newflag(0, 0, 0, 0)
return entity
}
// NewEntities creates a "n" amount of entities in the current world.
func (w *World) NewEntities(n int) []Entity {
w.lock.Lock()
defer w.lock.Unlock()
nn := w.nextEntity
entities := make([]Entity, n)
for k := range entities {
nn++
e := Entity(nn)
w.entities[e] = newflag(0, 0, 0, 0)
entities[k] = e
}
w.nextEntity = nn
return entities
}
// ContainsEntity tests if an entity is present in the world.
func (w *World) ContainsEntity(entity Entity) bool {
w.lock.RLock()
defer w.lock.RUnlock()
_, ok := w.entities[entity]
return ok
}
// AddComponentToEntity adds a component to an entity.
//
// All the existing views are updated if the entity matches the requirements.
func (w *World) AddComponentToEntity(entity Entity, component *Component, data interface{}) error {
w.lock.RLock()
if _, ok := w.entities[entity]; !ok {
w.lock.RUnlock()
return fmt.Errorf("world does not contain entity")
}
if _, ok := w.components[component.flag]; !ok {
w.lock.RUnlock()
return fmt.Errorf("world does not contain component")
}
w.lock.RUnlock()
// entity and component are valid
component.lock.RLock()
if component.validatedata != nil {
if !component.validatedata(data) {
component.lock.RUnlock()
return fmt.Errorf("invalid component data [ValidateComponentData]")
}
}
component.lock.RUnlock()
component.lock.Lock()
component.data[entity] = data
w.lock.Lock()
w.entities[entity] = w.entities[entity].or(component.flag)
w.lock.Unlock()
component.lock.Unlock()
//
// get fingerprint of newly modified instance
clist := make([]*Component, 0)
w.lock.RLock()
for _, v := range w.components {
v.lock.RLock()
if _, ok := v.data[entity]; ok {
clist = append(clist, v)
}
v.lock.RUnlock()
}
fingerprint := getfingerprint(clist...)
for _, view := range w.views {
if view.matchesEntitySignature(fingerprint) {
view.upsert(entity)
} else {
index := -1
view.lock.RLock()
if i2, ok := view.matchmap[entity]; ok {
index = i2
}
view.lock.RUnlock()
if index != -1 {
view.remove(entity)
}
}
}
w.lock.RUnlock()
//
return nil
}
// RemoveComponentFromEntity removes a component from an entity.
//
// All the existing views are updated if the entity matches the requirements.
func (w *World) RemoveComponentFromEntity(entity Entity, component *Component) error {
w.lock.RLock()
if _, ok := w.entities[entity]; !ok {
w.lock.RUnlock()
return fmt.Errorf("world does not contain entity")
}
if _, ok := w.components[component.flag]; !ok {
w.lock.RUnlock()
return fmt.Errorf("world does not contain component")
}
w.lock.RUnlock()
// entity and component are valid
var destructor ComponentDestructor
component.lock.RLock()
if component.destructor != nil {
destructor = component.destructor
}
ldata := component.data[entity]
compflag := component.flag
component.lock.RUnlock()
// remove/add from/to views
w.lock.RLock()
for _, view := range w.views {
view.lock.RLock()
ookk := view.includemask.contains(compflag)
newsig := w.entities[entity].xor(compflag)
view.lock.RUnlock()
if ookk {
// by removing this component, the entity became ineligible for this view
view.remove(entity)
} else {
// by removing this component, the entity became eligible for this view
if view.matchesEntitySignature(newsig) {
view.upsert(entity)
}
}
}
// remove from data
w.lock.RUnlock()
w.lock.Lock()
w.entities[entity] = w.entities[entity].xor(compflag)
w.lock.Unlock()
component.lock.Lock()
delete(component.data, entity)
component.lock.Unlock()
// call destructor if exists
if destructor != nil {
destructor(w, entity, ldata)
}
return nil
}
// RemoveEntity removes an entity from the world (and all components)
func (w *World) RemoveEntity(entity Entity) bool {
w.lock.RLock()
eflag, ok := w.entities[entity]
if !ok {
w.lock.RUnlock()
return false
}
comps := make([]*Component, 0, len(w.components))
for cflag, c := range w.components {
if eflag.contains(cflag) {
comps = append(comps, c)
}
}
w.lock.RUnlock()
for _, comp := range comps {
_ = w.RemoveComponentFromEntity(entity, comp)
}
w.lock.Lock()
delete(w.entities, entity)
w.lock.Unlock()
return true
}
// Query will return all entities (and components) that contain the
// combination of components.
func (w *World) Query(components ...*Component) []QueryMatch {
flag0 := newflag(0, 0, 0, 0)
for _, comp := range components {
flag0 = flag0.or(comp.flag)
}
results := make([]QueryMatch, 0)
w.lock.RLock()
defer w.lock.RUnlock()
for entity, eflag := range w.entities {
if eflag.contains(flag0) {
mmap := make(map[*Component]interface{})
for _, comp := range components {
comp.lock.RLock()
mmap[comp] = comp.data[entity]
comp.lock.RUnlock()
}
match := QueryMatch{
Entity: entity,
Components: mmap,
}
results = append(results, match)
}
}
return results
}
// QueryMask will return all entities (and components) that contain the
// combination of components, excluding excludemask.
func (w *World) QueryMask(excludemask []*Component, includemask []*Component) []QueryMatch {
flag0 := newflag(0, 0, 0, 0)
negflag := newflag(0, 0, 0, 0)
for _, comp := range includemask {
flag0 = flag0.or(comp.flag)
}
for _, comp := range excludemask {
negflag = negflag.or(comp.flag)
}
results := make([]QueryMatch, 0)
w.lock.RLock()
defer w.lock.RUnlock()
for entity, eflag := range w.entities {
if eflag.contains(flag0) && eflag.and(negflag).iszero() {
mmap := make(map[*Component]interface{})
for _, comp := range includemask {
comp.lock.RLock()
mmap[comp] = comp.data[entity]
comp.lock.RUnlock()
}
match := QueryMatch{
Entity: entity,
Components: mmap,
}
results = append(results, match)
}
}
return results
}
// Run will iterate through all systems loop function (sorted by priority).
func (w *World) Run(delta float64) (taken time.Duration) {
t0 := time.Now()
w.lock.RLock()
allsystems := w.systems
w.lock.RUnlock()
rctx := context.Background()
for _, system := range allsystems {
system.runfn(w.ctxbuilder(rctx, delta, system, w))
}
return time.Now().Sub(t0)
}
// RunWithTag will iterate through all systems that contain the given tag (sorted by priority).
func (w *World) RunWithTag(tag string, delta float64) (taken time.Duration) {
t0 := time.Now()
w.lock.RLock()
allsystems := w.systems
w.lock.RUnlock()
rctx := context.Background()
for _, system := range allsystems {
if !system.ContainsTag(tag) {
continue
}
system.runfn(w.ctxbuilder(rctx, delta, system, w))
}
return time.Now().Sub(t0)
}
// RunWithoutTag will iterate through all systems that don't contain the given tag (sorted by priority).
func (w *World) RunWithoutTag(tag string, delta float64) (taken time.Duration) {
t0 := time.Now()
w.lock.RLock()
allsystems := w.systems
w.lock.RUnlock()
rctx := context.Background()
for _, system := range allsystems {
if system.ContainsTag(tag) {
continue
}
system.runfn(w.ctxbuilder(rctx, delta, system, w))
}
return time.Now().Sub(t0)
}
// Get a global variable
func (w *World) Get(key string) interface{} {
return w.globals.Get(key)
}
// Set a global variable
func (w *World) Set(key string, val interface{}) {
w.globals.Set(key, val)
}