...
1 package gohan
2
3 import (
4 "time"
5 )
6
7
8 type Entity int
9
10
11
12 func NewEntity() Entity {
13 w.entityMutex.Lock()
14 defer w.entityMutex.Unlock()
15
16 if len(w.availableEntities) > 0 {
17 id := w.availableEntities[0]
18 w.availableEntities = w.availableEntities[1:]
19 w.allEntities = append(w.allEntities, id)
20 return id
21 }
22
23 w.maxEntityID++
24 w.allEntities = append(w.allEntities, w.maxEntityID)
25 w.components = append(w.components, make([]interface{}, w.maxComponentID+1))
26
27 return w.maxEntityID
28 }
29
30
31
32
33 func (e Entity) Remove() bool {
34 w.entityMutex.Lock()
35 defer w.entityMutex.Unlock()
36
37 for i, ent := range w.allEntities {
38 if ent == e {
39 w.allEntities = _removeAt(w.allEntities, i)
40
41
42 for i := range w.components[e] {
43 w.components[e][i] = nil
44 }
45
46 w.removedEntities = append(w.removedEntities, e)
47 return true
48 }
49 }
50 return false
51 }
52
53
54
55 func AllEntities() []Entity {
56 w.entityMutex.Lock()
57 defer w.entityMutex.Unlock()
58 allEntities := make([]Entity, len(w.allEntities))
59 copy(allEntities, w.allEntities)
60 return allEntities
61 }
62
63 var numEntities int
64 var numEntitiesT time.Time
65
66
67 func CurrentEntities() int {
68 if time.Since(numEntitiesT) >= w.cacheTime {
69 numEntities = len(w.allEntities)
70 numEntitiesT = time.Now()
71 }
72 return numEntities
73 }
74
75 func _removeAt(v []Entity, i int) []Entity {
76 v[i] = v[len(v)-1]
77 return v[:len(v)-1]
78 }
79
View as plain text