• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mlange-42 / ark / 13705674638

06 Mar 2025 06:31PM CUT coverage: 99.41% (+0.03%) from 99.379%
13705674638

Pull #147

github

web-flow
Merge becb7e527 into a5c169bcb
Pull Request #147: Optimize getting table from archetype

2 of 2 new or added lines in 2 files covered. (100.0%)

6237 of 6274 relevant lines covered (99.41%)

28634.75 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.81
/ecs/storage.go
1
package ecs
2

3
import (
4
        "unsafe"
5
)
6

7
type storage struct {
8
        config     config
9
        registry   componentRegistry
10
        entities   []entityIndex
11
        isTarget   []bool
12
        entityPool entityPool
13
        graph      graph
14
        cache      cache
15

16
        archetypes         []archetype
17
        relationArchetypes []archetypeID
18
        tables             []table
19
        components         []componentStorage
20
}
21

22
type componentStorage struct {
23
        columns []*column
24
}
25

26
func newStorage(capacity ...int) storage {
196✔
27
        config := newConfig(capacity...)
196✔
28

196✔
29
        reg := newComponentRegistry()
196✔
30
        entities := make([]entityIndex, reservedEntities, config.initialCapacity+reservedEntities)
196✔
31
        isTarget := make([]bool, reservedEntities, config.initialCapacity+reservedEntities)
196✔
32
        // Reserved zero and wildcard entities
196✔
33
        for i := range reservedEntities {
588✔
34
                entities[i] = entityIndex{table: maxTableID, row: 0}
392✔
35
        }
392✔
36
        componentsMap := make([]int16, MaskTotalBits)
196✔
37
        for i := range MaskTotalBits {
50,372✔
38
                componentsMap[i] = -1
50,176✔
39
        }
50,176✔
40

41
        tables := make([]table, 0, 128)
196✔
42
        tables = append(tables, newTable(0, 0, uint32(config.initialCapacity), &reg, []ID{}, componentsMap, []bool{}, []Entity{}, []RelationID{}))
196✔
43
        archetypes := make([]archetype, 0, 128)
196✔
44
        archetypes = append(archetypes, newArchetype(0, 0, &Mask{}, []ID{}, []tableID{0}, &reg))
196✔
45
        return storage{
196✔
46
                config:     config,
196✔
47
                registry:   reg,
196✔
48
                cache:      newCache(),
196✔
49
                entities:   entities,
196✔
50
                isTarget:   isTarget,
196✔
51
                entityPool: newEntityPool(uint32(config.initialCapacity), reservedEntities),
196✔
52
                graph:      newGraph(),
196✔
53
                archetypes: archetypes,
196✔
54
                tables:     tables,
196✔
55
                components: make([]componentStorage, 0, MaskTotalBits),
196✔
56
        }
196✔
57
}
58

59
func (s *storage) findOrCreateTable(oldTable *table, add []ID, remove []ID, relations []RelationID, outMask *Mask) *table {
494,981✔
60
        startNode := s.archetypes[oldTable.archetype].node
494,981✔
61

494,981✔
62
        node := s.graph.Find(startNode, add, remove, outMask)
494,981✔
63
        var arch *archetype
494,981✔
64
        if archID, ok := node.GetArchetype(); ok {
989,569✔
65
                arch = &s.archetypes[archID]
494,588✔
66
        } else {
494,981✔
67
                arch = s.createArchetype(node)
393✔
68
                node.archetype = arch.id
393✔
69
        }
393✔
70

71
        var allRelations []RelationID
494,981✔
72
        if len(relations) > 0 {
495,639✔
73
                allRelations = appendNew(oldTable.relationIDs, relations...)
658✔
74
        } else {
494,981✔
75
                allRelations = oldTable.relationIDs
494,323✔
76
        }
494,323✔
77
        table, ok := arch.GetTable(s, allRelations)
494,981✔
78
        if !ok {
495,429✔
79
                table = s.createTable(arch, allRelations)
448✔
80
        }
448✔
81
        return table
494,981✔
82
}
83

84
func (s *storage) AddComponent(id uint8) {
895✔
85
        if len(s.components) != int(id) {
896✔
86
                panic("components can only be added to a storage sequentially")
1✔
87
        }
88
        s.components = append(s.components, componentStorage{columns: make([]*column, len(s.tables))})
894✔
89
}
90

