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.

79 lines
2.3KB

  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using System.Runtime.InteropServices;
  4. #pragma warning disable 660,661
  5. namespace Svelto.ECS
  6. {
  7. /// <summary>
  8. /// Todo: EntityReference shouldn't map EGIDs as dictionaries keys but directly the indices in the EntityDB arrays
  9. /// </summary>
  10. [Serialization.DoNotSerialize]
  11. [Serializable]
  12. [StructLayout(LayoutKind.Explicit)]
  13. public struct EntityReference : IEquatable<EntityReference>
  14. {
  15. [FieldOffset(0)] public readonly uint uniqueID;
  16. [FieldOffset(4)] public readonly uint version;
  17. [FieldOffset(0)] readonly ulong _GID;
  18. internal uint index => uniqueID - 1;
  19. public static bool operator ==(EntityReference obj1, EntityReference obj2)
  20. {
  21. return obj1._GID == obj2._GID;
  22. }
  23. public static bool operator !=(EntityReference obj1, EntityReference obj2)
  24. {
  25. return obj1._GID != obj2._GID;
  26. }
  27. public EntityReference(uint uniqueId) : this(uniqueId, 0) {}
  28. public EntityReference(uint uniqueId, uint version) : this()
  29. {
  30. _GID = MAKE_GLOBAL_ID(uniqueId, version);
  31. }
  32. public bool Equals(EntityReference other)
  33. {
  34. return _GID == other._GID;
  35. }
  36. public bool Equals(EntityReference x, EntityReference y)
  37. {
  38. return x._GID == y._GID;
  39. }
  40. public override string ToString()
  41. {
  42. return "id:".FastConcat(uniqueID).FastConcat(" version:").FastConcat(version);
  43. }
  44. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  45. public EGID ToEGID(EntitiesDB entitiesDB)
  46. {
  47. DBC.ECS.Check.Require(this != Invalid, "Invalid Reference Used");
  48. return entitiesDB.GetEGID(this);
  49. }
  50. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  51. public bool ToEGID(EntitiesDB entitiesDB, out EGID egid)
  52. {
  53. DBC.ECS.Check.Require(this != Invalid, "Invalid Reference Used");
  54. return entitiesDB.TryGetEGID(this, out egid);
  55. }
  56. static ulong MAKE_GLOBAL_ID(uint uniqueId, uint version)
  57. {
  58. return (ulong)version << 32 | ((ulong)uniqueId & 0xFFFFFFFF);
  59. }
  60. public static EntityReference Invalid => default;
  61. }
  62. }