blob: a59c87ced5f4192c7b02b9b4e77dd39098db0f51 (
plain)
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
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using Microsoft.Xna.Framework;
using MonoGame.Extended.Collections;
using MonoGame.Extended.Entities.Systems;
namespace MonoGame.Extended.Entities
{
public interface IComponentMapperService
{
ComponentMapper<T> GetMapper<T>() where T : class;
}
public class ComponentManager : UpdateSystem, IComponentMapperService
{
public ComponentManager()
{
_componentMappers = new Bag<ComponentMapper>();
_componentTypes = new Dictionary<Type, int>();
}
private readonly Bag<ComponentMapper> _componentMappers;
private readonly Dictionary<Type, int> _componentTypes;
public Action<int> ComponentsChanged;
private ComponentMapper<T> CreateMapperForType<T>(int componentTypeId)
where T : class
{
// TODO: We can probably do better than this without a huge performance penalty by creating our own bit vector that grows after the first 32 bits.
if (componentTypeId >= 32)
throw new InvalidOperationException("Component type limit exceeded. We currently only allow 32 component types for performance reasons.");
var mapper = new ComponentMapper<T>(componentTypeId, ComponentsChanged);
_componentMappers[componentTypeId] = mapper;
return mapper;
}
public ComponentMapper GetMapper(int componentTypeId)
{
return _componentMappers[componentTypeId];
}
public ComponentMapper<T> GetMapper<T>()
where T : class
{
var componentTypeId = GetComponentTypeId(typeof(T));
if (_componentMappers[componentTypeId] != null)
return _componentMappers[componentTypeId] as ComponentMapper<T>;
return CreateMapperForType<T>(componentTypeId);
}
public int GetComponentTypeId(Type type)
{
if (_componentTypes.TryGetValue(type, out var id))
return id;
id = _componentTypes.Count;
_componentTypes.Add(type, id);
return id;
}
public BitVector32 CreateComponentBits(int entityId)
{
var componentBits = new BitVector32();
var mask = BitVector32.CreateMask();
for (var componentId = 0; componentId < _componentMappers.Count; componentId++)
{
componentBits[mask] = _componentMappers[componentId]?.Has(entityId) ?? false;
mask = BitVector32.CreateMask(mask);
}
return componentBits;
}
public void Destroy(int entityId)
{
foreach (var componentMapper in _componentMappers)
componentMapper?.Delete(entityId);
}
public override void Update(GameTime gameTime)
{
}
}
}
|