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

mlange-42 / arche / 4835368405

28 Apr 2023 10:44PM CUT coverage: 100.0%. Remained the same
4835368405

Pull #231

github

GitHub
Merge db7a79cd0 into c9fbc3a05
Pull Request #231: Entity relations

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

2814 of 2814 relevant lines covered (100.0%)

4178.32 hits per line

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

100.0
/ecs/archetype.go
1
package ecs
2

3
import (
4
        "math"
5
        "reflect"
6
        "unsafe"
7

8
        "github.com/mlange-42/arche/ecs/stats"
9
)
10

11
// layoutSize is the size of an archetype column layout in bytes.
12
var layoutSize = unsafe.Sizeof(layout{})
13

14
// archetypeNode is a node in the archetype graph.
15
type archetypeNode struct {
16
        mask             Mask       // Mask of the archetype
17
        archetype        *archetype // The archetype
18
        archetypes       map[eid]*archetype
19
        TransitionAdd    idMap[*archetypeNode] // Mapping from component ID to add to the resulting archetype
20
        TransitionRemove idMap[*archetypeNode] // Mapping from component ID to remove to the resulting archetype
21
        relation         int8
22
}
23

24
// Creates a new archetypeNode
25
func newArchetypeNode(mask Mask, relation int8) archetypeNode {
1,211✔
26
        var arch map[eid]*archetype
1,211✔
27
        if relation >= 0 {
1,214✔
28
                arch = map[eid]*archetype{}
3✔
29
        }
3✔
30
        return archetypeNode{
1,211✔
31
                mask:             mask,
1,211✔
32
                archetypes:       arch,
1,211✔
33
                TransitionAdd:    newIDMap[*archetypeNode](),
1,211✔
34
                TransitionRemove: newIDMap[*archetypeNode](),
1,211✔
35
                relation:         relation,
1,211✔
36
        }
1,211✔
37
}
38

39
func (a *archetypeNode) GetArchetype(id eid) *archetype {
2,511✔
40
        if a.relation >= 0 {
2,531✔
41
                return a.archetypes[id]
20✔
42
        }
20✔
43
        return a.archetype
2,491✔
44
}
45

46
func (a *archetypeNode) SetArchetype(id eid, arch *archetype) {
1,188✔
47
        if a.relation >= 0 {
1,193✔
48
                a.archetypes[id] = arch
5✔
49
        } else {
1,188✔
50
                a.archetype = arch
1,183✔
51
        }
1,183✔
52
}
53

54
// Helper for accessing data from an archetype
55
type archetypeAccess struct {
56
        Mask              Mask           // Archetype's mask
57
        basePointer       unsafe.Pointer // Pointer to the first component column layout.
58
        entityPointer     unsafe.Pointer // Pointer to the entity storage
59
        Relation          Entity
60
        RelationComponent int8
61
}
62

63
// Matches checks if the archetype matches the given mask.
64
func (a *archetype) Matches(f Filter) bool {
1,652✔
65
        return f.Matches(a.Mask, &a.Relation)
1,652✔
66
}
1,652✔
67

68
// GetEntity returns the entity at the given index
69
func (a *archetypeAccess) GetEntity(index uintptr) Entity {
32,297✔
70
        return *(*Entity)(unsafe.Add(a.entityPointer, entitySize*index))
32,297✔
71
}
32,297✔
72

73
// Get returns the component with the given ID at the given index
74
func (a *archetypeAccess) Get(index uintptr, id ID) unsafe.Pointer {
142,084✔
75
        return a.getLayout(id).Get(index)
142,084✔
76
}
142,084✔
77

78
// HasComponent returns whether the archetype contains the given component ID
79
func (a *archetypeAccess) HasComponent(id ID) bool {
48,463✔
80
        return a.getLayout(id).pointer != nil
48,463✔
81
}
48,463✔
82

83
// GetLayout returns the column layout for a component.
84
func (a *archetypeAccess) getLayout(id ID) *layout {
232,345✔
85
        return (*layout)(unsafe.Add(a.basePointer, layoutSize*uintptr(id)))
232,345✔
86
}
232,345✔
87

88
// layout specification of a component column.
89
type layout struct {
90
        pointer  unsafe.Pointer // Pointer to the first element in the component column.
91
        itemSize uintptr        // Component/step size
92
}
93

94
// Get returns a pointer to the item at the given index.
95
func (l *layout) Get(index uintptr) unsafe.Pointer {
142,082✔
96
        if l.pointer == nil {
142,083✔
97
                return nil
1✔
98
        }
1✔
99
        return unsafe.Add(l.pointer, l.itemSize*index)
142,081✔
100
}
101

