-
Notifications
You must be signed in to change notification settings - Fork 9
/
component_getter.go
83 lines (73 loc) · 1.6 KB
/
component_getter.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
package ecs
import (
"reflect"
"unsafe"
)
type GetterCache struct {
indices []reflect.Type
values []unsafe.Pointer
}
func NewGetterCache(initCap ...int) *GetterCache {
cap := 0
if len(initCap) > 0 {
cap = initCap[0]
}
return &GetterCache{
indices: make([]reflect.Type, 0, cap),
values: make([]unsafe.Pointer, 0, cap),
}
}
func (g *GetterCache) Add(key reflect.Type, value unsafe.Pointer) {
g.indices = append(g.indices, key)
g.values = append(g.values, value)
}
func (g *GetterCache) Remove(key reflect.Type) {
idx := -1
for i, t := range g.indices {
if t == key {
idx = i
break
}
}
if idx == -1 {
return
}
// remove from indices
g.indices = append(g.indices[:idx], g.indices[idx+1:]...)
// remove from values
g.values = append(g.values[:idx], g.values[idx+1:]...)
}
func (g *GetterCache) Get(key reflect.Type) unsafe.Pointer {
for i, t := range g.indices {
if t == key {
return g.values[i]
}
}
return nil
}
type ComponentGetter[T ComponentObject] struct {
permission ComponentPermission
set *ComponentSet[T]
}
func NewComponentGetter[T ComponentObject](sys ISystem) *ComponentGetter[T] {
typ := TypeOf[T]()
r, isRequire := sys.GetRequirements()[typ]
if !isRequire {
return nil
}
getter := &ComponentGetter[T]{}
seti := sys.World().getComponentSet(typ)
if seti == nil {
return nil
}
getter.set = seti.(*ComponentSet[T])
getter.permission = r.getPermission()
return getter
}
func (c *ComponentGetter[T]) Get(entity Entity) *T {
if c.permission == ComponentReadOnly {
return &(*c.set.getByEntity(entity))
} else {
return c.set.getByEntity(entity)
}
}