SyncSet.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. namespace Mirror
  5. {
  6. public class SyncSet<T> : SyncObject, ISet<T>
  7. {
  8. public delegate void SyncSetChanged(Operation op, T item);
  9. protected readonly ISet<T> objects;
  10. public int Count => objects.Count;
  11. public bool IsReadOnly { get; private set; }
  12. public event SyncSetChanged Callback;
  13. public enum Operation : byte
  14. {
  15. OP_ADD,
  16. OP_CLEAR,
  17. OP_REMOVE
  18. }
  19. struct Change
  20. {
  21. internal Operation operation;
  22. internal T item;
  23. }
  24. // list of changes.
  25. // -> insert/delete/clear is only ONE change
  26. // -> changing the same slot 10x caues 10 changes.
  27. // -> note that this grows until next sync(!)
  28. // TODO Dictionary<key, change> to avoid ever growing changes / redundant changes!
  29. readonly List<Change> changes = new List<Change>();
  30. // how many changes we need to ignore
  31. // this is needed because when we initialize the list,
  32. // we might later receive changes that have already been applied
  33. // so we need to skip them
  34. int changesAhead;
  35. public SyncSet(ISet<T> objects)
  36. {
  37. this.objects = objects;
  38. }
  39. public override void Reset()
  40. {
  41. IsReadOnly = false;
  42. changes.Clear();
  43. changesAhead = 0;
  44. objects.Clear();
  45. }
  46. // throw away all the changes
  47. // this should be called after a successful sync
  48. public override void ClearChanges() => changes.Clear();
  49. void AddOperation(Operation op, T item)
  50. {
  51. if (IsReadOnly)
  52. {
  53. throw new InvalidOperationException("SyncSets can only be modified at the server");
  54. }
  55. Change change = new Change
  56. {
  57. operation = op,
  58. item = item
  59. };
  60. if (IsRecording())
  61. {
  62. changes.Add(change);
  63. OnDirty?.Invoke();
  64. }
  65. Callback?.Invoke(op, item);
  66. }
  67. void AddOperation(Operation op) => AddOperation(op, default);
  68. public override void OnSerializeAll(NetworkWriter writer)
  69. {
  70. // if init, write the full list content
  71. writer.WriteUInt((uint)objects.Count);
  72. foreach (T obj in objects)
  73. {
  74. writer.Write(obj);
  75. }
  76. // all changes have been applied already
  77. // thus the client will need to skip all the pending changes
  78. // or they would be applied again.
  79. // So we write how many changes are pending
  80. writer.WriteUInt((uint)changes.Count);
  81. }
  82. public override void OnSerializeDelta(NetworkWriter writer)
  83. {
  84. // write all the queued up changes
  85. writer.WriteUInt((uint)changes.Count);
  86. for (int i = 0; i < changes.Count; i++)
  87. {
  88. Change change = changes[i];
  89. writer.WriteByte((byte)change.operation);
  90. switch (change.operation)
  91. {
  92. case Operation.OP_ADD:
  93. writer.Write(change.item);
  94. break;
  95. case Operation.OP_CLEAR:
  96. break;
  97. case Operation.OP_REMOVE:
  98. writer.Write(change.item);
  99. break;
  100. }
  101. }
  102. }
  103. public override void OnDeserializeAll(NetworkReader reader)
  104. {
  105. // This list can now only be modified by synchronization
  106. IsReadOnly = true;
  107. // if init, write the full list content
  108. int count = (int)reader.ReadUInt();
  109. objects.Clear();
  110. changes.Clear();
  111. for (int i = 0; i < count; i++)
  112. {
  113. T obj = reader.Read<T>();
  114. objects.Add(obj);
  115. }
  116. // We will need to skip all these changes
  117. // the next time the list is synchronized
  118. // because they have already been applied
  119. changesAhead = (int)reader.ReadUInt();
  120. }
  121. public override void OnDeserializeDelta(NetworkReader reader)
  122. {
  123. // This list can now only be modified by synchronization
  124. IsReadOnly = true;
  125. int changesCount = (int)reader.ReadUInt();
  126. for (int i = 0; i < changesCount; i++)
  127. {
  128. Operation operation = (Operation)reader.ReadByte();
  129. // apply the operation only if it is a new change
  130. // that we have not applied yet
  131. bool apply = changesAhead == 0;
  132. T item = default;
  133. switch (operation)
  134. {
  135. case Operation.OP_ADD:
  136. item = reader.Read<T>();
  137. if (apply)
  138. {
  139. objects.Add(item);
  140. }
  141. break;
  142. case Operation.OP_CLEAR:
  143. if (apply)
  144. {
  145. objects.Clear();
  146. }
  147. break;
  148. case Operation.OP_REMOVE:
  149. item = reader.Read<T>();
  150. if (apply)
  151. {
  152. objects.Remove(item);
  153. }
  154. break;
  155. }
  156. if (apply)
  157. {
  158. Callback?.Invoke(operation, item);
  159. }
  160. // we just skipped this change
  161. else
  162. {
  163. changesAhead--;
  164. }
  165. }
  166. }
  167. public bool Add(T item)
  168. {
  169. if (objects.Add(item))
  170. {
  171. AddOperation(Operation.OP_ADD, item);
  172. return true;
  173. }
  174. return false;
  175. }
  176. void ICollection<T>.Add(T item)
  177. {
  178. if (objects.Add(item))
  179. {
  180. AddOperation(Operation.OP_ADD, item);
  181. }
  182. }
  183. public void Clear()
  184. {
  185. objects.Clear();
  186. AddOperation(Operation.OP_CLEAR);
  187. }
  188. public bool Contains(T item) => objects.Contains(item);
  189. public void CopyTo(T[] array, int index) => objects.CopyTo(array, index);
  190. public bool Remove(T item)
  191. {
  192. if (objects.Remove(item))
  193. {
  194. AddOperation(Operation.OP_REMOVE, item);
  195. return true;
  196. }
  197. return false;
  198. }
  199. public IEnumerator<T> GetEnumerator() => objects.GetEnumerator();
  200. IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  201. public void ExceptWith(IEnumerable<T> other)
  202. {
  203. if (other == this)
  204. {
  205. Clear();
  206. return;
  207. }
  208. // remove every element in other from this
  209. foreach (T element in other)
  210. {
  211. Remove(element);
  212. }
  213. }
  214. public void IntersectWith(IEnumerable<T> other)
  215. {
  216. if (other is ISet<T> otherSet)
  217. {
  218. IntersectWithSet(otherSet);
  219. }
  220. else
  221. {
  222. HashSet<T> otherAsSet = new HashSet<T>(other);
  223. IntersectWithSet(otherAsSet);
  224. }
  225. }
  226. void IntersectWithSet(ISet<T> otherSet)
  227. {
  228. List<T> elements = new List<T>(objects);
  229. foreach (T element in elements)
  230. {
  231. if (!otherSet.Contains(element))
  232. {
  233. Remove(element);
  234. }
  235. }
  236. }
  237. public bool IsProperSubsetOf(IEnumerable<T> other) => objects.IsProperSubsetOf(other);
  238. public bool IsProperSupersetOf(IEnumerable<T> other) => objects.IsProperSupersetOf(other);
  239. public bool IsSubsetOf(IEnumerable<T> other) => objects.IsSubsetOf(other);
  240. public bool IsSupersetOf(IEnumerable<T> other) => objects.IsSupersetOf(other);
  241. public bool Overlaps(IEnumerable<T> other) => objects.Overlaps(other);
  242. public bool SetEquals(IEnumerable<T> other) => objects.SetEquals(other);
  243. // custom implementation so we can do our own Clear/Add/Remove for delta
  244. public void SymmetricExceptWith(IEnumerable<T> other)
  245. {
  246. if (other == this)
  247. {
  248. Clear();
  249. }
  250. else
  251. {
  252. foreach (T element in other)
  253. {
  254. if (!Remove(element))
  255. {
  256. Add(element);
  257. }
  258. }
  259. }
  260. }
  261. // custom implementation so we can do our own Clear/Add/Remove for delta
  262. public void UnionWith(IEnumerable<T> other)
  263. {
  264. if (other != this)
  265. {
  266. foreach (T element in other)
  267. {
  268. Add(element);
  269. }
  270. }
  271. }
  272. }
  273. public class SyncHashSet<T> : SyncSet<T>
  274. {
  275. public SyncHashSet() : this(EqualityComparer<T>.Default) {}
  276. public SyncHashSet(IEqualityComparer<T> comparer) : base(new HashSet<T>(comparer ?? EqualityComparer<T>.Default)) {}
  277. // allocation free enumerator
  278. public new HashSet<T>.Enumerator GetEnumerator() => ((HashSet<T>)objects).GetEnumerator();
  279. }
  280. public class SyncSortedSet<T> : SyncSet<T>
  281. {
  282. public SyncSortedSet() : this(Comparer<T>.Default) {}
  283. public SyncSortedSet(IComparer<T> comparer) : base(new SortedSet<T>(comparer ?? Comparer<T>.Default)) {}
  284. // allocation free enumerator
  285. public new SortedSet<T>.Enumerator GetEnumerator() => ((SortedSet<T>)objects).GetEnumerator();
  286. }
  287. }