102
// archetype represents an ECS archetype
103
type archetype struct {
104
        archetypeAccess                   // Access helper, passed to queries.
105
        graphNode         *archetypeNode  // Node in the archetype graph.
106
        Ids               []ID            // List of component IDs.
107
        layouts           []layout        // Column layouts by ID.
108
        indices           idMap[uint32]   // Mapping from IDs to buffer indices.
109
        buffers           []reflect.Value // Reflection arrays containing component data.
110
        entityBuffer      reflect.Value   // Reflection array containing entity data.
111
        len               uint32          // Current number of entities
112
        cap               uint32          // Current capacity
113
        capacityIncrement uint32          // Capacity increment
114
        zeroValue         []byte          // Used as source for setting storage to zero
115
        zeroPointer       unsafe.Pointer  // Points to zeroValue for fast access
116
}
117

118
// Init initializes an archetype
119
func (a *archetype) Init(node *archetypeNode, capacityIncrement int, forStorage bool, relation Entity, relationComp int8, components ...componentType) {
1,197✔
120
        var mask Mask
1,197✔
121
        if len(components) > 0 {
2,316✔
122
                a.Ids = make([]ID, len(components))
1,119✔
123
        }
1,119✔
124

125
        a.buffers = make([]reflect.Value, len(components))
1,197✔
126
        a.layouts = make([]layout, MaskTotalBits)
1,197✔
127
        a.indices = newIDMap[uint32]()
1,197✔
128

1,197✔
129
        cap := 1
1,197✔
130
        if forStorage {
2,312✔
131
                cap = capacityIncrement
1,115✔
132
        }
1,115✔
133

134
        prev := -1
1,197✔
135
        var maxSize uintptr = 0
1,197✔
136
        for i, c := range components {
6,471✔
137
                if int(c.ID) <= prev {
5,275✔
138
                        panic("component arguments must be sorted by ID")
1✔
139
                }
140
                prev = int(c.ID)
5,273✔
141
                mask.Set(c.ID, true)
5,273✔
142

5,273✔
143
                size, align := c.Type.Size(), uintptr(c.Type.Align())
5,273✔
144
                size = (size + (align - 1)) / align * align
5,273✔
145
                if size > maxSize {
6,392✔
146
                        maxSize = size
1,119✔
147
                }
1,119✔
148

149
                a.Ids[i] = c.ID
5,273✔
150
                a.buffers[i] = reflect.New(reflect.ArrayOf(cap, c.Type)).Elem()
5,273✔
151
                a.layouts[c.ID] = layout{
5,273✔
152
                        a.buffers[i].Addr().UnsafePointer(),
5,273✔
153
                        size,
5,273✔
154
                }
5,273✔
155
                a.indices.Set(c.ID, uint32(i))
5,273✔
156
        }
157
        a.entityBuffer = reflect.New(reflect.ArrayOf(cap, entityType)).Elem()
1,196✔
158

1,196✔
159
        a.archetypeAccess = archetypeAccess{
1,196✔
160
                basePointer:       unsafe.Pointer(&a.layouts[0]),
1,196✔
161
                entityPointer:     a.entityBuffer.Addr().UnsafePointer(),
1,196✔
162
                Mask:              mask,
1,196✔
163
                Relation:          relation,
1,196✔
164
                RelationComponent: relationComp,
1,196✔
165
        }
1,196✔
166

1,196✔
167
        a.graphNode = node
1,196✔
168

1,196✔
169
        a.capacityIncrement = uint32(capacityIncrement)
1,196✔
170
        a.len = 0
1,196✔
171
        a.cap = uint32(cap)
1,196✔
172

1,196✔
173
        if maxSize > 0 {
2,313✔
174
                a.zeroValue = make([]byte, maxSize)
1,117✔
175
                a.zeroPointer = unsafe.Pointer(&a.zeroValue[0])
1,117✔
176
        }
1,117✔
177
}
178

179
// Add adds an entity with optionally zeroed components to the archetype
180
func (a *archetype) Alloc(entity Entity) uintptr {
4,675✔
181
        idx := uintptr(a.len)
4,675✔
182
        a.extend(1)
4,675✔
183
        a.addEntity(idx, &entity)
4,675✔
184
        a.len++
4,675✔
185
        return idx
4,675✔
186
}
4,675✔
187

188
// Add adds storage to the archetype
189
func (a *archetype) AllocN(count uint32) {
28✔
190
        a.extend(count)
28✔
191
        a.len += count
28✔
192
}
28✔
193

