A stable modding interface between Techblox and mods https://mod.exmods.org/
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.

94 lines
3.0KB

  1. using System;
  2. using Svelto.DataStructures;
  3. using Svelto.ECS;
  4. using Svelto.ECS.Hybrid;
  5. using Svelto.ECS.Internal;
  6. namespace TechbloxModdingAPI.Utility
  7. {
  8. public readonly ref struct RefCollection<T> where T : struct, IBaseEntityComponent
  9. {
  10. private readonly bool managed;
  11. private readonly int count;
  12. private readonly NB<T> nativeArray;
  13. private readonly MB<T> managedArray;
  14. private readonly NativeEntityIDs nativeIDs;
  15. private readonly ManagedEntityIDs managedIDs;
  16. private readonly ExclusiveGroupStruct group;
  17. public RefCollection(int count, MB<T> managedArray, ManagedEntityIDs managedIDs, ExclusiveGroupStruct group)
  18. {
  19. this.count = count;
  20. this.managedArray = managedArray;
  21. this.managedIDs = managedIDs;
  22. this.group = group;
  23. managed = true;
  24. nativeArray = default;
  25. nativeIDs = default;
  26. }
  27. public RefCollection(int count, NB<T> nativeArray, NativeEntityIDs nativeIDs, ExclusiveGroupStruct group)
  28. {
  29. this.count = count;
  30. this.nativeArray = nativeArray;
  31. this.nativeIDs = nativeIDs;
  32. this.group = group;
  33. managed = false;
  34. managedArray = default;
  35. managedIDs = default;
  36. }
  37. public Enumerator GetEnumerator() => new(this);
  38. /// <summary>
  39. /// The amount of items in the collection.
  40. /// </summary>
  41. public int Count => count;
  42. public T[] ToArray() => ToArray(a => a.Component);
  43. public TA[] ToArray<TA>(Func<(T Component, EGID ID), TA> transformFunction, Predicate<(T Component, EGID ID)> predicateFunction = null)
  44. {
  45. var result = new TA[Count];
  46. int i = 0;
  47. foreach (var opt in this)
  48. {
  49. if (predicateFunction != null && !predicateFunction((opt.Get(), opt.EGID))) continue;
  50. result[i] = transformFunction((opt.Get(), opt.EGID));
  51. i++;
  52. }
  53. return result;
  54. }
  55. public ref struct Enumerator
  56. {
  57. private RefCollection<T> coll;
  58. private int index;
  59. public Enumerator(RefCollection<T> collection)
  60. {
  61. index = -1;
  62. coll = collection;
  63. }
  64. public OptionalRef<T> Current
  65. {
  66. get
  67. {
  68. if (coll.count <= index && index >= 0) return default;
  69. if (coll.managed)
  70. return new OptionalRef<T>(coll.managedArray, (uint)index,
  71. new EGID(coll.managedIDs[index], coll.group));
  72. return new OptionalRef<T>(coll.nativeArray, (uint)index,
  73. new EGID(coll.nativeIDs[index], coll.group));
  74. }
  75. }
  76. public bool MoveNext()
  77. {
  78. return ++index < coll.count;
  79. }
  80. }
  81. }
  82. }