-
Notifications
You must be signed in to change notification settings - Fork 461
Expand file tree
/
Copy pathNetworkedBehaviour.cs
More file actions
807 lines (706 loc) · 34.6 KB
/
NetworkedBehaviour.cs
File metadata and controls
807 lines (706 loc) · 34.6 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
805
806
807
using System;
using System.Collections.Generic;
using System.ComponentModel;
using UnityEngine;
using System.Reflection;
using System.Linq;
using System.IO;
using MLAPI.Configuration;
using MLAPI.Logging;
using MLAPI.Messaging;
using MLAPI.NetworkedVar;
using MLAPI.Profiling;
using MLAPI.Reflection;
using MLAPI.Security;
using MLAPI.Serialization;
using MLAPI.Serialization.Pooled;
using MLAPI.Spawning;
using BitStream = MLAPI.Serialization.BitStream;
using Unity.Profiling;
#if UNITY_EDITOR
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Unity.Multiplayer.MLAPI.Editor.CodeGen")]
#endif // UNITY_EDITOR
namespace MLAPI
{
/// <summary>
/// The base class to override to write networked code. Inherits MonoBehaviour
/// </summary>
public abstract class NetworkedBehaviour : MonoBehaviour
{
// RuntimeAccessModifiersILPP will make this `protected`
internal enum NExec
{
None = 0,
Server = 1,
Client = 2
}
/// <summary>
/// This is a temporary solution for channel names and the below hardcoded value might not be mandatory in the future.
/// </summary>
private const string StandardRpc_ChannelName = "STDRPC";
#pragma warning disable 414
// RuntimeAccessModifiersILPP will make this `protected`
internal NExec __nexec = NExec.None;
#pragma warning restore 414
// RuntimeAccessModifiersILPP will make this `protected`
internal BitWriter BeginSendServerRpc(ServerRpcSendParams sendParams, bool isReliable)
{
var rpcQueueMananger = NetworkingManager.Singleton.RpcQueueManager;
var writer = rpcQueueMananger.BeginAddQueueItemToOutboundFrame(RpcQueueContainer.QueueItemType.ServerRpc, Time.realtimeSinceStartup, StandardRpc_ChannelName, 0, NetworkingManager.Singleton.ServerClientId, null);
writer.WriteUInt64Packed(NetworkId); // NetworkObjectId
writer.WriteUInt16Packed(GetBehaviourId()); // NetworkBehaviourId
return writer;
}
// RuntimeAccessModifiersILPP will make this `protected`
internal void EndSendServerRpc(BitWriter writer, ServerRpcSendParams sendParams, bool isReliable)
{
if (writer == null) return;
var rpcQueueMananger = NetworkingManager.Singleton.RpcQueueManager;
rpcQueueMananger?.EndAddQueueItemToOutboundFrame(writer);
}
// RuntimeAccessModifiersILPP will make this `protected`
internal BitWriter BeginSendClientRpc(ClientRpcSendParams sendParams, bool isReliable)
{
//This will start a new queue item entry and will then return the writer to the current frame's stream
var rpcQueueMananger = NetworkingManager.Singleton.RpcQueueManager;
var writer = rpcQueueMananger.BeginAddQueueItemToOutboundFrame(RpcQueueContainer.QueueItemType.ClientRpc, Time.realtimeSinceStartup, StandardRpc_ChannelName, 0, NetworkId, sendParams.TargetClientIds ?? NetworkingManager.Singleton.ConnectedClientsList.Select(c => c.ClientId).ToArray());
writer.WriteUInt64Packed(NetworkId); // NetworkObjectId
writer.WriteUInt16Packed(GetBehaviourId()); // NetworkBehaviourId
return writer;
}
// RuntimeAccessModifiersILPP will make this `protected`
internal void EndSendClientRpc(BitWriter writer, ClientRpcSendParams sendParams, bool isReliable)
{
if (writer == null) return;
var rpcQueueMananger = NetworkingManager.Singleton.RpcQueueManager;
rpcQueueMananger?.EndAddQueueItemToOutboundFrame(writer);
}
/// <summary>
/// Gets if the object is the the personal clients player object
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use IsLocalPlayer instead", false)]
public bool isLocalPlayer => IsLocalPlayer;
/// <summary>
/// Gets if the object is the the personal clients player object
/// </summary>
public bool IsLocalPlayer => NetworkedObject.IsLocalPlayer;
/// <summary>
/// Gets if the object is owned by the local player or if the object is the local player object
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use IsOwner instead", false)]
public bool isOwner => IsOwner;
/// <summary>
/// Gets if the object is owned by the local player or if the object is the local player object
/// </summary>
public bool IsOwner => NetworkedObject.IsOwner;
/// <summary>
/// Gets if we are executing as server
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use IsServer instead", false)]
protected bool isServer => IsServer;
/// <summary>
/// Gets if we are executing as server
/// </summary>
protected static bool IsServer => IsRunning && NetworkingManager.Singleton.IsServer;
/// <summary>
/// Gets if we are executing as client
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use IsClient instead")]
protected bool isClient => IsClient;
/// <summary>
/// Gets if we are executing as client
/// </summary>
protected bool IsClient => IsRunning && NetworkingManager.Singleton.IsClient;
/// <summary>
/// Gets if we are executing as Host, I.E Server and Client
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use IsHost instead", false)]
protected bool isHost => IsHost;
/// <summary>
/// Gets if we are executing as Host, I.E Server and Client
/// </summary>
protected bool IsHost => IsRunning && NetworkingManager.Singleton.IsHost;
private static bool IsRunning => NetworkingManager.Singleton != null && NetworkingManager.Singleton.IsListening;
/// <summary>
/// Gets Whether or not the object has a owner
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use IsOwnedByServer instead", false)]
public bool isOwnedByServer => IsOwnedByServer;
/// <summary>
/// Gets Whether or not the object has a owner
/// </summary>
public bool IsOwnedByServer => NetworkedObject.IsOwnedByServer;
/// <summary>
/// Gets the NetworkedObject that owns this NetworkedBehaviour instance
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use NetworkedObject instead", false)]
public NetworkedObject networkedObject => NetworkedObject;
/// <summary>
/// Gets the NetworkedObject that owns this NetworkedBehaviour instance
/// </summary>
public NetworkedObject NetworkedObject
{
get
{
if (_networkedObject == null)
{
_networkedObject = GetComponentInParent<NetworkedObject>();
}
if (_networkedObject == null)
{
throw new NullReferenceException("Could not get NetworkedObject for the NetworkedBehaviour. Are you missing a NetworkedObject component?");
}
return _networkedObject;
}
}
/// <summary>
/// Gets whether or not this NetworkedBehaviour instance has a NetworkedObject owner.
/// </summary>
public bool HasNetworkedObject
{
get
{
if (_networkedObject == null)
{
_networkedObject = GetComponentInParent<NetworkedObject>();
}
return _networkedObject != null;
}
}
private NetworkedObject _networkedObject = null;
/// <summary>
/// Gets the NetworkId of the NetworkedObject that owns the NetworkedBehaviour instance
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use NetworkId instead", false)]
public ulong networkId => NetworkId;
/// <summary>
/// Gets the NetworkId of the NetworkedObject that owns the NetworkedBehaviour instance
/// </summary>
public ulong NetworkId => NetworkedObject.NetworkId;
/// <summary>
/// Gets the clientId that owns the NetworkedObject
/// </summary>
public ulong OwnerClientId => NetworkedObject.OwnerClientId;
internal bool networkedStartInvoked = false;
internal bool internalNetworkedStartInvoked = false;
/// <summary>
/// Gets called when message handlers are ready to be registered and the networking is setup
/// </summary>
public virtual void NetworkStart()
{
}
/// <summary>
/// Gets called when message handlers are ready to be registered and the networking is setup. Provides a Payload if it was provided
/// </summary>
/// <param name="stream">The stream containing the spawn payload</param>
public virtual void NetworkStart(Stream stream)
{
NetworkStart();
}
internal void InternalNetworkStart()
{
InitializeVars();
}
/// <summary>
/// Gets called when the local client gains ownership of this object
/// </summary>
public virtual void OnGainedOwnership()
{
}
/// <summary>
/// Gets called when we loose ownership of this object
/// </summary>
public virtual void OnLostOwnership()
{
}
/// <summary>
/// Gets behaviourId for this NetworkedBehaviour on this NetworkedObject
/// </summary>
/// <returns>The behaviourId for the current NetworkedBehaviour</returns>
public ushort GetBehaviourId()
{
return NetworkedObject.GetOrderIndex(this);
}
/// <summary>
/// Returns a the NetworkedBehaviour with a given behaviourId for the current networkedObject
/// </summary>
/// <param name="id">The behaviourId to return</param>
/// <returns>Returns NetworkedBehaviour with given behaviourId</returns>
protected NetworkedBehaviour GetBehaviour(ushort id)
{
return NetworkedObject.GetBehaviourAtOrderIndex(id);
}
#region NetworkedVar
private bool varInit = false;
private readonly List<HashSet<int>> channelMappedNetworkedVarIndexes = new List<HashSet<int>>();
private readonly List<string> channelsForNetworkedVarGroups = new List<string>();
internal readonly List<INetworkedVar> networkedVarFields = new List<INetworkedVar>();
private static HashSet<MLAPI.NetworkedObject> touched = new HashSet<MLAPI.NetworkedObject>();
private static readonly Dictionary<Type, FieldInfo[]> fieldTypes = new Dictionary<Type, FieldInfo[]>();
private static FieldInfo[] GetFieldInfoForType(Type type)
{
if (!fieldTypes.ContainsKey(type))
fieldTypes.Add(type, GetFieldInfoForTypeRecursive(type));
return fieldTypes[type];
}
private static FieldInfo[] GetFieldInfoForTypeRecursive(Type type, List<FieldInfo> list = null)
{
if (list == null)
{
list = new List<FieldInfo>();
list.AddRange(type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance));
}
else
{
list.AddRange(type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance));
}
if (type.BaseType != null && type.BaseType != typeof(NetworkedBehaviour))
{
return GetFieldInfoForTypeRecursive(type.BaseType, list);
}
else
{
return list.OrderBy(x => x.Name, StringComparer.Ordinal).ToArray();
}
}
internal void InitializeVars()
{
if (varInit)
return;
varInit = true;
FieldInfo[] sortedFields = GetFieldInfoForType(GetType());
for (int i = 0; i < sortedFields.Length; i++)
{
Type fieldType = sortedFields[i].FieldType;
if (fieldType.HasInterface(typeof(INetworkedVar)))
{
INetworkedVar instance = (INetworkedVar)sortedFields[i].GetValue(this);
if (instance == null)
{
instance = (INetworkedVar)Activator.CreateInstance(fieldType, true);
sortedFields[i].SetValue(this, instance);
}
instance.SetNetworkedBehaviour(this);
networkedVarFields.Add(instance);
}
}
{
// Create index map for channels
Dictionary<string, int> firstLevelIndex = new Dictionary<string, int>();
int secondLevelCounter = 0;
for (int i = 0; i < networkedVarFields.Count; i++)
{
string channel = networkedVarFields[i].GetChannel(); // Cache this here. Some developers are stupid. You don't know what shit they will do in their methods
if (!firstLevelIndex.ContainsKey(channel))
{
firstLevelIndex.Add(channel, secondLevelCounter);
channelsForNetworkedVarGroups.Add(channel);
secondLevelCounter++;
}
if (firstLevelIndex[channel] >= channelMappedNetworkedVarIndexes.Count)
{
channelMappedNetworkedVarIndexes.Add(new HashSet<int>());
}
channelMappedNetworkedVarIndexes[firstLevelIndex[channel]].Add(i);
}
}
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
public static ProfilerMarker s_NetworkedBehaviourUpdate = new ProfilerMarker("MLAPI.NetworkedObject.NetworkedBehaviourUpdate");
#endif
internal static void NetworkedBehaviourUpdate()
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_NetworkedBehaviourUpdate.Begin();
#endif
try
{
if (IsServer)
{
touched.Clear();
for (int i = 0; i < NetworkingManager.Singleton.ConnectedClientsList.Count; i++)
{
var client = NetworkingManager.Singleton.ConnectedClientsList[i];
var spawnedObjs = SpawnManager.SpawnedObjectsList;
touched.UnionWith(spawnedObjs);
foreach (var sobj in spawnedObjs)
{
// Sync just the variables for just the objects this client sees
for (int k = 0; k < sobj.childNetworkedBehaviours.Count; k++)
{
sobj.childNetworkedBehaviours[k].VarUpdate(client.ClientId);
}
}
}
// Now, reset all the no-longer-dirty variables
foreach (var sobj in touched)
{
for (int k = 0; k < sobj.childNetworkedBehaviours.Count; k++)
{
sobj.childNetworkedBehaviours[k].PostNetworkVariableWrite();
}
}
}
else
{
// when client updates the sever, it tells it about all its objects
foreach (var sobj in SpawnManager.SpawnedObjectsList)
{
for (int k = 0; k < sobj.childNetworkedBehaviours.Count; k++)
{
sobj.childNetworkedBehaviours[k].VarUpdate(NetworkingManager.Singleton.ServerClientId);
}
}
// Now, reset all the no-longer-dirty variables
foreach (var sobj in SpawnManager.SpawnedObjectsList)
{
for (int k = 0; k < sobj.childNetworkedBehaviours.Count; k++)
{
sobj.childNetworkedBehaviours[k].PostNetworkVariableWrite();
}
}
}
}
finally
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_NetworkedBehaviourUpdate.End();
#endif
}
}
internal void PreNetworkVariableWrite()
{
// reset our "which variables got written" data
networkedVarIndexesToReset.Clear();
networkedVarIndexesToResetSet.Clear();
}
internal void PostNetworkVariableWrite()
{
// mark any variables we wrote as no longer dirty
for (int i = 0; i < networkedVarIndexesToReset.Count; i++)
{
networkedVarFields[networkedVarIndexesToReset[i]].ResetDirty();
}
}
internal void VarUpdate(ulong clientId)
{
if (!varInit)
InitializeVars();
PreNetworkVariableWrite();
NetworkedVarUpdate(clientId);
}
private readonly List<int> networkedVarIndexesToReset = new List<int>();
private readonly HashSet<int> networkedVarIndexesToResetSet = new HashSet<int>();
private void NetworkedVarUpdate(ulong clientId)
{
if (!CouldHaveDirtyNetworkedVars())
return;
for (int j = 0; j < channelMappedNetworkedVarIndexes.Count; j++)
{
using (PooledBitStream stream = PooledBitStream.Get())
{
using (PooledBitWriter writer = PooledBitWriter.Get(stream))
{
writer.WriteUInt64Packed(NetworkId);
writer.WriteUInt16Packed(NetworkedObject.GetOrderIndex(this));
bool writtenAny = false;
for (int k = 0; k < networkedVarFields.Count; k++)
{
if (!channelMappedNetworkedVarIndexes[j].Contains(k))
{
// This var does not belong to the currently iterating channel group.
if (NetworkingManager.Singleton.NetworkConfig.EnsureNetworkedVarLengthSafety)
{
writer.WriteUInt16Packed(0);
}
else
{
writer.WriteBool(false);
}
continue;
}
bool isDirty = networkedVarFields[k].IsDirty(); // cache this here. You never know what operations users will do in the dirty methods
// if I'm dirty AND a client, write (server always has all permissions)
// if I'm dirty AND the server AND the client can read me, send.
bool shouldWrite = isDirty && (!IsServer || networkedVarFields[k].CanClientRead(clientId));
if (NetworkingManager.Singleton.NetworkConfig.EnsureNetworkedVarLengthSafety)
{
if (!shouldWrite)
{
writer.WriteUInt16Packed(0);
}
}
else
{
writer.WriteBool(shouldWrite);
}
if (shouldWrite)
{
writtenAny = true;
if (NetworkingManager.Singleton.NetworkConfig.EnsureNetworkedVarLengthSafety)
{
using (PooledBitStream varStream = PooledBitStream.Get())
{
networkedVarFields[k].WriteDelta(varStream);
varStream.PadStream();
writer.WriteUInt16Packed((ushort)varStream.Length);
stream.CopyFrom(varStream);
}
}
else
{
networkedVarFields[k].WriteDelta(stream);
}
if (!networkedVarIndexesToResetSet.Contains(k))
{
networkedVarIndexesToResetSet.Add(k);
networkedVarIndexesToReset.Add(k);
}
}
}
if (writtenAny)
{
InternalMessageSender.Send(clientId,
MLAPIConstants.MLAPI_NETWORKED_VAR_DELTA,
channelsForNetworkedVarGroups[j], stream, SecuritySendFlags.None);
}
}
}
}
}
private bool CouldHaveDirtyNetworkedVars()
{
// TODO: There should be a better way by reading one dirty variable vs. 'n'
for (int i = 0; i < networkedVarFields.Count; i++)
{
if (networkedVarFields[i].IsDirty())
return true;
}
return false;
}
internal static void HandleNetworkedVarDeltas(List<INetworkedVar> networkedVarList, Stream stream, ulong clientId, NetworkedBehaviour logInstance)
{
using (PooledBitReader reader = PooledBitReader.Get(stream))
{
for (int i = 0; i < networkedVarList.Count; i++)
{
ushort varSize = 0;
if (NetworkingManager.Singleton.NetworkConfig.EnsureNetworkedVarLengthSafety)
{
varSize = reader.ReadUInt16Packed();
if (varSize == 0)
continue;
}
else
{
if (!reader.ReadBool())
continue;
}
if (IsServer && !networkedVarList[i].CanClientWrite(clientId))
{
if (NetworkingManager.Singleton.NetworkConfig.EnsureNetworkedVarLengthSafety)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Client wrote to NetworkedVar without permission. " + (logInstance != null ? ("NetworkId: " + logInstance.NetworkId + " BehaviourIndex: " + logInstance.NetworkedObject.GetOrderIndex(logInstance) + " VariableIndex: " + i) : string.Empty));
stream.Position += varSize;
continue;
}
else
{
//This client wrote somewhere they are not allowed. This is critical
//We can't just skip this field. Because we don't actually know how to dummy read
//That is, we don't know how many bytes to skip. Because the interface doesn't have a
//Read that gives us the value. Only a Read that applies the value straight away
//A dummy read COULD be added to the interface for this situation, but it's just being too nice.
//This is after all a developer fault. A critical error should be fine.
// - TwoTen
if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogError("Client wrote to NetworkedVar without permission. No more variables can be read. This is critical. " + (logInstance != null ? ("NetworkId: " + logInstance.NetworkId + " BehaviourIndex: " + logInstance.NetworkedObject.GetOrderIndex(logInstance) + " VariableIndex: " + i) : string.Empty));
return;
}
}
long readStartPos = stream.Position;
networkedVarList[i].ReadDelta(stream, IsServer);
ProfilerStatManager.networkVarsRcvd.Record();
if (NetworkingManager.Singleton.NetworkConfig.EnsureNetworkedVarLengthSafety)
{
(stream as BitStream).SkipPadBits();
if (stream.Position > (readStartPos + varSize))
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Var delta read too far. " + (stream.Position - (readStartPos + varSize)) + " bytes." + (logInstance != null ? ("NetworkId: " + logInstance.NetworkId + " BehaviourIndex: " + logInstance.NetworkedObject.GetOrderIndex(logInstance) + " VariableIndex: " + i) : string.Empty));
stream.Position = readStartPos + varSize;
}
else if (stream.Position < (readStartPos + varSize))
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Var delta read too little. " + ((readStartPos + varSize) - stream.Position) + " bytes." + (logInstance != null ? ("NetworkId: " + logInstance.NetworkId + " BehaviourIndex: " + logInstance.NetworkedObject.GetOrderIndex(logInstance) + " VariableIndex: " + i) : string.Empty));
stream.Position = readStartPos + varSize;
}
}
}
}
}
internal static void HandleNetworkedVarUpdate(List<INetworkedVar> networkedVarList, Stream stream, ulong clientId, NetworkedBehaviour logInstance)
{
using (PooledBitReader reader = PooledBitReader.Get(stream))
{
for (int i = 0; i < networkedVarList.Count; i++)
{
ushort varSize = 0;
if (NetworkingManager.Singleton.NetworkConfig.EnsureNetworkedVarLengthSafety)
{
varSize = reader.ReadUInt16Packed();
if (varSize == 0)
continue;
}
else
{
if (!reader.ReadBool())
continue;
}
if (IsServer && !networkedVarList[i].CanClientWrite(clientId))
{
if (NetworkingManager.Singleton.NetworkConfig.EnsureNetworkedVarLengthSafety)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Client wrote to NetworkedVar without permission. " + (logInstance != null ? ("NetworkId: " + logInstance.NetworkId + " BehaviourIndex: " + logInstance.NetworkedObject.GetOrderIndex(logInstance) + " VariableIndex: " + i) : string.Empty));
stream.Position += varSize;
continue;
}
else
{
//This client wrote somewhere they are not allowed. This is critical
//We can't just skip this field. Because we don't actually know how to dummy read
//That is, we don't know how many bytes to skip. Because the interface doesn't have a
//Read that gives us the value. Only a Read that applies the value straight away
//A dummy read COULD be added to the interface for this situation, but it's just being too nice.
//This is after all a developer fault. A critical error should be fine.
// - TwoTen
if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogError("Client wrote to NetworkedVar without permission. No more variables can be read. This is critical. " + (logInstance != null ? ("NetworkId: " + logInstance.NetworkId + " BehaviourIndex: " + logInstance.NetworkedObject.GetOrderIndex(logInstance) + " VariableIndex: " + i) : string.Empty));
return;
}
}
long readStartPos = stream.Position;
networkedVarList[i].ReadField(stream);
ProfilerStatManager.networkVarsRcvd.Record();
if (NetworkingManager.Singleton.NetworkConfig.EnsureNetworkedVarLengthSafety)
{
if (stream is BitStream bitStream)
{
bitStream.SkipPadBits();
}
if (stream.Position > (readStartPos + varSize))
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Var update read too far. " + (stream.Position - (readStartPos + varSize)) + " bytes." + (logInstance != null ? ("NetworkId: " + logInstance.NetworkId + " BehaviourIndex: " + logInstance.NetworkedObject.GetOrderIndex(logInstance) + " VariableIndex: " + i) : string.Empty));
stream.Position = readStartPos + varSize;
}
else if (stream.Position < (readStartPos + varSize))
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Var update read too little. " + ((readStartPos + varSize) - stream.Position) + " bytes." + (logInstance != null ? ("NetworkId: " + logInstance.NetworkId + " BehaviourIndex: " + logInstance.NetworkedObject.GetOrderIndex(logInstance) + " VariableIndex: " + i) : string.Empty));
stream.Position = readStartPos + varSize;
}
}
}
}
}
internal static void WriteNetworkedVarData(List<INetworkedVar> networkedVarList, Stream stream, ulong clientId)
{
if (networkedVarList.Count == 0)
return;
using (PooledBitWriter writer = PooledBitWriter.Get(stream))
{
for (int j = 0; j < networkedVarList.Count; j++)
{
bool canClientRead = networkedVarList[j].CanClientRead(clientId);
if (NetworkingManager.Singleton.NetworkConfig.EnsureNetworkedVarLengthSafety)
{
if (!canClientRead)
{
writer.WriteUInt16Packed(0);
}
}
else
{
writer.WriteBool(canClientRead);
}
if (canClientRead)
{
if (NetworkingManager.Singleton.NetworkConfig.EnsureNetworkedVarLengthSafety)
{
using (PooledBitStream varStream = PooledBitStream.Get())
{
networkedVarList[j].WriteField(varStream);
varStream.PadStream();
writer.WriteUInt16Packed((ushort)varStream.Length);
varStream.CopyTo(stream);
}
}
else
{
networkedVarList[j].WriteField(stream);
}
}
}
}
}
internal static void SetNetworkedVarData(List<INetworkedVar> networkedVarList, Stream stream)
{
if (networkedVarList.Count == 0)
return;
using (PooledBitReader reader = PooledBitReader.Get(stream))
{
for (int j = 0; j < networkedVarList.Count; j++)
{
ushort varSize = 0;
if (NetworkingManager.Singleton.NetworkConfig.EnsureNetworkedVarLengthSafety)
{
varSize = reader.ReadUInt16Packed();
if (varSize == 0)
continue;
}
else
{
if (!reader.ReadBool())
continue;
}
long readStartPos = stream.Position;
networkedVarList[j].ReadField(stream);
if (NetworkingManager.Singleton.NetworkConfig.EnsureNetworkedVarLengthSafety)
{
if (stream is BitStream bitStream)
{
bitStream.SkipPadBits();
}
if (stream.Position > (readStartPos + varSize))
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Var data read too far. " + (stream.Position - (readStartPos + varSize)) + " bytes.");
stream.Position = readStartPos + varSize;
}
else if (stream.Position < (readStartPos + varSize))
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) NetworkLog.LogWarning("Var data read too little. " + ((readStartPos + varSize) - stream.Position) + " bytes.");
stream.Position = readStartPos + varSize;
}
}
}
}
}
#endregion
/// <summary>
/// Gets the local instance of a object with a given NetworkId
/// </summary>
/// <param name="networkId"></param>
/// <returns></returns>
protected NetworkedObject GetNetworkedObject(ulong networkId)
{
if(SpawnManager.SpawnedObjects.ContainsKey(networkId))
return SpawnManager.SpawnedObjects[networkId];
return null;
}
}
}