-
Notifications
You must be signed in to change notification settings - Fork 459
Expand file tree
/
Copy pathNetworkSpawnManager.cs
More file actions
2288 lines (2058 loc) · 116 KB
/
NetworkSpawnManager.cs
File metadata and controls
2288 lines (2058 loc) · 116 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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Unity.Netcode
{
/// <summary>
/// Class that handles object spawning
/// </summary>
public class NetworkSpawnManager
{
// Stores the objects that need to be shown at end-of-frame
internal Dictionary<ulong, List<NetworkObject>> ObjectsToShowToClient = new Dictionary<ulong, List<NetworkObject>>();
internal Dictionary<NetworkObject, List<ulong>> ClientsToShowObject = new Dictionary<NetworkObject, List<ulong>>();
/// <summary>
/// Dictionary of currently spawned network objects.
/// A table of:
/// [<see cref="NetworkObject.NetworkObjectId"/>][<see cref="NetworkObject"/>]
/// </summary>
public readonly Dictionary<ulong, NetworkObject> SpawnedObjects = new Dictionary<ulong, NetworkObject>();
/// <summary>
/// A list of the spawned objects
/// </summary>
public readonly HashSet<NetworkObject> SpawnedObjectsList = new HashSet<NetworkObject>();
/// <summary>
/// Use to get all NetworkObjects owned by a client
/// Ownership to Objects Table Format:
/// [ClientId][NetworkObjectId][NetworkObject]
/// Server: Keeps track of all clients' ownership
/// Client: Keeps track of only its ownership
/// </summary>
public readonly Dictionary<ulong, Dictionary<ulong, NetworkObject>> OwnershipToObjectsTable = new Dictionary<ulong, Dictionary<ulong, NetworkObject>>();
/// <summary>
/// Object to Ownership Table:
/// [NetworkObjectId][ClientId]
/// Used internally to find the client Id that currently owns
/// the NetworkObject
/// </summary>
private Dictionary<ulong, ulong> m_ObjectToOwnershipTable = new Dictionary<ulong, ulong>();
/// <summary>
/// In distributed authority mode, a list of known spawned player NetworkObject instance is maintained by each client.
/// </summary>
public IReadOnlyList<NetworkObject> PlayerObjects => m_PlayerObjects;
// Since NetworkSpawnManager is destroyed when NetworkManager shuts down, it will always be an empty list for each new network session.
// DANGO-TODO: We need to add something like a ConnectionStateMessage that is sent by either the DAHost or CMBService to each client when a client
// is connected and synchronized or when a cient disconnects (but the player objects list we should keep as it is useful to have).
private List<NetworkObject> m_PlayerObjects = new List<NetworkObject>();
private Dictionary<ulong, List<NetworkObject>> m_PlayerObjectsTable = new Dictionary<ulong, List<NetworkObject>>();
/// <summary>
/// Returns the connect client identifiers
/// </summary>
/// <returns>connected client identifier list</returns>
public List<ulong> GetConnectedPlayers()
{
return m_PlayerObjectsTable.Keys.ToList();
}
/// <summary>
/// Adds a player object and updates all other players' observers list
/// </summary>
private void AddPlayerObject(NetworkObject playerObject)
{
if (!playerObject.IsPlayerObject)
{
if (NetworkManager.LogLevel == LogLevel.Normal)
{
NetworkLog.LogError($"Attempting to register a {nameof(NetworkObject)} as a player object but {nameof(NetworkObject.IsPlayerObject)} is not set!");
return;
}
}
foreach (var player in m_PlayerObjects)
{
// If the player's SpawnWithObservers is not set then do not add the new player object's owner as an observer.
if (player.SpawnWithObservers)
{
player.Observers.Add(playerObject.OwnerClientId);
}
// If the new player object's SpawnWithObservers is not set then do not add this player as an observer to the new player object.
if (playerObject.SpawnWithObservers)
{
playerObject.Observers.Add(player.OwnerClientId);
}
}
// Only if spawn with observers is set or we are using a distributed authority network topology and this is the client's player should we add
// the owner as an observer.
if (playerObject.SpawnWithObservers || (NetworkManager.DistributedAuthorityMode && NetworkManager.LocalClientId == playerObject.OwnerClientId))
{
playerObject.Observers.Add(playerObject.OwnerClientId);
}
m_PlayerObjects.Add(playerObject);
if (!m_PlayerObjectsTable.ContainsKey(playerObject.OwnerClientId))
{
m_PlayerObjectsTable.Add(playerObject.OwnerClientId, new List<NetworkObject>());
}
m_PlayerObjectsTable[playerObject.OwnerClientId].Add(playerObject);
}
internal void UpdateNetworkClientPlayer(NetworkObject playerObject)
{
// If the player's client does not already have a NetworkClient entry
if (!NetworkManager.ConnectionManager.ConnectedClients.ContainsKey(playerObject.OwnerClientId))
{
// Add the player's client
NetworkManager.ConnectionManager.AddClient(playerObject.OwnerClientId);
}
var playerNetworkClient = NetworkManager.ConnectionManager.ConnectedClients[playerObject.OwnerClientId];
// If a client changes their player object, then we should adjust for the client's new player
if (playerNetworkClient.PlayerObject != null && m_PlayerObjects.Contains(playerNetworkClient.PlayerObject))
{
// Just remove the previous player object but keep the assigned observers of the NetworkObject
RemovePlayerObject(playerNetworkClient.PlayerObject);
}
// Now update the associated NetworkClient's player object
NetworkManager.ConnectionManager.ConnectedClients[playerObject.OwnerClientId].AssignPlayerObject(ref playerObject);
AddPlayerObject(playerObject);
}
/// <summary>
/// Removes a player object and updates all other players' observers list
/// </summary>
private void RemovePlayerObject(NetworkObject playerObject, bool destroyingObject = false)
{
if (!playerObject.IsPlayerObject)
{
if (NetworkManager.LogLevel == LogLevel.Normal)
{
NetworkLog.LogError($"Attempting to deregister a {nameof(NetworkObject)} as a player object but {nameof(NetworkObject.IsPlayerObject)} is not set!");
return;
}
}
playerObject.IsPlayerObject = false;
m_PlayerObjects.Remove(playerObject);
if (m_PlayerObjectsTable.ContainsKey(playerObject.OwnerClientId))
{
m_PlayerObjectsTable[playerObject.OwnerClientId].Remove(playerObject);
if (m_PlayerObjectsTable[playerObject.OwnerClientId].Count == 0)
{
m_PlayerObjectsTable.Remove(playerObject.OwnerClientId);
}
}
if (NetworkManager.ConnectionManager.ConnectedClients.ContainsKey(playerObject.OwnerClientId) && destroyingObject)
{
NetworkManager.ConnectionManager.ConnectedClients[playerObject.OwnerClientId].PlayerObject = null;
}
}
internal void MarkObjectForShowingTo(NetworkObject networkObject, ulong clientId)
{
if (!ObjectsToShowToClient.ContainsKey(clientId))
{
ObjectsToShowToClient.Add(clientId, new List<NetworkObject>());
}
ObjectsToShowToClient[clientId].Add(networkObject);
if (NetworkManager.DistributedAuthorityMode)
{
if (!ClientsToShowObject.ContainsKey(networkObject))
{
ClientsToShowObject.Add(networkObject, new List<ulong>());
}
ClientsToShowObject[networkObject].Add(clientId);
}
}
// returns whether any matching objects would have become visible and were returned to hidden state
internal bool RemoveObjectFromShowingTo(NetworkObject networkObject, ulong clientId)
{
if (NetworkManager.DistributedAuthorityMode)
{
if (ClientsToShowObject.ContainsKey(networkObject))
{
ClientsToShowObject[networkObject].Remove(clientId);
if (ClientsToShowObject[networkObject].Count == 0)
{
ClientsToShowObject.Remove(networkObject);
}
}
}
var ret = false;
if (!ObjectsToShowToClient.ContainsKey(clientId))
{
return false;
}
// probably overkill, but deals with multiple entries
while (ObjectsToShowToClient[clientId].Contains(networkObject))
{
Debug.LogWarning(
"Object was shown and hidden from the same client in the same Network frame. As a result, the client will _not_ receive a NetworkSpawn");
ObjectsToShowToClient[clientId].Remove(networkObject);
ret = true;
}
if (ret)
{
networkObject.Observers.Remove(clientId);
}
return ret;
}
/// <summary>
/// Used to update a NetworkObject's ownership
/// </summary>
internal void UpdateOwnershipTable(NetworkObject networkObject, ulong newOwner, bool isRemoving = false)
{
var previousOwner = newOwner;
// Use internal lookup table to see if the NetworkObject has a previous owner
if (m_ObjectToOwnershipTable.ContainsKey(networkObject.NetworkObjectId))
{
// Keep track of the previous owner's ClientId
previousOwner = m_ObjectToOwnershipTable[networkObject.NetworkObjectId];
// We are either despawning (remove) or changing ownership (assign)
if (isRemoving)
{
m_ObjectToOwnershipTable.Remove(networkObject.NetworkObjectId);
}
else
{
// If we already had this owner in our table then just exit
if (NetworkManager.DistributedAuthorityMode && previousOwner == newOwner)
{
return;
}
m_ObjectToOwnershipTable[networkObject.NetworkObjectId] = newOwner;
}
}
else
{
// Otherwise, just add a new lookup entry
m_ObjectToOwnershipTable.Add(networkObject.NetworkObjectId, newOwner);
}
// Check to see if we had a previous owner
if (previousOwner != newOwner && OwnershipToObjectsTable.ContainsKey(previousOwner))
{
// Before updating the previous owner, assure this entry exists
if (OwnershipToObjectsTable[previousOwner].ContainsKey(networkObject.NetworkObjectId))
{
// Remove the previous owner's entry
OwnershipToObjectsTable[previousOwner].Remove(networkObject.NetworkObjectId);
// If we are removing the entry (i.e. despawning or client lost ownership)
if (isRemoving)
{
return;
}
}
else
{
// Really, as long as UpdateOwnershipTable is invoked when ownership is gained or lost this should never happen
throw new Exception($"Client-ID {previousOwner} had a partial {nameof(m_ObjectToOwnershipTable)} entry! Potentially corrupted {nameof(OwnershipToObjectsTable)}?");
}
}
// If the owner doesn't have an entry then create one
if (!OwnershipToObjectsTable.ContainsKey(newOwner))
{
OwnershipToObjectsTable.Add(newOwner, new Dictionary<ulong, NetworkObject>());
}
// Sanity check to make sure we don't already have this entry (we shouldn't)
if (!OwnershipToObjectsTable[newOwner].ContainsKey(networkObject.NetworkObjectId))
{
// Add the new ownership entry
OwnershipToObjectsTable[newOwner].Add(networkObject.NetworkObjectId, networkObject);
}
else if (isRemoving)
{
OwnershipToObjectsTable[previousOwner].Remove(networkObject.NetworkObjectId);
}
else if (NetworkManager.LogLevel == LogLevel.Developer && previousOwner == newOwner)
{
NetworkLog.LogWarning($"Setting ownership twice? Client-ID {previousOwner} already owns NetworkObject ID {networkObject.NetworkObjectId}!");
}
}
/// <summary>
/// Returns an array of all NetworkObjects that belong to a client.
/// </summary>
/// <param name="clientId">the client's id <see cref="NetworkManager.LocalClientId"/></param>
/// <returns>returns an array of the <see cref="NetworkObject"/>s owned by the client</returns>
public NetworkObject[] GetClientOwnedObjects(ulong clientId)
{
if (!OwnershipToObjectsTable.ContainsKey(clientId))
{
OwnershipToObjectsTable.Add(clientId, new Dictionary<ulong, NetworkObject>());
}
return OwnershipToObjectsTable[clientId].Values.ToArray();
}
/// <summary>
/// Gets the NetworkManager associated with this SpawnManager.
/// </summary>
public NetworkManager NetworkManager { get; }
internal readonly Queue<ReleasedNetworkId> ReleasedNetworkObjectIds = new Queue<ReleasedNetworkId>();
private ulong m_NetworkObjectIdCounter;
// A list of target ClientId, use when sending despawn commands. Kept as a member to reduce memory allocations
private List<ulong> m_TargetClientIds = new List<ulong>();
internal ulong GetNetworkObjectId()
{
if (ReleasedNetworkObjectIds.Count > 0 && NetworkManager.NetworkConfig.RecycleNetworkIds && (NetworkManager.RealTimeProvider.UnscaledTime - ReleasedNetworkObjectIds.Peek().ReleaseTime) >= NetworkManager.NetworkConfig.NetworkIdRecycleDelay)
{
return ReleasedNetworkObjectIds.Dequeue().NetworkId;
}
m_NetworkObjectIdCounter++;
// DANGO-TODO: Need a more robust solution here.
return m_NetworkObjectIdCounter + (NetworkManager.LocalClientId * 10000);
}
/// <summary>
/// Returns the local player object or null if one does not exist
/// </summary>
/// <returns>The local player object or null if one does not exist</returns>
public NetworkObject GetLocalPlayerObject()
{
return GetPlayerNetworkObject(NetworkManager.LocalClientId);
}
/// <summary>
/// Returns all <see cref="NetworkObject"/> instances assigned to the client identifier
/// </summary>
/// <param name="clientId">the client identifier of the player</param>
/// <returns>A list of <see cref="NetworkObject"/> instances (if more than one are assigned)</returns>
public List<NetworkObject> GetPlayerNetworkObjects(ulong clientId)
{
if (m_PlayerObjectsTable.ContainsKey(clientId))
{
return m_PlayerObjectsTable[clientId];
}
return null;
}
/// <summary>
/// Returns the player object with a given clientId or null if one does not exist. This is only valid server side.
/// </summary>
/// <param name="clientId">the client identifier of the player</param>
/// <returns>The player object with a given clientId or null if one does not exist</returns>
public NetworkObject GetPlayerNetworkObject(ulong clientId)
{
if (!NetworkManager.DistributedAuthorityMode)
{
if (!NetworkManager.IsServer && NetworkManager.LocalClientId != clientId)
{
throw new NotServerException("Only the server can find player objects from other clients.");
}
if (TryGetNetworkClient(clientId, out NetworkClient networkClient))
{
return networkClient.PlayerObject;
}
}
else
{
if (m_PlayerObjectsTable.ContainsKey(clientId))
{
return m_PlayerObjectsTable[clientId].First();
}
}
return null;
}
/// <summary>
/// Helper function to get a network client for a clientId from the NetworkManager.
/// On the server this will check the <see cref="NetworkManager.ConnectedClients"/> list.
/// On a non-server this will check the <see cref="NetworkManager.LocalClient"/> only.
/// </summary>
/// <param name="clientId">The clientId for which to try getting the NetworkClient for.</param>
/// <param name="networkClient">The found NetworkClient. Null if no client was found.</param>
/// <returns>True if a NetworkClient with a matching id was found else false.</returns>
private bool TryGetNetworkClient(ulong clientId, out NetworkClient networkClient)
{
if (NetworkManager.IsServer)
{
return NetworkManager.ConnectedClients.TryGetValue(clientId, out networkClient);
}
if (NetworkManager.LocalClient != null && clientId == NetworkManager.LocalClient.ClientId)
{
networkClient = NetworkManager.LocalClient;
return true;
}
networkClient = null;
return false;
}
/// <summary>
/// Not used.
/// </summary>
/// <param name="perviousOwner">not used</param>
/// <param name="newOwner">not used</param>
protected virtual void InternalOnOwnershipChanged(ulong perviousOwner, ulong newOwner)
{
}
internal void RemoveOwnership(NetworkObject networkObject)
{
if (NetworkManager.DistributedAuthorityMode && !NetworkManager.ShutdownInProgress)
{
Debug.LogError($"Removing ownership is invalid in Distributed Authority Mode. Use {nameof(ChangeOwnership)} instead.");
return;
}
ChangeOwnership(networkObject, NetworkManager.ServerClientId, true);
}
private Dictionary<ulong, float> m_LastChangeInOwnership = new Dictionary<ulong, float>();
private const int k_MaximumTickOwnershipChangeMultiplier = 6;
internal void ChangeOwnership(NetworkObject networkObject, ulong clientId, bool isAuthorized, bool isRequestApproval = false)
{
if (clientId == networkObject.OwnerClientId)
{
if (NetworkManager.LogLevel <= LogLevel.Developer)
{
Debug.LogWarning($"[{nameof(NetworkSpawnManager)}][{nameof(ChangeOwnership)}] Attempting to change ownership to Client-{clientId} when the owner is already {networkObject.OwnerClientId}! (Ignoring)");
}
return;
}
// For client-server:
// If ownership changes faster than the latency between the client-server and there are NetworkVariables being updated during ownership changes,
// then notify the user they could potentially lose state updates if developer logging is enabled.
if (NetworkManager.LogLevel == LogLevel.Developer && !NetworkManager.DistributedAuthorityMode && m_LastChangeInOwnership.ContainsKey(networkObject.NetworkObjectId) && m_LastChangeInOwnership[networkObject.NetworkObjectId] > Time.realtimeSinceStartup)
{
for (int i = 0; i < networkObject.ChildNetworkBehaviours.Count; i++)
{
if (networkObject.ChildNetworkBehaviours[i].NetworkVariableFields.Count > 0)
{
NetworkLog.LogWarningServer($"[Rapid Ownership Change Detected][Potential Loss in State] Detected a rapid change in ownership that exceeds a frequency less than {k_MaximumTickOwnershipChangeMultiplier}x the current network tick rate! Provide at least {k_MaximumTickOwnershipChangeMultiplier}x the current network tick rate between ownership changes to avoid NetworkVariable state loss.");
break;
}
}
}
if (NetworkManager.DistributedAuthorityMode)
{
// Ensure only the session owner can change ownership (i.e. acquire) and that the session owner is not trying to assign a non-session owner client
// ownership of a NetworkObject with SessionOwner permissions.
if (networkObject.IsOwnershipSessionOwner && (!NetworkManager.LocalClient.IsSessionOwner || clientId != NetworkManager.CurrentSessionOwner))
{
if (NetworkManager.LogLevel <= LogLevel.Developer)
{
NetworkLog.LogErrorServer($"[{networkObject.name}][Session Owner Only] You cannot change ownership of a {nameof(NetworkObject)} that has the {NetworkObject.OwnershipStatus.SessionOwner} flag set!");
}
networkObject.OnOwnershipPermissionsFailure?.Invoke(NetworkObject.OwnershipPermissionsFailureStatus.SessionOwnerOnly);
return;
}
// If are not authorized and this is not an approved ownership change, then check to see if we can change ownership
if (!isAuthorized && !isRequestApproval)
{
if (networkObject.IsOwnershipLocked)
{
if (NetworkManager.LogLevel <= LogLevel.Developer)
{
NetworkLog.LogErrorServer($"[{networkObject.name}][Locked] You cannot change ownership while a {nameof(NetworkObject)} is locked!");
}
networkObject.OnOwnershipPermissionsFailure?.Invoke(NetworkObject.OwnershipPermissionsFailureStatus.Locked);
return;
}
if (networkObject.IsRequestInProgress)
{
if (NetworkManager.LogLevel <= LogLevel.Developer)
{
NetworkLog.LogErrorServer($"[{networkObject.name}][Request Pending] You cannot change ownership while a {nameof(NetworkObject)} has a pending ownership request!");
}
networkObject.OnOwnershipPermissionsFailure?.Invoke(NetworkObject.OwnershipPermissionsFailureStatus.RequestInProgress);
return;
}
if (networkObject.IsOwnershipRequestRequired)
{
if (NetworkManager.LogLevel <= LogLevel.Developer)
{
NetworkLog.LogErrorServer($"[{networkObject.name}][Request Required] You cannot change ownership directly if a {nameof(NetworkObject)} has the {NetworkObject.OwnershipStatus.RequestRequired} flag set!");
}
networkObject.OnOwnershipPermissionsFailure?.Invoke(NetworkObject.OwnershipPermissionsFailureStatus.RequestRequired);
return;
}
if (!networkObject.IsOwnershipTransferable)
{
if (NetworkManager.LogLevel <= LogLevel.Developer)
{
NetworkLog.LogErrorServer($"[{networkObject.name}][Not transferrable] You cannot change ownership of a {nameof(NetworkObject)} that does not have the {NetworkObject.OwnershipStatus.Transferable} flag set!");
}
networkObject.OnOwnershipPermissionsFailure?.Invoke(NetworkObject.OwnershipPermissionsFailureStatus.NotTransferrable);
return;
}
}
}
else if (!isAuthorized)
{
throw new NotServerException("Only the server can change ownership");
}
if (!networkObject.IsSpawned)
{
throw new SpawnStateException("Object is not spawned");
}
if (networkObject.OwnerClientId == clientId && networkObject.PreviousOwnerId == clientId)
{
if (NetworkManager.LogLevel == LogLevel.Developer)
{
NetworkLog.LogWarningServer($"[Already Owner] Unnecessary ownership change for {networkObject.name} as it is already the owned by client-{clientId}");
}
return;
}
if (!networkObject.Observers.Contains(clientId))
{
if (NetworkManager.LogLevel == LogLevel.Developer)
{
NetworkLog.LogWarningServer($"[Invalid Owner] Cannot send Ownership change as client-{clientId} cannot see {networkObject.name}! Use {nameof(NetworkObject.NetworkShow)} first.");
}
return;
}
// Save the previous owner to work around a bit of a nasty issue with assuring NetworkVariables are serialized when ownership changes
var originalPreviousOwnerId = networkObject.PreviousOwnerId;
var originalOwner = networkObject.OwnerClientId;
// Used to distinguish whether a new owner should receive any currently dirty NetworkVariable updates
networkObject.PreviousOwnerId = networkObject.OwnerClientId;
// Assign the new owner
networkObject.OwnerClientId = clientId;
// Always notify locally on the server when ownership is lost
networkObject.InvokeBehaviourOnLostOwnership();
// Authority adds entries for all client ownership
UpdateOwnershipTable(networkObject, networkObject.OwnerClientId);
// Always notify locally on the server when a new owner is assigned
networkObject.InvokeBehaviourOnGainedOwnership();
// If we are the original owner, then we want to synchronize owner read & write NetworkVariables.
if (originalOwner == NetworkManager.LocalClientId)
{
networkObject.SynchronizeOwnerNetworkVariables(originalOwner, originalPreviousOwnerId);
}
var size = 0;
if (NetworkManager.DistributedAuthorityMode)
{
var message = new ChangeOwnershipMessage
{
NetworkObjectId = networkObject.NetworkObjectId,
OwnerClientId = networkObject.OwnerClientId,
DistributedAuthorityMode = NetworkManager.DistributedAuthorityMode,
RequestApproved = isRequestApproval,
OwnershipIsChanging = true,
RequestClientId = networkObject.PreviousOwnerId,
OwnershipFlags = (ushort)networkObject.Ownership,
};
// If we are connected to the CMB service or not the DAHost (i.e. pure DA-Clients only)
if (NetworkManager.CMBServiceConnection || !NetworkManager.DAHost)
{
// Always update the network properties in distributed authority mode for the client gaining ownership
for (int i = 0; i < networkObject.ChildNetworkBehaviours.Count; i++)
{
networkObject.ChildNetworkBehaviours[i].UpdateNetworkProperties();
}
// Populate valid target client identifiers that should receive this change in ownership message.
message.ClientIds = NetworkManager.ConnectedClientsIds.Where((c) => !IsObjectVisibilityPending(c, ref networkObject) && networkObject.IsNetworkVisibleTo(c)).ToArray();
message.ClientIdCount = message.ClientIds.Length;
size = NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, NetworkManager.ServerClientId);
NetworkManager.NetworkMetrics.TrackOwnershipChangeSent(NetworkManager.LocalClientId, networkObject, size);
}
else // We are the DAHost so broadcast the ownership change
{
foreach (var client in NetworkManager.ConnectedClients)
{
if (client.Value.ClientId == NetworkManager.ServerClientId || IsObjectVisibilityPending(client.Key, ref networkObject))
{
continue;
}
if (networkObject.IsNetworkVisibleTo(client.Value.ClientId))
{
size = NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, client.Value.ClientId);
NetworkManager.NetworkMetrics.TrackOwnershipChangeSent(client.Key, networkObject, size);
}
}
}
}
else // Normal Client-Server mode
{
var message = new ChangeOwnershipMessage
{
NetworkObjectId = networkObject.NetworkObjectId,
OwnerClientId = networkObject.OwnerClientId,
};
foreach (var client in NetworkManager.ConnectedClients)
{
if (client.Value.ClientId == NetworkManager.ServerClientId || IsObjectVisibilityPending(client.Key, ref networkObject))
{
continue;
}
if (networkObject.IsNetworkVisibleTo(client.Value.ClientId))
{
if (client.Key != client.Value.ClientId)
{
NetworkLog.LogError($"[Client-{client.Key}] Client key ({client.Key}) does not match the {nameof(NetworkClient)} client Id {client.Value.ClientId}! Client-{client.Key} will not receive ownership changed message!");
continue;
}
size = NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, client.Value.ClientId);
NetworkManager.NetworkMetrics.TrackOwnershipChangeSent(client.Key, networkObject, size);
}
}
}
// After we have sent the change ownership message to all client observers, invoke the ownership changed notification.
// !!Important!!
// This gets called specifically *after* sending the ownership message so any additional messages that need to proceed an ownership
// change can be sent from NetworkBehaviours that override the <see cref="NetworkBehaviour.OnOwnershipChanged"></see>
networkObject.InvokeOwnershipChanged(networkObject.PreviousOwnerId, clientId);
// Keep track of the ownership change frequency to assure a user is not exceeding changes faster than 2x the current Tick Rate.
if (!NetworkManager.DistributedAuthorityMode)
{
if (!m_LastChangeInOwnership.ContainsKey(networkObject.NetworkObjectId))
{
m_LastChangeInOwnership.Add(networkObject.NetworkObjectId, 0.0f);
}
var tickFrequency = 1.0f / NetworkManager.NetworkConfig.TickRate;
m_LastChangeInOwnership[networkObject.NetworkObjectId] = Time.realtimeSinceStartup + (tickFrequency * k_MaximumTickOwnershipChangeMultiplier);
}
}
/// <summary>
/// Will determine if a client has been granted visibility for a NetworkObject but
/// the <see cref="CreateObjectMessage"/> has yet to be generated for it. Under this case,
/// the client might not need to be sent a message (i.e. <see cref="ChangeOwnershipMessage")
/// </summary>
/// <param name="clientId">the client to check</param>
/// <param name="networkObject">the <see cref="NetworkObject"/> to check if it is pending show</param>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
internal bool IsObjectVisibilityPending(ulong clientId, ref NetworkObject networkObject)
{
if (NetworkManager.DistributedAuthorityMode && ClientsToShowObject.ContainsKey(networkObject))
{
return ClientsToShowObject[networkObject].Contains(clientId);
}
else if (ObjectsToShowToClient.ContainsKey(clientId))
{
return ObjectsToShowToClient[clientId].Contains(networkObject);
}
return false;
}
internal bool HasPrefab(NetworkObject.SceneObject sceneObject)
{
if (!NetworkManager.NetworkConfig.EnableSceneManagement || !sceneObject.IsSceneObject)
{
if (NetworkManager.PrefabHandler.ContainsHandler(sceneObject.Hash))
{
return true;
}
if (NetworkManager.NetworkConfig.Prefabs.NetworkPrefabOverrideLinks.TryGetValue(sceneObject.Hash, out var networkPrefab))
{
switch (networkPrefab.Override)
{
default:
case NetworkPrefabOverride.None:
return networkPrefab.Prefab != null;
case NetworkPrefabOverride.Hash:
case NetworkPrefabOverride.Prefab:
return networkPrefab.OverridingTargetPrefab != null;
}
}
return false;
}
var networkObject = NetworkManager.SceneManager.GetSceneRelativeInSceneNetworkObject(sceneObject.Hash, sceneObject.NetworkSceneHandle);
return networkObject != null;
}
internal enum InstantiateAndSpawnErrorTypes
{
NetworkPrefabNull,
NotAuthority,
InvokedWhenShuttingDown,
NotRegisteredNetworkPrefab,
NetworkManagerNull,
NoActiveSession,
}
internal static readonly Dictionary<InstantiateAndSpawnErrorTypes, string> InstantiateAndSpawnErrors = new Dictionary<InstantiateAndSpawnErrorTypes, string>(
new KeyValuePair<InstantiateAndSpawnErrorTypes, string>[]{
new KeyValuePair<InstantiateAndSpawnErrorTypes, string>(InstantiateAndSpawnErrorTypes.NetworkPrefabNull, $"The {nameof(NetworkObject)} prefab parameter was null!"),
new KeyValuePair<InstantiateAndSpawnErrorTypes, string>(InstantiateAndSpawnErrorTypes.NotAuthority, $"Only the server has authority to {nameof(InstantiateAndSpawn)}!"),
new KeyValuePair<InstantiateAndSpawnErrorTypes, string>(InstantiateAndSpawnErrorTypes.InvokedWhenShuttingDown, $"Invoking {nameof(InstantiateAndSpawn)} while shutting down! Calls to {nameof(InstantiateAndSpawn)} will be ignored."),
new KeyValuePair<InstantiateAndSpawnErrorTypes, string>(InstantiateAndSpawnErrorTypes.NotRegisteredNetworkPrefab, $"The {nameof(NetworkObject)} parameter is not a registered network prefab. Did you forget to register it or are you trying to instantiate and spawn an instance of a network prefab?"),
new KeyValuePair<InstantiateAndSpawnErrorTypes, string>(InstantiateAndSpawnErrorTypes.NetworkManagerNull, $"The {nameof(NetworkManager)} parameter was null!"),
new KeyValuePair<InstantiateAndSpawnErrorTypes, string>(InstantiateAndSpawnErrorTypes.NoActiveSession, "You can only invoke this method when you are connected to an existing/in-progress network session!")
});
/// <summary>
/// Use this method to easily instantiate and spawn an instance of a network prefab.
/// InstantiateAndSpawn will:
/// - Find any override associated with the <see cref="NetworkObject"/> prefab
/// - If there is no override, then the current <see cref="NetworkObject"/> prefab type is used.
/// - Create an instance of the <see cref="NetworkObject"/> prefab (or its override).
/// - Spawn the <see cref="NetworkObject"/> prefab instance
/// </summary>
/// <param name="networkPrefab">The <see cref="NetworkObject"/> of the pefab asset.</param>
/// <param name="ownerClientId">The owner of the <see cref="NetworkObject"/> instance (defaults to server).</param>
/// <param name="destroyWithScene">Whether the <see cref="NetworkObject"/> instance will be destroyed when the scene it is located within is unloaded (default is false).</param>
/// <param name="isPlayerObject">Whether the <see cref="NetworkObject"/> instance is a player object or not (default is false).</param>
/// <param name="forceOverride">Whether you want to force spawning the override when running as a host or server or if you want it to spawn the override for host mode and
/// the source prefab for server. If there is an override, clients always spawn that as opposed to the source prefab (defaults to false). </param>
/// <param name="position">The starting poisiton of the <see cref="NetworkObject"/> instance.</param>
/// <param name="rotation">The starting rotation of the <see cref="NetworkObject"/> instance.</param>
/// <returns>The newly instantiated and spawned <see cref="NetworkObject"/> prefab instance.</returns>
public NetworkObject InstantiateAndSpawn(NetworkObject networkPrefab, ulong ownerClientId = NetworkManager.ServerClientId, bool destroyWithScene = false, bool isPlayerObject = false, bool forceOverride = false, Vector3 position = default, Quaternion rotation = default)
{
if (networkPrefab == null)
{
Debug.LogError(InstantiateAndSpawnErrors[InstantiateAndSpawnErrorTypes.NetworkPrefabNull]);
return null;
}
ownerClientId = NetworkManager.DistributedAuthorityMode ? NetworkManager.LocalClientId : ownerClientId;
// We only need to check for authority when running in client-server mode
if (!NetworkManager.IsServer && !NetworkManager.DistributedAuthorityMode)
{
Debug.LogError(InstantiateAndSpawnErrors[InstantiateAndSpawnErrorTypes.NotAuthority]);
return null;
}
if (NetworkManager.ShutdownInProgress)
{
Debug.LogWarning(InstantiateAndSpawnErrors[InstantiateAndSpawnErrorTypes.InvokedWhenShuttingDown]);
return null;
}
// Verify it is actually a valid prefab
if (!NetworkManager.NetworkConfig.Prefabs.Contains(networkPrefab.gameObject))
{
Debug.LogError(InstantiateAndSpawnErrors[InstantiateAndSpawnErrorTypes.NotRegisteredNetworkPrefab]);
return null;
}
return InstantiateAndSpawnNoParameterChecks(networkPrefab, ownerClientId, destroyWithScene, isPlayerObject, forceOverride, position, rotation);
}
/// <summary>
/// !!! Does not perform any parameter checks prior to attempting to instantiate and spawn the NetworkObject !!!
/// </summary>
internal NetworkObject InstantiateAndSpawnNoParameterChecks(NetworkObject networkPrefab, ulong ownerClientId = NetworkManager.ServerClientId, bool destroyWithScene = false, bool isPlayerObject = false, bool forceOverride = false, Vector3 position = default, Quaternion rotation = default)
{
var networkObject = networkPrefab;
// - Host and clients always instantiate the override if one exists.
// - Server instantiates the original prefab unless:
// -- forceOverride is set to true =or=
// -- The prefab has a registered prefab handler, then we let user code determine what to spawn.
// - Distributed authority mode always spawns the override if one exists.
if (forceOverride || NetworkManager.IsClient || NetworkManager.DistributedAuthorityMode || NetworkManager.PrefabHandler.ContainsHandler(networkPrefab.GlobalObjectIdHash))
{
networkObject = GetNetworkObjectToSpawn(networkPrefab.GlobalObjectIdHash, ownerClientId, position, rotation);
}
else // Under this case, server instantiate the prefab passed in.
{
networkObject = InstantiateNetworkPrefab(networkPrefab.gameObject, networkPrefab.GlobalObjectIdHash, position, rotation);
}
if (networkObject == null)
{
Debug.LogError($"Failed to instantiate and spawn {networkPrefab.name}!");
return null;
}
networkObject.IsPlayerObject = isPlayerObject;
networkObject.transform.position = position;
networkObject.transform.rotation = rotation;
// If spawning as a player, then invoke SpawnAsPlayerObject
if (isPlayerObject)
{
networkObject.SpawnAsPlayerObject(ownerClientId, destroyWithScene);
}
else // Otherwise just spawn with ownership
{
networkObject.SpawnWithOwnership(ownerClientId, destroyWithScene);
}
return networkObject;
}
/// <summary>
/// Gets the right NetworkObject prefab instance to spawn. If a handler is registered or there is an override assigned to the
/// passed in globalObjectIdHash value, then that is what will be instantiated, spawned, and returned.
/// </summary>
internal NetworkObject GetNetworkObjectToSpawn(uint globalObjectIdHash, ulong ownerId, Vector3? position, Quaternion? rotation, bool isScenePlaced = false, byte[] instantiationData = null)
{
NetworkObject networkObject = null;
// If the prefab hash has a registered INetworkPrefabInstanceHandler derived class
if (NetworkManager.PrefabHandler.ContainsHandler(globalObjectIdHash))
{
// Let the handler spawn the NetworkObject
networkObject = NetworkManager.PrefabHandler.HandleNetworkPrefabSpawn(globalObjectIdHash, ownerId, position ?? default, rotation ?? default, instantiationData);
networkObject.NetworkManagerOwner = NetworkManager;
}
else
{
// See if there is a valid registered NetworkPrefabOverrideLink associated with the provided prefabHash
var networkPrefabReference = (GameObject)null;
var inScenePlacedWithNoSceneManagement = !NetworkManager.NetworkConfig.EnableSceneManagement && isScenePlaced;
if (NetworkManager.NetworkConfig.Prefabs.NetworkPrefabOverrideLinks.ContainsKey(globalObjectIdHash))
{
var networkPrefab = NetworkManager.NetworkConfig.Prefabs.NetworkPrefabOverrideLinks[globalObjectIdHash];
switch (networkPrefab.Override)
{
default:
case NetworkPrefabOverride.None:
networkPrefabReference = networkPrefab.Prefab;
break;
case NetworkPrefabOverride.Hash:
case NetworkPrefabOverride.Prefab:
{
// When scene management is disabled and this is an in-scene placed NetworkObject, we want to always use the
// SourcePrefabToOverride and not any possible prefab override as a user might want to spawn overrides dynamically
// but might want to use the same source network prefab as an in-scene placed NetworkObject.
// (When scene management is enabled, clients don't delete their in-scene placed NetworkObjects prior to dynamically
// spawning them so the original prefab placed is preserved and this is not needed)
if (inScenePlacedWithNoSceneManagement)
{
networkPrefabReference = networkPrefab.SourcePrefabToOverride ? networkPrefab.SourcePrefabToOverride : networkPrefab.Prefab;
}
else
{
networkPrefabReference = NetworkManager.NetworkConfig.Prefabs.NetworkPrefabOverrideLinks[globalObjectIdHash].OverridingTargetPrefab;
}
break;
}
}
}
// If not, then there is an issue (user possibly didn't register the prefab properly?)
if (networkPrefabReference == null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error)
{
NetworkLog.LogError($"Failed to create object locally. [{nameof(globalObjectIdHash)}={globalObjectIdHash}]. {nameof(NetworkPrefab)} could not be found. Is the prefab registered with {NetworkManager.name}?");
}
}
else
{
// Create prefab instance while applying any pre-assigned position and rotation values
networkObject = InstantiateNetworkPrefab(networkPrefabReference, globalObjectIdHash, position, rotation);
}
}
return networkObject;
}
/// <summary>
/// Instantiates a network prefab instance, assigns the base prefab <see cref="NetworkObject.GlobalObjectIdHash"/>, positions, and orients
/// the instance.
/// !!! Should only be invoked by <see cref="GetNetworkObjectToSpawn"/> unless used by an integration test !!!
/// </summary>
/// <remarks>
/// <param name="prefabGlobalObjectIdHash"> should be the base prefab <see cref="NetworkObject.GlobalObjectIdHash"/> value and not the
/// overrided value.
/// (Can be used for integration testing)
/// </remarks>
/// <param name="networkPrefab">prefab to instantiate</param>
/// <param name="prefabGlobalObjectIdHash"><see cref="NetworkObject.GlobalObjectIdHash"/> of the base prefab instance</param>
/// <param name="position">conditional position in place of the network prefab's default position</param>
/// <param name="rotation">conditional rotation in place of the network prefab's default rotation</param>
/// <returns>the instance of the <see cref="NetworkObject"/></returns>
internal NetworkObject InstantiateNetworkPrefab(GameObject networkPrefab, uint prefabGlobalObjectIdHash, Vector3? position, Quaternion? rotation)
{
var networkObject = UnityEngine.Object.Instantiate(networkPrefab).GetComponent<NetworkObject>();
networkObject.transform.position = position ?? networkObject.transform.position;
networkObject.transform.rotation = rotation ?? networkObject.transform.rotation;
networkObject.NetworkManagerOwner = NetworkManager;
networkObject.PrefabGlobalObjectIdHash = prefabGlobalObjectIdHash;
return networkObject;
}
/// <summary>
/// Creates a local NetowrkObject to be spawned.
/// </summary>
/// <remarks>
/// For most cases this is client-side only, with the exception of when the server
/// is spawning a player.
/// </remarks>
internal NetworkObject CreateLocalNetworkObject(NetworkObject.SceneObject sceneObject, byte[] instantiationData = null)
{
NetworkObject networkObject = null;
var globalObjectIdHash = sceneObject.Hash;
var position = sceneObject.HasTransform ? sceneObject.Transform.Position : default;
var rotation = sceneObject.HasTransform ? sceneObject.Transform.Rotation : default;
var scale = sceneObject.HasTransform ? sceneObject.Transform.Scale : default;
var parentNetworkId = sceneObject.HasParent ? sceneObject.ParentObjectId : default;
var worldPositionStays = (!sceneObject.HasParent) || sceneObject.WorldPositionStays;
// If scene management is disabled or the NetworkObject was dynamically spawned
if (!NetworkManager.NetworkConfig.EnableSceneManagement || !sceneObject.IsSceneObject)
{
networkObject = GetNetworkObjectToSpawn(sceneObject.Hash, sceneObject.OwnerClientId, position, rotation, sceneObject.IsSceneObject, instantiationData);
}
else // Get the in-scene placed NetworkObject
{
networkObject = NetworkManager.SceneManager.GetSceneRelativeInSceneNetworkObject(globalObjectIdHash, sceneObject.NetworkSceneHandle);
if (networkObject == null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error)
{
NetworkLog.LogError($"{nameof(NetworkPrefab)} hash was not found! In-Scene placed {nameof(NetworkObject)} soft synchronization failure for Hash: {globalObjectIdHash}!");
}
}
// Since this NetworkObject is an in-scene placed NetworkObject, if it is disabled then enable it so
// NetworkBehaviours will have their OnNetworkSpawn method invoked
if (networkObject != null && !networkObject.gameObject.activeInHierarchy)
{
networkObject.gameObject.SetActive(true);
}
}
if (networkObject != null)
{
networkObject.DestroyWithScene = sceneObject.DestroyWithScene;
networkObject.NetworkSceneHandle = sceneObject.NetworkSceneHandle;
networkObject.DontDestroyWithOwner = sceneObject.DontDestroyWithOwner;
networkObject.Ownership = (NetworkObject.OwnershipStatus)sceneObject.OwnershipFlags;
var nonNetworkObjectParent = false;
// SPECIAL CASE FOR IN-SCENE PLACED: (only when the parent has a NetworkObject)
// This is a special case scenario where a late joining client has joined and loaded one or
// more scenes that contain nested in-scene placed NetworkObject children yet the server's
// synchronization information does not indicate the NetworkObject in question has a parent =or=
// the parent has changed.
// For this we will want to remove the parent before spawning and setting the transform values based
// on several possible scenarios.
if (sceneObject.IsSceneObject && networkObject.transform.parent != null)
{
var parentNetworkObject = networkObject.transform.parent.GetComponent<NetworkObject>();
// special case to handle being parented under a GameObject with no NetworkObject
nonNetworkObjectParent = !parentNetworkObject && sceneObject.HasParent;
// If the in-scene placed NetworkObject has a parent NetworkObject...
if (parentNetworkObject)
{
// Then remove the parent only if:
// - The authority says we don't have a parent (but locally we do).
// - The auhtority says we have a parent but either of the two are true:
// -- It isn't the same parent.
// -- It was parented using world position stays.
if (!sceneObject.HasParent || (sceneObject.IsLatestParentSet
&& (sceneObject.LatestParent.Value != parentNetworkObject.NetworkObjectId || sceneObject.WorldPositionStays)))
{
// If parenting without notifications then we are temporarily removing the parent to set the transform
// values before reparenting under the current parent.
networkObject.ApplyNetworkParenting(true, true, enableNotification: !sceneObject.HasParent);
}
}
}
// Set the transform only if the sceneObject includes transform information.
if (sceneObject.HasTransform)
{
// If world position stays is true or we have auto object parent synchronization disabled
// then we want to apply the position and rotation values world space relative
if ((worldPositionStays && !nonNetworkObjectParent) || !networkObject.AutoObjectParentSync)
{
networkObject.transform.position = position;
networkObject.transform.rotation = rotation;