ComponentMapper.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Diagnostics.CodeAnalysis;
  3. using MonoGame.Extended.Collections;
  4. namespace MonoGame.Extended.ECS
  5. {
  6. public abstract class ComponentMapper
  7. {
  8. protected ComponentMapper(int id, Type componentType)
  9. {
  10. Id = id;
  11. ComponentType = componentType;
  12. }
  13. public int Id { get; }
  14. public Type ComponentType { get; }
  15. public abstract bool Has(int entityId);
  16. public abstract void Delete(int entityId);
  17. }
  18. public class ComponentMapper<T> : ComponentMapper
  19. where T : class
  20. {
  21. public event Action<int> OnPut;
  22. public event Action<int> OnDelete;
  23. private readonly Action<int> _onCompositionChanged;
  24. public ComponentMapper(int id, Action<int> onCompositionChanged)
  25. : base(id, typeof(T))
  26. {
  27. _onCompositionChanged = onCompositionChanged;
  28. Components = new Bag<T>();
  29. }
  30. public Bag<T> Components { get; }
  31. public void Put(int entityId, T component)
  32. {
  33. Components[entityId] = component;
  34. _onCompositionChanged(entityId);
  35. OnPut?.Invoke(entityId);
  36. }
  37. public T Get(Entity entity)
  38. {
  39. return Get(entity.Id);
  40. }
  41. public T Get(int entityId)
  42. {
  43. return Components[entityId];
  44. }
  45. public bool TryGet(Entity entity, [NotNullWhen(true)] out T result)
  46. {
  47. return TryGet(entity.Id, out result);
  48. }
  49. public bool TryGet(int entityId, [NotNullWhen(true)] out T result)
  50. {
  51. result = Get(entityId);
  52. return result != null;
  53. }
  54. public override bool Has(int entityId)
  55. {
  56. if (entityId >= Components.Count)
  57. return false;
  58. return Components[entityId] != null;
  59. }
  60. public override void Delete(int entityId)
  61. {
  62. Components[entityId] = null;
  63. _onCompositionChanged(entityId);
  64. OnDelete?.Invoke(entityId);
  65. }
  66. }
  67. }