-
Notifications
You must be signed in to change notification settings - Fork 459
Expand file tree
/
Copy pathNetworkList.cs
More file actions
804 lines (722 loc) · 29.8 KB
/
NetworkList.cs
File metadata and controls
804 lines (722 loc) · 29.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Unity.Collections;
namespace Unity.Netcode
{
/// <summary>
/// Event based NetworkVariable container for syncing Lists
/// </summary>
/// <typeparam name="T">The type for the list</typeparam>
[GenerateSerializationForGenericParameter(0)]
public class NetworkList<T> : NetworkVariableBase where T : unmanaged, IEquatable<T>
{
private NativeList<T> m_List = new NativeList<T>(64, Allocator.Persistent);
private NativeList<NetworkListEvent<T>> m_DirtyEvents = new NativeList<NetworkListEvent<T>>(64, Allocator.Persistent);
/// <summary>
/// Delegate type for list changed event
/// </summary>
/// <param name="changeEvent">Struct containing information about the change event</param>
public delegate void OnListChangedDelegate(NetworkListEvent<T> changeEvent);
/// <summary>
/// Creates A NetworkList/>
/// </summary>
public event OnListChangedDelegate OnListChanged;
/// <summary>
/// Constructor method for <see cref="NetworkList{T}"/>
/// </summary>
public NetworkList() { }
/// <inheritdoc cref="NetworkList{T}"/>
/// <param name="values">An optional collection of initial values to populate the list. If null, the list will start empty.</param>
/// <param name="readPerm">The read permission level for the network list. Determines who can read the list (e.g., server-only or everyone). Default is defined by DefaultReadPerm</param>
/// <param name="writePerm">The write permission level for the network list. Determines who can modify the list (e.g., server-only or specific clients). Default is defined by DefaultWritePerm.</param>
public NetworkList(IEnumerable<T> values = default,
NetworkVariableReadPermission readPerm = DefaultReadPerm,
NetworkVariableWritePermission writePerm = DefaultWritePerm)
: base(readPerm, writePerm)
{
// allow null IEnumerable<T> to mean "no values"
if (values != null)
{
foreach (var value in values)
{
m_List.Add(value);
}
}
}
/// <summary>
/// Finalizer that ensures proper cleanup of network list resources
/// </summary>
~NetworkList()
{
Dispose();
}
internal override void OnSpawned()
{
// If the NetworkList is:
// - Dirty
// - State updates can be sent:
// -- The instance has write permissions.
// -- The last sent time plus the max send time period is less than the current time.
// - User script has modified the list during spawn.
// - This instance is on the spawn authority side.
// When the NetworkObject is finished spawning (on the same frame), go ahead and reset
// the dirty related properties and last sent time to prevent duplicate entries from
// being sent (i.e. CreateObjectMessage will contain the changes so we don't need to
// send a proceeding NetworkVariableDeltaMessage).
if (IsDirty() && CanSend() && m_NetworkObject.IsSpawnAuthority)
{
UpdateLastSentTime();
ResetDirty();
SetDirty(false);
}
base.OnSpawned();
}
/// <inheritdoc cref="NetworkVariable{T}.ResetDirty"/>
public override void ResetDirty()
{
base.ResetDirty();
if (m_DirtyEvents.Length > 0)
{
m_DirtyEvents.Clear();
}
}
/// <inheritdoc cref="NetworkVariable{T}.IsDirty"/>
public override bool IsDirty()
{
// we call the base class to allow the SetDirty() mechanism to work
return base.IsDirty() || m_DirtyEvents.Length > 0;
}
internal void MarkNetworkObjectDirty()
{
MarkNetworkBehaviourDirty();
}
/// <inheritdoc cref="NetworkVariable{T}.WriteDelta"/>
public override void WriteDelta(FastBufferWriter writer)
{
if (base.IsDirty())
{
writer.WriteValueSafe((ushort)1);
writer.WriteValueSafe(NetworkListEvent<T>.EventType.Full);
WriteField(writer);
return;
}
writer.WriteValueSafe((ushort)m_DirtyEvents.Length);
for (int i = 0; i < m_DirtyEvents.Length; i++)
{
var element = m_DirtyEvents.ElementAt(i);
writer.WriteValueSafe(element.Type);
switch (element.Type)
{
case NetworkListEvent<T>.EventType.Add:
{
NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
}
break;
case NetworkListEvent<T>.EventType.Insert:
{
BytePacker.WriteValueBitPacked(writer, element.Index);
NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
}
break;
case NetworkListEvent<T>.EventType.Remove:
{
NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
}
break;
case NetworkListEvent<T>.EventType.RemoveAt:
{
BytePacker.WriteValueBitPacked(writer, element.Index);
}
break;
case NetworkListEvent<T>.EventType.Value:
{
BytePacker.WriteValueBitPacked(writer, element.Index);
NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
}
break;
case NetworkListEvent<T>.EventType.Clear:
{
//Nothing has to be written
}
break;
}
}
}
/// <inheritdoc cref="NetworkVariable{T}.WriteField"/>
public override void WriteField(FastBufferWriter writer)
{
writer.WriteValueSafe((ushort)m_List.Length);
for (int i = 0; i < m_List.Length; i++)
{
NetworkVariableSerialization<T>.Serializer.Write(writer, ref m_List.ElementAt(i));
}
}
/// <inheritdoc cref="NetworkVariable{T}.ReadField"/>
public override void ReadField(FastBufferReader reader)
{
m_List.Clear();
reader.ReadValueSafe(out ushort count);
for (int i = 0; i < count; i++)
{
var value = new T();
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
m_List.Add(value);
}
}
/// <inheritdoc cref="NetworkVariable{T}.ReadDelta"/>
public override void ReadDelta(FastBufferReader reader, bool keepDirtyDelta)
{
// This is only invoked by <see cref="NetworkVariableDeltaMessage"/> and the only time
// keepDirtyDelta is set is when it is the server processing. To be able to handle previous
// versions, we use IsServer to keep the dirty states received and the keepDirtyDelta to
// actually mark this as dirty and add it to the list of <see cref="NetworkObject"/>s to
// be updated. With the forwarding of deltas being handled by <see cref="NetworkVariableDeltaMessage"/>,
// once all clients have been forwarded the dirty events, we clear them by invoking <see cref="PostDeltaRead"/>.
var isServer = m_NetworkManager.IsServer;
reader.ReadValueSafe(out ushort deltaCount);
for (int i = 0; i < deltaCount; i++)
{
reader.ReadValueSafe(out NetworkListEvent<T>.EventType eventType);
switch (eventType)
{
case NetworkListEvent<T>.EventType.Add:
{
var value = new T();
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
m_List.Add(value);
if (OnListChanged != null)
{
OnListChanged(new NetworkListEvent<T>
{
Type = eventType,
Index = m_List.Length - 1,
Value = m_List[m_List.Length - 1]
});
}
if (isServer)
{
m_DirtyEvents.Add(new NetworkListEvent<T>()
{
Type = eventType,
Index = m_List.Length - 1,
Value = m_List[m_List.Length - 1]
});
// Preserve the legacy way of handling this
if (keepDirtyDelta)
{
MarkNetworkObjectDirty();
}
}
}
break;
case NetworkListEvent<T>.EventType.Insert:
{
ByteUnpacker.ReadValueBitPacked(reader, out int index);
var value = new T();
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
if (index < m_List.Length)
{
m_List.InsertRangeWithBeginEnd(index, index + 1);
m_List[index] = value;
}
else
{
m_List.Add(value);
}
if (OnListChanged != null)
{
OnListChanged(new NetworkListEvent<T>
{
Type = eventType,
Index = index,
Value = m_List[index]
});
}
if (isServer)
{
m_DirtyEvents.Add(new NetworkListEvent<T>()
{
Type = eventType,
Index = index,
Value = m_List[index]
});
// Preserve the legacy way of handling this
if (keepDirtyDelta)
{
MarkNetworkObjectDirty();
}
}
}
break;
case NetworkListEvent<T>.EventType.Remove:
{
var value = new T();
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
int index = m_List.IndexOf(value);
if (index == -1)
{
break;
}
m_List.RemoveAt(index);
if (OnListChanged != null)
{
OnListChanged(new NetworkListEvent<T>
{
Type = eventType,
Index = index,
Value = value
});
}
if (isServer)
{
m_DirtyEvents.Add(new NetworkListEvent<T>()
{
Type = eventType,
Index = index,
Value = value
});
// Preserve the legacy way of handling this
if (keepDirtyDelta)
{
MarkNetworkObjectDirty();
}
}
}
break;
case NetworkListEvent<T>.EventType.RemoveAt:
{
ByteUnpacker.ReadValueBitPacked(reader, out int index);
T value = m_List[index];
m_List.RemoveAt(index);
if (OnListChanged != null)
{
OnListChanged(new NetworkListEvent<T>
{
Type = eventType,
Index = index,
Value = value
});
}
if (isServer)
{
m_DirtyEvents.Add(new NetworkListEvent<T>()
{
Type = eventType,
Index = index,
Value = value
});
// Preserve the legacy way of handling this
if (keepDirtyDelta)
{
MarkNetworkObjectDirty();
}
}
}
break;
case NetworkListEvent<T>.EventType.Value:
{
ByteUnpacker.ReadValueBitPacked(reader, out int index);
var value = new T();
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
if (index >= m_List.Length)
{
throw new Exception("Shouldn't be here, index is higher than list length");
}
var previousValue = m_List[index];
m_List[index] = value;
if (OnListChanged != null)
{
OnListChanged(new NetworkListEvent<T>
{
Type = eventType,
Index = index,
Value = value,
PreviousValue = previousValue
});
}
if (isServer)
{
m_DirtyEvents.Add(new NetworkListEvent<T>()
{
Type = eventType,
Index = index,
Value = value,
PreviousValue = previousValue
});
// Preserve the legacy way of handling this
if (keepDirtyDelta)
{
MarkNetworkObjectDirty();
}
}
}
break;
case NetworkListEvent<T>.EventType.Clear:
{
//Read nothing
m_List.Clear();
if (OnListChanged != null)
{
OnListChanged(new NetworkListEvent<T>
{
Type = eventType,
});
}
if (isServer)
{
m_DirtyEvents.Add(new NetworkListEvent<T>()
{
Type = eventType
});
// Preserve the legacy way of handling this
if (keepDirtyDelta)
{
MarkNetworkObjectDirty();
}
}
}
break;
case NetworkListEvent<T>.EventType.Full:
{
ReadField(reader);
ResetDirty();
}
break;
}
}
}
/// <inheritdoc cref="NetworkVariable{T}.PostDeltaRead"/>
/// <remarks>
/// For NetworkList, we just need to reset dirty if a server has read deltas
/// </remarks>
internal override void PostDeltaRead()
{
if (m_NetworkManager.IsServer)
{
ResetDirty();
}
}
/// <summary>
/// Returns an enumerator that iterates through the <see cref="NetworkList{T}" />.
/// </summary>
/// <returns>An enumerator for the <see cref="NetworkList{T}"/>.</returns>
public IEnumerator<T> GetEnumerator()
{
return m_List.GetEnumerator();
}
/// <summary>
/// Adds an item to the end of the <see cref="NetworkList{T}"/>.
/// </summary>
/// <param name="item">The item to be added to the list.</param>
/// <remarks>
/// This method checks for write permissions before adding the item.
/// </remarks>
public void Add(T item)
{
// check write permissions
if (CannotWrite())
{
LogWritePermissionError();
return;
}
m_List.Add(item);
var listEvent = new NetworkListEvent<T>()
{
Type = NetworkListEvent<T>.EventType.Add,
Value = item,
Index = m_List.Length - 1
};
HandleAddListEvent(listEvent);
}
/// <summary>
/// Removes all items from the <see cref="NetworkList{T}"/>.
/// </summary>
/// <remarks>
/// This method checks for write permissions before clearing the list.
/// </remarks>
public void Clear()
{
// check write permissions
if (CannotWrite())
{
LogWritePermissionError();
return;
}
m_List.Clear();
var listEvent = new NetworkListEvent<T>()
{
Type = NetworkListEvent<T>.EventType.Clear
};
HandleAddListEvent(listEvent);
}
/// <summary>
/// Determines whether the <see cref="NetworkList{T}"/> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="NetworkList{T}"/>.</param>
/// <returns><see langword="true" /> if the <see cref="item"/> is found in the <see cref="NetworkList{T}"/>; otherwise, <see langword="false" />.</returns>
public bool Contains(T item)
{
int index = m_List.IndexOf(item);
return index != -1;
}
/// <summary>
/// Removes the first occurrence of a specific object from the NetworkList.
/// </summary>
/// <remarks>
/// This method checks for write permissions before removing the item.
/// </remarks>
/// <param name="item">The object to remove from the list.</param>
/// <returns><see langword="true" /> if the item was successfully removed from the list; otherwise, <see langword="false" />.</returns>
public bool Remove(T item)
{
// check write permissions
if (CannotWrite())
{
LogWritePermissionError();
return false;
}
int index = m_List.IndexOf(item);
if (index == -1)
{
return false;
}
m_List.RemoveAt(index);
var listEvent = new NetworkListEvent<T>()
{
Type = NetworkListEvent<T>.EventType.Remove,
Value = item
};
HandleAddListEvent(listEvent);
return true;
}
/// <summary>
/// Gets the number of elements contained in the <see cref="NetworkList{T}"/>.
/// </summary>
public int Count => m_List.Length;
/// <summary>
/// Determines the index of a specific <see cref="item"/> in the <see cref="NetworkList{T}"/>.
/// </summary>
/// <param name="item">The object to remove from the list.</param>
/// <returns>The index of the <see cref="item"/> if found in the list; otherwise, -1.</returns>
public int IndexOf(T item)
{
return m_List.IndexOf(item);
}
/// <summary>
/// Inserts <see cref="item"/> to the <see cref="NetworkList{T}"/> at the specified <see cref="index"/>.
/// </summary>
/// <remarks>
/// This method checks for write permissions before inserting the item.
/// </remarks>
/// <param name="index">The index at which the item should be inserted.</param>
/// <param name="item">The item to insert.</param>
public void Insert(int index, T item)
{
// check write permissions
if (CannotWrite())
{
LogWritePermissionError();
return;
}
if (index < m_List.Length)
{
m_List.InsertRangeWithBeginEnd(index, index + 1);
m_List[index] = item;
}
else
{
m_List.Add(item);
}
var listEvent = new NetworkListEvent<T>()
{
Type = NetworkListEvent<T>.EventType.Insert,
Index = index,
Value = item
};
HandleAddListEvent(listEvent);
}
/// <summary>
/// Removes the <see cref="NetworkList{T}"/> item at the specified <see cref="index"/>.
/// </summary>
/// <remarks>
/// This method checks for write permissions before removing the item.
/// </remarks>
/// <param name="index">The index of the element to remove.</param>
public void RemoveAt(int index)
{
// check write permissions
if (CannotWrite())
{
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
}
var value = m_List[index];
m_List.RemoveAt(index);
var listEvent = new NetworkListEvent<T>()
{
Type = NetworkListEvent<T>.EventType.RemoveAt,
Index = index,
Value = value
};
HandleAddListEvent(listEvent);
}
/// <summary>
/// Sets the element at the specified index in the <see cref="NetworkList{T}"/>.
/// </summary>
/// <remarks>
/// This method checks for write permissions and equality before setting and updating the value.
/// </remarks>
/// <param name="index">The zero-based index of the element to set.</param>
/// <param name="value">The new value to set at the given index</param>
/// <param name="forceUpdate">
/// Ignores the equality check when setting the value.
/// This option can send unnecessary updates to all clients when the value hasn't changed.
/// </param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Set(int index, T value, bool forceUpdate = false)
{
// check write permissions
if (CannotWrite())
{
LogWritePermissionError();
return;
}
var previousValue = m_List[index];
// Only trigger an event if the value has changed
if (!forceUpdate && NetworkVariableSerialization<T>.AreEqual(ref previousValue, ref value))
{
return;
}
m_List[index] = value;
var listEvent = new NetworkListEvent<T>()
{
Type = NetworkListEvent<T>.EventType.Value,
Index = index,
Value = value,
PreviousValue = previousValue
};
HandleAddListEvent(listEvent);
}
/// <summary>
/// Gets or sets the element at the specified index in the <see cref="NetworkList{T}"/>.
/// </summary>
/// <remarks>
/// This method checks for write permissions before setting the value.
/// </remarks>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <value>The element at the specified index.</value>
public T this[int index]
{
get => m_List[index];
set => Set(index, value);
}
/// <summary>
/// Gets a **zero‑allocation**, <see cref="NativeArray{T}.ReadOnly"/> view over the current
/// elements of this <see cref="NetworkList{T}"/>.
/// </summary>
/// <remarks>
/// The returned array stays valid **only until** the list is mutated (add, remove,
/// clear, resize) or <see cref="Dispose()"/> is called on the container. Continuing to use
/// the array after it is invalid will result in undefined behaviour;
/// callers are responsible for ensuring a safe lifetime.
/// </remarks>
/// <returns>
/// A <see cref="NativeArray{T}.ReadOnly"/> reference that shares the same backing memory as this list.
/// </returns>
public NativeArray<T>.ReadOnly AsNativeArray()
{
return m_List.AsReadOnly();
}
private void HandleAddListEvent(NetworkListEvent<T> listEvent)
{
m_DirtyEvents.Add(listEvent);
MarkNetworkObjectDirty();
OnListChanged?.Invoke(listEvent);
}
/// <summary>
/// This method should not be used. It is left over from a previous interface
/// </summary>
public int LastModifiedTick
{
get
{
// todo: implement proper network tick for NetworkList
return NetworkTickSystem.NoTick;
}
}
/// <summary>
/// Overridden <see cref="IDisposable"/> implementation.
/// CAUTION: If you derive from this class and override the <see cref="Dispose"/> method,
/// you **must** always invoke the base.Dispose() method!
/// </summary>
public override void Dispose()
{
if (m_List.IsCreated)
{
m_List.Dispose();
}
if (m_DirtyEvents.IsCreated)
{
m_DirtyEvents.Dispose();
}
base.Dispose();
}
}
/// <summary>
/// Struct containing event information about changes to a NetworkList.
/// </summary>
/// <typeparam name="T">The type for the list that the event is about</typeparam>
public struct NetworkListEvent<T>
{
/// <summary>
/// Enum representing the different operations available for triggering an event.
/// </summary>
public enum EventType : byte
{
/// <summary>
/// Add
/// </summary>
Add,
/// <summary>
/// Insert
/// </summary>
Insert,
/// <summary>
/// Remove
/// </summary>
Remove,
/// <summary>
/// Remove at
/// </summary>
RemoveAt,
/// <summary>
/// Value changed
/// </summary>
Value,
/// <summary>
/// Clear
/// </summary>
Clear,
/// <summary>
/// Full list refresh
/// </summary>
Full
}
/// <summary>
/// Enum representing the operation made to the list.
/// </summary>
public EventType Type;
/// <summary>
/// The value changed, added or removed if available.
/// </summary>
public T Value;
/// <summary>
/// The previous value when "Value" has changed, if available.
/// </summary>
public T PreviousValue;
/// <summary>
/// the index changed, added or removed if available
/// </summary>
public int Index;
}
}