194
// Add adds an entity with components to the archetype
195
func (a *archetype) Add(entity Entity, components ...Component) uintptr {
9✔
196
        if len(components) != len(a.Ids) {
10✔
197
                panic("Invalid number of components")
1✔
198
        }
199
        idx := uintptr(a.len)
8✔
200

8✔
201
        a.extend(1)
8✔
202
        a.addEntity(idx, &entity)
8✔
203
        for _, c := range components {
24✔
204
                lay := a.getLayout(c.ID)
16✔
205
                size := lay.itemSize
16✔
206
                if size == 0 {
18✔
207
                        continue
2✔
208
                }
209
                src := reflect.ValueOf(c.Comp).UnsafePointer()
14✔
210
                dst := a.Get(uintptr(idx), c.ID)
14✔
211
                a.copy(src, dst, size)
14✔
212
        }
213
        a.len++
8✔
214
        return idx
8✔
215
}
216

217
// Remove removes an entity and its components from the archetype.
218
//
219
// Performs a swap-remove and reports whether a swap was necessary
220
// (i.e. not the last entity that was removed).
221
func (a *archetype) Remove(index uintptr) bool {
2,414✔
222
        swapped := a.removeEntity(index)
2,414✔
223

2,414✔
224
        old := uintptr(a.len - 1)
2,414✔
225

2,414✔
226
        if index != old {
2,583✔
227
                for _, id := range a.Ids {
381✔
228
                        lay := a.getLayout(id)
212✔
229
                        size := lay.itemSize
212✔
230
                        if size == 0 {
213✔
231
                                continue
1✔
232
                        }
233
                        src := unsafe.Add(lay.pointer, old*size)
211✔
234
                        dst := unsafe.Add(lay.pointer, index*size)
211✔
235
                        a.copy(src, dst, size)
211✔
236
                }
237
        }
238
        a.ZeroAll(old)
2,414✔
239
        a.len--
2,414✔
240

2,414✔
241
        return swapped
2,414✔
242
}
243

244
// ZeroAll resets a block of storage in all buffers.
245
func (a *archetype) ZeroAll(index uintptr) {
2,414✔
246
        for _, id := range a.Ids {
2,774✔
247
                a.Zero(index, id)
360✔
248
        }
360✔
249
}
250

251
// ZeroAll resets a block of storage in one buffer.
252
func (a *archetype) Zero(index uintptr, id ID) {
360✔
253
        lay := a.getLayout(id)
360✔
254
        size := lay.itemSize
360✔
255
        if size == 0 {
363✔
256
                return
3✔
257
        }
3✔
258
        dst := unsafe.Add(lay.pointer, index*size)
357✔
259
        a.copy(a.zeroPointer, dst, size)
357✔
260
}
261

262
// SetEntity overwrites an entity
263
func (a *archetype) SetEntity(index uintptr, entity Entity) {
71,342✔
264
        a.addEntity(index, &entity)
71,342✔
265
}
71,342✔
266

267
// Set overwrites a component with the data behind the given pointer
268
func (a *archetype) Set(index uintptr, id ID, comp interface{}) unsafe.Pointer {
41,125✔
269
        lay := a.getLayout(id)
41,125✔
270
        dst := a.Get(index, id)
41,125✔
271
        size := lay.itemSize
41,125✔
272
        if size == 0 {
41,126✔
273
                return dst
1✔
274
        }
1✔
275
        rValue := reflect.ValueOf(comp)
41,124✔
276

41,124✔
277
        src := rValue.UnsafePointer()
41,124✔
278
        a.copy(src, dst, size)
41,124✔
279
        return dst
41,124✔
280
}
281

282
// SetPointer overwrites a component with the data behind the given pointer
283
func (a *archetype) SetPointer(index uintptr, id ID, comp unsafe.Pointer) unsafe.Pointer {
23✔
284
        lay := a.getLayout(id)
23✔
285
        dst := a.Get(index, id)
23✔
286
        size := lay.itemSize
23✔
287
        if size == 0 {
24✔
288
                return dst
1✔
289
        }
1✔
290

291
        a.copy(comp, dst, size)
22✔
292
        return dst
22✔
293
}
294

295
// Reset removes all entities and components.
296
//
297
// Does NOT free the reserved memory.
298
func (a *archetype) Reset() {
15✔
299
        a.len = 0
15✔
300
        for _, buf := range a.buffers {
31✔
301
                buf.SetZero()
16✔
302
        }
16✔
303
}
304

305
// Components returns the component IDs for this archetype
306
func (a *archetype) Components() []ID {
2,189✔
307
        return a.Ids
2,189✔
308
}
2,189✔
309

310
// Len reports the number of entities in the archetype
311
func (a *archetype) Len() uint32 {
1,715✔
312
        return a.len
1,715✔
313
}
1,715✔
314