91
// RemoveEntity removes the given entity from the world.
92
func (s *storage) RemoveEntity(entity Entity) {
492,009✔
93
        if !s.entityPool.Alive(entity) {
492,010✔
94
                panic("can't remove a dead entity")
1✔
95
        }
96
        index := &s.entities[entity.id]
492,008✔
97
        table := &s.tables[index.table]
492,008✔
98

492,008✔
99
        swapped := table.Remove(index.row)
492,008✔
100

492,008✔
101
        s.entityPool.Recycle(entity)
492,008✔
102

492,008✔
103
        if swapped {
982,614✔
104
                swapEntity := table.GetEntity(uintptr(index.row))
490,606✔
105
                s.entities[swapEntity.id].row = index.row
490,606✔
106
        }
490,606✔
107
        index.table = maxTableID
492,008✔
108

492,008✔
109
        if s.isTarget[entity.id] {
492,011✔
110
                s.cleanupArchetypes(entity)
3✔
111
                s.isTarget[entity.id] = false
3✔
112
        }
3✔
113
}
114

115
func (s *storage) Reset() {
1✔
116
        s.entities = s.entities[:reservedEntities]
1✔
117
        s.entityPool.Reset()
1✔
118
        s.isTarget = s.isTarget[:reservedEntities]
1✔
119
        s.cache.Reset()
1✔
120

1✔
121
        for i := range s.archetypes {
5✔
122
                s.archetypes[i].Reset(s)
4✔
123
        }
4✔
124
}
125

126
func (s *storage) get(entity Entity, component ID) unsafe.Pointer {
5✔
127
        if !s.entityPool.Alive(entity) {
6✔
128
                panic("can't get component of a dead entity")
1✔
129
        }
130
        return s.getUnchecked(entity, component)
4✔
131
}
132

133
func (s *storage) getUnchecked(entity Entity, component ID) unsafe.Pointer {
5✔
134
        s.checkHasComponent(entity, component)
5✔
135
        index := s.entities[entity.id]
5✔
136
        return s.tables[index.table].Get(component, uintptr(index.row))
5✔
137
}
5✔
138

139
func (s *storage) has(entity Entity, component ID) bool {
17✔
140
        if !s.entityPool.Alive(entity) {
18✔
141
                panic("can't get component of a dead entity")
1✔
142
        }
143
        return s.hasUnchecked(entity, component)
16✔
144
}
145

146
func (s *storage) hasUnchecked(entity Entity, component ID) bool {
18✔
147
        s.checkHasComponent(entity, component)
18✔
148
        index := s.entities[entity.id]
18✔
149
        return s.tables[index.table].Has(component)
18✔
150
}
18✔
151

152
func (s *storage) getRelation(entity Entity, comp ID) Entity {
347✔
153
        if !s.entityPool.Alive(entity) {
348✔
154
                panic("can't get relation for a dead entity")
1✔
155
        }
156
        return s.getRelationUnchecked(entity, comp)
346✔
157
}
158

159
func (s *storage) getRelationUnchecked(entity Entity, comp ID) Entity {
351✔
160
        s.checkHasComponent(entity, comp)
351✔
161
        return s.tables[s.entities[entity.id].table].GetRelation(comp)
351✔
162
}
351✔
163

164
func (s *storage) registerTargets(relations []RelationID) {
495,035✔
165
        for _, rel := range relations {
495,789✔
166
                s.isTarget[rel.target.id] = true
754✔
167
        }
754✔
168
}
169

170
func (s *storage) registerFilter(batch *Batch) cacheID {
31✔
171
        return s.cache.register(s, batch)
31✔
172
}
31✔
173

174
func (s *storage) unregisterFilter(entry cacheID) {
28✔
175
        s.cache.unregister(entry)
28✔
176
}
28✔
177

178
func (s *storage) getRegisteredFilter(id cacheID) *cacheEntry {
28✔
179
        return s.cache.getEntry(id)
28✔
180
}
28✔
181

182
func (s *storage) createEntity(table tableID) (Entity, uint32) {
494,420✔
183
        entity := s.entityPool.Get()
494,420✔
184

494,420✔
185
        idx := s.tables[table].Add(entity)
494,420✔
186
        len := len(s.entities)
494,420✔
187
        if int(entity.id) == len {
498,965✔
188
                s.entities = append(s.entities, entityIndex{table: table, row: idx})
4,545✔
189
                s.isTarget = append(s.isTarget, false)
4,545✔
190
        } else {
494,420✔
191
                s.entities[entity.id] = entityIndex{table: table, row: idx}
489,875✔
192
        }
489,875✔
193
        return entity, idx
494,420✔
194
}
195

196
func (s *storage) createEntities(table *table, count int) {
144✔
197
        startIdx := table.Len()
144✔
198
        table.Alloc(uint32(count))
144✔
199

144✔
200
        len := len(s.entities)
144✔
201
        for i := range count {
2,398✔
202
                index := uint32(startIdx + i)
2,254✔
203
                entity := s.entityPool.Get()
2,254✔
204
                table.SetEntity(index, entity)
2,254✔
205

2,254✔
206
                if int(entity.id) == len {
4,492✔
207
                        s.entities = append(s.entities, entityIndex{table: table.id, row: index})
2,238✔
208
                        s.isTarget = append(s.isTarget, false)
2,238✔
209
                        len++
2,238✔
210
                } else {
2,254✔
211
                        s.entities[entity.id] = entityIndex{table: table.id, row: index}
16✔
212
                }
16✔
213
        }
214
}
215

