SyncSet.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 => !IsWritable();
  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. changes.Clear();
  42. changesAhead = 0;
  43. objects.Clear();
  44. }
  45. // throw away all the changes
  46. // this should be called after a successful sync
  47. public override void ClearChanges() => changes.Clear();
  48. void AddOperation(Operation op, T item, bool checkAccess)
  49. {
  50. if (checkAccess && IsReadOnly)
  51. {
  52. throw new InvalidOperationException("SyncSets can only be modified by the owner.");
  53. }
  54. Change change = new Change
  55. {
  56. operation = op,
  57. item = item
  58. };
  59. if (IsRecording())
  60. {
  61. changes.Add(change);
  62. OnDirty?.Invoke();
  63. }
  64. Callback?.Invoke(op, item);
  65. }
  66. void AddOperation(Operation op, bool checkAccess) => AddOperation(op, default, checkAccess);
  67. public override void OnSerializeAll(NetworkWriter writer)
  68. {
  69. // if init, write the full list content
  70. writer.WriteUInt((uint)objects.Count);
  71. foreach (T obj in objects)
  72. {
  73. writer.Write(obj);
  74. }
  75. // all changes have been applied already
  76. // thus the client will need to skip all the pending changes
  77. // or they would be applied again.
  78. // So we write how many changes are pending
  79. writer.WriteUInt((uint)changes.Count);
  80. }
  81. public override void OnSerializeDelta(NetworkWriter writer)
  82. {
  83. // write all the queued up changes
  84. writer.WriteUInt((uint)changes.Count);
  85. for (int i = 0; i < changes.Count; i++)
  86. {
  87. Change change = changes[i];
  88. writer.WriteByte((byte)change.operation);
  89. switch (change.operation)
  90. {
  91. case Operation.OP_ADD:
  92. writer.Write(change.item);
  93. break;
  94. case Operation.OP_CLEAR:
  95. break;
  96. case Operation.OP_REMOVE:
  97. writer.Write(change.item);
  98. break;
  99. }
  100. }
  101. }
  102. public override void OnDeserializeAll(NetworkReader reader)
  103. {
  104. // if init, write the full list content
  105. int count = (int)reader.ReadUInt();
  106. objects.Clear();
  107. changes.Clear();
  108. for (int i = 0; i < count; i++)
  109. {
  110. T obj = reader.Read<T>();
  111. objects.Add(obj);
  112. }
  113. // We will need to skip all these changes
  114. // the next time the list is synchronized
  115. // because they have already been applied
  116. changesAhead = (int)reader.ReadUInt();
  117. }
  118. public override void OnDeserializeDelta(NetworkReader reader)
  119. {
  120. int changesCount = (int)reader.ReadUInt();
  121. for (int i = 0; i < changesCount; i++)
  122. {
  123. Operation operation = (Operation)reader.ReadByte();
  124. // apply the operation only if it is a new change
  125. // that we have not applied yet
  126. bool apply = changesAhead == 0;
  127. T item = default;
  128. switch (operation)
  129. {
  130. case Operation.OP_ADD:
  131. item = reader.Read<T>();
  132. if (apply)
  133. {
  134. objects.Add(item);
  135. // add dirty + changes.
  136. // ClientToServer needs to set dirty in server OnDeserialize.
  137. // no access check: server OnDeserialize can always
  138. // write, even for ClientToServer (for broadcasting).
  139. AddOperation(Operation.OP_ADD, item, false);
  140. }
  141. break;
  142. case Operation.OP_CLEAR:
  143. if (apply)
  144. {
  145. objects.Clear();
  146. // add dirty + changes.
  147. // ClientToServer needs to set dirty in server OnDeserialize.
  148. // no access check: server OnDeserialize can always
  149. // write, even for ClientToServer (for broadcasting).
  150. AddOperation(Operation.OP_CLEAR, false);
  151. }
  152. break;
  153. case Operation.OP_REMOVE:
  154. item = reader.Read<T>();
  155. if (apply)
  156. {
  157. objects.Remove(item);
  158. // add dirty + changes.
  159. // ClientToServer needs to set dirty in server OnDeserialize.
  160. // no access check: server OnDeserialize can always
  161. // write, even for ClientToServer (for broadcasting).
  162. AddOperation(Operation.OP_REMOVE, item, false);
  163. }
  164. break;
  165. }
  166. if (!apply)
  167. {
  168. // we just skipped this change
  169. changesAhead--;
  170. }
  171. }
  172. }
  173. public bool Add(T item)
  174. {
  175. if (objects.Add(item))
  176. {
  177. AddOperation(Operation.OP_ADD, item, true);
  178. return true;
  179. }
  180. return false;
  181. }
  182. void ICollection<T>.Add(T item)
  183. {
  184. if (objects.Add(item))
  185. {
  186. AddOperation(Operation.OP_ADD, item, true);
  187. }
  188. }
  189. public void Clear()
  190. {
  191. objects.Clear();
  192. AddOperation(Operation.OP_CLEAR, true);
  193. }
  194. public bool Contains(T item) => objects.Contains(item);
  195. public void CopyTo(T[] array, int index) => objects.CopyTo(array, index);
  196. public bool Remove(T item)
  197. {
  198. if (objects.Remove(item))
  199. {
  200. AddOperation(Operation.OP_REMOVE, item, true);
  201. return true;
  202. }
  203. return false;
  204. }
  205. public IEnumerator<T> GetEnumerator() => objects.GetEnumerator();
  206. IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  207. public void ExceptWith(IEnumerable<T> other)
  208. {
  209. if (other == this)
  210. {
  211. Clear();
  212. return;
  213. }
  214. // remove every element in other from this
  215. foreach (T element in other)
  216. {
  217. Remove(element);
  218. }
  219. }
  220. public void IntersectWith(IEnumerable<T> other)
  221. {
  222. if (other is ISet<T> otherSet)
  223. {
  224. IntersectWithSet(otherSet);
  225. }
  226. else
  227. {
  228. HashSet<T> otherAsSet = new HashSet<T>(other);
  229. IntersectWithSet(otherAsSet);
  230. }
  231. }
  232. void IntersectWithSet(ISet<T> otherSet)
  233. {
  234. List<T> elements = new List<T>(objects);
  235. foreach (T element in elements)
  236. {
  237. if (!otherSet.Contains(element))
  238. {
  239. Remove(element);
  240. }
  241. }
  242. }
  243. public bool IsProperSubsetOf(IEnumerable<T> other) => objects.IsProperSubsetOf(other);
  244. public bool IsProperSupersetOf(IEnumerable<T> other) => objects.IsProperSupersetOf(other);
  245. public bool IsSubsetOf(IEnumerable<T> other) => objects.IsSubsetOf(other);
  246. public bool IsSupersetOf(IEnumerable<T> other) => objects.IsSupersetOf(other);
  247. public bool Overlaps(IEnumerable<T> other) => objects.Overlaps(other);
  248. public bool SetEquals(IEnumerable<T> other) => objects.SetEquals(other);
  249. // custom implementation so we can do our own Clear/Add/Remove for delta
  250. public void SymmetricExceptWith(IEnumerable<T> other)
  251. {
  252. if (other == this)
  253. {
  254. Clear();
  255. }
  256. else
  257. {
  258. foreach (T element in other)
  259. {
  260. if (!Remove(element))
  261. {
  262. Add(element);
  263. }
  264. }
  265. }
  266. }
  267. // custom implementation so we can do our own Clear/Add/Remove for delta
  268. public void UnionWith(IEnumerable<T> other)
  269. {
  270. if (other != this)
  271. {
  272. foreach (T element in other)
  273. {
  274. Add(element);
  275. }
  276. }
  277. }
  278. }
  279. public class SyncHashSet<T> : SyncSet<T>
  280. {
  281. public SyncHashSet() : this(EqualityComparer<T>.Default) {}
  282. public SyncHashSet(IEqualityComparer<T> comparer) : base(new HashSet<T>(comparer ?? EqualityComparer<T>.Default)) {}
  283. // allocation free enumerator
  284. public new HashSet<T>.Enumerator GetEnumerator() => ((HashSet<T>)objects).GetEnumerator();
  285. }
  286. public class SyncSortedSet<T> : SyncSet<T>
  287. {
  288. public SyncSortedSet() : this(Comparer<T>.Default) {}
  289. public SyncSortedSet(IComparer<T> comparer) : base(new SortedSet<T>(comparer ?? Comparer<T>.Default)) {}
  290. // allocation free enumerator
  291. public new SortedSet<T>.Enumerator GetEnumerator() => ((SortedSet<T>)objects).GetEnumerator();
  292. }
  293. }