315
// Cap reports the current capacity of the archetype
316
func (a *archetype) Cap() uint32 {
18✔
317
        return a.cap
18✔
318
}
18✔
319

320
// Stats generates statistics for an archetype
321
func (a *archetype) Stats(reg *componentRegistry[ID]) stats.ArchetypeStats {
5✔
322
        ids := a.Components()
5✔
323
        aCompCount := len(ids)
5✔
324
        aTypes := make([]reflect.Type, aCompCount)
5✔
325
        for j, id := range ids {
9✔
326
                aTypes[j], _ = reg.ComponentType(id)
4✔
327
        }
4✔
328

329
        cap := int(a.Cap())
5✔
330
        memPerEntity := 0
5✔
331
        for _, id := range a.Ids {
9✔
332
                lay := a.getLayout(id)
4✔
333
                memPerEntity += int(lay.itemSize)
4✔
334
        }
4✔
335
        memory := cap * (int(entitySize) + memPerEntity)
5✔
336

5✔
337
        return stats.ArchetypeStats{
5✔
338
                Size:            int(a.Len()),
5✔
339
                Capacity:        cap,
5✔
340
                Components:      aCompCount,
5✔
341
                ComponentIDs:    ids,
5✔
342
                ComponentTypes:  aTypes,
5✔
343
                Memory:          memory,
5✔
344
                MemoryPerEntity: memPerEntity,
5✔
345
        }
5✔
346
}
347

348
// UpdateStats updates statistics for an archetype
349
func (a *archetype) UpdateStats(stats *stats.ArchetypeStats) {
3✔
350
        cap := int(a.Cap())
3✔
351
        memory := cap * (int(entitySize) + stats.MemoryPerEntity)
3✔
352

3✔
353
        stats.Size = int(a.Len())
3✔
354
        stats.Capacity = cap
3✔
355
        stats.Memory = memory
3✔
356
}
3✔
357

358
// copy from one pointer to another.
359
func (a *archetype) copy(src, dst unsafe.Pointer, itemSize uintptr) {
117,922✔
360
        dstSlice := (*[math.MaxInt32]byte)(dst)[:itemSize:itemSize]
117,922✔
361
        srcSlice := (*[math.MaxInt32]byte)(src)[:itemSize:itemSize]
117,922✔
362
        copy(dstSlice, srcSlice)
117,922✔
363
}
117,922✔
364

365
// extend the memory buffers if necessary for adding an entity.
366
func (a *archetype) extend(by uint32) {
4,714✔
367
        required := a.len + by
4,714✔
368
        if a.cap >= required {
9,384✔
369
                return
4,670✔
370
        }
4,670✔
371
        a.cap = capacityU32(required, a.capacityIncrement)
44✔
372

44✔
373
        old := a.entityBuffer
44✔
374
        a.entityBuffer = reflect.New(reflect.ArrayOf(int(a.cap), entityType)).Elem()
44✔
375
        a.entityPointer = a.entityBuffer.Addr().UnsafePointer()
44✔
376
        reflect.Copy(a.entityBuffer, old)
44✔
377

44✔
378
        for _, id := range a.Ids {
102✔
379
                lay := a.getLayout(id)
58✔
380
                if lay.itemSize == 0 {
59✔
381
                        continue
1✔
382
                }
383
                index, _ := a.indices.Get(id)
57✔
384
                old := a.buffers[index]
57✔
385
                a.buffers[index] = reflect.New(reflect.ArrayOf(int(a.cap), old.Type().Elem())).Elem()
57✔
386
                lay.pointer = a.buffers[index].Addr().UnsafePointer()
57✔
387
                reflect.Copy(a.buffers[index], old)
57✔
388
        }
389
}
390

391
// Adds an entity at the given index. Does not extend the entity buffer.
392
func (a *archetype) addEntity(index uintptr, entity *Entity) {
76,025✔
393
        dst := unsafe.Add(a.entityPointer, entitySize*index)
76,025✔
394
        src := unsafe.Pointer(entity)
76,025✔
395
        a.copy(src, dst, entitySize)
76,025✔
396
}
76,025✔
397

398
// removeEntity removes an entity from tne archetype.
399
// Components need to be removed separately.
400
func (a *archetype) removeEntity(index uintptr) bool {
2,414✔
401
        old := uintptr(a.len - 1)
2,414✔
402

2,414✔
403
        if index == old {
4,659✔
404
                return false
2,245✔
405
        }
2,245✔
406

407
        src := unsafe.Add(a.entityPointer, old*entitySize)
169✔
408
        dst := unsafe.Add(a.entityPointer, index*entitySize)
169✔
409
        a.copy(src, dst, entitySize)
169✔
410

169✔
411
        return true
169✔
412
}
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