216
func (s *storage) createArchetype(node *node) *archetype {
393✔
217
        comps := node.mask.toTypes(&s.registry.registry)
393✔
218
        index := len(s.archetypes)
393✔
219
        s.archetypes = append(s.archetypes, newArchetype(archetypeID(index), node.id, &node.mask, comps, nil, &s.registry))
393✔
220
        archetype := &s.archetypes[index]
393✔
221
        if archetype.HasRelations() {
442✔
222
                s.relationArchetypes = append(s.relationArchetypes, archetype.id)
49✔
223
        }
49✔
224
        return archetype
393✔
225
}
226

227
func (s *storage) createTable(archetype *archetype, relations []RelationID) *table {
471✔
228
        targets := make([]Entity, len(archetype.components))
471✔
229
        numRelations := uint8(0)
471✔
230
        for _, rel := range relations {
606✔
231
                idx := archetype.componentsMap[rel.component.id]
135✔
232
                targets[idx] = rel.target
135✔
233
                numRelations++
135✔
234
        }
135✔
235
        if numRelations != archetype.numRelations {
471✔
236
                panic("relations must be fully specified")
×
237
        }
238
        for i := range relations {
606✔
239
                rel := &relations[i]
135✔
240
                s.checkRelationComponent(rel.component)
135✔
241
                s.checkRelationTarget(rel.target)
135✔
242
        }
135✔
243

244
        var newTableID tableID
471✔
245
        if id, ok := archetype.GetFreeTable(); ok {
473✔
246
                newTableID = id
2✔
247
                s.tables[newTableID].recycle(targets, relations)
2✔
248
        } else {
471✔
249
                newTableID = tableID(len(s.tables))
469✔
250
                cap := s.config.initialCapacity
469✔
251
                if archetype.HasRelations() {
594✔
252
                        cap = s.config.initialCapacityRelations
125✔
253
                }
125✔
254
                s.tables = append(s.tables, newTable(
469✔
255
                        newTableID, archetype.id, uint32(cap), &s.registry,
469✔
256
                        archetype.components, archetype.componentsMap,
469✔
257
                        archetype.isRelation, targets, relations))
469✔
258
        }
259
        archetype.AddTable(&s.tables[newTableID])
471✔
260

471✔
261
        table := &s.tables[newTableID]
471✔
262
        for i := range s.components {
3,000✔
263
                id := ID{id: uint8(i)}
2,529✔
264
                comps := &s.components[i]
2,529✔
265
                if archetype.mask.Get(id) {
4,247✔
266
                        comps.columns = append(comps.columns, table.GetColumn(id))
1,718✔
267
                } else {
2,529✔
268
                        comps.columns = append(comps.columns, nil)
811✔
269
                }
811✔
270
        }
271

272
        s.cache.addTable(s, table)
471✔
273
        return table
471✔
274
}
275

276
// Removes empty archetypes that have a target relation to the given entity.
277
func (s *storage) cleanupArchetypes(target Entity) {
6✔
278
        newRelations := []RelationID{}
6✔
279
        for _, arch := range s.relationArchetypes {
19✔
280
                archetype := &s.archetypes[arch]
13✔
281
                len := len(archetype.tables)
13✔
282
                for i := len - 1; i >= 0; i-- {
33✔
283
                        table := &s.tables[archetype.tables[i]]
20✔
284

20✔
285
                        foundTarget := false
20✔
286
                        for _, rel := range table.relationIDs {
40✔
287
                                if rel.target.id == target.id {
29✔
288
                                        newRelations = append(newRelations, RelationID{component: rel.component, target: Entity{}})
9✔
289
                                        foundTarget = true
9✔
290
                                }
9✔
291
                        }
292
                        if !foundTarget {
31✔
293
                                continue
11✔
294
                        }
295

296
                        if table.Len() > 0 {
10✔
297
                                allRelations := s.getExchangeTargetsUnchecked(table, newRelations)
1✔
298
                                newTable, ok := archetype.GetTable(s, allRelations)
1✔
299
                                if !ok {
2✔
300
                                        newTable = s.createTable(archetype, newRelations)
1✔
301
                                }
1✔
302
                                s.moveEntities(table, newTable, uint32(table.Len()))
1✔
303
                        }
304
                        archetype.FreeTable(table.id)
9✔
305
                        s.cache.removeTable(s, table)
9✔
306

9✔
307
                        newRelations = newRelations[:0]
9✔
308
                }
309
                archetype.RemoveTarget(target)
13✔
310
        }
311
}
312

