-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patharchetype.go
92 lines (74 loc) · 2.22 KB
/
archetype.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
package volt
import (
"slices"
)
func (world *World) createArchetype(componentsIds ...ComponentId) *archetype {
archetypeKey := archetypeId(len(world.archetypes))
archetype := archetype{
Id: archetypeKey,
Type: componentsIds,
}
world.archetypes = append(world.archetypes, archetype)
return &world.archetypes[archetypeKey]
}
func (world *World) getArchetype(entityRecord entityRecord) *archetype {
archetypeId := entityRecord.archetypeId
if int(archetypeId) >= len(world.archetypes) {
return nil
}
return &world.archetypes[archetypeId]
}
func (world *World) setArchetype(entityRecord entityRecord, archetype *archetype) {
archetype.entities = append(archetype.entities, entityRecord.Id)
entityRecord.key = len(archetype.entities) - 1
entityRecord.archetypeId = archetype.Id
world.entities[entityRecord.Id] = entityRecord
}
func (world *World) getArchetypeForComponentsIds(componentsIds ...ComponentId) *archetype {
for i, archetype := range world.archetypes {
if len(archetype.Type) != len(componentsIds) {
continue
}
count := 0
for _, componentId := range componentsIds {
if slices.Contains(archetype.Type, componentId) {
count++
} else {
break
}
}
if count == len(archetype.Type) {
return &world.archetypes[i]
}
}
return world.createArchetype(componentsIds...)
}
func (world *World) getArchetypesForComponentsIds(componentsIds ...ComponentId) []archetype {
var archetypes []archetype
for _, archetype := range world.archetypes {
i := 0
for _, componentId := range componentsIds {
if slices.Contains(archetype.Type, componentId) {
i++
}
}
if i == len(componentsIds) {
archetypes = append(archetypes, archetype)
}
}
return archetypes
}
func (world *World) getNextArchetype(entityRecord entityRecord, componentsIds ...ComponentId) *archetype {
var archetype *archetype
if entityRecord.archetypeId == 0 {
archetype = world.getArchetypeForComponentsIds(componentsIds...)
} else {
oldArchetype := world.getArchetype(entityRecord)
if oldArchetype != nil {
archetype = world.getArchetypeForComponentsIds(append(componentsIds, oldArchetype.Type...)...)
} else {
archetype = world.getArchetypeForComponentsIds(componentsIds...)
}
}
return archetype
}