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.

75 lines
2.7KB

  1. using System;
  2. using Svelto.DataStructures;
  3. using Svelto.ECS.Internal;
  4. namespace Svelto.ECS
  5. {
  6. public ref struct EntityStructInitializer
  7. {
  8. public EntityStructInitializer(EGID id, FasterDictionary<RefWrapper<Type>, ITypeSafeDictionary> group)
  9. {
  10. _group = group;
  11. _ID = id;
  12. }
  13. public void Init<T>(T initializer) where T : struct, IEntityStruct
  14. {
  15. if (_group.TryGetValue(new RefWrapper<Type>(EntityBuilder<T>.ENTITY_VIEW_TYPE),
  16. out var typeSafeDictionary) == false) return;
  17. var dictionary = (TypeSafeDictionary<T>) typeSafeDictionary;
  18. if (EntityBuilder<T>.HAS_EGID)
  19. SetEGIDWithoutBoxing<T>.SetIDWithoutBoxing(ref initializer, _ID);
  20. if (dictionary.TryFindIndex(_ID.entityID, out var findElementIndex))
  21. dictionary.GetDirectValue(findElementIndex) = initializer;
  22. }
  23. public void CopyFrom<T>(T initializer) where T : struct, IEntityStruct
  24. {
  25. var dictionary = (TypeSafeDictionary<T>) _group[new RefWrapper<Type>(EntityBuilder<T>.ENTITY_VIEW_TYPE)];
  26. if (EntityBuilder<T>.HAS_EGID)
  27. SetEGIDWithoutBoxing<T>.SetIDWithoutBoxing(ref initializer, _ID);
  28. dictionary[_ID.entityID] = initializer;
  29. }
  30. public ref T GetOrCreate<T>() where T : struct, IEntityStruct
  31. {
  32. ref var entityDictionary = ref _group.GetOrCreate(new RefWrapper<Type>(EntityBuilder<T>.ENTITY_VIEW_TYPE)
  33. , () => new TypeSafeDictionary<T>());
  34. var dictionary = (TypeSafeDictionary<T>) entityDictionary;
  35. return ref dictionary.GetOrCreate(_ID.entityID);
  36. }
  37. public T Get<T>() where T : struct, IEntityStruct
  38. {
  39. return (_group[new RefWrapper<Type>(EntityBuilder<T>.ENTITY_VIEW_TYPE)] as TypeSafeDictionary<T>)[_ID.entityID];
  40. }
  41. public bool Has<T>() where T : struct, IEntityStruct
  42. {
  43. if (_group.TryGetValue(new RefWrapper<Type>(EntityBuilder<T>.ENTITY_VIEW_TYPE),
  44. out var typeSafeDictionary))
  45. {
  46. var dictionary = (TypeSafeDictionary<T>) typeSafeDictionary;
  47. if (dictionary.ContainsKey(_ID.entityID))
  48. return true;
  49. }
  50. return false;
  51. }
  52. public static EntityStructInitializer CreateEmptyInitializer()
  53. {
  54. return new EntityStructInitializer(new EGID(), new FasterDictionary<RefWrapper<Type>, ITypeSafeDictionary>());
  55. }
  56. readonly EGID _ID;
  57. readonly FasterDictionary<RefWrapper<Type>, ITypeSafeDictionary> _group;
  58. }
  59. }