313
// moveEntities moves all entities from src to dst.
314
func (s *storage) moveEntities(src, dst *table, count uint32) {
10✔
315
        oldLen := dst.Len()
10✔
316
        dst.AddAll(src, count)
10✔
317

10✔
318
        newLen := dst.Len()
10✔
319
        newTable := dst.id
10✔
320
        for i := oldLen; i < newLen; i++ {
258✔
321
                entity := dst.GetEntity(uintptr(i))
248✔
322
                s.entities[entity.id] = entityIndex{table: newTable, row: uint32(i)}
248✔
323
        }
248✔
324
        src.Reset()
10✔
325
}
326

327
func (s *storage) getExchangeTargetsUnchecked(oldTable *table, relations []RelationID) []RelationID {
1✔
328
        targets := make([]Entity, len(oldTable.columns))
1✔
329
        for i := range oldTable.columns {
3✔
330
                targets[i] = oldTable.columns[i].target
2✔
331
        }
2✔
332
        for _, rel := range relations {
2✔
333
                index := oldTable.components[rel.component.id]
1✔
334
                if rel.target == targets[index] {
1✔
335
                        continue
×
336
                }
337
                targets[index] = rel.target
1✔
338
        }
339

340
        result := make([]RelationID, 0, len(oldTable.relationIDs))
1✔
341
        for i, e := range targets {
3✔
342
                if !oldTable.columns[i].isRelation {
3✔
343
                        continue
1✔
344
                }
345
                id := oldTable.ids[i]
1✔
346
                result = append(result, RelationID{component: id, target: e})
1✔
347
        }
348

349
        return result
1✔
350
}
351

352
func (s *storage) getExchangeTargets(oldTable *table, relations []RelationID) ([]RelationID, bool) {
54✔
353
        changed := false
54✔
354
        targets := make([]Entity, len(oldTable.columns))
54✔
355
        for i := range oldTable.columns {
201✔
356
                targets[i] = oldTable.columns[i].target
147✔
357
        }
147✔
358
        for _, rel := range relations {
109✔
359
                // Validity of the target is checked when creating a new table.
55✔
360
                // Whether the component is a relation is checked when creating a new table.
55✔
361
                index := oldTable.components[rel.component.id]
55✔
362
                if rel.target == targets[index] {
55✔
363
                        continue
×
364
                }
365
                targets[index] = rel.target
55✔
366
                changed = true
55✔
367
        }
368
        if !changed {
54✔
369
                return nil, false
×
370
        }
×
371

372
        result := make([]RelationID, 0, len(oldTable.relationIDs))
54✔
373
        for i, e := range targets {
201✔
374
                if !oldTable.columns[i].isRelation {
238✔
375
                        continue
91✔
376
                }
377
                id := oldTable.ids[i]
56✔
378
                result = append(result, RelationID{component: id, target: e})
56✔
379
        }
380

381
        return result, true
54✔
382
}
383

384
func (s *storage) getTables(batch *Batch) []*table {
91✔
385
        tables := []*table{}
91✔
386

91✔
387
        for i := range s.archetypes {
422✔
388
                archetype := &s.archetypes[i]
331✔
389
                if !batch.filter.matches(&archetype.mask) {
486✔
390
                        continue
155✔
391
                }
392

393
                if !archetype.HasRelations() {
340✔
394
                        table := &s.tables[archetype.tables[0]]
164✔
395
                        tables = append(tables, table)
164✔
396
                        continue
164✔
397
                }
398

399
                tableIDs := archetype.GetTables(batch.relations)
12✔
400
                for _, tab := range tableIDs {
27✔
401
                        table := &s.tables[tab]
15✔
402
                        if !table.Matches(batch.relations) {
15✔
403
                                continue
×
404
                        }
405
                        tables = append(tables, table)
15✔
406
                }
407
        }
408
        return tables
91✔
409
}
410

411
func (s *storage) getTableIDs(batch *Batch) []tableID {
33✔
412
        tables := []tableID{}
33✔
413

33✔
414
        for i := range s.archetypes {
99✔
415
                archetype := &s.archetypes[i]
66✔
416
                if !batch.filter.matches(&archetype.mask) {
100✔
417
                        continue
34✔
418
                }
419

420
                if !archetype.HasRelations() {
39✔
421
                        tables = append(tables, archetype.tables[0])
7✔
422
                        continue
7✔
423
                }
424

425
                tableIDs := archetype.GetTables(batch.relations)
25✔
426
                for _, tab := range tableIDs {
84✔
427
                        table := &s.tables[tab]
59✔
428
                        if !table.Matches(batch.relations) {
59✔
429
                                continue
×
430
                        }
431
                        tables = append(tables, tab)
59✔
432
                }
433
        }
434
        return tables
33✔
435
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc