com.unity.netcode.gameobjects@2.2.0

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

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)
This commit is contained in:
Unity Technologies
2024-12-12 00:00:00 +00:00
parent 016788c21e
commit 8fe07bbad2
78 changed files with 2243 additions and 1187 deletions

1
.signature Normal file
View File

@@ -0,0 +1 @@
{"timestamp":1734331212,"signature":"mMrBXdBegYd6TPqNVci9OkWh1H10YU8Ug8KlSpiyNzbXlS5z7O7Rdif3gvTdXK0O07HWmIuszcUoljQIaxkGAYq2g9A85IcvhbWsAAqxjSEZfQPsxFZlJQ9PqU4tfMItk7K1VP1YfcBxitxPHcUeO2IwBYVLx51gg6X/0qHWtkifmZ/cBbGTBNEYE+m7KfRYUyu23kOPMGOCBeULivZO9y/2A0qXkMeBiPo3KQFU6481n4GV6fahyLrG2llfM8xtW8YeouPyt/IMD86at8eeY+E5mW0iXGms9IMLf/DH6vjJnuSEfgMXfjcGnRO0m+RP+ig8HzjbPVty7oAOgfm6Oc1frOP4Cmudk97fIEzC10B0lj2uzFudT5UVPk4Hr6Mf/2ka0m+XTdRNHVRyOYBcHsJQYf0HKW/4jJPwWrSCSk2uE0fPn1sTvMb+i4pXCn7J700b7NMLPFJaWeb6kA2e3v8w5FybshFZWCU6fyLWGn1AR60u0BxL88Hx4VO5UjnJ","publicKey":"LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQm9qQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FZOEFNSUlCaWdLQ0FZRUFzdUhXYUhsZ0I1cVF4ZEJjTlJKSAordHR4SmoxcVY1NTdvMlZaRE1XaXhYRVBkRTBEMVFkT1JIRXNSS1RscmplUXlERU83ZlNQS0ZwZ1A3MU5TTnJCCkFHM2NFSU45aHNQVDhOVmllZmdWem5QTkVMenFkVmdEbFhpb2VpUnV6OERKWFgvblpmU1JWKytwbk9ySTRibG4KS0twelJlNW14OTc1SjhxZ1FvRktKT0NNRlpHdkJMR2MxSzZZaEIzOHJFODZCZzgzbUovWjBEYkVmQjBxZm13cgo2ZDVFUXFsd0E5Y3JZT1YyV1VpWXprSnBLNmJZNzRZNmM1TmpBcEFKeGNiaTFOaDlRVEhUcU44N0ZtMDF0R1ZwCjVNd1pXSWZuYVRUemEvTGZLelR5U0pka0tldEZMVGdkYXpMYlpzUEE2aHBSK0FJRTJhc0tLTi84UUk1N3UzU2cKL2xyMnZKS1IvU2l5eEN1Q20vQWJkYnJMbXk0WjlSdm1jMGdpclA4T0lLQWxBRWZ2TzV5Z2hSKy8vd1RpTFlzUQp1SllDM0V2UE16ZGdKUzdGR2FscnFLZzlPTCsxVzROY05yNWdveVdSUUJ0cktKaWlTZEJVWmVxb0RvSUY5NHpCCndGbzJJT1JFdXFqcU51M3diMWZIM3p1dGdtalFra3IxVjJhd3hmcExLWlROQWdNQkFBRT0KLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tCg"}

View File

@@ -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)

View File

@@ -237,7 +237,7 @@ namespace Unity.Netcode.Editor
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"));

View File

@@ -88,6 +88,14 @@ namespace Unity.Netcode.Editor
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 @@ namespace Unity.Netcode.Editor
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 @@ namespace Unity.Netcode.Editor
// 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();
}

View File

@@ -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.

View File

@@ -230,6 +230,7 @@ namespace Unity.Netcode.Components
}
}
#if UNITY_EDITOR
private void ParseStateMachineStates(int layerIndex, ref AnimatorController animatorController, ref AnimatorStateMachine stateMachine)
{
@@ -263,7 +264,6 @@ namespace Unity.Netcode.Components
{
case AnimatorControllerParameterType.Trigger:
{
if (transition.destinationStateMachine != null)
{
var destinationStateMachine = transition.destinationStateMachine;
@@ -297,18 +297,12 @@ namespace Unity.Netcode.Components
}
}
}
#endif
/// <summary>
/// Creates the TransitionStateInfoList table
/// </summary>
private void BuildTransitionStateInfoList()
{
#if UNITY_EDITOR
if (UnityEditor.EditorApplication.isUpdating || UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
{
return;
}
if (m_Animator == null)
{
return;
@@ -326,9 +320,18 @@ namespace Unity.Netcode.Components
var stateMachine = animatorController.layers[x].stateMachine;
ParseStateMachineStates(x, ref animatorController, ref stateMachine);
}
#endif
}
/// <summary>
/// In-Editor Only
/// Virtual OnValidate method for custom derived NetworkAnimator classes.
/// </summary>
protected virtual void OnValidate()
{
BuildTransitionStateInfoList();
}
#endif
public void OnAfterDeserialize()
{
BuildDestinationToTransitionInfoTable();
@@ -336,7 +339,7 @@ namespace Unity.Netcode.Components
public void OnBeforeSerialize()
{
BuildTransitionStateInfoList();
// Do nothing when serializing (handled during OnValidate)
}
internal struct AnimationState : INetworkSerializable
@@ -419,8 +422,8 @@ namespace Unity.Netcode.Components
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<AnimationState> AnimationStates;
@@ -496,7 +499,7 @@ namespace Unity.Netcode.Components
}
/// <summary>
/// Override this method and return false to switch to owner authoritative mode
/// Override this method and return false to switch to owner authoritative mode.
/// </summary>
/// <remarks>
/// When using a distributed authority network topology, this will default to
@@ -507,10 +510,6 @@ namespace Unity.Netcode.Components
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 @@ namespace Unity.Netcode.Components
}
// 128 bytes per Animator
private FastBufferWriter m_ParameterWriter = new FastBufferWriter(k_MaxAnimationParams * sizeof(float), Allocator.Persistent);
private FastBufferWriter m_ParameterWriter;
private NativeArray<AnimatorParamCache> m_CachedAnimatorParameters;
@@ -586,6 +585,14 @@ namespace Unity.Netcode.Components
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 @@ namespace Unity.Netcode.Components
}
}
// 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<AnimatorParamCache>(parameters.Length, Allocator.Persistent);
@@ -655,7 +665,37 @@ namespace Unity.Netcode.Components
}
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);
}
/// <summary>
@@ -697,7 +737,7 @@ namespace Unity.Netcode.Components
}
/// <summary>
/// Wries all parameter and state information needed to initially synchronize a client
/// Writes all parameter and state information needed to initially synchronize a client
/// </summary>
private void WriteSynchronizationData<T>(ref BufferSerializer<T> serializer) where T : IReaderWriter
{
@@ -772,8 +812,10 @@ namespace Unity.Netcode.Components
}
}
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 @@ namespace Unity.Netcode.Components
{
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 @@ namespace Unity.Netcode.Components
// 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 @@ namespace Unity.Netcode.Components
{
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 @@ namespace Unity.Netcode.Components
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 @@ namespace Unity.Netcode.Components
/// <summary>
/// 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
/// </summary>
/// <param name="animationTriggerMessage">the payload containing the trigger data to apply</param>
[Rpc(SendTo.NotAuthority)]
@@ -1447,7 +1492,7 @@ namespace Unity.Netcode.Components
/// <summary>
/// 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
/// </summary>
/// <param name="animationTriggerMessage">the payload containing the trigger data to apply</param>
/// <param name="clientRpcParams">unused</param>
@@ -1513,7 +1558,7 @@ namespace Unity.Netcode.Components
}
/// <summary>
/// Resets the trigger for the associated animation. See <see cref="SetTrigger(string)">SetTrigger</see> for more on how triggers are special
/// Resets the trigger for the associated animation. See <see cref="SetTrigger(string)">SetTrigger</see> for more on how triggers are special
/// </summary>
/// <param name="triggerName">The string name of the trigger to reset</param>
public void ResetTrigger(string triggerName)
@@ -1529,4 +1574,5 @@ namespace Unity.Netcode.Components
}
}
}
#endif // COM_UNITY_MODULES_ANIMATION
// COM_UNITY_MODULES_ANIMATION
#endif

View File

@@ -180,7 +180,7 @@ namespace Unity.Netcode.Components
/// </summary>
/// <remarks>
/// For <see cref="Rigidbody2D"/>, only the x and y components of the <see cref="Vector3"/> are applied.
/// </remarks>
/// </remarks>
public void SetLinearVelocity(Vector3 linearVelocity)
{
if (m_IsRigidbody2D)
@@ -546,7 +546,7 @@ namespace Unity.Netcode.Components
{
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 @@ namespace Unity.Netcode.Components
}
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

View File

@@ -32,7 +32,8 @@ namespace Unity.Netcode.Components
/// </summary>
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 @@ namespace Unity.Netcode.Components
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 @@ namespace Unity.Netcode.Components
}
/// <summary>
/// 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.
/// </summary>
public bool IsUnreliableFrameSync()
@@ -929,8 +937,6 @@ namespace Unity.Netcode.Components
#endregion
#region PROPERTIES AND GENERAL METHODS
public enum AuthorityModes
{
Server,
@@ -1370,7 +1376,8 @@ namespace Unity.Netcode.Components
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 @@ namespace Unity.Netcode.Components
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 @@ namespace Unity.Netcode.Components
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 @@ namespace Unity.Netcode.Components
/// - Local space to local space (<see cref="NetworkObject"/> parent to <see cref="NetworkObject"/> parent)
/// Will all smoothly transition while interpolation is enabled.
/// (Does not work if using a <see cref="Rigidbody"/> or <see cref="Rigidbody2D"/> for motion)
///
///
/// When a parent changes, non-authoritative instances should:<br />
/// - Apply the resultant position, rotation, and scale from the parenting action.<br />
/// - Clear interpolators (even if not enabled on this frame)<br />
@@ -3575,7 +3582,7 @@ namespace Unity.Netcode.Components
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 @@ namespace Unity.Netcode.Components
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 @@ namespace Unity.Netcode.Components
// 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 @@ namespace Unity.Netcode.Components
/// <summary>
/// Determines whether the <see cref="NetworkTransform"/> is <see cref="AuthorityModes.Server"/> or <see cref="AuthorityModes.Owner"/> based on the <see cref="AuthorityMode"/> property.
/// You can override this method to control this logic.
/// You can override this method to control this logic.
/// </summary>
/// <returns><see cref="true"/> or <see cref="false"/></returns>
protected virtual bool OnIsServerAuthoritative()
@@ -3772,7 +3779,6 @@ namespace Unity.Netcode.Components
return OnIsServerAuthoritative();
}
}
#endregion
#region MESSAGE HANDLING
@@ -3964,7 +3970,7 @@ namespace Unity.Netcode.Components
{
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;
}
/// <summary>
@@ -3974,25 +3980,25 @@ namespace Unity.Netcode.Components
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 @@ namespace Unity.Netcode.Components
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<float> m_TicksAgoSamples = new List<float>();
@@ -4032,16 +4038,16 @@ namespace Unity.Netcode.Components
//// 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;

View File

@@ -27,7 +27,7 @@ namespace Unity.Netcode.Components
}
/// <summary>
/// Default implementation required to register a <see cref="Rigidbody"/> with a <see cref="RigidbodyContactEventManager"/> instance.
/// Default implementation required to register a <see cref="Rigidbody"/> with a <see cref="RigidbodyContactEventManager"/> instance.
/// </summary>
/// <remarks>
/// Recommended to implement this method on a <see cref="NetworkBehaviour"/> component
@@ -52,7 +52,7 @@ namespace Unity.Netcode.Components
}
/// <summary>
/// This is an extended version of <see cref="IContactEventHandler"/> and can be used to register a <see cref="Rigidbody"/> with a <see cref="RigidbodyContactEventManager"/> instance. <br />
/// This is an extended version of <see cref="IContactEventHandler"/> and can be used to register a <see cref="Rigidbody"/> with a <see cref="RigidbodyContactEventManager"/> instance.<br />
/// This provides additional <see cref="ContactEventHandlerInfo"/> information to the <see cref="RigidbodyContactEventManager"/> for each set of contact events it is processing.
/// </summary>
public interface IContactEventHandlerWithInfo : IContactEventHandler
@@ -66,9 +66,9 @@ namespace Unity.Netcode.Components
/// <summary>
/// Add this component to an in-scene placed GameObject to provide faster collision event processing between <see cref="Rigidbody"/> instances and optionally static colliders.
/// <see cref="IContactEventHandler"/> <br />
/// <see cref="IContactEventHandlerWithInfo"/> <br />
/// <see cref="ContactEventHandlerInfo"/> <br />
/// <see cref="IContactEventHandler"/><br />
/// <see cref="IContactEventHandlerWithInfo"/><br />
/// <see cref="ContactEventHandlerInfo"/><br />
/// </summary>
[AddComponentMenu("Netcode/Rigidbody Contact Event Manager")]
public class RigidbodyContactEventManager : MonoBehaviour

View File

@@ -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;
/// <summary>
/// The protocol version. Different versions doesn't talk to each other.
/// </summary>
@@ -132,6 +140,8 @@ namespace Unity.Netcode
/// 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.
/// </summary>
[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;
/// <summary>
@@ -176,6 +186,21 @@ namespace Unity.Netcode
[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;
/// <summary>
/// Invoked by <see cref="NetworkManager"/> when it is validated.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
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);
}
/// <summary>
/// Returns a base64 encoded version of the configuration
/// </summary>

View File

@@ -0,0 +1,58 @@
namespace Unity.Netcode
{
internal class SessionConfig
{
/// <summary>
/// The running list of session versions
/// </summary>
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;
/// <summary>
/// Service to client
/// Set when the client receives a <see cref="ConnectionApprovedMessage"/>
/// </summary>
/// <param name="serviceConfig">the session's settings</param>
public SessionConfig(ServiceConfig serviceConfig)
{
SessionVersion = serviceConfig.SessionVersion;
ServiceSideDistribution = serviceConfig.ServerRedistribution;
}
/// <summary>
/// Can be used to directly set the version.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="version">version to set</param>
public SessionConfig(uint version)
{
SessionVersion = version;
ServiceSideDistribution = false;
}
/// <summary>
/// Client to Service
/// Default package constructor set when <see cref="NetworkManager.Initialize(bool)"/> is invoked.
/// </summary>
public SessionConfig()
{
// The current
SessionVersion = PackageSessionVersion;
ServiceSideDistribution = false;
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e0512e5a3e1dc484bbbf98c03a574645

View File

@@ -10,15 +10,54 @@ using UnityEngine;
namespace Unity.Netcode
{
/// <summary>
/// The connection event type set within <see cref="ConnectionEventData"/> to signify the type of connection event notification received.
/// </summary>
/// <remarks>
/// <see cref="ConnectionEventData"/> is returned as a parameter of the <see cref="NetworkManager.OnConnectionEvent"/> event notification.
/// <see cref="ClientConnected"/> and <see cref="ClientDisconnected"/> event types occur on the client-side of the newly connected client and on the server-side. <br />
/// <see cref="PeerConnected"/> and <see cref="PeerDisconnected"/> event types occur on connected clients to notify that a new client (peer) has joined/connected.
/// </remarks>
public enum ConnectionEvent
{
/// <summary>
/// This event is set on the client-side of the newly connected client and on the server-side.<br />
/// </summary>
/// <remarks>
/// On the newly connected client side, the <see cref="ConnectionEventData.ClientId"/> will be the <see cref="NetworkManager.LocalClientId"/>.<br />
/// On the server side, the <see cref="ConnectionEventData.ClientId"/> will be the ID of the client that just connected.
/// </remarks>
ClientConnected,
/// <summary>
/// This event is set on clients that are already connected to the session.
/// </summary>
/// <remarks>
/// The <see cref="ConnectionEventData.ClientId"/> will be the ID of the client that just connected.
/// </remarks>
PeerConnected,
/// <summary>
/// This event is set on the client-side of the client that disconnected client and on the server-side.
/// </summary>
/// <remarks>
/// On the disconnected client side, the <see cref="ConnectionEventData.ClientId"/> will be the <see cref="NetworkManager.LocalClientId"/>.<br />
/// On the server side, this will be the ID of the client that disconnected.
/// </remarks>
ClientDisconnected,
/// <summary>
/// This event is set on clients that are already connected to the session.
/// </summary>
/// <remarks>
/// The <see cref="ConnectionEventData.ClientId"/> will be the ID of the client that just disconnected.
/// </remarks>
PeerDisconnected
}
/// <summary>
/// Returned as a parameter of the <see cref="NetworkManager.OnConnectionEvent"/> event notification.
/// </summary>
/// <remarks>
/// See <see cref="ConnectionEvent"/> for more details on the types of connection events received.
/// </remarks>
public struct ConnectionEventData
{
public ConnectionEvent EventType;
@@ -563,7 +602,7 @@ namespace Unity.Netcode
{
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 @@ namespace Unity.Netcode
MessageVersions = new NativeArray<MessageVersionData>(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 @@ namespace Unity.Netcode
}
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 @@ namespace Unity.Netcode
{
// 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 @@ namespace Unity.Netcode
childObject.SetOwnershipLock(false);
}
// Ignore session owner marked objects
if (childObject.IsOwnershipSessionOwner)
{
continue;
}
NetworkManager.SpawnManager.ChangeOwnership(childObject, targetOwner, true);
if (EnableDistributeLogging)
{

View File

@@ -826,7 +826,7 @@ namespace Unity.Netcode
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 @@ namespace Unity.Netcode
{
// 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 @@ namespace Unity.Netcode
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 @@ namespace Unity.Netcode
{
// 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 @@ namespace Unity.Netcode
// 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 @@ namespace Unity.Netcode
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))
{

View File

@@ -141,6 +141,9 @@ namespace Unity.Netcode
// 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();
}
}
}

View File

@@ -80,6 +80,18 @@ namespace Unity.Netcode
}
#endif
internal SessionConfig SessionConfig;
/// <summary>
/// Used for internal testing purposes
/// </summary>
internal delegate SessionConfig OnGetSessionConfigHandler();
internal OnGetSessionConfigHandler OnGetSessionConfig;
private SessionConfig GetSessionConfig()
{
return OnGetSessionConfig != null ? OnGetSessionConfig.Invoke() : new SessionConfig();
}
internal static bool IsDistributedAuthority;
/// <summary>
@@ -162,10 +174,30 @@ namespace Unity.Netcode
}
}
// 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<ulong> ClientsToRedistribute = new List<ulong>();
internal bool RedistributeToClients;
/// <summary>
/// Handles object redistribution when scene management is disabled.
/// <see cref="NetworkBehaviourUpdater.NetworkBehaviourUpdater_Tick"/>
/// DANGO-TODO: Determine if this needs to be removed once the service handles object distribution
/// </summary>
internal void HandleRedistributionToClients()
{
if (!DistributedAuthorityMode || !RedistributeToClients || NetworkConfig.EnableSceneManagement || ShutdownInProgress)
{
return;
}
foreach (var clientId in ClientsToRedistribute)
{
SpawnManager.DistributeNetworkObjects(clientId);
}
RedistributeToClients = false;
ClientsToRedistribute.Clear();
}
internal List<NetworkObject> DeferredDespawnObjects = new List<NetworkObject>();
@@ -193,11 +225,7 @@ namespace Unity.Netcode
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 @@ namespace Unity.Netcode
case NetworkUpdateStage.EarlyUpdate:
{
UpdateTopology();
// Handle processing any new connections or transport events
NetworkConfig.NetworkTransport.EarlyUpdate();
ConnectionManager.ProcessPendingApprovals();
ConnectionManager.PollAndHandleNetworkEvents();
@@ -298,6 +330,7 @@ namespace Unity.Netcode
AnticipationSystem.SetupForUpdate();
MessageManager.ProcessIncomingMessageQueue();
MessageManager.CleanupDisconnectedClients();
AnticipationSystem.ProcessReanticipation();
}
@@ -379,22 +412,15 @@ namespace Unity.Netcode
// 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 @@ namespace Unity.Netcode
return; // May occur when the component is added
}
// Do a validation pass on NetworkConfig properties
NetworkConfig.OnValidate();
if (GetComponentInChildren<NetworkObject>() != null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
@@ -993,8 +1022,7 @@ namespace Unity.Netcode
{
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 @@ namespace Unity.Netcode
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)
{

View File

@@ -102,10 +102,22 @@ namespace Unity.Netcode
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 @@ namespace Unity.Netcode
NetworkObjectRefreshTool.ProcessScenes();
}
/// <summary>
/// Register for <see cref="PrefabStage"/> opened and closing event notifications.
/// </summary>
[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);
}
/// <summary>
/// Determines if we have opened a network prefab in edit mode (InContext or InIsolation)
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="prefabStage"></param>
private static void CheckPrefabStage(PrefabStage prefabStage)
{
s_PrefabStage = prefabStage;
s_PrefabInstance = prefabStage.prefabContentsRoot?.GetComponent<NetworkObject>();
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<NetworkObject>();
}
catch
{
s_PrefabAsset = null;
}
}
else
{
// When editing in InIsolation mode, load the original prefab asset from the provided path.
s_PrefabAsset = AssetDatabase.LoadAssetAtPath<NetworkObject>(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;
}
}
/// <summary>
/// GlobalObjectIdHash values are generated during validation.
/// </summary>
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 @@ namespace Unity.Netcode
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;
}
/// <summary>
@@ -210,13 +303,12 @@ namespace Unity.Netcode
/// <remarks>
/// 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.)
/// </remarks>
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 @@ namespace Unity.Netcode
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<NetworkObject>(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
/// <summary>
@@ -396,6 +439,13 @@ namespace Unity.Netcode
/// </remarks>
public bool IsOwnershipDistributable => Ownership.HasFlag(OwnershipStatus.Distributable);
/// <summary>
/// When true, the <see cref="NetworkObject"/> can only be owned by the current Session Owner.
/// To set <see cref="OwnershipStatus.SessionOwner"/> during runtime, use <see cref="ChangeOwnership(ulong)"/> to ensure the session owner owns the object.
/// Once the session owner owns the object, then use <see cref="SetOwnershipStatus(OwnershipStatus, bool, OwnershipLockActions)"/>.
/// </summary>
public bool IsOwnershipSessionOwner => Ownership.HasFlag(OwnershipStatus.SessionOwner);
/// <summary>
/// Returns true if the <see cref="NetworkObject"/> is has ownership locked.
/// When locked, the <see cref="NetworkObject"/> cannot be redistributed nor can it be transferred by another client.
@@ -438,7 +488,8 @@ namespace Unity.Netcode
/// <see cref="None"/>: If nothing is set, then ownership is considered "static" and cannot be redistributed, requested, or transferred (i.e. a Player would have this).
/// <see cref="Distributable"/>: When set, this instance will be automatically redistributed when a client joins (if not locked or no request is pending) or leaves.
/// <see cref="Transferable"/>: When set, a non-owner can obtain ownership immediately (without requesting and as long as it is not locked).
/// <see cref="RequestRequired"/>: When set, When set, a non-owner must request ownership from the owner (will always get locked once ownership is transferred).
/// <see cref="RequestRequired"/>: When set, a non-owner must request ownership from the owner (will always get locked once ownership is transferred).
/// <see cref="SessionOwner"/>: When set, only the current session owner may have ownership over this object.
/// </summary>
// Ranges from 1 to 8 bits
[Flags]
@@ -448,6 +499,7 @@ namespace Unity.Netcode
Distributable = 1 << 0,
Transferable = 1 << 1,
RequestRequired = 1 << 2,
SessionOwner = 1 << 3,
}
/// <summary>
@@ -506,7 +558,7 @@ namespace Unity.Netcode
}
// 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 @@ namespace Unity.Netcode
/// <see cref="RequestRequired"/>: The <see cref="NetworkObject"/> requires an ownership request via <see cref="RequestOwnership"/>.
/// <see cref="RequestInProgress"/>: The <see cref="NetworkObject"/> is already processing an ownership request and ownership cannot be acquired at this time.
/// <see cref="NotTransferrable"/>: The <see cref="NetworkObject"/> does not have the <see cref="OwnershipStatus.Transferable"/> flag set and ownership cannot be acquired.
/// <see cref="SessionOwnerOnly"/>: The <see cref="NetworkObject"/> has the <see cref="OwnershipStatus.SessionOwner"/> flag set and ownership cannot be acquired.
/// </summary>
public enum OwnershipPermissionsFailureStatus
{
Locked,
RequestRequired,
RequestInProgress,
NotTransferrable
NotTransferrable,
SessionOwnerOnly
}
/// <summary>
@@ -567,6 +621,7 @@ namespace Unity.Netcode
/// <see cref="RequestRequiredNotSet"/>: The <see cref="OwnershipStatus.RequestRequired"/> flag is not set on this <see cref="NetworkObject"/>
/// <see cref="Locked"/>: The current owner has locked ownership which means requests are not available at this time.
/// <see cref="RequestInProgress"/>: There is already a known request in progress. You can scan for ownership changes and try upon
/// <see cref="SessionOwnerOnly"/>: 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.
/// </summary>
public enum OwnershipRequestStatus
@@ -576,6 +631,7 @@ namespace Unity.Netcode
RequestRequiredNotSet,
Locked,
RequestInProgress,
SessionOwnerOnly,
}
/// <summary>
@@ -588,6 +644,7 @@ namespace Unity.Netcode
/// <see cref="OwnershipRequestStatus.RequestRequiredNotSet"/>: The <see cref="OwnershipStatus.RequestRequired"/> flag is not set on this <see cref="NetworkObject"/>
/// <see cref="OwnershipRequestStatus.Locked"/>: The current owner has locked ownership which means requests are not available at this time.
/// <see cref="OwnershipRequestStatus.RequestInProgress"/>: There is already a known request in progress. You can scan for ownership changes and try upon
/// <see cref="OwnershipRequestStatus.SessionOwnerOnly"/>: 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.
/// </remarks>
/// <returns><see cref="OwnershipRequestStatus"/></returns>
@@ -617,6 +674,12 @@ namespace Unity.Netcode
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 @@ namespace Unity.Netcode
{
response = OwnershipRequestResponseStatus.RequestInProgress;
}
else if (!IsOwnershipRequestRequired && !IsOwnershipTransferable)
else if (!(IsOwnershipRequestRequired || IsOwnershipTransferable) || IsOwnershipSessionOwner)
{
response = OwnershipRequestResponseStatus.CannotRequest;
}
@@ -793,6 +856,12 @@ namespace Unity.Netcode
/// </remarks>
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 @@ namespace Unity.Netcode
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))
{
SetOwnershipLock(lockAction == OwnershipLockActions.SetAndLock);
Ownership = OwnershipStatus.SessionOwner;
}
else if (Ownership.HasFlag(OwnershipStatus.SessionOwner))
{
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 @@ namespace Unity.Netcode
// 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 @@ namespace Unity.Netcode
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 @@ namespace Unity.Netcode
SyncObservers = syncObservers,
Observers = syncObservers ? Observers.ToArray() : null,
NetworkSceneHandle = NetworkSceneHandle,
Hash = HostCheckForGlobalObjectIdHashOverride(),
Hash = CheckForGlobalObjectIdHashOverride(),
OwnerObject = this,
TargetClientId = targetClientId
};
@@ -3244,14 +3327,15 @@ namespace Unity.Netcode
}
/// <summary>
/// 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.
/// </summary>
/// <returns></returns>
internal uint HostCheckForGlobalObjectIdHashOverride()
/// <returns>appropriate hash value</returns>
internal uint CheckForGlobalObjectIdHashOverride()
{
if (NetworkManager.IsServer)
if (NetworkManager.IsServer || NetworkManager.DistributedAuthorityMode)
{
if (NetworkManager.PrefabHandler.ContainsHandler(this))
{

View File

@@ -11,7 +11,7 @@ using UnityEngine.SceneManagement;
namespace Unity.Netcode
{
/// <summary>
/// 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.
/// </summary>

View File

@@ -16,7 +16,7 @@ namespace Unity.Netcode
/// <summary>
/// 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.
/// </summary>
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

View File

@@ -17,7 +17,7 @@ namespace Unity.Netcode
/// <summary>
/// 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
/// </summary>
internal ulong RequestClientId;
internal int ClientIdCount;
@@ -272,7 +272,7 @@ namespace Unity.Netcode
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 @@ namespace Unity.Netcode
}
/// <summary>
/// Handle the
/// Handle the extended distributed authority ownership updates
/// </summary>
/// <param name="context"></param>
private void HandleExtendedOwnershipUpdate(ref NetworkContext context)
@@ -332,8 +332,8 @@ namespace Unity.Netcode
// 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 @@ namespace Unity.Netcode
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();

View File

@@ -55,19 +55,24 @@ namespace Unity.Netcode
// 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
/// <see cref="NetworkBehaviourUpdater.NetworkBehaviourUpdater_Tick"/>
/// DANGO-TODO: Determine if this needs to be removed once the service handles object distribution
networkManager.RedistributeToClients = true;
networkManager.ClientsToRedistribute.Add(ClientId);
}
}
}

View File

@@ -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<T>(BufferSerializer<T> 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 @@ namespace Unity.Netcode
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);
}
}

View File

@@ -7,31 +7,28 @@ namespace Unity.Netcode
/// </summary>
internal struct ClientConfig : INetworkSerializable
{
/// <summary>
/// We start at version 1, where anything less than version 1 on the service side
/// is not bypass feature compatible.
/// </summary>
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<T>(BufferSerializer<T> 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 @@ namespace Unity.Netcode
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 @@ namespace Unity.Netcode
public int Version => k_SendClientConfigToService;
public ulong ConfigHash;
public bool CMBServiceConnection;
public bool DistributedAuthority;
public ClientConfig ClientConfig;
public byte[] ConnectionData;
@@ -72,7 +71,7 @@ namespace Unity.Netcode
// END FORBIDDEN SEGMENT
// ============================================================
if (CMBServiceConnection)
if (DistributedAuthority)
{
writer.WriteNetworkSerializable(ClientConfig);
}
@@ -120,6 +119,11 @@ namespace Unity.Netcode
// END FORBIDDEN SEGMENT
// ============================================================
if (networkManager.DAHost)
{
reader.ReadNetworkSerializable(out ClientConfig);
}
if (networkManager.NetworkConfig.ConnectionApproval)
{
if (!reader.TryBeginRead(FastBufferWriter.GetWriteSize(ConfigHash) + FastBufferWriter.GetWriteSize<int>()))
@@ -182,6 +186,17 @@ namespace Unity.Netcode
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

View File

@@ -257,7 +257,7 @@ namespace Unity.Netcode
{
// 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.

View File

@@ -128,7 +128,7 @@ namespace Unity.Netcode
}
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;
}

View File

@@ -70,10 +70,6 @@ namespace Unity.Netcode
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);

View File

@@ -141,28 +141,6 @@ namespace Unity.Netcode
{
RegisterMessageType(type);
}
#if UNITY_EDITOR
if (EnableMessageOrderConsoleLog)
{
// DANGO-TODO: Remove this when we have some form of message type indices stability in place
// For now, just log the messages and their assigned types for reference purposes.
var networkManager = m_Owner as NetworkManager;
if (networkManager != null)
{
if (networkManager.DistributedAuthorityMode)
{
var messageListing = new StringBuilder();
messageListing.AppendLine("NGO Message Index to Type Listing:");
foreach (var message in m_MessageTypes)
{
messageListing.AppendLine($"[{message.Value}][{message.Key.Name}]");
}
Debug.Log(messageListing);
}
}
}
#endif
}
catch (Exception)
{

View File

@@ -17,7 +17,8 @@ namespace Unity.Netcode
// 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;
}

View File

@@ -4,12 +4,14 @@ namespace Unity.Netcode
{
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 @@ namespace Unity.Netcode
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 @@ namespace Unity.Netcode
{
m_ServerRpcTarget = new ServerRpcTarget(manager);
m_LocalSendRpcTarget = new LocalSendRpcTarget(manager);
m_NotAuthorityRpcTarget = new NotAuthorityRpcTarget(manager);
}
}
}

View File

@@ -51,7 +51,13 @@ namespace Unity.Netcode
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;

View File

@@ -5,9 +5,12 @@ namespace Unity.Netcode
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 @@ namespace Unity.Netcode
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 @@ namespace Unity.Netcode
{
m_LocalRpcTarget = new LocalSendRpcTarget(manager);
m_ServerRpcTarget = new ServerRpcTarget(manager);
m_AuthorityRpcTarget = new AuthorityRpcTarget(manager);
}
}
}

View File

@@ -79,9 +79,28 @@ namespace Unity.Netcode
SpecifiedInParams
}
/// <summary>
/// This parameter configures a performance optimization. This optimization is not valid in all situations.<br />
/// Because BaseRpcTarget is a managed type, allocating a new one is expensive, as it puts pressure on the garbage collector.
/// </summary>
/// <remarks>
/// When using a <see cref="Temp"/> allocation type for the RPC target(s):<br />
/// You typically don't need to worry about persisting the <see cref="BaseRpcTarget"/> generated.
/// When using a <see cref="Persistent"/> allocation type for the RPC target(s): <br />
/// You will want to use <see cref="RpcTarget"/>, which returns <see cref="BaseRpcTarget"/>, during <see cref="NetworkBehaviour"/> initialization (i.e. <see cref="NetworkBehaviour.OnNetworkPostSpawn"/>) and it to a property.<br />
/// Then, When invoking the RPC, you would use your <see cref="BaseRpcTarget"/> which is a persisted allocation of a given set of client identifiers.
/// !! Important !!<br />
/// You will want to invoke <see cref="BaseRpcTarget.Dispose"/> of any persisted properties created via <see cref="RpcTarget"/> when despawning or destroying the associated <see cref="NetworkBehaviour"/> component's <see cref="NetworkObject"/>. Not doing so will result in small memory leaks.
/// </remarks>
public enum RpcTargetUse
{
/// <summary>
/// Creates a temporary <see cref="BaseRpcTarget"/> used for the frame an <see cref="RpcAttribute"/> decorated method is invoked.
/// </summary>
Temp,
/// <summary>
/// Creates a persisted <see cref="BaseRpcTarget"/> that does not change and will persist until <see cref="BaseRpcTarget.Dispose"/> is called.
/// </summary>
Persistent
}

View File

@@ -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 @@ namespace Unity.Netcode
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;
}

View File

@@ -24,7 +24,6 @@ namespace Unity.Netcode
/// The callback to be invoked when the list gets changed
/// </summary>
public event OnListChangedDelegate OnListChanged;
internal override NetworkVariableType Type => NetworkVariableType.NetworkList;
/// <summary>
/// Constructor method for <see cref="NetworkList"/>
@@ -50,6 +49,11 @@ namespace Unity.Netcode
}
}
~NetworkList()
{
Dispose();
}
/// <inheritdoc />
public override void ResetDirty()
{
@@ -131,20 +135,6 @@ namespace Unity.Netcode
/// <inheritdoc />
public override void WriteField(FastBufferWriter writer)
{
if (m_NetworkManager.DistributedAuthorityMode)
{
writer.WriteValueSafe(NetworkVariableSerialization<T>.Serializer.Type);
if (NetworkVariableSerialization<T>.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<T>.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 @@ namespace Unity.Netcode
public override void ReadField(FastBufferReader reader)
{
m_List.Clear();
if (m_NetworkManager.DistributedAuthorityMode)
{
SerializationTools.ReadType(reader, NetworkVariableSerialization<T>.Serializer);
// Collection item type is used by the DA server, drop value here.
if (NetworkVariableSerialization<T>.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 @@ namespace Unity.Netcode
/// </summary>
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();
}
}

View File

@@ -45,8 +45,6 @@ namespace Unity.Netcode
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_PreviousValue);
}
internal override NetworkVariableType Type => NetworkVariableType.Value;
/// <summary>
/// Constructor for <see cref="NetworkVariable{T}"/>
/// </summary>
@@ -92,7 +90,7 @@ namespace Unity.Netcode
// 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 @@ namespace Unity.Netcode
}
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 @@ namespace Unity.Netcode
/// 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 <see cref="NetworkVariableDeltaMessage.Handle(ref NetworkContext)"/> method.
/// </summary>
internal override void PostDeltaRead()

View File

@@ -35,8 +35,6 @@ namespace Unity.Netcode
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 @@ namespace Unity.Netcode
/// 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 <see cref="NetworkVariableDeltaMessage.Handle(ref NetworkContext)"/> method.
/// </summary>
internal virtual void PostDeltaRead()

View File

@@ -1,40 +0,0 @@
#if UNITY_EDITOR
#endif
namespace Unity.Netcode
{
/// <summary>
/// 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.
/// </summary>
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/// Add any new Variable types to this table at the END with incremented index value
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
internal enum NetworkVariableType : byte
{
/// <summary>
/// Value
/// Used for all of the basic NetworkVariables that contain a single value
/// </summary>
Value = 0,
/// <summary>
/// For any type that is not known at runtime
/// </summary>
Unknown = 1,
/// <summary>
/// NetworkList
/// </summary>
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,
}
}

View File

@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: df4a4005f1c842669f94a404019400ed
timeCreated: 1718292058

View File

@@ -14,9 +14,6 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class FallbackSerializer<T> : INetworkVariableSerializer<T>
{
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<T>)}. 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<T>)}.{nameof(UserNetworkVariableSerialization<T>.WriteValue)}, {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.ReadValue)}, and {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.DuplicateValue)}, or if it's serializable by memcpy (contains no pointers), wrap it in {typeof(ForceNetworkSerializeByMemcpy<>).Name}.");
@@ -82,11 +79,6 @@ namespace Unity.Netcode
}
UserNetworkVariableSerialization<T>.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`

View File

@@ -2,28 +2,8 @@ using Unity.Collections;
namespace Unity.Netcode
{
/// <summary>
/// Interface used by NetworkVariables to serialize them with additional information for the DA runtime
/// </summary>
///
/// <typeparam name="T"></typeparam>
internal interface IDistributedAuthoritySerializer<T>
{
/// <summary>
/// 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
/// </summary>
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);
}
/// <typeparam name="T"></typeparam>
internal interface INetworkVariableSerializer<T> : IDistributedAuthoritySerializer<T>
internal interface INetworkVariableSerializer<T>
{
// Write has to be taken by ref here because of INetworkSerializable
// Open Instance Delegates (pointers to methods without an instance attached to them)

View File

@@ -14,8 +14,6 @@ namespace Unity.Netcode
{
internal static INetworkVariableSerializer<T> Serializer = new FallbackSerializer<T>();
internal static bool IsDistributedAuthority => NetworkManager.IsDistributedAuthority;
/// <summary>
/// A callback to check if two values are equal.
/// </summary>
@@ -53,20 +51,7 @@ namespace Unity.Netcode
/// <param name="value"></param>
public static void Write(FastBufferWriter writer, ref T value)
{
if (IsDistributedAuthority)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (!NetworkManager.DisableNotOptimizedSerializedType && !Serializer.IsDistributedAuthorityOptimized)
{
NetworkManager.LogSerializedTypeNotOptimized<T>();
}
#endif
Serializer.WriteDistributedAuthority(writer, ref value);
}
else
{
Serializer.Write(writer, ref value);
}
Serializer.Write(writer, ref value);
}
/// <summary>
@@ -91,14 +76,7 @@ namespace Unity.Netcode
/// <param name="value"></param>
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);
}
/// <summary>
@@ -120,20 +98,7 @@ namespace Unity.Netcode
/// <param name="value"></param>
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<T>();
}
#endif
Serializer.WriteDeltaDistributedAuthority(writer, ref value, ref previousValue);
}
else
{
Serializer.WriteDelta(writer, ref value, ref previousValue);
}
Serializer.WriteDelta(writer, ref value, ref previousValue);
}
/// <summary>
@@ -158,14 +123,7 @@ namespace Unity.Netcode
/// <param name="value"></param>
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);
}
/// <summary>

View File

@@ -10,21 +10,6 @@ namespace Unity.Netcode
/// </summary>
internal class ShortSerializer : INetworkVariableSerializer<short>
{
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 @@ namespace Unity.Netcode
/// </summary>
internal class UshortSerializer : INetworkVariableSerializer<ushort>
{
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 @@ namespace Unity.Netcode
/// </summary>
internal class IntSerializer : INetworkVariableSerializer<int>
{
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 @@ namespace Unity.Netcode
/// </summary>
internal class UintSerializer : INetworkVariableSerializer<uint>
{
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 @@ namespace Unity.Netcode
/// </summary>
internal class LongSerializer : INetworkVariableSerializer<long>
{
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 @@ namespace Unity.Netcode
/// </summary>
internal class UlongSerializer : INetworkVariableSerializer<ulong>
{
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 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class UnmanagedTypeSerializer<T> : INetworkVariableSerializer<T> 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 @@ namespace Unity.Netcode
internal class ListSerializer<T> : INetworkVariableSerializer<List<T>>
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref List<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref List<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref List<T> value, ref List<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref List<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref List<T> value)
{
var isNull = value == null;
@@ -468,20 +353,6 @@ namespace Unity.Netcode
internal class HashSetSerializer<T> : INetworkVariableSerializer<HashSet<T>> where T : IEquatable<T>
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref HashSet<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref HashSet<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref HashSet<T> value, ref HashSet<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref HashSet<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref HashSet<T> value)
{
var isNull = value == null;
@@ -563,20 +434,6 @@ namespace Unity.Netcode
internal class DictionarySerializer<TKey, TVal> : INetworkVariableSerializer<Dictionary<TKey, TVal>>
where TKey : IEquatable<TKey>
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref Dictionary<TKey, TVal> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref Dictionary<TKey, TVal> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref Dictionary<TKey, TVal> value, ref Dictionary<TKey, TVal> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref Dictionary<TKey, TVal> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref Dictionary<TKey, TVal> value)
{
var isNull = value == null;
@@ -659,20 +516,6 @@ namespace Unity.Netcode
internal class UnmanagedArraySerializer<T> : INetworkVariableSerializer<NativeArray<T>> where T : unmanaged
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value, ref NativeArray<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeArray<T> value)
{
writer.WriteUnmanagedSafe(value);
@@ -718,20 +561,6 @@ namespace Unity.Netcode
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
internal class UnmanagedListSerializer<T> : INetworkVariableSerializer<NativeList<T>> where T : unmanaged
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeList<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value, ref NativeList<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeList<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeList<T> value)
{
writer.WriteUnmanagedSafe(value);
@@ -775,21 +604,6 @@ namespace Unity.Netcode
internal class NativeHashSetSerializer<T> : INetworkVariableSerializer<NativeHashSet<T>> where T : unmanaged, IEquatable<T>
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeHashSet<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeHashSet<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeHashSet<T> value, ref NativeHashSet<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeHashSet<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeHashSet<T> value)
{
writer.WriteValueSafe(value);
@@ -835,21 +649,6 @@ namespace Unity.Netcode
where TKey : unmanaged, IEquatable<TKey>
where TVal : unmanaged
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeHashMap<TKey, TVal> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeHashMap<TKey, TVal> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeHashMap<TKey, TVal> value, ref NativeHashMap<TKey, TVal> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeHashMap<TKey, TVal> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeHashMap<TKey, TVal> value)
{
writer.WriteValueSafe(value);
@@ -897,21 +696,6 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class FixedStringSerializer<T> : INetworkVariableSerializer<T> where T : unmanaged, INativeList<byte>, 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 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class FixedStringArraySerializer<T> : INetworkVariableSerializer<NativeArray<T>> where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value, ref NativeArray<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeArray<T> value)
{
writer.WriteValueSafe(value);
@@ -1083,21 +853,6 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class FixedStringListSerializer<T> : INetworkVariableSerializer<NativeList<T>> where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeList<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value, ref NativeList<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeList<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeList<T> value)
{
writer.WriteValueSafe(value);
@@ -1145,21 +900,6 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class UnmanagedNetworkSerializableSerializer<T> : INetworkVariableSerializer<T> 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<BufferSerializerWriter>(new BufferSerializerWriter(writer));
@@ -1212,20 +952,6 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class UnmanagedNetworkSerializableArraySerializer<T> : INetworkVariableSerializer<NativeArray<T>> where T : unmanaged, INetworkSerializable
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value, ref NativeArray<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeArray<T> value)
{
writer.WriteNetworkSerializable(value);
@@ -1276,21 +1002,6 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class UnmanagedNetworkSerializableListSerializer<T> : INetworkVariableSerializer<NativeList<T>> where T : unmanaged, INetworkSerializable
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeList<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value, ref NativeList<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeList<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeList<T> value)
{
writer.WriteNetworkSerializable(value);
@@ -1338,20 +1049,6 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class ManagedNetworkSerializableSerializer<T> : INetworkVariableSerializer<T> 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<BufferSerializerWriter>(new BufferSerializerWriter(writer));

View File

@@ -1,54 +0,0 @@
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
namespace Unity.Netcode
{
internal static class SerializationTools
{
public delegate void WriteDelegate<T>(FastBufferWriter writer, ref T value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteWithSize<T>(WriteDelegate<T> 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<T>(FastBufferReader writer, ref T value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ReadWithSize<T>(ReadDelegate<T> 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<T>(FastBufferReader reader, INetworkVariableSerializer<T> serializer)
{
reader.ReadValueSafe(out NetworkVariableType type);
if (type != serializer.Type)
{
throw new SerializationException();
}
}
}
}

View File

@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: 52a4ce368df54b0a8887c08f3402bcd3
timeCreated: 1718300602

View File

@@ -1081,14 +1081,19 @@ namespace Unity.Netcode
}
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);
}
}
}
/// <summary>
@@ -1898,10 +1903,12 @@ namespace Unity.Netcode
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,

View File

@@ -62,7 +62,7 @@ namespace Unity.Netcode
/// 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

View File

@@ -88,6 +88,13 @@ namespace Unity.Netcode
}
}
// 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 @@ namespace Unity.Netcode
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 @@ namespace Unity.Netcode
/// <summary>
/// Removes a player object and updates all other players' observers list
/// </summary>
private void RemovePlayerObject(NetworkObject playerObject, bool keepObservers = false)
private void RemovePlayerObject(NetworkObject playerObject, bool destroyingObject = false)
{
if (!playerObject.IsPlayerObject)
{
@@ -141,16 +149,21 @@ namespace Unity.Netcode
}
}
// 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 @@ namespace Unity.Netcode
{
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 @@ namespace Unity.Netcode
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 @@ namespace Unity.Netcode
{
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 @@ namespace Unity.Netcode
internal NetworkObject InstantiateAndSpawnNoParameterChecks(NetworkObject networkPrefab, ulong ownerClientId = NetworkManager.ServerClientId, bool destroyWithScene = false, bool isPlayerObject = false, bool forceOverride = false, Vector3 position = default, Quaternion rotation = default)
{
var networkObject = networkPrefab;
// Host spawns the ovveride and server spawns the original prefab unless forceOverride is set to true where both server or host will spawn the override.
// 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 @@ namespace Unity.Netcode
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;
}
/// <summary>
/// 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.
/// </summary>
internal NetworkObject GetNetworkObjectToSpawn(uint globalObjectIdHash, ulong ownerId, Vector3? position, Quaternion? rotation, bool isScenePlaced = false)
@@ -775,8 +796,8 @@ namespace Unity.Netcode
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 @@ namespace Unity.Netcode
else
{
// Create prefab instance while applying any pre-assigned position and rotation values
networkObject = UnityEngine.Object.Instantiate(networkPrefabReference).GetComponent<NetworkObject>();
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;
}
/// <summary>
/// Instantiates a network prefab instance, assigns the base prefab <see cref="NetworkObject.GlobalObjectIdHash"/>, positions, and orients
/// the instance.
/// !!! Should only be invoked by <see cref="GetNetworkObjectToSpawn"/> unless used by an integration test !!!
/// </summary>
/// <remarks>
/// <param name="prefabGlobalObjectIdHash"> should be the base prefab <see cref="NetworkObject.GlobalObjectIdHash"/> value and not the
/// overrided value.
/// (Can be used for integration testing)
/// </remarks>
/// <param name="networkPrefab">prefab to instantiate</param>
/// <param name="prefabGlobalObjectIdHash"><see cref="NetworkObject.GlobalObjectIdHash"/> of the base prefab instance</param>
/// <param name="position">conditional position in place of the network prefab's default position</param>
/// <param name="rotation">conditional rotation in place of the network prefab's default rotation</param>
/// <returns>the instance of the <see cref="NetworkObject"/></returns>
internal NetworkObject InstantiateNetworkPrefab(GameObject networkPrefab, uint prefabGlobalObjectIdHash, Vector3? position, Quaternion? rotation)
{
var networkObject = UnityEngine.Object.Instantiate(networkPrefab).GetComponent<NetworkObject>();
networkObject.transform.position = position ?? networkObject.transform.position;
networkObject.transform.rotation = rotation ?? networkObject.transform.rotation;
networkObject.NetworkManagerOwner = NetworkManager;
networkObject.PrefabGlobalObjectIdHash = prefabGlobalObjectIdHash;
return networkObject;
}
/// <summary>
/// Creates a local NetowrkObject to be spawned.
/// </summary>
@@ -949,7 +991,7 @@ namespace Unity.Netcode
/// - 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 @@ namespace Unity.Netcode
// 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 @@ namespace Unity.Netcode
}
}
// 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 @@ namespace Unity.Netcode
}
}
// 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 @@ namespace Unity.Netcode
SpawnedObjectsList.Remove(networkObject);
}
// DANGO-TODO: When we fix the issue with observers not being applied to NetworkObjects,
// (client connect/disconnect) we can remove this hacky way of doing this.
// Basically, when a player disconnects and/or is destroyed they are removed as an observer from all other client
// NetworkOject instances.
if (networkObject.IsPlayerObject && !networkObject.IsOwner && networkObject.OwnerClientId != NetworkManager.LocalClientId)
{
foreach (var netObject in SpawnedObjects)
{
if (netObject.Value.Observers.Contains(networkObject.OwnerClientId))
{
netObject.Value.Observers.Remove(networkObject.OwnerClientId);
}
}
}
if (networkObject.IsPlayerObject)
{
RemovePlayerObject(networkObject);
RemovePlayerObject(networkObject, destroyGameObject);
}
// Always clear out the observers list when despawned
@@ -1705,6 +1748,11 @@ namespace Unity.Netcode
foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList)
{
if (networkObject.IsOwnershipSessionOwner)
{
continue;
}
if (networkObject.IsOwnershipDistributable && !networkObject.IsOwnershipLocked)
{
if (networkObject.transform.parent != null)
@@ -1715,17 +1763,15 @@ namespace Unity.Netcode
continue;
}
}
// We have to check if it is an in-scene placed NetworkObject and if it is get the source prefab asset GlobalObjectIdHash value of the in-scene placed instance
// since all in-scene placed instances use unique GlobalObjectIdHash values.
var globalOjectIdHash = networkObject.IsSceneObject.HasValue && networkObject.IsSceneObject.Value ? networkObject.InScenePlacedSourceGlobalObjectIdHash : networkObject.GlobalObjectIdHash;
if (networkObject.IsSceneObject.Value)
if (!objectTypeCount.ContainsKey(globalOjectIdHash))
{
continue;
objectTypeCount.Add(globalOjectIdHash, 0);
}
if (!objectTypeCount.ContainsKey(networkObject.GlobalObjectIdHash))
{
objectTypeCount.Add(networkObject.GlobalObjectIdHash, 0);
}
objectTypeCount[networkObject.GlobalObjectIdHash] += 1;
objectTypeCount[globalOjectIdHash] += 1;
// DANGO-TODO-MVP: Remove this once the service handles object distribution
if (onlyIncludeOwnedObjects && !networkObject.IsOwner)
@@ -1733,133 +1779,141 @@ namespace Unity.Netcode
continue;
}
// Divide up by prefab type (GlobalObjectIdHash) to get a better distribution of object types
if (!objectByTypeAndOwner.ContainsKey(networkObject.GlobalObjectIdHash))
if (!objectByTypeAndOwner.ContainsKey(globalOjectIdHash))
{
objectByTypeAndOwner.Add(networkObject.GlobalObjectIdHash, new Dictionary<ulong, List<NetworkObject>>());
objectByTypeAndOwner.Add(globalOjectIdHash, new Dictionary<ulong, List<NetworkObject>>());
}
// 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<NetworkObject>());
objectByTypeAndOwner[globalOjectIdHash].Add(networkObject.OwnerClientId, new List<NetworkObject>());
}
// 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))
if (!NetworkManager.DistributedAuthorityMode)
{
// 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<uint, Dictionary<ulong, List<NetworkObject>>>();
return;
}
// 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<uint, int>();
if (NetworkManager.SessionConfig.ServiceSideDistribution)
{
return;
}
// 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;
// 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<uint, Dictionary<ulong, List<NetworkObject>>>();
// Cycle through each prefab type
foreach (var objectTypeEntry in distributedNetworkObjects)
// 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<uint, int>();
// 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)
// If the object per client count is zero, then move to the next type.
if (objPerClient <= 0)
{
continue;
}
// Evenly distribute this object type amongst the clients
foreach (var ownerList in objectTypeEntry.Value)
{
if (ownerList.Value.Count <= 1)
{
continue;
}
// Evenly distribute this object type amongst the clients
foreach (var ownerList in objectTypeEntry.Value)
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)
{
if (ownerList.Value.Count <= 1)
{
continue;
}
Debug.Log($"[{objPerClient} of {totalObjectsToDistribute}][Client-{ownerList.Key}] Count: {ownerList.Value.Count} | ObjPerClient: {objPerClient} | maxD: {maxDistributeCount} | Offset: {offsetCount}");
}
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)
for (int i = 0; i < ownerList.Value.Count; i++)
{
if ((i % offsetCount) == 0)
{
Debug.Log($"[{objPerClient} of {totalObjectsToDistribute}][Client-{ownerList.Key}] Count: {ownerList.Value.Count} | ObjPerClient: {objPerClient} | maxD: {maxDistributeCount} | Offset: {offsetCount}");
}
for (int i = 0; i < ownerList.Value.Count; i++)
{
if ((i % offsetCount) == 0)
ChangeOwnership(ownerList.Value[i], clientId, true);
//if (EnableDistributeLogging)
{
ChangeOwnership(ownerList.Value[i], clientId, true);
if (EnableDistributeLogging)
{
Debug.Log($"[Client-{ownerList.Key}][NetworkObjectId-{ownerList.Value[i].NetworkObjectId} Distributed to Client-{clientId}");
}
distributed++;
}
if (distributed == maxDistributeCount)
{
break;
Debug.Log($"[Client-{ownerList.Key}][NetworkObjectId-{ownerList.Value[i].NetworkObjectId} Distributed to Client-{clientId}");
}
distributed++;
}
if (distributed == maxDistributeCount)
{
break;
}
}
}
// If EnableDistributeLogging is enabled, log the object type distribution counts per client
if (EnableDistributeLogging)
{
var builder = new StringBuilder();
distributedNetworkObjects.Clear();
objectTypeCount.Clear();
GetObjectDistribution(ref distributedNetworkObjects, ref objectTypeCount);
builder.AppendLine($"Client Relative Distributed Object Count: (distribution follows)");
// Cycle through each prefab type
foreach (var objectTypeEntry in distributedNetworkObjects)
{
builder.AppendLine($"[GID: {objectTypeEntry.Key} | {objectTypeEntry.Value.First().Value.First().name}][Total Count: {objectTypeCount[objectTypeEntry.Key]}]");
builder.AppendLine($"[GID: {objectTypeEntry.Key} | {objectTypeEntry.Value.First().Value.First().name}] Distribution:");
// Evenly distribute this type amongst clients
foreach (var ownerList in objectTypeEntry.Value)
{
builder.AppendLine($"[Client-{ownerList.Key}] Count: {ownerList.Value.Count}");
}
}
Debug.Log(builder.ToString());
}
}
// If EnableDistributeLogging is enabled, log the object type distribution counts per client
if (EnableDistributeLogging)
{
var builder = new StringBuilder();
distributedNetworkObjects.Clear();
objectTypeCount.Clear();
GetObjectDistribution(ref distributedNetworkObjects, ref objectTypeCount);
builder.AppendLine($"Client Relative Distributed Object Count: (distribution follows)");
// Cycle through each prefab type
foreach (var objectTypeEntry in distributedNetworkObjects)
{
builder.AppendLine($"[GID: {objectTypeEntry.Key} | {objectTypeEntry.Value.First().Value.First().name}][Total Count: {objectTypeCount[objectTypeEntry.Key]}]");
builder.AppendLine($"[GID: {objectTypeEntry.Key} | {objectTypeEntry.Value.First().Value.First().name}] Distribution:");
// Evenly distribute this type amongst clients
foreach (var ownerList in objectTypeEntry.Value)
{
builder.AppendLine($"[Client-{ownerList.Key}] Count: {ownerList.Value.Count}");
}
}
Debug.Log(builder.ToString());
}
}
internal struct DeferredDespawnObject
@@ -1969,14 +2023,14 @@ namespace Unity.Netcode
/// synchronizing in order to "show" (spawn) anything that might be currently hidden from
/// the session owner.
/// </summary>
/// <remarks>
/// Replacement is: SynchronizeObjectsToNewlyJoinedClient
/// </remarks>
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 @@ namespace Unity.Netcode
}
}
}
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);
}
}
}
}
}

View File

@@ -107,6 +107,45 @@ namespace Unity.Netcode
/// /// <param name="networkManager">optionally pass in NetworkManager</param>
public abstract void Initialize(NetworkManager networkManager = null);
/// <summary>
/// Invoked by NetworkManager at the beginning of its EarlyUpdate.
/// For order of operations see: <see cref="NetworkManager.NetworkUpdate(NetworkUpdateStage)"/>
/// </summary>
/// Useful to handle processing any transport-layer events such as processing inbound messages or changes in connection state(s).
/// </remarks>
protected virtual void OnEarlyUpdate()
{
}
/// <summary>
/// Invoked by NetworkManager at the beginning of its EarlyUpdate
/// </summary>
internal void EarlyUpdate()
{
OnEarlyUpdate();
}
/// <summary>
/// Invoked by NetworkManager towards the end of the PostLateUpdate.
/// For order of operations see: <see cref="NetworkManager.NetworkUpdate(NetworkUpdateStage)"/>
/// </summary>
/// <remarks>
/// Useful to handle any end of frame transport tasks such as sending queued transport messages.
/// </remarks>
protected virtual void OnPostLateUpdate()
{
}
/// <summary>
/// Invoked by NetworkManager towards the end of the PostLateUpdate
/// </summary>
internal void PostLateUpdate()
{
OnPostLateUpdate();
}
protected virtual NetworkTopologyTypes OnCurrentTopology()
{
return NetworkTopologyTypes.ClientServer;

View File

@@ -405,6 +405,7 @@ namespace Unity.Netcode.Transports.UTP
#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 @@ namespace Unity.Netcode.Transports.UTP
return false;
}
private void Update()
/// <summary>
/// Handles accepting new connections and processing transport events.
/// </summary>
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 @@ namespace Unity.Netcode.Transports.UTP
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();
}
/// <summary>
/// Handles sending any queued batched messages.
/// </summary>
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 @@ namespace Unity.Netcode.Transports.UTP
}
#endif
}
base.OnPostLateUpdate();
}
private void OnDestroy()
@@ -1241,6 +1262,30 @@ namespace Unity.Netcode.Transports.UTP
return (ulong)ExtractRtt(ParseClientId(clientId));
}
/// <summary>
/// Provides the <see cref="NetworkEndpoint"/> for the NGO client identifier specified.
/// </summary>
/// <remarks>
/// - 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.
/// </remarks>
/// <param name="clientId">NGO client identifier to get endpoint information about.</param>
/// <returns><see cref="NetworkEndpoint"/></returns>
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();
}
/// <summary>
/// Initializes the transport
/// </summary>
@@ -1450,8 +1495,18 @@ namespace Unity.Netcode.Transports.UTP
/// </summary>
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 @@ namespace Unity.Netcode.Transports.UTP
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;

View File

@@ -1,4 +0,0 @@
{
"displayName": "Bootstrap",
"description": "A lightweight sample to get started"
}

View File

@@ -1,7 +1,7 @@
{
"name": "Bootstrap",
"name": "Bootstrap",
"rootNamespace": "Unity.Netcode.Samples",
"references": [
"Unity.Netcode.Runtime"
]
}
}

View File

@@ -87,6 +87,8 @@ namespace Unity.Netcode.TestHelpers.Runtime
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) { }

View File

@@ -1759,6 +1759,13 @@ namespace Unity.Netcode.TestHelpers.Runtime
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;
}
/// <summary>
/// Optional Host or Server integration tests
/// Constructor that allows you To break tests up as a host

View File

@@ -559,6 +559,29 @@ namespace Unity.Netcode.TestHelpers.Runtime
}
}
/// <summary>
/// Creates a <see cref="NetworkObject"/> to be used with integration testing
/// </summary>
/// <param name="baseName">namr of the object</param>
/// <param name="owner">owner of the object</param>
/// <param name="moveToDDOL">when true, the instance is automatically migrated into the DDOL</param>
/// <returns></returns>
internal static GameObject CreateNetworkObject(string baseName, NetworkManager owner, bool moveToDDOL = false)
{
var gameObject = new GameObject
{
name = baseName
};
var networkObject = gameObject.AddComponent<NetworkObject>();
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 @@ namespace Unity.Netcode.TestHelpers.Runtime
Assert.IsNotNull(server, prefabCreateAssertError);
Assert.IsFalse(server.IsListening, prefabCreateAssertError);
var gameObject = new GameObject
{
name = baseName
};
var networkObject = gameObject.AddComponent<NetworkObject>();
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

View File

@@ -205,13 +205,14 @@ namespace Unity.Netcode.RuntimeTests
[UnityTest]
public IEnumerator NetworkVariableDelta()
{
var component = Client.LocalClient.PlayerObject.GetComponent<TestNetworkComponent>();
var message = new NetworkVariableDeltaMessage
{
NetworkObjectId = 0,
NetworkBehaviourIndex = 1,
DeliveryMappedNetworkVariableIndex = new HashSet<int> { 2, 3, 4 },
NetworkObjectId = Client.LocalClient.PlayerObject.NetworkObjectId,
NetworkBehaviourIndex = component.NetworkBehaviourId,
DeliveryMappedNetworkVariableIndex = new HashSet<int> { 0, 1 },
TargetClientId = 5,
NetworkBehaviour = Client.LocalClient.PlayerObject.GetComponent<TestNetworkComponent>(),
NetworkBehaviour = component,
};
yield return SendMessage(ref message);
@@ -569,7 +570,7 @@ namespace Unity.Netcode.RuntimeTests
private IEnumerator SendMessage<T>(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<ulong>(1, Allocator.Temp);
clientIds[0] = k_ClientId;
@@ -625,7 +626,8 @@ namespace Unity.Netcode.RuntimeTests
}
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))

View File

@@ -216,6 +216,21 @@ namespace Unity.Netcode.RuntimeTests
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 @@ namespace Unity.Netcode.RuntimeTests
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 @@ namespace Unity.Netcode.RuntimeTests
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 @@ namespace Unity.Netcode.RuntimeTests
return m_PlayerPrefabs[Random.Range(0, m_PlayerPrefabs.Count() - 1)].GetComponent<NetworkObject>();
}
public enum PlayerSpawnTypes
{
Normal,
NetworkObject,
SpawnManager
}
/// <summary>
/// Validates that when a client changes their player object that all connected client instances mirror the
/// client's new player object.
/// </summary>
[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 @@ namespace Unity.Netcode.RuntimeTests
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);
}

View File

@@ -128,7 +128,7 @@ namespace Unity.Netcode.RuntimeTests
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 @@ namespace Unity.Netcode.RuntimeTests
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 @@ namespace Unity.Netcode.RuntimeTests
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 @@ namespace Unity.Netcode.RuntimeTests
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 @@ namespace Unity.Netcode.RuntimeTests
// 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 @@ namespace Unity.Netcode.RuntimeTests
// 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 @@ namespace Unity.Netcode.RuntimeTests
$" 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 @@ namespace Unity.Netcode.RuntimeTests
// 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 @@ namespace Unity.Netcode.RuntimeTests
// 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 @@ namespace Unity.Netcode.RuntimeTests
// 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 @@ namespace Unity.Netcode.RuntimeTests
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 @@ namespace Unity.Netcode.RuntimeTests
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 @@ namespace Unity.Netcode.RuntimeTests
// 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 @@ namespace Unity.Netcode.RuntimeTests
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 @@ namespace Unity.Netcode.RuntimeTests
// 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<OwnershipPermissionsTestHelper>();
// 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

View File

@@ -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;
/// <summary>
/// Callback used to mock the scenario where a client has an invalid session version
/// </summary>
/// <returns><see cref="SessionConfig"/></returns>
private SessionConfig GetInavlidSessionConfig()
{
return new SessionConfig(m_ServerNetworkManager.SessionConfig.SessionVersion - 1);
}
/// <summary>
/// Overriding this method allows us to configure the newly instantiated client's
/// NetworkManager prior to it being started.
/// </summary>
/// <param name="networkManager">the newly instantiated NetworkManager</param>
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);
}
/// <summary>
/// Tracks if the client was disconnected or not
/// </summary>
private void OnClientDisconnectCallback(ulong clientId)
{
m_ClientWasDisconnected = true;
m_ClientNetworkManager.OnClientDisconnectCallback -= OnClientDisconnectCallback;
}
/// <summary>
/// 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).
/// </summary>
/// <param name="networkManager"></param>
/// <returns>true = wait | false = don't wait</returns>
protected override bool ShouldWaitForNewClientToConnect(NetworkManager networkManager)
{
return m_UseValidSessionVersion;
}
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// This is just a mock of the service logic to validate everything on the NGO side is
/// working correctly.
/// </remarks>
/// <param name="useValidSessionVersion">true = use valid session version | false = use invalid session version</param>
[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!");
}
}
/// <summary>
/// Invoked at the end of each integration test pass.
/// Primarily used to clean up for the next pass.
/// </summary>
protected override IEnumerator OnTearDown()
{
m_ClientNetworkManager.OnClientDisconnectCallback -= OnClientDisconnectCallback;
m_ClientNetworkManager = null;
yield return base.OnTearDown();
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 62913c78d28137141acc47ea8f63e657

View File

@@ -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 @@ namespace Unity.Netcode.RuntimeTests
}
}
}
/// <summary>
/// Verifies the UnityTransport.GetEndpoint method returns
/// valid NetworkEndpoint information.
/// </summary>
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);
}
}
}

View File

@@ -127,7 +127,11 @@ namespace Unity.Netcode.RuntimeTests
}
// 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 @@ namespace Unity.Netcode.RuntimeTests
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;

View File

@@ -36,13 +36,25 @@ namespace Unity.Netcode.RuntimeTests
{
VerifyObjectIsSpawnedOnClient.ResetObjectTable();
m_ClientNetworkTransformPrefab = CreateNetworkObjectPrefab("OwnerAuthorityTest");
var clientNetworkObject = m_ClientNetworkTransformPrefab.GetComponent<NetworkObject>();
// 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<TestClientNetworkTransform>();
clientNetworkTransform.AuthorityMode = NetworkTransform.AuthorityModes.Owner;
clientNetworkTransform.Interpolate = false;
clientNetworkTransform.UseHalfFloatPrecision = false;
var rigidBody = m_ClientNetworkTransformPrefab.AddComponent<Rigidbody>();
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 @@ namespace Unity.Netcode.RuntimeTests
m_ClientNetworkTransformPrefab.AddComponent<VerifyObjectIsSpawnedOnClient>();
m_NetworkTransformPrefab = CreateNetworkObjectPrefab("ServerAuthorityTest");
var networkTransform = m_NetworkTransformPrefab.AddComponent<NetworkTransform>();
var networkObject = m_ClientNetworkTransformPrefab.GetComponent<NetworkObject>();
// 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<TestClientNetworkTransform>();
rigidBody = m_NetworkTransformPrefab.AddComponent<Rigidbody>();
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 @@ namespace Unity.Netcode.RuntimeTests
};
if (m_MotionModel == MotionModels.UseRigidbody)
{
TestClientNetworkTransform.EnableLogState(m_EnableVerboseDebug);
var ownerRigidbody = ownerInstance.GetComponent<Rigidbody>();
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 @@ namespace Unity.Netcode.RuntimeTests
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<Rigidbody>().linearVelocity = Vector3.zero;
Assert.True(nonOwnerInstance.OwnerClientId == networkManagerNonOwner.LocalClientId, $"Client-{networkManagerNonOwner.LocalClientId} failed to change ownership!");
LogNonOwnerRigidBody(3);
yield return WaitForConditionOrTimeOut(() => ownerInstance.GetComponent<NetworkObject>().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<NetworkObject>(), networkManagerNonOwner.LocalClientId, true);
LogNonOwnerRigidBody(3);
yield return WaitForConditionOrTimeOut(() => nonOwnerInstance.GetComponent<NetworkObject>().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<NetworkObject>().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 @@ namespace Unity.Netcode.RuntimeTests
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<Rigidbody>().isKinematic, $"{networkManagerOwner.name}'s object instance {ownerInstance.name} is kinematic when it should not be!");
@@ -344,7 +377,7 @@ namespace Unity.Netcode.RuntimeTests
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<TestClientNetworkTransform>().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 @@ namespace Unity.Netcode.RuntimeTests
var ownerRigidbody = ownerInstance.GetComponent<Rigidbody>();
ownerRigidbody.Move(valueSetByOwner, rotation);
LogOwnerRigidBody(2);
yield return new WaitForFixedUpdate();
ownerInstance.GetComponent<NetworkTransform>().LogMotion = m_EnableVerboseDebug;
nonOwnerInstance.GetComponent<NetworkTransform>().LogMotion = m_EnableVerboseDebug;
ownerRigidbody.linearVelocity = Vector3.zero;
@@ -377,10 +411,11 @@ namespace Unity.Netcode.RuntimeTests
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<TestClientNetworkTransform>().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 @@ namespace Unity.Netcode.RuntimeTests
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();
}
/// <summary>
/// NetworkTransformOwnershipTests helper behaviour
/// </summary>
@@ -457,6 +498,10 @@ namespace Unity.Netcode.RuntimeTests
NetworkManagerRelativeSpawnedObjects.Clear();
}
/// <summary>
/// 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.
/// </summary>
public override void OnGainedOwnership()
{
if (!NetworkManagerRelativeSpawnedObjects.ContainsKey(NetworkManager.LocalClientId))
@@ -466,6 +511,10 @@ namespace Unity.Netcode.RuntimeTests
base.OnGainedOwnership();
}
/// <summary>
/// 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.
/// </summary>
public override void OnLostOwnership()
{
if (!NetworkManagerRelativeSpawnedObjects.ContainsKey(NetworkManager.LocalClientId))
@@ -515,28 +564,57 @@ namespace Unity.Netcode.RuntimeTests
[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<Rigidbody>().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 @@ namespace Unity.Netcode.RuntimeTests
foreach (var networkManager in m_NetworkManagers)
{
// Randomize the position
// Randomize the position
RandomizeObjectTransformPositions(m_SpawnObject);
// Create an instance owned by the specified networkmanager

View File

@@ -123,7 +123,7 @@ namespace Unity.Netcode.RuntimeTests
}
/// <summary>
/// This test validates the SwitchTransformSpaceWhenParented setting under all network topologies
/// This test validates the SwitchTransformSpaceWhenParented setting under all network topologies
/// </summary>
[Test]
public void SwitchTransformSpaceWhenParentedTest([Values(0.5f, 1.0f, 5.0f)] float scale)

View File

@@ -20,7 +20,7 @@ namespace Unity.Netcode.RuntimeTests
/// - HashSet
/// This also does some testing on nested collections, but does
/// not test every possible combination.
/// </summary>
/// </summary>
[TestFixture(HostOrServer.Host)]
[TestFixture(HostOrServer.Server)]
public class NetworkVariableCollectionsTests : NetcodeIntegrationTest
@@ -218,7 +218,7 @@ namespace Unity.Netcode.RuntimeTests
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 @@ namespace Unity.Netcode.RuntimeTests
// Only test restore on non-host clients (otherwise a host is both server and client/owner)
if (!client.IsServer)
{
// No Write Client Remove List<int> item with CheckDirtyState restore
// No Write Client Remove List<int> 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 @@ namespace Unity.Netcode.RuntimeTests
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 @@ namespace Unity.Netcode.RuntimeTests
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 @@ namespace Unity.Netcode.RuntimeTests
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());

View File

@@ -1012,8 +1012,7 @@ namespace Unity.Netcode.RuntimeTests
}
[Test]
// Exceptions should be thrown in DA mode with UserNetworkVariableSerialization
public void TestUnsupportedManagedTypesWithUserSerializationDoNotThrowExceptionsInClientServerMode()
public void TestUnsupportedManagedTypesWithUserSerializationDoNotThrowExceptions()
{
var variable = new NetworkVariable<string>();
UserNetworkVariableSerialization<string>.ReadValue = (FastBufferReader reader, out string value) =>
@@ -1039,10 +1038,6 @@ namespace Unity.Netcode.RuntimeTests
variable.ReadField(reader);
Assert.AreEqual("012345", variable.Value);
}
catch (Exception)
{
Assert.True(NetworkVariableSerialization<UserNetworkVariableSerialization<string>>.IsDistributedAuthority);
}
finally
{
UserNetworkVariableSerialization<string>.ReadValue = null;

View File

@@ -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 @@ namespace Unity.Netcode.RuntimeTests
}
}
}
/// <summary>
/// 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.
/// </summary>
[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<NetworkManager> 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<NetworkManager>();
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}");
}
}
}

View File

@@ -1,6 +1,7 @@
fileFormatVersion: 2
guid: 2a43005be301c9043aab7034757d4868
TextScriptImporter:
guid: 83133d71f2112db45ba626157c46e7f8
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:

View File

@@ -85,9 +85,14 @@ namespace Unity.Netcode.RuntimeTests
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);

View File

@@ -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
{
/// <summary>
/// Integration test that validates spawning instances of <see cref="NetworkPrefab"/>s with overrides and
/// <see cref="NetworkPrefabHandler"/> registered overrides.
/// </summary>
[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) { }
/// <summary>
/// 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.
/// </summary>
public class TestPrefabOverrideHandler : MonoBehaviour, INetworkPrefabInstanceHandler
{
public GameObject ServerSideInstance;
public GameObject ClientSideInstance;
private NetworkManager m_NetworkManager;
private void Start()
{
m_NetworkManager = GetComponent<NetworkManager>();
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<NetworkObject>();
}
public void Destroy(NetworkObject networkObject)
{
Object.Destroy(networkObject);
}
}
/// <summary>
/// Mock component for testing that the client-side player is using the right
/// network prefab.
/// </summary>
public class ClientSideOnlyComponent : MonoBehaviour
{
}
/// <summary>
/// When we create the player prefab, make a modified instance that will be used
/// with the <see cref="TestPrefabOverrideHandler"/>.
/// </summary>
protected override void OnCreatePlayerPrefab()
{
var clientPlayer = Object.Instantiate(m_PlayerPrefab);
clientPlayer.AddComponent<ClientSideOnlyComponent>();
Object.DontDestroyOnLoad(clientPlayer);
m_ClientSidePlayerPrefab = new NetworkPrefab()
{
Prefab = clientPlayer,
};
base.OnCreatePlayerPrefab();
}
/// <summary>
/// Add the additional <see cref="NetworkPrefab"/>s and <see cref="TestPrefabOverrideHandler"/>s to
/// all <see cref="NetworkManager"/> instances.
/// </summary>
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<TestPrefabOverrideHandler>();
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<TestPrefabOverrideHandler>();
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<NetworkObject>().IsSceneObject = false;
m_PrefabOverride.SourcePrefabToOverride.GetComponent<NetworkObject>().IsSceneObject = false;
m_PrefabOverride.OverridingTargetPrefab.GetComponent<NetworkObject>().IsSceneObject = false;
m_ClientSidePlayerPrefab.Prefab.GetComponent<NetworkObject>().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<NetworkObject>();
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<NetworkObject>();
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<NetworkObject>().GlobalObjectIdHash : m_PrefabOverride.SourcePrefabToOverride.GetComponent<NetworkObject>().GlobalObjectIdHash;
var expectedClientGlobalObjectIdHash = m_PrefabOverride.OverridingTargetPrefab.GetComponent<NetworkObject>().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}");
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c5e27e24bc5f783458d6a45585308f87

View File

@@ -33,7 +33,7 @@ namespace Unity.Netcode.RuntimeTests
if (transport)
{
transport.Shutdown();
UnityEngine.Object.DestroyImmediate(transport);
UnityEngine.Object.DestroyImmediate(transport.gameObject);
}
}
@@ -42,6 +42,7 @@ namespace Unity.Netcode.RuntimeTests
transportEvents?.Clear();
}
UnityTransportTestComponent.CleanUp();
yield return null;
}
@@ -59,6 +60,7 @@ namespace Unity.Netcode.RuntimeTests
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 @@ namespace Unity.Netcode.RuntimeTests
// 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 @@ namespace Unity.Netcode.RuntimeTests
{
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 @@ namespace Unity.Netcode.RuntimeTests
{
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 @@ namespace Unity.Netcode.RuntimeTests
// 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 @@ namespace Unity.Netcode.RuntimeTests
// 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.

View File

@@ -36,6 +36,24 @@ namespace Unity.Netcode.RuntimeTests
Assert.Fail("Timed out while waiting for network event.");
}
// Wait to ensure no event is sent.
public static IEnumerator EnsureNoNetworkEvent(List<TransportEvent> 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<TransportEvent> events,
int maxPayloadSize = UnityTransport.InitialMaxPayloadSize, int maxSendQueueSize = 0, NetworkFamily family = NetworkFamily.Ipv4)
@@ -43,7 +61,7 @@ namespace Unity.Netcode.RuntimeTests
var logger = new TransportEventLogger();
events = logger.Events;
transport = new GameObject().AddComponent<UnityTransport>();
transport = new GameObject().AddComponent<UnityTransportTestComponent>();
transport.OnTransportEvent += logger.HandleEvent;
transport.MaxPayloadSize = maxPayloadSize;
@@ -91,5 +109,58 @@ namespace Unity.Netcode.RuntimeTests
});
}
}
internal class UnityTransportTestComponent : UnityTransport, INetworkUpdateSystem
{
private static List<UnityTransportTestComponent> s_Instances = new List<UnityTransportTestComponent>();
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();
}
/// <summary>
/// Simulate the <see cref="NetworkManager.NetworkUpdate"/> being invoked so <see cref="UnityTransport.EarlyUpdate"/>
/// and <see cref="UnityTransport.PostLateUpdate"/> are invoked.
/// </summary>
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);
}
}
}
}

View File

@@ -60,11 +60,11 @@ namespace Unity.Netcode.RuntimeTests
// 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 @@ namespace Unity.Netcode.RuntimeTests
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 @@ namespace Unity.Netcode.RuntimeTests
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 @@ namespace Unity.Netcode.RuntimeTests
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 @@ namespace Unity.Netcode.RuntimeTests
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 @@ namespace Unity.Netcode.RuntimeTests
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 @@ namespace Unity.Netcode.RuntimeTests
m_Client1.Shutdown();
yield return WaitForNetworkEvent(NetworkEvent.Data, m_ServerEvents);
yield return null;
}
[UnityTest]
@@ -472,8 +460,6 @@ namespace Unity.Netcode.RuntimeTests
m_Client1.DisconnectLocalClient();
yield return WaitForNetworkEvent(NetworkEvent.Data, m_ServerEvents);
yield return null;
}
[UnityTest]
@@ -493,8 +479,6 @@ namespace Unity.Netcode.RuntimeTests
m_Server.DisconnectRemoteClient(m_ServerEvents[0].ClientID);
yield return WaitForNetworkEvent(NetworkEvent.Data, m_Client1Events);
yield return null;
}
[UnityTest]
@@ -514,8 +498,47 @@ namespace Unity.Netcode.RuntimeTests
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<byte>(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);
}
}
}
}

View File

@@ -1,4 +0,0 @@
{
"ErrorExceptions": [],
"WarningExceptions": []
}

View File

@@ -2,23 +2,11 @@
"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"
},
"_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 owners 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)"
},
"upmCi": {
"footprint": "8331c76150e539e36659d8b7be3ba0fb6d21027a"
},
"documentationUrl": "https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@2.1/manual/index.html",
"repository": {
"url": "https://github.com/Unity-Technologies/com.unity.netcode.gameobjects.git",
"type": "git",
"revision": "264b30d176dd71fcedd022a8d6f4d59a2e3922bc"
"com.unity.transport": "2.4.0"
},
"samples": [
{
@@ -26,5 +14,17 @@
"description": "A lightweight sample to get started",
"path": "Samples~/Bootstrap"
}
]
],
"_upm": {
"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": "9d95aefc0dccf8f9dc0bcf0017dee417d7d31f56"
},
"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": "ba490651a8c6cf2f98c2bbacef8b24a1170860b3"
}
}