Mirror of Svelto.ECS because we're a fan of it
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.7KB

  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using Svelto.Common;
  4. using Svelto.DataStructures;
  5. using Svelto.ECS.Internal;
  6. namespace Svelto.ECS
  7. {
  8. /// <summary>
  9. /// Note: does mono devirtualize sealed classes? If so it could be worth to use TypeSafeDictionary instead of
  10. /// the interface
  11. /// </summary>
  12. /// <typeparam name="T"></typeparam>
  13. public readonly struct EGIDMapper<T>: IEGIDMapper where T : struct, IEntityComponent
  14. {
  15. public uint length => _map.count;
  16. public ExclusiveGroupStruct groupID { get; }
  17. public Type entityType => TypeCache<T>.type;
  18. internal EGIDMapper(ExclusiveGroupStruct groupStructId, ITypeSafeDictionary<T> dic) : this()
  19. {
  20. groupID = groupStructId;
  21. _map = dic;
  22. }
  23. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  24. public ref T Entity(uint entityID)
  25. {
  26. #if DEBUG && !PROFILE_SVELTO
  27. if (_map == null)
  28. throw new System.Exception("Not initialized EGIDMapper in this group ".FastConcat(typeof(T).ToString()));
  29. if (_map.TryFindIndex(entityID, out var findIndex) == false)
  30. throw new System.Exception("Entity not found in this group ".FastConcat(typeof(T).ToString()));
  31. #else
  32. _map.TryFindIndex(entityID, out var findIndex);
  33. #endif
  34. return ref _map.GetDirectValueByRef(findIndex);
  35. }
  36. public bool TryGetEntity(uint entityID, out T value)
  37. {
  38. if (_map != null && _map.TryFindIndex(entityID, out var index))
  39. {
  40. value = _map.GetDirectValueByRef(index);
  41. return true;
  42. }
  43. value = default;
  44. return false;
  45. }
  46. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  47. public bool Exists(uint idEntityId)
  48. {
  49. return _map.count > 0 && _map.TryFindIndex(idEntityId, out _);
  50. }
  51. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  52. public uint GetIndex(uint entityID)
  53. {
  54. return _map.GetIndex(entityID);
  55. }
  56. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  57. public bool FindIndex(uint valueKey, out uint index)
  58. {
  59. return _map.TryFindIndex(valueKey, out index);
  60. }
  61. internal readonly ITypeSafeDictionary<T> _map;
  62. }
  63. public interface IEGIDMapper
  64. {
  65. bool FindIndex(uint valueKey, out uint index);
  66. uint GetIndex(uint entityID);
  67. bool Exists(uint idEntityId);
  68. ExclusiveGroupStruct groupID { get; }
  69. Type entityType { get; }
  70. }
  71. }