1
+ using System ;
2
+
3
+ namespace Bitron . Ecs
4
+ {
5
+ public sealed class World
6
+ {
7
+ private EntityMeta [ ] _entityMetas ;
8
+ private int _entityCount ;
9
+
10
+ private int _despawnedEntityCount ;
11
+ private int [ ] _despawnedEntities ;
12
+
13
+ private IStorage [ ] _pools ;
14
+ private int _poolCount ;
15
+
16
+ public Entity Spawn ( )
17
+ {
18
+ int id ;
19
+ int gen ;
20
+
21
+ if ( _despawnedEntityCount > 0 )
22
+ {
23
+ id = _despawnedEntities [ -- _despawnedEntityCount ] ;
24
+ gen = - ( _entityMetas [ id ] ) . Gen ;
25
+ }
26
+ else
27
+ {
28
+ id = _entityCount ++ ;
29
+ gen = 1 ;
30
+ }
31
+
32
+ _entityMetas [ id ] . Gen = gen ;
33
+
34
+ return new Entity ( ) { Id = id , Gen = gen } ;
35
+ }
36
+
37
+ public void Despawn ( Entity entity )
38
+ {
39
+ if ( _entityMetas [ entity . Id ] . Gen < 0 )
40
+ {
41
+ return ;
42
+ }
43
+
44
+ if ( _despawnedEntityCount == _despawnedEntities . Length )
45
+ {
46
+ Array . Resize ( ref _despawnedEntities , _despawnedEntityCount << 1 ) ;
47
+ }
48
+
49
+ ref var meta = ref _entityMetas [ entity . Id ] ;
50
+ meta . Gen = - ( meta . Gen + 1 ) ;
51
+
52
+ _despawnedEntities [ _despawnedEntityCount ++ ] = entity . Id ;
53
+ }
54
+
55
+ public Storage < Component > GetStorage < Component > ( ) where Component : struct
56
+ {
57
+ var typeId = ComponentType < Component > . Id ;
58
+
59
+ if ( typeId == _poolCount )
60
+ {
61
+ Array . Resize ( ref _pools , _poolCount << 1 ) ;
62
+ _pools [ typeId ] = new Storage < Component > ( ) ;
63
+ _poolCount ++ ;
64
+ }
65
+
66
+ return _pools [ typeId ] as Storage < Component > ;
67
+ }
68
+ }
69
+
70
+ internal struct EntityMeta
71
+ {
72
+ public int Gen ;
73
+ }
74
+
75
+ internal class ComponentType
76
+ {
77
+ protected static int counter = 0 ;
78
+ }
79
+
80
+ internal class ComponentType < T > : ComponentType
81
+ {
82
+ public static readonly int Id ;
83
+
84
+ static ComponentType ( ) => Id = counter ++ ;
85
+ }
86
+ }
0 commit comments