diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c3955b..5740236 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,79 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com). +## [2.0.0-exp.2] - 2024-04-02 + +### Added +- Added updates to all internal messages to account for a distributed authority network session connection. (#2863) +- Added `NetworkRigidbodyBase` that provides users with a more customizable network rigidbody, handles both `Rigidbody` and `Rigidbody2D`, and provides an option to make `NetworkTransform` use the rigid body for motion. (#2863) + - For a customized `NetworkRigidbodyBase` class: + - `NetworkRigidbodyBase.AutoUpdateKinematicState` provides control on whether the kinematic setting will be automatically set or not when ownership changes. + - `NetworkRigidbodyBase.AutoSetKinematicOnDespawn` provides control on whether isKinematic will automatically be set to true when the associated `NetworkObject` is despawned. + - `NetworkRigidbodyBase.Initialize` is a protected method that, when invoked, will initialize the instance. This includes options to: + - Set whether using a `RigidbodyTypes.Rigidbody` or `RigidbodyTypes.Rigidbody2D`. + - Includes additional optional parameters to set the `NetworkTransform`, `Rigidbody`, and `Rigidbody2d` to use. + - Provides additional public methods: + - `NetworkRigidbodyBase.GetPosition` to return the position of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). + - `NetworkRigidbodyBase.GetRotation` to return the rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). + - `NetworkRigidbodyBase.MovePosition` to move to the position of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). + - `NetworkRigidbodyBase.MoveRotation` to move to the rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). + - `NetworkRigidbodyBase.Move` to move to the position and rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). + - `NetworkRigidbodyBase.Move` to move to the position and rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). + - `NetworkRigidbodyBase.SetPosition` to set the position of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). + - `NetworkRigidbodyBase.SetRotation` to set the rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). + - `NetworkRigidbodyBase.ApplyCurrentTransform` to set the position and rotation of the `Rigidbody` or `Rigidbody2d` based on the associated `GameObject` transform (depending upon its initialized setting). + - `NetworkRigidbodyBase.WakeIfSleeping` to wake up the rigid body if sleeping. + - `NetworkRigidbodyBase.SleepRigidbody` to put the rigid body to sleep. + - `NetworkRigidbodyBase.IsKinematic` to determine if the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting) is currently kinematic. + - `NetworkRigidbodyBase.SetIsKinematic` to set the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting) current kinematic state. + - `NetworkRigidbodyBase.ResetInterpolation` to reset the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting) back to its original interpolation value when initialized. + - Now includes a `MonoBehaviour.FixedUpdate` implementation that will update the assigned `NetworkTransform` when `NetworkRigidbodyBase.UseRigidBodyForMotion` is true. (#2863) +- Added `RigidbodyContactEventManager` that provides a more optimized way to process collision enter and collision stay events as opposed to the `Monobehaviour` approach. (#2863) + - Can be used in client-server and distributed authority modes, but is particularly useful in distributed authority. +- Added rigid body motion updates to `NetworkTransform` which allows users to set interolation on rigid bodies. (#2863) + - Extrapolation is only allowed on authoritative instances, but custom class derived from `NetworkRigidbodyBase` or `NetworkRigidbody` or `NetworkRigidbody2D` automatically switches non-authoritative instances to interpolation if set to extrapolation. +- Added distributed authority mode support to `NetworkAnimator`. (#2863) +- Added session mode selection to `NetworkManager` inspector view. (#2863) +- Added distributed authority permissions feature. (#2863) +- Added distributed authority mode specific `NetworkObject` permissions flags (Distributable, Transferable, and RequestRequired). (#2863) +- Added distributed authority mode specific `NetworkObject.SetOwnershipStatus` method that applies one or more `NetworkObject` instance's ownership flags. If updated when spawned, the ownership permission changes are synchronized with the other connected clients. (#2863) +- Added distributed authority mode specific `NetworkObject.RemoveOwnershipStatus` method that removes one or more `NetworkObject` instance's ownership flags. If updated when spawned, the ownership permission changes are synchronized with the other connected clients. (#2863) +- Added distributed authority mode specific `NetworkObject.HasOwnershipStatus` method that will return (true or false) whether one or more ownership flags is set. (#2863) +- Added distributed authority mode specific `NetworkObject.SetOwnershipLock` method that locks ownership of a `NetworkObject` to prevent ownership from changing until the current owner releases the lock. (#2863) +- Added distributed authority mode specific `NetworkObject.RequestOwnership` method that sends an ownership request to the current owner of a spawned `NetworkObject` instance. (#2863) +- Added distributed authority mode specific `NetworkObject.OnOwnershipRequested` callback handler that is invoked on the owner/authoritative side when a non-owner requests ownership. Depending upon the boolean returned value depends upon whether the request is approved or denied. (#2863) +- Added distributed authority mode specific `NetworkObject.OnOwnershipRequestResponse` callback handler that is invoked when a non-owner's request has been processed. This callback includes a `NetworkObjet.OwnershipRequestResponseStatus` response parameter that describes whether the request was approved or the reason why it was not approved. (#2863) +- Added distributed authority mode specific `NetworkObject.DeferDespawn` method that defers the despawning of `NetworkObject` instances on non-authoritative clients based on the tick offset parameter. (#2863) +- Added distributed authority mode specific `NetworkObject.OnDeferredDespawnComplete` callback handler that can be used to further control when deferring the despawning of a `NetworkObject` on non-authoritative instances. (#2863) +- Added `NetworkClient.SessionModeType` as one way to determine the current session mode of the network session a client is connected to. (#2863) +- Added distributed authority mode specific `NetworkClient.IsSessionOwner` property to determine if the current local client is the current session owner of a distributed authority session. (#2863) +- Added distributed authority mode specific client side spawning capabilities. When running in distributed authority mode, clients can instantiate and spawn `NetworkObject` instances (the local client is authomatically the owner of the spawned object). (#2863) + - This is useful to better visually synchronize owner authoritative motion models and newly spawned `NetworkObject` instances (i.e. projectiles for example). +- Added distributed authority mode specific client side player spawning capabilities. Clients will automatically spawn their associated player object locally. (#2863) +- Added distributed authority mode specific `NetworkConfig.AutoSpawnPlayerPrefabClientSide` property (default is true) to provide control over the automatic spawning of player prefabs on the local client side. (#2863) +- Added distributed authority mode specific `NetworkManager.OnFetchLocalPlayerPrefabToSpawn` callback that, when assigned, will allow the local client to provide the player prefab to be spawned for the local client. (#2863) + - This is only invoked if the `NetworkConfig.AutoSpawnPlayerPrefabClientSide` property is set to true. +- Added distributed authority mode specific `NetworkBehaviour.HasAuthority` property that determines if the local client has authority over the associated `NetworkObject` instance (typical use case is within a `NetworkBehaviour` script much like that of `IsServer` or `IsClient`). (#2863) +- Added distributed authority mode specific `NetworkBehaviour.IsSessionOwner` property that determines if the local client is the session owner (typical use case would be to determine if the local client can has scene management authority within a `NetworkBehaviour` script). (#2863) +- Added support for distributed authority mode scene management where the currently assigned session owner can start scene events (i.e. scene loading and scene unloading). (#2863) + +### Fixed + +- Fixed issue where the host was not invoking `OnClientDisconnectCallback` for its own local client when internally shutting down. (#2822) +- Fixed issue where NetworkTransform could potentially attempt to "unregister" a named message prior to it being registered. (#2807) +- Fixed issue where in-scene placed `NetworkObject`s with complex nested children `NetworkObject`s (more than one child in depth) would not synchronize properly if WorldPositionStays was set to true. (#2796) + +### Changed +- Changed client side awareness of other clients is now the same as a server or host. (#2863) +- Changed `NetworkManager.ConnectedClients` can now be accessed by both server and clients. (#2863) +- Changed `NetworkManager.ConnectedClientsList` can now be accessed by both server and clients. (#2863) +- Changed `NetworkTransform` defaults to owner authoritative when connected to a distributed authority session. (#2863) +- Changed `NetworkVariable` defaults to owner write and everyone read permissions when connected to a distributed authority session (even if declared with server read or write permissions). (#2863) +- Changed `NetworkObject` no longer implements the `MonoBehaviour.Update` method in order to determine whether a `NetworkObject` instance has been migrated to a different scene. Instead, only `NetworkObjects` with the `SceneMigrationSynchronization` property set will be updated internally during the `NetworkUpdateStage.PostLateUpdate` by `NetworkManager`. (#2863) +- Changed `NetworkManager` inspector view layout where properties are now organized by category. (#2863) +- Changed `NetworkTransform` to now use `NetworkTransformMessage` as opposed to named messages for NetworkTransformState updates. (#2810) +- Changed `CustomMessageManager` so it no longer attempts to register or "unregister" a null or empty string and will log an error if this condition occurs. (#2807) + ## [1.8.1] - 2024-02-05 ### Fixed diff --git a/Components/Messages.meta b/Components/Messages.meta new file mode 100644 index 0000000..fcf8b73 --- /dev/null +++ b/Components/Messages.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a9db1d18fa0117f4da5e8e65386b894a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Components/Messages/NetworkTransformMessage.cs b/Components/Messages/NetworkTransformMessage.cs new file mode 100644 index 0000000..28a423e --- /dev/null +++ b/Components/Messages/NetworkTransformMessage.cs @@ -0,0 +1,205 @@ +using Unity.Netcode.Components; +using UnityEngine; + +namespace Unity.Netcode +{ + /// + /// NetworkTransform State Update Message + /// + internal struct NetworkTransformMessage : INetworkMessage + { + public int Version => 0; + public ulong NetworkObjectId; + public int NetworkBehaviourId; + // This is only used when serializing but not serialized + public bool DistributedAuthorityMode; + // Might get removed + public ulong[] TargetIds; + + private int GetTargetIdLength() + { + if (TargetIds != null) + { + return TargetIds.Length; + } + return 0; + } + + public NetworkTransform.NetworkTransformState State; + + private NetworkTransform m_ReceiverNetworkTransform; + private FastBufferReader m_CurrentReader; + + private unsafe void CopyPayload(ref FastBufferWriter writer) + { + writer.WriteBytesSafe(m_CurrentReader.GetUnsafePtrAtCurrentPosition(), m_CurrentReader.Length - m_CurrentReader.Position); + } + + public void Serialize(FastBufferWriter writer, int targetVersion) + { + if (m_CurrentReader.IsInitialized) + { + CopyPayload(ref writer); + } + else + { + BytePacker.WriteValueBitPacked(writer, NetworkObjectId); + BytePacker.WriteValueBitPacked(writer, NetworkBehaviourId); + writer.WriteNetworkSerializable(State); + if (DistributedAuthorityMode) + { + var length = GetTargetIdLength(); + BytePacker.WriteValuePacked(writer, length); + // If no target ids, then just exit early (DAHost specific) + if (length == 0) + { + return; + } + foreach (var target in TargetIds) + { + BytePacker.WriteValuePacked(writer, target); + } + } + } + } + + public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) + { + var networkManager = context.SystemOwner as NetworkManager; + if (networkManager == null) + { + Debug.LogError($"[{nameof(NetworkTransformMessage)}] System owner context was not of type {nameof(NetworkManager)}!"); + return false; + } + var currentPosition = reader.Position; + ByteUnpacker.ReadValueBitPacked(reader, out NetworkObjectId); + var isSpawnedLocally = networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId); + + // Only defer if the NetworkObject is not spawned yet and the local NetworkManager is not running as a DAHost. + if (!isSpawnedLocally && !networkManager.DAHost) + { + networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context); + return false; + } + + // While the below check and assignment might seem out of place, this is specific to running in DAHost mode when a NetworkObject is + // hidden from the DAHost but is visible to other clients. Since the DAHost needs to forward updates to the clients, we ignore processing + // this message locally + var networkObject = (NetworkObject)null; + var isServerAuthoritative = false; + var ownerAuthoritativeServerSide = false; + + // Get the behaviour index + ByteUnpacker.ReadValueBitPacked(reader, out NetworkBehaviourId); + + // Deserialize the state + reader.ReadNetworkSerializableInPlace(ref State); + + if (networkManager.DistributedAuthorityMode) + { + var targetCount = 0; + ByteUnpacker.ReadValueBitPacked(reader, out targetCount); + if (targetCount > 0) + { + TargetIds = new ulong[targetCount]; + } + var targetId = (ulong)0; + for (int i = 0; i < targetCount; i++) + { + ByteUnpacker.ReadValueBitPacked(reader, out targetId); + TargetIds[i] = targetId; + } + } + + if (isSpawnedLocally) + { + networkObject = networkManager.SpawnManager.SpawnedObjects[NetworkObjectId]; + // Get the target NetworkTransform + m_ReceiverNetworkTransform = networkObject.ChildNetworkBehaviours[NetworkBehaviourId] as NetworkTransform; + isServerAuthoritative = m_ReceiverNetworkTransform.IsServerAuthoritative(); + ownerAuthoritativeServerSide = !isServerAuthoritative && networkManager.IsServer; + } + else + { + // If we are the DAHost and the NetworkObject is hidden from the host we still need to forward this message + ownerAuthoritativeServerSide = networkManager.DAHost && !isSpawnedLocally; + } + + if (ownerAuthoritativeServerSide) + { + var ownerClientId = (ulong)0; + + if (networkObject != null) + { + ownerClientId = networkObject.OwnerClientId; + if (ownerClientId == NetworkManager.ServerClientId) + { + // Ownership must have changed, ignore any additional pending messages that might have + // come from a previous owner client. + return true; + } + } + else if (networkManager.DAHost) + { + // Specific to distributed authority mode, the only sender of state updates will be the owner + ownerClientId = context.SenderId; + } + + var networkDelivery = State.IsReliableStateUpdate() ? NetworkDelivery.ReliableSequenced : NetworkDelivery.UnreliableSequenced; + + // Forward the state update if there are any remote clients to foward it to + if (networkManager.ConnectionManager.ConnectedClientsList.Count > (networkManager.IsHost ? 2 : 1)) + { + var clientCount = networkManager.DistributedAuthorityMode ? GetTargetIdLength() : networkManager.ConnectionManager.ConnectedClientsList.Count; + if (clientCount == 0) + { + return true; + } + + // This is only to copy the existing and already serialized struct for forwarding purposes only. + // This will not include any changes made to this struct at this particular stage of processing the message. + var currentMessage = this; + // Create a new reader that replicates this message + currentMessage.m_CurrentReader = new FastBufferReader(reader, Collections.Allocator.None); + // Rewind the new reader to the beginning of the message's payload + currentMessage.m_CurrentReader.Seek(currentPosition); + // Forward the message to all connected clients that are observers of the associated NetworkObject + + for (int i = 0; i < clientCount; i++) + { + var clientId = networkManager.DistributedAuthorityMode ? TargetIds[i] : networkManager.ConnectionManager.ConnectedClientsList[i].ClientId; + if (NetworkManager.ServerClientId == clientId || (!isServerAuthoritative && clientId == ownerClientId) || + (!networkManager.DistributedAuthorityMode && !networkObject.Observers.Contains(clientId))) + { + continue; + } + + networkManager.MessageManager.SendMessage(ref currentMessage, networkDelivery, clientId); + } + // Dispose of the reader used for forwarding + currentMessage.m_CurrentReader.Dispose(); + } + } + return true; + } + + public void Handle(ref NetworkContext context) + { + var networkManager = context.SystemOwner as NetworkManager; + // Only if the local NetworkManager instance is running as the DAHost we just exit if there is no local + // NetworkTransform component to apply the state update to (i.e. it is hidden from the DAHost and it + // just forwarded the state update to any other connected client) + if (networkManager.DAHost && m_ReceiverNetworkTransform == null) + { + return; + } + + if (m_ReceiverNetworkTransform == null) + { + Debug.LogError($"[{nameof(NetworkTransformMessage)}][Dropped] Reciever {nameof(NetworkTransform)} was not set!"); + return; + } + m_ReceiverNetworkTransform.TransformStateUpdate(ref State, context.SenderId); + } + } +} diff --git a/Components/Messages/NetworkTransformMessage.cs.meta b/Components/Messages/NetworkTransformMessage.cs.meta new file mode 100644 index 0000000..640ec3b --- /dev/null +++ b/Components/Messages/NetworkTransformMessage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dcfc8ac43fef97e42adb19b998d70c37 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Components/NetworkAnimator.cs b/Components/NetworkAnimator.cs index 79030b7..73555e2 100644 --- a/Components/NetworkAnimator.cs +++ b/Components/NetworkAnimator.cs @@ -25,26 +25,48 @@ namespace Unity.Netcode.Components { foreach (var animationUpdate in m_SendAnimationUpdates) { - m_NetworkAnimator.SendAnimStateClientRpc(animationUpdate.AnimationMessage, animationUpdate.ClientRpcParams); + + if (m_NetworkAnimator.NetworkManager.DistributedAuthorityMode) + { + m_NetworkAnimator.SendAnimStateRpc(animationUpdate.AnimationMessage); + } + else + { + m_NetworkAnimator.SendAnimStateClientRpc(animationUpdate.AnimationMessage, animationUpdate.ClientRpcParams); + } } m_SendAnimationUpdates.Clear(); foreach (var sendEntry in m_SendParameterUpdates) { - m_NetworkAnimator.SendParametersUpdateClientRpc(sendEntry.ParametersUpdateMessage, sendEntry.ClientRpcParams); + if (m_NetworkAnimator.NetworkManager.DistributedAuthorityMode) + { + m_NetworkAnimator.SendParametersUpdateRpc(sendEntry.ParametersUpdateMessage); + } + else + { + m_NetworkAnimator.SendParametersUpdateClientRpc(sendEntry.ParametersUpdateMessage, sendEntry.ClientRpcParams); + } } m_SendParameterUpdates.Clear(); foreach (var sendEntry in m_SendTriggerUpdates) { - if (!sendEntry.SendToServer) + if (m_NetworkAnimator.NetworkManager.DistributedAuthorityMode) { - m_NetworkAnimator.SendAnimTriggerClientRpc(sendEntry.AnimationTriggerMessage, sendEntry.ClientRpcParams); + m_NetworkAnimator.SendAnimTriggerRpc(sendEntry.AnimationTriggerMessage); } else { - m_NetworkAnimator.SendAnimTriggerServerRpc(sendEntry.AnimationTriggerMessage); + if (!sendEntry.SendToServer) + { + m_NetworkAnimator.SendAnimTriggerClientRpc(sendEntry.AnimationTriggerMessage, sendEntry.ClientRpcParams); + } + else + { + m_NetworkAnimator.SendAnimTriggerServerRpc(sendEntry.AnimationTriggerMessage); + } } } m_SendTriggerUpdates.Clear(); @@ -652,17 +674,14 @@ namespace Unity.Netcode.Components NetworkLog.LogWarningServer($"[{gameObject.name}][{nameof(NetworkAnimator)}] {nameof(Animator)} is not assigned! Animation synchronization will not work for this instance!"); } - if (IsServer) + m_ClientSendList = new List(128); + m_ClientRpcParams = new ClientRpcParams { - m_ClientSendList = new List(128); - m_ClientRpcParams = new ClientRpcParams + Send = new ClientRpcSendParams { - Send = new ClientRpcSendParams - { - TargetClientIds = m_ClientSendList - } - }; - } + TargetClientIds = m_ClientSendList + } + }; // Create a handler for state changes m_NetworkAnimatorStateChangeHandler = new NetworkAnimatorStateChangeHandler(this); @@ -908,6 +927,11 @@ namespace Unity.Netcode.Components // Send an AnimationMessage only if there are dirty AnimationStates to send if (m_AnimationMessage.IsDirtyCount > 0) { + if (NetworkManager.DistributedAuthorityMode) + { + SendAnimStateRpc(m_AnimationMessage); + } + else if (!IsServer && IsOwner) { SendAnimStateServerRpc(m_AnimationMessage); @@ -932,20 +956,33 @@ namespace Unity.Netcode.Components { Parameters = m_ParameterWriter.ToArray() }; - - if (!IsServer) + if (NetworkManager.DistributedAuthorityMode) { - SendParametersUpdateServerRpc(parametersMessage); - } - else - { - if (sendDirect) + if (IsOwner) { - SendParametersUpdateClientRpc(parametersMessage, clientRpcParams); + SendParametersUpdateRpc(parametersMessage); } else { - m_NetworkAnimatorStateChangeHandler.SendParameterUpdate(parametersMessage, clientRpcParams); + Debug.LogError($"[{name}][Client-{NetworkManager.LocalClientId}] Attempting to send parameter updates but not the owner!"); + } + } + else + { + if (!IsServer) + { + SendParametersUpdateServerRpc(parametersMessage); + } + else + { + if (sendDirect) + { + SendParametersUpdateClientRpc(parametersMessage, clientRpcParams); + } + else + { + m_NetworkAnimatorStateChangeHandler.SendParameterUpdate(parametersMessage, clientRpcParams); + } } } } @@ -1225,10 +1262,19 @@ namespace Unity.Netcode.Components } /// - /// Updates the client's animator's parameters + /// Distributed Authority: Updates the client's animator's parameters + /// + [Rpc(SendTo.NotAuthority)] + internal void SendParametersUpdateRpc(ParametersUpdateMessage parametersUpdate) + { + m_NetworkAnimatorStateChangeHandler.ProcessParameterUpdate(parametersUpdate); + } + + /// + /// Client-Server: Updates the client's animator's parameters /// [ClientRpc] - internal unsafe void SendParametersUpdateClientRpc(ParametersUpdateMessage parametersUpdate, ClientRpcParams clientRpcParams = default) + internal void SendParametersUpdateClientRpc(ParametersUpdateMessage parametersUpdate, ClientRpcParams clientRpcParams = default) { var isServerAuthoritative = IsServerAuthoritative(); if (!isServerAuthoritative && !IsOwner || isServerAuthoritative) @@ -1242,7 +1288,7 @@ namespace Unity.Netcode.Components /// The server sets its local state and then forwards the message to the remaining clients /// [ServerRpc] - private unsafe void SendAnimStateServerRpc(AnimationMessage animationMessage, ServerRpcParams serverRpcParams = default) + private void SendAnimStateServerRpc(AnimationMessage animationMessage, ServerRpcParams serverRpcParams = default) { if (IsServerAuthoritative()) { @@ -1273,26 +1319,44 @@ namespace Unity.Netcode.Components } /// - /// Internally-called RPC client receiving function to update some animation state on a client + /// Client-Server: Internally-called RPC client-side receiving function to update animation states /// [ClientRpc] - internal unsafe void SendAnimStateClientRpc(AnimationMessage animationMessage, ClientRpcParams clientRpcParams = default) + internal void SendAnimStateClientRpc(AnimationMessage animationMessage, ClientRpcParams clientRpcParams = default) { - // This should never happen - if (IsHost) + ProcessAnimStates(animationMessage); + } + + /// + /// Distributed Authority: Internally-called RPC non-authority receiving function to update animation states + /// + [Rpc(SendTo.NotAuthority)] + internal void SendAnimStateRpc(AnimationMessage animationMessage) + { + ProcessAnimStates(animationMessage); + } + + private void ProcessAnimStates(AnimationMessage animationMessage) + { + if (HasAuthority) { if (NetworkManager.LogLevel == LogLevel.Developer) { - NetworkLog.LogWarning("Detected the Host is sending itself animation updates! Please report this issue."); + var hostOrOwner = NetworkManager.DistributedAuthorityMode ? "Owner" : "Host"; + var clientServerOrDAMode = NetworkManager.DistributedAuthorityMode ? "distributed authority" : "client-server"; + NetworkLog.LogWarning($"Detected the {hostOrOwner} is sending itself animation updates in {clientServerOrDAMode} mode! Please report this issue."); } return; } + foreach (var animationState in animationMessage.AnimationStates) { UpdateAnimationState(animationState); } } + + /// /// Server-side trigger state update request /// The server sets its local state and then forwards the message to the remaining clients @@ -1337,7 +1401,18 @@ namespace Unity.Netcode.Components } /// - /// Internally-called RPC client receiving function to update a trigger when the server wants to forward + /// Distributed Authority: Internally-called RPC client receiving function to update a trigger when the server wants to forward + /// a trigger for a client to play / reset + /// + /// the payload containing the trigger data to apply + [Rpc(SendTo.NotAuthority)] + internal void SendAnimTriggerRpc(AnimationTriggerMessage animationTriggerMessage) + { + InternalSetTrigger(animationTriggerMessage.Hash, animationTriggerMessage.IsTriggerSet); + } + + /// + /// Client Server: Internally-called RPC client receiving function to update a trigger when the server wants to forward /// a trigger for a client to play / reset /// /// the payload containing the trigger data to apply @@ -1362,15 +1437,26 @@ namespace Unity.Netcode.Components /// sets (true) or resets (false) the trigger. The default is to set it (true). public void SetTrigger(int hash, bool setTrigger = true) { + if (!IsSpawned) + { + NetworkLog.LogError($"[{gameObject.name}] Cannot set a synchronized trigger when the {nameof(NetworkObject)} is not spawned!"); + return; + } + // MTT-3564: // After fixing the issue with trigger controlled Transitions being synchronized twice, // it exposed additional issues with this logic. Now, either the owner or the server can // update triggers. Since server-side RPCs are immediately invoked, for a host a trigger // will happen when SendAnimTriggerClientRpc is called. For a client owner, we call the // SendAnimTriggerServerRpc and then trigger locally when running in owner authority mode. - if (IsOwner || IsServer) + var animTriggerMessage = new AnimationTriggerMessage() { Hash = hash, IsTriggerSet = setTrigger }; + if (NetworkManager.DistributedAuthorityMode && HasAuthority) + { + m_NetworkAnimatorStateChangeHandler.QueueTriggerUpdateToClient(animTriggerMessage); + InternalSetTrigger(hash, setTrigger); + } + else if (!NetworkManager.DistributedAuthorityMode && (IsOwner || IsServer)) { - var animTriggerMessage = new AnimationTriggerMessage() { Hash = hash, IsTriggerSet = setTrigger }; if (IsServer) { /// as to why we queue diff --git a/Components/NetworkRigidBodyBase.cs b/Components/NetworkRigidBodyBase.cs new file mode 100644 index 0000000..d156314 --- /dev/null +++ b/Components/NetworkRigidBodyBase.cs @@ -0,0 +1,535 @@ +#if COM_UNITY_MODULES_PHYSICS +using System.Runtime.CompilerServices; +using UnityEngine; + +namespace Unity.Netcode.Components +{ + /// + /// NetworkRigidbodyBase is a unified and integration that helps to synchronize physics motion, collision, and interpolation + /// when used with a . + /// + /// + /// For a customizable netcode Rigidbody, create your own component from this class and use + /// during instantiation (i.e. invoked from within the Awake method). You can re-initialize after having initialized but only when the is not spawned. + /// + public abstract class NetworkRigidbodyBase : NetworkBehaviour + { + /// + /// When enabled, the associated will use the Rigidbody/Rigidbody2D to apply and synchronize changes in position, rotation, and + /// allows for the use of Rigidbody interpolation/extrapolation. + /// + /// + /// If is enabled, non-authoritative instances can only use Rigidbody interpolation. If a network prefab is set to + /// extrapolation and is enabled, then non-authoritative instances will automatically be adjusted to use Rigidbody + /// interpolation while the authoritative instance will still use extrapolation. + /// + public bool UseRigidBodyForMotion; + + /// + /// When enabled (default), automatically set the Kinematic state of the Rigidbody based on ownership. + /// When disabled, Kinematic state needs to be set by external script(s). + /// + public bool AutoUpdateKinematicState = true; + + /// + /// Primarily applies to the property when disabled but you still want + /// the Rigidbody to be automatically set to Kinematic when despawned. + /// + public bool AutoSetKinematicOnDespawn = true; + + // Determines if this is a Rigidbody or Rigidbody2D implementation + private bool m_IsRigidbody2D => RigidbodyType == RigidbodyTypes.Rigidbody2D; + // Used to cache the authority state of this Rigidbody during the last frame + private bool m_IsAuthority; + private Rigidbody m_Rigidbody; + private Rigidbody2D m_Rigidbody2D; + private NetworkTransform m_NetworkTransform; + private enum InterpolationTypes + { + None, + Interpolate, + Extrapolate + } + private InterpolationTypes m_OriginalInterpolation; + + /// + /// Used to define the type of Rigidbody implemented. + /// + /// + public enum RigidbodyTypes + { + Rigidbody, + Rigidbody2D, + } + + public RigidbodyTypes RigidbodyType { get; private set; } + + /// + /// Initializes the networked Rigidbody based on the + /// passed in as a parameter. + /// + /// + /// Cannot be initialized while the associated is spawned. + /// + /// type of rigid body being initialized + /// (optional) The to be used + /// (optional) The to be used + protected void Initialize(RigidbodyTypes rigidbodyType, NetworkTransform networkTransform = null, Rigidbody2D rigidbody2D = null, Rigidbody rigidbody = null) + { + // Don't initialize if already spawned + if (IsSpawned) + { + Debug.LogError($"[{name}] Attempting to initialize while spawned is not allowed."); + return; + } + RigidbodyType = rigidbodyType; + m_Rigidbody2D = rigidbody2D; + m_Rigidbody = rigidbody; + m_NetworkTransform = networkTransform; + + if (m_IsRigidbody2D && m_Rigidbody2D == null) + { + m_Rigidbody2D = GetComponent(); + + } + else if (m_Rigidbody == null) + { + m_Rigidbody = GetComponent(); + } + + SetOriginalInterpolation(); + + if (m_NetworkTransform == null) + { + m_NetworkTransform = GetComponent(); + } + + if (m_NetworkTransform != null) + { + m_NetworkTransform.RegisterRigidbody(this); + } + else + { + throw new System.Exception($"[Missing {nameof(NetworkTransform)}] No {nameof(NetworkTransform)} is assigned or can be found during initialization!"); + } + + if (AutoUpdateKinematicState) + { + SetIsKinematic(true); + } + } + + /// + /// Gets the position of the Rigidbody + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Vector3 GetPosition() + { + if (m_IsRigidbody2D) + { + return m_Rigidbody2D.position; + } + else + { + return m_Rigidbody.position; + } + } + + /// + /// Gets the rotation of the Rigidbody + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Quaternion GetRotation() + { + if (m_IsRigidbody2D) + { + var quaternion = Quaternion.identity; + var angles = quaternion.eulerAngles; + angles.z = m_Rigidbody2D.rotation; + quaternion.eulerAngles = angles; + return quaternion; + } + else + { + return m_Rigidbody.rotation; + } + } + + /// + /// Moves the rigid body + /// + /// The position to move towards + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void MovePosition(Vector3 position) + { + if (m_IsRigidbody2D) + { + m_Rigidbody2D.MovePosition(position); + } + else + { + m_Rigidbody.MovePosition(position); + } + } + + /// + /// Directly applies a position (like teleporting) + /// + /// position to apply to the Rigidbody + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetPosition(Vector3 position) + { + if (m_IsRigidbody2D) + { + m_Rigidbody2D.position = position; + } + else + { + m_Rigidbody.position = position; + } + } + + /// + /// Applies the rotation and position of the 's + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ApplyCurrentTransform() + { + if (m_IsRigidbody2D) + { + m_Rigidbody2D.position = transform.position; + m_Rigidbody2D.rotation = transform.eulerAngles.z; + } + else + { + m_Rigidbody.position = transform.position; + m_Rigidbody.rotation = transform.rotation; + } + } + + /// + /// Rotatates the Rigidbody towards a specified rotation + /// + /// The rotation expressed as a + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void MoveRotation(Quaternion rotation) + { + if (m_IsRigidbody2D) + { + m_Rigidbody2D.MoveRotation(rotation); + } + else + { + m_Rigidbody.MoveRotation(rotation); + } + } + + /// + /// Applies a rotation to the Rigidbody + /// + /// The rotation to apply expressed as a + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetRotation(Quaternion rotation) + { + if (m_IsRigidbody2D) + { + m_Rigidbody2D.rotation = rotation.eulerAngles.z; + } + else + { + m_Rigidbody.rotation = rotation; + } + } + + /// + /// Sets the original interpolation of the Rigidbody while taking the Rigidbody type into consideration + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void SetOriginalInterpolation() + { + if (m_IsRigidbody2D) + { + switch (m_Rigidbody2D.interpolation) + { + case RigidbodyInterpolation2D.None: + { + m_OriginalInterpolation = InterpolationTypes.None; + break; + } + case RigidbodyInterpolation2D.Interpolate: + { + m_OriginalInterpolation = InterpolationTypes.Interpolate; + break; + } + case RigidbodyInterpolation2D.Extrapolate: + { + m_OriginalInterpolation = InterpolationTypes.Extrapolate; + break; + } + } + } + else + { + switch (m_Rigidbody.interpolation) + { + case RigidbodyInterpolation.None: + { + m_OriginalInterpolation = InterpolationTypes.None; + break; + } + case RigidbodyInterpolation.Interpolate: + { + m_OriginalInterpolation = InterpolationTypes.Interpolate; + break; + } + case RigidbodyInterpolation.Extrapolate: + { + m_OriginalInterpolation = InterpolationTypes.Extrapolate; + break; + } + } + } + } + + /// + /// Wakes the Rigidbody if it is sleeping + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void WakeIfSleeping() + { + if (m_IsRigidbody2D) + { + if (m_Rigidbody2D.IsSleeping()) + { + m_Rigidbody2D.WakeUp(); + } + } + else + { + if (m_Rigidbody.IsSleeping()) + { + m_Rigidbody.WakeUp(); + } + } + } + + /// + /// Puts the Rigidbody to sleep + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SleepRigidbody() + { + if (m_IsRigidbody2D) + { + m_Rigidbody2D.Sleep(); + } + else + { + m_Rigidbody.Sleep(); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool IsKinematic() + { + if (m_IsRigidbody2D) + { + return m_Rigidbody2D.isKinematic; + } + else + { + return m_Rigidbody.isKinematic; + } + } + + /// + /// Sets the kinematic state of the Rigidbody and handles updating the Rigidbody's + /// interpolation setting based on the Kinematic state. + /// + /// + /// When using the Rigidbody for motion, this automatically + /// adjusts from extrapolation to interpolation if: + /// - The Rigidbody was originally set to extrapolation + /// - The NetworkTransform is set to interpolate + /// When the two above conditions are true: + /// - When switching from non-kinematic to kinematic this will automatically + /// switch the Rigidbody from extrapolation to interpolate. + /// - When switching from kinematic to non-kinematic this will automatically + /// switch the Rigidbody from interpolation back to extrapolation. + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void SetIsKinematic(bool isKinematic) + { + if (m_IsRigidbody2D) + { + m_Rigidbody2D.isKinematic = isKinematic; + } + else + { + m_Rigidbody.isKinematic = isKinematic; + } + + // If we are not spawned, then exit early + if (!IsSpawned) + { + return; + } + + if (UseRigidBodyForMotion) + { + // Only if the NetworkTransform is set to interpolate do we need to check for extrapolation + if (m_NetworkTransform.Interpolate && m_OriginalInterpolation == InterpolationTypes.Extrapolate) + { + if (IsKinematic()) + { + // If not already set to interpolate then set the Rigidbody to interpolate + if (m_Rigidbody.interpolation == RigidbodyInterpolation.Extrapolate) + { + // Sleep until the next fixed update when switching from extrapolation to interpolation + SleepRigidbody(); + SetInterpolation(InterpolationTypes.Interpolate); + } + } + else + { + // Switch it back to the original interpolation if non-kinematic (doesn't require sleep). + SetInterpolation(m_OriginalInterpolation); + } + } + } + else + { + SetInterpolation(m_IsAuthority ? m_OriginalInterpolation : (m_NetworkTransform.Interpolate ? InterpolationTypes.None : m_OriginalInterpolation)); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void SetInterpolation(InterpolationTypes interpolationType) + { + switch (interpolationType) + { + case InterpolationTypes.None: + { + if (m_IsRigidbody2D) + { + m_Rigidbody2D.interpolation = RigidbodyInterpolation2D.None; + } + else + { + m_Rigidbody.interpolation = RigidbodyInterpolation.None; + } + break; + } + case InterpolationTypes.Interpolate: + { + if (m_IsRigidbody2D) + { + m_Rigidbody2D.interpolation = RigidbodyInterpolation2D.Interpolate; + } + else + { + m_Rigidbody.interpolation = RigidbodyInterpolation.Interpolate; + } + break; + } + case InterpolationTypes.Extrapolate: + { + if (m_IsRigidbody2D) + { + m_Rigidbody2D.interpolation = RigidbodyInterpolation2D.Extrapolate; + } + else + { + m_Rigidbody.interpolation = RigidbodyInterpolation.Extrapolate; + } + break; + } + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void ResetInterpolation() + { + SetInterpolation(m_OriginalInterpolation); + } + + protected override void OnOwnershipChanged(ulong previous, ulong current) + { + UpdateOwnershipAuthority(); + base.OnOwnershipChanged(previous, current); + } + + /// + /// Sets the authority based on whether it is server or owner authoritative + /// + /// + /// Distributed authority sessions will always be owner authoritative. + /// + internal void UpdateOwnershipAuthority() + { + if (NetworkManager.DistributedAuthorityMode) + { + // When in distributed authority mode, always use HasAuthority + m_IsAuthority = HasAuthority; + } + else + { + if (m_NetworkTransform.IsServerAuthoritative()) + { + m_IsAuthority = NetworkManager.IsServer; + } + else + { + m_IsAuthority = IsOwner; + } + } + + if (AutoUpdateKinematicState) + { + SetIsKinematic(!m_IsAuthority); + } + } + + /// + public override void OnNetworkSpawn() + { + UpdateOwnershipAuthority(); + } + + /// + public override void OnNetworkDespawn() + { + // If we are automatically handling the kinematic state... + if (AutoUpdateKinematicState || AutoSetKinematicOnDespawn) + { + // Turn off physics for the rigid body until spawned, otherwise + // non-owners can run fixed updates before the first full + // NetworkTransform update and physics will be applied (i.e. gravity, etc) + SetIsKinematic(true); + } + SetInterpolation(m_OriginalInterpolation); + } + + /// + /// When is enabled, the will update Kinematic instances using + /// the Rigidbody's move methods allowing Rigidbody interpolation settings to be taken into consideration by the physics simulation. + /// + /// + /// This will update the associated during FixedUpdate which also avoids the added expense of adding + /// a FixedUpdate to all instances where some might not be using a Rigidbody. + /// + private void FixedUpdate() + { + if (!IsSpawned || m_NetworkTransform == null || !UseRigidBodyForMotion) + { + return; + } + m_NetworkTransform.OnFixedUpdate(); + } + } +} +#endif // COM_UNITY_MODULES_PHYSICS + diff --git a/Components/NetworkRigidBodyBase.cs.meta b/Components/NetworkRigidBodyBase.cs.meta new file mode 100644 index 0000000..544ddba --- /dev/null +++ b/Components/NetworkRigidBodyBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8c4434f0563fb7f42b3b2993c97ae81a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Components/NetworkRigidbody.cs b/Components/NetworkRigidbody.cs index 0569aa9..7c93a5d 100644 --- a/Components/NetworkRigidbody.cs +++ b/Components/NetworkRigidbody.cs @@ -7,96 +7,14 @@ namespace Unity.Netcode.Components /// NetworkRigidbody allows for the use of on network objects. By controlling the kinematic /// mode of the and disabling it on all peers but the authoritative one. /// - [RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(NetworkTransform))] + [RequireComponent(typeof(Rigidbody))] [AddComponentMenu("Netcode/Network Rigidbody")] - public class NetworkRigidbody : NetworkBehaviour + public class NetworkRigidbody : NetworkRigidbodyBase { - /// - /// Determines if we are server (true) or owner (false) authoritative - /// - private bool m_IsServerAuthoritative; - - private Rigidbody m_Rigidbody; - private NetworkTransform m_NetworkTransform; - private RigidbodyInterpolation m_OriginalInterpolation; - - // Used to cache the authority state of this Rigidbody during the last frame - private bool m_IsAuthority; - - private void Awake() + protected virtual void Awake() { - m_NetworkTransform = GetComponent(); - m_IsServerAuthoritative = m_NetworkTransform.IsServerAuthoritative(); - - m_Rigidbody = GetComponent(); - m_OriginalInterpolation = m_Rigidbody.interpolation; - - // Set interpolation to none if NetworkTransform is handling interpolation, otherwise it sets it to the original value - m_Rigidbody.interpolation = m_NetworkTransform.Interpolate ? RigidbodyInterpolation.None : m_OriginalInterpolation; - - // Turn off physics for the rigid body until spawned, otherwise - // clients can run fixed update before the first full - // NetworkTransform update - m_Rigidbody.isKinematic = true; - } - - /// - /// For owner authoritative (i.e. ClientNetworkTransform) - /// we adjust our authority when we gain ownership - /// - public override void OnGainedOwnership() - { - UpdateOwnershipAuthority(); - } - - /// - /// For owner authoritative(i.e. ClientNetworkTransform) - /// we adjust our authority when we have lost ownership - /// - public override void OnLostOwnership() - { - UpdateOwnershipAuthority(); - } - - /// - /// Sets the authority differently depending upon - /// whether it is server or owner authoritative - /// - private void UpdateOwnershipAuthority() - { - if (m_IsServerAuthoritative) - { - m_IsAuthority = NetworkManager.IsServer; - } - else - { - m_IsAuthority = IsOwner; - } - - // If you have authority then you are not kinematic - m_Rigidbody.isKinematic = !m_IsAuthority; - - // Set interpolation of the Rigidbody based on authority - // With authority: let local transform handle interpolation - // Without authority: let the NetworkTransform handle interpolation - m_Rigidbody.interpolation = m_IsAuthority ? m_OriginalInterpolation : RigidbodyInterpolation.None; - } - - /// - public override void OnNetworkSpawn() - { - UpdateOwnershipAuthority(); - } - - /// - public override void OnNetworkDespawn() - { - m_Rigidbody.interpolation = m_OriginalInterpolation; - // Turn off physics for the rigid body until spawned, otherwise - // non-owners can run fixed updates before the first full - // NetworkTransform update and physics will be applied (i.e. gravity, etc) - m_Rigidbody.isKinematic = true; + Initialize(RigidbodyTypes.Rigidbody); } } } diff --git a/Components/NetworkRigidbody2D.cs b/Components/NetworkRigidbody2D.cs index 246519c..a178660 100644 --- a/Components/NetworkRigidbody2D.cs +++ b/Components/NetworkRigidbody2D.cs @@ -7,76 +7,14 @@ namespace Unity.Netcode.Components /// NetworkRigidbody allows for the use of on network objects. By controlling the kinematic /// mode of the rigidbody and disabling it on all peers but the authoritative one. /// - [RequireComponent(typeof(Rigidbody2D))] [RequireComponent(typeof(NetworkTransform))] + [RequireComponent(typeof(Rigidbody2D))] [AddComponentMenu("Netcode/Network Rigidbody 2D")] - public class NetworkRigidbody2D : NetworkBehaviour + public class NetworkRigidbody2D : NetworkRigidbodyBase { - private Rigidbody2D m_Rigidbody; - private NetworkTransform m_NetworkTransform; - - private bool m_OriginalKinematic; - private RigidbodyInterpolation2D m_OriginalInterpolation; - - // Used to cache the authority state of this rigidbody during the last frame - private bool m_IsAuthority; - - /// - /// Gets a bool value indicating whether this on this peer currently holds authority. - /// - private bool HasAuthority => m_NetworkTransform.CanCommitToTransform; - - private void Awake() + protected virtual void Awake() { - m_Rigidbody = GetComponent(); - m_NetworkTransform = GetComponent(); - } - - private void FixedUpdate() - { - if (IsSpawned) - { - if (HasAuthority != m_IsAuthority) - { - m_IsAuthority = HasAuthority; - UpdateRigidbodyKinematicMode(); - } - } - } - - // Puts the rigidbody in a kinematic non-interpolated mode on everyone but the server. - private void UpdateRigidbodyKinematicMode() - { - if (m_IsAuthority == false) - { - m_OriginalKinematic = m_Rigidbody.isKinematic; - m_Rigidbody.isKinematic = true; - - m_OriginalInterpolation = m_Rigidbody.interpolation; - // Set interpolation to none, the NetworkTransform component interpolates the position of the object. - m_Rigidbody.interpolation = RigidbodyInterpolation2D.None; - } - else - { - // Resets the rigidbody back to it's non replication only state. Happens on shutdown and when authority is lost - m_Rigidbody.isKinematic = m_OriginalKinematic; - m_Rigidbody.interpolation = m_OriginalInterpolation; - } - } - - /// - public override void OnNetworkSpawn() - { - m_IsAuthority = HasAuthority; - m_OriginalKinematic = m_Rigidbody.isKinematic; - m_OriginalInterpolation = m_Rigidbody.interpolation; - UpdateRigidbodyKinematicMode(); - } - - /// - public override void OnNetworkDespawn() - { - UpdateRigidbodyKinematicMode(); + Initialize(RigidbodyTypes.Rigidbody2D); } } } diff --git a/Components/NetworkTransform.cs b/Components/NetworkTransform.cs index c463d39..3d0d0c1 100644 --- a/Components/NetworkTransform.cs +++ b/Components/NetworkTransform.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Runtime.CompilerServices; -using Unity.Collections; +using System.Text; using Unity.Mathematics; +using Unity.Netcode.Transports.UTP; using UnityEngine; namespace Unity.Netcode.Components @@ -17,67 +19,7 @@ namespace Unity.Netcode.Components [DefaultExecutionOrder(100000)] // this is needed to catch the update time after the transform was updated by user scripts public class NetworkTransform : NetworkBehaviour { - /// - /// The default position change threshold value. - /// Any changes above this threshold will be replicated. - /// - public const float PositionThresholdDefault = 0.001f; - - /// - /// The default rotation angle change threshold value. - /// Any changes above this threshold will be replicated. - /// - public const float RotAngleThresholdDefault = 0.01f; - - /// - /// The default scale change threshold value. - /// Any changes above this threshold will be replicated. - /// - public const float ScaleThresholdDefault = 0.01f; - - /// - /// The handler delegate type that takes client requested changes and returns resulting changes handled by the server. - /// - /// The position requested by the client. - /// The rotation requested by the client. - /// The scale requested by the client. - /// The resulting position, rotation and scale changes after handling. - public delegate (Vector3 pos, Quaternion rotOut, Vector3 scale) OnClientRequestChangeDelegate(Vector3 pos, Quaternion rot, Vector3 scale); - - /// - /// The handler that gets invoked when server receives a change from a client. - /// This handler would be useful for server to modify pos/rot/scale before applying client's request. - /// - public OnClientRequestChangeDelegate OnClientRequestChange; - - /// - /// When set each state update will contain a state identifier - /// - internal static bool TrackByStateId; - - /// - /// Enabled by default. - /// When set (enabled by default), NetworkTransform will send common state updates using unreliable network delivery - /// to provide a higher tolerance to poor network conditions (especially packet loss). When disabled, all state updates - /// are sent using a reliable fragmented sequenced network delivery. - /// - /// - /// The following more critical state updates are still sent as reliable fragmented sequenced: - /// - The initial synchronization state update - /// - The teleporting state update. - /// - When using half float precision and the `NetworkDeltaPosition` delta exceeds the maximum delta forcing the axis in - /// question to be collapsed into the core base position, this state update will be sent as reliable fragmented sequenced. - /// - /// In order to preserve a continual consistency of axial values when unreliable delta messaging is enabled (due to the - /// possibility of dropping packets), NetworkTransform instances will send 1 axial frame synchronization update per - /// second (only for the axis marked to synchronize are sent as reliable fragmented sequenced) as long as a delta state - /// update had been previously sent. When a NetworkObject is at rest, axial frame synchronization updates are not sent. - /// - [Tooltip("When set, NetworkTransform will send common state updates using unreliable network delivery " + - "to provide a higher tolerance to poor network conditions (especially packet loss). When disabled, all state updates are " + - "sent using reliable fragmented sequenced network delivery.")] - public bool UseUnreliableDeltas = false; - + #region NETWORK TRANSFORM STATE /// /// Data structure used to synchronize the /// @@ -105,7 +47,7 @@ namespace Unity.Netcode.Components private const int k_ReliableSequenced = 0x00080000; private const int k_UseUnreliableDeltas = 0x00100000; private const int k_UnreliableFrameSync = 0x00200000; - private const int k_TrackStateId = 0x10000000; // (Internal Debugging) When set each state update will contain a state identifier + private const int k_TrackStateId = 0x10000000; // (Internal Debugging) When set each state update will contain a state identifier // Stores persistent and state relative flags private uint m_Bitset; @@ -587,7 +529,7 @@ namespace Unity.Netcode.Components /// /// When there is no change in an updated state's position then there are no values to return. /// Checking for is one way to detect this. - /// When used with half precision it returns the half precision delta position state update + /// When used with half precision it returns the half precision delta position state update /// which will not be the full position. /// To get a NettworkTransform's full position, use and /// pass true as the parameter. @@ -898,7 +840,7 @@ namespace Unity.Netcode.Components if (HasScaleChange) { // If we are teleporting (which includes synchronizing) and the associated NetworkObject has a parent - // then we want to serialize the LossyScale since NetworkObject spawn order is not guaranteed + // then we want to serialize the LossyScale since NetworkObject spawn order is not guaranteed if (IsTeleportingNextFrame && IsParented) { serializer.SerializeValue(ref LossyScale); @@ -977,6 +919,69 @@ namespace Unity.Netcode.Components } } } + #endregion + + #region PROPERTIES AND GENERAL METHODS + /// + /// The default position change threshold value. + /// Any changes above this threshold will be replicated. + /// + public const float PositionThresholdDefault = 0.001f; + + /// + /// The default rotation angle change threshold value. + /// Any changes above this threshold will be replicated. + /// + public const float RotAngleThresholdDefault = 0.01f; + + /// + /// The default scale change threshold value. + /// Any changes above this threshold will be replicated. + /// + public const float ScaleThresholdDefault = 0.01f; + + /// + /// The handler delegate type that takes client requested changes and returns resulting changes handled by the server. + /// + /// The position requested by the client. + /// The rotation requested by the client. + /// The scale requested by the client. + /// The resulting position, rotation and scale changes after handling. + public delegate (Vector3 pos, Quaternion rotOut, Vector3 scale) OnClientRequestChangeDelegate(Vector3 pos, Quaternion rot, Vector3 scale); + + /// + /// The handler that gets invoked when server receives a change from a client. + /// This handler would be useful for server to modify pos/rot/scale before applying client's request. + /// + public OnClientRequestChangeDelegate OnClientRequestChange; + + /// + /// When set each state update will contain a state identifier + /// + internal static bool TrackByStateId = false; + + /// + /// Enabled by default. + /// When set (enabled by default), NetworkTransform will send common state updates using unreliable network delivery + /// to provide a higher tolerance to poor network conditions (especially packet loss). When disabled, all state updates + /// are sent using a reliable fragmented sequenced network delivery. + /// + /// + /// The following more critical state updates are still sent as reliable fragmented sequenced: + /// - The initial synchronization state update + /// - The teleporting state update. + /// - When using half float precision and the `NetworkDeltaPosition` delta exceeds the maximum delta forcing the axis in + /// question to be collapsed into the core base position, this state update will be sent as reliable fragmented sequenced. + /// + /// In order to preserve a continual consistency of axial values when unreliable delta messaging is enabled (due to the + /// possibility of dropping packets), NetworkTransform instances will send 1 axial frame synchronization update per + /// second (only for the axis marked to synchronize are sent as reliable fragmented sequenced) as long as a delta state + /// update had been previously sent. When a NetworkObject is at rest, axial frame synchronization updates are not sent. + /// + [Tooltip("When set, NetworkTransform will send common state updates using unreliable network delivery " + + "to provide a higher tolerance to poor network conditions (especially packet loss). When disabled, all state updates are " + + "sent using reliable fragmented sequenced network delivery.")] + public bool UseUnreliableDeltas = false; /// /// When enabled (default), the x component of position will be synchronized by authority. @@ -1321,6 +1326,9 @@ namespace Unity.Netcode.Components private BufferedLinearInterpolatorVector3 m_ScaleInterpolator; private BufferedLinearInterpolatorQuaternion m_RotationInterpolator; // rotation is a single Quaternion since each Euler axis will affect the quaternion's final value + // The previous network state + private NetworkTransformState m_OldState = new NetworkTransformState(); + // Non-Authoritative's current position, scale, and rotation that is used to assure the non-authoritative side cannot make adjustments to // the portions of the transform being synchronized. private Vector3 m_CurrentPosition; @@ -1330,25 +1338,20 @@ namespace Unity.Netcode.Components private Quaternion m_CurrentRotation; private Vector3 m_TargetRotation; - // Used to for each instance to uniquely identify the named message - private string m_MessageName; + // DANGO-EXP TODO: ADD Rigidbody2D +#if COM_UNITY_MODULES_PHYSICS + private bool m_UseRigidbodyForMotion; + private NetworkRigidbodyBase m_NetworkRigidbodyInternal; - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal void UpdatePositionInterpolator(Vector3 position, double time, bool resetInterpolator = false) + internal void RegisterRigidbody(NetworkRigidbodyBase networkRigidbody) { - if (!CanCommitToTransform) + if (networkRigidbody != null) { - if (resetInterpolator) - { - m_PositionInterpolator.ResetTo(position, time); - } - else - { - m_PositionInterpolator.AddMeasurement(position, time); - } + m_NetworkRigidbodyInternal = networkRigidbody; + m_UseRigidbodyForMotion = m_NetworkRigidbodyInternal.UseRigidBodyForMotion; } } +#endif #if DEBUG_NETWORKTRANSFORM || UNITY_INCLUDE_TESTS /// @@ -1406,8 +1409,8 @@ namespace Unity.Netcode.Components { if (!IsServerAuthoritative() && NetworkObject.OwnerClientId == targetClientId) { - // Return false for all client owners but return true for the server - return NetworkObject.IsOwnedByServer; + // In distributed authority mode we want to synchronize the half float if we are the owner. + return (!NetworkManager.DistributedAuthorityMode && NetworkObject.IsOwnedByServer) || (NetworkManager.DistributedAuthorityMode); } return true; } @@ -1415,6 +1418,11 @@ namespace Unity.Netcode.Components // For test logging purposes internal NetworkTransformState SynchronizeState; + // DANGO-TODO: We will want to remove this when we migrate NetworkTransforms to a dedicated internal message + private const ushort k_NetworkTransformStateMagic = 0xf48d; + #endregion + + #region ONSYNCHRONIZE /// /// This is invoked when a new client joins (server and client sides) /// Server Side: Serializes as if we were teleporting (everything is sent via NetworkTransformState) @@ -1435,15 +1443,24 @@ namespace Unity.Netcode.Components HalfVectorRotation = new HalfVector4(), HalfVectorScale = new HalfVector3(), NetworkDeltaPosition = new NetworkDeltaPosition(), + }; if (serializer.IsWriter) { + // DANGO-TODO: This magic value is sent to the server in order to identify the network transform. + // The server discards it before forwarding synchronization data to other clients. + if (NetworkManager.DistributedAuthorityMode && NetworkManager.CMBServiceConnection) + { + var writer = serializer.GetFastBufferWriter(); + writer.WriteValueSafe(k_NetworkTransformStateMagic); + } + synchronizationState.IsTeleportingNextFrame = true; var transformToCommit = transform; // If we are using Half Float Precision, then we want to only synchronize the authority's m_HalfPositionState.FullPosition in order for // for the non-authority side to be able to properly synchronize delta position updates. - ApplyTransformToNetworkStateWithInfo(ref synchronizationState, ref transformToCommit, true, targetClientId); + CheckForStateChange(ref synchronizationState, ref transformToCommit, true, targetClientId); synchronizationState.NetworkSerialize(serializer); SynchronizeState = synchronizationState; } @@ -1467,7 +1484,9 @@ namespace Unity.Netcode.Components m_LocalAuthoritativeNetworkState.IsSynchronizing = false; } } + #endregion + #region AUTHORITY STATE UPDATE /// /// This will try to send/commit the current transform delta states (if any) /// @@ -1547,7 +1566,7 @@ namespace Unity.Netcode.Components } // If the transform has deltas (returns dirty) or if an explicitly set state is pending - if (m_LocalAuthoritativeNetworkState.ExplicitSet || ApplyTransformToNetworkStateWithInfo(ref m_LocalAuthoritativeNetworkState, ref transformToCommit, synchronize)) + if (m_LocalAuthoritativeNetworkState.ExplicitSet || CheckForStateChange(ref m_LocalAuthoritativeNetworkState, ref transformToCommit, synchronize)) { m_LocalAuthoritativeNetworkState.LastSerializedSize = m_OldState.LastSerializedSize; @@ -1593,20 +1612,6 @@ namespace Unity.Netcode.Components } } - /// - /// Initializes the interpolators with the current transform values - /// - private void ResetInterpolatedStateToCurrentAuthoritativeState() - { - var serverTime = NetworkManager.ServerTime.Time; - - UpdatePositionInterpolator(GetSpaceRelativePosition(), serverTime, true); - UpdatePositionSlerp(); - - m_ScaleInterpolator.ResetTo(transform.localScale, serverTime); - m_RotationInterpolator.ResetTo(GetSpaceRelativeRotation(), serverTime); - } - /// /// Used for integration testing: /// Will apply the transform to the LocalAuthoritativeNetworkState and get detailed dirty information returned @@ -1621,7 +1626,7 @@ namespace Unity.Netcode.Components m_LocalAuthoritativeNetworkState.ClearBitSetForNextTick(); // Now check the transform for any threshold value changes - ApplyTransformToNetworkStateWithInfo(ref m_LocalAuthoritativeNetworkState, ref transform); + CheckForStateChange(ref m_LocalAuthoritativeNetworkState, ref transform); // Return the entire state to be used by the integration test return m_LocalAuthoritativeNetworkState; @@ -1641,14 +1646,14 @@ namespace Unity.Netcode.Components networkState.UseUnreliableDeltas = UseUnreliableDeltas; m_HalfPositionState = new NetworkDeltaPosition(Vector3.zero, 0, math.bool3(SyncPositionX, SyncPositionY, SyncPositionZ)); - return ApplyTransformToNetworkStateWithInfo(ref networkState, ref transformToUse); + return CheckForStateChange(ref networkState, ref transformToUse); } /// /// Applies the transform to the specified. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - private bool ApplyTransformToNetworkStateWithInfo(ref NetworkTransformState networkState, ref Transform transformToUse, bool isSynchronization = false, ulong targetClientId = 0) + private bool CheckForStateChange(ref NetworkTransformState networkState, ref Transform transformToUse, bool isSynchronization = false, ulong targetClientId = 0) { // As long as we are not doing our first synchronization and we are sending unreliable deltas, each // NetworkTransform will stagger its full transfom synchronization over a 1 second period based on the @@ -1680,8 +1685,14 @@ namespace Unity.Netcode.Components var isRotationDirty = isTeleportingAndNotSynchronizing ? networkState.HasRotAngleChange : false; var isScaleDirty = isTeleportingAndNotSynchronizing ? networkState.HasScaleChange : false; +#if COM_UNITY_MODULES_PHYSICS + var position = m_UseRigidbodyForMotion ? m_NetworkRigidbodyInternal.GetPosition() : InLocalSpace ? transformToUse.localPosition : transformToUse.position; + var rotation = m_UseRigidbodyForMotion ? m_NetworkRigidbodyInternal.GetRotation() : InLocalSpace ? transformToUse.localRotation : transformToUse.rotation; +#else var position = InLocalSpace ? transformToUse.localPosition : transformToUse.position; - var rotAngles = InLocalSpace ? transformToUse.localEulerAngles : transformToUse.eulerAngles; + var rotation = InLocalSpace ? transformToUse.localRotation : transformToUse.rotation; +#endif + var rotAngles = rotation.eulerAngles; var scale = transformToUse.localScale; networkState.IsSynchronizing = isSynchronization; @@ -1964,8 +1975,8 @@ namespace Unity.Netcode.Components } } - // For scale, we need to check for parenting when synchronizing and/or teleporting - if (isSynchronization || networkState.IsTeleportingNextFrame) + // For scale, we need to check for parenting when synchronizing and/or teleporting (synchronization is always teleporting) + if (networkState.IsTeleportingNextFrame) { // If we are synchronizing and the associated NetworkObject has a parent then we want to send the // LossyScale if the NetworkObject has a parent since NetworkObject spawn order is not guaranteed @@ -2051,6 +2062,58 @@ namespace Unity.Netcode.Components return isDirty; } + + /// + /// Authority subscribes to network tick events and will invoke + /// each network tick. + /// + private void OnNetworkTick() + { + // As long as we are still authority + if (CanCommitToTransform) + { + if (m_CachedNetworkManager.DistributedAuthorityMode && !IsOwner) + { + Debug.LogError($"Non-owner Client-{m_CachedNetworkManager.LocalClientId} is being updated by network tick still!!!!"); + } + // Update any changes to the transform + var transformSource = transform; + OnUpdateAuthoritativeState(ref transformSource); +#if COM_UNITY_MODULES_PHYSICS + m_CurrentPosition = m_TargetPosition = m_UseRigidbodyForMotion ? m_NetworkRigidbodyInternal.GetPosition() : GetSpaceRelativePosition(); +#else + m_CurrentPosition = GetSpaceRelativePosition(); + m_TargetPosition = GetSpaceRelativePosition(); +#endif + } + else // If we are no longer authority, unsubscribe to the tick event + if (NetworkManager != null && NetworkManager.NetworkTickSystem != null) + { + NetworkManager.NetworkTickSystem.Tick -= OnNetworkTick; + } + } + #endregion + + #region NON-AUTHORITY STATE UPDATE + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void UpdatePositionInterpolator(Vector3 position, double time, bool resetInterpolator = false) + { + if (!CanCommitToTransform) + { + if (resetInterpolator) + { + m_PositionInterpolator.ResetTo(position, time); + } + else + { + m_PositionInterpolator.AddMeasurement(position, time); + } + } + } + + internal bool LogMotion; + /// /// Applies the authoritative state to the transform /// @@ -2062,6 +2125,7 @@ namespace Unity.Netcode.Components // cannot make adjustments to any portions the transform not being synchronized. var adjustedPosition = m_CurrentPosition; var adjustedRotation = m_CurrentRotation; + var adjustedRotAngles = adjustedRotation.eulerAngles; var adjustedScale = m_CurrentScale; @@ -2187,13 +2251,27 @@ namespace Unity.Netcode.Components { m_CurrentPosition = adjustedPosition; } - if (InLocalSpace) +#if COM_UNITY_MODULES_PHYSICS + if (m_UseRigidbodyForMotion) { - transform.localPosition = m_CurrentPosition; + m_NetworkRigidbodyInternal.MovePosition(m_CurrentPosition); + if (LogMotion) + { + Debug.Log($"[Client-{m_CachedNetworkManager.LocalClientId}][Interpolate: {networkState.UseInterpolation}][TransPos: {transform.position}][RBPos: {m_NetworkRigidbodyInternal.GetPosition()}][CurrentPos: {m_CurrentPosition}"); + } + } else +#endif { - transform.position = m_CurrentPosition; + if (InLocalSpace) + { + transform.localPosition = m_CurrentPosition; + } + else + { + transform.position = m_CurrentPosition; + } } } @@ -2205,13 +2283,23 @@ namespace Unity.Netcode.Components { m_CurrentRotation = adjustedRotation; } - if (InLocalSpace) + +#if COM_UNITY_MODULES_PHYSICS + if (m_UseRigidbodyForMotion) { - transform.localRotation = m_CurrentRotation; + m_NetworkRigidbodyInternal.MoveRotation(m_CurrentRotation); } else +#endif { - transform.rotation = m_CurrentRotation; + if (InLocalSpace) + { + transform.localRotation = m_CurrentRotation; + } + else + { + transform.rotation = m_CurrentRotation; + } } } @@ -2317,6 +2405,13 @@ namespace Unity.Netcode.Components transform.position = currentPosition; } +#if COM_UNITY_MODULES_PHYSICS + if (m_UseRigidbodyForMotion) + { + m_NetworkRigidbodyInternal.SetPosition(transform.position); + } +#endif + if (Interpolate) { UpdatePositionInterpolator(currentPosition, sentTime, true); @@ -2411,6 +2506,13 @@ namespace Unity.Netcode.Components transform.rotation = currentRotation; } +#if COM_UNITY_MODULES_PHYSICS + if (m_UseRigidbodyForMotion) + { + m_NetworkRigidbodyInternal.SetRotation(transform.rotation); + } +#endif + if (Interpolate) { m_RotationInterpolator.ResetTo(currentRotation, sentTime); @@ -2455,7 +2557,6 @@ namespace Unity.Netcode.Components var sentTime = newState.SentTime; var currentRotation = GetSpaceRelativeRotation(); - var currentEulerAngles = currentRotation.eulerAngles; // Only if using half float precision and our position had changed last update then if (UseHalfFloatPrecision && m_LocalAuthoritativeNetworkState.HasPositionChange) @@ -2555,7 +2656,7 @@ namespace Unity.Netcode.Components } else { - currentEulerAngles = m_TargetRotation; + var currentEulerAngles = m_TargetRotation; // Adjust based on which axis changed // (both half precision and full precision apply Eulers to the RotAngle properties when reading the update) if (m_LocalAuthoritativeNetworkState.HasRotAngleX) @@ -2590,8 +2691,7 @@ namespace Unity.Netcode.Components } - private NetworkTransformState m_OldState = new NetworkTransformState(); - + internal bool LogStateUpdate; /// /// Only non-authoritative instances should invoke this method /// @@ -2613,6 +2713,24 @@ namespace Unity.Netcode.Components // Get the time when this new state was sent newState.SentTime = new NetworkTime(m_CachedNetworkManager.NetworkConfig.TickRate, newState.NetworkTick).Time; + if (LogStateUpdate) + { + var builder = new StringBuilder(); + builder.AppendLine($"[Client-{m_CachedNetworkManager.LocalClientId}][State Update: {newState.GetNetworkTick()}][HasPos: {newState.HasPositionChange}][Has Rot: {newState.HasRotAngleChange}][Has Scale: {newState.HasScaleChange}]"); + if (newState.HasPositionChange) + { + builder.AppendLine($"Position = {newState.GetPosition()}"); + } + if (newState.HasRotAngleChange) + { + builder.AppendLine($"Rotation = {newState.GetRotation()}"); + } + if (newState.HasScaleChange) + { + builder.AppendLine($"Scale = {newState.GetScale()}"); + } + Debug.Log(builder); + } // Apply the new state ApplyUpdatedState(newState); @@ -2636,18 +2754,6 @@ namespace Unity.Netcode.Components m_ScaleInterpolator.MaxInterpolationBound = maxInterpolationBound; } - /// - /// Create interpolators when first instantiated to avoid memory allocations if the - /// associated NetworkObject persists (i.e. despawned but not destroyed or pools) - /// - protected virtual void Awake() - { - // Rotation is a single Quaternion since each Euler axis will affect the quaternion's final value - m_RotationInterpolator = new BufferedLinearInterpolatorQuaternion(); - m_PositionInterpolator = new BufferedLinearInterpolatorVector3(); - m_ScaleInterpolator = new BufferedLinearInterpolatorVector3(); - } - /// /// Checks for changes in the axis to synchronize. If one or more did change it /// then determines if the axis were enabled and if the delta between the last known @@ -2718,28 +2824,19 @@ namespace Unity.Netcode.Components TryCommitTransform(ref transformSource); } + #endregion + #region SPAWN, DESPAWN, AND INITIALIZATION /// - /// Authority subscribes to network tick events and will invoke - /// each network tick. + /// Create interpolators when first instantiated to avoid memory allocations if the + /// associated NetworkObject persists (i.e. despawned but not destroyed or pools) /// - private void NetworkTickSystem_Tick() + protected virtual void Awake() { - // As long as we are still authority - if (CanCommitToTransform) - { - // Update any changes to the transform - var transformSource = transform; - OnUpdateAuthoritativeState(ref transformSource); - - m_CurrentPosition = GetSpaceRelativePosition(); - m_TargetPosition = GetSpaceRelativePosition(); - } - else // If we are no longer authority, unsubscribe to the tick event - if (NetworkManager != null && NetworkManager.NetworkTickSystem != null) - { - NetworkManager.NetworkTickSystem.Tick -= NetworkTickSystem_Tick; - } + // Rotation is a single Quaternion since each Euler axis will affect the quaternion's final value + m_RotationInterpolator = new BufferedLinearInterpolatorQuaternion(); + m_PositionInterpolator = new BufferedLinearInterpolatorVector3(); + m_ScaleInterpolator = new BufferedLinearInterpolatorVector3(); } /// @@ -2753,64 +2850,34 @@ namespace Unity.Netcode.Components // Started using this again to avoid the getter processing cost of NetworkBehaviour.NetworkManager m_CachedNetworkManager = NetworkManager; - // Register a custom named message specifically for this instance - m_MessageName = $"NTU_{NetworkObjectId}_{NetworkBehaviourId}"; - m_CachedNetworkManager.CustomMessagingManager.RegisterNamedMessageHandler(m_MessageName, TransformStateUpdate); Initialize(); + + if (CanCommitToTransform) + { + SetState(GetSpaceRelativePosition(), GetSpaceRelativeRotation(), GetScale(), false); + } + } + + private void CleanUpOnDestroyOrDespawn() + { + DeregisterForTickUpdate(this); + CanCommitToTransform = false; } /// public override void OnNetworkDespawn() { - // During destroy, use NetworkBehaviour.NetworkManager as opposed to m_CachedNetworkManager - if (!NetworkManager.ShutdownInProgress && NetworkManager.CustomMessagingManager != null) - { - NetworkManager.CustomMessagingManager.UnregisterNamedMessageHandler(m_MessageName); - } - - DeregisterForTickUpdate(this); - - CanCommitToTransform = false; - if (NetworkManager != null && NetworkManager.NetworkTickSystem != null) - { - NetworkManager.NetworkTickSystem.Tick -= NetworkTickSystem_Tick; - } + CleanUpOnDestroyOrDespawn(); + base.OnNetworkDespawn(); } /// public override void OnDestroy() { - // During destroy, use NetworkBehaviour.NetworkManager as opposed to m_CachedNetworkManager - if (NetworkManager != null && NetworkManager.NetworkTickSystem != null) - { - NetworkManager.NetworkTickSystem.Tick -= NetworkTickSystem_Tick; - } - CanCommitToTransform = false; + CleanUpOnDestroyOrDespawn(); base.OnDestroy(); } - /// - public override void OnLostOwnership() - { - base.OnLostOwnership(); - } - - /// - public override void OnGainedOwnership() - { - base.OnGainedOwnership(); - } - - protected override void OnOwnershipChanged(ulong previous, ulong current) - { - // If we were the previous owner or the newly assigned owner then reinitialize - if (current == m_CachedNetworkManager.LocalClientId || previous == m_CachedNetworkManager.LocalClientId) - { - InternalInitialization(true); - } - base.OnOwnershipChanged(previous, current); - } - /// /// Invoked when first spawned and when ownership changes. /// @@ -2819,10 +2886,6 @@ namespace Unity.Netcode.Components { } - /// - /// An owner read and owner write NetworkVariable so it doesn't generate any messages - /// - private NetworkVariable m_InternalStatNetVar = new NetworkVariable(default, NetworkVariableReadPermission.Owner, NetworkVariableWritePermission.Owner); /// /// This method is only invoked by the owner /// Use: OnInitialize(ref NetworkTransformState replicatedState) to be notified on all instances @@ -2835,6 +2898,27 @@ namespace Unity.Netcode.Components private int m_HalfFloatTargetTickOwnership; + /// + /// Initializes the interpolators with the current transform values + /// + private void ResetInterpolatedStateToCurrentAuthoritativeState() + { + var serverTime = NetworkManager.ServerTime.Time; +#if COM_UNITY_MODULES_PHYSICS + var position = m_UseRigidbodyForMotion ? m_NetworkRigidbodyInternal.GetPosition() : GetSpaceRelativePosition(); + var rotation = m_UseRigidbodyForMotion ? m_NetworkRigidbodyInternal.GetRotation() : GetSpaceRelativeRotation(); +#else + var position = GetSpaceRelativePosition(); + var rotation = GetSpaceRelativeRotation(); +#endif + + UpdatePositionInterpolator(position, serverTime, true); + UpdatePositionSlerp(); + + m_ScaleInterpolator.ResetTo(transform.localScale, serverTime); + m_RotationInterpolator.ResetTo(rotation, serverTime); + } + /// /// The internal initialzation method to allow for internal API adjustments /// @@ -2850,6 +2934,26 @@ namespace Unity.Netcode.Components var currentPosition = GetSpaceRelativePosition(); var currentRotation = GetSpaceRelativeRotation(); + if (NetworkManager.DistributedAuthorityMode) + { + RegisterNetworkManagerForTickUpdate(NetworkManager); + m_NetworkTransformTickRegistration = s_NetworkTickRegistration[m_CachedNetworkManager]; + } + +#if COM_UNITY_MODULES_PHYSICS + // Depending upon order of operations, we invoke this in order to assure that proper settings are applied. + if (m_NetworkRigidbodyInternal) + { + m_NetworkRigidbodyInternal.UpdateOwnershipAuthority(); + } + + if (m_UseRigidbodyForMotion) + { + m_NetworkRigidbodyInternal.SetPosition(currentPosition); + m_NetworkRigidbodyInternal.SetRotation(currentRotation); + } +#endif + if (CanCommitToTransform) { if (UseHalfFloatPrecision) @@ -2883,12 +2987,6 @@ namespace Unity.Netcode.Components } OnInitialize(ref m_LocalAuthoritativeNetworkState); - - if (IsOwner) - { - m_InternalStatNetVar.Value = m_LocalAuthoritativeNetworkState; - OnInitialize(ref m_InternalStatNetVar); - } } /// @@ -2898,6 +2996,30 @@ namespace Unity.Netcode.Components { InternalInitialization(); } + #endregion + + #region PARENTING AND OWNERSHIP + /// + public override void OnLostOwnership() + { + base.OnLostOwnership(); + } + + /// + public override void OnGainedOwnership() + { + base.OnGainedOwnership(); + } + + protected override void OnOwnershipChanged(ulong previous, ulong current) + { + // If we were the previous owner or the newly assigned owner then reinitialize + if (current == m_CachedNetworkManager.LocalClientId || previous == m_CachedNetworkManager.LocalClientId) + { + InternalInitialization(true); + } + base.OnOwnershipChanged(previous, current); + } /// /// @@ -2912,8 +3034,15 @@ namespace Unity.Netcode.Components // Only if we are not authority if (!CanCommitToTransform) { - m_TargetPosition = m_CurrentPosition = GetSpaceRelativePosition(); - m_CurrentRotation = GetSpaceRelativeRotation(); +#if COM_UNITY_MODULES_PHYSICS + var position = m_UseRigidbodyForMotion ? m_NetworkRigidbodyInternal.GetPosition() : GetSpaceRelativePosition(); + var rotation = m_UseRigidbodyForMotion ? m_NetworkRigidbodyInternal.GetRotation() : GetSpaceRelativeRotation(); +#else + var position = GetSpaceRelativePosition(); + var rotation = GetSpaceRelativeRotation(); +#endif + m_TargetPosition = m_CurrentPosition = position; + m_CurrentRotation = rotation; m_TargetRotation = m_CurrentRotation.eulerAngles; m_TargetScale = m_CurrentScale = GetScale(); @@ -2932,7 +3061,9 @@ namespace Unity.Netcode.Components } base.OnNetworkObjectParentChanged(parentNetworkObject); } + #endregion + #region API STATE UPDATE METHODS /// /// Directly sets a state on the authoritative transform. /// Owner clients can directly set the state on a server authoritative transform @@ -2963,9 +3094,15 @@ namespace Unity.Netcode.Components NetworkLog.LogError(errorMessage); return; } - - Vector3 pos = posIn == null ? GetSpaceRelativePosition() : posIn.Value; - Quaternion rot = rotIn == null ? GetSpaceRelativeRotation() : rotIn.Value; +#if COM_UNITY_MODULES_PHYSICS + var position = m_UseRigidbodyForMotion ? m_NetworkRigidbodyInternal.GetPosition() : GetSpaceRelativePosition(); + var rotation = m_UseRigidbodyForMotion ? m_NetworkRigidbodyInternal.GetRotation() : GetSpaceRelativeRotation(); +#else + var position = GetSpaceRelativePosition(); + var rotation = GetSpaceRelativeRotation(); +#endif + Vector3 pos = posIn == null ? position : posIn.Value; + Quaternion rot = rotIn == null ? rotation : rotIn.Value; Vector3 scale = scaleIn == null ? transform.localScale : scaleIn.Value; if (!CanCommitToTransform) @@ -2994,15 +3131,26 @@ namespace Unity.Netcode.Components /// private void SetStateInternal(Vector3 pos, Quaternion rot, Vector3 scale, bool shouldTeleport) { - if (InLocalSpace) +#if COM_UNITY_MODULES_PHYSICS + if (m_UseRigidbodyForMotion) { - transform.localPosition = pos; - transform.localRotation = rot; + m_NetworkRigidbodyInternal.SetPosition(pos); + m_NetworkRigidbodyInternal.SetRotation(rot); } else +#endif { - transform.SetPositionAndRotation(pos, rot); + if (InLocalSpace) + { + transform.localPosition = pos; + transform.localRotation = rot; + } + else + { + transform.SetPositionAndRotation(pos, rot); + } } + transform.localScale = scale; m_LocalAuthoritativeNetworkState.IsTeleportingNextFrame = shouldTeleport; @@ -3015,7 +3163,7 @@ namespace Unity.Netcode.Components var explicitState = m_LocalAuthoritativeNetworkState.ExplicitSet; // Apply any delta states to the m_LocalAuthoritativeNetworkState - var isDirty = ApplyTransformToNetworkStateWithInfo(ref m_LocalAuthoritativeNetworkState, ref transformToCommit); + var isDirty = CheckForStateChange(ref m_LocalAuthoritativeNetworkState, ref transformToCommit); // If we were dirty and the explicit state was set (prior to checking for deltas) or the current explicit state is dirty, // then we set the explicit state flag. @@ -3025,7 +3173,6 @@ namespace Unity.Netcode.Components // in between a fractional tick period and the current explicit set state did not find any deltas that we preserve any // previous dirty state. m_LocalAuthoritativeNetworkState.IsDirty = m_LocalAuthoritativeNetworkState.ExplicitSet; - } /// @@ -3058,21 +3205,55 @@ namespace Unity.Netcode.Components SetStateInternal(pos, rot, scale, shouldTeleport); } + /// + /// Teleport the transform to the given values without interpolating + /// + /// new position to move to. + /// new rotation to rotate to. + /// new scale to scale to. + /// + public void Teleport(Vector3 newPosition, Quaternion newRotation, Vector3 newScale) + { + if (!CanCommitToTransform) + { + throw new Exception("Teleporting on non-authoritative side is not allowed!"); + } + // Teleporting now is as simple as setting the internal state and passing the teleport flag + SetStateInternal(newPosition, newRotation, newScale, true); + } + #endregion + + #region UPDATES AND AUTHORITY CHECKS + private NetworkTransformTickRegistration m_NetworkTransformTickRegistration; private void UpdateInterpolation() { // Non-Authority if (Interpolate) { var serverTime = m_CachedNetworkManager.ServerTime; - var cachedDeltaTime = m_CachedNetworkManager.RealTimeProvider.DeltaTime; var cachedServerTime = serverTime.Time; - + var offset = 0f; +#if COM_UNITY_MODULES_PHYSICS + var cachedDeltaTime = m_UseRigidbodyForMotion ? m_CachedNetworkManager.RealTimeProvider.FixedDeltaTime : m_CachedNetworkManager.RealTimeProvider.DeltaTime; +#else + var cachedDeltaTime = m_CachedNetworkManager.RealTimeProvider.DeltaTime; +#endif // With owner authoritative mode, non-authority clients can lag behind // by more than 1 tick period of time. The current "solution" for now // is to make their cachedRenderTime run 2 ticks behind. - var ticksAgo = !IsServerAuthoritative() && !IsServer ? 2 : 1; - var cachedRenderTime = serverTime.TimeTicksAgo(ticksAgo).Time; +#if COM_UNITY_MODULES_PHYSICS + var ticksAgo = (!IsServerAuthoritative() && !IsServer) || m_UseRigidbodyForMotion ? 2 : 1; +#else + var ticksAgo = (!IsServerAuthoritative() && !IsServer) ? 2 : 1; +#endif + if (m_CachedNetworkManager.DistributedAuthorityMode) + { + ticksAgo = Mathf.Max(ticksAgo, (int)m_NetworkTransformTickRegistration.TicksAgo); + offset = m_NetworkTransformTickRegistration.Offset; + } + + var cachedRenderTime = serverTime.TimeTicksAgo(ticksAgo, offset).Time; // Now only update the interpolators for the portions of the transform being synchronized if (SynchronizePosition) @@ -3104,35 +3285,45 @@ namespace Unity.Netcode.Components protected virtual void Update() { // If not spawned or this instance has authority, exit early +#if COM_UNITY_MODULES_PHYSICS + if (!IsSpawned || CanCommitToTransform || m_UseRigidbodyForMotion) +#else if (!IsSpawned || CanCommitToTransform) +#endif { return; } - // Non-Authority + // Update interpolation UpdateInterpolation(); // Apply the current authoritative state ApplyAuthoritativeState(); } + +#if COM_UNITY_MODULES_PHYSICS /// - /// Teleport the transform to the given values without interpolating + /// When paired with a NetworkRigidbody and NetworkRigidbody.UseRigidBodyForMotion is enabled, + /// this will be invoked during . /// - /// new position to move to. - /// new rotation to rotate to. - /// new scale to scale to. - /// - public void Teleport(Vector3 newPosition, Quaternion newRotation, Vector3 newScale) + internal void OnFixedUpdate() { - if (!CanCommitToTransform) + // If not spawned or this instance has authority, exit early + if (!m_UseRigidbodyForMotion || !IsSpawned || CanCommitToTransform) { - throw new Exception("Teleporting on non-authoritative side is not allowed!"); + return; } - // Teleporting now is as simple as setting the internal state and passing the teleport flag - SetStateInternal(newPosition, newRotation, newScale, true); + m_NetworkRigidbodyInternal.WakeIfSleeping(); + + // Update interpolation + UpdateInterpolation(); + + // Apply the current authoritative state + ApplyAuthoritativeState(); } +#endif /// /// Override this method and return false to switch to owner authoritative mode @@ -3140,6 +3331,10 @@ namespace Unity.Netcode.Components /// ( or ) where when false it runs as owner-client authoritative protected virtual bool OnIsServerAuthoritative() { + if (m_CachedNetworkManager) + { + return !m_CachedNetworkManager.DistributedAuthorityMode; + } return true; } @@ -3155,80 +3350,31 @@ namespace Unity.Netcode.Components return OnIsServerAuthoritative(); } - /// - /// Receives the named message updates - /// - /// authority of the transform - /// serialzied - private void TransformStateUpdate(ulong senderId, FastBufferReader messagePayload) - { - var ownerAuthoritativeServerSide = !OnIsServerAuthoritative() && IsServer; - if (ownerAuthoritativeServerSide && OwnerClientId == NetworkManager.ServerClientId) - { - // Ownership must have changed, ignore any additional pending messages that might have - // come from a previous owner client. - return; - } + #endregion + #region MESSAGE HANDLING + /// + /// Invoked by to update the transform state + /// + /// + internal void TransformStateUpdate(ref NetworkTransformState networkTransformState, ulong senderId) + { + if (CanCommitToTransform) + { + Debug.LogError($"Authority receiving transform update from Client-{senderId}!"); + } // Store the previous/old state m_OldState = m_LocalAuthoritativeNetworkState; - // Save the current payload stream position - var currentPosition = messagePayload.Position; + // Assign the new incoming state + m_LocalAuthoritativeNetworkState = networkTransformState; - // Deserialize the message (and determine network delivery) - messagePayload.ReadNetworkSerializableInPlace(ref m_LocalAuthoritativeNetworkState); - - // Rewind back prior to serialization - messagePayload.Seek(currentPosition); - - // Get the network delivery method used to send this state update - var networkDelivery = m_LocalAuthoritativeNetworkState.ReliableSequenced ? NetworkDelivery.ReliableSequenced : NetworkDelivery.UnreliableSequenced; - - // Forward owner authoritative messages before doing anything else - if (ownerAuthoritativeServerSide) - { - // Forward the state update if there are any remote clients to foward it to - if (m_CachedNetworkManager.ConnectionManager.ConnectedClientsList.Count > (IsHost ? 2 : 1)) - { - ForwardStateUpdateMessage(messagePayload, networkDelivery); - } - } - - // Apply the message + // Apply the state update OnNetworkStateChanged(m_OldState, m_LocalAuthoritativeNetworkState); } /// - /// Forwards owner authoritative state updates when received by the server - /// - /// the owner state message payload - private unsafe void ForwardStateUpdateMessage(FastBufferReader messagePayload, NetworkDelivery networkDelivery) - { - var serverAuthoritative = OnIsServerAuthoritative(); - var currentPosition = messagePayload.Position; - var messageSize = messagePayload.Length - currentPosition; - var writer = new FastBufferWriter(messageSize, Allocator.Temp); - using (writer) - { - writer.WriteBytesSafe(messagePayload.GetUnsafePtr(), messageSize, currentPosition); - - var clientCount = m_CachedNetworkManager.ConnectionManager.ConnectedClientsList.Count; - for (int i = 0; i < clientCount; i++) - { - var clientId = m_CachedNetworkManager.ConnectionManager.ConnectedClientsList[i].ClientId; - if (NetworkManager.ServerClientId == clientId || (!serverAuthoritative && clientId == OwnerClientId)) - { - continue; - } - m_CachedNetworkManager.CustomMessagingManager.SendNamedMessage(m_MessageName, clientId, writer, networkDelivery); - } - } - messagePayload.Seek(currentPosition); - } - - /// - /// Sends named message updates by the authority of the transform + /// Invoked by the authoritative instance to sends a containing the /// private void UpdateTransformState() { @@ -3248,7 +3394,16 @@ namespace Unity.Netcode.Components } var customMessageManager = m_CachedNetworkManager.CustomMessagingManager; - var writer = new FastBufferWriter(128, Allocator.Temp); + var networkTransformMessage = new NetworkTransformMessage() + { + NetworkObjectId = NetworkObjectId, + NetworkBehaviourId = NetworkBehaviourId, + State = m_LocalAuthoritativeNetworkState, + DistributedAuthorityMode = m_CachedNetworkManager.DistributedAuthorityMode, + // Don't populate if we are the DAHost as we send directly to each client + TargetIds = m_CachedNetworkManager.DistributedAuthorityMode && !m_CachedNetworkManager.DAHost ? NetworkObject.Observers.Where((c) => c != m_CachedNetworkManager.LocalClientId).ToArray() : null, + }; + // Determine what network delivery method to use: // When to send reliable packets: @@ -3259,33 +3414,69 @@ namespace Unity.Netcode.Components | m_LocalAuthoritativeNetworkState.UnreliableFrameSync | m_LocalAuthoritativeNetworkState.SynchronizeBaseHalfFloat ? NetworkDelivery.ReliableSequenced : NetworkDelivery.UnreliableSequenced; - using (writer) + // Server-host-dahost always sends updates to all clients (but itself) + if (IsServer) { - writer.WriteNetworkSerializable(m_LocalAuthoritativeNetworkState); - // Server-host always sends updates to all clients (but itself) - if (IsServer) + var clientCount = m_CachedNetworkManager.ConnectionManager.ConnectedClientsList.Count; + for (int i = 0; i < clientCount; i++) { - var clientCount = m_CachedNetworkManager.ConnectionManager.ConnectedClientsList.Count; - for (int i = 0; i < clientCount; i++) + var clientId = m_CachedNetworkManager.ConnectionManager.ConnectedClientsList[i].ClientId; + if (NetworkManager.ServerClientId == clientId) { - var clientId = m_CachedNetworkManager.ConnectionManager.ConnectedClientsList[i].ClientId; - if (NetworkManager.ServerClientId == clientId) - { - continue; - } - customMessageManager.SendNamedMessage(m_MessageName, clientId, writer, networkDelivery); + continue; } - } - else - { - // Clients (owner authoritative) send messages to the server-host - customMessageManager.SendNamedMessage(m_MessageName, NetworkManager.ServerClientId, writer, networkDelivery); + if (!NetworkObject.Observers.Contains(clientId)) + { + continue; + } + NetworkManager.MessageManager.SendMessage(ref networkTransformMessage, networkDelivery, clientId); } } + else + { + // Clients (owner authoritative) send messages to the server-host + NetworkManager.MessageManager.SendMessage(ref networkTransformMessage, networkDelivery, NetworkManager.ServerClientId); + } + } + #endregion + + #region NETWORK TICK REGISTRATOIN AND HANDLING + private static Dictionary s_NetworkTickRegistration = new Dictionary(); + + internal static float GetTickLatency(NetworkManager networkManager) + { + if (s_NetworkTickRegistration.ContainsKey(networkManager)) + { + return s_NetworkTickRegistration[networkManager].TicksAgo; + } + return 0f; } + /// + /// Returns the number of ticks (fractional) a client is latent relative + /// to its current RTT. + /// + public static float GetTickLatency() + { + return GetTickLatency(NetworkManager.Singleton); + } - private static Dictionary s_NetworkTickRegistration = new Dictionary(); + internal static float GetTickLatencyInSeconds(NetworkManager networkManager) + { + if (s_NetworkTickRegistration.ContainsKey(networkManager)) + { + return s_NetworkTickRegistration[networkManager].TicksAgoInSeconds(); + } + return 0f; + } + + /// + /// Returns the tick latency in seconds (typically fractional) + /// + public static float GetTickLatencyInSeconds() + { + return GetTickLatencyInSeconds(NetworkManager.Singleton); + } private static void RemoveTickUpdate(NetworkManager networkManager) { @@ -3316,12 +3507,37 @@ namespace Unity.Netcode.Components RemoveTickUpdate(m_NetworkManager); } + internal float TicksAgoInSeconds() + { + return Mathf.Max(1.0f, TicksAgo) * m_TickFrequency; + } + /// /// Invoked once per network tick, this will update any registered /// authority instances. /// private void TickUpdate() { + if (m_UnityTransport != null) + { + // Determine the desired ticks ago by the RTT (this really should be the combination of the + // authority and non-authority 1/2 RTT but in the end anything beyond 300ms is considered very poor + // network quality so latent interpolation is going to be expected). + var rtt = Mathf.Max(m_TickInMS, m_UnityTransport.GetCurrentRtt(NetworkManager.ServerClientId)); + m_TicksAgoSamples[m_TickSampleIndex] = Mathf.Max(1, (int)(rtt * m_TickFrequency)); + var tickAgoSum = 0.0f; + foreach (var tickAgo in m_TicksAgoSamples) + { + tickAgoSum += tickAgo; + } + m_PreviousTicksAgo = TicksAgo; + TicksAgo = Mathf.Lerp(m_PreviousTicksAgo, tickAgoSum / m_TickRate, m_TickFrequency); + m_TickSampleIndex = (m_TickSampleIndex + 1) % m_TickRate; + // Get the partial tick value for when this is all calculated to provide an offset for determining + // the relative starting interpolation point for the next update + Offset = m_OffsetTickFrequency * (Mathf.Max(2, TicksAgo) - (int)TicksAgo); + } + // TODO FIX: The local NetworkTickSystem can invoke with the same network tick as before if (m_NetworkManager.ServerTime.Tick <= m_LastTick) { @@ -3331,17 +3547,45 @@ namespace Unity.Netcode.Components { if (networkTransform.IsSpawned) { - networkTransform.NetworkTickSystem_Tick(); + networkTransform.OnNetworkTick(); } } m_LastTick = m_NetworkManager.ServerTime.Tick; } + + private UnityTransport m_UnityTransport; + private float m_TickFrequency; + private float m_OffsetTickFrequency; + private ulong m_TickInMS; + private int m_TickSampleIndex; + private int m_TickRate; + public float TicksAgo { get; private set; } + public float Offset { get; private set; } + private float m_PreviousTicksAgo; + + private List m_TicksAgoSamples = new List(); + public NetworkTransformTickRegistration(NetworkManager networkManager) { m_NetworkManager = networkManager; m_NetworkTickUpdate = new Action(TickUpdate); networkManager.NetworkTickSystem.Tick += m_NetworkTickUpdate; + m_TickRate = (int)m_NetworkManager.NetworkConfig.TickRate; + m_TickFrequency = 1.0f / m_TickRate; + // For the offset, it uses the fractional remainder of the tick to determine the offset. + // In order to keep within tick boundaries, we increment the tick rate by 1 to assure it + // will always be < the tick frequency. + m_OffsetTickFrequency = 1.0f / (m_TickRate + 1); + m_TickInMS = (ulong)(1000 * m_TickFrequency); + m_UnityTransport = m_NetworkManager.NetworkConfig.NetworkTransport as UnityTransport; + // Fill the sample with a starting value of 1 + for (int i = 0; i < m_TickRate; i++) + { + m_TicksAgoSamples.Add(1f); + } + TicksAgo = 1f; + m_PreviousTicksAgo = 1f; if (networkManager.IsServer) { networkManager.OnServerStopped += OnNetworkManagerStopped; @@ -3361,6 +3605,14 @@ namespace Unity.Netcode.Components m_NextTickSync = NetworkManager.ServerTime.Tick + (s_TickSynchPosition % (int)NetworkManager.NetworkConfig.TickRate); } + private static void RegisterNetworkManagerForTickUpdate(NetworkManager networkManager) + { + if (!s_NetworkTickRegistration.ContainsKey(networkManager)) + { + s_NetworkTickRegistration.Add(networkManager, new NetworkTransformTickRegistration(networkManager)); + } + } + /// /// Will register the NetworkTransform instance for the single tick update entry point. /// If a NetworkTransformTickRegistration has not yet been registered for the NetworkManager @@ -3369,31 +3621,38 @@ namespace Unity.Netcode.Components /// private static void RegisterForTickUpdate(NetworkTransform networkTransform) { - if (!s_NetworkTickRegistration.ContainsKey(networkTransform.NetworkManager)) + + if (!networkTransform.NetworkManager.DistributedAuthorityMode && !s_NetworkTickRegistration.ContainsKey(networkTransform.NetworkManager)) { s_NetworkTickRegistration.Add(networkTransform.NetworkManager, new NetworkTransformTickRegistration(networkTransform.NetworkManager)); } + networkTransform.RegisterForTickSynchronization(); s_NetworkTickRegistration[networkTransform.NetworkManager].NetworkTransforms.Add(networkTransform); } /// /// If a NetworkTransformTickRegistration exists for the NetworkManager instance, then this will - /// remove the NetworkTransform instance from the single tick update entry point. + /// remove the NetworkTransform instance from the single tick update entry point. /// /// private static void DeregisterForTickUpdate(NetworkTransform networkTransform) { + if (networkTransform.NetworkManager == null) + { + return; + } if (s_NetworkTickRegistration.ContainsKey(networkTransform.NetworkManager)) { s_NetworkTickRegistration[networkTransform.NetworkManager].NetworkTransforms.Remove(networkTransform); - if (s_NetworkTickRegistration[networkTransform.NetworkManager].NetworkTransforms.Count == 0) + if (!networkTransform.NetworkManager.DistributedAuthorityMode && s_NetworkTickRegistration[networkTransform.NetworkManager].NetworkTransforms.Count == 0) { var registrationEntry = s_NetworkTickRegistration[networkTransform.NetworkManager]; registrationEntry.Remove(); } } } + #endregion } internal interface INetworkTransformLogStateEntry diff --git a/Components/RigidbodyContactEventManager.cs b/Components/RigidbodyContactEventManager.cs new file mode 100644 index 0000000..9471a94 --- /dev/null +++ b/Components/RigidbodyContactEventManager.cs @@ -0,0 +1,230 @@ +#if COM_UNITY_MODULES_PHYSICS +using System.Collections.Generic; +using Unity.Collections; +using Unity.Jobs; +using UnityEngine; + +namespace Unity.Netcode.Components +{ + public interface IContactEventHandler + { + Rigidbody GetRigidbody(); + + void ContactEvent(ulong eventId, Vector3 averagedCollisionNormal, Rigidbody collidingBody, Vector3 contactPoint, bool hasCollisionStay = false, Vector3 averagedCollisionStayNormal = default); + } + + [AddComponentMenu("Netcode/Rigidbody Contact Event Manager")] + public class RigidbodyContactEventManager : MonoBehaviour + { + public static RigidbodyContactEventManager Instance { get; private set; } + + private struct JobResultStruct + { + public bool HasCollisionStay; + public int ThisInstanceID; + public int OtherInstanceID; + public Vector3 AverageNormal; + public Vector3 AverageCollisionStayNormal; + public Vector3 ContactPoint; + } + + private NativeArray m_ResultsArray; + private int m_Count = 0; + private JobHandle m_JobHandle; + + private readonly Dictionary m_RigidbodyMapping = new Dictionary(); + private readonly Dictionary m_HandlerMapping = new Dictionary(); + + private void OnEnable() + { + m_ResultsArray = new NativeArray(16, Allocator.Persistent); + Physics.ContactEvent += Physics_ContactEvent; + if (Instance != null) + { + NetworkLog.LogError($"[Invalid][Multiple Instances] Found more than one instance of {nameof(RigidbodyContactEventManager)}: {name} and {Instance.name}"); + NetworkLog.LogError($"[Disable][Additional Instance] Disabling {name} instance!"); + gameObject.SetActive(false); + return; + } + Instance = this; + } + + public void RegisterHandler(IContactEventHandler contactEventHandler, bool register = true) + { + var rigidbody = contactEventHandler.GetRigidbody(); + var instanceId = rigidbody.GetInstanceID(); + if (register) + { + if (!m_RigidbodyMapping.ContainsKey(instanceId)) + { + m_RigidbodyMapping.Add(instanceId, rigidbody); + } + + if (!m_HandlerMapping.ContainsKey(instanceId)) + { + m_HandlerMapping.Add(instanceId, contactEventHandler); + } + } + else + { + m_RigidbodyMapping.Remove(instanceId); + m_HandlerMapping.Remove(instanceId); + } + } + + private void OnDisable() + { + m_JobHandle.Complete(); + m_ResultsArray.Dispose(); + + Physics.ContactEvent -= Physics_ContactEvent; + + m_RigidbodyMapping.Clear(); + Instance = null; + } + + private bool m_HasCollisions; + private int m_CurrentCount = 0; + + private void ProcessCollisions() + { + // Process all collisions + for (int i = 0; i < m_Count; i++) + { + var thisInstanceID = m_ResultsArray[i].ThisInstanceID; + var otherInstanceID = m_ResultsArray[i].OtherInstanceID; + var rb0Valid = thisInstanceID != 0 && m_RigidbodyMapping.ContainsKey(thisInstanceID); + var rb1Valid = otherInstanceID != 0 && m_RigidbodyMapping.ContainsKey(otherInstanceID); + // Only notify registered rigid bodies. + if (!rb0Valid || !rb1Valid || !m_HandlerMapping.ContainsKey(thisInstanceID)) + { + continue; + } + if (m_ResultsArray[i].HasCollisionStay) + { + m_HandlerMapping[thisInstanceID].ContactEvent(m_EventId, m_ResultsArray[i].AverageNormal, m_RigidbodyMapping[otherInstanceID], m_ResultsArray[i].ContactPoint, m_ResultsArray[i].HasCollisionStay, m_ResultsArray[i].AverageCollisionStayNormal); + } + else + { + m_HandlerMapping[thisInstanceID].ContactEvent(m_EventId, m_ResultsArray[i].AverageNormal, m_RigidbodyMapping[otherInstanceID], m_ResultsArray[i].ContactPoint); + } + } + } + + private void FixedUpdate() + { + // Only process new collisions + if (!m_HasCollisions && m_CurrentCount == 0) + { + return; + } + + // This assures we won't process the same collision + // set after it has been processed. + if (m_HasCollisions) + { + m_CurrentCount = m_Count; + m_HasCollisions = false; + m_JobHandle.Complete(); + } + ProcessCollisions(); + } + + private void LateUpdate() + { + m_CurrentCount = 0; + } + + private ulong m_EventId; + private void Physics_ContactEvent(PhysicsScene scene, NativeArray.ReadOnly pairHeaders) + { + m_EventId++; + m_HasCollisions = true; + int n = pairHeaders.Length; + if (m_ResultsArray.Length < n) + { + m_ResultsArray.Dispose(); + m_ResultsArray = new NativeArray(Mathf.NextPowerOfTwo(n), Allocator.Persistent); + } + m_Count = n; + var job = new GetCollisionsJob() + { + PairedHeaders = pairHeaders, + ResultsArray = m_ResultsArray + }; + m_JobHandle = job.Schedule(n, 256); + } + + private struct GetCollisionsJob : IJobParallelFor + { + [ReadOnly] + public NativeArray.ReadOnly PairedHeaders; + + public NativeArray ResultsArray; + + public void Execute(int index) + { + Vector3 averageNormal = Vector3.zero; + Vector3 averagePoint = Vector3.zero; + Vector3 averageCollisionStay = Vector3.zero; + int count = 0; + int collisionStaycount = 0; + int positionCount = 0; + for (int j = 0; j < PairedHeaders[index].pairCount; j++) + { + ref readonly var pair = ref PairedHeaders[index].GetContactPair(j); + + if (pair.isCollisionExit) + { + continue; + } + + for (int k = 0; k < pair.contactCount; k++) + { + ref readonly var contact = ref pair.GetContactPoint(k); + averagePoint += contact.position; + positionCount++; + if (!pair.isCollisionStay) + { + averageNormal += contact.normal; + count++; + } + else + { + averageCollisionStay += contact.normal; + collisionStaycount++; + } + } + } + + if (count != 0) + { + averageNormal /= count; + } + + if (collisionStaycount != 0) + { + averageCollisionStay /= collisionStaycount; + } + + if (positionCount != 0) + { + averagePoint /= positionCount; + } + + var result = new JobResultStruct() + { + ThisInstanceID = PairedHeaders[index].bodyInstanceID, + OtherInstanceID = PairedHeaders[index].otherBodyInstanceID, + AverageNormal = averageNormal, + HasCollisionStay = collisionStaycount != 0, + AverageCollisionStayNormal = averageCollisionStay, + ContactPoint = averagePoint + }; + + ResultsArray[index] = result; + } + } + } +} +#endif diff --git a/Components/RigidbodyContactEventManager.cs.meta b/Components/RigidbodyContactEventManager.cs.meta new file mode 100644 index 0000000..c0f2a00 --- /dev/null +++ b/Components/RigidbodyContactEventManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 739e5cee846b6384988f9a47e4691836 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/CodeGen/CodeGenHelpers.cs b/Editor/CodeGen/CodeGenHelpers.cs index 6368e5e..75387fa 100644 --- a/Editor/CodeGen/CodeGenHelpers.cs +++ b/Editor/CodeGen/CodeGenHelpers.cs @@ -21,6 +21,7 @@ namespace Unity.Netcode.Editor.CodeGen public const string NetcodeModuleName = "Unity.Netcode.Runtime.dll"; public const string RuntimeAssemblyName = "Unity.Netcode.Runtime"; + public const string ComponentsAssemblyName = "Unity.Netcode.Components"; public static readonly string NetworkBehaviour_FullName = typeof(NetworkBehaviour).FullName; public static readonly string INetworkMessage_FullName = typeof(INetworkMessage).FullName; diff --git a/Editor/CodeGen/INetworkMessageILPP.cs b/Editor/CodeGen/INetworkMessageILPP.cs index 23436bf..d74b737 100644 --- a/Editor/CodeGen/INetworkMessageILPP.cs +++ b/Editor/CodeGen/INetworkMessageILPP.cs @@ -17,7 +17,7 @@ namespace Unity.Netcode.Editor.CodeGen { public override ILPPInterface GetInstance() => this; - public override bool WillProcess(ICompiledAssembly compiledAssembly) => compiledAssembly.Name == CodeGenHelpers.RuntimeAssemblyName; + public override bool WillProcess(ICompiledAssembly compiledAssembly) => compiledAssembly.Name == CodeGenHelpers.RuntimeAssemblyName || compiledAssembly.Name == CodeGenHelpers.ComponentsAssemblyName; private readonly List m_Diagnostics = new List(); diff --git a/Editor/CodeGen/NetworkBehaviourILPP.cs b/Editor/CodeGen/NetworkBehaviourILPP.cs index 55a195f..974b492 100644 --- a/Editor/CodeGen/NetworkBehaviourILPP.cs +++ b/Editor/CodeGen/NetworkBehaviourILPP.cs @@ -31,6 +31,43 @@ namespace Unity.Netcode.Editor.CodeGen private readonly List m_Diagnostics = new List(); + public void AddWrappedType(TypeReference wrappedType) + { + if (!m_WrappedNetworkVariableTypes.Contains(wrappedType)) + { + m_WrappedNetworkVariableTypes.Add(wrappedType); + + var resolved = wrappedType.Resolve(); + if (resolved != null) + { + if (resolved.FullName == "System.Collections.Generic.List`1") + { + AddWrappedType(((GenericInstanceType)wrappedType).GenericArguments[0]); + } + if (resolved.FullName == "System.Collections.Generic.HashSet`1") + { + AddWrappedType(((GenericInstanceType)wrappedType).GenericArguments[0]); + } + else if (resolved.FullName == "System.Collections.Generic.Dictionary`2") + { + AddWrappedType(((GenericInstanceType)wrappedType).GenericArguments[0]); + AddWrappedType(((GenericInstanceType)wrappedType).GenericArguments[1]); + } +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + else if (resolved.FullName == "Unity.Collections.NativeHashSet`1") + { + AddWrappedType(((GenericInstanceType)wrappedType).GenericArguments[0]); + } + else if (resolved.FullName == "Unity.Collections.NativeHashMap`2") + { + AddWrappedType(((GenericInstanceType)wrappedType).GenericArguments[0]); + AddWrappedType(((GenericInstanceType)wrappedType).GenericArguments[1]); + } +#endif + } + } + } + public override ILPostProcessResult Process(ICompiledAssembly compiledAssembly) { if (!WillProcess(compiledAssembly)) @@ -87,10 +124,7 @@ namespace Unity.Netcode.Editor.CodeGen if (attribute.AttributeType.Name == nameof(GenerateSerializationForTypeAttribute)) { var wrappedType = mainModule.ImportReference((TypeReference)attribute.ConstructorArguments[0].Value); - if (!m_WrappedNetworkVariableTypes.Contains(wrappedType)) - { - m_WrappedNetworkVariableTypes.Add(wrappedType); - } + AddWrappedType(wrappedType); } } @@ -101,10 +135,7 @@ namespace Unity.Netcode.Editor.CodeGen if (attribute.AttributeType.Name == nameof(GenerateSerializationForTypeAttribute)) { var wrappedType = mainModule.ImportReference((TypeReference)attribute.ConstructorArguments[0].Value); - if (!m_WrappedNetworkVariableTypes.Contains(wrappedType)) - { - m_WrappedNetworkVariableTypes.Add(wrappedType); - } + AddWrappedType(wrappedType); } } } @@ -241,6 +272,36 @@ namespace Unity.Netcode.Editor.CodeGen serializeMethod?.GenericArguments.Add(wrappedType); equalityMethod.GenericArguments.Add(wrappedType); } + else if (type.Resolve().FullName == "System.Collections.Generic.List`1") + { + var wrappedType = ((GenericInstanceType)type).GenericArguments[0]; + serializeMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeSerializer_List_MethodRef); + + equalityMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeEqualityChecker_List_MethodRef); + serializeMethod.GenericArguments.Add(wrappedType); + equalityMethod.GenericArguments.Add(wrappedType); + } + else if (type.Resolve().FullName == "System.Collections.Generic.HashSet`1") + { + var wrappedType = ((GenericInstanceType)type).GenericArguments[0]; + serializeMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeSerializer_HashSet_MethodRef); + + equalityMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeEqualityChecker_HashSet_MethodRef); + serializeMethod.GenericArguments.Add(wrappedType); + equalityMethod.GenericArguments.Add(wrappedType); + } + else if (type.Resolve().FullName == "System.Collections.Generic.Dictionary`2") + { + var wrappedKeyType = ((GenericInstanceType)type).GenericArguments[0]; + var wrappedValType = ((GenericInstanceType)type).GenericArguments[1]; + serializeMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeSerializer_Dictionary_MethodRef); + + equalityMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeEqualityChecker_Dictionary_MethodRef); + serializeMethod.GenericArguments.Add(wrappedKeyType); + serializeMethod.GenericArguments.Add(wrappedValType); + equalityMethod.GenericArguments.Add(wrappedKeyType); + equalityMethod.GenericArguments.Add(wrappedValType); + } #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT else if (type.Resolve().FullName == "Unity.Collections.NativeList`1") { @@ -267,12 +328,30 @@ namespace Unity.Netcode.Editor.CodeGen equalityMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEqualsList_MethodRef); } - if (serializeMethod != null) - { - serializeMethod.GenericArguments.Add(wrappedType); - } + serializeMethod?.GenericArguments.Add(wrappedType); equalityMethod.GenericArguments.Add(wrappedType); } + else if (type.Resolve().FullName == "Unity.Collections.NativeHashSet`1") + { + var wrappedType = ((GenericInstanceType)type).GenericArguments[0]; + serializeMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashSet_MethodRef); + + equalityMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashSet_MethodRef); + serializeMethod.GenericArguments.Add(wrappedType); + equalityMethod.GenericArguments.Add(wrappedType); + } + else if (type.Resolve().FullName == "Unity.Collections.NativeHashMap`2") + { + var wrappedKeyType = ((GenericInstanceType)type).GenericArguments[0]; + var wrappedValType = ((GenericInstanceType)type).GenericArguments[1]; + serializeMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashMap_MethodRef); + + equalityMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashMap_MethodRef); + serializeMethod.GenericArguments.Add(wrappedKeyType); + serializeMethod.GenericArguments.Add(wrappedValType); + equalityMethod.GenericArguments.Add(wrappedKeyType); + equalityMethod.GenericArguments.Add(wrappedValType); + } #endif else if (type.IsValueType) { @@ -398,7 +477,12 @@ namespace Unity.Netcode.Editor.CodeGen private MethodReference m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializableArray_MethodRef; #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT private MethodReference m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializableList_MethodRef; + private MethodReference m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashSet_MethodRef; + private MethodReference m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashMap_MethodRef; #endif + private MethodReference m_NetworkVariableSerializationTypes_InitializeSerializer_List_MethodRef; + private MethodReference m_NetworkVariableSerializationTypes_InitializeSerializer_HashSet_MethodRef; + private MethodReference m_NetworkVariableSerializationTypes_InitializeSerializer_Dictionary_MethodRef; private MethodReference m_NetworkVariableSerializationTypes_InitializeSerializer_ManagedINetworkSerializable_MethodRef; private MethodReference m_NetworkVariableSerializationTypes_InitializeSerializer_FixedString_MethodRef; private MethodReference m_NetworkVariableSerializationTypes_InitializeSerializer_FixedStringArray_MethodRef; @@ -415,7 +499,12 @@ namespace Unity.Netcode.Editor.CodeGen private MethodReference m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEqualsArray_MethodRef; #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT private MethodReference m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEqualsList_MethodRef; + private MethodReference m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashSet_MethodRef; + private MethodReference m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashMap_MethodRef; #endif + private MethodReference m_NetworkVariableSerializationTypes_InitializeEqualityChecker_List_MethodRef; + private MethodReference m_NetworkVariableSerializationTypes_InitializeEqualityChecker_HashSet_MethodRef; + private MethodReference m_NetworkVariableSerializationTypes_InitializeEqualityChecker_Dictionary_MethodRef; private MethodReference m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef; private MethodReference m_RuntimeInitializeOnLoadAttribute_Ctor; @@ -940,7 +1029,22 @@ namespace Unity.Netcode.Editor.CodeGen case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedINetworkSerializableList): m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializableList_MethodRef = method; break; + case nameof(NetworkVariableSerializationTypes.InitializeSerializer_NativeHashSet): + m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashSet_MethodRef = method; + break; + case nameof(NetworkVariableSerializationTypes.InitializeSerializer_NativeHashMap): + m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashMap_MethodRef = method; + break; #endif + case nameof(NetworkVariableSerializationTypes.InitializeSerializer_List): + m_NetworkVariableSerializationTypes_InitializeSerializer_List_MethodRef = method; + break; + case nameof(NetworkVariableSerializationTypes.InitializeSerializer_HashSet): + m_NetworkVariableSerializationTypes_InitializeSerializer_HashSet_MethodRef = method; + break; + case nameof(NetworkVariableSerializationTypes.InitializeSerializer_Dictionary): + m_NetworkVariableSerializationTypes_InitializeSerializer_Dictionary_MethodRef = method; + break; case nameof(NetworkVariableSerializationTypes.InitializeSerializer_ManagedINetworkSerializable): m_NetworkVariableSerializationTypes_InitializeSerializer_ManagedINetworkSerializable_MethodRef = method; break; @@ -971,7 +1075,22 @@ namespace Unity.Netcode.Editor.CodeGen case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatableList): m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatableList_MethodRef = method; break; + case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_NativeHashSet): + m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashSet_MethodRef = method; + break; + case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_NativeHashMap): + m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashMap_MethodRef = method; + break; #endif + case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_List): + m_NetworkVariableSerializationTypes_InitializeEqualityChecker_List_MethodRef = method; + break; + case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_HashSet): + m_NetworkVariableSerializationTypes_InitializeEqualityChecker_HashSet_MethodRef = method; + break; + case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_Dictionary): + m_NetworkVariableSerializationTypes_InitializeEqualityChecker_Dictionary_MethodRef = method; + break; case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEquals): m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEquals_MethodRef = method; break; @@ -1246,10 +1365,7 @@ namespace Unity.Netcode.Editor.CodeGen continue; } var wrappedType = genericInstanceType.GenericArguments[idx]; - if (!m_WrappedNetworkVariableTypes.Contains(wrappedType)) - { - m_WrappedNetworkVariableTypes.Add(wrappedType); - } + AddWrappedType(wrappedType); } } } @@ -1282,10 +1398,7 @@ namespace Unity.Netcode.Editor.CodeGen continue; } var wrappedType = genericInstanceType.GenericArguments[idx]; - if (!m_WrappedNetworkVariableTypes.Contains(wrappedType)) - { - m_WrappedNetworkVariableTypes.Add(wrappedType); - } + AddWrappedType(wrappedType); } } } diff --git a/Editor/Configuration/NetcodeSettingsProvider.cs b/Editor/Configuration/NetcodeSettingsProvider.cs index ce8023b..8a814ac 100644 --- a/Editor/Configuration/NetcodeSettingsProvider.cs +++ b/Editor/Configuration/NetcodeSettingsProvider.cs @@ -19,7 +19,7 @@ namespace Unity.Netcode.Editor.Configuration { // First parameter is the path in the Settings window. // Second parameter is the scope of this setting: it only appears in the Settings window for the Project scope. - var provider = new SettingsProvider("Project/NetcodeForGameObjects", SettingsScope.Project) + var provider = new SettingsProvider("Project/Multiplayer/NetcodeForGameObjects", SettingsScope.Project) { label = "Netcode for GameObjects", keywords = new[] { "netcode", "editor" }, diff --git a/Editor/NetworkManagerEditor.cs b/Editor/NetworkManagerEditor.cs index 1713ba2..011fe5d 100644 --- a/Editor/NetworkManagerEditor.cs +++ b/Editor/NetworkManagerEditor.cs @@ -1,6 +1,3 @@ -#if UNITY_2022_3_OR_NEWER && (RELAY_SDK_INSTALLED && !UNITY_WEBGL ) || (RELAY_SDK_INSTALLED && UNITY_WEBGL && UTP_TRANSPORT_2_0_ABOVE) -#define RELAY_INTEGRATION_AVAILABLE -#endif using System; using System.Collections.Generic; using System.IO; @@ -33,7 +30,7 @@ namespace Unity.Netcode.Editor private SerializedProperty m_ProtocolVersionProperty; private SerializedProperty m_NetworkTransportProperty; private SerializedProperty m_TickRateProperty; - private SerializedProperty m_MaxObjectUpdatesPerTickProperty; + private SerializedProperty m_SessionModeProperty; private SerializedProperty m_ClientConnectionBufferTimeoutProperty; private SerializedProperty m_ConnectionApprovalProperty; private SerializedProperty m_EnsureNetworkVariableLengthSafetyProperty; @@ -41,6 +38,7 @@ namespace Unity.Netcode.Editor private SerializedProperty m_EnableSceneManagementProperty; private SerializedProperty m_RecycleNetworkIdsProperty; private SerializedProperty m_NetworkIdRecycleDelayProperty; + private SerializedProperty m_SpawnTimeOutProperty; private SerializedProperty m_RpcHashSizeProperty; private SerializedProperty m_LoadSceneTimeOutProperty; private SerializedProperty m_PrefabsList; @@ -51,27 +49,6 @@ namespace Unity.Netcode.Editor private readonly List m_TransportTypes = new List(); private string[] m_TransportNames = { "Select transport..." }; - /// - public override void OnInspectorGUI() - { - Initialize(); - CheckNullProperties(); - -#if !MULTIPLAYER_TOOLS - DrawInstallMultiplayerToolsTip(); -#endif - - if (m_NetworkManager.IsServer || m_NetworkManager.IsClient) - { - DrawDisconnectButton(); - } - else - { - DrawAllPropertyFields(); - ShowStartConnectionButtons(); - } - } - private void ReloadTransports() { m_TransportTypes.Clear(); @@ -120,15 +97,20 @@ namespace Unity.Netcode.Editor m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion"); m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport"); m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate"); + m_SessionModeProperty = m_NetworkConfigProperty.FindPropertyRelative("SessionMode"); m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout"); m_ConnectionApprovalProperty = m_NetworkConfigProperty.FindPropertyRelative("ConnectionApproval"); m_EnsureNetworkVariableLengthSafetyProperty = m_NetworkConfigProperty.FindPropertyRelative("EnsureNetworkVariableLengthSafety"); m_ForceSamePrefabsProperty = m_NetworkConfigProperty.FindPropertyRelative("ForceSamePrefabs"); - m_EnableSceneManagementProperty = m_NetworkConfigProperty.FindPropertyRelative("EnableSceneManagement"); m_RecycleNetworkIdsProperty = m_NetworkConfigProperty.FindPropertyRelative("RecycleNetworkIds"); m_NetworkIdRecycleDelayProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkIdRecycleDelay"); - m_RpcHashSizeProperty = m_NetworkConfigProperty.FindPropertyRelative("RpcHashSize"); + + m_EnableSceneManagementProperty = m_NetworkConfigProperty.FindPropertyRelative("EnableSceneManagement"); + m_SpawnTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("SpawnTimeout"); m_LoadSceneTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("LoadSceneTimeOut"); + + + m_RpcHashSizeProperty = m_NetworkConfigProperty.FindPropertyRelative("RpcHashSize"); m_PrefabsList = m_NetworkConfigProperty .FindPropertyRelative(nameof(NetworkConfig.Prefabs)) .FindPropertyRelative(nameof(NetworkPrefabs.NetworkPrefabsLists)); @@ -148,325 +130,213 @@ namespace Unity.Netcode.Editor m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion"); m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport"); m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate"); + m_SessionModeProperty = m_NetworkConfigProperty.FindPropertyRelative("SessionMode"); m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout"); m_ConnectionApprovalProperty = m_NetworkConfigProperty.FindPropertyRelative("ConnectionApproval"); m_EnsureNetworkVariableLengthSafetyProperty = m_NetworkConfigProperty.FindPropertyRelative("EnsureNetworkVariableLengthSafety"); m_ForceSamePrefabsProperty = m_NetworkConfigProperty.FindPropertyRelative("ForceSamePrefabs"); - m_EnableSceneManagementProperty = m_NetworkConfigProperty.FindPropertyRelative("EnableSceneManagement"); m_RecycleNetworkIdsProperty = m_NetworkConfigProperty.FindPropertyRelative("RecycleNetworkIds"); m_NetworkIdRecycleDelayProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkIdRecycleDelay"); - m_RpcHashSizeProperty = m_NetworkConfigProperty.FindPropertyRelative("RpcHashSize"); + + + m_EnableSceneManagementProperty = m_NetworkConfigProperty.FindPropertyRelative("EnableSceneManagement"); + m_SpawnTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("SpawnTimeout"); m_LoadSceneTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("LoadSceneTimeOut"); + + m_RpcHashSizeProperty = m_NetworkConfigProperty.FindPropertyRelative("RpcHashSize"); m_PrefabsList = m_NetworkConfigProperty .FindPropertyRelative(nameof(NetworkConfig.Prefabs)) .FindPropertyRelative(nameof(NetworkPrefabs.NetworkPrefabsLists)); } - private void DrawAllPropertyFields() + /// + public override void OnInspectorGUI() { - serializedObject.Update(); - EditorGUILayout.PropertyField(m_RunInBackgroundProperty); - EditorGUILayout.PropertyField(m_LogLevelProperty); - EditorGUILayout.Space(); + Initialize(); + CheckNullProperties(); - EditorGUILayout.PropertyField(m_PlayerPrefabProperty); - EditorGUILayout.Space(); - - DrawPrefabListField(); - - EditorGUILayout.Space(); - - EditorGUILayout.LabelField("General", EditorStyles.boldLabel); - EditorGUILayout.PropertyField(m_ProtocolVersionProperty); - - DrawTransportField(); - - EditorGUILayout.PropertyField(m_TickRateProperty); - - EditorGUILayout.LabelField("Performance", EditorStyles.boldLabel); - - EditorGUILayout.PropertyField(m_EnsureNetworkVariableLengthSafetyProperty); - - EditorGUILayout.LabelField("Connection", EditorStyles.boldLabel); - EditorGUILayout.PropertyField(m_ConnectionApprovalProperty); - - using (new EditorGUI.DisabledScope(!m_NetworkManager.NetworkConfig.ConnectionApproval)) - { - EditorGUILayout.PropertyField(m_ClientConnectionBufferTimeoutProperty); - } - - EditorGUILayout.LabelField("Spawning", EditorStyles.boldLabel); - EditorGUILayout.PropertyField(m_ForceSamePrefabsProperty); - - EditorGUILayout.PropertyField(m_RecycleNetworkIdsProperty); - - using (new EditorGUI.DisabledScope(!m_NetworkManager.NetworkConfig.RecycleNetworkIds)) - { - EditorGUILayout.PropertyField(m_NetworkIdRecycleDelayProperty); - } - - EditorGUILayout.LabelField("Bandwidth", EditorStyles.boldLabel); - EditorGUILayout.PropertyField(m_RpcHashSizeProperty); - - EditorGUILayout.LabelField("Scene Management", EditorStyles.boldLabel); - EditorGUILayout.PropertyField(m_EnableSceneManagementProperty); - - using (new EditorGUI.DisabledScope(!m_NetworkManager.NetworkConfig.EnableSceneManagement)) - { - EditorGUILayout.PropertyField(m_LoadSceneTimeOutProperty); - } - - serializedObject.ApplyModifiedProperties(); - } - - private void DrawTransportField() - { -#if RELAY_INTEGRATION_AVAILABLE - var useRelay = EditorPrefs.GetBool(k_UseEasyRelayIntegrationKey, false); -#else - var useRelay = false; +#if !MULTIPLAYER_TOOLS + DrawInstallMultiplayerToolsTip(); #endif - if (useRelay) + if (!m_NetworkManager.IsServer && !m_NetworkManager.IsClient) { - EditorGUILayout.HelpBox("Test connection with relay is enabled, so the default Unity Transport will be used", MessageType.Info); - GUI.enabled = false; + serializedObject.Update(); + EditorGUILayout.PropertyField(m_RunInBackgroundProperty); + EditorGUILayout.PropertyField(m_LogLevelProperty); + EditorGUILayout.PropertyField(m_SessionModeProperty); + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Network Settings", EditorStyles.boldLabel); + EditorGUILayout.PropertyField(m_ProtocolVersionProperty); EditorGUILayout.PropertyField(m_NetworkTransportProperty); - GUI.enabled = true; - return; - } - - EditorGUILayout.PropertyField(m_NetworkTransportProperty); - - if (m_NetworkTransportProperty.objectReferenceValue == null) - { - EditorGUILayout.HelpBox("You have no transport selected. A transport is required for netcode to work. Which one do you want?", MessageType.Warning); - - int selection = EditorGUILayout.Popup(0, m_TransportNames); - - if (selection > 0) + if (m_NetworkTransportProperty.objectReferenceValue == null) { - ReloadTransports(); + EditorGUILayout.HelpBox("You have no transport selected. A transport is required for netcode to work. Which one do you want?", MessageType.Warning); - var transportComponent = m_NetworkManager.gameObject.GetComponent(m_TransportTypes[selection - 1]) ?? m_NetworkManager.gameObject.AddComponent(m_TransportTypes[selection - 1]); - m_NetworkTransportProperty.objectReferenceValue = transportComponent; + int selection = EditorGUILayout.Popup(0, m_TransportNames); - Repaint(); + if (selection > 0) + { + ReloadTransports(); + + var transportComponent = m_NetworkManager.gameObject.GetComponent(m_TransportTypes[selection - 1]) ?? m_NetworkManager.gameObject.AddComponent(m_TransportTypes[selection - 1]); + m_NetworkTransportProperty.objectReferenceValue = transportComponent; + + Repaint(); + } } - } - } - -#if RELAY_INTEGRATION_AVAILABLE - private readonly string k_UseEasyRelayIntegrationKey = "NetworkManagerUI_UseRelay_" + Application.dataPath.GetHashCode(); - private string m_JoinCode = ""; - private string m_StartConnectionError = null; - private string m_Region = ""; - - // wait for next frame so that ImGui finishes the current frame - private static void RunNextFrame(Action action) => EditorApplication.delayCall += () => action(); -#endif - - private void ShowStartConnectionButtons() - { - EditorGUILayout.LabelField("Start Connection", EditorStyles.boldLabel); - -#if RELAY_INTEGRATION_AVAILABLE - // use editor prefs to persist the setting when entering / leaving play mode / exiting Unity - var useRelay = EditorPrefs.GetBool(k_UseEasyRelayIntegrationKey, false); - GUILayout.BeginHorizontal(); - useRelay = GUILayout.Toggle(useRelay, "Try Relay in the Editor"); - - var icon = EditorGUIUtility.IconContent("_Help"); - icon.tooltip = "This will help you test relay in the Editor. Click here to know how to integrate Relay in your build"; - if (GUILayout.Button(icon, GUIStyle.none, GUILayout.Width(20))) - { - Application.OpenURL("https://docs-multiplayer.unity3d.com/netcode/current/relay/"); - } - GUILayout.EndHorizontal(); - - EditorPrefs.SetBool(k_UseEasyRelayIntegrationKey, useRelay); - if (useRelay && !Application.isPlaying && !CloudProjectSettings.projectBound) - { - EditorGUILayout.HelpBox("To use relay, you need to setup your project in the Project Settings in the Services section.", MessageType.Warning); - if (GUILayout.Button("Open Project settings")) + EditorGUILayout.PropertyField(m_TickRateProperty); + EditorGUILayout.PropertyField(m_SpawnTimeOutProperty); + EditorGUILayout.PropertyField(m_ConnectionApprovalProperty); + if (m_NetworkManager.NetworkConfig.ConnectionApproval) { - SettingsService.OpenProjectSettings("Project/Services"); + EditorGUILayout.PropertyField(m_ClientConnectionBufferTimeoutProperty); } - } + EditorGUILayout.PropertyField(m_EnsureNetworkVariableLengthSafetyProperty, new GUIContent("NetworkVariable Length Safety")); + EditorGUILayout.PropertyField(m_RecycleNetworkIdsProperty); + if (m_NetworkManager.NetworkConfig.RecycleNetworkIds) + { + EditorGUILayout.PropertyField(m_NetworkIdRecycleDelayProperty); + } + EditorGUILayout.PropertyField(m_RpcHashSizeProperty); + + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Prefab Settings", EditorStyles.boldLabel); + EditorGUILayout.PropertyField(m_ForceSamePrefabsProperty); + EditorGUILayout.PropertyField(m_PlayerPrefabProperty, new GUIContent("Default Player Prefab")); + + if (m_NetworkManager.NetworkConfig.HasOldPrefabList()) + { + EditorGUILayout.HelpBox("Network Prefabs serialized in old format. Migrate to new format to edit the list.", MessageType.Info); + if (GUILayout.Button(new GUIContent("Migrate Prefab List", "Converts the old format Network Prefab list to a new Scriptable Object"))) + { + // Default directory + var directory = "Assets/"; + var assetPath = AssetDatabase.GetAssetPath(m_NetworkManager); + if (assetPath == "") + { + assetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(m_NetworkManager); + } + + if (assetPath != "") + { + directory = Path.GetDirectoryName(assetPath); + } + else + { +#if UNITY_2021_1_OR_NEWER + var prefabStage = UnityEditor.SceneManagement.PrefabStageUtility.GetPrefabStage(m_NetworkManager.gameObject); #else - var useRelay = false; + var prefabStage = UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetPrefabStage(m_NetworkManager.gameObject); #endif + if (prefabStage != null) + { + var prefabPath = prefabStage.assetPath; + if (!string.IsNullOrEmpty(prefabPath)) + { + directory = Path.GetDirectoryName(prefabPath); + } + } + if (m_NetworkManager.gameObject.scene != null) + { + var scenePath = m_NetworkManager.gameObject.scene.path; + if (!string.IsNullOrEmpty(scenePath)) + { + directory = Path.GetDirectoryName(scenePath); + } + } + } + var networkPrefabs = m_NetworkManager.NetworkConfig.MigrateOldNetworkPrefabsToNetworkPrefabsList(); + string path = Path.Combine(directory, $"NetworkPrefabs-{m_NetworkManager.GetInstanceID()}.asset"); + Debug.Log("Saving migrated Network Prefabs List to " + path); + AssetDatabase.CreateAsset(networkPrefabs, path); + EditorUtility.SetDirty(m_NetworkManager); + } + } + else + { + if (m_NetworkManager.NetworkConfig.Prefabs.NetworkPrefabsLists.Count == 0) + { + EditorGUILayout.HelpBox("You have no prefab list selected. You will have to add your prefabs manually at runtime for netcode to work.", MessageType.Warning); + } + EditorGUILayout.PropertyField(m_PrefabsList); + } - string buttonDisabledReasonSuffix = ""; + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Scene Management Settings", EditorStyles.boldLabel); + EditorGUILayout.PropertyField(m_EnableSceneManagementProperty); + if (m_NetworkManager.NetworkConfig.EnableSceneManagement) + { + EditorGUILayout.PropertyField(m_LoadSceneTimeOutProperty); + } - if (!EditorApplication.isPlaying) - { - buttonDisabledReasonSuffix = ". This can only be done in play mode"; - GUI.enabled = false; - } + serializedObject.ApplyModifiedProperties(); - if (useRelay) - { - ShowStartConnectionButtons_Relay(buttonDisabledReasonSuffix); + + // Start buttons below + { + string buttonDisabledReasonSuffix = ""; + + if (!EditorApplication.isPlaying) + { + buttonDisabledReasonSuffix = ". This can only be done in play mode"; + GUI.enabled = false; + } + + if (GUILayout.Button(new GUIContent("Start Host", "Starts a host instance" + buttonDisabledReasonSuffix))) + { + m_NetworkManager.StartHost(); + } + + if (GUILayout.Button(new GUIContent("Start Server", "Starts a server instance" + buttonDisabledReasonSuffix))) + { + m_NetworkManager.StartServer(); + } + + if (GUILayout.Button(new GUIContent("Start Client", "Starts a client instance" + buttonDisabledReasonSuffix))) + { + m_NetworkManager.StartClient(); + } + + if (!EditorApplication.isPlaying) + { + GUI.enabled = true; + } + } } else { - ShowStartConnectionButtons_Standard(buttonDisabledReasonSuffix); - } + string instanceType = string.Empty; - if (!EditorApplication.isPlaying) - { - GUI.enabled = true; - } - } - - private void ShowStartConnectionButtons_Relay(string buttonDisabledReasonSuffix) - { -#if RELAY_INTEGRATION_AVAILABLE - - void AddStartServerOrHostButton(bool isServer) - { - var type = isServer ? "Server" : "Host"; - if (GUILayout.Button(new GUIContent($"Start {type}", $"Starts a {type} instance with Relay{buttonDisabledReasonSuffix}"))) + if (m_NetworkManager.IsHost) { - m_StartConnectionError = null; - RunNextFrame(async () => - { - try - { - var (joinCode, allocation) = isServer ? await m_NetworkManager.StartServerWithRelay() : await m_NetworkManager.StartHostWithRelay(); - m_JoinCode = joinCode; - m_Region = allocation.Region; - Repaint(); - } - catch (Exception e) - { - m_StartConnectionError = e.Message; - throw; - } - }); + instanceType = "Host"; } - } - - AddStartServerOrHostButton(isServer: true); - AddStartServerOrHostButton(isServer: false); - - GUILayout.Space(8f); - m_JoinCode = EditorGUILayout.TextField("Relay Join Code", m_JoinCode); - if (GUILayout.Button(new GUIContent("Start Client", "Starts a client instance with Relay" + buttonDisabledReasonSuffix))) - { - m_StartConnectionError = null; - RunNextFrame(async () => + else if (m_NetworkManager.IsServer) { - if (string.IsNullOrEmpty(m_JoinCode)) - { - m_StartConnectionError = "Please provide a join code!"; - return; - } - - try - { - var allocation = await m_NetworkManager.StartClientWithRelay(m_JoinCode); - m_Region = allocation.Region; - Repaint(); - } - catch (Exception e) - { - m_StartConnectionError = e.Message; - throw; - } - }); - } - - if (Application.isPlaying && !string.IsNullOrEmpty(m_StartConnectionError)) - { - EditorGUILayout.HelpBox(m_StartConnectionError, MessageType.Error); - } -#endif - } - - private void ShowStartConnectionButtons_Standard(string buttonDisabledReasonSuffix) - { - if (GUILayout.Button(new GUIContent("Start Host", "Starts a host instance" + buttonDisabledReasonSuffix))) - { - m_NetworkManager.StartHost(); - } - - if (GUILayout.Button(new GUIContent("Start Server", "Starts a server instance" + buttonDisabledReasonSuffix))) - { - m_NetworkManager.StartServer(); - } - - if (GUILayout.Button(new GUIContent("Start Client", "Starts a client instance" + buttonDisabledReasonSuffix))) - { - m_NetworkManager.StartClient(); - } - } - - private void DrawDisconnectButton() - { - string instanceType = string.Empty; - - if (m_NetworkManager.IsHost) - { - instanceType = "Host"; - } - else if (m_NetworkManager.IsServer) - { - instanceType = "Server"; - } - else if (m_NetworkManager.IsClient) - { - instanceType = "Client"; - } - - EditorGUILayout.HelpBox($"You cannot edit the NetworkConfig when a {instanceType} is running.", MessageType.Info); - -#if RELAY_INTEGRATION_AVAILABLE - if (!string.IsNullOrEmpty(m_JoinCode) && !string.IsNullOrEmpty(m_Region)) - { - var style = new GUIStyle(EditorStyles.helpBox) + instanceType = "Server"; + } + else if (m_NetworkManager.IsClient) { - fontSize = 10, - alignment = TextAnchor.MiddleCenter, - }; - - GUILayout.BeginHorizontal(style, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(false), GUILayout.MaxWidth(800)); - GUILayout.Label(new GUIContent(EditorGUIUtility.IconContent(k_InfoIconName)), GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(true)); - GUILayout.Space(25f); - GUILayout.BeginVertical(); - GUILayout.Space(4f); - GUILayout.Label($"Connected via relay ({m_Region}).\nJoin code: {m_JoinCode}", EditorStyles.miniLabel, GUILayout.ExpandHeight(true)); - - if (GUILayout.Button("Copy code", GUILayout.ExpandHeight(true))) - { - GUIUtility.systemCopyBuffer = m_JoinCode; + instanceType = "Client"; } - GUILayout.Space(4f); - GUILayout.EndVertical(); - GUILayout.Space(2f); - GUILayout.EndHorizontal(); - } -#endif + EditorGUILayout.HelpBox("You cannot edit the NetworkConfig when a " + instanceType + " is running.", MessageType.Info); - if (GUILayout.Button(new GUIContent($"Stop {instanceType}", $"Stops the {instanceType} instance."))) - { -#if RELAY_INTEGRATION_AVAILABLE - m_JoinCode = ""; -#endif - m_NetworkManager.Shutdown(); + if (GUILayout.Button(new GUIContent("Stop " + instanceType, "Stops the " + instanceType + " instance."))) + { + m_NetworkManager.Shutdown(); + } } } - private const string k_InfoIconName = "console.infoicon"; private static void DrawInstallMultiplayerToolsTip() { const string getToolsText = "Access additional tools for multiplayer development by installing the Multiplayer Tools package in the Package Manager."; const string openDocsButtonText = "Open Docs"; const string dismissButtonText = "Dismiss"; const string targetUrl = "https://docs-multiplayer.unity3d.com/tools/current/install-tools"; - + const string infoIconName = "console.infoicon"; if (NetcodeForGameObjectsEditorSettings.GetNetcodeInstallMultiplayerToolTips() != 0) { @@ -497,7 +367,7 @@ namespace Unity.Netcode.Editor GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(s_HelpBoxStyle, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(false), GUILayout.MaxWidth(800)); { - GUILayout.Label(new GUIContent(EditorGUIUtility.IconContent(k_InfoIconName)), GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(true)); + GUILayout.Label(new GUIContent(EditorGUIUtility.IconContent(infoIconName)), GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(true)); GUILayout.Space(4); GUILayout.Label(getToolsText, s_CenteredWordWrappedLabelStyle, GUILayout.ExpandHeight(true)); @@ -530,69 +400,5 @@ namespace Unity.Netcode.Editor GUILayout.Space(10); } - - private void DrawPrefabListField() - { - if (!m_NetworkManager.NetworkConfig.HasOldPrefabList()) - { - if (m_NetworkManager.NetworkConfig.Prefabs.NetworkPrefabsLists.Count == 0) - { - EditorGUILayout.HelpBox("You have no prefab list selected. You will have to add your prefabs manually at runtime for netcode to work.", MessageType.Warning); - } - - EditorGUILayout.PropertyField(m_PrefabsList); - return; - } - - // Old format of prefab list - EditorGUILayout.HelpBox("Network Prefabs serialized in old format. Migrate to new format to edit the list.", MessageType.Info); - if (GUILayout.Button(new GUIContent("Migrate Prefab List", "Converts the old format Network Prefab list to a new Scriptable Object"))) - { - // Default directory - var directory = "Assets/"; - var assetPath = AssetDatabase.GetAssetPath(m_NetworkManager); - if (assetPath == "") - { - assetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(m_NetworkManager); - } - - if (assetPath != "") - { - directory = Path.GetDirectoryName(assetPath); - } - else - { - -#if UNITY_2021_1_OR_NEWER - var prefabStage = UnityEditor.SceneManagement.PrefabStageUtility.GetPrefabStage(m_NetworkManager.gameObject); -#else - var prefabStage = UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetPrefabStage(m_NetworkManager.gameObject); -#endif - if (prefabStage != null) - { - var prefabPath = prefabStage.assetPath; - if (!string.IsNullOrEmpty(prefabPath)) - { - directory = Path.GetDirectoryName(prefabPath); - } - } - - if (m_NetworkManager.gameObject.scene != null) - { - var scenePath = m_NetworkManager.gameObject.scene.path; - if (!string.IsNullOrEmpty(scenePath)) - { - directory = Path.GetDirectoryName(scenePath); - } - } - } - - var networkPrefabs = m_NetworkManager.NetworkConfig.MigrateOldNetworkPrefabsToNetworkPrefabsList(); - string path = Path.Combine(directory, $"NetworkPrefabs-{m_NetworkManager.GetInstanceID()}.asset"); - Debug.Log("Saving migrated Network Prefabs List to " + path); - AssetDatabase.CreateAsset(networkPrefabs, path); - EditorUtility.SetDirty(m_NetworkManager); - } - } } } diff --git a/Editor/NetworkObjectEditor.cs b/Editor/NetworkObjectEditor.cs index 1b582f8..cc4b9d3 100644 --- a/Editor/NetworkObjectEditor.cs +++ b/Editor/NetworkObjectEditor.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; using UnityEditor; using UnityEngine; @@ -49,6 +50,10 @@ namespace Unity.Netcode.Editor { var guiEnabled = GUI.enabled; GUI.enabled = false; + if (m_NetworkObject.NetworkManager.DistributedAuthorityMode) + { + EditorGUILayout.PropertyField(serializedObject.FindProperty(nameof(NetworkObject.Ownership))); + } EditorGUILayout.TextField(nameof(NetworkObject.GlobalObjectIdHash), m_NetworkObject.GlobalObjectIdHash.ToString()); EditorGUILayout.TextField(nameof(NetworkObject.NetworkObjectId), m_NetworkObject.NetworkObjectId.ToString()); EditorGUILayout.TextField(nameof(NetworkObject.OwnerClientId), m_NetworkObject.OwnerClientId.ToString()); @@ -138,4 +143,49 @@ namespace Unity.Netcode.Editor NetworkBehaviourEditor.CheckForNetworkObject(m_GameObject, true); } } + + + [CustomPropertyDrawer(typeof(NetworkObject.OwnershipStatus))] + public class NetworkObjectOwnership : PropertyDrawer + { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) + { + label = EditorGUI.BeginProperty(position, label, property); + // Don't allow modification while in play mode + EditorGUI.BeginDisabledGroup(EditorApplication.isPlaying); + + // This is a temporary work around due to EditorGUI.EnumFlagsField having a bug in how it displays mask values. + // For now, we will just display the flags as a toggle and handle the masking of the value ourselves. + EditorGUILayout.BeginHorizontal(); + var names = System.Enum.GetNames(typeof(NetworkObject.OwnershipStatus)).ToList(); + names.RemoveAt(0); + var value = property.enumValueFlag; + var compareValue = 0x01; + GUILayout.Label(label); + foreach (var name in names) + { + var isSet = (value & compareValue) > 0; + isSet = GUILayout.Toggle(isSet, name); + if (isSet) + { + value |= compareValue; + } + else + { + value &= ~compareValue; + } + compareValue = compareValue << 1; + } + property.enumValueFlag = value; + EditorGUILayout.EndHorizontal(); + + // The below can cause visual anomalies and/or throws an exception within the EditorGUI itself (index out of bounds of the array). and has + // The visual anomaly is when you select one field it is set in the drop down but then the flags selection in the popup menu selects more items + // even though if you exit the popup menu the flag setting is correct. + //var ownership = (NetworkObject.OwnershipStatus)EditorGUI.EnumFlagsField(position, label, (NetworkObject.OwnershipStatus)property.enumValueFlag); + //property.enumValueFlag = (int)ownership; + EditorGUI.EndDisabledGroup(); + EditorGUI.EndProperty(); + } + } } diff --git a/LICENSE.md b/LICENSE.md index a5eb171..031978c 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,9 +1,7 @@ -MIT License +Unity Companion License (UCL License) -Copyright (c) 2021 Unity Technologies +com.unity.netcode.gameobjects copyright © 2021-2024 Unity Technologies +Licensed under the Unity Companion License for Unity-dependent projects (see https://unity3d.com/legal/licenses/unity_companion_license). +Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. Please review the license for details on these and other terms and conditions. -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Runtime/Configuration/NetworkConfig.cs b/Runtime/Configuration/NetworkConfig.cs index 9b855ec..ff806c6 100644 --- a/Runtime/Configuration/NetworkConfig.cs +++ b/Runtime/Configuration/NetworkConfig.cs @@ -129,9 +129,9 @@ namespace Unity.Netcode public int LoadSceneTimeOut = 120; /// - /// The amount of time a message should be buffered if the asset or object needed to process it doesn't exist yet. If the asset is not added/object is not spawned within this time, it will be dropped. + /// The amount of time a message will be held (deferred) if the destination NetworkObject needed to process the message doesn't exist yet. If the NetworkObject is not spawned within this time period, all deferred messages for that NetworkObject will be dropped. /// - [Tooltip("The amount of time a message should be buffered if the asset or object needed to process it doesn't exist yet. If the asset is not added/object is not spawned within this time, it will be dropped")] + [Tooltip("The amount of time a message will be held (deferred) if the destination NetworkObject needed to process the message doesn't exist yet. If the NetworkObject is not spawned within this time period, all deferred messages for that NetworkObject will be dropped.")] public float SpawnTimeout = 10f; /// @@ -149,6 +149,15 @@ namespace Unity.Netcode /// public const int RttWindowSize = 64; // number of slots to use for RTT computations (max number of in-flight packets) + [Tooltip("Determines if the network session will run in client-server or distributed authority mode.")] + public SessionModeTypes SessionMode; + + [HideInInspector] + public bool UseCMBService; + + [Tooltip("When enabled (default), the player prefab will automatically be spawned (client-side) upon the client being approved and synchronized.")] + public bool AutoSpawnPlayerPrefabClientSide = true; + /// /// Returns a base64 encoded version of the configuration /// diff --git a/Runtime/Connection/NetworkClient.cs b/Runtime/Connection/NetworkClient.cs index 370f651..63b24bd 100644 --- a/Runtime/Connection/NetworkClient.cs +++ b/Runtime/Connection/NetworkClient.cs @@ -1,7 +1,15 @@ using System.Collections.Generic; +using UnityEngine; namespace Unity.Netcode { + + public enum SessionModeTypes + { + ClientServer, + DistributedAuthority + } + /// /// A NetworkClient /// @@ -33,6 +41,15 @@ namespace Unity.Netcode /// internal bool IsApproved { get; set; } + public SessionModeTypes SessionModeType { get; internal set; } + + public bool DAHost { get; internal set; } + + /// + /// Is true when the client has been assigned session ownership in distributed authority mode + /// + public bool IsSessionOwner { get; internal set; } + /// /// The ClientId of the NetworkClient /// @@ -50,21 +67,54 @@ namespace Unity.Netcode internal NetworkSpawnManager SpawnManager { get; private set; } - internal void SetRole(bool isServer, bool isClient, NetworkManager networkManager = null) + internal bool SetRole(bool isServer, bool isClient, NetworkManager networkManager = null) { + ResetClient(isServer, isClient); + IsServer = isServer; IsClient = isClient; - if (!IsServer && !isClient) + + if (networkManager != null) + { + SpawnManager = networkManager.SpawnManager; + SessionModeType = networkManager.NetworkConfig.SessionMode; + + if (SessionModeType == SessionModeTypes.DistributedAuthority) + { + DAHost = IsClient && IsServer; + + // DANGO-TODO: We might allow a dedicated mock CMB server, but for now do not allow this + if (!IsClient && IsServer) + { + Debug.LogError("You cannot start NetworkManager as a server when operating in distributed authority mode!"); + return false; + } + + if (DAHost && networkManager.CMBServiceConnection) + { + Debug.LogError("You cannot start a host when connecting to a distributed authority CMB Service!"); + return false; + } + } + } + return true; + } + + /// + /// Only to be invoked when setting the role. + /// This resets the current NetworkClient's properties. + /// + private void ResetClient(bool isServer, bool isClient) + { + // If we are niether client nor server, then reset properties (i.e. client has no role) + if (!IsServer && !IsClient) { PlayerObject = null; ClientId = 0; IsConnected = false; IsApproved = false; - } - - if (networkManager != null) - { - SpawnManager = networkManager.SpawnManager; + SpawnManager = null; + DAHost = false; } } diff --git a/Runtime/Connection/NetworkConnectionManager.cs b/Runtime/Connection/NetworkConnectionManager.cs index d737598..cb19efe 100644 --- a/Runtime/Connection/NetworkConnectionManager.cs +++ b/Runtime/Connection/NetworkConnectionManager.cs @@ -1,12 +1,12 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Linq; using System.Runtime.CompilerServices; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using Unity.Profiling; using UnityEngine; -using Object = UnityEngine.Object; namespace Unity.Netcode { @@ -366,6 +366,10 @@ namespace Unity.Netcode { networkEvent = NetworkManager.NetworkConfig.NetworkTransport.PollEvent(out ulong transportClientId, out ArraySegment payload, out float receiveTime); HandleNetworkEvent(networkEvent, transportClientId, payload, receiveTime); + if (networkEvent == NetworkEvent.Disconnect || networkEvent == NetworkEvent.TransportFailure) + { + break; + } // Only do another iteration if: there are no more messages AND (there is no limit to max events or we have processed less than the maximum) } while (NetworkManager.IsListening && networkEvent != NetworkEvent.Nothing); @@ -430,16 +434,17 @@ namespace Unity.Netcode { if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) { - NetworkLog.LogInfo("Client Connected"); + var hostServer = NetworkManager.IsHost ? "Host" : "Server"; + NetworkLog.LogInfo($"[{hostServer}-Side] Transport connection established with pending Client-{clientId}."); } - AddPendingClient(clientId); } else { if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) { - NetworkLog.LogInfo("Connected"); + var serverOrService = NetworkManager.DistributedAuthorityMode ? NetworkManager.CMBServiceConnection ? "service" : "DAHost" : "server"; + NetworkLog.LogInfo($"[Approval Pending][Client] Transport connection with {serverOrService} established! Awaiting connection approval..."); } SendConnectionRequest(); @@ -546,6 +551,10 @@ namespace Unity.Netcode { var message = new ConnectionRequestMessage { + CMBServiceConnection = NetworkManager.CMBServiceConnection, + TickRate = NetworkManager.NetworkConfig.TickRate, + EnableSceneManagement = NetworkManager.NetworkConfig.EnableSceneManagement, + // Since only a remote client will send a connection request, we should always force the rebuilding of the NetworkConfig hash value ConfigHash = NetworkManager.NetworkConfig.GetConfig(false), ShouldSendConnectionData = NetworkManager.NetworkConfig.ConnectionApproval, @@ -701,6 +710,12 @@ namespace Unity.Netcode } } + /// + /// Adding this because message hooks cannot happen fast enough under certain scenarios + /// where the message is sent and responded to before the hook is in place. + /// + internal bool MockSkippingApproval; + /// /// Server Side: Handles the approval of a client /// @@ -712,12 +727,15 @@ namespace Unity.Netcode LocalClient.IsApproved = response.Approved; if (response.Approved) { + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) + { + NetworkLog.LogInfo($"[Server-Side] Pending Client-{ownerClientId} connection approved!"); + } // The client was approved, stop the server-side approval time out coroutine RemovePendingClient(ownerClientId); var client = AddClient(ownerClientId); - - if (response.CreatePlayerObject) + if (!NetworkManager.DistributedAuthorityMode && response.CreatePlayerObject && NetworkManager.NetworkConfig.PlayerPrefab != null) { var prefabNetworkObject = NetworkManager.NetworkConfig.PlayerPrefab.GetComponent(); var playerPrefabHash = response.PlayerPrefabHash ?? prefabNetworkObject.GlobalObjectIdHash; @@ -732,6 +750,7 @@ namespace Unity.Netcode HasTransform = prefabNetworkObject.SynchronizeTransform, Hash = playerPrefabHash, TargetClientId = ownerClientId, + DontDestroyWithOwner = prefabNetworkObject.DontDestroyWithOwner, Transform = new NetworkObject.SceneObject.TransformData { Position = response.Position.GetValueOrDefault(), @@ -761,6 +780,7 @@ namespace Unity.Netcode { OwnerClientId = ownerClientId, NetworkTick = NetworkManager.LocalTime.Tick, + IsDistributedAuthority = NetworkManager.DistributedAuthorityMode, ConnectedClientIds = new NativeArray(ConnectedClientIds.Count, Allocator.Temp) }; @@ -794,10 +814,20 @@ namespace Unity.Netcode }; } } - - SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, ownerClientId); + if (!MockSkippingApproval) + { + SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, ownerClientId); + } + else + { + NetworkLog.LogInfo("Mocking server not responding with connection approved..."); + } message.MessageVersions.Dispose(); message.ConnectedClientIds.Dispose(); + if (MockSkippingApproval) + { + return; + } // If scene management is disabled, then we are done and notify the local host-server the client is connected if (!NetworkManager.NetworkConfig.EnableSceneManagement) @@ -808,10 +838,19 @@ namespace Unity.Netcode { InvokeOnPeerConnectedCallback(ownerClientId); } + NetworkManager.SpawnManager.DistributeNetworkObjects(ownerClientId); + } else // Otherwise, let NetworkSceneManager handle the initial scene and NetworkObject synchronization { - NetworkManager.SceneManager.SynchronizeNetworkObjects(ownerClientId); + if (NetworkManager.DistributedAuthorityMode && NetworkManager.LocalClient.IsSessionOwner) + { + NetworkManager.SceneManager.SynchronizeNetworkObjects(ownerClientId); + } + else if (!NetworkManager.DistributedAuthorityMode) + { + NetworkManager.SceneManager.SynchronizeNetworkObjects(ownerClientId); + } } } else // Server just adds itself as an observer to all spawned NetworkObjects @@ -819,6 +858,17 @@ namespace Unity.Netcode LocalClient = client; NetworkManager.SpawnManager.UpdateObservedNetworkObjects(ownerClientId); LocalClient.IsConnected = true; + // If running mock service, then set the instance as the default session owner + if (NetworkManager.DistributedAuthorityMode && NetworkManager.DAHost) + { + NetworkManager.SetSessionOwner(NetworkManager.LocalClientId); + NetworkManager.SceneManager.InitializeScenesLoaded(); + } + + if (NetworkManager.DistributedAuthorityMode && NetworkManager.AutoSpawnPlayerPrefabClientSide) + { + CreateAndSpawnPlayer(ownerClientId); + } } if (!response.CreatePlayerObject || (response.PlayerPrefabHash == null && NetworkManager.NetworkConfig.PlayerPrefab == null)) @@ -826,6 +876,11 @@ namespace Unity.Netcode return; } + // Players are always spawned by their respective client, exit early. (DAHost mode anyway, CMB Service will never spawn player prefab) + if (NetworkManager.DistributedAuthorityMode) + { + return; + } // Separating this into a contained function call for potential further future separation of when this notification is sent. ApprovedPlayerSpawn(ownerClientId, response.PlayerPrefabHash ?? NetworkManager.NetworkConfig.PlayerPrefab.GetComponent().GlobalObjectIdHash); } @@ -840,11 +895,28 @@ namespace Unity.Netcode SendMessage(ref disconnectReason, NetworkDelivery.Reliable, ownerClientId); MessageManager.ProcessSendQueues(); } - DisconnectRemoteClient(ownerClientId); } } + /// + /// Client-Side Spawning in distributed authority mode uses this to spawn the player. + /// + internal void CreateAndSpawnPlayer(ulong ownerId, Vector3 position = default, Quaternion rotation = default) + { + if (NetworkManager.DistributedAuthorityMode && NetworkManager.AutoSpawnPlayerPrefabClientSide) + { + var playerPrefab = NetworkManager.FetchLocalPlayerPrefabToSpawn(); + if (playerPrefab != null) + { + var globalObjectIdHash = playerPrefab.GetComponent().GlobalObjectIdHash; + var networkObject = NetworkManager.SpawnManager.GetNetworkObjectToSpawn(globalObjectIdHash, ownerId, position, rotation); + networkObject.IsSceneObject = false; + networkObject.SpawnAsPlayerObject(ownerId, networkObject.DestroyWithScene); + } + } + } + /// /// Spawns the newly approved player /// @@ -864,8 +936,10 @@ namespace Unity.Netcode var message = new CreateObjectMessage { - ObjectInfo = ConnectedClients[clientId].PlayerObject.GetMessageSceneObject(clientPair.Key) + ObjectInfo = ConnectedClients[clientId].PlayerObject.GetMessageSceneObject(clientPair.Key), + IncludesSerializedObject = true, }; + message.ObjectInfo.Hash = playerPrefabHash; message.ObjectInfo.IsSceneObject = false; message.ObjectInfo.HasParent = false; @@ -883,20 +957,92 @@ namespace Unity.Netcode /// internal NetworkClient AddClient(ulong clientId) { + if (ConnectedClients.ContainsKey(clientId) && ConnectedClientIds.Contains(clientId) && ConnectedClientsList.Contains(ConnectedClients[clientId])) + { + return ConnectedClients[clientId]; + } + var networkClient = LocalClient; - networkClient = new NetworkClient(); + // If this is not the local client then create a new one + if (clientId != NetworkManager.LocalClientId) + { + networkClient = new NetworkClient(); + } networkClient.SetRole(clientId == NetworkManager.ServerClientId, isClient: true, NetworkManager); networkClient.ClientId = clientId; + if (!ConnectedClients.ContainsKey(clientId)) + { + ConnectedClients.Add(clientId, networkClient); + } + if (!ConnectedClientsList.Contains(networkClient)) + { + ConnectedClientsList.Add(networkClient); + } + + if (NetworkManager.LocalClientId != clientId) + { + if ((!NetworkManager.DistributedAuthorityMode && NetworkManager.IsServer) || + (NetworkManager.DistributedAuthorityMode && NetworkManager.NetworkConfig.EnableSceneManagement && NetworkManager.DAHost && NetworkManager.LocalClient.IsSessionOwner)) + { + var message = new ClientConnectedMessage { ClientId = clientId }; + NetworkManager.MessageManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, ConnectedClientIds.Where((c) => c != NetworkManager.LocalClientId).ToArray()); + } + else if (NetworkManager.DistributedAuthorityMode && NetworkManager.NetworkConfig.EnableSceneManagement && NetworkManager.DAHost && !NetworkManager.LocalClient.IsSessionOwner) + { + var message = new ClientConnectedMessage + { + ShouldSynchronize = true, + ClientId = clientId + }; + NetworkManager.MessageManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, NetworkManager.CurrentSessionOwner); + } + } + if (!ConnectedClientIds.Contains(clientId)) + { + ConnectedClientIds.Add(clientId); + } + + foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList) + { + if (networkObject.SpawnWithObservers) + { + networkObject.Observers.Add(clientId); + } + } - ConnectedClients.Add(clientId, networkClient); - ConnectedClientsList.Add(networkClient); - var message = new ClientConnectedMessage { ClientId = clientId }; - NetworkManager.MessageManager.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, ConnectedClientIds); - ConnectedClientIds.Add(clientId); return networkClient; } + /// + /// Invoked on clients when another client disconnects + /// + /// the client identifier to remove + internal void RemoveClient(ulong clientId) + { + if (ConnectedClientIds.Contains(clientId)) + { + ConnectedClientIds.Remove(clientId); + } + if (ConnectedClients.ContainsKey(clientId)) + { + ConnectedClientsList.Remove(ConnectedClients[clientId]); + } + + ConnectedClients.Remove(clientId); + + foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList) + { + networkObject.Observers.Remove(clientId); + } + } + + /// + /// DANGO-TODO: Until we have the CMB Server end-to-end with all features verified working via integration tests, + /// I am keeping this debug toggle available. (NSS) + /// + internal bool EnableDistributeLogging; + /// /// Server-Side: /// Invoked when a client is disconnected from a server-host @@ -923,25 +1069,55 @@ namespace Unity.Netcode { if (!playerObject.DontDestroyWithOwner) { - if (NetworkManager.PrefabHandler.ContainsHandler(ConnectedClients[clientId].PlayerObject.GlobalObjectIdHash)) + // DANGO-TODO: This is something that would be best for CMB Service to handle as it is part of the disconnection process + // If a player NetworkObject is being despawned, make sure to remove all children if they are marked to not be destroyed + // with the owner. + if (NetworkManager.DistributedAuthorityMode && NetworkManager.DAHost) { - NetworkManager.PrefabHandler.HandleNetworkPrefabDestroy(ConnectedClients[clientId].PlayerObject); + // Remove any children from the player object if they are not going to be destroyed with the owner + var childNetworkObjects = playerObject.GetComponentsInChildren(); + foreach (var child in childNetworkObjects) + { + // TODO: We have always just removed all children, but we might think about changing this to preserve the nested child + // hierarchy. + if (child.DontDestroyWithOwner && child.transform.transform.parent != null) + { + // If we are here, then we are running in DAHost mode and have the authority to remove the child from its parent + child.AuthorityAppliedParenting = true; + child.TryRemoveParentCachedWorldPositionStays(); + } + } + } + + if (NetworkManager.PrefabHandler.ContainsHandler(playerObject.GlobalObjectIdHash)) + { + if (NetworkManager.DAHost && NetworkManager.DistributedAuthorityMode) + { + NetworkManager.SpawnManager.DespawnObject(playerObject, true, NetworkManager.DistributedAuthorityMode); + } + else + { + NetworkManager.PrefabHandler.HandleNetworkPrefabDestroy(playerObject); + } } else if (playerObject.IsSpawned) { // Call despawn to assure NetworkBehaviour.OnNetworkDespawn is invoked on the server-side (when the client side disconnected). // This prevents the issue (when just destroying the GameObject) where any NetworkBehaviour component(s) destroyed before the NetworkObject would not have OnNetworkDespawn invoked. - NetworkManager.SpawnManager.DespawnObject(playerObject, true); + NetworkManager.SpawnManager.DespawnObject(playerObject, true, NetworkManager.DistributedAuthorityMode); } } else if (!NetworkManager.ShutdownInProgress) { - playerObject.RemoveOwnership(); + if (!NetworkManager.ShutdownInProgress) + { + playerObject.RemoveOwnership(); + } } } // Get the NetworkObjects owned by the disconnected client - var clientOwnedObjects = NetworkManager.SpawnManager.GetClientOwnedObjects(clientId); + var clientOwnedObjects = NetworkManager.SpawnManager.SpawnedObjectsList.Where((c) => c.OwnerClientId == clientId).ToList(); if (clientOwnedObjects == null) { // This could happen if a client is never assigned a player object and is disconnected @@ -954,6 +1130,9 @@ namespace Unity.Netcode else { // Handle changing ownership and prefab handlers + var clientCounter = 0; + var predictedClientCount = ConnectedClientsList.Count - 1; + var remainingClients = NetworkManager.DistributedAuthorityMode ? ConnectedClientsList.Where((c) => c.ClientId != clientId).ToList() : null; for (int i = clientOwnedObjects.Count - 1; i >= 0; i--) { var ownedObject = clientOwnedObjects[i]; @@ -963,16 +1142,72 @@ namespace Unity.Netcode { if (NetworkManager.PrefabHandler.ContainsHandler(clientOwnedObjects[i].GlobalObjectIdHash)) { + NetworkManager.SpawnManager.DespawnObject(ownedObject, true, true); NetworkManager.PrefabHandler.HandleNetworkPrefabDestroy(clientOwnedObjects[i]); } else { - Object.Destroy(ownedObject.gameObject); + NetworkManager.SpawnManager.DespawnObject(ownedObject, true, true); } } else if (!NetworkManager.ShutdownInProgress) { - ownedObject.RemoveOwnership(); + // NOTE: All of the below code only handles ownership transfer. + // For client-server, we just remove the ownership. + // For distributed authority, we need to change ownership based on parenting + if (NetworkManager.DistributedAuthorityMode) + { + // Only NetworkObjects that have the OwnershipStatus.Distributable flag set and no parent + // (ownership is transferred to all children) will have their ownership redistributed. + if (ownedObject.IsOwnershipDistributable && ownedObject.GetCachedParent() == null) + { + if (ownedObject.IsOwnershipLocked) + { + ownedObject.SetOwnershipLock(false); + } + + // DANGO-TODO: We will want to match how the CMB service handles this. For now, we just try to evenly distribute + // ownership. + var targetOwner = NetworkManager.ServerClientId; + if (predictedClientCount > 1) + { + clientCounter++; + clientCounter = clientCounter % predictedClientCount; + targetOwner = remainingClients[clientCounter].ClientId; + } + if (EnableDistributeLogging) + { + Debug.Log($"[Disconnected][Client-{clientId}][NetworkObjectId-{ownedObject.NetworkObjectId} Distributed to Client-{targetOwner}"); + } + NetworkManager.SpawnManager.ChangeOwnership(ownedObject, targetOwner, true); + // DANGO-TODO: Should we try handling inactive NetworkObjects? + // Ownership gets passed down to all children + var childNetworkObjects = ownedObject.GetComponentsInChildren(); + foreach (var childObject in childNetworkObjects) + { + // We already changed ownership for this + if (childObject == ownedObject) + { + continue; + } + // If the client owner disconnected, it is ok to unlock this at this point in time. + if (childObject.IsOwnershipLocked) + { + childObject.SetOwnershipLock(false); + } + + NetworkManager.SpawnManager.ChangeOwnership(childObject, targetOwner, true); + if (EnableDistributeLogging) + { + Debug.Log($"[Disconnected][Client-{clientId}][Child of {ownedObject.NetworkObjectId}][NetworkObjectId-{ownedObject.NetworkObjectId} Distributed to Client-{targetOwner}"); + } + } + } + } + else + { + ownedObject.RemoveOwnership(); + } } } } @@ -993,6 +1228,37 @@ namespace Unity.Netcode ConnectedClientIds.Remove(clientId); var message = new ClientDisconnectedMessage { ClientId = clientId }; MessageManager?.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, ConnectedClientIds); + + if (NetworkManager.DistributedAuthorityMode && !NetworkManager.ShutdownInProgress && NetworkManager.IsListening) + { + var newSessionOwner = NetworkManager.LocalClientId; + if (ConnectedClientIds.Count > 1) + { + var lowestRTT = ulong.MaxValue; + var unityTransport = NetworkManager.NetworkConfig.NetworkTransport as Transports.UTP.UnityTransport; + + foreach (var identifier in ConnectedClientIds) + { + if (identifier == NetworkManager.LocalClientId) + { + continue; + } + var rtt = unityTransport.GetCurrentRtt(identifier); + if (rtt < lowestRTT) + { + newSessionOwner = identifier; + lowestRTT = rtt; + } + } + } + + var sessionOwnerMessage = new SessionOwnerMessage() + { + SessionOwner = newSessionOwner, + }; + MessageManager?.SendMessage(ref sessionOwnerMessage, NetworkDelivery.ReliableFragmentedSequenced, ConnectedClientIds); + NetworkManager.SetSessionOwner(newSessionOwner); + } } // If the client ID transport map exists @@ -1259,8 +1525,8 @@ namespace Unity.Netcode internal int SendMessage(ref T message, NetworkDelivery delivery, ulong clientId) where T : INetworkMessage { - // Prevent server sending to itself - if (LocalClient.IsServer && clientId == NetworkManager.ServerClientId) + // Prevent server sending to itself or if there is no MessageManager yet then exit early + if ((LocalClient.IsServer && clientId == NetworkManager.ServerClientId) || MessageManager == null) { return 0; } diff --git a/Runtime/Core/NetworkBehaviour.cs b/Runtime/Core/NetworkBehaviour.cs index 6d099c0..ce0f648 100644 --- a/Runtime/Core/NetworkBehaviour.cs +++ b/Runtime/Core/NetworkBehaviour.cs @@ -69,6 +69,7 @@ namespace Unity.Netcode internal void __endSendServerRpc(ref FastBufferWriter bufferWriter, uint rpcMethodId, ServerRpcParams serverRpcParams, RpcDelivery rpcDelivery) #pragma warning restore IDE1006 // restore naming rule violation check { + var networkManager = NetworkManager; var serverRpcMessage = new ServerRpcMessage { Metadata = new RpcMetadata @@ -88,7 +89,7 @@ namespace Unity.Netcode networkDelivery = NetworkDelivery.ReliableFragmentedSequenced; break; case RpcDelivery.Unreliable: - if (bufferWriter.Length > NetworkManager.MessageManager.NonFragmentedMessageMaxSize) + if (bufferWriter.Length > networkManager.MessageManager.NonFragmentedMessageMaxSize) { throw new OverflowException("RPC parameters are too large for unreliable delivery."); } @@ -97,16 +98,16 @@ namespace Unity.Netcode } var rpcWriteSize = 0; - - // If we are a server/host then we just no op and send to ourself - if (IsHost || IsServer) + // Authority just no ops and sends to itself + // Client-Server: Only the server-host sends to self + if (IsServer) { using var tempBuffer = new FastBufferReader(bufferWriter, Allocator.Temp); var context = new NetworkContext { SenderId = NetworkManager.ServerClientId, - Timestamp = NetworkManager.RealTimeProvider.RealTimeSinceStartup, - SystemOwner = NetworkManager, + Timestamp = networkManager.RealTimeProvider.RealTimeSinceStartup, + SystemOwner = networkManager, // header information isn't valid since it's not a real message. // RpcMessage doesn't access this stuff so it's just left empty. Header = new NetworkMessageHeader(), @@ -149,6 +150,7 @@ namespace Unity.Netcode internal void __endSendClientRpc(ref FastBufferWriter bufferWriter, uint rpcMethodId, ClientRpcParams clientRpcParams, RpcDelivery rpcDelivery) #pragma warning restore IDE1006 // restore naming rule violation check { + var networkManager = NetworkManager; var clientRpcMessage = new ClientRpcMessage { Metadata = new RpcMetadata @@ -168,7 +170,7 @@ namespace Unity.Netcode networkDelivery = NetworkDelivery.ReliableFragmentedSequenced; break; case RpcDelivery.Unreliable: - if (bufferWriter.Length > NetworkManager.MessageManager.NonFragmentedMessageMaxSize) + if (bufferWriter.Length > networkManager.MessageManager.NonFragmentedMessageMaxSize) { throw new OverflowException("RPC parameters are too large for unreliable delivery."); } @@ -180,24 +182,22 @@ namespace Unity.Netcode // We check to see if we need to shortcut for the case where we are the host/server and we can send a clientRPC // to ourself. Sadly we have to figure that out from the list of clientIds :( - bool shouldSendToHost = false; + bool shouldInvokeLocally = false; if (clientRpcParams.Send.TargetClientIds != null) { foreach (var targetClientId in clientRpcParams.Send.TargetClientIds) { if (targetClientId == NetworkManager.ServerClientId) { - shouldSendToHost = true; - break; + shouldInvokeLocally = true; + continue; } - // Check to make sure we are sending to only observers, if not log an error. - if (NetworkManager.LogLevel >= LogLevel.Error && !NetworkObject.Observers.Contains(targetClientId)) + if (networkManager.LogLevel >= LogLevel.Error && !NetworkObject.Observers.Contains(targetClientId)) { NetworkLog.LogError(GenerateObserverErrorMessage(clientRpcParams, targetClientId)); } } - rpcWriteSize = NetworkManager.ConnectionManager.SendMessage(ref clientRpcMessage, networkDelivery, in clientRpcParams.Send.TargetClientIds); } else if (clientRpcParams.Send.TargetClientIdsNativeArray != null) @@ -206,17 +206,15 @@ namespace Unity.Netcode { if (targetClientId == NetworkManager.ServerClientId) { - shouldSendToHost = true; - break; + shouldInvokeLocally = true; + continue; } - // Check to make sure we are sending to only observers, if not log an error. - if (NetworkManager.LogLevel >= LogLevel.Error && !NetworkObject.Observers.Contains(targetClientId)) + if (networkManager.LogLevel >= LogLevel.Error && !NetworkObject.Observers.Contains(targetClientId)) { NetworkLog.LogError(GenerateObserverErrorMessage(clientRpcParams, targetClientId)); } } - rpcWriteSize = NetworkManager.ConnectionManager.SendMessage(ref clientRpcMessage, networkDelivery, clientRpcParams.Send.TargetClientIdsNativeArray.Value); } else @@ -227,7 +225,7 @@ namespace Unity.Netcode // Skip over the host if (IsHost && observerEnumerator.Current == NetworkManager.LocalClientId) { - shouldSendToHost = true; + shouldInvokeLocally = true; continue; } rpcWriteSize = NetworkManager.ConnectionManager.SendMessage(ref clientRpcMessage, networkDelivery, observerEnumerator.Current); @@ -235,14 +233,14 @@ namespace Unity.Netcode } // If we are a server/host then we just no op and send to ourself - if (shouldSendToHost) + if (shouldInvokeLocally) { using var tempBuffer = new FastBufferReader(bufferWriter, Allocator.Temp); var context = new NetworkContext { SenderId = NetworkManager.ServerClientId, - Timestamp = NetworkManager.RealTimeProvider.RealTimeSinceStartup, - SystemOwner = NetworkManager, + Timestamp = networkManager.RealTimeProvider.RealTimeSinceStartup, + SystemOwner = networkManager, // header information isn't valid since it's not a real message. // RpcMessage doesn't access this stuff so it's just left empty. Header = new NetworkMessageHeader(), @@ -261,7 +259,7 @@ namespace Unity.Netcode { foreach (var targetClientId in clientRpcParams.Send.TargetClientIds) { - NetworkManager.NetworkMetrics.TrackRpcSent( + networkManager.NetworkMetrics.TrackRpcSent( targetClientId, NetworkObject, rpcMethodName, @@ -273,7 +271,7 @@ namespace Unity.Netcode { foreach (var targetClientId in clientRpcParams.Send.TargetClientIdsNativeArray) { - NetworkManager.NetworkMetrics.TrackRpcSent( + networkManager.NetworkMetrics.TrackRpcSent( targetClientId, NetworkObject, rpcMethodName, @@ -286,7 +284,7 @@ namespace Unity.Netcode var observerEnumerator = NetworkObject.Observers.GetEnumerator(); while (observerEnumerator.MoveNext()) { - NetworkManager.NetworkMetrics.TrackRpcSent( + networkManager.NetworkMetrics.TrackRpcSent( observerEnumerator.Current, NetworkObject, rpcMethodName, @@ -372,6 +370,12 @@ namespace Unity.Netcode case SendTo.ClientsAndHost: rpcParams.Send.Target = RpcTarget.ClientsAndHost; break; + case SendTo.Authority: + rpcParams.Send.Target = RpcTarget.Authority; + break; + case SendTo.NotAuthority: + rpcParams.Send.Target = RpcTarget.NotAuthority; + break; case SendTo.SpecifiedInParams: throw new RpcException("This method requires a runtime-specified send target."); } @@ -456,6 +460,31 @@ namespace Unity.Netcode /// public bool IsServer { get; private set; } + /// + /// Determines if the local client has authority over the associated NetworkObject + /// Client-Server: This will return true if IsServer or IsHost + /// Distributed Authority: This will return true if IsOwner + /// + public bool HasAuthority { get; internal set; } + + internal NetworkClient LocalClient { get; private set; } + + /// + /// Gets if the client is the distributed authority mode session owner + /// + public bool IsSessionOwner + { + get + { + if (LocalClient == null) + { + return false; + } + + return LocalClient.IsSessionOwner; + } + } + /// /// Gets if the server (local or remote) is a host - i.e., also a client /// @@ -505,12 +534,14 @@ namespace Unity.Netcode { get { + if (m_NetworkObject != null) + { + return m_NetworkObject; + } + try { - if (m_NetworkObject == null) - { - m_NetworkObject = GetComponentInParent(); - } + m_NetworkObject = GetComponentInParent(); } catch (Exception) { @@ -579,30 +610,34 @@ namespace Unity.Netcode /// internal void UpdateNetworkProperties() { + var networkObject = NetworkObject; // Set NetworkObject dependent properties - if (NetworkObject != null) + if (networkObject != null) { + var networkManager = NetworkManager; // Set identification related properties - NetworkObjectId = NetworkObject.NetworkObjectId; - IsLocalPlayer = NetworkObject.IsLocalPlayer; + NetworkObjectId = networkObject.NetworkObjectId; + IsLocalPlayer = networkObject.IsLocalPlayer; // This is "OK" because GetNetworkBehaviourOrderIndex uses the order of // NetworkObject.ChildNetworkBehaviours which is set once when first // accessed. - NetworkBehaviourId = NetworkObject.GetNetworkBehaviourOrderIndex(this); + NetworkBehaviourId = networkObject.GetNetworkBehaviourOrderIndex(this); // Set ownership related properties - IsOwnedByServer = NetworkObject.IsOwnedByServer; - IsOwner = NetworkObject.IsOwner; - OwnerClientId = NetworkObject.OwnerClientId; + IsOwnedByServer = networkObject.IsOwnedByServer; + IsOwner = networkObject.IsOwner; + OwnerClientId = networkObject.OwnerClientId; // Set NetworkManager dependent properties - if (NetworkManager != null) + if (networkManager != null) { - IsHost = NetworkManager.IsListening && NetworkManager.IsHost; - IsClient = NetworkManager.IsListening && NetworkManager.IsClient; - IsServer = NetworkManager.IsListening && NetworkManager.IsServer; - ServerIsHost = NetworkManager.IsListening && NetworkManager.ServerIsHost; + IsHost = networkManager.IsListening && networkManager.IsHost; + IsClient = networkManager.IsListening && networkManager.IsClient; + IsServer = networkManager.IsListening && networkManager.IsServer; + LocalClient = networkManager.LocalClient; + HasAuthority = networkObject.HasAuthority; + ServerIsHost = networkManager.IsListening && networkManager.ServerIsHost; } } else // Shouldn't happen, but if so then set the properties to their default value; @@ -610,9 +645,21 @@ namespace Unity.Netcode OwnerClientId = NetworkObjectId = default; IsOwnedByServer = IsOwner = IsHost = IsClient = IsServer = ServerIsHost = default; NetworkBehaviourId = default; + LocalClient = default; + HasAuthority = default; } } + /// + /// Distributed Authority Mode Only + /// Invoked only on the authority instance when a is deferring its despawn on non-authoritative instances. + /// + /// + /// See also: + /// + /// the future network tick that the will be despawned on non-authoritative instances + public virtual void OnDeferringDespawn(int despawnTick) { } + /// /// Gets called when the gets spawned, message handlers are ready to be registered and the network is setup. /// @@ -642,7 +689,8 @@ namespace Unity.Netcode } InitializeVariables(); - if (IsServer) + + if (NetworkObject.HasAuthority) { // Since we just spawned the object and since user code might have modified their NetworkVariable, esp. // NetworkList, we need to mark the object as free of updates. @@ -679,7 +727,7 @@ namespace Unity.Netcode /// /// Invoked on all clients, override this method to be notified of any /// ownership changes (even if the instance was niether the previous or - /// newly assigned current owner). + /// newly assigned current owner). /// /// the previous owner /// the current owner @@ -838,65 +886,83 @@ namespace Unity.Netcode PreNetworkVariableWrite(); } - internal void VariableUpdate(ulong targetClientId) - { - NetworkVariableUpdate(targetClientId, NetworkBehaviourId); - } - internal readonly List NetworkVariableIndexesToReset = new List(); internal readonly HashSet NetworkVariableIndexesToResetSet = new HashSet(); - private void NetworkVariableUpdate(ulong targetClientId, int behaviourIndex) + internal void NetworkVariableUpdate(ulong targetClientId) { if (!CouldHaveDirtyNetworkVariables()) { return; } + // Getting these ahead of time actually improves performance + var networkManager = NetworkManager; + var networkObject = NetworkObject; + var behaviourIndex = networkObject.GetNetworkBehaviourOrderIndex(this); + var messageManager = networkManager.MessageManager; + var connectionManager = networkManager.ConnectionManager; + for (int j = 0; j < m_DeliveryMappedNetworkVariableIndices.Count; j++) { + var networkVariable = (NetworkVariableBase)null; var shouldSend = false; for (int k = 0; k < NetworkVariableFields.Count; k++) { - var networkVariable = NetworkVariableFields[k]; + networkVariable = NetworkVariableFields[k]; if (networkVariable.IsDirty() && networkVariable.CanClientRead(targetClientId)) { shouldSend = true; break; } } - - if (shouldSend) + // All of this is just to prevent the DA Host from re-sending a NetworkVariable update it received from the client owner + // If this NetworkManager is running as a DAHost: + // - Only when the write permissions is owner (to pass existing integration tests running as DAHost) + // - If the target client ID is the owner and the owner is not the local NetworkManager instance + // - **Special** As long as ownership did not just change and we are sending the new owner any dirty/updated NetworkVariables + // Under these conditions we should not send to the client + if (shouldSend && networkManager.DAHost && networkVariable.WritePerm == NetworkVariableWritePermission.Owner && + networkObject.OwnerClientId == targetClientId && networkObject.OwnerClientId != networkManager.LocalClientId && + networkObject.PreviousOwnerId == networkObject.OwnerClientId) { - var message = new NetworkVariableDeltaMessage + shouldSend = false; + } + + if (!shouldSend) + { + continue; + } + var message = new NetworkVariableDeltaMessage + { + NetworkObjectId = NetworkObjectId, + NetworkBehaviourIndex = behaviourIndex, + NetworkBehaviour = this, + TargetClientId = targetClientId, + DeliveryMappedNetworkVariableIndex = m_DeliveryMappedNetworkVariableIndices[j] + }; + // TODO: Serialization is where the IsDirty flag gets changed. + // Messages don't get sent from the server to itself, so if we're host and sending to ourselves, + // we still have to actually serialize the message even though we're not sending it, otherwise + // the dirty flag doesn't change properly. These two pieces should be decoupled at some point + // so we don't have to do this serialization work if we're not going to use the result. + if (IsServer && targetClientId == NetworkManager.ServerClientId) + { + var tmpWriter = new FastBufferWriter(messageManager.NonFragmentedMessageMaxSize, Allocator.Temp, messageManager.FragmentedMessageMaxSize); + using (tmpWriter) { - NetworkObjectId = NetworkObjectId, - NetworkBehaviourIndex = NetworkObject.GetNetworkBehaviourOrderIndex(this), - NetworkBehaviour = this, - TargetClientId = targetClientId, - DeliveryMappedNetworkVariableIndex = m_DeliveryMappedNetworkVariableIndices[j] - }; - // TODO: Serialization is where the IsDirty flag gets changed. - // Messages don't get sent from the server to itself, so if we're host and sending to ourselves, - // we still have to actually serialize the message even though we're not sending it, otherwise - // the dirty flag doesn't change properly. These two pieces should be decoupled at some point - // so we don't have to do this serialization work if we're not going to use the result. - if (IsServer && targetClientId == NetworkManager.ServerClientId) - { - var tmpWriter = new FastBufferWriter(NetworkManager.MessageManager.NonFragmentedMessageMaxSize, Allocator.Temp, NetworkManager.MessageManager.FragmentedMessageMaxSize); - using (tmpWriter) - { - message.Serialize(tmpWriter, message.Version); - } - } - else - { - NetworkManager.ConnectionManager.SendMessage(ref message, m_DeliveryTypesForNetworkVariableGroups[j], targetClientId); + message.Serialize(tmpWriter, message.Version); } } + else + { + connectionManager.SendMessage(ref message, m_DeliveryTypesForNetworkVariableGroups[j], targetClientId); + } } } + internal static bool LogSentVariableUpdateMessage; + private bool CouldHaveDirtyNetworkVariables() { // TODO: There should be a better way by reading one dirty variable vs. 'n' @@ -929,17 +995,30 @@ namespace Unity.Netcode /// internal void WriteNetworkVariableData(FastBufferWriter writer, ulong targetClientId) { + var networkManager = NetworkManager; + if (networkManager.DistributedAuthorityMode) + { + writer.WriteValueSafe((ushort)NetworkVariableFields.Count); + } + if (NetworkVariableFields.Count == 0) { return; } + // DANGO-TODO: Made some modifications here that overlap/won't play nice with EnsureNetworkVariableLenghtSafety. + // Worth either merging or more cleanly separating these codepaths. for (int j = 0; j < NetworkVariableFields.Count; j++) { - + // Note: In distributed authority mode, all clients can read if (NetworkVariableFields[j].CanClientRead(targetClientId)) { - if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (networkManager.DistributedAuthorityMode) + { + writer.WriteValueSafe(NetworkVariableFields[j].Type); + } + + if (networkManager.DistributedAuthorityMode || networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { var writePos = writer.Position; // Note: This value can't be packed because we don't know how large it will be in advance @@ -960,10 +1039,13 @@ namespace Unity.Netcode NetworkVariableFields[j].WriteField(writer); } } - else // Only if EnsureNetworkVariableLengthSafety, otherwise just skip - if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + else { - writer.WriteValueSafe((ushort)0); + // Only if EnsureNetworkVariableLengthSafety, otherwise just skip + if (networkManager.DistributedAuthorityMode || networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + { + writer.WriteValueSafe((ushort)0); + } } } } @@ -978,16 +1060,29 @@ namespace Unity.Netcode /// internal void SetNetworkVariableData(FastBufferReader reader, ulong clientId) { + var networkManager = NetworkManager; + if (networkManager.DistributedAuthorityMode) + { + reader.ReadValueSafe(out ushort variableCount); + if (variableCount != NetworkVariableFields.Count) + { + Debug.LogError("NetworkVariable count mismatch."); + return; + } + } + if (NetworkVariableFields.Count == 0) { return; } + // DANGO-TODO: Made some modifications here that overlap/won't play nice with EnsureNetworkVariableLenghtSafety. + // Worth either merging or more cleanly separating these codepaths. for (int j = 0; j < NetworkVariableFields.Count; j++) { var varSize = (ushort)0; var readStartPos = 0; - if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { reader.ReadValueSafe(out varSize); if (varSize == 0) @@ -999,12 +1094,35 @@ namespace Unity.Netcode else // If the client cannot read this field, then skip it if (!NetworkVariableFields[j].CanClientRead(clientId)) { + if (networkManager.DistributedAuthorityMode) + { + reader.ReadValueSafe(out ushort size); + if (size != 0) + { + Debug.LogError("Expected zero size"); + } + } continue; } - NetworkVariableFields[j].ReadField(reader); + if (networkManager.DistributedAuthorityMode) + { + // Explicit setting of the NetworkVariableType is only needed for CMB Runtime + reader.ReadValueSafe(out NetworkVariableType _); + reader.ReadValueSafe(out ushort size); + var start_marker = reader.Position; + NetworkVariableFields[j].ReadField(reader); + if (reader.Position - start_marker != size) + { + Debug.LogError("Mismatched network variable size"); + } + } + else + { + NetworkVariableFields[j].ReadField(reader); + } - if (NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { if (reader.Position > (readStartPos + varSize)) { @@ -1170,7 +1288,7 @@ namespace Unity.Netcode { if (NetworkManager.LogLevel <= LogLevel.Normal) { - NetworkLog.LogWarning($"{name} read {totalBytesRead} bytes but was expected to read {expectedBytesToRead} bytes during synchronization deserialization! This {nameof(NetworkBehaviour)} is being skipped and will not be synchronized!"); + NetworkLog.LogWarning($"{name} read {totalBytesRead} bytes but was expected to read {expectedBytesToRead} bytes during synchronization deserialization! This {nameof(NetworkBehaviour)}({GetType().Name})is being skipped and will not be synchronized!"); } synchronizationError = true; } diff --git a/Runtime/Core/NetworkBehaviourUpdater.cs b/Runtime/Core/NetworkBehaviourUpdater.cs index e6bcfc5..e190702 100644 --- a/Runtime/Core/NetworkBehaviourUpdater.cs +++ b/Runtime/Core/NetworkBehaviourUpdater.cs @@ -44,13 +44,12 @@ namespace Unity.Netcode for (int i = 0; i < m_ConnectionManager.ConnectedClientsList.Count; i++) { var client = m_ConnectionManager.ConnectedClientsList[i]; - - if (dirtyObj.IsNetworkVisibleTo(client.ClientId)) + if (m_NetworkManager.DistributedAuthorityMode || dirtyObj.IsNetworkVisibleTo(client.ClientId)) { // Sync just the variables for just the objects this client sees for (int k = 0; k < dirtyObj.ChildNetworkBehaviours.Count; k++) { - dirtyObj.ChildNetworkBehaviours[k].VariableUpdate(client.ClientId); + dirtyObj.ChildNetworkBehaviours[k].NetworkVariableUpdate(client.ClientId); } } } @@ -69,7 +68,7 @@ namespace Unity.Netcode } for (int k = 0; k < sobj.ChildNetworkBehaviours.Count; k++) { - sobj.ChildNetworkBehaviours[k].VariableUpdate(NetworkManager.ServerClientId); + sobj.ChildNetworkBehaviours[k].NetworkVariableUpdate(NetworkManager.ServerClientId); } } } @@ -95,6 +94,8 @@ namespace Unity.Netcode foreach (var dirtyobj in m_DirtyNetworkObjects) { dirtyobj.PostNetworkVariableWrite(); + // Once done processing, we set the previous owner id to the current owner id + dirtyobj.PreviousOwnerId = dirtyobj.OwnerClientId; } m_DirtyNetworkObjects.Clear(); } diff --git a/Runtime/Core/NetworkManager.cs b/Runtime/Core/NetworkManager.cs index 4fd66e3..64637c8 100644 --- a/Runtime/Core/NetworkManager.cs +++ b/Runtime/Core/NetworkManager.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using Unity.Collections; +using System.Linq; using UnityEngine; #if UNITY_EDITOR using UnityEditor; @@ -34,6 +35,148 @@ namespace Unity.Netcode #pragma warning restore IDE1006 // restore naming rule violation check + /// + /// Distributed Authority Mode + /// Returns true if the current session is running in distributed authority mode. + /// + public bool DistributedAuthorityMode + { + get + { + return NetworkConfig.SessionMode == SessionModeTypes.DistributedAuthority; + } + } + + /// + /// Distributed Authority Mode + /// Gets whether the NetworkManager is connected to a distributed authority state service. + /// to determine if the instance is mocking the state service. + /// + public bool CMBServiceConnection + { + get + { + return NetworkConfig.UseCMBService; + } + } + + /// + /// Distributed Authority Mode + /// When enabled, the player prefab will be automatically spawned on the newly connected client-side. + /// + /// + /// Refer to to enable/disable automatic spawning of the player prefab. + /// Alternately, override the to control what prefab the player should spawn. + /// + public bool AutoSpawnPlayerPrefabClientSide + { + get + { + return NetworkConfig.AutoSpawnPlayerPrefabClientSide; + } + } + + /// + /// Distributed Authority Mode + /// Delegate definition for + /// + /// Player Prefab + public delegate GameObject OnFetchLocalPlayerPrefabToSpawnDelegateHandler(); + + /// + /// Distributed Authority Mode + /// When a callback is assigned, this provides control over what player prefab a client will be using. + /// This is invoked only when is enabled. + /// + public OnFetchLocalPlayerPrefabToSpawnDelegateHandler OnFetchLocalPlayerPrefabToSpawn; + + internal GameObject FetchLocalPlayerPrefabToSpawn() + { + if (!AutoSpawnPlayerPrefabClientSide) + { + Debug.LogError($"[{nameof(FetchLocalPlayerPrefabToSpawn)}] Invoked when {nameof(NetworkConfig.AutoSpawnPlayerPrefabClientSide)} was not set! Check call paths!"); + return null; + } + if (OnFetchLocalPlayerPrefabToSpawn == null && NetworkConfig.PlayerPrefab == null) + { + return null; + } + + if (OnFetchLocalPlayerPrefabToSpawn != null) + { + return OnFetchLocalPlayerPrefabToSpawn(); + } + return NetworkConfig.PlayerPrefab; + } + + /// + /// Distributed Authority Mode + /// Gets whether the current NetworkManager is running as a mock distributed authority state service (DAHost) + /// + public bool DAHost + { + get + { + return LocalClient.DAHost; + } + } + + // DANGO-TODO-MVP: Remove these properties once the service handles object distribution + internal ulong ClientToRedistribute; + internal bool RedistributeToClient; + internal int TickToRedistribute; + + internal List DeferredDespawnObjects = new List(); + + public ulong CurrentSessionOwner { get; internal set; } + + internal void SetSessionOwner(ulong sessionOwner) + { + var previousSessionOwner = CurrentSessionOwner; + CurrentSessionOwner = sessionOwner; + LocalClient.IsSessionOwner = LocalClientId == sessionOwner; + if (LocalClient.IsSessionOwner) + { + foreach (var networkObjectEntry in SpawnManager.SpawnedObjects) + { + var networkObject = networkObjectEntry.Value; + if (networkObject.IsSceneObject == null || !networkObject.IsSceneObject.Value) + { + continue; + } + if (networkObject.OwnerClientId != LocalClientId) + { + SpawnManager.ChangeOwnership(networkObject, LocalClientId, true); + } + } + } + } + + // TODO: Make this internal after testing + public void PromoteSessionOwner(ulong clientId) + { + if (!DistributedAuthorityMode) + { + NetworkLog.LogErrorServer($"[SceneManagement][NotDA] Invoking promote session owner while not in distributed authority mode!"); + return; + } + if (!DAHost) + { + NetworkLog.LogErrorServer($"[SceneManagement][NotDAHost] Client is attempting to promote another client as the session owner!"); + return; + } + SetSessionOwner(clientId); + var sessionOwnerMessage = new SessionOwnerMessage() + { + SessionOwner = clientId, + }; + var clients = ConnectionManager.ConnectedClientIds.Where(c => c != LocalClientId).ToArray(); + foreach (var targetClient in clients) + { + ConnectionManager.SendMessage(ref sessionOwnerMessage, NetworkDelivery.ReliableSequenced, targetClient); + } + } + public void NetworkUpdate(NetworkUpdateStage updateStage) { switch (updateStage) @@ -56,6 +199,15 @@ namespace Unity.Netcode break; case NetworkUpdateStage.PostLateUpdate: { + // Handle deferred despawning + if (DistributedAuthorityMode) + { + SpawnManager.DeferredDespawnUpdate(ServerTime); + } + + // Update any NetworkObject's registered to notify of scene migration changes. + NetworkObject.UpdateNetworkObjectSceneChanges(); + // This should be invoked just prior to the MessageManager processes its outbound queue. SceneManager.CheckForAndSendNetworkObjectSceneChanged(); @@ -71,6 +223,16 @@ namespace Unity.Netcode // This is "ok" to invoke when not processing messages since it is just cleaning up messages that never got handled within their timeout period. DeferredMessageManager.CleanupStaleTriggers(); + // DANGO-TODO-MVP: Remove this once the service handles object distribution + // NOTE: This needs to be the last thing done and should happen exactly at this point + // in the update + if (RedistributeToClient && ServerTime.Tick <= TickToRedistribute) + { + RedistributeToClient = false; + SpawnManager.DistributeNetworkObjects(ClientToRedistribute); + ClientToRedistribute = 0; + } + if (m_ShuttingDown) { // Host-server will disconnect any connected clients prior to finalizing its shutdown @@ -171,17 +333,17 @@ namespace Unity.Netcode } /// - /// Gets a dictionary of connected clients and their clientId keys. This is only accessible on the server. + /// Gets a dictionary of connected clients and their clientId keys. /// - public IReadOnlyDictionary ConnectedClients => IsServer ? ConnectionManager.ConnectedClients : throw new NotServerException($"{nameof(ConnectionManager.ConnectedClients)} should only be accessed on server."); + public IReadOnlyDictionary ConnectedClients => ConnectionManager.ConnectedClients; /// - /// Gets a list of connected clients. This is only accessible on the server. + /// Gets a list of connected clients. /// - public IReadOnlyList ConnectedClientsList => IsServer ? ConnectionManager.ConnectedClientsList : throw new NotServerException($"{nameof(ConnectionManager.ConnectedClientsList)} should only be accessed on server."); + public IReadOnlyList ConnectedClientsList => ConnectionManager.ConnectedClientsList; /// - /// Gets a list of just the IDs of all connected clients. This is only accessible on the server. + /// Gets a list of just the IDs of all connected clients. /// public IReadOnlyList ConnectedClientsIds => ConnectionManager.ConnectedClientIds; @@ -780,6 +942,10 @@ namespace Unity.Netcode internal void Initialize(bool server) { + + //DANGOEXP TODO: Remove this before finalizing the experimental release + NetworkConfig.AutoSpawnPlayerPrefabClientSide = DistributedAuthorityMode; + // Make sure the ServerShutdownState is reset when initializing if (server) { @@ -930,7 +1096,10 @@ namespace Unity.Netcode return false; } - ConnectionManager.LocalClient.SetRole(true, false, this); + if (!ConnectionManager.LocalClient.SetRole(true, false, this)) + { + return false; + } ConnectionManager.LocalClient.ClientId = ServerClientId; Initialize(true); @@ -976,7 +1145,10 @@ namespace Unity.Netcode return false; } - ConnectionManager.LocalClient.SetRole(false, true, this); + if (!ConnectionManager.LocalClient.SetRole(false, true, this)) + { + return false; + } Initialize(false); @@ -1019,7 +1191,11 @@ namespace Unity.Netcode return false; } - ConnectionManager.LocalClient.SetRole(true, true, this); + if (!ConnectionManager.LocalClient.SetRole(true, true, this)) + { + return false; + } + Initialize(true); try { @@ -1075,7 +1251,8 @@ namespace Unity.Netcode var response = new ConnectionApprovalResponse { Approved = true, - CreatePlayerObject = NetworkConfig.PlayerPrefab != null + // Distributed authority always returns true since the client side handles spawning (whether automatically or manually) + CreatePlayerObject = DistributedAuthorityMode || NetworkConfig.PlayerPrefab != null, }; ConnectionManager.HandleConnectionApproval(ServerClientId, response); } @@ -1185,6 +1362,12 @@ namespace Unity.Netcode IsListening = false; m_ShuttingDown = false; + // Generate a local notification that the host client is disconnected + if (IsHost) + { + ConnectionManager.InvokeOnClientDisconnectCallback(LocalClientId); + } + if (ConnectionManager.LocalClient.IsClient) { // If we were a client, we want to know if we were a host @@ -1218,6 +1401,7 @@ namespace Unity.Netcode NetworkTickSystem = null; } + // Ensures that the NetworkManager is cleaned up before OnDestroy is run on NetworkObjects and NetworkBehaviours when quitting the application. private void OnApplicationQuit() { diff --git a/Runtime/Core/NetworkObject.cs b/Runtime/Core/NetworkObject.cs index 4c47753..7aa3a72 100644 --- a/Runtime/Core/NetworkObject.cs +++ b/Runtime/Core/NetworkObject.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Runtime.CompilerServices; #if UNITY_EDITOR using UnityEditor; @@ -255,7 +256,630 @@ namespace Unity.Netcode /// /// Gets the NetworkManager that owns this NetworkObject instance /// - public NetworkManager NetworkManager => NetworkManagerOwner ?? NetworkManager.Singleton; + public NetworkManager NetworkManager => NetworkManagerOwner ? NetworkManagerOwner : NetworkManager.Singleton; + + /// + /// Useful to know if we should or should not send a message + /// + internal bool HasRemoteObservers => !(Observers.Count() == 0 || (Observers.Contains(NetworkManager.LocalClientId) && Observers.Count() == 1)); + + /// + /// Distributed Authority Mode Only + /// When set, NetworkObjects despawned remotely will be delayed until the tick count specified is reached on all non-owner instances. + /// It will still despawn immediately on the owner-local side. + /// + [HideInInspector] + public int DeferredDespawnTick; + + /// + /// Distributed Authority Mode Only + /// The delegate handler declaration for . + /// + /// true (despawn) or false (do not despawn) + public delegate bool OnDeferedDespawnCompleteDelegateHandler(); + + /// + /// If assigned, this callback will be invoked each frame update to determine if a that has had its despawn deferred + /// should despawn. Use this callback to handle scenarios where you might have additional changes in state that could vindicate despawning earlier + /// than the deferred despawn targeted future network tick. + /// + public OnDeferedDespawnCompleteDelegateHandler OnDeferredDespawnComplete; + + /// + /// Distributed Authority Mode Only + /// When invoked by the authority of the , this will locally despawn the while + /// sending a delayed despawn to all non-authority instances. The tick offset + the authority's current known network tick (ServerTime.Tick) + /// is when non-authority instances will despawn this instance. + /// + /// The number of ticks from the authority's currently known to delay the despawn. + /// Defaults to true, determines whether the will be destroyed. + public void DeferDespawn(int tickOffset, bool destroy = true) + { + if (!NetworkManager.DistributedAuthorityMode) + { + NetworkLog.LogError($"This method is only available in distributed authority mode."); + return; + } + + if (!IsSpawned) + { + NetworkLog.LogError($"Cannot defer despawning {name} because it is not spawned!"); + return; + } + + if (!HasAuthority) + { + NetworkLog.LogError($"Only the authoirty can invoke {nameof(DeferDespawn)} and local Client-{NetworkManager.LocalClientId} is not the authority of {name}!"); + return; + } + + // Apply the relative tick offset for when this NetworkObject should be despawned on + // non-authoritative instances. + DeferredDespawnTick = NetworkManager.ServerTime.Tick + tickOffset; + + var connectionManager = NetworkManager.ConnectionManager; + + for (int i = 0; i < ChildNetworkBehaviours.Count; i++) + { + ChildNetworkBehaviours[i].PreVariableUpdate(); + // Notify all NetworkBehaviours that the authority is performing a deferred despawn. + // This is when user script would update NetworkVariable states that might be needed + // for the deferred despawn sequence on non-authoritative instances. + ChildNetworkBehaviours[i].OnDeferringDespawn(DeferredDespawnTick); + } + + // DAHost handles sending updates to all clients + if (NetworkManager.DAHost) + { + for (int i = 0; i < connectionManager.ConnectedClientsList.Count; i++) + { + var client = connectionManager.ConnectedClientsList[i]; + if (IsNetworkVisibleTo(client.ClientId)) + { + // Sync just the variables for just the objects this client sees + for (int k = 0; k < ChildNetworkBehaviours.Count; k++) + { + ChildNetworkBehaviours[k].NetworkVariableUpdate(client.ClientId); + } + } + } + } + else // Clients just send their deltas to the service or DAHost + { + for (int k = 0; k < ChildNetworkBehaviours.Count; k++) + { + ChildNetworkBehaviours[k].NetworkVariableUpdate(NetworkManager.ServerClientId); + } + } + + // Now despawn the local authority instance + Despawn(destroy); + } + + /// + /// When enabled, NetworkObject ownership is distributed amongst clients. + /// To set during runtime, use + /// + /// + /// Scenarios of interest: + /// - If the is locked and the current owner is still connected, then it will not be redistributed upon a new client joining. + /// - If the has an ownership request in progress, then it will not be redistributed upon a new client joining. + /// - If the is locked but the owner is not longer connected, then it will be redistributed. + /// - If the has an ownership request in progress but the target client is no longer connected, then it will be redistributed. + /// + public bool IsOwnershipDistributable => Ownership.HasFlag(OwnershipStatus.Distributable); + + /// + /// Returns true if the is has ownership locked. + /// When locked, the cannot be redistributed nor can it be transferred by another client. + /// To toggle the ownership loked status during runtime, use . + /// + public bool IsOwnershipLocked => ((OwnershipStatusExtended)Ownership).HasFlag(OwnershipStatusExtended.Locked); + + /// + /// When true, the 's ownership can be acquired by any non-owner client. + /// To set during runtime, use . + /// + public bool IsOwnershipTransferable => Ownership.HasFlag(OwnershipStatus.Transferable); + + /// + /// When true, the 's ownership can be acquired through non-owner client requesting ownership. + /// To set during runtime, use + /// To request ownership, use . + /// + public bool IsOwnershipRequestRequired => Ownership.HasFlag(OwnershipStatus.RequestRequired); + + /// + /// When true, the 's ownership cannot be acquired because an ownership request is underway. + /// In order for this status to be applied, the the must have the + /// flag set and a non-owner client must have sent a request via . + /// + public bool IsRequestInProgress => ((OwnershipStatusExtended)Ownership).HasFlag(OwnershipStatusExtended.Requested); + + /// + /// Determines whether a NetworkObject can be distributed to other clients during + /// a session. + /// + [SerializeField] + internal OwnershipStatus Ownership = OwnershipStatus.Distributable; + + /// + /// Ownership status flags: + /// : If nothing is set, then ownership is considered "static" and cannot be redistributed, requested, or transferred (i.e. a Player would have this). + /// : When set, this instance will be automatically redistributed when a client joins (if not locked or no request is pending) or leaves. + /// : When set, a non-owner can obtain ownership immediately (without requesting and as long as it is not locked). + /// : When set, When set, a non-owner must request ownership from the owner (will always get locked once ownership is transferred). + /// + // Ranges from 1 to 8 bits + [Flags] + public enum OwnershipStatus + { + None = 0, + Distributable = 1 << 0, + Transferable = 1 << 1, + RequestRequired = 1 << 2, + } + + /// + /// Intentionally internal + /// + // Ranges from 9 to 16 bits + [Flags] + internal enum OwnershipStatusExtended + { + // When locked and CanRequest is set, a non-owner can request ownership. If the owner responds by removing the Locked status, then ownership is transferred. + // If the owner responds by removing the Requested status only, then ownership is denied. + Requested = (1 << 8), + Locked = (1 << 9), + } + + internal bool HasExtendedOwnershipStatus(OwnershipStatusExtended extended) + { + var extendedOwnership = (OwnershipStatusExtended)Ownership; + return extendedOwnership.HasFlag(extended); + } + + internal void AddOwnershipExtended(OwnershipStatusExtended extended) + { + var extendedOwnership = (OwnershipStatusExtended)Ownership; + extendedOwnership |= extended; + Ownership = (OwnershipStatus)extendedOwnership; + } + + internal void RemoveOwnershipExtended(OwnershipStatusExtended extended) + { + var extendedOwnership = (OwnershipStatusExtended)Ownership; + extendedOwnership &= ~extended; + Ownership = (OwnershipStatus)extendedOwnership; + } + + /// + /// Distributed Authority Only + /// Locks ownership of a NetworkObject by the current owner. + /// + /// defaults to lock (true) or unlock (false) + /// true or false depending upon lock operation's success + public bool SetOwnershipLock(bool lockOwnership = true) + { + // If we are not in distributed autority mode, then exit early + if (!NetworkManager.DistributedAuthorityMode) + { + Debug.LogError($"[Feature Not Allowed In Client-Server Mode] Ownership flags are a distributed authority feature only!"); + return false; + } + + // If we don't have authority exit early + if (!HasAuthority) + { + NetworkLog.LogWarningServer($"[Attempted Lock Without Authority] Client-{NetworkManager.LocalClientId} is trying to lock ownership but does not have authority!"); + return false; + } + + // If we don't have the Transferable flag set and it is not a player object, then it is the same as having a static lock on ownership + if (!IsOwnershipTransferable && !IsPlayerObject) + { + NetworkLog.LogWarning($"Trying to add or remove ownership lock on [{name}] which does not have the {nameof(OwnershipStatus.Transferable)} flag set!"); + return false; + } + + // If we are locking and are already locked or we are unlocking and are already unlocked exit early and return true + if (!(IsOwnershipLocked ^ lockOwnership)) + { + return true; + } + + if (lockOwnership) + { + AddOwnershipExtended(OwnershipStatusExtended.Locked); + } + else + { + RemoveOwnershipExtended(OwnershipStatusExtended.Locked); + } + + SendOwnershipStatusUpdate(); + + return true; + } + + /// + /// In the event of an immediate (local instance) failure to change ownership, the following ownership + /// permission failure status codes will be returned via . + /// : The is locked and ownership cannot be acquired. + /// : The requires an ownership request via . + /// : The already is processing an ownership request and ownership cannot be acquired at this time. + /// does not have the flag set and ownership cannot be acquired. + /// + public enum OwnershipPermissionsFailureStatus + { + Locked, + RequestRequired, + RequestInProgress, + NotTransferrable + } + + /// + /// + /// + /// + public delegate void OnOwnershipPermissionsFailureDelegateHandler(OwnershipPermissionsFailureStatus changeOwnershipFailure); + + /// + /// If there is any callback assigned or subscriptions to this handler, then upon any ownership permissions failure that occurs during + /// the invocation of will trigger this notification containing an . + /// + public OnOwnershipPermissionsFailureDelegateHandler OnOwnershipPermissionsFailure; + + /// + /// Returned by to signify w + /// : The request for ownership was sent (does not mean it will be granted, but the request was sent). + /// : The current client is already the owner (no need to request ownership). + /// : The flag is not set on this + /// : The current owner has locked ownership which means requests are not available at this time. + /// : There is already a known request in progress. You can scan for ownership changes and try upon + /// a change in ownership or just try again after a specific period of time or no longer attempt to request ownership. + /// + public enum OwnershipRequestStatus + { + RequestSent, + AlreadyOwner, + RequestRequiredNotSet, + Locked, + RequestInProgress, + } + + /// + /// Invoke this from a non-authority client to request ownership. + /// + /// + /// The results of requesting ownership: + /// : The request for ownership was sent (does not mean it will be granted, but the request was sent). + /// : The current client is already the owner (no need to request ownership). + /// : The flag is not set on this + /// : The current owner has locked ownership which means requests are not available at this time. + /// : There is already a known request in progress. You can scan for ownership changes and try upon + /// a change in ownership or just try again after a specific period of time or no longer attempt to request ownership. + /// + /// + public OwnershipRequestStatus RequestOwnership() + { + // Exit early the local client is already the owner + if (OwnerClientId == NetworkManager.LocalClientId) + { + return OwnershipRequestStatus.AlreadyOwner; + } + + // Exit early if it doesn't have the RequestRequired flag + if (!IsOwnershipRequestRequired) + { + return OwnershipRequestStatus.RequestRequiredNotSet; + } + + // Exit early if it is locked + if (IsOwnershipLocked) + { + return OwnershipRequestStatus.Locked; + } + + // Exit early if there is already a request in progress + if (IsRequestInProgress) + { + return OwnershipRequestStatus.RequestInProgress; + } + + // Otherwise, send the request ownership message + var changeOwnership = new ChangeOwnershipMessage + { + NetworkObjectId = NetworkObjectId, + OwnerClientId = OwnerClientId, + ClientIdCount = 1, + RequestClientId = NetworkManager.LocalClientId, + ClientIds = new ulong[1] { OwnerClientId }, + DistributedAuthorityMode = true, + RequestOwnership = true, + OwnershipFlags = (ushort)Ownership, + }; + + var sendTarget = NetworkManager.DAHost ? OwnerClientId : NetworkManager.ServerClientId; + NetworkManager.ConnectionManager.SendMessage(ref changeOwnership, NetworkDelivery.Reliable, sendTarget); + + return OwnershipRequestStatus.RequestSent; + } + + /// + /// The delegate handler declaration used by . + /// + /// + /// + public delegate bool OnOwnershipRequestedDelegateHandler(ulong clientRequesting); + + /// + /// The callback that can be used + /// to control when ownership can be transferred to a non-authority client. + /// + /// + /// Requesting ownership requires the flags to have the flag set. + /// + public OnOwnershipRequestedDelegateHandler OnOwnershipRequested; + + /// + /// Invoked by ChangeOwnershipMessage + /// + /// the client requesting ownership + /// + internal void OwnershipRequest(ulong clientRequestingOwnership) + { + var response = OwnershipRequestResponseStatus.Approved; + + // Do a last check to make sure this NetworkObject can be requested + // CMB-DANGO-TODO: We could help optimize this process and check the below flags on the service side. + // It wouldn't cover the scenario were an update was in-bound to the service from the owner, but it would + // handle the case where something had already changed and the service was already "aware" of the change. + if (IsOwnershipLocked) + { + response = OwnershipRequestResponseStatus.Locked; + } + else if (IsRequestInProgress) + { + response = OwnershipRequestResponseStatus.RequestInProgress; + } + else if (!IsOwnershipRequestRequired && !IsOwnershipTransferable) + { + response = OwnershipRequestResponseStatus.CannotRequest; + } + + // Finally, check to see if OnOwnershipRequested is registered and if user script is allowing + // this transfer of ownership + if (OnOwnershipRequested != null && !OnOwnershipRequested.Invoke(clientRequestingOwnership)) + { + response = OwnershipRequestResponseStatus.Denied; + } + + // If we made it here and the response is still approved, then change ownership + if (response == OwnershipRequestResponseStatus.Approved) + { + // When requested and approved, the owner immediately sets the Requested flag **prior to** + // changing the ownership. This prevents race conditions from happening. + // Until the ownership change has propagated out, requests can still flow through this owner, + // but by that time this owner's instance will have the extended Requested flag and will + // respond to any additional ownership request with OwnershipRequestResponseStatus.RequestInProgress. + AddOwnershipExtended(OwnershipStatusExtended.Requested); + + // This action is always authorized as long as the client still has authority. + // We need to pass in that this is a request approval ownership change. + NetworkManager.SpawnManager.ChangeOwnership(this, clientRequestingOwnership, HasAuthority, true); + } + else + { + // Otherwise, send back the reason why the ownership request was denied for the clientRequestingOwnership + /// Notes: + /// We always apply the as opposed to to the + /// value as ownership could have changed and the denied requests + /// targeting this instance are because there is a request pending. + /// DANGO-TODO: What happens if the client requesting disconnects prior to responding with the update in request pending? + var changeOwnership = new ChangeOwnershipMessage + { + NetworkObjectId = NetworkObjectId, + OwnerClientId = NetworkManager.LocalClientId, // Always use the local clientId (see above notes) + RequestClientId = clientRequestingOwnership, + DistributedAuthorityMode = true, + RequestDenied = true, + OwnershipRequestResponseStatus = (byte)response, + OwnershipFlags = (ushort)Ownership, + }; + + var sendTarget = NetworkManager.DAHost ? clientRequestingOwnership : NetworkManager.ServerClientId; + NetworkManager.ConnectionManager.SendMessage(ref changeOwnership, NetworkDelivery.Reliable, sendTarget); + } + } + + /// + /// What is returned via after an ownership request has been sent via + /// + /// + /// Approved: Granted ownership, and returned after the requesting client has gained ownership on the local instance. + /// Locked: Was locked after request was sent. + /// RequestInProgress: A request started before this request was received. + /// CannotRequest: The RequestRequired status changed while the request was in flight. + /// Denied: General denied message that is only set if returns false by the authority instance. + /// + public enum OwnershipRequestResponseStatus + { + Approved, + Locked, + RequestInProgress, + CannotRequest, + Denied, + } + + /// + /// The delegate handler declaration used by . + /// + /// + public delegate void OnOwnershipRequestResponseDelegateHandler(OwnershipRequestResponseStatus ownershipRequestResponse); + + /// + /// The callback that can be used + /// to control when ownership can be transferred to a non-authority client. + /// + /// + /// Requesting ownership requires the flags to have the flag set. + /// + public OnOwnershipRequestResponseDelegateHandler OnOwnershipRequestResponse; + + /// + /// Invoked when a request is denied + /// + internal void OwnershipRequestResponse(OwnershipRequestResponseStatus ownershipRequestResponse) + { + OnOwnershipRequestResponse?.Invoke(ownershipRequestResponse); + } + + /// + /// When passed as a parameter in , the following additional locking actions will occur: + /// - : (default) No locking action + /// - : Will set the passed in flags and then lock the + /// - : Will set the passed in flags and then unlock the + /// + public enum OwnershipLockActions + { + None, + SetAndLock, + SetAndUnlock + } + + /// + /// Adds an flag to the flags + /// + /// flag(s) to update + /// defaults to false, but when true will clear the permissions and then set the permissions flags + /// defaults to , but when set it to anther action type it will either lock or unlock ownership after setting the flags + /// true (applied)/false (not applied) + /// + /// If it returns false, then this means the flag(s) you are attempting to + /// set were already set on the instance. + /// If it returns true, then the flags were set and an ownership update message + /// was sent to all observers of the instance. + /// + public bool SetOwnershipStatus(OwnershipStatus status, bool clearAndSet = false, OwnershipLockActions lockAction = OwnershipLockActions.None) + { + // If it already has the flag do nothing + if (!clearAndSet && Ownership.HasFlag(status)) + { + return false; + } + + if (clearAndSet || status == OwnershipStatus.None) + { + Ownership = OwnershipStatus.None; + } + + // Faster to just OR a None status than to check + // if it is !None before "OR'ing". + Ownership |= status; + + if (lockAction != OwnershipLockActions.None) + { + SetOwnershipLock(lockAction == OwnershipLockActions.SetAndLock); + } + + SendOwnershipStatusUpdate(); + + return true; + } + + /// + /// Use this method to remove one or more ownership flags from the NetworkObject. + /// If you want to clear and then set, use . + /// + /// the flag(s) to remove + /// true/false + /// + /// If it returns false, then this means the flag(s) you are attempting to + /// remove were not already set on the instance. + /// If it returns true, then the flags were removed and an ownership update message + /// was sent to all observers of the instance. + /// + public bool RemoveOwnershipStatus(OwnershipStatus status) + { + // If it doesn't have the ownership flag or we are trying to remove the None permission, then return false + if (!Ownership.HasFlag(status) || status == OwnershipStatus.None) + { + return false; + } + + Ownership &= ~status; + + SendOwnershipStatusUpdate(); + + return true; + } + + /// + /// Sends an update ownership status to all non-owner clients + /// + internal void SendOwnershipStatusUpdate() + { + // If there are no remote observers, then exit early + if (!HasRemoteObservers) + { + return; + } + + var changeOwnership = new ChangeOwnershipMessage + { + NetworkObjectId = NetworkObjectId, + OwnerClientId = OwnerClientId, + DistributedAuthorityMode = true, + OwnershipFlagsUpdate = true, + OwnershipFlags = (ushort)Ownership, + }; + + if (NetworkManager.DAHost) + { + foreach (var clientId in Observers) + { + if (clientId == NetworkManager.LocalClientId) + { + continue; + } + NetworkManager.ConnectionManager.SendMessage(ref changeOwnership, NetworkDelivery.Reliable, clientId); + } + } + else + { + changeOwnership.ClientIdCount = Observers.Count(); + changeOwnership.ClientIds = Observers.ToArray(); + NetworkManager.ConnectionManager.SendMessage(ref changeOwnership, NetworkDelivery.Reliable, NetworkManager.ServerClientId); + } + } + + /// + /// Use this method to determine if a has one or more ownership flags set. + /// + /// one or more flags + /// true if the flag(s) are set and false if the flag or any one of the flags are not set + public bool HasOwnershipStatus(OwnershipStatus status) + { + return Ownership.HasFlag(status); + } + + /// + /// This property can be used in client-server or distributed authority modes to determine if the local instance has authority. + /// When in client-server mode, the server will always have authority over the NetworkObject and associated NetworkBehaviours. + /// When in distributed authority mode, the owner is always the authority. + /// + /// + /// When in client-server mode, authority should is not considered the same as ownership. + /// + public bool HasAuthority => InternalHasAuthority(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool InternalHasAuthority() + { + var networkManager = NetworkManager; + return networkManager.DistributedAuthorityMode ? OwnerClientId == networkManager.LocalClientId : networkManager.IsServer; + } /// /// The NetworkManager that owns this NetworkObject. @@ -275,6 +899,8 @@ namespace Unity.Netcode /// public ulong OwnerClientId { get; internal set; } + internal ulong PreviousOwnerId; + /// /// If true, the object will always be replicated as root on clients and the parent will be ignored. /// @@ -322,6 +948,12 @@ namespace Unity.Netcode /// public bool? IsSceneObject { get; internal set; } + //DANGOEXP TODO: Determine if we want to keep this + public void SetSceneObjectStatus(bool isSceneObject = false) + { + IsSceneObject = isSceneObject; + } + /// /// Gets whether or not the object should be automatically removed when the scene is unloaded. /// @@ -449,6 +1081,7 @@ namespace Unity.Netcode /// /// The clientId of the client /// True if the client knows about the object + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsNetworkVisibleTo(ulong clientId) { if (!IsSpawned) @@ -510,12 +1143,6 @@ namespace Unity.Netcode return SceneOriginHandle != 0 ? SceneOriginHandle : gameObject.scene.handle; } - private void Awake() - { - SetCachedParent(transform.parent); - SceneOrigin = gameObject.scene; - } - /// /// Makes the previously hidden "netcode visible" to the targeted client. /// @@ -537,14 +1164,29 @@ namespace Unity.Netcode throw new SpawnStateException("Object is not spawned"); } - if (!NetworkManager.IsServer) + if (!HasAuthority) { - throw new NotServerException("Only server can change visibility"); + if (NetworkManager.DistributedAuthorityMode) + { + throw new NotServerException($"Only the owner-authority can change visibility when distributed authority mode is enabled!"); + } + else + { + throw new NotServerException("Only the authority can change visibility"); + } } if (Observers.Contains(clientId)) { - throw new VisibilityChangeException("The object is already visible"); + if (NetworkManager.DistributedAuthorityMode) + { + Debug.LogError($"The object {name} is already visible to Client-{clientId}!"); + return; + } + else + { + throw new NotServerException("Only server can change visibility"); + } } if (CheckObjectVisibility != null && !CheckObjectVisibility(clientId)) @@ -579,19 +1221,42 @@ namespace Unity.Netcode { if (networkObjects == null || networkObjects.Count == 0) { - throw new ArgumentNullException("At least one " + nameof(NetworkObject) + " has to be provided"); - } - - NetworkManager networkManager = networkObjects[0].NetworkManager; - - if (!networkManager.IsServer) - { - throw new NotServerException("Only server can change visibility"); + NetworkLog.LogErrorServer($"At least one {nameof(NetworkObject)} has to be provided when showing a list of {nameof(NetworkObject)}s!"); + return; } // Do the safety loop first to prevent putting the netcode in an invalid state. for (int i = 0; i < networkObjects.Count; i++) { + var networkObject = networkObjects[i]; + var networkManager = networkObject.NetworkManager; + + if (networkManager.DistributedAuthorityMode && clientId == networkObject.OwnerClientId) + { + NetworkLog.LogErrorServer($"Cannot hide an object from the owner when distributed authority mode is enabled! (Skipping {networkObject.gameObject.name})"); + } + else if (!networkManager.DistributedAuthorityMode && clientId == NetworkManager.ServerClientId) + { + NetworkLog.LogErrorServer("Cannot hide an object from the server!"); + continue; + } + + // Distributed authority mode adjustments to log a network error and continue when trying to show a NetworkObject + // that the local instance does not own + if (!networkObjects[i].HasAuthority) + { + if (networkObjects[i].NetworkManager.DistributedAuthorityMode) + { + // It will log locally and to the "master-host". + NetworkLog.LogErrorServer("Only the owner-authority can change visibility when distributed authority mode is enabled!"); + continue; + } + else + { + throw new NotServerException("Only server can change visibility"); + } + } + if (!networkObjects[i].IsSpawned) { throw new SpawnStateException("Object is not spawned"); @@ -635,31 +1300,68 @@ namespace Unity.Netcode throw new SpawnStateException("Object is not spawned"); } - if (!NetworkManager.IsServer) + if (!HasAuthority && !NetworkManager.DAHost) { - throw new NotServerException("Only server can change visibility"); - } - - if (clientId == NetworkManager.ServerClientId) - { - throw new VisibilityChangeException("Cannot hide an object from the server"); + if (NetworkManager.DistributedAuthorityMode) + { + throw new NotServerException($"Only the owner-authority can change visibility when distributed authority mode is enabled!"); + } + else + { + throw new NotServerException("Only the authority can change visibility"); + } } if (!NetworkManager.SpawnManager.RemoveObjectFromShowingTo(this, clientId)) { if (!Observers.Contains(clientId)) { - throw new VisibilityChangeException("The object is already hidden"); + if (NetworkManager.LogLevel <= LogLevel.Developer) + { + Debug.LogWarning($"{name} is already hidden from Client-{clientId}! (ignoring)"); + return; + } } Observers.Remove(clientId); var message = new DestroyObjectMessage { NetworkObjectId = NetworkObjectId, - DestroyGameObject = !IsSceneObject.Value + DestroyGameObject = !IsSceneObject.Value, + IsDistributedAuthority = NetworkManager.DistributedAuthorityMode, + IsTargetedDestroy = NetworkManager.DistributedAuthorityMode, + TargetClientId = clientId, // Just always populate this value whether we write it or not + DeferredDespawnTick = DeferredDespawnTick, }; - // Send destroy call - var size = NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, clientId); + + var size = 0; + if (NetworkManager.DistributedAuthorityMode) + { + if (!NetworkManager.DAHost) + { + // Send destroy call to service or DAHost + size = NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, NetworkManager.ServerClientId); + } + else // DAHost mocking service + { + // Send destroy call + size = NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, clientId); + // Broadcast the destroy to all clients so they can update their observers list + foreach (var client in NetworkManager.ConnectedClientsIds) + { + if (client == clientId || client == NetworkManager.LocalClientId) + { + continue; + } + size += NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, client); + } + } + } + else + { + // Send destroy call + size = NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, clientId); + } NetworkManager.NetworkMetrics.TrackObjectDestroySent(clientId, this, size); } } @@ -683,24 +1385,43 @@ namespace Unity.Netcode { if (networkObjects == null || networkObjects.Count == 0) { - throw new ArgumentNullException("At least one " + nameof(NetworkObject) + " has to be provided"); - } - - var networkManager = networkObjects[0].NetworkManager; - - if (!networkManager.IsServer) - { - throw new NotServerException("Only server can change visibility"); - } - - if (clientId == NetworkManager.ServerClientId) - { - throw new VisibilityChangeException("Cannot hide an object from the server"); + NetworkLog.LogErrorServer($"At least one {nameof(NetworkObject)} has to be provided when hiding a list of {nameof(NetworkObject)}s!"); + return; } // Do the safety loop first to prevent putting the netcode in an invalid state. for (int i = 0; i < networkObjects.Count; i++) { + var networkObject = networkObjects[i]; + var networkManager = networkObject.NetworkManager; + + if (networkManager.DistributedAuthorityMode && clientId == networkObject.OwnerClientId) + { + NetworkLog.LogErrorServer($"Cannot hide an object from the owner when distributed authority mode is enabled! (Skipping {networkObject.gameObject.name})"); + } + else if (!networkManager.DistributedAuthorityMode && clientId == NetworkManager.ServerClientId) + { + NetworkLog.LogErrorServer("Cannot hide an object from the server!"); + continue; + } + + // Distributed authority mode adjustments to log a network error and continue when trying to show a NetworkObject + // that the local instance does not own + if (!networkObjects[i].HasAuthority) + { + if (networkObjects[i].NetworkManager.DistributedAuthorityMode) + { + // It will log locally and to the "master-host". + NetworkLog.LogErrorServer($"Only the owner-authority can change hide a {nameof(NetworkObject)} when distributed authority mode is enabled!"); + continue; + } + else + { + throw new NotServerException("Only server can change visibility!"); + } + } + + // CLIENT SPAWNING TODO: Log error and continue as opposed to throwing an exception if (!networkObjects[i].IsSpawned) { throw new SpawnStateException("Object is not spawned"); @@ -731,7 +1452,10 @@ namespace Unity.Netcode return; } - if (NetworkManager.IsListening && !NetworkManager.IsServer && IsSpawned && + // Authority is the server (client-server) and the owner or DAHost (distributed authority) when destroying a NetworkObject + var isAuthority = HasAuthority || NetworkManager.DAHost; + + if (NetworkManager.IsListening && !isAuthority && IsSpawned && (IsSceneObject == null || (IsSceneObject.Value != true))) { // Clients should not despawn NetworkObjects while connected to a session, but we don't want to destroy the current call stack @@ -741,7 +1465,14 @@ namespace Unity.Netcode // Since we still have a session connection, log locally and on the server to inform user of this issue. if (NetworkManager.LogLevel <= LogLevel.Error) { - NetworkLog.LogErrorServer($"[Invalid Destroy][{gameObject.name}][NetworkObjectId:{NetworkObjectId}] Destroy a spawned {nameof(NetworkObject)} on a non-host client is not valid. Call {nameof(Destroy)} or {nameof(Despawn)} on the server/host instead."); + if (NetworkManager.DistributedAuthorityMode) + { + NetworkLog.LogError($"[Invalid Destroy][{gameObject.name}][NetworkObjectId:{NetworkObjectId}] Destroy a spawned {nameof(NetworkObject)} on a non-owner client is not valid during a distributed authority session. Call {nameof(Destroy)} or {nameof(Despawn)} on the client-owner instead."); + } + else + { + NetworkLog.LogErrorServer($"[Invalid Destroy][{gameObject.name}][NetworkObjectId:{NetworkObjectId}] Destroy a spawned {nameof(NetworkObject)} on a non-host client is not valid. Call {nameof(Destroy)} or {nameof(Despawn)} on the server/host instead."); + } } return; } @@ -760,25 +1491,68 @@ namespace Unity.Netcode [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void SpawnInternal(bool destroyWithScene, ulong ownerClientId, bool playerObject) { + if (NetworkManagerOwner == null) + { + NetworkManagerOwner = NetworkManager.Singleton; + } if (!NetworkManager.IsListening) { throw new NotListeningException($"{nameof(NetworkManager)} is not listening, start a server or host before spawning objects"); } - if (!NetworkManager.IsServer) + if ((!NetworkManager.IsServer && !NetworkManager.DistributedAuthorityMode) || (NetworkManager.DistributedAuthorityMode && !NetworkManager.LocalClient.IsSessionOwner && NetworkManager.LocalClientId != ownerClientId)) { - throw new NotServerException($"Only server can spawn {nameof(NetworkObject)}s"); + if (NetworkManager.DistributedAuthorityMode) + { + throw new NotServerException($"When distributed authority mode is enabled, you can only spawn NetworkObjects that belong to the local instance! Local instance id {NetworkManager.LocalClientId} is not the same as the assigned owner id: {ownerClientId}!"); + } + else + { + throw new NotServerException($"Only server can spawn {nameof(NetworkObject)}s"); + } + } + + if (NetworkManager.DistributedAuthorityMode) + { + if (NetworkManager.NetworkConfig.EnableSceneManagement) + { + NetworkSceneHandle = NetworkManager.SceneManager.ClientSceneHandleToServerSceneHandle[gameObject.scene.handle]; + } + if (DontDestroyWithOwner && !IsOwnershipDistributable) + { + //Ownership |= OwnershipStatus.Distributable; + // DANGO-TODO: Review over don't destroy with owner being set but DistributeOwnership not being set + if (NetworkManager.LogLevel == LogLevel.Developer) + { + NetworkLog.LogWarning("DANGO-TODO: Review over don't destroy with owner being set but DistributeOwnership not being set. For now, if the NetworkObject does not destroy with the owner it will automatically set DistributeOwnership."); + } + } } NetworkManager.SpawnManager.SpawnNetworkObjectLocally(this, NetworkManager.SpawnManager.GetNetworkObjectId(), IsSceneObject.HasValue && IsSceneObject.Value, playerObject, ownerClientId, destroyWithScene); - for (int i = 0; i < NetworkManager.ConnectedClientsList.Count; i++) + if ((NetworkManager.DistributedAuthorityMode && NetworkManager.DAHost) || (!NetworkManager.DistributedAuthorityMode && NetworkManager.IsServer)) { - if (Observers.Contains(NetworkManager.ConnectedClientsList[i].ClientId)) + for (int i = 0; i < NetworkManager.ConnectedClientsList.Count; i++) { - NetworkManager.SpawnManager.SendSpawnCallForObject(NetworkManager.ConnectedClientsList[i].ClientId, this); + if (NetworkManager.ConnectedClientsList[i].ClientId == NetworkManager.ServerClientId) + { + continue; + } + if (Observers.Contains(NetworkManager.ConnectedClientsList[i].ClientId)) + { + NetworkManager.SpawnManager.SendSpawnCallForObject(NetworkManager.ConnectedClientsList[i].ClientId, this); + } } } + else if (NetworkManager.DistributedAuthorityMode && !NetworkManager.DAHost) + { + NetworkManager.SpawnManager.SendSpawnCallForObject(NetworkManager.ServerClientId, this); + } + else + { + NetworkLog.LogWarningServer($"Ran into unknown conditional check during spawn when determining distributed authority mode or not"); + } } /// @@ -831,26 +1605,28 @@ namespace Unity.Netcode return null; } - if (!networkManager.IsServer) + ownerClientId = networkManager.DistributedAuthorityMode ? networkManager.LocalClientId : NetworkManager.ServerClientId; + // We only need to check for authority when running in client-server mode + if (!networkManager.IsServer && !networkManager.DistributedAuthorityMode) { Debug.LogError(NetworkSpawnManager.InstantiateAndSpawnErrors[NetworkSpawnManager.InstantiateAndSpawnErrorTypes.NotAuthority]); return null; } - if (NetworkManager.ShutdownInProgress) + if (networkManager.ShutdownInProgress) { Debug.LogWarning(NetworkSpawnManager.InstantiateAndSpawnErrors[NetworkSpawnManager.InstantiateAndSpawnErrorTypes.InvokedWhenShuttingDown]); return null; } // Verify it is actually a valid prefab - if (!NetworkManager.NetworkConfig.Prefabs.Contains(gameObject)) + if (!networkManager.NetworkConfig.Prefabs.Contains(gameObject)) { Debug.LogError(NetworkSpawnManager.InstantiateAndSpawnErrors[NetworkSpawnManager.InstantiateAndSpawnErrorTypes.NotRegisteredNetworkPrefab]); return null; } - return NetworkManager.SpawnManager.InstantiateAndSpawnNoParameterChecks(this, ownerClientId, destroyWithScene, isPlayerObject, forceOverride, position, rotation); + return networkManager.SpawnManager.InstantiateAndSpawnNoParameterChecks(this, ownerClientId, destroyWithScene, isPlayerObject, forceOverride, position, rotation); } /// @@ -859,7 +1635,8 @@ namespace Unity.Netcode /// Should the object be destroyed when the scene is changed public void Spawn(bool destroyWithScene = false) { - SpawnInternal(destroyWithScene, NetworkManager.ServerClientId, false); + var clientId = NetworkManager.DistributedAuthorityMode ? NetworkManager.LocalClientId : NetworkManager.ServerClientId; + SpawnInternal(destroyWithScene, clientId, false); } /// @@ -906,17 +1683,21 @@ namespace Unity.Netcode /// The new owner clientId public void ChangeOwnership(ulong newOwnerClientId) { - NetworkManager.SpawnManager.ChangeOwnership(this, newOwnerClientId); + NetworkManager.SpawnManager.ChangeOwnership(this, newOwnerClientId, HasAuthority); } internal void InvokeBehaviourOnLostOwnership() { - // Server already handles this earlier, hosts should ignore, all clients should update + // Always update the ownership table in distributed authority mode + if (NetworkManager.DistributedAuthorityMode) + { + NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId, true); + } + else // Server already handles this earlier, hosts should ignore and only client owners should update if (!NetworkManager.IsServer) { NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId, true); } - for (int i = 0; i < ChildNetworkBehaviours.Count; i++) { ChildNetworkBehaviours[i].InternalOnLostOwnership(); @@ -925,7 +1706,12 @@ namespace Unity.Netcode internal void InvokeBehaviourOnGainedOwnership() { - // Server already handles this earlier, hosts should ignore and only client owners should update + // Always update the ownership table in distributed authority mode + if (NetworkManager.DistributedAuthorityMode) + { + NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId); + } + else // Server already handles this earlier, hosts should ignore and only client owners should update if (!NetworkManager.IsServer && NetworkManager.LocalClientId == OwnerClientId) { NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId); @@ -971,6 +1757,13 @@ namespace Unity.Netcode private Transform m_CachedParent; // What is our last set parent Transform reference? private bool m_CachedWorldPositionStays = true; // Used to preserve the world position stays parameter passed in TrySetParent + /// + /// With distributed authority, we need to have a way to determine if the parenting action is authorized. + /// This is set when handling an incoming ParentSyncMessage and when running as a DAHost and a client has disconnected. + /// + internal bool AuthorityAppliedParenting = false; + + /// /// Returns the last known cached WorldPositionStays value for this NetworkObject /// @@ -989,9 +1782,15 @@ namespace Unity.Netcode internal void SetCachedParent(Transform parentTransform) { + AuthorityAppliedParenting = false; m_CachedParent = parentTransform; } + internal Transform GetCachedParent() + { + return m_CachedParent; + } + internal ulong? GetNetworkParenting() => m_LatestParent; internal void SetNetworkParenting(ulong? latestParent, bool worldPositionStays) @@ -1045,7 +1844,7 @@ namespace Unity.Netcode /// internal bool TryRemoveParentCachedWorldPositionStays() { - return TrySetParent((NetworkObject)null, m_CachedWorldPositionStays); + return InternalTrySetParent(null, m_CachedWorldPositionStays); } /// @@ -1079,19 +1878,29 @@ namespace Unity.Netcode return false; } - if (!NetworkManager.IsServer && !NetworkManager.ShutdownInProgress) + // DANGO-TODO: Do we want to worry about ownership permissions here? + // It wouldn't make sense to not allow parenting, but keeping this note here as a reminder. + var isAuthority = HasAuthority; + + // If we don't have authority and we are not shutting down, then don't allow any parenting. + // If we are shutting down and don't have authority then allow it. + if (!isAuthority && !NetworkManager.ShutdownInProgress) { return false; } - // If the parent is not null fail only if either of the two is true: - // - This instance is spawned and the parent is not. - // - This instance is not spawned and the parent is. - // Basically, don't allow parenting when either the child or parent is not spawned. - // Caveat: if the parent is null then we can allow parenting whether the instance is or is not spawned. + return InternalTrySetParent(parent, worldPositionStays); + } + + internal bool InternalTrySetParent(NetworkObject parent, bool worldPositionStays = true) + { + if (parent != null && (IsSpawned ^ parent.IsSpawned)) { - return false; + if (NetworkManager != null && !NetworkManager.ShutdownInProgress) + { + return false; + } } m_CachedWorldPositionStays = worldPositionStays; @@ -1110,7 +1919,7 @@ namespace Unity.Netcode private void OnTransformParentChanged() { - if (!AutoObjectParentSync) + if (!AutoObjectParentSync || NetworkManager.ShutdownInProgress) { return; } @@ -1122,36 +1931,50 @@ namespace Unity.Netcode if (NetworkManager == null || !NetworkManager.IsListening) { + // DANGO-TODO: Review as to whether we want to provide a better way to handle changing parenting of objects when the + // object is not spawned. Really, we shouldn't care about these types of changes. + if (NetworkManager.DistributedAuthorityMode && m_CachedParent != null && transform.parent == null) + { + m_CachedParent = null; + return; + } transform.parent = m_CachedParent; Debug.LogException(new NotListeningException($"{nameof(NetworkManager)} is not listening, start a server or host before reparenting")); return; } + var isAuthority = false; + // With distributed authority, we need to track "valid authoritative" parenting changes. + // So, either the authority or AuthorityAppliedParenting is considered a "valid parenting change". + isAuthority = HasAuthority || AuthorityAppliedParenting; + var distributedAuthority = NetworkManager.DistributedAuthorityMode; - if (!NetworkManager.IsServer) + // If we do not have authority and we are spawned + if (!isAuthority && IsSpawned) { - // Log exception if we are a client and not shutting down. - if (!NetworkManager.ShutdownInProgress) + + // If the cached parent has not already been set and we are in distributed authority mode, then log an exception and exit early as a non-authority instance + // is trying to set the parent. + if (distributedAuthority) + { + transform.parent = m_CachedParent; + NetworkLog.LogError($"[Not Owner] Only the owner-authority of child {gameObject.name}'s {nameof(NetworkObject)} component can reparent it!"); + } + else { transform.parent = m_CachedParent; Debug.LogException(new NotServerException($"Only the server can reparent {nameof(NetworkObject)}s")); } - else // Otherwise, if we are removing a parent then go ahead and allow parenting to occur - if (transform.parent == null) - { - m_LatestParent = null; - m_CachedParent = null; - InvokeBehaviourOnNetworkObjectParentChanged(null); - } return; } - else // Otherwise, on the serer side if this instance is not spawned... + if (!IsSpawned) { - // ,,,and we are removing the parent, then go ahead and allow parenting to occur + AuthorityAppliedParenting = false; + // and we are removing the parent, then go ahead and allow parenting to occur if (transform.parent == null) { m_LatestParent = null; - m_CachedParent = null; + SetCachedParent(null); InvokeBehaviourOnNetworkObjectParentChanged(null); } else @@ -1168,13 +1991,14 @@ namespace Unity.Netcode if (!transform.parent.TryGetComponent(out var parentObject)) { transform.parent = m_CachedParent; + AuthorityAppliedParenting = false; Debug.LogException(new InvalidParentException($"Invalid parenting, {nameof(NetworkObject)} moved under a non-{nameof(NetworkObject)} parent")); return; } - - if (!parentObject.IsSpawned) + else if (!parentObject.IsSpawned) { transform.parent = m_CachedParent; + AuthorityAppliedParenting = false; Debug.LogException(new SpawnStateException($"{nameof(NetworkObject)} can only be reparented under another spawned {nameof(NetworkObject)}")); return; } @@ -1187,6 +2011,8 @@ namespace Unity.Netcode removeParent = m_CachedParent != null; } + // This can be reset within ApplyNetworkParenting + var authorityApplied = AuthorityAppliedParenting; ApplyNetworkParenting(removeParent); var message = new ParentSyncMessage @@ -1195,6 +2021,7 @@ namespace Unity.Netcode IsLatestParentSet = m_LatestParent != null && m_LatestParent.HasValue, LatestParent = m_LatestParent, RemoveParent = removeParent, + AuthorityApplied = authorityApplied, WorldPositionStays = m_CachedWorldPositionStays, Position = m_CachedWorldPositionStays ? transform.position : transform.localPosition, Rotation = m_CachedWorldPositionStays ? transform.rotation : transform.localRotation, @@ -1209,20 +2036,48 @@ namespace Unity.Netcode m_CachedWorldPositionStays = true; } - unsafe + // If we are connected to a CMB service or we are running a mock CMB service then send to the "server" identifier + if (distributedAuthority) { - var maxCount = NetworkManager.ConnectedClientsIds.Count; - ulong* clientIds = stackalloc ulong[maxCount]; - int idx = 0; - foreach (var clientId in NetworkManager.ConnectedClientsIds) + if (!NetworkManager.DAHost) { - if (Observers.Contains(clientId)) + NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, 0); + return; + } + else + { + foreach (var clientId in NetworkManager.ConnectedClientsIds) { - clientIds[idx++] = clientId; + if (clientId == NetworkManager.ServerClientId) + { + continue; + } + NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, clientId); } } - - NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, clientIds, idx); + } + else + { + // Otherwise we are running in client-server =or= this has to be a DAHost instance. + // Send to all connected clients. + unsafe + { + var maxCount = NetworkManager.ConnectedClientsIds.Count; + ulong* clientIds = stackalloc ulong[maxCount]; + int idx = 0; + foreach (var clientId in NetworkManager.ConnectedClientsIds) + { + if (clientId == NetworkManager.ServerClientId) + { + continue; + } + if (Observers.Contains(clientId)) + { + clientIds[idx++] = clientId; + } + } + NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, clientIds, idx); + } } } @@ -1236,7 +2091,7 @@ namespace Unity.Netcode // we call CheckOrphanChildren() method and quickly iterate over OrphanChildren set and see if we can reparent/adopt one. internal static HashSet OrphanChildren = new HashSet(); - internal bool ApplyNetworkParenting(bool removeParent = false, bool ignoreNotSpawned = false) + internal bool ApplyNetworkParenting(bool removeParent = false, bool ignoreNotSpawned = false, bool orphanedChildPass = false) { if (!AutoObjectParentSync) { @@ -1289,7 +2144,7 @@ namespace Unity.Netcode SetNetworkParenting(parentNetworkObject.NetworkObjectId, false); // Set the cached parent - m_CachedParent = parentNetworkObject.transform; + SetCachedParent(parentNetworkObject.transform); return true; } @@ -1303,7 +2158,7 @@ namespace Unity.Netcode // or a parent was removed prior to the client connecting (i.e. in-scene placed NetworkObjects) if (removeParent || !m_LatestParent.HasValue) { - m_CachedParent = null; + SetCachedParent(null); // We must use Transform.SetParent when taking WorldPositionStays into // consideration, otherwise just setting transform.parent = null defaults // to WorldPositionStays which can cause scaling issues if the parent's @@ -1324,9 +2179,16 @@ namespace Unity.Netcode // If we made it here, then parent this instance under the parentObject var parentObject = NetworkManager.SpawnManager.SpawnedObjects[m_LatestParent.Value]; - m_CachedParent = parentObject.transform; + // If we are handling an orphaned child and its parent is orphaned too, then don't parent yet. + if (orphanedChildPass) + { + if (OrphanChildren.Contains(parentObject)) + { + return false; + } + } + SetCachedParent(parentObject.transform); transform.SetParent(parentObject.transform, m_CachedWorldPositionStays); - InvokeBehaviourOnNetworkObjectParentChanged(parentObject); return true; } @@ -1336,7 +2198,7 @@ namespace Unity.Netcode var objectsToRemove = new List(); foreach (var orphanObject in OrphanChildren) { - if (orphanObject.ApplyNetworkParenting()) + if (orphanObject.ApplyNetworkParenting(orphanedChildPass: true)) { objectsToRemove.Add(orphanObject); } @@ -1351,6 +2213,11 @@ namespace Unity.Netcode { NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId); + if (SceneMigrationSynchronization && NetworkManager.NetworkConfig.EnableSceneManagement) + { + AddNetworkObjectToSceneChangedUpdates(this); + } + for (int i = 0; i < ChildNetworkBehaviours.Count; i++) { if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy) @@ -1379,6 +2246,11 @@ namespace Unity.Netcode { ChildNetworkBehaviours[i].InternalOnNetworkDespawn(); } + + if (SceneMigrationSynchronization && NetworkManager.NetworkConfig.EnableSceneManagement) + { + RemoveNetworkObjectFromSceneChangedUpdates(this); + } } private List m_ChildNetworkBehaviours; @@ -1408,6 +2280,14 @@ namespace Unity.Netcode internal void WriteNetworkVariableData(FastBufferWriter writer, ulong targetClientId) { + if (NetworkManager.DistributedAuthorityMode) + { + writer.WriteValueSafe((ushort)ChildNetworkBehaviours.Count); + if (ChildNetworkBehaviours.Count == 0) + { + return; + } + } for (int i = 0; i < ChildNetworkBehaviours.Count; i++) { var behavior = ChildNetworkBehaviours[i]; @@ -1450,17 +2330,29 @@ namespace Unity.Netcode /// /// Only invoked during first synchronization of a NetworkObject (late join or newly spawned) /// - internal void SetNetworkVariableData(FastBufferReader reader, ulong clientId) + internal bool SetNetworkVariableData(FastBufferReader reader, ulong clientId) { + if (NetworkManager.DistributedAuthorityMode) + { + var readerPosition = reader.Position; + reader.ReadValueSafe(out ushort behaviorCount); + if (behaviorCount != ChildNetworkBehaviours.Count) + { + Debug.LogError($"Network Behavior Count Mismatch! [{readerPosition}][{reader.Position}]"); + return false; + } + } + for (int i = 0; i < ChildNetworkBehaviours.Count; i++) { var behaviour = ChildNetworkBehaviours[i]; behaviour.InitializeVariables(); behaviour.SetNetworkVariableData(reader, clientId); } + return true; } - internal ushort GetNetworkBehaviourOrderIndex(NetworkBehaviour instance) + public ushort GetNetworkBehaviourOrderIndex(NetworkBehaviour instance) { // read the cached index, and verify it first if (instance.NetworkBehaviourIdCache < ChildNetworkBehaviours.Count) @@ -1487,7 +2379,7 @@ namespace Unity.Netcode return 0; } - public NetworkBehaviour GetNetworkBehaviourAtOrderIndex(ushort index) + internal NetworkBehaviour GetNetworkBehaviourAtOrderIndex(ushort index) { if (index >= ChildNetworkBehaviours.Count) { @@ -1515,10 +2407,11 @@ namespace Unity.Netcode internal struct SceneObject { - private byte m_BitField; + private ushort m_BitField; public uint Hash; public ulong NetworkObjectId; public ulong OwnerClientId; + public ushort OwnershipFlags; public bool IsPlayerObject { @@ -1565,6 +2458,34 @@ namespace Unity.Netcode set => ByteUtility.SetBit(ref m_BitField, 6, value); } + public bool DontDestroyWithOwner + { + get => ByteUtility.GetBit(m_BitField, 7); + set => ByteUtility.SetBit(ref m_BitField, 7, value); + } + + public bool HasOwnershipFlags + { + get => ByteUtility.GetBit(m_BitField, 8); + set => ByteUtility.SetBit(ref m_BitField, 8, value); + } + + public bool SyncObservers + { + get => ByteUtility.GetBit(m_BitField, 9); + set => ByteUtility.SetBit(ref m_BitField, 9, value); + } + + public bool SpawnWithObservers + { + get => ByteUtility.GetBit(m_BitField, 10); + set => ByteUtility.SetBit(ref m_BitField, 10, value); + } + + // When handling the initial synchronization of NetworkObjects, + // this will be populated with the known observers. + public ulong[] Observers; + //If(Metadata.HasParent) public ulong ParentObjectId; @@ -1591,6 +2512,11 @@ namespace Unity.Netcode public void Serialize(FastBufferWriter writer) { + if (OwnerObject.NetworkManager.DistributedAuthorityMode) + { + HasOwnershipFlags = true; + SpawnWithObservers = OwnerObject.SpawnWithObservers; + } writer.WriteValueSafe(m_BitField); writer.WriteValueSafe(Hash); BytePacker.WriteValueBitPacked(writer, NetworkObjectId); @@ -1605,6 +2531,20 @@ namespace Unity.Netcode } } + if (HasOwnershipFlags) + { + writer.WriteValueSafe(OwnershipFlags); + } + + if (SyncObservers) + { + BytePacker.WriteValuePacked(writer, Observers.Length); + foreach (var observer in Observers) + { + BytePacker.WriteValuePacked(writer, observer); + } + } + var writeSize = 0; writeSize += HasTransform ? FastBufferWriter.GetWriteSize() : 0; writeSize += FastBufferWriter.GetWriteSize(); @@ -1621,7 +2561,14 @@ namespace Unity.Netcode // The NetworkSceneHandle is the server-side relative // scene handle that the NetworkObject resides in. - writer.WriteValue(OwnerObject.GetSceneOriginHandle()); + if (OwnerObject.NetworkManager.DistributedAuthorityMode) + { + writer.WriteValue(OwnerObject.NetworkSceneHandle); + } + else + { + writer.WriteValue(OwnerObject.GetSceneOriginHandle()); + } // Synchronize NetworkVariables and NetworkBehaviours var bufferSerializer = new BufferSerializer(new BufferSerializerWriter(writer)); @@ -1645,6 +2592,24 @@ namespace Unity.Netcode } } + if (HasOwnershipFlags) + { + reader.ReadValueSafe(out OwnershipFlags); + } + + if (SyncObservers) + { + var observerCount = 0; + var observerId = (ulong)0; + ByteUnpacker.ReadValuePacked(reader, out observerCount); + Observers = new ulong[observerCount]; + for (int i = 0; i < observerCount; i++) + { + ByteUnpacker.ReadValuePacked(reader, out observerId); + Observers[i] = observerId; + } + } + var readSize = 0; readSize += HasTransform ? FastBufferWriter.GetWriteSize() : 0; readSize += FastBufferWriter.GetWriteSize(); @@ -1724,29 +2689,47 @@ namespace Unity.Netcode } else { + var seekToEndOfSynchData = 0; var reader = serializer.GetFastBufferReader(); - - reader.ReadValueSafe(out ushort sizeOfSynchronizationData); - var seekToEndOfSynchData = reader.Position + sizeOfSynchronizationData; - // Apply the network variable synchronization data - SetNetworkVariableData(reader, targetClientId); - // Read the number of NetworkBehaviours to synchronize - reader.ReadValueSafe(out byte numberSynchronized); - var networkBehaviourId = (ushort)0; - - // If a NetworkBehaviour writes synchronization data, it will first - // write its NetworkBehaviourId so when deserializing the client-side - // can find the right NetworkBehaviour to deserialize the synchronization data. - for (int i = 0; i < numberSynchronized; i++) + try { - serializer.SerializeValue(ref networkBehaviourId); - var networkBehaviour = GetNetworkBehaviourAtOrderIndex(networkBehaviourId); - networkBehaviour.Synchronize(ref serializer, targetClientId); + reader.ReadValueSafe(out ushort sizeOfSynchronizationData); + seekToEndOfSynchData = reader.Position + sizeOfSynchronizationData; + // Apply the network variable synchronization data + if (!SetNetworkVariableData(reader, targetClientId)) + { + reader.Seek(seekToEndOfSynchData); + return; + } + + // Read the number of NetworkBehaviours to synchronize + reader.ReadValueSafe(out byte numberSynchronized); + + var networkBehaviourId = (ushort)0; + + // If a NetworkBehaviour writes synchronization data, it will first + // write its NetworkBehaviourId so when deserializing the client-side + // can find the right NetworkBehaviour to deserialize the synchronization data. + for (int i = 0; i < numberSynchronized; i++) + { + reader.ReadValueSafe(out networkBehaviourId); + var networkBehaviour = GetNetworkBehaviourAtOrderIndex(networkBehaviourId); + networkBehaviour.Synchronize(ref serializer, targetClientId); + } + + if (seekToEndOfSynchData != reader.Position) + { + Debug.LogWarning($"[Size mismatch] Expected: {seekToEndOfSynchData} Currently At: {reader.Position}!"); + } + } + catch + { + reader.Seek(seekToEndOfSynchData); } } } - internal SceneObject GetMessageSceneObject(ulong targetClientId) + internal SceneObject GetMessageSceneObject(ulong targetClientId = NetworkManager.ServerClientId, bool syncObservers = false) { var obj = new SceneObject { @@ -1755,6 +2738,12 @@ namespace Unity.Netcode IsPlayerObject = IsPlayerObject, IsSceneObject = IsSceneObject ?? true, DestroyWithScene = DestroyWithScene, + DontDestroyWithOwner = DontDestroyWithOwner, + HasOwnershipFlags = NetworkManager.DistributedAuthorityMode, + OwnershipFlags = (ushort)Ownership, + SyncObservers = syncObservers, + Observers = syncObservers ? Observers.ToArray() : null, + NetworkSceneHandle = NetworkSceneHandle, Hash = HostCheckForGlobalObjectIdHashOverride(), OwnerObject = this, TargetClientId = targetClientId @@ -1797,6 +2786,12 @@ namespace Unity.Netcode var syncRotationPositionLocalSpaceRelative = obj.HasParent && !m_CachedWorldPositionStays; var syncScaleLocalSpaceRelative = obj.HasParent && !m_CachedWorldPositionStays; + // Always synchronize in-scene placed object's scale using local space + if (obj.IsSceneObject) + { + syncScaleLocalSpaceRelative = obj.HasParent; + } + // If auto object synchronization is turned off if (!AutoObjectParentSync) { @@ -1808,7 +2803,6 @@ namespace Unity.Netcode syncScaleLocalSpaceRelative = obj.HasParent; } - obj.Transform = new SceneObject.TransformData { // If we are parented and we have the m_CachedWorldPositionStays disabled, then use local space @@ -1824,7 +2818,6 @@ namespace Unity.Netcode Scale = syncScaleLocalSpaceRelative ? transform.localScale : transform.lossyScale, }; } - return obj; } @@ -1835,8 +2828,9 @@ namespace Unity.Netcode /// Deserialized scene object data /// FastBufferReader for the NetworkVariable data /// NetworkManager instance - /// optional to use NetworkObject deserialized - internal static NetworkObject AddSceneObject(in SceneObject sceneObject, FastBufferReader reader, NetworkManager networkManager) + /// will be true if invoked by CreateObjectMessage + /// The deserialized NetworkObject or null if deserialization failed + internal static NetworkObject AddSceneObject(in SceneObject sceneObject, FastBufferReader reader, NetworkManager networkManager, bool invokedByMessage = false) { //Attempt to create a local NetworkObject var networkObject = networkManager.SpawnManager.CreateLocalNetworkObject(sceneObject); @@ -1875,6 +2869,55 @@ namespace Unity.Netcode // Spawn the NetworkObject networkManager.SpawnManager.SpawnNetworkObjectLocally(networkObject, sceneObject, sceneObject.DestroyWithScene); + if (sceneObject.SyncObservers) + { + foreach (var observer in sceneObject.Observers) + { + networkObject.Observers.Add(observer); + } + } + + if (networkManager.DistributedAuthorityMode) + { + networkObject.SpawnWithObservers = sceneObject.SpawnWithObservers; + } + + // If this was not invoked by a message handler, we are in distributed authority mode, and we are spawning with observers or + // we are an observer (in case SpawnWithObservers is false) + if (networkManager.DistributedAuthorityMode && (!invokedByMessage || networkObject.IsPlayerObject) && + (networkObject.SpawnWithObservers || networkObject.Observers.Contains(networkManager.LocalClientId))) + { + if (networkManager.LocalClient != null && networkManager.LocalClient.PlayerObject != null) + { + var playerObject = networkManager.LocalClient.PlayerObject; + if (networkObject.IsPlayerObject) + { + // If it is another player, then make sure the local player is aware of the player + playerObject.Observers.Add(networkObject.OwnerClientId); + } + + // Assure the local player has observability + networkObject.Observers.Add(playerObject.OwnerClientId); + + // If it is a player object, then add it to all known spawned NetworkObjects that spawn with observers + if (networkObject.IsPlayerObject) + { + foreach (var netObject in networkManager.SpawnManager.SpawnedObjects) + { + if (netObject.Value.SpawnWithObservers) + { + netObject.Value.Observers.Add(networkObject.OwnerClientId); + } + } + } + + // Add all known players to the observers list if they don't already exist + foreach (var player in networkManager.SpawnManager.PlayerObjects) + { + networkObject.Observers.Add(player.OwnerClientId); + } + } + } return networkObject; } @@ -1929,22 +2972,37 @@ namespace Unity.Netcode internal void SceneChangedUpdate(Scene scene, bool notify = false) { // Avoiding edge case scenarios, if no NetworkSceneManager exit early - if (NetworkManager.SceneManager == null) + if (NetworkManager.SceneManager == null || !IsSpawned) { return; } + if (NetworkManager.SceneManager.IsSceneEventInProgress()) + { + return; + } + + var isAuthority = HasAuthority; SceneOriginHandle = scene.handle; - // Clients need to update the NetworkSceneHandle - if (!NetworkManager.IsServer && NetworkManager.SceneManager.ClientSceneHandleToServerSceneHandle.ContainsKey(SceneOriginHandle)) + + // non-authority needs to update the NetworkSceneHandle + if (!isAuthority && NetworkManager.SceneManager.ClientSceneHandleToServerSceneHandle.ContainsKey(SceneOriginHandle)) { NetworkSceneHandle = NetworkManager.SceneManager.ClientSceneHandleToServerSceneHandle[SceneOriginHandle]; } - else if (NetworkManager.IsServer) + else if (isAuthority) { - // Since the server is the source of truth for the NetworkSceneHandle, + // Since the authority is the source of truth for the NetworkSceneHandle, // the NetworkSceneHandle is the same as the SceneOriginHandle. - NetworkSceneHandle = SceneOriginHandle; + if (NetworkManager.DistributedAuthorityMode) + { + NetworkSceneHandle = NetworkManager.SceneManager.ClientSceneHandleToServerSceneHandle[SceneOriginHandle]; + } + else + { + NetworkSceneHandle = SceneOriginHandle; + } + } else // Otherwise, the client did not find the client to server scene handle if (NetworkManager.LogLevel == LogLevel.Developer) @@ -1959,13 +3017,44 @@ namespace Unity.Netcode } OnMigratedToNewScene?.Invoke(); - // Only the server side will notify clients of non-parented NetworkObject scene changes - if (NetworkManager.IsServer && notify && transform.parent == null) + // Only the authority side will notify clients of non-parented NetworkObject scene changes + if (isAuthority && notify && transform.parent == null) { NetworkManager.SceneManager.NotifyNetworkObjectSceneChanged(this); } } + internal static Dictionary NetworkObjectsToSynchronizeSceneChanges = new Dictionary(); + + internal static void AddNetworkObjectToSceneChangedUpdates(NetworkObject networkObject) + { + if (!NetworkObjectsToSynchronizeSceneChanges.ContainsKey(networkObject.NetworkObjectId)) + { + NetworkObjectsToSynchronizeSceneChanges.Add(networkObject.NetworkObjectId, networkObject); + } + + networkObject.UpdateForSceneChanges(); + } + + internal static void RemoveNetworkObjectFromSceneChangedUpdates(NetworkObject networkObject) + { + NetworkObjectsToSynchronizeSceneChanges.Remove(networkObject.NetworkObjectId); + } + + internal static void UpdateNetworkObjectSceneChanges() + { + foreach (var entry in NetworkObjectsToSynchronizeSceneChanges) + { + entry.Value.UpdateForSceneChanges(); + } + } + + private void Awake() + { + SetCachedParent(transform.parent); + SceneOrigin = gameObject.scene; + } + /// /// Update /// Detects if a NetworkObject's scene has changed for both server and client instances @@ -1977,13 +3066,13 @@ namespace Unity.Netcode /// to add this same functionality to in-scene placed NetworkObjects until we have a way to generate /// per-NetworkObject-instance unique GlobalObjectIdHash values for in-scene placed NetworkObjects. /// - private void Update() + internal void UpdateForSceneChanges() { // Early exit if SceneMigrationSynchronization is disabled, there is no NetworkManager assigned, // the NetworkManager is shutting down, the NetworkObject is not spawned, it is an in-scene placed // NetworkObject, or the GameObject's current scene handle is the same as the SceneOriginHandle - if (!SceneMigrationSynchronization || NetworkManager == null || NetworkManager.ShutdownInProgress || !IsSpawned - || IsSceneObject != false || gameObject.scene.handle == SceneOriginHandle) + if (!SceneMigrationSynchronization || !IsSpawned || NetworkManager == null || NetworkManager.ShutdownInProgress || + !NetworkManager.NetworkConfig.EnableSceneManagement || IsSceneObject != false || gameObject.scene.handle == SceneOriginHandle) { return; } @@ -2048,7 +3137,7 @@ namespace Unity.Netcode { if (networkBehaviour.IsSpawned && IsSpawned) { - if (NetworkManager.LogLevel == LogLevel.Developer) + if (NetworkManager?.LogLevel == LogLevel.Developer) { NetworkLog.LogWarning($"{nameof(NetworkBehaviour)}-{networkBehaviour.name} is being destroyed while {nameof(NetworkObject)}-{name} is still spawned! (could break state synchronization)"); } diff --git a/Runtime/Logging/NetworkLog.cs b/Runtime/Logging/NetworkLog.cs index c8160f0..cd29c6a 100644 --- a/Runtime/Logging/NetworkLog.cs +++ b/Runtime/Logging/NetworkLog.cs @@ -39,6 +39,12 @@ namespace Unity.Netcode /// The message to log public static void LogInfoServer(string message) => LogServer(message, LogType.Info); + /// + /// Logs an info log locally and on the session owner if possible. + /// + /// The message to log + public static void LogInfoSessionOwner(string message) => LogServer(message, LogType.Info); + /// /// Logs a warning log locally and on the server if possible. /// @@ -58,7 +64,8 @@ namespace Unity.Netcode var networkManager = NetworkManagerOverride ??= NetworkManager.Singleton; // Get the sender of the local log ulong localId = networkManager?.LocalClientId ?? 0; - bool isServer = networkManager?.IsServer ?? true; + bool isServer = networkManager && networkManager.DistributedAuthorityMode ? networkManager.LocalClient.IsSessionOwner : + networkManager && !networkManager.DistributedAuthorityMode ? networkManager.IsServer : true; switch (logType) { case LogType.Info: @@ -98,7 +105,8 @@ namespace Unity.Netcode var networkMessage = new ServerLogMessage { LogType = logType, - Message = message + Message = message, + SenderId = localId }; var size = networkManager.ConnectionManager.SendMessage(ref networkMessage, NetworkDelivery.ReliableFragmentedSequenced, NetworkManager.ServerClientId); @@ -106,9 +114,19 @@ namespace Unity.Netcode } } - internal static void LogInfoServerLocal(string message, ulong sender) => Debug.Log($"[Netcode-Server Sender={sender}] {message}"); - internal static void LogWarningServerLocal(string message, ulong sender) => Debug.LogWarning($"[Netcode-Server Sender={sender}] {message}"); - internal static void LogErrorServerLocal(string message, ulong sender) => Debug.LogError($"[Netcode-Server Sender={sender}] {message}"); + private static string Header() + { + var networkManager = NetworkManagerOverride ??= NetworkManager.Singleton; + if (networkManager.DistributedAuthorityMode) + { + return "Session-Owner"; + } + return "Netcode-Server"; + } + + internal static void LogInfoServerLocal(string message, ulong sender) => Debug.Log($"[{Header()} Sender={sender}] {message}"); + internal static void LogWarningServerLocal(string message, ulong sender) => Debug.LogWarning($"[{Header()} Sender={sender}] {message}"); + internal static void LogErrorServerLocal(string message, ulong sender) => Debug.LogError($"[{Header()} Sender={sender}] {message}"); internal enum LogType : byte { diff --git a/Runtime/Messaging/CustomMessageManager.cs b/Runtime/Messaging/CustomMessageManager.cs index 4e15ec6..1b8626c 100644 --- a/Runtime/Messaging/CustomMessageManager.cs +++ b/Runtime/Messaging/CustomMessageManager.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using Unity.Collections; +using UnityEngine; namespace Unity.Netcode { @@ -151,18 +152,14 @@ namespace Unity.Netcode // We dont know what size to use. Try every (more collision prone) if (m_NamedMessageHandlers32.TryGetValue(hash, out HandleNamedMessageDelegate messageHandler32)) { - // handler can remove itself, cache the name for metrics - string messageName = m_MessageHandlerNameLookup32[hash]; messageHandler32(sender, reader); - m_NetworkManager.NetworkMetrics.TrackNamedMessageReceived(sender, messageName, bytesCount); + m_NetworkManager.NetworkMetrics.TrackNamedMessageReceived(sender, m_MessageHandlerNameLookup32[hash], bytesCount); } if (m_NamedMessageHandlers64.TryGetValue(hash, out HandleNamedMessageDelegate messageHandler64)) { - // handler can remove itself, cache the name for metrics - string messageName = m_MessageHandlerNameLookup64[hash]; messageHandler64(sender, reader); - m_NetworkManager.NetworkMetrics.TrackNamedMessageReceived(sender, messageName, bytesCount); + m_NetworkManager.NetworkMetrics.TrackNamedMessageReceived(sender, m_MessageHandlerNameLookup64[hash], bytesCount); } } else @@ -173,19 +170,15 @@ namespace Unity.Netcode case HashSize.VarIntFourBytes: if (m_NamedMessageHandlers32.TryGetValue(hash, out HandleNamedMessageDelegate messageHandler32)) { - // handler can remove itself, cache the name for metrics - string messageName = m_MessageHandlerNameLookup32[hash]; messageHandler32(sender, reader); - m_NetworkManager.NetworkMetrics.TrackNamedMessageReceived(sender, messageName, bytesCount); + m_NetworkManager.NetworkMetrics.TrackNamedMessageReceived(sender, m_MessageHandlerNameLookup32[hash], bytesCount); } break; case HashSize.VarIntEightBytes: if (m_NamedMessageHandlers64.TryGetValue(hash, out HandleNamedMessageDelegate messageHandler64)) { - // handler can remove itself, cache the name for metrics - string messageName = m_MessageHandlerNameLookup64[hash]; messageHandler64(sender, reader); - m_NetworkManager.NetworkMetrics.TrackNamedMessageReceived(sender, messageName, bytesCount); + m_NetworkManager.NetworkMetrics.TrackNamedMessageReceived(sender, m_MessageHandlerNameLookup64[hash], bytesCount); } break; } @@ -199,6 +192,14 @@ namespace Unity.Netcode /// The callback to run when a named message is received. public void RegisterNamedMessageHandler(string name, HandleNamedMessageDelegate callback) { + if (string.IsNullOrEmpty(name)) + { + if (m_NetworkManager.LogLevel <= LogLevel.Error) + { + Debug.LogError($"[{nameof(RegisterNamedMessageHandler)}] Cannot register a named message of type null or empty!"); + } + return; + } var hash32 = XXHash.Hash32(name); var hash64 = XXHash.Hash64(name); @@ -215,6 +216,15 @@ namespace Unity.Netcode /// The name of the message. public void UnregisterNamedMessageHandler(string name) { + if (string.IsNullOrEmpty(name)) + { + if (m_NetworkManager.LogLevel <= LogLevel.Error) + { + Debug.LogError($"[{nameof(UnregisterNamedMessageHandler)}] Cannot unregister a named message of type null or empty!"); + } + return; + } + var hash32 = XXHash.Hash32(name); var hash64 = XXHash.Hash64(name); diff --git a/Runtime/Messaging/DeferredMessageManager.cs b/Runtime/Messaging/DeferredMessageManager.cs index 728f0a7..f05d000 100644 --- a/Runtime/Messaging/DeferredMessageManager.cs +++ b/Runtime/Messaging/DeferredMessageManager.cs @@ -15,6 +15,7 @@ namespace Unity.Netcode } protected struct TriggerInfo { + public string MessageType; public float Expiry; public NativeList TriggerData; } @@ -36,7 +37,7 @@ namespace Unity.Netcode /// There is a one second maximum lifetime of triggers to avoid memory leaks. After one second has passed /// without the requested object ID being spawned, the triggers for it are automatically deleted. /// - public virtual unsafe void DeferMessage(IDeferredNetworkMessageManager.TriggerType trigger, ulong key, FastBufferReader reader, ref NetworkContext context) + public virtual unsafe void DeferMessage(IDeferredNetworkMessageManager.TriggerType trigger, ulong key, FastBufferReader reader, ref NetworkContext context, string messageType) { if (!m_Triggers.TryGetValue(trigger, out var triggers)) { @@ -48,6 +49,7 @@ namespace Unity.Netcode { triggerInfo = new TriggerInfo { + MessageType = messageType, Expiry = m_NetworkManager.RealTimeProvider.RealTimeSinceStartup + m_NetworkManager.NetworkConfig.SpawnTimeout, TriggerData = new NativeList(Allocator.Persistent) }; @@ -90,11 +92,29 @@ namespace Unity.Netcode } } + /// + /// Used for testing purposes + /// + internal static bool IncludeMessageType = true; + + private string GetWarningMessage(IDeferredNetworkMessageManager.TriggerType triggerType, ulong key, TriggerInfo triggerInfo, float spawnTimeout) + { + if (IncludeMessageType) + { + return $"[Deferred {triggerType}] Messages were received for a trigger of type {triggerInfo.MessageType} associated with id ({key}), but the {nameof(NetworkObject)} was not received within the timeout period {spawnTimeout} second(s)."; + } + else + { + return $"Deferred messages were received for a trigger of type {triggerType} associated with id ({key}), but the {nameof(NetworkObject)} was not received within the timeout period {spawnTimeout} second(s)."; + } + } + protected virtual void PurgeTrigger(IDeferredNetworkMessageManager.TriggerType triggerType, ulong key, TriggerInfo triggerInfo) { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) + var logLevel = m_NetworkManager.DistributedAuthorityMode ? LogLevel.Developer : LogLevel.Normal; + if (NetworkLog.CurrentLogLevel <= logLevel) { - NetworkLog.LogWarning($"Deferred messages were received for a trigger of type {triggerType} with key {key}, but that trigger was not received within within {m_NetworkManager.NetworkConfig.SpawnTimeout} second(s)."); + NetworkLog.LogWarning(GetWarningMessage(triggerType, key, triggerInfo, m_NetworkManager.NetworkConfig.SpawnTimeout)); } foreach (var data in triggerInfo.TriggerData) diff --git a/Runtime/Messaging/IDeferredNetworkMessageManager.cs b/Runtime/Messaging/IDeferredNetworkMessageManager.cs index 0a9ec91..0f55de9 100644 --- a/Runtime/Messaging/IDeferredNetworkMessageManager.cs +++ b/Runtime/Messaging/IDeferredNetworkMessageManager.cs @@ -1,3 +1,4 @@ + namespace Unity.Netcode { internal interface IDeferredNetworkMessageManager @@ -17,7 +18,7 @@ namespace Unity.Netcode /// There is a one second maximum lifetime of triggers to avoid memory leaks. After one second has passed /// without the requested object ID being spawned, the triggers for it are automatically deleted. /// - void DeferMessage(TriggerType trigger, ulong key, FastBufferReader reader, ref NetworkContext context); + void DeferMessage(TriggerType trigger, ulong key, FastBufferReader reader, ref NetworkContext context, string messageType = null); /// /// Cleans up any trigger that's existed for more than a second. diff --git a/Runtime/Messaging/Messages/ChangeOwnershipMessage.cs b/Runtime/Messaging/Messages/ChangeOwnershipMessage.cs index b0d1ca7..7ab41b8 100644 --- a/Runtime/Messaging/Messages/ChangeOwnershipMessage.cs +++ b/Runtime/Messaging/Messages/ChangeOwnershipMessage.cs @@ -1,3 +1,4 @@ + namespace Unity.Netcode { internal struct ChangeOwnershipMessage : INetworkMessage, INetworkSerializeByMemcpy @@ -6,11 +7,146 @@ namespace Unity.Netcode public ulong NetworkObjectId; public ulong OwnerClientId; + // DANGOEXP TODO: Remove these notes or change their format + // SERVICE NOTES: + // When forwarding the message to clients on the CMB Service side, + // you can set the ClientIdCount to 0 and skip writing the ClientIds. + // See the NetworkObjet.OwnershipRequest for more potential service side additions + + /// + /// When requesting, RequestClientId is the requestor. + /// When approving, RequestClientId is the owner that approved. + /// When responding (only for denied), RequestClientId is the requestor + /// + internal ulong RequestClientId; + internal int ClientIdCount; + internal ulong[] ClientIds; + internal bool DistributedAuthorityMode; + internal ushort OwnershipFlags; + internal byte OwnershipRequestResponseStatus; + private byte m_OwnershipMessageTypeFlags; + + private const byte k_OwnershipChanging = 0x01; + private const byte k_OwnershipFlagsUpdate = 0x02; + private const byte k_RequestOwnership = 0x04; + private const byte k_RequestApproved = 0x08; + private const byte k_RequestDenied = 0x10; + + // If no flags are set, then ownership is changing + internal bool OwnershipIsChanging + { + get + { + return GetFlag(k_OwnershipChanging); + } + + set + { + SetFlag(value, k_OwnershipChanging); + } + } + + internal bool OwnershipFlagsUpdate + { + get + { + return GetFlag(k_OwnershipFlagsUpdate); + } + + set + { + SetFlag(value, k_OwnershipFlagsUpdate); + } + } + + internal bool RequestOwnership + { + get + { + return GetFlag(k_RequestOwnership); + } + + set + { + SetFlag(value, k_RequestOwnership); + } + } + + internal bool RequestApproved + { + get + { + return GetFlag(k_RequestApproved); + } + + set + { + SetFlag(value, k_RequestApproved); + } + } + + internal bool RequestDenied + { + get + { + return GetFlag(k_RequestDenied); + } + + set + { + SetFlag(value, k_RequestDenied); + } + } + + private bool GetFlag(int flag) + { + return (m_OwnershipMessageTypeFlags & flag) != 0; + } + + private void SetFlag(bool set, byte flag) + { + if (set) { m_OwnershipMessageTypeFlags = (byte)(m_OwnershipMessageTypeFlags | flag); } + else { m_OwnershipMessageTypeFlags = (byte)(m_OwnershipMessageTypeFlags & ~flag); } + } public void Serialize(FastBufferWriter writer, int targetVersion) { BytePacker.WriteValueBitPacked(writer, NetworkObjectId); BytePacker.WriteValueBitPacked(writer, OwnerClientId); + if (DistributedAuthorityMode) + { + BytePacker.WriteValueBitPacked(writer, ClientIdCount); + if (ClientIdCount > 0) + { + if (ClientIdCount != ClientIds.Length) + { + throw new System.Exception($"[{nameof(ChangeOwnershipMessage)}] ClientIdCount is {ClientIdCount} but the ClientIds length is {ClientIds.Length}!"); + } + foreach (var clientId in ClientIds) + { + BytePacker.WriteValueBitPacked(writer, clientId); + } + } + + writer.WriteValueSafe(m_OwnershipMessageTypeFlags); + if (OwnershipFlagsUpdate || OwnershipIsChanging) + { + writer.WriteValueSafe(OwnershipFlags); + } + + // When requesting, it is the requestor + // When approving, it is the owner that approved + // When denied, it is the requestor + if (RequestOwnership || RequestApproved || RequestDenied) + { + writer.WriteValueSafe(RequestClientId); + + if (RequestDenied) + { + writer.WriteValueSafe(OwnershipRequestResponseStatus); + } + } + } } public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) @@ -22,46 +158,241 @@ namespace Unity.Netcode } ByteUnpacker.ReadValueBitPacked(reader, out NetworkObjectId); ByteUnpacker.ReadValueBitPacked(reader, out OwnerClientId); - if (!networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId)) + + if (networkManager.DistributedAuthorityMode) { - networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context); - return false; + ByteUnpacker.ReadValueBitPacked(reader, out ClientIdCount); + if (ClientIdCount > 0) + { + ClientIds = new ulong[ClientIdCount]; + var clientId = (ulong)0; + for (int i = 0; i < ClientIdCount; i++) + { + ByteUnpacker.ReadValueBitPacked(reader, out clientId); + ClientIds[i] = clientId; + } + } + + reader.ReadValueSafe(out m_OwnershipMessageTypeFlags); + if (OwnershipFlagsUpdate || OwnershipIsChanging) + { + reader.ReadValueSafe(out OwnershipFlags); + } + + // When requesting, it is the requestor + // When approving, it is the owner that approved + // When denied, it is the requestor + if (RequestOwnership || RequestApproved || RequestDenied) + { + reader.ReadValueSafe(out RequestClientId); + + if (RequestDenied) + { + reader.ReadValueSafe(out OwnershipRequestResponseStatus); + } + } } + // If we are not a DAHost instance and the NetworkObject does not exist then defer it as it very likely is not spawned yet. + // Otherwise if we are the DAHost and it does not exist then we want to forward this message because when the NetworkObject + // is made visible again, the ownership flags and owner information will be synchronized with the DAHost by the current + // authority of the NetworkObject in question. + if (!networkManager.DAHost && !networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId)) + { + networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, GetType().Name); + return false; + } return true; } public void Handle(ref NetworkContext context) { var networkManager = (NetworkManager)context.SystemOwner; - var networkObject = networkManager.SpawnManager.SpawnedObjects[NetworkObjectId]; - var originalOwner = networkObject.OwnerClientId; + // If we are the DAHost then forward this message + if (networkManager.DAHost) + { + var clientList = ClientIdCount > 0 ? ClientIds : networkManager.ConnectedClientsIds; + + var message = new ChangeOwnershipMessage() + { + NetworkObjectId = NetworkObjectId, + OwnerClientId = OwnerClientId, + DistributedAuthorityMode = true, + OwnershipFlags = OwnershipFlags, + RequestClientId = RequestClientId, + ClientIdCount = 0, + m_OwnershipMessageTypeFlags = m_OwnershipMessageTypeFlags, + }; + + if (RequestDenied) + { + // If the local DAHost's client is not the target, then forward to the target + if (RequestClientId != networkManager.LocalClientId) + { + message.OwnershipRequestResponseStatus = OwnershipRequestResponseStatus; + networkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.Reliable, RequestClientId); + // We don't want the local DAHost's client to process this message, so exit early + return; + } + } + else if (RequestOwnership) + { + // If the DAHost client is not authority, just forward the message to the authority + if (OwnerClientId != networkManager.LocalClientId) + { + networkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.Reliable, OwnerClientId); + // We don't want the local DAHost's client to process this message, so exit early + return; + } + // Otherwise, fall through and process the request. + } + else + { + foreach (var clientId in clientList) + { + if (clientId == networkManager.LocalClientId) + { + continue; + } + + // If ownership is changing and this is not an ownership request approval then ignore the OnwerClientId + // If it is just updating flags then ignore sending to the owner + // If it is a request or approving request, then ignore the RequestClientId + if ((OwnershipIsChanging && !RequestApproved && OwnerClientId == clientId) || (OwnershipFlagsUpdate && clientId == OwnerClientId) + || ((RequestOwnership || RequestApproved) && clientId == RequestClientId)) + { + continue; + } + + networkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.Reliable, clientId); + } + } + // If the NetworkObject is not visible to the DAHost client, then exit early + if (!networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId)) + { + return; + } + } + + // If ownership is changing, then run through the ownershipd changed sequence + // Note: There is some extended ownership script at the bottom of HandleOwnershipChange + // If not in distributed authority mode, then always go straight to HandleOwnershipChange + if (OwnershipIsChanging || !networkManager.DistributedAuthorityMode) + { + HandleOwnershipChange(ref context); + } + else if (networkManager.DistributedAuthorityMode) + { + // Otherwise, we handle and extended ownership update + HandleExtendedOwnershipUpdate(ref context); + } + } + + /// + /// Handle the + /// + /// + private void HandleExtendedOwnershipUpdate(ref NetworkContext context) + { + var networkManager = (NetworkManager)context.SystemOwner; + + // Handle the extended ownership message types + var networkObject = networkManager.SpawnManager.SpawnedObjects[NetworkObjectId]; + + if (OwnershipFlagsUpdate) + { + // Just update the ownership flags + networkObject.Ownership = (NetworkObject.OwnershipStatus)OwnershipFlags; + } + else if (RequestOwnership) + { + // Requesting ownership, if allowed it will automatically send the ownership change message + networkObject.OwnershipRequest(RequestClientId); + } + else if (RequestDenied) + { + networkObject.OwnershipRequestResponse((NetworkObject.OwnershipRequestResponseStatus)OwnershipRequestResponseStatus); + } + } + + /// + /// Handle the traditional change in ownership message type logic + /// + /// + private void HandleOwnershipChange(ref NetworkContext context) + { + var networkManager = (NetworkManager)context.SystemOwner; + var networkObject = networkManager.SpawnManager.SpawnedObjects[NetworkObjectId]; + + // DANGO-TODO: This probably shouldn't be allowed to happen. + if (networkObject.OwnerClientId == OwnerClientId) + { + UnityEngine.Debug.LogWarning($"Unnecessary ownership changed message for {NetworkObjectId}"); + } + + var originalOwner = networkObject.OwnerClientId; networkObject.OwnerClientId = OwnerClientId; - // We are current owner. - if (originalOwner == networkManager.LocalClientId) + if (networkManager.DistributedAuthorityMode) + { + networkObject.Ownership = (NetworkObject.OwnershipStatus)OwnershipFlags; + } + + // We are current owner (client-server) or running in distributed authority mode + if (originalOwner == networkManager.LocalClientId || networkManager.DistributedAuthorityMode) { networkObject.InvokeBehaviourOnLostOwnership(); } - // We are new owner. - if (OwnerClientId == networkManager.LocalClientId) + // We are new owner or (client-server) or running in distributed authority mode + if (OwnerClientId == networkManager.LocalClientId || networkManager.DistributedAuthorityMode) { networkObject.InvokeBehaviourOnGainedOwnership(); } - // For all other clients that are neither the former or current owner, update the behaviours' properties - if (OwnerClientId != networkManager.LocalClientId && originalOwner != networkManager.LocalClientId) + // If in distributed authority mode + if (networkManager.DistributedAuthorityMode) { + // Always update the network properties in distributed authority mode for (int i = 0; i < networkObject.ChildNetworkBehaviours.Count; i++) { networkObject.ChildNetworkBehaviours[i].UpdateNetworkProperties(); } } + else // Otherwise update properties like we would in client-server + { + // For all other clients that are neither the former or current owner, update the behaviours' properties + if (OwnerClientId != networkManager.LocalClientId && originalOwner != networkManager.LocalClientId) + { + for (int i = 0; i < networkObject.ChildNetworkBehaviours.Count; i++) + { + networkObject.ChildNetworkBehaviours[i].UpdateNetworkProperties(); + } + } + } + // Always invoke ownership change notifications networkObject.InvokeOwnershipChanged(originalOwner, OwnerClientId); + // If this change was requested, then notify that the request was approved (doing this last so all ownership + // changes have already been applied if the callback is invoked) + if (networkManager.DistributedAuthorityMode && networkManager.LocalClientId == OwnerClientId) + { + if (RequestApproved) + { + networkObject.OwnershipRequestResponse(NetworkObject.OwnershipRequestResponseStatus.Approved); + } + + // If the NetworkObject changed ownership and the Requested flag was set (i.e. it was an ownership request), + // then the new owner granted ownership removes the Requested flag and sends out an ownership status update. + if (networkObject.HasExtendedOwnershipStatus(NetworkObject.OwnershipStatusExtended.Requested)) + { + networkObject.RemoveOwnershipExtended(NetworkObject.OwnershipStatusExtended.Requested); + networkObject.SendOwnershipStatusUpdate(); + } + } + networkManager.NetworkMetrics.TrackOwnershipChangeReceived(context.SenderId, networkObject, context.MessageSize); } } diff --git a/Runtime/Messaging/Messages/ClientConnectedMessage.cs b/Runtime/Messaging/Messages/ClientConnectedMessage.cs index 92ed2eb..819b632 100644 --- a/Runtime/Messaging/Messages/ClientConnectedMessage.cs +++ b/Runtime/Messaging/Messages/ClientConnectedMessage.cs @@ -6,9 +6,13 @@ namespace Unity.Netcode public ulong ClientId; + public bool ShouldSynchronize; + + public void Serialize(FastBufferWriter writer, int targetVersion) { BytePacker.WriteValueBitPacked(writer, ClientId); + writer.WriteValueSafe(ShouldSynchronize); } public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) @@ -19,17 +23,44 @@ namespace Unity.Netcode return false; } ByteUnpacker.ReadValueBitPacked(reader, out ClientId); + reader.ReadValueSafe(out ShouldSynchronize); + return true; } public void Handle(ref NetworkContext context) { var networkManager = (NetworkManager)context.SystemOwner; - networkManager.ConnectionManager.ConnectedClientIds.Add(ClientId); + if ((ShouldSynchronize || networkManager.CMBServiceConnection) && networkManager.DistributedAuthorityMode && networkManager.LocalClient.IsSessionOwner) + { + networkManager.SceneManager.SynchronizeNetworkObjects(ClientId); + } + else + { + // All modes support adding NetworkClients + networkManager.ConnectionManager.AddClient(ClientId); + } + if (!networkManager.ConnectionManager.ConnectedClientIds.Contains(ClientId)) + { + networkManager.ConnectionManager.ConnectedClientIds.Add(ClientId); + } if (networkManager.IsConnectedClient) { networkManager.ConnectionManager.InvokeOnPeerConnectedCallback(ClientId); } + + // DANGO-TODO: Remove the session owner object distribution check once the service handles object distribution + if (networkManager.DistributedAuthorityMode && networkManager.CMBServiceConnection && !networkManager.NetworkConfig.EnableSceneManagement) + { + // Don't redistribute for the local instance + if (ClientId != networkManager.LocalClientId) + { + // We defer redistribution to the end of the NetworkUpdateStage.PostLateUpdate + networkManager.RedistributeToClient = true; + networkManager.ClientToRedistribute = ClientId; + networkManager.TickToRedistribute = networkManager.ServerTime.Tick + 20; + } + } } } } diff --git a/Runtime/Messaging/Messages/ClientDisconnectedMessage.cs b/Runtime/Messaging/Messages/ClientDisconnectedMessage.cs index 9d306cb..6cf0e41 100644 --- a/Runtime/Messaging/Messages/ClientDisconnectedMessage.cs +++ b/Runtime/Messaging/Messages/ClientDisconnectedMessage.cs @@ -25,6 +25,8 @@ namespace Unity.Netcode public void Handle(ref NetworkContext context) { var networkManager = (NetworkManager)context.SystemOwner; + // All modes support removing NetworkClients + networkManager.ConnectionManager.RemoveClient(ClientId); networkManager.ConnectionManager.ConnectedClientIds.Remove(ClientId); if (networkManager.IsConnectedClient) { diff --git a/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs b/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs index 5635f23..174eba3 100644 --- a/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs +++ b/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs @@ -10,6 +10,11 @@ namespace Unity.Netcode public ulong OwnerClientId; public int NetworkTick; + // The cloud state service should set this if we are restoring a session + public bool IsRestoredSession; + public ulong CurrentSessionOwner; + // Not serialized + public bool IsDistributedAuthority; // Not serialized, held as references to serialize NetworkVariable data public HashSet SpawnedObjectsList; @@ -38,6 +43,11 @@ namespace Unity.Netcode BytePacker.WriteValueBitPacked(writer, OwnerClientId); BytePacker.WriteValueBitPacked(writer, NetworkTick); + if (IsDistributedAuthority) + { + writer.WriteValueSafe(IsRestoredSession); + BytePacker.WriteValueBitPacked(writer, CurrentSessionOwner); + } if (targetVersion >= k_VersionAddClientIds) { @@ -59,7 +69,8 @@ namespace Unity.Netcode if (sobj.SpawnWithObservers && (sobj.CheckObjectVisibility == null || sobj.CheckObjectVisibility(OwnerClientId))) { sobj.Observers.Add(OwnerClientId); - var sceneObject = sobj.GetMessageSceneObject(OwnerClientId); + // In distributed authority mode, we send the currently known observers of each NetworkObject to the client being synchronized. + var sceneObject = sobj.GetMessageSceneObject(OwnerClientId, IsDistributedAuthority); sceneObject.Serialize(writer); ++sceneObjectCount; } @@ -114,6 +125,11 @@ namespace Unity.Netcode ByteUnpacker.ReadValueBitPacked(reader, out OwnerClientId); ByteUnpacker.ReadValueBitPacked(reader, out NetworkTick); + if (networkManager.DistributedAuthorityMode) + { + reader.ReadValueSafe(out IsRestoredSession); + ByteUnpacker.ReadValueBitPacked(reader, out CurrentSessionOwner); + } if (receivedMessageVersion >= k_VersionAddClientIds) { @@ -131,10 +147,23 @@ namespace Unity.Netcode public void Handle(ref NetworkContext context) { var networkManager = (NetworkManager)context.SystemOwner; + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) + { + NetworkLog.LogInfo($"[Client-{OwnerClientId}] Connection approved! Synchronizing..."); + } networkManager.LocalClientId = OwnerClientId; networkManager.MessageManager.SetLocalClientId(networkManager.LocalClientId); networkManager.NetworkMetrics.SetConnectionId(networkManager.LocalClientId); + if (networkManager.DistributedAuthorityMode) + { + networkManager.SetSessionOwner(CurrentSessionOwner); + if (networkManager.LocalClient.IsSessionOwner && networkManager.NetworkConfig.EnableSceneManagement) + { + networkManager.SceneManager.InitializeScenesLoaded(); + } + } + var time = new NetworkTime(networkManager.NetworkTickSystem.TickRate, NetworkTick); networkManager.NetworkTimeSystem.Reset(time.Time, 0.15f); // Start with a constant RTT of 150 until we receive values from the transport. networkManager.NetworkTickSystem.Reset(networkManager.NetworkTimeSystem.LocalTime, networkManager.NetworkTimeSystem.ServerTime); @@ -148,13 +177,26 @@ namespace Unity.Netcode networkManager.ConnectionManager.ConnectedClientIds.Clear(); foreach (var clientId in ConnectedClientIds) { - networkManager.ConnectionManager.ConnectedClientIds.Add(clientId); + if (!networkManager.ConnectionManager.ConnectedClientIds.Contains(clientId)) + { + networkManager.ConnectionManager.AddClient(clientId); + } } // Only if scene management is disabled do we handle NetworkObject synchronization at this point if (!networkManager.NetworkConfig.EnableSceneManagement) { - networkManager.SpawnManager.DestroySceneObjects(); + // DANGO-TODO: This is a temporary fix for no DA CMB scene event handling. + // We will either use this same concept or provide some way for the CMB state plugin to handle it. + if (networkManager.DistributedAuthorityMode && networkManager.LocalClient.IsSessionOwner) + { + networkManager.SpawnManager.ServerSpawnSceneObjectsOnStartSweep(); + } + else + { + networkManager.SpawnManager.DestroySceneObjects(); + } + m_ReceivedSceneObjectData.ReadValueSafe(out uint sceneObjectCount); // Deserializing NetworkVariable data is deferred from Receive() to Handle to avoid needing @@ -168,10 +210,38 @@ namespace Unity.Netcode // Mark the client being connected networkManager.IsConnectedClient = true; + + if (networkManager.AutoSpawnPlayerPrefabClientSide) + { + networkManager.ConnectionManager.CreateAndSpawnPlayer(OwnerClientId); + } + + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) + { + NetworkLog.LogInfo($"[Client-{OwnerClientId}][Scene Management Disabled] Synchronization complete!"); + } // When scene management is disabled we notify after everything is synchronized networkManager.ConnectionManager.InvokeOnClientConnectedCallback(context.SenderId); } + else + { + if (networkManager.DistributedAuthorityMode && networkManager.CMBServiceConnection && networkManager.LocalClient.IsSessionOwner && networkManager.NetworkConfig.EnableSceneManagement) + { + // Mark the client being connected + networkManager.IsConnectedClient = true; + // Spawn any in-scene placed NetworkObjects + networkManager.SpawnManager.ServerSpawnSceneObjectsOnStartSweep(); + + // Spawn the local player of the session owner + if (networkManager.AutoSpawnPlayerPrefabClientSide) + { + networkManager.ConnectionManager.CreateAndSpawnPlayer(OwnerClientId); + } + // Synchronize the service with the initial session owner's loaded scenes and spawned objects + networkManager.SceneManager.SynchronizeNetworkObjects(NetworkManager.ServerClientId); + } + } ConnectedClientIds.Dispose(); } } diff --git a/Runtime/Messaging/Messages/ConnectionRequestMessage.cs b/Runtime/Messaging/Messages/ConnectionRequestMessage.cs index 8d558bf..790791d 100644 --- a/Runtime/Messaging/Messages/ConnectionRequestMessage.cs +++ b/Runtime/Messaging/Messages/ConnectionRequestMessage.cs @@ -8,6 +8,10 @@ namespace Unity.Netcode public ulong ConfigHash; + public bool CMBServiceConnection; + public uint TickRate; + public bool EnableSceneManagement; + public byte[] ConnectionData; public bool ShouldSendConnectionData; @@ -30,6 +34,12 @@ namespace Unity.Netcode // END FORBIDDEN SEGMENT // ============================================================ + if (CMBServiceConnection) + { + writer.WriteValueSafe(TickRate); + writer.WriteValueSafe(EnableSceneManagement); + } + if (ShouldSendConnectionData) { writer.WriteValueSafe(ConfigHash); @@ -151,7 +161,7 @@ namespace Unity.Netcode var response = new NetworkManager.ConnectionApprovalResponse { Approved = true, - CreatePlayerObject = networkManager.NetworkConfig.PlayerPrefab != null + CreatePlayerObject = networkManager.DistributedAuthorityMode && networkManager.AutoSpawnPlayerPrefabClientSide ? false : networkManager.NetworkConfig.PlayerPrefab != null }; networkManager.ConnectionManager.HandleConnectionApproval(senderId, response); } diff --git a/Runtime/Messaging/Messages/CreateObjectMessage.cs b/Runtime/Messaging/Messages/CreateObjectMessage.cs index 809b7c9..6382cbb 100644 --- a/Runtime/Messaging/Messages/CreateObjectMessage.cs +++ b/Runtime/Messaging/Messages/CreateObjectMessage.cs @@ -1,4 +1,6 @@ +using System.Linq; using System.Runtime.CompilerServices; + namespace Unity.Netcode { internal struct CreateObjectMessage : INetworkMessage @@ -8,9 +10,109 @@ namespace Unity.Netcode public NetworkObject.SceneObject ObjectInfo; private FastBufferReader m_ReceivedNetworkVariableData; + // DA - NGO CMB SERVICE NOTES: + // The ObserverIds and ExistingObserverIds will only be populated if k_UpdateObservers is set + // ObserverIds is the full list of observers (see below) + internal ulong[] ObserverIds; + + // While this does consume a bit more bandwidth, this is only sent by the authority/owner + // and can be used to determine which clients should receive the ObjectInfo serialized data. + // All other already existing observers just need to receive the NewObserverIds and the + // NetworkObjectId + internal ulong[] NewObserverIds; + + // If !IncludesSerializedObject then the NetworkObjectId will be serialized. + // This happens when we are just sending an update to the observers list + // to clients that already have the NetworkObject spawned + internal ulong NetworkObjectId; + + private const byte k_IncludesSerializedObject = 0x01; + private const byte k_UpdateObservers = 0x02; + private const byte k_UpdateNewObservers = 0x04; + + + private byte m_CreateObjectMessageTypeFlags; + + internal bool IncludesSerializedObject + { + get + { + return GetFlag(k_IncludesSerializedObject); + } + + set + { + SetFlag(value, k_IncludesSerializedObject); + } + } + + internal bool UpdateObservers + { + get + { + return GetFlag(k_UpdateObservers); + } + + set + { + SetFlag(value, k_UpdateObservers); + } + } + + internal bool UpdateNewObservers + { + get + { + return GetFlag(k_UpdateNewObservers); + } + + set + { + SetFlag(value, k_UpdateNewObservers); + } + } + + private bool GetFlag(int flag) + { + return (m_CreateObjectMessageTypeFlags & flag) != 0; + } + + private void SetFlag(bool set, byte flag) + { + if (set) { m_CreateObjectMessageTypeFlags = (byte)(m_CreateObjectMessageTypeFlags | flag); } + else { m_CreateObjectMessageTypeFlags = (byte)(m_CreateObjectMessageTypeFlags & ~flag); } + } + public void Serialize(FastBufferWriter writer, int targetVersion) { - ObjectInfo.Serialize(writer); + writer.WriteValueSafe(m_CreateObjectMessageTypeFlags); + + if (UpdateObservers) + { + BytePacker.WriteValuePacked(writer, ObserverIds.Length); + foreach (var clientId in ObserverIds) + { + BytePacker.WriteValuePacked(writer, clientId); + } + } + + if (UpdateNewObservers) + { + BytePacker.WriteValuePacked(writer, NewObserverIds.Length); + foreach (var clientId in NewObserverIds) + { + BytePacker.WriteValuePacked(writer, clientId); + } + } + + if (IncludesSerializedObject) + { + ObjectInfo.Serialize(writer); + } + else + { + BytePacker.WriteValuePacked(writer, NetworkObjectId); + } } public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) @@ -21,10 +123,45 @@ namespace Unity.Netcode return false; } - ObjectInfo.Deserialize(reader); + reader.ReadValueSafe(out m_CreateObjectMessageTypeFlags); + if (UpdateObservers) + { + var length = 0; + ByteUnpacker.ReadValuePacked(reader, out length); + ObserverIds = new ulong[length]; + var clientId = (ulong)0; + for (int i = 0; i < length; i++) + { + ByteUnpacker.ReadValuePacked(reader, out clientId); + ObserverIds[i] = clientId; + } + } + + if (UpdateNewObservers) + { + var length = 0; + ByteUnpacker.ReadValuePacked(reader, out length); + NewObserverIds = new ulong[length]; + var clientId = (ulong)0; + for (int i = 0; i < length; i++) + { + ByteUnpacker.ReadValuePacked(reader, out clientId); + NewObserverIds[i] = clientId; + } + } + + if (IncludesSerializedObject) + { + ObjectInfo.Deserialize(reader); + } + else + { + ByteUnpacker.ReadValuePacked(reader, out NetworkObjectId); + } + if (!networkManager.NetworkConfig.ForceSamePrefabs && !networkManager.SpawnManager.HasPrefab(ObjectInfo)) { - networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnAddPrefab, ObjectInfo.Hash, reader, ref context); + networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnAddPrefab, ObjectInfo.Hash, reader, ref context, GetType().Name); return false; } m_ReceivedNetworkVariableData = reader; @@ -38,21 +175,130 @@ namespace Unity.Netcode // If a client receives a create object message and it is still synchronizing, then defer the object creation until it has finished synchronizing if (networkManager.SceneManager.ShouldDeferCreateObject()) { - networkManager.SceneManager.DeferCreateObject(context.SenderId, context.MessageSize, ObjectInfo, m_ReceivedNetworkVariableData); + networkManager.SceneManager.DeferCreateObject(context.SenderId, context.MessageSize, ObjectInfo, m_ReceivedNetworkVariableData, ObserverIds, NewObserverIds); } else { - CreateObject(ref networkManager, context.SenderId, context.MessageSize, ObjectInfo, m_ReceivedNetworkVariableData); + if (networkManager.DistributedAuthorityMode && !IncludesSerializedObject && UpdateObservers) + { + ObjectInfo = new NetworkObject.SceneObject() + { + NetworkObjectId = NetworkObjectId, + }; + } + CreateObject(ref networkManager, context.SenderId, context.MessageSize, ObjectInfo, m_ReceivedNetworkVariableData, ObserverIds, NewObserverIds); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static void CreateObject(ref NetworkManager networkManager, ulong senderId, uint messageSize, NetworkObject.SceneObject sceneObject, FastBufferReader networkVariableData) + internal static void CreateObject(ref NetworkManager networkManager, ref NetworkSceneManager.DeferredObjectCreation deferredObjectCreation) { + var senderId = deferredObjectCreation.SenderId; + var observerIds = deferredObjectCreation.ObserverIds; + var newObserverIds = deferredObjectCreation.NewObserverIds; + var messageSize = deferredObjectCreation.MessageSize; + var sceneObject = deferredObjectCreation.SceneObject; + var networkVariableData = deferredObjectCreation.FastBufferReader; + CreateObject(ref networkManager, senderId, messageSize, sceneObject, networkVariableData, observerIds, newObserverIds); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void CreateObject(ref NetworkManager networkManager, ulong senderId, uint messageSize, NetworkObject.SceneObject sceneObject, FastBufferReader networkVariableData, ulong[] observerIds, ulong[] newObserverIds) + { + var networkObject = (NetworkObject)null; try { - var networkObject = NetworkObject.AddSceneObject(sceneObject, networkVariableData, networkManager); - networkManager.NetworkMetrics.TrackObjectSpawnReceived(senderId, networkObject, messageSize); + if (!networkManager.DistributedAuthorityMode) + { + networkObject = NetworkObject.AddSceneObject(sceneObject, networkVariableData, networkManager); + } + else + { + var hasObserverIdList = observerIds != null && observerIds.Length > 0; + var hasNewObserverIdList = newObserverIds != null && newObserverIds.Length > 0; + // Depending upon visibility of the NetworkObject and the client in question, it could be that + // this client already has visibility of this NetworkObject + if (networkManager.SpawnManager.SpawnedObjects.ContainsKey(sceneObject.NetworkObjectId)) + { + // If so, then just get the local instance + networkObject = networkManager.SpawnManager.SpawnedObjects[sceneObject.NetworkObjectId]; + + // This should not happen, logging error just in case + if (hasNewObserverIdList && newObserverIds.Contains(networkManager.LocalClientId)) + { + NetworkLog.LogErrorServer($"[{nameof(CreateObjectMessage)}][Duplicate-Broadcast] Detected duplicated object creation for {sceneObject.NetworkObjectId}!"); + } + else // Trap to make sure the owner is not receiving any messages it sent + if (networkManager.CMBServiceConnection && networkManager.LocalClientId == networkObject.OwnerClientId) + { + NetworkLog.LogWarning($"[{nameof(CreateObjectMessage)}][Client-{networkManager.LocalClientId}][Duplicate-CreateObjectMessage][Client Is Owner] Detected duplicated object creation for {networkObject.name}-{sceneObject.NetworkObjectId}!"); + } + } + else + { + networkObject = NetworkObject.AddSceneObject(sceneObject, networkVariableData, networkManager, true); + } + + // DA - NGO CMB SERVICE NOTES: + // It is possible for two clients to connect at the exact same time which, due to client-side spawning, can cause each client + // to miss their spawns. For now, all player NetworkObject spawns will always be visible to all known connected clients + var clientList = hasObserverIdList && !networkObject.IsPlayerObject ? observerIds : networkManager.ConnectedClientsIds; + + // Update the observers for this instance + foreach (var clientId in clientList) + { + networkObject.Observers.Add(clientId); + } + + // Mock CMB Service and forward to all clients + if (networkManager.DAHost) + { + // DA - NGO CMB SERVICE NOTES: + // (*** See above notes fist ***) + // If it is a player object freshly spawning and one or more clients all connect at the exact same time (i.e. received on effectively + // the same frame), then we need to check the observers list to make sure all players are visible upon first spawning. At a later date, + // for area of interest we will need to have some form of follow up "observer update" message to cull out players not within each + // player's AOI. + if (networkObject.IsPlayerObject && hasNewObserverIdList && clientList.Count != observerIds.Length) + { + // For same-frame newly spawned players that might not be aware of all other players, update the player's observer + // list. + observerIds = clientList.ToArray(); + } + + var createObjectMessage = new CreateObjectMessage() + { + ObjectInfo = sceneObject, + m_ReceivedNetworkVariableData = networkVariableData, + ObserverIds = hasObserverIdList ? observerIds : null, + NetworkObjectId = networkObject.NetworkObjectId, + IncludesSerializedObject = true, + }; + foreach (var clientId in clientList) + { + // DA - NGO CMB SERVICE NOTES: + // If the authority did not specify the list of clients and the client is not an observer or we are the owner/originator + // or we are the DAHost, then we skip sending the message. + if ((!hasObserverIdList && (!networkObject.Observers.Contains(clientId)) || + clientId == networkObject.OwnerClientId || clientId == NetworkManager.ServerClientId)) + { + continue; + } + + // DA - NGO CMB SERVICE NOTES: + // If this included a list of new observers and the targeted clientId is one of the observers, then send the serialized data. + // Otherwise, the targeted clientId has already has visibility (i.e. it is already spawned) and so just send the updated + // observers list to that client's instance. + createObjectMessage.IncludesSerializedObject = hasNewObserverIdList && newObserverIds.Contains(clientId); + + networkManager.SpawnManager.SendSpawnCallForObject(clientId, networkObject); + } + } + } + if (networkObject != null) + { + networkManager.NetworkMetrics.TrackObjectSpawnReceived(senderId, networkObject, messageSize); + } } catch (System.Exception ex) { diff --git a/Runtime/Messaging/Messages/DestroyObjectMessage.cs b/Runtime/Messaging/Messages/DestroyObjectMessage.cs index b02b42c..b3d799a 100644 --- a/Runtime/Messaging/Messages/DestroyObjectMessage.cs +++ b/Runtime/Messaging/Messages/DestroyObjectMessage.cs @@ -1,3 +1,5 @@ +using System.Linq; + namespace Unity.Netcode { internal struct DestroyObjectMessage : INetworkMessage, INetworkSerializeByMemcpy @@ -6,10 +8,53 @@ namespace Unity.Netcode public ulong NetworkObjectId; public bool DestroyGameObject; + private byte m_DestroyFlags; + + internal int DeferredDespawnTick; + // Temporary until we make this a list + internal ulong TargetClientId; + + internal bool IsDistributedAuthority; + + internal const byte ClientTargetedDestroy = 0x01; + + internal bool IsTargetedDestroy + { + get + { + return GetFlag(ClientTargetedDestroy); + } + + set + { + SetFlag(value, ClientTargetedDestroy); + } + } + + private bool GetFlag(int flag) + { + return (m_DestroyFlags & flag) != 0; + } + + private void SetFlag(bool set, byte flag) + { + if (set) { m_DestroyFlags = (byte)(m_DestroyFlags | flag); } + else { m_DestroyFlags = (byte)(m_DestroyFlags & ~flag); } + } public void Serialize(FastBufferWriter writer, int targetVersion) { BytePacker.WriteValueBitPacked(writer, NetworkObjectId); + if (IsDistributedAuthority) + { + writer.WriteByteSafe(m_DestroyFlags); + + if (IsTargetedDestroy) + { + BytePacker.WriteValueBitPacked(writer, TargetClientId); + } + BytePacker.WriteValueBitPacked(writer, DeferredDespawnTick); + } writer.WriteValueSafe(DestroyGameObject); } @@ -22,12 +67,25 @@ namespace Unity.Netcode } ByteUnpacker.ReadValueBitPacked(reader, out NetworkObjectId); + if (networkManager.DistributedAuthorityMode) + { + reader.ReadByteSafe(out m_DestroyFlags); + if (IsTargetedDestroy) + { + ByteUnpacker.ReadValueBitPacked(reader, out TargetClientId); + } + ByteUnpacker.ReadValueBitPacked(reader, out DeferredDespawnTick); + } + reader.ReadValueSafe(out DestroyGameObject); if (!networkManager.SpawnManager.SpawnedObjects.TryGetValue(NetworkObjectId, out var networkObject)) { - networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context); - return false; + // Client-Server mode we always defer where in distributed authority mode we only defer if it is not a targeted destroy + if (!networkManager.DistributedAuthorityMode || (networkManager.DistributedAuthorityMode && !IsTargetedDestroy)) + { + networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, GetType().Name); + } } return true; } @@ -35,14 +93,80 @@ namespace Unity.Netcode public void Handle(ref NetworkContext context) { var networkManager = (NetworkManager)context.SystemOwner; - if (!networkManager.SpawnManager.SpawnedObjects.TryGetValue(NetworkObjectId, out var networkObject)) + + var networkObject = (NetworkObject)null; + if (!networkManager.DistributedAuthorityMode) { - // This is the same check and log message that happens inside OnDespawnObject, but we have to do it here - return; + // If this NetworkObject does not exist on this instance then exit early + if (!networkManager.SpawnManager.SpawnedObjects.TryGetValue(NetworkObjectId, out networkObject)) + { + return; + } + } + else + { + networkManager.SpawnManager.SpawnedObjects.TryGetValue(NetworkObjectId, out networkObject); + if (!networkManager.DAHost && networkObject == null) + { + // If this NetworkObject does not exist on this instance then exit early + return; + } + } + // DANGO-TODO: This is just a quick way to foward despawn messages to the remaining clients + if (networkManager.DistributedAuthorityMode && networkManager.DAHost) + { + var message = new DestroyObjectMessage + { + NetworkObjectId = NetworkObjectId, + DestroyGameObject = DestroyGameObject, + IsDistributedAuthority = true, + IsTargetedDestroy = IsTargetedDestroy, + TargetClientId = TargetClientId, // Just always populate this value whether we write it or not + DeferredDespawnTick = DeferredDespawnTick, + }; + var ownerClientId = networkObject == null ? context.SenderId : networkObject.OwnerClientId; + var clientIds = networkObject == null ? networkManager.ConnectedClientsIds.ToList() : networkObject.Observers.ToList(); + + foreach (var clientId in clientIds) + { + if (clientId == networkManager.LocalClientId || clientId == ownerClientId) + { + continue; + } + networkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, clientId); + } } - networkManager.NetworkMetrics.TrackObjectDestroyReceived(context.SenderId, networkObject, context.MessageSize); - networkManager.SpawnManager.OnDespawnObject(networkObject, DestroyGameObject); + // If we are deferring the despawn, then add it to the deferred despawn queue + if (networkManager.DistributedAuthorityMode) + { + if (DeferredDespawnTick > 0) + { + // Clients always add it to the queue while DAHost will only add it to the queue if it is not a targeted destroy or it is and the target is the + // DAHost client. + if (!networkManager.DAHost || (networkManager.DAHost && (!IsTargetedDestroy || (IsTargetedDestroy && TargetClientId == 0)))) + { + networkObject.DeferredDespawnTick = DeferredDespawnTick; + var hasCallback = networkObject.OnDeferredDespawnComplete != null; + networkManager.SpawnManager.DeferDespawnNetworkObject(NetworkObjectId, DeferredDespawnTick, hasCallback); + return; + } + } + + // If this is targeted and we are not the target, then just update our local observers for this object + if (IsTargetedDestroy && TargetClientId != networkManager.LocalClientId && networkObject != null) + { + networkObject.Observers.Remove(TargetClientId); + return; + } + } + + if (networkObject != null) + { + // Otherwise just despawn the NetworkObject right now + networkManager.SpawnManager.OnDespawnObject(networkObject, DestroyGameObject); + networkManager.NetworkMetrics.TrackObjectDestroyReceived(context.SenderId, networkObject, context.MessageSize); + } } } } diff --git a/Runtime/Messaging/Messages/NetworkVariableDeltaMessage.cs b/Runtime/Messaging/Messages/NetworkVariableDeltaMessage.cs index 99970c4..ed6a469 100644 --- a/Runtime/Messaging/Messages/NetworkVariableDeltaMessage.cs +++ b/Runtime/Messaging/Messages/NetworkVariableDeltaMessage.cs @@ -23,6 +23,8 @@ namespace Unity.Netcode private FastBufferReader m_ReceivedNetworkVariableData; + // DANGO-TODO: Made some modifications here that overlap/won't play nice with EnsureNetworkVariableLenghtSafety. + // Worth either merging or more cleanly separating these codepaths. public void Serialize(FastBufferWriter writer, int targetVersion) { if (!writer.TryBeginWrite(FastBufferWriter.GetWriteSize(NetworkObjectId) + FastBufferWriter.GetWriteSize(NetworkBehaviourIndex))) @@ -30,15 +32,26 @@ namespace Unity.Netcode throw new OverflowException($"Not enough space in the buffer to write {nameof(NetworkVariableDeltaMessage)}"); } + var obj = NetworkBehaviour.NetworkObject; + var networkManager = obj.NetworkManagerOwner; + BytePacker.WriteValueBitPacked(writer, NetworkObjectId); BytePacker.WriteValueBitPacked(writer, NetworkBehaviourIndex); + if (networkManager.DistributedAuthorityMode) + { + writer.WriteValueSafe((ushort)NetworkBehaviour.NetworkVariableFields.Count); + } for (int i = 0; i < NetworkBehaviour.NetworkVariableFields.Count; i++) { if (!DeliveryMappedNetworkVariableIndex.Contains(i)) { // This var does not belong to the currently iterating delivery group. - if (NetworkBehaviour.NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (networkManager.DistributedAuthorityMode) + { + writer.WriteValueSafe(0); + } + else if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { BytePacker.WriteValueBitPacked(writer, (ushort)0); } @@ -54,7 +67,7 @@ namespace Unity.Netcode var networkVariable = NetworkBehaviour.NetworkVariableFields[i]; var shouldWrite = networkVariable.IsDirty() && networkVariable.CanClientRead(TargetClientId) && - (NetworkBehaviour.NetworkManager.IsServer || networkVariable.CanClientWrite(NetworkBehaviour.NetworkManager.LocalClientId)); + (networkManager.IsServer || networkVariable.CanClientWrite(networkManager.LocalClientId)); // Prevent the server from writing to the client that owns a given NetworkVariable // Allowing the write would send an old value to the client and cause jitter @@ -67,14 +80,21 @@ namespace Unity.Netcode // The object containing the behaviour we're about to process is about to be shown to this client // As a result, the client will get the fully serialized NetworkVariable and would be confused by // an extraneous delta - if (NetworkBehaviour.NetworkManager.SpawnManager.ObjectsToShowToClient.ContainsKey(TargetClientId) && - NetworkBehaviour.NetworkManager.SpawnManager.ObjectsToShowToClient[TargetClientId] - .Contains(NetworkBehaviour.NetworkObject)) + if (networkManager.SpawnManager.ObjectsToShowToClient.ContainsKey(TargetClientId) && + networkManager.SpawnManager.ObjectsToShowToClient[TargetClientId] + .Contains(obj)) { shouldWrite = false; } - if (NetworkBehaviour.NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (networkManager.DistributedAuthorityMode) + { + if (!shouldWrite) + { + writer.WriteValueSafe(0); + } + } + else if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { if (!shouldWrite) { @@ -88,9 +108,9 @@ namespace Unity.Netcode if (shouldWrite) { - if (NetworkBehaviour.NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { - var tempWriter = new FastBufferWriter(NetworkBehaviour.NetworkManager.MessageManager.NonFragmentedMessageMaxSize, Allocator.Temp, NetworkBehaviour.NetworkManager.MessageManager.FragmentedMessageMaxSize); + var tempWriter = new FastBufferWriter(networkManager.MessageManager.NonFragmentedMessageMaxSize, Allocator.Temp, networkManager.MessageManager.FragmentedMessageMaxSize); NetworkBehaviour.NetworkVariableFields[i].WriteDelta(tempWriter); BytePacker.WriteValueBitPacked(writer, tempWriter.Length); @@ -103,11 +123,30 @@ namespace Unity.Netcode } else { - networkVariable.WriteDelta(writer); + // DANGO-TODO: + // Complex types with custom type serialization (either registered custom types or INetworkSerializable implementations) will be problematic + // Non-complex types always provide a full state update per delta + // DANGO-TODO: Add NetworkListEvent.EventType awareness to the cloud-state server + if (networkManager.DistributedAuthorityMode) + { + var size_marker = writer.Position; + writer.WriteValueSafe(0); + var start_marker = writer.Position; + networkVariable.WriteDelta(writer); + var end_marker = writer.Position; + writer.Seek(size_marker); + var size = end_marker - start_marker; + writer.WriteValueSafe((ushort)size); + writer.Seek(end_marker); + } + else + { + networkVariable.WriteDelta(writer); + } } - NetworkBehaviour.NetworkManager.NetworkMetrics.TrackNetworkVariableDeltaSent( + networkManager.NetworkMetrics.TrackNetworkVariableDeltaSent( TargetClientId, - NetworkBehaviour.NetworkObject, + obj, networkVariable.Name, NetworkBehaviour.__getTypeName(), writer.Length - startingSize); @@ -125,6 +164,8 @@ namespace Unity.Netcode return true; } + // DANGO-TODO: Made some modifications here that overlap/won't play nice with EnsureNetworkVariableLenghtSafety. + // Worth either merging or more cleanly separating these codepaths. public void Handle(ref NetworkContext context) { var networkManager = (NetworkManager)context.SystemOwner; @@ -142,10 +183,29 @@ namespace Unity.Netcode } else { + if (networkManager.DistributedAuthorityMode) + { + m_ReceivedNetworkVariableData.ReadValueSafe(out ushort variableCount); + if (variableCount != networkBehaviour.NetworkVariableFields.Count) + { + UnityEngine.Debug.LogError("Variable count mismatch"); + } + } + for (int i = 0; i < networkBehaviour.NetworkVariableFields.Count; i++) { int varSize = 0; - if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (networkManager.DistributedAuthorityMode) + { + m_ReceivedNetworkVariableData.ReadValueSafe(out ushort variableSize); + varSize = variableSize; + + if (varSize == 0) + { + continue; + } + } + else if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) { ByteUnpacker.ReadValueBitPacked(m_ReceivedNetworkVariableData, out varSize); @@ -197,6 +257,7 @@ namespace Unity.Netcode } int readStartPos = m_ReceivedNetworkVariableData.Position; + // Read Delta so we also notify any subscribers to a change in the NetworkVariable networkVariable.ReadDelta(m_ReceivedNetworkVariableData, networkManager.IsServer); networkManager.NetworkMetrics.TrackNetworkVariableDeltaReceived( @@ -206,7 +267,7 @@ namespace Unity.Netcode networkBehaviour.__getTypeName(), context.MessageSize); - if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety) + if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety || networkManager.DistributedAuthorityMode) { if (m_ReceivedNetworkVariableData.Position > (readStartPos + varSize)) { @@ -232,7 +293,10 @@ namespace Unity.Netcode } else { - networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, m_ReceivedNetworkVariableData, ref context); + // DANGO-TODO: Fix me! + // When a client-spawned NetworkObject is despawned by the owner client, the owner client will still get messages for deltas and cause this to + // log a warning. The issue is primarily how NetworkVariables handle updating and will require some additional re-factoring. + networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, m_ReceivedNetworkVariableData, ref context, GetType().Name); } } } diff --git a/Runtime/Messaging/Messages/ParentSyncMessage.cs b/Runtime/Messaging/Messages/ParentSyncMessage.cs index abbe888..473f775 100644 --- a/Runtime/Messaging/Messages/ParentSyncMessage.cs +++ b/Runtime/Messaging/Messages/ParentSyncMessage.cs @@ -33,6 +33,12 @@ namespace Unity.Netcode set => ByteUtility.SetBit(ref m_BitField, 2, value); } + public bool AuthorityApplied + { + get => ByteUtility.GetBit(m_BitField, 3); + set => ByteUtility.SetBit(ref m_BitField, 3, value); + } + // These additional properties are used to synchronize clients with the current position, // rotation, and scale after parenting/de-parenting (world/local space relative). This // allows users to control the final child's transform values without having to have a @@ -83,9 +89,10 @@ namespace Unity.Netcode reader.ReadValueSafe(out Rotation); reader.ReadValueSafe(out Scale); - if (!networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId)) + // If the target NetworkObject does not exist =or= the target latest parent does not exist then defer the message + if (!networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId) || (LatestParent.HasValue && !networkManager.SpawnManager.SpawnedObjects.ContainsKey(LatestParent.Value))) { - networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context); + networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, GetType().Name); return false; } return true; @@ -95,6 +102,16 @@ namespace Unity.Netcode { var networkManager = (NetworkManager)context.SystemOwner; var networkObject = networkManager.SpawnManager.SpawnedObjects[NetworkObjectId]; + + // For either DA or Client-Server modes, parenting is only valid if the parent was owned by a different authority (i.e. AuthorityApplied) or the sender is from the owner (DA mode) + // or the server (client-server mode). + networkObject.AuthorityAppliedParenting = AuthorityApplied || context.SenderId == networkObject.OwnerClientId || context.SenderId == NetworkManager.ServerClientId; + if (!networkObject.AuthorityAppliedParenting && networkManager.LogLevel <= LogLevel.Normal) + { + NetworkLog.LogWarningServer($"Client-{context.SenderId} sent a ParentSyncMessage but is not the authority of {networkObject.gameObject.name}'s {nameof(NetworkObject)} component!"); + // DANGO-TODO: Still determining if we should not apply this change (I am leaning towards not allowing it). + } + networkObject.SetNetworkParenting(LatestParent, WorldPositionStays); networkObject.ApplyNetworkParenting(RemoveParent); @@ -111,6 +128,30 @@ namespace Unity.Netcode networkObject.transform.rotation = Rotation; } networkObject.transform.localScale = Scale; + + // If in distributed authority mode and we are running a DAHost and this is the DAHost, then forward the parent changed message to any remaining clients + if (networkManager.DistributedAuthorityMode && !networkManager.CMBServiceConnection && networkManager.DAHost) + { + var size = 0; + var message = this; + + foreach (var client in networkManager.ConnectedClients) + { + if (client.Value.ClientId == networkObject.OwnerClientId || client.Value.ClientId == networkManager.LocalClientId) + { + 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 + { + Debug.Log($"[DAHost][ParentingProxy] Client-{client.Value.ClientId} has no visibility to {networkObject.name}!"); + } + } + } } } } diff --git a/Runtime/Messaging/Messages/ProxyMessage.cs b/Runtime/Messaging/Messages/ProxyMessage.cs index f47237c..c7322c4 100644 --- a/Runtime/Messaging/Messages/ProxyMessage.cs +++ b/Runtime/Messaging/Messages/ProxyMessage.cs @@ -31,11 +31,24 @@ namespace Unity.Netcode public unsafe void Handle(ref NetworkContext context) { - var networkManager = (NetworkManager)context.SystemOwner; if (!networkManager.SpawnManager.SpawnedObjects.TryGetValue(WrappedMessage.Metadata.NetworkObjectId, out var networkObject)) { - throw new InvalidOperationException($"An RPC called on a {nameof(NetworkObject)} that is not in the spawned objects list. Please make sure the {nameof(NetworkObject)} is spawned before calling RPCs."); + // With distributed authority mode, we can send Rpcs before we have been notified the NetworkObject is despawned. + // DANGO-TODO: Should the CMB Service cull out any Rpcs targeting recently despawned NetworkObjects? + // DANGO-TODO: This would require the service to keep track of despawned NetworkObjects since we re-use NetworkObject identifiers. + if (networkManager.DistributedAuthorityMode) + { + if (networkManager.LogLevel == LogLevel.Developer) + { + NetworkLog.LogWarning($"[{WrappedMessage.Metadata.NetworkObjectId}, {WrappedMessage.Metadata.NetworkBehaviourId}, {WrappedMessage.Metadata.NetworkRpcMethodId}]An RPC called on a {nameof(NetworkObject)} that is not in the spawned objects list. Please make sure the {nameof(NetworkObject)} is spawned before calling RPCs."); + } + return; + } + else + { + throw new InvalidOperationException($"[{WrappedMessage.Metadata.NetworkObjectId}, {WrappedMessage.Metadata.NetworkBehaviourId}, {WrappedMessage.Metadata.NetworkRpcMethodId}]An RPC called on a {nameof(NetworkObject)} that is not in the spawned objects list. Please make sure the {nameof(NetworkObject)} is spawned before calling RPCs."); + } } var observers = networkObject.Observers; diff --git a/Runtime/Messaging/Messages/RpcMessages.cs b/Runtime/Messaging/Messages/RpcMessages.cs index e6961fb..a15749e 100644 --- a/Runtime/Messaging/Messages/RpcMessages.cs +++ b/Runtime/Messaging/Messages/RpcMessages.cs @@ -14,7 +14,7 @@ namespace Unity.Netcode writer.WriteBytesSafe(payload.GetUnsafePtr(), payload.Length); } - public static unsafe bool Deserialize(ref FastBufferReader reader, ref NetworkContext context, ref RpcMetadata metadata, ref FastBufferReader payload) + public static unsafe bool Deserialize(ref FastBufferReader reader, ref NetworkContext context, ref RpcMetadata metadata, ref FastBufferReader payload, string messageType) { ByteUnpacker.ReadValueBitPacked(reader, out metadata.NetworkObjectId); ByteUnpacker.ReadValueBitPacked(reader, out metadata.NetworkBehaviourId); @@ -23,7 +23,7 @@ namespace Unity.Netcode var networkManager = (NetworkManager)context.SystemOwner; if (!networkManager.SpawnManager.SpawnedObjects.ContainsKey(metadata.NetworkObjectId)) { - networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, metadata.NetworkObjectId, reader, ref context); + networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, metadata.NetworkObjectId, reader, ref context, messageType); return false; } @@ -52,7 +52,6 @@ namespace Unity.Netcode reader.Length); } #endif - return true; } @@ -107,7 +106,7 @@ namespace Unity.Netcode public unsafe bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) { - return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer); + return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, GetType().Name); } public void Handle(ref NetworkContext context) @@ -142,7 +141,7 @@ namespace Unity.Netcode public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) { - return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer); + return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, GetType().Name); } public void Handle(ref NetworkContext context) @@ -179,7 +178,8 @@ namespace Unity.Netcode public unsafe bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) { ByteUnpacker.ReadValuePacked(reader, out SenderClientId); - return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer); + + return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, GetType().Name); } public void Handle(ref NetworkContext context) @@ -197,4 +197,138 @@ namespace Unity.Netcode RpcMessageHelpers.Handle(ref context, ref Metadata, ref ReadBuffer, ref rpcParams); } } + + // DANGO-EXP TODO: REMOVE THIS + internal struct ForwardServerRpcMessage : INetworkMessage + { + public int Version => 0; + public ulong OwnerId; + public NetworkDelivery NetworkDelivery; + public ServerRpcMessage ServerRpcMessage; + + public unsafe void Serialize(FastBufferWriter writer, int targetVersion) + { + writer.WriteValueSafe(OwnerId); + writer.WriteValueSafe(NetworkDelivery); + ServerRpcMessage.Serialize(writer, targetVersion); + } + + public unsafe bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) + { + reader.ReadValueSafe(out OwnerId); + reader.ReadValueSafe(out NetworkDelivery); + ServerRpcMessage.ReadBuffer = new FastBufferReader(reader, Allocator.Persistent, reader.Length - reader.Position, sizeof(RpcMetadata)); + + // If deserializing failed or this message was deferred. + if (!ServerRpcMessage.Deserialize(reader, ref context, receivedMessageVersion)) + { + // release this reader as the handler will either be invoked later (deferred) or will not be invoked at all. + ServerRpcMessage.ReadBuffer.Dispose(); + return false; + } + return true; + } + + public void Handle(ref NetworkContext context) + { + var networkManager = (NetworkManager)context.SystemOwner; + if (networkManager.DAHost) + { + try + { + // Since this is temporary, we will not be collection metrics for this. + // DAHost just forwards the message to the owner + ServerRpcMessage.WriteBuffer = new FastBufferWriter(ServerRpcMessage.ReadBuffer.Length, Allocator.TempJob); + ServerRpcMessage.WriteBuffer.WriteBytesSafe(ServerRpcMessage.ReadBuffer.ToArray()); + networkManager.ConnectionManager.SendMessage(ref ServerRpcMessage, NetworkDelivery, OwnerId); + } + catch (Exception ex) + { + Debug.LogException(ex); + } + } + else + { + NetworkLog.LogErrorServer($"Received {nameof(ForwardServerRpcMessage)} on client-{networkManager.LocalClientId}! Only DAHost may forward RPC messages!"); + } + ServerRpcMessage.ReadBuffer.Dispose(); + ServerRpcMessage.WriteBuffer.Dispose(); + } + + } + + // DANGO-EXP TODO: REMOVE THIS + internal struct ForwardClientRpcMessage : INetworkMessage + { + public int Version => 0; + public bool BroadCast; + public ulong[] TargetClientIds; + public NetworkDelivery NetworkDelivery; + public ClientRpcMessage ClientRpcMessage; + + public unsafe void Serialize(FastBufferWriter writer, int targetVersion) + { + if (TargetClientIds == null) + { + BroadCast = true; + writer.WriteValueSafe(BroadCast); + } + else + { + BroadCast = false; + writer.WriteValueSafe(BroadCast); + writer.WriteValueSafe(TargetClientIds); + } + writer.WriteValueSafe(NetworkDelivery); + ClientRpcMessage.Serialize(writer, targetVersion); + } + + public unsafe bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) + { + reader.ReadValueSafe(out BroadCast); + + if (!BroadCast) + { + reader.ReadValueSafe(out TargetClientIds); + } + + reader.ReadValueSafe(out NetworkDelivery); + + ClientRpcMessage.ReadBuffer = new FastBufferReader(reader, Allocator.Persistent, reader.Length - reader.Position, sizeof(RpcMetadata)); + // If deserializing failed or this message was deferred. + if (!ClientRpcMessage.Deserialize(reader, ref context, receivedMessageVersion)) + { + // release this reader as the handler will either be invoked later (deferred) or will not be invoked at all. + ClientRpcMessage.ReadBuffer.Dispose(); + return false; + } + return true; + } + + public void Handle(ref NetworkContext context) + { + var networkManager = (NetworkManager)context.SystemOwner; + if (networkManager.DAHost) + { + ClientRpcMessage.WriteBuffer = new FastBufferWriter(ClientRpcMessage.ReadBuffer.Length, Allocator.TempJob); + ClientRpcMessage.WriteBuffer.WriteBytesSafe(ClientRpcMessage.ReadBuffer.ToArray()); + // Since this is temporary, we will not be collection metrics for this. + // DAHost just forwards the message to the clients + if (BroadCast) + { + networkManager.ConnectionManager.SendMessage(ref ClientRpcMessage, NetworkDelivery, networkManager.ConnectedClientsIds); + } + else + { + networkManager.ConnectionManager.SendMessage(ref ClientRpcMessage, NetworkDelivery, TargetClientIds); + } + } + else + { + NetworkLog.LogErrorServer($"Received {nameof(ForwardClientRpcMessage)} on client-{networkManager.LocalClientId}! Only DAHost may forward RPC messages!"); + } + ClientRpcMessage.WriteBuffer.Dispose(); + ClientRpcMessage.ReadBuffer.Dispose(); + } + } } diff --git a/Runtime/Messaging/Messages/SceneEventMessage.cs b/Runtime/Messaging/Messages/SceneEventMessage.cs index 4417569..25c53a2 100644 --- a/Runtime/Messaging/Messages/SceneEventMessage.cs +++ b/Runtime/Messaging/Messages/SceneEventMessage.cs @@ -1,3 +1,4 @@ + namespace Unity.Netcode { // Todo: Would be lovely to get this one nicely formatted with all the data it sends in the struct @@ -8,6 +9,7 @@ namespace Unity.Netcode public SceneEventData EventData; + private FastBufferReader m_ReceivedData; public void Serialize(FastBufferWriter writer, int targetVersion) @@ -23,7 +25,8 @@ namespace Unity.Netcode public void Handle(ref NetworkContext context) { - ((NetworkManager)context.SystemOwner).SceneManager.HandleSceneEvent(context.SenderId, m_ReceivedData); + var networkManager = (NetworkManager)context.SystemOwner; + networkManager.SceneManager.HandleSceneEvent(context.SenderId, m_ReceivedData); } } } diff --git a/Runtime/Messaging/Messages/ServerLogMessage.cs b/Runtime/Messaging/Messages/ServerLogMessage.cs index b12c008..23f32a6 100644 --- a/Runtime/Messaging/Messages/ServerLogMessage.cs +++ b/Runtime/Messaging/Messages/ServerLogMessage.cs @@ -4,6 +4,8 @@ namespace Unity.Netcode { public int Version => 0; + public ulong SenderId; + public NetworkLog.LogType LogType; // It'd be lovely to be able to replace this with FixedString or NativeArray... // But it's not really practical. On the sending side, the user is likely to want @@ -12,30 +14,39 @@ namespace Unity.Netcode // So an allocation is unavoidable here on both sides. public string Message; - public void Serialize(FastBufferWriter writer, int targetVersion) { writer.WriteValueSafe(LogType); BytePacker.WriteValuePacked(writer, Message); + BytePacker.WriteValueBitPacked(writer, SenderId); } public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) { var networkManager = (NetworkManager)context.SystemOwner; - if (networkManager.IsServer && networkManager.NetworkConfig.EnableNetworkLogs) + + if ((networkManager.IsServer || networkManager.LocalClient.IsSessionOwner) && networkManager.NetworkConfig.EnableNetworkLogs) { reader.ReadValueSafe(out LogType); ByteUnpacker.ReadValuePacked(reader, out Message); + ByteUnpacker.ReadValuePacked(reader, out SenderId); + // If in distributed authority mode and the DAHost is not the session owner, then the DAHost will just forward the message. + if (networkManager.DAHost && networkManager.CurrentSessionOwner != networkManager.LocalClientId) + { + var message = this; + var size = networkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, networkManager.CurrentSessionOwner); + networkManager.NetworkMetrics.TrackServerLogSent(networkManager.CurrentSessionOwner, (uint)LogType, size); + return false; + } return true; } - return false; } public void Handle(ref NetworkContext context) { var networkManager = (NetworkManager)context.SystemOwner; - var senderId = context.SenderId; + var senderId = networkManager.DistributedAuthorityMode ? SenderId : context.SenderId; networkManager.NetworkMetrics.TrackServerLogReceived(senderId, (uint)LogType, context.MessageSize); diff --git a/Runtime/Messaging/Messages/SessionOwnerMessage.cs b/Runtime/Messaging/Messages/SessionOwnerMessage.cs new file mode 100644 index 0000000..e4ac254 --- /dev/null +++ b/Runtime/Messaging/Messages/SessionOwnerMessage.cs @@ -0,0 +1,26 @@ +namespace Unity.Netcode +{ + internal struct SessionOwnerMessage : INetworkMessage + { + public int Version => 0; + + public ulong SessionOwner; + + public void Serialize(FastBufferWriter writer, int targetVersion) + { + BytePacker.WriteValuePacked(writer, SessionOwner); + } + + public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) + { + ByteUnpacker.ReadValuePacked(reader, out SessionOwner); + return true; + } + + public unsafe void Handle(ref NetworkContext context) + { + var networkManager = (NetworkManager)context.SystemOwner; + networkManager.SetSessionOwner(SessionOwner); + } + } +} diff --git a/Runtime/Messaging/Messages/SessionOwnerMessage.cs.meta b/Runtime/Messaging/Messages/SessionOwnerMessage.cs.meta new file mode 100644 index 0000000..832da7f --- /dev/null +++ b/Runtime/Messaging/Messages/SessionOwnerMessage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8e02985965397ab44809c99406914311 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Messaging/NetworkMessageManager.cs b/Runtime/Messaging/NetworkMessageManager.cs index 24699eb..7dd4dae 100644 --- a/Runtime/Messaging/NetworkMessageManager.cs +++ b/Runtime/Messaging/NetworkMessageManager.cs @@ -167,6 +167,28 @@ namespace Unity.Netcode { RegisterMessageType(type); } + +#if UNITY_EDITOR + if (EnableMessageOrderConsoleLog) + { + // DANGO-TODO: Remove this when we have some form of message type indices stability in place + // For now, just log the messages and their assigned types for reference purposes. + var networkManager = m_Owner as NetworkManager; + if (networkManager != null) + { + if (networkManager.DistributedAuthorityMode) + { + var messageListing = new StringBuilder(); + messageListing.AppendLine("NGO Message Index to Type Listing:"); + foreach (var message in m_MessageTypes) + { + messageListing.AppendLine($"[{message.Value}][{message.Key.Name}]"); + } + Debug.Log(messageListing); + } + } + } +#endif } catch (Exception) { @@ -175,6 +197,8 @@ namespace Unity.Netcode } } + internal static bool EnableMessageOrderConsoleLog = false; + public void Dispose() { if (m_Disposed) @@ -823,7 +847,11 @@ namespace Unity.Netcode internal unsafe int SendMessage(ref T message, NetworkDelivery delivery, in NativeList clientIds) where T : INetworkMessage { +#if UTP_TRANSPORT_2_0_ABOVE + return SendMessage(ref message, delivery, new PointerListWrapper(clientIds.GetUnsafePtr(), clientIds.Length)); +#else return SendMessage(ref message, delivery, new PointerListWrapper((ulong*)clientIds.GetUnsafePtr(), clientIds.Length)); +#endif } internal unsafe void ProcessSendQueues() diff --git a/Runtime/Messaging/RpcTargets/AuthorityRpcTarget.cs b/Runtime/Messaging/RpcTargets/AuthorityRpcTarget.cs new file mode 100644 index 0000000..30d22d4 --- /dev/null +++ b/Runtime/Messaging/RpcTargets/AuthorityRpcTarget.cs @@ -0,0 +1,75 @@ +namespace Unity.Netcode +{ + internal class AuthorityRpcTarget : ServerRpcTarget + { + private ProxyRpcTarget m_AuthorityTarget; + private DirectSendRpcTarget m_DirectSendTarget; + + public override void Dispose() + { + if (m_AuthorityTarget != null) + { + m_AuthorityTarget.Dispose(); + m_AuthorityTarget = null; + } + + if (m_DirectSendTarget != null) + { + m_DirectSendTarget.Dispose(); + m_DirectSendTarget = null; + } + + base.Dispose(); + } + + internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams) + { + if (behaviour.NetworkManager.DistributedAuthorityMode) + { + // If invoked locally, then send locally + if (behaviour.HasAuthority) + { + if (m_UnderlyingTarget == null) + { + m_UnderlyingTarget = new LocalSendRpcTarget(m_NetworkManager); + } + m_UnderlyingTarget.Send(behaviour, ref message, delivery, rpcParams); + } + else if (behaviour.NetworkManager.DAHost) + { + if (m_DirectSendTarget == null) + { + m_DirectSendTarget = new DirectSendRpcTarget(behaviour.OwnerClientId, m_NetworkManager); + } + else + { + m_DirectSendTarget.ClientId = behaviour.OwnerClientId; + } + m_DirectSendTarget.Send(behaviour, ref message, delivery, rpcParams); + } + else // Otherwise (for now), we always proxy the RPC messages to the owner + { + if (m_AuthorityTarget == null) + { + m_AuthorityTarget = new ProxyRpcTarget(behaviour.OwnerClientId, m_NetworkManager); + } + else + { + // Since the owner can change, for now we will just clear and set the owner each time + m_AuthorityTarget.SetClientId(behaviour.OwnerClientId); + } + m_AuthorityTarget.Send(behaviour, ref message, delivery, rpcParams); + } + } + else + { + // If we are not in distributed authority mode, then we invoke the normal ServerRpc code. + base.Send(behaviour, ref message, delivery, rpcParams); + } + } + + internal AuthorityRpcTarget(NetworkManager manager) : base(manager) + { + } + } +} diff --git a/Runtime/Messaging/RpcTargets/AuthorityRpcTarget.cs.meta b/Runtime/Messaging/RpcTargets/AuthorityRpcTarget.cs.meta new file mode 100644 index 0000000..fe0f8ac --- /dev/null +++ b/Runtime/Messaging/RpcTargets/AuthorityRpcTarget.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6b8f28b7a617fd34faee91e5f88e89ac +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Messaging/RpcTargets/LocalSendRpcTarget.cs b/Runtime/Messaging/RpcTargets/LocalSendRpcTarget.cs index 92e2083..ffc9b5b 100644 --- a/Runtime/Messaging/RpcTargets/LocalSendRpcTarget.cs +++ b/Runtime/Messaging/RpcTargets/LocalSendRpcTarget.cs @@ -36,7 +36,7 @@ namespace Unity.Netcode MessageType = m_NetworkManager.MessageManager.GetMessageType(typeof(RpcMessage)) }; - behaviour.NetworkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnNextFrame, 0, reader, ref context); + networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnNextFrame, 0, reader, ref context); length = reader.Length; } else @@ -49,8 +49,8 @@ namespace Unity.Netcode #if DEVELOPMENT_BUILD || UNITY_EDITOR if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName)) { - behaviour.NetworkManager.NetworkMetrics.TrackRpcSent( - behaviour.NetworkManager.LocalClientId, + networkManager.NetworkMetrics.TrackRpcSent( + networkManager.LocalClientId, behaviour.NetworkObject, rpcMethodName, behaviour.__getTypeName(), diff --git a/Runtime/Messaging/RpcTargets/NotAuthorityRpcTarget.cs b/Runtime/Messaging/RpcTargets/NotAuthorityRpcTarget.cs new file mode 100644 index 0000000..5001f72 --- /dev/null +++ b/Runtime/Messaging/RpcTargets/NotAuthorityRpcTarget.cs @@ -0,0 +1,65 @@ +namespace Unity.Netcode +{ + internal class NotAuthorityRpcTarget : NotServerRpcTarget + { + internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams) + { + var networkObject = behaviour.NetworkObject; + if (m_NetworkManager.DistributedAuthorityMode) + { + if (m_GroupSendTarget == null) + { + // When mocking the CMB service, we are running a server so create a non-proxy target group + if (m_NetworkManager.DAHost) + { + m_GroupSendTarget = new RpcTargetGroup(m_NetworkManager); + } + else // Otherwise (for now), we always proxy the RPC messages + { + m_GroupSendTarget = new ProxyRpcTargetGroup(m_NetworkManager); + } + } + m_GroupSendTarget.Clear(); + + if (behaviour.HasAuthority) + { + foreach (var clientId in networkObject.Observers) + { + if (clientId == behaviour.OwnerClientId) + { + continue; + } + m_GroupSendTarget.Add(clientId); + } + } + else + { + foreach (var clientId in m_NetworkManager.ConnectedClientsIds) + { + if (clientId == behaviour.OwnerClientId || !networkObject.Observers.Contains(clientId)) + { + continue; + } + + if (clientId == m_NetworkManager.LocalClientId) + { + m_LocalSendRpcTarget.Send(behaviour, ref message, delivery, rpcParams); + continue; + } + m_GroupSendTarget.Add(clientId); + } + } + + m_GroupSendTarget.Target.Send(behaviour, ref message, delivery, rpcParams); + } + else + { + base.Send(behaviour, ref message, delivery, rpcParams); + } + } + + internal NotAuthorityRpcTarget(NetworkManager manager) : base(manager) + { + } + } +} diff --git a/Runtime/Messaging/RpcTargets/NotAuthorityRpcTarget.cs.meta b/Runtime/Messaging/RpcTargets/NotAuthorityRpcTarget.cs.meta new file mode 100644 index 0000000..6dd6f00 --- /dev/null +++ b/Runtime/Messaging/RpcTargets/NotAuthorityRpcTarget.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4968ce7e70c277d4a892c1ed209ce4d6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Messaging/RpcTargets/NotMeRpcTarget.cs b/Runtime/Messaging/RpcTargets/NotMeRpcTarget.cs index 50f81f2..5ea6871 100644 --- a/Runtime/Messaging/RpcTargets/NotMeRpcTarget.cs +++ b/Runtime/Messaging/RpcTargets/NotMeRpcTarget.cs @@ -49,11 +49,18 @@ namespace Unity.Netcode { continue; } + // In distributed authority mode, we send to target id 0 (which would be a DAHost) via the group + if (clientId == NetworkManager.ServerClientId && !m_NetworkManager.DistributedAuthorityMode) + { + continue; + } m_GroupSendTarget.Add(clientId); } } m_GroupSendTarget.Target.Send(behaviour, ref message, delivery, rpcParams); - if (!behaviour.IsServer) + + // In distributed authority mode, we don't use ServerRpc + if (!behaviour.IsServer && !m_NetworkManager.DistributedAuthorityMode) { m_ServerRpcTarget.Send(behaviour, ref message, delivery, rpcParams); } diff --git a/Runtime/Messaging/RpcTargets/NotOwnerRpcTarget.cs b/Runtime/Messaging/RpcTargets/NotOwnerRpcTarget.cs index ece1ded..e4f64f0 100644 --- a/Runtime/Messaging/RpcTargets/NotOwnerRpcTarget.cs +++ b/Runtime/Messaging/RpcTargets/NotOwnerRpcTarget.cs @@ -40,6 +40,10 @@ namespace Unity.Netcode { continue; } + if (clientId == NetworkManager.ServerClientId) + { + continue; + } if (clientId == behaviour.NetworkManager.LocalClientId) { m_LocalSendRpcTarget.Send(behaviour, ref message, delivery, rpcParams); @@ -57,6 +61,10 @@ namespace Unity.Netcode { continue; } + if (clientId == NetworkManager.ServerClientId) + { + continue; + } if (clientId == behaviour.NetworkManager.LocalClientId) { m_LocalSendRpcTarget.Send(behaviour, ref message, delivery, rpcParams); diff --git a/Runtime/Messaging/RpcTargets/NotServerRpcTarget.cs b/Runtime/Messaging/RpcTargets/NotServerRpcTarget.cs index d348660..30b745e 100644 --- a/Runtime/Messaging/RpcTargets/NotServerRpcTarget.cs +++ b/Runtime/Messaging/RpcTargets/NotServerRpcTarget.cs @@ -2,8 +2,8 @@ namespace Unity.Netcode { internal class NotServerRpcTarget : BaseRpcTarget { - private IGroupRpcTarget m_GroupSendTarget; - private LocalSendRpcTarget m_LocalSendRpcTarget; + protected IGroupRpcTarget m_GroupSendTarget; + protected LocalSendRpcTarget m_LocalSendRpcTarget; public override void Dispose() { diff --git a/Runtime/Messaging/RpcTargets/RpcTarget.cs b/Runtime/Messaging/RpcTargets/RpcTarget.cs index 8d99c94..c5706a8 100644 --- a/Runtime/Messaging/RpcTargets/RpcTarget.cs +++ b/Runtime/Messaging/RpcTargets/RpcTarget.cs @@ -62,6 +62,18 @@ namespace Unity.Netcode /// ClientsAndHost, /// + /// Send this RPC to the authority. + /// In distributed authority mode, this will be the owner of the NetworkObject. + /// In normal client-server mode, this is basically the exact same thing as a server rpc. + /// + Authority, + /// + /// Send this RPC to all non-authority instances. + /// In distributed authority mode, this will be the non-owners of the NetworkObject. + /// In normal client-server mode, this is basically the exact same thing as a client rpc. + /// + NotAuthority, + /// /// This RPC cannot be sent without passing in a target in RpcSendParams. /// SpecifiedInParams @@ -100,7 +112,8 @@ namespace Unity.Netcode NotMe = new NotMeRpcTarget(manager); Me = new LocalSendRpcTarget(manager); ClientsAndHost = new ClientsAndHostRpcTarget(manager); - + Authority = new AuthorityRpcTarget(manager); + NotAuthority = new NotAuthorityRpcTarget(manager); m_CachedProxyRpcTargetGroup = new ProxyRpcTargetGroup(manager); m_CachedTargetGroup = new RpcTargetGroup(manager); m_CachedDirectSendTarget = new DirectSendRpcTarget(manager); @@ -122,7 +135,8 @@ namespace Unity.Netcode NotMe.Dispose(); Me.Dispose(); ClientsAndHost.Dispose(); - + Authority.Dispose(); + NotAuthority.Dispose(); m_CachedProxyRpcTargetGroup.Unlock(); m_CachedTargetGroup.Unlock(); m_CachedDirectSendTarget.Unlock(); @@ -134,7 +148,6 @@ namespace Unity.Netcode m_CachedProxyRpcTarget.Dispose(); } - /// /// Send to the NetworkObject's current owner. /// Will execute locally if the local process is the owner. @@ -196,6 +209,20 @@ namespace Unity.Netcode /// public BaseRpcTarget ClientsAndHost; + /// + /// Send this RPC to the authority. + /// In distributed authority mode, this will be the owner of the NetworkObject. + /// In normal client-server mode, this is basically the exact same thing as a server rpc. + /// + public BaseRpcTarget Authority; + + /// + /// Send this RPC to all non-authority instances. + /// In distributed authority mode, this will be the non-owners of the NetworkObject. + /// In normal client-server mode, this is basically the exact same thing as a client rpc. + /// + public BaseRpcTarget NotAuthority; + /// /// Send to a specific single client ID. /// diff --git a/Runtime/Messaging/RpcTargets/ServerRpcTarget.cs b/Runtime/Messaging/RpcTargets/ServerRpcTarget.cs index 09b789d..8ad53fb 100644 --- a/Runtime/Messaging/RpcTargets/ServerRpcTarget.cs +++ b/Runtime/Messaging/RpcTargets/ServerRpcTarget.cs @@ -2,7 +2,7 @@ namespace Unity.Netcode { internal class ServerRpcTarget : BaseRpcTarget { - private BaseRpcTarget m_UnderlyingTarget; + protected BaseRpcTarget m_UnderlyingTarget; public override void Dispose() { @@ -15,6 +15,12 @@ namespace Unity.Netcode internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams) { + if (behaviour.NetworkManager.DistributedAuthorityMode && behaviour.NetworkManager.CMBServiceConnection) + { + UnityEngine.Debug.LogWarning("[Invalid Target] There is no server to send to when in Distributed Authority mode!"); + return; + } + if (m_UnderlyingTarget == null) { if (behaviour.NetworkManager.IsServer) diff --git a/Runtime/NetworkVariable/CollectionSerializationUtility.cs b/Runtime/NetworkVariable/CollectionSerializationUtility.cs new file mode 100644 index 0000000..912bcf9 --- /dev/null +++ b/Runtime/NetworkVariable/CollectionSerializationUtility.cs @@ -0,0 +1,769 @@ +using System; +using System.Collections.Generic; +using Unity.Collections; +using Unity.Collections.LowLevel.Unsafe; +using Unity.Mathematics; + +namespace Unity.Netcode +{ + internal static class CollectionSerializationUtility + { + public static void WriteNativeArrayDelta(FastBufferWriter writer, ref NativeArray value, ref NativeArray previousValue) where T : unmanaged + { + // This bit vector serializes the list of which fields have changed using 1 bit per field. + // This will always be 1 bit per field of the whole array (rounded up to the nearest 8 bits) + // even if there is only one change, so as compared to serializing the index with each item, + // this will use more bandwidth when the overall bandwidth usage is small and the array is large, + // but less when the overall bandwidth usage is large. So it optimizes for the worst case while accepting + // some reduction in efficiency in the best case. + using var changes = new ResizableBitVector(Allocator.Temp); + int minLength = math.min(value.Length, previousValue.Length); + var numChanges = 0; + // Iterate the array, checking which values have changed and marking that in the bit vector + for (var i = 0; i < minLength; ++i) + { + var val = value[i]; + var prevVal = previousValue[i]; + if (!NetworkVariableSerialization.AreEqual(ref val, ref prevVal)) + { + ++numChanges; + changes.Set(i); + } + } + + // Mark any newly added items as well + // We don't need to mark removed items because they are captured by serializing the length + for (var i = previousValue.Length; i < value.Length; ++i) + { + ++numChanges; + changes.Set(i); + } + + // If the size of serializing the dela is greater than the size of serializing the whole array (i.e., + // because almost the entire array has changed and the overhead of the change set increases bandwidth), + // then we just do a normal full serialization instead of a delta. + if (changes.GetSerializedSize() + FastBufferWriter.GetWriteSize() * numChanges > FastBufferWriter.GetWriteSize() * value.Length) + { + // 1 = full serialization + writer.WriteByteSafe(1); + writer.WriteValueSafe(value); + return; + } + // 0 = delta serialization + writer.WriteByte(0); + // Write the length, which will be used on the read side to resize the array + BytePacker.WriteValuePacked(writer, value.Length); + writer.WriteValueSafe(changes); + unsafe + { + var ptr = (T*)value.GetUnsafePtr(); + var prevPtr = (T*)previousValue.GetUnsafePtr(); + for (int i = 0; i < value.Length; ++i) + { + if (changes.IsSet(i)) + { + if (i < previousValue.Length) + { + // If we have an item in the previous array for this index, we can do nested deltas! + NetworkVariableSerialization.WriteDelta(writer, ref ptr[i], ref prevPtr[i]); + } + else + { + // If not, just write it normally + NetworkVariableSerialization.Write(writer, ref ptr[i]); + } + } + } + } + } + public static void ReadNativeArrayDelta(FastBufferReader reader, ref NativeArray value) where T : unmanaged + { + // 1 = full serialization, 0 = delta serialization + reader.ReadByteSafe(out byte full); + if (full == 1) + { + // If we're doing full serialization, we fall back on reading the whole array. + value.Dispose(); + reader.ReadValueSafe(out value, Allocator.Persistent); + return; + } + // If not, first read the length and the change bits + ByteUnpacker.ReadValuePacked(reader, out int length); + var changes = new ResizableBitVector(Allocator.Temp); + using var toDispose = changes; + { + reader.ReadNetworkSerializableInPlace(ref changes); + + // If the length has changed, we need to resize. + // NativeArray is not resizeable, so we have to dispose and allocate a new one. + var previousLength = value.Length; + if (length != value.Length) + { + var newArray = new NativeArray(length, Allocator.Persistent); + unsafe + { + UnsafeUtility.MemCpy(newArray.GetUnsafePtr(), value.GetUnsafePtr(), math.min(newArray.Length * sizeof(T), value.Length * sizeof(T))); + } + value.Dispose(); + value = newArray; + } + + unsafe + { + var ptr = (T*)value.GetUnsafePtr(); + for (var i = 0; i < value.Length; ++i) + { + if (changes.IsSet(i)) + { + if (i < previousLength) + { + // If we have an item to read a delta into, read it as a delta + NetworkVariableSerialization.ReadDelta(reader, ref ptr[i]); + } + else + { + // If not, read as a standard element + NetworkVariableSerialization.Read(reader, ref ptr[i]); + } + } + } + } + } + } + public static void WriteListDelta(FastBufferWriter writer, ref List value, ref List previousValue) + { + // Lists can be null, so we have to handle that case. + // We do that by marking this as a full serialization and using the existing null handling logic + // in NetworkVariableSerialization> + if (value == null || previousValue == null) + { + writer.WriteByteSafe(1); + NetworkVariableSerialization>.Write(writer, ref value); + return; + } + // This bit vector serializes the list of which fields have changed using 1 bit per field. + // This will always be 1 bit per field of the whole array (rounded up to the nearest 8 bits) + // even if there is only one change, so as compared to serializing the index with each item, + // this will use more bandwidth when the overall bandwidth usage is small and the array is large, + // but less when the overall bandwidth usage is large. So it optimizes for the worst case while accepting + // some reduction in efficiency in the best case. + using var changes = new ResizableBitVector(Allocator.Temp); + int minLength = math.min(value.Count, previousValue.Count); + var numChanges = 0; + // Iterate the list, checking which values have changed and marking that in the bit vector + for (var i = 0; i < minLength; ++i) + { + var val = value[i]; + var prevVal = previousValue[i]; + if (!NetworkVariableSerialization.AreEqual(ref val, ref prevVal)) + { + ++numChanges; + changes.Set(i); + } + } + + // Mark any newly added items as well + // We don't need to mark removed items because they are captured by serializing the length + for (var i = previousValue.Count; i < value.Count; ++i) + { + ++numChanges; + changes.Set(i); + } + + // If the size of serializing the dela is greater than the size of serializing the whole array (i.e., + // because almost the entire array has changed and the overhead of the change set increases bandwidth), + // then we just do a normal full serialization instead of a delta. + // In the case of List, it's difficult to know exactly what the serialized size is going to be before + // we serialize it, so we fudge it. + if (numChanges >= value.Count * 0.9) + { + // 1 = full serialization + writer.WriteByteSafe(1); + NetworkVariableSerialization>.Write(writer, ref value); + return; + } + + // 0 = delta serialization + writer.WriteByteSafe(0); + // Write the length, which will be used on the read side to resize the list + BytePacker.WriteValuePacked(writer, value.Count); + writer.WriteValueSafe(changes); + for (int i = 0; i < value.Count; ++i) + { + if (changes.IsSet(i)) + { + var reffable = value[i]; + if (i < previousValue.Count) + { + // If we have an item in the previous array for this index, we can do nested deltas! + var prevReffable = previousValue[i]; + NetworkVariableSerialization.WriteDelta(writer, ref reffable, ref prevReffable); + } + else + { + // If not, just write it normally. + NetworkVariableSerialization.Write(writer, ref reffable); + } + } + } + } + public static void ReadListDelta(FastBufferReader reader, ref List value) + { + // 1 = full serialization, 0 = delta serialization + reader.ReadByteSafe(out byte full); + if (full == 1) + { + // If we're doing full serialization, we fall back on reading the whole list. + NetworkVariableSerialization>.Read(reader, ref value); + return; + } + // If not, first read the length and the change bits + ByteUnpacker.ReadValuePacked(reader, out int length); + var changes = new ResizableBitVector(Allocator.Temp); + using var toDispose = changes; + { + reader.ReadNetworkSerializableInPlace(ref changes); + + // If the list shrank, we need to resize it down. + // List has no method to reserve space for future elements, + // so if we have to grow it, we just do that using Add() below. + if (length < value.Count) + { + value.RemoveRange(length, value.Count - length); + } + + for (var i = 0; i < length; ++i) + { + if (changes.IsSet(i)) + { + if (i < value.Count) + { + // If we have an item to read a delta into, read it as a delta + T item = value[i]; + NetworkVariableSerialization.ReadDelta(reader, ref item); + value[i] = item; + } + else + { + // If not, just read it as a standard item. + T item = default; + NetworkVariableSerialization.Read(reader, ref item); + value.Add(item); + } + } + } + } + } + + // For HashSet and Dictionary, we need to have some local space to hold lists we need to serialize. + // We don't want to do allocations all the time and we know each one needs a maximum of three lists, + // so we're going to keep static lists that we can reuse in these methods. + private static class ListCache + { + private static List s_AddedList = new List(); + private static List s_RemovedList = new List(); + private static List s_ChangedList = new List(); + + public static List GetAddedList() + { + s_AddedList.Clear(); + return s_AddedList; + } + public static List GetRemovedList() + { + s_RemovedList.Clear(); + return s_RemovedList; + } + public static List GetChangedList() + { + s_ChangedList.Clear(); + return s_ChangedList; + } + } + + public static void WriteHashSetDelta(FastBufferWriter writer, ref HashSet value, ref HashSet previousValue) where T : IEquatable + { + // HashSets can be null, so we have to handle that case. + // We do that by marking this as a full serialization and using the existing null handling logic + // in NetworkVariableSerialization> + if (value == null || previousValue == null) + { + writer.WriteByteSafe(1); + NetworkVariableSerialization>.Write(writer, ref value); + return; + } + // No changed array because a set can't have a "changed" element, only added and removed. + var added = ListCache.GetAddedList(); + var removed = ListCache.GetRemovedList(); + // collect the new elements + foreach (var item in value) + { + if (!previousValue.Contains(item)) + { + added.Add(item); + } + } + + // collect the removed elements + foreach (var item in previousValue) + { + if (!value.Contains(item)) + { + removed.Add(item); + } + } + + // If we've got more changes than total items, we just do a full serialization + if (added.Count + removed.Count >= value.Count) + { + writer.WriteByteSafe(1); + NetworkVariableSerialization>.Write(writer, ref value); + return; + } + + writer.WriteByteSafe(0); + // Write out the added and removed arrays. + writer.WriteValueSafe(added.Count); + for (var i = 0; i < added.Count; ++i) + { + var item = added[i]; + NetworkVariableSerialization.Write(writer, ref item); + } + writer.WriteValueSafe(removed.Count); + for (var i = 0; i < removed.Count; ++i) + { + var item = removed[i]; + NetworkVariableSerialization.Write(writer, ref item); + } + } + + public static void ReadHashSetDelta(FastBufferReader reader, ref HashSet value) where T : IEquatable + { + // 1 = full serialization, 0 = delta serialization + reader.ReadByteSafe(out byte full); + if (full != 0) + { + NetworkVariableSerialization>.Read(reader, ref value); + return; + } + // Read in the added and removed values + reader.ReadValueSafe(out int addedCount); + for (var i = 0; i < addedCount; ++i) + { + T item = default; + NetworkVariableSerialization.Read(reader, ref item); + value.Add(item); + } + reader.ReadValueSafe(out int removedCount); + for (var i = 0; i < removedCount; ++i) + { + T item = default; + NetworkVariableSerialization.Read(reader, ref item); + value.Remove(item); + } + } + public static void WriteDictionaryDelta(FastBufferWriter writer, ref Dictionary value, ref Dictionary previousValue) + where TKey : IEquatable + { + if (value == null || previousValue == null) + { + writer.WriteByteSafe(1); + NetworkVariableSerialization>.Write(writer, ref value); + return; + } + var added = ListCache>.GetAddedList(); + var changed = ListCache>.GetRemovedList(); + var removed = ListCache>.GetChangedList(); + // Collect items that have been added or have changed + foreach (var item in value) + { + var val = item.Value; + var hasPrevVal = previousValue.TryGetValue(item.Key, out var prevVal); + if (!hasPrevVal) + { + added.Add(item); + } + else if (!NetworkVariableSerialization.AreEqual(ref val, ref prevVal)) + { + changed.Add(item); + } + } + + // collect the items that have been removed + foreach (var item in previousValue) + { + if (!value.ContainsKey(item.Key)) + { + removed.Add(item); + } + } + + // If there are more changes than total values, just do a full serialization + if (added.Count + removed.Count + changed.Count >= value.Count) + { + writer.WriteByteSafe(1); + NetworkVariableSerialization>.Write(writer, ref value); + return; + } + + writer.WriteByteSafe(0); + // Else, write out the added, removed, and changed arrays + writer.WriteValueSafe(added.Count); + for (var i = 0; i < added.Count; ++i) + { + (var key, var val) = (added[i].Key, added[i].Value); + NetworkVariableSerialization.Write(writer, ref key); + NetworkVariableSerialization.Write(writer, ref val); + } + writer.WriteValueSafe(removed.Count); + for (var i = 0; i < removed.Count; ++i) + { + var key = removed[i].Key; + NetworkVariableSerialization.Write(writer, ref key); + } + writer.WriteValueSafe(changed.Count); + for (var i = 0; i < changed.Count; ++i) + { + (var key, var val) = (changed[i].Key, changed[i].Value); + NetworkVariableSerialization.Write(writer, ref key); + NetworkVariableSerialization.Write(writer, ref val); + } + } + + public static void ReadDictionaryDelta(FastBufferReader reader, ref Dictionary value) + where TKey : IEquatable + { + // 1 = full serialization, 0 = delta serialization + reader.ReadByteSafe(out byte full); + if (full != 0) + { + NetworkVariableSerialization>.Read(reader, ref value); + return; + } + // Added + reader.ReadValueSafe(out int length); + for (var i = 0; i < length; ++i) + { + (TKey key, TVal val) = (default, default); + NetworkVariableSerialization.Read(reader, ref key); + NetworkVariableSerialization.Read(reader, ref val); + value.Add(key, val); + } + // Removed + reader.ReadValueSafe(out length); + for (var i = 0; i < length; ++i) + { + TKey key = default; + NetworkVariableSerialization.Read(reader, ref key); + value.Remove(key); + } + // Changed + reader.ReadValueSafe(out length); + for (var i = 0; i < length; ++i) + { + (TKey key, TVal val) = (default, default); + NetworkVariableSerialization.Read(reader, ref key); + NetworkVariableSerialization.Read(reader, ref val); + value[key] = val; + } + } + +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public static void WriteNativeListDelta(FastBufferWriter writer, ref NativeList value, ref NativeList previousValue) where T : unmanaged + { + // See WriteListDelta and WriteNativeArrayDelta to understand most of this. It's basically the same, + // just adjusted for the NativeList API + using var changes = new ResizableBitVector(Allocator.Temp); + int minLength = math.min(value.Length, previousValue.Length); + var numChanges = 0; + for (var i = 0; i < minLength; ++i) + { + var val = value[i]; + var prevVal = previousValue[i]; + if (!NetworkVariableSerialization.AreEqual(ref val, ref prevVal)) + { + ++numChanges; + changes.Set(i); + } + } + + for (var i = previousValue.Length; i < value.Length; ++i) + { + ++numChanges; + changes.Set(i); + } + + if (changes.GetSerializedSize() + FastBufferWriter.GetWriteSize() * numChanges > FastBufferWriter.GetWriteSize() * value.Length) + { + writer.WriteByteSafe(1); + writer.WriteValueSafe(value); + return; + } + + writer.WriteByte(0); + BytePacker.WriteValuePacked(writer, value.Length); + writer.WriteValueSafe(changes); + unsafe + { +#if UTP_TRANSPORT_2_0_ABOVE + var ptr = value.GetUnsafePtr(); + var prevPtr = previousValue.GetUnsafePtr(); +#else + var ptr = (T*)value.GetUnsafePtr(); + var prevPtr = (T*)previousValue.GetUnsafePtr(); +#endif + for (int i = 0; i < value.Length; ++i) + { + if (changes.IsSet(i)) + { + if (i < previousValue.Length) + { + NetworkVariableSerialization.WriteDelta(writer, ref ptr[i], ref prevPtr[i]); + } + else + { + NetworkVariableSerialization.Write(writer, ref ptr[i]); + } + } + } + } + } + public static void ReadNativeListDelta(FastBufferReader reader, ref NativeList value) where T : unmanaged + { + // See ReadListDelta and ReadNativeArrayDelta to understand most of this. It's basically the same, + // just adjusted for the NativeList API + reader.ReadByteSafe(out byte full); + if (full == 1) + { + reader.ReadValueSafeInPlace(ref value); + return; + } + ByteUnpacker.ReadValuePacked(reader, out int length); + var changes = new ResizableBitVector(Allocator.Temp); + using var toDispose = changes; + { + reader.ReadNetworkSerializableInPlace(ref changes); + + var previousLength = value.Length; + // The one big difference between this and NativeArray/List is that NativeList supports + // easy and fast resizing and reserving space. + if (length != value.Length) + { + value.Resize(length, NativeArrayOptions.UninitializedMemory); + } + + unsafe + { +#if UTP_TRANSPORT_2_0_ABOVE + var ptr = value.GetUnsafePtr(); +#else + var ptr = (T*)value.GetUnsafePtr(); +#endif + for (var i = 0; i < value.Length; ++i) + { + if (changes.IsSet(i)) + { + if (i < previousLength) + { + NetworkVariableSerialization.ReadDelta(reader, ref ptr[i]); + } + else + { + NetworkVariableSerialization.Read(reader, ref ptr[i]); + } + } + } + } + } + } + + public static unsafe void WriteNativeHashSetDelta(FastBufferWriter writer, ref NativeHashSet value, ref NativeHashSet previousValue) where T : unmanaged, IEquatable + { + // See WriteHashSet; this is the same algorithm, adjusted for the NativeHashSet API + var added = stackalloc T[value.Count]; + var removed = stackalloc T[previousValue.Count]; + var addedCount = 0; + var removedCount = 0; + foreach (var item in value) + { + if (!previousValue.Contains(item)) + { + added[addedCount] = item; + ++addedCount; + } + } + + foreach (var item in previousValue) + { + if (!value.Contains(item)) + { + removed[removedCount] = item; + ++removedCount; + } + } +#if UTP_TRANSPORT_2_0_ABOVE + if (addedCount + removedCount >= value.Count) +#else + if (addedCount + removedCount >= value.Count()) +#endif + { + writer.WriteByteSafe(1); + writer.WriteValueSafe(value); + return; + } + + writer.WriteByteSafe(0); + writer.WriteValueSafe(addedCount); + for (var i = 0; i < addedCount; ++i) + { + NetworkVariableSerialization.Write(writer, ref added[i]); + } + writer.WriteValueSafe(removedCount); + for (var i = 0; i < removedCount; ++i) + { + NetworkVariableSerialization.Write(writer, ref removed[i]); + } + } + + public static void ReadNativeHashSetDelta(FastBufferReader reader, ref NativeHashSet value) where T : unmanaged, IEquatable + { + // See ReadHashSet; this is the same algorithm, adjusted for the NativeHashSet API + reader.ReadByteSafe(out byte full); + if (full != 0) + { + reader.ReadValueSafeInPlace(ref value); + return; + } + reader.ReadValueSafe(out int addedCount); + for (var i = 0; i < addedCount; ++i) + { + T item = default; + NetworkVariableSerialization.Read(reader, ref item); + value.Add(item); + } + reader.ReadValueSafe(out int removedCount); + for (var i = 0; i < removedCount; ++i) + { + T item = default; + NetworkVariableSerialization.Read(reader, ref item); + value.Remove(item); + } + } + + public static unsafe void WriteNativeHashMapDelta(FastBufferWriter writer, ref NativeHashMap value, ref NativeHashMap previousValue) + where TKey : unmanaged, IEquatable + where TVal : unmanaged + { + // See WriteDictionary; this is the same algorithm, adjusted for the NativeHashMap API +#if UTP_TRANSPORT_2_0_ABOVE + var added = stackalloc KVPair[value.Count]; + var changed = stackalloc KVPair[value.Count]; + var removed = stackalloc KVPair[previousValue.Count]; +#else + var added = stackalloc KeyValue[value.Count()]; + var changed = stackalloc KeyValue[value.Count()]; + var removed = stackalloc KeyValue[previousValue.Count()]; +#endif + var addedCount = 0; + var changedCount = 0; + var removedCount = 0; + foreach (var item in value) + { + + var hasPrevVal = previousValue.TryGetValue(item.Key, out var prevVal); + if (!hasPrevVal) + { + added[addedCount] = item; + ++addedCount; + } + else if (!NetworkVariableSerialization.AreEqual(ref item.Value, ref prevVal)) + { + changed[changedCount] = item; + ++changedCount; + } + } + + foreach (var item in previousValue) + { + if (!value.ContainsKey(item.Key)) + { + removed[removedCount] = item; + ++removedCount; + } + } + +#if UTP_TRANSPORT_2_0_ABOVE + if (addedCount + removedCount + changedCount >= value.Count) +#else + if (addedCount + removedCount + changedCount >= value.Count()) +#endif + { + writer.WriteByteSafe(1); + writer.WriteValueSafe(value); + return; + } + + writer.WriteByteSafe(0); + writer.WriteValueSafe(addedCount); + for (var i = 0; i < addedCount; ++i) + { + (var key, var val) = (added[i].Key, added[i].Value); + NetworkVariableSerialization.Write(writer, ref key); + NetworkVariableSerialization.Write(writer, ref val); + } + writer.WriteValueSafe(removedCount); + for (var i = 0; i < removedCount; ++i) + { + var key = removed[i].Key; + NetworkVariableSerialization.Write(writer, ref key); + } + writer.WriteValueSafe(changedCount); + for (var i = 0; i < changedCount; ++i) + { + (var key, var val) = (changed[i].Key, changed[i].Value); + NetworkVariableSerialization.Write(writer, ref key); + NetworkVariableSerialization.Write(writer, ref val); + } + } + + public static void ReadNativeHashMapDelta(FastBufferReader reader, ref NativeHashMap value) + where TKey : unmanaged, IEquatable + where TVal : unmanaged + { + // See ReadDictionary; this is the same algorithm, adjusted for the NativeHashMap API + reader.ReadByteSafe(out byte full); + if (full != 0) + { + reader.ReadValueSafeInPlace(ref value); + return; + } + // Added + reader.ReadValueSafe(out int length); + for (var i = 0; i < length; ++i) + { + (TKey key, TVal val) = (default, default); + NetworkVariableSerialization.Read(reader, ref key); + NetworkVariableSerialization.Read(reader, ref val); + value.Add(key, val); + } + // Removed + reader.ReadValueSafe(out length); + for (var i = 0; i < length; ++i) + { + TKey key = default; + NetworkVariableSerialization.Read(reader, ref key); + value.Remove(key); + } + // Changed + reader.ReadValueSafe(out length); + for (var i = 0; i < length; ++i) + { + (TKey key, TVal val) = (default, default); + NetworkVariableSerialization.Read(reader, ref key); + NetworkVariableSerialization.Read(reader, ref val); + value[key] = val; + } + } +#endif + } +} diff --git a/Runtime/NetworkVariable/CollectionSerializationUtility.cs.meta b/Runtime/NetworkVariable/CollectionSerializationUtility.cs.meta new file mode 100644 index 0000000..2d25365 --- /dev/null +++ b/Runtime/NetworkVariable/CollectionSerializationUtility.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c822ece4e24f4676861e07288a7f8526 +timeCreated: 1705437250 \ No newline at end of file diff --git a/Runtime/NetworkVariable/Collections/NetworkList.cs b/Runtime/NetworkVariable/Collections/NetworkList.cs index a082b4e..0c10224 100644 --- a/Runtime/NetworkVariable/Collections/NetworkList.cs +++ b/Runtime/NetworkVariable/Collections/NetworkList.cs @@ -24,6 +24,7 @@ namespace Unity.Netcode /// The callback to be invoked when the list gets changed /// public event OnListChangedDelegate OnListChanged; + internal override NetworkVariableType Type => NetworkVariableType.NetworkList; /// /// Constructor method for @@ -98,7 +99,7 @@ namespace Unity.Netcode break; case NetworkListEvent.EventType.Insert: { - writer.WriteValueSafe(element.Index); + BytePacker.WriteValueBitPacked(writer, element.Index); NetworkVariableSerialization.Write(writer, ref element.Value); } break; @@ -109,12 +110,12 @@ namespace Unity.Netcode break; case NetworkListEvent.EventType.RemoveAt: { - writer.WriteValueSafe(element.Index); + BytePacker.WriteValueBitPacked(writer, element.Index); } break; case NetworkListEvent.EventType.Value: { - writer.WriteValueSafe(element.Index); + BytePacker.WriteValueBitPacked(writer, element.Index); NetworkVariableSerialization.Write(writer, ref element.Value); } break; @@ -130,6 +131,20 @@ namespace Unity.Netcode /// public override void WriteField(FastBufferWriter writer) { + if (m_NetworkManager.DistributedAuthorityMode) + { + writer.WriteValueSafe(NetworkVariableSerialization.Type); + if (NetworkVariableSerialization.Type == CollectionItemType.Unmanaged) + { + // Write the size of the unmanaged serialized type as it has a fixed size. This allows the CMB runtime to correctly read the unmanged type. + var placeholder = new T(); + var startPos = writer.Position; + NetworkVariableSerialization.Write(writer, ref placeholder); + var size = writer.Position - startPos; + writer.Seek(startPos); + BytePacker.WriteValueBitPacked(writer, size); + } + } writer.WriteValueSafe((ushort)m_List.Length); for (int i = 0; i < m_List.Length; i++) { @@ -141,6 +156,15 @@ namespace Unity.Netcode public override void ReadField(FastBufferReader reader) { m_List.Clear(); + if (m_NetworkManager.DistributedAuthorityMode) + { + // Collection item type is used by the CMB rust service, drop value here. + reader.ReadValueSafe(out CollectionItemType type); + if (type == CollectionItemType.Unmanaged) + { + ByteUnpacker.ReadValueBitPacked(reader, out int _); + } + } reader.ReadValueSafe(out ushort count); for (int i = 0; i < count; i++) { @@ -189,7 +213,7 @@ namespace Unity.Netcode break; case NetworkListEvent.EventType.Insert: { - reader.ReadValueSafe(out int index); + ByteUnpacker.ReadValueBitPacked(reader, out int index); var value = new T(); NetworkVariableSerialization.Read(reader, ref value); @@ -261,7 +285,7 @@ namespace Unity.Netcode break; case NetworkListEvent.EventType.RemoveAt: { - reader.ReadValueSafe(out int index); + ByteUnpacker.ReadValueBitPacked(reader, out int index); T value = m_List[index]; m_List.RemoveAt(index); @@ -289,7 +313,7 @@ namespace Unity.Netcode break; case NetworkListEvent.EventType.Value: { - reader.ReadValueSafe(out int index); + ByteUnpacker.ReadValueBitPacked(reader, out int index); var value = new T(); NetworkVariableSerialization.Read(reader, ref value); if (index >= m_List.Length) @@ -367,7 +391,7 @@ namespace Unity.Netcode public void Add(T item) { // check write permissions - if (!CanClientWrite(m_NetworkBehaviour.NetworkManager.LocalClientId)) + if (!CanClientWrite(m_NetworkManager.LocalClientId)) { throw new InvalidOperationException("Client is not allowed to write to this NetworkList"); } @@ -388,7 +412,7 @@ namespace Unity.Netcode public void Clear() { // check write permissions - if (!CanClientWrite(m_NetworkBehaviour.NetworkManager.LocalClientId)) + if (!CanClientWrite(m_NetworkManager.LocalClientId)) { throw new InvalidOperationException("Client is not allowed to write to this NetworkList"); } @@ -414,7 +438,7 @@ namespace Unity.Netcode public bool Remove(T item) { // check write permissions - if (!CanClientWrite(m_NetworkBehaviour.NetworkManager.LocalClientId)) + if (!CanClientWrite(m_NetworkManager.LocalClientId)) { throw new InvalidOperationException("Client is not allowed to write to this NetworkList"); } @@ -449,7 +473,7 @@ namespace Unity.Netcode public void Insert(int index, T item) { // check write permissions - if (!CanClientWrite(m_NetworkBehaviour.NetworkManager.LocalClientId)) + if (!CanClientWrite(m_NetworkManager.LocalClientId)) { throw new InvalidOperationException("Client is not allowed to write to this NetworkList"); } @@ -478,7 +502,7 @@ namespace Unity.Netcode public void RemoveAt(int index) { // check write permissions - if (!CanClientWrite(m_NetworkBehaviour.NetworkManager.LocalClientId)) + if (!CanClientWrite(m_NetworkManager.LocalClientId)) { throw new InvalidOperationException("Client is not allowed to write to this NetworkList"); } @@ -503,7 +527,7 @@ namespace Unity.Netcode set { // check write permissions - if (!CanClientWrite(m_NetworkBehaviour.NetworkManager.LocalClientId)) + if (!CanClientWrite(m_NetworkManager.LocalClientId)) { throw new InvalidOperationException("Client is not allowed to write to this NetworkList"); } @@ -551,6 +575,7 @@ namespace Unity.Netcode { m_List.Dispose(); m_DirtyEvents.Dispose(); + base.Dispose(); } } diff --git a/Runtime/NetworkVariable/NetworkVariable.cs b/Runtime/NetworkVariable/NetworkVariable.cs index db33b7b..cf4d36e 100644 --- a/Runtime/NetworkVariable/NetworkVariable.cs +++ b/Runtime/NetworkVariable/NetworkVariable.cs @@ -21,6 +21,7 @@ namespace Unity.Netcode /// The callback to be invoked when the value gets changed /// public OnValueChangedDelegate OnValueChanged; + internal override NetworkVariableType Type => NetworkVariableType.Value; /// /// Constructor for @@ -43,6 +44,19 @@ namespace Unity.Netcode m_PreviousValue = default; } + /// + /// Resets the NetworkVariable when the associated NetworkObject is not spawned + /// + /// the value to reset the NetworkVariable to (if none specified it resets to the default) + public void Reset(T value = default) + { + if (m_NetworkBehaviour == null || m_NetworkBehaviour != null && !m_NetworkBehaviour.NetworkObject.IsSpawned) + { + m_InternalValue = value; + m_PreviousValue = default; + } + } + /// /// The internal value of the NetworkVariable /// @@ -68,9 +82,9 @@ namespace Unity.Netcode return; } - if (m_NetworkBehaviour && !CanClientWrite(m_NetworkBehaviour.NetworkManager.LocalClientId)) + if (m_NetworkManager && !CanClientWrite(m_NetworkManager.LocalClientId)) { - throw new InvalidOperationException("Client is not allowed to write to this NetworkVariable"); + throw new InvalidOperationException($"[Client-{m_NetworkManager.LocalClientId}][{m_NetworkBehaviour.name}][{Name}] Write permissions ({WritePerm}) for this client instance is not allowed!"); } Set(value); @@ -104,6 +118,8 @@ namespace Unity.Netcode } m_PreviousValue = default; + + base.Dispose(); } ~NetworkVariable() @@ -142,16 +158,16 @@ namespace Unity.Netcode /// public override void ResetDirty() { - base.ResetDirty(); // Resetting the dirty value declares that the current value is not dirty // Therefore, we set the m_PreviousValue field to a duplicate of the current // field, so that our next dirty check is made against the current "not dirty" // value. - if (!m_HasPreviousValue || !NetworkVariableSerialization.AreEqual(ref m_InternalValue, ref m_PreviousValue)) + if (IsDirty()) { m_HasPreviousValue = true; NetworkVariableSerialization.Duplicate(m_InternalValue, ref m_PreviousValue); } + base.ResetDirty(); } /// @@ -173,7 +189,7 @@ namespace Unity.Netcode /// The stream to write the value to public override void WriteDelta(FastBufferWriter writer) { - WriteField(writer); + NetworkVariableSerialization.WriteDelta(writer, ref m_InternalValue, ref m_PreviousValue); } /// @@ -189,7 +205,7 @@ namespace Unity.Netcode // would be stored in different fields T previousValue = m_InternalValue; - NetworkVariableSerialization.Read(reader, ref m_InternalValue); + NetworkVariableSerialization.ReadDelta(reader, ref m_InternalValue); if (keepDirtyDelta) { diff --git a/Runtime/NetworkVariable/NetworkVariableBase.cs b/Runtime/NetworkVariable/NetworkVariableBase.cs index 927687c..e142fe9 100644 --- a/Runtime/NetworkVariable/NetworkVariableBase.cs +++ b/Runtime/NetworkVariable/NetworkVariableBase.cs @@ -18,6 +18,22 @@ namespace Unity.Netcode /// private protected NetworkBehaviour m_NetworkBehaviour; + private NetworkManager m_InternalNetworkManager; + + internal virtual NetworkVariableType Type => NetworkVariableType.Custom; + + private protected NetworkManager m_NetworkManager + { + get + { + if (m_InternalNetworkManager == null && m_NetworkBehaviour && m_NetworkBehaviour.NetworkObject?.NetworkManager) + { + m_InternalNetworkManager = m_NetworkBehaviour.NetworkObject?.NetworkManager; + } + return m_InternalNetworkManager; + } + } + public NetworkBehaviour GetBehaviour() { return m_NetworkBehaviour; @@ -29,7 +45,14 @@ namespace Unity.Netcode /// The NetworkBehaviour the NetworkVariable belongs to public void Initialize(NetworkBehaviour networkBehaviour) { + m_InternalNetworkManager = null; m_NetworkBehaviour = networkBehaviour; + if (m_NetworkBehaviour && m_NetworkBehaviour.NetworkObject?.NetworkManager) + { + m_InternalNetworkManager = m_NetworkBehaviour.NetworkObject?.NetworkManager; + // When in distributed authority mode, there is no such thing as server write permissions + InternalWritePerm = m_InternalNetworkManager.DistributedAuthorityMode ? NetworkVariableWritePermission.Owner : InternalWritePerm; + } } /// @@ -53,7 +76,7 @@ namespace Unity.Netcode NetworkVariableWritePermission writePerm = DefaultWritePerm) { ReadPerm = readPerm; - WritePerm = writePerm; + InternalWritePerm = writePerm; } /// @@ -76,7 +99,17 @@ namespace Unity.Netcode /// /// The write permission for this var /// - public readonly NetworkVariableWritePermission WritePerm; + public NetworkVariableWritePermission WritePerm + { + get + { + return InternalWritePerm; + } + } + + // We had to change the Write Permission in distributed authority. + // (It is too bad we initially declared it as readonly) + internal NetworkVariableWritePermission InternalWritePerm; /// /// Sets whether or not the variable needs to be delta synced @@ -92,12 +125,17 @@ namespace Unity.Netcode } } + internal static bool IgnoreInitializeWarning; + protected void MarkNetworkBehaviourDirty() { if (m_NetworkBehaviour == null) { - Debug.LogWarning($"NetworkVariable is written to, but doesn't know its NetworkBehaviour yet. " + - "Are you modifying a NetworkVariable before the NetworkObject is spawned?"); + if (!IgnoreInitializeWarning) + { + Debug.LogWarning($"NetworkVariable is written to, but doesn't know its NetworkBehaviour yet. " + + "Are you modifying a NetworkVariable before the NetworkObject is spawned?"); + } return; } if (m_NetworkBehaviour.NetworkManager.ShutdownInProgress) @@ -109,7 +147,7 @@ namespace Unity.Netcode } return; } - m_NetworkBehaviour.NetworkManager.BehaviourUpdater.AddForUpdate(m_NetworkBehaviour.NetworkObject); + m_NetworkBehaviour.NetworkManager.BehaviourUpdater?.AddForUpdate(m_NetworkBehaviour.NetworkObject); } /// @@ -136,6 +174,11 @@ namespace Unity.Netcode /// Whether or not the client has permission to read public bool CanClientRead(ulong clientId) { + // When in distributed authority mode, everyone can read (but only the owner can write) + if (m_NetworkManager != null && m_NetworkManager.DistributedAuthorityMode) + { + return true; + } switch (ReadPerm) { default: @@ -201,6 +244,50 @@ namespace Unity.Netcode /// public virtual void Dispose() { + m_InternalNetworkManager = null; } } + + /// + /// Enum representing the different types of Network Variables. + /// + public enum NetworkVariableType : byte + { + /// + /// Value + /// Used for all of the basic NetworkVariables that contain a single value + /// + Value = 0, + + /// + /// Custom + /// For any custom implemented extension of the NetworkVariableBase + /// + Custom = 1, + + /// + /// NetworkList + /// + NetworkList = 2 + } + + public enum CollectionItemType : byte + { + /// + /// For any type that is not valid inside a NetworkVariable collection + /// + Unknown = 0, + + /// + /// The following types are valid types inside of NetworkVariable collections + /// + Short = 1, + UShort = 2, + Int = 3, + UInt = 4, + Long = 5, + ULong = 6, + Unmanaged = 7, + } + } diff --git a/Runtime/NetworkVariable/NetworkVariableSerialization.cs b/Runtime/NetworkVariable/NetworkVariableSerialization.cs index fc900e6..df7c3b9 100644 --- a/Runtime/NetworkVariable/NetworkVariableSerialization.cs +++ b/Runtime/NetworkVariable/NetworkVariableSerialization.cs @@ -1,6 +1,8 @@ using System; +using System.Collections.Generic; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; +using Unity.Mathematics; using UnityEditor; using UnityEngine; @@ -20,6 +22,8 @@ namespace Unity.Netcode // of it to pass it as a ref parameter. public void Write(FastBufferWriter writer, ref T value); public void Read(FastBufferReader reader, ref T value); + public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue); + public void ReadDelta(FastBufferReader reader, ref T value); internal void ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator); public void Duplicate(in T value, ref T duplicatedValue); } @@ -38,6 +42,15 @@ namespace Unity.Netcode ByteUnpacker.ReadValueBitPacked(reader, out value); } + public void WriteDelta(FastBufferWriter writer, ref short value, ref short previousValue) + { + Write(writer, ref value); + } + public void ReadDelta(FastBufferReader reader, ref short value) + { + Read(reader, ref value); + } + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out short value, Allocator allocator) { throw new NotImplementedException(); @@ -63,6 +76,15 @@ namespace Unity.Netcode ByteUnpacker.ReadValueBitPacked(reader, out value); } + public void WriteDelta(FastBufferWriter writer, ref ushort value, ref ushort previousValue) + { + Write(writer, ref value); + } + public void ReadDelta(FastBufferReader reader, ref ushort value) + { + Read(reader, ref value); + } + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out ushort value, Allocator allocator) { throw new NotImplementedException(); @@ -88,6 +110,15 @@ namespace Unity.Netcode ByteUnpacker.ReadValueBitPacked(reader, out value); } + public void WriteDelta(FastBufferWriter writer, ref int value, ref int previousValue) + { + Write(writer, ref value); + } + public void ReadDelta(FastBufferReader reader, ref int value) + { + Read(reader, ref value); + } + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out int value, Allocator allocator) { throw new NotImplementedException(); @@ -113,6 +144,15 @@ namespace Unity.Netcode ByteUnpacker.ReadValueBitPacked(reader, out value); } + public void WriteDelta(FastBufferWriter writer, ref uint value, ref uint previousValue) + { + Write(writer, ref value); + } + public void ReadDelta(FastBufferReader reader, ref uint value) + { + Read(reader, ref value); + } + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out uint value, Allocator allocator) { throw new NotImplementedException(); @@ -138,6 +178,15 @@ namespace Unity.Netcode ByteUnpacker.ReadValueBitPacked(reader, out value); } + public void WriteDelta(FastBufferWriter writer, ref long value, ref long previousValue) + { + Write(writer, ref value); + } + public void ReadDelta(FastBufferReader reader, ref long value) + { + Read(reader, ref value); + } + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out long value, Allocator allocator) { throw new NotImplementedException(); @@ -163,6 +212,15 @@ namespace Unity.Netcode ByteUnpacker.ReadValueBitPacked(reader, out value); } + public void WriteDelta(FastBufferWriter writer, ref ulong value, ref ulong previousValue) + { + Write(writer, ref value); + } + public void ReadDelta(FastBufferReader reader, ref ulong value) + { + Read(reader, ref value); + } + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out ulong value, Allocator allocator) { throw new NotImplementedException(); @@ -193,6 +251,15 @@ namespace Unity.Netcode reader.ReadUnmanagedSafe(out value); } + public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue) + { + Write(writer, ref value); + } + public void ReadDelta(FastBufferReader reader, ref T value) + { + Read(reader, ref value); + } + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator) { throw new NotImplementedException(); @@ -204,6 +271,237 @@ namespace Unity.Netcode } } + internal class ListSerializer : INetworkVariableSerializer> + { + public void Write(FastBufferWriter writer, ref List value) + { + bool isNull = value == null; + writer.WriteValueSafe(isNull); + if (!isNull) + { + BytePacker.WriteValuePacked(writer, value.Count); + foreach (var item in value) + { + var reffable = item; + NetworkVariableSerialization.Write(writer, ref reffable); + } + } + } + public void Read(FastBufferReader reader, ref List value) + { + reader.ReadValueSafe(out bool isNull); + if (isNull) + { + value = null; + } + else + { + if (value == null) + { + value = new List(); + } + + ByteUnpacker.ReadValuePacked(reader, out int len); + if (len < value.Count) + { + value.RemoveRange(len, value.Count - len); + } + for (var i = 0; i < len; ++i) + { + // Read in place where possible + if (i < value.Count) + { + T item = value[i]; + NetworkVariableSerialization.Read(reader, ref item); + value[i] = item; + } + else + { + T item = default; + NetworkVariableSerialization.Read(reader, ref item); + value.Add(item); + } + } + } + } + + public void WriteDelta(FastBufferWriter writer, ref List value, ref List previousValue) + { + CollectionSerializationUtility.WriteListDelta(writer, ref value, ref previousValue); + } + public void ReadDelta(FastBufferReader reader, ref List value) + { + CollectionSerializationUtility.ReadListDelta(reader, ref value); + } + + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out List value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in List value, ref List duplicatedValue) + { + if (duplicatedValue == null) + { + duplicatedValue = new List(); + } + + duplicatedValue.Clear(); + foreach (var item in value) + { + duplicatedValue.Add(item); + } + } + } + + internal class HashSetSerializer : INetworkVariableSerializer> where T : IEquatable + { + public void Write(FastBufferWriter writer, ref HashSet value) + { + bool isNull = value == null; + writer.WriteValueSafe(isNull); + if (!isNull) + { + writer.WriteValueSafe(value.Count); + foreach (var item in value) + { + var reffable = item; + NetworkVariableSerialization.Write(writer, ref reffable); + } + } + } + public void Read(FastBufferReader reader, ref HashSet value) + { + reader.ReadValueSafe(out bool isNull); + if (isNull) + { + value = null; + } + else + { + if (value == null) + { + value = new HashSet(); + } + else + { + value.Clear(); + } + reader.ReadValueSafe(out int len); + for (var i = 0; i < len; ++i) + { + T item = default; + NetworkVariableSerialization.Read(reader, ref item); + value.Add(item); + } + } + } + + public void WriteDelta(FastBufferWriter writer, ref HashSet value, ref HashSet previousValue) + { + CollectionSerializationUtility.WriteHashSetDelta(writer, ref value, ref previousValue); + } + public void ReadDelta(FastBufferReader reader, ref HashSet value) + { + CollectionSerializationUtility.ReadHashSetDelta(reader, ref value); + } + + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out HashSet value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in HashSet value, ref HashSet duplicatedValue) + { + if (duplicatedValue == null) + { + duplicatedValue = new HashSet(); + } + + duplicatedValue.Clear(); + foreach (var item in value) + { + duplicatedValue.Add(item); + } + } + } + + + internal class DictionarySerializer : INetworkVariableSerializer> + where TKey : IEquatable + { + public void Write(FastBufferWriter writer, ref Dictionary value) + { + bool isNull = value == null; + writer.WriteValueSafe(isNull); + if (!isNull) + { + writer.WriteValueSafe(value.Count); + foreach (var item in value) + { + (var key, var val) = (item.Key, item.Value); + NetworkVariableSerialization.Write(writer, ref key); + NetworkVariableSerialization.Write(writer, ref val); + } + } + } + public void Read(FastBufferReader reader, ref Dictionary value) + { + reader.ReadValueSafe(out bool isNull); + if (isNull) + { + value = null; + } + else + { + if (value == null) + { + value = new Dictionary(); + } + else + { + value.Clear(); + } + reader.ReadValueSafe(out int len); + for (var i = 0; i < len; ++i) + { + (TKey key, TVal val) = (default, default); + NetworkVariableSerialization.Read(reader, ref key); + NetworkVariableSerialization.Read(reader, ref val); + value.Add(key, val); + } + } + } + + public void WriteDelta(FastBufferWriter writer, ref Dictionary value, ref Dictionary previousValue) + { + CollectionSerializationUtility.WriteDictionaryDelta(writer, ref value, ref previousValue); + } + public void ReadDelta(FastBufferReader reader, ref Dictionary value) + { + CollectionSerializationUtility.ReadDictionaryDelta(reader, ref value); + } + + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out Dictionary value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in Dictionary value, ref Dictionary duplicatedValue) + { + if (duplicatedValue == null) + { + duplicatedValue = new Dictionary(); + } + + duplicatedValue.Clear(); + foreach (var item in value) + { + duplicatedValue.Add(item.Key, item.Value); + } + } + } + internal class UnmanagedArraySerializer : INetworkVariableSerializer> where T : unmanaged { public void Write(FastBufferWriter writer, ref NativeArray value) @@ -216,6 +514,15 @@ namespace Unity.Netcode reader.ReadUnmanagedSafe(out value, Allocator.Persistent); } + public void WriteDelta(FastBufferWriter writer, ref NativeArray value, ref NativeArray previousValue) + { + CollectionSerializationUtility.WriteNativeArrayDelta(writer, ref value, ref previousValue); + } + public void ReadDelta(FastBufferReader reader, ref NativeArray value) + { + CollectionSerializationUtility.ReadNativeArrayDelta(reader, ref value); + } + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeArray value, Allocator allocator) { reader.ReadUnmanagedSafe(out value, allocator); @@ -249,6 +556,15 @@ namespace Unity.Netcode reader.ReadUnmanagedSafeInPlace(ref value); } + public void WriteDelta(FastBufferWriter writer, ref NativeList value, ref NativeList previousValue) + { + CollectionSerializationUtility.WriteNativeListDelta(writer, ref value, ref previousValue); + } + public void ReadDelta(FastBufferReader reader, ref NativeList value) + { + CollectionSerializationUtility.ReadNativeListDelta(reader, ref value); + } + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeList value, Allocator allocator) { throw new NotImplementedException(); @@ -268,6 +584,90 @@ namespace Unity.Netcode duplicatedValue.CopyFrom(value); } } + + + internal class NativeHashSetSerializer : INetworkVariableSerializer> where T : unmanaged, IEquatable + { + public void Write(FastBufferWriter writer, ref NativeHashSet value) + { + writer.WriteValueSafe(value); + } + public void Read(FastBufferReader reader, ref NativeHashSet value) + { + reader.ReadValueSafeInPlace(ref value); + } + + public void WriteDelta(FastBufferWriter writer, ref NativeHashSet value, ref NativeHashSet previousValue) + { + CollectionSerializationUtility.WriteNativeHashSetDelta(writer, ref value, ref previousValue); + } + public void ReadDelta(FastBufferReader reader, ref NativeHashSet value) + { + CollectionSerializationUtility.ReadNativeHashSetDelta(reader, ref value); + } + + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeHashSet value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in NativeHashSet value, ref NativeHashSet duplicatedValue) + { + if (!duplicatedValue.IsCreated) + { + duplicatedValue = new NativeHashSet(value.Capacity, Allocator.Persistent); + } + + duplicatedValue.Clear(); + foreach (var item in value) + { + duplicatedValue.Add(item); + } + } + } + + + internal class NativeHashMapSerializer : INetworkVariableSerializer> + where TKey : unmanaged, IEquatable + where TVal : unmanaged + { + public void Write(FastBufferWriter writer, ref NativeHashMap value) + { + writer.WriteValueSafe(value); + } + public void Read(FastBufferReader reader, ref NativeHashMap value) + { + reader.ReadValueSafeInPlace(ref value); + } + + public void WriteDelta(FastBufferWriter writer, ref NativeHashMap value, ref NativeHashMap previousValue) + { + CollectionSerializationUtility.WriteNativeHashMapDelta(writer, ref value, ref previousValue); + } + public void ReadDelta(FastBufferReader reader, ref NativeHashMap value) + { + CollectionSerializationUtility.ReadNativeHashMapDelta(reader, ref value); + } + + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeHashMap value, Allocator allocator) + { + throw new NotImplementedException(); + } + + public void Duplicate(in NativeHashMap value, ref NativeHashMap duplicatedValue) + { + if (!duplicatedValue.IsCreated) + { + duplicatedValue = new NativeHashMap(value.Capacity, Allocator.Persistent); + } + + duplicatedValue.Clear(); + foreach (var item in value) + { + duplicatedValue.Add(item.Key, item.Value); + } + } + } #endif /// @@ -285,6 +685,93 @@ namespace Unity.Netcode reader.ReadValueSafeInPlace(ref value); } + // Because of how strings are generally used, it is likely that most strings will still write as full strings + // instead of deltas. This actually adds one byte to the data to encode that it was serialized in full. + // But the potential savings from a small change to a large string are valuable enough to be worth that extra + // byte. + public unsafe void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue) + { + using var changes = new ResizableBitVector(Allocator.Temp); + int minLength = math.min(value.Length, previousValue.Length); + var numChanges = 0; + for (var i = 0; i < minLength; ++i) + { + var val = value[i]; + var prevVal = previousValue[i]; + if (!NetworkVariableSerialization.AreEqual(ref val, ref prevVal)) + { + ++numChanges; + changes.Set(i); + } + } + + for (var i = previousValue.Length; i < value.Length; ++i) + { + ++numChanges; + changes.Set(i); + } + + if (changes.GetSerializedSize() + FastBufferWriter.GetWriteSize() * numChanges > FastBufferWriter.GetWriteSize() * value.Length) + { + writer.WriteByteSafe(1); + writer.WriteValueSafe(value); + return; + } + writer.WriteByte(0); + BytePacker.WriteValuePacked(writer, value.Length); + writer.WriteValueSafe(changes); + unsafe + { + byte* ptr = value.GetUnsafePtr(); + byte* prevPtr = previousValue.GetUnsafePtr(); + for (int i = 0; i < value.Length; ++i) + { + if (changes.IsSet(i)) + { + if (i < previousValue.Length) + { + NetworkVariableSerialization.WriteDelta(writer, ref ptr[i], ref prevPtr[i]); + } + else + { + NetworkVariableSerialization.Write(writer, ref ptr[i]); + } + } + } + } + } + public unsafe void ReadDelta(FastBufferReader reader, ref T value) + { + // Writing can use the NativeArray logic as it is, but reading is a little different. + // Using the NativeArray logic for reading would result in length changes allocating a new NativeArray, + // which is not what we want for FixedString. With FixedString, the actual size of the data does not change, + // only an in-memory "length" value - so if the length changes, the only thing we want to do is change + // that value, and otherwise read everything in-place. + reader.ReadByteSafe(out byte full); + if (full == 1) + { + reader.ReadValueSafeInPlace(ref value); + return; + } + ByteUnpacker.ReadValuePacked(reader, out int length); + var changes = new ResizableBitVector(Allocator.Temp); + using var toDispose = changes; + { + reader.ReadNetworkSerializableInPlace(ref changes); + + value.Length = length; + + byte* ptr = value.GetUnsafePtr(); + for (var i = 0; i < value.Length; ++i) + { + if (changes.IsSet(i)) + { + reader.ReadByte(out ptr[i]); + } + } + } + } + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator) { throw new NotImplementedException(); @@ -312,6 +799,16 @@ namespace Unity.Netcode reader.ReadValueSafe(out value, Allocator.Persistent); } + + public void WriteDelta(FastBufferWriter writer, ref NativeArray value, ref NativeArray previousValue) + { + CollectionSerializationUtility.WriteNativeArrayDelta(writer, ref value, ref previousValue); + } + public void ReadDelta(FastBufferReader reader, ref NativeArray value) + { + CollectionSerializationUtility.ReadNativeArrayDelta(reader, ref value); + } + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeArray value, Allocator allocator) { reader.ReadValueSafe(out value, allocator); @@ -349,6 +846,15 @@ namespace Unity.Netcode reader.ReadValueSafeInPlace(ref value); } + public void WriteDelta(FastBufferWriter writer, ref NativeList value, ref NativeList previousValue) + { + CollectionSerializationUtility.WriteNativeListDelta(writer, ref value, ref previousValue); + } + public void ReadDelta(FastBufferReader reader, ref NativeList value) + { + CollectionSerializationUtility.ReadNativeListDelta(reader, ref value); + } + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeList value, Allocator allocator) { throw new NotImplementedException(); @@ -387,6 +893,25 @@ namespace Unity.Netcode value.NetworkSerialize(bufferSerializer); } + public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue) + { + if (UserNetworkVariableSerialization.WriteDelta != null && UserNetworkVariableSerialization.ReadDelta != null) + { + UserNetworkVariableSerialization.WriteDelta(writer, value, previousValue); + return; + } + Write(writer, ref value); + } + public void ReadDelta(FastBufferReader reader, ref T value) + { + if (UserNetworkVariableSerialization.WriteDelta != null && UserNetworkVariableSerialization.ReadDelta != null) + { + UserNetworkVariableSerialization.ReadDelta(reader, ref value); + return; + } + Read(reader, ref value); + } + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator) { throw new NotImplementedException(); @@ -414,6 +939,16 @@ namespace Unity.Netcode reader.ReadNetworkSerializable(out value, Allocator.Persistent); } + + public void WriteDelta(FastBufferWriter writer, ref NativeArray value, ref NativeArray previousValue) + { + CollectionSerializationUtility.WriteNativeArrayDelta(writer, ref value, ref previousValue); + } + public void ReadDelta(FastBufferReader reader, ref NativeArray value) + { + CollectionSerializationUtility.ReadNativeArrayDelta(reader, ref value); + } + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeArray value, Allocator allocator) { reader.ReadNetworkSerializable(out value, allocator); @@ -451,6 +986,15 @@ namespace Unity.Netcode reader.ReadNetworkSerializableInPlace(ref value); } + public void WriteDelta(FastBufferWriter writer, ref NativeList value, ref NativeList previousValue) + { + CollectionSerializationUtility.WriteNativeListDelta(writer, ref value, ref previousValue); + } + public void ReadDelta(FastBufferReader reader, ref NativeList value) + { + CollectionSerializationUtility.ReadNativeListDelta(reader, ref value); + } + void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeList value, Allocator allocator) { throw new NotImplementedException(); @@ -507,6 +1051,25 @@ namespace Unity.Netcode } } + public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue) + { + if (UserNetworkVariableSerialization.WriteDelta != null && UserNetworkVariableSerialization.ReadDelta != null) + { + UserNetworkVariableSerialization.WriteDelta(writer, value, previousValue); + return; + } + Write(writer, ref value); + } + public void ReadDelta(FastBufferReader reader, ref T value) + { + if (UserNetworkVariableSerialization.WriteDelta != null && UserNetworkVariableSerialization.ReadDelta != null) + { + UserNetworkVariableSerialization.ReadDelta(reader, ref value); + return; + } + Read(reader, ref value); + } + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator) { throw new NotImplementedException(); @@ -539,6 +1102,13 @@ namespace Unity.Netcode /// The value of type `T` to be written public delegate void WriteValueDelegate(FastBufferWriter writer, in T value); + /// + /// The write value delegate handler definition + /// + /// The to write the value of type `T` + /// The value of type `T` to be written + public delegate void WriteDeltaDelegate(FastBufferWriter writer, in T value, in T previousValue); + /// /// The read value delegate handler definition /// @@ -546,6 +1116,13 @@ namespace Unity.Netcode /// The value of type `T` to be read public delegate void ReadValueDelegate(FastBufferReader reader, out T value); + /// + /// The read value delegate handler definition + /// + /// The to read the value of type `T` + /// The value of type `T` to be read + public delegate void ReadDeltaDelegate(FastBufferReader reader, ref T value); + /// /// The read value delegate handler definition /// @@ -563,6 +1140,17 @@ namespace Unity.Netcode /// public static ReadValueDelegate ReadValue; + /// + /// Callback to write a delta between two values, based on computing the difference between the previous and + /// current values. + /// + public static WriteDeltaDelegate WriteDelta; + + /// + /// Callback to read a delta, applying only select changes to the current value. + /// + public static ReadDeltaDelegate ReadDelta; + /// /// Callback to create a duplicate of a value, used to check for dirty status. /// @@ -602,6 +1190,36 @@ namespace Unity.Netcode UserNetworkVariableSerialization.ReadValue(reader, out value); } + public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue) + { + if (UserNetworkVariableSerialization.ReadValue == null || UserNetworkVariableSerialization.WriteValue == null || UserNetworkVariableSerialization.DuplicateValue == null) + { + ThrowArgumentError(); + } + + if (UserNetworkVariableSerialization.WriteDelta == null || UserNetworkVariableSerialization.ReadDelta == null) + { + UserNetworkVariableSerialization.WriteValue(writer, value); + return; + } + UserNetworkVariableSerialization.WriteDelta(writer, value, previousValue); + } + + public void ReadDelta(FastBufferReader reader, ref T value) + { + if (UserNetworkVariableSerialization.ReadValue == null || UserNetworkVariableSerialization.WriteValue == null || UserNetworkVariableSerialization.DuplicateValue == null) + { + ThrowArgumentError(); + } + + if (UserNetworkVariableSerialization.WriteDelta == null || UserNetworkVariableSerialization.ReadDelta == null) + { + UserNetworkVariableSerialization.ReadValue(reader, out value); + return; + } + UserNetworkVariableSerialization.ReadDelta(reader, ref value); + } + void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator) { throw new NotImplementedException(); @@ -649,6 +1267,14 @@ namespace Unity.Netcode NetworkVariableSerialization.AreEqual = NetworkVariableSerialization.ValueEquals; NetworkVariableSerialization.Serializer = new UlongSerializer(); NetworkVariableSerialization.AreEqual = NetworkVariableSerialization.ValueEquals; + + // DANGO-EXP TODO: Determine if this is distributed authority only and impacts of this in client-server + NetworkVariableSerialization.Type = CollectionItemType.Short; + NetworkVariableSerialization.Type = CollectionItemType.UShort; + NetworkVariableSerialization.Type = CollectionItemType.Int; + NetworkVariableSerialization.Type = CollectionItemType.UInt; + NetworkVariableSerialization.Type = CollectionItemType.Long; + NetworkVariableSerialization.Type = CollectionItemType.ULong; } /// @@ -658,6 +1284,8 @@ namespace Unity.Netcode public static void InitializeSerializer_UnmanagedByMemcpy() where T : unmanaged { NetworkVariableSerialization.Serializer = new UnmanagedTypeSerializer(); + // DANGO-EXP TODO: Determine if this is distributed authority only and impacts of this in client-server + NetworkVariableSerialization.Type = CollectionItemType.Unmanaged; } /// @@ -678,8 +1306,55 @@ namespace Unity.Netcode { NetworkVariableSerialization>.Serializer = new UnmanagedListSerializer(); } + + /// + /// Registeres a native hash set (this generic implementation works with all types) + /// + /// + public static void InitializeSerializer_NativeHashSet() where T : unmanaged, IEquatable + { + NetworkVariableSerialization>.Serializer = new NativeHashSetSerializer(); + } + + /// + /// Registeres a native hash set (this generic implementation works with all types) + /// + /// + public static void InitializeSerializer_NativeHashMap() + where TKey : unmanaged, IEquatable + where TVal : unmanaged + { + NetworkVariableSerialization>.Serializer = new NativeHashMapSerializer(); + } #endif + /// + /// Registeres a native hash set (this generic implementation works with all types) + /// + /// + public static void InitializeSerializer_List() + { + NetworkVariableSerialization>.Serializer = new ListSerializer(); + } + + /// + /// Registeres a native hash set (this generic implementation works with all types) + /// + /// + public static void InitializeSerializer_HashSet() where T : IEquatable + { + NetworkVariableSerialization>.Serializer = new HashSetSerializer(); + } + + /// + /// Registeres a native hash set (this generic implementation works with all types) + /// + /// + public static void InitializeSerializer_Dictionary() where TKey : IEquatable + { + NetworkVariableSerialization>.Serializer = new DictionarySerializer(); + } + /// /// Registers an unmanaged type that implements INetworkSerializable and will be serialized through a call to /// NetworkSerialize @@ -780,6 +1455,31 @@ namespace Unity.Netcode { NetworkVariableSerialization>.AreEqual = NetworkVariableSerialization.EqualityEqualsArray; } + /// + /// Registers an unmanaged type that will be checked for equality using T.Equals() + /// + /// + public static void InitializeEqualityChecker_List() + { + NetworkVariableSerialization>.AreEqual = NetworkVariableSerialization.EqualityEqualsList; + } + /// + /// Registers an unmanaged type that will be checked for equality using T.Equals() + /// + /// + public static void InitializeEqualityChecker_HashSet() where T : IEquatable + { + NetworkVariableSerialization>.AreEqual = NetworkVariableSerialization.EqualityEqualsHashSet; + } + /// + /// Registers an unmanaged type that will be checked for equality using T.Equals() + /// + /// + public static void InitializeEqualityChecker_Dictionary() + where TKey : IEquatable + { + NetworkVariableSerialization>.AreEqual = NetworkVariableDictionarySerialization.GenericEqualsDictionary; + } #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT /// @@ -788,7 +1488,25 @@ namespace Unity.Netcode /// public static void InitializeEqualityChecker_UnmanagedIEquatableList() where T : unmanaged, IEquatable { - NetworkVariableSerialization>.AreEqual = NetworkVariableSerialization.EqualityEqualsList; + NetworkVariableSerialization>.AreEqual = NetworkVariableSerialization.EqualityEqualsNativeList; + } + /// + /// Registers an unmanaged type that will be checked for equality using T.Equals() + /// + /// + public static void InitializeEqualityChecker_NativeHashSet() where T : unmanaged, IEquatable + { + NetworkVariableSerialization>.AreEqual = NetworkVariableSerialization.EqualityEqualsNativeHashSet; + } + /// + /// Registers an unmanaged type that will be checked for equality using T.Equals() + /// + /// + public static void InitializeEqualityChecker_NativeHashMap() + where TKey : unmanaged, IEquatable + where TVal : unmanaged + { + NetworkVariableSerialization>.AreEqual = NetworkVariableMapSerialization.GenericEqualsNativeHashMap; } #endif @@ -846,6 +1564,12 @@ namespace Unity.Netcode { internal static INetworkVariableSerializer Serializer = new FallbackSerializer(); + /// + /// The collection item type tells the CMB server how to read the bytes of each item in the collection + /// + /// DANGO-EXP TODO: Determine if this is distributed authority only and impacts of this in client-server + internal static CollectionItemType Type = CollectionItemType.Unknown; + /// /// A callback to check if two values are equal. /// @@ -912,6 +1636,53 @@ namespace Unity.Netcode Serializer.Read(reader, ref value); } + /// + /// Serialize a value using the best-known serialization method for a generic value. + /// Will reliably serialize any value that is passed to it correctly with no boxing. + ///
+ ///
+ /// Note: If you are using this in a custom generic class, please make sure your class is + /// decorated with so that codegen can + /// initialize the serialization mechanisms correctly. If your class is NOT + /// generic, it is better to use FastBufferWriter directly. + ///
+ ///
+ /// If the codegen is unable to determine a serializer for a type, + /// . is called, which, by default, + /// will throw an exception, unless you have assigned a user serialization callback to it at runtime. + ///
+ /// + /// + public static void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue) + { + Serializer.WriteDelta(writer, ref value, ref previousValue); + } + + /// + /// Deserialize a value using the best-known serialization method for a generic value. + /// Will reliably deserialize any value that is passed to it correctly with no boxing. + /// For types whose deserialization can be determined by codegen (which is most types), + /// GC will only be incurred if the type is a managed type and the ref value passed in is `null`, + /// in which case a new value is created; otherwise, it will be deserialized in-place. + ///
+ ///
+ /// Note: If you are using this in a custom generic class, please make sure your class is + /// decorated with so that codegen can + /// initialize the serialization mechanisms correctly. If your class is NOT + /// generic, it is better to use FastBufferReader directly. + ///
+ ///
+ /// If the codegen is unable to determine a serializer for a type, + /// . is called, which, by default, + /// will throw an exception, unless you have assigned a user deserialization callback to it at runtime. + ///
+ /// + /// + public static void ReadDelta(FastBufferReader reader, ref T value) + { + Serializer.ReadDelta(reader, ref value); + } + /// /// Duplicates a value using the most efficient means of creating a complete copy. /// For most types this is a simple assignment or memcpy. @@ -970,8 +1741,14 @@ namespace Unity.Netcode return false; } +#if UTP_TRANSPORT_2_0_ABOVE + var aptr = a.GetUnsafePtr(); + var bptr = b.GetUnsafePtr(); +#else var aptr = (TValueType*)a.GetUnsafePtr(); var bptr = (TValueType*)b.GetUnsafePtr(); +#endif + return UnsafeUtility.MemCmp(aptr, bptr, sizeof(TValueType) * a.Length) == 0; } #endif @@ -1021,11 +1798,69 @@ namespace Unity.Netcode return a.Equals(b); } + internal static bool EqualityEqualsList(ref List a, ref List b) + { + if ((a == null) != (b == null)) + { + return false; + } + + if (a == null) + { + return true; + } + + if (a.Count != b.Count) + { + return false; + } + + for (var i = 0; i < a.Count; ++i) + { + var aItem = a[i]; + var bItem = b[i]; + if (!NetworkVariableSerialization.AreEqual(ref aItem, ref bItem)) + { + return false; + } + } + + return true; + } + + internal static bool EqualityEqualsHashSet(ref HashSet a, ref HashSet b) where TValueType : IEquatable + { + if ((a == null) != (b == null)) + { + return false; + } + + if (a == null) + { + return true; + } + + if (a.Count != b.Count) + { + return false; + } + + foreach (var item in a) + { + if (!b.Contains(item)) + { + return false; + } + } + + return true; + } + #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT // Compares two values of the same unmanaged type by underlying memory // Ignoring any overridden value checks // Size is fixed - internal static unsafe bool EqualityEqualsList(ref NativeList a, ref NativeList b) where TValueType : unmanaged, IEquatable + internal static unsafe bool EqualityEqualsNativeList(ref NativeList a, ref NativeList b) where TValueType : unmanaged, IEquatable { if (a.IsCreated != b.IsCreated) { @@ -1042,8 +1877,13 @@ namespace Unity.Netcode return false; } +#if UTP_TRANSPORT_2_0_ABOVE + var aptr = a.GetUnsafePtr(); + var bptr = b.GetUnsafePtr(); +#else var aptr = (TValueType*)a.GetUnsafePtr(); var bptr = (TValueType*)b.GetUnsafePtr(); +#endif for (var i = 0; i < a.Length; ++i) { if (!EqualityEquals(ref aptr[i], ref bptr[i])) @@ -1054,6 +1894,38 @@ namespace Unity.Netcode return true; } + + internal static bool EqualityEqualsNativeHashSet(ref NativeHashSet a, ref NativeHashSet b) where TValueType : unmanaged, IEquatable + { + if (a.IsCreated != b.IsCreated) + { + return false; + } + + if (!a.IsCreated) + { + return true; + } + +#if UTP_TRANSPORT_2_0_ABOVE + if (a.Count != b.Count) +#else + if (a.Count() != b.Count()) +#endif + { + return false; + } + + foreach (var item in a) + { + if (!b.Contains(item)) + { + return false; + } + } + + return true; + } #endif // Compares two values of the same unmanaged type by underlying memory @@ -1094,6 +1966,86 @@ namespace Unity.Netcode return a == b; } } + internal class NetworkVariableDictionarySerialization + where TKey : IEquatable + { + + internal static bool GenericEqualsDictionary(ref Dictionary a, ref Dictionary b) + { + if ((a == null) != (b == null)) + { + return false; + } + + if (a == null) + { + return true; + } + + if (a.Count != b.Count) + { + return false; + } + + foreach (var item in a) + { + var hasKey = b.TryGetValue(item.Key, out var val); + if (!hasKey) + { + return false; + } + + var bVal = item.Value; + if (!NetworkVariableSerialization.AreEqual(ref bVal, ref val)) + { + return false; + } + } + + return true; + } + } + +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + internal class NetworkVariableMapSerialization + where TKey : unmanaged, IEquatable + where TVal : unmanaged + { + + internal static bool GenericEqualsNativeHashMap(ref NativeHashMap a, ref NativeHashMap b) + { + if (a.IsCreated != b.IsCreated) + { + return false; + } + + if (!a.IsCreated) + { + return true; + } + +#if UTP_TRANSPORT_2_0_ABOVE + if (a.Count != b.Count) +#else + if (a.Count() != b.Count()) +#endif + { + return false; + } + + foreach (var item in a) + { + var hasKey = b.TryGetValue(item.Key, out var val); + if (!hasKey || !NetworkVariableSerialization.AreEqual(ref item.Value, ref val)) + { + return false; + } + } + + return true; + } + } +#endif // RuntimeAccessModifiersILPP will make this `public` // This is just pass-through to NetworkVariableSerialization but is here becaues I could not get ILPP diff --git a/Runtime/NetworkVariable/ResizableBitVector.cs b/Runtime/NetworkVariable/ResizableBitVector.cs new file mode 100644 index 0000000..b4b4b76 --- /dev/null +++ b/Runtime/NetworkVariable/ResizableBitVector.cs @@ -0,0 +1,115 @@ +using System; +using Unity.Collections; +using Unity.Collections.LowLevel.Unsafe; + +namespace Unity.Netcode +{ + /// + /// This is a simple resizable bit vector - i.e., a list of flags that use 1 bit each and can + /// grow to an indefinite size. This is backed by a NativeList<byte> instead of a single + /// integer value, allowing it to contain any size of memory. Contains built-in serialization support. + /// + internal struct ResizableBitVector : INetworkSerializable, IDisposable + { + private NativeList m_Bits; + private const int k_Divisor = sizeof(byte) * 8; + + public ResizableBitVector(Allocator allocator) + { + m_Bits = new NativeList(allocator); + } + + public void Dispose() + { + m_Bits.Dispose(); + } + + public int GetSerializedSize() + { + return sizeof(int) + m_Bits.Length; + } + + private (int, int) GetBitData(int i) + { + var index = i / k_Divisor; + var bitWithinIndex = i % k_Divisor; + return (index, bitWithinIndex); + } + + /// + /// Set bit 'i' - i.e., bit 0 is 00000001, bit 1 is 00000010, and so on. + /// There is no upper bound on i except for the memory available in the system. + /// + /// + public void Set(int i) + { + var (index, bitWithinIndex) = GetBitData(i); + if (index >= m_Bits.Length) + { + m_Bits.Resize(index + 1, NativeArrayOptions.ClearMemory); + } + + m_Bits[index] |= (byte)(1 << bitWithinIndex); + } + + /// + /// Unset bit 'i' - i.e., bit 0 is 00000001, bit 1 is 00000010, and so on. + /// There is no upper bound on i except for the memory available in the system. + /// Note that once a BitVector has grown to a certain size, it will not shrink back down, + /// so if you set and unset every bit, it will still serialize at its high watermark size. + /// + /// + public void Unset(int i) + { + var (index, bitWithinIndex) = GetBitData(i); + if (index >= m_Bits.Length) + { + return; + } + + m_Bits[index] &= (byte)~(1 << bitWithinIndex); + } + + /// + /// Check if bit 'i' is set - i.e., bit 0 is 00000001, bit 1 is 00000010, and so on. + /// There is no upper bound on i except for the memory available in the system. + /// + /// + public bool IsSet(int i) + { + var (index, bitWithinIndex) = GetBitData(i); + if (index >= m_Bits.Length) + { + return false; + } + + return (m_Bits[index] & (byte)(1 << bitWithinIndex)) != 0; + } + + public unsafe void NetworkSerialize(BufferSerializer serializer) where T : IReaderWriter + { + var length = m_Bits.Length; + serializer.SerializeValue(ref length); + m_Bits.ResizeUninitialized(length); + var ptr = m_Bits.GetUnsafePtr(); + { + if (serializer.IsReader) + { +#if UTP_TRANSPORT_2_0_ABOVE + serializer.GetFastBufferReader().ReadBytesSafe(ptr, length); +#else + serializer.GetFastBufferReader().ReadBytesSafe((byte*)ptr, length); +#endif + } + else + { +#if UTP_TRANSPORT_2_0_ABOVE + serializer.GetFastBufferWriter().WriteBytesSafe(ptr, length); +#else + serializer.GetFastBufferWriter().WriteBytesSafe((byte*)ptr, length); +#endif + } + } + } + } +} diff --git a/Runtime/NetworkVariable/ResizableBitVector.cs.meta b/Runtime/NetworkVariable/ResizableBitVector.cs.meta new file mode 100644 index 0000000..5b3238a --- /dev/null +++ b/Runtime/NetworkVariable/ResizableBitVector.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 664696a622e244dfa43b26628c05e4a6 +timeCreated: 1705437231 \ No newline at end of file diff --git a/Runtime/SceneManagement/DefaultSceneManagerHandler.cs b/Runtime/SceneManagement/DefaultSceneManagerHandler.cs index 4879b6c..9de36e9 100644 --- a/Runtime/SceneManagement/DefaultSceneManagerHandler.cs +++ b/Runtime/SceneManagement/DefaultSceneManagerHandler.cs @@ -18,6 +18,7 @@ namespace Unity.Netcode public bool IsAssigned; public Scene Scene; } + public bool IsIntegrationTest() { return false; } internal Dictionary> SceneNameToSceneHandles = new Dictionary>(); @@ -327,8 +328,8 @@ namespace Unity.Netcode public void SetClientSynchronizationMode(ref NetworkManager networkManager, LoadSceneMode mode) { var sceneManager = networkManager.SceneManager; - // Don't let client's set this value - if (!networkManager.IsServer) + // Don't let non-authority set this value + if ((!networkManager.DistributedAuthorityMode && !networkManager.IsServer) || (networkManager.DistributedAuthorityMode && !networkManager.LocalClient.IsSessionOwner)) { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { diff --git a/Runtime/SceneManagement/ISceneManagerHandler.cs b/Runtime/SceneManagement/ISceneManagerHandler.cs index 240a5c9..9cd3ed1 100644 --- a/Runtime/SceneManagement/ISceneManagerHandler.cs +++ b/Runtime/SceneManagement/ISceneManagerHandler.cs @@ -32,5 +32,7 @@ namespace Unity.Netcode void SetClientSynchronizationMode(ref NetworkManager networkManager, LoadSceneMode mode); bool ClientShouldPassThrough(string sceneName, bool isPrimaryScene, LoadSceneMode clientSynchronizationMode, NetworkManager networkManager); + + bool IsIntegrationTest(); } } diff --git a/Runtime/SceneManagement/NetworkSceneManager.cs b/Runtime/SceneManagement/NetworkSceneManager.cs index ba1b0ee..1e6dacf 100644 --- a/Runtime/SceneManagement/NetworkSceneManager.cs +++ b/Runtime/SceneManagement/NetworkSceneManager.cs @@ -423,6 +423,20 @@ namespace Unity.Netcode /// internal Dictionary ScenesLoaded = new Dictionary(); + /// + /// Returns the currently loaded scenes that are synchronized with the session owner or server depending upon the selected + /// NetworkManager session mode. + /// + /// + /// The scenes loaded returns all scenes loaded where this returns only the scenes that have been + /// synchronized remotely. This can be useful when using scene validation and excluding certain scenes from being synchronized. + /// + /// List of the known synchronized scenes + public List GetSynchronizedScenes() + { + return ScenesLoaded.Values.ToList(); + } + /// /// Since Scene.handle is unique per client, we create a look-up table between the client and server to associate server unique scene /// instances with client unique scene instances @@ -550,6 +564,15 @@ namespace Unity.Netcode /// private bool m_DisableValidationWarningMessages; + internal bool HasSceneAuthority() + { + if (!NetworkManager) + { + return false; + } + return (!NetworkManager.DistributedAuthorityMode && NetworkManager.IsServer) || (NetworkManager.DistributedAuthorityMode && NetworkManager.LocalClient.IsSessionOwner); + } + /// /// Handle NetworkSeneManager clean up /// @@ -614,7 +637,7 @@ namespace Unity.Netcode internal bool ShouldDeferCreateObject() { // This applies only to remote clients and when scene management is enabled - if (!NetworkManager.NetworkConfig.EnableSceneManagement || NetworkManager.IsServer) + if (!NetworkManager.NetworkConfig.EnableSceneManagement || HasSceneAuthority()) { return false; } @@ -782,10 +805,11 @@ namespace Unity.Netcode // Since NetworkManager is now always migrated to the DDOL we will use this to get the DDOL scene DontDestroyOnLoadScene = networkManager.gameObject.scene; - // Since the server tracks loaded scenes, we need to add any currently loaded scenes on the + // Since the server tracks loaded scenes, we need to add any currently loaded scenes on the // server side when the NetworkManager is started and NetworkSceneManager instantiated when // scene management is enabled. - if (networkManager.IsServer && networkManager.NetworkConfig.EnableSceneManagement) + + if (!NetworkManager.DistributedAuthorityMode && NetworkManager.IsServer && networkManager.NetworkConfig.EnableSceneManagement) { for (int i = 0; i < SceneManager.sceneCount; i++) { @@ -799,11 +823,34 @@ namespace Unity.Netcode UpdateServerClientSceneHandle(DontDestroyOnLoadScene.handle, DontDestroyOnLoadScene.handle, DontDestroyOnLoadScene); } + internal void InitializeScenesLoaded() + { + if (!NetworkManager.DistributedAuthorityMode) + { + return; + } + + if (HasSceneAuthority() && NetworkManager.NetworkConfig.EnableSceneManagement) + { + for (int i = 0; i < SceneManager.sceneCount; i++) + { + var loadedScene = SceneManager.GetSceneAt(i); + UpdateServerClientSceneHandle(loadedScene.handle, loadedScene.handle, loadedScene); + } + SceneManagerHandler.PopulateLoadedScenes(ref ScenesLoaded, NetworkManager); + } + } + /// /// Synchronizes clients when the currently active scene is changed /// private void SceneManager_ActiveSceneChanged(Scene current, Scene next) { + if ((!NetworkManager.DistributedAuthorityMode && !NetworkManager.IsServer) || (NetworkManager.DistributedAuthorityMode && !NetworkManager.LocalClient.IsSessionOwner)) + { + return; + } + // If no clients are connected, then don't worry about notifications if (!(NetworkManager.ConnectedClientsIds.Count > (NetworkManager.IsHost ? 1 : 0))) { @@ -826,7 +873,12 @@ namespace Unity.Netcode var sceneEvent = BeginSceneEvent(); sceneEvent.SceneEventType = SceneEventType.ActiveSceneChanged; sceneEvent.ActiveSceneHash = BuildIndexToHash[next.buildIndex]; - SendSceneEventData(sceneEvent.SceneEventId, NetworkManager.ConnectedClientsIds.Where(c => c != NetworkManager.ServerClientId).ToArray()); + var sessionOwner = NetworkManager.ServerClientId; + if (NetworkManager.DistributedAuthorityMode) + { + sessionOwner = NetworkManager.CurrentSessionOwner; + } + SendSceneEventData(sceneEvent.SceneEventId, NetworkManager.ConnectedClientsIds.Where(c => c != sessionOwner).ToArray()); EndSceneEvent(sceneEvent.SceneEventId); } } @@ -860,11 +912,10 @@ namespace Unity.Netcode if (!validated && !m_DisableValidationWarningMessages) { var serverHostorClient = "Client"; - if (NetworkManager.IsServer) + if (HasSceneAuthority()) { - serverHostorClient = NetworkManager.IsHost ? "Host" : "Server"; + serverHostorClient = NetworkManager.DistributedAuthorityMode ? "Session Owner" : NetworkManager.IsHost ? "Host" : "Server"; } - Debug.LogWarning($"Scene {sceneName} of Scenes in Build Index {sceneIndex} being loaded in {loadSceneMode} mode failed validation on the {serverHostorClient}!"); } return validated; @@ -961,7 +1012,7 @@ namespace Unity.Netcode // This could be the scenario where NetworkManager.DontDestroy is false and we are creating the first NetworkObject (client side) to be in the DontDestroyOnLoad scene // Otherwise, this is some other specific scenario that we might not be handling currently. - Debug.LogWarning($"[{nameof(SceneEventData)}- Scene Handle Mismatch] {nameof(serverSceneHandle)} could not be found in {nameof(ServerSceneHandleToClientSceneHandle)}. Using the currently active scene."); + Debug.LogWarning($"[{nameof(SceneEventData)}- Scene Handle Mismatch] {nameof(serverSceneHandle)} ({serverSceneHandle}) could not be found in {nameof(ServerSceneHandleToClientSceneHandle)}. Using the currently active scene."); } } } @@ -976,7 +1027,7 @@ namespace Unity.Netcode if (ScenePlacedObjects.ContainsKey(globalObjectIdHash)) { var sceneHandle = SceneBeingSynchronized.handle; - if (networkSceneHandle.HasValue && networkSceneHandle.Value != 0) + if (networkSceneHandle.HasValue && networkSceneHandle.Value != 0 && ServerSceneHandleToClientSceneHandle.ContainsKey(networkSceneHandle.Value)) { sceneHandle = ServerSceneHandleToClientSceneHandle[networkSceneHandle.Value]; } @@ -1000,13 +1051,32 @@ namespace Unity.Netcode // Silently return as there is nothing to be done return; } - var message = new SceneEventMessage - { - EventData = SceneEventDataStore[sceneEventId] - }; - var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, targetClientIds); + var sceneEvent = SceneEventDataStore[sceneEventId]; + sceneEvent.SenderClientId = NetworkManager.LocalClientId; + + if (NetworkManager.DistributedAuthorityMode && !NetworkManager.DAHost) + { + foreach (var clientId in targetClientIds) + { + sceneEvent.TargetClientId = clientId; + var message = new SceneEventMessage + { + EventData = sceneEvent, + }; + var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, NetworkManager.ServerClientId); + NetworkManager.NetworkMetrics.TrackSceneEventSent(clientId, (uint)sceneEvent.SceneEventType, SceneNameFromHash(sceneEvent.SceneHash), size); + } + } + else + { + var message = new SceneEventMessage + { + EventData = sceneEvent, + }; + var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, targetClientIds); + NetworkManager.NetworkMetrics.TrackSceneEventSent(targetClientIds, (uint)SceneEventDataStore[sceneEventId].SceneEventType, SceneNameFromHash(SceneEventDataStore[sceneEventId].SceneHash), size); + } - NetworkManager.NetworkMetrics.TrackSceneEventSent(targetClientIds, (uint)SceneEventDataStore[sceneEventId].SceneEventType, SceneNameFromHash(SceneEventDataStore[sceneEventId].SceneHash), size); } /// @@ -1022,10 +1092,18 @@ namespace Unity.Netcode return new SceneEventProgress(null, SceneEventProgressStatus.SceneManagementNotEnabled); } - if (!NetworkManager.IsServer) + if (!HasSceneAuthority()) { - Debug.LogWarning($"[{nameof(SceneEventProgressStatus.ServerOnlyAction)}][Unload] Clients cannot invoke the {nameof(UnloadScene)} method!"); - return new SceneEventProgress(null, SceneEventProgressStatus.ServerOnlyAction); + if (NetworkManager.DistributedAuthorityMode) + { + Debug.LogWarning($"[{nameof(SceneEventProgressStatus.SessionOwnerOnlyAction)}][Unload] Clients cannot invoke the {nameof(UnloadScene)} method!"); + return new SceneEventProgress(null, SceneEventProgressStatus.SessionOwnerOnlyAction); + } + else + { + Debug.LogWarning($"[{nameof(SceneEventProgressStatus.ServerOnlyAction)}][Unload] Clients cannot invoke the {nameof(UnloadScene)} method!"); + return new SceneEventProgress(null, SceneEventProgressStatus.ServerOnlyAction); + } } if (!scene.isLoaded) @@ -1050,12 +1128,19 @@ namespace Unity.Netcode return new SceneEventProgress(null, SceneEventProgressStatus.SceneManagementNotEnabled); } - if (!NetworkManager.IsServer) + if (!HasSceneAuthority()) { - Debug.LogWarning($"[{nameof(SceneEventProgressStatus.ServerOnlyAction)}][Load] Clients cannot invoke the {nameof(LoadScene)} method!"); - return new SceneEventProgress(null, SceneEventProgressStatus.ServerOnlyAction); + if (NetworkManager.DistributedAuthorityMode) + { + Debug.LogWarning($"[{nameof(SceneEventProgressStatus.SessionOwnerOnlyAction)}][Load] Only the session owner can invoke the {nameof(LoadScene)} method!"); + return new SceneEventProgress(null, SceneEventProgressStatus.SessionOwnerOnlyAction); + } + else + { + Debug.LogWarning($"[{nameof(SceneEventProgressStatus.ServerOnlyAction)}][Load] Clients cannot invoke the {nameof(LoadScene)} method!"); + return new SceneEventProgress(null, SceneEventProgressStatus.ServerOnlyAction); + } } - return ValidateSceneEvent(sceneName); } @@ -1111,24 +1196,31 @@ namespace Unity.Netcode sceneEventData.LoadSceneMode = sceneEventProgress.LoadSceneMode; sceneEventData.ClientsTimedOut = clientsThatTimedOut; - var message = new SceneEventMessage + if (NetworkManager.DistributedAuthorityMode) { - EventData = sceneEventData - }; - var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, NetworkManager.ConnectedClientsIds); + SendSceneEventData(sceneEventData.SceneEventId, NetworkManager.ConnectedClientsIds.Where(c => c != NetworkManager.LocalClientId).ToArray()); + } + else + { + var message = new SceneEventMessage + { + EventData = sceneEventData + }; - NetworkManager.NetworkMetrics.TrackSceneEventSent( - NetworkManager.ConnectedClientsIds, - (uint)sceneEventProgress.SceneEventType, - SceneNameFromHash(sceneEventProgress.SceneHash), - size); + var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, NetworkManager.ConnectedClientsIds); + NetworkManager.NetworkMetrics.TrackSceneEventSent( + NetworkManager.ConnectedClientsIds, + (uint)sceneEventProgress.SceneEventType, + SceneNameFromHash(sceneEventProgress.SceneHash), + size); + } - // Send a local notification to the server that all clients are done loading or unloading + // Send a local notification to the session owner that all clients are done loading or unloading OnSceneEvent?.Invoke(new SceneEvent() { SceneEventType = sceneEventProgress.SceneEventType, SceneName = SceneNameFromHash(sceneEventProgress.SceneHash), - ClientId = NetworkManager.ServerClientId, + ClientId = NetworkManager.CurrentSessionOwner, LoadSceneMode = sceneEventProgress.LoadSceneMode, ClientsThatCompleted = clientsThatCompleted, ClientsThatTimedOut = clientsThatTimedOut, @@ -1159,6 +1251,7 @@ namespace Unity.Netcode var sceneName = scene.name; var sceneHandle = scene.handle; + if (!scene.isLoaded) { Debug.LogWarning($"{nameof(UnloadScene)} was called, but the scene {scene.name} is not currently loaded!"); @@ -1177,6 +1270,14 @@ namespace Unity.Netcode return SceneEventProgressStatus.InternalNetcodeError; } + if (NetworkManager.DistributedAuthorityMode) + { + if (ClientSceneHandleToServerSceneHandle.ContainsKey(sceneHandle)) + { + sceneHandle = ClientSceneHandleToServerSceneHandle[sceneHandle]; + } + } + // Any NetworkObjects marked to not be destroyed with a scene and reside within the scene about to be unloaded // should be migrated temporarily into the DDOL, once the scene is unloaded they will be migrated into the // currently active scene. @@ -1193,10 +1294,16 @@ namespace Unity.Netcode // This will be the message we send to everyone when this scene event sceneEventProgress is complete sceneEventProgress.SceneEventType = SceneEventType.UnloadEventCompleted; - ScenesLoaded.Remove(scene.handle); sceneEventProgress.SceneEventId = sceneEventData.SceneEventId; sceneEventProgress.OnSceneEventCompleted = OnSceneUnloaded; + + if (!RemoveServerClientSceneHandle(sceneEventData.SceneHandle, scene.handle)) + { + Debug.LogError($"Failed to remove {SceneNameFromHash(sceneEventData.SceneHash)} scene handles [Server ({sceneEventData.SceneHandle})][Local({scene.handle})]"); + } + var sceneUnload = SceneManagerHandler.UnloadSceneAsync(scene, sceneEventProgress); + // Notify local server that a scene is going to be unloaded OnSceneEvent?.Invoke(new SceneEvent() { @@ -1204,10 +1311,10 @@ namespace Unity.Netcode SceneEventType = sceneEventData.SceneEventType, LoadSceneMode = sceneEventData.LoadSceneMode, SceneName = sceneName, - ClientId = NetworkManager.ServerClientId // Server can only invoke this + ClientId = NetworkManager.LocalClientId // Session owner can only invoke this }); - OnUnload?.Invoke(NetworkManager.ServerClientId, sceneName, sceneUnload); + OnUnload?.Invoke(NetworkManager.LocalClientId, sceneName, sceneUnload); //Return the status return sceneEventProgress.Status; @@ -1245,13 +1352,18 @@ namespace Unity.Netcode // currently active scene. var networkManager = NetworkManager; SceneManagerHandler.MoveObjectsFromSceneToDontDestroyOnLoad(ref networkManager, scene); - m_IsSceneEventActive = true; var sceneEventProgress = new SceneEventProgress(NetworkManager) { SceneEventId = sceneEventData.SceneEventId, - OnSceneEventCompleted = OnSceneUnloaded + OnSceneEventCompleted = OnSceneUnloaded, }; + + if (NetworkManager.DistributedAuthorityMode) + { + SceneEventProgressTracking.Add(sceneEventData.SceneEventProgressId, sceneEventProgress); + } + var sceneUnload = SceneManagerHandler.UnloadSceneAsync(scene, sceneEventProgress); SceneManagerHandler.StopTrackingScene(sceneHandle, sceneName, NetworkManager); @@ -1285,27 +1397,34 @@ namespace Unity.Netcode // If we are shutdown or about to shutdown, then ignore this event if (!NetworkManager.IsListening || NetworkManager.ShutdownInProgress) { + EndSceneEvent(sceneEventId); return; } // Migrate the NetworkObjects marked to not be destroyed with the scene into the currently active scene MoveObjectsFromDontDestroyOnLoadToScene(SceneManager.GetActiveScene()); - var sceneEventData = SceneEventDataStore[sceneEventId]; - // First thing we do, if we are a server, is to send the unload scene event. - if (NetworkManager.IsServer) + + if (HasSceneAuthority()) { + var sessionOwner = NetworkManager.DistributedAuthorityMode ? NetworkManager.CurrentSessionOwner : NetworkManager.ServerClientId; + // Server sends the unload scene notification after unloading because it will despawn all scene relative in-scene NetworkObjects // If we send this event to all clients before the server is finished unloading they will get warning about an object being // despawned that no longer exists - SendSceneEventData(sceneEventId, NetworkManager.ConnectedClientsIds.Where(c => c != NetworkManager.ServerClientId).ToArray()); + SendSceneEventData(sceneEventId, NetworkManager.ConnectedClientsIds.Where(c => c != sessionOwner).ToArray()); - //Only if we are a host do we want register having loaded for the associated SceneEventProgress - if (SceneEventProgressTracking.ContainsKey(sceneEventData.SceneEventProgressId) && NetworkManager.IsHost) + //Only if we are session owner do we want register having loaded for the associated SceneEventProgress + if (SceneEventProgressTracking.ContainsKey(sceneEventData.SceneEventProgressId) && HasSceneAuthority()) { - SceneEventProgressTracking[sceneEventData.SceneEventProgressId].ClientFinishedSceneEvent(NetworkManager.ServerClientId); + SceneEventProgressTracking[sceneEventData.SceneEventProgressId].ClientFinishedSceneEvent(sessionOwner); } } + else if (NetworkManager.DistributedAuthorityMode) + { + SceneEventProgressTracking.Remove(sceneEventData.SceneEventProgressId); + m_IsSceneEventActive = false; + } // Next we prepare to send local notifications for unload complete sceneEventData.SceneEventType = SceneEventType.UnloadComplete; @@ -1316,17 +1435,25 @@ namespace Unity.Netcode SceneEventType = sceneEventData.SceneEventType, LoadSceneMode = sceneEventData.LoadSceneMode, SceneName = SceneNameFromHash(sceneEventData.SceneHash), - ClientId = NetworkManager.IsServer ? NetworkManager.ServerClientId : NetworkManager.LocalClientId + ClientId = NetworkManager.LocalClientId, }); OnUnloadComplete?.Invoke(NetworkManager.LocalClientId, SceneNameFromHash(sceneEventData.SceneHash)); - // Clients send a notification back to the server they have completed the unload scene event - if (!NetworkManager.IsServer) + if (!HasSceneAuthority()) { - SendSceneEventData(sceneEventId, new ulong[] { NetworkManager.ServerClientId }); + sceneEventData.TargetClientId = NetworkManager.CurrentSessionOwner; + sceneEventData.SenderClientId = NetworkManager.LocalClientId; + var message = new SceneEventMessage + { + EventData = sceneEventData, + }; + // This might seem like it needs more logic to determine the target, but the only scenario where we send to the session owner is if the + // current instance is the DAHost. + var target = NetworkManager.DAHost ? NetworkManager.CurrentSessionOwner : NetworkManager.ServerClientId; + var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, target); + NetworkManager.NetworkMetrics.TrackSceneEventSent(target, (uint)sceneEventData.SceneEventType, SceneNameFromHash(sceneEventData.SceneHash), size); } - EndSceneEvent(sceneEventId); // This scene event is now considered "complete" m_IsSceneEventActive = false; @@ -1357,7 +1484,16 @@ namespace Unity.Netcode SceneEventId = sceneEventId, OnSceneEventCompleted = EmptySceneUnloadedOperation }; + + if (ClientSceneHandleToServerSceneHandle.ContainsKey(keyHandleEntry.Value.handle)) + { + var serverSceneHandle = ClientSceneHandleToServerSceneHandle[keyHandleEntry.Value.handle]; + ServerSceneHandleToClientSceneHandle.Remove(serverSceneHandle); + } + ClientSceneHandleToServerSceneHandle.Remove(keyHandleEntry.Value.handle); + var sceneUnload = SceneManagerHandler.UnloadSceneAsync(keyHandleEntry.Value, sceneEventProgress); + SceneUnloadEventHandler.RegisterScene(this, keyHandleEntry.Value, LoadSceneMode.Additive, sceneUnload); } } @@ -1428,6 +1564,7 @@ namespace Unity.Netcode sceneEventProgress.SceneEventId = sceneEventId; sceneEventProgress.OnSceneEventCompleted = OnSceneLoaded; var sceneLoad = SceneManagerHandler.LoadSceneAsync(sceneName, loadSceneMode, sceneEventProgress); + // Notify the local server that a scene loading event has begun OnSceneEvent?.Invoke(new SceneEvent() { @@ -1435,10 +1572,9 @@ namespace Unity.Netcode SceneEventType = sceneEventData.SceneEventType, LoadSceneMode = sceneEventData.LoadSceneMode, SceneName = sceneName, - ClientId = NetworkManager.ServerClientId + ClientId = NetworkManager.LocalClientId }); - - OnLoad?.Invoke(NetworkManager.ServerClientId, sceneName, sceneEventData.LoadSceneMode, sceneLoad); + OnLoad?.Invoke(NetworkManager.LocalClientId, sceneName, sceneEventData.LoadSceneMode, sceneLoad); //Return our scene progress instance return sceneEventProgress.Status; @@ -1459,7 +1595,7 @@ namespace Unity.Netcode { s_Instances.Add(networkManager, new List()); } - var clientId = networkManager.IsServer ? NetworkManager.ServerClientId : networkManager.LocalClientId; + var clientId = networkManager.LocalClientId; s_Instances[networkManager].Add(new SceneUnloadEventHandler(networkSceneManager, scene, clientId, loadSceneMode, asyncOperation)); } @@ -1594,8 +1730,15 @@ namespace Unity.Netcode var sceneEventProgress = new SceneEventProgress(NetworkManager) { SceneEventId = sceneEventId, - OnSceneEventCompleted = OnSceneLoaded + OnSceneEventCompleted = OnSceneLoaded, + Status = SceneEventProgressStatus.Started, }; + + if (NetworkManager.DistributedAuthorityMode) + { + SceneEventProgressTracking.Add(sceneEventData.SceneEventProgressId, sceneEventProgress); + m_IsSceneEventActive = true; + } var sceneLoad = SceneManagerHandler.LoadSceneAsync(sceneName, sceneEventData.LoadSceneMode, sceneEventProgress); OnSceneEvent?.Invoke(new SceneEvent() @@ -1619,6 +1762,7 @@ namespace Unity.Netcode // If we are shutdown or about to shutdown, then ignore this event if (!NetworkManager.IsListening || NetworkManager.ShutdownInProgress) { + EndSceneEvent(sceneEventId); return; } @@ -1634,6 +1778,31 @@ namespace Unity.Netcode SceneManager.SetActiveScene(nextScene); } + if (NetworkManager.DistributedAuthorityMode) + { + var networkSceneHandle = nextScene.handle; + if (!HasSceneAuthority()) + { + networkSceneHandle = sceneEventData.SceneHandle; + } + + // Update the server scene handle to client scene handle look up table + if (!UpdateServerClientSceneHandle(networkSceneHandle, nextScene.handle, nextScene)) + { + // If the exact same handle exists then there are problems with using handles + Debug.LogWarning($"Server Scene Handle ({networkSceneHandle}) already exist! Happened during scene load of {nextScene.name} with the local handle ({nextScene.handle})"); + } + } + else if (NetworkManager.IsServer) + { + // Update the server scene handle to client scene handle look up table + if (!UpdateServerClientSceneHandle(nextScene.handle, nextScene.handle, nextScene)) + { + // If the exact same handle exists then there are problems with using handles + Debug.LogWarning($"Server Scene Handle ({nextScene.handle}) already exist! Happened during scene load of {nextScene.name} with the local handle ({nextScene.handle})"); + } + } + //Get all NetworkObjects loaded by the scene PopulateScenePlacedObjects(nextScene); @@ -1650,28 +1819,30 @@ namespace Unity.Netcode // not destroy temporary scene are moved into the active scene IsSpawnedObjectsPendingInDontDestroyOnLoad = false; - if (NetworkManager.IsServer) + if (HasSceneAuthority()) { - OnServerLoadedScene(sceneEventId, nextScene); + OnSessionOwnerLoadedScene(sceneEventId, nextScene); } else { - // For the client, we make a server scene handle to client scene handle look up table - if (!UpdateServerClientSceneHandle(sceneEventData.SceneHandle, nextScene.handle, nextScene)) + if (!NetworkManager.DistributedAuthorityMode) { - // If the exact same handle exists then there are problems with using handles - throw new Exception($"Server Scene Handle ({sceneEventData.SceneHandle}) already exist! Happened during scene load of {nextScene.name} with Client Handle ({nextScene.handle})"); + // For the client, we make a server scene handle to client scene handle look up table + if (!UpdateServerClientSceneHandle(sceneEventData.SceneHandle, nextScene.handle, nextScene)) + { + // If the exact same handle exists then there are problems with using handles + throw new Exception($"Server Scene Handle ({sceneEventData.SceneHandle}) already exist! Happened during scene load of {nextScene.name} with Client Handle ({nextScene.handle})"); + } } - OnClientLoadedScene(sceneEventId, nextScene); } } /// - /// Server side: + /// Server/SessionOwner side: /// On scene loaded callback method invoked by OnSceneLoading only /// - private void OnServerLoadedScene(uint sceneEventId, Scene scene) + private void OnSessionOwnerLoadedScene(uint sceneEventId, Scene scene) { var sceneEventData = SceneEventDataStore[sceneEventId]; // Register in-scene placed NetworkObjects with spawn manager @@ -1683,7 +1854,7 @@ namespace Unity.Netcode { // All in-scene placed NetworkObjects default to being owned by the server NetworkManager.SpawnManager.SpawnNetworkObjectLocally(keyValuePairBySceneHandle.Value, - NetworkManager.SpawnManager.GetNetworkObjectId(), true, false, NetworkManager.ServerClientId, true); + NetworkManager.SpawnManager.GetNetworkObjectId(), true, false, NetworkManager.LocalClientId, true); } } } @@ -1694,22 +1865,15 @@ namespace Unity.Netcode // Set the server's scene's handle so the client can build a look up table sceneEventData.SceneHandle = scene.handle; + var sessionOwner = NetworkManager.ServerClientId; // Send all clients the scene load event - for (int j = 0; j < NetworkManager.ConnectedClientsList.Count; j++) + if (NetworkManager.DistributedAuthorityMode) { - var clientId = NetworkManager.ConnectedClientsList[j].ClientId; - if (clientId != NetworkManager.ServerClientId) - { - sceneEventData.TargetClientId = clientId; - var message = new SceneEventMessage - { - EventData = sceneEventData - }; - var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, clientId); - NetworkManager.NetworkMetrics.TrackSceneEventSent(clientId, (uint)sceneEventData.SceneEventType, scene.name, size); - } + sessionOwner = NetworkManager.CurrentSessionOwner; } + SendSceneEventData(sceneEventData.SceneEventId, NetworkManager.ConnectedClientsIds.Where(c => c != sessionOwner).ToArray()); + m_IsSceneEventActive = false; //First, notify local server that the scene was loaded OnSceneEvent?.Invoke(new SceneEvent() @@ -1717,16 +1881,16 @@ namespace Unity.Netcode SceneEventType = SceneEventType.LoadComplete, LoadSceneMode = sceneEventData.LoadSceneMode, SceneName = SceneNameFromHash(sceneEventData.SceneHash), - ClientId = NetworkManager.ServerClientId, + ClientId = NetworkManager.LocalClientId, Scene = scene, }); - OnLoadComplete?.Invoke(NetworkManager.ServerClientId, SceneNameFromHash(sceneEventData.SceneHash), sceneEventData.LoadSceneMode); + OnLoadComplete?.Invoke(NetworkManager.LocalClientId, SceneNameFromHash(sceneEventData.SceneHash), sceneEventData.LoadSceneMode); //Second, only if we are a host do we want register having loaded for the associated SceneEventProgress - if (SceneEventProgressTracking.ContainsKey(sceneEventData.SceneEventProgressId) && NetworkManager.IsHost) + if (SceneEventProgressTracking.ContainsKey(sceneEventData.SceneEventProgressId) && NetworkManager.IsClient) { - SceneEventProgressTracking[sceneEventData.SceneEventProgressId].ClientFinishedSceneEvent(NetworkManager.ServerClientId); + SceneEventProgressTracking[sceneEventData.SceneEventProgressId].ClientFinishedSceneEvent(NetworkManager.LocalClientId); } EndSceneEvent(sceneEventId); } @@ -1741,12 +1905,35 @@ namespace Unity.Netcode sceneEventData.DeserializeScenePlacedObjects(); sceneEventData.SceneEventType = SceneEventType.LoadComplete; - SendSceneEventData(sceneEventId, new ulong[] { NetworkManager.ServerClientId }); + + if (NetworkManager.DistributedAuthorityMode) + { + sceneEventData.TargetClientId = NetworkManager.CurrentSessionOwner; + sceneEventData.SenderClientId = NetworkManager.LocalClientId; + var message = new SceneEventMessage + { + EventData = sceneEventData, + }; + var target = NetworkManager.DAHost ? NetworkManager.CurrentSessionOwner : NetworkManager.ServerClientId; + var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, target); + NetworkManager.NetworkMetrics.TrackSceneEventSent(target, (uint)sceneEventData.SceneEventType, SceneNameFromHash(sceneEventData.SceneHash), size); + } + else + { + SendSceneEventData(sceneEventId, new ulong[] { NetworkManager.ServerClientId }); + } + m_IsSceneEventActive = false; // Process any pending create object messages that the client received while loading a scene ProcessDeferredCreateObjectMessages(); + if (NetworkManager.DistributedAuthorityMode) + { + SceneEventProgressTracking.Remove(sceneEventData.SceneEventProgressId); + m_IsSceneEventActive = false; + } + // Notify local client that the scene was loaded OnSceneEvent?.Invoke(new SceneEvent() { @@ -1820,25 +2007,53 @@ namespace Unity.Netcode continue; } sceneEventData.SceneHash = SceneHashFromNameOrPath(scene.path); - sceneEventData.SceneHandle = scene.handle; + + // If we are just a normal client, then always use the server scene handle + if (NetworkManager.DistributedAuthorityMode) + { + sceneEventData.SenderClientId = NetworkManager.LocalClientId; + sceneEventData.SceneHandle = ClientSceneHandleToServerSceneHandle[scene.handle]; + } + else + { + sceneEventData.SceneHandle = scene.handle; + } } else if (!ValidateSceneBeforeLoading(scene.buildIndex, scene.name, LoadSceneMode.Additive)) { continue; } - sceneEventData.AddSceneToSynchronize(SceneHashFromNameOrPath(scene.path), scene.handle); + + // If we are just a normal client and in distributed authority mode, then always use the known server scene handle + if (NetworkManager.DistributedAuthorityMode && !NetworkManager.DAHost) + { + sceneEventData.AddSceneToSynchronize(SceneHashFromNameOrPath(scene.path), ClientSceneHandleToServerSceneHandle[scene.handle]); + } + else + { + sceneEventData.AddSceneToSynchronize(SceneHashFromNameOrPath(scene.path), scene.handle); + } } sceneEventData.AddSpawnedNetworkObjects(); sceneEventData.AddDespawnedInSceneNetworkObjects(); - var message = new SceneEventMessage { EventData = sceneEventData }; - var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, clientId); + + var size = 0; + if (NetworkManager.DistributedAuthorityMode && !NetworkManager.DAHost) + { + size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, NetworkManager.ServerClientId); + } + else + { + size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, clientId); + } NetworkManager.NetworkMetrics.TrackSceneEventSent(clientId, (uint)sceneEventData.SceneEventType, "", size); + // Notify the local server that the client has been sent the synchronize event OnSceneEvent?.Invoke(new SceneEvent() { @@ -1975,12 +2190,18 @@ namespace Unity.Netcode responseSceneEventData.SceneEventType = SceneEventType.LoadComplete; responseSceneEventData.SceneHash = sceneEventData.ClientSceneHash; - + var target = NetworkManager.ServerClientId; + if (NetworkManager.DistributedAuthorityMode) + { + responseSceneEventData.SenderClientId = NetworkManager.LocalClientId; + responseSceneEventData.TargetClientId = NetworkManager.CurrentSessionOwner; + target = NetworkManager.DAHost ? NetworkManager.CurrentSessionOwner : NetworkManager.ServerClientId; + } var message = new SceneEventMessage { EventData = responseSceneEventData }; - var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, NetworkManager.ServerClientId); + var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, target); NetworkManager.NetworkMetrics.TrackSceneEventSent(NetworkManager.ServerClientId, (uint)responseSceneEventData.SceneEventType, sceneName, size); @@ -2064,11 +2285,12 @@ namespace Unity.Netcode SceneManager.SetActiveScene(scene); } } + EndSceneEvent(sceneEventId); break; } case SceneEventType.ObjectSceneChanged: { - MigrateNetworkObjectsIntoScenes(); + EndSceneEvent(sceneEventId); break; } case SceneEventType.Load: @@ -2112,11 +2334,56 @@ namespace Unity.Netcode ProcessDeferredCreateObjectMessages(); sceneEventData.SceneEventType = SceneEventType.SynchronizeComplete; - SendSceneEventData(sceneEventId, new ulong[] { NetworkManager.ServerClientId }); + if (NetworkManager.DistributedAuthorityMode) + { + if (NetworkManager.CMBServiceConnection) + { + foreach (var clientId in NetworkManager.ConnectedClientsIds) + { + if (clientId == NetworkManager.LocalClientId) + { + continue; + } + sceneEventData.TargetClientId = clientId; + sceneEventData.SenderClientId = NetworkManager.LocalClientId; + var message = new SceneEventMessage + { + EventData = sceneEventData, + }; + var target = NetworkManager.DAHost ? NetworkManager.CurrentSessionOwner : NetworkManager.ServerClientId; + var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, target); + NetworkManager.NetworkMetrics.TrackSceneEventSent(target, (uint)sceneEventData.SceneEventType, SceneNameFromHash(sceneEventData.SceneHash), size); + } + } + else + { + sceneEventData.TargetClientId = NetworkManager.CurrentSessionOwner; + sceneEventData.SenderClientId = NetworkManager.LocalClientId; + var message = new SceneEventMessage + { + EventData = sceneEventData, + }; + var target = NetworkManager.DAHost ? NetworkManager.CurrentSessionOwner : NetworkManager.ServerClientId; + var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, target); + NetworkManager.NetworkMetrics.TrackSceneEventSent(target, (uint)sceneEventData.SceneEventType, SceneNameFromHash(sceneEventData.SceneHash), size); + } + } + else + { + SendSceneEventData(sceneEventId, new ulong[] { NetworkManager.ServerClientId }); + } // All scenes are synchronized, let the server know we are done synchronizing NetworkManager.IsConnectedClient = true; + // With distributed authority, either the client-side automatically spawns the default assigned player prefab or + // if AutoSpawnPlayerPrefabClientSide is disabled the client-side will determine what player prefab to spawn and + // when it gets spawned. + if (NetworkManager.DistributedAuthorityMode && NetworkManager.AutoSpawnPlayerPrefabClientSide) + { + NetworkManager.ConnectionManager.CreateAndSpawnPlayer(NetworkManager.LocalClientId); + } + // Client is now synchronized and fully "connected". This also means the client can send "RPCs" at this time NetworkManager.ConnectionManager.InvokeOnClientConnectedCallback(NetworkManager.LocalClientId); @@ -2142,6 +2409,10 @@ namespace Unity.Netcode OnSynchronizeComplete?.Invoke(NetworkManager.LocalClientId); + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) + { + NetworkLog.LogInfo($"[Client-{NetworkManager.LocalClientId}][Scene Management Enabled] Synchronization complete!"); + } EndSceneEvent(sceneEventId); } break; @@ -2194,10 +2465,10 @@ namespace Unity.Netcode } /// - /// Server Side: - /// Handles incoming Scene_Event messages for host or server + /// Session Owner Side: + /// Handles incoming Scene_Event messages for the current session owner /// - private void HandleServerSceneEvent(uint sceneEventId, ulong clientId) + private void HandleSessionOwnerEvent(uint sceneEventId, ulong clientId) { var sceneEventData = SceneEventDataStore[sceneEventId]; switch (sceneEventData.SceneEventType) @@ -2244,16 +2515,41 @@ namespace Unity.Netcode } case SceneEventType.SynchronizeComplete: { - // Notify the local server that a client has finished synchronizing - OnSceneEvent?.Invoke(new SceneEvent() - { - SceneEventType = sceneEventData.SceneEventType, - SceneName = string.Empty, - ClientId = clientId - }); - // At this point the client is considered fully "connected" - NetworkManager.ConnectedClients[clientId].IsConnected = true; + if ((NetworkManager.DistributedAuthorityMode && NetworkManager.LocalClient.IsSessionOwner) || !NetworkManager.DistributedAuthorityMode) + { + if (NetworkManager.DistributedAuthorityMode && !NetworkManager.DAHost) + { + // DANGO-EXP TODO: Remove this once service is sending the synchronization message to all clients + if (NetworkManager.ConnectedClients.ContainsKey(clientId) && NetworkManager.ConnectionManager.ConnectedClientIds.Contains(clientId) && NetworkManager.ConnectedClientsList.Contains(NetworkManager.ConnectedClients[clientId])) + { + EndSceneEvent(sceneEventId); + return; + } + NetworkManager.ConnectionManager.AddClient(clientId); + } + + // Notify the local server that a client has finished synchronizing + OnSceneEvent?.Invoke(new SceneEvent() + { + SceneEventType = sceneEventData.SceneEventType, + SceneName = string.Empty, + ClientId = clientId + }); + if (NetworkManager.ConnectedClients.ContainsKey(clientId)) + { + NetworkManager.ConnectedClients[clientId].IsConnected = true; + } + } + else + { + // DANGO-EXP TODO: Remove this once service distributes objects + // Non-session owners receive this notification from newly connected clients and upon receiving + // the event they will redistribute their NetworkObjects + NetworkManager.SpawnManager.DistributeNetworkObjects(clientId); + EndSceneEvent(sceneEventId); + return; + } // All scenes are synchronized, let the server know we are done synchronizing OnSynchronizeComplete?.Invoke(clientId); @@ -2285,6 +2581,8 @@ namespace Unity.Netcode ClientId = clientId }); } + // DANGO-EXP TODO: Remove this once service distributes objects + NetworkManager.SpawnManager.DistributeNetworkObjects(clientId); EndSceneEvent(sceneEventId); break; } @@ -2296,6 +2594,11 @@ namespace Unity.Netcode } } + /// + /// Skips scene handling to be able to test CMB DA_NGO Codec tests + /// + internal bool SkipSceneHandling; + /// /// Both Client and Server: Incoming scene event entry point /// @@ -2306,8 +2609,53 @@ namespace Unity.Netcode if (NetworkManager != null) { var sceneEventData = BeginSceneEvent(); - sceneEventData.Deserialize(reader); + if (SkipSceneHandling) + { + return; + } + + // DA HOST Will keep track of session owner and if it is not the scene owner it will forward the message + // to the current session owner + if (NetworkManager.DistributedAuthorityMode && NetworkManager.DAHost) + { + // If the event is server directed + if (!sceneEventData.IsSceneEventClientSide()) + { + // If the DAHost is not the session owner, then forward the message to the current session owner + if (NetworkManager.CurrentSessionOwner != NetworkManager.LocalClientId) + { + var message = new SceneEventMessage() + { + EventData = sceneEventData, + }; + // Forward synchronization to client then exit early because DAHost is not the current session owner + NetworkManager.MessageManager.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, NetworkManager.CurrentSessionOwner); + EndSceneEvent(sceneEventData.SceneEventId); + return; + } + } + else + { + // DAHost will forward any messages not targeting the DAHost to the targeted client + if (sceneEventData.TargetClientId != NetworkManager.LocalClientId) + { + if (NetworkManager.LogLevel == LogLevel.Developer) + { + NetworkLog.LogInfoServer($"[Forward To: Client-{sceneEventData.TargetClientId}][{Enum.GetName(typeof(SceneEventType), sceneEventData.SceneEventType)}]"); + } + sceneEventData.ForwardSynchronization = sceneEventData.SceneEventType == SceneEventType.Synchronize; + sceneEventData.IsForwarding = true; + var message = new SceneEventMessage() + { + EventData = sceneEventData, + }; + NetworkManager.MessageManager.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, sceneEventData.TargetClientId); + EndSceneEvent(sceneEventData.SceneEventId); + return; + } + } + } NetworkManager.NetworkMetrics.TrackSceneEventReceived( clientId, (uint)sceneEventData.SceneEventType, SceneNameFromHash(sceneEventData.SceneHash), reader.Length); @@ -2335,7 +2683,12 @@ namespace Unity.Netcode } else { - HandleServerSceneEvent(sceneEventData.SceneEventId, clientId); + var sendingClient = clientId; + if (NetworkManager.DistributedAuthorityMode) + { + sendingClient = sceneEventData.SenderClientId; + } + HandleSessionOwnerEvent(sceneEventData.SceneEventId, sendingClient); } } else @@ -2367,9 +2720,13 @@ namespace Unity.Netcode if (networkObject.gameObject.transform.parent == null && networkObject.IsSceneObject != null && !networkObject.IsSceneObject.Value) { UnityEngine.Object.DontDestroyOnLoad(networkObject.gameObject); + // When temporarily migrating to the DDOL, adjust the network and origin scene handles so no messages are generated + // about objects being moved to a new scene. + networkObject.NetworkSceneHandle = ClientSceneHandleToServerSceneHandle[networkObject.gameObject.scene.handle]; + networkObject.SceneOriginHandle = networkObject.gameObject.scene.handle; } } - else if (NetworkManager.IsServer) + else if (networkObject.HasAuthority) { networkObject.Despawn(); } @@ -2449,6 +2806,21 @@ namespace Unity.Netcode // back into the currently active scene if (networkObject.gameObject.transform.parent == null && networkObject.IsSceneObject != null && !networkObject.IsSceneObject.Value) { + if (NetworkManager.DistributedAuthorityMode) + { + // When migrating out of the DDOL to the currently active scene, adjust the network and origin scene handles so no messages are generated + // about objects being moved to a new scene. + if (SceneManagerHandler.IsIntegrationTest() && SceneManager.GetActiveScene() == scene) + { + networkObject.NetworkSceneHandle = scene.handle; + } + else + { + networkObject.NetworkSceneHandle = ClientSceneHandleToServerSceneHandle[scene.handle]; + } + networkObject.SceneOriginHandle = scene.handle; + } + SceneManager.MoveGameObjectToScene(networkObject.gameObject, scene); } } @@ -2459,7 +2831,24 @@ namespace Unity.Netcode /// Holds a list of scene handles (server-side relative) and NetworkObjects migrated into it /// during the current frame. /// - internal Dictionary> ObjectsMigratedIntoNewScene = new Dictionary>(); + internal Dictionary>> ObjectsMigratedIntoNewScene = new Dictionary>>(); + + internal bool IsSceneEventInProgress() + { + if (!NetworkManager.NetworkConfig.EnableSceneManagement) + { + return false; + } + + foreach (var sceneEventEntry in SceneEventProgressTracking) + { + if (!sceneEventEntry.Value.HasTimedOut() && sceneEventEntry.Value.SceneEventType != SceneEventType.Synchronize && sceneEventEntry.Value.Status == SceneEventProgressStatus.Started) + { + return true; + } + } + return false; + } /// /// Handles notifying clients when a NetworkObject has been migrated into a new scene @@ -2467,7 +2856,7 @@ namespace Unity.Netcode internal void NotifyNetworkObjectSceneChanged(NetworkObject networkObject) { // Really, this should never happen but in case it does - if (!NetworkManager.IsServer) + if (!networkObject.HasAuthority) { if (NetworkManager.LogLevel == LogLevel.Developer) { @@ -2496,20 +2885,23 @@ namespace Unity.Netcode // Don't notify if a scene event is in progress // Note: This does not apply to SceneEventType.Synchronize since synchronization isn't a global connected client event. - foreach (var sceneEventEntry in SceneEventProgressTracking) + if (IsSceneEventInProgress()) { - if (!sceneEventEntry.Value.HasTimedOut() && sceneEventEntry.Value.Status == SceneEventProgressStatus.Started) - { - return; - } + return; } // Otherwise, add the NetworkObject into the list of NetworkObjects who's scene has changed - if (!ObjectsMigratedIntoNewScene.ContainsKey(networkObject.gameObject.scene.handle)) + if (!ObjectsMigratedIntoNewScene.ContainsKey(networkObject.NetworkSceneHandle)) { - ObjectsMigratedIntoNewScene.Add(networkObject.gameObject.scene.handle, new List()); + ObjectsMigratedIntoNewScene.Add(networkObject.NetworkSceneHandle, new Dictionary>()); } - ObjectsMigratedIntoNewScene[networkObject.gameObject.scene.handle].Add(networkObject); + + if (!ObjectsMigratedIntoNewScene[networkObject.NetworkSceneHandle].ContainsKey(NetworkManager.LocalClientId)) + { + ObjectsMigratedIntoNewScene[networkObject.NetworkSceneHandle].Add(NetworkManager.LocalClientId, new List()); + } + + ObjectsMigratedIntoNewScene[networkObject.NetworkSceneHandle][NetworkManager.LocalClientId].Add(networkObject); } /// @@ -2526,12 +2918,21 @@ namespace Unity.Netcode if (ServerSceneHandleToClientSceneHandle.ContainsKey(sceneEntry.Key)) { var clientSceneHandle = ServerSceneHandleToClientSceneHandle[sceneEntry.Key]; - if (ScenesLoaded.ContainsKey(ServerSceneHandleToClientSceneHandle[sceneEntry.Key])) + foreach (var ownerEntry in sceneEntry.Value) { - var scene = ScenesLoaded[clientSceneHandle]; - foreach (var networkObject in sceneEntry.Value) + if (ownerEntry.Key == NetworkManager.LocalClientId) { - SceneManager.MoveGameObjectToScene(networkObject.gameObject, scene); + continue; + } + if (ScenesLoaded.ContainsKey(clientSceneHandle)) + { + var scene = ScenesLoaded[clientSceneHandle]; + foreach (var networkObject in ownerEntry.Value) + { + SceneManager.MoveGameObjectToScene(networkObject.gameObject, scene); + networkObject.NetworkSceneHandle = sceneEntry.Key; + networkObject.SceneOriginHandle = scene.handle; + } } } } @@ -2541,9 +2942,6 @@ namespace Unity.Netcode { NetworkLog.LogErrorServer($"{ex.Message}\n Stack Trace:\n {ex.StackTrace}"); } - - // Clear out the list once complete - ObjectsMigratedIntoNewScene.Clear(); } @@ -2555,21 +2953,28 @@ namespace Unity.Netcode internal void CheckForAndSendNetworkObjectSceneChanged() { // Early exit if not the server or there is nothing pending - if (!NetworkManager.IsServer || ObjectsMigratedIntoNewScene.Count == 0) + if (ObjectsMigratedIntoNewScene.Count == 0) { return; } + MigrateNetworkObjectsIntoScenes(); + // Double check that the NetworkObjects to migrate still exist m_ScenesToRemoveFromObjectMigration.Clear(); foreach (var sceneEntry in ObjectsMigratedIntoNewScene) { - for (int i = sceneEntry.Value.Count - 1; i >= 0; i--) + if (!sceneEntry.Value.ContainsKey(NetworkManager.LocalClientId)) + { + continue; + } + var ownerSceneEntry = sceneEntry.Value[NetworkManager.LocalClientId]; + for (int i = sceneEntry.Value[NetworkManager.LocalClientId].Count - 1; i >= 0; i--) { // Remove NetworkObjects that are no longer spawned - if (!sceneEntry.Value[i].IsSpawned) + if (!sceneEntry.Value[NetworkManager.LocalClientId][i].IsSpawned) { - sceneEntry.Value.RemoveAt(i); + sceneEntry.Value[NetworkManager.LocalClientId].RemoveAt(i); } } // If the scene entry no longer has any NetworkObjects to migrate @@ -2581,22 +2986,35 @@ namespace Unity.Netcode } } - // Remove sceneHandle entries that no longer have any NetworkObjects remaining + // Remove owner sceneHandle entries that no longer have any NetworkObjects remaining foreach (var sceneHandle in m_ScenesToRemoveFromObjectMigration) { - ObjectsMigratedIntoNewScene.Remove(sceneHandle); + ObjectsMigratedIntoNewScene[sceneHandle].Remove(NetworkManager.LocalClientId); } - // If there is nothing to send a migration notification for then exit - if (ObjectsMigratedIntoNewScene.Count == 0) + var localOwnerHasEntries = false; + + foreach (var sceneEntry in ObjectsMigratedIntoNewScene) { + if (sceneEntry.Value.ContainsKey(NetworkManager.LocalClientId)) + { + localOwnerHasEntries = true; + break; + } + } + + // If the local owner has no entries, then exit + if (!localOwnerHasEntries) + { + ObjectsMigratedIntoNewScene.Clear(); return; } // Some NetworkObjects still exist, send the message var sceneEvent = BeginSceneEvent(); sceneEvent.SceneEventType = SceneEventType.ObjectSceneChanged; - SendSceneEventData(sceneEvent.SceneEventId, NetworkManager.ConnectedClientsIds.Where(c => c != NetworkManager.ServerClientId).ToArray()); + SendSceneEventData(sceneEvent.SceneEventId, NetworkManager.ConnectedClientsIds.Where(c => c != NetworkManager.LocalClientId).ToArray()); + ObjectsMigratedIntoNewScene.Clear(); EndSceneEvent(sceneEvent.SceneEventId); } @@ -2604,6 +3022,7 @@ namespace Unity.Netcode // a client is synchronizing internal struct DeferredObjectsMovedEvent { + internal ulong OwnerId; internal Dictionary> ObjectsMigratedTable; } internal List DeferredObjectsMovedEvents = new List(); @@ -2612,6 +3031,9 @@ namespace Unity.Netcode { internal ulong SenderId; internal uint MessageSize; + // When we transfer session owner and we are using a DAHost, this will be pertinent (otherwise it is not when connected to a DA service) + internal ulong[] ObserverIds; + internal ulong[] NewObserverIds; internal NetworkObject.SceneObject SceneObject; internal FastBufferReader FastBufferReader; } @@ -2619,12 +3041,15 @@ namespace Unity.Netcode internal List DeferredObjectCreationList = new List(); internal int DeferredObjectCreationCount; - internal void DeferCreateObject(ulong senderId, uint messageSize, NetworkObject.SceneObject sceneObject, FastBufferReader fastBufferReader) + // The added clientIds is specific to DAHost when session ownership changes and a normal client is controlling scene loading + internal void DeferCreateObject(ulong senderId, uint messageSize, NetworkObject.SceneObject sceneObject, FastBufferReader fastBufferReader, ulong[] observerIds, ulong[] newObserverIds) { var deferredObjectCreationEntry = new DeferredObjectCreation() { SenderId = senderId, MessageSize = messageSize, + ObserverIds = observerIds, + NewObserverIds = newObserverIds, SceneObject = sceneObject, }; @@ -2645,12 +3070,93 @@ namespace Unity.Netcode } var networkManager = NetworkManager; // Process all deferred create object messages. - foreach (var deferredObjectCreation in DeferredObjectCreationList) + for (int i = 0; i < DeferredObjectCreationList.Count; i++) { - CreateObjectMessage.CreateObject(ref networkManager, deferredObjectCreation.SenderId, deferredObjectCreation.MessageSize, deferredObjectCreation.SceneObject, deferredObjectCreation.FastBufferReader); + var deferredObjectCreation = DeferredObjectCreationList[i]; + CreateObjectMessage.CreateObject(ref networkManager, ref deferredObjectCreation); } DeferredObjectCreationCount = DeferredObjectCreationList.Count; DeferredObjectCreationList.Clear(); } + + public enum MapTypes + { + ServerToClient, + ClientToServer + } + public struct SceneMap : INetworkSerializable + { + public MapTypes MapType; + public Scene Scene; + public bool ScenePresent; + public string SceneName; + public int ServerHandle; + public int MappedLocalHandle; + public int LocalHandle; + + public void NetworkSerialize(BufferSerializer serializer) where T : IReaderWriter + { + serializer.SerializeValue(ref MapType); + serializer.SerializeValue(ref ScenePresent); + if (serializer.IsReader) + { + SceneName = "Not Present"; + } + if (ScenePresent) + { + serializer.SerializeValue(ref SceneName); + serializer.SerializeValue(ref LocalHandle); + + } + serializer.SerializeValue(ref ServerHandle); + serializer.SerializeValue(ref MappedLocalHandle); + } + } + + public List GetSceneMapping(MapTypes mapType) + { + var mapping = new List(); + if (mapType == MapTypes.ServerToClient) + { + foreach (var entry in ServerSceneHandleToClientSceneHandle) + { + var scene = ScenesLoaded[entry.Value]; + var sceneIsPresent = scene.IsValid() && scene.isLoaded; + var sceneMap = new SceneMap() + { + MapType = mapType, + ServerHandle = entry.Key, + MappedLocalHandle = entry.Value, + LocalHandle = scene.handle, + Scene = scene, + ScenePresent = sceneIsPresent, + SceneName = sceneIsPresent ? scene.name : "NotPresent", + }; + mapping.Add(sceneMap); + } + } + else + { + foreach (var entry in ClientSceneHandleToServerSceneHandle) + { + var scene = ScenesLoaded[entry.Key]; + var sceneIsPresent = scene.IsValid() && scene.isLoaded; + var sceneMap = new SceneMap() + { + MapType = mapType, + ServerHandle = entry.Value, + MappedLocalHandle = entry.Key, + LocalHandle = scene.handle, + Scene = scene, + ScenePresent = sceneIsPresent, + SceneName = sceneIsPresent ? scene.name : "NotPresent", + }; + mapping.Add(sceneMap); + } + } + + return mapping; + } + } } diff --git a/Runtime/SceneManagement/SceneEventData.cs b/Runtime/SceneManagement/SceneEventData.cs index 351e49d..f0293e4 100644 --- a/Runtime/SceneManagement/SceneEventData.cs +++ b/Runtime/SceneManagement/SceneEventData.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text; using Unity.Collections; using UnityEngine.SceneManagement; @@ -114,7 +115,10 @@ namespace Unity.Netcode /// Only used for scene events, this assures permissions when writing /// NetworkVariable information. If that process changes, then we need to update this + /// In distributed authority mode this is used to route messages to the appropriate destination client internal ulong TargetClientId; + /// Only used with a DAHost + internal ulong SenderClientId; private Dictionary> m_SceneNetworkObjects; private Dictionary m_SceneNetworkObjectDataOffsets; @@ -243,8 +247,76 @@ namespace Unity.Netcode { SceneHandlesToSynchronize.Clear(); } + ForwardSynchronization = false; } + /// + /// Used with SortParentedNetworkObjects to sort the children of the root parent NetworkObject + /// + /// object to be sorted + /// object to be compared to for sorting the first object + /// + private int SortChildrenNetworkObjects(NetworkObject first, NetworkObject second) + { + var firstParent = first.GetCachedParent()?.GetComponent(); + // If the second is the first's parent then move the first down + if (firstParent != null && firstParent == second) + { + return 1; + } + + var secondParent = second.GetCachedParent()?.GetComponent(); + // If the first is the second's parent then move the first up + if (secondParent != null && secondParent == first) + { + return -1; + } + + // Otherwise, don't move the first at all + return 0; + } + + /// + /// Sorts the synchronization order of the NetworkObjects to be serialized + /// by parents before children order + /// + private void SortParentedNetworkObjects() + { + var networkObjectList = m_NetworkObjectsSync.ToList(); + foreach (var networkObject in networkObjectList) + { + // Find only the root parent NetworkObjects + if (networkObject.transform.childCount > 0 && networkObject.transform.parent == null) + { + // Get all child NetworkObjects of the root + var childNetworkObjects = networkObject.GetComponentsInChildren().ToList(); + + childNetworkObjects.Sort(SortChildrenNetworkObjects); + + // Remove the root from the children list + childNetworkObjects.Remove(networkObject); + + // Remove the root's children from the primary list + foreach (var childObject in childNetworkObjects) + { + m_NetworkObjectsSync.Remove(childObject); + } + // Insert or Add the sorted children list + var nextIndex = m_NetworkObjectsSync.IndexOf(networkObject) + 1; + if (nextIndex == m_NetworkObjectsSync.Count) + { + m_NetworkObjectsSync.AddRange(childNetworkObjects); + } + else + { + m_NetworkObjectsSync.InsertRange(nextIndex, childNetworkObjects); + } + } + } + } + + internal static bool LogSerializationOrder = false; + internal void AddSpawnedNetworkObjects() { m_NetworkObjectsSync.Clear(); @@ -256,22 +328,22 @@ namespace Unity.Netcode } } - // Sort by parents before children - m_NetworkObjectsSync.Sort(SortParentedNetworkObjects); - // Sort by INetworkPrefabInstanceHandler implementation before the // NetworkObjects spawned by the implementation m_NetworkObjectsSync.Sort(SortNetworkObjects); + // The last thing we sort is parents before children + SortParentedNetworkObjects(); + // This is useful to know what NetworkObjects a client is going to be synchronized with // as well as the order in which they will be deserialized - if (m_NetworkManager.LogLevel == LogLevel.Developer) + if (LogSerializationOrder && m_NetworkManager.LogLevel == LogLevel.Developer) { - var messageBuilder = new System.Text.StringBuilder(0xFFFF); - messageBuilder.Append("[Server-Side Client-Synchronization] NetworkObject serialization order:"); + var messageBuilder = new StringBuilder(0xFFFF); + messageBuilder.AppendLine("[Server-Side Client-Synchronization] NetworkObject serialization order:"); foreach (var networkObject in m_NetworkObjectsSync) { - messageBuilder.Append($"{networkObject.name}"); + messageBuilder.AppendLine($"{networkObject.name}"); } NetworkLog.LogInfo(messageBuilder.ToString()); } @@ -362,31 +434,35 @@ namespace Unity.Netcode return 0; } - /// - /// Sorts the synchronization order of the NetworkObjects to be serialized - /// by parents before children. - /// - /// - /// This only handles late joining players. Spawning and nesting several children - /// dynamically is still handled by the orphaned child list when deserialized out of - /// hierarchical order (i.e. Spawn parent and child dynamically, parent message is - /// dropped and re-sent but child object is received and processed) - /// - private int SortParentedNetworkObjects(NetworkObject first, NetworkObject second) + internal bool EnableSerializationLogs = false; + + private void LogArray(byte[] data, int start = 0, int stop = 0, StringBuilder builder = null) { - // If the first has a parent, move the first down - if (first.transform.parent != null) + var usingExternalBuilder = builder != null; + if (!usingExternalBuilder) { - return 1; + builder = new StringBuilder(); } - else // If the second has a parent and the first does not, then move the first up - if (second.transform.parent != null) + + if (stop == 0) { - return -1; + stop = data.Length; + } + + builder.AppendLine($"[Start Data Dump][Start = {start}][Stop = {stop}] Size ({stop - start})"); + for (int i = start; i < stop; i++) + { + builder.Append($"{data[i]:X2} "); + } + builder.Append("\n"); + + if (!usingExternalBuilder) + { + UnityEngine.Debug.Log(builder.ToString()); } - return 0; } + internal bool ForwardSynchronization; /// /// Client and Server Side: @@ -398,6 +474,12 @@ namespace Unity.Netcode // Write the scene event type writer.WriteValueSafe(SceneEventType); + if (m_NetworkManager.DistributedAuthorityMode) + { + BytePacker.WriteValueBitPacked(writer, TargetClientId); + BytePacker.WriteValueBitPacked(writer, SenderClientId); + } + if (SceneEventType == SceneEventType.ActiveSceneChanged) { writer.WriteValueSafe(ActiveSceneHash); @@ -432,12 +514,25 @@ namespace Unity.Netcode case SceneEventType.Synchronize: { writer.WriteValueSafe(ActiveSceneHash); + WriteSceneSynchronizationData(writer); + + if (EnableSerializationLogs) + { + LogArray(writer.ToArray(), 0, writer.Length); + } break; } case SceneEventType.Load: { - SerializeScenePlacedObjects(writer); + if (m_NetworkManager.DistributedAuthorityMode && IsForwarding && m_NetworkManager.DAHost) + { + CopyInternalBuffer(ref writer); + } + else + { + SerializeScenePlacedObjects(writer); + } break; } case SceneEventType.SynchronizeComplete: @@ -459,6 +554,11 @@ namespace Unity.Netcode } } + private unsafe void CopyInternalBuffer(ref FastBufferWriter writer) + { + writer.WriteBytesSafe(InternalBuffer.GetUnsafePtrAtCurrentPosition(), InternalBuffer.Length); + } + /// /// Server Side: /// Called at the end of a event once the scene is loaded and scene placed NetworkObjects @@ -466,13 +566,29 @@ namespace Unity.Netcode /// internal void WriteSceneSynchronizationData(FastBufferWriter writer) { + var builder = (StringBuilder)null; + if (EnableSerializationLogs) + { + builder = new StringBuilder(); + builder.AppendLine($"[Write][Synchronize-Start][WPos: {writer.Position}] Begin:"); + } // Write the scenes we want to load, in the order we want to load them writer.WriteValueSafe(ScenesToSynchronize.ToArray()); writer.WriteValueSafe(SceneHandlesToSynchronize.ToArray()); - // Store our current position in the stream to come back and say how much data we have written var positionStart = writer.Position; + if (m_NetworkManager.DistributedAuthorityMode && ForwardSynchronization && m_NetworkManager.DAHost) + { + writer.WriteValueSafe(m_InternalBufferSize); + CopyInternalBuffer(ref writer); + if (EnableSerializationLogs) + { + LogArray(writer.ToArray(), positionStart); + } + return; + } + // Size Place Holder -- Start // !!NOTE!!: Since this is a placeholder to be set after we know how much we have written, // for stream offset purposes this MUST not be a packed value! @@ -481,15 +597,34 @@ namespace Unity.Netcode // Write the number of NetworkObjects we are serializing writer.WriteValueSafe(m_NetworkObjectsSync.Count); + if (EnableSerializationLogs) + { + builder.AppendLine($"[Synchronize Objects][positionStart: {positionStart}][WPos: {writer.Position}][NO-Count: {m_NetworkObjectsSync.Count}] Begin:"); + } + var distributedAuthority = m_NetworkManager.DistributedAuthorityMode; // Serialize all NetworkObjects that are spawned for (var i = 0; i < m_NetworkObjectsSync.Count; ++i) { + var networkObject = m_NetworkObjectsSync[i]; var noStart = writer.Position; - var sceneObject = m_NetworkObjectsSync[i].GetMessageSceneObject(TargetClientId); + // In distributed authority mode, we send the currently known observers of each NetworkObject to the client being synchronized. + var sceneObject = m_NetworkObjectsSync[i].GetMessageSceneObject(TargetClientId, distributedAuthority); + sceneObject.Serialize(writer); var noStop = writer.Position; totalBytes += noStop - noStart; + if (EnableSerializationLogs) + { + var offStart = noStart - (positionStart + sizeof(int)); + var offStop = noStop - (positionStart + sizeof(int)); + builder.AppendLine($"[Head: {offStart}][Tail: {offStop}][Size: {offStop - offStart}][{networkObject.name}][NID-{networkObject.NetworkObjectId}][Children: {networkObject.ChildNetworkBehaviours.Count}]"); + LogArray(writer.ToArray(), noStart, noStop, builder); + } + } + if (EnableSerializationLogs) + { + UnityEngine.Debug.Log(builder.ToString()); } // Write the number of despawned in-scene placed NetworkObjects @@ -511,6 +646,10 @@ namespace Unity.Netcode // Write the total size written to the stream by NetworkObjects being serialized writer.WriteValueSafe(bytesWritten); writer.Seek(positionEnd); + if (EnableSerializationLogs) + { + LogArray(writer.ToArray(), positionStart); + } } /// @@ -526,6 +665,7 @@ namespace Unity.Netcode // Write our count place holder (must not be packed!) writer.WriteValueSafe((ushort)0); + var distributedAuthority = m_NetworkManager.DistributedAuthorityMode; foreach (var keyValuePairByGlobalObjectIdHash in m_NetworkManager.SceneManager.ScenePlacedObjects) { @@ -534,7 +674,7 @@ namespace Unity.Netcode if (keyValuePairBySceneHandle.Value.Observers.Contains(TargetClientId)) { // Serialize the NetworkObject - var sceneObject = keyValuePairBySceneHandle.Value.GetMessageSceneObject(TargetClientId); + var sceneObject = keyValuePairBySceneHandle.Value.GetMessageSceneObject(TargetClientId, distributedAuthority); sceneObject.Serialize(writer); numberOfObjects++; } @@ -567,6 +707,12 @@ namespace Unity.Netcode internal void Deserialize(FastBufferReader reader) { reader.ReadValueSafe(out SceneEventType); + if (m_NetworkManager.DistributedAuthorityMode) + { + ByteUnpacker.ReadValueBitPacked(reader, out TargetClientId); + ByteUnpacker.ReadValueBitPacked(reader, out SenderClientId); + } + if (SceneEventType == SceneEventType.ActiveSceneChanged) { reader.ReadValueSafe(out ActiveSceneHash); @@ -607,6 +753,10 @@ namespace Unity.Netcode case SceneEventType.Synchronize: { reader.ReadValueSafe(out ActiveSceneHash); + if (EnableSerializationLogs) + { + LogArray(reader.ToArray(), 0, reader.Length); + } CopySceneSynchronizationData(reader); break; } @@ -641,6 +791,8 @@ namespace Unity.Netcode } } + private int m_InternalBufferSize; + /// /// Client Side: /// Prepares for a scene synchronization event and copies the scene synchronization data @@ -657,6 +809,8 @@ namespace Unity.Netcode // is not packed! reader.ReadValueSafe(out int sizeToCopy); + m_InternalBufferSize = sizeToCopy; + unsafe { if (!reader.TryBeginRead(sizeToCopy)) @@ -667,6 +821,10 @@ namespace Unity.Netcode m_HasInternalBuffer = true; // We use Allocator.Persistent since scene synchronization will most likely take longer than 4 frames InternalBuffer = new FastBufferReader(reader.GetUnsafePtrAtCurrentPosition(), Allocator.Persistent, sizeToCopy); + if (EnableSerializationLogs) + { + LogArray(InternalBuffer.ToArray()); + } } } @@ -916,12 +1074,24 @@ namespace Unity.Netcode /// internal void SynchronizeSceneNetworkObjects(NetworkManager networkManager) { + var builder = (StringBuilder)null; + if (EnableSerializationLogs) + { + builder = new StringBuilder(); + } + try { // Process all spawned NetworkObjects for this network session InternalBuffer.ReadValueSafe(out int newObjectsCount); + if (EnableSerializationLogs) + { + builder.AppendLine($"[Read][Synchronize Objects][WPos: {InternalBuffer.Position}][NO-Count: {newObjectsCount}] Begin:"); + } + for (int i = 0; i < newObjectsCount; i++) { + var noStart = InternalBuffer.Position; var sceneObject = new NetworkObject.SceneObject(); sceneObject.Deserialize(InternalBuffer); @@ -932,6 +1102,12 @@ namespace Unity.Netcode } var spawnedNetworkObject = NetworkObject.AddSceneObject(sceneObject, InternalBuffer, networkManager); + var noStop = InternalBuffer.Position; + if (EnableSerializationLogs) + { + builder.AppendLine($"[Head: {noStart}][Tail: {noStop}][Size: {noStop - noStart}][{spawnedNetworkObject.name}][NID-{spawnedNetworkObject.NetworkObjectId}][Children: {spawnedNetworkObject.ChildNetworkBehaviours.Count}]"); + LogArray(InternalBuffer.ToArray(), noStart, noStop, builder); + } // If we failed to deserialize the NetowrkObject then don't add null to the list if (spawnedNetworkObject != null) { @@ -941,11 +1117,20 @@ namespace Unity.Netcode } } } + if (EnableSerializationLogs) + { + UnityEngine.Debug.Log(builder.ToString()); + } // Now deserialize the despawned in-scene placed NetworkObjects list (if any) DeserializeDespawnedInScenePlacedNetworkObjects(); } + catch (Exception ex) + { + UnityEngine.Debug.LogException(ex); + UnityEngine.Debug.Log(builder.ToString()); + } finally { InternalBuffer.Dispose(); @@ -999,24 +1184,38 @@ namespace Unity.Netcode /// Serialize scene handles and associated NetworkObjects that were migrated /// into a new scene. /// + internal bool IsForwarding; + private ulong m_OwnerId; + private void SerializeObjectsMovedIntoNewScene(FastBufferWriter writer) { var sceneManager = m_NetworkManager.SceneManager; + var ownerId = m_NetworkManager.LocalClientId; + if (IsForwarding) + { + ownerId = m_OwnerId; + } + + // Write the owner identifier + writer.WriteValueSafe(ownerId); + // Write the number of scene handles writer.WriteValueSafe(sceneManager.ObjectsMigratedIntoNewScene.Count); foreach (var sceneHandleObjects in sceneManager.ObjectsMigratedIntoNewScene) { + if (!sceneManager.ObjectsMigratedIntoNewScene[sceneHandleObjects.Key].ContainsKey(ownerId)) + { + throw new Exception($"Trying to send object scene migration for Client-{ownerId} but the client has no entries to send!"); + } // Write the scene handle writer.WriteValueSafe(sceneHandleObjects.Key); // Write the number of NetworkObjectIds to expect - writer.WriteValueSafe(sceneHandleObjects.Value.Count); - foreach (var networkObject in sceneHandleObjects.Value) + writer.WriteValueSafe(sceneHandleObjects.Value[ownerId].Count); + foreach (var networkObject in sceneHandleObjects.Value[ownerId]) { writer.WriteValueSafe(networkObject.NetworkObjectId); } } - // Once we are done, clear the table - sceneManager.ObjectsMigratedIntoNewScene.Clear(); } /// @@ -1027,17 +1226,30 @@ namespace Unity.Netcode { var sceneManager = m_NetworkManager.SceneManager; var spawnManager = m_NetworkManager.SpawnManager; - // Just always assure this has no entries - sceneManager.ObjectsMigratedIntoNewScene.Clear(); + var numberOfScenes = 0; var sceneHandle = 0; var objectCount = 0; var networkObjectId = (ulong)0; + + var ownerID = (ulong)0; + reader.ReadValueSafe(out ownerID); + m_OwnerId = ownerID; reader.ReadValueSafe(out numberOfScenes); + for (int i = 0; i < numberOfScenes; i++) { reader.ReadValueSafe(out sceneHandle); - sceneManager.ObjectsMigratedIntoNewScene.Add(sceneHandle, new List()); + if (!sceneManager.ObjectsMigratedIntoNewScene.ContainsKey(sceneHandle)) + { + sceneManager.ObjectsMigratedIntoNewScene.Add(sceneHandle, new Dictionary>()); + } + + if (!sceneManager.ObjectsMigratedIntoNewScene[sceneHandle].ContainsKey(ownerID)) + { + sceneManager.ObjectsMigratedIntoNewScene[sceneHandle].Add(ownerID, new List()); + } + reader.ReadValueSafe(out objectCount); for (int j = 0; j < objectCount; j++) { @@ -1047,9 +1259,9 @@ namespace Unity.Netcode NetworkLog.LogError($"[Object Scene Migration] Trying to synchronize NetworkObjectId ({networkObjectId}) but it was not spawned or no longer exists!!"); continue; } + var networkObject = spawnManager.SpawnedObjects[networkObjectId]; // Add NetworkObject scene migration to ObjectsMigratedIntoNewScene dictionary that is processed - // - sceneManager.ObjectsMigratedIntoNewScene[sceneHandle].Add(spawnManager.SpawnedObjects[networkObjectId]); + sceneManager.ObjectsMigratedIntoNewScene[sceneHandle][ownerID].Add(networkObject); } } } @@ -1065,16 +1277,22 @@ namespace Unity.Netcode { var sceneManager = m_NetworkManager.SceneManager; var spawnManager = m_NetworkManager.SpawnManager; + var ownerId = (ulong)0; var numberOfScenes = 0; var sceneHandle = 0; var objectCount = 0; var networkObjectId = (ulong)0; + reader.ReadValueSafe(out ownerId); + + var deferredObjectsMovedEvent = new NetworkSceneManager.DeferredObjectsMovedEvent() { - ObjectsMigratedTable = new Dictionary>() + OwnerId = ownerId, + ObjectsMigratedTable = new Dictionary>(), }; + reader.ReadValueSafe(out numberOfScenes); for (int i = 0; i < numberOfScenes; i++) { @@ -1104,8 +1322,13 @@ namespace Unity.Netcode { if (!sceneManager.ObjectsMigratedIntoNewScene.ContainsKey(keyEntry.Key)) { - sceneManager.ObjectsMigratedIntoNewScene.Add(keyEntry.Key, new List()); + sceneManager.ObjectsMigratedIntoNewScene.Add(keyEntry.Key, new Dictionary>()); } + if (!sceneManager.ObjectsMigratedIntoNewScene[keyEntry.Key].ContainsKey(objectsMovedEvent.OwnerId)) + { + sceneManager.ObjectsMigratedIntoNewScene[keyEntry.Key].Add(objectsMovedEvent.OwnerId, new List()); + } + foreach (var objectId in keyEntry.Value) { if (!spawnManager.SpawnedObjects.ContainsKey(objectId)) @@ -1114,22 +1337,15 @@ namespace Unity.Netcode continue; } var networkObject = spawnManager.SpawnedObjects[objectId]; - if (!sceneManager.ObjectsMigratedIntoNewScene[keyEntry.Key].Contains(networkObject)) + if (!sceneManager.ObjectsMigratedIntoNewScene[keyEntry.Key][objectsMovedEvent.OwnerId].Contains(networkObject)) { - sceneManager.ObjectsMigratedIntoNewScene[keyEntry.Key].Add(networkObject); + sceneManager.ObjectsMigratedIntoNewScene[keyEntry.Key][objectsMovedEvent.OwnerId].Add(networkObject); } } } objectsMovedEvent.ObjectsMigratedTable.Clear(); } - sceneManager.DeferredObjectsMovedEvents.Clear(); - - // If there are any pending objects to migrate, then migrate them - if (sceneManager.ObjectsMigratedIntoNewScene.Count > 0) - { - sceneManager.MigrateNetworkObjectsIntoScenes(); - } } /// diff --git a/Runtime/SceneManagement/SceneEventProgress.cs b/Runtime/SceneManagement/SceneEventProgress.cs index d50c6c7..e9b52a2 100644 --- a/Runtime/SceneManagement/SceneEventProgress.cs +++ b/Runtime/SceneManagement/SceneEventProgress.cs @@ -55,6 +55,10 @@ namespace Unity.Netcode /// This is returned when a client attempts to perform a server only action /// ServerOnlyAction, + /// + /// This is returned when a client that is not the session owner attempts to perform a session owner only action + /// + SessionOwnerOnlyAction, } /// @@ -157,22 +161,20 @@ namespace Unity.Netcode if (status == SceneEventProgressStatus.Started) { m_NetworkManager = networkManager; - - if (networkManager.IsServer) + WhenSceneEventHasTimedOut = networkManager.RealTimeProvider.RealTimeSinceStartup + networkManager.NetworkConfig.LoadSceneTimeOut; + if ((networkManager.IsServer && !networkManager.DistributedAuthorityMode) || (networkManager.DistributedAuthorityMode && networkManager.LocalClient.IsSessionOwner)) { m_NetworkManager.OnClientDisconnectCallback += OnClientDisconnectCallback; // Track the clients that were connected when we started this event foreach (var connectedClientId in networkManager.ConnectedClientsIds) { - // Ignore the host client - if (NetworkManager.ServerClientId == connectedClientId) + // Ignore the host or session owner + if ((!networkManager.DistributedAuthorityMode && NetworkManager.ServerClientId == connectedClientId) || (networkManager.DistributedAuthorityMode && networkManager.CurrentSessionOwner == connectedClientId)) { continue; } ClientsProcessingSceneEvent.Add(connectedClientId, false); } - - WhenSceneEventHasTimedOut = networkManager.RealTimeProvider.RealTimeSinceStartup + networkManager.NetworkConfig.LoadSceneTimeOut; m_TimeOutCoroutine = m_NetworkManager.StartCoroutine(TimeOutSceneEventProgress()); } } @@ -298,7 +300,7 @@ namespace Unity.Netcode m_NetworkManager.OnClientDisconnectCallback -= OnClientDisconnectCallback; } - if (m_TimeOutCoroutine != null) + if (m_TimeOutCoroutine != null && m_NetworkManager != null) { m_NetworkManager.StopCoroutine(m_TimeOutCoroutine); } diff --git a/Runtime/Serialization/FastBufferReader.cs b/Runtime/Serialization/FastBufferReader.cs index f91a41e..c2cfc13 100644 --- a/Runtime/Serialization/FastBufferReader.cs +++ b/Runtime/Serialization/FastBufferReader.cs @@ -245,6 +245,11 @@ namespace Unity.Netcode /// public unsafe void Dispose() { + if (Handle == null) + { + return; + } + UnsafeUtility.Free(Handle, Handle->Allocator); Handle = null; } @@ -1069,6 +1074,36 @@ namespace Unity.Netcode ReadUnmanagedSafeInPlace(ref value); } } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void ReadValueSafeInPlace(ref NativeHashSet value) where T : unmanaged, IEquatable + { + ReadUnmanagedSafe(out int length); + value.Clear(); + for (var i = 0; i < length; ++i) + { + T val = default; + NetworkVariableSerialization.Read(this, ref val); + value.Add(val); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void ReadValueSafeInPlace(ref NativeHashMap value) + where TKey : unmanaged, IEquatable + where TVal : unmanaged + { + ReadUnmanagedSafe(out int length); + value.Clear(); + for (var i = 0; i < length; ++i) + { + TKey key = default; + TVal val = default; + NetworkVariableSerialization.Read(this, ref key); + NetworkVariableSerialization.Read(this, ref val); + value[key] = val; + } + } #endif /// diff --git a/Runtime/Serialization/FastBufferWriter.cs b/Runtime/Serialization/FastBufferWriter.cs index 475b00a..a686540 100644 --- a/Runtime/Serialization/FastBufferWriter.cs +++ b/Runtime/Serialization/FastBufferWriter.cs @@ -772,7 +772,11 @@ namespace Unity.Netcode [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void WriteBytes(NativeList value, int size = -1, int offset = 0) { +#if UTP_TRANSPORT_2_0_ABOVE + byte* ptr = value.GetUnsafePtr(); +#else byte* ptr = (byte*)value.GetUnsafePtr(); +#endif WriteBytes(ptr, size == -1 ? value.Length : size, offset); } @@ -816,7 +820,11 @@ namespace Unity.Netcode [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void WriteBytesSafe(NativeList value, int size = -1, int offset = 0) { +#if UTP_TRANSPORT_2_0_ABOVE + byte* ptr = value.GetUnsafePtr(); +#else byte* ptr = (byte*)value.GetUnsafePtr(); +#endif WriteBytesSafe(ptr, size == -1 ? value.Length : size, offset); } @@ -985,7 +993,11 @@ namespace Unity.Netcode internal unsafe void WriteUnmanaged(NativeList value) where T : unmanaged { WriteUnmanaged(value.Length); +#if UTP_TRANSPORT_2_0_ABOVE + var ptr = value.GetUnsafePtr(); +#else var ptr = (T*)value.GetUnsafePtr(); +#endif { byte* bytes = (byte*)ptr; WriteBytes(bytes, sizeof(T) * value.Length); @@ -995,7 +1007,11 @@ namespace Unity.Netcode internal unsafe void WriteUnmanagedSafe(NativeList value) where T : unmanaged { WriteUnmanagedSafe(value.Length); +#if UTP_TRANSPORT_2_0_ABOVE + var ptr = value.GetUnsafePtr(); +#else var ptr = (T*)value.GetUnsafePtr(); +#endif { byte* bytes = (byte*)ptr; WriteBytesSafe(bytes, sizeof(T) * value.Length); @@ -1189,6 +1205,39 @@ namespace Unity.Netcode WriteUnmanaged(value); } } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void WriteValueSafe(NativeHashSet value) where T : unmanaged, IEquatable + { +#if UTP_TRANSPORT_2_0_ABOVE + WriteUnmanagedSafe(value.Count); +#else + WriteUnmanagedSafe(value.Count()); +#endif + foreach (var item in value) + { + var iReffable = item; + NetworkVariableSerialization.Write(this, ref iReffable); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void WriteValueSafe(NativeHashMap value) + where TKey : unmanaged, IEquatable + where TVal : unmanaged + { +#if UTP_TRANSPORT_2_0_ABOVE + WriteUnmanagedSafe(value.Count); +#else + WriteUnmanagedSafe(value.Count()); +#endif + foreach (var item in value) + { + (var key, var val) = (item.Key, item.Value); + NetworkVariableSerialization.Write(this, ref key); + NetworkVariableSerialization.Write(this, ref val); + } + } #endif /// diff --git a/Runtime/Serialization/NetworkBehaviourReference.cs b/Runtime/Serialization/NetworkBehaviourReference.cs index 6df91b8..ab2a886 100644 --- a/Runtime/Serialization/NetworkBehaviourReference.cs +++ b/Runtime/Serialization/NetworkBehaviourReference.cs @@ -40,7 +40,7 @@ namespace Unity.Netcode /// True if the was found; False if the was not found. This can happen if the corresponding has not been spawned yet. you can try getting the reference at a later point in time. public bool TryGet(out NetworkBehaviour networkBehaviour, NetworkManager networkManager = null) { - networkBehaviour = GetInternal(this, null); + networkBehaviour = GetInternal(this, networkManager); return networkBehaviour != null; } @@ -53,7 +53,7 @@ namespace Unity.Netcode /// True if the was found; False if the was not found. This can happen if the corresponding has not been spawned yet. you can try getting the reference at a later point in time. public bool TryGet(out T networkBehaviour, NetworkManager networkManager = null) where T : NetworkBehaviour { - networkBehaviour = GetInternal(this, null) as T; + networkBehaviour = GetInternal(this, networkManager) as T; return networkBehaviour != null; } diff --git a/Runtime/Spawning/NetworkSpawnManager.cs b/Runtime/Spawning/NetworkSpawnManager.cs index 45b3dff..482b603 100644 --- a/Runtime/Spawning/NetworkSpawnManager.cs +++ b/Runtime/Spawning/NetworkSpawnManager.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text; using UnityEngine; namespace Unity.Netcode @@ -13,6 +14,8 @@ namespace Unity.Netcode // Stores the objects that need to be shown at end-of-frame internal Dictionary> ObjectsToShowToClient = new Dictionary>(); + internal Dictionary> ClientsToShowObject = new Dictionary>(); + /// /// The currently spawned objects /// @@ -40,6 +43,105 @@ namespace Unity.Netcode /// private Dictionary m_ObjectToOwnershipTable = new Dictionary(); + /// + /// In distributed authority mode, a list of known spawned player NetworkObject instance is maintained by each client. + /// + public IReadOnlyList 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 m_PlayerObjects = new List(); + + private Dictionary> m_PlayerObjectsTable = new Dictionary>(); + + public List GetConnectedPlayers() + { + return m_PlayerObjectsTable.Keys.ToList(); + } + + /// + /// Adds a player object and updates all other players' observers list + /// + 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) + { + player.Observers.Add(playerObject.OwnerClientId); + playerObject.Observers.Add(player.OwnerClientId); + } + m_PlayerObjects.Add(playerObject); + if (!m_PlayerObjectsTable.ContainsKey(playerObject.OwnerClientId)) + { + m_PlayerObjectsTable.Add(playerObject.OwnerClientId, new List()); + } + 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, true); + } + // Now update the associated NetworkClient's player object + NetworkManager.ConnectionManager.ConnectedClients[playerObject.OwnerClientId].AssignPlayerObject(ref playerObject); + AddPlayerObject(playerObject); + } + + /// + /// Removes a player object and updates all other players' observers list + /// + private void RemovePlayerObject(NetworkObject playerObject, bool keepObservers = 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 we want to keep the observers, then exit early + if (keepObservers) + { + return; + } + + foreach (var player in m_PlayerObjects) + { + player.Observers.Remove(playerObject.OwnerClientId); + } + } + internal void MarkObjectForShowingTo(NetworkObject networkObject, ulong clientId) { if (!ObjectsToShowToClient.ContainsKey(clientId)) @@ -47,11 +149,30 @@ namespace Unity.Netcode ObjectsToShowToClient.Add(clientId, new List()); } ObjectsToShowToClient[clientId].Add(networkObject); + if (NetworkManager.DistributedAuthorityMode) + { + if (!ClientsToShowObject.ContainsKey(networkObject)) + { + ClientsToShowObject.Add(networkObject, new List()); + } + 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)) { @@ -95,6 +216,11 @@ namespace Unity.Netcode } else { + // If we already had this owner in our table then just exit + if (NetworkManager.DistributedAuthorityMode && previousOwner == newOwner) + { + return; + } m_ObjectToOwnershipTable[networkObject.NetworkObjectId] = newOwner; } } @@ -142,7 +268,7 @@ namespace Unity.Netcode { OwnershipToObjectsTable[previousOwner].Remove(networkObject.NetworkObjectId); } - else if (NetworkManager.LogLevel == LogLevel.Developer) + else if (NetworkManager.LogLevel == LogLevel.Developer && previousOwner == newOwner) { NetworkLog.LogWarning($"Setting ownership twice? Client-ID {previousOwner} already owns NetworkObject ID {networkObject.NetworkObjectId}!"); } @@ -182,7 +308,8 @@ namespace Unity.Netcode m_NetworkObjectIdCounter++; - return m_NetworkObjectIdCounter; + // DANGO-TODO: Need a more robust solution here. + return m_NetworkObjectIdCounter + (NetworkManager.LocalClientId * 10000); } /// @@ -194,6 +321,19 @@ namespace Unity.Netcode return GetPlayerNetworkObject(NetworkManager.LocalClientId); } + /// + /// Returns all instances assigned to the client identifier + /// + /// the client identifier of the player + /// A list of instances (if more than one are assigned) + public List GetPlayerNetworkObjects(ulong clientId) + { + if (m_PlayerObjectsTable.ContainsKey(clientId)) + { + return m_PlayerObjectsTable[clientId]; + } + return null; + } /// /// Returns the player object with a given clientId or null if one does not exist. This is only valid server side. @@ -202,14 +342,23 @@ namespace Unity.Netcode /// The player object with a given clientId or null if one does not exist public NetworkObject GetPlayerNetworkObject(ulong clientId) { - if (!NetworkManager.IsServer && NetworkManager.LocalClientId != clientId) + if (!NetworkManager.DistributedAuthorityMode) { - throw new NotServerException("Only the server can find player objects from other clients."); + 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; + } } - - if (TryGetNetworkClient(clientId, out NetworkClient networkClient)) + else { - return networkClient.PlayerObject; + if (m_PlayerObjectsTable.ContainsKey(clientId)) + { + return m_PlayerObjectsTable[clientId].First(); + } } return null; @@ -240,14 +389,86 @@ namespace Unity.Netcode return false; } - internal void RemoveOwnership(NetworkObject networkObject) + protected virtual void InternalOnOwnershipChanged(ulong perviousOwner, ulong newOwner) { - ChangeOwnership(networkObject, NetworkManager.ServerClientId); + } - internal void ChangeOwnership(NetworkObject networkObject, ulong clientId) + internal void RemoveOwnership(NetworkObject networkObject) { - if (!NetworkManager.IsServer) + if (NetworkManager.DistributedAuthorityMode && !NetworkManager.ShutdownInProgress) + { + if (networkObject.IsOwnershipDistributable || networkObject.IsOwnershipTransferable) + { + if (networkObject.IsOwner || NetworkManager.DAHost) + { + NetworkLog.LogWarning("DANGO-TODO: Determine if removing ownership should make the CMB Service redistribute ownership or if this just isn't a valid thing in DAMode."); + return; + } + else + { + NetworkLog.LogError($"Only the owner is allowed to remove ownership in distributed authority mode!"); + return; + } + } + else + { + if (!NetworkManager.DAHost) + { + Debug.LogError($"Only {nameof(NetworkObject)}s with {nameof(NetworkObject.IsOwnershipDistributable)} or {nameof(NetworkObject.IsOwnershipTransferable)} set can perform ownership changes!"); + } + return; + } + } + ChangeOwnership(networkObject, NetworkManager.ServerClientId, true); + } + + internal void ChangeOwnership(NetworkObject networkObject, ulong clientId, bool isAuthorized, bool isRequestApproval = false) + { + if (NetworkManager.DistributedAuthorityMode) + { + // 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"); } @@ -257,7 +478,19 @@ namespace Unity.Netcode throw new SpawnStateException("Object is not spawned"); } - var previous = networkObject.OwnerClientId; + + 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; + } + + // 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; @@ -267,24 +500,67 @@ namespace Unity.Netcode networkObject.MarkVariablesDirty(true); NetworkManager.BehaviourUpdater.AddForUpdate(networkObject); - // Server adds entries for all client ownership + // 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(); - var message = new ChangeOwnershipMessage + var size = 0; + if (NetworkManager.DistributedAuthorityMode) { - NetworkObjectId = networkObject.NetworkObjectId, - OwnerClientId = networkObject.OwnerClientId - }; - - foreach (var client in NetworkManager.ConnectedClients) - { - if (networkObject.IsNetworkVisibleTo(client.Value.ClientId)) + var message = new ChangeOwnershipMessage { - var size = NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, client.Value.ClientId); - NetworkManager.NetworkMetrics.TrackOwnershipChangeSent(client.Key, networkObject, size); + 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(); + } + + 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) + { + 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 (networkObject.IsNetworkVisibleTo(client.Value.ClientId)) + { + size = NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, client.Value.ClientId); + NetworkManager.NetworkMetrics.TrackOwnershipChangeSent(client.Key, networkObject, size); + } } } @@ -292,7 +568,7 @@ namespace Unity.Netcode /// !!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 - networkObject.InvokeOwnershipChanged(previous, clientId); + networkObject.InvokeOwnershipChanged(networkObject.PreviousOwnerId, clientId); } internal bool HasPrefab(NetworkObject.SceneObject sceneObject) @@ -367,7 +643,9 @@ namespace Unity.Netcode return null; } - if (!NetworkManager.IsServer) + ownerClientId = NetworkManager.DistributedAuthorityMode ? NetworkManager.LocalClientId : NetworkManager.ServerClientId; + // 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; @@ -394,10 +672,10 @@ namespace Unity.Netcode /// 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 spawns the ovveride and server spawns the original prefab unless forceOverride is set to true where both server or host will spawn the override. - if (forceOverride || NetworkManager.IsHost) + // In distributed authority mode, we alaways get the override + if (forceOverride || NetworkManager.IsHost || NetworkManager.DistributedAuthorityMode) { networkObject = GetNetworkObjectToSpawn(networkPrefab.GlobalObjectIdHash, ownerClientId, position, rotation); } @@ -509,7 +787,6 @@ namespace Unity.Netcode else // Get the in-scene placed NetworkObject { networkObject = NetworkManager.SceneManager.GetSceneRelativeInSceneNetworkObject(globalObjectIdHash, sceneObject.NetworkSceneHandle); - if (networkObject == null) { if (NetworkLog.CurrentLogLevel <= LogLevel.Error) @@ -530,6 +807,8 @@ namespace Unity.Netcode { networkObject.DestroyWithScene = sceneObject.DestroyWithScene; networkObject.NetworkSceneHandle = sceneObject.NetworkSceneHandle; + networkObject.DontDestroyWithOwner = sceneObject.DontDestroyWithOwner; + networkObject.Ownership = (NetworkObject.OwnershipStatus)sceneObject.OwnershipFlags; // 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 @@ -604,7 +883,19 @@ namespace Unity.Netcode return networkObject; } - // Ran on both server and client + /// + /// Invoked from: + /// - ConnectionManager after instantiating a player prefab when running in client-server. + /// - NetworkObject when spawning a newly instantiated NetworkObject for the first time. + /// - NetworkSceneManager after a server/session-owner has loaded a scene to locally spawn the newly instantiated in-scene placed NetworkObjects. + /// - NetworkSpawnManager when spawning any already loaded in-scene placed NetworkObjects (client-server or session owner). + /// + /// Client-Server: + /// Server is the only instance that invokes this method. + /// + /// Distributed Authority: + /// DAHost client and standard DA clients invoke this method. + /// internal void SpawnNetworkObjectLocally(NetworkObject networkObject, ulong networkId, bool sceneObject, bool playerObject, ulong ownerClientId, bool destroyWithScene) { if (networkObject == null) @@ -614,7 +905,8 @@ namespace Unity.Netcode if (networkObject.IsSpawned) { - throw new SpawnStateException("Object is already spawned"); + Debug.LogError($"{networkObject.name} is already spawned!"); + return; } if (!sceneObject) @@ -626,10 +918,51 @@ namespace Unity.Netcode } } + // DANGO-TODO: It would be nice to allow users to specify which clients are observers prior to spawning + // For now, this is the best place I could find to add all connected clients as observers for newly + // instantiated and spawned NetworkObjects on the authoritative side. + if (NetworkManager.DistributedAuthorityMode) + { + if (NetworkManager.NetworkConfig.EnableSceneManagement && sceneObject) + { + networkObject.SceneOriginHandle = networkObject.gameObject.scene.handle; + networkObject.NetworkSceneHandle = NetworkManager.SceneManager.ClientSceneHandleToServerSceneHandle[networkObject.gameObject.scene.handle]; + } + + // Always add the owner/authority even if SpawnWithObservers is false + // (authority should not take into consideration networkObject.CheckObjectVisibility when SpawnWithObservers is false) + if (!networkObject.SpawnWithObservers) + { + networkObject.Observers.Add(ownerClientId); + } + else + { + foreach (var clientId in NetworkManager.ConnectedClientsIds) + { + // If SpawnWithObservers is enabled, then authority does take networkObject.CheckObjectVisibility into consideration + if (networkObject.CheckObjectVisibility != null && !networkObject.CheckObjectVisibility.Invoke(clientId)) + { + continue; + } + networkObject.Observers.Add(clientId); + } + + // Sanity check to make sure the owner is always included + // Itentionally checking as opposed to just assigning in order to generate notification. + if (!networkObject.Observers.Contains(ownerClientId)) + { + Debug.LogError($"Client-{ownerClientId} is the owner of {networkObject.name} but is not an observer! Adding owner, but there is a bug in observer synchronization!"); + networkObject.Observers.Add(ownerClientId); + } + } + } SpawnNetworkObjectLocallyCommon(networkObject, networkId, sceneObject, playerObject, ownerClientId, destroyWithScene); } - // Ran on both server and client + /// + /// This is only invoked to instantiate a serialized NetworkObject via + /// + /// internal void SpawnNetworkObjectLocally(NetworkObject networkObject, in NetworkObject.SceneObject sceneObject, bool destroyWithScene) { if (networkObject == null) @@ -639,7 +972,7 @@ namespace Unity.Netcode if (networkObject.IsSpawned) { - throw new SpawnStateException("Object is already spawned"); + throw new SpawnStateException($"[{networkObject.name}] Object-{networkObject.NetworkObjectId} is already spawned!"); } SpawnNetworkObjectLocallyCommon(networkObject, sceneObject.NetworkObjectId, sceneObject.IsSceneObject, sceneObject.IsPlayerObject, sceneObject.OwnerClientId, destroyWithScene); @@ -649,7 +982,7 @@ namespace Unity.Netcode { if (SpawnedObjects.ContainsKey(networkId)) { - Debug.LogWarning($"Trying to spawn {nameof(NetworkObject.NetworkObjectId)} {networkId} that already exists!"); + Debug.LogWarning($"[{NetworkManager.name}] Trying to spawn {networkObject.name} with a {nameof(NetworkObject.NetworkObjectId)} of {networkId} but it is already in the spawned list!"); return; } @@ -674,49 +1007,34 @@ namespace Unity.Netcode networkObject.DestroyWithScene = sceneObject || destroyWithScene; - networkObject.OwnerClientId = ownerClientId; - networkObject.IsPlayerObject = playerObject; + networkObject.OwnerClientId = ownerClientId; + + // When spawned, previous owner is always the first assigned owner + networkObject.PreviousOwnerId = ownerClientId; + + // If this the player and the client is the owner, then lock ownership by default + if (NetworkManager.DistributedAuthorityMode && NetworkManager.LocalClientId == ownerClientId && playerObject) + { + networkObject.SetOwnershipLock(); + } SpawnedObjects.Add(networkObject.NetworkObjectId, networkObject); SpawnedObjectsList.Add(networkObject); - if (NetworkManager.IsServer) - { - if (playerObject) - { - // If there was an already existing player object for this player, then mark it as no longer - // a player object. - if (NetworkManager.ConnectedClients[ownerClientId].PlayerObject != null) - { - NetworkManager.ConnectedClients[ownerClientId].PlayerObject.IsPlayerObject = false; - } - NetworkManager.ConnectedClients[ownerClientId].PlayerObject = networkObject; - } - } - else if (ownerClientId == NetworkManager.LocalClientId) - { - if (playerObject) - { - // If there was an already existing player object for this player, then mark it as no longer a player object. - if (NetworkManager.LocalClient.PlayerObject != null) - { - NetworkManager.LocalClient.PlayerObject.IsPlayerObject = false; - } - NetworkManager.LocalClient.PlayerObject = networkObject; - } - } - - // If we are the server and should spawn with observers - if (NetworkManager.IsServer && networkObject.SpawnWithObservers) + // If we are not running in DA mode, this is the server, and the NetworkObject has SpawnWithObservers set, + // then add all connected clients as observers + if (!NetworkManager.DistributedAuthorityMode && NetworkManager.IsServer && networkObject.SpawnWithObservers) { // Add client observers - for (int i = 0; i < NetworkManager.ConnectedClientsList.Count; i++) + for (int i = 0; i < NetworkManager.ConnectedClientsIds.Count; i++) { - if (networkObject.CheckObjectVisibility == null || networkObject.CheckObjectVisibility(NetworkManager.ConnectedClientsList[i].ClientId)) + // If CheckObjectVisibility has a callback, then allow that method determine who the observers are. + if (networkObject.CheckObjectVisibility != null && !networkObject.CheckObjectVisibility(NetworkManager.ConnectedClientsIds[i])) { - networkObject.Observers.Add(NetworkManager.ConnectedClientsList[i].ClientId); + continue; } + networkObject.Observers.Add(NetworkManager.ConnectedClientsIds[i]); } } @@ -745,6 +1063,11 @@ namespace Unity.Netcode networkObject.SubscribeToActiveSceneForSynch(); } + if (networkObject.IsPlayerObject) + { + UpdateNetworkClientPlayer(networkObject); + } + // If we are an in-scene placed NetworkObject and our InScenePlacedSourceGlobalObjectIdHash is set // then assign this to the PrefabGlobalObjectIdHash if (networkObject.IsSceneObject.Value && networkObject.InScenePlacedSourceGlobalObjectIdHash != 0) @@ -756,19 +1079,53 @@ namespace Unity.Netcode internal void SendSpawnCallForObject(ulong clientId, NetworkObject networkObject) { // If we are a host and sending to the host's client id, then we can skip sending ourselves the spawn message. - if (clientId == NetworkManager.ServerClientId) + var updateObservers = NetworkManager.DistributedAuthorityMode && networkObject.SpawnWithObservers; + + // Only skip if distributed authority mode is not enabled + if (clientId == NetworkManager.ServerClientId && !NetworkManager.DistributedAuthorityMode) { return; } var message = new CreateObjectMessage { - ObjectInfo = networkObject.GetMessageSceneObject(clientId) + ObjectInfo = networkObject.GetMessageSceneObject(clientId, NetworkManager.DistributedAuthorityMode), + IncludesSerializedObject = true, + UpdateObservers = NetworkManager.DistributedAuthorityMode, + ObserverIds = NetworkManager.DistributedAuthorityMode ? networkObject.Observers.ToArray() : null, }; var size = NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, clientId); NetworkManager.NetworkMetrics.TrackObjectSpawnSent(clientId, networkObject, size); } + /// + /// Only used to update object visibility/observers. + /// ** Clients are the only instances that use this method ** + /// + internal void SendSpawnCallForObserverUpdate(ulong[] newObservers, NetworkObject networkObject) + { + if (!NetworkManager.DistributedAuthorityMode) + { + throw new Exception("[SendSpawnCallForObserverUpdate] Invoking a distributed authority only method when distributed authority is not enabled!"); + } + + var message = new CreateObjectMessage + { + ObjectInfo = networkObject.GetMessageSceneObject(), + ObserverIds = networkObject.Observers.ToArray(), + NewObserverIds = newObservers.ToArray(), + IncludesSerializedObject = true, + UpdateObservers = true, + UpdateNewObservers = true, + }; + var size = NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, NetworkManager.ServerClientId); + foreach (var clientId in newObservers) + { + // TODO: We might want to track observer update sent as well? + NetworkManager.NetworkMetrics.TrackObjectSpawnSent(clientId, networkObject, size); + } + } + internal ulong? GetSpawnParentId(NetworkObject networkObject) { NetworkObject parentNetworkObject = null; @@ -786,19 +1143,29 @@ namespace Unity.Netcode return parentNetworkObject.NetworkObjectId; } - internal void DespawnObject(NetworkObject networkObject, bool destroyObject = false) + internal void DespawnObject(NetworkObject networkObject, bool destroyObject = false, bool playerDisconnect = false) { if (!networkObject.IsSpawned) { - throw new SpawnStateException("Object is not spawned"); + NetworkLog.LogErrorServer("Object is not spawned!"); + return; } - if (!NetworkManager.IsServer) + if (!NetworkManager.IsServer && !NetworkManager.DistributedAuthorityMode) { - throw new NotServerException("Only server can despawn objects"); + NetworkLog.LogErrorServer("Only server can despawn objects"); + return; } - OnDespawnObject(networkObject, destroyObject); + if (NetworkManager.DistributedAuthorityMode && networkObject.OwnerClientId != NetworkManager.LocalClientId) + { + if (!NetworkManager.DAHost || NetworkManager.DAHost && !playerDisconnect) + { + NetworkLog.LogErrorServer($"In distributed authority mode, only the owner of the NetworkObject can despawn it! Local Client is ({NetworkManager.LocalClientId}) while the owner is ({networkObject.OwnerClientId})"); + return; + } + } + OnDespawnObject(networkObject, destroyObject, playerDisconnect); } // Makes scene objects ready to be reused @@ -913,11 +1280,15 @@ namespace Unity.Netcode { if (NetworkManager.PrefabHandler.ContainsHandler(networkObjects[i])) { - NetworkManager.PrefabHandler.HandleNetworkPrefabDestroy(networkObjects[i]); if (SpawnedObjects.ContainsKey(networkObjects[i].NetworkObjectId)) { + // This method invokes HandleNetworkPrefabDestroy, we only want to handle this once. OnDespawnObject(networkObjects[i], false); } + else // If not spawned, then just invoke the handler + { + NetworkManager.PrefabHandler.HandleNetworkPrefabDestroy(networkObjects[i]); + } } else { @@ -935,27 +1306,29 @@ namespace Unity.Netcode #else var networkObjects = UnityEngine.Object.FindObjectsOfType(); #endif - var networkObjectsToSpawn = new List(); - + var isConnectedCMBService = NetworkManager.CMBServiceConnection; for (int i = 0; i < networkObjects.Length; i++) { if (networkObjects[i].NetworkManager == NetworkManager) { + // This used to be two loops. + // The first added all NetworkObjects to a list and the second spawned all NetworkObjects in the list. + // Now, a parent will set its children's IsSceneObject value when spawned, so we check for null or for true. if (networkObjects[i].IsSceneObject == null || (networkObjects[i].IsSceneObject.HasValue && networkObjects[i].IsSceneObject.Value)) { - networkObjectsToSpawn.Add(networkObjects[i]); + var ownerId = networkObjects[i].OwnerClientId; + if (NetworkManager.DistributedAuthorityMode) + { + ownerId = NetworkManager.LocalClientId; + } + + SpawnNetworkObjectLocally(networkObjects[i], GetNetworkObjectId(), true, false, ownerId, true); } } } - - - foreach (var networkObject in networkObjectsToSpawn) - { - SpawnNetworkObjectLocally(networkObject, GetNetworkObjectId(), true, false, networkObject.OwnerClientId, true); - } } - internal void OnDespawnObject(NetworkObject networkObject, bool destroyGameObject) + internal void OnDespawnObject(NetworkObject networkObject, bool destroyGameObject, bool modeDestroy = false) { if (NetworkManager == null) { @@ -972,43 +1345,64 @@ namespace Unity.Netcode // Removal of spawned object if (!SpawnedObjects.ContainsKey(networkObject.NetworkObjectId)) { - Debug.LogWarning($"Trying to destroy object {networkObject.NetworkObjectId} but it doesn't seem to exist anymore!"); + if (!NetworkManager.ShutdownInProgress) + { + Debug.LogWarning($"Trying to destroy object {networkObject.NetworkObjectId} but it doesn't seem to exist anymore!"); + } return; } // If we are shutting down the NetworkManager, then ignore resetting the parent // and only attempt to remove the child's parent on the server-side - if (!NetworkManager.ShutdownInProgress && NetworkManager.IsServer) + var distributedAuthority = NetworkManager.DistributedAuthorityMode; + if (!NetworkManager.ShutdownInProgress && (NetworkManager.IsServer || distributedAuthority)) { - // Move child NetworkObjects to the root when parent NetworkObject is destroyed - foreach (var spawnedNetObj in SpawnedObjectsList) - { - var latestParent = spawnedNetObj.GetNetworkParenting(); - if (latestParent.HasValue && latestParent.Value == networkObject.NetworkObjectId) - { - // Try to remove the parent using the cached WorldPositioNStays value - // Note: WorldPositionStays will still default to true if this was an - // in-scene placed NetworkObject and parenting was predefined in the - // scene via the editor. - if (!spawnedNetObj.TryRemoveParentCachedWorldPositionStays()) - { - if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) - { - NetworkLog.LogError($"{nameof(NetworkObject)} #{spawnedNetObj.NetworkObjectId} could not be moved to the root when its parent {nameof(NetworkObject)} #{networkObject.NetworkObjectId} was being destroyed"); - } - } + // Get all child NetworkObjects + var objectsToRemoveParent = networkObject.GetComponentsInChildren(); + // Move child NetworkObjects to the root when parent NetworkObject is destroyed + foreach (var spawnedNetObj in objectsToRemoveParent) + { + if (spawnedNetObj == networkObject) + { + continue; + } + var latestParent = spawnedNetObj.GetNetworkParenting(); + // Only deparent the first generation children of the NetworkObject being spawned. + // Ignore any nested children under first generation children. + if (latestParent.HasValue && latestParent.Value != networkObject.NetworkObjectId) + { + continue; + } + // For mixed authority hierarchies, if the parent is despawned then any removal of children + // is considered "authority approved". If we don't have authority over the object and we are + // in distributed authority mode, then set the AuthorityAppliedParenting flag. + spawnedNetObj.AuthorityAppliedParenting = distributedAuthority && !spawnedNetObj.HasAuthority; + + // Try to remove the parent using the cached WorldPositionStays value + // Note: WorldPositionStays will still default to true if this was an + // in-scene placed NetworkObject and parenting was predefined in the + // scene via the editor. + if (!spawnedNetObj.TryRemoveParentCachedWorldPositionStays()) + { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) { - NetworkLog.LogWarning($"{nameof(NetworkObject)} #{spawnedNetObj.NetworkObjectId} moved to the root because its parent {nameof(NetworkObject)} #{networkObject.NetworkObjectId} is destroyed"); + NetworkLog.LogError($"{nameof(NetworkObject)} #{spawnedNetObj.NetworkObjectId} could not be moved to the root when its parent {nameof(NetworkObject)} #{networkObject.NetworkObjectId} was being destroyed"); } } + else + if (NetworkLog.CurrentLogLevel <= LogLevel.Developer) + { + NetworkLog.LogWarning($"{nameof(NetworkObject)} #{spawnedNetObj.NetworkObjectId} moved to the root because its parent {nameof(NetworkObject)} #{networkObject.NetworkObjectId} is destroyed"); + } } } networkObject.InvokeBehaviourNetworkDespawn(); - if (NetworkManager != null && NetworkManager.IsServer) + if (NetworkManager != null && ((NetworkManager.IsServer && (!distributedAuthority || + (distributedAuthority && modeDestroy))) || + (distributedAuthority && networkObject.OwnerClientId == NetworkManager.LocalClientId))) { if (NetworkManager.NetworkConfig.RecycleNetworkIds) { @@ -1018,36 +1412,54 @@ namespace Unity.Netcode ReleaseTime = NetworkManager.RealTimeProvider.UnscaledTime }); } + m_TargetClientIds.Clear(); - if (networkObject != null) + // If clients are not allowed to spawn locally then go ahead and send the despawn message or if we are in distributed authority mode, we are the server, we own this NetworkObject + // send the despawn message, and as long as we have any remaining clients, then notify of the object being destroy. + if (NetworkManager.IsServer && NetworkManager.ConnectedClientsList.Count > 0 && (!distributedAuthority || + (NetworkManager.DAHost && distributedAuthority && + (networkObject.OwnerClientId == NetworkManager.LocalClientId || modeDestroy)))) { - // As long as we have any remaining clients, then notify of the object being destroy. - if (NetworkManager.ConnectedClientsList.Count > 0) + // We keep only the client for which the object is visible + // as the other clients have them already despawned + foreach (var clientId in NetworkManager.ConnectedClientsIds) { - m_TargetClientIds.Clear(); - - // We keep only the client for which the object is visible - // as the other clients have them already despawned - foreach (var clientId in NetworkManager.ConnectedClientsIds) + if ((distributedAuthority && clientId == networkObject.OwnerClientId) || clientId == NetworkManager.LocalClientId) { - if (networkObject.IsNetworkVisibleTo(clientId)) - { - m_TargetClientIds.Add(clientId); - } + continue; } - - var message = new DestroyObjectMessage + if (networkObject.IsNetworkVisibleTo(clientId)) { - NetworkObjectId = networkObject.NetworkObjectId, - DestroyGameObject = networkObject.IsSceneObject != false ? destroyGameObject : true - }; - var size = NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, m_TargetClientIds); - foreach (var targetClientId in m_TargetClientIds) - { - NetworkManager.NetworkMetrics.TrackObjectDestroySent(targetClientId, networkObject, size); + m_TargetClientIds.Add(clientId); } } } + else // DANGO-TODO: If we are not the server, distributed authority mode is enabled, and we are the owner then inform the DAHost to despawn the NetworkObject + if (!NetworkManager.IsServer && distributedAuthority && networkObject.OwnerClientId == NetworkManager.LocalClientId) + { + // DANGO-TODO: If a shutdown is not in progress or a shutdown is in progress and we can destroy with the owner then notify the DAHost + if (!NetworkManager.ShutdownInProgress || (NetworkManager.ShutdownInProgress && !networkObject.DontDestroyWithOwner)) + { + m_TargetClientIds.Add(NetworkManager.ServerClientId); + } + } + + if (m_TargetClientIds.Count > 0 && !NetworkManager.ShutdownInProgress) + { + var message = new DestroyObjectMessage + { + NetworkObjectId = networkObject.NetworkObjectId, + DeferredDespawnTick = networkObject.DeferredDespawnTick, + DestroyGameObject = networkObject.IsSceneObject != false ? destroyGameObject : true, + IsTargetedDestroy = false, + IsDistributedAuthority = distributedAuthority, + }; + foreach (var clientId in m_TargetClientIds) + { + var size = NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, clientId); + NetworkManager.NetworkMetrics.TrackObjectDestroySent(clientId, networkObject, size); + } + } } networkObject.IsSpawned = false; @@ -1057,6 +1469,25 @@ namespace Unity.Netcode SpawnedObjectsList.Remove(networkObject); } + // DANGO-TODO: When we fix the issue with observers not being applied to NetworkObjects, + // (client connect/disconnect) we can remove this hacky way of doing this. + // Basically, when a player disconnects and/or is destroyed they are removed as an observer from all other client + // NetworkOject instances. + if (networkObject.IsPlayerObject && !networkObject.IsOwner && networkObject.OwnerClientId != NetworkManager.LocalClientId) + { + foreach (var netObject in SpawnedObjects) + { + if (netObject.Value.Observers.Contains(networkObject.OwnerClientId)) + { + netObject.Value.Observers.Remove(networkObject.OwnerClientId); + } + } + } + if (networkObject.IsPlayerObject) + { + RemovePlayerObject(networkObject); + } + // Always clear out the observers list when despawned networkObject.Observers.Clear(); @@ -1075,7 +1506,7 @@ namespace Unity.Netcode } /// - /// Updates all spawned for the specified newly connected client + /// Updates all spawned for the specified newly connected client /// Note: if the clientId is the server then it is observable to all spawned 's /// /// @@ -1089,8 +1520,8 @@ namespace Unity.Netcode // If the NetworkObject has no visibility check then prepare to add this client as an observer if (sobj.CheckObjectVisibility == null) { - // If the client is not part of the observers and spawn with observers is enabled on this instance or the clientId is the server - if (sobj.SpawnWithObservers || clientId == NetworkManager.ServerClientId) + // If the client is not part of the observers and spawn with observers is enabled on this instance or the clientId is the server/host/DAHost + if (!sobj.Observers.Contains(clientId) && (sobj.SpawnWithObservers || clientId == NetworkManager.ServerClientId)) { sobj.Observers.Add(clientId); } @@ -1115,6 +1546,20 @@ namespace Unity.Netcode /// internal void HandleNetworkObjectShow() { + // In distributed authority mode, we send a single message that is broadcasted to all clients + // that will be shown the object (i.e. 1 message to service that then broadcasts that to the + // targeted clients). When using a DAHost, we skip this and send like we do in client-server + if (NetworkManager.DistributedAuthorityMode && !NetworkManager.DAHost) + { + foreach (var entry in ClientsToShowObject) + { + SendSpawnCallForObserverUpdate(entry.Value.ToArray(), entry.Key); + } + ClientsToShowObject.Clear(); + ObjectsToShowToClient.Clear(); + return; + } + // Handle NetworkObjects to show foreach (var client in ObjectsToShowToClient) { @@ -1131,5 +1576,264 @@ namespace Unity.Netcode { NetworkManager = networkManager; } + + /// + /// DANGO-TODO: Until we have the CMB Server end-to-end with all features verified working via integration tests, + /// I am keeping this debug toggle available. (NSS) + /// + internal bool EnableDistributeLogging = false; + + /// + /// Fills the first table passed in with the current distribution of prefab types relative to their owners + /// Fills the second table passed in with the total number of spawned objects of that particular type. + /// The second table allows us to calculate how many objects per client there should be in order to determine + /// how many of that type should be distributed. + /// + /// the table to populate + /// the total number of the specific object type to distribute + internal void GetObjectDistribution(ref Dictionary>> objectByTypeAndOwner, ref Dictionary objectTypeCount) + { + // DANGO-TODO-MVP: Remove this once the service handles object distribution + var onlyIncludeOwnedObjects = NetworkManager.CMBServiceConnection; + + foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList) + { + if (networkObject.IsOwnershipDistributable && !networkObject.IsOwnershipLocked) + { + if (networkObject.transform.parent != null) + { + var parentNetworkObject = networkObject.transform.parent.GetComponent(); + if (parentNetworkObject != null && parentNetworkObject.OwnerClientId == networkObject.OwnerClientId) + { + continue; + } + } + + if (networkObject.IsSceneObject.Value) + { + continue; + } + + if (!objectTypeCount.ContainsKey(networkObject.GlobalObjectIdHash)) + { + objectTypeCount.Add(networkObject.GlobalObjectIdHash, 0); + } + objectTypeCount[networkObject.GlobalObjectIdHash] += 1; + + // DANGO-TODO-MVP: Remove this once the service handles object distribution + if (onlyIncludeOwnedObjects && !networkObject.IsOwner) + { + continue; + } + + // Divide up by prefab type (GlobalObjectIdHash) to get a better distribution of object types + if (!objectByTypeAndOwner.ContainsKey(networkObject.GlobalObjectIdHash)) + { + objectByTypeAndOwner.Add(networkObject.GlobalObjectIdHash, new Dictionary>()); + } + + // Sub-divide each type by owner + if (!objectByTypeAndOwner[networkObject.GlobalObjectIdHash].ContainsKey(networkObject.OwnerClientId)) + { + objectByTypeAndOwner[networkObject.GlobalObjectIdHash].Add(networkObject.OwnerClientId, new List()); + } + + // Add to the client's spawned object list + objectByTypeAndOwner[networkObject.GlobalObjectIdHash][networkObject.OwnerClientId].Add(networkObject); + } + } + } + + internal void DistributeNetworkObjects(ulong clientId) + { + // Distributed authority mode ownership distribution + // DANGO-TODO-MVP: Remove the session owner object distribution check once the service handles object distribution + if (NetworkManager.DistributedAuthorityMode && (NetworkManager.DAHost || NetworkManager.CMBServiceConnection)) + { + // DA-NGO CMB SERVICE NOTES: + // The most basic object distribution should be broken up into a table of spawned object types + // where each type contains a list of each client's owned objects of that type that can be + // distributed. + // The table format: + // [GlobalObjectIdHashValue][ClientId][List of Owned Objects] + var distributedNetworkObjects = new Dictionary>>(); + + // DA-NGO CMB SERVICE NOTES: + // This is optional, but I found it easier to get the total count of spawned objects for each prefab + // type contained in the previous table in order to be able to calculate the targeted object distribution + // count of that type per client. + var objectTypeCount = new Dictionary(); + + // Get all spawned objects by type and then by client owner that are spawned and can be distributed + GetObjectDistribution(ref distributedNetworkObjects, ref objectTypeCount); + + var clientCount = NetworkManager.ConnectedClientsIds.Count; + + // Cycle through each prefab type + foreach (var objectTypeEntry in distributedNetworkObjects) + { + // Calculate the number of objects that should be distributed amongst the clients + var totalObjectsToDistribute = objectTypeCount[objectTypeEntry.Key]; + var objPerClientF = totalObjectsToDistribute * (1.0f / clientCount); + var floorValue = (int)Math.Floor(objPerClientF); + var fractional = objPerClientF - floorValue; + var objPerClient = 0; + if (fractional >= 0.556f) + { + objPerClient = (int)Math.Round(totalObjectsToDistribute * (1.0f / clientCount)); + } + else + { + objPerClient = floorValue; + } + + // If the object per client count is zero, then move to the next type. + if (objPerClient <= 0) + { + continue; + } + + // Evenly distribute this object type amongst the clients + foreach (var ownerList in objectTypeEntry.Value) + { + if (ownerList.Value.Count <= 1) + { + continue; + } + + var maxDistributeCount = Mathf.Max(ownerList.Value.Count - objPerClient, 1); + var distributed = 0; + + // For now when we have more players then distributed NetworkObjects that + // a specific client owns, just assign half of the NetworkObjects to the new client + var offsetCount = Mathf.Max((int)Math.Round((float)(ownerList.Value.Count / objPerClient)), 1); + if (EnableDistributeLogging) + { + Debug.Log($"[{objPerClient} of {totalObjectsToDistribute}][Client-{ownerList.Key}] Count: {ownerList.Value.Count} | ObjPerClient: {objPerClient} | maxD: {maxDistributeCount} | Offset: {offsetCount}"); + } + + for (int i = 0; i < ownerList.Value.Count; i++) + { + if ((i % offsetCount) == 0) + { + ChangeOwnership(ownerList.Value[i], clientId, true); + if (EnableDistributeLogging) + { + Debug.Log($"[Client-{ownerList.Key}][NetworkObjectId-{ownerList.Value[i].NetworkObjectId} Distributed to Client-{clientId}"); + } + distributed++; + } + if (distributed == maxDistributeCount) + { + break; + } + } + } + } + + // If EnableDistributeLogging is enabled, log the object type distribution counts per client + if (EnableDistributeLogging) + { + var builder = new StringBuilder(); + distributedNetworkObjects.Clear(); + objectTypeCount.Clear(); + GetObjectDistribution(ref distributedNetworkObjects, ref objectTypeCount); + builder.AppendLine($"Client Relative Distributed Object Count: (distribution follows)"); + // Cycle through each prefab type + foreach (var objectTypeEntry in distributedNetworkObjects) + { + builder.AppendLine($"[GID: {objectTypeEntry.Key} | {objectTypeEntry.Value.First().Value.First().name}][Total Count: {objectTypeCount[objectTypeEntry.Key]}]"); + builder.AppendLine($"[GID: {objectTypeEntry.Key} | {objectTypeEntry.Value.First().Value.First().name}] Distribution:"); + // Evenly distribute this type amongst clients + foreach (var ownerList in objectTypeEntry.Value) + { + builder.AppendLine($"[Client-{ownerList.Key}] Count: {ownerList.Value.Count}"); + } + } + Debug.Log(builder.ToString()); + } + } + } + + internal struct DeferredDespawnObject + { + public int TickToDespawn; + public bool HasDeferredDespawnCheck; + public ulong NetworkObjectId; + } + + internal List DeferredDespawnObjects = new List(); + + /// + /// Adds a deferred despawn entry to be processed + /// + /// associated NetworkObject + /// when to despawn the NetworkObject + /// if true, user script is to be invoked to determine when to despawn + internal void DeferDespawnNetworkObject(ulong networkObjectId, int tickToDespawn, bool hasDeferredDespawnCheck) + { + var deferredDespawnObject = new DeferredDespawnObject() + { + TickToDespawn = tickToDespawn, + HasDeferredDespawnCheck = hasDeferredDespawnCheck, + NetworkObjectId = networkObjectId, + }; + DeferredDespawnObjects.Add(deferredDespawnObject); + } + + /// + /// Processes any deferred despawn entries + /// + internal void DeferredDespawnUpdate(NetworkTime serverTime) + { + // Exit early if there is nothing to process + if (DeferredDespawnObjects.Count == 0) + { + return; + } + var currentTick = serverTime.Tick; + var deferredCallbackObjects = DeferredDespawnObjects.Where((c) => c.HasDeferredDespawnCheck); + var deferredCallbackCount = deferredCallbackObjects.Count(); + for (int i = 0; i < deferredCallbackCount - 1; i++) + { + var deferredObjectEntry = deferredCallbackObjects.ElementAt(i); + var networkObject = SpawnedObjects[deferredObjectEntry.NetworkObjectId]; + // Double check to make sure user did not remove the callback + if (networkObject.OnDeferredDespawnComplete != null) + { + // If the user callback returns true, then we despawn it this tick + if (networkObject.OnDeferredDespawnComplete.Invoke()) + { + deferredObjectEntry.TickToDespawn = currentTick; + } + else + { + // If the user callback does not verify the NetworkObject can be despawned, + // continue setting this value in the event user script adjusts it. + deferredObjectEntry.TickToDespawn = networkObject.DeferredDespawnTick; + } + } + else + { + // If it was removed, then in case it is being left to defer naturally exclude it + // from the next query. + deferredObjectEntry.HasDeferredDespawnCheck = false; + } + } + + var despawnObjects = DeferredDespawnObjects.Where((c) => c.TickToDespawn < currentTick).ToList(); + foreach (var deferredObjectEntry in despawnObjects) + { + if (!SpawnedObjects.ContainsKey(deferredObjectEntry.NetworkObjectId)) + { + DeferredDespawnObjects.Remove(deferredObjectEntry); + continue; + } + var networkObject = SpawnedObjects[deferredObjectEntry.NetworkObjectId]; + // Local instance despawns the instance + OnDespawnObject(networkObject, true); + DeferredDespawnObjects.Remove(deferredObjectEntry); + } + } } } diff --git a/Runtime/Timing/IRealTimeProvider.cs b/Runtime/Timing/IRealTimeProvider.cs index 07740c8..e6a32af 100644 --- a/Runtime/Timing/IRealTimeProvider.cs +++ b/Runtime/Timing/IRealTimeProvider.cs @@ -6,5 +6,6 @@ namespace Unity.Netcode float UnscaledTime { get; } float UnscaledDeltaTime { get; } float DeltaTime { get; } + float FixedDeltaTime { get; } } } diff --git a/Runtime/Timing/NetworkTime.cs b/Runtime/Timing/NetworkTime.cs index 7af210b..71e3349 100644 --- a/Runtime/Timing/NetworkTime.cs +++ b/Runtime/Timing/NetworkTime.cs @@ -113,9 +113,9 @@ namespace Unity.Netcode /// /// The number of ticks ago we're querying the time /// - public NetworkTime TimeTicksAgo(int ticks) + public NetworkTime TimeTicksAgo(int ticks, float offset = 0.0f) { - return this - new NetworkTime(TickRate, ticks); + return this - new NetworkTime(TickRate, ticks, offset); } private void UpdateCache() diff --git a/Runtime/Timing/RealTimeProvider.cs b/Runtime/Timing/RealTimeProvider.cs index 840180d..51a2044 100644 --- a/Runtime/Timing/RealTimeProvider.cs +++ b/Runtime/Timing/RealTimeProvider.cs @@ -8,5 +8,6 @@ namespace Unity.Netcode public float UnscaledTime => Time.unscaledTime; public float UnscaledDeltaTime => Time.unscaledDeltaTime; public float DeltaTime => Time.deltaTime; + public float FixedDeltaTime => Time.fixedDeltaTime; } } diff --git a/Runtime/Transports/UTP/BatchedSendQueue.cs b/Runtime/Transports/UTP/BatchedSendQueue.cs index b1bd3fa..9e71f36 100644 --- a/Runtime/Transports/UTP/BatchedSendQueue.cs +++ b/Runtime/Transports/UTP/BatchedSendQueue.cs @@ -106,7 +106,11 @@ namespace Unity.Netcode.Transports.UTP { unsafe { +#if UTP_TRANSPORT_2_0_ABOVE + var writer = new DataStreamWriter(m_Data.GetUnsafePtr() + TailIndex, Capacity - TailIndex); +#else var writer = new DataStreamWriter((byte*)m_Data.GetUnsafePtr() + TailIndex, Capacity - TailIndex); +#endif writer.WriteInt(data.Count); @@ -145,7 +149,11 @@ namespace Unity.Netcode.Transports.UTP { unsafe { +#if UTP_TRANSPORT_2_0_ABOVE + UnsafeUtility.MemMove(m_Data.GetUnsafePtr(), m_Data.GetUnsafePtr() + HeadIndex, Length); +#else UnsafeUtility.MemMove(m_Data.GetUnsafePtr(), (byte*)m_Data.GetUnsafePtr() + HeadIndex, Length); +#endif } TailIndex = Length; @@ -231,7 +239,11 @@ namespace Unity.Netcode.Transports.UTP if (bytesToWrite > softMaxBytes && bytesToWrite <= writer.Capacity) { writer.WriteInt(messageLength); +#if UTP_TRANSPORT_2_0_ABOVE + WriteBytes(ref writer, m_Data.GetUnsafePtr() + reader.GetBytesRead(), messageLength); +#else WriteBytes(ref writer, (byte*)m_Data.GetUnsafePtr() + reader.GetBytesRead(), messageLength); +#endif return bytesToWrite; } @@ -248,7 +260,11 @@ namespace Unity.Netcode.Transports.UTP if (bytesWritten + bytesToWrite <= softMaxBytes) { writer.WriteInt(messageLength); +#if UTP_TRANSPORT_2_0_ABOVE + WriteBytes(ref writer, m_Data.GetUnsafePtr() + reader.GetBytesRead(), messageLength); +#else WriteBytes(ref writer, (byte*)m_Data.GetUnsafePtr() + reader.GetBytesRead(), messageLength); +#endif readerOffset += bytesToWrite; bytesWritten += bytesToWrite; @@ -292,7 +308,11 @@ namespace Unity.Netcode.Transports.UTP unsafe { +#if UTP_TRANSPORT_2_0_ABOVE + WriteBytes(ref writer, m_Data.GetUnsafePtr() + HeadIndex, copyLength); +#else WriteBytes(ref writer, (byte*)m_Data.GetUnsafePtr() + HeadIndex, copyLength); +#endif } return copyLength; diff --git a/TestHelpers/Runtime/IntegrationTestSceneHandler.cs b/TestHelpers/Runtime/IntegrationTestSceneHandler.cs index d979c74..b414bcd 100644 --- a/TestHelpers/Runtime/IntegrationTestSceneHandler.cs +++ b/TestHelpers/Runtime/IntegrationTestSceneHandler.cs @@ -23,6 +23,8 @@ namespace Unity.Netcode.TestHelpers.Runtime public Scene Scene; } + public bool IsIntegrationTest() { return true; } + internal static Dictionary>> SceneNameToSceneHandles = new Dictionary>>(); // All IntegrationTestSceneHandler instances register their associated NetworkManager @@ -165,13 +167,30 @@ namespace Unity.Netcode.TestHelpers.Runtime foreach (var sobj in inSceneNetworkObjects) { - if (sobj.NetworkManagerOwner != networkManager) + ProcessInSceneObject(sobj, networkManager); + } + } + + /// + /// Assures to apply an ObjectNameIdentifier to all children + /// + private static void ProcessInSceneObject(NetworkObject networkObject, NetworkManager networkManager) + { + if (networkObject.NetworkManagerOwner != networkManager) + { + networkObject.NetworkManagerOwner = networkManager; + } + if (networkObject.GetComponent() == null) + { + networkObject.gameObject.AddComponent(); + var networkObjects = networkObject.gameObject.GetComponentsInChildren(); + foreach (var child in networkObjects) { - sobj.NetworkManagerOwner = networkManager; - } - if (sobj.GetComponent() == null && sobj.GetComponentInChildren() == null) - { - sobj.gameObject.AddComponent(); + if (child == networkObject) + { + continue; + } + ProcessInSceneObject(child, networkManager); } } } diff --git a/TestHelpers/Runtime/IntegrationTestWithApproximation.cs b/TestHelpers/Runtime/IntegrationTestWithApproximation.cs index 462fd74..54f546b 100644 --- a/TestHelpers/Runtime/IntegrationTestWithApproximation.cs +++ b/TestHelpers/Runtime/IntegrationTestWithApproximation.cs @@ -1,12 +1,24 @@ +using System; using System.Runtime.CompilerServices; using UnityEngine; +using Random = UnityEngine.Random; namespace Unity.Netcode.TestHelpers.Runtime { public abstract class IntegrationTestWithApproximation : NetcodeIntegrationTest { - private const float k_AproximateDeltaVariance = 0.01f; + private const float k_AproximateDeltaVariance = 0.016f; + + protected string GetVector3Values(ref Vector3 vector3) + { + return $"({vector3.x:F6},{vector3.y:F6},{vector3.z:F6})"; + } + + protected string GetVector3Values(Vector3 vector3) + { + return GetVector3Values(ref vector3); + } protected virtual float GetDeltaVarianceThreshold() { @@ -40,17 +52,17 @@ namespace Unity.Netcode.TestHelpers.Runtime protected bool Approximately(Vector2 a, Vector2 b) { var deltaVariance = GetDeltaVarianceThreshold(); - return Mathf.Abs(a.x - b.x) <= deltaVariance && - Mathf.Abs(a.y - b.y) <= deltaVariance; + return Math.Round(Mathf.Abs(a.x - b.x), 2) <= deltaVariance && + Math.Round(Mathf.Abs(a.y - b.y), 2) <= deltaVariance; } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected bool Approximately(Vector3 a, Vector3 b) { var deltaVariance = GetDeltaVarianceThreshold(); - return Mathf.Abs(a.x - b.x) <= deltaVariance && - Mathf.Abs(a.y - b.y) <= deltaVariance && - Mathf.Abs(a.z - b.z) <= deltaVariance; + return Math.Round(Mathf.Abs(a.x - b.x), 2) <= deltaVariance && + Math.Round(Mathf.Abs(a.y - b.y), 2) <= deltaVariance && + Math.Round(Mathf.Abs(a.z - b.z), 2) <= deltaVariance; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -75,5 +87,10 @@ namespace Unity.Netcode.TestHelpers.Runtime return new Vector3(Random.Range(min, max), Random.Range(min, max), Random.Range(min, max)); } + public IntegrationTestWithApproximation(SessionModeTypes sessionModeType) : base(sessionModeType) { } + + public IntegrationTestWithApproximation(HostOrServer hostOrServer) : base(hostOrServer) { } + + public IntegrationTestWithApproximation() : base() { } } } diff --git a/TestHelpers/Runtime/MockTimeProvider.cs b/TestHelpers/Runtime/MockTimeProvider.cs index f97b5dc..daf2709 100644 --- a/TestHelpers/Runtime/MockTimeProvider.cs +++ b/TestHelpers/Runtime/MockTimeProvider.cs @@ -7,6 +7,9 @@ namespace Unity.Netcode.TestHelpers.Runtime public float UnscaledDeltaTime => (float)s_DoubleDelta; public float DeltaTime => (float)s_DoubleDelta; + // DANGO-EXP TODO: Figure out how we want to handle time travel with fixed delta time. + public float FixedDeltaTime => (float)s_DoubleDelta; + public static float StaticRealTimeSinceStartup => (float)s_DoubleRealTime; public static float StaticUnscaledTime => (float)s_DoubleRealTime; public static float StaticUnscaledDeltaTime => (float)s_DoubleDelta; diff --git a/TestHelpers/Runtime/NetcodeIntegrationTest.cs b/TestHelpers/Runtime/NetcodeIntegrationTest.cs index f05ee46..25dd190 100644 --- a/TestHelpers/Runtime/NetcodeIntegrationTest.cs +++ b/TestHelpers/Runtime/NetcodeIntegrationTest.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; +using System.Text; using NUnit.Framework; using Unity.Netcode.RuntimeTests; using Unity.Netcode.Transports.UTP; @@ -29,6 +30,13 @@ namespace Unity.Netcode.TestHelpers.Runtime protected static WaitForSecondsRealtime s_DefaultWaitForTick = new WaitForSecondsRealtime(1.0f / k_DefaultTickRate); public NetcodeLogAssert NetcodeLogAssert; + public enum SceneManagementState + { + SceneManagementEnabled, + SceneManagementDisabled + } + + private StringBuilder m_InternalErrorLog = new StringBuilder(); /// /// Registered list of all NetworkObjects spawned. @@ -112,7 +120,8 @@ namespace Unity.Netcode.TestHelpers.Runtime public enum HostOrServer { Host, - Server + Server, + DAHost } protected GameObject m_PlayerPrefab; @@ -129,6 +138,26 @@ namespace Unity.Netcode.TestHelpers.Runtime protected Dictionary> m_PlayerNetworkObjects = new Dictionary>(); protected bool m_UseHost = true; + protected bool m_DistributedAuthority; + protected SessionModeTypes m_SessionModeType = SessionModeTypes.ClientServer; + + protected virtual bool UseCMBService() + { + return false; + } + + protected virtual SessionModeTypes OnGetSessionmode() + { + return m_SessionModeType; + } + + protected void SetDistributedAuthorityProperties(NetworkManager networkManager) + { + networkManager.NetworkConfig.SessionMode = m_SessionModeType; + networkManager.NetworkConfig.AutoSpawnPlayerPrefabClientSide = m_DistributedAuthority; + networkManager.NetworkConfig.UseCMBService = UseCMBService() && m_DistributedAuthority; + } + protected int m_TargetFrameRate = 60; private NetworkManagerInstatiationMode m_NetworkManagerInstatiationMode; @@ -338,6 +367,7 @@ namespace Unity.Netcode.TestHelpers.Runtime else { yield return StartServerAndClients(); + } } @@ -367,6 +397,7 @@ namespace Unity.Netcode.TestHelpers.Runtime m_PlayerPrefab = new GameObject("Player"); OnPlayerPrefabGameObjectCreated(); NetworkObject networkObject = m_PlayerPrefab.AddComponent(); + networkObject.IsSceneObject = false; // Make it a prefab NetcodeIntegrationTestHelpers.MakeNetworkObjectTestPrefab(networkObject); @@ -455,6 +486,7 @@ namespace Unity.Netcode.TestHelpers.Runtime { var networkManager = NetcodeIntegrationTestHelpers.CreateNewClient(m_ClientNetworkManagers.Length, m_EnableTimeTravel); networkManager.NetworkConfig.PlayerPrefab = m_PlayerPrefab; + SetDistributedAuthorityProperties(networkManager); // Notification that the new client (NetworkManager) has been created // in the event any modifications need to be made before starting the client @@ -483,12 +515,64 @@ namespace Unity.Netcode.TestHelpers.Runtime Object.DestroyImmediate(networkManager.gameObject); } - AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for the new client to be connected!"); + AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for the new client to be connected!\n {m_InternalErrorLog}"); ClientNetworkManagerPostStart(networkManager); + if (networkManager.DistributedAuthorityMode) + { + yield return WaitForConditionOrTimeOut(() => AllPlayerObjectClonesSpawned(networkManager)); + AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for all sessions to spawn Client-{networkManager.LocalClientId}'s player object!"); + } + VerboseDebug($"[{networkManager.name}] Created and connected!"); } } + private bool AllPlayerObjectClonesSpawned(NetworkManager joinedClient) + { + m_InternalErrorLog.Clear(); + // Continue to populate the PlayerObjects list until all player object (local and clone) are found + ClientNetworkManagerPostStart(joinedClient); + + var playerObjectRelative = m_ServerNetworkManager.SpawnManager.PlayerObjects.Where((c) => c.OwnerClientId == joinedClient.LocalClientId).FirstOrDefault(); + if (playerObjectRelative == null) + { + m_InternalErrorLog.Append($"[AllPlayerObjectClonesSpawned][Server-Side] Joining Client-{joinedClient.LocalClientId} was not populated in the {nameof(NetworkSpawnManager.PlayerObjects)} list!"); + return false; + } + else + { + // Go ahead and create an entry for this new client + if (!m_PlayerNetworkObjects[m_ServerNetworkManager.LocalClientId].ContainsKey(joinedClient.LocalClientId)) + { + m_PlayerNetworkObjects[m_ServerNetworkManager.LocalClientId].Add(joinedClient.LocalClientId, playerObjectRelative); + } + } + + foreach (var clientNetworkManager in m_ClientNetworkManagers) + { + if (clientNetworkManager.LocalClientId == joinedClient.LocalClientId) + { + continue; + } + + playerObjectRelative = clientNetworkManager.SpawnManager.PlayerObjects.Where((c) => c.OwnerClientId == joinedClient.LocalClientId).FirstOrDefault(); + if (playerObjectRelative == null) + { + m_InternalErrorLog.Append($"[AllPlayerObjectClonesSpawned][Client-{clientNetworkManager.LocalClientId}] Client-{joinedClient.LocalClientId} was not populated in the {nameof(NetworkSpawnManager.PlayerObjects)} list!"); + return false; + } + else + { + // Go ahead and create an entry for this new client + if (!m_PlayerNetworkObjects[clientNetworkManager.LocalClientId].ContainsKey(joinedClient.LocalClientId)) + { + m_PlayerNetworkObjects[clientNetworkManager.LocalClientId].Add(joinedClient.LocalClientId, playerObjectRelative); + } + } + } + return true; + } + /// /// This will create, start, and connect a new client while in the middle of an /// integration test. @@ -497,6 +581,7 @@ namespace Unity.Netcode.TestHelpers.Runtime { var networkManager = NetcodeIntegrationTestHelpers.CreateNewClient(m_ClientNetworkManagers.Length, m_EnableTimeTravel); networkManager.NetworkConfig.PlayerPrefab = m_PlayerPrefab; + SetDistributedAuthorityProperties(networkManager); // Notification that the new client (NetworkManager) has been created // in the event any modifications need to be made before starting the client @@ -534,7 +619,10 @@ namespace Unity.Netcode.TestHelpers.Runtime protected IEnumerator StopOneClient(NetworkManager networkManager, bool destroy = false) { NetcodeIntegrationTestHelpers.StopOneClient(networkManager, destroy); - AddRemoveNetworkManager(networkManager, false); + if (destroy) + { + AddRemoveNetworkManager(networkManager, false); + } yield return WaitForConditionOrTimeOut(() => !networkManager.IsConnectedClient); } @@ -581,9 +669,12 @@ namespace Unity.Netcode.TestHelpers.Runtime // Set the player prefab for the server and clients m_ServerNetworkManager.NetworkConfig.PlayerPrefab = m_PlayerPrefab; + SetDistributedAuthorityProperties(m_ServerNetworkManager); + foreach (var client in m_ClientNetworkManagers) { client.NetworkConfig.PlayerPrefab = m_PlayerPrefab; + SetDistributedAuthorityProperties(client); } // Provides opportunity to allow child derived classes to @@ -730,22 +821,27 @@ namespace Unity.Netcode.TestHelpers.Runtime // Start the instances and pass in our SceneManagerInitialization action that is invoked immediately after host-server // is started and after each client is started. - if (!NetcodeIntegrationTestHelpers.Start(m_UseHost, m_ServerNetworkManager, m_ClientNetworkManagers)) + + // When using the CMBService, don't start the server. + bool startServer = !(UseCMBService() && m_DistributedAuthority); + if (!NetcodeIntegrationTestHelpers.Start(m_UseHost, startServer, m_ServerNetworkManager, m_ClientNetworkManagers)) { Debug.LogError("Failed to start instances"); Assert.Fail("Failed to start instances"); } // When scene management is enabled, we need to re-apply the scenes populated list since we have overriden the ISceneManagerHandler - // imeplementation at this point. This assures any pre-loaded scenes will be automatically assigned to the server and force clients + // imeplementation at this point. This assures any pre-loaded scenes will be automatically assigned to the server and force clients // to load their own scenes. if (m_ServerNetworkManager.NetworkConfig.EnableSceneManagement) { - var scenesLoaded = m_ServerNetworkManager.SceneManager.ScenesLoaded; - m_ServerNetworkManager.SceneManager.SceneManagerHandler.PopulateLoadedScenes(ref scenesLoaded, m_ServerNetworkManager); + if (startServer) + { + var scenesLoaded = m_ServerNetworkManager.SceneManager.ScenesLoaded; + m_ServerNetworkManager.SceneManager.SceneManagerHandler.PopulateLoadedScenes(ref scenesLoaded, m_ServerNetworkManager); + } } - if (LogAllMessages) { EnableMessageLogging(); @@ -762,7 +858,7 @@ namespace Unity.Netcode.TestHelpers.Runtime // Wait for all clients to connect yield return WaitForClientsConnectedOrTimeOut(); - AssertOnTimeout($"{nameof(StartServerAndClients)} timed out waiting for all clients to be connected!"); + AssertOnTimeout($"{nameof(StartServerAndClients)} timed out waiting for all clients to be connected!\n {m_InternalErrorLog}"); if (m_UseHost || m_ServerNetworkManager.IsHost) { @@ -783,9 +879,25 @@ namespace Unity.Netcode.TestHelpers.Runtime m_PlayerNetworkObjects[playerNetworkObject.NetworkManager.LocalClientId].Add(m_ServerNetworkManager.LocalClientId, playerNetworkObject); } } - + if (m_DistributedAuthority) + { + //yield return WaitForConditionOrTimeOut(AllClientPlayersSpawned); + //AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for all sessions to spawn all player objects!"); + foreach (var networkManager in m_ClientNetworkManagers) + { + if (networkManager.DistributedAuthorityMode) + { + yield return WaitForConditionOrTimeOut(() => AllPlayerObjectClonesSpawned(networkManager)); + AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for all sessions to spawn Client-{networkManager.LocalClientId}'s player object!\n {m_InternalErrorLog}"); + } + } + if (m_ServerNetworkManager != null) + { + yield return WaitForConditionOrTimeOut(() => AllPlayerObjectClonesSpawned(m_ServerNetworkManager)); + AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for all sessions to spawn Client-{m_ServerNetworkManager.LocalClientId}'s player object!\n {m_InternalErrorLog}"); + } + } ClientNetworkManagerPostStartInit(); - // Notification that at this time the server and client(s) are instantiated, // started, and connected on both sides. yield return OnServerAndClientsConnected(); @@ -807,7 +919,9 @@ namespace Unity.Netcode.TestHelpers.Runtime // Start the instances and pass in our SceneManagerInitialization action that is invoked immediately after host-server // is started and after each client is started. - if (!NetcodeIntegrationTestHelpers.Start(m_UseHost, m_ServerNetworkManager, m_ClientNetworkManagers)) + // When using the CMBService, don't start the server. + var usingCMBService = UseCMBService() && m_DistributedAuthority; + if (!NetcodeIntegrationTestHelpers.Start(m_UseHost, !usingCMBService, m_ServerNetworkManager, m_ClientNetworkManagers)) { Debug.LogError("Failed to start instances"); Assert.Fail("Failed to start instances"); @@ -857,6 +971,24 @@ namespace Unity.Netcode.TestHelpers.Runtime } } + if (m_DistributedAuthority) + { + + foreach (var networkManager in m_ClientNetworkManagers) + { + if (networkManager.DistributedAuthorityMode) + { + WaitForConditionOrTimeOutWithTimeTravel(() => AllPlayerObjectClonesSpawned(m_ServerNetworkManager)); + AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for all sessions to spawn Client-{networkManager.LocalClientId}'s player object!"); + } + } + if (m_ServerNetworkManager != null) + { + WaitForConditionOrTimeOutWithTimeTravel(() => AllPlayerObjectClonesSpawned(m_ServerNetworkManager)); + AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for all sessions to spawn Client-{m_ServerNetworkManager.LocalClientId}'s player object!"); + } + } + ClientNetworkManagerPostStartInit(); // Notification that at this time the server and client(s) are instantiated, @@ -965,6 +1097,45 @@ namespace Unity.Netcode.TestHelpers.Runtime VerboseDebug($"Exiting {nameof(ShutdownAndCleanUp)}"); } + protected IEnumerator CoroutineShutdownAndCleanUp() + { + VerboseDebug($"Entering {nameof(ShutdownAndCleanUp)}"); + // Shutdown and clean up both of our NetworkManager instances + try + { + DeRegisterSceneManagerHandler(); + + NetcodeIntegrationTestHelpers.Destroy(); + + m_PlayerNetworkObjects.Clear(); + s_GlobalNetworkObjects.Clear(); + } + catch (Exception e) + { + throw e; + } + finally + { + if (m_PlayerPrefab != null) + { + Object.DestroyImmediate(m_PlayerPrefab); + m_PlayerPrefab = null; + } + } + + // Allow time for NetworkManagers to fully shutdown + yield return s_DefaultWaitForTick; + + // Cleanup any remaining NetworkObjects + DestroySceneNetworkObjects(); + + UnloadRemainingScenes(); + + // reset the m_ServerWaitForTick for the next test to initialize + s_DefaultWaitForTick = new WaitForSecondsRealtime(1.0f / k_DefaultTickRate); + VerboseDebug($"Exiting {nameof(ShutdownAndCleanUp)}"); + } + /// /// Note: For mode /// this is called before ShutdownAndCleanUp. @@ -994,7 +1165,14 @@ namespace Unity.Netcode.TestHelpers.Runtime if (m_NetworkManagerInstatiationMode == NetworkManagerInstatiationMode.PerTest) { - ShutdownAndCleanUp(); + if (m_TearDownIsACoroutine) + { + yield return CoroutineShutdownAndCleanUp(); + } + else + { + ShutdownAndCleanUp(); + } } if (m_EnableTimeTravel) @@ -1230,11 +1408,35 @@ namespace Unity.Netcode.TestHelpers.Runtime /// An array of clients to be checked protected IEnumerator WaitForClientsConnectedOrTimeOut(NetworkManager[] clientsToCheck) { - var remoteClientCount = clientsToCheck.Length; - var serverClientCount = m_ServerNetworkManager.IsHost ? remoteClientCount + 1 : remoteClientCount; + yield return WaitForConditionOrTimeOut(() => CheckClientsConnected(clientsToCheck)); + } - yield return WaitForConditionOrTimeOut(() => clientsToCheck.Where((c) => c.IsConnectedClient).Count() == remoteClientCount && - m_ServerNetworkManager.ConnectedClients.Count == serverClientCount); + /// + /// Validation for clients connected that includes additional information for easier troubleshooting purposes. + /// + private bool CheckClientsConnected(NetworkManager[] clientsToCheck) + { + m_InternalErrorLog.Clear(); + var allClientsConnected = true; + + for (int i = 0; i < clientsToCheck.Length; i++) + { + if (!clientsToCheck[i].IsConnectedClient) + { + allClientsConnected = false; + m_InternalErrorLog.AppendLine($"[Client-{i + 1}] Client is not connected!"); + } + } + var expectedCount = m_ServerNetworkManager.IsHost ? clientsToCheck.Length + 1 : clientsToCheck.Length; + var currentCount = m_ServerNetworkManager.ConnectedClients.Count; + + if (currentCount != expectedCount) + { + allClientsConnected = false; + m_InternalErrorLog.AppendLine($"[Server-Side] Expected {expectedCount} clients to connect but only {currentCount} connected!"); + } + + return allClientsConnected; } /// @@ -1286,7 +1488,7 @@ namespace Unity.Netcode.TestHelpers.Runtime // Used to determine if all clients received the CreateObjectMessage var hooks = new MessageHooksConditional(messageHookEntriesForSpawn); yield return WaitForConditionOrTimeOut(hooks); - Assert.False(s_GlobalTimeoutHelper.TimedOut); + AssertOnTimeout($"Timed out waiting for message type {typeof(T).Name}!"); } internal IEnumerator WaitForMessagesReceived(List messagesInOrder, List waitForReceivedBy, ReceiptType type = ReceiptType.Handled) @@ -1306,7 +1508,12 @@ namespace Unity.Netcode.TestHelpers.Runtime // Used to determine if all clients received the CreateObjectMessage var hooks = new MessageHooksConditional(messageHookEntriesForSpawn); yield return WaitForConditionOrTimeOut(hooks); - Assert.False(s_GlobalTimeoutHelper.TimedOut); + var stringBuilder = new StringBuilder(); + foreach (var messageType in messagesInOrder) + { + stringBuilder.Append($"{messageType.Name},"); + } + AssertOnTimeout($"Timed out waiting for message types: {stringBuilder}!"); } @@ -1323,7 +1530,7 @@ namespace Unity.Netcode.TestHelpers.Runtime // Used to determine if all clients received the CreateObjectMessage var hooks = new MessageHooksConditional(messageHookEntriesForSpawn); - Assert.True(WaitForConditionOrTimeOutWithTimeTravel(hooks)); + Assert.True(WaitForConditionOrTimeOutWithTimeTravel(hooks), $"[Message Not Recieved] {hooks.GetHooksStillWaiting()}"); } internal void WaitForMessagesReceivedWithTimeTravel(List messagesInOrder, List waitForReceivedBy, ReceiptType type = ReceiptType.Handled) @@ -1342,7 +1549,7 @@ namespace Unity.Netcode.TestHelpers.Runtime // Used to determine if all clients received the CreateObjectMessage var hooks = new MessageHooksConditional(messageHookEntriesForSpawn); - Assert.True(WaitForConditionOrTimeOutWithTimeTravel(hooks)); + Assert.True(WaitForConditionOrTimeOutWithTimeTravel(hooks), $"[Messages Not Recieved] {hooks.GetHooksStillWaiting()}"); } /// @@ -1358,8 +1565,11 @@ namespace Unity.Netcode.TestHelpers.Runtime $"but before {nameof(OnStartedServerAndClients)}!"; Assert.IsNotNull(m_ServerNetworkManager, prefabCreateAssertError); Assert.IsFalse(m_ServerNetworkManager.IsListening, prefabCreateAssertError); - - return NetcodeIntegrationTestHelpers.CreateNetworkObjectPrefab(baseName, m_ServerNetworkManager, m_ClientNetworkManagers); + var prefabObject = NetcodeIntegrationTestHelpers.CreateNetworkObjectPrefab(baseName, m_ServerNetworkManager, m_ClientNetworkManagers); + // DANGO-TODO: Ownership flags could require us to change this + // For testing purposes, we default to true for the distribute ownership property when in distirbuted authority session mode. + prefabObject.GetComponent().Ownership |= NetworkObject.OwnershipStatus.Distributable; + return prefabObject; } /// @@ -1372,6 +1582,16 @@ namespace Unity.Netcode.TestHelpers.Runtime return SpawnObject(prefabNetworkObject, owner, destroyWithScene); } + /// + /// Overloaded method + /// + protected GameObject SpawnPlayerObject(GameObject prefabGameObject, NetworkManager owner, bool destroyWithScene = false) + { + var prefabNetworkObject = prefabGameObject.GetComponent(); + Assert.IsNotNull(prefabNetworkObject, $"{nameof(GameObject)} {prefabGameObject.name} does not have a {nameof(NetworkObject)} component!"); + return SpawnObject(prefabNetworkObject, owner, destroyWithScene, true); + } + /// /// Spawn a NetworkObject prefab instance /// @@ -1379,28 +1599,57 @@ namespace Unity.Netcode.TestHelpers.Runtime /// the owner of the instance /// default is false /// GameObject instance spawned - private GameObject SpawnObject(NetworkObject prefabNetworkObject, NetworkManager owner, bool destroyWithScene = false) + private GameObject SpawnObject(NetworkObject prefabNetworkObject, NetworkManager owner, bool destroyWithScene = false, bool isPlayerObject = false) { Assert.IsTrue(prefabNetworkObject.GlobalObjectIdHash > 0, $"{nameof(GameObject)} {prefabNetworkObject.name} has a {nameof(NetworkObject.GlobalObjectIdHash)} value of 0! Make sure to make it a valid prefab before trying to spawn!"); var newInstance = Object.Instantiate(prefabNetworkObject.gameObject); var networkObjectToSpawn = newInstance.GetComponent(); - networkObjectToSpawn.NetworkManagerOwner = m_ServerNetworkManager; // Required to assure the server does the spawning - if (owner == m_ServerNetworkManager) + + if (owner.NetworkConfig.SessionMode == SessionModeTypes.DistributedAuthority) { - if (m_UseHost) + networkObjectToSpawn.NetworkManagerOwner = owner; // Required to assure the client does the spawning + if (isPlayerObject) { - networkObjectToSpawn.SpawnWithOwnership(owner.LocalClientId, destroyWithScene); + networkObjectToSpawn.SpawnAsPlayerObject(owner.LocalClientId, destroyWithScene); } else { - networkObjectToSpawn.Spawn(destroyWithScene); + networkObjectToSpawn.SpawnWithOwnership(owner.LocalClientId, destroyWithScene); } } else { - networkObjectToSpawn.SpawnWithOwnership(owner.LocalClientId, destroyWithScene); + networkObjectToSpawn.NetworkManagerOwner = m_ServerNetworkManager; // Required to assure the server does the spawning + if (owner == m_ServerNetworkManager) + { + if (m_UseHost) + { + if (isPlayerObject) + { + networkObjectToSpawn.SpawnAsPlayerObject(owner.LocalClientId, destroyWithScene); + } + else + { + networkObjectToSpawn.SpawnWithOwnership(owner.LocalClientId, destroyWithScene); + } + } + else + { + networkObjectToSpawn.Spawn(destroyWithScene); + } + } + else + { + if (isPlayerObject) + { + networkObjectToSpawn.SpawnAsPlayerObject(owner.LocalClientId, destroyWithScene); + } + else + { + networkObjectToSpawn.SpawnWithOwnership(owner.LocalClientId, destroyWithScene); + } + } } - return newInstance; } @@ -1438,6 +1687,15 @@ namespace Unity.Netcode.TestHelpers.Runtime /// public NetcodeIntegrationTest() { + m_SessionModeType = OnGetSessionmode(); + m_DistributedAuthority = OnGetSessionmode() == SessionModeTypes.DistributedAuthority; + NetworkMessageManager.EnableMessageOrderConsoleLog = false; + } + + public NetcodeIntegrationTest(SessionModeTypes sessionMode) + { + m_SessionModeType = sessionMode; + m_DistributedAuthority = OnGetSessionmode() == SessionModeTypes.DistributedAuthority; } /// @@ -1458,7 +1716,9 @@ namespace Unity.Netcode.TestHelpers.Runtime /// public NetcodeIntegrationTest(HostOrServer hostOrServer) { - m_UseHost = hostOrServer == HostOrServer.Host ? true : false; + m_UseHost = hostOrServer == HostOrServer.Host || hostOrServer == HostOrServer.DAHost; + m_SessionModeType = hostOrServer == HostOrServer.DAHost ? SessionModeTypes.DistributedAuthority : SessionModeTypes.ClientServer; + m_DistributedAuthority = OnGetSessionmode() == SessionModeTypes.DistributedAuthority; } /// @@ -1489,7 +1749,7 @@ namespace Unity.Netcode.TestHelpers.Runtime } } - private System.Text.StringBuilder m_WaitForLog = new System.Text.StringBuilder(); + private StringBuilder m_WaitForLog = new StringBuilder(); private void LogWaitForMessages() { diff --git a/TestHelpers/Runtime/NetcodeIntegrationTestHelpers.cs b/TestHelpers/Runtime/NetcodeIntegrationTestHelpers.cs index bf26f9f..a296066 100644 --- a/TestHelpers/Runtime/NetcodeIntegrationTestHelpers.cs +++ b/TestHelpers/Runtime/NetcodeIntegrationTestHelpers.cs @@ -410,12 +410,31 @@ namespace Unity.Netcode.TestHelpers.Runtime { networkManager.SceneManager.ScenesLoaded.Add(scene.handle, scene); } + // In distributed authority we need to check if this scene is already added + if (networkManager.DistributedAuthorityMode) + { + if (!networkManager.SceneManager.ServerSceneHandleToClientSceneHandle.ContainsKey(scene.handle)) + { + networkManager.SceneManager.ServerSceneHandleToClientSceneHandle.Add(scene.handle, scene.handle); + } + + if (!networkManager.SceneManager.ClientSceneHandleToServerSceneHandle.ContainsKey(scene.handle)) + { + networkManager.SceneManager.ClientSceneHandleToServerSceneHandle.Add(scene.handle, scene.handle); + } + return; + } networkManager.SceneManager.ServerSceneHandleToClientSceneHandle.Add(scene.handle, scene.handle); } } public delegate void BeforeClientStartCallback(); + internal static bool Start(bool host, bool startServer, NetworkManager server, NetworkManager[] clients) + { + return Start(host, server, clients, null, startServer); + } + /// /// Starts NetworkManager instances created by the Create method. /// @@ -424,7 +443,7 @@ namespace Unity.Netcode.TestHelpers.Runtime /// The Clients NetworkManager /// called immediately after server is started and before client(s) are started /// - public static bool Start(bool host, NetworkManager server, NetworkManager[] clients, BeforeClientStartCallback callback = null) + public static bool Start(bool host, NetworkManager server, NetworkManager[] clients, BeforeClientStartCallback callback = null, bool startServer = true) { if (s_IsStarted) { @@ -433,24 +452,26 @@ namespace Unity.Netcode.TestHelpers.Runtime s_IsStarted = true; s_ClientCount = clients.Length; - - if (host) + var hooks = (MultiInstanceHooks)null; + if (startServer) { - server.StartHost(); + if (host) + { + server.StartHost(); + } + else + { + server.StartServer(); + } + + hooks = new MultiInstanceHooks(); + server.ConnectionManager.MessageManager.Hook(hooks); + s_Hooks[server] = hooks; + + // Register the server side handler (always pass true for server) + RegisterHandlers(server, true); + callback?.Invoke(); } - else - { - server.StartServer(); - } - - var hooks = new MultiInstanceHooks(); - server.ConnectionManager.MessageManager.Hook(hooks); - s_Hooks[server] = hooks; - - // Register the server side handler (always pass true for server) - RegisterHandlers(server, true); - - callback?.Invoke(); for (int i = 0; i < clients.Length; i++) { diff --git a/Tests/Editor/Build/BuildTests.cs b/Tests/Editor/Build/BuildTests.cs index c8cde89..bbb24a3 100644 --- a/Tests/Editor/Build/BuildTests.cs +++ b/Tests/Editor/Build/BuildTests.cs @@ -1,3 +1,4 @@ +#if !MULTIPLAYER_TOOLS using System.IO; using System.Reflection; using NUnit.Framework; @@ -38,3 +39,4 @@ namespace Unity.Netcode.EditorTests } } } +#endif diff --git a/Tests/Editor/Serialization/FastBufferWriterTests.cs b/Tests/Editor/Serialization/FastBufferWriterTests.cs index f658fcb..5967d49 100644 --- a/Tests/Editor/Serialization/FastBufferWriterTests.cs +++ b/Tests/Editor/Serialization/FastBufferWriterTests.cs @@ -311,8 +311,11 @@ namespace Unity.Netcode.EditorTests { int* sizeValue = (int*)(unsafePtr + offset); Assert.AreEqual(value.Length, *sizeValue); - +#if UTP_TRANSPORT_2_0_ABOVE + var asTPointer = value.GetUnsafePtr(); +#else var asTPointer = (T*)value.GetUnsafePtr(); +#endif var underlyingTArray = (T*)(unsafePtr + sizeof(int) + offset); for (var i = 0; i < value.Length; ++i) { diff --git a/Tests/Editor/Transports/BatchedReceiveQueueTests.cs b/Tests/Editor/Transports/BatchedReceiveQueueTests.cs index 5470f21..e072f3c 100644 --- a/Tests/Editor/Transports/BatchedReceiveQueueTests.cs +++ b/Tests/Editor/Transports/BatchedReceiveQueueTests.cs @@ -2,7 +2,9 @@ using System; using NUnit.Framework; using Unity.Collections; using Unity.Netcode.Transports.UTP; +#if !UTP_TRANSPORT_2_0_ABOVE using Unity.Networking.Transport; +#endif namespace Unity.Netcode.EditorTests { diff --git a/Tests/Editor/Transports/BatchedSendQueueTests.cs b/Tests/Editor/Transports/BatchedSendQueueTests.cs index c1550da..ca6a354 100644 --- a/Tests/Editor/Transports/BatchedSendQueueTests.cs +++ b/Tests/Editor/Transports/BatchedSendQueueTests.cs @@ -2,7 +2,9 @@ using System; using NUnit.Framework; using Unity.Collections; using Unity.Netcode.Transports.UTP; +#if !UTP_TRANSPORT_2_0_ABOVE using Unity.Networking.Transport; +#endif namespace Unity.Netcode.EditorTests { diff --git a/Tests/Runtime/ConnectionApprovalTimeoutTests.cs b/Tests/Runtime/ConnectionApprovalTimeoutTests.cs index 0300f04..0cf9658 100644 --- a/Tests/Runtime/ConnectionApprovalTimeoutTests.cs +++ b/Tests/Runtime/ConnectionApprovalTimeoutTests.cs @@ -26,9 +26,9 @@ namespace Unity.Netcode.RuntimeTests m_ApprovalFailureType = approvalFailureType; } - // Must be >= 2 since this is an int value and the test waits for timeout - 1 to try to verify it doesn't + // Must be >= 5 since this is an int value and the test waits for timeout - 1 to try to verify it doesn't // time out early - private const int k_TestTimeoutPeriod = 1; + private const int k_TestTimeoutPeriod = 5; private Regex m_ExpectedLogMessage; private LogType m_LogType; @@ -59,6 +59,7 @@ namespace Unity.Netcode.RuntimeTests { if (m_ApprovalFailureType == ApprovalTimedOutTypes.ServerDoesNotRespond) { + m_ServerNetworkManager.ConnectionManager.MockSkippingApproval = true; // We catch (don't process) the incoming approval message to simulate the server not sending the approved message in time m_ClientNetworkManagers[0].ConnectionManager.MessageManager.Hook(new MessageCatcher(m_ClientNetworkManagers[0])); m_ExpectedLogMessage = new Regex("Timed out waiting for the server to approve the connection request."); @@ -80,18 +81,18 @@ namespace Unity.Netcode.RuntimeTests [UnityTest] public IEnumerator ValidateApprovalTimeout() { - // Delay for half of the wait period - yield return new WaitForSeconds(k_TestTimeoutPeriod * 0.5f); + // Just delay for a second + yield return new WaitForSeconds(1); // Verify we haven't received the time out message yet NetcodeLogAssert.LogWasNotReceived(LogType.Log, m_ExpectedLogMessage); - yield return new WaitForSeconds(k_TestTimeoutPeriod * 1.5f); + yield return new WaitForSeconds(k_TestTimeoutPeriod * 1.25f); // We should have the test relative log message by this time. NetcodeLogAssert.LogWasReceived(m_LogType, m_ExpectedLogMessage); - Debug.Log("Checking connected client count"); + VerboseDebug("Checking connected client count"); // It should only have the host client connected Assert.AreEqual(1, m_ServerNetworkManager.ConnectedClients.Count, $"Expected only one client when there were {m_ServerNetworkManager.ConnectedClients.Count} clients connected!"); diff --git a/Tests/Runtime/DeferredMessagingTests.cs b/Tests/Runtime/DeferredMessagingTests.cs index f85a9cb..564bde6 100644 --- a/Tests/Runtime/DeferredMessagingTests.cs +++ b/Tests/Runtime/DeferredMessagingTests.cs @@ -5,6 +5,7 @@ using NUnit.Framework; using Unity.Netcode.TestHelpers.Runtime; using UnityEngine; using UnityEngine.TestTools; + using Object = UnityEngine.Object; namespace Unity.Netcode.RuntimeTests @@ -84,12 +85,11 @@ namespace Unity.Netcode.RuntimeTests return 0; } - - public override void DeferMessage(IDeferredNetworkMessageManager.TriggerType trigger, ulong key, FastBufferReader reader, ref NetworkContext context) + public override void DeferMessage(IDeferredNetworkMessageManager.TriggerType trigger, ulong key, FastBufferReader reader, ref NetworkContext context, string messageType) { OnBeforeDefer?.Invoke(this, key); DeferMessageCalled = true; - base.DeferMessage(trigger, key, reader, ref context); + base.DeferMessage(trigger, key, reader, ref context, messageType); } public override void ProcessTriggers(IDeferredNetworkMessageManager.TriggerType trigger, ulong key) @@ -203,6 +203,9 @@ namespace Unity.Netcode.RuntimeTests protected override void OnInlineSetup() { + // Revert back to standard deferred message format for tests (for now) + DeferredMessageManager.IncludeMessageType = false; + DeferredMessageTestRpcAndNetworkVariableComponent.ClientInstances.Clear(); DeferredMessageTestRpcComponent.ClientInstances.Clear(); DeferredMessageTestNetworkVariableComponent.ClientInstances.Clear(); @@ -894,7 +897,7 @@ namespace Unity.Netcode.RuntimeTests foreach (var unused in m_ClientNetworkManagers) { - LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredNetworkMessageManager.TriggerType.OnSpawn} with key {serverObject.GetComponent().NetworkObjectId}, but that trigger was not received within within {timeout} second(s)."); + LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredNetworkMessageManager.TriggerType.OnSpawn} associated with id ({serverObject.GetComponent().NetworkObjectId}), but the {nameof(NetworkObject)} was not received within the timeout period {timeout} second(s)."); } int purgeCount = 0; @@ -904,7 +907,7 @@ namespace Unity.Netcode.RuntimeTests { ++purgeCount; var elapsed = client.RealTimeProvider.RealTimeSinceStartup - start; - Debug.Log(client.RealTimeProvider.GetType().FullName); + VerboseDebug(client.RealTimeProvider.GetType().FullName); Assert.GreaterOrEqual(elapsed, timeout); Assert.AreEqual(1, manager.DeferredMessageCountTotal()); Assert.AreEqual(1, manager.DeferredMessageCountForType(IDeferredNetworkMessageManager.TriggerType.OnSpawn)); @@ -990,7 +993,7 @@ namespace Unity.Netcode.RuntimeTests foreach (var unused in m_ClientNetworkManagers) { - LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredNetworkMessageManager.TriggerType.OnSpawn} with key {serverObject.GetComponent().NetworkObjectId}, but that trigger was not received within within {timeout} second(s)."); + LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredNetworkMessageManager.TriggerType.OnSpawn} associated with id ({serverObject.GetComponent().NetworkObjectId}), but the {nameof(NetworkObject)} was not received within the timeout period {timeout} second(s)."); } int purgeCount = 0; @@ -1095,9 +1098,8 @@ namespace Unity.Netcode.RuntimeTests foreach (var unused in m_ClientNetworkManagers) { - - LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredNetworkMessageManager.TriggerType.OnSpawn} with key {serverObject.GetComponent().NetworkObjectId}, but that trigger was not received within within {timeout} second(s)."); - LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredNetworkMessageManager.TriggerType.OnSpawn} with key {serverObject2.GetComponent().NetworkObjectId}, but that trigger was not received within within {timeout} second(s)."); + LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredNetworkMessageManager.TriggerType.OnSpawn} associated with id ({serverObject.GetComponent().NetworkObjectId}), but the {nameof(NetworkObject)} was not received within the timeout period {timeout} second(s)."); + LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredNetworkMessageManager.TriggerType.OnSpawn} associated with id ({serverObject2.GetComponent().NetworkObjectId}), but the {nameof(NetworkObject)} was not received within the timeout period {timeout} second(s)."); } int purgeCount = 0; @@ -1188,7 +1190,7 @@ namespace Unity.Netcode.RuntimeTests foreach (var unused in m_ClientNetworkManagers) { - LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredNetworkMessageManager.TriggerType.OnSpawn} with key {serverObject.GetComponent().NetworkObjectId}, but that trigger was not received within within {timeout} second(s)."); + LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredNetworkMessageManager.TriggerType.OnSpawn} associated with id ({serverObject.GetComponent().NetworkObjectId}), but the {nameof(NetworkObject)} was not received within the timeout period {timeout} second(s)."); } int purgeCount = 0; @@ -1271,7 +1273,11 @@ namespace Unity.Netcode.RuntimeTests Assert.AreEqual(0, manager.DeferredMessageCountForKey(IDeferredNetworkMessageManager.TriggerType.OnSpawn, serverObject2.GetComponent().NetworkObjectId)); } - serverObject2.GetComponent().ChangeOwnership(m_ServerNetworkManager.LocalClientId); + // KITTY-TODO: Review this change please: + // Changing ownership when the owner specified is already an owner should not send any messages + // The original test was changing ownership to the server when the object was spawned with the server being an owner. + //serverObject2.GetComponent().ChangeOwnership(m_ServerNetworkManager.LocalClientId); + serverObject2.GetComponent().ChangeOwnership(m_ClientNetworkManagers[1].LocalClientId); WaitForAllClientsToReceive(); foreach (var client in m_ClientNetworkManagers) @@ -1285,7 +1291,7 @@ namespace Unity.Netcode.RuntimeTests foreach (var unused in m_ClientNetworkManagers) { - LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredNetworkMessageManager.TriggerType.OnSpawn} with key {serverObject.GetComponent().NetworkObjectId}, but that trigger was not received within within {timeout} second(s)."); + LogAssert.Expect(LogType.Warning, $"[Netcode] Deferred messages were received for a trigger of type {IDeferredNetworkMessageManager.TriggerType.OnSpawn} associated with id ({serverObject.GetComponent().NetworkObjectId}), but the {nameof(NetworkObject)} was not received within the timeout period {timeout} second(s)."); } int purgeCount = 0; diff --git a/Tests/Runtime/DisconnectTests.cs b/Tests/Runtime/DisconnectTests.cs index c72cfdd..bdc298a 100644 --- a/Tests/Runtime/DisconnectTests.cs +++ b/Tests/Runtime/DisconnectTests.cs @@ -1,4 +1,5 @@ using System.Collections; +using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Unity.Netcode.TestHelpers.Runtime; @@ -37,7 +38,10 @@ namespace Unity.Netcode.RuntimeTests protected override int NumberOfClients => 1; private OwnerPersistence m_OwnerPersistence; + private ClientDisconnectType m_ClientDisconnectType; private bool m_ClientDisconnected; + private Dictionary m_DisconnectedEvent = new Dictionary(); + private ulong m_DisconnectEventClientId; private ulong m_TransportClientId; private ulong m_ClientId; @@ -89,6 +93,16 @@ namespace Unity.Netcode.RuntimeTests m_ClientDisconnected = true; } + private void OnConnectionEvent(NetworkManager networkManager, ConnectionEventData connectionEventData) + { + if (connectionEventData.EventType != ConnectionEvent.ClientDisconnected) + { + return; + } + + m_DisconnectedEvent.Add(networkManager, connectionEventData); + } + /// /// Conditional check to assure the transport to client (and vice versa) mappings are cleaned up /// @@ -126,6 +140,7 @@ namespace Unity.Netcode.RuntimeTests public IEnumerator ClientPlayerDisconnected([Values] ClientDisconnectType clientDisconnectType) { m_ClientId = m_ClientNetworkManagers[0].LocalClientId; + m_ClientDisconnectType = clientDisconnectType; var serverSideClientPlayer = m_ServerNetworkManager.ConnectionManager.ConnectedClients[m_ClientId].PlayerObject; @@ -134,11 +149,15 @@ namespace Unity.Netcode.RuntimeTests if (clientDisconnectType == ClientDisconnectType.ServerDisconnectsClient) { m_ClientNetworkManagers[0].OnClientDisconnectCallback += OnClientDisconnectCallback; + m_ClientNetworkManagers[0].OnConnectionEvent += OnConnectionEvent; + m_ServerNetworkManager.OnConnectionEvent += OnConnectionEvent; m_ServerNetworkManager.DisconnectClient(m_ClientId); } else { m_ServerNetworkManager.OnClientDisconnectCallback += OnClientDisconnectCallback; + m_ServerNetworkManager.OnConnectionEvent += OnConnectionEvent; + m_ClientNetworkManagers[0].OnConnectionEvent += OnConnectionEvent; yield return StopOneClient(m_ClientNetworkManagers[0]); } @@ -146,6 +165,23 @@ namespace Unity.Netcode.RuntimeTests yield return WaitForConditionOrTimeOut(() => m_ClientDisconnected); AssertOnTimeout("Timed out waiting for client to disconnect!"); + if (clientDisconnectType == ClientDisconnectType.ServerDisconnectsClient) + { + Assert.IsTrue(m_DisconnectedEvent.ContainsKey(m_ServerNetworkManager), $"Could not find the server {nameof(NetworkManager)} disconnect event entry!"); + Assert.IsTrue(m_DisconnectedEvent[m_ServerNetworkManager].ClientId == m_ClientId, $"Expected ClientID {m_ClientId} but found ClientID {m_DisconnectedEvent[m_ServerNetworkManager].ClientId} for the server {nameof(NetworkManager)} disconnect event entry!"); + Assert.IsTrue(m_DisconnectedEvent.ContainsKey(m_ClientNetworkManagers[0]), $"Could not find the client {nameof(NetworkManager)} disconnect event entry!"); + Assert.IsTrue(m_DisconnectedEvent[m_ClientNetworkManagers[0]].ClientId == m_ClientId, $"Expected ClientID {m_ClientId} but found ClientID {m_DisconnectedEvent[m_ServerNetworkManager].ClientId} for the client {nameof(NetworkManager)} disconnect event entry!"); + // Unregister for this event otherwise it will be invoked during teardown + m_ServerNetworkManager.OnConnectionEvent -= OnConnectionEvent; + } + else + { + Assert.IsTrue(m_DisconnectedEvent.ContainsKey(m_ServerNetworkManager), $"Could not find the server {nameof(NetworkManager)} disconnect event entry!"); + Assert.IsTrue(m_DisconnectedEvent[m_ServerNetworkManager].ClientId == m_ClientId, $"Expected ClientID {m_ClientId} but found ClientID {m_DisconnectedEvent[m_ServerNetworkManager].ClientId} for the server {nameof(NetworkManager)} disconnect event entry!"); + Assert.IsTrue(m_DisconnectedEvent.ContainsKey(m_ClientNetworkManagers[0]), $"Could not find the client {nameof(NetworkManager)} disconnect event entry!"); + Assert.IsTrue(m_DisconnectedEvent[m_ClientNetworkManagers[0]].ClientId == m_ClientId, $"Expected ClientID {m_ClientId} but found ClientID {m_DisconnectedEvent[m_ServerNetworkManager].ClientId} for the client {nameof(NetworkManager)} disconnect event entry!"); + } + if (m_OwnerPersistence == OwnerPersistence.DestroyWithOwner) { // When we are destroying with the owner, validate the player object is destroyed on the server side @@ -161,6 +197,21 @@ namespace Unity.Netcode.RuntimeTests yield return WaitForConditionOrTimeOut(TransportIdCleanedUp); AssertOnTimeout("Timed out waiting for transport and client id mappings to be cleaned up!"); + + // Validate the host-client generates a OnClientDisconnected event when it shutsdown. + // Only test when the test run is the client disconnecting from the server (otherwise the server will be shutdown already) + if (clientDisconnectType == ClientDisconnectType.ClientDisconnectsFromServer) + { + m_DisconnectedEvent.Clear(); + m_ClientDisconnected = false; + m_ServerNetworkManager.Shutdown(); + + yield return WaitForConditionOrTimeOut(() => m_ClientDisconnected); + AssertOnTimeout("Timed out waiting for host-client to generate disconnect message!"); + + Assert.IsTrue(m_DisconnectedEvent.ContainsKey(m_ServerNetworkManager), $"Could not find the server {nameof(NetworkManager)} disconnect event entry!"); + Assert.IsTrue(m_DisconnectedEvent[m_ServerNetworkManager].ClientId == NetworkManager.ServerClientId, $"Expected ClientID {m_ClientId} but found ClientID {m_DisconnectedEvent[m_ServerNetworkManager].ClientId} for the server {nameof(NetworkManager)} disconnect event entry!"); + } } } } diff --git a/Tests/Runtime/DistributedAuthority.meta b/Tests/Runtime/DistributedAuthority.meta new file mode 100644 index 0000000..ee02283 --- /dev/null +++ b/Tests/Runtime/DistributedAuthority.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 421e3306c97e10f47b9efb6101a998ee +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Tests/Runtime/DistributedAuthority/DeferredDespawningTests.cs b/Tests/Runtime/DistributedAuthority/DeferredDespawningTests.cs new file mode 100644 index 0000000..b6abd74 --- /dev/null +++ b/Tests/Runtime/DistributedAuthority/DeferredDespawningTests.cs @@ -0,0 +1,266 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using NUnit.Framework; +using Unity.Netcode.TestHelpers.Runtime; +using UnityEngine; +using UnityEngine.TestTools; + + +namespace Unity.Netcode.RuntimeTests +{ + public class DeferredDespawningTests : IntegrationTestWithApproximation + { + private const int k_DaisyChainedCount = 5; + protected override int NumberOfClients => 2; + private List m_DaisyChainedDespawnObjects = new List(); + private List m_HasReachedEnd = new List(); + + public DeferredDespawningTests() : base(HostOrServer.DAHost) + { + } + + protected override void OnServerAndClientsCreated() + { + var daisyChainPrevious = (DeferredDespawnDaisyChained)null; + for (int i = 0; i < k_DaisyChainedCount; i++) + { + var daisyChainNode = CreateNetworkObjectPrefab($"Daisy-{i}"); + var daisyChainBehaviour = daisyChainNode.AddComponent(); + daisyChainBehaviour.IsRoot = i == 0; + if (daisyChainPrevious != null) + { + daisyChainPrevious.PrefabToSpawnWhenDespawned = daisyChainBehaviour.gameObject; + } + m_DaisyChainedDespawnObjects.Add(daisyChainNode); + + daisyChainPrevious = daisyChainBehaviour; + } + + base.OnServerAndClientsCreated(); + } + + + + [UnityTest] + public IEnumerator DeferredDespawning() + { + DeferredDespawnDaisyChained.EnableVerbose = m_EnableVerboseDebug; + var rootInstance = SpawnObject(m_DaisyChainedDespawnObjects[0], m_ServerNetworkManager); + DeferredDespawnDaisyChained.ReachedLastChainInstance = ReachedLastChainObject; + var timeoutHelper = new TimeoutHelper(300); + yield return WaitForConditionOrTimeOut(HaveAllClientsReachedEndOfChain, timeoutHelper); + AssertOnTimeout($"Timed out waiting for all children to reach the end of their chained deferred despawns!", timeoutHelper); + } + + private bool HaveAllClientsReachedEndOfChain() + { + if (!m_HasReachedEnd.Contains(m_ServerNetworkManager.LocalClientId)) + { + return false; + } + + foreach (var client in m_ClientNetworkManagers) + { + if (!m_HasReachedEnd.Contains(client.LocalClientId)) + { + return false; + } + } + return true; + } + + private void ReachedLastChainObject(ulong clientId) + { + m_HasReachedEnd.Add(clientId); + } + } + + /// + /// This helper behaviour handles the majority of the validation for deferred despawning. + /// Each instance triggers a series of deferred despawns where the owner validates the + /// NetworkVariables are updated and spawns another prefab prior to despawning locally + /// and the non-owners validate receiving the NetworkVariable change notification which + /// contains a reference to a DeferredDespawnDaisyChained component on the newly spawned + /// prefab driven by the authority. This repeats for the number specified in the integration + /// test. + /// + public class DeferredDespawnDaisyChained : NetworkBehaviour + { + public static bool EnableVerbose; + public static Action ReachedLastChainInstance; + private const int k_StartingDeferTick = 4; + public static Dictionary> ClientRelativeInstances = new Dictionary>(); + public bool IsRoot; + public GameObject PrefabToSpawnWhenDespawned; + public bool WasContactedByPeviousChainMember { get; private set; } + public int DeferDespawnTick { get; private set; } + + private void PingInstance() + { + WasContactedByPeviousChainMember = true; + } + + /// + /// This hits two birds with one NetworkVariable: + /// - Validates that NetworkVariables modified while the authority is in the middle of deferring a despawn are serialized and received by non-authority instances. + /// - Validates that the non-authority instances receive the updates within the deferred tick period of time and can use them to handle other visual synchronization + /// realted tasks (or the like). + /// + private NetworkVariable m_ValidateDirtyNetworkVarUpdate = new NetworkVariable(); + + private DeferredDespawnDaisyChained m_NextNodeSpawned = null; + + private void FailTest(string msg) + { + Assert.Fail($"[{nameof(DeferredDespawnDaisyChained)}][Client-{NetworkManager.LocalClientId}] {msg}"); + } + + public override void OnNetworkSpawn() + { + var localId = NetworkManager.LocalClientId; + if (!ClientRelativeInstances.ContainsKey(localId)) + { + ClientRelativeInstances.Add(localId, new Dictionary()); + } + + if (ClientRelativeInstances[localId].ContainsKey(NetworkObject.NetworkObjectId)) + { + FailTest($"[{nameof(OnNetworkSpawn)}] Client already has a table entry for NetworkObject-{NetworkObject.NetworkObjectId} | {name}!"); + } + + ClientRelativeInstances[localId].Add(NetworkObject.NetworkObjectId, this); + + if (!HasAuthority) + { + m_ValidateDirtyNetworkVarUpdate.OnValueChanged += OnValidateDirtyChanged; + } + + if (HasAuthority && IsRoot) + { + DeferDespawnTick = k_StartingDeferTick; + } + + base.OnNetworkSpawn(); + } + + private void OnValidateDirtyChanged(NetworkBehaviourReference previous, NetworkBehaviourReference current) + { + if (!HasAuthority) + { + if (!current.TryGet(out m_NextNodeSpawned, NetworkManager)) + { + FailTest($"[{nameof(OnValidateDirtyChanged)}][{nameof(NetworkBehaviourReference)}] Failed to get the {nameof(DeferredDespawnDaisyChained)} behaviour from the {nameof(NetworkBehaviourReference)}!"); + } + + if (m_NextNodeSpawned.NetworkManager != NetworkManager) + { + FailTest($"[{nameof(NetworkManager)}][{nameof(NetworkBehaviourReference.TryGet)}] The {nameof(NetworkManager)} of {nameof(m_NextNodeSpawned)} does not match the local relative {nameof(NetworkManager)} instance!"); + } + } + } + + public override void OnNetworkDespawn() + { + if (!HasAuthority && !NetworkManager.ShutdownInProgress) + { + if (PrefabToSpawnWhenDespawned != null) + { + m_NextNodeSpawned.PingInstance(); + } + else + { + ReachedLastChainInstance?.Invoke(NetworkManager.LocalClientId); + } + } + base.OnNetworkDespawn(); + } + + private void InvokeDespawn() + { + if (!HasAuthority) + { + FailTest($"[{nameof(InvokeDespawn)}] Client is not the authority but this was invoked (integration test logic issue)!"); + } + NetworkObject.DeferDespawn(DeferDespawnTick); + } + + public override void OnDeferringDespawn(int despawnTick) + { + if (!HasAuthority) + { + FailTest($"[{nameof(OnDeferringDespawn)}] Client is not the authority but this was invoked (integration test logic issue)!"); + } + + if (despawnTick != (DeferDespawnTick + NetworkManager.ServerTime.Tick)) + { + FailTest($"[{nameof(OnDeferringDespawn)}] The passed in {despawnTick} parameter ({despawnTick}) does not equal the expected value of ({DeferDespawnTick + NetworkManager.ServerTime.Tick})!"); + } + + if (PrefabToSpawnWhenDespawned != null) + { + var deferNetworkObject = PrefabToSpawnWhenDespawned.GetComponent().InstantiateAndSpawn(NetworkManager); + var deferComponent = deferNetworkObject.GetComponent(); + // Slowly increment the despawn tick count as we process the chain of deferred despawns + deferComponent.DeferDespawnTick = DeferDespawnTick + 1; + // This should get updated on all non-authority instances before they despawn + m_ValidateDirtyNetworkVarUpdate.Value = new NetworkBehaviourReference(deferComponent); + } + else + { + ReachedLastChainInstance?.Invoke(NetworkManager.LocalClientId); + } + base.OnDeferringDespawn(despawnTick); + } + + private bool m_DeferredDespawn; + private void Update() + { + if (!IsSpawned || !HasAuthority || m_DeferredDespawn) + { + return; + } + + // Wait until all clients have this instance + foreach (var clientId in NetworkManager.ConnectedClientsIds) + { + if (!ClientRelativeInstances.ContainsKey(clientId)) + { + // exit early if the client doesn't exist yet + return; + } + + if (!ClientRelativeInstances[clientId].ContainsKey(NetworkObjectId)) + { + // exit early if the client hasn't spawned a clone of this instance yet + return; + } + + if (clientId == NetworkManager.LocalClientId) + { + continue; + } + + // This should happen shortly afte the instances spawns (based on the deferred despawn count) + if (!IsRoot && !ClientRelativeInstances[clientId][NetworkObjectId].WasContactedByPeviousChainMember) + { + // exit early if the non-authority instance has not been contacted yet + return; + } + } + + // If we made it here, then defer despawn this instance + InvokeDespawn(); + m_DeferredDespawn = true; + } + + private void Log(string message) + { + if (!EnableVerbose) + { + return; + } + Debug.Log($"[{name}][Client-{NetworkManager.LocalClientId}][{NetworkObjectId}] {message}"); + } + } +} diff --git a/Tests/Runtime/DistributedAuthority/DeferredDespawningTests.cs.meta b/Tests/Runtime/DistributedAuthority/DeferredDespawningTests.cs.meta new file mode 100644 index 0000000..e7d54c6 --- /dev/null +++ b/Tests/Runtime/DistributedAuthority/DeferredDespawningTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c7b700919b058f446a75a398d5be9af4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Tests/Runtime/DistributedAuthority/DistributeObjectsTests.cs b/Tests/Runtime/DistributedAuthority/DistributeObjectsTests.cs new file mode 100644 index 0000000..75a1e9c --- /dev/null +++ b/Tests/Runtime/DistributedAuthority/DistributeObjectsTests.cs @@ -0,0 +1,520 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using NUnit.Framework; +using Unity.Netcode.Components; +using Unity.Netcode.TestHelpers.Runtime; +using Unity.Netcode.Transports.UTP; +using UnityEngine; +using UnityEngine.TestTools; +using Random = UnityEngine.Random; + +namespace Unity.Netcode.RuntimeTests +{ + /// + /// Validates that distributable NetworkObjects are distributed upon + /// a client connecting or disconnecting. + /// + public class DistributeObjectsTests : IntegrationTestWithApproximation + { + private GameObject m_DistributeObject; + + private StringBuilder m_ErrorLog = new StringBuilder(); + + private const int k_LateJoinClientCount = 4; + protected override int NumberOfClients => 0; + + public DistributeObjectsTests() : base(HostOrServer.DAHost) + { + } + + protected override IEnumerator OnSetup() + { + m_ObjectToValidate = null; + return base.OnSetup(); + } + + protected override void OnServerAndClientsCreated() + { + var serverTransport = m_ServerNetworkManager.NetworkConfig.NetworkTransport as UnityTransport; + // I hate having to add time to our tests, but in case a VM is running slow the disconnect timeout needs to be reasonably high + serverTransport.DisconnectTimeoutMS = 1000; + m_DistributeObject = CreateNetworkObjectPrefab("DisObject"); + m_DistributeObject.AddComponent(); + m_DistributeObject.AddComponent(); + + // Set baseline to be distributable + var networkObject = m_DistributeObject.GetComponent(); + networkObject.SetOwnershipStatus(NetworkObject.OwnershipStatus.Distributable); + networkObject.DontDestroyWithOwner = true; + base.OnServerAndClientsCreated(); + } + + protected override IEnumerator OnServerAndClientsConnected() + { + m_ServerNetworkManager.SpawnManager.EnableDistributeLogging = m_EnableVerboseDebug; + m_ServerNetworkManager.ConnectionManager.EnableDistributeLogging = m_EnableVerboseDebug; + return base.OnServerAndClientsConnected(); + } + + private NetworkObject m_ObjectToValidate; + + private bool ValidateObjectSpawnedOnAllClients() + { + m_ErrorLog.Clear(); + + var networkObjectId = m_ObjectToValidate.NetworkObjectId; + var name = m_ObjectToValidate.name; + if (!UseCMBService() && !m_ServerNetworkManager.SpawnManager.SpawnedObjects.ContainsKey(networkObjectId)) + { + m_ErrorLog.Append($"Client-{m_ServerNetworkManager.LocalClientId} has not spawned {name}!"); + return false; + } + + foreach (var client in m_ClientNetworkManagers) + { + if (!client.SpawnManager.SpawnedObjects.ContainsKey(networkObjectId)) + { + m_ErrorLog.Append($"Client-{client.LocalClientId} has not spawned {name}!"); + return false; + } + } + return true; + } + + private const int k_ObjectCount = 20; + + private bool ValidateDistributedObjectsSpawned(bool lateJoining) + { + m_ErrorLog.Clear(); + var hostId = m_ServerNetworkManager.LocalClientId; + if (!DistributeObjectsTestHelper.DistributedObjects.ContainsKey(hostId)) + { + m_ErrorLog.AppendLine($"[Client-{hostId}] Does not have an entry in the root of the {nameof(DistributeObjectsTestHelper.DistributedObjects)} table!"); + return false; + } + var daHostObjectTracking = DistributeObjectsTestHelper.DistributedObjects[hostId]; + if (!daHostObjectTracking.ContainsKey(hostId)) + { + m_ErrorLog.AppendLine($"[Client-{hostId}] Does not have a local an entry in the {nameof(DistributeObjectsTestHelper.DistributedObjects)} table!"); + return false; + } + + var daHostObjects = daHostObjectTracking[hostId]; + var expected = 0; + if (lateJoining) + { + expected = k_ObjectCount / (m_ClientNetworkManagers.Count() + 1); + } + else + { + expected = k_ObjectCount / (m_ClientNetworkManagers.Where((c) => c.IsConnectedClient).Count() + 1); + } + + // It should theoretically be the expected or... + if (daHostObjects.Count != expected) + { + // due to not rounding one more than the expected + expected++; + if (daHostObjects.Count != expected) + { + m_ErrorLog.AppendLine($"[Client-{hostId}][General] Expected {expected} spawned objects, but only {daHostObjects.Count} exist!"); + return false; + } + } + + foreach (var networkObject in daHostObjects) + { + m_ObjectToValidate = networkObject.Value; + if (!ValidateObjectSpawnedOnAllClients()) + { + m_ErrorLog.AppendLine($"[{m_ObjectToValidate.name}] Was not spawned on all clients!"); + return false; + } + } + return true; + } + + private bool ValidateOwnershipTablesMatch() + { + m_ErrorLog.Clear(); + var hostId = m_ServerNetworkManager.LocalClientId; + var expectedEntries = m_ClientNetworkManagers.Where((c) => c.IsListening && c.IsConnectedClient).Count() + 1; + // Make sure all clients have an table created + if (DistributeObjectsTestHelper.DistributedObjects.Count < expectedEntries) + { + m_ErrorLog.AppendLine($"[General] Expected {expectedEntries} entries in the root of the {nameof(DistributeObjectsTestHelper.DistributedObjects)} table but only {DistributeObjectsTestHelper.DistributedObjects.Count} exist!"); + return false; + } + + if (!DistributeObjectsTestHelper.DistributedObjects.ContainsKey(hostId)) + { + m_ErrorLog.AppendLine($"[Client-{hostId}] Does not have an entry in the root of the {nameof(DistributeObjectsTestHelper.DistributedObjects)} table!"); + return false; + } + var daHostEntries = DistributeObjectsTestHelper.DistributedObjects[hostId]; + if (!daHostEntries.ContainsKey(hostId)) + { + m_ErrorLog.AppendLine($"[Client-{hostId}] Does not have a local an entry in the {nameof(DistributeObjectsTestHelper.DistributedObjects)} table!"); + return false; + } + var clients = m_ServerNetworkManager.ConnectedClientsIds.ToList(); + clients.Remove(0); + + // Cycle through each client's entry on the DAHost to run a comparison + foreach (var hostClientEntry in daHostEntries) + { + foreach (var ownerEntry in hostClientEntry.Value) + { + foreach (var client in clients) + { + var clientOwnerTable = DistributeObjectsTestHelper.DistributedObjects[client]; + if (!clientOwnerTable.ContainsKey(hostClientEntry.Key)) + { + m_ErrorLog.AppendLine($"[Client-{client}] No ownership table exists the client relative section of the {nameof(DistributeObjectsTestHelper.DistributedObjects)} table!"); + return false; + } + var clientEntry = clientOwnerTable[hostClientEntry.Key]; + if (!clientEntry.ContainsKey(ownerEntry.Key)) + { + m_ErrorLog.AppendLine($"[Client-{client}] {ownerEntry.Value.name} does not exists in Client-{client}'s sub-section for Owner-{hostClientEntry.Key} relative section of the {nameof(DistributeObjectsTestHelper.DistributedObjects)} table!"); + return false; + } + var clientObjectEntry = clientEntry[ownerEntry.Key]; + if (clientObjectEntry.OwnerClientId != ownerEntry.Value.OwnerClientId) + { + m_ErrorLog.AppendLine($"[Client-{client}][Owner Mismatch] {clientObjectEntry.OwnerClientId} does equal {ownerEntry.Value.OwnerClientId}!"); + return false; + } + // Assure the observers match + foreach (var observer in ownerEntry.Value.Observers) + { + if (!clientObjectEntry.Observers.Contains(observer)) + { + m_ErrorLog.AppendLine($"[Client-{client}][Observer Mismatch] {nameof(NetworkObject)} {clientObjectEntry.name}'s observers does not contain {observer}, but the authority instance does!"); + return false; + } + } + } + } + } + return true; + } + + private bool ValidateTransformsMatch() + { + m_ErrorLog.Clear(); + var hostId = m_ServerNetworkManager.LocalClientId; + var daHostEntries = DistributeObjectsTestHelper.DistributedObjects[hostId]; + var clients = m_ServerNetworkManager.ConnectedClientsIds.ToList(); + foreach (var clientOwner in daHostEntries.Keys) + { + // Cycle through the owner's objects + foreach (var entry in DistributeObjectsTestHelper.DistributedObjects[clientOwner][clientOwner].Values) + { + var ownerTestTransform = entry.GetComponent(); + // Compare against the other client instances of that object + foreach (var client in clients) + { + if (client == clientOwner) + { + continue; + } + + var clientObjectInstance = DistributeObjectsTestHelper.DistributedObjects[client][clientOwner][entry.NetworkObjectId]; + if (!ownerTestTransform.IsPositionClose(clientObjectInstance.transform.position)) + { + m_ErrorLog.AppendLine($"[Position Mismatch] Client-{client} Instance: {GetVector3Values(clientObjectInstance.transform.position)} != Owner Instance: {GetVector3Values(ownerTestTransform.transform.position)}!"); + return false; + } + } + } + } + return true; + } + + protected override void OnNewClientCreated(NetworkManager networkManager) + { + networkManager.NetworkConfig.Prefabs = m_ServerNetworkManager.NetworkConfig.Prefabs; + base.OnNewClientCreated(networkManager); + } + + private bool SpawnCountsMatch() + { + var passed = true; + var spawnCount = 0; + m_ErrorLog.Clear(); + if (!UseCMBService()) + { + spawnCount = m_ServerNetworkManager.SpawnManager.SpawnedObjects.Count; + } + else + { + spawnCount = m_ClientNetworkManagers[0].SpawnManager.SpawnedObjects.Count; + } + foreach (var client in m_ClientNetworkManagers) + { + var clientCount = client.SpawnManager.SpawnedObjects.Count; + if (clientCount != spawnCount) + { + m_ErrorLog.AppendLine($"[Client-{client.LocalClientId}] Has a spawn count of {clientCount} but {spawnCount} was expected!"); + passed = false; + } + } + return passed; + } + + /// + /// This is a straight forward validation for the distribution of NetworkObjects + /// upon a client connecting or disconnecting. It also validates that the observers + /// on each non-authority instance matches the authority instance's. Finally, it + /// also includes validation that NetworkTransform updates continue to update and + /// synchronize properly after ownership for a set number of objects has changed. + /// + [UnityTest] + public IEnumerator DistributeNetworkObjects() + { + for (int i = 0; i < k_ObjectCount; i++) + { + SpawnObject(m_DistributeObject, m_ServerNetworkManager); + } + + // Validate NetworkObjects get redistributed properly when a client joins + for (int j = 0; j < k_LateJoinClientCount; j++) + { + yield return CreateAndStartNewClient(); + + yield return WaitForConditionOrTimeOut(() => ValidateDistributedObjectsSpawned(true)); + AssertOnTimeout($"[Client-{j + 1}][Initial Spawn] Not all clients spawned all objects!\n {m_ErrorLog}"); + + yield return WaitForConditionOrTimeOut(ValidateOwnershipTablesMatch); + AssertOnTimeout($"[Client-{j + 1}][OnwershipTable Mismatch] {m_ErrorLog}"); + + // When ownership changes, the new owner will randomly pick a new target to move towards and will move towards the target. + // Validate all other instances of the NetworkObjects that have had newly assigned owners have matching positions to the + // newly assigned owenr's instance. + yield return WaitForConditionOrTimeOut(ValidateTransformsMatch); + AssertOnTimeout($"[Client-{j + 1}][Transform Mismatch] {m_ErrorLog}"); + DisplayOwnership(); + + yield return WaitForConditionOrTimeOut(SpawnCountsMatch); + AssertOnTimeout($"[Spawn Count Mismatch] {m_ErrorLog}"); + } + + // Validate NetworkObjects get redistributed properly when a client disconnects + for (int j = k_LateJoinClientCount - 1; j >= 0; j--) + { + var client = m_ClientNetworkManagers[j]; + + // Remove the client from the other clients' ownership tracking table + DistributeObjectsTestHelper.RemoveClient(client.LocalClientId); + + // Disconnect the client + yield return StopOneClient(client, true); + + //yield return new WaitForSeconds(0.1f); + + // Validate all tables match + yield return WaitForConditionOrTimeOut(ValidateOwnershipTablesMatch); + + AssertOnTimeout($"[Client-{j + 1}][OnwershipTable Mismatch] {m_ErrorLog}"); + + // When ownership changes, the new owner will randomly pick a new target to move towards and will move towards the target. + // Validate all other instances of the NetworkObjects that have had newly assigned owners have matching positions to the + // newly assigned owenr's instance. + yield return WaitForConditionOrTimeOut(ValidateTransformsMatch); + AssertOnTimeout($"[Client-{j + 1}][Transform Mismatch] {m_ErrorLog}"); + + // DANGO-TODO: Make this tied to verbose mode once we know the CMB Service integration works properly + DisplayOwnership(); + + yield return WaitForConditionOrTimeOut(SpawnCountsMatch); + AssertOnTimeout($"[Spawn Count Mismatch] {m_ErrorLog}"); + } + } + + private void DisplayOwnership() + { + m_ErrorLog.Clear(); + var daHostEntries = DistributeObjectsTestHelper.DistributedObjects[0]; + + foreach (var entry in daHostEntries) + { + m_ErrorLog.AppendLine($"[Client-{entry.Key}][Owned Objects: {entry.Value.Count}]"); + } + + VerboseDebug($"{m_ErrorLog}"); + } + + /// + /// This keeps track of each clients perspective of which NetworkObjects are owned by which client. + /// It is used to validate that all clients are in synch with ownership updates. + /// + public class DistributeObjectsTestHelper : NetworkBehaviour + { + /// + /// [Client Context][Client Owners][NetworkObjectId][NetworkObject] + /// + public static Dictionary>> DistributedObjects = new Dictionary>>(); + + public static void RemoveClient(ulong clientId) + { + foreach (var clients in DistributedObjects.Values) + { + clients.Remove(clientId); + } + DistributedObjects.Remove(clientId); + } + + internal ulong ClientId; + + public override void OnNetworkSpawn() + { + ClientId = NetworkManager.LocalClientId; + UpdateOwnerTableAdd(); + base.OnNetworkSpawn(); + } + + private void UpdateOwnerTableAdd() + { + if (!DistributedObjects.ContainsKey(ClientId)) + { + DistributedObjects.Add(ClientId, new Dictionary>()); + } + if (!DistributedObjects[ClientId].ContainsKey(OwnerClientId)) + { + DistributedObjects[ClientId].Add(OwnerClientId, new Dictionary()); + } + + if (DistributedObjects[ClientId][OwnerClientId].ContainsKey(NetworkObject.NetworkObjectId)) + { + throw new Exception($"[Client-{ClientId}][{name}] {nameof(NetworkObject)} already exists in Client-{ClientId}'s " + + $"DistributedObjects being tracking under Client-{OwnerClientId}'s list of owned {nameof(NetworkObject)}s!"); + } + DistributedObjects[ClientId][OwnerClientId].Add(NetworkObject.NetworkObjectId, NetworkObject); + } + + private void UpdateOwnerTableRemove(ulong previous) + { + // This does not need to exist when first starting, but will (at one point in testing) + // become valid. + if (DistributedObjects[ClientId].ContainsKey(previous)) + { + if (DistributedObjects[ClientId][previous].ContainsKey(NetworkObject.NetworkObjectId)) + { + DistributedObjects[ClientId][previous].Remove(NetworkObject.NetworkObjectId); + } + } + } + + protected override void OnOwnershipChanged(ulong previous, ulong current) + { + // At start, if NetworkSpawn has not been completed the local client ignores this + if (!DistributedObjects.ContainsKey(ClientId)) + { + return; + } + UpdateOwnerTableRemove(previous); + UpdateOwnerTableAdd(); + base.OnOwnershipChanged(previous, current); + } + } + + /// + /// This is used to validate that upon distributed ownership changes NetworkTransform sycnhronization + /// still works properly. + /// + public class DistributeTestTransform : NetworkTransform + { + private float m_DeltaVarPosition = 0.15f; + private float m_DeltaVarQauternion = 0.015f; + protected Vector3 GetRandomVector3(float min, float max, Vector3 baseLine, bool randomlyApplySign = false) + { + var retValue = new Vector3(baseLine.x * Random.Range(min, max), baseLine.y * Random.Range(min, max), baseLine.z * Random.Range(min, max)); + if (!randomlyApplySign) + { + return retValue; + } + + retValue.x *= Random.Range(1, 100) >= 50 ? -1 : 1; + retValue.y *= Random.Range(1, 100) >= 50 ? -1 : 1; + retValue.z *= Random.Range(1, 100) >= 50 ? -1 : 1; + return retValue; + } + + protected override bool OnIsServerAuthoritative() + { + var isOwnerAuth = base.OnIsServerAuthoritative(); + Assert.IsFalse(isOwnerAuth, $"Base {nameof(NetworkTransform)} did not automatically return false in distributed authority mode!"); + return isOwnerAuth; + } + + public override void OnNetworkSpawn() + { + base.OnNetworkSpawn(); + + if (CanCommitToTransform) + { + var randomPos = GetRandomVector3(1.0f, 10.0f, Vector3.one, true); + SetState(randomPos, null, null, false); + m_TargetPosition = randomPos; + } + } + + private Vector3 m_TargetPosition; + private Vector3 m_DirToTarget; + private bool m_ReachedTarget; + + protected override void OnOwnershipChanged(ulong previous, ulong current) + { + base.OnOwnershipChanged(previous, current); + m_TargetPosition = transform.position + GetRandomVector3(4.0f, 8.0f, Vector3.one, true); + m_DirToTarget = (m_TargetPosition - transform.position).normalized; + m_ReachedTarget = false; + } + + protected override void Update() + { + base.Update(); + + if (CanCommitToTransform) + { + if (!m_ReachedTarget) + { + var distance = Vector3.Distance(transform.position, m_TargetPosition); + + var speed = Mathf.Clamp(distance, 0.10f, 2.0f); + + transform.position += m_DirToTarget * speed * Time.deltaTime; + + m_ReachedTarget = IsPositionClose(m_TargetPosition); + } + } + } + + public bool IsPositionClose(Vector3 position) + { + return Approximately(transform.position, position); + } + + protected bool Approximately(Vector3 a, Vector3 b) + { + var deltaVariance = m_DeltaVarPosition; + return Math.Round(Mathf.Abs(a.x - b.x), 2) <= deltaVariance && + Math.Round(Mathf.Abs(a.y - b.y), 2) <= deltaVariance && + Math.Round(Mathf.Abs(a.z - b.z), 2) <= deltaVariance; + } + + protected bool Approximately(Quaternion a, Quaternion b) + { + var deltaVariance = m_DeltaVarQauternion; + return Mathf.Abs(a.x - b.x) <= deltaVariance && + Mathf.Abs(a.y - b.y) <= deltaVariance && + Mathf.Abs(a.z - b.z) <= deltaVariance && + Mathf.Abs(a.w - b.w) <= deltaVariance; + } + } + } +} diff --git a/Tests/Runtime/DistributedAuthority/DistributeObjectsTests.cs.meta b/Tests/Runtime/DistributedAuthority/DistributeObjectsTests.cs.meta new file mode 100644 index 0000000..b48a2d0 --- /dev/null +++ b/Tests/Runtime/DistributedAuthority/DistributeObjectsTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4a759aeb53d12d842899381b411f3d2e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Tests/Runtime/DistributedAuthority/DistributedAuthorityCodecTests.cs b/Tests/Runtime/DistributedAuthority/DistributedAuthorityCodecTests.cs new file mode 100644 index 0000000..58dd33b --- /dev/null +++ b/Tests/Runtime/DistributedAuthority/DistributedAuthorityCodecTests.cs @@ -0,0 +1,718 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using NUnit.Framework; +using Unity.Collections; +using Unity.Netcode.TestHelpers.Runtime; +using Unity.Netcode.Transports.UTP; +#if UTP_TRANSPORT_2_0_ABOVE +using Unity.Networking.Transport; +#endif +using UnityEngine; +using UnityEngine.SceneManagement; +using UnityEngine.TestTools; + +namespace Unity.Netcode.RuntimeTests +{ + public class DistributedAuthorityCodecTests : NetcodeIntegrationTest + { + protected override int NumberOfClients => 1; + + // Use the CMB Service for all tests + protected override bool UseCMBService() => true; + + // Set the session mode to distributed authority for all tests + protected override SessionModeTypes OnGetSessionmode() => SessionModeTypes.DistributedAuthority; + + private CodecTestHooks m_ClientCodecHook; + private NetworkManager Client => m_ClientNetworkManagers[0]; + + private string m_TransportHost = Environment.GetEnvironmentVariable("NGO_HOST") ?? "127.0.0.1"; + private const int k_TransportPort = 7777; + private const int k_ClientId = 0; + + private GameObject m_SpawnObject; + + public class TestNetworkComponent : NetworkBehaviour + { + public NetworkList MyNetworkList = new NetworkList(new List { 1, 2, 3 }); + + [Rpc(SendTo.NotAuthority)] + public void TestNotAuthorityRpc(byte[] _) + { + } + + [Rpc(SendTo.Authority)] + public void TestAuthorityRpc(byte[] _) + { + } + } + + protected override void OnOneTimeSetup() + { + // Prevents the tests from running if no CMB Service is detected +#if !UTP_TRANSPORT_2_0_ABOVE + Assert.Ignore("ignoring DA codec tests because UTP transport must be 2.0"); +#else + if (!CanConnectToServer(m_TransportHost, k_TransportPort)) + { + Assert.Ignore("ignoring DA codec tests because UTP transport cannot connect to the runtime"); + } +#endif + base.OnOneTimeSetup(); + } + + /// + /// Add any additional components to default player prefab + /// + protected override void OnCreatePlayerPrefab() + { + m_PlayerPrefab.AddComponent(); + base.OnCreatePlayerPrefab(); + } + + /// + /// Modify NetworkManager instances for settings specific to tests + /// + protected override void OnServerAndClientsCreated() + { + var utpTransport = Client.gameObject.AddComponent(); + Client.NetworkConfig.NetworkTransport = utpTransport; + Client.NetworkConfig.EnableSceneManagement = false; + Client.NetworkConfig.AutoSpawnPlayerPrefabClientSide = true; + utpTransport.ConnectionData.Address = Dns.GetHostAddresses(m_TransportHost).First().ToString(); + utpTransport.ConnectionData.Port = k_TransportPort; + Client.LogLevel = LogLevel.Developer; + + // Validate we are in distributed authority mode with client side spawning and using CMB Service + Assert.True(Client.DistributedAuthorityMode, "Distributed authority is not set!"); + Assert.True(Client.AutoSpawnPlayerPrefabClientSide, "Client side spawning is not set!"); + Assert.True(Client.CMBServiceConnection, "CMBServiceConnection is not set!"); + + // Create a prefab for creating and destroying tests (auto-registers with NetworkManagers) + m_SpawnObject = CreateNetworkObjectPrefab("TestObject"); + m_SpawnObject.AddComponent(); + + // Ignore the client connection timeout after starting the client + m_BypassConnectionTimeout = true; + } + + protected override IEnumerator OnStartedServerAndClients() + { + // Register hooks after starting clients and server (in this case just the one client) + // We do this at this point in time because the MessageManager exists (happens within the same call stack when starting NetworkManagers) + m_ClientCodecHook = new CodecTestHooks(); + Client.MessageManager.Hook(m_ClientCodecHook); + yield return base.OnStartedServerAndClients(); + + // wait for client to connect since m_BypassConnectionTimeout + yield return WaitForConditionOrTimeOut(() => Client.LocalClient.PlayerObject != null); + AssertOnTimeout($"Timed out waiting for the client's player to be spanwed!"); + } + + [UnityTest] + public IEnumerator AuthorityRpc() + { + var player = Client.LocalClient.PlayerObject; + player.OwnerClientId = Client.LocalClientId + 1; + + var networkComponent = player.GetComponent(); + networkComponent.UpdateNetworkProperties(); + networkComponent.TestAuthorityRpc(new byte[] { 1, 2, 3, 4 }); + + // Universal Rpcs are sent as a ProxyMessage (which contains an RpcMessage) + yield return m_ClientCodecHook.WaitForMessageReceived(); + } + + [UnityTest] + public IEnumerator ChangeOwnership() + { + var message = new ChangeOwnershipMessage + { + DistributedAuthorityMode = true, + NetworkObjectId = 100, + OwnerClientId = 2, + }; + + yield return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator ClientConnected() + { + var message = new ClientConnectedMessage() + { + ClientId = 2, + }; + + yield return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator ClientDisconnected() + { + var message = new ClientDisconnectedMessage() + { + ClientId = 2, + }; + + yield return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator CreateObject() + { + SpawnObject(m_SpawnObject, Client); + yield return m_ClientCodecHook.WaitForMessageReceived(); + } + + [UnityTest] + public IEnumerator DestroyObject() + { + var spawnedObject = SpawnObject(m_SpawnObject, Client); + yield return m_ClientCodecHook.WaitForMessageReceived(); + spawnedObject.GetComponent().Despawn(); + yield return m_ClientCodecHook.WaitForMessageReceived(); + } + + [UnityTest] + public IEnumerator Disconnect() + { + var message = new DisconnectReasonMessage + { + Reason = "test" + }; + + return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator NamedMessage() + { + var writeBuffer = new FastBufferWriter(sizeof(int), Allocator.Temp); + writeBuffer.WriteValueSafe(5); + + var message = new NamedMessage + { + Hash = 3, + SendData = writeBuffer, + }; + + yield return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator NetworkVariableDelta() + { + var message = new NetworkVariableDeltaMessage + { + NetworkObjectId = 0, + NetworkBehaviourIndex = 1, + DeliveryMappedNetworkVariableIndex = new HashSet { 2, 3, 4 }, + TargetClientId = 5, + NetworkBehaviour = Client.LocalClient.PlayerObject.GetComponent(), + }; + + yield return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator NotAuthorityRpc() + { + Client.LocalClient.PlayerObject.GetComponent().TestNotAuthorityRpc(new byte[] { 1, 2, 3, 4 }); + + // Universal Rpcs are sent as a ProxyMessage (which contains an RpcMessage) + yield return m_ClientCodecHook.WaitForMessageReceived(); + } + + [UnityTest] + public IEnumerator ParentSync() + { + var message = new ParentSyncMessage + { + NetworkObjectId = 0, + WorldPositionStays = true, + IsLatestParentSet = false, + Position = new Vector3(1, 2, 3), + Rotation = new Quaternion(4, 5, 6, 7), + Scale = new Vector3(8, 9, 10), + }; + + yield return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator SessionOwner() + { + var message = new SessionOwnerMessage() + { + SessionOwner = 2, + }; + + yield return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator ServerLog() + { + var message = new ServerLogMessage() + { + LogType = NetworkLog.LogType.Info, + Message = "test", + }; + + yield return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator UnnamedMessage() + { + var writeBuffer = new FastBufferWriter(sizeof(int), Allocator.Temp); + writeBuffer.WriteValueSafe(5); + + var message = new UnnamedMessage + { + SendData = writeBuffer, + }; + + yield return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator SceneEventMessageLoad() + { + Client.SceneManager.SkipSceneHandling = true; + var eventData = new SceneEventData(Client) + { + SceneEventType = SceneEventType.Load, + LoadSceneMode = LoadSceneMode.Single, + SceneEventProgressId = Guid.NewGuid(), + SceneHash = XXHash.Hash32("SomeRandomSceneName"), + SceneHandle = 23456, + }; + + var message = new SceneEventMessage() + { + EventData = eventData + }; + yield return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator SceneEventMessageLoadWithObjects() + { + Client.SceneManager.SkipSceneHandling = true; + var prefabNetworkObject = m_SpawnObject.GetComponent(); + + Client.SceneManager.ScenePlacedObjects.Add(0, new Dictionary() + { + { 1, prefabNetworkObject } + }); + var eventData = new SceneEventData(Client) + { + SceneEventType = SceneEventType.Load, + LoadSceneMode = LoadSceneMode.Single, + SceneEventProgressId = Guid.NewGuid(), + SceneHash = XXHash.Hash32("SomeRandomSceneName"), + SceneHandle = 23456, + }; + + var message = new SceneEventMessage() + { + EventData = eventData + }; + yield return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator SceneEventMessageUnload() + { + Client.SceneManager.SkipSceneHandling = true; + var eventData = new SceneEventData(Client) + { + SceneEventType = SceneEventType.Unload, + LoadSceneMode = LoadSceneMode.Single, + SceneEventProgressId = Guid.NewGuid(), + SceneHash = XXHash.Hash32("SomeRandomSceneName"), + SceneHandle = 23456, + }; + + var message = new SceneEventMessage() + { + EventData = eventData + }; + yield return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator SceneEventMessageLoadComplete() + { + Client.SceneManager.SkipSceneHandling = true; + var eventData = new SceneEventData(Client) + { + SceneEventType = SceneEventType.LoadComplete, + LoadSceneMode = LoadSceneMode.Single, + SceneEventProgressId = Guid.NewGuid(), + SceneHash = XXHash.Hash32("SomeRandomSceneName"), + SceneHandle = 23456, + }; + + var message = new SceneEventMessage() + { + EventData = eventData + }; + yield return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator SceneEventMessageUnloadComplete() + { + Client.SceneManager.SkipSceneHandling = true; + var eventData = new SceneEventData(Client) + { + SceneEventType = SceneEventType.UnloadComplete, + LoadSceneMode = LoadSceneMode.Single, + SceneEventProgressId = Guid.NewGuid(), + SceneHash = XXHash.Hash32("SomeRandomSceneName"), + SceneHandle = 23456, + }; + + var message = new SceneEventMessage() + { + EventData = eventData + }; + yield return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator SceneEventMessageLoadCompleted() + { + Client.SceneManager.SkipSceneHandling = true; + var eventData = new SceneEventData(Client) + { + SceneEventType = SceneEventType.LoadEventCompleted, + LoadSceneMode = LoadSceneMode.Single, + SceneEventProgressId = Guid.NewGuid(), + SceneHash = XXHash.Hash32("SomeRandomSceneName"), + SceneHandle = 23456, + ClientsCompleted = new List() { k_ClientId }, + ClientsTimedOut = new List() { 123456789 }, + }; + + var message = new SceneEventMessage() + { + EventData = eventData + }; + yield return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator SceneEventMessageUnloadLoadCompleted() + { + Client.SceneManager.SkipSceneHandling = true; + var eventData = new SceneEventData(Client) + { + SceneEventType = SceneEventType.UnloadEventCompleted, + LoadSceneMode = LoadSceneMode.Single, + SceneEventProgressId = Guid.NewGuid(), + SceneHash = XXHash.Hash32("SomeRandomSceneName"), + SceneHandle = 23456, + ClientsCompleted = new List() { k_ClientId }, + ClientsTimedOut = new List() { 123456789 }, + }; + + var message = new SceneEventMessage() + { + EventData = eventData + }; + yield return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator SceneEventMessageSynchronize() + { + Client.SceneManager.SkipSceneHandling = true; + var eventData = new SceneEventData(Client) + { + SceneEventType = SceneEventType.Synchronize, + LoadSceneMode = LoadSceneMode.Single, + ClientSynchronizationMode = LoadSceneMode.Single, + SceneHash = XXHash.Hash32("SomeRandomSceneName"), + SceneHandle = 23456, + ScenesToSynchronize = new Queue() + }; + eventData.ScenesToSynchronize.Enqueue(101); + eventData.SceneHandlesToSynchronize = new Queue(); + eventData.SceneHandlesToSynchronize.Enqueue(202); + + + var message = new SceneEventMessage() + { + EventData = eventData + }; + yield return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator SceneEventMessageReSynchronize() + { + Client.SceneManager.SkipSceneHandling = true; + var eventData = new SceneEventData(Client) + { + SceneEventType = SceneEventType.ReSynchronize, + LoadSceneMode = LoadSceneMode.Single, + ClientSynchronizationMode = LoadSceneMode.Single, + SceneHash = XXHash.Hash32("SomeRandomSceneName"), + SceneHandle = 23456, + }; + + var message = new SceneEventMessage() + { + EventData = eventData + }; + yield return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator SceneEventMessageSynchronizeComplete() + { + Client.SceneManager.SkipSceneHandling = true; + var eventData = new SceneEventData(Client) + { + SceneEventType = SceneEventType.ReSynchronize, + LoadSceneMode = LoadSceneMode.Single, + ClientSynchronizationMode = LoadSceneMode.Single, + SceneHash = XXHash.Hash32("SomeRandomSceneName"), + SceneHandle = 23456, + }; + + var message = new SceneEventMessage() + { + EventData = eventData + }; + yield return SendMessage(ref message); + } + + [UnityTest] + public IEnumerator SceneEventMessageActiveSceneChanged() + { + Client.SceneManager.SkipSceneHandling = true; + var eventData = new SceneEventData(Client) + { + SceneEventType = SceneEventType.ActiveSceneChanged, + ActiveSceneHash = XXHash.Hash32("ActiveScene") + }; + + var message = new SceneEventMessage() + { + EventData = eventData + }; + yield return SendMessage(ref message); + } + + [UnityTest, Ignore("Serializing twice causes data to disappear in the SceneManager for this event")] + public IEnumerator SceneEventMessageObjectSceneChanged() + { + Client.SceneManager.SkipSceneHandling = true; + var prefabNetworkObject = m_SpawnObject.GetComponent(); + Client.SceneManager.ObjectsMigratedIntoNewScene = new Dictionary>> + { + { 0, new Dictionary>()} + }; + + Client.SceneManager.ObjectsMigratedIntoNewScene[0].Add(Client.LocalClientId, new List() { prefabNetworkObject }); + var eventData = new SceneEventData(Client) + { + SceneEventType = SceneEventType.ObjectSceneChanged, + }; + + var message = new SceneEventMessage() + { + EventData = eventData + }; + yield return SendMessage(ref message); + } + + + private IEnumerator SendMessage(ref T message) where T : INetworkMessage + { + Client.MessageManager.SetVersion(k_ClientId, XXHash.Hash32(typeof(T).FullName), 0); + + var clientIds = new NativeArray(1, Allocator.Temp); + clientIds[0] = k_ClientId; + Client.MessageManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, clientIds); + Client.MessageManager.ProcessSendQueues(); + return m_ClientCodecHook.WaitForMessageReceived(message); + } + +#if UTP_TRANSPORT_2_0_ABOVE + private static bool CanConnectToServer(string host, ushort port, double timeoutMs = 100) + { + var address = Dns.GetHostAddresses(host).First(); + var endpoint = NetworkEndpoint.Parse(address.ToString(), port); + + var driver = NetworkDriver.Create(); + var connection = driver.Connect(endpoint); + + var start = DateTime.Now; + var ev = Networking.Transport.NetworkEvent.Type.Empty; + while (ev != Networking.Transport.NetworkEvent.Type.Connect) + { + driver.ScheduleUpdate().Complete(); + ev = driver.PopEventForConnection(connection, out _, out _); + + if (DateTime.Now - start > TimeSpan.FromMilliseconds(timeoutMs)) + { + return false; + } + } + + driver.Disconnect(connection); + return true; + } +#endif + } + + internal class CodecTestHooks : INetworkHooks + { + private Dictionary> m_ExpectedMessages = new Dictionary>(); + private Dictionary> m_ReceivedMessages = new Dictionary>(); + + private struct TestMessage + { + public string Name; + public byte[] Data; + } + + public void OnBeforeSendMessage(ulong clientId, ref T message, NetworkDelivery delivery) where T : INetworkMessage + { + if (message is ConnectionRequestMessage) + { + return; + } + + var writer = new FastBufferWriter(1024, Allocator.Temp); + message.Serialize(writer, 0); + + var testName = TestContext.CurrentContext.Test.Name; + if (!m_ExpectedMessages.ContainsKey(testName)) + { + m_ExpectedMessages[testName] = new Queue(); + } + + m_ExpectedMessages[testName].Enqueue(new TestMessage + { + Name = typeof(T).ToString(), + Data = writer.ToArray(), + }); + + writer.Dispose(); + } + + public void OnAfterSendMessage(ulong clientId, ref T message, NetworkDelivery delivery, int messageSizeBytes) where T : INetworkMessage + { + } + + public void OnBeforeReceiveMessage(ulong senderId, Type messageType, int messageSizeBytes) + { + } + + + public void OnAfterReceiveMessage(ulong senderId, Type messageType, int messageSizeBytes) + { + } + + + public void OnBeforeSendBatch(ulong clientId, int messageCount, int batchSizeInBytes, NetworkDelivery delivery) + { + } + + + public void OnAfterSendBatch(ulong clientId, int messageCount, int batchSizeInBytes, NetworkDelivery delivery) + { + } + + + public void OnBeforeReceiveBatch(ulong senderId, int messageCount, int batchSizeInBytes) + { + } + + + public void OnAfterReceiveBatch(ulong senderId, int messageCount, int batchSizeInBytes) + { + } + + + public bool OnVerifyCanSend(ulong destinationId, Type messageType, NetworkDelivery delivery) + { + return true; + } + + public bool OnVerifyCanReceive(ulong senderId, Type messageType, FastBufferReader messageContent, ref NetworkContext context) + { + if (messageType == typeof(ConnectionApprovedMessage)) + { + return true; + } + + var testName = TestContext.CurrentContext.Test.Name; + Assert.True(m_ExpectedMessages.ContainsKey(testName)); + Assert.IsNotEmpty(m_ExpectedMessages[testName]); + + var nextMessage = m_ExpectedMessages[testName].Dequeue(); + Assert.AreEqual(messageType.ToString(), nextMessage.Name, $"received unexpected message type: {messageType}"); + + if (!m_ReceivedMessages.ContainsKey(testName)) + { + m_ReceivedMessages[testName] = new HashSet(); + } + + m_ReceivedMessages[testName].Add(messageType.ToString()); + + // ServerLogMessage is an exception - it gets decoded correctly, but the bytes from the runtime do not directly match those sent by the SDK. + if (messageType == typeof(ServerLogMessage)) + { + return true; + } + + var expectedBytes = nextMessage.Data; + var receivedBytes = messageContent.ToArray(); + Assert.AreEqual(expectedBytes, receivedBytes); + + return true; + } + + public void OnBeforeHandleMessage(ref T message, ref NetworkContext context) where T : INetworkMessage + { + } + + public void OnAfterHandleMessage(ref T message, ref NetworkContext context) where T : INetworkMessage + { + } + + public IEnumerator WaitForMessageReceived(float timeout = 5) where T : INetworkMessage + { + var testName = TestContext.CurrentContext.Test.Name; + var messageType = typeof(T).FullName; + var startTime = Time.realtimeSinceStartup; + + while ((!m_ReceivedMessages.ContainsKey(testName) || !m_ReceivedMessages[testName].Contains(messageType)) && Time.realtimeSinceStartup - startTime < timeout) + { + yield return null; + } + + Assert.True(m_ReceivedMessages.ContainsKey(testName), "failed to receive any messages"); + Assert.True(m_ReceivedMessages[testName].Contains(messageType), $"failed to receive {messageType} message, received: {string.Join(", ", m_ReceivedMessages[testName])}"); + + // Reset received messages + m_ReceivedMessages[testName] = new HashSet(); + } + + public IEnumerator WaitForMessageReceived(T _, float timeout = 5) where T : INetworkMessage + { + return WaitForMessageReceived(timeout: timeout); + } + } +} diff --git a/Tests/Runtime/DistributedAuthority/DistributedAuthorityCodecTests.cs.meta b/Tests/Runtime/DistributedAuthority/DistributedAuthorityCodecTests.cs.meta new file mode 100644 index 0000000..72b937f --- /dev/null +++ b/Tests/Runtime/DistributedAuthority/DistributedAuthorityCodecTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4cec6e6e1b9bdb746806290355d8cb50 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Tests/Runtime/DistributedAuthority/NetworkClientAndPlayerObjectTests.cs b/Tests/Runtime/DistributedAuthority/NetworkClientAndPlayerObjectTests.cs new file mode 100644 index 0000000..fa7a641 --- /dev/null +++ b/Tests/Runtime/DistributedAuthority/NetworkClientAndPlayerObjectTests.cs @@ -0,0 +1,298 @@ +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using NUnit.Framework; +using Unity.Netcode.TestHelpers.Runtime; +using UnityEngine; +using UnityEngine.TestTools; +using Random = UnityEngine.Random; + + +namespace Unity.Netcode.RuntimeTests +{ + [TestFixture(HostOrServer.Host)] + [TestFixture(HostOrServer.Server)] + [TestFixture(HostOrServer.DAHost)] + public class NetworkClientAndPlayerObjectTests : NetcodeIntegrationTest + { + private const int k_PlayerPrefabCount = 6; + protected override int NumberOfClients => 2; + + private List m_PlayerPrefabs = new List(); + private Dictionary m_ChangedPlayerPrefabs = new Dictionary(); + + + public NetworkClientAndPlayerObjectTests(HostOrServer hostOrServer) : base(hostOrServer) + { + } + + protected override IEnumerator OnTearDown() + { + m_PlayerPrefabs.Clear(); + return base.OnTearDown(); + } + + protected override void OnServerAndClientsCreated() + { + m_PlayerPrefabs.Clear(); + for (int i = 0; i < k_PlayerPrefabCount; i++) + { + m_PlayerPrefabs.Add(CreateNetworkObjectPrefab($"PlayerPrefab{i}")); + } + base.OnServerAndClientsCreated(); + } + + protected override void OnNewClientCreated(NetworkManager networkManager) + { + networkManager.NetworkConfig.Prefabs = m_ServerNetworkManager.NetworkConfig.Prefabs; + if (m_DistributedAuthority) + { + networkManager.OnFetchLocalPlayerPrefabToSpawn = FetchPlayerPrefabToSpawn; + } + base.OnNewClientCreated(networkManager); + } + + /// + /// Only for distributed authority mode + /// + /// a unique player prefab for the player + private GameObject FetchPlayerPrefabToSpawn() + { + var prefabObject = GetRandomPlayerPrefab(); + var clientId = m_ClientNetworkManagers[m_ClientNetworkManagers.Length - 1].LocalClientId; + m_ChangedPlayerPrefabs.Add(clientId, prefabObject.GlobalObjectIdHash); + return prefabObject.gameObject; + } + + + private StringBuilder m_ErrorLogLevel3 = new StringBuilder(); + private StringBuilder m_ErrorLogLevel2 = new StringBuilder(); + private StringBuilder m_ErrorLogLevel1 = new StringBuilder(); + + private bool ValidateNetworkClient(NetworkClient networkClient) + { + m_ErrorLogLevel3.Clear(); + var success = true; + if (networkClient == null) + { + m_ErrorLogLevel3.Append($"[NetworkClient is NULL]"); + // Log error + success = false; + } + if (!networkClient.IsConnected) + { + m_ErrorLogLevel3.Append($"[NetworkClient {nameof(NetworkClient.IsConnected)}] is false]"); + // Log error + success = false; + } + if (networkClient.PlayerObject == null) + { + m_ErrorLogLevel3.Append($"[NetworkClient {nameof(NetworkClient.PlayerObject)}] is NULL]"); + // Log error + success = false; + } + return success; + } + + private bool ValidateNetworkManagerNetworkClients(NetworkManager networkManager) + { + var success = true; + m_ErrorLogLevel2.Clear(); + + // Number of connected clients plus the DAHost + var expectedCount = m_ClientNetworkManagers.Length + (m_UseHost ? 1 : 0); + + if (networkManager.ConnectedClients.Count != expectedCount) + { + m_ErrorLogLevel2.Append($"[{nameof(NetworkManager.ConnectedClients)} count: {networkManager.ConnectedClients.Count} vs expected count: {expectedCount}]"); + // Log error + success = false; + } + + if (m_UseHost && !ValidateNetworkClient(networkManager.LocalClient)) + { + m_ErrorLogLevel2.Append($"[Local NetworkClient: --({m_ErrorLogLevel3})--]"); + // Log error + success = false; + } + + foreach (var networkClient in networkManager.ConnectedClients) + { + // When just running a server, ignore the server's local NetworkClient + if (!m_UseHost && networkManager.IsServer) + { + continue; + } + if (!ValidateNetworkClient(networkManager.LocalClient)) + { + // Log error + success = false; + m_ErrorLogLevel2.Append($"[NetworkClient-{networkManager.LocalClientId}: --({m_ErrorLogLevel3})--]"); + } + } + return success; + } + + private bool AllNetworkClientsValidated() + { + m_ErrorLogLevel1.Clear(); + var success = true; + + if (!UseCMBService()) + { + if (!ValidateNetworkManagerNetworkClients(m_ServerNetworkManager)) + { + m_ErrorLogLevel1.AppendLine($"[Client-{m_ServerNetworkManager.LocalClientId}]{m_ErrorLogLevel2}"); + // Log error + success = false; + } + } + + foreach (var clientNetworkManager in m_ClientNetworkManagers) + { + if (!ValidateNetworkManagerNetworkClients(clientNetworkManager)) + { + m_ErrorLogLevel1.AppendLine($"[Client-{clientNetworkManager.LocalClientId}]{m_ErrorLogLevel2}"); + // Log error + success = false; + } + } + return success; + } + + /// + /// Validates that all NetworkManager instances have valid NetworkClients for all connected clients + /// Validates the same thing when a client late joins and when a client disconnects. + /// + [UnityTest] + public IEnumerator ValidateNetworkClients() + { + // Validate the initial clients created + yield return WaitForConditionOrTimeOut(AllNetworkClientsValidated); + AssertOnTimeout($"[Start] Not all NetworkClients were valid!\n{m_ErrorLogLevel1}"); + + // Late join a player and revalidate all instances + yield return CreateAndStartNewClient(); + yield return WaitForConditionOrTimeOut(AllNetworkClientsValidated); + AssertOnTimeout($"[Late Join] Not all NetworkClients were valid!\n{m_ErrorLogLevel1}"); + + // Disconnect a player and revalidate all instances + var initialCount = m_ClientNetworkManagers.Length; + yield return StopOneClient(m_ClientNetworkManagers[m_ClientNetworkManagers.Length - 1], true); + // Sanity check to assure we removed the NetworkManager from m_ClientNetworkManagers + Assert.False(initialCount == m_ClientNetworkManagers.Length, $"Disconnected player and expected total number of client {nameof(NetworkManager)}s " + + $"to be {initialCount - 1} but it was still {initialCount}!"); + + yield return WaitForConditionOrTimeOut(AllNetworkClientsValidated); + AssertOnTimeout($"[Client Disconnect] Not all NetworkClients were valid!\n{m_ErrorLogLevel1}"); + + } + + /// + /// Verify that all NetworkClients are pointing to the correct player object, even if + /// the player object is changed. + /// + private bool ValidatePlayerObjectOnClients(NetworkManager clientToValidate) + { + m_ErrorLogLevel2.Clear(); + var success = true; + var expectedGlobalObjectIdHash = m_ChangedPlayerPrefabs[clientToValidate.LocalClientId]; + if (expectedGlobalObjectIdHash != clientToValidate.LocalClient.PlayerObject.GlobalObjectIdHash) + { + m_ErrorLogLevel2.Append($"[Local Prefab Mismatch][Expected GlobalObjectIdHash: {expectedGlobalObjectIdHash} but was {clientToValidate.LocalClient.PlayerObject.GlobalObjectIdHash}]"); + success = false; + } + + foreach (var client in m_ClientNetworkManagers) + { + if (client == clientToValidate) + { + continue; + } + var remoteNetworkClient = client.ConnectedClients[clientToValidate.LocalClientId]; + if (expectedGlobalObjectIdHash != remoteNetworkClient.PlayerObject.GlobalObjectIdHash) + { + m_ErrorLogLevel2.Append($"[Client-{client.LocalClientId} Prefab Mismatch][Expected GlobalObjectIdHash: {expectedGlobalObjectIdHash} but was {remoteNetworkClient.PlayerObject.GlobalObjectIdHash}]"); + success = false; + } + } + return success; + } + + private bool ValidateAllPlayerObjects() + { + m_ErrorLogLevel1.Clear(); + var success = true; + if (m_UseHost && !UseCMBService()) + { + if (!ValidatePlayerObjectOnClients(m_ServerNetworkManager)) + { + m_ErrorLogLevel1.AppendLine($"[Client-{m_ServerNetworkManager.LocalClientId}]{m_ErrorLogLevel2}"); + success = false; + } + } + + foreach (var client in m_ClientNetworkManagers) + { + if (!ValidatePlayerObjectOnClients(client)) + { + m_ErrorLogLevel1.AppendLine($"[Client-{client.LocalClientId}]{m_ErrorLogLevel2}"); + success = false; + } + } + + return success; + } + + private NetworkObject GetRandomPlayerPrefab() + { + return m_PlayerPrefabs[Random.Range(0, m_PlayerPrefabs.Count() - 1)].GetComponent(); + } + + /// + /// Validates that when a client changes their player object that all connected client instances mirror the + /// client's new player object. + /// + [UnityTest] + public IEnumerator ValidatePlayerObjects() + { + // Just do a quick validation for all connected client's NetworkClients + yield return WaitForConditionOrTimeOut(AllNetworkClientsValidated); + AssertOnTimeout($"Not all NetworkClients were valid!\n{m_ErrorLogLevel1}"); + + // Now, have each client spawn a new player object + m_ChangedPlayerPrefabs.Clear(); + var playerInstance = (GameObject)null; + var playerPrefabToSpawn = (NetworkObject)null; + if (m_UseHost) + { + playerPrefabToSpawn = GetRandomPlayerPrefab(); + playerInstance = SpawnPlayerObject(playerPrefabToSpawn.gameObject, m_ServerNetworkManager); + m_ChangedPlayerPrefabs.Add(m_ServerNetworkManager.LocalClientId, playerPrefabToSpawn.GlobalObjectIdHash); + } + + foreach (var client in m_ClientNetworkManagers) + { + playerPrefabToSpawn = GetRandomPlayerPrefab(); + playerInstance = SpawnPlayerObject(playerPrefabToSpawn.gameObject, client); + m_ChangedPlayerPrefabs.Add(client.LocalClientId, playerPrefabToSpawn.GlobalObjectIdHash); + } + + // Validate that all connected clients' NetworkClient instances have the correct player object for each connected client + yield return WaitForConditionOrTimeOut(ValidateAllPlayerObjects); + AssertOnTimeout($"[Existing Clients] Not all NetworkClient player objects were valid!\n{m_ErrorLogLevel1}"); + + // Distributed authority only feature validation (NetworkManager.OnFetchLocalPlayerPrefabToSpawn) + if (m_DistributedAuthority) + { + // Now test the fetch prefab callback to assure that this is working correctly. + // Start a new client and wait for it to connect + yield return CreateAndStartNewClient(); + // Do another validation pass. + yield return WaitForConditionOrTimeOut(ValidateAllPlayerObjects); + AssertOnTimeout($"[Late Joined Client] Not all NetworkClient player objects were valid!\n{m_ErrorLogLevel1}"); + } + } + } +} diff --git a/Tests/Runtime/DistributedAuthority/NetworkClientAndPlayerObjectTests.cs.meta b/Tests/Runtime/DistributedAuthority/NetworkClientAndPlayerObjectTests.cs.meta new file mode 100644 index 0000000..bacb517 --- /dev/null +++ b/Tests/Runtime/DistributedAuthority/NetworkClientAndPlayerObjectTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: db4c955c05fdc194eb47e7774b9c5101 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Tests/Runtime/DistributedAuthority/OwnershipPermissionsTests.cs b/Tests/Runtime/DistributedAuthority/OwnershipPermissionsTests.cs new file mode 100644 index 0000000..e56798b --- /dev/null +++ b/Tests/Runtime/DistributedAuthority/OwnershipPermissionsTests.cs @@ -0,0 +1,406 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using NUnit.Framework; +using Unity.Netcode.TestHelpers.Runtime; +using UnityEngine; +using UnityEngine.TestTools; + +namespace Unity.Netcode.RuntimeTests +{ + public class OwnershipPermissionsTests : IntegrationTestWithApproximation + { + private GameObject m_PermissionsObject; + + private StringBuilder m_ErrorLog = new StringBuilder(); + + protected override int NumberOfClients => 4; + + public OwnershipPermissionsTests() : base(HostOrServer.DAHost) + { + } + + protected override IEnumerator OnSetup() + { + m_ObjectToValidate = null; + OwnershipPermissionsTestHelper.CurrentOwnedInstance = null; + return base.OnSetup(); + } + + protected override void OnServerAndClientsCreated() + { + m_PermissionsObject = CreateNetworkObjectPrefab("PermObject"); + m_PermissionsObject.AddComponent(); + + base.OnServerAndClientsCreated(); + } + + private NetworkObject m_ObjectToValidate; + + private bool ValidateObjectSpawnedOnAllClients() + { + m_ErrorLog.Clear(); + + var networkObjectId = m_ObjectToValidate.NetworkObjectId; + var name = m_ObjectToValidate.name; + if (!UseCMBService() && !m_ServerNetworkManager.SpawnManager.SpawnedObjects.ContainsKey(networkObjectId)) + { + m_ErrorLog.Append($"Client-{m_ServerNetworkManager.LocalClientId} has not spawned {name}!"); + return false; + } + + foreach (var client in m_ClientNetworkManagers) + { + if (!client.SpawnManager.SpawnedObjects.ContainsKey(networkObjectId)) + { + m_ErrorLog.Append($"Client-{client.LocalClientId} has not spawned {name}!"); + return false; + } + } + return true; + } + + private bool ValidatePermissionsOnAllClients() + { + var currentPermissions = (ushort)m_ObjectToValidate.Ownership; + var otherPermissions = (ushort)0; + var networkObjectId = m_ObjectToValidate.NetworkObjectId; + var objectName = m_ObjectToValidate.name; + m_ErrorLog.Clear(); + if (!UseCMBService()) + { + otherPermissions = (ushort)m_ServerNetworkManager.SpawnManager.SpawnedObjects[networkObjectId].Ownership; + if (currentPermissions != otherPermissions) + { + m_ErrorLog.Append($"Client-{m_ServerNetworkManager.LocalClientId} permissions for {objectName} is {otherPermissions} when it should be {currentPermissions}!"); + return false; + } + } + + foreach (var client in m_ClientNetworkManagers) + { + otherPermissions = (ushort)client.SpawnManager.SpawnedObjects[networkObjectId].Ownership; + if (currentPermissions != otherPermissions) + { + m_ErrorLog.Append($"Client-{client.LocalClientId} permissions for {objectName} is {otherPermissions} when it should be {currentPermissions}!"); + return false; + } + } + return true; + } + + private bool ValidateAllInstancesAreOwnedByClient(ulong clientId) + { + var networkObjectId = m_ObjectToValidate.NetworkObjectId; + var otherNetworkObject = (NetworkObject)null; + m_ErrorLog.Clear(); + if (!UseCMBService()) + { + otherNetworkObject = m_ServerNetworkManager.SpawnManager.SpawnedObjects[networkObjectId]; + if (otherNetworkObject.OwnerClientId != clientId) + { + m_ErrorLog.Append($"[Client-{m_ServerNetworkManager.LocalClientId}][{otherNetworkObject.name}] Expected owner to be {clientId} but it was {otherNetworkObject.OwnerClientId}!"); + return false; + } + } + + foreach (var client in m_ClientNetworkManagers) + { + otherNetworkObject = client.SpawnManager.SpawnedObjects[networkObjectId]; + if (otherNetworkObject.OwnerClientId != clientId) + { + m_ErrorLog.Append($"[Client-{client.LocalClientId}][{otherNetworkObject.name}] Expected owner to be {clientId} but it was {otherNetworkObject.OwnerClientId}!"); + return false; + } + } + return true; + } + + [UnityTest] + public IEnumerator ValidateOwnershipPermissionsTest() + { + var firstInstance = SpawnObject(m_PermissionsObject, m_ClientNetworkManagers[0]).GetComponent(); + OwnershipPermissionsTestHelper.CurrentOwnedInstance = firstInstance; + var firstInstanceHelper = firstInstance.GetComponent(); + var networkObjectId = firstInstance.NetworkObjectId; + m_ObjectToValidate = OwnershipPermissionsTestHelper.CurrentOwnedInstance; + yield return WaitForConditionOrTimeOut(ValidateObjectSpawnedOnAllClients); + AssertOnTimeout($"[Failed To Spawn] {firstInstance.name}: \n {m_ErrorLog}"); + + // Validate the base non-assigned persmissions value for all instances are the same. + yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); + AssertOnTimeout($"[Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}"); + + ////////////////////////////////////// + // Setting & Removing Ownership Flags: + ////////////////////////////////////// + + // Now, cycle through all permissions and validate that when the owner changes them the change + // is synchronized on all non-owner clients. + foreach (var permissionObject in Enum.GetValues(typeof(NetworkObject.OwnershipStatus))) + { + var permission = (NetworkObject.OwnershipStatus)permissionObject; + // Add the status + firstInstance.SetOwnershipStatus(permission); + // Validate the persmissions value for all instances are the same. + yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); + AssertOnTimeout($"[Add][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}"); + + // Remove the status unless it is None (ignore None). + if (permission == NetworkObject.OwnershipStatus.None) + { + continue; + } + firstInstance.RemoveOwnershipStatus(permission); + // Validate the persmissions value for all instances are the same. + yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); + AssertOnTimeout($"[Remove][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}"); + } + + //Add multiple flags at the same time + var multipleFlags = NetworkObject.OwnershipStatus.Transferable | NetworkObject.OwnershipStatus.Distributable | NetworkObject.OwnershipStatus.RequestRequired; + firstInstance.SetOwnershipStatus(multipleFlags, true); + Assert.IsTrue(firstInstance.HasOwnershipStatus(multipleFlags), $"[Set][Multi-flag Failure] Expected: {(ushort)multipleFlags} but was {(ushort)firstInstance.Ownership}!"); + + // Validate the persmissions value for all instances are the same. + yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); + AssertOnTimeout($"[Set Multiple][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}"); + + // Remove multiple flags at the same time + multipleFlags = NetworkObject.OwnershipStatus.Transferable | NetworkObject.OwnershipStatus.RequestRequired; + firstInstance.RemoveOwnershipStatus(multipleFlags); + // Validate the two flags no longer are set + Assert.IsFalse(firstInstance.HasOwnershipStatus(multipleFlags), $"[Remove][Multi-flag Failure] Expected: {(ushort)NetworkObject.OwnershipStatus.Distributable} but was {(ushort)firstInstance.Ownership}!"); + // Validate that the Distributable flag is still set + Assert.IsTrue(firstInstance.HasOwnershipStatus(NetworkObject.OwnershipStatus.Distributable), $"[Remove][Multi-flag Failure] Expected: {(ushort)NetworkObject.OwnershipStatus.Distributable} but was {(ushort)firstInstance.Ownership}!"); + + // Validate the persmissions value for all instances are the same. + yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); + AssertOnTimeout($"[Set Multiple][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}"); + + ////////////////////// + // Changing Ownership: + ////////////////////// + + // Clear the flags, set the permissions to transferrable, and lock ownership in one pass. + firstInstance.SetOwnershipStatus(NetworkObject.OwnershipStatus.Transferable, true, NetworkObject.OwnershipLockActions.SetAndLock); + + // Validate the persmissions value for all instances are the same. + yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); + AssertOnTimeout($"[Reset][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}"); + + var secondInstance = m_ClientNetworkManagers[1].SpawnManager.SpawnedObjects[networkObjectId]; + var secondInstanceHelper = secondInstance.GetComponent(); + + secondInstance.ChangeOwnership(m_ClientNetworkManagers[1].LocalClientId); + Assert.IsTrue(secondInstanceHelper.OwnershipPermissionsFailureStatus == NetworkObject.OwnershipPermissionsFailureStatus.Locked, + $"Expected {secondInstance.name} to return {NetworkObject.OwnershipPermissionsFailureStatus.Locked} but its permission failure" + + $" status is {secondInstanceHelper.OwnershipPermissionsFailureStatus}!"); + + firstInstance.SetOwnershipLock(false); + // Validate the persmissions value for all instances are the same. + yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); + AssertOnTimeout($"[Unlock][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}"); + + // Sanity check to assure this client's instance isn't already the owner. + Assert.True(!secondInstance.IsOwner, $"[Ownership Check] Client-{m_ClientNetworkManagers[1].LocalClientId} already is the owner!"); + // Now try to acquire ownership + secondInstance.ChangeOwnership(m_ClientNetworkManagers[1].LocalClientId); + + // Validate the persmissions value for all instances are the same + yield return WaitForConditionOrTimeOut(() => secondInstance.IsOwner); + AssertOnTimeout($"[Acquire Ownership Failed] Client-{m_ClientNetworkManagers[1].LocalClientId} failed to get ownership!"); + + m_ObjectToValidate = OwnershipPermissionsTestHelper.CurrentOwnedInstance; + // Validate all other client instances are showing the same owner + yield return WaitForConditionOrTimeOut(() => ValidateAllInstancesAreOwnedByClient(m_ClientNetworkManagers[1].LocalClientId)); + AssertOnTimeout($"[Ownership Mismatch] {secondInstance.name}: \n {m_ErrorLog}"); + + // Clear the flags, set the permissions to RequestRequired, and lock ownership in one pass. + secondInstance.SetOwnershipStatus(NetworkObject.OwnershipStatus.RequestRequired, true); + + // Validate the persmissions value for all instances are the same. + yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); + AssertOnTimeout($"[Unlock][Permissions Mismatch] {secondInstance.name}: \n {m_ErrorLog}"); + + // Attempt to acquire ownership by just changing it + firstInstance.ChangeOwnership(firstInstance.NetworkManager.LocalClientId); + + // Assure we are denied ownership due to it requiring ownership be requested + Assert.IsTrue(firstInstanceHelper.OwnershipPermissionsFailureStatus == NetworkObject.OwnershipPermissionsFailureStatus.RequestRequired, + $"Expected {secondInstance.name} to return {NetworkObject.OwnershipPermissionsFailureStatus.RequestRequired} but its permission failure" + + $" status is {secondInstanceHelper.OwnershipPermissionsFailureStatus}!"); + + ////////////////////////////////// + // Test for single race condition: + ////////////////////////////////// + + // Start with a request for the client we expect to be given ownership + var requestStatus = firstInstance.RequestOwnership(); + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent, $"Client-{firstInstance.NetworkManager.LocalClientId} was unabled to send a request for ownership because: {requestStatus}!"); + + // Get the 3rd client to send a request at the "relatively" same time + var thirdInstance = m_ClientNetworkManagers[2].SpawnManager.SpawnedObjects[networkObjectId]; + var thirdInstanceHelper = thirdInstance.GetComponent(); + + // At the same time send a request by the third client. + requestStatus = thirdInstance.RequestOwnership(); + + // We expect the 3rd client's request should be able to be sent at this time as well (i.e. creates the race condition between two clients) + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent, $"Client-{m_ServerNetworkManager.LocalClientId} was unabled to send a request for ownership because: {requestStatus}!"); + + // We expect the first requesting client to be given ownership + yield return WaitForConditionOrTimeOut(() => firstInstance.IsOwner); + AssertOnTimeout($"[Acquire Ownership Failed] Client-{firstInstance.NetworkManager.LocalClientId} failed to get ownership! ({firstInstanceHelper.OwnershipRequestResponseStatus})(Owner: {OwnershipPermissionsTestHelper.CurrentOwnedInstance.OwnerClientId}"); + m_ObjectToValidate = OwnershipPermissionsTestHelper.CurrentOwnedInstance; + + // Just do a sanity check to assure ownership has changed on all clients. + yield return WaitForConditionOrTimeOut(() => ValidateAllInstancesAreOwnedByClient(firstInstance.NetworkManager.LocalClientId)); + AssertOnTimeout($"[Ownership Mismatch] {firstInstance.name}: \n {m_ErrorLog}"); + + // Now, the third client should get a RequestInProgress returned as their request response + yield return WaitForConditionOrTimeOut(() => thirdInstanceHelper.OwnershipRequestResponseStatus == NetworkObject.OwnershipRequestResponseStatus.RequestInProgress); + AssertOnTimeout($"[Request In Progress Failed] Client-{thirdInstanceHelper.NetworkManager.LocalClientId} did not get the right request denied reponse!"); + + // Validate the persmissions value for all instances are the same. + yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); + AssertOnTimeout($"[Unlock][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}"); + + /////////////////////////////////////////////// + // Test for multiple ownership race conditions: + /////////////////////////////////////////////// + + // Get the 4th client's instance + var fourthInstance = m_ClientNetworkManagers[3].SpawnManager.SpawnedObjects[networkObjectId]; + var fourthInstanceHelper = fourthInstance.GetComponent(); + + // Send out a request from three clients at the same time + // The first one sent (and received for this test) gets ownership + requestStatus = secondInstance.RequestOwnership(); + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent, $"Client-{secondInstance.NetworkManager.LocalClientId} was unabled to send a request for ownership because: {requestStatus}!"); + requestStatus = thirdInstance.RequestOwnership(); + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent, $"Client-{thirdInstance.NetworkManager.LocalClientId} was unabled to send a request for ownership because: {requestStatus}!"); + requestStatus = fourthInstance.RequestOwnership(); + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent, $"Client-{fourthInstance.NetworkManager.LocalClientId} was unabled to send a request for ownership because: {requestStatus}!"); + + // The 2nd and 3rd client should be denied and the 4th client should be approved + yield return WaitForConditionOrTimeOut(() => + (fourthInstanceHelper.OwnershipRequestResponseStatus == NetworkObject.OwnershipRequestResponseStatus.RequestInProgress) && + (thirdInstanceHelper.OwnershipRequestResponseStatus == NetworkObject.OwnershipRequestResponseStatus.RequestInProgress) && + (secondInstanceHelper.OwnershipRequestResponseStatus == NetworkObject.OwnershipRequestResponseStatus.Approved) + ); + AssertOnTimeout($"[Targeted Owner] Client-{secondInstanceHelper.NetworkManager.LocalClientId} did not get the right request denied reponse: {secondInstanceHelper.OwnershipRequestResponseStatus}!"); + m_ObjectToValidate = OwnershipPermissionsTestHelper.CurrentOwnedInstance; + // Just do a sanity check to assure ownership has changed on all clients. + yield return WaitForConditionOrTimeOut(() => ValidateAllInstancesAreOwnedByClient(secondInstance.NetworkManager.LocalClientId)); + AssertOnTimeout($"[Ownership Mismatch] {secondInstance.name}: \n {m_ErrorLog}"); + + // Validate the persmissions value for all instances are the same. + yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); + AssertOnTimeout($"[Unlock][Permissions Mismatch] {secondInstance.name}: \n {m_ErrorLog}"); + + /////////////////////////////////////////////// + // Test for targeted ownership request: + /////////////////////////////////////////////// + + // Now get the DAHost's client's instance + var daHostInstance = m_ServerNetworkManager.SpawnManager.SpawnedObjects[networkObjectId]; + var daHostInstanceHelper = daHostInstance.GetComponent(); + + secondInstanceHelper.AllowOwnershipRequest = true; + secondInstanceHelper.OnlyAllowTargetClientId = true; + secondInstanceHelper.ClientToAllowOwnership = daHostInstance.NetworkManager.LocalClientId; + + // Send out a request from all three clients + requestStatus = firstInstance.RequestOwnership(); + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent, $"Client-{firstInstance.NetworkManager.LocalClientId} was unabled to send a request for ownership because: {requestStatus}!"); + requestStatus = thirdInstance.RequestOwnership(); + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent, $"Client-{thirdInstance.NetworkManager.LocalClientId} was unabled to send a request for ownership because: {requestStatus}!"); + requestStatus = fourthInstance.RequestOwnership(); + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent, $"Client-{fourthInstance.NetworkManager.LocalClientId} was unabled to send a request for ownership because: {requestStatus}!"); + requestStatus = daHostInstance.RequestOwnership(); + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent, $"Client-{daHostInstance.NetworkManager.LocalClientId} was unabled to send a request for ownership because: {requestStatus}!"); + + // The server and the 2nd client should be denied and the third client should be approved + yield return WaitForConditionOrTimeOut(() => + (firstInstanceHelper.OwnershipRequestResponseStatus == NetworkObject.OwnershipRequestResponseStatus.Denied) && + (thirdInstanceHelper.OwnershipRequestResponseStatus == NetworkObject.OwnershipRequestResponseStatus.Denied) && + (fourthInstanceHelper.OwnershipRequestResponseStatus == NetworkObject.OwnershipRequestResponseStatus.Denied) && + (daHostInstanceHelper.OwnershipRequestResponseStatus == NetworkObject.OwnershipRequestResponseStatus.Approved) + ); + AssertOnTimeout($"[Targeted Owner] Client-{daHostInstance.NetworkManager.LocalClientId} did not get the right request reponse: {daHostInstanceHelper.OwnershipRequestResponseStatus} Expecting: {NetworkObject.OwnershipRequestResponseStatus.Approved}!"); + } + + public class OwnershipPermissionsTestHelper : NetworkBehaviour + { + public static NetworkObject CurrentOwnedInstance; + + public static Dictionary>> DistributedObjects = new Dictionary>>(); + + public bool AllowOwnershipRequest = true; + public bool OnlyAllowTargetClientId = false; + public ulong ClientToAllowOwnership; + + public NetworkObject.OwnershipRequestResponseStatus OwnershipRequestResponseStatus { get; private set; } + + public NetworkObject.OwnershipPermissionsFailureStatus OwnershipPermissionsFailureStatus { get; private set; } + + public NetworkObject.OwnershipRequestResponseStatus ExpectOwnershipRequestResponseStatus { get; set; } + + public override void OnNetworkSpawn() + { + NetworkObject.OnOwnershipRequested = OnOwnershipRequested; + NetworkObject.OnOwnershipRequestResponse = OnOwnershipRequestResponse; + NetworkObject.OnOwnershipPermissionsFailure = OnOwnershipPermissionsFailure; + + base.OnNetworkSpawn(); + } + + private bool OnOwnershipRequested(ulong clientId) + { + // If we are not allowing any client to request (without locking), then deny all requests + if (!AllowOwnershipRequest) + { + return false; + } + + // If we are only allowing a specific client and the requesting client is not the target, + // then deny the request + if (OnlyAllowTargetClientId && clientId != ClientToAllowOwnership) + { + return false; + } + + // Otherwise, approve the request + return true; + } + + private void OnOwnershipRequestResponse(NetworkObject.OwnershipRequestResponseStatus ownershipRequestResponseStatus) + { + OwnershipRequestResponseStatus = ownershipRequestResponseStatus; + } + + private void OnOwnershipPermissionsFailure(NetworkObject.OwnershipPermissionsFailureStatus ownershipPermissionsFailureStatus) + { + OwnershipPermissionsFailureStatus = ownershipPermissionsFailureStatus; + } + + public override void OnNetworkDespawn() + { + NetworkObject.OnOwnershipRequested = null; + NetworkObject.OnOwnershipRequestResponse = null; + base.OnNetworkSpawn(); + } + + protected override void OnOwnershipChanged(ulong previous, ulong current) + { + if (current == NetworkManager.LocalClientId) + { + CurrentOwnedInstance = NetworkObject; + } + base.OnOwnershipChanged(previous, current); + } + } + } +} diff --git a/Tests/Runtime/DistributedAuthority/OwnershipPermissionsTests.cs.meta b/Tests/Runtime/DistributedAuthority/OwnershipPermissionsTests.cs.meta new file mode 100644 index 0000000..392a011 --- /dev/null +++ b/Tests/Runtime/DistributedAuthority/OwnershipPermissionsTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f35119aec96feb348a49b8e0fcd779de +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Tests/Runtime/HiddenVariableTests.cs b/Tests/Runtime/HiddenVariableTests.cs index 83d1597..c87fe80 100644 --- a/Tests/Runtime/HiddenVariableTests.cs +++ b/Tests/Runtime/HiddenVariableTests.cs @@ -22,13 +22,24 @@ namespace Unity.Netcode.RuntimeTests public static int ExpectedSize = 0; public static int SpawnCount = 0; + public static bool EnableVerbose; + + public static void VerboseDebug(string message) + { + if (!EnableVerbose) + { + return; + } + Debug.Log(message); + } + public override void OnNetworkSpawn() { if (!IsServer) { ClientInstancesSpawned.Add(NetworkObject); } - Debug.Log($"{nameof(HiddenVariableObject)}.{nameof(OnNetworkSpawn)}() with value {MyNetworkVariable.Value}"); + VerboseDebug($"{nameof(HiddenVariableObject)}.{nameof(OnNetworkSpawn)}() with value {MyNetworkVariable.Value}"); MyNetworkVariable.OnValueChanged += Changed; MyNetworkList.OnListChanged += ListChanged; @@ -48,7 +59,7 @@ namespace Unity.Netcode.RuntimeTests public void Changed(int before, int after) { - Debug.Log($"Value changed from {before} to {after} on {NetworkManager.LocalClientId}"); + VerboseDebug($"Value changed from {before} to {after} on {NetworkManager.LocalClientId}"); ValueOnClient[NetworkManager.LocalClientId] = after; } public void ListChanged(NetworkListEvent listEvent) @@ -155,18 +166,19 @@ namespace Unity.Netcode.RuntimeTests yield return WaitForConditionOrTimeOut(VerifyLists); Assert.IsFalse(s_GlobalTimeoutHelper.TimedOut, "Timed out waiting for all clients to have identical values!"); - Debug.Log("Value changed"); + VerboseDebug("Value changed"); } [UnityTest] public IEnumerator HiddenVariableTest() { + HiddenVariableObject.EnableVerbose = m_EnableVerboseDebug; HiddenVariableObject.SpawnCount = 0; HiddenVariableObject.ValueOnClient.Clear(); HiddenVariableObject.ExpectedSize = 0; HiddenVariableObject.SpawnCount = 0; - Debug.Log("Running test"); + VerboseDebug("Running test"); // ==== Spawn object with ownership on one client var client = m_ServerNetworkManager.ConnectedClientsList[1]; @@ -178,7 +190,7 @@ namespace Unity.Netcode.RuntimeTests // === Check spawn occurred yield return WaitForSpawnCount(NumberOfClients + 1); Debug.Assert(HiddenVariableObject.SpawnCount == NumberOfClients + 1); - Debug.Log("Objects spawned"); + VerboseDebug("Objects spawned"); // ==== Set the NetworkVariable value to 2 HiddenVariableObject.ExpectedSize = 1; @@ -207,7 +219,7 @@ namespace Unity.Netcode.RuntimeTests // ==== Wait for object to be spawned yield return WaitForSpawnCount(1); Debug.Assert(HiddenVariableObject.SpawnCount == 1); - Debug.Log("Object spawned"); + VerboseDebug("Object spawned"); // ==== We need a refresh for the newly re-spawned object yield return RefreshGameObects(4); diff --git a/Tests/Runtime/ListChangedTest.cs b/Tests/Runtime/ListChangedTest.cs index f88f70a..45f7081 100644 --- a/Tests/Runtime/ListChangedTest.cs +++ b/Tests/Runtime/ListChangedTest.cs @@ -1,4 +1,5 @@ using System.Collections; +using NUnit.Framework; using Unity.Netcode.TestHelpers.Runtime; using UnityEngine; using UnityEngine.TestTools; @@ -45,6 +46,8 @@ namespace Unity.Netcode.RuntimeTests } } + [TestFixture(SessionModeTypes.DistributedAuthority)] + [TestFixture(SessionModeTypes.ClientServer)] public class NetworkListChangedTests : NetcodeIntegrationTest { protected override int NumberOfClients => 2; @@ -54,6 +57,8 @@ namespace Unity.Netcode.RuntimeTests private NetworkObject m_NetSpawnedObject1; + public NetworkListChangedTests(SessionModeTypes sessionModeType) : base(sessionModeType) { } + protected override void OnServerAndClientsCreated() { m_PrefabToSpawn = CreateNetworkObjectPrefab("ListChangedObject"); diff --git a/Tests/Runtime/Messaging/NamedMessageTests.cs b/Tests/Runtime/Messaging/NamedMessageTests.cs index 90eeb71..ae243cc 100644 --- a/Tests/Runtime/Messaging/NamedMessageTests.cs +++ b/Tests/Runtime/Messaging/NamedMessageTests.cs @@ -86,6 +86,24 @@ namespace Unity.Netcode.RuntimeTests Assert.AreEqual(m_ServerNetworkManager.LocalClientId, receivedMessageSender); } + private void MockNamedMessageCallback(ulong sender, FastBufferReader reader) + { + + } + + [Test] + public void NullOrEmptyNamedMessageDoesNotThrowException() + { + LogAssert.Expect(UnityEngine.LogType.Error, $"[{nameof(CustomMessagingManager.RegisterNamedMessageHandler)}] Cannot register a named message of type null or empty!"); + m_ServerNetworkManager.CustomMessagingManager.RegisterNamedMessageHandler(string.Empty, MockNamedMessageCallback); + LogAssert.Expect(UnityEngine.LogType.Error, $"[{nameof(CustomMessagingManager.RegisterNamedMessageHandler)}] Cannot register a named message of type null or empty!"); + m_ServerNetworkManager.CustomMessagingManager.RegisterNamedMessageHandler(null, MockNamedMessageCallback); + LogAssert.Expect(UnityEngine.LogType.Error, $"[{nameof(CustomMessagingManager.UnregisterNamedMessageHandler)}] Cannot unregister a named message of type null or empty!"); + m_ServerNetworkManager.CustomMessagingManager.UnregisterNamedMessageHandler(string.Empty); + LogAssert.Expect(UnityEngine.LogType.Error, $"[{nameof(CustomMessagingManager.UnregisterNamedMessageHandler)}] Cannot unregister a named message of type null or empty!"); + m_ServerNetworkManager.CustomMessagingManager.UnregisterNamedMessageHandler(null); + } + [UnityTest] public IEnumerator NamedMessageIsReceivedOnMultipleClientsWithContent() { diff --git a/Tests/Runtime/Metrics/NetworkObjectMetricsTests.cs b/Tests/Runtime/Metrics/NetworkObjectMetricsTests.cs index 1679607..dce1864 100644 --- a/Tests/Runtime/Metrics/NetworkObjectMetricsTests.cs +++ b/Tests/Runtime/Metrics/NetworkObjectMetricsTests.cs @@ -73,20 +73,18 @@ namespace Unity.Netcode.RuntimeTests.Metrics [UnityTest] public IEnumerator TrackNetworkObjectDestroySentMetric() { - var networkObject = SpawnNetworkObject(); - - yield return s_DefaultWaitForTick; - var waitForMetricEvent = new WaitForEventMetricValues(ServerMetrics.Dispatcher, NetworkMetricTypes.ObjectDestroyedSent); + var networkObject = SpawnNetworkObject(); var objectName = networkObject.name; Server.SpawnManager.OnDespawnObject(networkObject, true); - yield return s_DefaultWaitForTick; + // Wait for the metric to be received yield return waitForMetricEvent.WaitForMetricsReceived(); - var objectDestroyedSentMetricValues = waitForMetricEvent.AssertMetricValuesHaveBeenFound(); - Assert.AreEqual(2, objectDestroyedSentMetricValues.Count); + + // The server should have sent 1 destroy message to the 1 client connected + Assert.AreEqual(1, objectDestroyedSentMetricValues.Count); var objectDestroyed = objectDestroyedSentMetricValues.Last(); Assert.AreEqual(Client.LocalClientId, objectDestroyed.Connection.Id); @@ -242,20 +240,47 @@ namespace Unity.Netcode.RuntimeTests.Metrics [UnityTest] public IEnumerator TrackNetworkObjectCountAfterDespawnOnClient() { - var objectList = Server.SpawnManager.SpawnedObjectsList; - for (int i = objectList.Count - 1; i >= 0; --i) + var initialSpawnCount = Server.SpawnManager.SpawnedObjectsList.Count; + var spawnedObjects = new List(); + //By default, we have 2 network objects and will have spawned 4 so we want to wait for metrics to tell us we have 6 spawned objects + var waitForGaugeValues = new WaitForGaugeMetricValues(ClientMetrics.Dispatcher, NetworkMetricTypes.NetworkObjects, metric => (int)metric == 6); + + for (int i = 0; i < 4; i++) { - objectList.ElementAt(i).Despawn(); + spawnedObjects.Add(SpawnObject(m_NewNetworkPrefab, Server)); } - //By default, we have 2 network objects - //There's a slight delay between the spawn on the server and the spawn on the client - //We want to have metrics when the value is different than the 2 default one to confirm the client has the new value - var waitForGaugeValues = new WaitForGaugeMetricValues(ClientMetrics.Dispatcher, NetworkMetricTypes.NetworkObjects, metric => (int)metric != 2); - yield return waitForGaugeValues.WaitForMetricsReceived(); - var value = waitForGaugeValues.AssertMetricValueHaveBeenFound(); + Assert.AreEqual(6, value); + + // Create a new gauge that waits for the initial spawned client count + waitForGaugeValues = new WaitForGaugeMetricValues(ClientMetrics.Dispatcher, NetworkMetricTypes.NetworkObjects, metric => (int)metric != 6); + + // Now despawn the 4 spawned objects + foreach (var spawnedObject in spawnedObjects) + { + spawnedObject.GetComponent().Despawn(); + } + spawnedObjects.Clear(); + yield return waitForGaugeValues.WaitForMetricsReceived(); + value = waitForGaugeValues.AssertMetricValueHaveBeenFound(); + + // Validate the value is equals to the spawned objects prior to spawning the network prefab instances + Assert.AreEqual(initialSpawnCount, value); + + // Create a new gauge that waits for the initial spawned client count + waitForGaugeValues = new WaitForGaugeMetricValues(ClientMetrics.Dispatcher, NetworkMetricTypes.NetworkObjects, metric => (int)metric == 0); + + // Now assure despawning players are being tracked too + var spawnedPlayers = Server.SpawnManager.SpawnedObjectsList.ToList(); + foreach (var spawnedObject in spawnedPlayers) + { + spawnedObject.Despawn(); + } + yield return waitForGaugeValues.WaitForMetricsReceived(); + value = waitForGaugeValues.AssertMetricValueHaveBeenFound(); + // Nothing should be spawned on the client at this point Assert.AreEqual(0, value); } #endif diff --git a/Tests/Runtime/NetworkBehaviourUpdaterTests.cs b/Tests/Runtime/NetworkBehaviourUpdaterTests.cs index 90e0be7..9cf021a 100644 --- a/Tests/Runtime/NetworkBehaviourUpdaterTests.cs +++ b/Tests/Runtime/NetworkBehaviourUpdaterTests.cs @@ -14,33 +14,6 @@ namespace Unity.Netcode.RuntimeTests /// public class NetVarContainer : NetworkBehaviour { - /// - /// Creates a prefab with two instances of this NetworkBehaviour - /// - /// - public static GameObject CreatePrefabGameObject(NetVarCombinationTypes netVarsToCheck) - { - var gameObject = new GameObject - { - // Always a good idea to name the Prefab for easy identification purposes - name = "NetVarContainerObject" - }; - var networkObject = gameObject.AddComponent(); - - // Create the two instances of the NetVarContainer components and add them to the - // GameObject of this prefab - var netVarContainer = gameObject.AddComponent(); - netVarContainer.NumberOfNetVarsToCheck = netVarsToCheck.FirstType; - netVarContainer.ValueToSetNetVarTo = NetworkBehaviourUpdaterTests.NetVarValueToSet; - netVarContainer = gameObject.AddComponent(); - netVarContainer.NumberOfNetVarsToCheck = netVarsToCheck.SecondType; - netVarContainer.ValueToSetNetVarTo = NetworkBehaviourUpdaterTests.NetVarValueToSet; - - NetcodeIntegrationTestHelpers.MakeNetworkObjectTestPrefab(networkObject); - - return gameObject; - } - public enum NetVarsToCheck { One, @@ -106,10 +79,16 @@ namespace Unity.Netcode.RuntimeTests private NetworkVariable m_FirstValue = new NetworkVariable(); private NetworkVariable m_SeconValue = new NetworkVariable(); + public void SetOwnerWrite() + { + m_FirstValue = new NetworkVariable(default, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner); + m_SeconValue = new NetworkVariable(default, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner); + } + public override void OnNetworkSpawn() { - // Clients will register each NetworkObject when it is spawned - if (!IsServer) + // Non-Authority will register each NetworkObject when it is spawned + if ((NetworkManager.DistributedAuthorityMode && !IsOwner) || (!NetworkManager.DistributedAuthorityMode && !IsServer)) { NetworkBehaviourUpdaterTests.ClientSideNotifyObjectSpawned(gameObject); } @@ -121,7 +100,7 @@ namespace Unity.Netcode.RuntimeTests /// public void SetNetworkVariableValues() { - if (IsServer) + if ((NetworkManager.DistributedAuthorityMode && IsOwner) || (!NetworkManager.DistributedAuthorityMode && IsServer)) { switch (NumberOfNetVarsToCheck) { @@ -153,13 +132,56 @@ namespace Unity.Netcode.RuntimeTests public NetVarContainer.NetVarsToCheck SecondType; } + /// + /// Server and Distributed Authority modes require at least 1 client while the host does not. + /// + /// [Session Mode][Number of Clients][First NetVar Type][Second NetVar Type] + [TestFixture(HostOrServer.DAHost, 1, NetVarContainer.NetVarsToCheck.One, NetVarContainer.NetVarsToCheck.One)] + [TestFixture(HostOrServer.DAHost, 1, NetVarContainer.NetVarsToCheck.One, NetVarContainer.NetVarsToCheck.Two)] + [TestFixture(HostOrServer.DAHost, 1, NetVarContainer.NetVarsToCheck.Two, NetVarContainer.NetVarsToCheck.Two)] + [TestFixture(HostOrServer.DAHost, 2, NetVarContainer.NetVarsToCheck.One, NetVarContainer.NetVarsToCheck.One)] + [TestFixture(HostOrServer.DAHost, 2, NetVarContainer.NetVarsToCheck.One, NetVarContainer.NetVarsToCheck.Two)] + [TestFixture(HostOrServer.DAHost, 2, NetVarContainer.NetVarsToCheck.Two, NetVarContainer.NetVarsToCheck.Two)] + [TestFixture(HostOrServer.Server, 1, NetVarContainer.NetVarsToCheck.One, NetVarContainer.NetVarsToCheck.One)] + [TestFixture(HostOrServer.Server, 1, NetVarContainer.NetVarsToCheck.One, NetVarContainer.NetVarsToCheck.Two)] + [TestFixture(HostOrServer.Server, 1, NetVarContainer.NetVarsToCheck.Two, NetVarContainer.NetVarsToCheck.Two)] + [TestFixture(HostOrServer.Server, 2, NetVarContainer.NetVarsToCheck.One, NetVarContainer.NetVarsToCheck.One)] + [TestFixture(HostOrServer.Server, 2, NetVarContainer.NetVarsToCheck.One, NetVarContainer.NetVarsToCheck.Two)] + [TestFixture(HostOrServer.Server, 2, NetVarContainer.NetVarsToCheck.Two, NetVarContainer.NetVarsToCheck.Two)] + [TestFixture(HostOrServer.Host, 0, NetVarContainer.NetVarsToCheck.One, NetVarContainer.NetVarsToCheck.One)] + [TestFixture(HostOrServer.Host, 0, NetVarContainer.NetVarsToCheck.One, NetVarContainer.NetVarsToCheck.Two)] + [TestFixture(HostOrServer.Host, 0, NetVarContainer.NetVarsToCheck.Two, NetVarContainer.NetVarsToCheck.Two)] + [TestFixture(HostOrServer.Host, 1, NetVarContainer.NetVarsToCheck.One, NetVarContainer.NetVarsToCheck.One)] + [TestFixture(HostOrServer.Host, 1, NetVarContainer.NetVarsToCheck.One, NetVarContainer.NetVarsToCheck.Two)] + [TestFixture(HostOrServer.Host, 1, NetVarContainer.NetVarsToCheck.Two, NetVarContainer.NetVarsToCheck.Two)] + [TestFixture(HostOrServer.Host, 2, NetVarContainer.NetVarsToCheck.One, NetVarContainer.NetVarsToCheck.One)] + [TestFixture(HostOrServer.Host, 2, NetVarContainer.NetVarsToCheck.One, NetVarContainer.NetVarsToCheck.Two)] + [TestFixture(HostOrServer.Host, 2, NetVarContainer.NetVarsToCheck.Two, NetVarContainer.NetVarsToCheck.Two)] public class NetworkBehaviourUpdaterTests : NetcodeIntegrationTest { // Go ahead and create maximum number of clients (not all tests will use them) - protected override int NumberOfClients => 2; + protected override int NumberOfClients => m_NumberOfClients; public const int NetVarValueToSet = 1; private static List s_ClientSpawnedNetworkObjects = new List(); - private List m_ActiveClientsForCurrentTest; + private GameObject m_PrefabToSpawn; + private NetVarCombinationTypes m_NetVarCombinationTypes; + private int m_NumberOfClients = 0; + + public NetworkBehaviourUpdaterTests(HostOrServer hostOrServer, int numberOfClients, NetVarContainer.NetVarsToCheck first, NetVarContainer.NetVarsToCheck second) : base(hostOrServer) + { + m_NetVarCombinationTypes = new NetVarCombinationTypes() + { + FirstType = first, + SecondType = second + }; + m_NumberOfClients = numberOfClients; + } + + protected override IEnumerator OnSetup() + { + s_ClientSpawnedNetworkObjects.Clear(); + return base.OnSetup(); + } /// /// Clients will call this when NetworkObjects are spawned on their end @@ -173,70 +195,32 @@ namespace Unity.Netcode.RuntimeTests } } - protected override bool CanStartServerAndClients() + protected override void OnServerAndClientsCreated() { - return false; + m_PrefabToSpawn = CreateNetworkObjectPrefab("NetVarCont"); + // Create the two instances of the NetVarContainer components and add them to the + // GameObject of this prefab + var netVarContainer = m_PrefabToSpawn.AddComponent(); + netVarContainer.NumberOfNetVarsToCheck = m_NetVarCombinationTypes.FirstType; + if (m_SessionModeType == SessionModeTypes.DistributedAuthority) + { + netVarContainer.SetOwnerWrite(); + } + + netVarContainer.ValueToSetNetVarTo = NetVarValueToSet; + netVarContainer = m_PrefabToSpawn.AddComponent(); + + if (m_SessionModeType == SessionModeTypes.DistributedAuthority) + { + netVarContainer.SetOwnerWrite(); + } + + netVarContainer.NumberOfNetVarsToCheck = m_NetVarCombinationTypes.SecondType; + netVarContainer.ValueToSetNetVarTo = NetVarValueToSet; + + base.OnServerAndClientsCreated(); } - /// - /// Creates the server and client(s) required for this particular test iteration - /// - private IEnumerator StartClientsAndServer(bool useHost, int numberOfClients, GameObject prefabObject) - { - void AddNetworkPrefab(NetworkConfig config, NetworkPrefab prefab) - { - config.Prefabs.Add(prefab); - } - - // Sanity check to make sure we are not trying to create more clients than we have available to use - Assert.True(numberOfClients <= m_ClientNetworkManagers.Length); - m_ActiveClientsForCurrentTest = new List(); - - // Create a list of the clients to be used in this test from the available clients - for (int i = 0; i < numberOfClients; i++) - { - m_ActiveClientsForCurrentTest.Add(m_ClientNetworkManagers[i]); - } - - // Add the prefab to be used for this particular test iteration - var np = new NetworkPrefab { Prefab = prefabObject }; - AddNetworkPrefab(m_ServerNetworkManager.NetworkConfig, np); - m_ServerNetworkManager.NetworkConfig.TickRate = 30; - foreach (var clientManager in m_ActiveClientsForCurrentTest) - { - m_ServerNetworkManager.NetworkConfig.TickRate = 30; - AddNetworkPrefab(clientManager.NetworkConfig, np); - } - - // Now spin everything up normally - var clientsAsArry = m_ActiveClientsForCurrentTest.ToArray(); - Assert.True(NetcodeIntegrationTestHelpers.Start(useHost, m_ServerNetworkManager, clientsAsArry), "Failed to start server and client instances"); - - // Only if we have clients (not host) - if (numberOfClients > 0) - { - RegisterSceneManagerHandler(); - } - - // Wait for connection on client and server side - yield return WaitForClientsConnectedOrTimeOut(clientsAsArry); - } - - /// - /// This list replaces the original NetworkVariable types to be checked. - /// Both NetworkVariables are of type int and the original version of this test was testing - /// the NetworkBehaviour Update when there were 1 or more (i.e two) on the same NetworkBehaviour. - /// After reviewing, we really only needed to test a much smaller combination of types and so - /// this pre-generated array represents the reduced set of combinations to test. - /// Note: - /// The original test was also testing for no NetworkVariables of type int, which there ended up - /// being no reason to do that and only added to the length of the execution time for this test. - /// - public static NetVarCombinationTypes[] NetVarCombinationTypeValues = new[]{ - new NetVarCombinationTypes() { FirstType = NetVarContainer.NetVarsToCheck.One, SecondType = NetVarContainer.NetVarsToCheck.One }, - new NetVarCombinationTypes() { FirstType = NetVarContainer.NetVarsToCheck.One, SecondType = NetVarContainer.NetVarsToCheck.Two }, - new NetVarCombinationTypes() { FirstType = NetVarContainer.NetVarsToCheck.Two, SecondType = NetVarContainer.NetVarsToCheck.Two }}; - /// /// The updated BehaviourUpdaterAllTests was re-designed to replicate the same functionality being tested in the /// original version of this test with additional time out handling and a re-organization in the order of operations. @@ -246,59 +230,36 @@ namespace Unity.Netcode.RuntimeTests /// version like the desktop tests use). /// This update also updated how the server and clients were being constructed to help reduce the execution time. /// - /// whether to run the server as a host or not - /// the NetworkVariable combination types - /// number of clients to use for the test + /// whether to run the server as a host or not /// number of NetworkObjects to be spawned [UnityTest] - public IEnumerator BehaviourUpdaterAllTests([Values] bool useHost, - [ValueSource(nameof(NetVarCombinationTypeValues))] NetVarCombinationTypes varCombinationTypes, - [Values(0, 1, 2)] int nbClients, [Values(1, 2)] int numToSpawn) + public IEnumerator BehaviourUpdaterAllTests([Values(1, 2)] int numToSpawn) { - s_ClientSpawnedNetworkObjects.Clear(); - - // The edge case scenario where we can exit early is when we are running - // just the server (i.e. non-host) and there are zero clients. Under this - // edge case scenario of the various combinations we do not need to run - // this test as the IsDirty flag is never cleared when no clients exist at all. - if (nbClients == 0 && !useHost) - { - yield break; - } - - // Create our prefab based on the NetVarCombinationTypes - var prefabToSpawn = NetVarContainer.CreatePrefabGameObject(varCombinationTypes); - - yield return StartClientsAndServer(useHost, nbClients, prefabToSpawn); - // Tracks the server-side spawned prefab instances var spawnedPrefabs = new List(); - var tickInterval = 1.0f / m_ServerNetworkManager.NetworkConfig.TickRate; // Used to determine if the client-side checks of this test should be // executed or not as well is used to make sure all clients have spawned // the appropriate number of NetworkObjects with the NetVarContainer behaviour - var numberOfObjectsToSpawnOnClients = numToSpawn * nbClients; + var numberOfObjectsToSpawn = numToSpawn * NumberOfClients; + + var authority = m_SessionModeType == SessionModeTypes.DistributedAuthority ? m_ClientNetworkManagers[0] : m_ServerNetworkManager; // spawn the objects for (int i = 0; i < numToSpawn; i++) { - var spawnedObject = Object.Instantiate(prefabToSpawn); + var spawnedObject = Object.Instantiate(m_PrefabToSpawn); spawnedPrefabs.Add(spawnedObject); var networkSpawnedObject = spawnedObject.GetComponent(); - networkSpawnedObject.NetworkManagerOwner = m_ServerNetworkManager; + networkSpawnedObject.NetworkManagerOwner = authority; networkSpawnedObject.Spawn(); } - // When there are no clients (excluding when server is in host mode), we can skip all of this - // wait until all objects are spawned on the clients - if (numberOfObjectsToSpawnOnClients > 0) - { - // Waits for all clients to spawn the NetworkObjects - yield return WaitForConditionOrTimeOut(() => numberOfObjectsToSpawnOnClients == s_ClientSpawnedNetworkObjects.Count); - Assert.IsFalse(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for clients to report spawning objects! " + - $"Total reported client-side spawned objects {s_ClientSpawnedNetworkObjects.Count}"); - } + // Waits for all clients to spawn the NetworkObjects + yield return WaitForConditionOrTimeOut(() => numberOfObjectsToSpawn == s_ClientSpawnedNetworkObjects.Count); + Assert.IsFalse(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for clients to report spawning objects! " + + $"Total reported client-side spawned objects {s_ClientSpawnedNetworkObjects.Count}"); + // Once all clients have spawned the NetworkObjects, set the network variables for // those NetworkObjects on the server-side. @@ -312,39 +273,33 @@ namespace Unity.Netcode.RuntimeTests } // Update the NetworkBehaviours to make sure all network variables are no longer marked as dirty - m_ServerNetworkManager.BehaviourUpdater.NetworkBehaviourUpdate(); + authority.BehaviourUpdater.NetworkBehaviourUpdate(); // Verify that all network variables are no longer dirty on server side only if we have clients (including host) - foreach (var serverSpawnedObject in spawnedPrefabs) + foreach (var spawnedPrefab in spawnedPrefabs) { - var netVarContainers = serverSpawnedObject.GetComponents(); + var netVarContainers = spawnedPrefab.GetComponents(); foreach (var netVarContainer in netVarContainers) { Assert.False(netVarContainer.AreNetVarsDirty(), "Some NetworkVariables were still marked dirty after NetworkBehaviourUpdate!"); } } - // When there are no clients (excluding when server is in host mode), we can skip all of this - if (numberOfObjectsToSpawnOnClients > 0) + // Get a list of all NetVarContainer components on the client-side spawned NetworkObjects + var clientSideNetVarContainers = new List(); + foreach (var clientSpawnedObjects in s_ClientSpawnedNetworkObjects) { - // Get a list of all NetVarContainer components on the client-side spawned NetworkObjects - var clientSideNetVarContainers = new List(); - foreach (var clientSpawnedObjects in s_ClientSpawnedNetworkObjects) + var netVarContainers = clientSpawnedObjects.GetComponents(); + foreach (var netvarContiner in netVarContainers) { - var netVarContainers = clientSpawnedObjects.GetComponents(); - foreach (var netvarContiner in netVarContainers) - { - clientSideNetVarContainers.Add(netvarContiner); - } + clientSideNetVarContainers.Add(netvarContiner); } - - yield return WaitForConditionOrTimeOut(() => - clientSideNetVarContainers.Where(d => - d.HaveAllValuesChanged(NetVarValueToSet)).Count() == clientSideNetVarContainers.Count); - Assert.IsFalse(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for client side NetVarContainers to report all NetworkVariables have been updated!"); } - Object.DestroyImmediate(prefabToSpawn); + yield return WaitForConditionOrTimeOut(() => + clientSideNetVarContainers.Where(d => + d.HaveAllValuesChanged(NetVarValueToSet)).Count() == clientSideNetVarContainers.Count); + Assert.IsFalse(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for client side NetVarContainers to report all NetworkVariables have been updated!"); } } } diff --git a/Tests/Runtime/NetworkObject/NetworkObjectDestroyTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectDestroyTests.cs index 0e6d20e..7a751b3 100644 --- a/Tests/Runtime/NetworkObject/NetworkObjectDestroyTests.cs +++ b/Tests/Runtime/NetworkObject/NetworkObjectDestroyTests.cs @@ -13,16 +13,21 @@ namespace Unity.Netcode.RuntimeTests /// - Server destroy spawned => Object gets destroyed and despawned/destroyed on all clients. Server does not run . Client runs it. /// - Client destroy spawned => throw exception. /// + + [TestFixture(SessionModeTypes.DistributedAuthority)] + [TestFixture(SessionModeTypes.ClientServer)] public class NetworkObjectDestroyTests : NetcodeIntegrationTest { - protected override int NumberOfClients => 1; + protected override int NumberOfClients => 2; + + public NetworkObjectDestroyTests(SessionModeTypes sessionModeType) : base(sessionModeType) { } /// /// Tests that a server can destroy a NetworkObject and that it gets despawned correctly. /// /// [UnityTest] - public IEnumerator TestNetworkObjectServerDestroy() + public IEnumerator TestNetworkObjectAuthorityDestroy() { // This is the *SERVER VERSION* of the *CLIENT PLAYER* var serverClientPlayerResult = new NetcodeIntegrationTestHelpers.ResultWrapper(); @@ -35,15 +40,25 @@ namespace Unity.Netcode.RuntimeTests Assert.IsNotNull(serverClientPlayerResult.Result.gameObject); Assert.IsNotNull(clientClientPlayerResult.Result.gameObject); - // destroy the server player - Object.Destroy(serverClientPlayerResult.Result.gameObject); + var targetNetworkManager = m_ClientNetworkManagers[0]; + if (m_DistributedAuthority) + { + targetNetworkManager = m_ClientNetworkManagers[1]; + // destroy the authoritative player (distributed authority) + Object.Destroy(clientClientPlayerResult.Result.gameObject); + } + else + { + // destroy the authoritative player (client-server) + Object.Destroy(serverClientPlayerResult.Result.gameObject); + } - yield return NetcodeIntegrationTestHelpers.WaitForMessageOfTypeHandled(m_ClientNetworkManagers[0]); + yield return NetcodeIntegrationTestHelpers.WaitForMessageOfTypeHandled(targetNetworkManager); Assert.IsTrue(serverClientPlayerResult.Result == null); // Assert.IsNull doesn't work here Assert.IsTrue(clientClientPlayerResult.Result == null); - // create an unspawned networkobject and destroy it + // validate that any unspawned networkobject can be destroyed var go = new GameObject(); go.AddComponent(); Object.Destroy(go); @@ -74,16 +89,42 @@ namespace Unity.Netcode.RuntimeTests //destroying a NetworkObject while shutting down is allowed if (isShuttingDown) { - m_ClientNetworkManagers[0].Shutdown(); + if (m_DistributedAuthority) + { + // Shutdown the 2nd client + m_ClientNetworkManagers[1].Shutdown(); + } + else + { + // Shutdown the + m_ClientNetworkManagers[0].Shutdown(); + } } else { LogAssert.ignoreFailingMessages = true; NetworkLog.NetworkManagerOverride = m_ClientNetworkManagers[0]; } + m_ClientPlayerName = clientPlayer.gameObject.name; m_ClientNetworkObjectId = clientPlayer.NetworkObjectId; - Object.DestroyImmediate(clientPlayer.gameObject); + if (m_DistributedAuthority) + { + m_ClientPlayerName = m_PlayerNetworkObjects[m_ClientNetworkManagers[1].LocalClientId][m_ClientNetworkManagers[0].LocalClientId].gameObject.name; + m_ClientNetworkObjectId = m_PlayerNetworkObjects[m_ClientNetworkManagers[1].LocalClientId][m_ClientNetworkManagers[0].LocalClientId].NetworkObjectId; + + if (!isShuttingDown) + { + NetworkLog.NetworkManagerOverride = m_ClientNetworkManagers[1]; + } + // the 2nd client attempts to destroy the 1st client's player object (if shutting down then "ok" if not then not "ok") + Object.DestroyImmediate(m_PlayerNetworkObjects[m_ClientNetworkManagers[1].LocalClientId][m_ClientNetworkManagers[0].LocalClientId].gameObject); + } + else + { + // the 1st client attempts to destroy its own player object (if shutting down then "ok" if not then not "ok") + Object.DestroyImmediate(m_ClientNetworkManagers[0].LocalClient.PlayerObject.gameObject); + } // destroying a NetworkObject while a session is active is not allowed if (!isShuttingDown) @@ -95,16 +136,25 @@ namespace Unity.Netcode.RuntimeTests private bool HaveLogsBeenReceived() { - if (!NetcodeLogAssert.HasLogBeenReceived(LogType.Error, $"[Netcode] [Invalid Destroy][{m_ClientPlayerName}][NetworkObjectId:{m_ClientNetworkObjectId}] Destroy a spawned {nameof(NetworkObject)} on a non-host client is not valid. Call Destroy or Despawn on the server/host instead.")) + if (m_DistributedAuthority) { - return false; + if (!NetcodeLogAssert.HasLogBeenReceived(LogType.Error, $"[Netcode] [Invalid Destroy][{m_ClientPlayerName}][NetworkObjectId:{m_ClientNetworkObjectId}] Destroy a spawned {nameof(NetworkObject)} on a non-owner client is not valid during a distributed authority session. Call Destroy or Despawn on the client-owner instead.")) + { + return false; + } } - - if (!NetcodeLogAssert.HasLogBeenReceived(LogType.Error, $"[Netcode-Server Sender={m_ClientNetworkManagers[0].LocalClientId}] [Invalid Destroy][{m_ClientPlayerName}][NetworkObjectId:{m_ClientNetworkObjectId}] Destroy a spawned {nameof(NetworkObject)} on a non-host client is not valid. Call Destroy or Despawn on the server/host instead.")) + else { - return false; - } + if (!NetcodeLogAssert.HasLogBeenReceived(LogType.Error, $"[Netcode] [Invalid Destroy][{m_ClientPlayerName}][NetworkObjectId:{m_ClientNetworkObjectId}] Destroy a spawned {nameof(NetworkObject)} on a non-host client is not valid. Call Destroy or Despawn on the server/host instead.")) + { + return false; + } + if (!NetcodeLogAssert.HasLogBeenReceived(LogType.Error, $"[Netcode-Server Sender={m_ClientNetworkManagers[0].LocalClientId}] [Invalid Destroy][{m_ClientPlayerName}][NetworkObjectId:{m_ClientNetworkObjectId}] Destroy a spawned {nameof(NetworkObject)} on a non-host client is not valid. Call Destroy or Despawn on the server/host instead.")) + { + return false; + } + } return true; } diff --git a/Tests/Runtime/NetworkObject/NetworkObjectDontDestroyWithOwnerTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectDontDestroyWithOwnerTests.cs index 4300afd..f77a06e 100644 --- a/Tests/Runtime/NetworkObject/NetworkObjectDontDestroyWithOwnerTests.cs +++ b/Tests/Runtime/NetworkObject/NetworkObjectDontDestroyWithOwnerTests.cs @@ -8,6 +8,7 @@ using UnityEngine.TestTools; namespace Unity.Netcode.RuntimeTests { + [TestFixture(HostOrServer.DAHost)] [TestFixture(HostOrServer.Host)] [TestFixture(HostOrServer.Server)] public class NetworkObjectDontDestroyWithOwnerTests : NetcodeIntegrationTest @@ -36,6 +37,22 @@ namespace Unity.Netcode.RuntimeTests yield return WaitForConditionOrTimeOut(() => client.SpawnManager.GetClientOwnedObjects(clientId).Count() == k_NumberObjectsToSpawn + 1); Assert.False(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for client to have 33 NetworkObjects spawned! Only {client.SpawnManager.GetClientOwnedObjects(clientId).Count()} were assigned!"); + // Since clients spawn their objects locally in distributed authority mode, we have to rebuild the list of the client + // owned objects on the (DAHost) server-side because when the client disconnects it will destroy its local instances. + if (m_DistributedAuthority) + { + networkObjects.Clear(); + var serversideClientOwnedObjects = m_ServerNetworkManager.SpawnManager.GetClientOwnedObjects(clientId); + + foreach (var networkObject in serversideClientOwnedObjects) + { + if (!networkObject.IsPlayerObject) + { + networkObjects.Add(networkObject.gameObject); + } + } + } + // disconnect the client that owns all the clients NetcodeIntegrationTestHelpers.StopOneClient(client); diff --git a/Tests/Runtime/NetworkObject/NetworkObjectOnNetworkDespawnTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectOnNetworkDespawnTests.cs index ae1ea07..56adc0a 100644 --- a/Tests/Runtime/NetworkObject/NetworkObjectOnNetworkDespawnTests.cs +++ b/Tests/Runtime/NetworkObject/NetworkObjectOnNetworkDespawnTests.cs @@ -10,12 +10,13 @@ namespace Unity.Netcode.RuntimeTests /// /// Tests that check OnNetworkDespawn being invoked /// + [TestFixture(HostOrServer.DAHost)] [TestFixture(HostOrServer.Host)] [TestFixture(HostOrServer.Server)] public class NetworkObjectOnNetworkDespawnTests : NetcodeIntegrationTest { private const string k_ObjectName = "TestDespawn"; - public enum InstanceType + public enum InstanceTypes { Server, Client @@ -23,7 +24,10 @@ namespace Unity.Netcode.RuntimeTests protected override int NumberOfClients => 1; private GameObject m_ObjectToSpawn; + private NetworkObject m_NetworkObject; + private HostOrServer m_HostOrServer; + public NetworkObjectOnNetworkDespawnTests(HostOrServer hostOrServer) : base(hostOrServer) { m_HostOrServer = hostOrServer; @@ -31,32 +35,17 @@ namespace Unity.Netcode.RuntimeTests internal class OnNetworkDespawnTestComponent : NetworkBehaviour { - public static bool OnServerNetworkDespawnCalled { get; internal set; } - public static bool OnClientNetworkDespawnCalled { get; internal set; } + public bool OnNetworkDespawnCalled { get; internal set; } public override void OnNetworkSpawn() { - if (IsServer) - { - OnServerNetworkDespawnCalled = false; - } - else - { - OnClientNetworkDespawnCalled = false; - } + OnNetworkDespawnCalled = false; base.OnNetworkSpawn(); } public override void OnNetworkDespawn() { - if (IsServer) - { - OnServerNetworkDespawnCalled = true; - } - else - { - OnClientNetworkDespawnCalled = true; - } + OnNetworkDespawnCalled = true; base.OnNetworkDespawn(); } } @@ -68,46 +57,67 @@ namespace Unity.Netcode.RuntimeTests base.OnServerAndClientsCreated(); } + private bool ObjectSpawnedOnAllNetworkManagerInstances() + { + if (!s_GlobalNetworkObjects.ContainsKey(m_ServerNetworkManager.LocalClientId)) + { + return false; + } + if (!s_GlobalNetworkObjects[m_ServerNetworkManager.LocalClientId].ContainsKey(m_NetworkObject.NetworkObjectId)) + { + return false; + } + + foreach (var clientNetworkManager in m_ClientNetworkManagers) + { + if (!s_GlobalNetworkObjects.ContainsKey(clientNetworkManager.LocalClientId)) + { + return false; + } + if (!s_GlobalNetworkObjects[clientNetworkManager.LocalClientId].ContainsKey(m_NetworkObject.NetworkObjectId)) + { + return false; + } + } + + return true; + } + /// /// This test validates that is invoked when the /// is shutdown. /// [UnityTest] - public IEnumerator TestNetworkObjectDespawnOnShutdown() + public IEnumerator TestNetworkObjectDespawnOnShutdown([Values(InstanceTypes.Server, InstanceTypes.Client)] InstanceTypes despawnCheck) { - // Spawn the test object - var spawnedObject = SpawnObject(m_ObjectToSpawn, m_ServerNetworkManager); - var spawnedNetworkObject = spawnedObject.GetComponent(); - - // Wait for the client to spawn the object - yield return WaitForConditionOrTimeOut(() => + var networkManager = despawnCheck == InstanceTypes.Server ? m_ServerNetworkManager : m_ClientNetworkManagers[0]; + var networkManagerOwner = m_ServerNetworkManager; + if (m_DistributedAuthority) { - if (!s_GlobalNetworkObjects.ContainsKey(m_ClientNetworkManagers[0].LocalClientId)) - { - return false; - } - if (!s_GlobalNetworkObjects[m_ClientNetworkManagers[0].LocalClientId].ContainsKey(spawnedNetworkObject.NetworkObjectId)) - { - return false; - } - return true; - }); + networkManagerOwner = networkManager; + } - AssertOnTimeout($"Timed out waiting for client to spawn {k_ObjectName}!"); + // Spawn the test object + var spawnedObject = SpawnObject(m_ObjectToSpawn, networkManagerOwner); + m_NetworkObject = spawnedObject.GetComponent(); + + + yield return WaitForConditionOrTimeOut(ObjectSpawnedOnAllNetworkManagerInstances); + AssertOnTimeout($"Timed out waiting for all {nameof(NetworkManager)} instances to spawn {m_NetworkObject.name}!"); + + // Get the spawned object relative to which NetworkManager instance we are testing. + var relativeSpawnedObject = s_GlobalNetworkObjects[networkManager.LocalClientId][m_NetworkObject.NetworkObjectId]; + var onNetworkDespawnTestComponent = relativeSpawnedObject.GetComponent(); // Confirm it is not set before shutting down the NetworkManager - Assert.IsFalse(OnNetworkDespawnTestComponent.OnClientNetworkDespawnCalled, "[Client-side] despawn state is already set (should not be set at this point)!"); - Assert.IsFalse(OnNetworkDespawnTestComponent.OnServerNetworkDespawnCalled, $"[{m_HostOrServer}-side] despawn state is already set (should not be set at this point)!"); + Assert.IsFalse(onNetworkDespawnTestComponent.OnNetworkDespawnCalled, $"{nameof(OnNetworkDespawnTestComponent.OnNetworkDespawnCalled)} was set prior to shutting down!"); - // Shutdown the client-side first to validate the client-side instance invokes OnNetworkDespawn - m_ClientNetworkManagers[0].Shutdown(); - yield return WaitForConditionOrTimeOut(() => OnNetworkDespawnTestComponent.OnClientNetworkDespawnCalled); - AssertOnTimeout($"[Client-side] Timed out waiting for {k_ObjectName}'s {nameof(NetworkBehaviour.OnNetworkDespawn)} to be invoked!"); + // Shutdown the NetworkManager instance we are testing. + networkManager.Shutdown(); - // Shutdown the servr-host-side second to validate servr-host-side instance invokes OnNetworkDespawn - m_ServerNetworkManager.Shutdown(); - yield return WaitForConditionOrTimeOut(() => OnNetworkDespawnTestComponent.OnClientNetworkDespawnCalled); - AssertOnTimeout($"[{m_HostOrServer}-side]Timed out waiting for {k_ObjectName}'s {nameof(NetworkBehaviour.OnNetworkDespawn)} to be invoked!"); + // Confirm that OnNetworkDespawn is invoked after shutdown + yield return WaitForConditionOrTimeOut(() => onNetworkDespawnTestComponent.OnNetworkDespawnCalled); + AssertOnTimeout($"Timed out waiting for {nameof(NetworkObject)} instance to despawn on the {despawnCheck} side!"); } } } diff --git a/Tests/Runtime/NetworkObject/NetworkObjectOnSpawnTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectOnSpawnTests.cs index 17b618a..cefdc2d 100644 --- a/Tests/Runtime/NetworkObject/NetworkObjectOnSpawnTests.cs +++ b/Tests/Runtime/NetworkObject/NetworkObjectOnSpawnTests.cs @@ -7,6 +7,8 @@ using UnityEngine.TestTools; namespace Unity.Netcode.RuntimeTests { + [TestFixture(SessionModeTypes.DistributedAuthority)] + [TestFixture(SessionModeTypes.ClientServer)] public class NetworkObjectOnSpawnTests : NetcodeIntegrationTest { private GameObject m_TestNetworkObjectPrefab; @@ -27,23 +29,39 @@ namespace Unity.Netcode.RuntimeTests private const string k_WithObserversError = "Not all clients spawned the"; private const string k_WithoutObserversError = "A client spawned the"; + public NetworkObjectOnSpawnTests(SessionModeTypes sessionModeType) : base(sessionModeType) { } + protected override void OnServerAndClientsCreated() { m_ObserverPrefab = CreateNetworkObjectPrefab(k_ObserverTestObjName); base.OnServerAndClientsCreated(); } - private bool CheckClientsSideObserverTestObj() { foreach (var client in m_ClientNetworkManagers) { - if (!s_GlobalNetworkObjects.ContainsKey(client.LocalClientId)) + if (m_ObserverTestType == ObserverTestTypes.WithObservers) { - // When no observers there shouldn't be any client spawned NetworkObjects - // (players are held in a different list) - return !(m_ObserverTestType == ObserverTestTypes.WithObservers); + // When validating this portion of the test and spawning with observers is true, there + // should be spawned objects on the clients. + if (!s_GlobalNetworkObjects.ContainsKey(client.LocalClientId)) + { + return false; + } } + else + { + // When validating this portion of the test and spawning with observers is false, there + // should be no spawned objects on the clients. + if (s_GlobalNetworkObjects.ContainsKey(client.LocalClientId)) + { + return false; + } + // We don't need to check anything else for spawn without observers + continue; + } + var clientObjects = s_GlobalNetworkObjects[client.LocalClientId]; // Make sure they did spawn the object if (m_ObserverTestType == ObserverTestTypes.WithObservers) @@ -83,10 +101,16 @@ namespace Unity.Netcode.RuntimeTests /// /// whether to spawn with or without observers [UnityTest] - public IEnumerator ObserverSpawnTests([Values] ObserverTestTypes observerTestTypes, [Values] bool sceneManagement) + public IEnumerator ObserverSpawnTests([Values] ObserverTestTypes observerTestTypes, [Values] SceneManagementState sceneManagement) { - if (!sceneManagement) + if (sceneManagement == SceneManagementState.SceneManagementDisabled) { + // When scene management is disabled, we need this wait period for all clients to be up to date with + // all other clients before beginning the process of stopping all clients. + if (m_DistributedAuthority) + { + yield return new WaitForSeconds(0.5f); + } // Disable prefabs to prevent them from being destroyed foreach (var networkPrefab in m_ServerNetworkManager.NetworkConfig.Prefabs.Prefabs) { @@ -156,8 +180,10 @@ namespace Unity.Netcode.RuntimeTests m_ObserverTestType = ObserverTestTypes.WithoutObservers; // Just give a little time to make sure nothing spawned yield return s_DefaultWaitForTick; - yield return WaitForConditionOrTimeOut(CheckClientsSideObserverTestObj); - AssertOnTimeout($"{(withoutObservers ? k_WithoutObserversError : k_WithObserversError)} {k_ObserverTestObjName} object!"); + + // This just requires a targeted check to assure the newly joined client did not spawn the NetworkObject with SpawnWithObservers set to false + var lateJoinClientId = m_ClientNetworkManagers[m_ClientNetworkManagers.Length - 1].LocalClientId; + Assert.False(s_GlobalNetworkObjects.ContainsKey(lateJoinClientId), $"[Client-{lateJoinClientId}] Spawned {instance.name} when it shouldn't have!"); // Now validate that we can make the NetworkObject visible to the newly joined client m_ObserverTestNetworkObject.NetworkShow(m_ClientNetworkManagers[NumberOfClients].LocalClientId); diff --git a/Tests/Runtime/NetworkObject/NetworkObjectOwnershipPropertiesTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectOwnershipPropertiesTests.cs new file mode 100644 index 0000000..e198f0d --- /dev/null +++ b/Tests/Runtime/NetworkObject/NetworkObjectOwnershipPropertiesTests.cs @@ -0,0 +1,205 @@ +using System.Collections; +using System.Linq; +using System.Text; +using NUnit.Framework; +using Unity.Netcode.TestHelpers.Runtime; +using UnityEngine; +using UnityEngine.TestTools; + +namespace Unity.Netcode.RuntimeTests +{ + [TestFixture(SessionModeTypes.DistributedAuthority)] + [TestFixture(SessionModeTypes.ClientServer)] + public class NetworkObjectOwnershipPropertiesTests : NetcodeIntegrationTest + { + private class DummyNetworkBehaviour : NetworkBehaviour + { + + } + + protected override int NumberOfClients => 2; + private GameObject m_PrefabToSpawn; + private NetworkObject m_OwnerSpawnedInstance; + private NetworkObject m_TargetOwnerInstance; + private NetworkManager m_InitialOwner; + private NetworkManager m_NextTargetOwner; + + private ulong m_InitialOwnerId; + private ulong m_TargetOwnerId; + private bool m_SpawnedInstanceIsOwner; + private bool m_InitialOwnerOwnedBySever; + private bool m_TargetOwnerOwnedBySever; + + public NetworkObjectOwnershipPropertiesTests(SessionModeTypes sessionModeType) : base(sessionModeType) { } + + protected override IEnumerator OnTearDown() + { + m_OwnerSpawnedInstance = null; + m_InitialOwner = null; + m_NextTargetOwner = null; + m_PrefabToSpawn = null; + return base.OnTearDown(); + } + + protected override void OnServerAndClientsCreated() + { + m_PrefabToSpawn = CreateNetworkObjectPrefab("ClientOwnedObject"); + m_PrefabToSpawn.gameObject.AddComponent(); + m_PrefabToSpawn.GetComponent().SetOwnershipStatus(NetworkObject.OwnershipStatus.Distributable); + } + + public enum InstanceTypes + { + Server, + Client + } + + private StringBuilder m_OwnershipPropagatedFailures = new StringBuilder(); + private bool OwnershipPropagated() + { + var conditionMet = true; + m_OwnershipPropagatedFailures.Clear(); + // In distributed authority mode, we will check client owner to DAHost owner with InstanceTypes.Server and client owner to client + // when InstanceTypes.Client + if (m_DistributedAuthority) + { + if (!m_ClientNetworkManagers[1].SpawnManager.GetClientOwnedObjects(m_NextTargetOwner.LocalClientId).Any(x => x.NetworkObjectId == m_OwnerSpawnedInstance.NetworkObjectId)) + { + conditionMet = false; + m_OwnershipPropagatedFailures.AppendLine($"Client-{m_ClientNetworkManagers[1].LocalClientId} has no ownership entry for {m_OwnerSpawnedInstance.name} ({m_OwnerSpawnedInstance.NetworkObjectId})"); + } + if (!m_ClientNetworkManagers[0].SpawnManager.GetClientOwnedObjects(m_NextTargetOwner.LocalClientId).Any(x => x.NetworkObjectId == m_OwnerSpawnedInstance.NetworkObjectId)) + { + conditionMet = false; + m_OwnershipPropagatedFailures.AppendLine($"Client-{m_ClientNetworkManagers[0].LocalClientId} has no ownership entry for {m_OwnerSpawnedInstance.name} ({m_OwnerSpawnedInstance.NetworkObjectId})"); + } + if (!m_ServerNetworkManager.SpawnManager.GetClientOwnedObjects(m_NextTargetOwner.LocalClientId).Any(x => x.NetworkObjectId == m_OwnerSpawnedInstance.NetworkObjectId)) + { + conditionMet = false; + m_OwnershipPropagatedFailures.AppendLine($"Client-{m_ServerNetworkManager.LocalClientId} has no ownership entry for {m_OwnerSpawnedInstance.name} ({m_OwnerSpawnedInstance.NetworkObjectId})"); + } + } + else + { + if (m_NextTargetOwner != m_ServerNetworkManager) + { + if (!m_NextTargetOwner.SpawnManager.GetClientOwnedObjects(m_NextTargetOwner.LocalClientId).Any(x => x.NetworkObjectId == m_OwnerSpawnedInstance.NetworkObjectId)) + { + conditionMet = false; + m_OwnershipPropagatedFailures.AppendLine($"Client-{m_NextTargetOwner.LocalClientId} has no ownership entry for {m_OwnerSpawnedInstance.name} ({m_OwnerSpawnedInstance.NetworkObjectId})"); + } + } + if (!m_ServerNetworkManager.SpawnManager.GetClientOwnedObjects(m_NextTargetOwner.LocalClientId).Any(x => x.NetworkObjectId == m_OwnerSpawnedInstance.NetworkObjectId)) + { + conditionMet = false; + m_OwnershipPropagatedFailures.AppendLine($"Client-{m_ServerNetworkManager.LocalClientId} has no ownership entry for {m_OwnerSpawnedInstance.name} ({m_OwnerSpawnedInstance.NetworkObjectId})"); + } + } + return conditionMet; + } + + private void ValidateOwnerShipProperties(bool targetIsOwner = false) + { + Assert.AreEqual(m_OwnerSpawnedInstance.IsOwner, m_SpawnedInstanceIsOwner); + Assert.AreEqual(m_OwnerSpawnedInstance.IsOwnedByServer, m_InitialOwnerOwnedBySever); + Assert.AreEqual(targetIsOwner ? m_TargetOwnerId : m_InitialOwnerId, m_OwnerSpawnedInstance.OwnerClientId); + + var initialOwnerBehaviour = m_OwnerSpawnedInstance.GetComponent(); + Assert.AreEqual(initialOwnerBehaviour.IsOwner, m_SpawnedInstanceIsOwner); + Assert.AreEqual(initialOwnerBehaviour.IsOwnedByServer, m_InitialOwnerOwnedBySever); + Assert.AreEqual(targetIsOwner ? m_TargetOwnerId : m_InitialOwnerId, initialOwnerBehaviour.OwnerClientId); + + Assert.AreEqual(m_TargetOwnerInstance.IsOwner, targetIsOwner); + Assert.AreEqual(m_TargetOwnerInstance.IsOwnedByServer, m_TargetOwnerOwnedBySever); + + Assert.AreEqual(targetIsOwner ? m_TargetOwnerId : m_InitialOwnerId, m_TargetOwnerInstance.OwnerClientId); + var targetOwnerBehaviour = m_TargetOwnerInstance.GetComponent(); + Assert.AreEqual(targetOwnerBehaviour.IsOwner, targetIsOwner); + Assert.AreEqual(targetOwnerBehaviour.IsOwnedByServer, m_TargetOwnerOwnedBySever); + Assert.AreEqual(targetIsOwner ? m_TargetOwnerId : m_InitialOwnerId, m_TargetOwnerInstance.OwnerClientId); + } + + + [UnityTest] + public IEnumerator ValidatePropertiesWithOwnershipChanges([Values(InstanceTypes.Server, InstanceTypes.Client)] InstanceTypes instanceType) + { + m_NextTargetOwner = instanceType == InstanceTypes.Server ? m_ServerNetworkManager : m_ClientNetworkManagers[0]; + m_InitialOwner = instanceType == InstanceTypes.Client ? m_ServerNetworkManager : m_ClientNetworkManagers[0]; + + // In distributed authority mode, we will check client owner to DAHost owner with InstanceTypes.Server and client owner to client + // when InstanceTypes.Client + if (m_DistributedAuthority) + { + m_InitialOwner = m_ClientNetworkManagers[0]; + if (instanceType == InstanceTypes.Client) + { + m_NextTargetOwner = m_ClientNetworkManagers[1]; + } + m_PrefabToSpawn.GetComponent().SetOwnershipStatus(NetworkObject.OwnershipStatus.Transferable); + } + + m_InitialOwnerId = m_InitialOwner.LocalClientId; + m_TargetOwnerId = m_NextTargetOwner.LocalClientId; + m_InitialOwnerOwnedBySever = m_InitialOwner.IsServer; + m_TargetOwnerOwnedBySever = m_InitialOwner.IsServer; + var objectInstance = SpawnObject(m_PrefabToSpawn, m_InitialOwner); + + m_OwnerSpawnedInstance = objectInstance.GetComponent(); + m_SpawnedInstanceIsOwner = m_OwnerSpawnedInstance.NetworkManager == m_InitialOwner; + // Sanity check to verify that the next owner to target is not the owner of the spawned object + var hasEntry = m_InitialOwner.SpawnManager.GetClientOwnedObjects(m_NextTargetOwner.LocalClientId).Any(x => x.NetworkObjectId == m_OwnerSpawnedInstance.NetworkObjectId); + Assert.False(hasEntry); + + // Since CreateObjectMessage gets proxied by DAHost, just wait until the next target owner has the spawned instance in the s_GlobalNetworkObjects table. + yield return WaitForConditionOrTimeOut(() => s_GlobalNetworkObjects.ContainsKey(m_NextTargetOwner.LocalClientId) && s_GlobalNetworkObjects[m_NextTargetOwner.LocalClientId].ContainsKey(m_OwnerSpawnedInstance.NetworkObjectId)); + AssertOnTimeout($"Timed out waiting for Client-{m_NextTargetOwner.LocalClientId} to have an instance entry of {m_OwnerSpawnedInstance.name}-{m_OwnerSpawnedInstance.NetworkObjectId}!"); + + // Get the target client's instance of the spawned object + m_TargetOwnerInstance = s_GlobalNetworkObjects[m_NextTargetOwner.LocalClientId][m_OwnerSpawnedInstance.NetworkObjectId]; + + // Validate that NetworkObject and NetworkBehaviour ownership properties are correct + ValidateOwnerShipProperties(); + + // The authority always changes the ownership + // Client-Server: It will always be the host instance + // Distributed Authority: It can be either the DAHost or the client + if (m_DistributedAuthority) + { + // Use the target client's instance to change ownership + m_TargetOwnerInstance.ChangeOwnership(m_NextTargetOwner.LocalClientId); + if (instanceType == InstanceTypes.Client) + { + var networkManagersList = new System.Collections.Generic.List() { m_ServerNetworkManager, m_ClientNetworkManagers[0] }; + // Provide enough time for the client to receive and process the spawned message. + yield return WaitForMessageReceived(networkManagersList); + } + else + { + // Provide enough time for the client to receive and process the change in ownership message. + yield return WaitForMessageReceived(m_ClientNetworkManagers.ToList()); + } + } + else + { + m_OwnerSpawnedInstance.ChangeOwnership(m_NextTargetOwner.LocalClientId); + // Provide enough time for the client to receive and process the change in ownership message. + yield return WaitForMessageReceived(m_ClientNetworkManagers.ToList()); + } + + // Ensure it's the ownership tables are updated + yield return WaitForConditionOrTimeOut(OwnershipPropagated); + AssertOnTimeout($"Timed out waiting for ownership to propagate!\n{m_OwnershipPropagatedFailures}"); + + m_SpawnedInstanceIsOwner = m_OwnerSpawnedInstance.NetworkManager == m_NextTargetOwner; + if (m_SpawnedInstanceIsOwner) + { + m_InitialOwnerOwnedBySever = m_OwnerSpawnedInstance.NetworkManager.IsServer; + } + m_InitialOwnerOwnedBySever = m_NextTargetOwner.IsServer; + m_TargetOwnerOwnedBySever = m_NextTargetOwner.IsServer; + + // Validate that NetworkObject and NetworkBehaviour ownership properties are correct + ValidateOwnerShipProperties(true); + } + } +} diff --git a/Tests/Runtime/NetworkObject/NetworkObjectOwnershipPropertiesTests.cs.meta b/Tests/Runtime/NetworkObject/NetworkObjectOwnershipPropertiesTests.cs.meta new file mode 100644 index 0000000..5a555c0 --- /dev/null +++ b/Tests/Runtime/NetworkObject/NetworkObjectOwnershipPropertiesTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7c88cc36139c1574fba571485477d642 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Tests/Runtime/NetworkObject/NetworkObjectOwnershipTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectOwnershipTests.cs index 5fa4915..77d5a93 100644 --- a/Tests/Runtime/NetworkObject/NetworkObjectOwnershipTests.cs +++ b/Tests/Runtime/NetworkObject/NetworkObjectOwnershipTests.cs @@ -10,6 +10,8 @@ namespace Unity.Netcode.RuntimeTests { public class NetworkObjectOwnershipComponent : NetworkBehaviour { + public static Dictionary SpawnedInstances = new Dictionary(); + public bool OnLostOwnershipFired = false; public bool OnGainedOwnershipFired = false; @@ -23,6 +25,15 @@ namespace Unity.Netcode.RuntimeTests OnGainedOwnershipFired = true; } + public override void OnNetworkSpawn() + { + if (!SpawnedInstances.ContainsKey(NetworkManager.LocalClientId)) + { + SpawnedInstances.Add(NetworkManager.LocalClientId, this); + } + base.OnNetworkSpawn(); + } + public void ResetFlags() { OnLostOwnershipFired = false; @@ -30,6 +41,8 @@ namespace Unity.Netcode.RuntimeTests } } + + [TestFixture(HostOrServer.DAHost)] [TestFixture(HostOrServer.Host)] [TestFixture(HostOrServer.Server)] public class NetworkObjectOwnershipTests : NetcodeIntegrationTest @@ -48,10 +61,20 @@ namespace Unity.Netcode.RuntimeTests Remove } + protected override IEnumerator OnSetup() + { + NetworkObjectOwnershipComponent.SpawnedInstances.Clear(); + return base.OnSetup(); + } + protected override void OnServerAndClientsCreated() { m_OwnershipPrefab = CreateNetworkObjectPrefab("OnwershipPrefab"); m_OwnershipPrefab.AddComponent(); + if (m_DistributedAuthority) + { + m_OwnershipPrefab.GetComponent().SetOwnershipStatus(NetworkObject.OwnershipStatus.Transferable); + } base.OnServerAndClientsCreated(); } @@ -67,6 +90,23 @@ namespace Unity.Netcode.RuntimeTests Assert.NotNull(clientPlayerObject, $"Client Id {m_ClientNetworkManagers[0].LocalClientId} does not have its local player marked as an owned object using local client!"); } + private bool AllObjectsSpawnedOnClients() + { + if (!NetworkObjectOwnershipComponent.SpawnedInstances.ContainsKey(m_ServerNetworkManager.LocalClientId)) + { + return false; + } + + foreach (var client in m_ClientNetworkManagers) + { + if (!NetworkObjectOwnershipComponent.SpawnedInstances.ContainsKey(client.LocalClientId)) + { + return false; + } + } + return true; + } + [UnityTest] public IEnumerator TestOwnershipCallbacks([Values] OwnershipChecks ownershipChecks) { @@ -75,6 +115,9 @@ namespace Unity.Netcode.RuntimeTests yield return NetcodeIntegrationTestHelpers.WaitForMessageOfTypeHandled(m_ClientNetworkManagers[0]); + yield return WaitForConditionOrTimeOut(AllObjectsSpawnedOnClients); + AssertOnTimeout($"Timed out waiting for all clients to spawn the ownership object!"); + var ownershipNetworkObjectId = m_OwnershipNetworkObject.NetworkObjectId; Assert.That(ownershipNetworkObjectId, Is.GreaterThan(0)); Assert.That(m_ServerNetworkManager.SpawnManager.SpawnedObjects.ContainsKey(ownershipNetworkObjectId)); @@ -123,18 +166,22 @@ namespace Unity.Netcode.RuntimeTests else { // Validates that when ownership is removed the server gets an OnGainedOwnership notification - serverObject.RemoveOwnership(); + // In distributed authority mode, the current owner just rolls the ownership back over to the DAHost client (i.e. host mocking CMB Service) + if (m_DistributedAuthority) + { + clientObject.ChangeOwnership(NetworkManager.ServerClientId); + } + else + { + serverObject.RemoveOwnership(); + } } - yield return s_DefaultWaitForTick; + yield return WaitForConditionOrTimeOut(() => serverComponent.OnGainedOwnershipFired && serverComponent.OwnerClientId == m_ServerNetworkManager.LocalClientId); + AssertOnTimeout($"Timed out waiting for ownership to be transfered back to the host instance!"); - Assert.That(serverComponent.OnGainedOwnershipFired); - Assert.That(serverComponent.OwnerClientId, Is.EqualTo(m_ServerNetworkManager.LocalClientId)); - - yield return WaitForConditionOrTimeOut(() => clientComponent.OnLostOwnershipFired); - Assert.False(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for client to lose ownership!"); - Assert.That(clientComponent.OnLostOwnershipFired); - Assert.That(clientComponent.OwnerClientId, Is.EqualTo(m_ServerNetworkManager.LocalClientId)); + yield return WaitForConditionOrTimeOut(() => clientComponent.OnLostOwnershipFired && clientComponent.OwnerClientId == m_ServerNetworkManager.LocalClientId); + AssertOnTimeout($"Timed out waiting for client-side lose ownership event to trigger or owner identifier to be equal to the host!"); } /// @@ -193,11 +240,11 @@ namespace Unity.Netcode.RuntimeTests m_ServerNetworkManager.SpawnManager.RemoveOwnership(m_OwnershipNetworkObject); var serverObject = m_ServerNetworkManager.SpawnManager.SpawnedObjects[ownershipNetworkObjectId]; Assert.That(serverObject, Is.Not.Null); - + var clientObject = (NetworkObject)null; var clientObjects = new List(); for (int i = 0; i < NumberOfClients; i++) { - var clientObject = m_ClientNetworkManagers[i].SpawnManager.SpawnedObjects[ownershipNetworkObjectId]; + clientObject = m_ClientNetworkManagers[i].SpawnManager.SpawnedObjects[ownershipNetworkObjectId]; Assert.That(clientObject, Is.Not.Null); clientObjects.Add(clientObject); } @@ -217,9 +264,10 @@ namespace Unity.Netcode.RuntimeTests // After the 1st client has been given ownership to the object, this will be used to make sure each previous owner properly received the remove ownership message var previousClientComponent = (NetworkObjectOwnershipComponent)null; + for (int clientIndex = 0; clientIndex < NumberOfClients; clientIndex++) { - var clientObject = clientObjects[clientIndex]; + clientObject = clientObjects[clientIndex]; var clientId = m_ClientNetworkManagers[clientIndex].LocalClientId; Assert.That(m_ServerNetworkManager.ConnectedClients.ContainsKey(clientId)); @@ -271,7 +319,15 @@ namespace Unity.Netcode.RuntimeTests else { // Validates that when ownership is removed the server gets an OnGainedOwnership notification - serverObject.RemoveOwnership(); + // In distributed authority mode, the current owner just rolls the ownership back over to the DAHost client (i.e. host mocking CMB Service) + if (m_DistributedAuthority) + { + clientObject.ChangeOwnership(NetworkManager.ServerClientId); + } + else + { + serverObject.RemoveOwnership(); + } } yield return WaitForConditionOrTimeOut(ownershipMessageHooks); diff --git a/Tests/Runtime/NetworkObject/NetworkObjectSpawnManyObjectsTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectSpawnManyObjectsTests.cs index 8f35c97..7e41596 100644 --- a/Tests/Runtime/NetworkObject/NetworkObjectSpawnManyObjectsTests.cs +++ b/Tests/Runtime/NetworkObject/NetworkObjectSpawnManyObjectsTests.cs @@ -6,6 +6,9 @@ using UnityEngine.TestTools; namespace Unity.Netcode.RuntimeTests { + + [TestFixture(SessionModeTypes.ClientServer)] + [TestFixture(SessionModeTypes.DistributedAuthority)] public class NetworkObjectSpawnManyObjectsTests : NetcodeIntegrationTest { protected override int NumberOfClients => 1; @@ -15,6 +18,7 @@ namespace Unity.Netcode.RuntimeTests private NetworkPrefab m_PrefabToSpawn; + public NetworkObjectSpawnManyObjectsTests(SessionModeTypes sessionModeType) : base(sessionModeType) { } // Using this component assures we will know precisely how many prefabs were spawned on the client public class SpawnObjecTrackingComponent : NetworkBehaviour { @@ -35,6 +39,7 @@ namespace Unity.Netcode.RuntimeTests var gameObject = new GameObject("TestObject"); var networkObject = gameObject.AddComponent(); NetcodeIntegrationTestHelpers.MakeNetworkObjectTestPrefab(networkObject); + networkObject.IsSceneObject = false; gameObject.AddComponent(); m_PrefabToSpawn = new NetworkPrefab() { Prefab = gameObject }; diff --git a/Tests/Runtime/NetworkObject/NetworkObjectSynchronizationTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectSynchronizationTests.cs index 3ac712e..0a907c6 100644 --- a/Tests/Runtime/NetworkObject/NetworkObjectSynchronizationTests.cs +++ b/Tests/Runtime/NetworkObject/NetworkObjectSynchronizationTests.cs @@ -8,6 +8,8 @@ using Random = UnityEngine.Random; namespace Unity.Netcode.RuntimeTests { + + [TestFixture(VariableLengthSafety.DisableNetVarSafety, HostOrServer.DAHost)] [TestFixture(VariableLengthSafety.DisableNetVarSafety, HostOrServer.Host)] [TestFixture(VariableLengthSafety.EnabledNetVarSafety, HostOrServer.Host)] [TestFixture(VariableLengthSafety.DisableNetVarSafety, HostOrServer.Server)] @@ -29,17 +31,20 @@ namespace Unity.Netcode.RuntimeTests { DisableNetVarSafety, EnabledNetVarSafety, - } + }; - public NetworkObjectSynchronizationTests(VariableLengthSafety variableLengthSafety, HostOrServer hostOrServer) + public NetworkObjectSynchronizationTests(VariableLengthSafety variableLengthSafety, HostOrServer hostOrServer) : base(hostOrServer) { m_VariableLengthSafety = variableLengthSafety; - m_UseHost = hostOrServer == HostOrServer.Host; } protected override void OnCreatePlayerPrefab() { - m_PlayerPrefab.AddComponent(); + var component = m_PlayerPrefab.AddComponent(); + if (m_DistributedAuthority) + { + component.SetWritePermissions(NetworkVariableWritePermission.Owner); + } base.OnCreatePlayerPrefab(); } @@ -123,40 +128,64 @@ namespace Unity.Netcode.RuntimeTests if (m_UseHost) { + var delayCounter = 0; + while (m_ClientNetworkManagers.Length == 0) + { + delayCounter++; + Assert.True(delayCounter < 30, "TimeOut waiting for client to spawn!"); + yield return s_DefaultWaitForTick; + } + delayCounter = 0; + while (!m_PlayerNetworkObjects[m_ServerNetworkManager.LocalClientId].ContainsKey(m_ClientNetworkManagers[0].LocalClientId)) + { + delayCounter++; + if (delayCounter >= 30) + { + VerboseDebug("Trap!"); + } + Assert.True(delayCounter < 30, "TimeOut waiting for client to spawn!"); + yield return s_DefaultWaitForTick; + } + + var serverSideClientPlayerComponent = m_PlayerNetworkObjects[m_ServerNetworkManager.LocalClientId][m_ClientNetworkManagers[0].LocalClientId].GetComponent(); var serverSideHostPlayerComponent = m_ServerNetworkManager.LocalClient.PlayerObject.GetComponent(); var clientSidePlayerComponent = m_ClientNetworkManagers[0].LocalClient.PlayerObject.GetComponent(); var clientSideHostPlayerComponent = m_PlayerNetworkObjects[m_ClientNetworkManagers[0].LocalClientId][m_ServerNetworkManager.LocalClientId].GetComponent(); - + var modeText = m_DistributedAuthority ? "owner" : "server"; // Validate that the client side player values match the server side value of the client's player Assert.IsTrue(serverSideClientPlayerComponent.NetworkVariableData1.Value == clientSidePlayerComponent.NetworkVariableData1.Value, - $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData1)}][Client Player] Client side value ({serverSideClientPlayerComponent.NetworkVariableData1.Value})" + - $" does not equal the server side value ({serverSideClientPlayerComponent.NetworkVariableData1.Value})!"); + $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData1)}][Client Player-{clientSidePlayerComponent.OwnerClientId}] Client side value ({clientSidePlayerComponent.NetworkVariableData1.Value})" + + $" does not equal the {modeText} side value ({serverSideClientPlayerComponent.NetworkVariableData1.Value})!"); Assert.IsTrue(serverSideClientPlayerComponent.NetworkVariableData2.Value == clientSidePlayerComponent.NetworkVariableData2.Value, - $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData2)}][Client Player] Client side value ({serverSideClientPlayerComponent.NetworkVariableData2.Value})" + - $" does not equal the server side value ({serverSideClientPlayerComponent.NetworkVariableData2.Value})!"); + $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData2)}][Client Player-{clientSidePlayerComponent.OwnerClientId}] Client side value ({clientSidePlayerComponent.NetworkVariableData2.Value})" + + $" does not equal the {modeText} side value ({serverSideClientPlayerComponent.NetworkVariableData2.Value})!"); Assert.IsTrue(serverSideClientPlayerComponent.NetworkVariableData3.Value == clientSidePlayerComponent.NetworkVariableData3.Value, - $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData3)}][Client Player] Client side value ({serverSideClientPlayerComponent.NetworkVariableData3.Value})" + - $" does not equal the server side value ({serverSideClientPlayerComponent.NetworkVariableData3.Value})!"); + $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData3)}][Client Player-{clientSidePlayerComponent.OwnerClientId}] Client side value ({clientSidePlayerComponent.NetworkVariableData3.Value})" + + $" does not equal the {modeText} side value ({serverSideClientPlayerComponent.NetworkVariableData3.Value})!"); Assert.IsTrue(serverSideClientPlayerComponent.NetworkVariableData4.Value == clientSidePlayerComponent.NetworkVariableData4.Value, - $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData4)}][Client Player] Client side value ({serverSideClientPlayerComponent.NetworkVariableData4.Value})" + - $" does not equal the server side value ({serverSideClientPlayerComponent.NetworkVariableData4.Value})!"); + $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData4)}][Client Player-{clientSidePlayerComponent.OwnerClientId}] Client side value ({clientSidePlayerComponent.NetworkVariableData4.Value})" + + $" does not equal the {modeText} side value ({serverSideClientPlayerComponent.NetworkVariableData4.Value})!"); - - // Validate that only the 2nd and 4th NetworkVariable on the client side instance of the host's player is the same and the other two do not match - // (i.e. NetworkVariables owned by the server should not get synchronized on client) - Assert.IsTrue(serverSideHostPlayerComponent.NetworkVariableData1.Value != clientSideHostPlayerComponent.NetworkVariableData1.Value, - $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData1)}][Host Player] Client side value ({serverSideHostPlayerComponent.NetworkVariableData1.Value})" + - $" should not be equal to the server side value ({clientSideHostPlayerComponent.NetworkVariableData1.Value})!"); - Assert.IsTrue(serverSideHostPlayerComponent.NetworkVariableData2.Value == clientSideHostPlayerComponent.NetworkVariableData2.Value, - $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData2)}][Host Player] Client side value ({serverSideHostPlayerComponent.NetworkVariableData2.Value})" + - $" does not equal the server side value ({clientSideHostPlayerComponent.NetworkVariableData2.Value})!"); - Assert.IsTrue(serverSideHostPlayerComponent.NetworkVariableData3.Value != clientSideHostPlayerComponent.NetworkVariableData3.Value, - $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData3)}][Host Player] Client side value ({serverSideHostPlayerComponent.NetworkVariableData3.Value})" + - $" should not be equal to the server side value ({clientSideHostPlayerComponent.NetworkVariableData3.Value})!"); - Assert.IsTrue(serverSideHostPlayerComponent.NetworkVariableData4.Value == clientSideHostPlayerComponent.NetworkVariableData4.Value, - $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData4)}][Host Player] Client side value ({serverSideHostPlayerComponent.NetworkVariableData4.Value})" + - $" does not equal the server side value ({clientSideHostPlayerComponent.NetworkVariableData4.Value})!"); + // DANGO-TODO: This scenario is only possible to do if we add a DA-Server to mock the CMB Service or we integrate the CMB Service AND we have updated NetworkVariable permissions + // to only allow the service to write. For now, we will skip this validation for distributed authority + if (!m_DistributedAuthority) + { + // Validate that only the 2nd and 4th NetworkVariable on the client side instance of the host's player is the same and the other two do not match + // (i.e. NetworkVariables owned by the server should not get synchronized on client) + Assert.IsTrue(serverSideHostPlayerComponent.NetworkVariableData1.Value != clientSideHostPlayerComponent.NetworkVariableData1.Value, + $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData1)}][Host Player] Client side value ({clientSideHostPlayerComponent.NetworkVariableData1.Value})" + + $" should not be equal to the server side value ({serverSideHostPlayerComponent.NetworkVariableData1.Value})!"); + Assert.IsTrue(serverSideHostPlayerComponent.NetworkVariableData2.Value == clientSideHostPlayerComponent.NetworkVariableData2.Value, + $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData2)}][Host Player] Client side value ({clientSideHostPlayerComponent.NetworkVariableData2.Value})" + + $" does not equal the server side value ({serverSideHostPlayerComponent.NetworkVariableData2.Value})!"); + Assert.IsTrue(serverSideHostPlayerComponent.NetworkVariableData3.Value != clientSideHostPlayerComponent.NetworkVariableData3.Value, + $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData3)}][Host Player] Client side value ({clientSideHostPlayerComponent.NetworkVariableData3.Value})" + + $" should not be equal to the server side value ({serverSideHostPlayerComponent.NetworkVariableData3.Value})!"); + Assert.IsTrue(serverSideHostPlayerComponent.NetworkVariableData4.Value == serverSideHostPlayerComponent.NetworkVariableData4.Value, + $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData4)}][Host Player] Client side value ({clientSideHostPlayerComponent.NetworkVariableData4.Value})" + + $" does not equal the server side value ({serverSideHostPlayerComponent.NetworkVariableData4.Value})!"); + } } else { @@ -190,44 +219,53 @@ namespace Unity.Netcode.RuntimeTests $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData4)}][Player-{clientOneId}] Client-{clientOneId} value ({clientSide1PlayerComponent.NetworkVariableData4.Value})" + $" does not equal Client-{clientTwoId}'s clone side value ({clientSide2Player1Clone.NetworkVariableData4.Value})!"); + // DANGO-TODO: This scenario is only possible to do if we add a DA-Server to mock the CMB Service or we integrate the CMB Service AND we have updated NetworkVariable permissions + // to only allow the service to write. For now, we will skip this validation for distributed authority + if (!m_DistributedAuthority) + { + // Validate that client two's 2nd and 4th NetworkVariables for the local and clone instances match and the other two do not + Assert.IsTrue(clientSide2PlayerComponent.NetworkVariableData1.Value != clientSide1Player2Clone.NetworkVariableData1.Value, + $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData1)}][Player-{clientTwoId}] Client-{clientTwoId} value ({clientSide2PlayerComponent.NetworkVariableData1.Value})" + + $" should not be equal to Client-{clientOneId}'s clone side value ({clientSide1Player2Clone.NetworkVariableData1.Value})!"); - // Validate that client two's 2nd and 4th NetworkVariables for the local and clone instances match and the other two do not - Assert.IsTrue(clientSide2PlayerComponent.NetworkVariableData1.Value != clientSide1Player2Clone.NetworkVariableData1.Value, - $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData1)}][Player-{clientTwoId}] Client-{clientTwoId} value ({clientSide2PlayerComponent.NetworkVariableData1.Value})" + - $" should not be equal to Client-{clientOneId}'s clone side value ({clientSide1Player2Clone.NetworkVariableData1.Value})!"); + Assert.IsTrue(clientSide2PlayerComponent.NetworkVariableData2.Value == clientSide1Player2Clone.NetworkVariableData2.Value, + $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData2)}][Player-{clientTwoId}] Client-{clientTwoId} value ({clientSide2PlayerComponent.NetworkVariableData2.Value})" + + $" does not equal Client-{clientOneId}'s clone side value ({clientSide1Player2Clone.NetworkVariableData2.Value})!"); - Assert.IsTrue(clientSide2PlayerComponent.NetworkVariableData2.Value == clientSide1Player2Clone.NetworkVariableData2.Value, - $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData2)}][Player-{clientTwoId}] Client-{clientTwoId} value ({clientSide2PlayerComponent.NetworkVariableData2.Value})" + - $" does not equal Client-{clientOneId}'s clone side value ({clientSide1Player2Clone.NetworkVariableData2.Value})!"); + Assert.IsTrue(clientSide2PlayerComponent.NetworkVariableData3.Value != clientSide1Player2Clone.NetworkVariableData3.Value, + $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData3)}][Player-{clientTwoId}] Client-{clientTwoId} value ({clientSide2PlayerComponent.NetworkVariableData3.Value})" + + $" should not be equal to Client-{clientOneId}'s clone side value ({clientSide1Player2Clone.NetworkVariableData3.Value})!"); - Assert.IsTrue(clientSide2PlayerComponent.NetworkVariableData3.Value != clientSide1Player2Clone.NetworkVariableData3.Value, - $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData3)}][Player-{clientTwoId}] Client-{clientTwoId} value ({clientSide2PlayerComponent.NetworkVariableData3.Value})" + - $" should not be equal to Client-{clientOneId}'s clone side value ({clientSide1Player2Clone.NetworkVariableData3.Value})!"); - - Assert.IsTrue(clientSide2PlayerComponent.NetworkVariableData4.Value == clientSide1Player2Clone.NetworkVariableData4.Value, - $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData4)}][Player-{clientTwoId}] Client-{clientTwoId} value ({clientSide2PlayerComponent.NetworkVariableData4.Value})" + - $" does not equal Client-{clientOneId}'s clone side value ({clientSide1Player2Clone.NetworkVariableData4.Value})!"); + Assert.IsTrue(clientSide2PlayerComponent.NetworkVariableData4.Value == clientSide1Player2Clone.NetworkVariableData4.Value, + $"[{nameof(NetworkBehaviourWithOwnerNetworkVariables.NetworkVariableData4)}][Player-{clientTwoId}] Client-{clientTwoId} value ({clientSide2PlayerComponent.NetworkVariableData4.Value})" + + $" does not equal Client-{clientOneId}'s clone side value ({clientSide1Player2Clone.NetworkVariableData4.Value})!"); + } } - // Now validate all of the NetworkVariable values match to assure everything synchronized properly - foreach (var spawnedObject in validSpawnedNetworkObjects) + // DANGO-TODO: This scenario is only possible to do if we add a DA-Server to mock the CMB Service or we integrate the CMB Service AND we have updated NetworkVariable permissions + // to only allow the service to write. For now, we will skip this validation for distributed authority + if (!m_DistributedAuthority) { - foreach (var clientNetworkManager in m_ClientNetworkManagers) + // Now validate all of the NetworkVariable values match to assure everything synchronized properly + foreach (var spawnedObject in validSpawnedNetworkObjects) { - //Validate that the connected client has spawned all of the instances that shouldn't have failed. - var clientSideNetworkObjects = s_GlobalNetworkObjects[clientNetworkManager.LocalClientId]; + foreach (var clientNetworkManager in m_ClientNetworkManagers) + { + //Validate that the connected client has spawned all of the instances that shouldn't have failed. + var clientSideNetworkObjects = s_GlobalNetworkObjects[clientNetworkManager.LocalClientId]; - Assert.IsTrue(NetworkBehaviourWithNetworkVariables.ClientSpawnCount[clientNetworkManager.LocalClientId] == validSpawnedNetworkObjects.Count, $"Client-{clientNetworkManager.LocalClientId} spawned " + - $"({NetworkBehaviourWithNetworkVariables.ClientSpawnCount}) {nameof(NetworkObject)}s but the expected number of {nameof(NetworkObject)}s should have been ({validSpawnedNetworkObjects.Count})!"); + Assert.IsTrue(NetworkBehaviourWithNetworkVariables.ClientSpawnCount[clientNetworkManager.LocalClientId] == validSpawnedNetworkObjects.Count, $"Client-{clientNetworkManager.LocalClientId} spawned " + + $"({NetworkBehaviourWithNetworkVariables.ClientSpawnCount}) {nameof(NetworkObject)}s but the expected number of {nameof(NetworkObject)}s should have been ({validSpawnedNetworkObjects.Count})!"); - var spawnedNetworkObject = spawnedObject.GetComponent(); - Assert.IsTrue(clientSideNetworkObjects.ContainsKey(spawnedNetworkObject.NetworkObjectId), $"Failed to find valid spawned {nameof(NetworkObject)} on the client-side with a " + - $"{nameof(NetworkObject.NetworkObjectId)} of {spawnedNetworkObject.NetworkObjectId}"); + var spawnedNetworkObject = spawnedObject.GetComponent(); + Assert.IsTrue(clientSideNetworkObjects.ContainsKey(spawnedNetworkObject.NetworkObjectId), $"Failed to find valid spawned {nameof(NetworkObject)} on the client-side with a " + + $"{nameof(NetworkObject.NetworkObjectId)} of {spawnedNetworkObject.NetworkObjectId}"); - var clientSideObject = clientSideNetworkObjects[spawnedNetworkObject.NetworkObjectId]; - Assert.IsTrue(clientSideObject.NetworkManager == clientNetworkManager, $"Client-side object {clientSideObject}'s {nameof(NetworkManager)} is not valid!"); + var clientSideObject = clientSideNetworkObjects[spawnedNetworkObject.NetworkObjectId]; + Assert.IsTrue(clientSideObject.NetworkManager == clientNetworkManager, $"Client-side object {clientSideObject}'s {nameof(NetworkManager)} is not valid!"); - ValidateNetworkBehaviourWithNetworkVariables(spawnedNetworkObject, clientSideObject); + ValidateNetworkBehaviourWithNetworkVariables(spawnedNetworkObject, clientSideObject); + } } } } @@ -259,6 +297,22 @@ namespace Unity.Netcode.RuntimeTests $"does not match the client side instance value ({clientSideComponent.NetworkVariableData4.Value})!"); } + + private bool ClientSpawnedNetworkObjects(List spawnedObjectList) + { + var clientSideNetworkObjects = s_GlobalNetworkObjects[m_ClientNetworkManagers[0].LocalClientId]; + + foreach (var spawnedObject in spawnedObjectList) + { + var serverSideSpawnedNetworkObject = spawnedObject.GetComponent(); + if (!clientSideNetworkObjects.ContainsKey(serverSideSpawnedNetworkObject.NetworkObjectId)) + { + return false; + } + } + return true; + } + /// /// This validates that when a NetworkBehaviour fails serialization or deserialization during synchronizations that other NetworkBehaviours /// will still be initialized properly @@ -287,6 +341,9 @@ namespace Unity.Netcode.RuntimeTests // Validate that when a NetworkBehaviour fails to synchronize and is skipped over it does not // impact the rest of the NetworkBehaviours. var clientSideNetworkObjects = s_GlobalNetworkObjects[m_ClientNetworkManagers[0].LocalClientId]; + yield return WaitForConditionOrTimeOut(() => ClientSpawnedNetworkObjects(spawnedObjectList)); + AssertOnTimeout($"Timed out waiting for newly joined client to spawn all NetworkObjects!"); + foreach (var spawnedObject in spawnedObjectList) { var serverSideSpawnedNetworkObject = spawnedObject.GetComponent(); @@ -387,6 +444,24 @@ namespace Unity.Netcode.RuntimeTests /// public class NetworkBehaviourWithOwnerNetworkVariables : NetworkBehaviour { + private NetworkVariableWritePermission m_NetworkVariableWritePermission = NetworkVariableWritePermission.Server; + /// + /// For distributed authority, there is no such thing as a server and only owners + /// DANGO-TODO: When NetworkVariable permissions are updated, this test might need to be updated + /// + /// + public void SetWritePermissions(NetworkVariableWritePermission networkVariableWritePermission) + { + m_NetworkVariableWritePermission = networkVariableWritePermission; + // Should synchronize with everyone + NetworkVariableData1 = new NetworkVariable(default, NetworkVariableReadPermission.Everyone, networkVariableWritePermission); + // Should synchronize with everyone + NetworkVariableData2 = new NetworkVariable(default, NetworkVariableReadPermission.Everyone, networkVariableWritePermission); + // Should synchronize with everyone + NetworkVariableData3 = new NetworkVariable(default, NetworkVariableReadPermission.Everyone, networkVariableWritePermission); + // Should synchronize with everyone + NetworkVariableData4 = new NetworkVariable(default, NetworkVariableReadPermission.Everyone, networkVariableWritePermission); + } // Should not synchronize on non-owners public NetworkVariable NetworkVariableData1 = new NetworkVariable(default, NetworkVariableReadPermission.Owner, NetworkVariableWritePermission.Server); @@ -399,7 +474,9 @@ namespace Unity.Netcode.RuntimeTests public override void OnNetworkSpawn() { - if (IsServer) + // Adjustment for distributed authority mode + if ((m_NetworkVariableWritePermission == NetworkVariableWritePermission.Server && IsServer && !NetworkManager.DistributedAuthorityMode) || + (m_NetworkVariableWritePermission == NetworkVariableWritePermission.Owner && IsOwner && NetworkManager.DistributedAuthorityMode)) { NetworkVariableData1.Value = Random.Range(1, 1000); NetworkVariableData2.Value = Random.Range(1, 1000); diff --git a/Tests/Runtime/NetworkShowHideTests.cs b/Tests/Runtime/NetworkShowHideTests.cs index a68a041..3032553 100644 --- a/Tests/Runtime/NetworkShowHideTests.cs +++ b/Tests/Runtime/NetworkShowHideTests.cs @@ -1,6 +1,7 @@ using System.Collections; using System.Collections.Generic; using System.Linq; +using System.Text; using NUnit.Framework; using Unity.Netcode.TestHelpers.Runtime; using UnityEngine; @@ -16,7 +17,6 @@ namespace Unity.Netcode.RuntimeTests public static int ValueAfterOwnershipChange = 0; public static Dictionary ObjectsPerClientId = new Dictionary(); public static List ClientIdsRpcCalledOn; - public static NetworkObject GetNetworkObjectById(ulong networkObjectId) { foreach (var entry in ClientTargetedNetworkObjects) @@ -113,7 +113,10 @@ namespace Unity.Netcode.RuntimeTests [ClientRpc] public void SomeRandomClientRPC() { - Debug.Log($"RPC called {NetworkManager.LocalClientId}"); + if (!Silent) + { + Debug.Log($"RPC called {NetworkManager.LocalClientId}"); + } ClientIdsRpcCalledOn?.Add(NetworkManager.LocalClientId); } @@ -123,12 +126,15 @@ namespace Unity.Netcode.RuntimeTests } } + [TestFixture(SessionModeTypes.ClientServer)] + [TestFixture(SessionModeTypes.DistributedAuthority)] public class NetworkShowHideTests : NetcodeIntegrationTest { protected override int NumberOfClients => 4; private ulong m_ClientId0; private GameObject m_PrefabToSpawn; + private GameObject m_PrefabSpawnWithoutObservers; private NetworkObject m_NetSpawnedObject1; private NetworkObject m_NetSpawnedObject2; @@ -137,10 +143,15 @@ namespace Unity.Netcode.RuntimeTests private NetworkObject m_Object2OnClient0; private NetworkObject m_Object3OnClient0; + public NetworkShowHideTests(SessionModeTypes sessionModeType) : base(sessionModeType) { } + protected override void OnServerAndClientsCreated() { m_PrefabToSpawn = CreateNetworkObjectPrefab("ShowHideObject"); m_PrefabToSpawn.AddComponent(); + + m_PrefabSpawnWithoutObservers = CreateNetworkObjectPrefab("ObserversObject"); + m_PrefabSpawnWithoutObservers.GetComponent().SpawnWithObservers = false; } // Check that the first client see them, or not, as expected @@ -377,6 +388,105 @@ namespace Unity.Netcode.RuntimeTests LogAssert.NoUnexpectedReceived(); } + + private List m_ClientsWithVisibility = new List(); + private NetworkObject m_ObserverTestObject; + + private bool CheckListedClientsVisibility() + { + if (m_ClientsWithVisibility.Contains(m_ServerNetworkManager.LocalClientId)) + { + if (!m_ServerNetworkManager.SpawnManager.SpawnedObjects.ContainsKey(m_ObserverTestObject.NetworkObjectId)) + { + return false; + } + } + + foreach (var client in m_ClientNetworkManagers) + { + if (m_ClientsWithVisibility.Contains(client.LocalClientId)) + { + if (!client.SpawnManager.SpawnedObjects.ContainsKey(m_ObserverTestObject.NetworkObjectId)) + { + return false; + } + } + } + return true; + } + + [UnityTest] + public IEnumerator SpawnWithoutObserversTest() + { + var spawnedObject = SpawnObject(m_PrefabSpawnWithoutObservers, m_ServerNetworkManager); + + m_ObserverTestObject = spawnedObject.GetComponent(); + + yield return WaitForTicks(m_ServerNetworkManager, 3); + + // When in client-server, the server can spawn a NetworkObject without any observers (even when running as a host the host-client should not have visibility) + // When in distributed authority mode, the owner client has to be an observer of the object + if (!m_DistributedAuthority) + { + // No observers should be assigned at this point + Assert.True(m_ObserverTestObject.Observers.Count == m_ClientsWithVisibility.Count, $"Expected the observer count to be {m_ClientsWithVisibility.Count} but it was {m_ObserverTestObject.Observers.Count}!"); + m_ObserverTestObject.NetworkShow(m_ServerNetworkManager.LocalClientId); + } + m_ClientsWithVisibility.Add(m_ServerNetworkManager.LocalClientId); + + Assert.True(m_ObserverTestObject.Observers.Count == m_ClientsWithVisibility.Count, $"Expected the observer count to be {m_ClientsWithVisibility.Count} but it was {m_ObserverTestObject.Observers.Count}!"); + + yield return WaitForConditionOrTimeOut(CheckListedClientsVisibility); + AssertOnTimeout($"[Authority-Only] Timed out waiting for only the authority to be an observer!"); + + foreach (var client in m_ClientNetworkManagers) + { + m_ObserverTestObject.NetworkShow(client.LocalClientId); + m_ClientsWithVisibility.Add(client.LocalClientId); + Assert.True(m_ObserverTestObject.Observers.Contains(client.LocalClientId), $"[NetworkShow] Client-{client.LocalClientId} is still not an observer!"); + Assert.True(m_ObserverTestObject.Observers.Count == m_ClientsWithVisibility.Count, $"Expected the observer count to be {m_ClientsWithVisibility.Count} but it was {m_ObserverTestObject.Observers.Count}!"); + + yield return WaitForConditionOrTimeOut(CheckListedClientsVisibility); + AssertOnTimeout($"[Client-{client.LocalClientId}] Timed out waiting for the client to be an observer and spawn the {nameof(NetworkObject)}!"); + Assert.False(client.SpawnManager.SpawnedObjects[m_ObserverTestObject.NetworkObjectId].SpawnWithObservers, $"Client-{client.LocalClientId} instance of {m_ObserverTestObject.name} has a {nameof(NetworkObject.SpawnWithObservers)} value of true!"); + } + } + + private bool ClientsSpawnedObject1() + { + foreach (var client in m_ClientNetworkManagers) + { + if (!client.SpawnManager.SpawnedObjects.ContainsKey(m_NetSpawnedObject1.NetworkObjectId)) + { + return false; + } + } + return true; + } + + private StringBuilder m_ErrorLog = new StringBuilder(); + private ulong m_ClientWithoutVisibility; + private bool Object1IsNotVisibileToClient() + { + m_ErrorLog.Clear(); + foreach (var client in m_ClientNetworkManagers) + { + if (client.LocalClientId == m_ClientWithoutVisibility) + { + if (client.SpawnManager.SpawnedObjects.ContainsKey(m_NetSpawnedObject1.NetworkObjectId)) + { + m_ErrorLog.AppendLine($"{m_NetSpawnedObject1.name} is still visible to Client-{m_ClientWithoutVisibility}!"); + } + } + else + if (client.SpawnManager.SpawnedObjects[m_NetSpawnedObject1.NetworkObjectId].IsNetworkVisibleTo(m_ClientWithoutVisibility)) + { + m_ErrorLog.AppendLine($"Local instance of {m_NetSpawnedObject1.name} on Client-{client.LocalClientId} thinks Client-{m_ClientWithoutVisibility} still has visibility!"); + } + } + return m_ErrorLog.Length == 0; + } + [UnityTest] public IEnumerator NetworkHideChangeOwnership() { @@ -387,12 +497,29 @@ namespace Unity.Netcode.RuntimeTests var spawnedObject1 = SpawnObject(m_PrefabToSpawn, m_ServerNetworkManager); m_NetSpawnedObject1 = spawnedObject1.GetComponent(); + yield return WaitForConditionOrTimeOut(ClientsSpawnedObject1); + AssertOnTimeout($"Not all clients spawned object!"); + m_NetSpawnedObject1.GetComponent().MyNetworkVariable.Value++; // Hide an object to a client m_NetSpawnedObject1.NetworkHide(m_ClientNetworkManagers[1].LocalClientId); + m_ClientWithoutVisibility = m_ClientNetworkManagers[1].LocalClientId; + + yield return WaitForConditionOrTimeOut(Object1IsNotVisibileToClient); + AssertOnTimeout($"NetworkObject is still visible to Client-{m_ClientWithoutVisibility} or other clients think it is still visible to Client-{m_ClientWithoutVisibility}:\n {m_ErrorLog}"); yield return WaitForConditionOrTimeOut(() => ShowHideObject.ClientTargetedNetworkObjects.Count == 0); + foreach (var client in m_ClientNetworkManagers) + { + if (m_ClientNetworkManagers[1].LocalClientId == client.LocalClientId) + { + continue; + } + var clientInstance = client.SpawnManager.SpawnedObjects[m_NetSpawnedObject1.NetworkObjectId]; + Assert.IsFalse(clientInstance.IsNetworkVisibleTo(m_ClientNetworkManagers[1].LocalClientId), $"Object instance on Client-{client.LocalClientId} is still visible to Client-{m_ClientNetworkManagers[1].LocalClientId}!"); + } + // Change ownership while the object is hidden to some m_NetSpawnedObject1.ChangeOwnership(m_ClientNetworkManagers[0].LocalClientId); @@ -400,30 +527,49 @@ namespace Unity.Netcode.RuntimeTests yield return new WaitForSeconds(1.25f); LogAssert.NoUnexpectedReceived(); - // Show the object again to check nothing unexpected happens - m_NetSpawnedObject1.NetworkShow(m_ClientNetworkManagers[1].LocalClientId); + if (m_DistributedAuthority) + { + Assert.True(m_ClientNetworkManagers[0].SpawnManager.SpawnedObjects.ContainsKey(m_NetSpawnedObject1.NetworkObjectId), $"Client-{m_ClientNetworkManagers[0].LocalClientId} has no spawned object with an ID of: {m_NetSpawnedObject1.NetworkObjectId}!"); + var clientInstance = m_ClientNetworkManagers[0].SpawnManager.SpawnedObjects[m_NetSpawnedObject1.NetworkObjectId]; + Assert.True(clientInstance.HasAuthority, $"Client-{m_ClientNetworkManagers[0].LocalClientId} does not have authority to hide NetworkObject ID: {m_NetSpawnedObject1.NetworkObjectId}!"); + clientInstance.NetworkShow(m_ClientNetworkManagers[1].LocalClientId); + } + else + { + m_NetSpawnedObject1.NetworkShow(m_ClientNetworkManagers[1].LocalClientId); + } yield return WaitForConditionOrTimeOut(() => ShowHideObject.ClientTargetedNetworkObjects.Count == 1); Assert.True(ShowHideObject.ClientTargetedNetworkObjects[0].OwnerClientId == m_ClientNetworkManagers[0].LocalClientId); } + private bool AllClientsSpawnedObject1() + { + foreach (var client in m_ClientNetworkManagers) + { + if (!ShowHideObject.ObjectsPerClientId.ContainsKey(client.LocalClientId)) + { + return false; + } + } + return true; + } + [UnityTest] public IEnumerator NetworkHideChangeOwnershipNotHidden() { ShowHideObject.ClientTargetedNetworkObjects.Clear(); + ShowHideObject.ObjectsPerClientId.Clear(); ShowHideObject.ClientIdToTarget = m_ClientNetworkManagers[1].LocalClientId; ShowHideObject.Silent = true; var spawnedObject1 = SpawnObject(m_PrefabToSpawn, m_ServerNetworkManager); m_NetSpawnedObject1 = spawnedObject1.GetComponent(); - // wait for host to have spawned and gained ownership - while (ShowHideObject.GainOwnershipCount == 0) - { - yield return new WaitForSeconds(0.0f); - } + yield return WaitForConditionOrTimeOut(AllClientsSpawnedObject1); + AssertOnTimeout($"Timed out waiting for all clients to spawn {spawnedObject1.name}!"); // change the value m_NetSpawnedObject1.GetComponent().MyOwnerReadNetworkVariable.Value++; @@ -445,10 +591,10 @@ namespace Unity.Netcode.RuntimeTests yield return WaitForTicks(m_ClientNetworkManagers[0], 3); // verify ownership changed - Assert.True(ShowHideObject.ClientTargetedNetworkObjects[0].OwnerClientId == m_ClientNetworkManagers[0].LocalClientId); + Assert.AreEqual(ShowHideObject.ClientTargetedNetworkObjects[0].OwnerClientId, m_ClientNetworkManagers[0].LocalClientId); // verify the expected client got the OnValueChanged. (Only client 1 sets this value) - Assert.True(ShowHideObject.ValueAfterOwnershipChange == 1); + Assert.AreEqual(1, ShowHideObject.ValueAfterOwnershipChange); } private string Display(NetworkList list) @@ -487,20 +633,20 @@ namespace Unity.Netcode.RuntimeTests private IEnumerator HideThenShowAndHideThenModifyAndShow() { - Debug.Log("Hiding"); + VerboseDebug("Hiding"); // hide m_NetSpawnedObject1.NetworkHide(1); yield return WaitForTicks(m_ServerNetworkManager, 3); yield return WaitForTicks(m_ClientNetworkManagers[0], 3); - Debug.Log("Showing and Hiding"); + VerboseDebug("Showing and Hiding"); // show and hide m_NetSpawnedObject1.NetworkShow(1); m_NetSpawnedObject1.NetworkHide(1); yield return WaitForTicks(m_ServerNetworkManager, 3); yield return WaitForTicks(m_ClientNetworkManagers[0], 3); - Debug.Log("Modifying and Showing"); + VerboseDebug("Modifying and Showing"); // modify and show m_NetSpawnedObject1.GetComponent().MyList.Add(5); m_NetSpawnedObject1.NetworkShow(1); @@ -575,19 +721,19 @@ namespace Unity.Netcode.RuntimeTests switch (i) { case 0: - Debug.Log("Running HideThenModifyAndShow"); + VerboseDebug("Running HideThenModifyAndShow"); yield return HideThenModifyAndShow(); break; case 1: - Debug.Log("Running HideThenShowAndModify"); + VerboseDebug("Running HideThenShowAndModify"); yield return HideThenShowAndModify(); break; case 2: - Debug.Log("Running HideThenShowAndHideThenModifyAndShow"); + VerboseDebug("Running HideThenShowAndHideThenModifyAndShow"); yield return HideThenShowAndHideThenModifyAndShow(); break; case 3: - Debug.Log("Running HideThenShowAndRPC"); + VerboseDebug("Running HideThenShowAndRPC"); ShowHideObject.ClientIdsRpcCalledOn = new List(); yield return HideThenShowAndRPC(); // Provide enough time for slower systems or VM systems possibly under a heavy load could fail on this test diff --git a/Tests/Runtime/NetworkSpawnManagerTests.cs b/Tests/Runtime/NetworkSpawnManagerTests.cs index 0806775..63a83db 100644 --- a/Tests/Runtime/NetworkSpawnManagerTests.cs +++ b/Tests/Runtime/NetworkSpawnManagerTests.cs @@ -1,11 +1,12 @@ using System.Collections; using NUnit.Framework; using Unity.Netcode.TestHelpers.Runtime; -using UnityEngine; using UnityEngine.TestTools; namespace Unity.Netcode.RuntimeTests { + [TestFixture(HostOrServer.DAHost)] + [TestFixture(HostOrServer.Host)] public class NetworkSpawnManagerTests : NetcodeIntegrationTest { private ulong serverSideClientId => NetworkManager.ServerClientId; @@ -14,6 +15,8 @@ namespace Unity.Netcode.RuntimeTests protected override int NumberOfClients => 2; + public NetworkSpawnManagerTests(HostOrServer hostOrServer) : base(hostOrServer) { } + [Test] public void TestServerCanAccessItsOwnPlayer() { @@ -23,9 +26,16 @@ namespace Unity.Netcode.RuntimeTests Assert.AreEqual(serverSideClientId, serverSideServerPlayerObject.OwnerClientId); } - [Test] - public void TestServerCanAccessOtherPlayers() + + /// + /// Test was converted from a Test to UnityTest so distributed authority mode will pass this test. + /// In distributed authority mode, client-side player spawning is enabled by default which requires + /// all client (including DAHost) instances to wait for all players to be spawned. + /// + [UnityTest] + public IEnumerator TestServerCanAccessOtherPlayers() { + yield return null; // server can access other players var serverSideClientPlayerObject = m_ServerNetworkManager.SpawnManager.GetPlayerNetworkObject(clientSideClientId); Assert.NotNull(serverSideClientPlayerObject); @@ -34,11 +44,17 @@ namespace Unity.Netcode.RuntimeTests var serverSideOtherClientPlayerObject = m_ServerNetworkManager.SpawnManager.GetPlayerNetworkObject(otherClientSideClientId); Assert.NotNull(serverSideOtherClientPlayerObject); Assert.AreEqual(otherClientSideClientId, serverSideOtherClientPlayerObject.OwnerClientId); + } [Test] public void TestClientCantAccessServerPlayer() { + if (m_DistributedAuthority) + { + VerboseDebug($"Ignoring test: Clients have access to other player objects in {m_SessionModeType} mode."); + return; + } // client can't access server player Assert.Throws(() => { @@ -55,9 +71,29 @@ namespace Unity.Netcode.RuntimeTests Assert.AreEqual(clientSideClientId, clientSideClientPlayerObject.OwnerClientId); } + [Test] + public void TestClientCanAccessOtherPlayer() + { + + if (!m_DistributedAuthority) + { + VerboseDebug($"Ignoring test: Clients do not have access to other player objects in {m_SessionModeType} mode."); + return; + } + + var otherClientPlayer = m_ClientNetworkManagers[0].SpawnManager.GetPlayerNetworkObject(otherClientSideClientId); + Assert.NotNull(otherClientPlayer, $"Failed to obtain Client{otherClientSideClientId}'s player object!"); + } + [Test] public void TestClientCantAccessOtherPlayer() { + if (m_DistributedAuthority) + { + VerboseDebug($"Ignoring test: Clients have access to other player objects in {m_SessionModeType} mode."); + return; + } + // client can't access other player Assert.Throws(() => { @@ -97,18 +133,8 @@ namespace Unity.Netcode.RuntimeTests public IEnumerator TestConnectAndDisconnect() { // test when client connects, player object is now available - - // connect new client - if (!NetcodeIntegrationTestHelpers.CreateNewClients(1, out NetworkManager[] clients)) - { - Debug.LogError("Failed to create instances"); - Assert.Fail("Failed to create instances"); - } - var newClientNetworkManager = clients[0]; - newClientNetworkManager.NetworkConfig.PlayerPrefab = m_PlayerPrefab; - newClientNetworkManager.StartClient(); - yield return NetcodeIntegrationTestHelpers.WaitForClientConnected(newClientNetworkManager); - yield return WaitForConditionOrTimeOut(() => m_ServerNetworkManager.ConnectedClients.ContainsKey(newClientNetworkManager.LocalClientId)); + yield return CreateAndStartNewClient(); + var newClientNetworkManager = m_ClientNetworkManagers[NumberOfClients]; var newClientLocalClientId = newClientNetworkManager.LocalClientId; // test new client can get that itself locally diff --git a/Tests/Runtime/NetworkTransform/NetworkTransformBase.cs b/Tests/Runtime/NetworkTransform/NetworkTransformBase.cs index 736d402..9d725e0 100644 --- a/Tests/Runtime/NetworkTransform/NetworkTransformBase.cs +++ b/Tests/Runtime/NetworkTransform/NetworkTransformBase.cs @@ -12,12 +12,12 @@ namespace Unity.Netcode.RuntimeTests public class NetworkTransformBase : IntegrationTestWithApproximation { - // The number of iterations to change position, rotation, and scale for NetworkTransformMultipleChangesOverTime + // The number of iterations to change position, rotation, and scale for NetworkTransformMultipleChangesOverTime protected const int k_PositionRotationScaleIterations = 3; protected const int k_PositionRotationScaleIterations3Axis = 8; protected float m_CurrentHalfPrecision = 0.0f; - protected const float k_HalfPrecisionPosScale = 0.115f; + protected const float k_HalfPrecisionPosScale = 0.1256f; protected const float k_HalfPrecisionRot = 0.725f; @@ -126,7 +126,7 @@ namespace Unity.Netcode.RuntimeTests { return m_CurrentHalfPrecision; } - return 0.045f; + return 0.055f; } /// @@ -473,12 +473,12 @@ namespace Unity.Netcode.RuntimeTests } if (!Approximately(childLocalPosition, authorityObjectLocalPosition)) { - m_InfoMessage.AppendLine($"[{childParentName}][{childInstance.name}] Child's Local Position ({childLocalPosition}) | Authority Local Position ({authorityObjectLocalPosition})"); + m_InfoMessage.AppendLine($"[{childParentName}][{childInstance.name}] Child's Local Position ({GetVector3Values(childLocalPosition)}) | Authority Local Position ({GetVector3Values(authorityObjectLocalPosition)})"); success = false; } if (!Approximately(childLocalScale, authorityObjectLocalScale)) { - m_InfoMessage.AppendLine($"[{childParentName}][{childInstance.name}] Child's Local Scale ({childLocalScale}) | Authority Local Scale ({authorityObjectLocalScale})"); + m_InfoMessage.AppendLine($"[{childParentName}][{childInstance.name}] Child's Local Scale ({GetVector3Values(childLocalScale)}) | Authority Local Scale ({GetVector3Values(authorityObjectLocalScale)})"); success = false; } @@ -489,7 +489,7 @@ namespace Unity.Netcode.RuntimeTests } if (!ApproximatelyEuler(childLocalRotation, authorityObjectLocalRotation)) { - m_InfoMessage.AppendLine($"[{childParentName}][{childInstance.name}] Child's Local Rotation ({childLocalRotation}) | Authority Local Rotation ({authorityObjectLocalRotation})"); + m_InfoMessage.AppendLine($"[{childParentName}][{childInstance.name}] Child's Local Rotation ({GetVector3Values(childLocalRotation)}) | Authority Local Rotation ({GetVector3Values(authorityObjectLocalRotation)})"); success = false; } } diff --git a/Tests/Runtime/NetworkTransform/NetworkTransformOwnershipTests.cs b/Tests/Runtime/NetworkTransform/NetworkTransformOwnershipTests.cs index 1bcd7a9..d6d35f3 100644 --- a/Tests/Runtime/NetworkTransform/NetworkTransformOwnershipTests.cs +++ b/Tests/Runtime/NetworkTransform/NetworkTransformOwnershipTests.cs @@ -9,13 +9,28 @@ using UnityEngine; using UnityEngine.TestTools; namespace Unity.Netcode.RuntimeTests { + [TestFixture(HostOrServer.DAHost, MotionModels.UseTransform)] + [TestFixture(HostOrServer.DAHost, MotionModels.UseRigidbody)] + [TestFixture(HostOrServer.Host, MotionModels.UseTransform)] public class NetworkTransformOwnershipTests : IntegrationTestWithApproximation { + public enum MotionModels + { + UseRigidbody, + UseTransform + } protected override int NumberOfClients => 1; private GameObject m_ClientNetworkTransformPrefab; private GameObject m_NetworkTransformPrefab; + private MotionModels m_MotionModel; + + public NetworkTransformOwnershipTests(HostOrServer hostOrServer, MotionModels motionModel) : base(hostOrServer) + { + m_MotionModel = motionModel; + } + protected override void OnServerAndClientsCreated() { VerifyObjectIsSpawnedOnClient.ResetObjectTable(); @@ -25,20 +40,26 @@ namespace Unity.Netcode.RuntimeTests clientNetworkTransform.UseHalfFloatPrecision = false; var rigidBody = m_ClientNetworkTransformPrefab.AddComponent(); rigidBody.useGravity = false; + rigidBody.interpolation = RigidbodyInterpolation.None; + rigidBody.maxLinearVelocity = 0; // NOTE: We don't use a sphere collider for this integration test because by the time we can // assure they don't collide and skew the results the NetworkObjects are already synchronized // with skewed results - m_ClientNetworkTransformPrefab.AddComponent(); + var networkRigidbody = m_ClientNetworkTransformPrefab.AddComponent(); + networkRigidbody.UseRigidBodyForMotion = m_MotionModel == MotionModels.UseRigidbody; m_ClientNetworkTransformPrefab.AddComponent(); m_NetworkTransformPrefab = CreateNetworkObjectPrefab("ServerAuthorityTest"); var networkTransform = m_NetworkTransformPrefab.AddComponent(); rigidBody = m_NetworkTransformPrefab.AddComponent(); rigidBody.useGravity = false; + rigidBody.interpolation = RigidbodyInterpolation.None; + rigidBody.maxLinearVelocity = 0; // NOTE: We don't use a sphere collider for this integration test because by the time we can // assure they don't collide and skew the results the NetworkObjects are already synchronized // with skewed results - m_NetworkTransformPrefab.AddComponent(); + networkRigidbody = m_NetworkTransformPrefab.AddComponent(); + networkRigidbody.UseRigidBodyForMotion = m_MotionModel == MotionModels.UseRigidbody; m_NetworkTransformPrefab.AddComponent(); networkTransform.Interpolate = false; networkTransform.UseHalfFloatPrecision = false; @@ -99,10 +120,14 @@ namespace Unity.Netcode.RuntimeTests // Wait until the client gains ownership yield return WaitForConditionOrTimeOut(ClientIsOwner); + AssertOnTimeout($"Timed out waiting for the {nameof(ClientIsOwner)} condition to be met!"); // Spawn a new client yield return CreateAndStartNewClient(); + yield return WaitForConditionOrTimeOut(() => VerifyObjectIsSpawnedOnClient.NetworkManagerRelativeSpawnedObjects.ContainsKey(m_ClientNetworkManagers[1].LocalClientId)); + AssertOnTimeout($"Timed out waiting for late joing client VerifyObjectIsSpawnedOnClient entry to be created!"); + // Get the instance of the object relative to the newly joined client var newClientObjectInstance = VerifyObjectIsSpawnedOnClient.GetClientInstance(m_ClientNetworkManagers[1].LocalClientId); @@ -117,7 +142,16 @@ namespace Unity.Netcode.RuntimeTests // Wait one frame so the NetworkTransform can apply the owner's last state received on the late joining client side // (i.e. prevent the non-owner from changing the transform) - yield return null; + if (m_MotionModel == MotionModels.UseRigidbody) + { + // Allow fixed update to run twice for values to propogate to Unity transform + yield return new WaitForFixedUpdate(); + yield return new WaitForFixedUpdate(); + } + else + { + yield return null; + } // Get the owner instance var ownerInstance = VerifyObjectIsSpawnedOnClient.GetClientInstance(m_ClientNetworkManagers[0].LocalClientId); @@ -139,6 +173,23 @@ namespace Unity.Netcode.RuntimeTests ClientStartsAsOwner, } + private bool ClientAndServerSpawnedInstance() + { + return VerifyObjectIsSpawnedOnClient.NetworkManagerRelativeSpawnedObjects.ContainsKey(m_ServerNetworkManager.LocalClientId) && VerifyObjectIsSpawnedOnClient.NetworkManagerRelativeSpawnedObjects.ContainsKey(m_ClientNetworkManagers[0].LocalClientId); + } + + private bool m_UseAdjustedVariance; + private const float k_AdjustedVariance = 0.025f; + + protected override float GetDeltaVarianceThreshold() + { + if (m_UseAdjustedVariance) + { + return k_AdjustedVariance; + } + return base.GetDeltaVarianceThreshold(); + } + /// /// This verifies that when authority is owner authoritative the owner's /// Rigidbody is kinematic and the non-owner's is not. @@ -155,28 +206,90 @@ namespace Unity.Netcode.RuntimeTests // Spawn the m_ClientNetworkTransformPrefab and wait for the client-side to spawn the object var serverSideInstance = SpawnObject(m_ClientNetworkTransformPrefab, networkManagerOwner); - yield return WaitForConditionOrTimeOut(() => VerifyObjectIsSpawnedOnClient.GetClientsThatSpawnedThisPrefab().Contains(m_ClientNetworkManagers[0].LocalClientId)); + yield return WaitForConditionOrTimeOut(ClientAndServerSpawnedInstance); + AssertOnTimeout($"Timed out waiting for all object instances to be spawned!"); // Get owner relative instances var ownerInstance = VerifyObjectIsSpawnedOnClient.GetClientInstance(networkManagerOwner.LocalClientId); var nonOwnerInstance = VerifyObjectIsSpawnedOnClient.GetClientInstance(networkManagerNonOwner.LocalClientId); Assert.NotNull(ownerInstance); Assert.NotNull(nonOwnerInstance); + Assert.True(networkManagerOwner.LocalClientId != networkManagerNonOwner.LocalClientId); + Assert.True(nonOwnerInstance.OwnerClientId != networkManagerNonOwner.LocalClientId); + Assert.True(nonOwnerInstance.NetworkManager.LocalClientId == networkManagerNonOwner.LocalClientId); + + Vector3 GetNonOwnerPosition() + { + if (m_MotionModel == MotionModels.UseRigidbody) + { + return nonOwnerInstance.GetComponent().position; + } + else + { + return nonOwnerInstance.transform.position; + } + } + + Quaternion GetNonOwnerRotation() + { + if (m_MotionModel == MotionModels.UseRigidbody) + { + return nonOwnerInstance.GetComponent().rotation; + } + else + { + return nonOwnerInstance.transform.rotation; + } + } + + void LogNonOwnerRigidBody(int stage) + { + if (m_MotionModel == MotionModels.UseRigidbody && m_EnableVerboseDebug) + { + var rigidbody = nonOwnerInstance.GetComponent(); + Debug.Log($"[{stage}][Rigidbody-NonOwner][Owner:{nonOwnerInstance.OwnerClientId} [Client-{nonOwnerInstance.NetworkManager.LocalClientId}][Gravity: {rigidbody.useGravity}][Kinematic: {rigidbody.isKinematic}][RB-Pos: {rigidbody.position}][RB-Rotation: {rigidbody.rotation}]"); + } + } + + void LogOwnerRigidBody(int stage) + { + if (m_MotionModel == MotionModels.UseRigidbody && m_EnableVerboseDebug) + { + var rigidbody = ownerInstance.GetComponent(); + Debug.Log($"[{stage}][Rigidbody-Owner][Owner:{ownerInstance.OwnerClientId} [Client-{ownerInstance.NetworkManager.LocalClientId}][Gravity: {rigidbody.useGravity}][Kinematic: {rigidbody.isKinematic}][RB-Pos: {rigidbody.position}][RB-Rotation: {rigidbody.rotation}]"); + } + } // Make sure the owner is not kinematic and the non-owner(s) are kinematic Assert.True(nonOwnerInstance.GetComponent().isKinematic, $"{networkManagerNonOwner.name}'s object instance {nonOwnerInstance.name} is not kinematic when it should be!"); Assert.False(ownerInstance.GetComponent().isKinematic, $"{networkManagerOwner.name}'s object instance {ownerInstance.name} is kinematic when it should not be!"); - + if (m_MotionModel == MotionModels.UseRigidbody) + { + nonOwnerInstance.GetComponent().LogStateUpdate = m_EnableVerboseDebug; + } // Owner changes transform values var valueSetByOwner = Vector3.one * 2; - ownerInstance.transform.position = valueSetByOwner; - ownerInstance.transform.localScale = valueSetByOwner; var rotation = new Quaternion { eulerAngles = valueSetByOwner }; - ownerInstance.transform.rotation = rotation; + if (m_MotionModel == MotionModels.UseRigidbody) + { + var ownerRigidbody = ownerInstance.GetComponent(); + ownerRigidbody.Move(valueSetByOwner, rotation); + ownerRigidbody.linearVelocity = Vector3.zero; + yield return s_DefaultWaitForTick; + ownerInstance.transform.localScale = valueSetByOwner; + } + else + { + ownerInstance.transform.position = valueSetByOwner; + ownerInstance.transform.rotation = rotation; + ownerInstance.transform.localScale = valueSetByOwner; + } + var transformToTest = nonOwnerInstance.transform; + LogNonOwnerRigidBody(1); yield return WaitForConditionOrTimeOut(() => Approximately(transformToTest.position, valueSetByOwner) && Approximately(transformToTest.localScale, valueSetByOwner) && Approximately(transformToTest.rotation, rotation)); Assert.False(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for {networkManagerNonOwner.name}'s object instance {nonOwnerInstance.name} to change its transform!\n" + $"Expected Position: {valueSetByOwner} | Current Position: {transformToTest.position}\n" + @@ -186,14 +299,29 @@ namespace Unity.Netcode.RuntimeTests // Verify non-owners cannot change transform values nonOwnerInstance.transform.position = Vector3.zero; yield return s_DefaultWaitForTick; - Assert.True(Approximately(nonOwnerInstance.transform.position, valueSetByOwner), $"{networkManagerNonOwner.name}'s object instance {nonOwnerInstance.name} was allowed to change its position! Expected: {valueSetByOwner} Is Currently:{nonOwnerInstance.transform.position}"); + if (m_MotionModel == MotionModels.UseRigidbody) + { + yield return new WaitForFixedUpdate(); + } + + LogNonOwnerRigidBody(2); + Assert.True(Approximately(GetNonOwnerPosition(), valueSetByOwner), $"{networkManagerNonOwner.name}'s object instance {nonOwnerInstance.name} was allowed to change its position! Expected: {valueSetByOwner} Is Currently:{GetNonOwnerPosition()}"); // Change ownership and wait for the non-owner to reflect the change VerifyObjectIsSpawnedOnClient.ResetObjectTable(); - m_ServerNetworkManager.SpawnManager.ChangeOwnership(serverSideInstance.GetComponent(), networkManagerNonOwner.LocalClientId); + if (m_DistributedAuthority) + { + ownerInstance.NetworkObject.ChangeOwnership(networkManagerNonOwner.LocalClientId); + } + else + { + m_ServerNetworkManager.SpawnManager.ChangeOwnership(serverSideInstance.GetComponent(), networkManagerNonOwner.LocalClientId, true); + } + LogNonOwnerRigidBody(3); yield return WaitForConditionOrTimeOut(() => nonOwnerInstance.GetComponent().OwnerClientId == networkManagerNonOwner.LocalClientId); Assert.False(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for {networkManagerNonOwner.name}'s object instance {nonOwnerInstance.name} to change ownership!"); + LogNonOwnerRigidBody(4); // Re-assign the ownership references and wait for the non-owner instance to be notified of ownership change networkManagerOwner = startingOwnership == StartingOwnership.HostStartsAsOwner ? m_ClientNetworkManagers[0] : m_ServerNetworkManager; networkManagerNonOwner = startingOwnership == StartingOwnership.HostStartsAsOwner ? m_ServerNetworkManager : m_ClientNetworkManagers[0]; @@ -206,15 +334,48 @@ namespace Unity.Netcode.RuntimeTests // Make sure the owner is not kinematic and the non-owner(s) are kinematic Assert.False(ownerInstance.GetComponent().isKinematic, $"{networkManagerOwner.name}'s object instance {ownerInstance.name} is kinematic when it should not be!"); Assert.True(nonOwnerInstance.GetComponent().isKinematic, $"{networkManagerNonOwner.name}'s object instance {nonOwnerInstance.name} is not kinematic when it should be!"); + transformToTest = nonOwnerInstance.transform; + Assert.True(networkManagerOwner.LocalClientId != networkManagerNonOwner.LocalClientId); + Assert.True(nonOwnerInstance.OwnerClientId != networkManagerNonOwner.LocalClientId); + Assert.True(nonOwnerInstance.NetworkManager.LocalClientId == networkManagerNonOwner.LocalClientId); + yield return WaitForConditionOrTimeOut(() => Approximately(transformToTest.position, valueSetByOwner) && Approximately(transformToTest.localScale, valueSetByOwner) && Approximately(transformToTest.rotation, rotation)); + Assert.False(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for {networkManagerNonOwner.name}'s object instance {nonOwnerInstance.name} to change its transform!\n" + + $"Expected Position: {valueSetByOwner} | Current Position: {transformToTest.position}\n" + + $"Expected Rotation: {valueSetByOwner} | Current Rotation: {transformToTest.rotation.eulerAngles}\n" + + $"Expected Scale: {valueSetByOwner} | Current Scale: {transformToTest.localScale}"); + + LogNonOwnerRigidBody(5); // Have the new owner change transform values and wait for those values to be applied on the non-owner side. valueSetByOwner = Vector3.one * 10; - ownerInstance.transform.position = valueSetByOwner; ownerInstance.transform.localScale = valueSetByOwner; rotation.eulerAngles = valueSetByOwner; - ownerInstance.transform.rotation = rotation; - transformToTest = nonOwnerInstance.transform; - yield return WaitForConditionOrTimeOut(() => Approximately(transformToTest.position, valueSetByOwner) && Approximately(transformToTest.localScale, valueSetByOwner) && Approximately(transformToTest.rotation, rotation)); + LogOwnerRigidBody(1); + if (m_MotionModel == MotionModels.UseRigidbody) + { + m_UseAdjustedVariance = true; + var ownerRigidbody = ownerInstance.GetComponent(); + ownerRigidbody.Move(valueSetByOwner, rotation); + LogOwnerRigidBody(2); + ownerInstance.GetComponent().LogMotion = m_EnableVerboseDebug; + nonOwnerInstance.GetComponent().LogMotion = m_EnableVerboseDebug; + ownerRigidbody.linearVelocity = Vector3.zero; + } + else + { + m_UseAdjustedVariance = false; + ownerInstance.transform.position = valueSetByOwner; + ownerInstance.transform.rotation = rotation; + } + + LogOwnerRigidBody(3); + LogNonOwnerRigidBody(6); + yield return WaitForConditionOrTimeOut(() => Approximately(GetNonOwnerPosition(), valueSetByOwner) && Approximately(transformToTest.localScale, valueSetByOwner) && Approximately(GetNonOwnerRotation(), rotation)); + if (s_GlobalTimeoutHelper.TimedOut) + { + LogOwnerRigidBody(4); + LogNonOwnerRigidBody(7); + } Assert.False(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for {networkManagerNonOwner.name}'s object instance {nonOwnerInstance.name} to change its transform!\n" + $"Expected Position: {valueSetByOwner} | Current Position: {transformToTest.position}\n" + $"Expected Rotation: {valueSetByOwner} | Current Rotation: {transformToTest.rotation.eulerAngles}\n" + @@ -223,7 +384,11 @@ namespace Unity.Netcode.RuntimeTests // The last check is to verify non-owners cannot change transform values after ownership has changed nonOwnerInstance.transform.position = Vector3.zero; yield return s_DefaultWaitForTick; - Assert.True(Approximately(nonOwnerInstance.transform.position, valueSetByOwner), $"{networkManagerNonOwner.name}'s object instance {nonOwnerInstance.name} was allowed to change its position! Expected: {Vector3.one} Is Currently:{nonOwnerInstance.transform.position}"); + if (m_MotionModel == MotionModels.UseRigidbody) + { + yield return new WaitForFixedUpdate(); + } + Assert.True(Approximately(GetNonOwnerPosition(), valueSetByOwner), $"{networkManagerNonOwner.name}'s object instance {nonOwnerInstance.name} was allowed to change its position! Expected: {valueSetByOwner} Is Currently:{GetNonOwnerPosition()}"); } /// @@ -255,6 +420,12 @@ namespace Unity.Netcode.RuntimeTests eulerAngles = valueSetByOwner }; ownerInstance.transform.rotation = rotation; + + // Allow scale to update first when using rigid body motion + if (m_MotionModel == MotionModels.UseRigidbody) + { + yield return new WaitForFixedUpdate(); + } var transformToTest = nonOwnerInstance.transform; yield return WaitForConditionOrTimeOut(() => transformToTest.position == valueSetByOwner && transformToTest.localScale == valueSetByOwner && transformToTest.rotation == rotation); Assert.False(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for {m_ClientNetworkManagers[0].name}'s object instance {nonOwnerInstance.name} to change its transform!\n" + @@ -265,6 +436,11 @@ namespace Unity.Netcode.RuntimeTests // The last check is to verify clients cannot change transform values nonOwnerInstance.transform.position = Vector3.zero; yield return s_DefaultWaitForTick; + // Allow scale to update first when using rigid body motion + if (m_MotionModel == MotionModels.UseRigidbody) + { + yield return new WaitForFixedUpdate(); + } Assert.True(nonOwnerInstance.transform.position == valueSetByOwner, $"{m_ClientNetworkManagers[0].name}'s object instance {nonOwnerInstance.name} was allowed to change its position! Expected: {Vector3.one} Is Currently:{nonOwnerInstance.transform.position}"); } @@ -273,59 +449,59 @@ namespace Unity.Netcode.RuntimeTests /// public class VerifyObjectIsSpawnedOnClient : NetworkBehaviour { - private static Dictionary s_NetworkManagerRelativeSpawnedObjects = new Dictionary(); + public static Dictionary NetworkManagerRelativeSpawnedObjects = new Dictionary(); public static void ResetObjectTable() { - s_NetworkManagerRelativeSpawnedObjects.Clear(); + NetworkManagerRelativeSpawnedObjects.Clear(); } public override void OnGainedOwnership() { - if (!s_NetworkManagerRelativeSpawnedObjects.ContainsKey(NetworkManager.LocalClientId)) + if (!NetworkManagerRelativeSpawnedObjects.ContainsKey(NetworkManager.LocalClientId)) { - s_NetworkManagerRelativeSpawnedObjects.Add(NetworkManager.LocalClientId, this); + NetworkManagerRelativeSpawnedObjects.Add(NetworkManager.LocalClientId, this); } base.OnGainedOwnership(); } public override void OnLostOwnership() { - if (!s_NetworkManagerRelativeSpawnedObjects.ContainsKey(NetworkManager.LocalClientId)) + if (!NetworkManagerRelativeSpawnedObjects.ContainsKey(NetworkManager.LocalClientId)) { - s_NetworkManagerRelativeSpawnedObjects.Add(NetworkManager.LocalClientId, this); + NetworkManagerRelativeSpawnedObjects.Add(NetworkManager.LocalClientId, this); } base.OnLostOwnership(); } public static List GetClientsThatSpawnedThisPrefab() { - return s_NetworkManagerRelativeSpawnedObjects.Keys.ToList(); + return NetworkManagerRelativeSpawnedObjects.Keys.ToList(); } public static VerifyObjectIsSpawnedOnClient GetClientInstance(ulong clientId) { - if (s_NetworkManagerRelativeSpawnedObjects.ContainsKey(clientId)) + if (NetworkManagerRelativeSpawnedObjects.ContainsKey(clientId)) { - return s_NetworkManagerRelativeSpawnedObjects[clientId]; + return NetworkManagerRelativeSpawnedObjects[clientId]; } return null; } public override void OnNetworkSpawn() { - if (!s_NetworkManagerRelativeSpawnedObjects.ContainsKey(NetworkManager.LocalClientId)) + if (!NetworkManagerRelativeSpawnedObjects.ContainsKey(NetworkManager.LocalClientId)) { - s_NetworkManagerRelativeSpawnedObjects.Add(NetworkManager.LocalClientId, this); + NetworkManagerRelativeSpawnedObjects.Add(NetworkManager.LocalClientId, this); } base.OnNetworkSpawn(); } public override void OnNetworkDespawn() { - if (s_NetworkManagerRelativeSpawnedObjects.ContainsKey(NetworkManager.LocalClientId)) + if (NetworkManagerRelativeSpawnedObjects.ContainsKey(NetworkManager.LocalClientId)) { - s_NetworkManagerRelativeSpawnedObjects.Remove(NetworkManager.LocalClientId); + NetworkManagerRelativeSpawnedObjects.Remove(NetworkManager.LocalClientId); } base.OnNetworkDespawn(); } @@ -338,24 +514,24 @@ namespace Unity.Netcode.RuntimeTests [DisallowMultipleComponent] public class TestClientNetworkTransform : NetworkTransform { - public override void OnNetworkSpawn() - { - base.OnNetworkSpawn(); - CanCommitToTransform = IsOwner; - } + //public override void OnNetworkSpawn() + //{ + // base.OnNetworkSpawn(); + // CanCommitToTransform = IsOwner; + //} - protected override void Update() - { - CanCommitToTransform = IsOwner; - base.Update(); - if (NetworkManager.Singleton != null && (NetworkManager.Singleton.IsConnectedClient || NetworkManager.Singleton.IsListening)) - { - if (CanCommitToTransform) - { - TryCommitTransformToServer(transform, NetworkManager.LocalTime.Time); - } - } - } + //protected override void Update() + //{ + // CanCommitToTransform = IsOwner; + // base.Update(); + // if (NetworkManager.Singleton != null && (NetworkManager.Singleton.IsConnectedClient || NetworkManager.Singleton.IsListening)) + // { + // if (CanCommitToTransform) + // { + // TryCommitTransformToServer(transform, NetworkManager.LocalTime.Time); + // } + // } + //} protected override bool OnIsServerAuthoritative() { diff --git a/Tests/Runtime/NetworkTransform/NetworkTransformPacketLossTests.cs b/Tests/Runtime/NetworkTransform/NetworkTransformPacketLossTests.cs index 739fa4f..69bf8b1 100644 --- a/Tests/Runtime/NetworkTransform/NetworkTransformPacketLossTests.cs +++ b/Tests/Runtime/NetworkTransform/NetworkTransformPacketLossTests.cs @@ -14,6 +14,12 @@ namespace Unity.Netcode.RuntimeTests /// models for each operating mode when packet loss and latency is /// present. /// + [TestFixture(HostOrServer.DAHost, Authority.OwnerAuthority, RotationCompression.None, Rotation.Euler, Precision.Full)] + [TestFixture(HostOrServer.DAHost, Authority.OwnerAuthority, RotationCompression.None, Rotation.Euler, Precision.Half)] + [TestFixture(HostOrServer.DAHost, Authority.OwnerAuthority, RotationCompression.None, Rotation.Quaternion, Precision.Full)] + [TestFixture(HostOrServer.DAHost, Authority.OwnerAuthority, RotationCompression.None, Rotation.Quaternion, Precision.Half)] + [TestFixture(HostOrServer.DAHost, Authority.OwnerAuthority, RotationCompression.QuaternionCompress, Rotation.Quaternion, Precision.Full)] + [TestFixture(HostOrServer.DAHost, Authority.OwnerAuthority, RotationCompression.QuaternionCompress, Rotation.Quaternion, Precision.Half)] [TestFixture(HostOrServer.Host, Authority.ServerAuthority, RotationCompression.None, Rotation.Euler, Precision.Full)] [TestFixture(HostOrServer.Host, Authority.ServerAuthority, RotationCompression.None, Rotation.Euler, Precision.Half)] [TestFixture(HostOrServer.Host, Authority.ServerAuthority, RotationCompression.None, Rotation.Quaternion, Precision.Full)] @@ -54,13 +60,18 @@ namespace Unity.Netcode.RuntimeTests // We don't assert on timeout here because we want to log this information during PostAllChildrenLocalTransformValuesMatch yield return WaitForConditionOrTimeOut(() => AllInstancesKeptLocalTransformValues(useSubChild)); var success = true; - m_InfoMessage.AppendLine($"[{checkType}][{useSubChild}] Timed out waiting for all children to have the correct local space values:\n"); if (s_GlobalTimeoutHelper.TimedOut) { - var waitForMs = new WaitForSeconds(0.001f); + var waitForMs = new WaitForSeconds(0.0025f); + if (m_Precision == Precision.Half) + { + m_CurrentHalfPrecision = 0.2156f; + } // If we timed out, then wait for a full range of ticks to assure all data has been synchronized before declaring this a failed test. for (int j = 0; j < m_ServerNetworkManager.NetworkConfig.TickRate; j++) { + m_InfoMessage.Clear(); + m_InfoMessage.AppendLine($"[{checkType}][{useSubChild}] Timed out waiting for all children to have the correct local space values:\n"); var instances = useSubChild ? ChildObjectComponent.SubInstances : ChildObjectComponent.Instances; success = PostAllChildrenLocalTransformValuesMatch(useSubChild); yield return waitForMs; @@ -100,6 +111,11 @@ namespace Unity.Netcode.RuntimeTests var serverSideChild = SpawnObject(m_ChildObject.gameObject, authorityNetworkManager).GetComponent(); var serverSideSubChild = SpawnObject(m_SubChildObject.gameObject, authorityNetworkManager).GetComponent(); + yield return s_DefaultWaitForTick; + yield return s_DefaultWaitForTick; + yield return s_DefaultWaitForTick; + yield return s_DefaultWaitForTick; + // Assure all of the child object instances are spawned before proceeding to parenting yield return WaitForConditionOrTimeOut(AllChildObjectInstancesAreSpawned); AssertOnTimeout("Timed out waiting for all child instances to be spawned!"); diff --git a/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs b/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs index f2512ae..6cbc832 100644 --- a/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs +++ b/Tests/Runtime/NetworkTransform/NetworkTransformStateTests.cs @@ -1,3 +1,4 @@ +#if !MULTIPLAYER_TOOLS using NUnit.Framework; using Unity.Netcode.Components; using UnityEngine; @@ -233,6 +234,8 @@ namespace Unity.Netcode.RuntimeTests var manager = new GameObject($"Test-{nameof(NetworkManager)}.{nameof(TestSyncAxes)}"); var networkManager = manager.AddComponent(); + networkManager.NetworkConfig = new NetworkConfig(); + networkObject.NetworkManagerOwner = networkManager; networkTransform.enabled = false; // do not tick `FixedUpdate()` or `Update()` @@ -905,3 +908,4 @@ namespace Unity.Netcode.RuntimeTests } } } +#endif diff --git a/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs b/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs index 0b7be8a..abaac55 100644 --- a/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs +++ b/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs @@ -1,3 +1,4 @@ +using System.Collections; using NUnit.Framework; using UnityEngine; @@ -8,25 +9,37 @@ namespace Unity.Netcode.RuntimeTests /// server and host operating modes and will test both authoritative /// models for each operating mode. /// + [TestFixture(HostOrServer.DAHost, Authority.OwnerAuthority, RotationCompression.None, Rotation.Euler, Precision.Full)] +#if !MULTIPLAYER_TOOLS + [TestFixture(HostOrServer.DAHost, Authority.OwnerAuthority, RotationCompression.None, Rotation.Euler, Precision.Half)] + [TestFixture(HostOrServer.DAHost, Authority.OwnerAuthority, RotationCompression.None, Rotation.Quaternion, Precision.Full)] + [TestFixture(HostOrServer.DAHost, Authority.OwnerAuthority, RotationCompression.None, Rotation.Quaternion, Precision.Half)] + [TestFixture(HostOrServer.DAHost, Authority.OwnerAuthority, RotationCompression.QuaternionCompress, Rotation.Quaternion, Precision.Full)] + [TestFixture(HostOrServer.DAHost, Authority.OwnerAuthority, RotationCompression.QuaternionCompress, Rotation.Quaternion, Precision.Half)] +#endif [TestFixture(HostOrServer.Host, Authority.ServerAuthority, RotationCompression.None, Rotation.Euler, Precision.Full)] +#if !MULTIPLAYER_TOOLS [TestFixture(HostOrServer.Host, Authority.ServerAuthority, RotationCompression.None, Rotation.Euler, Precision.Half)] [TestFixture(HostOrServer.Host, Authority.ServerAuthority, RotationCompression.None, Rotation.Quaternion, Precision.Full)] [TestFixture(HostOrServer.Host, Authority.ServerAuthority, RotationCompression.None, Rotation.Quaternion, Precision.Half)] [TestFixture(HostOrServer.Host, Authority.ServerAuthority, RotationCompression.QuaternionCompress, Rotation.Quaternion, Precision.Full)] [TestFixture(HostOrServer.Host, Authority.ServerAuthority, RotationCompression.QuaternionCompress, Rotation.Quaternion, Precision.Half)] +#endif [TestFixture(HostOrServer.Host, Authority.OwnerAuthority, RotationCompression.None, Rotation.Euler, Precision.Full)] +#if !MULTIPLAYER_TOOLS [TestFixture(HostOrServer.Host, Authority.OwnerAuthority, RotationCompression.None, Rotation.Euler, Precision.Half)] [TestFixture(HostOrServer.Host, Authority.OwnerAuthority, RotationCompression.None, Rotation.Quaternion, Precision.Full)] [TestFixture(HostOrServer.Host, Authority.OwnerAuthority, RotationCompression.None, Rotation.Quaternion, Precision.Half)] [TestFixture(HostOrServer.Host, Authority.OwnerAuthority, RotationCompression.QuaternionCompress, Rotation.Quaternion, Precision.Full)] [TestFixture(HostOrServer.Host, Authority.OwnerAuthority, RotationCompression.QuaternionCompress, Rotation.Quaternion, Precision.Half)] +#endif public class NetworkTransformTests : NetworkTransformBase { protected const int k_TickRate = 60; /// /// Constructor /// - /// Determines if we are running as a server or host + /// Determines if we are running as a server or host /// Determines if we are using server or owner authority public NetworkTransformTests(HostOrServer testWithHost, Authority authority, RotationCompression rotationCompression, Rotation rotation, Precision precision) : base(testWithHost, authority, rotationCompression, rotation, precision) @@ -41,6 +54,24 @@ namespace Unity.Netcode.RuntimeTests return k_TickRate; } + private bool m_UseParentingThreshold; + private const float k_ParentingThreshold = 0.25f; + + protected override float GetDeltaVarianceThreshold() + { + if (m_UseParentingThreshold) + { + return k_ParentingThreshold; + } + return base.GetDeltaVarianceThreshold(); + } + + protected override IEnumerator OnSetup() + { + m_UseParentingThreshold = false; + return base.OnSetup(); + } + /// /// Handles validating the local space values match the original local space values. /// If not, it generates a message containing the axial values that did not match @@ -69,6 +100,7 @@ namespace Unity.Netcode.RuntimeTests } } +#if !MULTIPLAYER_TOOLS /// /// Validates that transform values remain the same when a NetworkTransform is /// parented under another NetworkTransform under all of the possible axial conditions @@ -77,6 +109,7 @@ namespace Unity.Netcode.RuntimeTests [Test] public void ParentedNetworkTransformTest([Values] Interpolation interpolation, [Values] bool worldPositionStays, [Values(0.5f, 1.0f, 5.0f)] float scale) { + m_UseParentingThreshold = true; // Get the NetworkManager that will have authority in order to spawn with the correct authority var isServerAuthority = m_Authority == Authority.ServerAuthority; var authorityNetworkManager = m_ServerNetworkManager; @@ -134,6 +167,10 @@ namespace Unity.Netcode.RuntimeTests Assert.True(success, "All transform values did not match prior to parenting!"); + success = WaitForConditionOrTimeOutWithTimeTravel(PositionRotationScaleMatches); + + Assert.True(success, "All transform values did not match prior to parenting!"); + // Parent the child under the parent with the current world position stays setting Assert.True(serverSideChild.TrySetParent(serverSideParent.transform, worldPositionStays), "[Server-Side Child] Failed to set child's parent!"); @@ -349,6 +386,7 @@ namespace Unity.Netcode.RuntimeTests } } } +#endif /// /// Tests changing all axial values one at a time. diff --git a/Tests/Runtime/NetworkVarBufferCopyTest.cs b/Tests/Runtime/NetworkVarBufferCopyTest.cs index 272e644..c7ee2af 100644 --- a/Tests/Runtime/NetworkVarBufferCopyTest.cs +++ b/Tests/Runtime/NetworkVarBufferCopyTest.cs @@ -6,6 +6,8 @@ using UnityEngine.TestTools; namespace Unity.Netcode.RuntimeTests { + [TestFixture(HostOrServer.DAHost)] + [TestFixture(HostOrServer.Host)] public class NetworkVarBufferCopyTest : NetcodeIntegrationTest { public class DummyNetVar : NetworkVariableBase @@ -67,15 +69,32 @@ namespace Unity.Netcode.RuntimeTests DeltaRead = true; } + + public DummyNetVar( + NetworkVariableReadPermission readPerm = DefaultReadPerm, + NetworkVariableWritePermission writePerm = DefaultWritePerm) : base(readPerm, writePerm) { } } public class DummyNetBehaviour : NetworkBehaviour { - public DummyNetVar NetVar = new DummyNetVar(); + public static bool DistributedAuthority; + public DummyNetVar NetVar; + + private void Awake() + { + if (DistributedAuthority) + { + NetVar = new DummyNetVar(writePerm: NetworkVariableWritePermission.Owner); + } + else + { + NetVar = new DummyNetVar(); + } + } public override void OnNetworkSpawn() { - if (!IsServer) + if ((NetworkManager.DistributedAuthorityMode && !IsOwner) || (!NetworkManager.DistributedAuthorityMode && !IsServer)) { ClientDummyNetBehaviourSpawned(this); } @@ -84,6 +103,8 @@ namespace Unity.Netcode.RuntimeTests } protected override int NumberOfClients => 1; + public NetworkVarBufferCopyTest(HostOrServer hostOrServer) : base(hostOrServer) { } + private static List s_ClientDummyNetBehavioursSpawned = new List(); public static void ClientDummyNetBehaviourSpawned(DummyNetBehaviour dummyNetBehaviour) { @@ -98,6 +119,7 @@ namespace Unity.Netcode.RuntimeTests protected override void OnCreatePlayerPrefab() { + DummyNetBehaviour.DistributedAuthority = m_DistributedAuthority; m_PlayerPrefab.AddComponent(); } @@ -127,27 +149,29 @@ namespace Unity.Netcode.RuntimeTests Assert.IsFalse(s_GlobalTimeoutHelper.TimedOut, "Timed out waiting for client side DummyNetBehaviour to register it was spawned!"); // Check that FieldWritten is written when dirty - serverComponent.NetVar.SetDirty(true); + var authorityComponent = m_DistributedAuthority ? clientComponent : serverComponent; + var nonAuthorityComponent = m_DistributedAuthority ? serverComponent : clientComponent; + authorityComponent.NetVar.SetDirty(true); yield return s_DefaultWaitForTick; - Assert.True(serverComponent.NetVar.FieldWritten); - + Assert.True(authorityComponent.NetVar.FieldWritten); // Check that DeltaWritten is written when dirty - serverComponent.NetVar.SetDirty(true); + authorityComponent.NetVar.SetDirty(true); yield return s_DefaultWaitForTick; - Assert.True(serverComponent.NetVar.DeltaWritten); + Assert.True(authorityComponent.NetVar.DeltaWritten); + // Check that both FieldRead and DeltaRead were invoked on the client side - yield return WaitForConditionOrTimeOut(() => clientComponent.NetVar.FieldRead == true && clientComponent.NetVar.DeltaRead == true); + yield return WaitForConditionOrTimeOut(() => nonAuthorityComponent.NetVar.FieldRead == true && nonAuthorityComponent.NetVar.DeltaRead == true); var timedOutMessage = "Timed out waiting for client reads: "; if (s_GlobalTimeoutHelper.TimedOut) { - if (!clientComponent.NetVar.FieldRead) + if (!nonAuthorityComponent.NetVar.FieldRead) { timedOutMessage += "[FieldRead]"; } - if (!clientComponent.NetVar.DeltaRead) + if (!nonAuthorityComponent.NetVar.DeltaRead) { timedOutMessage += "[DeltaRead]"; } diff --git a/Tests/Runtime/NetworkVariableTests.cs b/Tests/Runtime/NetworkVariableTests.cs index 8c17d1b..bc62563 100644 --- a/Tests/Runtime/NetworkVariableTests.cs +++ b/Tests/Runtime/NetworkVariableTests.cs @@ -1,3 +1,4 @@ +#if !NGO_MINIMALPROJECT using System; using System.Collections; using System.Collections.Generic; @@ -11,458 +12,28 @@ using Random = UnityEngine.Random; namespace Unity.Netcode.RuntimeTests { - public class NetVarPermTestComp : NetworkBehaviour - { - public NetworkVariable OwnerWritable_Position = new NetworkVariable(Vector3.one, NetworkVariableBase.DefaultReadPerm, NetworkVariableWritePermission.Owner); - public NetworkVariable ServerWritable_Position = new NetworkVariable(Vector3.one, NetworkVariableBase.DefaultReadPerm, NetworkVariableWritePermission.Server); - public NetworkVariable OwnerReadWrite_Position = new NetworkVariable(Vector3.one, NetworkVariableReadPermission.Owner, NetworkVariableWritePermission.Owner); - } - - public class NetworkVariableMiddleclass : NetworkVariable - { - - } - - public class NetworkVariableSubclass : NetworkVariableMiddleclass - { - - } - - public class NetworkBehaviourWithNetVarArray : NetworkBehaviour - { - public NetworkVariable Int0 = new NetworkVariable(); - public NetworkVariable Int1 = new NetworkVariable(); - public NetworkVariable Int2 = new NetworkVariable(); - public NetworkVariable Int3 = new NetworkVariable(); - public NetworkVariable Int4 = new NetworkVariable(); - public NetworkVariable[] AllInts = new NetworkVariable[5]; - - public int InitializedFieldCount => NetworkVariableFields.Count; - - - private void Awake() - { - AllInts[0] = Int0; - AllInts[1] = Int1; - AllInts[2] = Int2; - AllInts[3] = Int3; - AllInts[4] = Int4; - } - } - - internal struct TypeReferencedOnlyInCustomSerialization1 : INetworkSerializeByMemcpy - { - public int I; - } - - internal struct TypeReferencedOnlyInCustomSerialization2 : INetworkSerializeByMemcpy - { - public int I; - } - - internal struct TypeReferencedOnlyInCustomSerialization3 : INetworkSerializeByMemcpy - { - public int I; - } - - internal struct TypeReferencedOnlyInCustomSerialization4 : INetworkSerializeByMemcpy - { - public int I; - } - - internal struct TypeReferencedOnlyInCustomSerialization5 : INetworkSerializeByMemcpy - { - public int I; - } - - internal struct TypeReferencedOnlyInCustomSerialization6 : INetworkSerializeByMemcpy - { - public int I; - } - - // Both T and U are serializable - [GenerateSerializationForGenericParameter(0)] - [GenerateSerializationForGenericParameter(1)] - internal class CustomSerializableClass - { - - } - - // Only U is serializable - [GenerateSerializationForGenericParameter(1)] - internal class CustomSerializableBaseClass - { - - } - - // T is serializable, passes TypeReferencedOnlyInCustomSerialization3 as U to the subclass, making it serializable - [GenerateSerializationForGenericParameter(0)] - internal class CustomSerializableSubclass : CustomSerializableBaseClass - { - - } - - // T is serializable, passes TypeReferencedOnlyInCustomSerialization3 as U to the subclass, making it serializable - [GenerateSerializationForGenericParameter(0)] - internal class CustomSerializableSubclassWithNativeArray : CustomSerializableBaseClass> - { - - } - - internal class CustomGenericSerializationTestBehaviour : NetworkBehaviour - { - public CustomSerializableClass Value1; - public CustomSerializableClass, NativeArray> Value2; - public CustomSerializableSubclass Value3; - public CustomSerializableSubclassWithNativeArray> Value4; - } - - [GenerateSerializationForType(typeof(TypeReferencedOnlyInCustomSerialization5))] - [GenerateSerializationForType(typeof(NativeArray))] - internal struct SomeRandomStruct - { - [GenerateSerializationForType(typeof(TypeReferencedOnlyInCustomSerialization6))] - [GenerateSerializationForType(typeof(NativeArray))] - public void Foo() - { - - } - } - - public struct TemplatedValueOnlyReferencedByNetworkVariableSubclass : INetworkSerializeByMemcpy - where T : unmanaged - { - public T Value; - } - - public enum ByteEnum : byte - { - A, - B, - C = byte.MaxValue - } - public enum SByteEnum : sbyte - { - A, - B, - C = sbyte.MaxValue - } - public enum ShortEnum : short - { - A, - B, - C = short.MaxValue - } - public enum UShortEnum : ushort - { - A, - B, - C = ushort.MaxValue - } - public enum IntEnum : int - { - A, - B, - C = int.MaxValue - } - public enum UIntEnum : uint - { - A, - B, - C = uint.MaxValue - } - public enum LongEnum : long - { - A, - B, - C = long.MaxValue - } - public enum ULongEnum : ulong - { - A, - B, - C = ulong.MaxValue - } - - public struct NetworkVariableTestStruct : INetworkSerializeByMemcpy - { - public byte A; - public short B; - public ushort C; - public int D; - public uint E; - public long F; - public ulong G; - public bool H; - public char I; - public float J; - public double K; - - private static System.Random s_Random = new System.Random(); - - public static NetworkVariableTestStruct GetTestStruct() - { - var testStruct = new NetworkVariableTestStruct - { - A = (byte)s_Random.Next(), - B = (short)s_Random.Next(), - C = (ushort)s_Random.Next(), - D = s_Random.Next(), - E = (uint)s_Random.Next(), - F = ((long)s_Random.Next() << 32) + s_Random.Next(), - G = ((ulong)s_Random.Next() << 32) + (ulong)s_Random.Next(), - H = true, - I = '\u263a', - J = (float)s_Random.NextDouble(), - K = s_Random.NextDouble(), - }; - - return testStruct; - } - } - - // The ILPP code for NetworkVariables to determine how to serialize them relies on them existing as fields of a NetworkBehaviour to find them. - // Some of the tests below create NetworkVariables on the stack, so this class is here just to make sure the relevant types are all accounted for. - public class NetVarILPPClassForTests : NetworkBehaviour - { - public NetworkVariable ByteVar; - public NetworkVariable> ByteArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> ByteListVar; -#endif - public NetworkVariable SbyteVar; - public NetworkVariable> SbyteArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> SbyteListVar; -#endif - public NetworkVariable ShortVar; - public NetworkVariable> ShortArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> ShortListVar; -#endif - public NetworkVariable UshortVar; - public NetworkVariable> UshortArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> UshortListVar; -#endif - public NetworkVariable IntVar; - public NetworkVariable> IntArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> IntListVar; -#endif - public NetworkVariable UintVar; - public NetworkVariable> UintArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> UintListVar; -#endif - public NetworkVariable LongVar; - public NetworkVariable> LongArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> LongListVar; -#endif - public NetworkVariable UlongVar; - public NetworkVariable> UlongArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> UlongListVar; -#endif - public NetworkVariable BoolVar; - public NetworkVariable> BoolArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> BoolListVar; -#endif - public NetworkVariable CharVar; - public NetworkVariable> CharArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> CharListVar; -#endif - public NetworkVariable FloatVar; - public NetworkVariable> FloatArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> FloatListVar; -#endif - public NetworkVariable DoubleVar; - public NetworkVariable> DoubleArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> DoubleListVar; -#endif - public NetworkVariable ByteEnumVar; - public NetworkVariable> ByteEnumArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> ByteEnumListVar; -#endif - public NetworkVariable SByteEnumVar; - public NetworkVariable> SByteEnumArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> SByteEnumListVar; -#endif - public NetworkVariable ShortEnumVar; - public NetworkVariable> ShortEnumArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> ShortEnumListVar; -#endif - public NetworkVariable UShortEnumVar; - public NetworkVariable> UShortEnumArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> UShortEnumListVar; -#endif - public NetworkVariable IntEnumVar; - public NetworkVariable> IntEnumArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> IntEnumListVar; -#endif - public NetworkVariable UIntEnumVar; - public NetworkVariable> UIntEnumArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> UIntEnumListVar; -#endif - public NetworkVariable LongEnumVar; - public NetworkVariable> LongEnumArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> LongEnumListVar; -#endif - public NetworkVariable ULongEnumVar; - public NetworkVariable> ULongEnumArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> ULongEnumListVar; -#endif - public NetworkVariable Vector2Var; - public NetworkVariable> Vector2ArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> Vector2ListVar; -#endif - public NetworkVariable Vector3Var; - public NetworkVariable> Vector3ArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> Vector3ListVar; -#endif - public NetworkVariable Vector2IntVar; - public NetworkVariable> Vector2IntArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> Vector2IntListVar; -#endif - public NetworkVariable Vector3IntVar; - public NetworkVariable> Vector3IntArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> Vector3IntListVar; -#endif - public NetworkVariable Vector4Var; - public NetworkVariable> Vector4ArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> Vector4ListVar; -#endif - public NetworkVariable QuaternionVar; - public NetworkVariable> QuaternionArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> QuaternionListVar; -#endif - public NetworkVariable ColorVar; - public NetworkVariable> ColorArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> ColorListVar; -#endif - public NetworkVariable Color32Var; - public NetworkVariable> Color32ArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> Color32ListVar; -#endif - public NetworkVariable RayVar; - public NetworkVariable> RayArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> RayListVar; -#endif - public NetworkVariable Ray2DVar; - public NetworkVariable> Ray2DArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> Ray2DListVar; -#endif - public NetworkVariable TestStructVar; - public NetworkVariable> TestStructArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> TestStructListVar; -#endif - - public NetworkVariable FixedStringVar; - public NetworkVariable> FixedStringArrayVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> FixedStringListVar; -#endif - - public NetworkVariable UnmanagedNetworkSerializableTypeVar; -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - public NetworkVariable> UnmanagedNetworkSerializableListVar; -#endif - public NetworkVariable> UnmanagedNetworkSerializableArrayVar; - - public NetworkVariable ManagedNetworkSerializableTypeVar; - - public NetworkVariable StringVar; - public NetworkVariable GuidVar; - public NetworkVariableSubclass> SubclassVar; - } - - public class TemplateNetworkBehaviourType : NetworkBehaviour - { - public NetworkVariable TheVar; - } - - public class IntermediateNetworkBehavior : TemplateNetworkBehaviourType - { - public NetworkVariable TheVar2; - } - - public class ClassHavingNetworkBehaviour : IntermediateNetworkBehavior - { - - } - - // Please do not reference TestClass_ReferencedOnlyByTemplateNetworkBehavourType anywhere other than here! - public class ClassHavingNetworkBehaviour2 : TemplateNetworkBehaviourType - { - - } - - public class StructHavingNetworkBehaviour : TemplateNetworkBehaviourType - { - - } - - public struct StructUsedOnlyInNetworkList : IEquatable, INetworkSerializeByMemcpy - { - public int Value; - - public bool Equals(StructUsedOnlyInNetworkList other) - { - return Value == other.Value; - } - - public override bool Equals(object obj) - { - return obj is StructUsedOnlyInNetworkList other && Equals(other); - } - - public override int GetHashCode() - { - return Value; - } - } - [TestFixtureSource(nameof(TestDataSource))] public class NetworkVariablePermissionTests : NetcodeIntegrationTest { public static IEnumerable TestDataSource() { + NetworkVariableBase.IgnoreInitializeWarning = true; foreach (HostOrServer hostOrServer in Enum.GetValues(typeof(HostOrServer))) { + // DANGO-EXP TODO: Add support for distributed authority mode + if (hostOrServer == HostOrServer.DAHost) + { + continue; + } yield return new TestFixtureData(hostOrServer); } + + NetworkVariableBase.IgnoreInitializeWarning = false; } protected override int NumberOfClients => 3; - public NetworkVariablePermissionTests(HostOrServer hostOrServer) - : base(hostOrServer) - { - } + public NetworkVariablePermissionTests(HostOrServer hostOrServer) : base(hostOrServer) { } private GameObject m_TestObjPrefab; private ulong m_TestObjId = 0; @@ -864,7 +435,10 @@ namespace Unity.Netcode.RuntimeTests } } + +#if !MULTIPLAYER_TOOLS [TestFixture(true)] +#endif [TestFixture(false)] public class NetworkVariableTests : NetcodeIntegrationTest { @@ -908,6 +482,18 @@ namespace Unity.Netcode.RuntimeTests return false; } + protected override void OnOneTimeSetup() + { + NetworkVariableBase.IgnoreInitializeWarning = true; + base.OnOneTimeSetup(); + } + + protected override void OnOneTimeTearDown() + { + NetworkVariableBase.IgnoreInitializeWarning = false; + base.OnOneTimeTearDown(); + } + /// /// This is an adjustment to how the server and clients are started in order /// to avoid timing issues when running in a stand alone test runner build. @@ -975,6 +561,7 @@ namespace Unity.Netcode.RuntimeTests TimeTravelToNextTick(); } +#if !MULTIPLAYER_TOOLS /// /// Runs generalized tests on all predefined NetworkVariable types /// @@ -1393,6 +980,7 @@ namespace Unity.Netcode.RuntimeTests // Wait for the client-side to notify it is finished initializing and spawning. Assert.True(WaitForConditionOrTimeOutWithTimeTravel(VerifyCallback)); } +#endif [Test] public void TestINetworkSerializableStructCallsNetworkSerialize([Values] HostOrServer useHost) @@ -1632,38 +1220,61 @@ namespace Unity.Netcode.RuntimeTests Assert.IsTrue(NetworkVariableSerialization.AreEqual(ref serverVariable.RefValue(), ref clientVariable.RefValue())); } + public void AssertArraysMatch(ref NativeArray a, ref NativeArray b) where T : unmanaged + { + Assert.IsTrue(NetworkVariableSerialization>.AreEqual(ref a, ref b), + $"Lists do not match: {ArrayStr(a)} != {ArrayStr(b)}"); + } + public void AssertArraysDoNotMatch(ref NativeArray a, ref NativeArray b) where T : unmanaged + { + Assert.IsFalse(NetworkVariableSerialization>.AreEqual(ref a, ref b), + $"Lists match when they should not: {ArrayStr(a)} == {ArrayStr(b)}"); + } + private void TestValueTypeNativeArray(NativeArray testValue, NativeArray changedValue) where T : unmanaged { + VerboseDebug($"Changing {ArrayStr(testValue)} to {ArrayStr(changedValue)}"); var serverVariable = new NetworkVariable>(testValue); var clientVariable = new NetworkVariable>(new NativeArray(1, Allocator.Persistent)); - using var writer = new FastBufferWriter(1024, Allocator.Temp); + using var writer = new FastBufferWriter(1024, Allocator.Temp, int.MaxValue); serverVariable.WriteField(writer); - Assert.IsFalse(NetworkVariableSerialization>.AreEqual(ref serverVariable.RefValue(), ref clientVariable.RefValue())); + AssertArraysDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); using var reader = new FastBufferReader(writer, Allocator.None); clientVariable.ReadField(reader); - Assert.IsTrue(NetworkVariableSerialization>.AreEqual(ref serverVariable.RefValue(), ref clientVariable.RefValue())); + AssertArraysMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); - serverVariable.Dispose(); + serverVariable.ResetDirty(); + serverVariable.Value.Dispose(); serverVariable.Value = changedValue; - Assert.IsFalse(NetworkVariableSerialization>.AreEqual(ref serverVariable.RefValue(), ref clientVariable.RefValue())); + AssertArraysDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); writer.Seek(0); serverVariable.WriteDelta(writer); - Assert.IsFalse(NetworkVariableSerialization>.AreEqual(ref serverVariable.RefValue(), ref clientVariable.RefValue())); + AssertArraysDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); using var reader2 = new FastBufferReader(writer, Allocator.None); clientVariable.ReadDelta(reader2, false); - Assert.IsTrue(NetworkVariableSerialization>.AreEqual(ref serverVariable.RefValue(), ref clientVariable.RefValue())); + AssertArraysMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); serverVariable.ResetDirty(); Assert.IsFalse(serverVariable.IsDirty()); var cachedValue = changedValue[0]; - changedValue[0] = testValue[0]; + var differentValue = changedValue[0]; + foreach (var checkValue in testValue) + { + var checkValueRef = checkValue; + if (!NetworkVariableSerialization.AreEqual(ref checkValueRef, ref differentValue)) + { + differentValue = checkValue; + break; + } + } + changedValue[0] = differentValue; Assert.IsTrue(serverVariable.IsDirty()); serverVariable.ResetDirty(); Assert.IsFalse(serverVariable.IsDirty()); @@ -1675,45 +1286,57 @@ namespace Unity.Netcode.RuntimeTests clientVariable.Dispose(); } -#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT - private void TestValueTypeNativeList(NativeList testValue, NativeList changedValue) where T : unmanaged + public void AssertListsMatch(ref List a, ref List b) { - var serverVariable = new NetworkVariable>(testValue); - var inPlaceList = new NativeList(1, Allocator.Temp); - var clientVariable = new NetworkVariable>(inPlaceList); - using var writer = new FastBufferWriter(1024, Allocator.Temp); + Assert.IsTrue(NetworkVariableSerialization>.AreEqual(ref a, ref b), + $"Lists do not match: {ListStr(a)} != {ListStr(b)}"); + } + public void AssertListsDoNotMatch(ref List a, ref List b) + { + Assert.IsFalse(NetworkVariableSerialization>.AreEqual(ref a, ref b), + $"Lists match when they should not: {ListStr(a)} == {ListStr(b)}"); + } + + + private void TestList(List testValue, List changedValue) + { + VerboseDebug($"Changing {ListStr(testValue)} to {ListStr(changedValue)}"); + var serverVariable = new NetworkVariable>(testValue); + var inPlaceList = new List(); + var clientVariable = new NetworkVariable>(inPlaceList); + using var writer = new FastBufferWriter(1024, Allocator.Temp, int.MaxValue); serverVariable.WriteField(writer); - Assert.IsFalse(NetworkVariableSerialization>.AreEqual(ref serverVariable.RefValue(), ref clientVariable.RefValue())); + AssertListsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! - Assert.IsTrue(NetworkVariableSerialization>.AreEqual(ref clientVariable.RefValue(), ref inPlaceList)); + AssertListsMatch(ref clientVariable.RefValue(), ref inPlaceList); using var reader = new FastBufferReader(writer, Allocator.None); clientVariable.ReadField(reader); - Assert.IsTrue(NetworkVariableSerialization>.AreEqual(ref serverVariable.RefValue(), ref clientVariable.RefValue())); + AssertListsMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! - Assert.IsTrue(NetworkVariableSerialization>.AreEqual(ref clientVariable.RefValue(), ref inPlaceList)); + AssertListsMatch(ref clientVariable.RefValue(), ref inPlaceList); - serverVariable.Dispose(); + serverVariable.ResetDirty(); serverVariable.Value = changedValue; - Assert.IsFalse(NetworkVariableSerialization>.AreEqual(ref serverVariable.RefValue(), ref clientVariable.RefValue())); + AssertListsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! - Assert.IsTrue(NetworkVariableSerialization>.AreEqual(ref clientVariable.RefValue(), ref inPlaceList)); + AssertListsMatch(ref clientVariable.RefValue(), ref inPlaceList); writer.Seek(0); serverVariable.WriteDelta(writer); - Assert.IsFalse(NetworkVariableSerialization>.AreEqual(ref serverVariable.RefValue(), ref clientVariable.RefValue())); + AssertListsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! - Assert.IsTrue(NetworkVariableSerialization>.AreEqual(ref clientVariable.RefValue(), ref inPlaceList)); + AssertListsMatch(ref clientVariable.RefValue(), ref inPlaceList); using var reader2 = new FastBufferReader(writer, Allocator.None); clientVariable.ReadDelta(reader2, false); - Assert.IsTrue(NetworkVariableSerialization>.AreEqual(ref serverVariable.RefValue(), ref clientVariable.RefValue())); + AssertListsMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! - Assert.IsTrue(NetworkVariableSerialization>.AreEqual(ref clientVariable.RefValue(), ref inPlaceList)); + AssertListsMatch(ref clientVariable.RefValue(), ref inPlaceList); serverVariable.ResetDirty(); Assert.IsFalse(serverVariable.IsDirty()); @@ -1725,6 +1348,353 @@ namespace Unity.Netcode.RuntimeTests Assert.IsFalse(serverVariable.IsDirty()); serverVariable.Value.Add(default); Assert.IsTrue(serverVariable.IsDirty()); + } + + + public void AssertSetsMatch(ref HashSet a, ref HashSet b) where T : IEquatable + { + Assert.IsTrue(NetworkVariableSerialization>.AreEqual(ref a, ref b), + $"Sets do not match: {HashSetStr(a)} != {HashSetStr(b)}"); + } + public void AssertSetsDoNotMatch(ref HashSet a, ref HashSet b) where T : IEquatable + { + Assert.IsFalse(NetworkVariableSerialization>.AreEqual(ref a, ref b), + $"Sets match when they should not: {HashSetStr(a)} == {HashSetStr(b)}"); + } + + private void TestHashSet(HashSet testValue, HashSet changedValue) where T : IEquatable + { + VerboseDebug($"Changing {HashSetStr(testValue)} to {HashSetStr(changedValue)}"); + var serverVariable = new NetworkVariable>(testValue); + var inPlaceList = new HashSet(); + var clientVariable = new NetworkVariable>(inPlaceList); + using var writer = new FastBufferWriter(1024, Allocator.Temp, int.MaxValue); + serverVariable.WriteField(writer); + + AssertSetsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertSetsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + using var reader = new FastBufferReader(writer, Allocator.None); + clientVariable.ReadField(reader); + + AssertSetsMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertSetsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + serverVariable.ResetDirty(); + serverVariable.Value = changedValue; + AssertSetsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertSetsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + writer.Seek(0); + + serverVariable.WriteDelta(writer); + + AssertSetsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertSetsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + using var reader2 = new FastBufferReader(writer, Allocator.None); + clientVariable.ReadDelta(reader2, false); + AssertSetsMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertSetsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + serverVariable.ResetDirty(); + Assert.IsFalse(serverVariable.IsDirty()); + serverVariable.Value.Clear(); + Assert.IsTrue(serverVariable.IsDirty()); + + serverVariable.ResetDirty(); + + Assert.IsFalse(serverVariable.IsDirty()); + serverVariable.Value.Add(default); + Assert.IsTrue(serverVariable.IsDirty()); + } + + + public void AssertMapsMatch(ref Dictionary a, ref Dictionary b) + where TKey : IEquatable + { + Assert.IsTrue(NetworkVariableSerialization>.AreEqual(ref a, ref b), + $"Maps do not match: {DictionaryStr(a)} != {DictionaryStr(b)}"); + } + + public void AssertMapsDoNotMatch(ref Dictionary a, ref Dictionary b) + where TKey : IEquatable + { + Assert.IsFalse(NetworkVariableSerialization>.AreEqual(ref a, ref b), + $"Maps match when they should not: {DictionaryStr(a)} != {DictionaryStr(b)}"); + } + + private void TestDictionary(Dictionary testValue, Dictionary changedValue) + where TKey : IEquatable + { + VerboseDebug($"Changing {DictionaryStr(testValue)} to {DictionaryStr(changedValue)}"); + var serverVariable = new NetworkVariable>(testValue); + var inPlaceList = new Dictionary(); + var clientVariable = new NetworkVariable>(inPlaceList); + using var writer = new FastBufferWriter(1024, Allocator.Temp, int.MaxValue); + serverVariable.WriteField(writer); + + AssertMapsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertMapsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + using var reader = new FastBufferReader(writer, Allocator.None); + clientVariable.ReadField(reader); + + AssertMapsMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertMapsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + serverVariable.ResetDirty(); + serverVariable.Value = changedValue; + AssertMapsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertMapsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + writer.Seek(0); + + serverVariable.WriteDelta(writer); + + AssertMapsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertMapsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + using var reader2 = new FastBufferReader(writer, Allocator.None); + clientVariable.ReadDelta(reader2, false); + AssertMapsMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertMapsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + serverVariable.ResetDirty(); + Assert.IsFalse(serverVariable.IsDirty()); + serverVariable.Value.Clear(); + Assert.IsTrue(serverVariable.IsDirty()); + + serverVariable.ResetDirty(); + + Assert.IsFalse(serverVariable.IsDirty()); + foreach (var kvp in testValue) + { + if (!serverVariable.Value.ContainsKey(kvp.Key)) + { + serverVariable.Value.Add(kvp.Key, kvp.Value); + } + } + Assert.IsTrue(serverVariable.IsDirty()); + } + +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public void AssertListsMatch(ref NativeList a, ref NativeList b) where T : unmanaged + { + Assert.IsTrue(NetworkVariableSerialization>.AreEqual(ref a, ref b), + $"Lists do not match: {NativeListStr(a)} != {NativeListStr(b)}"); + } + public void AssertListsDoNotMatch(ref NativeList a, ref NativeList b) where T : unmanaged + { + Assert.IsFalse(NetworkVariableSerialization>.AreEqual(ref a, ref b), + $"Lists match when they should not: {NativeListStr(a)} == {NativeListStr(b)}"); + } + + + private void TestValueTypeNativeList(NativeList testValue, NativeList changedValue) where T : unmanaged + { + VerboseDebug($"Changing {NativeListStr(testValue)} to {NativeListStr(changedValue)}"); + var serverVariable = new NetworkVariable>(testValue); + var inPlaceList = new NativeList(1, Allocator.Temp); + var clientVariable = new NetworkVariable>(inPlaceList); + using var writer = new FastBufferWriter(1024, Allocator.Temp, int.MaxValue); + serverVariable.WriteField(writer); + + AssertListsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertListsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + using var reader = new FastBufferReader(writer, Allocator.None); + clientVariable.ReadField(reader); + + AssertListsMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertListsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + serverVariable.ResetDirty(); + serverVariable.Value.Dispose(); + serverVariable.Value = changedValue; + AssertListsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertListsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + writer.Seek(0); + + serverVariable.WriteDelta(writer); + + AssertListsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertListsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + using var reader2 = new FastBufferReader(writer, Allocator.None); + clientVariable.ReadDelta(reader2, false); + AssertListsMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertListsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + serverVariable.ResetDirty(); + Assert.IsFalse(serverVariable.IsDirty()); + serverVariable.Value.Clear(); + Assert.IsTrue(serverVariable.IsDirty()); + + serverVariable.ResetDirty(); + + Assert.IsFalse(serverVariable.IsDirty()); + serverVariable.Value.Add(default); + Assert.IsTrue(serverVariable.IsDirty()); + + serverVariable.Dispose(); + clientVariable.Dispose(); + } + + + public void AssertSetsMatch(ref NativeHashSet a, ref NativeHashSet b) where T : unmanaged, IEquatable + { + Assert.IsTrue(NetworkVariableSerialization>.AreEqual(ref a, ref b), + $"Sets do not match: {NativeHashSetStr(a)} != {NativeHashSetStr(b)}"); + } + public void AssertSetsDoNotMatch(ref NativeHashSet a, ref NativeHashSet b) where T : unmanaged, IEquatable + { + Assert.IsFalse(NetworkVariableSerialization>.AreEqual(ref a, ref b), + $"Sets match when they should not: {NativeHashSetStr(a)} == {NativeHashSetStr(b)}"); + } + + private void TestValueTypeNativeHashSet(NativeHashSet testValue, NativeHashSet changedValue) where T : unmanaged, IEquatable + { + VerboseDebug($"Changing {NativeHashSetStr(testValue)} to {NativeHashSetStr(changedValue)}"); + var serverVariable = new NetworkVariable>(testValue); + var inPlaceList = new NativeHashSet(1, Allocator.Temp); + var clientVariable = new NetworkVariable>(inPlaceList); + using var writer = new FastBufferWriter(1024, Allocator.Temp, int.MaxValue); + serverVariable.WriteField(writer); + + AssertSetsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertSetsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + using var reader = new FastBufferReader(writer, Allocator.None); + clientVariable.ReadField(reader); + + AssertSetsMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertSetsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + serverVariable.ResetDirty(); + serverVariable.Value.Dispose(); + serverVariable.Value = changedValue; + AssertSetsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertSetsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + writer.Seek(0); + + serverVariable.WriteDelta(writer); + + AssertSetsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertSetsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + using var reader2 = new FastBufferReader(writer, Allocator.None); + clientVariable.ReadDelta(reader2, false); + AssertSetsMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertSetsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + serverVariable.ResetDirty(); + Assert.IsFalse(serverVariable.IsDirty()); + serverVariable.Value.Clear(); + Assert.IsTrue(serverVariable.IsDirty()); + + serverVariable.ResetDirty(); + + Assert.IsFalse(serverVariable.IsDirty()); + serverVariable.Value.Add(default); + Assert.IsTrue(serverVariable.IsDirty()); + + serverVariable.Dispose(); + clientVariable.Dispose(); + } + + + public void AssertMapsMatch(ref NativeHashMap a, ref NativeHashMap b) + where TKey : unmanaged, IEquatable + where TVal : unmanaged + { + Assert.IsTrue(NetworkVariableSerialization>.AreEqual(ref a, ref b), + $"Maps do not match: {NativeHashMapStr(a)} != {NativeHashMapStr(b)}"); + } + + public void AssertMapsDoNotMatch(ref NativeHashMap a, ref NativeHashMap b) + where TKey : unmanaged, IEquatable + where TVal : unmanaged + { + Assert.IsFalse(NetworkVariableSerialization>.AreEqual(ref a, ref b), + $"Maps match when they should not: {NativeHashMapStr(a)} != {NativeHashMapStr(b)}"); + } + + private void TestValueTypeNativeHashMap(NativeHashMap testValue, NativeHashMap changedValue) + where TKey : unmanaged, IEquatable + where TVal : unmanaged + { + VerboseDebug($"Changing {NativeHashMapStr(testValue)} to {NativeHashMapStr(changedValue)}"); + var serverVariable = new NetworkVariable>(testValue); + var inPlaceList = new NativeHashMap(1, Allocator.Temp); + var clientVariable = new NetworkVariable>(inPlaceList); + using var writer = new FastBufferWriter(1024, Allocator.Temp, int.MaxValue); + serverVariable.WriteField(writer); + + AssertMapsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertMapsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + using var reader = new FastBufferReader(writer, Allocator.None); + clientVariable.ReadField(reader); + + AssertMapsMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertMapsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + serverVariable.ResetDirty(); + serverVariable.Value.Dispose(); + serverVariable.Value = changedValue; + AssertMapsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertMapsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + writer.Seek(0); + + serverVariable.WriteDelta(writer); + + AssertMapsDoNotMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertMapsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + using var reader2 = new FastBufferReader(writer, Allocator.None); + clientVariable.ReadDelta(reader2, false); + AssertMapsMatch(ref serverVariable.RefValue(), ref clientVariable.RefValue()); + // Lists are deserialized in place so this should ALWAYS be true. Checking it every time to make sure! + AssertMapsMatch(ref clientVariable.RefValue(), ref inPlaceList); + + serverVariable.ResetDirty(); + Assert.IsFalse(serverVariable.IsDirty()); + serverVariable.Value.Clear(); + Assert.IsTrue(serverVariable.IsDirty()); + + serverVariable.ResetDirty(); + + Assert.IsFalse(serverVariable.IsDirty()); + serverVariable.Value.Add(default, default); + Assert.IsTrue(serverVariable.IsDirty()); serverVariable.Dispose(); clientVariable.Dispose(); @@ -2132,6 +2102,1488 @@ namespace Unity.Netcode.RuntimeTests } } + public delegate T GetRandomElement(System.Random rand); + + public unsafe T RandGenBytes(System.Random rand) where T : unmanaged + { + var t = new T(); + T* tPtr = &t; + var s = new Span(tPtr, sizeof(T)); + rand.NextBytes(s); + return t; + } + + public FixedString32Bytes RandGenFixedString32(System.Random rand) + { + var s = new FixedString32Bytes(); + var len = rand.Next(s.Capacity); + s.Length = len; + for (var i = 0; i < len; ++i) + { + // Ascii visible character range + s[i] = (byte)rand.Next(32, 126); + } + + return s; + } + public string ArrayStr(NativeArray arr) where T : unmanaged + { + var str = "["; + var comma = false; + foreach (var item in arr) + { + if (comma) + { + str += ", "; + } + + comma = true; + str += $"{item}"; + } + + str += "]"; + return str; + } + + public (NativeArray original, NativeArray original2, NativeArray changed, NativeArray changed2) GetArarys(GetRandomElement generator) where T : unmanaged + { + + var rand = new System.Random(); + var originalSize = rand.Next(32, 64); + var changedSize = rand.Next(32, 64); + var changed2Changes = rand.Next(12, 16); + var changed2Adds = rand.Next(-16, 16); + + var original = new NativeArray(originalSize, Allocator.Temp); + var changed = new NativeArray(changedSize, Allocator.Temp); + var original2 = new NativeArray(originalSize, Allocator.Temp); + var changed2 = new NativeArray(originalSize + changed2Adds, Allocator.Temp); + + + for (var i = 0; i < originalSize; ++i) + { + var item = generator(rand); + original[i] = item; + original2[i] = item; + if (i < changed2.Length) + { + changed2[i] = item; + } + } + for (var i = 0; i < changedSize; ++i) + { + var item = generator(rand); + changed[i] = item; + } + + for (var i = 0; i < changed2Changes; ++i) + { + var idx = rand.Next(changed2.Length - 1); + var item = generator(rand); + changed2[idx] = item; + } + + for (var i = 0; i < changed2Adds; ++i) + { + var item = generator(rand); + changed2[originalSize + i] = item; + } + + VerboseDebug($"Original: {ArrayStr(original)}"); + VerboseDebug($"Changed: {ArrayStr(changed)}"); + VerboseDebug($"Original2: {ArrayStr(original2)}"); + VerboseDebug($"Changed2: {ArrayStr(changed2)}"); + return (original, original2, changed, changed2); + } + + [Test] + [Repeat(5)] + public void WhenSerializingAndDeserializingVeryLargeValueTypeNativeArrayNetworkVariables_ValuesAreSerializedCorrectly( + + [Values(typeof(byte), typeof(sbyte), typeof(short), typeof(ushort), typeof(int), typeof(uint), + typeof(long), typeof(ulong), typeof(bool), typeof(char), typeof(float), typeof(double), + typeof(Vector2), typeof(Vector3), typeof(Vector2Int), typeof(Vector3Int), typeof(Vector4), + typeof(Quaternion), typeof(Color), typeof(Color32), typeof(Ray), typeof(Ray2D), + typeof(NetworkVariableTestStruct), typeof(FixedString32Bytes))] + Type testType) + { + if (testType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetArarys(RandGenBytes); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(sbyte)) + { + (var original, var original2, var changed, var changed2) = GetArarys(RandGenBytes); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(short)) + { + (var original, var original2, var changed, var changed2) = GetArarys(RandGenBytes); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(ushort)) + { + (var original, var original2, var changed, var changed2) = GetArarys(RandGenBytes); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(int)) + { + (var original, var original2, var changed, var changed2) = GetArarys(RandGenBytes); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(uint)) + { + (var original, var original2, var changed, var changed2) = GetArarys(RandGenBytes); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(long)) + { + (var original, var original2, var changed, var changed2) = GetArarys(RandGenBytes); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetArarys(RandGenBytes); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(bool)) + { + (var original, var original2, var changed, var changed2) = GetArarys(RandGenBytes); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(char)) + { + (var original, var original2, var changed, var changed2) = GetArarys(RandGenBytes); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(float)) + { + (var original, var original2, var changed, var changed2) = GetArarys(RandGenBytes); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(double)) + { + (var original, var original2, var changed, var changed2) = GetArarys(RandGenBytes); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetArarys( + (rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(Vector3)) + { + (var original, var original2, var changed, var changed2) = GetArarys( + (rand) => new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(Vector2Int)) + { + (var original, var original2, var changed, var changed2) = GetArarys( + (rand) => new Vector2Int(rand.Next(), rand.Next()) + ); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(Vector3Int)) + { + (var original, var original2, var changed, var changed2) = GetArarys( + (rand) => new Vector3Int(rand.Next(), rand.Next(), rand.Next()) + ); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(Vector4)) + { + (var original, var original2, var changed, var changed2) = GetArarys( + (rand) => new Vector4((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(Quaternion)) + { + (var original, var original2, var changed, var changed2) = GetArarys( + (rand) => new Quaternion((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(Color)) + { + (var original, var original2, var changed, var changed2) = GetArarys( + (rand) => new Color((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(Color32)) + { + (var original, var original2, var changed, var changed2) = GetArarys( + (rand) => new Color32((byte)rand.Next(), (byte)rand.Next(), (byte)rand.Next(), (byte)rand.Next()) + ); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(Ray)) + { + (var original, var original2, var changed, var changed2) = GetArarys( + (rand) => new Ray( + new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()), + new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ) + ); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(Ray2D)) + { + (var original, var original2, var changed, var changed2) = GetArarys( + (rand) => new Ray2D( + new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), + new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()) + ) + ); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(NetworkVariableTestStruct)) + { + (var original, var original2, var changed, var changed2) = GetArarys(RandGenBytes); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + else if (testType == typeof(FixedString32Bytes)) + { + (var original, var original2, var changed, var changed2) = GetArarys(RandGenFixedString32); + TestValueTypeNativeArray(original, changed); + TestValueTypeNativeArray(original2, changed2); + } + } + + + public string ListStr(List list) + { + var str = "["; + var comma = false; + foreach (var item in list) + { + if (comma) + { + str += ", "; + } + + comma = true; + str += $"{item}"; + } + + str += "]"; + return str; + } + + public string HashSetStr(HashSet list) where T : IEquatable + { + var str = "{"; + var comma = false; + foreach (var item in list) + { + if (comma) + { + str += ", "; + } + + comma = true; + str += $"{item}"; + } + + str += "}"; + return str; + } + + public string DictionaryStr(Dictionary list) + where TKey : IEquatable + { + var str = "{"; + var comma = false; + foreach (var item in list) + { + if (comma) + { + str += ", "; + } + + comma = true; + str += $"{item.Key}: {item.Value}"; + } + + str += "}"; + return str; + } + + public (List original, List original2, List changed, List changed2) GetLists(GetRandomElement generator) + { + var original = new List(); + var changed = new List(); + var original2 = new List(); + var changed2 = new List(); + + var rand = new System.Random(); + var originalSize = rand.Next(32, 64); + var changedSize = rand.Next(32, 64); + var changed2Changes = rand.Next(12, 16); + var changed2Adds = rand.Next(-16, 16); + for (var i = 0; i < originalSize; ++i) + { + var item = generator(rand); + original.Add(item); + original2.Add(item); + changed2.Add(item); + } + for (var i = 0; i < changedSize; ++i) + { + var item = generator(rand); + changed.Add(item); + } + + for (var i = 0; i < changed2Changes; ++i) + { + var idx = rand.Next(changed2.Count - 1); + var item = generator(rand); + changed2[idx] = item; + } + + if (changed2Adds < 0) + { + changed2.RemoveRange(changed2.Count + changed2Adds, -changed2Adds); + } + else + { + for (var i = 0; i < changed2Adds; ++i) + { + var item = generator(rand); + changed2.Add(item); + } + + } + + VerboseDebug($"Original: {ListStr(original)}"); + VerboseDebug($"Changed: {ListStr(changed)}"); + VerboseDebug($"Original2: {ListStr(original2)}"); + VerboseDebug($"Changed2: {ListStr(changed2)}"); + return (original, original2, changed, changed2); + } + + public (HashSet original, HashSet original2, HashSet changed, HashSet changed2) GetHashSets(GetRandomElement generator) where T : IEquatable + { + var original = new HashSet(); + var changed = new HashSet(); + var original2 = new HashSet(); + var changed2 = new HashSet(); + + var rand = new System.Random(); + var originalSize = rand.Next(32, 64); + var changedSize = rand.Next(32, 64); + var changed2Removes = rand.Next(12, 16); + var changed2Adds = rand.Next(12, 16); + for (var i = 0; i < originalSize; ++i) + { + var item = generator(rand); + while (original.Contains(item)) + { + item = generator(rand); + } + original.Add(item); + original2.Add(item); + changed2.Add(item); + } + for (var i = 0; i < changedSize; ++i) + { + var item = generator(rand); + while (changed.Contains(item)) + { + item = generator(rand); + } + changed.Add(item); + } + + for (var i = 0; i < changed2Removes; ++i) + { + var which = rand.Next(changed2.Count()); + T toRemove = default; + foreach (var check in changed2) + { + if (which == 0) + { + toRemove = check; + break; + } + --which; + } + + changed2.Remove(toRemove); + } + + for (var i = 0; i < changed2Adds; ++i) + { + var item = generator(rand); + while (changed2.Contains(item)) + { + item = generator(rand); + } + changed2.Add(item); + } + + VerboseDebug($"Original: {HashSetStr(original)}"); + VerboseDebug($"Changed: {HashSetStr(changed)}"); + VerboseDebug($"Original2: {HashSetStr(original2)}"); + VerboseDebug($"Changed2: {HashSetStr(changed2)}"); + return (original, original2, changed, changed2); + } + + + public (Dictionary original, Dictionary original2, Dictionary changed, Dictionary changed2) GetDictionaries(GetRandomElement keyGenerator, GetRandomElement valGenerator) + where TKey : IEquatable + { + var original = new Dictionary(); + var changed = new Dictionary(); + var original2 = new Dictionary(); + var changed2 = new Dictionary(); + + var rand = new System.Random(); + var originalSize = rand.Next(32, 64); + var changedSize = rand.Next(32, 64); + var changed2Removes = rand.Next(12, 16); + var changed2Adds = rand.Next(12, 16); + var changed2Changes = rand.Next(12, 16); + for (var i = 0; i < originalSize; ++i) + { + var key = keyGenerator(rand); + while (original.ContainsKey(key)) + { + key = keyGenerator(rand); + } + var val = valGenerator(rand); + original.Add(key, val); + original2.Add(key, val); + changed2.Add(key, val); + } + for (var i = 0; i < changedSize; ++i) + { + var key = keyGenerator(rand); + while (changed.ContainsKey(key)) + { + key = keyGenerator(rand); + } + var val = valGenerator(rand); + changed.Add(key, val); + } + + for (var i = 0; i < changed2Removes; ++i) + { + var which = rand.Next(changed2.Count()); + TKey toRemove = default; + foreach (var check in changed2) + { + if (which == 0) + { + toRemove = check.Key; + break; + } + --which; + } + + changed2.Remove(toRemove); + } + + for (var i = 0; i < changed2Changes; ++i) + { + var which = rand.Next(changed2.Count()); + TKey key = default; + foreach (var check in changed2) + { + if (which == 0) + { + key = check.Key; + break; + } + --which; + } + + var val = valGenerator(rand); + changed2[key] = val; + } + + for (var i = 0; i < changed2Adds; ++i) + { + var key = keyGenerator(rand); + while (changed2.ContainsKey(key)) + { + key = keyGenerator(rand); + } + var val = valGenerator(rand); + changed2.Add(key, val); + } + + VerboseDebug($"Original: {DictionaryStr(original)}"); + VerboseDebug($"Changed: {DictionaryStr(changed)}"); + VerboseDebug($"Original2: {DictionaryStr(original2)}"); + VerboseDebug($"Changed2: {DictionaryStr(changed2)}"); + return (original, original2, changed, changed2); + } + + [Test] + [Repeat(5)] + public void WhenSerializingAndDeserializingVeryLargeListNetworkVariables_ValuesAreSerializedCorrectly( + + [Values(typeof(byte), typeof(sbyte), typeof(short), typeof(ushort), typeof(int), typeof(uint), + typeof(long), typeof(ulong), typeof(bool), typeof(char), typeof(float), typeof(double), + typeof(Vector2), typeof(Vector3), typeof(Vector2Int), typeof(Vector3Int), typeof(Vector4), + typeof(Quaternion), typeof(Color), typeof(Color32), typeof(Ray), typeof(Ray2D), + typeof(NetworkVariableTestClass), typeof(FixedString32Bytes))] + Type testType) + { + if (testType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetLists(RandGenBytes); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(sbyte)) + { + (var original, var original2, var changed, var changed2) = GetLists(RandGenBytes); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(short)) + { + (var original, var original2, var changed, var changed2) = GetLists(RandGenBytes); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(ushort)) + { + (var original, var original2, var changed, var changed2) = GetLists(RandGenBytes); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(int)) + { + (var original, var original2, var changed, var changed2) = GetLists(RandGenBytes); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(uint)) + { + (var original, var original2, var changed, var changed2) = GetLists(RandGenBytes); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(long)) + { + (var original, var original2, var changed, var changed2) = GetLists(RandGenBytes); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetLists(RandGenBytes); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(bool)) + { + (var original, var original2, var changed, var changed2) = GetLists(RandGenBytes); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(char)) + { + (var original, var original2, var changed, var changed2) = GetLists(RandGenBytes); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(float)) + { + (var original, var original2, var changed, var changed2) = GetLists(RandGenBytes); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(double)) + { + (var original, var original2, var changed, var changed2) = GetLists(RandGenBytes); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetLists( + (rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(Vector3)) + { + (var original, var original2, var changed, var changed2) = GetLists( + (rand) => new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(Vector2Int)) + { + (var original, var original2, var changed, var changed2) = GetLists( + (rand) => new Vector2Int(rand.Next(), rand.Next()) + ); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(Vector3Int)) + { + (var original, var original2, var changed, var changed2) = GetLists( + (rand) => new Vector3Int(rand.Next(), rand.Next(), rand.Next()) + ); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(Vector4)) + { + (var original, var original2, var changed, var changed2) = GetLists( + (rand) => new Vector4((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(Quaternion)) + { + (var original, var original2, var changed, var changed2) = GetLists( + (rand) => new Quaternion((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(Color)) + { + (var original, var original2, var changed, var changed2) = GetLists( + (rand) => new Color((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(Color32)) + { + (var original, var original2, var changed, var changed2) = GetLists( + (rand) => new Color32((byte)rand.Next(), (byte)rand.Next(), (byte)rand.Next(), (byte)rand.Next()) + ); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(Ray)) + { + (var original, var original2, var changed, var changed2) = GetLists( + (rand) => new Ray( + new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()), + new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ) + ); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(Ray2D)) + { + (var original, var original2, var changed, var changed2) = GetLists( + (rand) => new Ray2D( + new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), + new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()) + ) + ); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(NetworkVariableTestClass)) + { + (var original, var original2, var changed, var changed2) = GetLists((rand) => + { + return new NetworkVariableTestClass { Data = RandGenBytes(rand) }; + }); + TestList(original, changed); + TestList(original2, changed2); + } + else if (testType == typeof(FixedString32Bytes)) + { + (var original, var original2, var changed, var changed2) = GetLists(RandGenFixedString32); + TestList(original, changed); + TestList(original2, changed2); + } + } + + [Test] + [Repeat(5)] + public void WhenSerializingAndDeserializingVeryLargeHashSetNetworkVariables_ValuesAreSerializedCorrectly( + + [Values(typeof(byte), typeof(sbyte), typeof(short), typeof(ushort), typeof(int), typeof(uint), + typeof(long), typeof(ulong), typeof(bool), typeof(char), typeof(float), typeof(double), + typeof(Vector2), typeof(Vector3), typeof(Vector2Int), typeof(Vector3Int), typeof(Vector4), + typeof(Quaternion), typeof(HashableNetworkVariableTestClass), typeof(FixedString32Bytes))] + Type testType) + { + if (testType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetHashSets(RandGenBytes); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(sbyte)) + { + (var original, var original2, var changed, var changed2) = GetHashSets(RandGenBytes); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(short)) + { + (var original, var original2, var changed, var changed2) = GetHashSets(RandGenBytes); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(ushort)) + { + (var original, var original2, var changed, var changed2) = GetHashSets(RandGenBytes); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(int)) + { + (var original, var original2, var changed, var changed2) = GetHashSets(RandGenBytes); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(uint)) + { + (var original, var original2, var changed, var changed2) = GetHashSets(RandGenBytes); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(long)) + { + (var original, var original2, var changed, var changed2) = GetHashSets(RandGenBytes); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetHashSets(RandGenBytes); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(bool)) + { + (var original, var original2, var changed, var changed2) = GetHashSets(RandGenBytes); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(char)) + { + (var original, var original2, var changed, var changed2) = GetHashSets(RandGenBytes); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(float)) + { + (var original, var original2, var changed, var changed2) = GetHashSets(RandGenBytes); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(double)) + { + (var original, var original2, var changed, var changed2) = GetHashSets(RandGenBytes); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetHashSets( + (rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(Vector3)) + { + (var original, var original2, var changed, var changed2) = GetHashSets( + (rand) => new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(Vector2Int)) + { + (var original, var original2, var changed, var changed2) = GetHashSets( + (rand) => new Vector2Int(rand.Next(), rand.Next()) + ); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(Vector3Int)) + { + (var original, var original2, var changed, var changed2) = GetHashSets( + (rand) => new Vector3Int(rand.Next(), rand.Next(), rand.Next()) + ); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(Vector4)) + { + (var original, var original2, var changed, var changed2) = GetHashSets( + (rand) => new Vector4((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(Quaternion)) + { + (var original, var original2, var changed, var changed2) = GetHashSets( + (rand) => new Quaternion((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(Color)) + { + (var original, var original2, var changed, var changed2) = GetHashSets( + (rand) => new Color((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(HashableNetworkVariableTestClass)) + { + (var original, var original2, var changed, var changed2) = GetHashSets((rand) => + { + return new HashableNetworkVariableTestClass { Data = RandGenBytes(rand) }; + }); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + else if (testType == typeof(FixedString32Bytes)) + { + (var original, var original2, var changed, var changed2) = GetHashSets(RandGenFixedString32); + TestHashSet(original, changed); + TestHashSet(original2, changed2); + } + } + + [Test] + [Repeat(5)] + public void WhenSerializingAndDeserializingVeryLargeDictionaryNetworkVariables_ValuesAreSerializedCorrectly( + + [Values(typeof(byte), typeof(ulong), typeof(Vector2), typeof(HashMapKeyClass))] Type keyType, + [Values(typeof(byte), typeof(sbyte), typeof(short), typeof(ushort), typeof(int), typeof(uint), + typeof(long), typeof(ulong), typeof(bool), typeof(char), typeof(float), typeof(double), + typeof(Vector2), typeof(Vector3), typeof(Vector2Int), typeof(Vector3Int), typeof(Vector4), + typeof(Quaternion), typeof(HashMapValClass), typeof(FixedString32Bytes))] + Type valType) + { + if (valType == typeof(byte)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + else if (valType == typeof(sbyte)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + else if (valType == typeof(short)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + else if (valType == typeof(ushort)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + else if (valType == typeof(int)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + else if (valType == typeof(uint)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + else if (valType == typeof(long)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + else if (valType == typeof(ulong)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + else if (valType == typeof(bool)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + else if (valType == typeof(char)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + else if (valType == typeof(float)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + else if (valType == typeof(double)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, RandGenBytes); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + else if (valType == typeof(Vector2)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, (rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, (rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), (rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, (rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + else if (valType == typeof(Vector3)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, (rand) => new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, (rand) => new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), (rand) => new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, (rand) => new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + else if (valType == typeof(Vector2Int)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, (rand) => new Vector2Int(rand.Next(), rand.Next())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, (rand) => new Vector2Int(rand.Next(), rand.Next())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), (rand) => new Vector2Int(rand.Next(), rand.Next())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, (rand) => new Vector2Int(rand.Next(), rand.Next())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + else if (valType == typeof(Vector3Int)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, (rand) => new Vector3Int(rand.Next(), rand.Next(), rand.Next())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, (rand) => new Vector3Int(rand.Next(), rand.Next(), rand.Next())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), (rand) => new Vector3Int(rand.Next(), rand.Next(), rand.Next())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, (rand) => new Vector3Int(rand.Next(), rand.Next(), rand.Next())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + else if (valType == typeof(Vector4)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, (rand) => new Vector4((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, (rand) => new Vector4((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), (rand) => new Vector4((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, (rand) => new Vector4((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + else if (valType == typeof(Quaternion)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, (rand) => new Quaternion((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, (rand) => new Quaternion((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), (rand) => new Quaternion((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, (rand) => new Quaternion((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + else if (valType == typeof(HashMapValClass)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, (rand) => new HashMapValClass { Data = RandGenBytes(rand) }); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, (rand) => new HashMapValClass { Data = RandGenBytes(rand) }); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), (rand) => new HashMapValClass { Data = RandGenBytes(rand) }); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, (rand) => new HashMapValClass { Data = RandGenBytes(rand) }); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + else if (valType == typeof(FixedString32Bytes)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenFixedString32); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries(RandGenBytes, RandGenFixedString32); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenFixedString32); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyClass)) + { + (var original, var original2, var changed, var changed2) = GetDictionaries((rand) => new HashMapKeyClass { Data = RandGenBytes(rand) }, RandGenFixedString32); + TestDictionary(original, changed); + TestDictionary(original2, changed2); + } + } + } + + #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT [Test] public void WhenSerializingAndDeserializingValueTypeNativeListNetworkVariables_ValuesAreSerializedCorrectly( @@ -2373,6 +3825,1218 @@ namespace Unity.Netcode.RuntimeTests }); } } + + public string NativeListStr(NativeList list) where T : unmanaged + { + var str = "["; + var comma = false; + foreach (var item in list) + { + if (comma) + { + str += ", "; + } + + comma = true; + str += $"{item}"; + } + + str += "]"; + return str; + } + + public string NativeHashSetStr(NativeHashSet list) where T : unmanaged, IEquatable + { + var str = "{"; + var comma = false; + foreach (var item in list) + { + if (comma) + { + str += ", "; + } + + comma = true; + str += $"{item}"; + } + + str += "}"; + return str; + } + + public string NativeHashMapStr(NativeHashMap list) + where TKey : unmanaged, IEquatable + where TVal : unmanaged + { + var str = "{"; + var comma = false; + foreach (var item in list) + { + if (comma) + { + str += ", "; + } + + comma = true; + str += $"{item.Key}: {item.Value}"; + } + + str += "}"; + return str; + } + + public (NativeList original, NativeList original2, NativeList changed, NativeList changed2) GetNativeLists(GetRandomElement generator) where T : unmanaged + { + var original = new NativeList(Allocator.Temp); + var changed = new NativeList(Allocator.Temp); + var original2 = new NativeList(Allocator.Temp); + var changed2 = new NativeList(Allocator.Temp); + + var rand = new System.Random(); + var originalSize = rand.Next(32, 64); + var changedSize = rand.Next(32, 64); + var changed2Changes = rand.Next(12, 16); + var changed2Adds = rand.Next(-16, 16); + for (var i = 0; i < originalSize; ++i) + { + var item = generator(rand); + original.Add(item); + original2.Add(item); + changed2.Add(item); + } + for (var i = 0; i < changedSize; ++i) + { + var item = generator(rand); + changed.Add(item); + } + + for (var i = 0; i < changed2Changes; ++i) + { + var idx = rand.Next(changed2.Length - 1); + var item = generator(rand); + changed2[idx] = item; + } + + if (changed2Adds < 0) + { + changed2.Resize(changed2.Length + changed2Adds, NativeArrayOptions.UninitializedMemory); + } + else + { + for (var i = 0; i < changed2Adds; ++i) + { + var item = generator(rand); + changed2.Add(item); + } + + } + + VerboseDebug($"Original: {NativeListStr(original)}"); + VerboseDebug($"Changed: {NativeListStr(changed)}"); + VerboseDebug($"Original2: {NativeListStr(original2)}"); + VerboseDebug($"Changed2: {NativeListStr(changed2)}"); + return (original, original2, changed, changed2); + } + + public (NativeHashSet original, NativeHashSet original2, NativeHashSet changed, NativeHashSet changed2) GetNativeHashSets(GetRandomElement generator) where T : unmanaged, IEquatable + { + var original = new NativeHashSet(16, Allocator.Temp); + var changed = new NativeHashSet(16, Allocator.Temp); + var original2 = new NativeHashSet(16, Allocator.Temp); + var changed2 = new NativeHashSet(16, Allocator.Temp); + + var rand = new System.Random(); + var originalSize = rand.Next(32, 64); + var changedSize = rand.Next(32, 64); + var changed2Removes = rand.Next(12, 16); + var changed2Adds = rand.Next(12, 16); + for (var i = 0; i < originalSize; ++i) + { + var item = generator(rand); + while (original.Contains(item)) + { + item = generator(rand); + } + original.Add(item); + original2.Add(item); + changed2.Add(item); + } + for (var i = 0; i < changedSize; ++i) + { + var item = generator(rand); + while (changed.Contains(item)) + { + item = generator(rand); + } + changed.Add(item); + } + + for (var i = 0; i < changed2Removes; ++i) + { +#if UTP_TRANSPORT_2_0_ABOVE + var which = rand.Next(changed2.Count); +#else + var which = rand.Next(changed2.Count()); +#endif + T toRemove = default; + foreach (var check in changed2) + { + if (which == 0) + { + toRemove = check; + break; + } + --which; + } + + changed2.Remove(toRemove); + } + + for (var i = 0; i < changed2Adds; ++i) + { + var item = generator(rand); + while (changed2.Contains(item)) + { + item = generator(rand); + } + changed2.Add(item); + } + + VerboseDebug($"Original: {NativeHashSetStr(original)}"); + VerboseDebug($"Changed: {NativeHashSetStr(changed)}"); + VerboseDebug($"Original2: {NativeHashSetStr(original2)}"); + VerboseDebug($"Changed2: {NativeHashSetStr(changed2)}"); + return (original, original2, changed, changed2); + } + + + public (NativeHashMap original, NativeHashMap original2, NativeHashMap changed, NativeHashMap changed2) GetMaps(GetRandomElement keyGenerator, GetRandomElement valGenerator) + where TKey : unmanaged, IEquatable + where TVal : unmanaged + { + var original = new NativeHashMap(16, Allocator.Temp); + var changed = new NativeHashMap(16, Allocator.Temp); + var original2 = new NativeHashMap(16, Allocator.Temp); + var changed2 = new NativeHashMap(16, Allocator.Temp); + + var rand = new System.Random(); + var originalSize = rand.Next(32, 64); + var changedSize = rand.Next(32, 64); + var changed2Removes = rand.Next(12, 16); + var changed2Adds = rand.Next(12, 16); + var changed2Changes = rand.Next(12, 16); + for (var i = 0; i < originalSize; ++i) + { + var key = keyGenerator(rand); + while (original.ContainsKey(key)) + { + key = keyGenerator(rand); + } + var val = valGenerator(rand); + original.Add(key, val); + original2.Add(key, val); + changed2.Add(key, val); + } + for (var i = 0; i < changedSize; ++i) + { + var key = keyGenerator(rand); + while (changed.ContainsKey(key)) + { + key = keyGenerator(rand); + } + var val = valGenerator(rand); + changed.Add(key, val); + } + + for (var i = 0; i < changed2Removes; ++i) + { +#if UTP_TRANSPORT_2_0_ABOVE + var which = rand.Next(changed2.Count); +#else + var which = rand.Next(changed2.Count()); +#endif + TKey toRemove = default; + foreach (var check in changed2) + { + if (which == 0) + { + toRemove = check.Key; + break; + } + --which; + } + + changed2.Remove(toRemove); + } + + for (var i = 0; i < changed2Changes; ++i) + { +#if UTP_TRANSPORT_2_0_ABOVE + var which = rand.Next(changed2.Count); +#else + var which = rand.Next(changed2.Count()); +#endif + TKey key = default; + foreach (var check in changed2) + { + if (which == 0) + { + key = check.Key; + break; + } + --which; + } + + var val = valGenerator(rand); + changed2[key] = val; + } + + for (var i = 0; i < changed2Adds; ++i) + { + var key = keyGenerator(rand); + while (changed2.ContainsKey(key)) + { + key = keyGenerator(rand); + } + var val = valGenerator(rand); + changed2.Add(key, val); + } + + VerboseDebug($"Original: {NativeHashMapStr(original)}"); + VerboseDebug($"Changed: {NativeHashMapStr(changed)}"); + VerboseDebug($"Original2: {NativeHashMapStr(original2)}"); + VerboseDebug($"Changed2: {NativeHashMapStr(changed2)}"); + return (original, original2, changed, changed2); + } + + [Test] + [Repeat(5)] + public void WhenSerializingAndDeserializingVeryLargeValueTypeNativeListNetworkVariables_ValuesAreSerializedCorrectly( + + [Values(typeof(byte), typeof(sbyte), typeof(short), typeof(ushort), typeof(int), typeof(uint), + typeof(long), typeof(ulong), typeof(bool), typeof(char), typeof(float), typeof(double), + typeof(Vector2), typeof(Vector3), typeof(Vector2Int), typeof(Vector3Int), typeof(Vector4), + typeof(Quaternion), typeof(Color), typeof(Color32), typeof(Ray), typeof(Ray2D), + typeof(NetworkVariableTestStruct), typeof(FixedString32Bytes))] + Type testType) + { + if (testType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists(RandGenBytes); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(sbyte)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists(RandGenBytes); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(short)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists(RandGenBytes); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(ushort)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists(RandGenBytes); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(int)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists(RandGenBytes); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(uint)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists(RandGenBytes); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(long)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists(RandGenBytes); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists(RandGenBytes); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(bool)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists(RandGenBytes); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(char)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists(RandGenBytes); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(float)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists(RandGenBytes); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(double)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists(RandGenBytes); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists( + (rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(Vector3)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists( + (rand) => new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(Vector2Int)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists( + (rand) => new Vector2Int(rand.Next(), rand.Next()) + ); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(Vector3Int)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists( + (rand) => new Vector3Int(rand.Next(), rand.Next(), rand.Next()) + ); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(Vector4)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists( + (rand) => new Vector4((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(Quaternion)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists( + (rand) => new Quaternion((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(Color)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists( + (rand) => new Color((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(Color32)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists( + (rand) => new Color32((byte)rand.Next(), (byte)rand.Next(), (byte)rand.Next(), (byte)rand.Next()) + ); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(Ray)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists( + (rand) => new Ray( + new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()), + new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ) + ); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(Ray2D)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists( + (rand) => new Ray2D( + new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), + new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()) + ) + ); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(NetworkVariableTestStruct)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists(RandGenBytes); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + else if (testType == typeof(FixedString32Bytes)) + { + (var original, var original2, var changed, var changed2) = GetNativeLists(RandGenFixedString32); + TestValueTypeNativeList(original, changed); + TestValueTypeNativeList(original2, changed2); + } + } + + [Test] + [Repeat(5)] + public void WhenSerializingAndDeserializingVeryLargeValueTypeNativeHashSetNetworkVariables_ValuesAreSerializedCorrectly( + + [Values(typeof(byte), typeof(sbyte), typeof(short), typeof(ushort), typeof(int), typeof(uint), + typeof(long), typeof(ulong), typeof(bool), typeof(char), typeof(float), typeof(double), + typeof(Vector2), typeof(Vector3), typeof(Vector2Int), typeof(Vector3Int), typeof(Vector4), + typeof(Quaternion), typeof(HashableNetworkVariableTestStruct), typeof(FixedString32Bytes))] + Type testType) + { + if (testType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets(RandGenBytes); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(sbyte)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets(RandGenBytes); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(short)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets(RandGenBytes); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(ushort)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets(RandGenBytes); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(int)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets(RandGenBytes); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(uint)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets(RandGenBytes); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(long)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets(RandGenBytes); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets(RandGenBytes); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(bool)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets(RandGenBytes); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(char)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets(RandGenBytes); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(float)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets(RandGenBytes); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(double)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets(RandGenBytes); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets( + (rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(Vector3)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets( + (rand) => new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(Vector2Int)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets( + (rand) => new Vector2Int(rand.Next(), rand.Next()) + ); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(Vector3Int)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets( + (rand) => new Vector3Int(rand.Next(), rand.Next(), rand.Next()) + ); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(Vector4)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets( + (rand) => new Vector4((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(Quaternion)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets( + (rand) => new Quaternion((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(Color)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets( + (rand) => new Color((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()) + ); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(HashableNetworkVariableTestStruct)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets(RandGenBytes); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + else if (testType == typeof(FixedString32Bytes)) + { + (var original, var original2, var changed, var changed2) = GetNativeHashSets(RandGenFixedString32); + TestValueTypeNativeHashSet(original, changed); + TestValueTypeNativeHashSet(original2, changed2); + } + } + + [Test] + [Repeat(5)] + public void WhenSerializingAndDeserializingVeryLargeValueTypeNativeHashMapNetworkVariables_ValuesAreSerializedCorrectly( + + [Values(typeof(byte), typeof(ulong), typeof(Vector2), typeof(HashMapKeyStruct))] Type keyType, + [Values(typeof(byte), typeof(sbyte), typeof(short), typeof(ushort), typeof(int), typeof(uint), + typeof(long), typeof(ulong), typeof(bool), typeof(char), typeof(float), typeof(double), + typeof(Vector2), typeof(Vector3), typeof(Vector2Int), typeof(Vector3Int), typeof(Vector4), + typeof(Quaternion), typeof(HashMapValStruct), typeof(FixedString32Bytes))] + Type valType) + { + if (valType == typeof(byte)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + else if (valType == typeof(sbyte)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + else if (valType == typeof(short)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + else if (valType == typeof(ushort)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + else if (valType == typeof(int)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + else if (valType == typeof(uint)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + else if (valType == typeof(long)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + else if (valType == typeof(ulong)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + else if (valType == typeof(bool)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + else if (valType == typeof(char)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + else if (valType == typeof(float)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + else if (valType == typeof(double)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + else if (valType == typeof(Vector2)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, (rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, (rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), (rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, (rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + else if (valType == typeof(Vector3)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, (rand) => new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, (rand) => new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), (rand) => new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, (rand) => new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + else if (valType == typeof(Vector2Int)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, (rand) => new Vector2Int(rand.Next(), rand.Next())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, (rand) => new Vector2Int(rand.Next(), rand.Next())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), (rand) => new Vector2Int(rand.Next(), rand.Next())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, (rand) => new Vector2Int(rand.Next(), rand.Next())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + else if (valType == typeof(Vector3Int)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, (rand) => new Vector3Int(rand.Next(), rand.Next(), rand.Next())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, (rand) => new Vector3Int(rand.Next(), rand.Next(), rand.Next())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), (rand) => new Vector3Int(rand.Next(), rand.Next(), rand.Next())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, (rand) => new Vector3Int(rand.Next(), rand.Next(), rand.Next())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + else if (valType == typeof(Vector4)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, (rand) => new Vector4((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, (rand) => new Vector4((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), (rand) => new Vector4((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, (rand) => new Vector4((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + else if (valType == typeof(Quaternion)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, (rand) => new Quaternion((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, (rand) => new Quaternion((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), (rand) => new Quaternion((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, (rand) => new Quaternion((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + else if (valType == typeof(HashMapValStruct)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenBytes); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + else if (valType == typeof(FixedString32Bytes)) + { + if (keyType == typeof(byte)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenFixedString32); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(ulong)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenFixedString32); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + else if (keyType == typeof(Vector2)) + { + (var original, var original2, var changed, var changed2) = GetMaps((rand) => new Vector2((float)rand.NextDouble(), (float)rand.NextDouble()), RandGenFixedString32); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + + } + else if (keyType == typeof(HashMapKeyStruct)) + { + (var original, var original2, var changed, var changed2) = GetMaps(RandGenBytes, RandGenFixedString32); + TestValueTypeNativeHashMap(original, changed); + TestValueTypeNativeHashMap(original2, changed2); + } + } + } + #endif [Test] @@ -2459,6 +5123,7 @@ namespace Unity.Netcode.RuntimeTests } } + /// /// Handles the more generic conditional logic for NetworkList tests /// which can be used with the @@ -2709,6 +5374,18 @@ namespace Unity.Netcode.RuntimeTests private GameObject m_TestObjectPrefab; private ulong m_TestObjectId = 0; + protected override void OnOneTimeSetup() + { + NetworkVariableBase.IgnoreInitializeWarning = true; + base.OnOneTimeSetup(); + } + + protected override void OnOneTimeTearDown() + { + NetworkVariableBase.IgnoreInitializeWarning = false; + base.OnOneTimeTearDown(); + } + protected override void OnServerAndClientsCreated() { m_TestObjectPrefab = CreateNetworkObjectPrefab($"[{nameof(NetworkVariableInheritanceTests)}.{nameof(m_TestObjectPrefab)}]"); @@ -2804,6 +5481,18 @@ namespace Unity.Netcode.RuntimeTests private GameObject m_TestPrefab; + protected override void OnOneTimeSetup() + { + NetworkVariableBase.IgnoreInitializeWarning = true; + base.OnOneTimeSetup(); + } + + protected override void OnOneTimeTearDown() + { + NetworkVariableBase.IgnoreInitializeWarning = false; + base.OnOneTimeTearDown(); + } + protected override void OnServerAndClientsCreated() { m_TestPrefab = CreateNetworkObjectPrefab("NetVarDespawn"); @@ -2837,3 +5526,4 @@ namespace Unity.Netcode.RuntimeTests } } } +#endif diff --git a/Tests/Runtime/NetworkVariableTestsHelperTypes.cs b/Tests/Runtime/NetworkVariableTestsHelperTypes.cs new file mode 100644 index 0000000..6f2752c --- /dev/null +++ b/Tests/Runtime/NetworkVariableTestsHelperTypes.cs @@ -0,0 +1,937 @@ +using System; +using System.Collections.Generic; +using Unity.Collections; +using UnityEngine; + +namespace Unity.Netcode.RuntimeTests +{ + public class NetVarPermTestComp : NetworkBehaviour + { + public NetworkVariable OwnerWritable_Position = new NetworkVariable(Vector3.one, NetworkVariableBase.DefaultReadPerm, NetworkVariableWritePermission.Owner); + public NetworkVariable ServerWritable_Position = new NetworkVariable(Vector3.one, NetworkVariableBase.DefaultReadPerm, NetworkVariableWritePermission.Server); + public NetworkVariable OwnerReadWrite_Position = new NetworkVariable(Vector3.one, NetworkVariableReadPermission.Owner, NetworkVariableWritePermission.Owner); + } + + public class NetworkVariableMiddleclass : NetworkVariable + { + + } + + public class NetworkVariableSubclass : NetworkVariableMiddleclass + { + + } + + public class NetworkBehaviourWithNetVarArray : NetworkBehaviour + { + public NetworkVariable Int0 = new NetworkVariable(); + public NetworkVariable Int1 = new NetworkVariable(); + public NetworkVariable Int2 = new NetworkVariable(); + public NetworkVariable Int3 = new NetworkVariable(); + public NetworkVariable Int4 = new NetworkVariable(); + public NetworkVariable[] AllInts = new NetworkVariable[5]; + + public int InitializedFieldCount => NetworkVariableFields.Count; + + + private void Awake() + { + AllInts[0] = Int0; + AllInts[1] = Int1; + AllInts[2] = Int2; + AllInts[3] = Int3; + AllInts[4] = Int4; + } + } + + internal struct TypeReferencedOnlyInCustomSerialization1 : INetworkSerializeByMemcpy + { + public int I; + } + + internal struct TypeReferencedOnlyInCustomSerialization2 : INetworkSerializeByMemcpy + { + public int I; + } + + internal struct TypeReferencedOnlyInCustomSerialization3 : INetworkSerializeByMemcpy + { + public int I; + } + + internal struct TypeReferencedOnlyInCustomSerialization4 : INetworkSerializeByMemcpy + { + public int I; + } + + internal struct TypeReferencedOnlyInCustomSerialization5 : INetworkSerializeByMemcpy + { + public int I; + } + + internal struct TypeReferencedOnlyInCustomSerialization6 : INetworkSerializeByMemcpy + { + public int I; + } + + // Both T and U are serializable + [GenerateSerializationForGenericParameter(0)] + [GenerateSerializationForGenericParameter(1)] + internal class CustomSerializableClass + { + + } + + // Only U is serializable + [GenerateSerializationForGenericParameter(1)] + internal class CustomSerializableBaseClass + { + + } + + // T is serializable, passes TypeReferencedOnlyInCustomSerialization3 as U to the subclass, making it serializable + [GenerateSerializationForGenericParameter(0)] + internal class CustomSerializableSubclass : CustomSerializableBaseClass + { + + } + + // T is serializable, passes TypeReferencedOnlyInCustomSerialization3 as U to the subclass, making it serializable + [GenerateSerializationForGenericParameter(0)] + internal class CustomSerializableSubclassWithNativeArray : CustomSerializableBaseClass> + { + + } + + internal class CustomGenericSerializationTestBehaviour : NetworkBehaviour + { + public CustomSerializableClass Value1; + public CustomSerializableClass, NativeArray> Value2; + public CustomSerializableSubclass Value3; + public CustomSerializableSubclassWithNativeArray> Value4; + } + + [GenerateSerializationForType(typeof(TypeReferencedOnlyInCustomSerialization5))] + [GenerateSerializationForType(typeof(NativeArray))] + internal struct SomeRandomStruct + { + [GenerateSerializationForType(typeof(TypeReferencedOnlyInCustomSerialization6))] + [GenerateSerializationForType(typeof(NativeArray))] + public void Foo() + { + + } + } + + public struct TemplatedValueOnlyReferencedByNetworkVariableSubclass : INetworkSerializeByMemcpy + where T : unmanaged + { + public T Value; + } + + public enum ByteEnum : byte + { + A, + B, + C = byte.MaxValue + } + public enum SByteEnum : sbyte + { + A, + B, + C = sbyte.MaxValue + } + public enum ShortEnum : short + { + A, + B, + C = short.MaxValue + } + public enum UShortEnum : ushort + { + A, + B, + C = ushort.MaxValue + } + public enum IntEnum : int + { + A, + B, + C = int.MaxValue + } + public enum UIntEnum : uint + { + A, + B, + C = uint.MaxValue + } + public enum LongEnum : long + { + A, + B, + C = long.MaxValue + } + public enum ULongEnum : ulong + { + A, + B, + C = ulong.MaxValue + } + + public struct HashableNetworkVariableTestStruct : INetworkSerializeByMemcpy, IEquatable + { + public byte A; + public short B; + public ushort C; + public int D; + public uint E; + public long F; + public ulong G; + public bool H; + public char I; + public float J; + public double K; + + public bool Equals(HashableNetworkVariableTestStruct other) + { + return A == other.A && B == other.B && C == other.C && D == other.D && E == other.E && F == other.F && G == other.G && H == other.H && I == other.I && J.Equals(other.J) && K.Equals(other.K); + } + + public override bool Equals(object obj) + { + return obj is HashableNetworkVariableTestStruct other && Equals(other); + } + + public override int GetHashCode() + { + var hashCode = new HashCode(); + hashCode.Add(A); + hashCode.Add(B); + hashCode.Add(C); + hashCode.Add(D); + hashCode.Add(E); + hashCode.Add(F); + hashCode.Add(G); + hashCode.Add(H); + hashCode.Add(I); + hashCode.Add(J); + hashCode.Add(K); + return hashCode.ToHashCode(); + } + } + + public struct HashMapKeyStruct : INetworkSerializeByMemcpy, IEquatable + { + public byte A; + public short B; + public ushort C; + public int D; + public uint E; + public long F; + public ulong G; + public bool H; + public char I; + public float J; + public double K; + + public bool Equals(HashMapKeyStruct other) + { + return A == other.A && B == other.B && C == other.C && D == other.D && E == other.E && F == other.F && G == other.G && H == other.H && I == other.I && J.Equals(other.J) && K.Equals(other.K); + } + + public override bool Equals(object obj) + { + return obj is HashMapKeyStruct other && Equals(other); + } + + public override int GetHashCode() + { + var hashCode = new HashCode(); + hashCode.Add(A); + hashCode.Add(B); + hashCode.Add(C); + hashCode.Add(D); + hashCode.Add(E); + hashCode.Add(F); + hashCode.Add(G); + hashCode.Add(H); + hashCode.Add(I); + hashCode.Add(J); + hashCode.Add(K); + return hashCode.ToHashCode(); + } + } + + public struct HashMapValStruct : INetworkSerializeByMemcpy, IEquatable + { + public byte A; + public short B; + public ushort C; + public int D; + public uint E; + public long F; + public ulong G; + public bool H; + public char I; + public float J; + public double K; + + public bool Equals(HashMapValStruct other) + { + return A == other.A && B == other.B && C == other.C && D == other.D && E == other.E && F == other.F && G == other.G && H == other.H && I == other.I && J.Equals(other.J) && K.Equals(other.K); + } + + public override bool Equals(object obj) + { + return obj is HashMapValStruct other && Equals(other); + } + + public override int GetHashCode() + { + var hashCode = new HashCode(); + hashCode.Add(A); + hashCode.Add(B); + hashCode.Add(C); + hashCode.Add(D); + hashCode.Add(E); + hashCode.Add(F); + hashCode.Add(G); + hashCode.Add(H); + hashCode.Add(I); + hashCode.Add(J); + hashCode.Add(K); + return hashCode.ToHashCode(); + } + } + + public struct NetworkVariableTestStruct : INetworkSerializeByMemcpy + { + public byte A; + public short B; + public ushort C; + public int D; + public uint E; + public long F; + public ulong G; + public bool H; + public char I; + public float J; + public double K; + + private static System.Random s_Random = new System.Random(); + + public static NetworkVariableTestStruct GetTestStruct() + { + var testStruct = new NetworkVariableTestStruct + { + A = (byte)s_Random.Next(), + B = (short)s_Random.Next(), + C = (ushort)s_Random.Next(), + D = s_Random.Next(), + E = (uint)s_Random.Next(), + F = ((long)s_Random.Next() << 32) + s_Random.Next(), + G = ((ulong)s_Random.Next() << 32) + (ulong)s_Random.Next(), + H = true, + I = '\u263a', + J = (float)s_Random.NextDouble(), + K = s_Random.NextDouble(), + }; + + return testStruct; + } + } + + + public class HashableNetworkVariableTestClass : INetworkSerializable, IEquatable + { + public HashableNetworkVariableTestStruct Data; + + public bool Equals(HashableNetworkVariableTestClass other) + { + return Data.Equals(other.Data); + } + + public override bool Equals(object obj) + { + return obj is HashableNetworkVariableTestClass other && Equals(other); + } + + public override int GetHashCode() + { + return Data.GetHashCode(); + } + + public void NetworkSerialize(BufferSerializer serializer) where T : IReaderWriter + { + serializer.SerializeValue(ref Data); + } + } + + public class HashMapKeyClass : INetworkSerializable, IEquatable + { + public HashMapKeyStruct Data; + + public bool Equals(HashMapKeyClass other) + { + return Data.Equals(other.Data); + } + + public override bool Equals(object obj) + { + return obj is HashMapKeyClass other && Equals(other); + } + + public override int GetHashCode() + { + return Data.GetHashCode(); + } + + public void NetworkSerialize(BufferSerializer serializer) where T : IReaderWriter + { + serializer.SerializeValue(ref Data); + } + } + + public class HashMapValClass : INetworkSerializable, IEquatable + { + public HashMapValStruct Data; + + public bool Equals(HashMapValClass other) + { + return Data.Equals(other.Data); + } + + public override bool Equals(object obj) + { + return obj is HashMapValClass other && Equals(other); + } + + public override int GetHashCode() + { + return Data.GetHashCode(); + } + + public void NetworkSerialize(BufferSerializer serializer) where T : IReaderWriter + { + serializer.SerializeValue(ref Data); + } + } + + public class NetworkVariableTestClass : INetworkSerializable, IEquatable + { + public NetworkVariableTestStruct Data; + + public bool Equals(NetworkVariableTestClass other) + { + return NetworkVariableSerialization.AreEqual(ref Data, ref other.Data); + } + + public override bool Equals(object obj) + { + return obj is NetworkVariableTestClass other && Equals(other); + } + + // This type is not used for hashing, we just need to implement IEquatable to verify lists match. + public override int GetHashCode() + { + return 0; + } + + public void NetworkSerialize(BufferSerializer serializer) where T : IReaderWriter + { + serializer.SerializeValue(ref Data); + } + } + + + // The ILPP code for NetworkVariables to determine how to serialize them relies on them existing as fields of a NetworkBehaviour to find them. + // Some of the tests below create NetworkVariables on the stack, so this class is here just to make sure the relevant types are all accounted for. + public class NetVarILPPClassForTests : NetworkBehaviour + { + public NetworkVariable ByteVar; + public NetworkVariable> ByteArrayVar; + public NetworkVariable> ByteManagedListVar; + public NetworkVariable> ByteManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> ByteListVar; + public NetworkVariable> ByteHashSetVar; + public NetworkVariable> ByteByteHashMapVar; + public NetworkVariable> ULongByteHashMapVar; + public NetworkVariable> Vector2ByteHashMapVar; + public NetworkVariable> HashMapKeyStructByteHashMapVar; +#endif + public NetworkVariable> ByteByteDictionaryVar; + public NetworkVariable> ULongByteDictionaryVar; + public NetworkVariable> Vector2ByteDictionaryVar; + public NetworkVariable> HashMapKeyClassByteDictionaryVar; + + public NetworkVariable SbyteVar; + public NetworkVariable> SbyteArrayVar; + public NetworkVariable> SbyteManagedListVar; + public NetworkVariable> SbyteManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> SbyteListVar; + public NetworkVariable> SbyteHashSetVar; + public NetworkVariable> ByteSbyteHashMapVar; + public NetworkVariable> ULongSbyteHashMapVar; + public NetworkVariable> Vector2SbyteHashMapVar; + public NetworkVariable> HashMapKeyStructSbyteHashMapVar; +#endif + public NetworkVariable> ByteSbyteDictionaryVar; + public NetworkVariable> ULongSbyteDictionaryVar; + public NetworkVariable> Vector2SbyteDictionaryVar; + public NetworkVariable> HashMapKeyClassSbyteDictionaryVar; + + public NetworkVariable ShortVar; + public NetworkVariable> ShortArrayVar; + public NetworkVariable> ShortManagedListVar; + public NetworkVariable> ShortManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> ShortListVar; + public NetworkVariable> ShortHashSetVar; + public NetworkVariable> ByteShortHashMapVar; + public NetworkVariable> ULongShortHashMapVar; + public NetworkVariable> Vector2ShortHashMapVar; + public NetworkVariable> HashMapKeyStructShortHashMapVar; +#endif + public NetworkVariable> ByteShortDictionaryVar; + public NetworkVariable> ULongShortDictionaryVar; + public NetworkVariable> Vector2ShortDictionaryVar; + public NetworkVariable> HashMapKeyClassShortDictionaryVar; + + public NetworkVariable UshortVar; + public NetworkVariable> UshortArrayVar; + public NetworkVariable> UshortManagedListVar; + public NetworkVariable> UshortManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> UshortListVar; + public NetworkVariable> UshortHashSetVar; + public NetworkVariable> ByteUshortHashMapVar; + public NetworkVariable> ULongUshortHashMapVar; + public NetworkVariable> Vector2UshortHashMapVar; + public NetworkVariable> HashMapKeyStructUshortHashMapVar; +#endif + public NetworkVariable> ByteUshortDictionaryVar; + public NetworkVariable> ULongUshortDictionaryVar; + public NetworkVariable> Vector2UshortDictionaryVar; + public NetworkVariable> HashMapKeyClassUshortDictionaryVar; + + public NetworkVariable IntVar; + public NetworkVariable> IntArrayVar; + public NetworkVariable> IntManagedListVar; + public NetworkVariable> IntManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> IntListVar; + public NetworkVariable> IntHashSetVar; + public NetworkVariable> ByteIntHashMapVar; + public NetworkVariable> ULongIntHashMapVar; + public NetworkVariable> Vector2IntHashMapVar; + public NetworkVariable> HashMapKeyStructIntHashMapVar; +#endif + public NetworkVariable> ByteIntDictionaryVar; + public NetworkVariable> ULongIntDictionaryVar; + public NetworkVariable> Vector2IntDictionaryVar; + public NetworkVariable> HashMapKeyClassIntDictionaryVar; + + public NetworkVariable UintVar; + public NetworkVariable> UintArrayVar; + public NetworkVariable> UintManagedListVar; + public NetworkVariable> UintManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> UintListVar; + public NetworkVariable> UintHashSetVar; + public NetworkVariable> ByteUintHashMapVar; + public NetworkVariable> ULongUintHashMapVar; + public NetworkVariable> Vector2UintHashMapVar; + public NetworkVariable> HashMapKeyStructUintHashMapVar; +#endif + public NetworkVariable> ByteUintDictionaryVar; + public NetworkVariable> ULongUintDictionaryVar; + public NetworkVariable> Vector2UintDictionaryVar; + public NetworkVariable> HashMapKeyClassUintDictionaryVar; + + public NetworkVariable LongVar; + public NetworkVariable> LongArrayVar; + public NetworkVariable> LongManagedListVar; + public NetworkVariable> LongManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> LongListVar; + public NetworkVariable> LongHashSetVar; + public NetworkVariable> ByteLongHashMapVar; + public NetworkVariable> ULongLongHashMapVar; + public NetworkVariable> Vector2LongHashMapVar; + public NetworkVariable> HashMapKeyStructLongHashMapVar; +#endif + public NetworkVariable> ByteLongDictionaryVar; + public NetworkVariable> ULongLongDictionaryVar; + public NetworkVariable> Vector2LongDictionaryVar; + public NetworkVariable> HashMapKeyClassLongDictionaryVar; + + public NetworkVariable UlongVar; + public NetworkVariable> UlongArrayVar; + public NetworkVariable> UlongManagedListVar; + public NetworkVariable> UlongManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> UlongListVar; + public NetworkVariable> UlongHashSetVar; + public NetworkVariable> ByteUlongHashMapVar; + public NetworkVariable> ULongUlongHashMapVar; + public NetworkVariable> Vector2UlongHashMapVar; + public NetworkVariable> HashMapKeyStructUlongHashMapVar; +#endif + public NetworkVariable> ByteUlongDictionaryVar; + public NetworkVariable> ULongUlongDictionaryVar; + public NetworkVariable> Vector2UlongDictionaryVar; + public NetworkVariable> HashMapKeyClassUlongDictionaryVar; + + public NetworkVariable BoolVar; + public NetworkVariable> BoolArrayVar; + public NetworkVariable> BoolManagedListVar; + public NetworkVariable> BoolManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> BoolListVar; + public NetworkVariable> BoolHashSetVar; + public NetworkVariable> ByteBoolHashMapVar; + public NetworkVariable> ULongBoolHashMapVar; + public NetworkVariable> Vector2BoolHashMapVar; + public NetworkVariable> HashMapKeyStructBoolHashMapVar; +#endif + public NetworkVariable> ByteBoolDictionaryVar; + public NetworkVariable> ULongBoolDictionaryVar; + public NetworkVariable> Vector2BoolDictionaryVar; + public NetworkVariable> HashMapKeyClassBoolDictionaryVar; + + public NetworkVariable CharVar; + public NetworkVariable> CharArrayVar; + public NetworkVariable> CharManagedListVar; + public NetworkVariable> CharManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> CharListVar; + public NetworkVariable> CharHashSetVar; + public NetworkVariable> ByteCharHashMapVar; + public NetworkVariable> ULongCharHashMapVar; + public NetworkVariable> Vector2CharHashMapVar; + public NetworkVariable> HashMapKeyStructCharHashMapVar; +#endif + public NetworkVariable> ByteCharDictionaryVar; + public NetworkVariable> ULongCharDictionaryVar; + public NetworkVariable> Vector2CharDictionaryVar; + public NetworkVariable> HashMapKeyClassCharDictionaryVar; + + public NetworkVariable FloatVar; + public NetworkVariable> FloatArrayVar; + public NetworkVariable> FloatManagedListVar; + public NetworkVariable> FloatManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> FloatListVar; + public NetworkVariable> FloatHashSetVar; + public NetworkVariable> ByteFloatHashMapVar; + public NetworkVariable> ULongFloatHashMapVar; + public NetworkVariable> Vector2FloatHashMapVar; + public NetworkVariable> HashMapKeyStructFloatHashMapVar; +#endif + public NetworkVariable> ByteFloatDictionaryVar; + public NetworkVariable> ULongFloatDictionaryVar; + public NetworkVariable> Vector2FloatDictionaryVar; + public NetworkVariable> HashMapKeyClassFloatDictionaryVar; + + public NetworkVariable DoubleVar; + public NetworkVariable> DoubleArrayVar; + public NetworkVariable> DoubleManagedListVar; + public NetworkVariable> DoubleManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> DoubleListVar; + public NetworkVariable> DoubleHashSetVar; + public NetworkVariable> ByteDoubleHashMapVar; + public NetworkVariable> ULongDoubleHashMapVar; + public NetworkVariable> Vector2DoubleHashMapVar; + public NetworkVariable> HashMapKeyStructDoubleHashMapVar; +#endif + public NetworkVariable> ByteDoubleDictionaryVar; + public NetworkVariable> ULongDoubleDictionaryVar; + public NetworkVariable> Vector2DoubleDictionaryVar; + public NetworkVariable> HashMapKeyClassDoubleDictionaryVar; + + public NetworkVariable ByteEnumVar; + public NetworkVariable> ByteEnumArrayVar; + public NetworkVariable> ByteEnumManagedListVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> ByteEnumListVar; +#endif + public NetworkVariable SByteEnumVar; + public NetworkVariable> SByteEnumArrayVar; + public NetworkVariable> SByteEnumManagedListVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> SByteEnumListVar; +#endif + public NetworkVariable ShortEnumVar; + public NetworkVariable> ShortEnumArrayVar; + public NetworkVariable> ShortEnumManagedListVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> ShortEnumListVar; +#endif + public NetworkVariable UShortEnumVar; + public NetworkVariable> UShortEnumArrayVar; + public NetworkVariable> UShortEnumManagedListVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> UShortEnumListVar; +#endif + public NetworkVariable IntEnumVar; + public NetworkVariable> IntEnumArrayVar; + public NetworkVariable> IntEnumManagedListVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> IntEnumListVar; +#endif + public NetworkVariable UIntEnumVar; + public NetworkVariable> UIntEnumArrayVar; + public NetworkVariable> UIntEnumManagedListVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> UIntEnumListVar; +#endif + public NetworkVariable LongEnumVar; + public NetworkVariable> LongEnumArrayVar; + public NetworkVariable> LongEnumManagedListVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> LongEnumListVar; +#endif + public NetworkVariable ULongEnumVar; + public NetworkVariable> ULongEnumArrayVar; + public NetworkVariable> ULongEnumManagedListVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> ULongEnumListVar; +#endif + public NetworkVariable Vector2Var; + public NetworkVariable> Vector2ArrayVar; + public NetworkVariable> Vector2ManagedListVar; + public NetworkVariable> Vector2ManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> Vector2ListVar; + public NetworkVariable> Vector2HashSetVar; + public NetworkVariable> ByteVector2HashMapVar; + public NetworkVariable> ULongVector2HashMapVar; + public NetworkVariable> Vector2Vector2HashMapVar; + public NetworkVariable> HashMapKeyStructVector2HashMapVar; +#endif + public NetworkVariable> ByteVector2DictionaryVar; + public NetworkVariable> ULongVector2DictionaryVar; + public NetworkVariable> Vector2Vector2DictionaryVar; + public NetworkVariable> HashMapKeyClassVector2DictionaryVar; + + public NetworkVariable Vector3Var; + public NetworkVariable> Vector3ArrayVar; + public NetworkVariable> Vector3ManagedListVar; + public NetworkVariable> Vector3ManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> Vector3ListVar; + public NetworkVariable> Vector3HashSetVar; + public NetworkVariable> ByteVector3HashMapVar; + public NetworkVariable> ULongVector3HashMapVar; + public NetworkVariable> Vector2Vector3HashMapVar; + public NetworkVariable> HashMapKeyStructVector3HashMapVar; +#endif + public NetworkVariable> ByteVector3DictionaryVar; + public NetworkVariable> ULongVector3DictionaryVar; + public NetworkVariable> Vector2Vector3DictionaryVar; + public NetworkVariable> HashMapKeyClassVector3DictionaryVar; + + public NetworkVariable Vector2IntVar; + public NetworkVariable> Vector2IntArrayVar; + public NetworkVariable> Vector2IntManagedListVar; + public NetworkVariable> Vector2IntManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> Vector2IntListVar; + public NetworkVariable> Vector2IntHashSetVar; + public NetworkVariable> ByteVector2IntHashMapVar; + public NetworkVariable> ULongVector2IntHashMapVar; + public NetworkVariable> Vector2Vector2IntHashMapVar; + public NetworkVariable> HashMapKeyStructVector2IntHashMapVar; +#endif + public NetworkVariable> ByteVector2IntDictionaryVar; + public NetworkVariable> ULongVector2IntDictionaryVar; + public NetworkVariable> Vector2Vector2IntDictionaryVar; + public NetworkVariable> HashMapKeyClassVector2IntDictionaryVar; + + public NetworkVariable Vector3IntVar; + public NetworkVariable> Vector3IntArrayVar; + public NetworkVariable> Vector3IntManagedListVar; + public NetworkVariable> Vector3IntManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> Vector3IntListVar; + public NetworkVariable> Vector3IntHashSetVar; + public NetworkVariable> ByteVector3IntHashMapVar; + public NetworkVariable> ULongVector3IntHashMapVar; + public NetworkVariable> Vector2Vector3IntHashMapVar; + public NetworkVariable> HashMapKeyStructVector3IntHashMapVar; +#endif + public NetworkVariable> ByteVector3IntDictionaryVar; + public NetworkVariable> ULongVector3IntDictionaryVar; + public NetworkVariable> Vector2Vector3IntDictionaryVar; + public NetworkVariable> HashMapKeyClassVector3IntDictionaryVar; + + public NetworkVariable Vector4Var; + public NetworkVariable> Vector4ArrayVar; + public NetworkVariable> Vector4ManagedListVar; + public NetworkVariable> Vector4ManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> Vector4ListVar; + public NetworkVariable> Vector4HashSetVar; + public NetworkVariable> ByteVector4HashMapVar; + public NetworkVariable> ULongVector4HashMapVar; + public NetworkVariable> Vector2Vector4HashMapVar; + public NetworkVariable> HashMapKeyStructVector4HashMapVar; +#endif + public NetworkVariable> ByteVector4DictionaryVar; + public NetworkVariable> ULongVector4DictionaryVar; + public NetworkVariable> Vector2Vector4DictionaryVar; + public NetworkVariable> HashMapKeyClassVector4DictionaryVar; + + public NetworkVariable QuaternionVar; + public NetworkVariable> QuaternionArrayVar; + public NetworkVariable> QuaternionManagedListVar; + public NetworkVariable> QuaternionManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> QuaternionListVar; + public NetworkVariable> QuaternionHashSetVar; + public NetworkVariable> ByteQuaternionHashMapVar; + public NetworkVariable> ULongQuaternionHashMapVar; + public NetworkVariable> Vector2QuaternionHashMapVar; + public NetworkVariable> HashMapKeyStructQuaternionHashMapVar; +#endif + public NetworkVariable> ByteQuaternionDictionaryVar; + public NetworkVariable> ULongQuaternionDictionaryVar; + public NetworkVariable> Vector2QuaternionDictionaryVar; + public NetworkVariable> HashMapKeyClassQuaternionDictionaryVar; + + public NetworkVariable ColorVar; + public NetworkVariable> ColorArrayVar; + public NetworkVariable> ColorManagedListVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> ColorListVar; +#endif + public NetworkVariable Color32Var; + public NetworkVariable> Color32ArrayVar; + public NetworkVariable> Color32ManagedListVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> Color32ListVar; +#endif + public NetworkVariable RayVar; + public NetworkVariable> RayArrayVar; + public NetworkVariable> RayManagedListVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> RayListVar; +#endif + public NetworkVariable Ray2DVar; + public NetworkVariable> Ray2DArrayVar; + public NetworkVariable> Ray2DManagedListVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> Ray2DListVar; +#endif + public NetworkVariable TestStructVar; + public NetworkVariable> TestStructArrayVar; + public NetworkVariable> TestStructManagedListVar; + public NetworkVariable> TestStructManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> TestStructListVar; + public NetworkVariable> TestStructHashSetVar; + public NetworkVariable> ByteTestStructHashMapVar; + public NetworkVariable> ULongTestStructHashMapVar; + public NetworkVariable> Vector2TestStructHashMapVar; + public NetworkVariable> HashMapKeyStructTestStructHashMapVar; +#endif + public NetworkVariable> ByteTestStructDictionaryVar; + public NetworkVariable> ULongTestStructDictionaryVar; + public NetworkVariable> Vector2TestStructDictionaryVar; + public NetworkVariable> HashMapKeyClassTestStructDictionaryVar; + + + public NetworkVariable FixedStringVar; + public NetworkVariable> FixedStringArrayVar; + public NetworkVariable> FixedStringManagedListVar; + public NetworkVariable> FixedStringManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> FixedStringListVar; + public NetworkVariable> FixedStringHashSetVar; + public NetworkVariable> ByteFixedStringHashMapVar; + public NetworkVariable> ULongFixedStringHashMapVar; + public NetworkVariable> Vector2FixedStringHashMapVar; + public NetworkVariable> HashMapKeyStructFixedStringHashMapVar; +#endif + public NetworkVariable> ByteFixedStringDictionaryVar; + public NetworkVariable> ULongFixedStringDictionaryVar; + public NetworkVariable> Vector2FixedStringDictionaryVar; + public NetworkVariable> HashMapKeyClassFixedStringDictionaryVar; + + + public NetworkVariable UnmanagedNetworkSerializableTypeVar; + public NetworkVariable> UnmanagedNetworkSerializableManagedHashSetVar; +#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT + public NetworkVariable> UnmanagedNetworkSerializableListVar; + public NetworkVariable> UnmanagedNetworkSerializableHashSetVar; + public NetworkVariable> ByteUnmanagedNetworkSerializableHashMapVar; + public NetworkVariable> ULongUnmanagedNetworkSerializableHashMapVar; + public NetworkVariable> Vector2UnmanagedNetworkSerializableHashMapVar; + public NetworkVariable> HashMapKeyStructUnmanagedNetworkSerializableHashMapVar; +#endif + public NetworkVariable> ByteUnmanagedNetworkSerializableDictionaryVar; + public NetworkVariable> ULongUnmanagedNetworkSerializableDictionaryVar; + public NetworkVariable> Vector2UnmanagedNetworkSerializableDictionaryVar; + public NetworkVariable> HashMapKeyClassUnmanagedNetworkSerializableDictionaryVar; + + public NetworkVariable> UnmanagedNetworkSerializableArrayVar; + public NetworkVariable> UnmanagedNetworkSerializableManagedListVar; + + public NetworkVariable ManagedNetworkSerializableTypeVar; + + public NetworkVariable StringVar; + public NetworkVariable GuidVar; + public NetworkVariableSubclass> SubclassVar; + } + + public class TemplateNetworkBehaviourType : NetworkBehaviour + { + public NetworkVariable TheVar; + } + + public class IntermediateNetworkBehavior : TemplateNetworkBehaviourType + { + public NetworkVariable TheVar2; + } +#if !NGO_MINIMALPROJECT + public class ClassHavingNetworkBehaviour : IntermediateNetworkBehavior + { + + } + + // Please do not reference TestClass_ReferencedOnlyByTemplateNetworkBehavourType anywhere other than here! + public class ClassHavingNetworkBehaviour2 : TemplateNetworkBehaviourType + { + + } + + public class StructHavingNetworkBehaviour : TemplateNetworkBehaviourType + { + + } +#endif + + public struct StructUsedOnlyInNetworkList : IEquatable, INetworkSerializeByMemcpy + { + public int Value; + + public bool Equals(StructUsedOnlyInNetworkList other) + { + return Value == other.Value; + } + + public override bool Equals(object obj) + { + return obj is StructUsedOnlyInNetworkList other && Equals(other); + } + + public override int GetHashCode() + { + return Value; + } + } + +} diff --git a/Tests/Runtime/NetworkVariableTestsHelperTypes.cs.meta b/Tests/Runtime/NetworkVariableTestsHelperTypes.cs.meta new file mode 100644 index 0000000..c71cb92 --- /dev/null +++ b/Tests/Runtime/NetworkVariableTestsHelperTypes.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: a580aaafc247486193f372174a99fae4 +timeCreated: 1705098783 \ No newline at end of file diff --git a/Tests/Runtime/NetworkVisibilityTests.cs b/Tests/Runtime/NetworkVisibilityTests.cs index bbd9cb4..037481c 100644 --- a/Tests/Runtime/NetworkVisibilityTests.cs +++ b/Tests/Runtime/NetworkVisibilityTests.cs @@ -7,20 +7,18 @@ using UnityEngine.TestTools; namespace Unity.Netcode.RuntimeTests { - [TestFixture(SceneManagementState.SceneManagementEnabled)] - [TestFixture(SceneManagementState.SceneManagementDisabled)] + [TestFixture(SceneManagementState.SceneManagementEnabled, SessionModeTypes.DistributedAuthority)] + [TestFixture(SceneManagementState.SceneManagementDisabled, SessionModeTypes.DistributedAuthority)] + [TestFixture(SceneManagementState.SceneManagementEnabled, SessionModeTypes.ClientServer)] + [TestFixture(SceneManagementState.SceneManagementDisabled, SessionModeTypes.ClientServer)] public class NetworkVisibilityTests : NetcodeIntegrationTest { - public enum SceneManagementState - { - SceneManagementEnabled, - SceneManagementDisabled - } + protected override int NumberOfClients => 1; private GameObject m_TestNetworkPrefab; private bool m_SceneManagementEnabled; - public NetworkVisibilityTests(SceneManagementState sceneManagementState) + public NetworkVisibilityTests(SceneManagementState sceneManagementState, SessionModeTypes sessionModeType) : base(sessionModeType) { m_SceneManagementEnabled = sceneManagementState == SceneManagementState.SceneManagementEnabled; } diff --git a/Tests/Runtime/OwnerModifiedTests.cs b/Tests/Runtime/OwnerModifiedTests.cs index cc7b37e..6de84b1 100644 --- a/Tests/Runtime/OwnerModifiedTests.cs +++ b/Tests/Runtime/OwnerModifiedTests.cs @@ -18,6 +18,8 @@ namespace Unity.Netcode.RuntimeTests internal static int Updates = 0; + public static bool EnableVerbose; + private void Awake() { MyNetworkList = new NetworkList(new List(), NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner); @@ -34,7 +36,11 @@ namespace Unity.Netcode.RuntimeTests expected++; listString += i.ToString(); } - Debug.Log($"[{NetworkManager.LocalClientId}] Value changed to {listString}"); + if (EnableVerbose) + { + Debug.Log($"[{NetworkManager.LocalClientId}] Value changed to {listString}"); + } + Updates++; } @@ -68,10 +74,14 @@ namespace Unity.Netcode.RuntimeTests } } + [TestFixture(HostOrServer.DAHost)] + [TestFixture(HostOrServer.Host)] public class OwnerModifiedTests : NetcodeIntegrationTest { protected override int NumberOfClients => 2; + public OwnerModifiedTests(HostOrServer hostOrServer) : base(hostOrServer) { } + protected override void OnCreatePlayerPrefab() { m_PlayerPrefab.AddComponent(); @@ -80,6 +90,7 @@ namespace Unity.Netcode.RuntimeTests [UnityTest] public IEnumerator OwnerModifiedTest() { + OwnerModifiedObject.EnableVerbose = m_EnableVerboseDebug; // We use this to assure we are the "last client" connected. yield return CreateAndStartNewClient(); var ownerModLastClient = m_ClientNetworkManagers[2].LocalClient.PlayerObject.GetComponent(); @@ -89,7 +100,7 @@ namespace Unity.Netcode.RuntimeTests foreach (var updateLoopType in System.Enum.GetValues(typeof(NetworkUpdateStage))) { ownerModLastClient.NetworkUpdateStageToCheck = (NetworkUpdateStage)updateLoopType; - Debug.Log($"Testing Update Stage: {ownerModLastClient.NetworkUpdateStageToCheck}"); + VerboseDebug($"Testing Update Stage: {ownerModLastClient.NetworkUpdateStageToCheck}"); ownerModLastClient.AddValues = true; yield return WaitForTicks(m_ServerNetworkManager, 5); } diff --git a/Tests/Runtime/OwnerPermissionTests.cs b/Tests/Runtime/OwnerPermissionTests.cs index 7bd2816..5f8501d 100644 --- a/Tests/Runtime/OwnerPermissionTests.cs +++ b/Tests/Runtime/OwnerPermissionTests.cs @@ -50,7 +50,7 @@ namespace Unity.Netcode.RuntimeTests public override void OnNetworkSpawn() { Objects[CurrentlySpawning, NetworkManager.LocalClientId] = GetComponent(); - Debug.Log($"Object index ({CurrentlySpawning}) spawned on client {NetworkManager.LocalClientId}"); + //Debug.Log($"Object index ({CurrentlySpawning}) spawned on client {NetworkManager.LocalClientId}"); } private void Awake() @@ -131,7 +131,7 @@ namespace Unity.Netcode.RuntimeTests { // ==== Server-writable NetworkVariable ==== var gotException = false; - Debug.Log($"Writing to server-write variable on object {objectIndex} on client {clientWriting}"); + VerboseDebug($"Writing to server-write variable on object {objectIndex} on client {clientWriting}"); try { @@ -148,7 +148,7 @@ namespace Unity.Netcode.RuntimeTests // ==== Owner-writable NetworkVariable ==== gotException = false; - Debug.Log($"Writing to owner-write variable on object {objectIndex} on client {clientWriting}"); + VerboseDebug($"Writing to owner-write variable on object {objectIndex} on client {clientWriting}"); try { @@ -165,7 +165,6 @@ namespace Unity.Netcode.RuntimeTests // ==== Server-writable NetworkList ==== gotException = false; - Debug.Log($"Writing to server-write list on object {objectIndex} on client {clientWriting}"); try { @@ -182,7 +181,6 @@ namespace Unity.Netcode.RuntimeTests // ==== Owner-writable NetworkList ==== gotException = false; - Debug.Log($"Writing to owner-write list on object {objectIndex} on client {clientWriting}"); try { diff --git a/Tests/Runtime/PeerDisconnectCallbackTests.cs b/Tests/Runtime/PeerDisconnectCallbackTests.cs index 227b72e..f78dbf6 100644 --- a/Tests/Runtime/PeerDisconnectCallbackTests.cs +++ b/Tests/Runtime/PeerDisconnectCallbackTests.cs @@ -133,6 +133,7 @@ namespace Unity.Netcode.RuntimeTests } yield return WaitForConditionOrTimeOut(hooks); + Assert.False(s_GlobalTimeoutHelper.TimedOut); foreach (var client in m_ClientNetworkManagers) @@ -144,18 +145,18 @@ namespace Unity.Netcode.RuntimeTests } if (m_UseHost) { - Assert.IsTrue(client.ConnectedClientsIds.Contains(0ul)); + Assert.IsTrue(client.ConnectedClientsIds.Contains(0ul), $"[Client-{client.LocalClientId}][Connected ({client.IsConnectedClient})] Still has client identifier 0!"); } for (var i = 1ul; i < 3ul; ++i) { if (i == disconnectedClient) { - Assert.IsFalse(client.ConnectedClientsIds.Contains(i)); + Assert.IsFalse(client.ConnectedClientsIds.Contains(i), $"[Client-{client.LocalClientId}][Connected ({client.IsConnectedClient})] Still has client identifier {i}!"); } else { - Assert.IsTrue(client.ConnectedClientsIds.Contains(i)); + Assert.IsTrue(client.ConnectedClientsIds.Contains(i), $"[Client-{client.LocalClientId}][Connected ({client.IsConnectedClient})] Still has client identifier {i}!"); } } } diff --git a/Tests/Runtime/Physics/NetworkRigidbodyTest.cs b/Tests/Runtime/Physics/NetworkRigidbodyTest.cs index cb0b608..0a68e0d 100644 --- a/Tests/Runtime/Physics/NetworkRigidbodyTest.cs +++ b/Tests/Runtime/Physics/NetworkRigidbodyTest.cs @@ -8,16 +8,33 @@ using UnityEngine.TestTools; namespace Unity.Netcode.RuntimeTests { + [TestFixture(RigidbodyInterpolation.Interpolate, true, true)] // This should be allowed under all condistions when using Rigidbody motion + [TestFixture(RigidbodyInterpolation.Extrapolate, true, true)] // This should not allow extrapolation on non-auth instances when using Rigidbody motion & NT interpolation + [TestFixture(RigidbodyInterpolation.Extrapolate, false, true)] // This should allow extrapolation on non-auth instances when using Rigidbody & NT has no interpolation + [TestFixture(RigidbodyInterpolation.Interpolate, true, false)] // This should not allow kinematic instances to have Rigidbody interpolation enabled + [TestFixture(RigidbodyInterpolation.Interpolate, false, false)] // Testing that rigid body interpolation remains the same if NT interpolate is disabled public class NetworkRigidbodyTest : NetcodeIntegrationTest { protected override int NumberOfClients => 1; + private bool m_NetworkTransformInterpolate; + private bool m_UseRigidBodyForMotion; + private RigidbodyInterpolation m_RigidbodyInterpolation; + + public NetworkRigidbodyTest(RigidbodyInterpolation rigidbodyInterpolation, bool networkTransformInterpolate, bool useRigidbodyForMotion) + { + m_RigidbodyInterpolation = rigidbodyInterpolation; + m_NetworkTransformInterpolate = networkTransformInterpolate; + m_UseRigidBodyForMotion = useRigidbodyForMotion; + } protected override void OnCreatePlayerPrefab() { - m_PlayerPrefab.AddComponent(); - m_PlayerPrefab.AddComponent(); - m_PlayerPrefab.AddComponent(); - m_PlayerPrefab.GetComponent().interpolation = RigidbodyInterpolation.Interpolate; + var networkTransform = m_PlayerPrefab.AddComponent(); + networkTransform.Interpolate = m_NetworkTransformInterpolate; + var rigidbody = m_PlayerPrefab.AddComponent(); + rigidbody.interpolation = m_RigidbodyInterpolation; + var networkRigidbody = m_PlayerPrefab.AddComponent(); + networkRigidbody.UseRigidBodyForMotion = m_UseRigidBodyForMotion; } /// @@ -28,39 +45,67 @@ namespace Unity.Netcode.RuntimeTests public IEnumerator TestRigidbodyKinematicEnableDisable() { // This is the *SERVER VERSION* of the *CLIENT PLAYER* - var serverClientPlayerResult = new NetcodeIntegrationTestHelpers.ResultWrapper(); - yield return NetcodeIntegrationTestHelpers.GetNetworkObjectByRepresentation((x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId), m_ServerNetworkManager, serverClientPlayerResult); - var serverPlayer = serverClientPlayerResult.Result.gameObject; + var serverClientPlayerInstance = m_ServerNetworkManager.ConnectedClients[m_ClientNetworkManagers[0].LocalClientId].PlayerObject; // This is the *CLIENT VERSION* of the *CLIENT PLAYER* - var clientClientPlayerResult = new NetcodeIntegrationTestHelpers.ResultWrapper(); - yield return NetcodeIntegrationTestHelpers.GetNetworkObjectByRepresentation((x => x.IsPlayerObject && x.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId), m_ClientNetworkManagers[0], clientClientPlayerResult); - var clientPlayer = clientClientPlayerResult.Result.gameObject; + var clientPlayerInstance = m_ClientNetworkManagers[0].LocalClient.PlayerObject; - Assert.IsNotNull(serverPlayer, "serverPlayer is not null"); - Assert.IsNotNull(clientPlayer, "clientPlayer is not null"); + Assert.IsNotNull(serverClientPlayerInstance, $"{nameof(serverClientPlayerInstance)} is null!"); + Assert.IsNotNull(clientPlayerInstance, $"{nameof(clientPlayerInstance)} is null!"); - yield return WaitForTicks(m_ServerNetworkManager, 3); + var serverClientInstanceRigidBody = serverClientPlayerInstance.GetComponent(); + var clientRigidBody = clientPlayerInstance.GetComponent(); - // server rigidbody has authority and should not be kinematic - Assert.True(serverPlayer.GetComponent().isKinematic == false, "serverPlayer kinematic"); - Assert.AreEqual(RigidbodyInterpolation.Interpolate, serverPlayer.GetComponent().interpolation, "server equal interpolate"); + if (m_UseRigidBodyForMotion) + { + var interpolateCompareNonAuthoritative = m_NetworkTransformInterpolate ? RigidbodyInterpolation.Interpolate : m_RigidbodyInterpolation; - // client rigidbody has no authority and should have a kinematic mode of true - Assert.True(clientPlayer.GetComponent().isKinematic, "clientPlayer kinematic"); - Assert.AreEqual(RigidbodyInterpolation.None, clientPlayer.GetComponent().interpolation, "client equal interpolate"); + // Server authoritative NT should yield non-kinematic mode for the server-side player instance + Assert.False(serverClientInstanceRigidBody.isKinematic, $"[Server-Side] Client-{m_ClientNetworkManagers[0].LocalClientId} player's {nameof(Rigidbody)} is kinematic!"); + + // The authoritative instance can be None, Interpolate, or Extrapolate for the Rigidbody interpolation settings. + Assert.AreEqual(m_RigidbodyInterpolation, serverClientInstanceRigidBody.interpolation, $"[Server-Side] Client-{m_ClientNetworkManagers[0].LocalClientId} " + + $"player's {nameof(Rigidbody)}'s interpolation is {serverClientInstanceRigidBody.interpolation} and not {m_RigidbodyInterpolation}!"); + + // Server authoritative NT should yield kinematic mode for the client-side player instance + Assert.True(clientRigidBody.isKinematic, $"[Client-Side] Client-{m_ClientNetworkManagers[0].LocalClientId} player's {nameof(Rigidbody)} is not kinematic!"); + + // When using Rigidbody motion, authoritative and non-authoritative Rigidbody interpolation settings should be preserved (except when extrapolation is used + Assert.AreEqual(interpolateCompareNonAuthoritative, clientRigidBody.interpolation, $"[Client-Side] Client-{m_ClientNetworkManagers[0].LocalClientId} " + + $"player's {nameof(Rigidbody)}'s interpolation is {clientRigidBody.interpolation} and not {interpolateCompareNonAuthoritative}!"); + } + else + { + // server rigidbody has authority and should not be kinematic + Assert.False(serverClientInstanceRigidBody.isKinematic, $"[Server-Side] Client-{m_ClientNetworkManagers[0].LocalClientId} player's {nameof(Rigidbody)} is kinematic!"); + Assert.AreEqual(RigidbodyInterpolation.Interpolate, serverClientInstanceRigidBody.interpolation, $"[Server-Side] Client-{m_ClientNetworkManagers[0].LocalClientId} " + + $"player's {nameof(Rigidbody)}'s interpolation is {serverClientInstanceRigidBody.interpolation} and not {nameof(RigidbodyInterpolation.Interpolate)}!"); + + // Server authoritative NT should yield kinematic mode for the client-side player instance + Assert.True(clientRigidBody.isKinematic, $"[Client-Side] Client-{m_ClientNetworkManagers[0].LocalClientId} player's {nameof(Rigidbody)} is not kinematic!"); + + // client rigidbody has no authority with NT interpolation disabled should allow Rigidbody interpolation + if (!m_NetworkTransformInterpolate) + { + Assert.AreEqual(RigidbodyInterpolation.Interpolate, clientRigidBody.interpolation, $"[Client-Side] Client-{m_ClientNetworkManagers[0].LocalClientId} " + + $"player's {nameof(Rigidbody)}'s interpolation is {clientRigidBody.interpolation} and not {nameof(RigidbodyInterpolation.Interpolate)}!"); + } + else + { + Assert.AreEqual(RigidbodyInterpolation.None, clientRigidBody.interpolation, $"[Client-Side] Client-{m_ClientNetworkManagers[0].LocalClientId} " + + $"player's {nameof(Rigidbody)}'s interpolation is {clientRigidBody.interpolation} and not {nameof(RigidbodyInterpolation.None)}!"); + } + } // despawn the server player (but keep it around on the server) - serverPlayer.GetComponent().Despawn(false); + serverClientPlayerInstance.Despawn(false); - yield return WaitForTicks(m_ServerNetworkManager, 3); + yield return WaitForConditionOrTimeOut(() => !serverClientPlayerInstance.IsSpawned && !clientPlayerInstance.IsSpawned); + AssertOnTimeout("Timed out waiting for client player to despawn on both server and client!"); // When despawned, we should always be kinematic (i.e. don't apply physics when despawned) - Assert.IsTrue(serverPlayer.GetComponent().isKinematic == true, "serverPlayer second kinematic"); - - yield return WaitForTicks(m_ServerNetworkManager, 3); - - Assert.IsTrue(clientPlayer == null, "clientPlayer being null"); // safety check that object is actually despawned. + Assert.True(serverClientInstanceRigidBody.isKinematic, $"[Server-Side][Despawned] Client-{m_ClientNetworkManagers[0].LocalClientId} player's {nameof(Rigidbody)} is not kinematic when despawned!"); + Assert.IsTrue(clientPlayerInstance == null, $"[Client-Side] Player {nameof(NetworkObject)} is not null!"); } } } diff --git a/Tests/Runtime/PlayerObjectTests.cs b/Tests/Runtime/PlayerObjectTests.cs index bd947f2..2543c4d 100644 --- a/Tests/Runtime/PlayerObjectTests.cs +++ b/Tests/Runtime/PlayerObjectTests.cs @@ -6,6 +6,7 @@ using UnityEngine.TestTools; namespace Unity.Netcode.RuntimeTests { + [TestFixture(HostOrServer.DAHost)] [TestFixture(HostOrServer.Host)] [TestFixture(HostOrServer.Server)] public class PlayerObjectTests : NetcodeIntegrationTest @@ -25,6 +26,8 @@ namespace Unity.Netcode.RuntimeTests [UnityTest] public IEnumerator SpawnAndReplaceExistingPlayerObject() { + yield return WaitForConditionOrTimeOut(() => m_PlayerNetworkObjects[m_ServerNetworkManager.LocalClientId].ContainsKey(m_ClientNetworkManagers[0].LocalClientId)); + AssertOnTimeout("Timed out waiting for client-side player object to spawn!"); // Get the server-side player NetworkObject var originalPlayer = m_PlayerNetworkObjects[m_ServerNetworkManager.LocalClientId][m_ClientNetworkManagers[0].LocalClientId]; // Get the client-side player NetworkObject @@ -33,7 +36,8 @@ namespace Unity.Netcode.RuntimeTests // Create a new player prefab instance var newPlayer = Object.Instantiate(m_NewPlayerToSpawn); var newPlayerNetworkObject = newPlayer.GetComponent(); - newPlayerNetworkObject.NetworkManagerOwner = m_ServerNetworkManager; + // In distributed authority mode, the client owner spawns its new player + newPlayerNetworkObject.NetworkManagerOwner = m_DistributedAuthority ? m_ClientNetworkManagers[0] : m_ServerNetworkManager; // Spawn this instance as a new player object for the client who already has an assigned player object newPlayerNetworkObject.SpawnAsPlayerObject(m_ClientNetworkManagers[0].LocalClientId); diff --git a/Tests/Runtime/RpcTests.cs b/Tests/Runtime/RpcTests.cs index b26d5b2..ecb9337 100644 --- a/Tests/Runtime/RpcTests.cs +++ b/Tests/Runtime/RpcTests.cs @@ -5,7 +5,6 @@ using NUnit.Framework; using Unity.Collections; using Unity.Netcode.TestHelpers.Runtime; using UnityEngine.TestTools; -using Debug = UnityEngine.Debug; using Vector3 = UnityEngine.Vector3; namespace Unity.Netcode.RuntimeTests @@ -121,7 +120,7 @@ namespace Unity.Netcode.RuntimeTests localClienRpcTestNB.OnClient_Rpc += () => { - Debug.Log("ClientRpc received on client object"); + VerboseDebug("ClientRpc received on client object"); hasReceivedClientRpcRemotely = true; }; @@ -139,14 +138,14 @@ namespace Unity.Netcode.RuntimeTests serverClientRpcTestNB.OnServer_Rpc += (clientId, param) => { - Debug.Log("ServerRpc received on server object"); + VerboseDebug("ServerRpc received on server object"); Assert.True(param.Receive.SenderClientId == clientId); hasReceivedServerRpc = true; }; serverClientRpcTestNBFloat.OnServer_Rpc += (clientId, param) => { - Debug.Log("ServerRpc (float) received on server object"); + VerboseDebug("ServerRpc (float) received on server object"); Assert.True(param.Receive.SenderClientId == clientId); hasReceivedFloatServerRpc = true; }; @@ -154,7 +153,7 @@ namespace Unity.Netcode.RuntimeTests serverClientRpcTestNB.OnClient_Rpc += () => { // The RPC invoked locally. (Weaver failure?) - Debug.Log("ClientRpc received on server object"); + VerboseDebug("ClientRpc received on server object"); hasReceivedClientRpcLocally = true; }; @@ -167,7 +166,7 @@ namespace Unity.Netcode.RuntimeTests #endif param4) => { - Debug.Log("TypedServerRpc received on server object"); + VerboseDebug("TypedServerRpc received on server object"); Assert.AreEqual(param1, vector3); Assert.AreEqual(param2.Length, vector3s.Length); Assert.AreEqual(param2[0], vector3s[0]); diff --git a/Tests/Runtime/RpcTypeSerializationTests.cs b/Tests/Runtime/RpcTypeSerializationTests.cs index 9d09d67..3d57e4d 100644 --- a/Tests/Runtime/RpcTypeSerializationTests.cs +++ b/Tests/Runtime/RpcTypeSerializationTests.cs @@ -889,9 +889,9 @@ namespace Unity.Netcode.RuntimeTests clientObject.OnReceived = o => { receivedValue = o; - Debug.Log($"Received value {o}"); + VerboseDebug($"Received value {o}"); }; - Debug.Log($"Sending first RPC with {firstTest}"); + VerboseDebug($"Sending first RPC with {firstTest}"); method.Invoke(serverObject, new object[] { firstTest }); yield return WaitForMessageReceived(m_ClientNetworkManagers.ToList()); @@ -904,7 +904,7 @@ namespace Unity.Netcode.RuntimeTests receivedValue = null; - Debug.Log($"Sending second RPC with {secondTest}"); + VerboseDebug($"Sending second RPC with {secondTest}"); method.Invoke(serverObject, new object[] { secondTest }); yield return WaitForMessageReceived(m_ClientNetworkManagers.ToList()); @@ -943,9 +943,9 @@ namespace Unity.Netcode.RuntimeTests clientObject.OnReceived = o => { receivedValue = o; - Debug.Log($"Received value {o}"); + VerboseDebug($"Received value {o}"); }; - Debug.Log($"Sending first RPC with {firstTest}"); + VerboseDebug($"Sending first RPC with {firstTest}"); method.Invoke(serverObject, new object[] { firstTest }); yield return WaitForMessageReceived(m_ClientNetworkManagers.ToList()); @@ -958,7 +958,7 @@ namespace Unity.Netcode.RuntimeTests receivedValue = null; - Debug.Log($"Sending second RPC with {secondTest}"); + VerboseDebug($"Sending second RPC with {secondTest}"); method.Invoke(serverObject, new object[] { secondTest }); yield return WaitForMessageReceived(m_ClientNetworkManagers.ToList()); @@ -1005,9 +1005,9 @@ namespace Unity.Netcode.RuntimeTests Assert.AreEqual(o.GetType(), typeof(NativeArray)); var oAsArray = (NativeArray)o; receivedValue = new NativeArray(oAsArray, Allocator.Persistent); - Debug.Log($"Received value {o}"); + VerboseDebug($"Received value {o}"); }; - Debug.Log($"Sending first RPC with {firstTest}"); + VerboseDebug($"Sending first RPC with {firstTest}"); method.Invoke(serverObject, new object[] { firstTest }); yield return WaitForMessageReceived(m_ClientNetworkManagers.ToList()); @@ -1020,7 +1020,7 @@ namespace Unity.Netcode.RuntimeTests receivedValue = new NativeArray(); - Debug.Log($"Sending second RPC with {secondTest}"); + VerboseDebug($"Sending second RPC with {secondTest}"); method.Invoke(serverObject, new object[] { secondTest }); yield return WaitForMessageReceived(m_ClientNetworkManagers.ToList()); @@ -1066,9 +1066,9 @@ namespace Unity.Netcode.RuntimeTests { receivedValue.Add(item); } - Debug.Log($"Received value {o}"); + VerboseDebug($"Received value {o}"); }; - Debug.Log($"Sending first RPC with {firstTest}"); + VerboseDebug($"Sending first RPC with {firstTest}"); method.Invoke(serverObject, new object[] { firstTest }); yield return WaitForMessageReceived(m_ClientNetworkManagers.ToList()); @@ -1081,7 +1081,7 @@ namespace Unity.Netcode.RuntimeTests receivedValue = new NativeList(); - Debug.Log($"Sending second RPC with {secondTest}"); + VerboseDebug($"Sending second RPC with {secondTest}"); method.Invoke(serverObject, new object[] { secondTest }); yield return WaitForMessageReceived(m_ClientNetworkManagers.ToList()); diff --git a/Tests/Runtime/Timing/TimeInitializationTest.cs b/Tests/Runtime/Timing/TimeInitializationTest.cs index cbd7b99..fe7d935 100644 --- a/Tests/Runtime/Timing/TimeInitializationTest.cs +++ b/Tests/Runtime/Timing/TimeInitializationTest.cs @@ -80,7 +80,7 @@ namespace Unity.Netcode.RuntimeTests private void NetworkTickSystemOnTick() { - Debug.Log(m_Client.NetworkTickSystem.ServerTime.Tick); + //Debug.Log(m_Client.NetworkTickSystem.ServerTime.Tick); m_ClientTickCounter++; } @@ -88,7 +88,7 @@ namespace Unity.Netcode.RuntimeTests { // client connected to server m_ConnectedTick = m_Client.NetworkTickSystem.ServerTime.Tick; - Debug.Log($"Connected tick: {m_ConnectedTick}"); + //Debug.Log($"Connected tick: {m_ConnectedTick}"); } [UnityTearDown] diff --git a/Tests/Runtime/Timing/TimeIntegrationTest.cs b/Tests/Runtime/Timing/TimeIntegrationTest.cs index a04430d..e019bb2 100644 --- a/Tests/Runtime/Timing/TimeIntegrationTest.cs +++ b/Tests/Runtime/Timing/TimeIntegrationTest.cs @@ -1,6 +1,6 @@ +#if !MULTIPLAYER_TOOLS using System; using System.Collections; -using System.Linq; using NUnit.Framework; using Unity.Netcode.TestHelpers.Runtime; using UnityEngine; @@ -13,7 +13,7 @@ namespace Unity.Netcode.RuntimeTests /// public class TimeIntegrationTest : NetcodeIntegrationTest { - private const double k_AdditionalTimeTolerance = 0.3d; // magic number and in theory not needed but without this mac os test fail in Yamato because it looks like we get random framerate drops during unit test. + private const double k_AdditionalTimeTolerance = 0.3333d; // magic number and in theory not needed but without this mac os test fail in Yamato because it looks like we get random framerate drops during unit test. private NetworkTimeState m_ServerState; private NetworkTimeState m_Client1State; @@ -26,17 +26,11 @@ namespace Unity.Netcode.RuntimeTests return NetworkManagerInstatiationMode.DoNotCreate; } - private void UpdateTimeStates(NetworkManager[] networkManagers) + private void UpdateTimeStates() { - var server = networkManagers.First(t => t.IsServer); - var firstClient = networkManagers.First(t => t.IsClient); - var secondClient = networkManagers.Last(t => t.IsClient); - - Assert.AreNotEqual(firstClient, secondClient); - - m_ServerState = new NetworkTimeState(server); - m_Client1State = new NetworkTimeState(firstClient); - m_Client2State = new NetworkTimeState(secondClient); + m_ServerState = new NetworkTimeState(m_ServerNetworkManager); + m_Client1State = new NetworkTimeState(m_ClientNetworkManagers[0]); + m_Client2State = new NetworkTimeState(m_ClientNetworkManagers[1]); } [UnityTest] @@ -61,26 +55,21 @@ namespace Unity.Netcode.RuntimeTests double frameInterval = 1d / targetFrameRate; double tickInterval = 1d / tickRate; - var networkManagers = NetcodeIntegrationTestHelpers.NetworkManagerInstances.ToArray(); - - var server = networkManagers.First(t => t.IsServer); - var firstClient = networkManagers.First(t => !t.IsServer); - var secondClient = networkManagers.Last(t => !t.IsServer); - - Assert.AreNotEqual(firstClient, secondClient); + var server = m_ServerNetworkManager; + var firstClient = m_ClientNetworkManagers[0]; + var secondClient = m_ClientNetworkManagers[1]; // increase the buffer time of client 2 // the values for client 1 are 0.0333/0.0333 here secondClient.NetworkTimeSystem.LocalBufferSec = 0.2; secondClient.NetworkTimeSystem.ServerBufferSec = 0.1; - UpdateTimeStates(networkManagers); - - - // wait for at least one tick to pass - yield return new WaitUntil(() => m_ServerState.LocalTime.Tick != server.NetworkTickSystem.LocalTime.Tick); - yield return new WaitUntil(() => m_Client1State.LocalTime.Tick != firstClient.NetworkTickSystem.LocalTime.Tick); - yield return new WaitUntil(() => m_Client2State.LocalTime.Tick != secondClient.NetworkTickSystem.LocalTime.Tick); + UpdateTimeStates(); + // wait for a few ticks to pass + for (int i = 0; i < 4; i++) + { + yield return s_DefaultWaitForTick; + } var framesToRun = 3d / frameInterval; @@ -103,7 +92,7 @@ namespace Unity.Netcode.RuntimeTests currentAdjustment += additionalTimeTolerance * fpsAdjustment; } - UpdateTimeStates(networkManagers); + UpdateTimeStates(); // compares whether client times have the correct offset to server m_ServerState.AssertCheckDifference(m_Client1State, tickInterval, tickInterval, tickInterval * 2 + frameInterval * 2 + currentAdjustment); @@ -211,3 +200,4 @@ namespace Unity.Netcode.RuntimeTests } } } +#endif diff --git a/Tests/Runtime/TransformInterpolationTests.cs b/Tests/Runtime/TransformInterpolationTests.cs index 48f0472..ac64d2c 100644 --- a/Tests/Runtime/TransformInterpolationTests.cs +++ b/Tests/Runtime/TransformInterpolationTests.cs @@ -1,3 +1,4 @@ +#if !MULTIPLAYER_TOOLS using System.Collections; using NUnit.Framework; using Unity.Netcode.Components; @@ -221,8 +222,9 @@ namespace Unity.Netcode.RuntimeTests // and how they move var timeOutHelper = new TimeoutFrameCountHelper(10); yield return WaitForConditionOrTimeOut(spawnedObjectNetworkTransform.ReachedTargetLocalSpaceTransitionCount, timeOutHelper); - Debug.Log($"[TransformInterpolationTest] Wait condition reached or timed out. Frame Count ({timeOutHelper.GetFrameCount()}) | Time Elapsed ({timeOutHelper.GetTimeElapsed()})"); + VerboseDebug($"[TransformInterpolationTest] Wait condition reached or timed out. Frame Count ({timeOutHelper.GetFrameCount()}) | Time Elapsed ({timeOutHelper.GetTimeElapsed()})"); AssertOnTimeout($"Failed to reach desired local to world space transitions in the given time!", timeOutHelper); } } } +#endif diff --git a/Tests/Runtime/UniversalRpcTests.cs b/Tests/Runtime/UniversalRpcTests.cs index 49a1e47..a756bd7 100644 --- a/Tests/Runtime/UniversalRpcTests.cs +++ b/Tests/Runtime/UniversalRpcTests.cs @@ -1,3 +1,4 @@ +#if !MULTIPLAYER_TOOLS && !NGO_MINIMALPROJECT using System; using System.Collections.Generic; using System.Diagnostics; @@ -24,6 +25,7 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests public string Received = string.Empty; public Tuple ReceivedParams = null; public ulong ReceivedFrom = ulong.MaxValue; + public int ReceivedCount; public void OnRpcReceived() { @@ -32,6 +34,7 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests var currentMethod = sf.GetMethod(); Received = currentMethod.Name; + ReceivedCount++; } public void OnRpcReceivedWithParams(int a, bool b, float f, string s) { @@ -40,6 +43,7 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests var currentMethod = sf.GetMethod(); Received = currentMethod.Name; + ReceivedCount++; ReceivedParams = new Tuple(a, b, f, s); } @@ -93,6 +97,18 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests OnRpcReceived(); } + [Rpc(SendTo.Authority)] + public void DefaultToAuthorityRpc() + { + OnRpcReceived(); + } + + [Rpc(SendTo.NotAuthority)] + public void DefaultToNotAuthorityRpc() + { + OnRpcReceived(); + } + // RPCs with parameters [Rpc(SendTo.Everyone)] @@ -143,6 +159,18 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests OnRpcReceivedWithParams(i, b, f, s); } + [Rpc(SendTo.Authority)] + public void DefaultToAuthorityWithParamsRpc(int i, bool b, float f, string s) + { + OnRpcReceivedWithParams(i, b, f, s); + } + + [Rpc(SendTo.NotAuthority)] + public void DefaultToNotAuthorityWithParamsRpc(int i, bool b, float f, string s) + { + OnRpcReceivedWithParams(i, b, f, s); + } + // RPCs with RPC parameters [Rpc(SendTo.Everyone)] @@ -201,6 +229,19 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests ReceivedFrom = rpcParams.Receive.SenderClientId; } + [Rpc(SendTo.Authority)] + public void DefaultToAuthorityWithRpcParamsRpc(RpcParams rpcParams) + { + OnRpcReceived(); + ReceivedFrom = rpcParams.Receive.SenderClientId; + } + + [Rpc(SendTo.NotAuthority)] + public void DefaultToNotAuthorityWithRpcParamsRpc(RpcParams rpcParams) + { + OnRpcReceived(); + ReceivedFrom = rpcParams.Receive.SenderClientId; + } // RPCs with parameters and RPC parameters @@ -252,6 +293,18 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests OnRpcReceivedWithParams(i, b, f, s); } + [Rpc(SendTo.Authority)] + public void DefaultToAuthorityWithParamsAndRpcParamsRpc(int i, bool b, float f, string s, RpcParams rpcParams) + { + OnRpcReceivedWithParams(i, b, f, s); + } + + [Rpc(SendTo.NotAuthority)] + public void DefaultToNotAuthorityWithParamsAndRpcParamsRpc(int i, bool b, float f, string s, RpcParams rpcParams) + { + OnRpcReceivedWithParams(i, b, f, s); + } + // RPCs with AllowTargetOverride = true // AllowTargetOverried is implied with SpecifiedInParams and does not need to be stated @@ -310,6 +363,18 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests OnRpcReceived(); } + [Rpc(SendTo.Authority, AllowTargetOverride = true)] + public void DefaultToAuthorityAllowOverrideRpc(RpcParams rpcParams) + { + OnRpcReceived(); + } + + [Rpc(SendTo.NotAuthority, AllowTargetOverride = true)] + public void DefaultToNotAuthorityAllowOverrideRpc(RpcParams rpcParams) + { + OnRpcReceived(); + } + // RPCs with DeferLocal = true [Rpc(SendTo.Everyone, DeferLocal = true)] @@ -354,6 +419,18 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests OnRpcReceived(); } + [Rpc(SendTo.Authority, DeferLocal = true)] + public void DefaultToAuthorityDeferLocalRpc(RpcParams rpcParams) + { + OnRpcReceived(); + } + + [Rpc(SendTo.NotAuthority, DeferLocal = true)] + public void DefaultToNotAuthorityDeferLocalRpc(RpcParams rpcParams) + { + OnRpcReceived(); + } + // RPCs with RequireOwnership = true [Rpc(SendTo.Everyone, RequireOwnership = true)] @@ -410,6 +487,17 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests OnRpcReceived(); } + [Rpc(SendTo.Authority, RequireOwnership = true)] + public void DefaultToAuthorityRequireOwnershipRpc() + { + OnRpcReceived(); + } + + [Rpc(SendTo.NotAuthority, RequireOwnership = true)] + public void DefaultToNotAuthorityRequireOwnershipRpc() + { + OnRpcReceived(); + } // Mutual RPC Recursion @@ -496,6 +584,7 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests foreach (var obj in Object.FindObjectsByType(FindObjectsSortMode.None)) { obj.Received = string.Empty; + obj.ReceivedCount = 0; obj.ReceivedParams = null; obj.ReceivedFrom = ulong.MaxValue; } @@ -528,10 +617,11 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests return m_PlayerNetworkObjects[onClient][ownerClientId].GetComponent(); } - protected void VerifyLocalReceived(ulong objectOwner, ulong sender, string name, bool verifyReceivedFrom) + protected void VerifyLocalReceived(ulong objectOwner, ulong sender, string name, bool verifyReceivedFrom, int expectedReceived = 1) { var obj = GetPlayerObject(objectOwner, sender); Assert.AreEqual(name, obj.Received); + Assert.That(obj.ReceivedCount, Is.EqualTo(expectedReceived)); Assert.IsNull(obj.ReceivedParams); if (verifyReceivedFrom) { @@ -543,6 +633,7 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests { var obj = GetPlayerObject(objectOwner, sender); Assert.AreEqual(name, obj.Received); + Assert.That(obj.ReceivedCount, Is.EqualTo(1)); Assert.IsNotNull(obj.ReceivedParams); Assert.AreEqual(i, obj.ReceivedParams.Item1); Assert.AreEqual(b, obj.ReceivedParams.Item2); @@ -556,17 +647,18 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests { UniversalRpcNetworkBehaviour playerObject = GetPlayerObject(objectOwner, client); Assert.AreEqual(string.Empty, playerObject.Received); + Assert.That(playerObject.ReceivedCount, Is.EqualTo(0)); Assert.IsNull(playerObject.ReceivedParams); } } - protected void VerifyRemoteReceived(ulong objectOwner, ulong sender, string message, ulong[] receivedBy, bool verifyReceivedFrom, bool waitForMessages = true) + protected void VerifyRemoteReceived(ulong objectOwner, ulong sender, string message, ulong[] receivedBy, bool verifyReceivedFrom, bool waitForMessages = true, int expectedReceived = 1) { foreach (var client in receivedBy) { if (client == sender) { - VerifyLocalReceived(objectOwner, sender, message, verifyReceivedFrom); + VerifyLocalReceived(objectOwner, sender, message, verifyReceivedFrom, expectedReceived); break; } @@ -628,6 +720,7 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests { UniversalRpcNetworkBehaviour playerObject = GetPlayerObject(objectOwner, client); Assert.AreEqual(message, playerObject.Received); + Assert.That(playerObject.ReceivedCount, Is.EqualTo(expectedReceived)); Assert.IsNull(playerObject.ReceivedParams); if (verifyReceivedFrom) { @@ -701,6 +794,7 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests { UniversalRpcNetworkBehaviour playerObject = GetPlayerObject(objectOwner, client); Assert.AreEqual(message, playerObject.Received); + Assert.That(playerObject.ReceivedCount, Is.EqualTo(1)); Assert.IsNotNull(playerObject.ReceivedParams); Assert.AreEqual(i, playerObject.ReceivedParams.Item1); @@ -805,6 +899,26 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests VerifySentToNotId(objectOwner, sender, sender, methodName, false); } + public void VerifySentToAuthority(ulong objectOwner, ulong sender, string methodName) + { + var receiver = objectOwner; + if (!m_DistributedAuthority) + { + receiver = NetworkManager.ServerClientId; + } + VerifySentToId(objectOwner, sender, receiver, methodName, false); + } + + public void VerifySentToNotAuthority(ulong objectOwner, ulong sender, string methodName) + { + var receiver = objectOwner; + if (!m_DistributedAuthority) + { + receiver = NetworkManager.ServerClientId; + } + VerifySentToNotId(objectOwner, sender, receiver, methodName, false); + } + public void VerifySentToOwnerWithReceivedFrom(ulong objectOwner, ulong sender, string methodName) { VerifySentToId(objectOwner, sender, objectOwner, methodName, true); @@ -847,6 +961,26 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests VerifySentToNotId(objectOwner, sender, sender, methodName, true); } + public void VerifySentToAuthorityWithReceivedFrom(ulong objectOwner, ulong sender, string methodName) + { + var receiver = objectOwner; + if (!m_DistributedAuthority) + { + receiver = NetworkManager.ServerClientId; + } + VerifySentToId(objectOwner, sender, receiver, methodName, true); + } + + public void VerifySentToNotAuthorityWithReceivedFrom(ulong objectOwner, ulong sender, string methodName) + { + var receiver = objectOwner; + if (!m_DistributedAuthority) + { + receiver = NetworkManager.ServerClientId; + } + VerifySentToNotId(objectOwner, sender, receiver, methodName, true); + } + public void VerifySentToOwnerWithParams(ulong objectOwner, ulong sender, string methodName, int i, bool b, float f, string s) { VerifySentToIdWithParams(objectOwner, sender, objectOwner, methodName, i, b, f, s); @@ -889,6 +1023,26 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests VerifySentToNotIdWithParams(objectOwner, sender, sender, methodName, i, b, f, s); } + public void VerifySentToAuthorityWithParams(ulong objectOwner, ulong sender, string methodName, int i, bool b, float f, string s) + { + var receiver = objectOwner; + if (!m_DistributedAuthority) + { + receiver = NetworkManager.ServerClientId; + } + VerifySentToIdWithParams(objectOwner, sender, receiver, methodName, i, b, f, s); + } + + public void VerifySentToNotAuthorityWithParams(ulong objectOwner, ulong sender, string methodName, int i, bool b, float f, string s) + { + var receiver = objectOwner; + if (!m_DistributedAuthority) + { + receiver = NetworkManager.ServerClientId; + } + VerifySentToNotIdWithParams(objectOwner, sender, receiver, methodName, i, b, f, s); + } + public void RethrowTargetInvocationException(Action action) { try @@ -902,6 +1056,7 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests } } + [TestFixture(HostOrServer.DAHost)] [TestFixture(HostOrServer.Host)] [TestFixture(HostOrServer.Server)] internal class UniversalRpcTestSendingNoOverride : UniversalRpcTestsBase @@ -914,7 +1069,8 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests [Test] public void TestSendingNoOverride( // Excludes SendTo.SpecifiedInParams - [Values(SendTo.Everyone, SendTo.Me, SendTo.Owner, SendTo.Server, SendTo.NotMe, SendTo.NotOwner, SendTo.NotServer, SendTo.ClientsAndHost)] SendTo sendTo, + [Values(SendTo.Everyone, SendTo.Me, SendTo.Owner, SendTo.Server, SendTo.NotMe, SendTo.NotOwner, SendTo.NotServer, + SendTo.ClientsAndHost, SendTo.Authority, SendTo.NotAuthority)] SendTo sendTo, [Values(0u, 1u, 2u)] ulong objectOwner, [Values(0u, 1u, 2u)] ulong sender ) @@ -932,6 +1088,7 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests } + [TestFixture(HostOrServer.DAHost)] [TestFixture(HostOrServer.Host)] [TestFixture(HostOrServer.Server)] internal class UniversalRpcTestSenderClientId : UniversalRpcTestsBase @@ -944,7 +1101,7 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests [Test] public void TestSenderClientId( // Excludes SendTo.SpecifiedInParams - [Values(SendTo.Everyone, SendTo.Me, SendTo.Owner, SendTo.Server, SendTo.NotMe, SendTo.NotOwner, SendTo.NotServer, SendTo.ClientsAndHost)] SendTo sendTo, + [Values(SendTo.Everyone, SendTo.Me, SendTo.Owner, SendTo.Server, SendTo.NotMe, SendTo.NotOwner, SendTo.NotServer, SendTo.ClientsAndHost, SendTo.Authority, SendTo.NotAuthority)] SendTo sendTo, [Values(0u, 1u, 2u)] ulong objectOwner, [Values(0u, 1u, 2u)] ulong sender ) @@ -962,6 +1119,7 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests } + [TestFixture(HostOrServer.DAHost)] [TestFixture(HostOrServer.Host)] [TestFixture(HostOrServer.Server)] internal class UniversalRpcTestSendingNoOverrideWithParams : UniversalRpcTestsBase @@ -974,7 +1132,7 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests [Test] public void TestSendingNoOverrideWithParams( // Excludes SendTo.SpecifiedInParams - [Values(SendTo.Everyone, SendTo.Me, SendTo.Owner, SendTo.Server, SendTo.NotMe, SendTo.NotOwner, SendTo.NotServer, SendTo.ClientsAndHost)] SendTo sendTo, + [Values(SendTo.Everyone, SendTo.Me, SendTo.Owner, SendTo.Server, SendTo.NotMe, SendTo.NotOwner, SendTo.NotServer, SendTo.ClientsAndHost, SendTo.Authority, SendTo.NotAuthority)] SendTo sendTo, [Values(0u, 1u, 2u)] ulong objectOwner, [Values(0u, 1u, 2u)] ulong sender ) @@ -1004,6 +1162,7 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests } + [TestFixture(HostOrServer.DAHost)] [TestFixture(HostOrServer.Host)] [TestFixture(HostOrServer.Server)] internal class UniversalRpcTestSendingNoOverrideWithParamsAndRpcParams : UniversalRpcTestsBase @@ -1016,7 +1175,7 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests [Test] public void TestSendingNoOverrideWithParamsAndRpcParams( // Excludes SendTo.SpecifiedInParams - [Values(SendTo.Everyone, SendTo.Me, SendTo.Owner, SendTo.Server, SendTo.NotMe, SendTo.NotOwner, SendTo.NotServer, SendTo.ClientsAndHost)] SendTo sendTo, + [Values(SendTo.Everyone, SendTo.Me, SendTo.Owner, SendTo.Server, SendTo.NotMe, SendTo.NotOwner, SendTo.NotServer, SendTo.ClientsAndHost, SendTo.Authority, SendTo.NotAuthority)] SendTo sendTo, [Values(0u, 1u, 2u)] ulong objectOwner, [Values(0u, 1u, 2u)] ulong sender ) @@ -1046,6 +1205,8 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests } + + [TestFixture(HostOrServer.DAHost)] [TestFixture(HostOrServer.Host)] [TestFixture(HostOrServer.Server)] internal class UniversalRpcTestRequireOwnership : UniversalRpcTestsBase @@ -1058,7 +1219,7 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests [Test] public void TestRequireOwnership( // Excludes SendTo.SpecifiedInParams - [Values(SendTo.Everyone, SendTo.Me, SendTo.Owner, SendTo.Server, SendTo.NotMe, SendTo.NotOwner, SendTo.NotServer, SendTo.ClientsAndHost)] SendTo sendTo, + [Values(SendTo.Everyone, SendTo.Me, SendTo.Owner, SendTo.Server, SendTo.NotMe, SendTo.NotOwner, SendTo.NotServer, SendTo.ClientsAndHost, SendTo.Authority, SendTo.NotAuthority)] SendTo sendTo, [Values(0u, 1u, 2u)] ulong objectOwner, [Values(0u, 1u, 2u)] ulong sender ) @@ -1082,6 +1243,7 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests } } + [TestFixture(HostOrServer.DAHost)] [TestFixture(HostOrServer.Host)] [TestFixture(HostOrServer.Server)] internal class UniversalRpcTestDisallowedOverride : UniversalRpcTestsBase @@ -1091,10 +1253,11 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests } + // Add both authority and nonauthority [Test] public void TestDisallowedOverride( // Excludes SendTo.SpecifiedInParams - [Values(SendTo.Everyone, SendTo.Me, SendTo.Owner, SendTo.Server, SendTo.NotMe, SendTo.NotOwner, SendTo.NotServer, SendTo.ClientsAndHost)] SendTo sendTo, + [Values(SendTo.Everyone, SendTo.Me, SendTo.Owner, SendTo.Server, SendTo.NotMe, SendTo.NotOwner, SendTo.NotServer, SendTo.ClientsAndHost, SendTo.Authority, SendTo.NotAuthority)] SendTo sendTo, [Values(0u, 1u, 2u)] ulong objectOwner, [Values(0u, 1u, 2u)] ulong sender) { @@ -1126,6 +1289,7 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests } + // Look at the implementations and add both [Test] public void TestSendingWithTargetOverride( [Values] SendTo defaultSendTo, @@ -1382,6 +1546,7 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests } } + [TestFixture(HostOrServer.DAHost)] [TestFixture(HostOrServer.Host)] [TestFixture(HostOrServer.Server)] internal class UniversalRpcTestDeferLocal : UniversalRpcTestsBase @@ -1438,6 +1603,15 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests [TestCase(SendTo.ClientsAndHost, 2u, 0u)] [TestCase(SendTo.ClientsAndHost, 2u, 1u)] [TestCase(SendTo.ClientsAndHost, 2u, 2u)] + [TestCase(SendTo.Authority, 0u, 0u)] + [TestCase(SendTo.Authority, 1u, 1u)] + [TestCase(SendTo.Authority, 2u, 2u)] + [TestCase(SendTo.NotAuthority, 0u, 1u)] + [TestCase(SendTo.NotAuthority, 0u, 2u)] + [TestCase(SendTo.NotAuthority, 1u, 0u)] + [TestCase(SendTo.NotAuthority, 1u, 2u)] + [TestCase(SendTo.NotAuthority, 2u, 0u)] + [TestCase(SendTo.NotAuthority, 2u, 1u)] public void TestDeferLocal( SendTo defaultSendTo, ulong objectOwner, @@ -1450,6 +1624,13 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests // Just consider this case a success... return; } + + // Similar to above, since Server and NotServer are already tested we can consider this a success + if (!m_DistributedAuthority && defaultSendTo == SendTo.Authority || defaultSendTo == SendTo.NotAuthority) + { + return; + } + var sendMethodName = $"DefaultTo{defaultSendTo}DeferLocalRpc"; var verifyMethodName = $"VerifySentTo{defaultSendTo}"; var senderObject = GetPlayerObject(objectOwner, sender); @@ -1512,6 +1693,15 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests [TestCase(SendTo.ClientsAndHost, 2u, 0u)] [TestCase(SendTo.ClientsAndHost, 2u, 1u)] [TestCase(SendTo.ClientsAndHost, 2u, 2u)] + [TestCase(SendTo.Authority, 0u, 0u)] + [TestCase(SendTo.Authority, 1u, 1u)] + [TestCase(SendTo.Authority, 2u, 2u)] + [TestCase(SendTo.NotAuthority, 0u, 1u)] + [TestCase(SendTo.NotAuthority, 0u, 2u)] + [TestCase(SendTo.NotAuthority, 1u, 0u)] + [TestCase(SendTo.NotAuthority, 1u, 2u)] + [TestCase(SendTo.NotAuthority, 2u, 0u)] + [TestCase(SendTo.NotAuthority, 2u, 1u)] public void TestDeferLocalOverrideToTrue( SendTo defaultSendTo, ulong objectOwner, @@ -1524,6 +1714,12 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests // Just consider this case a success... return; } + // Similar to above, since Server and NotServer are already tested we can consider this a success + if (!m_DistributedAuthority && defaultSendTo == SendTo.Authority || defaultSendTo == SendTo.NotAuthority) + { + return; + } + var sendMethodName = $"DefaultTo{defaultSendTo}WithRpcParamsRpc"; var verifyMethodName = $"VerifySentTo{defaultSendTo}"; var senderObject = GetPlayerObject(objectOwner, sender); @@ -1586,6 +1782,15 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests [TestCase(SendTo.ClientsAndHost, 2u, 0u)] [TestCase(SendTo.ClientsAndHost, 2u, 1u)] [TestCase(SendTo.ClientsAndHost, 2u, 2u)] + [TestCase(SendTo.Authority, 0u, 0u)] + [TestCase(SendTo.Authority, 1u, 1u)] + [TestCase(SendTo.Authority, 2u, 2u)] + [TestCase(SendTo.NotAuthority, 0u, 1u)] + [TestCase(SendTo.NotAuthority, 0u, 2u)] + [TestCase(SendTo.NotAuthority, 1u, 0u)] + [TestCase(SendTo.NotAuthority, 1u, 2u)] + [TestCase(SendTo.NotAuthority, 2u, 0u)] + [TestCase(SendTo.NotAuthority, 2u, 1u)] public void TestDeferLocalOverrideToFalse( SendTo defaultSendTo, ulong objectOwner, @@ -1598,6 +1803,12 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests // Just consider this case a success... return; } + // Similar to above, since Server and NotServer are already tested we can consider this a success + if (!m_DistributedAuthority && defaultSendTo == SendTo.Authority || defaultSendTo == SendTo.NotAuthority) + { + return; + } + var sendMethodName = $"DefaultTo{defaultSendTo}DeferLocalRpc"; var verifyMethodName = $"VerifySentTo{defaultSendTo}"; var senderObject = GetPlayerObject(objectOwner, sender); @@ -1636,17 +1847,20 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests VerifyNotReceived(NetworkManager.ServerClientId, s_ClientIds); - for (var i = 0; i < 10; ++i) + var clientListExpected = 1; + var serverListExpected = 2; + for (var i = 1; i <= 10; ++i) { WaitForMessageReceivedWithTimeTravel(clientList); - VerifyRemoteReceived(NetworkManager.ServerClientId, NetworkManager.ServerClientId, nameof(UniversalRpcNetworkBehaviour.MutualRecursionClientRpc), clientIdArray, false, false); + VerifyRemoteReceived(NetworkManager.ServerClientId, NetworkManager.ServerClientId, nameof(UniversalRpcNetworkBehaviour.MutualRecursionClientRpc), clientIdArray, false, false, clientListExpected); VerifyNotReceived(NetworkManager.ServerClientId, serverIdArray); + clientListExpected *= 2; Clear(); - WaitForMessageReceivedWithTimeTravel(serverList); - VerifyRemoteReceived(NetworkManager.ServerClientId, NetworkManager.ServerClientId, nameof(UniversalRpcNetworkBehaviour.MutualRecursionServerRpc), serverIdArray, false, false); + VerifyRemoteReceived(NetworkManager.ServerClientId, NetworkManager.ServerClientId, nameof(UniversalRpcNetworkBehaviour.MutualRecursionServerRpc), serverIdArray, false, false, serverListExpected); VerifyNotReceived(NetworkManager.ServerClientId, clientIdArray); + serverListExpected *= 2; Clear(); } @@ -1915,3 +2129,4 @@ namespace Unity.Netcode.RuntimeTests.UniversalRpcTests } } +#endif diff --git a/Tests/Runtime/com.unity.netcode.runtimetests.asmdef b/Tests/Runtime/com.unity.netcode.runtimetests.asmdef index 719b7be..72d85ca 100644 --- a/Tests/Runtime/com.unity.netcode.runtimetests.asmdef +++ b/Tests/Runtime/com.unity.netcode.runtimetests.asmdef @@ -12,12 +12,20 @@ "Unity.Networking.Transport", "ClientNetworkTransform", "Unity.Netcode.TestHelpers.Runtime", - "Unity.Mathematics" + "Unity.Mathematics", + "UnityEngine.TestRunner", + "UnityEditor.TestRunner" ], - "optionalUnityReferences": [ - "TestAssemblies" + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": true, + "overrideReferences": true, + "precompiledReferences": [ + "nunit.framework.dll" ], + "autoReferenced": false, "defineConstraints": [ + "UNITY_INCLUDE_TESTS", "UNITY_INCLUDE_TESTS" ], "versionDefines": [ @@ -46,5 +54,6 @@ "expression": "2.0.0-exp", "define": "UTP_TRANSPORT_2_0_ABOVE" } - ] -} + ], + "noEngineReferences": false +} \ No newline at end of file diff --git a/ValidationExceptions.json b/ValidationExceptions.json index 2d81612..9128292 100644 --- a/ValidationExceptions.json +++ b/ValidationExceptions.json @@ -1,10 +1,4 @@ { - "ErrorExceptions": [ - { - "ValidationTest": "API Validation", - "ExceptionMessage": "Additions require a new minor or major version.", - "PackageVersion": "1.5.2" - } - ], + "ErrorExceptions": [], "WarningExceptions": [] -} \ No newline at end of file +} diff --git a/package.json b/package.json index 9774cf1..075b69c 100644 --- a/package.json +++ b/package.json @@ -2,23 +2,23 @@ "name": "com.unity.netcode.gameobjects", "displayName": "Netcode for GameObjects", "description": "Netcode for GameObjects is a high-level netcode SDK that provides networking capabilities to GameObject/MonoBehaviour workflows within Unity and sits on top of underlying transport layer.", - "version": "1.8.1", - "unity": "2021.3", + "version": "2.0.0-exp.2", + "unity": "6000.0", "dependencies": { - "com.unity.nuget.mono-cecil": "1.10.1", - "com.unity.transport": "1.4.0" + "com.unity.nuget.mono-cecil": "1.11.4", + "com.unity.transport": "2.2.1" }, "_upm": { - "changelog": "### Fixed\n\n- Fixed a compile error when compiling for IL2CPP targets when using the new `[Rpc]` attribute. (#2824)" + "changelog": "### Added\n- Added updates to all internal messages to account for a distributed authority network session connection. (#2863)\n- Added `NetworkRigidbodyBase` that provides users with a more customizable network rigidbody, handles both `Rigidbody` and `Rigidbody2D`, and provides an option to make `NetworkTransform` use the rigid body for motion. (#2863)\n - For a customized `NetworkRigidbodyBase` class:\n - `NetworkRigidbodyBase.AutoUpdateKinematicState` provides control on whether the kinematic setting will be automatically set or not when ownership changes.\n - `NetworkRigidbodyBase.AutoSetKinematicOnDespawn` provides control on whether isKinematic will automatically be set to true when the associated `NetworkObject` is despawned.\n - `NetworkRigidbodyBase.Initialize` is a protected method that, when invoked, will initialize the instance. This includes options to:\n - Set whether using a `RigidbodyTypes.Rigidbody` or `RigidbodyTypes.Rigidbody2D`.\n - Includes additional optional parameters to set the `NetworkTransform`, `Rigidbody`, and `Rigidbody2d` to use.\n - Provides additional public methods:\n - `NetworkRigidbodyBase.GetPosition` to return the position of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).\n - `NetworkRigidbodyBase.GetRotation` to return the rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).\n - `NetworkRigidbodyBase.MovePosition` to move to the position of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).\n - `NetworkRigidbodyBase.MoveRotation` to move to the rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).\n - `NetworkRigidbodyBase.Move` to move to the position and rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).\n - `NetworkRigidbodyBase.Move` to move to the position and rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).\n - `NetworkRigidbodyBase.SetPosition` to set the position of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).\n - `NetworkRigidbodyBase.SetRotation` to set the rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).\n - `NetworkRigidbodyBase.ApplyCurrentTransform` to set the position and rotation of the `Rigidbody` or `Rigidbody2d` based on the associated `GameObject` transform (depending upon its initialized setting).\n - `NetworkRigidbodyBase.WakeIfSleeping` to wake up the rigid body if sleeping.\n - `NetworkRigidbodyBase.SleepRigidbody` to put the rigid body to sleep.\n - `NetworkRigidbodyBase.IsKinematic` to determine if the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting) is currently kinematic.\n - `NetworkRigidbodyBase.SetIsKinematic` to set the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting) current kinematic state.\n - `NetworkRigidbodyBase.ResetInterpolation` to reset the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting) back to its original interpolation value when initialized.\n - Now includes a `MonoBehaviour.FixedUpdate` implementation that will update the assigned `NetworkTransform` when `NetworkRigidbodyBase.UseRigidBodyForMotion` is true. (#2863)\n- Added `RigidbodyContactEventManager` that provides a more optimized way to process collision enter and collision stay events as opposed to the `Monobehaviour` approach. (#2863)\n - Can be used in client-server and distributed authority modes, but is particularly useful in distributed authority.\n- Added rigid body motion updates to `NetworkTransform` which allows users to set interolation on rigid bodies. (#2863)\n - Extrapolation is only allowed on authoritative instances, but custom class derived from `NetworkRigidbodyBase` or `NetworkRigidbody` or `NetworkRigidbody2D` automatically switches non-authoritative instances to interpolation if set to extrapolation.\n- Added distributed authority mode support to `NetworkAnimator`. (#2863)\n- Added session mode selection to `NetworkManager` inspector view. (#2863)\n- Added distributed authority permissions feature. (#2863)\n- Added distributed authority mode specific `NetworkObject` permissions flags (Distributable, Transferable, and RequestRequired). (#2863)\n- Added distributed authority mode specific `NetworkObject.SetOwnershipStatus` method that applies one or more `NetworkObject` instance's ownership flags. If updated when spawned, the ownership permission changes are synchronized with the other connected clients. (#2863)\n- Added distributed authority mode specific `NetworkObject.RemoveOwnershipStatus` method that removes one or more `NetworkObject` instance's ownership flags. If updated when spawned, the ownership permission changes are synchronized with the other connected clients. (#2863)\n- Added distributed authority mode specific `NetworkObject.HasOwnershipStatus` method that will return (true or false) whether one or more ownership flags is set. (#2863)\n- Added distributed authority mode specific `NetworkObject.SetOwnershipLock` method that locks ownership of a `NetworkObject` to prevent ownership from changing until the current owner releases the lock. (#2863)\n- Added distributed authority mode specific `NetworkObject.RequestOwnership` method that sends an ownership request to the current owner of a spawned `NetworkObject` instance. (#2863)\n- Added distributed authority mode specific `NetworkObject.OnOwnershipRequested` callback handler that is invoked on the owner/authoritative side when a non-owner requests ownership. Depending upon the boolean returned value depends upon whether the request is approved or denied. (#2863)\n- Added distributed authority mode specific `NetworkObject.OnOwnershipRequestResponse` callback handler that is invoked when a non-owner's request has been processed. This callback includes a `NetworkObjet.OwnershipRequestResponseStatus` response parameter that describes whether the request was approved or the reason why it was not approved. (#2863)\n- Added distributed authority mode specific `NetworkObject.DeferDespawn` method that defers the despawning of `NetworkObject` instances on non-authoritative clients based on the tick offset parameter. (#2863)\n- Added distributed authority mode specific `NetworkObject.OnDeferredDespawnComplete` callback handler that can be used to further control when deferring the despawning of a `NetworkObject` on non-authoritative instances. (#2863)\n- Added `NetworkClient.SessionModeType` as one way to determine the current session mode of the network session a client is connected to. (#2863)\n- Added distributed authority mode specific `NetworkClient.IsSessionOwner` property to determine if the current local client is the current session owner of a distributed authority session. (#2863)\n- Added distributed authority mode specific client side spawning capabilities. When running in distributed authority mode, clients can instantiate and spawn `NetworkObject` instances (the local client is authomatically the owner of the spawned object). (#2863)\n - This is useful to better visually synchronize owner authoritative motion models and newly spawned `NetworkObject` instances (i.e. projectiles for example).\n- Added distributed authority mode specific client side player spawning capabilities. Clients will automatically spawn their associated player object locally. (#2863)\n- Added distributed authority mode specific `NetworkConfig.AutoSpawnPlayerPrefabClientSide` property (default is true) to provide control over the automatic spawning of player prefabs on the local client side. (#2863)\n- Added distributed authority mode specific `NetworkManager.OnFetchLocalPlayerPrefabToSpawn` callback that, when assigned, will allow the local client to provide the player prefab to be spawned for the local client. (#2863)\n - This is only invoked if the `NetworkConfig.AutoSpawnPlayerPrefabClientSide` property is set to true.\n- Added distributed authority mode specific `NetworkBehaviour.HasAuthority` property that determines if the local client has authority over the associated `NetworkObject` instance (typical use case is within a `NetworkBehaviour` script much like that of `IsServer` or `IsClient`). (#2863)\n- Added distributed authority mode specific `NetworkBehaviour.IsSessionOwner` property that determines if the local client is the session owner (typical use case would be to determine if the local client can has scene management authority within a `NetworkBehaviour` script). (#2863)\n- Added support for distributed authority mode scene management where the currently assigned session owner can start scene events (i.e. scene loading and scene unloading). (#2863)\n\n### Fixed\n\n- Fixed issue where the host was not invoking `OnClientDisconnectCallback` for its own local client when internally shutting down. (#2822)\n- Fixed issue where NetworkTransform could potentially attempt to \"unregister\" a named message prior to it being registered. (#2807)\n- Fixed issue where in-scene placed `NetworkObject`s with complex nested children `NetworkObject`s (more than one child in depth) would not synchronize properly if WorldPositionStays was set to true. (#2796)\n\n### Changed\n- Changed client side awareness of other clients is now the same as a server or host. (#2863)\n- Changed `NetworkManager.ConnectedClients` can now be accessed by both server and clients. (#2863)\n- Changed `NetworkManager.ConnectedClientsList` can now be accessed by both server and clients. (#2863)\n- Changed `NetworkTransform` defaults to owner authoritative when connected to a distributed authority session. (#2863)\n- Changed `NetworkVariable` defaults to owner write and everyone read permissions when connected to a distributed authority session (even if declared with server read or write permissions). (#2863)\n- Changed `NetworkObject` no longer implements the `MonoBehaviour.Update` method in order to determine whether a `NetworkObject` instance has been migrated to a different scene. Instead, only `NetworkObjects` with the `SceneMigrationSynchronization` property set will be updated internally during the `NetworkUpdateStage.PostLateUpdate` by `NetworkManager`. (#2863)\n- Changed `NetworkManager` inspector view layout where properties are now organized by category. (#2863)\n- Changed `NetworkTransform` to now use `NetworkTransformMessage` as opposed to named messages for NetworkTransformState updates. (#2810)\n- Changed `CustomMessageManager` so it no longer attempts to register or \"unregister\" a null or empty string and will log an error if this condition occurs. (#2807)" }, "upmCi": { - "footprint": "5e57664d4f43bf176189c5ec8fd10f595b668e7d" + "footprint": "30b58dd41527f0745f60a544f04a338712651b16" }, - "documentationUrl": "https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@1.8/manual/index.html", + "documentationUrl": "https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@2.0/manual/index.html", "repository": { "url": "https://github.com/Unity-Technologies/com.unity.netcode.gameobjects.git", "type": "git", - "revision": "eb213838233cbee2030891203bcb72d2354a5a7d" + "revision": "e7ac3c896eea828bced614363711b80dcad4d570" }, "samples": [ {