diff --git a/.signature b/.signature new file mode 100644 index 0000000..0ddcdf4 --- /dev/null +++ b/.signature @@ -0,0 +1 @@ +{"timestamp":1734331212,"signature":"mMrBXdBegYd6TPqNVci9OkWh1H10YU8Ug8KlSpiyNzbXlS5z7O7Rdif3gvTdXK0O07HWmIuszcUoljQIaxkGAYq2g9A85IcvhbWsAAqxjSEZfQPsxFZlJQ9PqU4tfMItk7K1VP1YfcBxitxPHcUeO2IwBYVLx51gg6X/0qHWtkifmZ/cBbGTBNEYE+m7KfRYUyu23kOPMGOCBeULivZO9y/2A0qXkMeBiPo3KQFU6481n4GV6fahyLrG2llfM8xtW8YeouPyt/IMD86at8eeY+E5mW0iXGms9IMLf/DH6vjJnuSEfgMXfjcGnRO0m+RP+ig8HzjbPVty7oAOgfm6Oc1frOP4Cmudk97fIEzC10B0lj2uzFudT5UVPk4Hr6Mf/2ka0m+XTdRNHVRyOYBcHsJQYf0HKW/4jJPwWrSCSk2uE0fPn1sTvMb+i4pXCn7J700b7NMLPFJaWeb6kA2e3v8w5FybshFZWCU6fyLWGn1AR60u0BxL88Hx4VO5UjnJ","publicKey":"LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQm9qQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FZOEFNSUlCaWdLQ0FZRUFzdUhXYUhsZ0I1cVF4ZEJjTlJKSAordHR4SmoxcVY1NTdvMlZaRE1XaXhYRVBkRTBEMVFkT1JIRXNSS1RscmplUXlERU83ZlNQS0ZwZ1A3MU5TTnJCCkFHM2NFSU45aHNQVDhOVmllZmdWem5QTkVMenFkVmdEbFhpb2VpUnV6OERKWFgvblpmU1JWKytwbk9ySTRibG4KS0twelJlNW14OTc1SjhxZ1FvRktKT0NNRlpHdkJMR2MxSzZZaEIzOHJFODZCZzgzbUovWjBEYkVmQjBxZm13cgo2ZDVFUXFsd0E5Y3JZT1YyV1VpWXprSnBLNmJZNzRZNmM1TmpBcEFKeGNiaTFOaDlRVEhUcU44N0ZtMDF0R1ZwCjVNd1pXSWZuYVRUemEvTGZLelR5U0pka0tldEZMVGdkYXpMYlpzUEE2aHBSK0FJRTJhc0tLTi84UUk1N3UzU2cKL2xyMnZKS1IvU2l5eEN1Q20vQWJkYnJMbXk0WjlSdm1jMGdpclA4T0lLQWxBRWZ2TzV5Z2hSKy8vd1RpTFlzUQp1SllDM0V2UE16ZGdKUzdGR2FscnFLZzlPTCsxVzROY05yNWdveVdSUUJ0cktKaWlTZEJVWmVxb0RvSUY5NHpCCndGbzJJT1JFdXFqcU51M3diMWZIM3p1dGdtalFra3IxVjJhd3hmcExLWlROQWdNQkFBRT0KLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tCg"} \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 3423d9a..e6930d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,37 @@ 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.2.0] - 2024-12-12 + +### Added + +- Added `NetworkObject.OwnershipStatus.SessionOwner` to allow Network Objects to be distributable and only owned by the Session Owner. This flag will override all other `OwnershipStatus` flags. (#3175) +- Added `UnityTransport.GetEndpoint` method to provide a way to obtain `NetworkEndpoint` information of a connection via client identifier. (#3130) +- Added `NetworkTransport.OnEarlyUpdate` and `NetworkTransport.OnPostLateUpdate` methods to provide more control over handling transport related events at the start and end of each frame. (#3113) + +### Fixed + +- Fixed issue where the server, host, or session owner would not populate the in-scene place `NetworkObject` table if the scene was loaded prior to starting the `NetworkManager`. (#3177) +- Fixed issue where the `NetworkObjectIdHash` value could be incorrect when entering play mode while still in prefab edit mode with pending changes and using MPPM. (#3162) +- Fixed issue where a sever only `NetworkManager` instance would spawn the actual `NetworkPrefab`'s `GameObject` as opposed to creating an instance of it. (#3160) +- Fixed issue where only the session owner (as opposed to all clients) would handle spawning prefab overrides properly when using a distributed authority network topology. (#3160) +- Fixed issue where an exception was thrown when calling `NetworkManager.Shutdown` after calling `UnityTransport.Shutdown`. (#3118) +- Fixed issue where `NetworkList` properties on in-scene placed `NetworkObject`s could cause small memory leaks when entering playmode. (#3147) +- Fixed in-scene `NertworkObject` synchronization issue when loading a scene with currently connected clients connected to a session created by a `NetworkManager` started as a server (i.e. not as a host). (#3133) +- Fixed issue where a `NetworkManager` started as a server would not add itself as an observer to in-scene placed `NetworkObject`s instantiated and spawned by a scene loading event. (#3133) +- Fixed issue where spawning a player using `NetworkObject.InstantiateAndSpawn` or `NetworkSpawnManager.InstantiateAndSpawn` would not update the `NetworkSpawnManager.PlayerObjects` or assign the newly spawned player to the `NetworkClient.PlayerObject`. (#3122) +- Fixed issue where queued UnitTransport (NetworkTransport) message batches were being sent on the next frame. They are now sent at the end of the frame during `PostLateUpdate`. (#3113) +- Fixed issue where `NotOwnerRpcTarget` or `OwnerRpcTarget` were not using their replacements `NotAuthorityRpcTarget` and `AuthorityRpcTarget` which would invoke a warning. (#3111) +- Fixed issue where client is removed as an observer from spawned objects when their player instance is despawned. (#3110) +- Fixed issue where `NetworkAnimator` would statically allocate write buffer space for `Animator` parameters that could cause a write error if the number of parameters exceeded the space allocated. (#3108) + +### Changed + +- In-scene placed `NetworkObject`s have been made distributable when balancing object distribution after a connection event. (#3175) +- Optimised `NetworkVariable` and `NetworkTransform` related packets when in Distributed Authority mode. +- The Debug Simulator section of the Unity Transport component was removed. This section was not functional anymore and users are now recommended to use the more featureful [Network Simulator](https://docs-multiplayer.unity3d.com/tools/current/tools-network-simulator/) tool from the Multiplayer Tools package instead. (#3121) + ## [2.1.1] - 2024-10-18 ### Added @@ -187,8 +218,8 @@ Additional documentation and release notes are available at [Multiplayer Documen ## [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) +- 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. @@ -324,6 +355,7 @@ Additional documentation and release notes are available at [Multiplayer Documen - Fixed issue where you could not have multiple source network prefab overrides targeting the same network prefab as their override. (#2710) ### Changed + - Changed the server or host shutdown so it will now perform a "soft shutdown" when `NetworkManager.Shutdown` is invoked. This will send a disconnect notification to all connected clients and the server-host will wait for all connected clients to disconnect or timeout after a 5 second period before completing the shutdown process. (#2789) - Changed `OnClientDisconnectedCallback` will now return the assigned client identifier on the local client side if the client was approved and assigned one prior to being disconnected. (#2789) - Changed `NetworkTransform.SetState` (and related methods) now are cumulative during a fractional tick period and sent on the next pending tick. (#2777) @@ -336,6 +368,7 @@ Additional documentation and release notes are available at [Multiplayer Documen - Changed in-scene placed `NetworkObject`s now set their `IsSceneObject` value when generating their `GlobalObjectIdHash` value. (#2710) - Changed the default `NetworkConfig.SpawnTimeout` value from 1.0s to 10.0s. (#2710) + ## [1.7.1] - 2023-11-15 ### Added @@ -385,7 +418,7 @@ Additional documentation and release notes are available at [Multiplayer Documen ### Added - Added a protected virtual method `NetworkTransform.OnInitialize(ref NetworkTransformState replicatedState)` that just returns the replicated state reference. - + ### Fixed - Fixed issue where invoking `NetworkManager.Shutdown` within `NetworkManager.OnClientStopped` or `NetworkManager.OnServerStopped` would force `NetworkManager.ShutdownInProgress` to remain true after completing the shutdown process. (#2661) @@ -443,7 +476,7 @@ Additional documentation and release notes are available at [Multiplayer Documen - Fixed issue where invalid endpoint addresses were not being detected and returning false from NGO UnityTransport. (#2496) - Fixed some errors that could occur if a connection is lost and the loss is detected when attempting to write to the socket. (#2495) -## Changed +### Changed - Adding network prefabs before NetworkManager initialization is now supported. (#2565) - Connecting clients being synchronized now switch to the server's active scene before spawning and synchronizing NetworkObjects. (#2532) diff --git a/Editor/NetworkManagerEditor.cs b/Editor/NetworkManagerEditor.cs index 0684d74..8ba4128 100644 --- a/Editor/NetworkManagerEditor.cs +++ b/Editor/NetworkManagerEditor.cs @@ -237,7 +237,7 @@ private void DisplayNetworkManagerProperties() if (m_NetworkManager.NetworkConfig.NetworkTopology == NetworkTopologyTypes.DistributedAuthority) { EditorGUILayout.PropertyField(m_AutoSpawnPlayerPrefabClientSide, new GUIContent("Auto Spawn Player Prefab")); - } + } #endif EditorGUILayout.PropertyField(m_PlayerPrefabProperty, new GUIContent("Default Player Prefab")); diff --git a/Editor/NetworkObjectEditor.cs b/Editor/NetworkObjectEditor.cs index ef6ea58..0860fd9 100644 --- a/Editor/NetworkObjectEditor.cs +++ b/Editor/NetworkObjectEditor.cs @@ -88,6 +88,14 @@ public override void OnInspectorGUI() while (observerClientIds.MoveNext()) { + if (!m_NetworkObject.NetworkManager.ConnectedClients.ContainsKey(observerClientIds.Current)) + { + if ((observerClientIds.Current == 0 && m_NetworkObject.NetworkManager.IsHost) || observerClientIds.Current > 0) + { + Debug.LogWarning($"Client-{observerClientIds.Current} is listed as an observer but is not connected!"); + } + continue; + } if (m_NetworkObject.NetworkManager.ConnectedClients[observerClientIds.Current].PlayerObject != null) { EditorGUILayout.ObjectField($"ClientId: {observerClientIds.Current}", m_NetworkObject.NetworkManager.ConnectedClients[observerClientIds.Current].PlayerObject, typeof(GameObject), false); @@ -107,6 +115,10 @@ public override void OnInspectorGUI() EditorGUI.BeginChangeCheck(); serializedObject.UpdateIfRequiredOrScript(); DrawPropertiesExcluding(serializedObject, k_HiddenFields); + if (m_NetworkObject.IsOwnershipSessionOwner) + { + m_NetworkObject.Ownership = NetworkObject.OwnershipStatus.SessionOwner; + } serializedObject.ApplyModifiedProperties(); EditorGUI.EndChangeCheck(); @@ -185,9 +197,9 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten // 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; + // 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 031978c..ee8cecf 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,7 +1,5 @@ Unity Companion License (UCL License) -com.unity.netcode.gameobjects copyright © 2021-2024 Unity Technologies +com.unity.netcode.gameobjects copyright © 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. - - diff --git a/Runtime/Components/NetworkAnimator.cs b/Runtime/Components/NetworkAnimator.cs index 16b77ca..583e7bd 100644 --- a/Runtime/Components/NetworkAnimator.cs +++ b/Runtime/Components/NetworkAnimator.cs @@ -230,6 +230,7 @@ private void BuildDestinationToTransitionInfoTable() } } + #if UNITY_EDITOR private void ParseStateMachineStates(int layerIndex, ref AnimatorController animatorController, ref AnimatorStateMachine stateMachine) { @@ -263,7 +264,6 @@ private void ParseStateMachineStates(int layerIndex, ref AnimatorController anim { case AnimatorControllerParameterType.Trigger: { - if (transition.destinationStateMachine != null) { var destinationStateMachine = transition.destinationStateMachine; @@ -297,18 +297,12 @@ private void ParseStateMachineStates(int layerIndex, ref AnimatorController anim } } } -#endif /// /// Creates the TransitionStateInfoList table /// private void BuildTransitionStateInfoList() { -#if UNITY_EDITOR - if (UnityEditor.EditorApplication.isUpdating || UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode) - { - return; - } if (m_Animator == null) { return; @@ -326,9 +320,18 @@ private void BuildTransitionStateInfoList() var stateMachine = animatorController.layers[x].stateMachine; ParseStateMachineStates(x, ref animatorController, ref stateMachine); } -#endif } + /// + /// In-Editor Only + /// Virtual OnValidate method for custom derived NetworkAnimator classes. + /// + protected virtual void OnValidate() + { + BuildTransitionStateInfoList(); + } +#endif + public void OnAfterDeserialize() { BuildDestinationToTransitionInfoTable(); @@ -336,7 +339,7 @@ public void OnAfterDeserialize() public void OnBeforeSerialize() { - BuildTransitionStateInfoList(); + // Do nothing when serializing (handled during OnValidate) } internal struct AnimationState : INetworkSerializable @@ -419,8 +422,8 @@ internal struct AnimationMessage : INetworkSerializable internal bool HasBeenProcessed; // This is preallocated/populated in OnNetworkSpawn for all instances in the event ownership or - // authority changes. When serializing, IsDirtyCount determines how many AnimationState entries - // should be serialized from the list. When deserializing the list is created and populated with + // authority changes. When serializing, IsDirtyCount determines how many AnimationState entries + // should be serialized from the list. When deserializing the list is created and populated with // only the number of AnimationStates received which is dictated by the deserialized IsDirtyCount. internal List AnimationStates; @@ -496,7 +499,7 @@ internal bool IsServerAuthoritative() } /// - /// Override this method and return false to switch to owner authoritative mode + /// Override this method and return false to switch to owner authoritative mode. /// /// /// When using a distributed authority network topology, this will default to @@ -507,10 +510,6 @@ protected virtual bool OnIsServerAuthoritative() return NetworkManager ? !NetworkManager.DistributedAuthorityMode : true; } - // Animators only support up to 32 parameters - // TODO: Look into making this a range limited property - private const int k_MaxAnimationParams = 32; - private int[] m_TransitionHash; private int[] m_AnimationHash; private float[] m_LayerWeights; @@ -534,7 +533,7 @@ private unsafe struct AnimatorParamCache } // 128 bytes per Animator - private FastBufferWriter m_ParameterWriter = new FastBufferWriter(k_MaxAnimationParams * sizeof(float), Allocator.Persistent); + private FastBufferWriter m_ParameterWriter; private NativeArray m_CachedAnimatorParameters; @@ -586,6 +585,14 @@ public override void OnDestroy() protected virtual void Awake() { + if (!m_Animator) + { +#if !UNITY_EDITOR + Debug.LogError($"{nameof(NetworkAnimator)} {name} does not have an {nameof(UnityEngine.Animator)} assigned to it. The {nameof(NetworkAnimator)} will not initialize properly."); +#endif + return; + } + int layers = m_Animator.layerCount; // Initializing the below arrays for everyone handles an issue // when running in owner authoritative mode and the owner changes. @@ -615,6 +622,9 @@ protected virtual void Awake() } } + // The total initialization size calculated for the m_ParameterWriter write buffer. + var totalParameterSize = sizeof(uint); + // Build our reference parameter values to detect when they change var parameters = m_Animator.parameters; m_CachedAnimatorParameters = new NativeArray(parameters.Length, Allocator.Persistent); @@ -655,7 +665,37 @@ protected virtual void Awake() } m_CachedAnimatorParameters[i] = cacheParam; + + // Calculate parameter sizes (index + type size) + switch (parameter.type) + { + case AnimatorControllerParameterType.Int: + { + totalParameterSize += sizeof(int) * 2; + break; + } + case AnimatorControllerParameterType.Bool: + case AnimatorControllerParameterType.Trigger: + { + // Bool is serialized to 1 byte + totalParameterSize += sizeof(int) + 1; + break; + } + case AnimatorControllerParameterType.Float: + { + totalParameterSize += sizeof(int) + sizeof(float); + break; + } + } } + + if (m_ParameterWriter.IsInitialized) + { + m_ParameterWriter.Dispose(); + } + + // Create our parameter write buffer for serialization + m_ParameterWriter = new FastBufferWriter(totalParameterSize, Allocator.Persistent); } /// @@ -697,7 +737,7 @@ public override void OnNetworkDespawn() } /// - /// Wries all parameter and state information needed to initially synchronize a client + /// Writes all parameter and state information needed to initially synchronize a client /// private void WriteSynchronizationData(ref BufferSerializer serializer) where T : IReaderWriter { @@ -772,8 +812,10 @@ private void WriteSynchronizationData(ref BufferSerializer serializer) whe } } - animationState.Transition = isInTransition; // The only time this could be set to true - animationState.StateHash = stateHash; // When a transition, this is the originating/starting state + // The only time this could be set to true + animationState.Transition = isInTransition; + // When a transition, this is the originating/starting state + animationState.StateHash = stateHash; animationState.NormalizedTime = normalizedTime; animationState.Layer = layer; animationState.Weight = m_LayerWeights[layer]; @@ -847,7 +889,8 @@ private void CheckForStateChange(int layer) { m_TransitionHash[layer] = nt.fullPathHash; m_AnimationHash[layer] = 0; - animState.DestinationStateHash = nt.fullPathHash; // Next state is the destination state for cross fade + // Next state is the destination state for cross fade + animState.DestinationStateHash = nt.fullPathHash; animState.CrossFade = true; animState.Transition = true; animState.Duration = tt.duration; @@ -865,7 +908,8 @@ private void CheckForStateChange(int layer) // first time in this transition for this layer m_TransitionHash[layer] = tt.fullPathHash; m_AnimationHash[layer] = 0; - animState.StateHash = tt.fullPathHash; // Transitioning from state + // Transitioning from state + animState.StateHash = tt.fullPathHash; animState.CrossFade = false; animState.Transition = true; animState.NormalizedTime = tt.normalizedTime; @@ -1081,7 +1125,7 @@ private unsafe void WriteParameters(ref FastBufferWriter writer) { writer.Seek(0); writer.Truncate(); - // Write how many parameter entries we are going to write + // Write out how many parameter entries to read BytePacker.WriteValuePacked(writer, (uint)m_ParametersToUpdate.Count); foreach (var parameterIndex in m_ParametersToUpdate) { @@ -1230,10 +1274,11 @@ internal void UpdateAnimationState(AnimationState animationState) NetworkLog.LogError($"[DestinationState To Transition Info] Layer ({animationState.Layer}) sub-table does not contain destination state ({animationState.DestinationStateHash})!"); } } - else if (NetworkManager.LogLevel == LogLevel.Developer) - { - NetworkLog.LogError($"[DestinationState To Transition Info] Layer ({animationState.Layer}) does not exist!"); - } + // For reference, it is valid to have no transition information + //else if (NetworkManager.LogLevel == LogLevel.Developer) + //{ + // NetworkLog.LogError($"[DestinationState To Transition Info] Layer ({animationState.Layer}) does not exist!"); + //} } else if (animationState.Transition && animationState.CrossFade) { @@ -1436,7 +1481,7 @@ private void InternalSetTrigger(int hash, bool isSet = true) /// /// 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 + /// a trigger to a client /// /// the payload containing the trigger data to apply [Rpc(SendTo.NotAuthority)] @@ -1447,7 +1492,7 @@ internal void SendAnimTriggerRpc(AnimationTriggerMessage animationTriggerMessage /// /// 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 + /// a trigger to a client /// /// the payload containing the trigger data to apply /// unused @@ -1513,7 +1558,7 @@ public void SetTrigger(int hash, bool setTrigger = true) } /// - /// Resets the trigger for the associated animation. See SetTrigger for more on how triggers are special + /// Resets the trigger for the associated animation. See SetTrigger for more on how triggers are special /// /// The string name of the trigger to reset public void ResetTrigger(string triggerName) @@ -1529,4 +1574,5 @@ public void ResetTrigger(int hash) } } } -#endif // COM_UNITY_MODULES_ANIMATION +// COM_UNITY_MODULES_ANIMATION +#endif diff --git a/Runtime/Components/NetworkRigidBodyBase.cs b/Runtime/Components/NetworkRigidBodyBase.cs index 7e88081..18b393b 100644 --- a/Runtime/Components/NetworkRigidBodyBase.cs +++ b/Runtime/Components/NetworkRigidBodyBase.cs @@ -180,7 +180,7 @@ internal Vector3 GetAdjustedRotationThreshold() /// /// /// For , only the x and y components of the are applied. - /// + /// public void SetLinearVelocity(Vector3 linearVelocity) { if (m_IsRigidbody2D) @@ -546,7 +546,7 @@ public void SetIsKinematic(bool isKinematic) { if (IsKinematic()) { - // If not already set to interpolate then set the Rigidbody to interpolate + // If not already set to interpolate then set the Rigidbody to interpolate if (m_InternalRigidbody.interpolation == RigidbodyInterpolation.Extrapolate) { // Sleep until the next fixed update when switching from extrapolation to interpolation @@ -849,36 +849,30 @@ public void DetachFromFixedJoint() } if (UseRigidBodyForMotion) { - if (m_IsRigidbody2D) + if (m_IsRigidbody2D && FixedJoint2D != null) { - if (FixedJoint2D != null) + if (!m_FixedJoint2DUsingGravity) { - if (!m_FixedJoint2DUsingGravity) - { - FixedJoint2D.connectedBody.gravityScale = m_OriginalGravityScale; - } - FixedJoint2D.connectedBody = null; - Destroy(FixedJoint2D); - FixedJoint2D = null; - ResetInterpolation(); - RemoveFromParentBody(); + FixedJoint2D.connectedBody.gravityScale = m_OriginalGravityScale; } + FixedJoint2D.connectedBody = null; + Destroy(FixedJoint2D); + FixedJoint2D = null; + ResetInterpolation(); + RemoveFromParentBody(); } - else + else if (FixedJoint != null) { - if (FixedJoint != null) - { - FixedJoint.connectedBody = null; - m_InternalRigidbody.useGravity = m_OriginalGravitySetting; - Destroy(FixedJoint); - FixedJoint = null; - ResetInterpolation(); - RemoveFromParentBody(); - } + FixedJoint.connectedBody = null; + m_InternalRigidbody.useGravity = m_OriginalGravitySetting; + Destroy(FixedJoint); + FixedJoint = null; + ResetInterpolation(); + RemoveFromParentBody(); } } } } } -#endif // COM_UNITY_MODULES_PHYSICS - +// COM_UNITY_MODULES_PHYSICS +#endif diff --git a/Runtime/Components/NetworkTransform.cs b/Runtime/Components/NetworkTransform.cs index a103b0f..3d2be47 100644 --- a/Runtime/Components/NetworkTransform.cs +++ b/Runtime/Components/NetworkTransform.cs @@ -32,7 +32,8 @@ public class NetworkTransform : NetworkBehaviour /// public struct NetworkTransformState : INetworkSerializable { - private const int k_InLocalSpaceBit = 0x00000001; // Persists between state updates (authority dictates if this is set) + // Persists between state updates (authority dictates if this is set) + private const int k_InLocalSpaceBit = 0x00000001; private const int k_PositionXBit = 0x00000002; private const int k_PositionYBit = 0x00000004; private const int k_PositionZBit = 0x00000008; @@ -43,18 +44,25 @@ public struct NetworkTransformState : INetworkSerializable private const int k_ScaleYBit = 0x00000100; private const int k_ScaleZBit = 0x00000200; private const int k_TeleportingBit = 0x00000400; - private const int k_Interpolate = 0x00000800; // Persists between state updates (authority dictates if this is set) - private const int k_QuaternionSync = 0x00001000; // Persists between state updates (authority dictates if this is set) - private const int k_QuaternionCompress = 0x00002000; // Persists between state updates (authority dictates if this is set) - private const int k_UseHalfFloats = 0x00004000; // Persists between state updates (authority dictates if this is set) + // Persists between state updates (authority dictates if this is set) + private const int k_Interpolate = 0x00000800; + // Persists between state updates (authority dictates if this is set) + private const int k_QuaternionSync = 0x00001000; + // Persists between state updates (authority dictates if this is set) + private const int k_QuaternionCompress = 0x00002000; + // Persists between state updates (authority dictates if this is set) + private const int k_UseHalfFloats = 0x00004000; private const int k_Synchronization = 0x00008000; - private const int k_PositionSlerp = 0x00010000; // Persists between state updates (authority dictates if this is set) - private const int k_IsParented = 0x00020000; // When parented and synchronizing, we need to have both lossy and local scale due to varying spawn order + // Persists between state updates (authority dictates if this is set) + private const int k_PositionSlerp = 0x00010000; + // When parented and synchronizing, we need to have both lossy and local scale due to varying spawn order + private const int k_IsParented = 0x00020000; private const int k_SynchBaseHalfFloat = 0x00040000; 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 + // (Internal Debugging) When set each state update will contain a state identifier + private const int k_TrackStateId = 0x10000000; // Stores persistent and state relative flags private uint m_Bitset; @@ -409,8 +417,8 @@ internal set } /// - /// Returns whether this state update was a frame synchronization when - /// UseUnreliableDeltas is enabled. When set, the entire transform will + /// Returns whether this state update was a frame synchronization when + /// UseUnreliableDeltas is enabled. When set, the entire transform will /// be or has been synchronized. /// public bool IsUnreliableFrameSync() @@ -929,8 +937,6 @@ public void NetworkSerialize(BufferSerializer serializer) where T : IReade #endregion #region PROPERTIES AND GENERAL METHODS - - public enum AuthorityModes { Server, @@ -1370,7 +1376,8 @@ internal NetworkTransformState LocalAuthoritativeNetworkState private BufferedLinearInterpolatorVector3 m_PositionInterpolator; private BufferedLinearInterpolatorVector3 m_ScaleInterpolator; - private BufferedLinearInterpolatorQuaternion m_RotationInterpolator; // rotation is a single Quaternion since each Euler axis will affect the quaternion's final value + // rotation is a single Quaternion since each Euler axis will affect the quaternion's final value + private BufferedLinearInterpolatorQuaternion m_RotationInterpolator; // The previous network state private NetworkTransformState m_OldState = new NetworkTransformState(); @@ -1643,11 +1650,11 @@ private void TryCommitTransform(ref Transform transformToCommit, bool synchroniz Debug.LogException(ex); } - // The below is part of assuring we only send a frame synch, when sending unreliable deltas, if + // The below is part of assuring we only send a frame synch, when sending unreliable deltas, if // we have already sent at least one unreliable delta state update. At this point in the callstack, // a delta state update has just been sent in the above UpdateTransformState() call and as long as // we didn't send a frame synch and we are not synchronizing then we know at least one unreliable - // delta has been sent. Under this scenario, we should start checking for this instance's alloted + // delta has been sent. Under this scenario, we should start checking for this instance's alloted // frame synch "tick slot". Once we send a frame synch, if no other deltas occur after that // (i.e. the object is at rest) then we will stop sending frame synch's until the object begins // moving, rotating, or scaling again. @@ -1964,7 +1971,7 @@ private bool CheckForStateChange(ref NetworkTransformState networkState, ref Tra networkState.NetworkDeltaPosition = m_HalfPositionState; - // If ownership offset is greater or we are doing an axial synchronization then synchronize the base position + // If ownership offset is greater or we are doing an axial synchronization then synchronize the base position if ((m_HalfFloatTargetTickOwnership > m_CachedNetworkManager.ServerTime.Tick || isAxisSync) && !networkState.IsTeleportingNextFrame) { networkState.SynchronizeBaseHalfFloat = true; @@ -3403,7 +3410,7 @@ internal void ChildRegistration(NetworkObject child, bool isAdding) /// - Local space to local space ( parent to parent) /// Will all smoothly transition while interpolation is enabled. /// (Does not work if using a or for motion) - /// + /// /// When a parent changes, non-authoritative instances should:
/// - Apply the resultant position, rotation, and scale from the parenting action.
/// - Clear interpolators (even if not enabled on this frame)
@@ -3575,7 +3582,7 @@ private void SetStateInternal(Vector3 pos, Quaternion rot, Vector3 scale, bool s var transformToCommit = transform; - // Explicit set states are cumulative during a fractional tick period of time (i.e. each SetState invocation will + // Explicit set states are cumulative during a fractional tick period of time (i.e. each SetState invocation will // update the axial deltas to whatever changes are applied). As such, we need to preserve the dirty and explicit // state flags. var stateWasDirty = m_LocalAuthoritativeNetworkState.IsDirty; @@ -3658,7 +3665,7 @@ private void UpdateInterpolation() var serverTime = m_CachedNetworkManager.ServerTime; var cachedServerTime = serverTime.Time; - //var offset = (float)serverTime.TickOffset; + // var offset = (float)serverTime.TickOffset; #if COM_UNITY_MODULES_PHYSICS || COM_UNITY_MODULES_PHYSICS2D var cachedDeltaTime = m_UseRigidbodyForMotion ? m_CachedNetworkManager.RealTimeProvider.FixedDeltaTime : m_CachedNetworkManager.RealTimeProvider.DeltaTime; #else @@ -3669,7 +3676,7 @@ private void UpdateInterpolation() // is to make their cachedRenderTime run 2 ticks behind. // TODO: This could most likely just always be 2 - //var ticksAgo = ((!IsServerAuthoritative() && !IsServer) || m_CachedNetworkManager.DistributedAuthorityMode) && !m_CachedNetworkManager.DAHost ? 2 : 1; + // var ticksAgo = ((!IsServerAuthoritative() && !IsServer) || m_CachedNetworkManager.DistributedAuthorityMode) && !m_CachedNetworkManager.DAHost ? 2 : 1; var ticksAgo = 2; var cachedRenderTime = serverTime.TimeTicksAgo(ticksAgo).Time; @@ -3746,7 +3753,7 @@ public virtual void OnFixedUpdate() /// /// Determines whether the is or based on the property. - /// You can override this method to control this logic. + /// You can override this method to control this logic. /// /// or protected virtual bool OnIsServerAuthoritative() @@ -3772,7 +3779,6 @@ public bool IsServerAuthoritative() return OnIsServerAuthoritative(); } } - #endregion #region MESSAGE HANDLING @@ -3964,7 +3970,7 @@ internal float TicksAgoInSeconds() { return 2 * m_TickFrequency; // TODO: We need an RTT that updates regularly and not just when the client sends packets - //return Mathf.Max(1.0f, TicksAgo) * m_TickFrequency; + // return Mathf.Max(1.0f, TicksAgo) * m_TickFrequency; } /// @@ -3974,25 +3980,25 @@ internal float TicksAgoInSeconds() private void TickUpdate() { // TODO: We need an RTT that updates regularly and not just when the client sends packets - //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); - //} + // 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) @@ -4012,13 +4018,13 @@ private void TickUpdate() private UnityTransport m_UnityTransport; private float m_TickFrequency; - //private float m_OffsetTickFrequency; - //private ulong m_TickInMS; - //private int m_TickSampleIndex; + // 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; + // public float Offset { get; private set; } + // private float m_PreviousTicksAgo; private List m_TicksAgoSamples = new List(); @@ -4032,16 +4038,16 @@ public NetworkTransformTickRegistration(NetworkManager networkManager) //// 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; + // 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); - //} + // for (int i = 0; i < m_TickRate; i++) + // { + // m_TicksAgoSamples.Add(1f); + // } TicksAgo = 2f; - //m_PreviousTicksAgo = 1f; + // m_PreviousTicksAgo = 1f; if (networkManager.IsServer) { networkManager.OnServerStopped += OnNetworkManagerStopped; diff --git a/Runtime/Components/RigidbodyContactEventManager.cs b/Runtime/Components/RigidbodyContactEventManager.cs index d0808d2..02f9c98 100644 --- a/Runtime/Components/RigidbodyContactEventManager.cs +++ b/Runtime/Components/RigidbodyContactEventManager.cs @@ -27,7 +27,7 @@ public struct ContactEventHandlerInfo } /// - /// Default implementation required to register a with a instance. + /// Default implementation required to register a with a instance. /// /// /// Recommended to implement this method on a component @@ -52,7 +52,7 @@ public interface IContactEventHandler } /// - /// This is an extended version of and can be used to register a with a instance.
+ /// This is an extended version of and can be used to register a with a instance.
/// This provides additional information to the for each set of contact events it is processing. ///
public interface IContactEventHandlerWithInfo : IContactEventHandler @@ -66,9 +66,9 @@ public interface IContactEventHandlerWithInfo : IContactEventHandler /// /// Add this component to an in-scene placed GameObject to provide faster collision event processing between instances and optionally static colliders. - ///
- ///
- ///
+ ///
+ ///
+ ///
///
[AddComponentMenu("Netcode/Rigidbody Contact Event Manager")] public class RigidbodyContactEventManager : MonoBehaviour diff --git a/Runtime/Configuration/NetworkConfig.cs b/Runtime/Configuration/NetworkConfig.cs index 79035a8..a966808 100644 --- a/Runtime/Configuration/NetworkConfig.cs +++ b/Runtime/Configuration/NetworkConfig.cs @@ -13,6 +13,14 @@ namespace Unity.Netcode [Serializable] public class NetworkConfig { + // Clamp spawn time outs to prevent dropping messages during scene events + // Note: The legacy versions of NGO defaulted to 1s which was too low. As + // well, the SpawnTimeOut is now being clamped to within this recommended + // range both via UI and when NetworkManager is validated. + internal const float MinSpawnTimeout = 10.0f; + // Clamp spawn time outs to no more than 1 hour (really that is a bit high) + internal const float MaxSpawnTimeout = 3600.0f; + /// /// The protocol version. Different versions doesn't talk to each other. /// @@ -132,6 +140,8 @@ public class NetworkConfig /// 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 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.")] + + [Range(MinSpawnTimeout, MaxSpawnTimeout)] public float SpawnTimeout = 10f; /// @@ -176,6 +186,21 @@ public class NetworkConfig [Tooltip("Enable (default) if you want to profile network messages with development builds and defaults to being disabled in release builds. When disabled, network messaging profiling will be disabled in development builds.")] public bool NetworkProfilingMetrics = true; + /// + /// Invoked by when it is validated. + /// + /// + /// Used to check for potential legacy values that have already been serialized and/or + /// runtime modifications to a property outside of the recommended range. + /// For each property checked below, provide a brief description of the reason. + /// + internal void OnValidate() + { + // Legacy NGO versions defaulted this value to 1 second that has since been determiend + // any range less than 10 seconds can lead to dropped messages during scene events. + SpawnTimeout = Mathf.Clamp(SpawnTimeout, MinSpawnTimeout, MaxSpawnTimeout); + } + /// /// Returns a base64 encoded version of the configuration /// diff --git a/Runtime/Configuration/SessionConfig.cs b/Runtime/Configuration/SessionConfig.cs new file mode 100644 index 0000000..671ae74 --- /dev/null +++ b/Runtime/Configuration/SessionConfig.cs @@ -0,0 +1,58 @@ +namespace Unity.Netcode +{ + internal class SessionConfig + { + /// + /// The running list of session versions + /// + public const uint NoFeatureCompatibility = 0; + public const uint BypassFeatureCompatible = 1; + public const uint ServerDistributionCompatible = 2; + + // The most current session version (!!!!set this when you increment!!!!!) + public static uint PackageSessionVersion => ServerDistributionCompatible; + + internal uint SessionVersion; + + public bool ServiceSideDistribution; + + + /// + /// Service to client + /// Set when the client receives a + /// + /// the session's settings + public SessionConfig(ServiceConfig serviceConfig) + { + SessionVersion = serviceConfig.SessionVersion; + ServiceSideDistribution = serviceConfig.ServerRedistribution; + } + + /// + /// Can be used to directly set the version. + /// + /// + /// If a client connects that does not support session configuration then + /// this will be invoked. The default values set in the constructor should + /// assume that no features are available. + /// Can also be used for mock/integration testing version handling. + /// + /// version to set + public SessionConfig(uint version) + { + SessionVersion = version; + ServiceSideDistribution = false; + } + + /// + /// Client to Service + /// Default package constructor set when is invoked. + /// + public SessionConfig() + { + // The current + SessionVersion = PackageSessionVersion; + ServiceSideDistribution = false; + } + } +} diff --git a/Runtime/Configuration/SessionConfig.cs.meta b/Runtime/Configuration/SessionConfig.cs.meta new file mode 100644 index 0000000..bb361b9 --- /dev/null +++ b/Runtime/Configuration/SessionConfig.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e0512e5a3e1dc484bbbf98c03a574645 \ No newline at end of file diff --git a/Runtime/Connection/NetworkConnectionManager.cs b/Runtime/Connection/NetworkConnectionManager.cs index 5c26df4..fe6bc48 100644 --- a/Runtime/Connection/NetworkConnectionManager.cs +++ b/Runtime/Connection/NetworkConnectionManager.cs @@ -10,15 +10,54 @@ namespace Unity.Netcode { - + /// + /// The connection event type set within to signify the type of connection event notification received. + /// + /// + /// is returned as a parameter of the event notification. + /// and event types occur on the client-side of the newly connected client and on the server-side.
+ /// and event types occur on connected clients to notify that a new client (peer) has joined/connected. + ///
public enum ConnectionEvent { + /// + /// This event is set on the client-side of the newly connected client and on the server-side.
+ ///
+ /// + /// On the newly connected client side, the will be the .
+ /// On the server side, the will be the ID of the client that just connected. + ///
ClientConnected, + /// + /// This event is set on clients that are already connected to the session. + /// + /// + /// The will be the ID of the client that just connected. + /// PeerConnected, + /// + /// This event is set on the client-side of the client that disconnected client and on the server-side. + /// + /// + /// On the disconnected client side, the will be the .
+ /// On the server side, this will be the ID of the client that disconnected. + ///
ClientDisconnected, + /// + /// This event is set on clients that are already connected to the session. + /// + /// + /// The will be the ID of the client that just disconnected. + /// PeerDisconnected } + /// + /// Returned as a parameter of the event notification. + /// + /// + /// See for more details on the types of connection events received. + /// public struct ConnectionEventData { public ConnectionEvent EventType; @@ -563,7 +602,7 @@ private void SendConnectionRequest() { var message = new ConnectionRequestMessage { - CMBServiceConnection = NetworkManager.CMBServiceConnection, + DistributedAuthority = NetworkManager.DistributedAuthorityMode, // 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, @@ -571,8 +610,9 @@ private void SendConnectionRequest() MessageVersions = new NativeArray(MessageManager.MessageHandlers.Length, Allocator.Temp) }; - if (NetworkManager.CMBServiceConnection) + if (NetworkManager.DistributedAuthorityMode) { + message.ClientConfig.SessionConfig = NetworkManager.SessionConfig; message.ClientConfig.TickRate = NetworkManager.NetworkConfig.TickRate; message.ClientConfig.EnableSceneManagement = NetworkManager.NetworkConfig.EnableSceneManagement; } @@ -1001,6 +1041,14 @@ internal NetworkClient AddClient(ulong clientId) } var distributedAuthority = NetworkManager.DistributedAuthorityMode; + + // If not using DA return early or if using DA and scene management is disabled then exit early Since we use NetworkShow to spawn + // objects on the newly connected client side. + if (!distributedAuthority || distributedAuthority && !NetworkManager.NetworkConfig.EnableSceneManagement) + { + return networkClient; + } + var sessionOwnerId = NetworkManager.CurrentSessionOwner; var isSessionOwner = NetworkManager.LocalClient.IsSessionOwner; foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList) @@ -1164,7 +1212,7 @@ internal void OnClientDisconnectFromServer(ulong clientId) { // 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.IsOwnershipDistributable && ownedObject.GetCachedParent() == null && !ownedObject.IsOwnershipSessionOwner) { if (ownedObject.IsOwnershipLocked) { @@ -1201,6 +1249,11 @@ internal void OnClientDisconnectFromServer(ulong clientId) childObject.SetOwnershipLock(false); } + // Ignore session owner marked objects + if (childObject.IsOwnershipSessionOwner) + { + continue; + } NetworkManager.SpawnManager.ChangeOwnership(childObject, targetOwner, true); if (EnableDistributeLogging) { diff --git a/Runtime/Core/NetworkBehaviour.cs b/Runtime/Core/NetworkBehaviour.cs index bcdd25f..adc7ec0 100644 --- a/Runtime/Core/NetworkBehaviour.cs +++ b/Runtime/Core/NetworkBehaviour.cs @@ -826,7 +826,7 @@ public virtual void OnGainedOwnership() { } internal void InternalOnGainedOwnership() { UpdateNetworkProperties(); - // New owners need to assure any NetworkVariables they have write permissions + // New owners need to assure any NetworkVariables they have write permissions // to are updated so the previous and original values are aligned with the // current value (primarily for collections). if (OwnerClientId == NetworkManager.LocalClientId) @@ -1181,14 +1181,8 @@ internal void WriteNetworkVariableData(FastBufferWriter writer, ulong targetClie { // Create any values that require accessing the NetworkManager locally (it is expensive to access it in NetworkBehaviour) var networkManager = NetworkManager; - var distributedAuthority = networkManager.DistributedAuthorityMode; var ensureLengthSafety = networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety; - // Always write the NetworkVariable count even if zero for distributed authority (used by comb server) - if (distributedAuthority) - { - writer.WriteValueSafe((ushort)NetworkVariableFields.Count); - } // Exit early if there are no NetworkVariables if (NetworkVariableFields.Count == 0) @@ -1203,14 +1197,8 @@ internal void WriteNetworkVariableData(FastBufferWriter writer, ulong targetClie if (NetworkVariableFields[j].CanClientRead(targetClientId)) { // Write additional NetworkVariable information when length safety is enabled or when in distributed authority mode - if (ensureLengthSafety || distributedAuthority) + if (ensureLengthSafety) { - // Write the type being serialized for distributed authority (only for comb-server) - if (distributedAuthority) - { - writer.WriteValueSafe(NetworkVariableFields[j].Type); - } - var writePos = writer.Position; // Note: This value can't be packed because we don't know how large it will be in advance // we reserve space for it, then write the data, then come back and fill in the space @@ -1261,20 +1249,8 @@ internal void SetNetworkVariableData(FastBufferReader reader, ulong clientId) { // Stack cache any values that requires accessing the NetworkManager (it is expensive to access it in NetworkBehaviour) var networkManager = NetworkManager; - var distributedAuthority = networkManager.DistributedAuthorityMode; var ensureLengthSafety = networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety; - // Always read the NetworkVariable count when in distributed authority (sanity check if comb-server matches what client has locally) - if (distributedAuthority) - { - reader.ReadValueSafe(out ushort variableCount); - if (variableCount != NetworkVariableFields.Count) - { - Debug.LogError($"[{name}][NetworkObjectId: {NetworkObjectId}][NetworkBehaviourId: {NetworkBehaviourId}] NetworkVariable count mismatch! (Read: {variableCount} vs. Expected: {NetworkVariableFields.Count})"); - return; - } - } - // Exit early if nothing else to read if (NetworkVariableFields.Count == 0) { @@ -1289,14 +1265,8 @@ internal void SetNetworkVariableData(FastBufferReader reader, ulong clientId) // Distributed Authority: All clients have read permissions, always try to read the value if (NetworkVariableFields[j].CanClientRead(clientId)) { - if (ensureLengthSafety || distributedAuthority) + if (ensureLengthSafety) { - // Read the type being serialized and discard it (for now) when in a distributed authority network topology (only used by comb-server) - if (distributedAuthority) - { - reader.ReadValueSafe(out NetworkVariableType _); - } - reader.ReadValueSafe(out varSize); if (varSize == 0) { @@ -1320,11 +1290,11 @@ internal void SetNetworkVariableData(FastBufferReader reader, ulong clientId) continue; } - // Read the NetworkVarible value + // Read the NetworkVariable value NetworkVariableFields[j].ReadField(reader); - // When EnsureNetworkVariableLengthSafety or DistributedAuthorityMode always do a bounds check - if (ensureLengthSafety || distributedAuthority) + // When EnsureNetworkVariableLengthSafety always do a bounds check + if (ensureLengthSafety) { if (reader.Position > (readStartPos + varSize)) { diff --git a/Runtime/Core/NetworkBehaviourUpdater.cs b/Runtime/Core/NetworkBehaviourUpdater.cs index 9062ebf..6a1dd74 100644 --- a/Runtime/Core/NetworkBehaviourUpdater.cs +++ b/Runtime/Core/NetworkBehaviourUpdater.cs @@ -141,6 +141,9 @@ private void NetworkBehaviourUpdater_Tick() // Then show any NetworkObjects queued to be made visible/shown m_NetworkManager.SpawnManager.HandleNetworkObjectShow(); + + // Handle object redistribution (DA + disabled scene management only) + m_NetworkManager.HandleRedistributionToClients(); } } } diff --git a/Runtime/Core/NetworkManager.cs b/Runtime/Core/NetworkManager.cs index de08ae0..9b3ef04 100644 --- a/Runtime/Core/NetworkManager.cs +++ b/Runtime/Core/NetworkManager.cs @@ -80,6 +80,18 @@ internal static void LogSerializedTypeNotOptimized() } #endif + internal SessionConfig SessionConfig; + + /// + /// Used for internal testing purposes + /// + internal delegate SessionConfig OnGetSessionConfigHandler(); + internal OnGetSessionConfigHandler OnGetSessionConfig; + private SessionConfig GetSessionConfig() + { + return OnGetSessionConfig != null ? OnGetSessionConfig.Invoke() : new SessionConfig(); + } + internal static bool IsDistributedAuthority; /// @@ -162,10 +174,30 @@ public bool DAHost } } - // DANGO-TODO-MVP: Remove these properties once the service handles object distribution - internal ulong ClientToRedistribute; - internal bool RedistributeToClient; - internal int TickToRedistribute; + // DANGO-TODO: Determine if this needs to be removed once the service handles object distribution + internal List ClientsToRedistribute = new List(); + internal bool RedistributeToClients; + + /// + /// Handles object redistribution when scene management is disabled. + /// + /// DANGO-TODO: Determine if this needs to be removed once the service handles object distribution + /// + internal void HandleRedistributionToClients() + { + if (!DistributedAuthorityMode || !RedistributeToClients || NetworkConfig.EnableSceneManagement || ShutdownInProgress) + { + return; + } + + foreach (var clientId in ClientsToRedistribute) + { + SpawnManager.DistributeNetworkObjects(clientId); + } + RedistributeToClients = false; + ClientsToRedistribute.Clear(); + } + internal List DeferredDespawnObjects = new List(); @@ -193,11 +225,7 @@ internal void SetSessionOwner(ulong sessionOwner) foreach (var networkObjectEntry in SpawnManager.SpawnedObjects) { var networkObject = networkObjectEntry.Value; - if (networkObject.IsSceneObject == null || !networkObject.IsSceneObject.Value) - { - continue; - } - if (networkObject.OwnerClientId != LocalClientId) + if (networkObject.IsOwnershipSessionOwner && LocalClient.IsSessionOwner) { SpawnManager.ChangeOwnership(networkObject, LocalClientId, true); } @@ -291,6 +319,10 @@ public void NetworkUpdate(NetworkUpdateStage updateStage) case NetworkUpdateStage.EarlyUpdate: { UpdateTopology(); + + // Handle processing any new connections or transport events + NetworkConfig.NetworkTransport.EarlyUpdate(); + ConnectionManager.ProcessPendingApprovals(); ConnectionManager.PollAndHandleNetworkEvents(); @@ -298,6 +330,7 @@ public void NetworkUpdate(NetworkUpdateStage updateStage) AnticipationSystem.SetupForUpdate(); MessageManager.ProcessIncomingMessageQueue(); + MessageManager.CleanupDisconnectedClients(); AnticipationSystem.ProcessReanticipation(); } @@ -379,22 +412,15 @@ public void NetworkUpdate(NetworkUpdateStage updateStage) // Metrics update needs to be driven by NetworkConnectionManager's update to assure metrics are dispatched after the send queue is processed. MetricsManager.UpdateMetrics(); + // Handle sending any pending transport messages + NetworkConfig.NetworkTransport.PostLateUpdate(); + // TODO: Determine a better way to handle this NetworkObject.VerifyParentingStatus(); // 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 @@ -925,6 +951,9 @@ internal void OnValidate() return; // May occur when the component is added } + // Do a validation pass on NetworkConfig properties + NetworkConfig.OnValidate(); + if (GetComponentInChildren() != null) { if (NetworkLog.CurrentLogLevel <= LogLevel.Normal) @@ -993,8 +1022,7 @@ private void ModeChanged(PlayModeStateChange change) { if (IsListening && change == PlayModeStateChange.ExitingPlayMode) { - // Make sure we are not holding onto anything in case domain reload is disabled - ShutdownInternal(); + OnApplicationQuit(); } } #endif @@ -1161,6 +1189,12 @@ internal void Initialize(bool server) UpdateTopology(); + // Always create a default session config when starting a NetworkManager instance + if (DistributedAuthorityMode) + { + SessionConfig = GetSessionConfig(); + } + // Make sure the ServerShutdownState is reset when initializing if (server) { diff --git a/Runtime/Core/NetworkObject.cs b/Runtime/Core/NetworkObject.cs index 3ccd8ea..c449c9a 100644 --- a/Runtime/Core/NetworkObject.cs +++ b/Runtime/Core/NetworkObject.cs @@ -102,10 +102,22 @@ public uint PrefabIdHash private const int k_SceneObjectType = 2; private const int k_SourceAssetObjectType = 3; + // Used to track any InContext or InIsolation prefab being edited. + private static PrefabStage s_PrefabStage; + // The network prefab asset that the edit mode scene has created an instance of (s_PrefabInstance). + private static NetworkObject s_PrefabAsset; + // The InContext or InIsolation edit mode network prefab scene instance of the prefab asset (s_PrefabAsset). + private static NetworkObject s_PrefabInstance; + + private static bool s_DebugPrefabIdGeneration; + + [ContextMenu("Refresh In-Scene Prefab Instances")] internal void RefreshAllPrefabInstances() { var instanceGlobalId = GlobalObjectId.GetGlobalObjectIdSlow(this); + // Assign the currently selected instance to be updated + NetworkObjectRefreshTool.PrefabNetworkObject = this; if (!PrefabUtility.IsPartOfAnyPrefab(this) || instanceGlobalId.identifierType != k_ImportedAssetObjectType) { EditorUtility.DisplayDialog("Network Prefab Assets Only", "This action can only be performed on a network prefab asset.", "Ok"); @@ -132,25 +144,119 @@ internal void RefreshAllPrefabInstances() NetworkObjectRefreshTool.ProcessScenes(); } + /// + /// Register for opened and closing event notifications. + /// + [InitializeOnLoadMethod] + private static void OnApplicationStart() + { + PrefabStage.prefabStageOpened -= PrefabStageOpened; + PrefabStage.prefabStageOpened += PrefabStageOpened; + PrefabStage.prefabStageClosing -= PrefabStageClosing; + PrefabStage.prefabStageClosing += PrefabStageClosing; + } + + private static void PrefabStageClosing(PrefabStage prefabStage) + { + // If domain reloading is enabled, then this will be null when we return from playmode. + if (s_PrefabStage == null) + { + // Determine if we have a network prefab opened in edit mode or not. + CheckPrefabStage(prefabStage); + } + + s_PrefabStage = null; + s_PrefabInstance = null; + s_PrefabAsset = null; + } + + private static void PrefabStageOpened(PrefabStage prefabStage) + { + // Determine if we have a network prefab opened in edit mode or not. + CheckPrefabStage(prefabStage); + } + + /// + /// Determines if we have opened a network prefab in edit mode (InContext or InIsolation) + /// + /// + /// InContext: Typically means a are in prefab edit mode for an in-scene placed network prefab instance. + /// (currently no such thing as a network prefab with nested network prefab instances) + /// + /// InIsolation: Typically means we are in prefb edit mode for a prefab asset. + /// + /// + private static void CheckPrefabStage(PrefabStage prefabStage) + { + s_PrefabStage = prefabStage; + s_PrefabInstance = prefabStage.prefabContentsRoot?.GetComponent(); + if (s_PrefabInstance) + { + // We acquire the source prefab that the prefab edit mode scene instance was instantiated from differently for InContext than InSolation. + if (s_PrefabStage.mode == PrefabStage.Mode.InContext && s_PrefabStage.openedFromInstanceRoot != null) + { + // This is needed to handle the scenario where a user completely loads a new scene while in an InContext prefab edit mode. + try + { + s_PrefabAsset = s_PrefabStage.openedFromInstanceRoot?.GetComponent(); + } + catch + { + s_PrefabAsset = null; + } + } + else + { + // When editing in InIsolation mode, load the original prefab asset from the provided path. + s_PrefabAsset = AssetDatabase.LoadAssetAtPath(s_PrefabStage.assetPath); + } + + if (s_PrefabInstance.GlobalObjectIdHash != s_PrefabAsset.GlobalObjectIdHash) + { + s_PrefabInstance.GlobalObjectIdHash = s_PrefabAsset.GlobalObjectIdHash; + // For InContext mode, we don't want to record these modifications (the in-scene GlobalObjectIdHash is serialized with the scene). + if (s_PrefabStage.mode == PrefabStage.Mode.InIsolation) + { + PrefabUtility.RecordPrefabInstancePropertyModifications(s_PrefabAsset); + } + } + } + else + { + s_PrefabStage = null; + s_PrefabInstance = null; + s_PrefabAsset = null; + } + } + + /// + /// GlobalObjectIdHash values are generated during validation. + /// internal void OnValidate() { - // do NOT regenerate GlobalObjectIdHash for NetworkPrefabs while Editor is in PlayMode + // Always exit early if we are in prefab edit mode and this instance is the + // prefab instance within the InContext or InIsolation edit scene. + if (s_PrefabInstance == this) + { + return; + } + + // Do not regenerate GlobalObjectIdHash for NetworkPrefabs while Editor is in play mode. if (EditorApplication.isPlaying && !string.IsNullOrEmpty(gameObject.scene.name)) { return; } - // do NOT regenerate GlobalObjectIdHash if Editor is transitioning into or out of PlayMode + // Do not regenerate GlobalObjectIdHash if Editor is transitioning into or out of play mode. if (!EditorApplication.isPlaying && EditorApplication.isPlayingOrWillChangePlaymode) { return; } - // Get a global object identifier for this network prefab - var globalId = GetGlobalId(); - + // Get a global object identifier for this network prefab. + var globalId = GlobalObjectId.GetGlobalObjectIdSlow(this); - // if the identifier type is 0, then don't update the GlobalObjectIdHash + // if the identifier type is 0, then don't update the GlobalObjectIdHash. if (globalId.identifierType == k_NullObjectType) { return; @@ -159,47 +265,34 @@ internal void OnValidate() var oldValue = GlobalObjectIdHash; GlobalObjectIdHash = globalId.ToString().Hash32(); - // If the GlobalObjectIdHash value changed, then mark the asset dirty + // Always check for in-scene placed to assure any previous version scene assets with in-scene place NetworkObjects gets updated. + CheckForInScenePlaced(); + + // If the GlobalObjectIdHash value changed, then mark the asset dirty. if (GlobalObjectIdHash != oldValue) { - // Check if this is an in-scnee placed NetworkObject (Special Case for In-Scene Placed) - if (!IsEditingPrefab() && gameObject.scene.name != null && gameObject.scene.name != gameObject.name) + // Check if this is an in-scnee placed NetworkObject (Special Case for In-Scene Placed). + if (IsSceneObject.HasValue && IsSceneObject.Value) { - // Sanity check to make sure this is a scene placed object + // Sanity check to make sure this is a scene placed object. if (globalId.identifierType != k_SceneObjectType) { - // This should never happen, but in the event it does throw and error + // This should never happen, but in the event it does throw and error. Debug.LogError($"[{gameObject.name}] is detected as an in-scene placed object but its identifier is of type {globalId.identifierType}! **Report this error**"); } - // If this is a prefab instance + // If this is a prefab instance, then we want to mark it as having been updated in order for the udpated GlobalObjectIdHash value to be saved. if (PrefabUtility.IsPartOfAnyPrefab(this)) { - // We must invoke this in order for the modifications to get saved with the scene (does not mark scene as dirty) + // We must invoke this in order for the modifications to get saved with the scene (does not mark scene as dirty). PrefabUtility.RecordPrefabInstancePropertyModifications(this); } } - else // Otherwise, this is a standard network prefab asset so we just mark it dirty for the AssetDatabase to update it + else // Otherwise, this is a standard network prefab asset so we just mark it dirty for the AssetDatabase to update it. { EditorUtility.SetDirty(this); } } - - // Always check for in-scene placed to assure any previous version scene assets with in-scene place NetworkObjects gets updated - CheckForInScenePlaced(); - } - - private bool IsEditingPrefab() - { - // Check if we are directly editing the prefab - var stage = PrefabStageUtility.GetPrefabStage(gameObject); - - // if we are not editing the prefab directly (or a sub-prefab), then return the object identifier - if (stage == null || stage.assetPath == null) - { - return false; - } - return true; } /// @@ -210,13 +303,12 @@ private bool IsEditingPrefab() /// /// This NetworkObject is considered an in-scene placed prefab asset instance if it is: /// - Part of a prefab - /// - Not being directly edited /// - Within a valid scene that is part of the scenes in build list /// (In-scene defined NetworkObjects that are not part of a prefab instance are excluded.) /// private void CheckForInScenePlaced() { - if (PrefabUtility.IsPartOfAnyPrefab(this) && !IsEditingPrefab() && gameObject.scene.IsValid() && gameObject.scene.isLoaded && gameObject.scene.buildIndex >= 0) + if (PrefabUtility.IsPartOfAnyPrefab(this) && gameObject.scene.IsValid() && gameObject.scene.isLoaded && gameObject.scene.buildIndex >= 0) { var prefab = PrefabUtility.GetCorrespondingObjectFromSource(gameObject); var assetPath = AssetDatabase.GetAssetPath(prefab); @@ -229,55 +321,6 @@ private void CheckForInScenePlaced() IsSceneObject = true; } } - - private GlobalObjectId GetGlobalId() - { - var instanceGlobalId = GlobalObjectId.GetGlobalObjectIdSlow(this); - - // If not editing a prefab, then just use the generated id - if (!IsEditingPrefab()) - { - return instanceGlobalId; - } - - // If the asset doesn't exist at the given path, then return the object identifier - var prefabStageAssetPath = PrefabStageUtility.GetPrefabStage(gameObject).assetPath; - // If (for some reason) the asset path is null return the generated id - if (prefabStageAssetPath == null) - { - return instanceGlobalId; - } - - var theAsset = AssetDatabase.LoadAssetAtPath(prefabStageAssetPath); - // If there is no asset at that path (for some odd/edge case reason), return the generated id - if (theAsset == null) - { - return instanceGlobalId; - } - - // If we can't get the asset GUID and/or the file identifier, then return the object identifier - if (!AssetDatabase.TryGetGUIDAndLocalFileIdentifier(theAsset, out var guid, out long localFileId)) - { - return instanceGlobalId; - } - - // Note: If we reached this point, then we are most likely opening a prefab to edit. - // The instanceGlobalId will be constructed as if it is a scene object, however when it - // is serialized its value will be treated as a file asset (the "why" to the below code). - - // Construct an imported asset identifier with the type being a source asset object type - var prefabGlobalIdText = string.Format(k_GlobalIdTemplate, k_SourceAssetObjectType, guid, (ulong)localFileId, 0); - - // If we can't parse the result log an error and return the instanceGlobalId - if (!GlobalObjectId.TryParse(prefabGlobalIdText, out var prefabGlobalId)) - { - Debug.LogError($"[GlobalObjectId Gen] Failed to parse ({prefabGlobalIdText}) returning default ({instanceGlobalId})! ** Please Report This Error **"); - return instanceGlobalId; - } - - // Otherwise, return the constructed identifier for the source prefab asset - return prefabGlobalId; - } #endif // UNITY_EDITOR /// @@ -396,6 +439,13 @@ public void DeferDespawn(int tickOffset, bool destroy = true) /// public bool IsOwnershipDistributable => Ownership.HasFlag(OwnershipStatus.Distributable); + /// + /// When true, the can only be owned by the current Session Owner. + /// To set during runtime, use to ensure the session owner owns the object. + /// Once the session owner owns the object, then use . + /// + public bool IsOwnershipSessionOwner => Ownership.HasFlag(OwnershipStatus.SessionOwner); + /// /// Returns true if the is has ownership locked. /// When locked, the cannot be redistributed nor can it be transferred by another client. @@ -438,7 +488,8 @@ public void DeferDespawn(int tickOffset, bool destroy = true) /// : 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). + /// : When set, a non-owner must request ownership from the owner (will always get locked once ownership is transferred). + /// : When set, only the current session owner may have ownership over this object. /// // Ranges from 1 to 8 bits [Flags] @@ -448,6 +499,7 @@ public enum OwnershipStatus Distributable = 1 << 0, Transferable = 1 << 1, RequestRequired = 1 << 2, + SessionOwner = 1 << 3, } /// @@ -506,7 +558,7 @@ public bool SetOwnershipLock(bool lockOwnership = true) } // 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) + if (!(IsOwnershipTransferable || IsPlayerObject) || IsOwnershipSessionOwner) { NetworkLog.LogWarning($"Trying to add or remove ownership lock on [{name}] which does not have the {nameof(OwnershipStatus.Transferable)} flag set!"); return false; @@ -539,13 +591,15 @@ public bool SetOwnershipLock(bool lockOwnership = true) /// : The requires an ownership request via . /// : The is already processing an ownership request and ownership cannot be acquired at this time. /// : The does not have the flag set and ownership cannot be acquired. + /// : The has the flag set and ownership cannot be acquired. /// public enum OwnershipPermissionsFailureStatus { Locked, RequestRequired, RequestInProgress, - NotTransferrable + NotTransferrable, + SessionOwnerOnly } /// @@ -567,6 +621,7 @@ public enum OwnershipPermissionsFailureStatus /// : 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 + /// : This object is marked as SessionOwnerOnly and therefore cannot be requested /// a change in ownership or just try again after a specific period of time or no longer attempt to request ownership. /// public enum OwnershipRequestStatus @@ -576,6 +631,7 @@ public enum OwnershipRequestStatus RequestRequiredNotSet, Locked, RequestInProgress, + SessionOwnerOnly, } /// @@ -588,6 +644,7 @@ public enum OwnershipRequestStatus /// : 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 + /// : This object can only belong the the session owner and so cannot be requested /// a change in ownership or just try again after a specific period of time or no longer attempt to request ownership. /// /// @@ -617,6 +674,12 @@ public OwnershipRequestStatus RequestOwnership() return OwnershipRequestStatus.RequestInProgress; } + // Exit early if it has the SessionOwner flag + if (IsOwnershipSessionOwner) + { + return OwnershipRequestStatus.SessionOwnerOnly; + } + // Otherwise, send the request ownership message var changeOwnership = new ChangeOwnershipMessage { @@ -673,7 +736,7 @@ internal void OwnershipRequest(ulong clientRequestingOwnership) { response = OwnershipRequestResponseStatus.RequestInProgress; } - else if (!IsOwnershipRequestRequired && !IsOwnershipTransferable) + else if (!(IsOwnershipRequestRequired || IsOwnershipTransferable) || IsOwnershipSessionOwner) { response = OwnershipRequestResponseStatus.CannotRequest; } @@ -793,6 +856,12 @@ public enum OwnershipLockActions /// public bool SetOwnershipStatus(OwnershipStatus status, bool clearAndSet = false, OwnershipLockActions lockAction = OwnershipLockActions.None) { + if (status.HasFlag(OwnershipStatus.SessionOwner) && !NetworkManager.LocalClient.IsSessionOwner) + { + NetworkLog.LogWarning("Only the session owner is allowed to set the ownership status to session owner only."); + return false; + } + // If it already has the flag do nothing if (!clearAndSet && Ownership.HasFlag(status)) { @@ -804,13 +873,25 @@ public bool SetOwnershipStatus(OwnershipStatus status, bool clearAndSet = false, 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) + if (status.HasFlag(OwnershipStatus.SessionOwner)) + { + Ownership = OwnershipStatus.SessionOwner; + } + else if (Ownership.HasFlag(OwnershipStatus.SessionOwner)) { - SetOwnershipLock(lockAction == OwnershipLockActions.SetAndLock); + NetworkLog.LogWarning("No other ownership statuses may be set while SessionOwner is set."); + return false; + } + else + { + // 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(); @@ -1586,7 +1667,7 @@ internal void SpawnInternal(bool destroyWithScene, ulong ownerClientId, bool pla // 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."); + 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 set ownership to SessionOwner."); } } } @@ -1964,12 +2045,14 @@ public bool TrySetParent(NetworkObject parent, bool worldPositionStays = true) internal bool InternalTrySetParent(NetworkObject parent, bool worldPositionStays = true) { - if (parent != null && (IsSpawned ^ parent.IsSpawned)) + if (parent != null && (IsSpawned ^ parent.IsSpawned) && NetworkManager != null && !NetworkManager.ShutdownInProgress) { - if (NetworkManager != null && !NetworkManager.ShutdownInProgress) + if (NetworkManager.LogLevel <= LogLevel.Developer) { - return false; + var nameOfNotSpawnedObject = IsSpawned ? $" the parent ({parent.name})" : $"the child ({name})"; + NetworkLog.LogWarning($"Parenting failed because {nameOfNotSpawnedObject} is not spawned!"); } + return false; } m_CachedWorldPositionStays = worldPositionStays; @@ -2892,7 +2975,7 @@ internal SceneObject GetMessageSceneObject(ulong targetClientId = NetworkManager SyncObservers = syncObservers, Observers = syncObservers ? Observers.ToArray() : null, NetworkSceneHandle = NetworkSceneHandle, - Hash = HostCheckForGlobalObjectIdHashOverride(), + Hash = CheckForGlobalObjectIdHashOverride(), OwnerObject = this, TargetClientId = targetClientId }; @@ -3244,14 +3327,15 @@ internal void UpdateForSceneChanges() } /// - /// Only applies to Host mode. + /// Client-Server: Only applies to spawn authority (i.e. Server) + /// Distributed Authority: Applies to all clients since they all have spawn authority. /// Will return the registered source NetworkPrefab's GlobalObjectIdHash if one exists. /// Server and Clients will always return the NetworkObject's GlobalObjectIdHash. /// - /// - internal uint HostCheckForGlobalObjectIdHashOverride() + /// appropriate hash value + internal uint CheckForGlobalObjectIdHashOverride() { - if (NetworkManager.IsServer) + if (NetworkManager.IsServer || NetworkManager.DistributedAuthorityMode) { if (NetworkManager.PrefabHandler.ContainsHandler(this)) { diff --git a/Runtime/Core/NetworkObjectRefreshTool.cs b/Runtime/Core/NetworkObjectRefreshTool.cs index 63d48e9..5309377 100644 --- a/Runtime/Core/NetworkObjectRefreshTool.cs +++ b/Runtime/Core/NetworkObjectRefreshTool.cs @@ -11,7 +11,7 @@ namespace Unity.Netcode { /// - /// This is a helper tool to update all in-scene placed instances of a prefab that + /// This is a helper tool to update all in-scene placed instances of a prefab that /// originally did not have a NetworkObject component but one was added to the prefab /// later. /// diff --git a/Runtime/Messaging/ILPPMessageProvider.cs b/Runtime/Messaging/ILPPMessageProvider.cs index b7f90f6..4e697ac 100644 --- a/Runtime/Messaging/ILPPMessageProvider.cs +++ b/Runtime/Messaging/ILPPMessageProvider.cs @@ -16,7 +16,7 @@ internal struct ILPPMessageProvider : INetworkMessageProvider /// /// Enum representing the different types of messages that can be sent over the network. /// The values cannot be changed, as they are used to serialize and deserialize messages. - /// Adding new messages should be done by adding new values to the end of the enum + /// Adding new messages should be done by adding new values to the end of the enum /// using the next free value. /// /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! diff --git a/Runtime/Messaging/Messages/ChangeOwnershipMessage.cs b/Runtime/Messaging/Messages/ChangeOwnershipMessage.cs index d418789..998e84d 100644 --- a/Runtime/Messaging/Messages/ChangeOwnershipMessage.cs +++ b/Runtime/Messaging/Messages/ChangeOwnershipMessage.cs @@ -17,7 +17,7 @@ internal struct ChangeOwnershipMessage : INetworkMessage, INetworkSerializeByMem /// /// When requesting, RequestClientId is the requestor. /// When approving, RequestClientId is the owner that approved. - /// When responding (only for denied), RequestClientId is the requestor + /// When responding (only for denied), RequestClientId is the requestor /// internal ulong RequestClientId; internal int ClientIdCount; @@ -272,7 +272,7 @@ public void Handle(ref NetworkContext context) networkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.Reliable, clientId); } } - // If the NetworkObject is not visible to the DAHost client, then exit early + // If the NetworkObject is not visible to the DAHost client, then exit early if (!networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId)) { return; @@ -294,7 +294,7 @@ public void Handle(ref NetworkContext context) } /// - /// Handle the + /// Handle the extended distributed authority ownership updates /// /// private void HandleExtendedOwnershipUpdate(ref NetworkContext context) @@ -332,8 +332,8 @@ private void HandleOwnershipChange(ref NetworkContext context) // Sanity check that we are not sending duplicated change ownership messages if (networkObject.OwnerClientId == OwnerClientId) { - UnityEngine.Debug.LogError($"Unnecessary ownership changed message for {NetworkObjectId}."); - // Ignore the message + // Log error and then ignore the message + UnityEngine.Debug.LogError($"Client-{context.SenderId} ({RequestClientId}) sent unnecessary ownership changed message for {NetworkObjectId}."); return; } @@ -351,10 +351,10 @@ private void HandleOwnershipChange(ref NetworkContext context) networkObject.InvokeBehaviourOnLostOwnership(); } - // If in distributed authority mode + // If in distributed authority mode if (networkManager.DistributedAuthorityMode) { - // Always update the network properties in distributed authority mode + // Always update the network properties in distributed authority mode for (int i = 0; i < networkObject.ChildNetworkBehaviours.Count; i++) { networkObject.ChildNetworkBehaviours[i].UpdateNetworkProperties(); diff --git a/Runtime/Messaging/Messages/ClientConnectedMessage.cs b/Runtime/Messaging/Messages/ClientConnectedMessage.cs index ef7ef5f..0234bc8 100644 --- a/Runtime/Messaging/Messages/ClientConnectedMessage.cs +++ b/Runtime/Messaging/Messages/ClientConnectedMessage.cs @@ -55,19 +55,24 @@ public void Handle(ref NetworkContext context) // Don't redistribute for the local instance if (ClientId != networkManager.LocalClientId) { + // Synchronize the client with spawned objects (relative to each client) + networkManager.SpawnManager.SynchronizeObjectsToNewlyJoinedClient(ClientId); + + // Keeping for reference in case the above doesn't resolve for hidden objects (theoretically it should) // Show any NetworkObjects that are: // - Hidden from the session owner // - Owned by this client // - Has NetworkObject.SpawnWithObservers set to true (the default) - if (!networkManager.LocalClient.IsSessionOwner) - { - networkManager.SpawnManager.ShowHiddenObjectsToNewlyJoinedClient(ClientId); - } + //if (!networkManager.LocalClient.IsSessionOwner) + //{ + // networkManager.SpawnManager.ShowHiddenObjectsToNewlyJoinedClient(ClientId); + //} - // We defer redistribution to the end of the NetworkUpdateStage.PostLateUpdate - networkManager.RedistributeToClient = true; - networkManager.ClientToRedistribute = ClientId; - networkManager.TickToRedistribute = networkManager.ServerTime.Tick + 20; + /// We defer redistribution to happen after NetworkShow has been invoked + /// + /// DANGO-TODO: Determine if this needs to be removed once the service handles object distribution + networkManager.RedistributeToClients = true; + networkManager.ClientsToRedistribute.Add(ClientId); } } } diff --git a/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs b/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs index 7b9a87f..5005c19 100644 --- a/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs +++ b/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs @@ -5,23 +5,38 @@ namespace Unity.Netcode { internal struct ServiceConfig : INetworkSerializable { - public uint Version; + public uint SessionVersion; public bool IsRestoredSession; public ulong CurrentSessionOwner; + public bool ServerRedistribution; public void NetworkSerialize(BufferSerializer serializer) where T : IReaderWriter { if (serializer.IsWriter) { - BytePacker.WriteValueBitPacked(serializer.GetFastBufferWriter(), Version); + BytePacker.WriteValueBitPacked(serializer.GetFastBufferWriter(), SessionVersion); serializer.SerializeValue(ref IsRestoredSession); BytePacker.WriteValueBitPacked(serializer.GetFastBufferWriter(), CurrentSessionOwner); + + if (SessionVersion >= SessionConfig.ServerDistributionCompatible) + { + serializer.SerializeValue(ref ServerRedistribution); + } } else { - ByteUnpacker.ReadValueBitPacked(serializer.GetFastBufferReader(), out Version); + ByteUnpacker.ReadValueBitPacked(serializer.GetFastBufferReader(), out SessionVersion); serializer.SerializeValue(ref IsRestoredSession); ByteUnpacker.ReadValueBitPacked(serializer.GetFastBufferReader(), out CurrentSessionOwner); + + if (SessionVersion >= SessionConfig.ServerDistributionCompatible) + { + serializer.SerializeValue(ref ServerRedistribution); + } + else + { + ServerRedistribution = false; + } } } } @@ -190,11 +205,13 @@ public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int if (receivedMessageVersion >= k_AddCMBServiceConfig) { reader.ReadNetworkSerializable(out ServiceConfig); + networkManager.SessionConfig = new SessionConfig(ServiceConfig); } else { reader.ReadValueSafe(out IsRestoredSession); ByteUnpacker.ReadValueBitPacked(reader, out CurrentSessionOwner); + networkManager.SessionConfig = new SessionConfig(SessionConfig.NoFeatureCompatibility); } } diff --git a/Runtime/Messaging/Messages/ConnectionRequestMessage.cs b/Runtime/Messaging/Messages/ConnectionRequestMessage.cs index d8e60d2..11aa4f3 100644 --- a/Runtime/Messaging/Messages/ConnectionRequestMessage.cs +++ b/Runtime/Messaging/Messages/ConnectionRequestMessage.cs @@ -7,31 +7,28 @@ namespace Unity.Netcode /// internal struct ClientConfig : INetworkSerializable { - /// - /// We start at version 1, where anything less than version 1 on the service side - /// is not bypass feature compatible. - /// - private const int k_BypassFeatureCompatible = 1; - public int Version => k_BypassFeatureCompatible; + public SessionConfig SessionConfig; + public int SessionVersion => (int)SessionConfig.SessionVersion; public uint TickRate; public bool EnableSceneManagement; // Only gets deserialized but should never be used unless testing - public int RemoteClientVersion; + public int RemoteClientSessionVersion; public void NetworkSerialize(BufferSerializer serializer) where T : IReaderWriter { + // Clients always write if (serializer.IsWriter) { var writer = serializer.GetFastBufferWriter(); - BytePacker.WriteValueBitPacked(writer, Version); + BytePacker.WriteValueBitPacked(writer, SessionVersion); BytePacker.WriteValueBitPacked(writer, TickRate); writer.WriteValueSafe(EnableSceneManagement); } else { var reader = serializer.GetFastBufferReader(); - ByteUnpacker.ReadValueBitPacked(reader, out RemoteClientVersion); + ByteUnpacker.ReadValueBitPacked(reader, out RemoteClientSessionVersion); ByteUnpacker.ReadValueBitPacked(reader, out TickRate); reader.ReadValueSafe(out EnableSceneManagement); } @@ -40,6 +37,8 @@ public void NetworkSerialize(BufferSerializer serializer) where T : IReade internal struct ConnectionRequestMessage : INetworkMessage { + internal const string InvalidSessionVersionMessage = "The client version is not compatible with the session version."; + // This version update is unidirectional (client to service) and version // handling occurs on the service side. This serialized data is never sent // to a host or server. @@ -47,7 +46,7 @@ internal struct ConnectionRequestMessage : INetworkMessage public int Version => k_SendClientConfigToService; public ulong ConfigHash; - public bool CMBServiceConnection; + public bool DistributedAuthority; public ClientConfig ClientConfig; public byte[] ConnectionData; @@ -72,7 +71,7 @@ public void Serialize(FastBufferWriter writer, int targetVersion) // END FORBIDDEN SEGMENT // ============================================================ - if (CMBServiceConnection) + if (DistributedAuthority) { writer.WriteNetworkSerializable(ClientConfig); } @@ -120,6 +119,11 @@ public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int // END FORBIDDEN SEGMENT // ============================================================ + if (networkManager.DAHost) + { + reader.ReadNetworkSerializable(out ClientConfig); + } + if (networkManager.NetworkConfig.ConnectionApproval) { if (!reader.TryBeginRead(FastBufferWriter.GetWriteSize(ConfigHash) + FastBufferWriter.GetWriteSize())) @@ -182,6 +186,17 @@ public void Handle(ref NetworkContext context) var networkManager = (NetworkManager)context.SystemOwner; var senderId = context.SenderId; + // DAHost mocking the service logic to disconnect clients trying to connect with a lower session version + if (networkManager.DAHost) + { + if (ClientConfig.RemoteClientSessionVersion < networkManager.SessionConfig.SessionVersion) + { + //Disconnect with reason + networkManager.ConnectionManager.DisconnectClient(senderId, InvalidSessionVersionMessage); + return; + } + } + if (networkManager.ConnectionManager.PendingClients.TryGetValue(senderId, out PendingClient client)) { // Set to pending approval to prevent future connection requests from being approved diff --git a/Runtime/Messaging/Messages/CreateObjectMessage.cs b/Runtime/Messaging/Messages/CreateObjectMessage.cs index 6c0656b..02f4263 100644 --- a/Runtime/Messaging/Messages/CreateObjectMessage.cs +++ b/Runtime/Messaging/Messages/CreateObjectMessage.cs @@ -257,7 +257,7 @@ internal static void CreateObject(ref NetworkManager networkManager, ulong sende { // 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 + // 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. diff --git a/Runtime/Messaging/Messages/NetworkTransformMessage.cs b/Runtime/Messaging/Messages/NetworkTransformMessage.cs index 56f25f2..cf4013f 100644 --- a/Runtime/Messaging/Messages/NetworkTransformMessage.cs +++ b/Runtime/Messaging/Messages/NetworkTransformMessage.cs @@ -128,7 +128,7 @@ public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int } else if (networkManager.DAHost) { - // Specific to distributed authority mode, the only sender of state updates will be the owner + // Specific to distributed authority mode, the only sender of state updates will be the owner ownerClientId = context.SenderId; } diff --git a/Runtime/Messaging/Messages/ParentSyncMessage.cs b/Runtime/Messaging/Messages/ParentSyncMessage.cs index bef5fe8..33caa7d 100644 --- a/Runtime/Messaging/Messages/ParentSyncMessage.cs +++ b/Runtime/Messaging/Messages/ParentSyncMessage.cs @@ -70,10 +70,6 @@ public void Serialize(FastBufferWriter writer, int targetVersion) public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) { var networkManager = (NetworkManager)context.SystemOwner; - if (!networkManager.IsClient) - { - return false; - } ByteUnpacker.ReadValueBitPacked(reader, out NetworkObjectId); reader.ReadValueSafe(out m_BitField); diff --git a/Runtime/Messaging/NetworkMessageManager.cs b/Runtime/Messaging/NetworkMessageManager.cs index 1850725..661fbd7 100644 --- a/Runtime/Messaging/NetworkMessageManager.cs +++ b/Runtime/Messaging/NetworkMessageManager.cs @@ -141,28 +141,6 @@ public NetworkMessageManager(INetworkMessageSender sender, object owner, INetwor { 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) { diff --git a/Runtime/Messaging/RpcTargets/ClientsAndHostRpcTarget.cs b/Runtime/Messaging/RpcTargets/ClientsAndHostRpcTarget.cs index 286b0b0..373e43f 100644 --- a/Runtime/Messaging/RpcTargets/ClientsAndHostRpcTarget.cs +++ b/Runtime/Messaging/RpcTargets/ClientsAndHostRpcTarget.cs @@ -17,7 +17,8 @@ internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, // ClientsAndHost sends to everyone who runs any client logic // So if the server is a host, this target includes it (as hosts run client logic) // If the server is not a host, this target leaves it out, ergo the selection of NotServer. - if (behaviour.NetworkManager.ServerIsHost) + // If we are in distributed authority mode and connected to a service, then send to all clients. + if (behaviour.NetworkManager.ServerIsHost || (m_NetworkManager.DistributedAuthorityMode && m_NetworkManager.CMBServiceConnection)) { m_UnderlyingTarget = behaviour.RpcTarget.Everyone; } diff --git a/Runtime/Messaging/RpcTargets/NotOwnerRpcTarget.cs b/Runtime/Messaging/RpcTargets/NotOwnerRpcTarget.cs index e4f64f0..348c1af 100644 --- a/Runtime/Messaging/RpcTargets/NotOwnerRpcTarget.cs +++ b/Runtime/Messaging/RpcTargets/NotOwnerRpcTarget.cs @@ -4,12 +4,14 @@ internal class NotOwnerRpcTarget : BaseRpcTarget { private IGroupRpcTarget m_GroupSendTarget; private ServerRpcTarget m_ServerRpcTarget; + private NotAuthorityRpcTarget m_NotAuthorityRpcTarget; private LocalSendRpcTarget m_LocalSendRpcTarget; public override void Dispose() { m_ServerRpcTarget.Dispose(); m_LocalSendRpcTarget.Dispose(); + m_NotAuthorityRpcTarget.Dispose(); if (m_GroupSendTarget != null) { m_GroupSendTarget.Target.Dispose(); @@ -19,6 +21,13 @@ public override void Dispose() internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams) { + // Not owner is the same as not authority in distributed authority mode + if (m_NetworkManager.DistributedAuthorityMode) + { + m_NotAuthorityRpcTarget.Send(behaviour, ref message, delivery, rpcParams); + return; + } + if (m_GroupSendTarget == null) { if (behaviour.IsServer) @@ -86,6 +95,7 @@ internal NotOwnerRpcTarget(NetworkManager manager) : base(manager) { m_ServerRpcTarget = new ServerRpcTarget(manager); m_LocalSendRpcTarget = new LocalSendRpcTarget(manager); + m_NotAuthorityRpcTarget = new NotAuthorityRpcTarget(manager); } } } diff --git a/Runtime/Messaging/RpcTargets/NotServerRpcTarget.cs b/Runtime/Messaging/RpcTargets/NotServerRpcTarget.cs index 30b745e..3ac0b23 100644 --- a/Runtime/Messaging/RpcTargets/NotServerRpcTarget.cs +++ b/Runtime/Messaging/RpcTargets/NotServerRpcTarget.cs @@ -51,7 +51,13 @@ internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, continue; } - if (clientId == behaviour.NetworkManager.LocalClientId) + // If we are in distributed authority mode and connected to the service, then we exclude the owner/authority from the list + if (m_NetworkManager.DistributedAuthorityMode && m_NetworkManager.CMBServiceConnection && clientId == behaviour.OwnerClientId) + { + continue; + } + + if (clientId == m_NetworkManager.LocalClientId) { m_LocalSendRpcTarget.Send(behaviour, ref message, delivery, rpcParams); continue; diff --git a/Runtime/Messaging/RpcTargets/OwnerRpcTarget.cs b/Runtime/Messaging/RpcTargets/OwnerRpcTarget.cs index 7c78294..e22c588 100644 --- a/Runtime/Messaging/RpcTargets/OwnerRpcTarget.cs +++ b/Runtime/Messaging/RpcTargets/OwnerRpcTarget.cs @@ -5,9 +5,12 @@ internal class OwnerRpcTarget : BaseRpcTarget private IIndividualRpcTarget m_UnderlyingTarget; private LocalSendRpcTarget m_LocalRpcTarget; private ServerRpcTarget m_ServerRpcTarget; + private AuthorityRpcTarget m_AuthorityRpcTarget; public override void Dispose() { + m_AuthorityRpcTarget.Dispose(); + m_ServerRpcTarget.Dispose(); m_LocalRpcTarget.Dispose(); if (m_UnderlyingTarget != null) { @@ -18,6 +21,13 @@ public override void Dispose() internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams) { + // Sending to owner is the same as sending to authority in distributed authority mode + if (m_NetworkManager.DistributedAuthorityMode) + { + m_AuthorityRpcTarget.Send(behaviour, ref message, delivery, rpcParams); + return; + } + if (behaviour.OwnerClientId == behaviour.NetworkManager.LocalClientId) { m_LocalRpcTarget.Send(behaviour, ref message, delivery, rpcParams); @@ -49,6 +59,7 @@ internal OwnerRpcTarget(NetworkManager manager) : base(manager) { m_LocalRpcTarget = new LocalSendRpcTarget(manager); m_ServerRpcTarget = new ServerRpcTarget(manager); + m_AuthorityRpcTarget = new AuthorityRpcTarget(manager); } } } diff --git a/Runtime/Messaging/RpcTargets/RpcTarget.cs b/Runtime/Messaging/RpcTargets/RpcTarget.cs index c5706a8..2864205 100644 --- a/Runtime/Messaging/RpcTargets/RpcTarget.cs +++ b/Runtime/Messaging/RpcTargets/RpcTarget.cs @@ -79,9 +79,28 @@ public enum SendTo SpecifiedInParams } + /// + /// This parameter configures a performance optimization. This optimization is not valid in all situations.
+ /// Because BaseRpcTarget is a managed type, allocating a new one is expensive, as it puts pressure on the garbage collector. + ///
+ /// + /// When using a allocation type for the RPC target(s):
+ /// You typically don't need to worry about persisting the generated. + /// When using a allocation type for the RPC target(s):
+ /// You will want to use , which returns , during initialization (i.e. ) and it to a property.
+ /// Then, When invoking the RPC, you would use your which is a persisted allocation of a given set of client identifiers. + /// !! Important !!
+ /// You will want to invoke of any persisted properties created via when despawning or destroying the associated component's . Not doing so will result in small memory leaks. + ///
public enum RpcTargetUse { + /// + /// Creates a temporary used for the frame an decorated method is invoked. + /// Temp, + /// + /// Creates a persisted that does not change and will persist until is called. + /// Persistent } diff --git a/Runtime/Messaging/RpcTargets/ServerRpcTarget.cs b/Runtime/Messaging/RpcTargets/ServerRpcTarget.cs index 8ad53fb..87bfbfb 100644 --- a/Runtime/Messaging/RpcTargets/ServerRpcTarget.cs +++ b/Runtime/Messaging/RpcTargets/ServerRpcTarget.cs @@ -1,8 +1,10 @@ +using Unity.Collections; namespace Unity.Netcode { internal class ServerRpcTarget : BaseRpcTarget { protected BaseRpcTarget m_UnderlyingTarget; + protected ProxyRpcTarget m_ProxyRpcTarget; public override void Dispose() { @@ -11,13 +13,62 @@ public override void Dispose() m_UnderlyingTarget.Dispose(); m_UnderlyingTarget = null; } + + if (m_ProxyRpcTarget != null) + { + m_ProxyRpcTarget.Dispose(); + m_ProxyRpcTarget = null; + } } internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams) { + // For distributed authority the "server" is considered the authority of the object if (behaviour.NetworkManager.DistributedAuthorityMode && behaviour.NetworkManager.CMBServiceConnection) { - UnityEngine.Debug.LogWarning("[Invalid Target] There is no server to send to when in Distributed Authority mode!"); + // If the local instance is the owner, then invoke the message locally on this behaviour + if (behaviour.IsOwner) + { + var context = new NetworkContext + { + SenderId = m_NetworkManager.LocalClientId, + Timestamp = m_NetworkManager.RealTimeProvider.RealTimeSinceStartup, + SystemOwner = m_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(), + SerializedHeaderSize = 0, + MessageSize = 0 + }; + using var tempBuffer = new FastBufferReader(message.WriteBuffer, Allocator.None); + message.ReadBuffer = tempBuffer; + message.Handle(ref context); + // If enabled, then add the RPC metrics for this +#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE + int length = tempBuffer.Length; + if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName)) + { + m_NetworkManager.NetworkMetrics.TrackRpcSent( + m_NetworkManager.LocalClientId, + behaviour.NetworkObject, + rpcMethodName, + behaviour.__getTypeName(), + length); + } +#endif + } + else // Otherwise, send a proxied message to the owner of the object + { + if (m_ProxyRpcTarget == null) + { + m_ProxyRpcTarget = new ProxyRpcTarget(behaviour.OwnerClientId, m_NetworkManager); + } + else + { + m_ProxyRpcTarget.SetClientId(behaviour.OwnerClientId); + } + m_ProxyRpcTarget.Send(behaviour, ref message, delivery, rpcParams); + } return; } diff --git a/Runtime/NetworkVariable/Collections/NetworkList.cs b/Runtime/NetworkVariable/Collections/NetworkList.cs index 203632c..4a34997 100644 --- a/Runtime/NetworkVariable/Collections/NetworkList.cs +++ b/Runtime/NetworkVariable/Collections/NetworkList.cs @@ -24,7 +24,6 @@ public class NetworkList : NetworkVariableBase where T : unmanaged, IEquatabl /// The callback to be invoked when the list gets changed ///
public event OnListChangedDelegate OnListChanged; - internal override NetworkVariableType Type => NetworkVariableType.NetworkList; /// /// Constructor method for @@ -50,6 +49,11 @@ public NetworkList(IEnumerable values = default, } } + ~NetworkList() + { + Dispose(); + } + /// public override void ResetDirty() { @@ -131,20 +135,6 @@ public override void WriteDelta(FastBufferWriter writer) /// public override void WriteField(FastBufferWriter writer) { - if (m_NetworkManager.DistributedAuthorityMode) - { - writer.WriteValueSafe(NetworkVariableSerialization.Serializer.Type); - if (NetworkVariableSerialization.Serializer.Type == NetworkVariableType.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.Serializer.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++) { @@ -156,15 +146,6 @@ public override void WriteField(FastBufferWriter writer) public override void ReadField(FastBufferReader reader) { m_List.Clear(); - if (m_NetworkManager.DistributedAuthorityMode) - { - SerializationTools.ReadType(reader, NetworkVariableSerialization.Serializer); - // Collection item type is used by the DA server, drop value here. - if (NetworkVariableSerialization.Serializer.Type == NetworkVariableType.Unmanaged) - { - ByteUnpacker.ReadValueBitPacked(reader, out int _); - } - } reader.ReadValueSafe(out ushort count); for (int i = 0; i < count; i++) { @@ -624,8 +605,16 @@ public int LastModifiedTick /// public override void Dispose() { - m_List.Dispose(); - m_DirtyEvents.Dispose(); + if (m_List.IsCreated) + { + m_List.Dispose(); + } + + if (m_DirtyEvents.IsCreated) + { + m_DirtyEvents.Dispose(); + } + base.Dispose(); } } diff --git a/Runtime/NetworkVariable/NetworkVariable.cs b/Runtime/NetworkVariable/NetworkVariable.cs index 16ca42a..c712a90 100644 --- a/Runtime/NetworkVariable/NetworkVariable.cs +++ b/Runtime/NetworkVariable/NetworkVariable.cs @@ -45,8 +45,6 @@ public override void OnInitialize() NetworkVariableSerialization.Duplicate(m_InternalValue, ref m_PreviousValue); } - internal override NetworkVariableType Type => NetworkVariableType.Value; - /// /// Constructor for /// @@ -92,7 +90,7 @@ public void Reset(T value = default) // The introduction of standard .NET collections caused an issue with permissions since there is no way to detect changes in the // collection without doing a full comparison. While this approach does consume more memory per collection instance, it is the // lowest risk approach to resolving the issue where a client with no write permissions could make changes to a collection locally - // which can cause a myriad of issues. + // which can cause a myriad of issues. private protected T m_InternalOriginalValue; private protected T m_PreviousValue; @@ -181,19 +179,26 @@ public override void Dispose() } m_IsDisposed = true; + // Dispose the internal value if (m_InternalValue is IDisposable internalValueDisposable) { internalValueDisposable.Dispose(); } - m_InternalValue = default; + + // Dispose the internal original value + if (m_InternalOriginalValue is IDisposable internalOriginalValueDisposable) + { + internalOriginalValueDisposable.Dispose(); + } m_InternalOriginalValue = default; + + // Dispose the previous value if there is one if (m_HasPreviousValue && m_PreviousValue is IDisposable previousValueDisposable) { m_HasPreviousValue = false; previousValueDisposable.Dispose(); } - m_PreviousValue = default; base.Dispose(); @@ -298,7 +303,7 @@ public override void ReadDelta(FastBufferReader reader, bool keepDirtyDelta) /// This should be always invoked (client & server) to assure the previous values are set /// !! IMPORTANT !! /// When a server forwards delta updates to connected clients, it needs to preserve the previous dirty value(s) - /// until it is done serializing all valid NetworkVariable field deltas (relative to each client). This is invoked + /// until it is done serializing all valid NetworkVariable field deltas (relative to each client). This is invoked /// after it is done forwarding the deltas at the end of the method. ///
internal override void PostDeltaRead() diff --git a/Runtime/NetworkVariable/NetworkVariableBase.cs b/Runtime/NetworkVariable/NetworkVariableBase.cs index 8802397..537d3eb 100644 --- a/Runtime/NetworkVariable/NetworkVariableBase.cs +++ b/Runtime/NetworkVariable/NetworkVariableBase.cs @@ -35,8 +35,6 @@ public abstract class NetworkVariableBase : IDisposable private NetworkManager m_InternalNetworkManager; - internal virtual NetworkVariableType Type => NetworkVariableType.Unknown; - internal string GetWritePermissionError() { return $"|Client-{m_NetworkManager.LocalClientId}|{m_NetworkBehaviour.name}|{Name}| Write permissions ({WritePerm}) for this client instance is not allowed!"; @@ -351,7 +349,7 @@ internal ulong OwnerClientId() /// This should be always invoked (client & server) to assure the previous values are set /// !! IMPORTANT !! /// When a server forwards delta updates to connected clients, it needs to preserve the previous dirty value(s) - /// until it is done serializing all valid NetworkVariable field deltas (relative to each client). This is invoked + /// until it is done serializing all valid NetworkVariable field deltas (relative to each client). This is invoked /// after it is done forwarding the deltas at the end of the method. ///
internal virtual void PostDeltaRead() diff --git a/Runtime/NetworkVariable/NetworkVariableTypes.cs b/Runtime/NetworkVariable/NetworkVariableTypes.cs deleted file mode 100644 index d8b6912..0000000 --- a/Runtime/NetworkVariable/NetworkVariableTypes.cs +++ /dev/null @@ -1,40 +0,0 @@ -#if UNITY_EDITOR -#endif - -namespace Unity.Netcode -{ - /// - /// Enum representing the different types of Network Variables that can be sent over the network. - /// The values cannot be changed, as they are used to serialize and deserialize variables on the DA server. - /// Adding new variables should be done by adding new values to the end of the enum - /// using the next free value. - /// - /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - /// Add any new Variable types to this table at the END with incremented index value - /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - internal enum NetworkVariableType : byte - { - /// - /// Value - /// Used for all of the basic NetworkVariables that contain a single value - /// - Value = 0, - /// - /// For any type that is not known at runtime - /// - Unknown = 1, - /// - /// NetworkList - /// - NetworkList = 2, - - // The following types are valid types inside of NetworkVariable collections - Short = 11, - UShort = 12, - Int = 13, - UInt = 14, - Long = 15, - ULong = 16, - Unmanaged = 17, - } -} diff --git a/Runtime/NetworkVariable/NetworkVariableTypes.cs.meta b/Runtime/NetworkVariable/NetworkVariableTypes.cs.meta deleted file mode 100644 index 4206dbc..0000000 --- a/Runtime/NetworkVariable/NetworkVariableTypes.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: df4a4005f1c842669f94a404019400ed -timeCreated: 1718292058 \ No newline at end of file diff --git a/Runtime/NetworkVariable/Serialization/FallbackSerializer.cs b/Runtime/NetworkVariable/Serialization/FallbackSerializer.cs index 0b1b2c1..5e85574 100644 --- a/Runtime/NetworkVariable/Serialization/FallbackSerializer.cs +++ b/Runtime/NetworkVariable/Serialization/FallbackSerializer.cs @@ -14,9 +14,6 @@ namespace Unity.Netcode /// internal class FallbackSerializer : INetworkVariableSerializer { - public NetworkVariableType Type => NetworkVariableType.Unknown; - public bool IsDistributedAuthorityOptimized => true; - private void ThrowArgumentError() { throw new ArgumentException($"Serialization has not been generated for type {typeof(T).FullName}. This can be addressed by adding a [{nameof(GenerateSerializationForGenericParameterAttribute)}] to your generic class that serializes this value (if you are using one), adding [{nameof(GenerateSerializationForTypeAttribute)}(typeof({typeof(T).FullName})] to the class or method that is attempting to serialize it, or creating a field on a {nameof(NetworkBehaviour)} of type {nameof(NetworkVariable)}. If this error continues to appear after doing one of those things and this is a type you can change, then either implement {nameof(INetworkSerializable)} or mark it as serializable by memcpy by adding {nameof(INetworkSerializeByMemcpy)} to its interface list to enable automatic serialization generation. If not, assign serialization code to {nameof(UserNetworkVariableSerialization)}.{nameof(UserNetworkVariableSerialization.WriteValue)}, {nameof(UserNetworkVariableSerialization)}.{nameof(UserNetworkVariableSerialization.ReadValue)}, and {nameof(UserNetworkVariableSerialization)}.{nameof(UserNetworkVariableSerialization.DuplicateValue)}, or if it's serializable by memcpy (contains no pointers), wrap it in {typeof(ForceNetworkSerializeByMemcpy<>).Name}."); @@ -82,11 +79,6 @@ public void Duplicate(in T value, ref T duplicatedValue) } UserNetworkVariableSerialization.DuplicateValue(value, ref duplicatedValue); } - - public void WriteDistributedAuthority(FastBufferWriter writer, ref T value) => ThrowArgumentError(); - public void ReadDistributedAuthority(FastBufferReader reader, ref T value) => ThrowArgumentError(); - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => ThrowArgumentError(); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => ThrowArgumentError(); } // RuntimeAccessModifiersILPP will make this `public` diff --git a/Runtime/NetworkVariable/Serialization/INetworkVariableSerializer.cs b/Runtime/NetworkVariable/Serialization/INetworkVariableSerializer.cs index 571d1dc..d515c0c 100644 --- a/Runtime/NetworkVariable/Serialization/INetworkVariableSerializer.cs +++ b/Runtime/NetworkVariable/Serialization/INetworkVariableSerializer.cs @@ -2,28 +2,8 @@ namespace Unity.Netcode { - /// - /// Interface used by NetworkVariables to serialize them with additional information for the DA runtime - /// - /// /// - internal interface IDistributedAuthoritySerializer - { - /// - /// The Type tells the DA server how to parse this type. - /// The user should never be able to override this value, as it is meaningful for the DA server - /// - public NetworkVariableType Type { get; } - public bool IsDistributedAuthorityOptimized { get; } - public void WriteDistributedAuthority(FastBufferWriter writer, ref T value); - public void ReadDistributedAuthority(FastBufferReader reader, ref T value); - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value); - } - - - /// - internal interface INetworkVariableSerializer : IDistributedAuthoritySerializer + internal interface INetworkVariableSerializer { // Write has to be taken by ref here because of INetworkSerializable // Open Instance Delegates (pointers to methods without an instance attached to them) diff --git a/Runtime/NetworkVariable/Serialization/NetworkVariableSerialization.cs b/Runtime/NetworkVariable/Serialization/NetworkVariableSerialization.cs index bc0f79f..8401df8 100644 --- a/Runtime/NetworkVariable/Serialization/NetworkVariableSerialization.cs +++ b/Runtime/NetworkVariable/Serialization/NetworkVariableSerialization.cs @@ -14,8 +14,6 @@ public static class NetworkVariableSerialization { internal static INetworkVariableSerializer Serializer = new FallbackSerializer(); - internal static bool IsDistributedAuthority => NetworkManager.IsDistributedAuthority; - /// /// A callback to check if two values are equal. /// @@ -53,20 +51,7 @@ public static class NetworkVariableSerialization /// public static void Write(FastBufferWriter writer, ref T value) { - if (IsDistributedAuthority) - { -#if DEVELOPMENT_BUILD || UNITY_EDITOR - if (!NetworkManager.DisableNotOptimizedSerializedType && !Serializer.IsDistributedAuthorityOptimized) - { - NetworkManager.LogSerializedTypeNotOptimized(); - } -#endif - Serializer.WriteDistributedAuthority(writer, ref value); - } - else - { - Serializer.Write(writer, ref value); - } + Serializer.Write(writer, ref value); } /// @@ -91,14 +76,7 @@ public static void Write(FastBufferWriter writer, ref T value) /// public static void Read(FastBufferReader reader, ref T value) { - if (IsDistributedAuthority) - { - Serializer.ReadDistributedAuthority(reader, ref value); - } - else - { - Serializer.Read(reader, ref value); - } + Serializer.Read(reader, ref value); } /// @@ -120,20 +98,7 @@ public static void Read(FastBufferReader reader, ref T value) /// public static void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue) { - if (IsDistributedAuthority) - { -#if DEVELOPMENT_BUILD || UNITY_EDITOR - if (!NetworkManager.DisableNotOptimizedSerializedType && !Serializer.IsDistributedAuthorityOptimized) - { - NetworkManager.LogSerializedTypeNotOptimized(); - } -#endif - Serializer.WriteDeltaDistributedAuthority(writer, ref value, ref previousValue); - } - else - { - Serializer.WriteDelta(writer, ref value, ref previousValue); - } + Serializer.WriteDelta(writer, ref value, ref previousValue); } /// @@ -158,14 +123,7 @@ public static void WriteDelta(FastBufferWriter writer, ref T value, ref T previo /// public static void ReadDelta(FastBufferReader reader, ref T value) { - if (IsDistributedAuthority) - { - Serializer.ReadDeltaDistributedAuthority(reader, ref value); - } - else - { - Serializer.ReadDelta(reader, ref value); - } + Serializer.ReadDelta(reader, ref value); } /// diff --git a/Runtime/NetworkVariable/Serialization/TypedSerializerImplementations.cs b/Runtime/NetworkVariable/Serialization/TypedSerializerImplementations.cs index 9f5a104..49e7e5e 100644 --- a/Runtime/NetworkVariable/Serialization/TypedSerializerImplementations.cs +++ b/Runtime/NetworkVariable/Serialization/TypedSerializerImplementations.cs @@ -10,21 +10,6 @@ namespace Unity.Netcode /// internal class ShortSerializer : INetworkVariableSerializer { - public NetworkVariableType Type => NetworkVariableType.Short; - public bool IsDistributedAuthorityOptimized => true; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref short value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref short value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref short value, ref short previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref short value) => Read(reader, ref value); - public void Write(FastBufferWriter writer, ref short value) { BytePacker.WriteValueBitPacked(writer, value); @@ -61,20 +46,6 @@ public void Duplicate(in short value, ref short duplicatedValue) /// internal class UshortSerializer : INetworkVariableSerializer { - public NetworkVariableType Type => NetworkVariableType.UShort; - public bool IsDistributedAuthorityOptimized => true; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref ushort value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref ushort value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref ushort value, ref ushort previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref ushort value) => Read(reader, ref value); public void Write(FastBufferWriter writer, ref ushort value) { BytePacker.WriteValueBitPacked(writer, value); @@ -111,20 +82,6 @@ public void Duplicate(in ushort value, ref ushort duplicatedValue) /// internal class IntSerializer : INetworkVariableSerializer { - public NetworkVariableType Type => NetworkVariableType.Int; - public bool IsDistributedAuthorityOptimized => true; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref int value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref int value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref int value, ref int previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref int value) => Read(reader, ref value); public void Write(FastBufferWriter writer, ref int value) { BytePacker.WriteValueBitPacked(writer, value); @@ -161,20 +118,6 @@ public void Duplicate(in int value, ref int duplicatedValue) /// internal class UintSerializer : INetworkVariableSerializer { - public NetworkVariableType Type => NetworkVariableType.UInt; - public bool IsDistributedAuthorityOptimized => true; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref uint value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref uint value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref uint value, ref uint previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref uint value) => Read(reader, ref value); public void Write(FastBufferWriter writer, ref uint value) { BytePacker.WriteValueBitPacked(writer, value); @@ -211,20 +154,6 @@ public void Duplicate(in uint value, ref uint duplicatedValue) ///
internal class LongSerializer : INetworkVariableSerializer { - public NetworkVariableType Type => NetworkVariableType.Long; - public bool IsDistributedAuthorityOptimized => true; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref long value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref long value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref long value, ref long previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref long value) => Read(reader, ref value); public void Write(FastBufferWriter writer, ref long value) { BytePacker.WriteValueBitPacked(writer, value); @@ -261,21 +190,6 @@ public void Duplicate(in long value, ref long duplicatedValue) /// internal class UlongSerializer : INetworkVariableSerializer { - public NetworkVariableType Type => NetworkVariableType.ULong; - public bool IsDistributedAuthorityOptimized => true; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref ulong value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref ulong value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref ulong value, ref ulong previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref ulong value) => Read(reader, ref value); - public void Write(FastBufferWriter writer, ref ulong value) { BytePacker.WriteValueBitPacked(writer, value); @@ -317,21 +231,6 @@ public void Duplicate(in ulong value, ref ulong duplicatedValue) /// internal class UnmanagedTypeSerializer : INetworkVariableSerializer where T : unmanaged { - public NetworkVariableType Type => NetworkVariableType.Unmanaged; - public bool IsDistributedAuthorityOptimized => false; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref T value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref T value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => Read(reader, ref value); - public void Write(FastBufferWriter writer, ref T value) { writer.WriteUnmanagedSafe(value); @@ -365,20 +264,6 @@ public void Duplicate(in T value, ref T duplicatedValue) internal class ListSerializer : INetworkVariableSerializer> { - public NetworkVariableType Type => NetworkVariableType.Value; - public bool IsDistributedAuthorityOptimized => false; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref List value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref List value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref List value, ref List previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref List value) => Read(reader, ref value); public void Write(FastBufferWriter writer, ref List value) { var isNull = value == null; @@ -468,20 +353,6 @@ public void Duplicate(in List value, ref List duplicatedValue) internal class HashSetSerializer : INetworkVariableSerializer> where T : IEquatable { - public NetworkVariableType Type => NetworkVariableType.Value; - public bool IsDistributedAuthorityOptimized => false; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref HashSet value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref HashSet value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref HashSet value, ref HashSet previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref HashSet value) => Read(reader, ref value); public void Write(FastBufferWriter writer, ref HashSet value) { var isNull = value == null; @@ -563,20 +434,6 @@ public void Duplicate(in HashSet value, ref HashSet duplicatedValue) internal class DictionarySerializer : INetworkVariableSerializer> where TKey : IEquatable { - public NetworkVariableType Type => NetworkVariableType.Value; - public bool IsDistributedAuthorityOptimized => false; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref Dictionary value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref Dictionary value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref Dictionary value, ref Dictionary previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref Dictionary value) => Read(reader, ref value); public void Write(FastBufferWriter writer, ref Dictionary value) { var isNull = value == null; @@ -659,20 +516,6 @@ public void Duplicate(in Dictionary value, ref Dictionary : INetworkVariableSerializer> where T : unmanaged { - public NetworkVariableType Type => NetworkVariableType.Value; - public bool IsDistributedAuthorityOptimized => false; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeArray value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref NativeArray value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeArray value, ref NativeArray previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeArray value) => Read(reader, ref value); public void Write(FastBufferWriter writer, ref NativeArray value) { writer.WriteUnmanagedSafe(value); @@ -718,20 +561,6 @@ public void Duplicate(in NativeArray value, ref NativeArray duplicatedValu #if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT internal class UnmanagedListSerializer : INetworkVariableSerializer> where T : unmanaged { - public NetworkVariableType Type => NetworkVariableType.Value; - public bool IsDistributedAuthorityOptimized => false; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeList value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref NativeList value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeList value, ref NativeList previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeList value) => Read(reader, ref value); public void Write(FastBufferWriter writer, ref NativeList value) { writer.WriteUnmanagedSafe(value); @@ -775,21 +604,6 @@ public void Duplicate(in NativeList value, ref NativeList duplicatedValue) internal class NativeHashSetSerializer : INetworkVariableSerializer> where T : unmanaged, IEquatable { - public NetworkVariableType Type => NetworkVariableType.Value; - public bool IsDistributedAuthorityOptimized => false; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeHashSet value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref NativeHashSet value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeHashSet value, ref NativeHashSet previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeHashSet value) => Read(reader, ref value); - public void Write(FastBufferWriter writer, ref NativeHashSet value) { writer.WriteValueSafe(value); @@ -835,21 +649,6 @@ internal class NativeHashMapSerializer : INetworkVariableSerializer< where TKey : unmanaged, IEquatable where TVal : unmanaged { - public NetworkVariableType Type => NetworkVariableType.Value; - public bool IsDistributedAuthorityOptimized => false; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeHashMap value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref NativeHashMap value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeHashMap value, ref NativeHashMap previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeHashMap value) => Read(reader, ref value); - public void Write(FastBufferWriter writer, ref NativeHashMap value) { writer.WriteValueSafe(value); @@ -897,21 +696,6 @@ public void Duplicate(in NativeHashMap value, ref NativeHashMap internal class FixedStringSerializer : INetworkVariableSerializer where T : unmanaged, INativeList, IUTF8Bytes { - public NetworkVariableType Type => NetworkVariableType.Value; - public bool IsDistributedAuthorityOptimized => false; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref T value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref T value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => Read(reader, ref value); - public void Write(FastBufferWriter writer, ref T value) { writer.WriteValueSafe(value); @@ -1019,20 +803,6 @@ public void Duplicate(in T value, ref T duplicatedValue) /// internal class FixedStringArraySerializer : INetworkVariableSerializer> where T : unmanaged, INativeList, IUTF8Bytes { - public NetworkVariableType Type => NetworkVariableType.Value; - public bool IsDistributedAuthorityOptimized => false; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeArray value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref NativeArray value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeArray value, ref NativeArray previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeArray value) => Read(reader, ref value); public void Write(FastBufferWriter writer, ref NativeArray value) { writer.WriteValueSafe(value); @@ -1083,21 +853,6 @@ public void Duplicate(in NativeArray value, ref NativeArray duplicatedValu /// internal class FixedStringListSerializer : INetworkVariableSerializer> where T : unmanaged, INativeList, IUTF8Bytes { - public NetworkVariableType Type => NetworkVariableType.Value; - public bool IsDistributedAuthorityOptimized => false; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeList value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref NativeList value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeList value, ref NativeList previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeList value) => Read(reader, ref value); - public void Write(FastBufferWriter writer, ref NativeList value) { writer.WriteValueSafe(value); @@ -1145,21 +900,6 @@ public void Duplicate(in NativeList value, ref NativeList duplicatedValue) /// internal class UnmanagedNetworkSerializableSerializer : INetworkVariableSerializer where T : unmanaged, INetworkSerializable { - public NetworkVariableType Type => NetworkVariableType.Value; - public bool IsDistributedAuthorityOptimized => false; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref T value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref T value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => Read(reader, ref value); - public void Write(FastBufferWriter writer, ref T value) { var bufferSerializer = new BufferSerializer(new BufferSerializerWriter(writer)); @@ -1212,20 +952,6 @@ public void Duplicate(in T value, ref T duplicatedValue) /// internal class UnmanagedNetworkSerializableArraySerializer : INetworkVariableSerializer> where T : unmanaged, INetworkSerializable { - public NetworkVariableType Type => NetworkVariableType.Value; - public bool IsDistributedAuthorityOptimized => false; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeArray value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref NativeArray value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeArray value, ref NativeArray previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeArray value) => Read(reader, ref value); public void Write(FastBufferWriter writer, ref NativeArray value) { writer.WriteNetworkSerializable(value); @@ -1276,21 +1002,6 @@ public void Duplicate(in NativeArray value, ref NativeArray duplicatedValu /// internal class UnmanagedNetworkSerializableListSerializer : INetworkVariableSerializer> where T : unmanaged, INetworkSerializable { - public NetworkVariableType Type => NetworkVariableType.Value; - public bool IsDistributedAuthorityOptimized => false; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeList value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref NativeList value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeList value, ref NativeList previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeList value) => Read(reader, ref value); - public void Write(FastBufferWriter writer, ref NativeList value) { writer.WriteNetworkSerializable(value); @@ -1338,20 +1049,6 @@ public void Duplicate(in NativeList value, ref NativeList duplicatedValue) /// internal class ManagedNetworkSerializableSerializer : INetworkVariableSerializer where T : class, INetworkSerializable, new() { - public NetworkVariableType Type => NetworkVariableType.Value; - public bool IsDistributedAuthorityOptimized => false; - - public void WriteDistributedAuthority(FastBufferWriter writer, ref T value) - { - Write(writer, ref value); - } - - public void ReadDistributedAuthority(FastBufferReader reader, ref T value) - { - Read(reader, ref value); - } - public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => Write(writer, ref value); - public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => Read(reader, ref value); public void Write(FastBufferWriter writer, ref T value) { var bufferSerializer = new BufferSerializer(new BufferSerializerWriter(writer)); diff --git a/Runtime/NetworkVariable/Serialization/VariableSerializationTools.cs b/Runtime/NetworkVariable/Serialization/VariableSerializationTools.cs deleted file mode 100644 index 50ea37d..0000000 --- a/Runtime/NetworkVariable/Serialization/VariableSerializationTools.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System.Runtime.CompilerServices; -using System.Runtime.Serialization; - -namespace Unity.Netcode -{ - - internal static class SerializationTools - { - public delegate void WriteDelegate(FastBufferWriter writer, ref T value); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void WriteWithSize(WriteDelegate writeMethod, FastBufferWriter writer, ref T value) - { - var writePos = writer.Position; - // Note: This value can't be packed because we don't know how large it will be in advance - // we reserve space for it, then write the data, then come back and fill in the space - // to pack here, we'd have to write data to a temporary buffer and copy it in - which - // isn't worth possibly saving one byte if and only if the data is less than 63 bytes long... - // The way we do packing, any value > 63 in a ushort will use the full 2 bytes to represent. - writer.WriteValueSafe((ushort)0); - var startPos = writer.Position; - writeMethod(writer, ref value); - var size = writer.Position - startPos; - writer.Seek(writePos); - writer.WriteValueSafe((ushort)size); - writer.Seek(startPos + size); - } - - public delegate void ReadDelegate(FastBufferReader writer, ref T value); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void ReadWithSize(ReadDelegate readMethod, FastBufferReader reader, ref T value) - { - reader.ReadValueSafe(out ushort _); - readMethod(reader, ref value); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void WriteType(FastBufferWriter writer, NetworkVariableType type) => writer.WriteValueSafe(type); - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void ReadType(FastBufferReader reader, INetworkVariableSerializer serializer) - { - reader.ReadValueSafe(out NetworkVariableType type); - if (type != serializer.Type) - { - throw new SerializationException(); - } - } - - - } - -} diff --git a/Runtime/NetworkVariable/Serialization/VariableSerializationTools.cs.meta b/Runtime/NetworkVariable/Serialization/VariableSerializationTools.cs.meta deleted file mode 100644 index 006046f..0000000 --- a/Runtime/NetworkVariable/Serialization/VariableSerializationTools.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 52a4ce368df54b0a8887c08f3402bcd3 -timeCreated: 1718300602 \ No newline at end of file diff --git a/Runtime/SceneManagement/NetworkSceneManager.cs b/Runtime/SceneManagement/NetworkSceneManager.cs index 6522200..8996dfc 100644 --- a/Runtime/SceneManagement/NetworkSceneManager.cs +++ b/Runtime/SceneManagement/NetworkSceneManager.cs @@ -1081,14 +1081,19 @@ private void SendSceneEventData(uint sceneEventId, ulong[] targetClientIds) } else { - var message = new SceneEventMessage + // Send to each individual client to assure only the in-scene placed NetworkObjects being observed by the client + // is serialized + foreach (var clientId in targetClientIds) { - 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); + sceneEvent.TargetClientId = clientId; + var message = new SceneEventMessage + { + EventData = sceneEvent, + }; + var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, clientId); + NetworkManager.NetworkMetrics.TrackSceneEventSent(clientId, (uint)sceneEvent.SceneEventType, SceneNameFromHash(sceneEvent.SceneHash), size); + } } - } /// @@ -1898,10 +1903,12 @@ private void OnSessionOwnerLoadedScene(uint sceneEventId, Scene scene) SendSceneEventData(sceneEventData.SceneEventId, NetworkManager.ConnectedClientsIds.Where(c => c != sessionOwner).ToArray()); m_IsSceneEventActive = false; + + sceneEventData.SceneEventType = SceneEventType.LoadComplete; //First, notify local server that the scene was loaded OnSceneEvent?.Invoke(new SceneEvent() { - SceneEventType = SceneEventType.LoadComplete, + SceneEventType = sceneEventData.SceneEventType, LoadSceneMode = sceneEventData.LoadSceneMode, SceneName = SceneNameFromHash(sceneEventData.SceneHash), ClientId = NetworkManager.LocalClientId, diff --git a/Runtime/Serialization/BitWriter.cs b/Runtime/Serialization/BitWriter.cs index 9eacd56..0e3ccfb 100644 --- a/Runtime/Serialization/BitWriter.cs +++ b/Runtime/Serialization/BitWriter.cs @@ -62,7 +62,7 @@ public void Dispose() /// When you know you will be writing multiple fields back-to-back and you know the total size, /// you can call TryBeginWriteBits() once on the total size, and then follow it with calls to /// WriteBit() or WriteBits(). - /// + /// /// Bitwise write operations will throw OverflowException in editor and development builds if you /// go past the point you've marked using TryBeginWriteBits(). In release builds, OverflowException will not be thrown /// for performance reasons, since the point of using TryBeginWrite is to avoid bounds checking in the following diff --git a/Runtime/Spawning/NetworkSpawnManager.cs b/Runtime/Spawning/NetworkSpawnManager.cs index c17e056..854bc8f 100644 --- a/Runtime/Spawning/NetworkSpawnManager.cs +++ b/Runtime/Spawning/NetworkSpawnManager.cs @@ -88,6 +88,13 @@ private void AddPlayerObject(NetworkObject playerObject) } } + // Only if spawn with observers is set or we are using a distributed authority network topology and this is the client's player should we add + // the owner as an observer. + if (playerObject.SpawnWithObservers || (NetworkManager.DistributedAuthorityMode && NetworkManager.LocalClientId == playerObject.OwnerClientId)) + { + playerObject.Observers.Add(playerObject.OwnerClientId); + } + m_PlayerObjects.Add(playerObject); if (!m_PlayerObjectsTable.ContainsKey(playerObject.OwnerClientId)) { @@ -110,8 +117,9 @@ internal void UpdateNetworkClientPlayer(NetworkObject playerObject) 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); + RemovePlayerObject(playerNetworkClient.PlayerObject); } + // Now update the associated NetworkClient's player object NetworkManager.ConnectionManager.ConnectedClients[playerObject.OwnerClientId].AssignPlayerObject(ref playerObject); AddPlayerObject(playerObject); @@ -120,7 +128,7 @@ internal void UpdateNetworkClientPlayer(NetworkObject playerObject) /// /// Removes a player object and updates all other players' observers list /// - private void RemovePlayerObject(NetworkObject playerObject, bool keepObservers = false) + private void RemovePlayerObject(NetworkObject playerObject, bool destroyingObject = false) { if (!playerObject.IsPlayerObject) { @@ -141,16 +149,21 @@ private void RemovePlayerObject(NetworkObject playerObject, bool keepObservers = } } - // If we want to keep the observers, then exit early - if (keepObservers) + if (NetworkManager.ConnectionManager.ConnectedClients.ContainsKey(playerObject.OwnerClientId) && destroyingObject) { - return; + NetworkManager.ConnectionManager.ConnectedClients[playerObject.OwnerClientId].PlayerObject = null; } - foreach (var player in m_PlayerObjects) - { - player.Observers.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) @@ -409,27 +422,8 @@ internal void RemoveOwnership(NetworkObject networkObject) { 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; - } + Debug.LogError($"Removing ownership is invalid in Distributed Authority Mode. Use {nameof(ChangeOwnership)} instead."); + return; } ChangeOwnership(networkObject, NetworkManager.ServerClientId, true); } @@ -461,6 +455,18 @@ internal void ChangeOwnership(NetworkObject networkObject, ulong clientId, bool if (NetworkManager.DistributedAuthorityMode) { + // Ensure only the session owner can change ownership (i.e. acquire) and that the session owner is not trying to assign a non-session owner client + // ownership of a NetworkObject with SessionOwner permissions. + if (networkObject.IsOwnershipSessionOwner && (!NetworkManager.LocalClient.IsSessionOwner || clientId != NetworkManager.CurrentSessionOwner)) + { + if (NetworkManager.LogLevel <= LogLevel.Developer) + { + NetworkLog.LogErrorServer($"[{networkObject.name}][Session Owner Only] You cannot change ownership of a {nameof(NetworkObject)} that has the {NetworkObject.OwnershipStatus.SessionOwner} flag set!"); + } + networkObject.OnOwnershipPermissionsFailure?.Invoke(NetworkObject.OwnershipPermissionsFailureStatus.SessionOwnerOnly); + return; + } + // If are not authorized and this is not an approved ownership change, then check to see if we can change ownership if (!isAuthorized && !isRequestApproval) { @@ -567,7 +573,6 @@ internal void ChangeOwnership(NetworkObject networkObject, ulong clientId, bool { networkObject.ChildNetworkBehaviours[i].UpdateNetworkProperties(); } - size = NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, NetworkManager.ServerClientId); NetworkManager.NetworkMetrics.TrackOwnershipChangeSent(NetworkManager.LocalClientId, networkObject, size); } @@ -724,12 +729,20 @@ public NetworkObject InstantiateAndSpawn(NetworkObject networkPrefab, ulong owne 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. - // In distributed authority mode, we alaways get the override - if (forceOverride || NetworkManager.IsHost || NetworkManager.DistributedAuthorityMode) + // - Host and clients always instantiate the override if one exists. + // - Server instantiates the original prefab unless: + // -- forceOverride is set to true =or= + // -- The prefab has a registered prefab handler, then we let user code determine what to spawn. + // - Distributed authority mode always spawns the override if one exists. + if (forceOverride || NetworkManager.IsClient || NetworkManager.DistributedAuthorityMode || NetworkManager.PrefabHandler.ContainsHandler(networkPrefab.GlobalObjectIdHash)) { networkObject = GetNetworkObjectToSpawn(networkPrefab.GlobalObjectIdHash, ownerClientId, position, rotation); } + else // Under this case, server instantiate the prefab passed in. + { + networkObject = InstantiateNetworkPrefab(networkPrefab.gameObject, networkPrefab.GlobalObjectIdHash, position, rotation); + } + if (networkObject == null) { Debug.LogError($"Failed to instantiate and spawn {networkPrefab.name}!"); @@ -738,12 +751,20 @@ internal NetworkObject InstantiateAndSpawnNoParameterChecks(NetworkObject networ networkObject.IsPlayerObject = isPlayerObject; networkObject.transform.position = position; networkObject.transform.rotation = rotation; - networkObject.SpawnWithOwnership(ownerClientId, destroyWithScene); + // If spawning as a player, then invoke SpawnAsPlayerObject + if (isPlayerObject) + { + networkObject.SpawnAsPlayerObject(ownerClientId, destroyWithScene); + } + else // Otherwise just spawn with ownership + { + networkObject.SpawnWithOwnership(ownerClientId, destroyWithScene); + } return networkObject; } /// - /// Gets the right NetworkObject prefab instance to spawn. If a handler is registered or there is an override assigned to the + /// Gets the right NetworkObject prefab instance to spawn. If a handler is registered or there is an override assigned to the /// passed in globalObjectIdHash value, then that is what will be instantiated, spawned, and returned. /// internal NetworkObject GetNetworkObjectToSpawn(uint globalObjectIdHash, ulong ownerId, Vector3? position, Quaternion? rotation, bool isScenePlaced = false) @@ -775,8 +796,8 @@ internal NetworkObject GetNetworkObjectToSpawn(uint globalObjectIdHash, ulong ow case NetworkPrefabOverride.Hash: case NetworkPrefabOverride.Prefab: { - // When scene management is disabled and this is an in-scene placed NetworkObject, we want to always use the - // SourcePrefabToOverride and not any possible prefab override as a user might want to spawn overrides dynamically + // When scene management is disabled and this is an in-scene placed NetworkObject, we want to always use the + // SourcePrefabToOverride and not any possible prefab override as a user might want to spawn overrides dynamically // but might want to use the same source network prefab as an in-scene placed NetworkObject. // (When scene management is enabled, clients don't delete their in-scene placed NetworkObjects prior to dynamically // spawning them so the original prefab placed is preserved and this is not needed) @@ -804,16 +825,37 @@ internal NetworkObject GetNetworkObjectToSpawn(uint globalObjectIdHash, ulong ow else { // Create prefab instance while applying any pre-assigned position and rotation values - networkObject = UnityEngine.Object.Instantiate(networkPrefabReference).GetComponent(); - networkObject.transform.position = position ?? networkObject.transform.position; - networkObject.transform.rotation = rotation ?? networkObject.transform.rotation; - networkObject.NetworkManagerOwner = NetworkManager; - networkObject.PrefabGlobalObjectIdHash = globalObjectIdHash; + networkObject = InstantiateNetworkPrefab(networkPrefabReference, globalObjectIdHash, position, rotation); } } return networkObject; } + /// + /// Instantiates a network prefab instance, assigns the base prefab , positions, and orients + /// the instance. + /// !!! Should only be invoked by unless used by an integration test !!! + /// + /// + /// should be the base prefab value and not the + /// overrided value. + /// (Can be used for integration testing) + /// + /// prefab to instantiate + /// of the base prefab instance + /// conditional position in place of the network prefab's default position + /// conditional rotation in place of the network prefab's default rotation + /// the instance of the + internal NetworkObject InstantiateNetworkPrefab(GameObject networkPrefab, uint prefabGlobalObjectIdHash, Vector3? position, Quaternion? rotation) + { + var networkObject = UnityEngine.Object.Instantiate(networkPrefab).GetComponent(); + networkObject.transform.position = position ?? networkObject.transform.position; + networkObject.transform.rotation = rotation ?? networkObject.transform.rotation; + networkObject.NetworkManagerOwner = NetworkManager; + networkObject.PrefabGlobalObjectIdHash = prefabGlobalObjectIdHash; + return networkObject; + } + /// /// Creates a local NetowrkObject to be spawned. /// @@ -949,7 +991,7 @@ internal NetworkObject CreateLocalNetworkObject(NetworkObject.SceneObject sceneO /// - 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. /// @@ -1098,6 +1140,12 @@ private void SpawnNetworkObjectLocallyCommon(NetworkObject networkObject, ulong // then add all connected clients as observers if (!NetworkManager.DistributedAuthorityMode && NetworkManager.IsServer && networkObject.SpawnWithObservers) { + // If running as a server only, then make sure to always add the server's client identifier + if (!NetworkManager.IsHost) + { + networkObject.Observers.Add(NetworkManager.LocalClientId); + } + // Add client observers for (int i = 0; i < NetworkManager.ConnectedClientsIds.Count; i++) { @@ -1321,7 +1369,7 @@ internal void DespawnAndDestroyNetworkObjects() } } - // If spawned, then despawn and potentially destroy. + // If spawned, then despawn and potentially destroy. if (networkObjects[i].IsSpawned) { OnDespawnObject(networkObjects[i], shouldDestroy); @@ -1401,6 +1449,15 @@ internal void ServerSpawnSceneObjectsOnStartSweep() } } + // Since we are spawing in-scene placed NetworkObjects for already loaded scenes, + // we need to add any in-scene placed NetworkObject to our tracking table + var clearFirst = true; + foreach (var sceneLoaded in NetworkManager.SceneManager.ScenesLoaded) + { + NetworkManager.SceneManager.PopulateScenePlacedObjects(sceneLoaded.Value, clearFirst); + clearFirst = false; + } + // Notify all in-scene placed NetworkObjects have been spawned foreach (var networkObject in networkObjectsToSpawn) { @@ -1550,23 +1607,9 @@ internal void OnDespawnObject(NetworkObject networkObject, bool destroyGameObjec 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); + RemovePlayerObject(networkObject, destroyGameObject); } // Always clear out the observers list when despawned @@ -1705,6 +1748,11 @@ internal void GetObjectDistribution(ref Dictionary>()); + objectByTypeAndOwner.Add(globalOjectIdHash, new Dictionary>()); } // Sub-divide each type by owner - if (!objectByTypeAndOwner[networkObject.GlobalObjectIdHash].ContainsKey(networkObject.OwnerClientId)) + if (!objectByTypeAndOwner[globalOjectIdHash].ContainsKey(networkObject.OwnerClientId)) { - objectByTypeAndOwner[networkObject.GlobalObjectIdHash].Add(networkObject.OwnerClientId, new List()); + objectByTypeAndOwner[globalOjectIdHash].Add(networkObject.OwnerClientId, new List()); } // Add to the client's spawned object list - objectByTypeAndOwner[networkObject.GlobalObjectIdHash][networkObject.OwnerClientId].Add(networkObject); + objectByTypeAndOwner[globalOjectIdHash][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); + if (!NetworkManager.DistributedAuthorityMode) + { + return; + } + + if (NetworkManager.SessionConfig.ServiceSideDistribution) + { + return; + } - var clientCount = NetworkManager.ConnectedClientsIds.Count; - // Cycle through each prefab type - foreach (var objectTypeEntry in distributedNetworkObjects) + // 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) { - // 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; - } + 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; + } - // If the object per client count is zero, then move to the next type. - if (objPerClient <= 0) + // Evenly distribute this object type amongst the clients + foreach (var ownerList in objectTypeEntry.Value) + { + if (ownerList.Value.Count <= 1) { 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; + 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 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++) + for (int i = 0; i < ownerList.Value.Count; i++) + { + if ((i % offsetCount) == 0) { - 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) + ChangeOwnership(ownerList.Value[i], clientId, true); + //if (EnableDistributeLogging) { - break; + 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) + // 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) { - 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($"[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}"); - } + builder.AppendLine($"[Client-{ownerList.Key}] Count: {ownerList.Value.Count}"); } - Debug.Log(builder.ToString()); } + Debug.Log(builder.ToString()); } + } internal struct DeferredDespawnObject @@ -1969,14 +2023,14 @@ internal void NotifyNetworkObjectsSynchronized() /// synchronizing in order to "show" (spawn) anything that might be currently hidden from /// the session owner. /// + /// + /// Replacement is: SynchronizeObjectsToNewlyJoinedClient + /// internal void ShowHiddenObjectsToNewlyJoinedClient(ulong newClientId) { - if (!NetworkManager.DistributedAuthorityMode) + if (NetworkManager == null || NetworkManager.ShutdownInProgress && NetworkManager.LogLevel <= LogLevel.Developer) { - if (NetworkManager == null || !NetworkManager.ShutdownInProgress && NetworkManager.LogLevel <= LogLevel.Developer) - { - Debug.LogWarning($"[Internal Error] {nameof(ShowHiddenObjectsToNewlyJoinedClient)} invoked while !"); - } + Debug.LogWarning($"[Internal Error] {nameof(ShowHiddenObjectsToNewlyJoinedClient)} invoked while shutdown is in progress!"); return; } @@ -2012,5 +2066,46 @@ internal void ShowHiddenObjectsToNewlyJoinedClient(ulong newClientId) } } } + + internal void SynchronizeObjectsToNewlyJoinedClient(ulong newClientId) + { + if (NetworkManager == null || NetworkManager.ShutdownInProgress && NetworkManager.LogLevel <= LogLevel.Developer) + { + Debug.LogWarning($"[Internal Error] {nameof(SynchronizeObjectsToNewlyJoinedClient)} invoked while shutdown is in progress!"); + return; + } + + if (!NetworkManager.DistributedAuthorityMode) + { + Debug.LogError($"[Internal Error] {nameof(SynchronizeObjectsToNewlyJoinedClient)} should only be invoked when using a distributed authority network topology!"); + return; + } + + if (NetworkManager.NetworkConfig.EnableSceneManagement) + { + Debug.LogError($"[Internal Error] {nameof(SynchronizeObjectsToNewlyJoinedClient)} should only be invoked when scene management is disabled!"); + return; + } + + var localClientId = NetworkManager.LocalClient.ClientId; + foreach (var networkObject in SpawnedObjectsList) + { + if (networkObject.SpawnWithObservers && networkObject.OwnerClientId == localClientId) + { + if (networkObject.Observers.Contains(newClientId)) + { + if (NetworkManager.LogLevel <= LogLevel.Developer) + { + // Temporary tracking to make sure we are not showing something already visibile (should never be the case for this) + Debug.LogWarning($"[{nameof(SynchronizeObjectsToNewlyJoinedClient)}][{networkObject.name}] New client as already an observer!"); + } + // For now, remove the client (impossible for the new client to have an instance since the session owner doesn't) to make sure newly added + // code to handle this edge case works. + networkObject.Observers.Remove(newClientId); + } + networkObject.NetworkShow(newClientId); + } + } + } } } diff --git a/Runtime/Transports/NetworkTransport.cs b/Runtime/Transports/NetworkTransport.cs index b624120..d647aea 100644 --- a/Runtime/Transports/NetworkTransport.cs +++ b/Runtime/Transports/NetworkTransport.cs @@ -107,6 +107,45 @@ protected void InvokeOnTransportEvent(NetworkEvent eventType, ulong clientId, Ar /// /// optionally pass in NetworkManager public abstract void Initialize(NetworkManager networkManager = null); + /// + /// Invoked by NetworkManager at the beginning of its EarlyUpdate. + /// For order of operations see: + /// + /// Useful to handle processing any transport-layer events such as processing inbound messages or changes in connection state(s). + /// + protected virtual void OnEarlyUpdate() + { + + } + + /// + /// Invoked by NetworkManager at the beginning of its EarlyUpdate + /// + internal void EarlyUpdate() + { + OnEarlyUpdate(); + } + + /// + /// Invoked by NetworkManager towards the end of the PostLateUpdate. + /// For order of operations see: + /// + /// + /// Useful to handle any end of frame transport tasks such as sending queued transport messages. + /// + protected virtual void OnPostLateUpdate() + { + + } + + /// + /// Invoked by NetworkManager towards the end of the PostLateUpdate + /// + internal void PostLateUpdate() + { + OnPostLateUpdate(); + } + protected virtual NetworkTopologyTypes OnCurrentTopology() { return NetworkTopologyTypes.ClientServer; diff --git a/Runtime/Transports/UTP/UnityTransport.cs b/Runtime/Transports/UTP/UnityTransport.cs index 0237517..634d544 100644 --- a/Runtime/Transports/UTP/UnityTransport.cs +++ b/Runtime/Transports/UTP/UnityTransport.cs @@ -405,6 +405,7 @@ public struct SimulatorParameters #if UTP_TRANSPORT_2_0_ABOVE [Obsolete("DebugSimulator is no longer supported and has no effect. Use Network Simulator from the Multiplayer Tools package.", false)] + [HideInInspector] #endif public SimulatorParameters DebugSimulator = new SimulatorParameters { @@ -944,17 +945,13 @@ private bool ProcessEvent() return false; } - private void Update() + /// + /// Handles accepting new connections and processing transport events. + /// + protected override void OnEarlyUpdate() { if (m_Driver.IsCreated) { - foreach (var kvp in m_SendQueue) - { - SendBatchedMessages(kvp.Key, kvp.Value); - } - - m_Driver.ScheduleUpdate().Complete(); - if (m_ProtocolType == ProtocolType.RelayUnityTransport && m_Driver.GetRelayConnectionStatus() == RelayConnectionStatus.AllocationInvalid) { Debug.LogError("Transport failure! Relay allocation needs to be recreated, and NetworkManager restarted. " + @@ -964,15 +961,38 @@ private void Update() return; } + m_Driver.ScheduleUpdate().Complete(); + + // Process any new connections while (AcceptConnection() && m_Driver.IsCreated) { ; } + // Process any transport events (i.e. connect, disconnect, data, etc) while (ProcessEvent() && m_Driver.IsCreated) { ; } + } + base.OnEarlyUpdate(); + } + + /// + /// Handles sending any queued batched messages. + /// + protected override void OnPostLateUpdate() + { + if (m_Driver.IsCreated) + { + foreach (var kvp in m_SendQueue) + { + SendBatchedMessages(kvp.Key, kvp.Value); + } + + // Schedule a flush send as the last transport action for the + // current frame. + m_Driver.ScheduleFlushSend(default).Complete(); #if MULTIPLAYER_TOOLS_1_0_0_PRE_7 if (m_NetworkManager) @@ -981,6 +1001,7 @@ private void Update() } #endif } + base.OnPostLateUpdate(); } private void OnDestroy() @@ -1241,6 +1262,30 @@ public override ulong GetCurrentRtt(ulong clientId) return (ulong)ExtractRtt(ParseClientId(clientId)); } + /// + /// Provides the for the NGO client identifier specified. + /// + /// + /// - This is only really useful for direct connections. + /// - Relay connections and clients connected using a distributed authority network topology will not provide the client's actual endpoint information. + /// - For LAN topologies this should work as long as it is a direct connection and not a relay connection. + /// + /// NGO client identifier to get endpoint information about. + /// + public NetworkEndpoint GetEndpoint(ulong clientId) + { + if (m_Driver.IsCreated && m_NetworkManager != null && m_NetworkManager.IsListening) + { + var transportId = m_NetworkManager.ConnectionManager.ClientIdToTransportId(clientId); + var networkConnection = ParseClientId(transportId); + if (m_Driver.GetConnectionState(networkConnection) == NetworkConnection.State.Connected) + { + return m_Driver.GetRemoteEndpoint(networkConnection); + } + } + return new NetworkEndpoint(); + } + /// /// Initializes the transport /// @@ -1450,8 +1495,18 @@ public override bool StartServer() /// public override void Shutdown() { + if (m_NetworkManager && !m_NetworkManager.ShutdownInProgress) + { + Debug.LogWarning("Directly calling `UnityTransport.Shutdown()` results in unexpected shutdown behaviour. All pending events will be lost. Use `NetworkManager.Shutdown()` instead."); + } + if (m_Driver.IsCreated) { + while (ProcessEvent() && m_Driver.IsCreated) + { + ; + } + // Flush all send queues to the network. NGO can be configured to flush its message // queue on shutdown. But this only calls the Send() method, which doesn't actually // get anything to the network. @@ -1469,6 +1524,7 @@ public override void Shutdown() DisposeInternals(); m_ReliableReceiveQueues.Clear(); + m_State = State.Disconnected; // We must reset this to zero because UTP actually re-uses clientIds if there is a clean disconnect m_ServerClientId = 0; diff --git a/Samples~/Bootstrap/.sample.json b/Samples~/Bootstrap/.sample.json deleted file mode 100644 index f62cf30..0000000 --- a/Samples~/Bootstrap/.sample.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "displayName": "Bootstrap", - "description": "A lightweight sample to get started" -} \ No newline at end of file diff --git a/Samples~/Bootstrap/Scripts/Bootstrap.asmdef b/Samples~/Bootstrap/Scripts/Bootstrap.asmdef index 07a8ac0..54cb675 100644 --- a/Samples~/Bootstrap/Scripts/Bootstrap.asmdef +++ b/Samples~/Bootstrap/Scripts/Bootstrap.asmdef @@ -1,7 +1,7 @@ { - "name": "Bootstrap", + "name": "Bootstrap", "rootNamespace": "Unity.Netcode.Samples", "references": [ "Unity.Netcode.Runtime" ] -} +} \ No newline at end of file diff --git a/TestHelpers/Runtime/IntegrationTestWithApproximation.cs b/TestHelpers/Runtime/IntegrationTestWithApproximation.cs index 02a5393..89b1e89 100644 --- a/TestHelpers/Runtime/IntegrationTestWithApproximation.cs +++ b/TestHelpers/Runtime/IntegrationTestWithApproximation.cs @@ -87,6 +87,8 @@ protected Vector3 GetRandomVector3(float min, float max) return new Vector3(Random.Range(min, max), Random.Range(min, max), Random.Range(min, max)); } + public IntegrationTestWithApproximation(NetworkTopologyTypes networkTopologyType, HostOrServer hostOrServer) : base(networkTopologyType, hostOrServer) { } + public IntegrationTestWithApproximation(NetworkTopologyTypes networkTopologyType) : base(networkTopologyType) { } public IntegrationTestWithApproximation(HostOrServer hostOrServer) : base(hostOrServer) { } diff --git a/TestHelpers/Runtime/NetcodeIntegrationTest.cs b/TestHelpers/Runtime/NetcodeIntegrationTest.cs index a84a7cc..921d70b 100644 --- a/TestHelpers/Runtime/NetcodeIntegrationTest.cs +++ b/TestHelpers/Runtime/NetcodeIntegrationTest.cs @@ -1759,6 +1759,13 @@ public NetcodeIntegrationTest(NetworkTopologyTypes networkTopologyType) m_DistributedAuthority = m_NetworkTopologyType == NetworkTopologyTypes.DistributedAuthority; } + public NetcodeIntegrationTest(NetworkTopologyTypes networkTopologyType, HostOrServer hostOrServer) + { + m_NetworkTopologyType = networkTopologyType; + m_DistributedAuthority = m_NetworkTopologyType == NetworkTopologyTypes.DistributedAuthority; + m_UseHost = hostOrServer == HostOrServer.Host || hostOrServer == HostOrServer.DAHost; + } + /// /// Optional Host or Server integration tests /// Constructor that allows you To break tests up as a host diff --git a/TestHelpers/Runtime/NetcodeIntegrationTestHelpers.cs b/TestHelpers/Runtime/NetcodeIntegrationTestHelpers.cs index 8758db8..1b4e094 100644 --- a/TestHelpers/Runtime/NetcodeIntegrationTestHelpers.cs +++ b/TestHelpers/Runtime/NetcodeIntegrationTestHelpers.cs @@ -559,6 +559,29 @@ public static void MakeNetworkObjectTestPrefab(NetworkObject networkObject, uint } } + /// + /// Creates a to be used with integration testing + /// + /// namr of the object + /// owner of the object + /// when true, the instance is automatically migrated into the DDOL + /// + internal static GameObject CreateNetworkObject(string baseName, NetworkManager owner, bool moveToDDOL = false) + { + var gameObject = new GameObject + { + name = baseName + }; + var networkObject = gameObject.AddComponent(); + networkObject.NetworkManagerOwner = owner; + MakeNetworkObjectTestPrefab(networkObject); + if (moveToDDOL) + { + Object.DontDestroyOnLoad(gameObject); + } + return gameObject; + } + public static GameObject CreateNetworkObjectPrefab(string baseName, NetworkManager server, params NetworkManager[] clients) { void AddNetworkPrefab(NetworkConfig config, NetworkPrefab prefab) @@ -570,13 +593,7 @@ void AddNetworkPrefab(NetworkConfig config, NetworkPrefab prefab) Assert.IsNotNull(server, prefabCreateAssertError); Assert.IsFalse(server.IsListening, prefabCreateAssertError); - var gameObject = new GameObject - { - name = baseName - }; - var networkObject = gameObject.AddComponent(); - networkObject.NetworkManagerOwner = server; - MakeNetworkObjectTestPrefab(networkObject); + var gameObject = CreateNetworkObject(baseName, server); var networkPrefab = new NetworkPrefab() { Prefab = gameObject }; // We could refactor this test framework to share a NetworkPrefabList instance, but at this point it's diff --git a/Tests/Runtime/DistributedAuthority/DistributedAuthorityCodecTests.cs b/Tests/Runtime/DistributedAuthority/DistributedAuthorityCodecTests.cs index 397d4f0..398d040 100644 --- a/Tests/Runtime/DistributedAuthority/DistributedAuthorityCodecTests.cs +++ b/Tests/Runtime/DistributedAuthority/DistributedAuthorityCodecTests.cs @@ -205,13 +205,14 @@ public IEnumerator NamedMessage() [UnityTest] public IEnumerator NetworkVariableDelta() { + var component = Client.LocalClient.PlayerObject.GetComponent(); var message = new NetworkVariableDeltaMessage { - NetworkObjectId = 0, - NetworkBehaviourIndex = 1, - DeliveryMappedNetworkVariableIndex = new HashSet { 2, 3, 4 }, + NetworkObjectId = Client.LocalClient.PlayerObject.NetworkObjectId, + NetworkBehaviourIndex = component.NetworkBehaviourId, + DeliveryMappedNetworkVariableIndex = new HashSet { 0, 1 }, TargetClientId = 5, - NetworkBehaviour = Client.LocalClient.PlayerObject.GetComponent(), + NetworkBehaviour = component, }; yield return SendMessage(ref message); @@ -569,7 +570,7 @@ public IEnumerator SceneEventMessageObjectSceneChanged() private IEnumerator SendMessage(ref T message) where T : INetworkMessage { - Client.MessageManager.SetVersion(k_ClientId, XXHash.Hash32(typeof(T).FullName), 0); + Client.MessageManager.SetVersion(k_ClientId, XXHash.Hash32(typeof(T).FullName), message.Version); var clientIds = new NativeArray(1, Allocator.Temp); clientIds[0] = k_ClientId; @@ -625,7 +626,8 @@ public void OnBeforeSendMessage(ulong clientId, ref T message, NetworkDeliver } var writer = new FastBufferWriter(1024, Allocator.Temp); - message.Serialize(writer, 0); + // Serialize the message using the known message version + message.Serialize(writer, message.Version); var testName = TestContext.CurrentContext.Test.Name; if (!m_ExpectedMessages.ContainsKey(testName)) diff --git a/Tests/Runtime/DistributedAuthority/NetworkClientAndPlayerObjectTests.cs b/Tests/Runtime/DistributedAuthority/NetworkClientAndPlayerObjectTests.cs index d7890c2..699b82d 100644 --- a/Tests/Runtime/DistributedAuthority/NetworkClientAndPlayerObjectTests.cs +++ b/Tests/Runtime/DistributedAuthority/NetworkClientAndPlayerObjectTests.cs @@ -216,6 +216,21 @@ private bool ValidatePlayerObjectOnClients(NetworkManager clientToValidate) m_ErrorLogLevel2.Append($"[Client-{client.LocalClientId} Prefab Mismatch][Expected GlobalObjectIdHash: {expectedGlobalObjectIdHash} but was {remoteNetworkClient.PlayerObject.GlobalObjectIdHash}]"); success = false; } + + var foundPlayer = false; + foreach (var playerObject in client.SpawnManager.PlayerObjects) + { + if (playerObject.NetworkObjectId == clientToValidate.LocalClient.PlayerObject.NetworkObjectId) + { + foundPlayer = true; + break; + } + } + if (!foundPlayer) + { + m_ErrorLogLevel1.AppendLine($"[Client-{client.LocalClientId}] Local {nameof(NetworkSpawnManager.PlayerObjects)} does not contain {clientToValidate.LocalClient.PlayerObject.name}!"); + success = false; + } } return success; } @@ -231,6 +246,12 @@ private bool ValidateAllPlayerObjects() m_ErrorLogLevel1.AppendLine($"[Client-{m_ServerNetworkManager.LocalClientId}]{m_ErrorLogLevel2}"); success = false; } + + if (m_ServerNetworkManager.LocalClient.PlayerObject == null) + { + m_ErrorLogLevel1.AppendLine($"[Client-{m_ServerNetworkManager.LocalClientId}] Local {nameof(NetworkClient.PlayerObject)} is null!"); + success = false; + } } foreach (var client in m_ClientNetworkManagers) @@ -240,6 +261,17 @@ private bool ValidateAllPlayerObjects() m_ErrorLogLevel1.AppendLine($"[Client-{client.LocalClientId}]{m_ErrorLogLevel2}"); success = false; } + if (client.LocalClient.PlayerObject == null) + { + m_ErrorLogLevel1.AppendLine($"[Client-{client.LocalClientId}] Local {nameof(NetworkClient.PlayerObject)} is null!"); + success = false; + } + else + if (!client.SpawnManager.PlayerObjects.Contains(client.LocalClient.PlayerObject)) + { + m_ErrorLogLevel1.AppendLine($"[Client-{client.LocalClientId}] Local {nameof(NetworkSpawnManager.PlayerObjects)} does not contain {client.LocalClient.PlayerObject.name}!"); + success = false; + } } return success; @@ -250,12 +282,19 @@ private NetworkObject GetRandomPlayerPrefab() return m_PlayerPrefabs[Random.Range(0, m_PlayerPrefabs.Count() - 1)].GetComponent(); } + public enum PlayerSpawnTypes + { + Normal, + NetworkObject, + SpawnManager + } + /// /// 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() + public IEnumerator ValidatePlayerObjects([Values] PlayerSpawnTypes playerSpawnType) { // Just do a quick validation for all connected client's NetworkClients yield return WaitForConditionOrTimeOut(AllNetworkClientsValidated); @@ -268,14 +307,51 @@ public IEnumerator ValidatePlayerObjects() if (m_UseHost) { playerPrefabToSpawn = GetRandomPlayerPrefab(); - playerInstance = SpawnPlayerObject(playerPrefabToSpawn.gameObject, m_ServerNetworkManager); + switch (playerSpawnType) + { + case PlayerSpawnTypes.Normal: + { + playerInstance = SpawnPlayerObject(playerPrefabToSpawn.gameObject, m_ServerNetworkManager); + break; + } + case PlayerSpawnTypes.NetworkObject: + { + playerInstance = NetworkObject.InstantiateAndSpawn(playerPrefabToSpawn.gameObject, m_ServerNetworkManager, isPlayerObject: true).gameObject; + break; + } + case PlayerSpawnTypes.SpawnManager: + { + playerInstance = m_ServerNetworkManager.SpawnManager.InstantiateAndSpawn(playerPrefabToSpawn, isPlayerObject: true).gameObject; + break; + } + } + m_ChangedPlayerPrefabs.Add(m_ServerNetworkManager.LocalClientId, playerPrefabToSpawn.GlobalObjectIdHash); } foreach (var client in m_ClientNetworkManagers) { playerPrefabToSpawn = GetRandomPlayerPrefab(); - playerInstance = SpawnPlayerObject(playerPrefabToSpawn.gameObject, client); + var networkManager = m_DistributedAuthority ? client : m_ServerNetworkManager; + + switch (playerSpawnType) + { + case PlayerSpawnTypes.Normal: + { + playerInstance = SpawnPlayerObject(playerPrefabToSpawn.gameObject, client); + break; + } + case PlayerSpawnTypes.NetworkObject: + { + playerInstance = NetworkObject.InstantiateAndSpawn(playerPrefabToSpawn.gameObject, networkManager, client.LocalClientId, isPlayerObject: true).gameObject; + break; + } + case PlayerSpawnTypes.SpawnManager: + { + playerInstance = networkManager.SpawnManager.InstantiateAndSpawn(playerPrefabToSpawn, client.LocalClientId, isPlayerObject: true).gameObject; + break; + } + } m_ChangedPlayerPrefabs.Add(client.LocalClientId, playerPrefabToSpawn.GlobalObjectIdHash); } diff --git a/Tests/Runtime/DistributedAuthority/OwnershipPermissionsTests.cs b/Tests/Runtime/DistributedAuthority/OwnershipPermissionsTests.cs index beccbdd..dcf44f7 100644 --- a/Tests/Runtime/DistributedAuthority/OwnershipPermissionsTests.cs +++ b/Tests/Runtime/DistributedAuthority/OwnershipPermissionsTests.cs @@ -128,7 +128,7 @@ public IEnumerator ValidateOwnershipPermissionsTest() 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. + // Validate the base non-assigned permissions value for all instances are the same. yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); AssertOnTimeout($"[Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}"); @@ -141,9 +141,15 @@ public IEnumerator ValidateOwnershipPermissionsTest() foreach (var permissionObject in Enum.GetValues(typeof(NetworkObject.OwnershipStatus))) { var permission = (NetworkObject.OwnershipStatus)permissionObject; + // Adding the SessionOwner flag here should fail as this NetworkObject is not owned by the Session Owner + if (permission == NetworkObject.OwnershipStatus.SessionOwner) + { + Assert.IsFalse(firstInstance.SetOwnershipStatus(permission), $"[Add][IncorrectPermissions] Setting {NetworkObject.OwnershipStatus.SessionOwner} is not valid when the client is not the Session Owner: \n {m_ErrorLog}!"); + continue; + } // Add the status firstInstance.SetOwnershipStatus(permission); - // Validate the persmissions value for all instances are the same. + // Validate the permissions value for all instances are the same. yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); AssertOnTimeout($"[Add][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}"); @@ -153,7 +159,7 @@ public IEnumerator ValidateOwnershipPermissionsTest() continue; } firstInstance.RemoveOwnershipStatus(permission); - // Validate the persmissions value for all instances are the same. + // Validate the permissions value for all instances are the same. yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); AssertOnTimeout($"[Remove][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}"); } @@ -163,7 +169,7 @@ public IEnumerator ValidateOwnershipPermissionsTest() 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. + // Validate the permissions value for all instances are the same. yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); AssertOnTimeout($"[Set Multiple][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}"); @@ -175,7 +181,7 @@ public IEnumerator ValidateOwnershipPermissionsTest() // 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. + // Validate the permissions value for all instances are the same. yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); AssertOnTimeout($"[Set Multiple][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}"); @@ -186,7 +192,7 @@ public IEnumerator ValidateOwnershipPermissionsTest() // 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. + // Validate the permissions value for all instances are the same. yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); AssertOnTimeout($"[Reset][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}"); @@ -199,7 +205,7 @@ public IEnumerator ValidateOwnershipPermissionsTest() $" status is {secondInstanceHelper.OwnershipPermissionsFailureStatus}!"); firstInstance.SetOwnershipLock(false); - // Validate the persmissions value for all instances are the same. + // Validate the permissions value for all instances are the same. yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); AssertOnTimeout($"[Unlock][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}"); @@ -208,7 +214,7 @@ public IEnumerator ValidateOwnershipPermissionsTest() // Now try to acquire ownership secondInstance.ChangeOwnership(m_ClientNetworkManagers[1].LocalClientId); - // Validate the persmissions value for all instances are the same + // Validate the permissions 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!"); @@ -220,7 +226,7 @@ public IEnumerator ValidateOwnershipPermissionsTest() // 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. + // Validate the permissions value for all instances are the same. yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); AssertOnTimeout($"[Unlock][Permissions Mismatch] {secondInstance.name}: \n {m_ErrorLog}"); @@ -238,7 +244,7 @@ public IEnumerator ValidateOwnershipPermissionsTest() // 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}!"); + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent, $"Client-{firstInstance.NetworkManager.LocalClientId} was unable 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]; @@ -248,7 +254,7 @@ public IEnumerator ValidateOwnershipPermissionsTest() 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}!"); + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent, $"Client-{m_ServerNetworkManager.LocalClientId} was unable to send a request for ownership because: {requestStatus}!"); // We expect the first requesting client to be given ownership yield return WaitForConditionOrTimeOut(() => firstInstance.IsOwner); @@ -263,7 +269,7 @@ public IEnumerator ValidateOwnershipPermissionsTest() 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. + // Validate the permissions value for all instances are the same. yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); AssertOnTimeout($"[Unlock][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}"); @@ -278,11 +284,11 @@ public IEnumerator ValidateOwnershipPermissionsTest() // 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}!"); + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent, $"Client-{secondInstance.NetworkManager.LocalClientId} was unable 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}!"); + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent, $"Client-{thirdInstance.NetworkManager.LocalClientId} was unable 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}!"); + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent, $"Client-{fourthInstance.NetworkManager.LocalClientId} was unable 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(() => @@ -296,7 +302,7 @@ public IEnumerator ValidateOwnershipPermissionsTest() 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. + // Validate the permissions value for all instances are the same. yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); AssertOnTimeout($"[Unlock][Permissions Mismatch] {secondInstance.name}: \n {m_ErrorLog}"); @@ -314,22 +320,84 @@ public IEnumerator ValidateOwnershipPermissionsTest() // 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}!"); + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent, $"Client-{firstInstance.NetworkManager.LocalClientId} was unable 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}!"); + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent, $"Client-{thirdInstance.NetworkManager.LocalClientId} was unable 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}!"); + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent, $"Client-{fourthInstance.NetworkManager.LocalClientId} was unable 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}!"); + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent, $"Client-{daHostInstance.NetworkManager.LocalClientId} was unable to send a request for ownership because: {requestStatus}!"); - // The server and the 2nd client should be denied and the third client should be approved + // Only the client marked as ClientToAllowOwnership (daHost) should be approved. All others should be denied. 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}!"); + AssertOnTimeout($"[Targeted Owner] Client-{daHostInstance.NetworkManager.LocalClientId} did not get the right request response: {daHostInstanceHelper.OwnershipRequestResponseStatus} Expecting: {NetworkObject.OwnershipRequestResponseStatus.Approved}!"); + + /////////////////////////////////////////////// + // Test OwnershipStatus.SessionOwner: + /////////////////////////////////////////////// + + OwnershipPermissionsTestHelper.CurrentOwnedInstance = daHostInstance; + m_ObjectToValidate = OwnershipPermissionsTestHelper.CurrentOwnedInstance; + + // Add multiple statuses + daHostInstance.SetOwnershipStatus(NetworkObject.OwnershipStatus.Transferable | NetworkObject.OwnershipStatus.SessionOwner); + // Validate the permissions value for all instances are the same. + yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); + AssertOnTimeout($"[Add][Permissions Mismatch] {daHostInstance.name}: \n {m_ErrorLog}"); + + // Trying to set SessionOwner flag should override any other flags. + Assert.IsFalse(daHostInstance.HasOwnershipStatus(NetworkObject.OwnershipStatus.Transferable), $"[Set][SessionOwner flag Failure] Expected: {NetworkObject.OwnershipStatus.Transferable} not to be set!"); + + // Add another status. Should fail as SessionOwner should be exclusive + daHostInstance.SetOwnershipStatus(NetworkObject.OwnershipStatus.Distributable); + Assert.IsFalse(daHostInstance.HasOwnershipStatus(NetworkObject.OwnershipStatus.Distributable), $"[Add][SessionOwner flag Failure] Expected: {NetworkObject.OwnershipStatus.Transferable} not to be set!"); + + // Request ownership of the SessionOwner flag instance + requestStatus = firstInstance.RequestOwnership(); + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestRequiredNotSet, $"Client-{firstInstance.NetworkManager.LocalClientId} should not be able to send a request for ownership because object is marked as owned by the session owner. {requestStatus}!"); + + // Set ownership directly on local object. This will allow the request to be sent + firstInstance.Ownership = NetworkObject.OwnershipStatus.RequestRequired; + requestStatus = firstInstance.RequestOwnership(); + Assert.True(requestStatus == NetworkObject.OwnershipRequestStatus.RequestSent, $"Client-{firstInstance.NetworkManager.LocalClientId} was unable to send a request for ownership because: {requestStatus}!"); + + // Request should be denied with CannotRequest + yield return WaitForConditionOrTimeOut(() => firstInstanceHelper.OwnershipRequestResponseStatus == NetworkObject.OwnershipRequestResponseStatus.CannotRequest); + AssertOnTimeout($"[Targeted Owner] Client-{firstInstance.NetworkManager.LocalClientId} did not get the right request response: {daHostInstanceHelper.OwnershipRequestResponseStatus} Expecting: {NetworkObject.OwnershipRequestResponseStatus.CannotRequest}!"); + + // Try changing the ownership explicitly + // Get the cloned daHostInstance instance on a client side + var clientInstance = m_ClientNetworkManagers[2].SpawnManager.SpawnedObjects[daHostInstance.NetworkObjectId]; + + // Get the client instance of the OwnershipPermissionsTestHelper component + var clientInstanceHelper = clientInstance.GetComponent(); + + // Have the client attempt to change ownership + clientInstance.ChangeOwnership(m_ClientNetworkManagers[2].LocalClientId); + + // Verify the client side gets a permission failure status of NetworkObject.OwnershipPermissionsFailureStatus.SessionOwnerOnly + Assert.IsTrue(clientInstanceHelper.OwnershipPermissionsFailureStatus == NetworkObject.OwnershipPermissionsFailureStatus.SessionOwnerOnly, + $"Expected {clientInstance.name} to return {NetworkObject.OwnershipPermissionsFailureStatus.SessionOwnerOnly} but its permission failure" + + $" status is {clientInstanceHelper.OwnershipPermissionsFailureStatus}!"); + + // Have the session owner attempt to change ownership to a non-session owner + daHostInstance.ChangeOwnership(m_ClientNetworkManagers[2].LocalClientId); + + // Verify the session owner cannot assign a SessionOwner permission NetworkObject to a non-sessionowner client + Assert.IsTrue(daHostInstanceHelper.OwnershipPermissionsFailureStatus == NetworkObject.OwnershipPermissionsFailureStatus.SessionOwnerOnly, + $"Expected {daHostInstance.name} to return {NetworkObject.OwnershipPermissionsFailureStatus.SessionOwnerOnly} but its permission failure" + + $" status is {daHostInstanceHelper.OwnershipPermissionsFailureStatus}!"); + + // Remove status + daHostInstance.RemoveOwnershipStatus(NetworkObject.OwnershipStatus.SessionOwner); + // Validate the permissions value for all instances are the same. + yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients); + AssertOnTimeout($"[Remove][Permissions Mismatch] {daHostInstance.name}: \n {m_ErrorLog}"); } internal class OwnershipPermissionsTestHelper : NetworkBehaviour diff --git a/Tests/Runtime/DistributedAuthority/SessionVersionConnectionRequest.cs b/Tests/Runtime/DistributedAuthority/SessionVersionConnectionRequest.cs new file mode 100644 index 0000000..cb37362 --- /dev/null +++ b/Tests/Runtime/DistributedAuthority/SessionVersionConnectionRequest.cs @@ -0,0 +1,106 @@ +using System.Collections; +using NUnit.Framework; +using Unity.Netcode.TestHelpers.Runtime; +using UnityEngine.TestTools; + +namespace Unity.Netcode.RuntimeTests +{ + internal class SessionVersionConnectionRequest : NetcodeIntegrationTest + { + protected override int NumberOfClients => 0; + + public SessionVersionConnectionRequest() : base(NetworkTopologyTypes.DistributedAuthority, HostOrServer.DAHost) { } + + private bool m_UseValidSessionVersion; + private bool m_ClientWasDisconnected; + private NetworkManager m_ClientNetworkManager; + + /// + /// Callback used to mock the scenario where a client has an invalid session version + /// + /// + private SessionConfig GetInavlidSessionConfig() + { + return new SessionConfig(m_ServerNetworkManager.SessionConfig.SessionVersion - 1); + } + + /// + /// Overriding this method allows us to configure the newly instantiated client's + /// NetworkManager prior to it being started. + /// + /// the newly instantiated NetworkManager + protected override void OnNewClientCreated(NetworkManager networkManager) + { + m_ClientWasDisconnected = false; + m_ClientNetworkManager = networkManager; + m_ClientNetworkManager.OnClientDisconnectCallback += OnClientDisconnectCallback; + if (!m_UseValidSessionVersion) + { + networkManager.OnGetSessionConfig = GetInavlidSessionConfig; + } + base.OnNewClientCreated(networkManager); + } + + /// + /// Tracks if the client was disconnected or not + /// + private void OnClientDisconnectCallback(ulong clientId) + { + m_ClientWasDisconnected = true; + m_ClientNetworkManager.OnClientDisconnectCallback -= OnClientDisconnectCallback; + } + + /// + /// This handles disabling the internal integration test logic that waits for + /// clients to be connected. When we know the client will be disconnected, + /// we want to have the NetcodeIntegrationTest not wait for the client to + /// connect (otherwise it will timeout there and fail the test). + /// + /// + /// true = wait | false = don't wait + protected override bool ShouldWaitForNewClientToConnect(NetworkManager networkManager) + { + return m_UseValidSessionVersion; + } + + /// + /// Validates that when the client's session config version is valid a client will be + /// allowed to connect and when it is not valid the client will be disconnected. + /// + /// + /// This is just a mock of the service logic to validate everything on the NGO side is + /// working correctly. + /// + /// true = use valid session version | false = use invalid session version + [UnityTest] + public IEnumerator ValidateSessionVersion([Values] bool useValidSessionVersion) + { + // Test client being disconnected due to invalid session version + m_UseValidSessionVersion = useValidSessionVersion; + yield return CreateAndStartNewClient(); + yield return s_DefaultWaitForTick; + if (!m_UseValidSessionVersion) + { + yield return WaitForConditionOrTimeOut(() => m_ClientWasDisconnected); + AssertOnTimeout("Client was not disconnected when it should have been!"); + Assert.True(m_ClientNetworkManager.DisconnectReason == ConnectionRequestMessage.InvalidSessionVersionMessage, "Client did not receive the correct invalid session version message!"); + } + else + { + Assert.False(m_ClientWasDisconnected, "Client was disconnected when it was expected to connect!"); + Assert.True(m_ClientNetworkManager.IsConnectedClient, "Client did not connect properly using the correct session version!"); + } + } + + /// + /// Invoked at the end of each integration test pass. + /// Primarily used to clean up for the next pass. + /// + protected override IEnumerator OnTearDown() + { + m_ClientNetworkManager.OnClientDisconnectCallback -= OnClientDisconnectCallback; + m_ClientNetworkManager = null; + yield return base.OnTearDown(); + } + } +} diff --git a/Tests/Runtime/DistributedAuthority/SessionVersionConnectionRequest.cs.meta b/Tests/Runtime/DistributedAuthority/SessionVersionConnectionRequest.cs.meta new file mode 100644 index 0000000..207359d --- /dev/null +++ b/Tests/Runtime/DistributedAuthority/SessionVersionConnectionRequest.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 62913c78d28137141acc47ea8f63e657 \ No newline at end of file diff --git a/Tests/Runtime/NetworkManagerTransportTests.cs b/Tests/Runtime/NetworkManagerTransportTests.cs index 788758c..484f630 100644 --- a/Tests/Runtime/NetworkManagerTransportTests.cs +++ b/Tests/Runtime/NetworkManagerTransportTests.cs @@ -1,6 +1,9 @@ using System; using System.Collections; using NUnit.Framework; +using Unity.Netcode.TestHelpers.Runtime; +using Unity.Netcode.Transports.UTP; +using Unity.Networking.Transport; using UnityEngine; using UnityEngine.TestTools; @@ -157,4 +160,49 @@ public override void DisconnectLocalClient() } } } + + /// + /// Verifies the UnityTransport.GetEndpoint method returns + /// valid NetworkEndpoint information. + /// + internal class TransportEndpointTests : NetcodeIntegrationTest + { + protected override int NumberOfClients => 2; + + [UnityTest] + public IEnumerator GetEndpointReportedCorrectly() + { + var serverUnityTransport = m_ServerNetworkManager.NetworkConfig.NetworkTransport as UnityTransport; + var serverEndpoint = new NetworkEndpoint(); + var clientEndpoint = new NetworkEndpoint(); + foreach (var client in m_ClientNetworkManagers) + { + var unityTransport = client.NetworkConfig.NetworkTransport as UnityTransport; + serverEndpoint = unityTransport.GetEndpoint(m_ServerNetworkManager.LocalClientId); + clientEndpoint = serverUnityTransport.GetEndpoint(client.LocalClientId); + Assert.IsTrue(serverEndpoint.IsValid); + Assert.IsTrue(clientEndpoint.IsValid); + Assert.IsTrue(clientEndpoint.Address.Split(":")[0] == unityTransport.ConnectionData.Address); + Assert.IsTrue(serverEndpoint.Address.Split(":")[0] == serverUnityTransport.ConnectionData.Address); + Assert.IsTrue(serverEndpoint.Port == unityTransport.ConnectionData.Port); + Assert.IsTrue(clientEndpoint.Port >= serverUnityTransport.ConnectionData.Port); + } + + // Now validate that when disconnected it returns a non-valid NetworkEndPoint + var clientId = m_ClientNetworkManagers[0].LocalClientId; + m_ClientNetworkManagers[0].Shutdown(); + yield return s_DefaultWaitForTick; + + serverEndpoint = (m_ClientNetworkManagers[0].NetworkConfig.NetworkTransport as UnityTransport).GetEndpoint(m_ServerNetworkManager.LocalClientId); + clientEndpoint = serverUnityTransport.GetEndpoint(clientId); + Assert.IsFalse(serverEndpoint.IsValid); + Assert.IsFalse(clientEndpoint.IsValid); + + // Validate that invalid client identifiers return an invalid NetworkEndPoint + serverEndpoint = (m_ClientNetworkManagers[0].NetworkConfig.NetworkTransport as UnityTransport).GetEndpoint((ulong)UnityEngine.Random.Range(NumberOfClients + 1, 30)); + clientEndpoint = serverUnityTransport.GetEndpoint((ulong)UnityEngine.Random.Range(NumberOfClients + 1, 30)); + Assert.IsFalse(serverEndpoint.IsValid); + Assert.IsFalse(clientEndpoint.IsValid); + } + } } diff --git a/Tests/Runtime/NetworkObject/NetworkObjectOwnershipTests.cs b/Tests/Runtime/NetworkObject/NetworkObjectOwnershipTests.cs index bda9d15..6c1fe6b 100644 --- a/Tests/Runtime/NetworkObject/NetworkObjectOwnershipTests.cs +++ b/Tests/Runtime/NetworkObject/NetworkObjectOwnershipTests.cs @@ -127,7 +127,11 @@ public IEnumerator TestOwnershipCallbacks([Values] OwnershipChecks ownershipChec } // Verifies that removing the ownership when the default (server) is already set does not cause a Key Not Found Exception - m_ServerNetworkManager.SpawnManager.RemoveOwnership(m_OwnershipNetworkObject); + // Distributed authority does not allow remove ownership (users are instructed to use change ownership) + if (!m_DistributedAuthority) + { + m_ServerNetworkManager.SpawnManager.RemoveOwnership(m_OwnershipNetworkObject); + } var serverObject = m_ServerNetworkManager.SpawnManager.SpawnedObjects[ownershipNetworkObjectId]; var clientObject = m_ClientNetworkManagers[0].SpawnManager.SpawnedObjects[ownershipNetworkObjectId]; @@ -237,7 +241,12 @@ bool WaitForClientsToSpawnNetworkObject() Assert.False(s_GlobalTimeoutHelper.TimedOut, "Timed out waiting for all clients to change ownership!"); // Verifies that removing the ownership when the default (server) is already set does not cause a Key Not Found Exception - m_ServerNetworkManager.SpawnManager.RemoveOwnership(m_OwnershipNetworkObject); + // Distributed authority does not allow remove ownership (users are instructed to use change ownership) + if (!m_DistributedAuthority) + { + m_ServerNetworkManager.SpawnManager.RemoveOwnership(m_OwnershipNetworkObject); + } + var serverObject = m_ServerNetworkManager.SpawnManager.SpawnedObjects[ownershipNetworkObjectId]; Assert.That(serverObject, Is.Not.Null); var clientObject = (NetworkObject)null; diff --git a/Tests/Runtime/NetworkTransform/NetworkTransformOwnershipTests.cs b/Tests/Runtime/NetworkTransform/NetworkTransformOwnershipTests.cs index 31105ef..229a067 100644 --- a/Tests/Runtime/NetworkTransform/NetworkTransformOwnershipTests.cs +++ b/Tests/Runtime/NetworkTransform/NetworkTransformOwnershipTests.cs @@ -36,13 +36,25 @@ protected override void OnServerAndClientsCreated() { VerifyObjectIsSpawnedOnClient.ResetObjectTable(); m_ClientNetworkTransformPrefab = CreateNetworkObjectPrefab("OwnerAuthorityTest"); + var clientNetworkObject = m_ClientNetworkTransformPrefab.GetComponent(); + // When running in distributed authority mode, make the NetworkObject transferable + clientNetworkObject.SetOwnershipStatus(m_DistributedAuthority ? NetworkObject.OwnershipStatus.Transferable : NetworkObject.OwnershipStatus.None); var clientNetworkTransform = m_ClientNetworkTransformPrefab.AddComponent(); + clientNetworkTransform.AuthorityMode = NetworkTransform.AuthorityModes.Owner; clientNetworkTransform.Interpolate = false; clientNetworkTransform.UseHalfFloatPrecision = false; var rigidBody = m_ClientNetworkTransformPrefab.AddComponent(); rigidBody.useGravity = false; + rigidBody.maxDepenetrationVelocity = 0; + rigidBody.mass = 100; + rigidBody.linearDamping = 100; rigidBody.interpolation = RigidbodyInterpolation.None; rigidBody.maxLinearVelocity = 0; + rigidBody.detectCollisions = false; + rigidBody.position = Vector3.zero; + rigidBody.rotation = Quaternion.identity; + rigidBody.transform.position = Vector3.zero; + rigidBody.transform.rotation = Quaternion.identity; // 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 @@ -51,11 +63,22 @@ protected override void OnServerAndClientsCreated() m_ClientNetworkTransformPrefab.AddComponent(); m_NetworkTransformPrefab = CreateNetworkObjectPrefab("ServerAuthorityTest"); - var networkTransform = m_NetworkTransformPrefab.AddComponent(); + var networkObject = m_ClientNetworkTransformPrefab.GetComponent(); + // When running in distributed authority mode, make the NetworkObject transferable + networkObject.SetOwnershipStatus(m_DistributedAuthority ? NetworkObject.OwnershipStatus.Transferable : NetworkObject.OwnershipStatus.None); + var networkTransform = m_NetworkTransformPrefab.AddComponent(); rigidBody = m_NetworkTransformPrefab.AddComponent(); rigidBody.useGravity = false; + rigidBody.maxDepenetrationVelocity = 0; + rigidBody.linearDamping = 100; + rigidBody.mass = 100; rigidBody.interpolation = RigidbodyInterpolation.None; rigidBody.maxLinearVelocity = 0; + rigidBody.detectCollisions = false; + rigidBody.position = Vector3.zero; + rigidBody.rotation = Quaternion.identity; + rigidBody.transform.position = Vector3.zero; + rigidBody.transform.rotation = Quaternion.identity; // 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 @@ -276,10 +299,12 @@ void LogOwnerRigidBody(int stage) }; if (m_MotionModel == MotionModels.UseRigidbody) { + TestClientNetworkTransform.EnableLogState(m_EnableVerboseDebug); var ownerRigidbody = ownerInstance.GetComponent(); ownerRigidbody.Move(valueSetByOwner, rotation); + yield return new WaitForFixedUpdate(); ownerRigidbody.linearVelocity = Vector3.zero; - yield return s_DefaultWaitForTick; + yield return new WaitForFixedUpdate(); ownerInstance.transform.localScale = valueSetByOwner; } else @@ -312,15 +337,22 @@ void LogOwnerRigidBody(int stage) VerifyObjectIsSpawnedOnClient.ResetObjectTable(); if (m_DistributedAuthority) { - ownerInstance.NetworkObject.ChangeOwnership(networkManagerNonOwner.LocalClientId); + Assert.True(nonOwnerInstance.OwnerClientId != networkManagerNonOwner.LocalClientId, $"Non-Owner Client-{networkManagerNonOwner.LocalClientId} was already the owner prior to changing ownership!"); + nonOwnerInstance.NetworkObject.ChangeOwnership(networkManagerNonOwner.LocalClientId); + nonOwnerInstance.GetComponent().linearVelocity = Vector3.zero; + Assert.True(nonOwnerInstance.OwnerClientId == networkManagerNonOwner.LocalClientId, $"Client-{networkManagerNonOwner.LocalClientId} failed to change ownership!"); + + LogNonOwnerRigidBody(3); + yield return WaitForConditionOrTimeOut(() => ownerInstance.GetComponent().OwnerClientId == networkManagerNonOwner.LocalClientId); + Assert.False(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for original owner {networkManagerOwner.name}'s object instance {nonOwnerInstance.name} to change ownership!"); } 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(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 @@ -331,6 +363,7 @@ void LogOwnerRigidBody(int stage) yield return WaitForConditionOrTimeOut(() => VerifyObjectIsSpawnedOnClient.GetClientInstance(networkManagerNonOwner.LocalClientId) != null); nonOwnerInstance = VerifyObjectIsSpawnedOnClient.GetClientInstance(networkManagerNonOwner.LocalClientId); Assert.NotNull(nonOwnerInstance); + Assert.True(!nonOwnerInstance.IsOwner, $"Ownership failed to change on Client-{networkManagerNonOwner.LocalClientId} side! Expected owner to be {networkManagerOwner.LocalClientId} but owner is still {networkManagerNonOwner.LocalClientId}!"); // 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!"); @@ -344,7 +377,7 @@ void LogOwnerRigidBody(int stage) 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}"); + $"Expected Scale: {valueSetByOwner} | Current Scale: {transformToTest.localScale}\n {nonOwnerInstance.GetComponent().LogInfoBuilder}"); LogNonOwnerRigidBody(5); // Have the new owner change transform values and wait for those values to be applied on the non-owner side. @@ -358,6 +391,7 @@ void LogOwnerRigidBody(int stage) var ownerRigidbody = ownerInstance.GetComponent(); ownerRigidbody.Move(valueSetByOwner, rotation); LogOwnerRigidBody(2); + yield return new WaitForFixedUpdate(); ownerInstance.GetComponent().LogMotion = m_EnableVerboseDebug; nonOwnerInstance.GetComponent().LogMotion = m_EnableVerboseDebug; ownerRigidbody.linearVelocity = Vector3.zero; @@ -377,10 +411,11 @@ void LogOwnerRigidBody(int stage) 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" + - $"Expected Scale: {valueSetByOwner} | Current Scale: {transformToTest.localScale}"); + $"Expected Scale: {valueSetByOwner} | Current Scale: {transformToTest.localScale}\n {nonOwnerInstance.GetComponent().LogInfoBuilder}"); // The last check is to verify non-owners cannot change transform values after ownership has changed nonOwnerInstance.transform.position = Vector3.zero; @@ -445,6 +480,12 @@ public IEnumerator ServerAuthoritativeTest() 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}"); } + protected override IEnumerator OnTearDown() + { + TestClientNetworkTransform.EnableLogState(false); + return base.OnTearDown(); + } + /// /// NetworkTransformOwnershipTests helper behaviour /// @@ -457,6 +498,10 @@ public static void ResetObjectTable() NetworkManagerRelativeSpawnedObjects.Clear(); } + /// + /// For testing, just before changing ownership the table is cleared to assure that + /// ownership tansfer occurs. This will add the new owner to the table. + /// public override void OnGainedOwnership() { if (!NetworkManagerRelativeSpawnedObjects.ContainsKey(NetworkManager.LocalClientId)) @@ -466,6 +511,10 @@ public override void OnGainedOwnership() base.OnGainedOwnership(); } + /// + /// For testing, just before changing ownership the table is cleared to assure that + /// ownership tansfer occurs. This will add the previous owner to the table. + /// public override void OnLostOwnership() { if (!NetworkManagerRelativeSpawnedObjects.ContainsKey(NetworkManager.LocalClientId)) @@ -515,28 +564,57 @@ public override void OnNetworkDespawn() [DisallowMultipleComponent] internal class TestClientNetworkTransform : NetworkTransform { - //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 bool OnIsServerAuthoritative() + public static void EnableLogState(bool enable) { - return false; + s_LogStateEnabled = enable; + TrackByStateId = enable; + } + + private static bool s_LogStateEnabled; + + internal StringBuilder LogInfoBuilder = new StringBuilder(); + + private void LogInfo(NetworkTransformState state) + { + if (s_LogStateEnabled) + { + LogInfoBuilder.AppendLine($"N:{name} | CID:{NetworkManager.LocalClientId} | SID: {state.StateId} | NT:{NetworkManager.ServerTime.Tick} | Pos: {transform.position} | Sc: {transform.localScale}"); + } + } + + protected override void OnOwnershipChanged(ulong previous, ulong current) + { + + if (s_LogStateEnabled) + { + LogInfoBuilder.AppendLine($"Ownership Changed: {previous} --> {current} | Position: {transform.position}"); + } + LogInfo(LocalAuthoritativeNetworkState); + base.OnOwnershipChanged(previous, current); + + // Assure no velocity is set on this object for this particular test + if (current == NetworkManager.LocalClientId) + { + GetComponent().linearVelocity = Vector3.zero; + } + } + + protected override void OnAuthorityPushTransformState(ref NetworkTransformState networkTransformState) + { + LogInfo(networkTransformState); + base.OnAuthorityPushTransformState(ref networkTransformState); + } + + protected override void OnBeforeUpdateTransformState() + { + LogInfo(LocalAuthoritativeNetworkState); + base.OnBeforeUpdateTransformState(); + } + + protected override void OnNetworkTransformStateUpdated(ref NetworkTransformState oldState, ref NetworkTransformState newState) + { + LogInfo(newState); + base.OnNetworkTransformStateUpdated(ref oldState, ref newState); } } } @@ -791,7 +869,7 @@ public IEnumerator NestedNetworkTransformSpawnPositionTest() foreach (var networkManager in m_NetworkManagers) { - // Randomize the position + // Randomize the position RandomizeObjectTransformPositions(m_SpawnObject); // Create an instance owned by the specified networkmanager diff --git a/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs b/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs index 95ca7e0..7e12934 100644 --- a/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs +++ b/Tests/Runtime/NetworkTransform/NetworkTransformTests.cs @@ -123,7 +123,7 @@ private void UpdateTransformWorld(Components.NetworkTransform networkTransformTe } /// - /// This test validates the SwitchTransformSpaceWhenParented setting under all network topologies + /// This test validates the SwitchTransformSpaceWhenParented setting under all network topologies /// [Test] public void SwitchTransformSpaceWhenParentedTest([Values(0.5f, 1.0f, 5.0f)] float scale) diff --git a/Tests/Runtime/NetworkVariable/NetworkVariableCollectionsTests.cs b/Tests/Runtime/NetworkVariable/NetworkVariableCollectionsTests.cs index 0c8a2ff..3276b3d 100644 --- a/Tests/Runtime/NetworkVariable/NetworkVariableCollectionsTests.cs +++ b/Tests/Runtime/NetworkVariable/NetworkVariableCollectionsTests.cs @@ -20,7 +20,7 @@ namespace Unity.Netcode.RuntimeTests /// - HashSet /// This also does some testing on nested collections, but does /// not test every possible combination. - /// + /// [TestFixture(HostOrServer.Host)] [TestFixture(HostOrServer.Server)] public class NetworkVariableCollectionsTests : NetcodeIntegrationTest @@ -218,7 +218,7 @@ public IEnumerator TestListBuiltInTypeCollections() yield return WaitForConditionOrTimeOut(() => compInt.CompareTrackedChanges(ListTestHelperBase.Targets.Owner)); AssertOnTimeout($"Client-{client.LocalClientId} full set failed to synchronize on {nameof(ListTestHelperInt)} {compInt.name}!"); ////////////////////////////////// - // Server Full Set + // Server Full Set compIntServer.FullSet(GetRandomIntList(5), ListTestHelperBase.Targets.Server); yield return WaitForConditionOrTimeOut(() => compIntServer.CompareTrackedChanges(ListTestHelperBase.Targets.Server)); AssertOnTimeout($"Server full set failed to synchronize on {nameof(ListTestHelperInt)} {compIntServer.name}!"); @@ -285,7 +285,7 @@ public IEnumerator TestListBuiltInTypeCollections() // Only test restore on non-host clients (otherwise a host is both server and client/owner) if (!client.IsServer) { - // No Write Client Remove List item with CheckDirtyState restore + // No Write Client Remove List item with CheckDirtyState restore compListInt.Remove(compListInt.ListCollectionServer.Value[index], ListTestHelperBase.Targets.Server); yield return WaitForConditionOrTimeOut(() => compListInt.CompareTrackedChanges(ListTestHelperBase.Targets.Server)); AssertOnTimeout($"Client-{client.LocalClientId} remove failed to restore on {nameof(ListTestHelperListInt)} {compListIntServer.name}! {compListIntServer.GetLog()}"); @@ -474,7 +474,7 @@ public IEnumerator TestListSerializableObjectCollections() yield return WaitForConditionOrTimeOut(() => compObjectServer.CompareTrackedChanges(ListTestHelperBase.Targets.Server)); AssertOnTimeout($"Client-{client.LocalClientId} change failed to restore on {nameof(ListTestHelperSerializableObject)} {compObjectServer.name}!"); - // No Write Client Remove Serializable item with owner state update restore + // No Write Client Remove Serializable item with owner state update restore compObject.ListCollectionServer.Value[index] = SerializableObject.GetRandomObject(); } compObjectServer.ListCollectionServer.Value[index] = SerializableObject.GetRandomObject(); @@ -838,7 +838,7 @@ public IEnumerator TestDictionaryCollections() compDictionaryServer.ListCollectionOwner.IsDirty(); yield return WaitForConditionOrTimeOut(() => compDictionaryServer.CompareTrackedChanges(ListTestHelperBase.Targets.Owner)); AssertOnTimeout($"Server add to owner write collection property failed to restore on {className} {compDictionaryServer.name}! {compDictionaryServer.GetLog()}"); - // Server-side add the same key and SerializableObject to owner write permission (would throw key exists exception too if previous failed) + // Server-side add the same key and SerializableObject to owner write permission (would throw key exists exception too if previous failed) compDictionaryServer.ListCollectionOwner.Value.Add(newEntry.Item1, newEntry.Item2); // Server-side add a completely new key and SerializableObject to to owner write permission property compDictionaryServer.ListCollectionOwner.Value.Add(GetNextKey(), SerializableObject.GetRandomObject()); @@ -864,7 +864,7 @@ public IEnumerator TestDictionaryCollections() compDictionary.ListCollectionServer.IsDirty(); yield return WaitForConditionOrTimeOut(() => compDictionary.CompareTrackedChanges(ListTestHelperBase.Targets.Server)); AssertOnTimeout($"Client-{client.LocalClientId} add to server write collection property failed to restore on {className} {compDictionary.name}! {compDictionary.GetLog()}"); - // Client-side add the same key and SerializableObject to server write permission property (would throw key exists exception too if previous failed) + // Client-side add the same key and SerializableObject to server write permission property (would throw key exists exception too if previous failed) compDictionary.ListCollectionServer.Value.Add(newEntry.Item1, newEntry.Item2); // Client-side add a completely new key and SerializableObject to to server write permission property compDictionary.ListCollectionServer.Value.Add(GetNextKey(), SerializableObject.GetRandomObject()); diff --git a/Tests/Runtime/NetworkVariable/NetworkVariableTests.cs b/Tests/Runtime/NetworkVariable/NetworkVariableTests.cs index d67d207..a67be4d 100644 --- a/Tests/Runtime/NetworkVariable/NetworkVariableTests.cs +++ b/Tests/Runtime/NetworkVariable/NetworkVariableTests.cs @@ -1012,8 +1012,7 @@ public void TestUnsupportedManagedTypesThrowExceptions() } [Test] - // Exceptions should be thrown in DA mode with UserNetworkVariableSerialization - public void TestUnsupportedManagedTypesWithUserSerializationDoNotThrowExceptionsInClientServerMode() + public void TestUnsupportedManagedTypesWithUserSerializationDoNotThrowExceptions() { var variable = new NetworkVariable(); UserNetworkVariableSerialization.ReadValue = (FastBufferReader reader, out string value) => @@ -1039,10 +1038,6 @@ public void TestUnsupportedManagedTypesWithUserSerializationDoNotThrowExceptions variable.ReadField(reader); Assert.AreEqual("012345", variable.Value); } - catch (Exception) - { - Assert.True(NetworkVariableSerialization>.IsDistributedAuthority); - } finally { UserNetworkVariableSerialization.ReadValue = null; diff --git a/Tests/Runtime/PlayerObjectTests.cs b/Tests/Runtime/PlayerObjectTests.cs index e382bcf..4ffb783 100644 --- a/Tests/Runtime/PlayerObjectTests.cs +++ b/Tests/Runtime/PlayerObjectTests.cs @@ -1,4 +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; @@ -184,4 +187,150 @@ public IEnumerator PlayerSpawnPosition() } } } + + /// + /// This test validates that when a player is spawned it has all observers + /// properly set and the spawned and player object lists are properly populated. + /// It also validates that when a player is despawned and the client is still connected + /// that the client maintains its observers for other players. + /// + [TestFixture(HostOrServer.DAHost)] + [TestFixture(HostOrServer.Host)] + [TestFixture(HostOrServer.Server)] + internal class PlayerSpawnAndDespawnTests : NetcodeIntegrationTest + { + protected override int NumberOfClients => 4; + + private StringBuilder m_ErrorLog = new StringBuilder(); + + public PlayerSpawnAndDespawnTests(HostOrServer hostOrServer) : base(hostOrServer) { } + + private bool ValidateObservers(ulong playerClientId, NetworkObject player, ref List networkManagers) + { + foreach (var networkManager in networkManagers) + { + if (player != null && player.IsSpawned) + { + if (!networkManager.SpawnManager.SpawnedObjects.ContainsKey(player.NetworkObjectId)) + { + m_ErrorLog.AppendLine($"Client-{networkManager.LocalClientId} does not contain a spawned object entry {nameof(NetworkObject)}-{player.NetworkObjectId} for Client-{playerClientId}!"); + return false; + } + + var playerClone = networkManager.SpawnManager.SpawnedObjects[player.NetworkObjectId]; + foreach (var clientId in networkManager.ConnectedClientsIds) + { + if (!playerClone.IsNetworkVisibleTo(clientId)) + { + m_ErrorLog.AppendLine($"Client-{networkManager.LocalClientId} failed visibility check for Client-{clientId} on {nameof(NetworkObject)}-{player.NetworkObjectId} for Client-{playerClientId}!"); + return false; + } + } + + var foundPlayerClone = (NetworkObject)null; + foreach (var playerObject in networkManager.SpawnManager.PlayerObjects) + { + if (playerObject.OwnerClientId == playerClientId && playerObject.NetworkObjectId == player.NetworkObjectId) + { + foundPlayerClone = playerObject; + break; + } + } + if (!foundPlayerClone) + { + m_ErrorLog.AppendLine($"Client-{networkManager.LocalClientId} does not contain a player entry for {nameof(NetworkObject)}-{player.NetworkObjectId} for Client-{playerClientId}!"); + return false; + } + + } + else + { + // If the player client in question is despawned, then no NetworkManager instance + // should contain a clone of that (or the client's NetworkManager instance as well) + foreach (var playerClone in networkManager.SpawnManager.PlayerObjects) + { + if (playerClone.OwnerClientId == playerClientId) + { + m_ErrorLog.AppendLine($"Client-{networkManager.LocalClientId} contains a player {nameof(NetworkObject)}-{playerClone.NetworkObjectId} for Client-{playerClientId} when it should be despawned!"); + return false; + } + } + } + } + return true; + } + + private bool ValidateAllClientPlayerObservers() + { + var networkManagers = new List(); + + if (m_ServerNetworkManager.IsHost) + { + networkManagers.Add(m_ServerNetworkManager); + } + foreach (var networkManager in m_ClientNetworkManagers) + { + networkManagers.Add(networkManager); + } + + m_ErrorLog.Clear(); + var success = true; + foreach (var networkManager in networkManagers) + { + var spawnedOrNot = networkManager.LocalClient.PlayerObject == null ? "despawned" : "spawned"; + m_ErrorLog.AppendLine($"Validating Client-{networkManager.LocalClientId} {spawnedOrNot} player."); + if (networkManager.LocalClient == null) + { + m_ErrorLog.AppendLine($"No {nameof(NetworkClient)} found for Client-{networkManager.LocalClientId}!"); + success = false; + break; + } + if (!ValidateObservers(networkManager.LocalClientId, networkManager.LocalClient.PlayerObject, ref networkManagers)) + { + m_ErrorLog.AppendLine($"Client-{networkManager.LocalClientId} validation pass failed."); + success = false; + break; + } + } + networkManagers.Clear(); + return success; + } + + + [UnityTest] + public IEnumerator PlayerSpawnDespawn() + { + // Validate all observers are properly set with all players spawned + yield return WaitForConditionOrTimeOut(ValidateAllClientPlayerObservers); + AssertOnTimeout($"First Validation Failed:\n {m_ErrorLog}"); + var selectedClient = m_ClientNetworkManagers[Random.Range(0, m_ClientNetworkManagers.Count() - 1)]; + var playerSelected = selectedClient.LocalClient.PlayerObject; + + if (m_DistributedAuthority) + { + playerSelected.Despawn(false); + } + else + { + m_ServerNetworkManager.SpawnManager.SpawnedObjects[playerSelected.NetworkObjectId].Despawn(true); + } + + // Validate all observers are properly set with one of the players despawned + yield return WaitForConditionOrTimeOut(ValidateAllClientPlayerObservers); + AssertOnTimeout($"Second Validation Failed:\n {m_ErrorLog}"); + + if (m_DistributedAuthority) + { + playerSelected.SpawnAsPlayerObject(selectedClient.LocalClientId, false); + } + else + { + SpawnPlayerObject(m_ServerNetworkManager.NetworkConfig.PlayerPrefab, selectedClient); + } + + // Validate all observers are properly set when the client's player is respawned. + yield return WaitForConditionOrTimeOut(ValidateAllClientPlayerObservers); + AssertOnTimeout($"Third Validation Failed:\n {m_ErrorLog}"); + } + } } diff --git a/ValidationExceptions.json.meta b/Tests/Runtime/Prefabs.meta similarity index 57% rename from ValidationExceptions.json.meta rename to Tests/Runtime/Prefabs.meta index 3316cf2..588c42f 100644 --- a/ValidationExceptions.json.meta +++ b/Tests/Runtime/Prefabs.meta @@ -1,6 +1,7 @@ fileFormatVersion: 2 -guid: 2a43005be301c9043aab7034757d4868 -TextScriptImporter: +guid: 83133d71f2112db45ba626157c46e7f8 +folderAsset: yes +DefaultImporter: externalObjects: {} userData: assetBundleName: diff --git a/Tests/Runtime/AddNetworkPrefabTests.cs b/Tests/Runtime/Prefabs/AddNetworkPrefabTests.cs similarity index 100% rename from Tests/Runtime/AddNetworkPrefabTests.cs rename to Tests/Runtime/Prefabs/AddNetworkPrefabTests.cs diff --git a/Tests/Runtime/AddNetworkPrefabTests.cs.meta b/Tests/Runtime/Prefabs/AddNetworkPrefabTests.cs.meta similarity index 100% rename from Tests/Runtime/AddNetworkPrefabTests.cs.meta rename to Tests/Runtime/Prefabs/AddNetworkPrefabTests.cs.meta diff --git a/Tests/Runtime/NetworkPrefabHandlerTests.cs b/Tests/Runtime/Prefabs/NetworkPrefabHandlerTests.cs similarity index 97% rename from Tests/Runtime/NetworkPrefabHandlerTests.cs rename to Tests/Runtime/Prefabs/NetworkPrefabHandlerTests.cs index 2dc5f60..c66c843 100644 --- a/Tests/Runtime/NetworkPrefabHandlerTests.cs +++ b/Tests/Runtime/Prefabs/NetworkPrefabHandlerTests.cs @@ -85,9 +85,14 @@ public void NetworkConfigInvalidNetworkPrefabTest() private const string k_PrefabObjectName = "NetworkPrefabHandlerTestObject"; [Test] - public void NetworkPrefabHandlerClass() + public void NetworkPrefabHandlerClass([Values] bool distributedAuthority) { - Assert.IsTrue(NetworkManagerHelper.StartNetworkManager(out _)); + var networkConfig = new NetworkConfig() + { + NetworkTopology = distributedAuthority ? NetworkTopologyTypes.DistributedAuthority : NetworkTopologyTypes.ClientServer, + }; + + Assert.IsTrue(NetworkManagerHelper.StartNetworkManager(out _, networkConfig: networkConfig)); var testPrefabObjectName = k_PrefabObjectName; Guid baseObjectID = NetworkManagerHelper.AddGameNetworkObject(testPrefabObjectName); diff --git a/Tests/Runtime/NetworkPrefabHandlerTests.cs.meta b/Tests/Runtime/Prefabs/NetworkPrefabHandlerTests.cs.meta similarity index 100% rename from Tests/Runtime/NetworkPrefabHandlerTests.cs.meta rename to Tests/Runtime/Prefabs/NetworkPrefabHandlerTests.cs.meta diff --git a/Tests/Runtime/Prefabs/NetworkPrefabOverrideTests.cs b/Tests/Runtime/Prefabs/NetworkPrefabOverrideTests.cs new file mode 100644 index 0000000..84d9c56 --- /dev/null +++ b/Tests/Runtime/Prefabs/NetworkPrefabOverrideTests.cs @@ -0,0 +1,268 @@ +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 +{ + /// + /// Integration test that validates spawning instances of s with overrides and + /// registered overrides. + /// + [TestFixture(NetworkTopologyTypes.ClientServer, HostOrServer.Server)] + [TestFixture(NetworkTopologyTypes.ClientServer, HostOrServer.Host)] + [TestFixture(NetworkTopologyTypes.DistributedAuthority, HostOrServer.DAHost)] + internal class NetworkPrefabOverrideTests : NetcodeIntegrationTest + { + private const string k_PrefabRootName = "PrefabObj"; + protected override int NumberOfClients => 2; + + private NetworkPrefab m_ClientSidePlayerPrefab; + private NetworkPrefab m_PrefabOverride; + + public NetworkPrefabOverrideTests(NetworkTopologyTypes networkTopologyType, HostOrServer hostOrServer) : base(networkTopologyType, hostOrServer) { } + + /// + /// Prefab override handler that will instantiate the ServerSideInstance (m_PlayerPrefab) only on server instances + /// and will spawn the ClientSideInstance (m_ClientSidePlayerPrefab.Prefab) only on clients and/or a host. + /// + public class TestPrefabOverrideHandler : MonoBehaviour, INetworkPrefabInstanceHandler + { + public GameObject ServerSideInstance; + public GameObject ClientSideInstance; + private NetworkManager m_NetworkManager; + + private void Start() + { + m_NetworkManager = GetComponent(); + m_NetworkManager.PrefabHandler.AddHandler(ServerSideInstance, this); + } + + private void OnDestroy() + { + if (m_NetworkManager != null && m_NetworkManager.PrefabHandler != null) + { + m_NetworkManager.PrefabHandler.RemoveHandler(ServerSideInstance); + } + } + + public NetworkObject Instantiate(ulong ownerClientId, Vector3 position, Quaternion rotation) + { + var instance = m_NetworkManager.IsClient ? Instantiate(ClientSideInstance) : Instantiate(ServerSideInstance); + return instance.GetComponent(); + } + + public void Destroy(NetworkObject networkObject) + { + Object.Destroy(networkObject); + } + } + + /// + /// Mock component for testing that the client-side player is using the right + /// network prefab. + /// + public class ClientSideOnlyComponent : MonoBehaviour + { + + } + + /// + /// When we create the player prefab, make a modified instance that will be used + /// with the . + /// + protected override void OnCreatePlayerPrefab() + { + var clientPlayer = Object.Instantiate(m_PlayerPrefab); + clientPlayer.AddComponent(); + Object.DontDestroyOnLoad(clientPlayer); + m_ClientSidePlayerPrefab = new NetworkPrefab() + { + Prefab = clientPlayer, + }; + + base.OnCreatePlayerPrefab(); + } + + /// + /// Add the additional s and s to + /// all instances. + /// + protected override void OnServerAndClientsCreated() + { + // Create a NetworkPrefab with an override + var basePrefab = NetcodeIntegrationTestHelpers.CreateNetworkObject($"{k_PrefabRootName}-base", m_ServerNetworkManager, true); + var targetPrefab = NetcodeIntegrationTestHelpers.CreateNetworkObject($"{k_PrefabRootName}-over", m_ServerNetworkManager, true); + m_PrefabOverride = new NetworkPrefab() + { + Prefab = basePrefab, + Override = NetworkPrefabOverride.Prefab, + SourcePrefabToOverride = basePrefab, + OverridingTargetPrefab = targetPrefab, + }; + + // Add the prefab override handler for instance specific player prefabs to the server side + var playerPrefabOverrideHandler = m_ServerNetworkManager.gameObject.AddComponent(); + playerPrefabOverrideHandler.ServerSideInstance = m_PlayerPrefab; + playerPrefabOverrideHandler.ClientSideInstance = m_ClientSidePlayerPrefab.Prefab; + + // Add the NetworkPrefab with override + m_ServerNetworkManager.NetworkConfig.Prefabs.Add(m_PrefabOverride); + // Add the client player prefab that will be used on clients (and the host) + m_ServerNetworkManager.NetworkConfig.Prefabs.Add(m_ClientSidePlayerPrefab); + + foreach (var networkManager in m_ClientNetworkManagers) + { + // Add the prefab override handler for instance specific player prefabs to the client side + playerPrefabOverrideHandler = networkManager.gameObject.AddComponent(); + playerPrefabOverrideHandler.ServerSideInstance = m_PlayerPrefab; + playerPrefabOverrideHandler.ClientSideInstance = m_ClientSidePlayerPrefab.Prefab; + + // Add the NetworkPrefab with override + networkManager.NetworkConfig.Prefabs.Add(m_PrefabOverride); + // Add the client player prefab that will be used on clients (and the host) + networkManager.NetworkConfig.Prefabs.Add(m_ClientSidePlayerPrefab); + } + + m_PrefabOverride.Prefab.GetComponent().IsSceneObject = false; + m_PrefabOverride.SourcePrefabToOverride.GetComponent().IsSceneObject = false; + m_PrefabOverride.OverridingTargetPrefab.GetComponent().IsSceneObject = false; + m_ClientSidePlayerPrefab.Prefab.GetComponent().IsSceneObject = false; + + base.OnServerAndClientsCreated(); + } + + protected override IEnumerator OnTearDown() + { + if (m_PrefabOverride != null) + { + if (m_PrefabOverride.SourcePrefabToOverride) + { + Object.Destroy(m_PrefabOverride.SourcePrefabToOverride); + } + + if (m_PrefabOverride.OverridingTargetPrefab) + { + Object.Destroy(m_PrefabOverride.OverridingTargetPrefab); + } + } + + if (m_ClientSidePlayerPrefab != null) + { + if (m_ClientSidePlayerPrefab.Prefab) + { + Object.Destroy(m_ClientSidePlayerPrefab.Prefab); + } + } + m_ClientSidePlayerPrefab = null; + m_PrefabOverride = null; + + yield return base.OnTearDown(); + } + + + private GameObject GetPlayerNetworkPrefabObject(NetworkManager networkManager) + { + return networkManager.IsClient ? m_ClientSidePlayerPrefab.Prefab : m_PlayerPrefab; + } + + [UnityTest] + public IEnumerator PrefabOverrideTests() + { + var prefabNetworkObject = (NetworkObject)null; + var spawnedGlobalObjectId = (uint)0; + + var networkManagers = m_ClientNetworkManagers.ToList(); + if (m_UseHost) + { + networkManagers.Insert(0, m_ServerNetworkManager); + } + else + { + // If running as just a server, validate that all player prefab clone instances are the server side version + prefabNetworkObject = GetPlayerNetworkPrefabObject(m_ServerNetworkManager).GetComponent(); + foreach (var playerEntry in m_PlayerNetworkObjects[m_ServerNetworkManager.LocalClientId]) + { + spawnedGlobalObjectId = playerEntry.Value.GlobalObjectIdHash; + Assert.IsTrue(prefabNetworkObject.GlobalObjectIdHash == spawnedGlobalObjectId, $"Server-Side {playerEntry.Value.name} was spawned as prefab ({spawnedGlobalObjectId}) but we expected ({prefabNetworkObject.GlobalObjectIdHash})!"); + } + } + + // Validates prefab overrides via the NetworkPrefabHandler. + // Validate the player prefab instance clones relative to all NetworkManagers. + foreach (var networkManager in networkManagers) + { + // Get the expected player prefab to be spawned based on the NetworkManager + prefabNetworkObject = GetPlayerNetworkPrefabObject(networkManager).GetComponent(); + if (networkManager.IsClient) + { + spawnedGlobalObjectId = networkManager.LocalClient.PlayerObject.GlobalObjectIdHash; + Assert.IsTrue(prefabNetworkObject.GlobalObjectIdHash == spawnedGlobalObjectId, $"{networkManager.name} spawned player prefab ({spawnedGlobalObjectId}) did not match the expected one ({prefabNetworkObject.GlobalObjectIdHash})!"); + } + + foreach (var playerEntry in m_PlayerNetworkObjects[networkManager.LocalClientId]) + { + // We already checked our locally spawned player prefab above + if (playerEntry.Key == networkManager.LocalClientId) + { + continue; + } + spawnedGlobalObjectId = playerEntry.Value.GlobalObjectIdHash; + Assert.IsTrue(prefabNetworkObject.GlobalObjectIdHash == spawnedGlobalObjectId, $"Client-{networkManager.LocalClientId} clone of {playerEntry.Value.name} was spawned as prefab ({spawnedGlobalObjectId}) but we expected ({prefabNetworkObject.GlobalObjectIdHash})!"); + } + } + + // Validates prefab overrides via NetworkPrefab configuration. + var spawnedInstance = (NetworkObject)null; + var networkManagerOwner = m_ServerNetworkManager; + + if (m_DistributedAuthority) + { + networkManagerOwner = m_ClientNetworkManagers[0]; + } + // Clients and Host will spawn the OverridingTargetPrefab while a dedicated server will spawn the SourcePrefabToOverride + var expectedServerGlobalObjectIdHash = networkManagerOwner.IsClient ? m_PrefabOverride.OverridingTargetPrefab.GetComponent().GlobalObjectIdHash : m_PrefabOverride.SourcePrefabToOverride.GetComponent().GlobalObjectIdHash; + var expectedClientGlobalObjectIdHash = m_PrefabOverride.OverridingTargetPrefab.GetComponent().GlobalObjectIdHash; + + spawnedInstance = NetworkObject.InstantiateAndSpawn(m_PrefabOverride.SourcePrefabToOverride, networkManagerOwner, networkManagerOwner.LocalClientId); + var builder = new StringBuilder(); + bool ObjectSpawnedOnAllNetworkMangers() + { + builder.Clear(); + if (!m_ServerNetworkManager.SpawnManager.SpawnedObjects.ContainsKey(spawnedInstance.NetworkObjectId)) + { + builder.AppendLine($"Client-{m_ServerNetworkManager.LocalClientId} failed to spawn {spawnedInstance.name}-{spawnedInstance.NetworkObjectId}!"); + return false; + } + var instanceGID = m_ServerNetworkManager.SpawnManager.SpawnedObjects[spawnedInstance.NetworkObjectId].GlobalObjectIdHash; + if (instanceGID != expectedServerGlobalObjectIdHash) + { + builder.AppendLine($"Client-{m_ServerNetworkManager.LocalClientId} instance {spawnedInstance.name}-{spawnedInstance.NetworkObjectId} GID is {instanceGID} but was expected to be {expectedServerGlobalObjectIdHash}!"); + return false; + } + + foreach (var networkManger in m_ClientNetworkManagers) + { + if (!networkManger.SpawnManager.SpawnedObjects.ContainsKey(spawnedInstance.NetworkObjectId)) + { + builder.AppendLine($"Client-{networkManger.LocalClientId} failed to spawn {spawnedInstance.name}-{spawnedInstance.NetworkObjectId}!"); + return false; + } + instanceGID = networkManger.SpawnManager.SpawnedObjects[spawnedInstance.NetworkObjectId].GlobalObjectIdHash; + if (instanceGID != expectedClientGlobalObjectIdHash) + { + builder.AppendLine($"Client-{networkManger.LocalClientId} instance {spawnedInstance.name}-{spawnedInstance.NetworkObjectId} GID is {instanceGID} but was expected to be {expectedClientGlobalObjectIdHash}!"); + return false; + } + } + return true; + } + + yield return WaitForConditionOrTimeOut(ObjectSpawnedOnAllNetworkMangers); + AssertOnTimeout($"The spawned prefab override validation failed!\n {builder}"); + } + } +} diff --git a/Tests/Runtime/Prefabs/NetworkPrefabOverrideTests.cs.meta b/Tests/Runtime/Prefabs/NetworkPrefabOverrideTests.cs.meta new file mode 100644 index 0000000..e0120db --- /dev/null +++ b/Tests/Runtime/Prefabs/NetworkPrefabOverrideTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c5e27e24bc5f783458d6a45585308f87 \ No newline at end of file diff --git a/Tests/Runtime/Transports/UnityTransportConnectionTests.cs b/Tests/Runtime/Transports/UnityTransportConnectionTests.cs index ac4c089..3e2c746 100644 --- a/Tests/Runtime/Transports/UnityTransportConnectionTests.cs +++ b/Tests/Runtime/Transports/UnityTransportConnectionTests.cs @@ -33,7 +33,7 @@ public IEnumerator Cleanup() if (transport) { transport.Shutdown(); - UnityEngine.Object.DestroyImmediate(transport); + UnityEngine.Object.DestroyImmediate(transport.gameObject); } } @@ -42,6 +42,7 @@ public IEnumerator Cleanup() transportEvents?.Clear(); } + UnityTransportTestComponent.CleanUp(); yield return null; } @@ -59,6 +60,7 @@ public void DetectInvalidEndpoint() Assert.False(m_Clients[0].StartClient(), "Client failed to detect invalid endpoint!"); netcodeLogAssert.LogWasReceived(LogType.Error, $"Network listen address ({m_Server.ConnectionData.Address}) is Invalid!"); netcodeLogAssert.LogWasReceived(LogType.Error, $"Target server network address ({m_Clients[0].ConnectionData.Address}) is Invalid!"); + UnityTransportTestComponent.CleanUp(); } // Check connection with a single client. @@ -161,8 +163,6 @@ public IEnumerator ServerDisconnectMultipleClients() // Check that all clients got a Disconnect event. Assert.True(m_ClientsEvents.All(evs => evs.Count == 2)); Assert.True(m_ClientsEvents.All(evs => evs[1].Type == NetworkEvent.Disconnect)); - - yield return null; } // Check client disconnection from a single client. @@ -188,13 +188,11 @@ public IEnumerator ClientDisconnectMultipleClients() { InitializeTransport(out m_Server, out m_ServerEvents); m_Server.StartServer(); - for (int i = 0; i < k_NumClients; i++) { InitializeTransport(out m_Clients[i], out m_ClientsEvents[i]); m_Clients[i].StartClient(); } - yield return WaitForNetworkEvent(NetworkEvent.Connect, m_ClientsEvents[k_NumClients - 1]); // Disconnect a single client. @@ -207,14 +205,11 @@ public IEnumerator ClientDisconnectMultipleClients() { m_Clients[i].DisconnectLocalClient(); } - yield return WaitForNetworkEvent(NetworkEvent.Disconnect, m_ServerEvents, 5); // Check that we got the correct number of Disconnect events on the server. Assert.AreEqual(k_NumClients * 2, m_ServerEvents.Count); Assert.AreEqual(k_NumClients, m_ServerEvents.Count(e => e.Type == NetworkEvent.Disconnect)); - - yield return null; } // Check that server re-disconnects are no-ops. @@ -244,8 +239,6 @@ public IEnumerator RepeatedServerDisconnectsNoop() // Check we haven't received anything else on the client or server. Assert.AreEqual(m_ServerEvents.Count, previousServerEventsCount); Assert.AreEqual(m_ClientsEvents[0].Count, previousClientEventsCount); - - yield return null; } // Check that client re-disconnects are no-ops. @@ -275,8 +268,6 @@ public IEnumerator RepeatedClientDisconnectsNoop() // Check we haven't received anything else on the client or server. Assert.AreEqual(m_ServerEvents.Count, previousServerEventsCount); Assert.AreEqual(m_ClientsEvents[0].Count, previousClientEventsCount); - - yield return null; } // Check connection with different server/listen addresses. diff --git a/Tests/Runtime/Transports/UnityTransportTestHelpers.cs b/Tests/Runtime/Transports/UnityTransportTestHelpers.cs index 62ae2b5..926b2fa 100644 --- a/Tests/Runtime/Transports/UnityTransportTestHelpers.cs +++ b/Tests/Runtime/Transports/UnityTransportTestHelpers.cs @@ -36,6 +36,24 @@ public static IEnumerator WaitForNetworkEvent(NetworkEvent type, List events, float timeout = MaxNetworkEventWaitTime) + { + int initialCount = events.Count; + float startTime = Time.realtimeSinceStartup; + + while (Time.realtimeSinceStartup - startTime < timeout) + { + if (events.Count > initialCount) + { + Assert.Fail("Received unexpected network event."); + } + + yield return new WaitForSeconds(0.01f); + } + } + + // Common code to initialize a UnityTransport that logs its events. public static void InitializeTransport(out UnityTransport transport, out List events, int maxPayloadSize = UnityTransport.InitialMaxPayloadSize, int maxSendQueueSize = 0, NetworkFamily family = NetworkFamily.Ipv4) @@ -43,7 +61,7 @@ public static void InitializeTransport(out UnityTransport transport, out List(); + transport = new GameObject().AddComponent(); transport.OnTransportEvent += logger.HandleEvent; transport.MaxPayloadSize = maxPayloadSize; @@ -91,5 +109,58 @@ public void HandleEvent(NetworkEvent type, ulong clientID, ArraySegment da }); } } + + internal class UnityTransportTestComponent : UnityTransport, INetworkUpdateSystem + { + private static List s_Instances = new List(); + + public static void CleanUp() + { + for (int i = s_Instances.Count - 1; i >= 0; i--) + { + var instance = s_Instances[i]; + instance.Shutdown(); + DestroyImmediate(instance.gameObject); + } + s_Instances.Clear(); + } + + /// + /// Simulate the being invoked so + /// and are invoked. + /// + public void NetworkUpdate(NetworkUpdateStage updateStage) + { + switch (updateStage) + { + case NetworkUpdateStage.EarlyUpdate: + { + EarlyUpdate(); + break; + } + case NetworkUpdateStage.PostLateUpdate: + { + PostLateUpdate(); + break; + } + } + } + + public override void Shutdown() + { + s_Instances.Remove(this); + base.Shutdown(); + this.UnregisterAllNetworkUpdates(); + } + + public override void Initialize(NetworkManager networkManager = null) + { + base.Initialize(networkManager); + this.RegisterNetworkUpdate(NetworkUpdateStage.EarlyUpdate); + this.RegisterNetworkUpdate(NetworkUpdateStage.PreUpdate); + this.RegisterNetworkUpdate(NetworkUpdateStage.PostLateUpdate); + s_Instances.Add(this); + } + } } } diff --git a/Tests/Runtime/Transports/UnityTransportTests.cs b/Tests/Runtime/Transports/UnityTransportTests.cs index 4a14206..016d457 100644 --- a/Tests/Runtime/Transports/UnityTransportTests.cs +++ b/Tests/Runtime/Transports/UnityTransportTests.cs @@ -60,11 +60,11 @@ public IEnumerator Cleanup() // Need to destroy the GameObject (all assigned components will get destroyed too) UnityEngine.Object.DestroyImmediate(m_Client2.gameObject); } - m_ServerEvents?.Clear(); m_Client1Events?.Clear(); m_Client2Events?.Clear(); + UnityTransportTestComponent.CleanUp(); yield return null; } @@ -217,8 +217,6 @@ public IEnumerator MultipleSendsSingleFrame( Assert.AreEqual(33, m_ServerEvents[3].Data.First()); Assert.AreEqual(10, m_ServerEvents[3].Data.Count); - - yield return null; } // Check sending data to multiple clients. @@ -260,8 +258,6 @@ public IEnumerator SendMultipleClients( byte c1Data = m_Client1Events[1].Data.First(); byte c2Data = m_Client2Events[1].Data.First(); Assert.That((c1Data == 11 && c2Data == 22) || (c1Data == 22 && c2Data == 11)); - - yield return null; } // Check receiving data from multiple clients. @@ -299,8 +295,6 @@ public IEnumerator ReceiveMultipleClients( byte sData1 = m_ServerEvents[2].Data.First(); byte sData2 = m_ServerEvents[3].Data.First(); Assert.That((sData1 == 11 && sData2 == 22) || (sData1 == 22 && sData2 == 11)); - - yield return null; } // Check that we get disconnected when overflowing the reliable send queue. @@ -332,8 +326,6 @@ public IEnumerator DisconnectOnReliableSendQueueOverflow() Assert.AreEqual(2, m_Client1Events.Count); Assert.AreEqual(NetworkEvent.Disconnect, m_Client1Events[1].Type); - - yield return null; } // Check that it's fine to overflow the unreliable send queue (traffic is flushed on overflow). @@ -373,8 +365,6 @@ public IEnumerator SendCompletesOnUnreliableSendQueueOverflow() Assert.AreEqual(NetworkEvent.Data, m_ServerEvents[i].Type); Assert.AreEqual(1024, m_ServerEvents[i].Data.Count); } - - yield return null; } #if !UTP_TRANSPORT_2_0_ABOVE @@ -451,8 +441,6 @@ public IEnumerator SendQueuesFlushedOnShutdown([ValueSource("k_DeliveryParameter m_Client1.Shutdown(); yield return WaitForNetworkEvent(NetworkEvent.Data, m_ServerEvents); - - yield return null; } [UnityTest] @@ -472,8 +460,6 @@ public IEnumerator SendQueuesFlushedOnLocalClientDisconnect([ValueSource("k_Deli m_Client1.DisconnectLocalClient(); yield return WaitForNetworkEvent(NetworkEvent.Data, m_ServerEvents); - - yield return null; } [UnityTest] @@ -493,8 +479,6 @@ public IEnumerator SendQueuesFlushedOnRemoteClientDisconnect([ValueSource("k_Del m_Server.DisconnectRemoteClient(m_ServerEvents[0].ClientID); yield return WaitForNetworkEvent(NetworkEvent.Data, m_Client1Events); - - yield return null; } [UnityTest] @@ -514,8 +498,47 @@ public IEnumerator ReliablePayloadsCanBeLargerThanMaximum() m_Server.Send(m_Client1.ServerClientId, data, NetworkDelivery.Reliable); yield return WaitForNetworkEvent(NetworkEvent.Data, m_Client1Events); + } - yield return null; + public enum AfterShutdownAction + { + Send, + DisconnectRemoteClient, + DisconnectLocalClient, + } + + [UnityTest] + public IEnumerator DoesNotActAfterShutdown([Values] AfterShutdownAction afterShutdownAction) + { + InitializeTransport(out m_Server, out m_ServerEvents); + InitializeTransport(out m_Client1, out m_Client1Events); + + m_Server.StartServer(); + m_Client1.StartClient(); + + yield return WaitForNetworkEvent(NetworkEvent.Connect, m_Client1Events); + + m_Server.Shutdown(); + + if (afterShutdownAction == AfterShutdownAction.Send) + { + var data = new ArraySegment(new byte[16]); + m_Server.Send(m_Client1.ServerClientId, data, NetworkDelivery.Reliable); + + yield return EnsureNoNetworkEvent(m_Client1Events); + } + else if (afterShutdownAction == AfterShutdownAction.DisconnectRemoteClient) + { + m_Server.DisconnectRemoteClient(m_Client1.ServerClientId); + + LogAssert.Expect(LogType.Assert, "DisconnectRemoteClient should be called on a listening server"); + } + else if (afterShutdownAction == AfterShutdownAction.DisconnectLocalClient) + { + m_Server.DisconnectLocalClient(); + + yield return EnsureNoNetworkEvent(m_Client1Events); + } } } } diff --git a/ValidationExceptions.json b/ValidationExceptions.json deleted file mode 100644 index 9128292..0000000 --- a/ValidationExceptions.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "ErrorExceptions": [], - "WarningExceptions": [] -} diff --git a/package.json b/package.json index ab43e49..bef660d 100644 --- a/package.json +++ b/package.json @@ -2,29 +2,29 @@ "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": "2.1.1", + "version": "2.2.0", "unity": "6000.0", "dependencies": { "com.unity.nuget.mono-cecil": "1.11.4", - "com.unity.transport": "2.3.0" + "com.unity.transport": "2.4.0" }, + "samples": [ + { + "displayName": "Bootstrap", + "description": "A lightweight sample to get started", + "path": "Samples~/Bootstrap" + } + ], "_upm": { - "changelog": "### Added\n\n- Added ability to edit the `NetworkConfig.AutoSpawnPlayerPrefabClientSide` within the inspector view. (#3097)\n- Added `IContactEventHandlerWithInfo` that derives from `IContactEventHandler` that can be updated per frame to provide `ContactEventHandlerInfo` information to the `RigidbodyContactEventManager` when processing collisions. (#3094)\n - `ContactEventHandlerInfo.ProvideNonRigidBodyContactEvents`: When set to true, non-`Rigidbody` collisions with the registered `Rigidbody` will generate contact event notifications. (#3094)\n - `ContactEventHandlerInfo.HasContactEventPriority`: When set to true, the `Rigidbody` will be prioritized as the instance that generates the event if the `Rigidbody` colliding does not have priority. (#3094)\n- Added a static `NetworkManager.OnInstantiated` event notification to be able to track when a new `NetworkManager` instance has been instantiated. (#3088)\n- Added a static `NetworkManager.OnDestroying` event notification to be able to track when an existing `NetworkManager` instance is being destroyed. (#3088)\n\n### Fixed\n\n- Fixed issue where `NetworkPrefabProcessor` would not mark the prefab list as dirty and prevent saving the `DefaultNetworkPrefabs` asset when only imports or only deletes were detected.(#3103)\n- Fixed an issue where nested `NetworkTransform` components in owner authoritative mode cleared their initial settings on the server, causing improper synchronization. (#3099)\n- Fixed issue with service not getting synchronized with in-scene placed `NetworkObject` instances when a session owner starts a `SceneEventType.Load` event. (#3096)\n- Fixed issue with the in-scene network prefab instance update menu tool where it was not properly updating scenes when invoked on the root prefab instance. (#3092)\n- Fixed an issue where newly synchronizing clients would always receive current `NetworkVariable` values, potentially causing issues with collections if there were pending updates. Now, pending state updates serialize previous values to avoid duplicates on new clients. (#3081)\n- Fixed issue where changing ownership would mark every `NetworkVariable` dirty. Now, it will only mark any `NetworkVariable` with owner read permissions as dirty and will send/flush any pending updates to all clients prior to sending the change in ownership message. (#3081)\n- Fixed an issue where transferring ownership of `NetworkVariable` collections didn't update the new owner’s previous value, causing the last added value to be detected as a change during additions or removals. (#3081)\n- Fixed issue where a client (or server) with no write permissions for a `NetworkVariable` using a standard .NET collection type could still modify the collection which could cause various issues depending upon the modification and collection type. (#3081)\n- Fixed issue where applying the position and/or rotation to the `NetworkManager.ConnectionApprovalResponse` when connection approval and auto-spawn player prefab were enabled would not apply the position and/or rotation when the player prefab was instantiated. (#3078)\n- Fixed issue where `NetworkObject.SpawnWithObservers` was not being honored when spawning the player prefab. (#3077)\n- Fixed issue with the client count not being correct on the host or server side when a client disconnects itself from a session. (#3075)\n\n### Changed\n\n- Changed `NetworkConfig.AutoSpawnPlayerPrefabClientSide` is no longer automatically set when starting `NetworkManager`. (#3097)\n- Updated `NetworkVariableDeltaMessage` so the server now forwards delta state updates from clients immediately, instead of waiting until the end of the frame or the next network tick. (#3081)" + "changelog": "### Added\n\n- Added `NetworkObject.OwnershipStatus.SessionOwner` to allow Network Objects to be distributable and only owned by the Session Owner. This flag will override all other `OwnershipStatus` flags. (#3175)\n- Added `UnityTransport.GetEndpoint` method to provide a way to obtain `NetworkEndpoint` information of a connection via client identifier. (#3130)\n- Added `NetworkTransport.OnEarlyUpdate` and `NetworkTransport.OnPostLateUpdate` methods to provide more control over handling transport related events at the start and end of each frame. (#3113)\n\n### Fixed\n\n- Fixed issue where the server, host, or session owner would not populate the in-scene place `NetworkObject` table if the scene was loaded prior to starting the `NetworkManager`. (#3177)\n- Fixed issue where the `NetworkObjectIdHash` value could be incorrect when entering play mode while still in prefab edit mode with pending changes and using MPPM. (#3162)\n- Fixed issue where a sever only `NetworkManager` instance would spawn the actual `NetworkPrefab`'s `GameObject` as opposed to creating an instance of it. (#3160)\n- Fixed issue where only the session owner (as opposed to all clients) would handle spawning prefab overrides properly when using a distributed authority network topology. (#3160)\n- Fixed issue where an exception was thrown when calling `NetworkManager.Shutdown` after calling `UnityTransport.Shutdown`. (#3118)\n- Fixed issue where `NetworkList` properties on in-scene placed `NetworkObject`s could cause small memory leaks when entering playmode. (#3147)\n- Fixed in-scene `NertworkObject` synchronization issue when loading a scene with currently connected clients connected to a session created by a `NetworkManager` started as a server (i.e. not as a host). (#3133)\n- Fixed issue where a `NetworkManager` started as a server would not add itself as an observer to in-scene placed `NetworkObject`s instantiated and spawned by a scene loading event. (#3133)\n- Fixed issue where spawning a player using `NetworkObject.InstantiateAndSpawn` or `NetworkSpawnManager.InstantiateAndSpawn` would not update the `NetworkSpawnManager.PlayerObjects` or assign the newly spawned player to the `NetworkClient.PlayerObject`. (#3122)\n- Fixed issue where queued UnitTransport (NetworkTransport) message batches were being sent on the next frame. They are now sent at the end of the frame during `PostLateUpdate`. (#3113)\n- Fixed issue where `NotOwnerRpcTarget` or `OwnerRpcTarget` were not using their replacements `NotAuthorityRpcTarget` and `AuthorityRpcTarget` which would invoke a warning. (#3111)\n- Fixed issue where client is removed as an observer from spawned objects when their player instance is despawned. (#3110)\n- Fixed issue where `NetworkAnimator` would statically allocate write buffer space for `Animator` parameters that could cause a write error if the number of parameters exceeded the space allocated. (#3108)\n\n### Changed\n\n- In-scene placed `NetworkObject`s have been made distributable when balancing object distribution after a connection event. (#3175)\n- Optimised `NetworkVariable` and `NetworkTransform` related packets when in Distributed Authority mode.\n- The Debug Simulator section of the Unity Transport component was removed. This section was not functional anymore and users are now recommended to use the more featureful [Network Simulator](https://docs-multiplayer.unity3d.com/tools/current/tools-network-simulator/) tool from the Multiplayer Tools package instead. (#3121)" }, "upmCi": { - "footprint": "8331c76150e539e36659d8b7be3ba0fb6d21027a" + "footprint": "9d95aefc0dccf8f9dc0bcf0017dee417d7d31f56" }, - "documentationUrl": "https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@2.1/manual/index.html", + "documentationUrl": "https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@2.2/manual/index.html", "repository": { "url": "https://github.com/Unity-Technologies/com.unity.netcode.gameobjects.git", "type": "git", - "revision": "264b30d176dd71fcedd022a8d6f4d59a2e3922bc" - }, - "samples": [ - { - "displayName": "Bootstrap", - "description": "A lightweight sample to get started", - "path": "Samples~/Bootstrap" - } - ] + "revision": "ba490651a8c6cf2f98c2bbacef8b24a1170860b3" + } }