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:
1
.signature
Normal file
1
.signature
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{"timestamp":1734331212,"signature":"mMrBXdBegYd6TPqNVci9OkWh1H10YU8Ug8KlSpiyNzbXlS5z7O7Rdif3gvTdXK0O07HWmIuszcUoljQIaxkGAYq2g9A85IcvhbWsAAqxjSEZfQPsxFZlJQ9PqU4tfMItk7K1VP1YfcBxitxPHcUeO2IwBYVLx51gg6X/0qHWtkifmZ/cBbGTBNEYE+m7KfRYUyu23kOPMGOCBeULivZO9y/2A0qXkMeBiPo3KQFU6481n4GV6fahyLrG2llfM8xtW8YeouPyt/IMD86at8eeY+E5mW0iXGms9IMLf/DH6vjJnuSEfgMXfjcGnRO0m+RP+ig8HzjbPVty7oAOgfm6Oc1frOP4Cmudk97fIEzC10B0lj2uzFudT5UVPk4Hr6Mf/2ka0m+XTdRNHVRyOYBcHsJQYf0HKW/4jJPwWrSCSk2uE0fPn1sTvMb+i4pXCn7J700b7NMLPFJaWeb6kA2e3v8w5FybshFZWCU6fyLWGn1AR60u0BxL88Hx4VO5UjnJ","publicKey":"LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQm9qQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FZOEFNSUlCaWdLQ0FZRUFzdUhXYUhsZ0I1cVF4ZEJjTlJKSAordHR4SmoxcVY1NTdvMlZaRE1XaXhYRVBkRTBEMVFkT1JIRXNSS1RscmplUXlERU83ZlNQS0ZwZ1A3MU5TTnJCCkFHM2NFSU45aHNQVDhOVmllZmdWem5QTkVMenFkVmdEbFhpb2VpUnV6OERKWFgvblpmU1JWKytwbk9ySTRibG4KS0twelJlNW14OTc1SjhxZ1FvRktKT0NNRlpHdkJMR2MxSzZZaEIzOHJFODZCZzgzbUovWjBEYkVmQjBxZm13cgo2ZDVFUXFsd0E5Y3JZT1YyV1VpWXprSnBLNmJZNzRZNmM1TmpBcEFKeGNiaTFOaDlRVEhUcU44N0ZtMDF0R1ZwCjVNd1pXSWZuYVRUemEvTGZLelR5U0pka0tldEZMVGdkYXpMYlpzUEE2aHBSK0FJRTJhc0tLTi84UUk1N3UzU2cKL2xyMnZKS1IvU2l5eEN1Q20vQWJkYnJMbXk0WjlSdm1jMGdpclA4T0lLQWxBRWZ2TzV5Z2hSKy8vd1RpTFlzUQp1SllDM0V2UE16ZGdKUzdGR2FscnFLZzlPTCsxVzROY05yNWdveVdSUUJ0cktKaWlTZEJVWmVxb0RvSUY5NHpCCndGbzJJT1JFdXFqcU51M3diMWZIM3p1dGdtalFra3IxVjJhd3hmcExLWlROQWdNQkFBRT0KLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tCg"}
|
||||||
35
CHANGELOG.md
35
CHANGELOG.md
@@ -6,6 +6,37 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
|
|||||||
|
|
||||||
Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).
|
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
|
## [2.1.1] - 2024-10-18
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
@@ -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)
|
- Fixed issue where you could not have multiple source network prefab overrides targeting the same network prefab as their override. (#2710)
|
||||||
|
|
||||||
### Changed
|
### 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 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 `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)
|
- 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 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)
|
- Changed the default `NetworkConfig.SpawnTimeout` value from 1.0s to 10.0s. (#2710)
|
||||||
|
|
||||||
|
|
||||||
## [1.7.1] - 2023-11-15
|
## [1.7.1] - 2023-11-15
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
@@ -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 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)
|
- 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)
|
- 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)
|
- Connecting clients being synchronized now switch to the server's active scene before spawning and synchronizing NetworkObjects. (#2532)
|
||||||
|
|||||||
@@ -88,6 +88,14 @@ namespace Unity.Netcode.Editor
|
|||||||
|
|
||||||
while (observerClientIds.MoveNext())
|
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)
|
if (m_NetworkObject.NetworkManager.ConnectedClients[observerClientIds.Current].PlayerObject != null)
|
||||||
{
|
{
|
||||||
EditorGUILayout.ObjectField($"ClientId: {observerClientIds.Current}", m_NetworkObject.NetworkManager.ConnectedClients[observerClientIds.Current].PlayerObject, typeof(GameObject), false);
|
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();
|
EditorGUI.BeginChangeCheck();
|
||||||
serializedObject.UpdateIfRequiredOrScript();
|
serializedObject.UpdateIfRequiredOrScript();
|
||||||
DrawPropertiesExcluding(serializedObject, k_HiddenFields);
|
DrawPropertiesExcluding(serializedObject, k_HiddenFields);
|
||||||
|
if (m_NetworkObject.IsOwnershipSessionOwner)
|
||||||
|
{
|
||||||
|
m_NetworkObject.Ownership = NetworkObject.OwnershipStatus.SessionOwner;
|
||||||
|
}
|
||||||
serializedObject.ApplyModifiedProperties();
|
serializedObject.ApplyModifiedProperties();
|
||||||
EditorGUI.EndChangeCheck();
|
EditorGUI.EndChangeCheck();
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
Unity Companion License (UCL License)
|
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).
|
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.
|
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.
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -230,6 +230,7 @@ namespace Unity.Netcode.Components
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#if UNITY_EDITOR
|
#if UNITY_EDITOR
|
||||||
private void ParseStateMachineStates(int layerIndex, ref AnimatorController animatorController, ref AnimatorStateMachine stateMachine)
|
private void ParseStateMachineStates(int layerIndex, ref AnimatorController animatorController, ref AnimatorStateMachine stateMachine)
|
||||||
{
|
{
|
||||||
@@ -263,7 +264,6 @@ namespace Unity.Netcode.Components
|
|||||||
{
|
{
|
||||||
case AnimatorControllerParameterType.Trigger:
|
case AnimatorControllerParameterType.Trigger:
|
||||||
{
|
{
|
||||||
|
|
||||||
if (transition.destinationStateMachine != null)
|
if (transition.destinationStateMachine != null)
|
||||||
{
|
{
|
||||||
var destinationStateMachine = transition.destinationStateMachine;
|
var destinationStateMachine = transition.destinationStateMachine;
|
||||||
@@ -297,18 +297,12 @@ namespace Unity.Netcode.Components
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Creates the TransitionStateInfoList table
|
/// Creates the TransitionStateInfoList table
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private void BuildTransitionStateInfoList()
|
private void BuildTransitionStateInfoList()
|
||||||
{
|
{
|
||||||
#if UNITY_EDITOR
|
|
||||||
if (UnityEditor.EditorApplication.isUpdating || UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (m_Animator == null)
|
if (m_Animator == null)
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
@@ -326,9 +320,18 @@ namespace Unity.Netcode.Components
|
|||||||
var stateMachine = animatorController.layers[x].stateMachine;
|
var stateMachine = animatorController.layers[x].stateMachine;
|
||||||
ParseStateMachineStates(x, ref animatorController, ref 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()
|
public void OnAfterDeserialize()
|
||||||
{
|
{
|
||||||
BuildDestinationToTransitionInfoTable();
|
BuildDestinationToTransitionInfoTable();
|
||||||
@@ -336,7 +339,7 @@ namespace Unity.Netcode.Components
|
|||||||
|
|
||||||
public void OnBeforeSerialize()
|
public void OnBeforeSerialize()
|
||||||
{
|
{
|
||||||
BuildTransitionStateInfoList();
|
// Do nothing when serializing (handled during OnValidate)
|
||||||
}
|
}
|
||||||
|
|
||||||
internal struct AnimationState : INetworkSerializable
|
internal struct AnimationState : INetworkSerializable
|
||||||
@@ -496,7 +499,7 @@ namespace Unity.Netcode.Components
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
/// <remarks>
|
/// <remarks>
|
||||||
/// When using a distributed authority network topology, this will default to
|
/// When using a distributed authority network topology, this will default to
|
||||||
@@ -507,10 +510,6 @@ namespace Unity.Netcode.Components
|
|||||||
return NetworkManager ? !NetworkManager.DistributedAuthorityMode : true;
|
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_TransitionHash;
|
||||||
private int[] m_AnimationHash;
|
private int[] m_AnimationHash;
|
||||||
private float[] m_LayerWeights;
|
private float[] m_LayerWeights;
|
||||||
@@ -534,7 +533,7 @@ namespace Unity.Netcode.Components
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 128 bytes per Animator
|
// 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;
|
private NativeArray<AnimatorParamCache> m_CachedAnimatorParameters;
|
||||||
|
|
||||||
@@ -586,6 +585,14 @@ namespace Unity.Netcode.Components
|
|||||||
|
|
||||||
protected virtual void Awake()
|
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;
|
int layers = m_Animator.layerCount;
|
||||||
// Initializing the below arrays for everyone handles an issue
|
// Initializing the below arrays for everyone handles an issue
|
||||||
// when running in owner authoritative mode and the owner changes.
|
// 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
|
// Build our reference parameter values to detect when they change
|
||||||
var parameters = m_Animator.parameters;
|
var parameters = m_Animator.parameters;
|
||||||
m_CachedAnimatorParameters = new NativeArray<AnimatorParamCache>(parameters.Length, Allocator.Persistent);
|
m_CachedAnimatorParameters = new NativeArray<AnimatorParamCache>(parameters.Length, Allocator.Persistent);
|
||||||
@@ -655,7 +665,37 @@ namespace Unity.Netcode.Components
|
|||||||
}
|
}
|
||||||
|
|
||||||
m_CachedAnimatorParameters[i] = cacheParam;
|
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>
|
/// <summary>
|
||||||
@@ -697,7 +737,7 @@ namespace Unity.Netcode.Components
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
private void WriteSynchronizationData<T>(ref BufferSerializer<T> serializer) where T : IReaderWriter
|
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
|
// The only time this could be set to true
|
||||||
animationState.StateHash = stateHash; // When a transition, this is the originating/starting state
|
animationState.Transition = isInTransition;
|
||||||
|
// When a transition, this is the originating/starting state
|
||||||
|
animationState.StateHash = stateHash;
|
||||||
animationState.NormalizedTime = normalizedTime;
|
animationState.NormalizedTime = normalizedTime;
|
||||||
animationState.Layer = layer;
|
animationState.Layer = layer;
|
||||||
animationState.Weight = m_LayerWeights[layer];
|
animationState.Weight = m_LayerWeights[layer];
|
||||||
@@ -847,7 +889,8 @@ namespace Unity.Netcode.Components
|
|||||||
{
|
{
|
||||||
m_TransitionHash[layer] = nt.fullPathHash;
|
m_TransitionHash[layer] = nt.fullPathHash;
|
||||||
m_AnimationHash[layer] = 0;
|
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.CrossFade = true;
|
||||||
animState.Transition = true;
|
animState.Transition = true;
|
||||||
animState.Duration = tt.duration;
|
animState.Duration = tt.duration;
|
||||||
@@ -865,7 +908,8 @@ namespace Unity.Netcode.Components
|
|||||||
// first time in this transition for this layer
|
// first time in this transition for this layer
|
||||||
m_TransitionHash[layer] = tt.fullPathHash;
|
m_TransitionHash[layer] = tt.fullPathHash;
|
||||||
m_AnimationHash[layer] = 0;
|
m_AnimationHash[layer] = 0;
|
||||||
animState.StateHash = tt.fullPathHash; // Transitioning from state
|
// Transitioning from state
|
||||||
|
animState.StateHash = tt.fullPathHash;
|
||||||
animState.CrossFade = false;
|
animState.CrossFade = false;
|
||||||
animState.Transition = true;
|
animState.Transition = true;
|
||||||
animState.NormalizedTime = tt.normalizedTime;
|
animState.NormalizedTime = tt.normalizedTime;
|
||||||
@@ -1081,7 +1125,7 @@ namespace Unity.Netcode.Components
|
|||||||
{
|
{
|
||||||
writer.Seek(0);
|
writer.Seek(0);
|
||||||
writer.Truncate();
|
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);
|
BytePacker.WriteValuePacked(writer, (uint)m_ParametersToUpdate.Count);
|
||||||
foreach (var parameterIndex in m_ParametersToUpdate)
|
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})!");
|
NetworkLog.LogError($"[DestinationState To Transition Info] Layer ({animationState.Layer}) sub-table does not contain destination state ({animationState.DestinationStateHash})!");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (NetworkManager.LogLevel == LogLevel.Developer)
|
// 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!");
|
//{
|
||||||
}
|
// NetworkLog.LogError($"[DestinationState To Transition Info] Layer ({animationState.Layer}) does not exist!");
|
||||||
|
//}
|
||||||
}
|
}
|
||||||
else if (animationState.Transition && animationState.CrossFade)
|
else if (animationState.Transition && animationState.CrossFade)
|
||||||
{
|
{
|
||||||
@@ -1436,7 +1481,7 @@ namespace Unity.Netcode.Components
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Distributed Authority: Internally-called RPC client receiving function to update a trigger when the server wants to forward
|
/// Distributed Authority: Internally-called RPC client receiving function to update a trigger when the server wants to forward
|
||||||
/// a trigger for a client to play / reset
|
/// a trigger to a client
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="animationTriggerMessage">the payload containing the trigger data to apply</param>
|
/// <param name="animationTriggerMessage">the payload containing the trigger data to apply</param>
|
||||||
[Rpc(SendTo.NotAuthority)]
|
[Rpc(SendTo.NotAuthority)]
|
||||||
@@ -1447,7 +1492,7 @@ namespace Unity.Netcode.Components
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Client Server: Internally-called RPC client receiving function to update a trigger when the server wants to forward
|
/// 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>
|
/// </summary>
|
||||||
/// <param name="animationTriggerMessage">the payload containing the trigger data to apply</param>
|
/// <param name="animationTriggerMessage">the payload containing the trigger data to apply</param>
|
||||||
/// <param name="clientRpcParams">unused</param>
|
/// <param name="clientRpcParams">unused</param>
|
||||||
@@ -1529,4 +1574,5 @@ namespace Unity.Netcode.Components
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // COM_UNITY_MODULES_ANIMATION
|
// COM_UNITY_MODULES_ANIMATION
|
||||||
|
#endif
|
||||||
|
|||||||
@@ -849,9 +849,7 @@ namespace Unity.Netcode.Components
|
|||||||
}
|
}
|
||||||
if (UseRigidBodyForMotion)
|
if (UseRigidBodyForMotion)
|
||||||
{
|
{
|
||||||
if (m_IsRigidbody2D)
|
if (m_IsRigidbody2D && FixedJoint2D != null)
|
||||||
{
|
|
||||||
if (FixedJoint2D != null)
|
|
||||||
{
|
{
|
||||||
if (!m_FixedJoint2DUsingGravity)
|
if (!m_FixedJoint2DUsingGravity)
|
||||||
{
|
{
|
||||||
@@ -863,10 +861,7 @@ namespace Unity.Netcode.Components
|
|||||||
ResetInterpolation();
|
ResetInterpolation();
|
||||||
RemoveFromParentBody();
|
RemoveFromParentBody();
|
||||||
}
|
}
|
||||||
}
|
else if (FixedJoint != null)
|
||||||
else
|
|
||||||
{
|
|
||||||
if (FixedJoint != null)
|
|
||||||
{
|
{
|
||||||
FixedJoint.connectedBody = null;
|
FixedJoint.connectedBody = null;
|
||||||
m_InternalRigidbody.useGravity = m_OriginalGravitySetting;
|
m_InternalRigidbody.useGravity = m_OriginalGravitySetting;
|
||||||
@@ -879,6 +874,5 @@ namespace Unity.Netcode.Components
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
// COM_UNITY_MODULES_PHYSICS
|
||||||
#endif // COM_UNITY_MODULES_PHYSICS
|
#endif
|
||||||
|
|
||||||
|
|||||||
@@ -32,7 +32,8 @@ namespace Unity.Netcode.Components
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public struct NetworkTransformState : INetworkSerializable
|
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_PositionXBit = 0x00000002;
|
||||||
private const int k_PositionYBit = 0x00000004;
|
private const int k_PositionYBit = 0x00000004;
|
||||||
private const int k_PositionZBit = 0x00000008;
|
private const int k_PositionZBit = 0x00000008;
|
||||||
@@ -43,18 +44,25 @@ namespace Unity.Netcode.Components
|
|||||||
private const int k_ScaleYBit = 0x00000100;
|
private const int k_ScaleYBit = 0x00000100;
|
||||||
private const int k_ScaleZBit = 0x00000200;
|
private const int k_ScaleZBit = 0x00000200;
|
||||||
private const int k_TeleportingBit = 0x00000400;
|
private const int k_TeleportingBit = 0x00000400;
|
||||||
private const int k_Interpolate = 0x00000800; // Persists between state updates (authority dictates if this is set)
|
// 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_Interpolate = 0x00000800;
|
||||||
private const int k_QuaternionCompress = 0x00002000; // Persists between state updates (authority dictates if this is set)
|
// 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)
|
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_Synchronization = 0x00008000;
|
||||||
private const int k_PositionSlerp = 0x00010000; // Persists between state updates (authority dictates if this is set)
|
// 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
|
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_SynchBaseHalfFloat = 0x00040000;
|
||||||
private const int k_ReliableSequenced = 0x00080000;
|
private const int k_ReliableSequenced = 0x00080000;
|
||||||
private const int k_UseUnreliableDeltas = 0x00100000;
|
private const int k_UseUnreliableDeltas = 0x00100000;
|
||||||
private const int k_UnreliableFrameSync = 0x00200000;
|
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
|
// Stores persistent and state relative flags
|
||||||
private uint m_Bitset;
|
private uint m_Bitset;
|
||||||
@@ -929,8 +937,6 @@ namespace Unity.Netcode.Components
|
|||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region PROPERTIES AND GENERAL METHODS
|
#region PROPERTIES AND GENERAL METHODS
|
||||||
|
|
||||||
|
|
||||||
public enum AuthorityModes
|
public enum AuthorityModes
|
||||||
{
|
{
|
||||||
Server,
|
Server,
|
||||||
@@ -1370,7 +1376,8 @@ namespace Unity.Netcode.Components
|
|||||||
|
|
||||||
private BufferedLinearInterpolatorVector3 m_PositionInterpolator;
|
private BufferedLinearInterpolatorVector3 m_PositionInterpolator;
|
||||||
private BufferedLinearInterpolatorVector3 m_ScaleInterpolator;
|
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
|
// The previous network state
|
||||||
private NetworkTransformState m_OldState = new NetworkTransformState();
|
private NetworkTransformState m_OldState = new NetworkTransformState();
|
||||||
@@ -3772,7 +3779,6 @@ namespace Unity.Netcode.Components
|
|||||||
return OnIsServerAuthoritative();
|
return OnIsServerAuthoritative();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region MESSAGE HANDLING
|
#region MESSAGE HANDLING
|
||||||
|
|||||||
@@ -13,6 +13,14 @@ namespace Unity.Netcode
|
|||||||
[Serializable]
|
[Serializable]
|
||||||
public class NetworkConfig
|
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>
|
/// <summary>
|
||||||
/// The protocol version. Different versions doesn't talk to each other.
|
/// The protocol version. Different versions doesn't talk to each other.
|
||||||
/// </summary>
|
/// </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.
|
/// 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>
|
/// </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.")]
|
[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;
|
public float SpawnTimeout = 10f;
|
||||||
|
|
||||||
/// <summary>
|
/// <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.")]
|
[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;
|
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>
|
/// <summary>
|
||||||
/// Returns a base64 encoded version of the configuration
|
/// Returns a base64 encoded version of the configuration
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
58
Runtime/Configuration/SessionConfig.cs
Normal file
58
Runtime/Configuration/SessionConfig.cs
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
2
Runtime/Configuration/SessionConfig.cs.meta
Normal file
2
Runtime/Configuration/SessionConfig.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: e0512e5a3e1dc484bbbf98c03a574645
|
||||||
@@ -10,15 +10,54 @@ using UnityEngine;
|
|||||||
|
|
||||||
namespace Unity.Netcode
|
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
|
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,
|
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,
|
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,
|
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
|
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 struct ConnectionEventData
|
||||||
{
|
{
|
||||||
public ConnectionEvent EventType;
|
public ConnectionEvent EventType;
|
||||||
@@ -563,7 +602,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
var message = new ConnectionRequestMessage
|
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
|
// 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),
|
ConfigHash = NetworkManager.NetworkConfig.GetConfig(false),
|
||||||
ShouldSendConnectionData = NetworkManager.NetworkConfig.ConnectionApproval,
|
ShouldSendConnectionData = NetworkManager.NetworkConfig.ConnectionApproval,
|
||||||
@@ -571,8 +610,9 @@ namespace Unity.Netcode
|
|||||||
MessageVersions = new NativeArray<MessageVersionData>(MessageManager.MessageHandlers.Length, Allocator.Temp)
|
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.TickRate = NetworkManager.NetworkConfig.TickRate;
|
||||||
message.ClientConfig.EnableSceneManagement = NetworkManager.NetworkConfig.EnableSceneManagement;
|
message.ClientConfig.EnableSceneManagement = NetworkManager.NetworkConfig.EnableSceneManagement;
|
||||||
}
|
}
|
||||||
@@ -1001,6 +1041,14 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
var distributedAuthority = NetworkManager.DistributedAuthorityMode;
|
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 sessionOwnerId = NetworkManager.CurrentSessionOwner;
|
||||||
var isSessionOwner = NetworkManager.LocalClient.IsSessionOwner;
|
var isSessionOwner = NetworkManager.LocalClient.IsSessionOwner;
|
||||||
foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList)
|
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
|
// Only NetworkObjects that have the OwnershipStatus.Distributable flag set and no parent
|
||||||
// (ownership is transferred to all children) will have their ownership redistributed.
|
// (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)
|
if (ownedObject.IsOwnershipLocked)
|
||||||
{
|
{
|
||||||
@@ -1201,6 +1249,11 @@ namespace Unity.Netcode
|
|||||||
childObject.SetOwnershipLock(false);
|
childObject.SetOwnershipLock(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Ignore session owner marked objects
|
||||||
|
if (childObject.IsOwnershipSessionOwner)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
NetworkManager.SpawnManager.ChangeOwnership(childObject, targetOwner, true);
|
NetworkManager.SpawnManager.ChangeOwnership(childObject, targetOwner, true);
|
||||||
if (EnableDistributeLogging)
|
if (EnableDistributeLogging)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1181,14 +1181,8 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
// Create any values that require accessing the NetworkManager locally (it is expensive to access it in NetworkBehaviour)
|
// Create any values that require accessing the NetworkManager locally (it is expensive to access it in NetworkBehaviour)
|
||||||
var networkManager = NetworkManager;
|
var networkManager = NetworkManager;
|
||||||
var distributedAuthority = networkManager.DistributedAuthorityMode;
|
|
||||||
var ensureLengthSafety = networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety;
|
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
|
// Exit early if there are no NetworkVariables
|
||||||
if (NetworkVariableFields.Count == 0)
|
if (NetworkVariableFields.Count == 0)
|
||||||
@@ -1203,14 +1197,8 @@ namespace Unity.Netcode
|
|||||||
if (NetworkVariableFields[j].CanClientRead(targetClientId))
|
if (NetworkVariableFields[j].CanClientRead(targetClientId))
|
||||||
{
|
{
|
||||||
// Write additional NetworkVariable information when length safety is enabled or when in distributed authority mode
|
// 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;
|
var writePos = writer.Position;
|
||||||
// Note: This value can't be packed because we don't know how large it will be in advance
|
// 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
|
// 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)
|
// Stack cache any values that requires accessing the NetworkManager (it is expensive to access it in NetworkBehaviour)
|
||||||
var networkManager = NetworkManager;
|
var networkManager = NetworkManager;
|
||||||
var distributedAuthority = networkManager.DistributedAuthorityMode;
|
|
||||||
var ensureLengthSafety = networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety;
|
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
|
// Exit early if nothing else to read
|
||||||
if (NetworkVariableFields.Count == 0)
|
if (NetworkVariableFields.Count == 0)
|
||||||
{
|
{
|
||||||
@@ -1289,14 +1265,8 @@ namespace Unity.Netcode
|
|||||||
// Distributed Authority: All clients have read permissions, always try to read the value
|
// Distributed Authority: All clients have read permissions, always try to read the value
|
||||||
if (NetworkVariableFields[j].CanClientRead(clientId))
|
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);
|
reader.ReadValueSafe(out varSize);
|
||||||
if (varSize == 0)
|
if (varSize == 0)
|
||||||
{
|
{
|
||||||
@@ -1320,11 +1290,11 @@ namespace Unity.Netcode
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read the NetworkVarible value
|
// Read the NetworkVariable value
|
||||||
NetworkVariableFields[j].ReadField(reader);
|
NetworkVariableFields[j].ReadField(reader);
|
||||||
|
|
||||||
// When EnsureNetworkVariableLengthSafety or DistributedAuthorityMode always do a bounds check
|
// When EnsureNetworkVariableLengthSafety always do a bounds check
|
||||||
if (ensureLengthSafety || distributedAuthority)
|
if (ensureLengthSafety)
|
||||||
{
|
{
|
||||||
if (reader.Position > (readStartPos + varSize))
|
if (reader.Position > (readStartPos + varSize))
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -141,6 +141,9 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
// Then show any NetworkObjects queued to be made visible/shown
|
// Then show any NetworkObjects queued to be made visible/shown
|
||||||
m_NetworkManager.SpawnManager.HandleNetworkObjectShow();
|
m_NetworkManager.SpawnManager.HandleNetworkObjectShow();
|
||||||
|
|
||||||
|
// Handle object redistribution (DA + disabled scene management only)
|
||||||
|
m_NetworkManager.HandleRedistributionToClients();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -80,6 +80,18 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
#endif
|
#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;
|
internal static bool IsDistributedAuthority;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -162,10 +174,30 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// DANGO-TODO-MVP: Remove these properties once the service handles object distribution
|
// DANGO-TODO: Determine if this needs to be removed once the service handles object distribution
|
||||||
internal ulong ClientToRedistribute;
|
internal List<ulong> ClientsToRedistribute = new List<ulong>();
|
||||||
internal bool RedistributeToClient;
|
internal bool RedistributeToClients;
|
||||||
internal int TickToRedistribute;
|
|
||||||
|
/// <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>();
|
internal List<NetworkObject> DeferredDespawnObjects = new List<NetworkObject>();
|
||||||
|
|
||||||
@@ -193,11 +225,7 @@ namespace Unity.Netcode
|
|||||||
foreach (var networkObjectEntry in SpawnManager.SpawnedObjects)
|
foreach (var networkObjectEntry in SpawnManager.SpawnedObjects)
|
||||||
{
|
{
|
||||||
var networkObject = networkObjectEntry.Value;
|
var networkObject = networkObjectEntry.Value;
|
||||||
if (networkObject.IsSceneObject == null || !networkObject.IsSceneObject.Value)
|
if (networkObject.IsOwnershipSessionOwner && LocalClient.IsSessionOwner)
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (networkObject.OwnerClientId != LocalClientId)
|
|
||||||
{
|
{
|
||||||
SpawnManager.ChangeOwnership(networkObject, LocalClientId, true);
|
SpawnManager.ChangeOwnership(networkObject, LocalClientId, true);
|
||||||
}
|
}
|
||||||
@@ -291,6 +319,10 @@ namespace Unity.Netcode
|
|||||||
case NetworkUpdateStage.EarlyUpdate:
|
case NetworkUpdateStage.EarlyUpdate:
|
||||||
{
|
{
|
||||||
UpdateTopology();
|
UpdateTopology();
|
||||||
|
|
||||||
|
// Handle processing any new connections or transport events
|
||||||
|
NetworkConfig.NetworkTransport.EarlyUpdate();
|
||||||
|
|
||||||
ConnectionManager.ProcessPendingApprovals();
|
ConnectionManager.ProcessPendingApprovals();
|
||||||
ConnectionManager.PollAndHandleNetworkEvents();
|
ConnectionManager.PollAndHandleNetworkEvents();
|
||||||
|
|
||||||
@@ -298,6 +330,7 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
AnticipationSystem.SetupForUpdate();
|
AnticipationSystem.SetupForUpdate();
|
||||||
MessageManager.ProcessIncomingMessageQueue();
|
MessageManager.ProcessIncomingMessageQueue();
|
||||||
|
|
||||||
MessageManager.CleanupDisconnectedClients();
|
MessageManager.CleanupDisconnectedClients();
|
||||||
AnticipationSystem.ProcessReanticipation();
|
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.
|
// Metrics update needs to be driven by NetworkConnectionManager's update to assure metrics are dispatched after the send queue is processed.
|
||||||
MetricsManager.UpdateMetrics();
|
MetricsManager.UpdateMetrics();
|
||||||
|
|
||||||
|
// Handle sending any pending transport messages
|
||||||
|
NetworkConfig.NetworkTransport.PostLateUpdate();
|
||||||
|
|
||||||
// TODO: Determine a better way to handle this
|
// TODO: Determine a better way to handle this
|
||||||
NetworkObject.VerifyParentingStatus();
|
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.
|
// 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();
|
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)
|
if (m_ShuttingDown)
|
||||||
{
|
{
|
||||||
// Host-server will disconnect any connected clients prior to finalizing its shutdown
|
// 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
|
return; // May occur when the component is added
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Do a validation pass on NetworkConfig properties
|
||||||
|
NetworkConfig.OnValidate();
|
||||||
|
|
||||||
if (GetComponentInChildren<NetworkObject>() != null)
|
if (GetComponentInChildren<NetworkObject>() != null)
|
||||||
{
|
{
|
||||||
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
|
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
|
||||||
@@ -993,8 +1022,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
if (IsListening && change == PlayModeStateChange.ExitingPlayMode)
|
if (IsListening && change == PlayModeStateChange.ExitingPlayMode)
|
||||||
{
|
{
|
||||||
// Make sure we are not holding onto anything in case domain reload is disabled
|
OnApplicationQuit();
|
||||||
ShutdownInternal();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
@@ -1161,6 +1189,12 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
UpdateTopology();
|
UpdateTopology();
|
||||||
|
|
||||||
|
// Always create a default session config when starting a NetworkManager instance
|
||||||
|
if (DistributedAuthorityMode)
|
||||||
|
{
|
||||||
|
SessionConfig = GetSessionConfig();
|
||||||
|
}
|
||||||
|
|
||||||
// Make sure the ServerShutdownState is reset when initializing
|
// Make sure the ServerShutdownState is reset when initializing
|
||||||
if (server)
|
if (server)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -102,10 +102,22 @@ namespace Unity.Netcode
|
|||||||
private const int k_SceneObjectType = 2;
|
private const int k_SceneObjectType = 2;
|
||||||
private const int k_SourceAssetObjectType = 3;
|
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")]
|
[ContextMenu("Refresh In-Scene Prefab Instances")]
|
||||||
internal void RefreshAllPrefabInstances()
|
internal void RefreshAllPrefabInstances()
|
||||||
{
|
{
|
||||||
var instanceGlobalId = GlobalObjectId.GetGlobalObjectIdSlow(this);
|
var instanceGlobalId = GlobalObjectId.GetGlobalObjectIdSlow(this);
|
||||||
|
// Assign the currently selected instance to be updated
|
||||||
|
NetworkObjectRefreshTool.PrefabNetworkObject = this;
|
||||||
if (!PrefabUtility.IsPartOfAnyPrefab(this) || instanceGlobalId.identifierType != k_ImportedAssetObjectType)
|
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");
|
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();
|
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()
|
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))
|
if (EditorApplication.isPlaying && !string.IsNullOrEmpty(gameObject.scene.name))
|
||||||
{
|
{
|
||||||
return;
|
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)
|
if (!EditorApplication.isPlaying && EditorApplication.isPlayingOrWillChangePlaymode)
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get a global object identifier for this network prefab
|
// Get a global object identifier for this network prefab.
|
||||||
var globalId = GetGlobalId();
|
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)
|
if (globalId.identifierType == k_NullObjectType)
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
@@ -159,47 +265,34 @@ namespace Unity.Netcode
|
|||||||
var oldValue = GlobalObjectIdHash;
|
var oldValue = GlobalObjectIdHash;
|
||||||
GlobalObjectIdHash = globalId.ToString().Hash32();
|
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)
|
if (GlobalObjectIdHash != oldValue)
|
||||||
{
|
{
|
||||||
// Check if this is an in-scnee placed NetworkObject (Special Case for In-Scene Placed)
|
// 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)
|
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)
|
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**");
|
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))
|
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);
|
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);
|
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>
|
/// <summary>
|
||||||
@@ -210,13 +303,12 @@ namespace Unity.Netcode
|
|||||||
/// <remarks>
|
/// <remarks>
|
||||||
/// This NetworkObject is considered an in-scene placed prefab asset instance if it is:
|
/// This NetworkObject is considered an in-scene placed prefab asset instance if it is:
|
||||||
/// - Part of a prefab
|
/// - Part of a prefab
|
||||||
/// - Not being directly edited
|
|
||||||
/// - Within a valid scene that is part of the scenes in build list
|
/// - 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.)
|
/// (In-scene defined NetworkObjects that are not part of a prefab instance are excluded.)
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
private void CheckForInScenePlaced()
|
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 prefab = PrefabUtility.GetCorrespondingObjectFromSource(gameObject);
|
||||||
var assetPath = AssetDatabase.GetAssetPath(prefab);
|
var assetPath = AssetDatabase.GetAssetPath(prefab);
|
||||||
@@ -229,55 +321,6 @@ namespace Unity.Netcode
|
|||||||
IsSceneObject = true;
|
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
|
#endif // UNITY_EDITOR
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -396,6 +439,13 @@ namespace Unity.Netcode
|
|||||||
/// </remarks>
|
/// </remarks>
|
||||||
public bool IsOwnershipDistributable => Ownership.HasFlag(OwnershipStatus.Distributable);
|
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>
|
/// <summary>
|
||||||
/// Returns true if the <see cref="NetworkObject"/> is has ownership locked.
|
/// 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.
|
/// 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="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="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="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>
|
/// </summary>
|
||||||
// Ranges from 1 to 8 bits
|
// Ranges from 1 to 8 bits
|
||||||
[Flags]
|
[Flags]
|
||||||
@@ -448,6 +499,7 @@ namespace Unity.Netcode
|
|||||||
Distributable = 1 << 0,
|
Distributable = 1 << 0,
|
||||||
Transferable = 1 << 1,
|
Transferable = 1 << 1,
|
||||||
RequestRequired = 1 << 2,
|
RequestRequired = 1 << 2,
|
||||||
|
SessionOwner = 1 << 3,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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 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!");
|
NetworkLog.LogWarning($"Trying to add or remove ownership lock on [{name}] which does not have the {nameof(OwnershipStatus.Transferable)} flag set!");
|
||||||
return false;
|
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="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="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="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>
|
/// </summary>
|
||||||
public enum OwnershipPermissionsFailureStatus
|
public enum OwnershipPermissionsFailureStatus
|
||||||
{
|
{
|
||||||
Locked,
|
Locked,
|
||||||
RequestRequired,
|
RequestRequired,
|
||||||
RequestInProgress,
|
RequestInProgress,
|
||||||
NotTransferrable
|
NotTransferrable,
|
||||||
|
SessionOwnerOnly
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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="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="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="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.
|
/// a change in ownership or just try again after a specific period of time or no longer attempt to request ownership.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public enum OwnershipRequestStatus
|
public enum OwnershipRequestStatus
|
||||||
@@ -576,6 +631,7 @@ namespace Unity.Netcode
|
|||||||
RequestRequiredNotSet,
|
RequestRequiredNotSet,
|
||||||
Locked,
|
Locked,
|
||||||
RequestInProgress,
|
RequestInProgress,
|
||||||
|
SessionOwnerOnly,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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.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.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.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.
|
/// a change in ownership or just try again after a specific period of time or no longer attempt to request ownership.
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
/// <returns><see cref="OwnershipRequestStatus"/></returns>
|
/// <returns><see cref="OwnershipRequestStatus"/></returns>
|
||||||
@@ -617,6 +674,12 @@ namespace Unity.Netcode
|
|||||||
return OwnershipRequestStatus.RequestInProgress;
|
return OwnershipRequestStatus.RequestInProgress;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Exit early if it has the SessionOwner flag
|
||||||
|
if (IsOwnershipSessionOwner)
|
||||||
|
{
|
||||||
|
return OwnershipRequestStatus.SessionOwnerOnly;
|
||||||
|
}
|
||||||
|
|
||||||
// Otherwise, send the request ownership message
|
// Otherwise, send the request ownership message
|
||||||
var changeOwnership = new ChangeOwnershipMessage
|
var changeOwnership = new ChangeOwnershipMessage
|
||||||
{
|
{
|
||||||
@@ -673,7 +736,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
response = OwnershipRequestResponseStatus.RequestInProgress;
|
response = OwnershipRequestResponseStatus.RequestInProgress;
|
||||||
}
|
}
|
||||||
else if (!IsOwnershipRequestRequired && !IsOwnershipTransferable)
|
else if (!(IsOwnershipRequestRequired || IsOwnershipTransferable) || IsOwnershipSessionOwner)
|
||||||
{
|
{
|
||||||
response = OwnershipRequestResponseStatus.CannotRequest;
|
response = OwnershipRequestResponseStatus.CannotRequest;
|
||||||
}
|
}
|
||||||
@@ -793,6 +856,12 @@ namespace Unity.Netcode
|
|||||||
/// </remarks>
|
/// </remarks>
|
||||||
public bool SetOwnershipStatus(OwnershipStatus status, bool clearAndSet = false, OwnershipLockActions lockAction = OwnershipLockActions.None)
|
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 it already has the flag do nothing
|
||||||
if (!clearAndSet && Ownership.HasFlag(status))
|
if (!clearAndSet && Ownership.HasFlag(status))
|
||||||
{
|
{
|
||||||
@@ -804,6 +873,17 @@ namespace Unity.Netcode
|
|||||||
Ownership = OwnershipStatus.None;
|
Ownership = OwnershipStatus.None;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (status.HasFlag(OwnershipStatus.SessionOwner))
|
||||||
|
{
|
||||||
|
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
|
// Faster to just OR a None status than to check
|
||||||
// if it is !None before "OR'ing".
|
// if it is !None before "OR'ing".
|
||||||
Ownership |= status;
|
Ownership |= status;
|
||||||
@@ -812,6 +892,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
SetOwnershipLock(lockAction == OwnershipLockActions.SetAndLock);
|
SetOwnershipLock(lockAction == OwnershipLockActions.SetAndLock);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
SendOwnershipStatusUpdate();
|
SendOwnershipStatusUpdate();
|
||||||
|
|
||||||
@@ -1586,7 +1667,7 @@ namespace Unity.Netcode
|
|||||||
// DANGO-TODO: Review over don't destroy with owner being set but DistributeOwnership not being set
|
// DANGO-TODO: Review over don't destroy with owner being set but DistributeOwnership not being set
|
||||||
if (NetworkManager.LogLevel == LogLevel.Developer)
|
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)
|
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;
|
m_CachedWorldPositionStays = worldPositionStays;
|
||||||
@@ -2892,7 +2975,7 @@ namespace Unity.Netcode
|
|||||||
SyncObservers = syncObservers,
|
SyncObservers = syncObservers,
|
||||||
Observers = syncObservers ? Observers.ToArray() : null,
|
Observers = syncObservers ? Observers.ToArray() : null,
|
||||||
NetworkSceneHandle = NetworkSceneHandle,
|
NetworkSceneHandle = NetworkSceneHandle,
|
||||||
Hash = HostCheckForGlobalObjectIdHashOverride(),
|
Hash = CheckForGlobalObjectIdHashOverride(),
|
||||||
OwnerObject = this,
|
OwnerObject = this,
|
||||||
TargetClientId = targetClientId
|
TargetClientId = targetClientId
|
||||||
};
|
};
|
||||||
@@ -3244,14 +3327,15 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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.
|
/// Will return the registered source NetworkPrefab's GlobalObjectIdHash if one exists.
|
||||||
/// Server and Clients will always return the NetworkObject's GlobalObjectIdHash.
|
/// Server and Clients will always return the NetworkObject's GlobalObjectIdHash.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns>appropriate hash value</returns>
|
||||||
internal uint HostCheckForGlobalObjectIdHashOverride()
|
internal uint CheckForGlobalObjectIdHashOverride()
|
||||||
{
|
{
|
||||||
if (NetworkManager.IsServer)
|
if (NetworkManager.IsServer || NetworkManager.DistributedAuthorityMode)
|
||||||
{
|
{
|
||||||
if (NetworkManager.PrefabHandler.ContainsHandler(this))
|
if (NetworkManager.PrefabHandler.ContainsHandler(this))
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -294,7 +294,7 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Handle the
|
/// Handle the extended distributed authority ownership updates
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="context"></param>
|
/// <param name="context"></param>
|
||||||
private void HandleExtendedOwnershipUpdate(ref NetworkContext context)
|
private void HandleExtendedOwnershipUpdate(ref NetworkContext context)
|
||||||
@@ -332,8 +332,8 @@ namespace Unity.Netcode
|
|||||||
// Sanity check that we are not sending duplicated change ownership messages
|
// Sanity check that we are not sending duplicated change ownership messages
|
||||||
if (networkObject.OwnerClientId == OwnerClientId)
|
if (networkObject.OwnerClientId == OwnerClientId)
|
||||||
{
|
{
|
||||||
UnityEngine.Debug.LogError($"Unnecessary ownership changed message for {NetworkObjectId}.");
|
// Log error and then ignore the message
|
||||||
// Ignore the message
|
UnityEngine.Debug.LogError($"Client-{context.SenderId} ({RequestClientId}) sent unnecessary ownership changed message for {NetworkObjectId}.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -55,19 +55,24 @@ namespace Unity.Netcode
|
|||||||
// Don't redistribute for the local instance
|
// Don't redistribute for the local instance
|
||||||
if (ClientId != networkManager.LocalClientId)
|
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:
|
// Show any NetworkObjects that are:
|
||||||
// - Hidden from the session owner
|
// - Hidden from the session owner
|
||||||
// - Owned by this client
|
// - Owned by this client
|
||||||
// - Has NetworkObject.SpawnWithObservers set to true (the default)
|
// - Has NetworkObject.SpawnWithObservers set to true (the default)
|
||||||
if (!networkManager.LocalClient.IsSessionOwner)
|
//if (!networkManager.LocalClient.IsSessionOwner)
|
||||||
{
|
//{
|
||||||
networkManager.SpawnManager.ShowHiddenObjectsToNewlyJoinedClient(ClientId);
|
// networkManager.SpawnManager.ShowHiddenObjectsToNewlyJoinedClient(ClientId);
|
||||||
}
|
//}
|
||||||
|
|
||||||
// We defer redistribution to the end of the NetworkUpdateStage.PostLateUpdate
|
/// We defer redistribution to happen after NetworkShow has been invoked
|
||||||
networkManager.RedistributeToClient = true;
|
/// <see cref="NetworkBehaviourUpdater.NetworkBehaviourUpdater_Tick"/>
|
||||||
networkManager.ClientToRedistribute = ClientId;
|
/// DANGO-TODO: Determine if this needs to be removed once the service handles object distribution
|
||||||
networkManager.TickToRedistribute = networkManager.ServerTime.Tick + 20;
|
networkManager.RedistributeToClients = true;
|
||||||
|
networkManager.ClientsToRedistribute.Add(ClientId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,23 +5,38 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
internal struct ServiceConfig : INetworkSerializable
|
internal struct ServiceConfig : INetworkSerializable
|
||||||
{
|
{
|
||||||
public uint Version;
|
public uint SessionVersion;
|
||||||
public bool IsRestoredSession;
|
public bool IsRestoredSession;
|
||||||
public ulong CurrentSessionOwner;
|
public ulong CurrentSessionOwner;
|
||||||
|
public bool ServerRedistribution;
|
||||||
|
|
||||||
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
|
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
|
||||||
{
|
{
|
||||||
if (serializer.IsWriter)
|
if (serializer.IsWriter)
|
||||||
{
|
{
|
||||||
BytePacker.WriteValueBitPacked(serializer.GetFastBufferWriter(), Version);
|
BytePacker.WriteValueBitPacked(serializer.GetFastBufferWriter(), SessionVersion);
|
||||||
serializer.SerializeValue(ref IsRestoredSession);
|
serializer.SerializeValue(ref IsRestoredSession);
|
||||||
BytePacker.WriteValueBitPacked(serializer.GetFastBufferWriter(), CurrentSessionOwner);
|
BytePacker.WriteValueBitPacked(serializer.GetFastBufferWriter(), CurrentSessionOwner);
|
||||||
|
|
||||||
|
if (SessionVersion >= SessionConfig.ServerDistributionCompatible)
|
||||||
|
{
|
||||||
|
serializer.SerializeValue(ref ServerRedistribution);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
ByteUnpacker.ReadValueBitPacked(serializer.GetFastBufferReader(), out Version);
|
ByteUnpacker.ReadValueBitPacked(serializer.GetFastBufferReader(), out SessionVersion);
|
||||||
serializer.SerializeValue(ref IsRestoredSession);
|
serializer.SerializeValue(ref IsRestoredSession);
|
||||||
ByteUnpacker.ReadValueBitPacked(serializer.GetFastBufferReader(), out CurrentSessionOwner);
|
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)
|
if (receivedMessageVersion >= k_AddCMBServiceConfig)
|
||||||
{
|
{
|
||||||
reader.ReadNetworkSerializable(out ServiceConfig);
|
reader.ReadNetworkSerializable(out ServiceConfig);
|
||||||
|
networkManager.SessionConfig = new SessionConfig(ServiceConfig);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
reader.ReadValueSafe(out IsRestoredSession);
|
reader.ReadValueSafe(out IsRestoredSession);
|
||||||
ByteUnpacker.ReadValueBitPacked(reader, out CurrentSessionOwner);
|
ByteUnpacker.ReadValueBitPacked(reader, out CurrentSessionOwner);
|
||||||
|
networkManager.SessionConfig = new SessionConfig(SessionConfig.NoFeatureCompatibility);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,31 +7,28 @@ namespace Unity.Netcode
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal struct ClientConfig : INetworkSerializable
|
internal struct ClientConfig : INetworkSerializable
|
||||||
{
|
{
|
||||||
/// <summary>
|
public SessionConfig SessionConfig;
|
||||||
/// We start at version 1, where anything less than version 1 on the service side
|
public int SessionVersion => (int)SessionConfig.SessionVersion;
|
||||||
/// is not bypass feature compatible.
|
|
||||||
/// </summary>
|
|
||||||
private const int k_BypassFeatureCompatible = 1;
|
|
||||||
public int Version => k_BypassFeatureCompatible;
|
|
||||||
public uint TickRate;
|
public uint TickRate;
|
||||||
public bool EnableSceneManagement;
|
public bool EnableSceneManagement;
|
||||||
|
|
||||||
// Only gets deserialized but should never be used unless testing
|
// 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
|
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
|
||||||
{
|
{
|
||||||
|
// Clients always write
|
||||||
if (serializer.IsWriter)
|
if (serializer.IsWriter)
|
||||||
{
|
{
|
||||||
var writer = serializer.GetFastBufferWriter();
|
var writer = serializer.GetFastBufferWriter();
|
||||||
BytePacker.WriteValueBitPacked(writer, Version);
|
BytePacker.WriteValueBitPacked(writer, SessionVersion);
|
||||||
BytePacker.WriteValueBitPacked(writer, TickRate);
|
BytePacker.WriteValueBitPacked(writer, TickRate);
|
||||||
writer.WriteValueSafe(EnableSceneManagement);
|
writer.WriteValueSafe(EnableSceneManagement);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
var reader = serializer.GetFastBufferReader();
|
var reader = serializer.GetFastBufferReader();
|
||||||
ByteUnpacker.ReadValueBitPacked(reader, out RemoteClientVersion);
|
ByteUnpacker.ReadValueBitPacked(reader, out RemoteClientSessionVersion);
|
||||||
ByteUnpacker.ReadValueBitPacked(reader, out TickRate);
|
ByteUnpacker.ReadValueBitPacked(reader, out TickRate);
|
||||||
reader.ReadValueSafe(out EnableSceneManagement);
|
reader.ReadValueSafe(out EnableSceneManagement);
|
||||||
}
|
}
|
||||||
@@ -40,6 +37,8 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
internal struct ConnectionRequestMessage : INetworkMessage
|
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
|
// This version update is unidirectional (client to service) and version
|
||||||
// handling occurs on the service side. This serialized data is never sent
|
// handling occurs on the service side. This serialized data is never sent
|
||||||
// to a host or server.
|
// to a host or server.
|
||||||
@@ -47,7 +46,7 @@ namespace Unity.Netcode
|
|||||||
public int Version => k_SendClientConfigToService;
|
public int Version => k_SendClientConfigToService;
|
||||||
|
|
||||||
public ulong ConfigHash;
|
public ulong ConfigHash;
|
||||||
public bool CMBServiceConnection;
|
public bool DistributedAuthority;
|
||||||
public ClientConfig ClientConfig;
|
public ClientConfig ClientConfig;
|
||||||
|
|
||||||
public byte[] ConnectionData;
|
public byte[] ConnectionData;
|
||||||
@@ -72,7 +71,7 @@ namespace Unity.Netcode
|
|||||||
// END FORBIDDEN SEGMENT
|
// END FORBIDDEN SEGMENT
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
if (CMBServiceConnection)
|
if (DistributedAuthority)
|
||||||
{
|
{
|
||||||
writer.WriteNetworkSerializable(ClientConfig);
|
writer.WriteNetworkSerializable(ClientConfig);
|
||||||
}
|
}
|
||||||
@@ -120,6 +119,11 @@ namespace Unity.Netcode
|
|||||||
// END FORBIDDEN SEGMENT
|
// END FORBIDDEN SEGMENT
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
|
if (networkManager.DAHost)
|
||||||
|
{
|
||||||
|
reader.ReadNetworkSerializable(out ClientConfig);
|
||||||
|
}
|
||||||
|
|
||||||
if (networkManager.NetworkConfig.ConnectionApproval)
|
if (networkManager.NetworkConfig.ConnectionApproval)
|
||||||
{
|
{
|
||||||
if (!reader.TryBeginRead(FastBufferWriter.GetWriteSize(ConfigHash) + FastBufferWriter.GetWriteSize<int>()))
|
if (!reader.TryBeginRead(FastBufferWriter.GetWriteSize(ConfigHash) + FastBufferWriter.GetWriteSize<int>()))
|
||||||
@@ -182,6 +186,17 @@ namespace Unity.Netcode
|
|||||||
var networkManager = (NetworkManager)context.SystemOwner;
|
var networkManager = (NetworkManager)context.SystemOwner;
|
||||||
var senderId = context.SenderId;
|
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))
|
if (networkManager.ConnectionManager.PendingClients.TryGetValue(senderId, out PendingClient client))
|
||||||
{
|
{
|
||||||
// Set to pending approval to prevent future connection requests from being approved
|
// Set to pending approval to prevent future connection requests from being approved
|
||||||
|
|||||||
@@ -70,10 +70,6 @@ namespace Unity.Netcode
|
|||||||
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
|
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
|
||||||
{
|
{
|
||||||
var networkManager = (NetworkManager)context.SystemOwner;
|
var networkManager = (NetworkManager)context.SystemOwner;
|
||||||
if (!networkManager.IsClient)
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
ByteUnpacker.ReadValueBitPacked(reader, out NetworkObjectId);
|
ByteUnpacker.ReadValueBitPacked(reader, out NetworkObjectId);
|
||||||
reader.ReadValueSafe(out m_BitField);
|
reader.ReadValueSafe(out m_BitField);
|
||||||
|
|||||||
@@ -141,28 +141,6 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
RegisterMessageType(type);
|
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)
|
catch (Exception)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -17,7 +17,8 @@ namespace Unity.Netcode
|
|||||||
// ClientsAndHost sends to everyone who runs any client logic
|
// 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)
|
// 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 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;
|
m_UnderlyingTarget = behaviour.RpcTarget.Everyone;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,12 +4,14 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
private IGroupRpcTarget m_GroupSendTarget;
|
private IGroupRpcTarget m_GroupSendTarget;
|
||||||
private ServerRpcTarget m_ServerRpcTarget;
|
private ServerRpcTarget m_ServerRpcTarget;
|
||||||
|
private NotAuthorityRpcTarget m_NotAuthorityRpcTarget;
|
||||||
private LocalSendRpcTarget m_LocalSendRpcTarget;
|
private LocalSendRpcTarget m_LocalSendRpcTarget;
|
||||||
|
|
||||||
public override void Dispose()
|
public override void Dispose()
|
||||||
{
|
{
|
||||||
m_ServerRpcTarget.Dispose();
|
m_ServerRpcTarget.Dispose();
|
||||||
m_LocalSendRpcTarget.Dispose();
|
m_LocalSendRpcTarget.Dispose();
|
||||||
|
m_NotAuthorityRpcTarget.Dispose();
|
||||||
if (m_GroupSendTarget != null)
|
if (m_GroupSendTarget != null)
|
||||||
{
|
{
|
||||||
m_GroupSendTarget.Target.Dispose();
|
m_GroupSendTarget.Target.Dispose();
|
||||||
@@ -19,6 +21,13 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
|
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 (m_GroupSendTarget == null)
|
||||||
{
|
{
|
||||||
if (behaviour.IsServer)
|
if (behaviour.IsServer)
|
||||||
@@ -86,6 +95,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
m_ServerRpcTarget = new ServerRpcTarget(manager);
|
m_ServerRpcTarget = new ServerRpcTarget(manager);
|
||||||
m_LocalSendRpcTarget = new LocalSendRpcTarget(manager);
|
m_LocalSendRpcTarget = new LocalSendRpcTarget(manager);
|
||||||
|
m_NotAuthorityRpcTarget = new NotAuthorityRpcTarget(manager);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,7 +51,13 @@ namespace Unity.Netcode
|
|||||||
continue;
|
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);
|
m_LocalSendRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||||
continue;
|
continue;
|
||||||
|
|||||||
@@ -5,9 +5,12 @@ namespace Unity.Netcode
|
|||||||
private IIndividualRpcTarget m_UnderlyingTarget;
|
private IIndividualRpcTarget m_UnderlyingTarget;
|
||||||
private LocalSendRpcTarget m_LocalRpcTarget;
|
private LocalSendRpcTarget m_LocalRpcTarget;
|
||||||
private ServerRpcTarget m_ServerRpcTarget;
|
private ServerRpcTarget m_ServerRpcTarget;
|
||||||
|
private AuthorityRpcTarget m_AuthorityRpcTarget;
|
||||||
|
|
||||||
public override void Dispose()
|
public override void Dispose()
|
||||||
{
|
{
|
||||||
|
m_AuthorityRpcTarget.Dispose();
|
||||||
|
m_ServerRpcTarget.Dispose();
|
||||||
m_LocalRpcTarget.Dispose();
|
m_LocalRpcTarget.Dispose();
|
||||||
if (m_UnderlyingTarget != null)
|
if (m_UnderlyingTarget != null)
|
||||||
{
|
{
|
||||||
@@ -18,6 +21,13 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
|
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)
|
if (behaviour.OwnerClientId == behaviour.NetworkManager.LocalClientId)
|
||||||
{
|
{
|
||||||
m_LocalRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
m_LocalRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||||
@@ -49,6 +59,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
m_LocalRpcTarget = new LocalSendRpcTarget(manager);
|
m_LocalRpcTarget = new LocalSendRpcTarget(manager);
|
||||||
m_ServerRpcTarget = new ServerRpcTarget(manager);
|
m_ServerRpcTarget = new ServerRpcTarget(manager);
|
||||||
|
m_AuthorityRpcTarget = new AuthorityRpcTarget(manager);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,9 +79,28 @@ namespace Unity.Netcode
|
|||||||
SpecifiedInParams
|
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
|
public enum RpcTargetUse
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Creates a temporary <see cref="BaseRpcTarget"/> used for the frame an <see cref="RpcAttribute"/> decorated method is invoked.
|
||||||
|
/// </summary>
|
||||||
Temp,
|
Temp,
|
||||||
|
/// <summary>
|
||||||
|
/// Creates a persisted <see cref="BaseRpcTarget"/> that does not change and will persist until <see cref="BaseRpcTarget.Dispose"/> is called.
|
||||||
|
/// </summary>
|
||||||
Persistent
|
Persistent
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
|
using Unity.Collections;
|
||||||
namespace Unity.Netcode
|
namespace Unity.Netcode
|
||||||
{
|
{
|
||||||
internal class ServerRpcTarget : BaseRpcTarget
|
internal class ServerRpcTarget : BaseRpcTarget
|
||||||
{
|
{
|
||||||
protected BaseRpcTarget m_UnderlyingTarget;
|
protected BaseRpcTarget m_UnderlyingTarget;
|
||||||
|
protected ProxyRpcTarget m_ProxyRpcTarget;
|
||||||
|
|
||||||
public override void Dispose()
|
public override void Dispose()
|
||||||
{
|
{
|
||||||
@@ -11,13 +13,62 @@ namespace Unity.Netcode
|
|||||||
m_UnderlyingTarget.Dispose();
|
m_UnderlyingTarget.Dispose();
|
||||||
m_UnderlyingTarget = null;
|
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)
|
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)
|
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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,6 @@ namespace Unity.Netcode
|
|||||||
/// The callback to be invoked when the list gets changed
|
/// The callback to be invoked when the list gets changed
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public event OnListChangedDelegate OnListChanged;
|
public event OnListChangedDelegate OnListChanged;
|
||||||
internal override NetworkVariableType Type => NetworkVariableType.NetworkList;
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Constructor method for <see cref="NetworkList"/>
|
/// Constructor method for <see cref="NetworkList"/>
|
||||||
@@ -50,6 +49,11 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
~NetworkList()
|
||||||
|
{
|
||||||
|
Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public override void ResetDirty()
|
public override void ResetDirty()
|
||||||
{
|
{
|
||||||
@@ -131,20 +135,6 @@ namespace Unity.Netcode
|
|||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public override void WriteField(FastBufferWriter writer)
|
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);
|
writer.WriteValueSafe((ushort)m_List.Length);
|
||||||
for (int i = 0; i < m_List.Length; i++)
|
for (int i = 0; i < m_List.Length; i++)
|
||||||
{
|
{
|
||||||
@@ -156,15 +146,6 @@ namespace Unity.Netcode
|
|||||||
public override void ReadField(FastBufferReader reader)
|
public override void ReadField(FastBufferReader reader)
|
||||||
{
|
{
|
||||||
m_List.Clear();
|
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);
|
reader.ReadValueSafe(out ushort count);
|
||||||
for (int i = 0; i < count; i++)
|
for (int i = 0; i < count; i++)
|
||||||
{
|
{
|
||||||
@@ -623,9 +604,17 @@ namespace Unity.Netcode
|
|||||||
/// you **must** always invoke the base.Dispose() method!
|
/// you **must** always invoke the base.Dispose() method!
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public override void Dispose()
|
public override void Dispose()
|
||||||
|
{
|
||||||
|
if (m_List.IsCreated)
|
||||||
{
|
{
|
||||||
m_List.Dispose();
|
m_List.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (m_DirtyEvents.IsCreated)
|
||||||
|
{
|
||||||
m_DirtyEvents.Dispose();
|
m_DirtyEvents.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
base.Dispose();
|
base.Dispose();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,8 +45,6 @@ namespace Unity.Netcode
|
|||||||
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_PreviousValue);
|
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_PreviousValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
internal override NetworkVariableType Type => NetworkVariableType.Value;
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Constructor for <see cref="NetworkVariable{T}"/>
|
/// Constructor for <see cref="NetworkVariable{T}"/>
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -181,19 +179,26 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
m_IsDisposed = true;
|
m_IsDisposed = true;
|
||||||
|
// Dispose the internal value
|
||||||
if (m_InternalValue is IDisposable internalValueDisposable)
|
if (m_InternalValue is IDisposable internalValueDisposable)
|
||||||
{
|
{
|
||||||
internalValueDisposable.Dispose();
|
internalValueDisposable.Dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
m_InternalValue = default;
|
m_InternalValue = default;
|
||||||
|
|
||||||
|
// Dispose the internal original value
|
||||||
|
if (m_InternalOriginalValue is IDisposable internalOriginalValueDisposable)
|
||||||
|
{
|
||||||
|
internalOriginalValueDisposable.Dispose();
|
||||||
|
}
|
||||||
m_InternalOriginalValue = default;
|
m_InternalOriginalValue = default;
|
||||||
|
|
||||||
|
// Dispose the previous value if there is one
|
||||||
if (m_HasPreviousValue && m_PreviousValue is IDisposable previousValueDisposable)
|
if (m_HasPreviousValue && m_PreviousValue is IDisposable previousValueDisposable)
|
||||||
{
|
{
|
||||||
m_HasPreviousValue = false;
|
m_HasPreviousValue = false;
|
||||||
previousValueDisposable.Dispose();
|
previousValueDisposable.Dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
m_PreviousValue = default;
|
m_PreviousValue = default;
|
||||||
|
|
||||||
base.Dispose();
|
base.Dispose();
|
||||||
|
|||||||
@@ -35,8 +35,6 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
private NetworkManager m_InternalNetworkManager;
|
private NetworkManager m_InternalNetworkManager;
|
||||||
|
|
||||||
internal virtual NetworkVariableType Type => NetworkVariableType.Unknown;
|
|
||||||
|
|
||||||
internal string GetWritePermissionError()
|
internal string GetWritePermissionError()
|
||||||
{
|
{
|
||||||
return $"|Client-{m_NetworkManager.LocalClientId}|{m_NetworkBehaviour.name}|{Name}| Write permissions ({WritePerm}) for this client instance is not allowed!";
|
return $"|Client-{m_NetworkManager.LocalClientId}|{m_NetworkBehaviour.name}|{Name}| Write permissions ({WritePerm}) for this client instance is not allowed!";
|
||||||
|
|||||||
@@ -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,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
fileFormatVersion: 2
|
|
||||||
guid: df4a4005f1c842669f94a404019400ed
|
|
||||||
timeCreated: 1718292058
|
|
||||||
@@ -14,9 +14,6 @@ namespace Unity.Netcode
|
|||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
internal class FallbackSerializer<T> : INetworkVariableSerializer<T>
|
internal class FallbackSerializer<T> : INetworkVariableSerializer<T>
|
||||||
{
|
{
|
||||||
public NetworkVariableType Type => NetworkVariableType.Unknown;
|
|
||||||
public bool IsDistributedAuthorityOptimized => true;
|
|
||||||
|
|
||||||
private void ThrowArgumentError()
|
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}.");
|
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);
|
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`
|
// RuntimeAccessModifiersILPP will make this `public`
|
||||||
|
|||||||
@@ -2,28 +2,8 @@ using Unity.Collections;
|
|||||||
|
|
||||||
namespace Unity.Netcode
|
namespace Unity.Netcode
|
||||||
{
|
{
|
||||||
/// <summary>
|
|
||||||
/// Interface used by NetworkVariables to serialize them with additional information for the DA runtime
|
|
||||||
/// </summary>
|
|
||||||
///
|
|
||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
internal interface IDistributedAuthoritySerializer<T>
|
internal interface INetworkVariableSerializer<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>
|
|
||||||
{
|
{
|
||||||
// Write has to be taken by ref here because of INetworkSerializable
|
// Write has to be taken by ref here because of INetworkSerializable
|
||||||
// Open Instance Delegates (pointers to methods without an instance attached to them)
|
// Open Instance Delegates (pointers to methods without an instance attached to them)
|
||||||
|
|||||||
@@ -14,8 +14,6 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
internal static INetworkVariableSerializer<T> Serializer = new FallbackSerializer<T>();
|
internal static INetworkVariableSerializer<T> Serializer = new FallbackSerializer<T>();
|
||||||
|
|
||||||
internal static bool IsDistributedAuthority => NetworkManager.IsDistributedAuthority;
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// A callback to check if two values are equal.
|
/// A callback to check if two values are equal.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -52,22 +50,9 @@ namespace Unity.Netcode
|
|||||||
/// <param name="writer"></param>
|
/// <param name="writer"></param>
|
||||||
/// <param name="value"></param>
|
/// <param name="value"></param>
|
||||||
public static void Write(FastBufferWriter writer, ref T value)
|
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>
|
/// <summary>
|
||||||
/// Deserialize a value using the best-known serialization method for a generic value.
|
/// Deserialize a value using the best-known serialization method for a generic value.
|
||||||
@@ -90,16 +75,9 @@ namespace Unity.Netcode
|
|||||||
/// <param name="reader"></param>
|
/// <param name="reader"></param>
|
||||||
/// <param name="value"></param>
|
/// <param name="value"></param>
|
||||||
public static void Read(FastBufferReader reader, ref T value)
|
public static void Read(FastBufferReader reader, ref T value)
|
||||||
{
|
|
||||||
if (IsDistributedAuthority)
|
|
||||||
{
|
|
||||||
Serializer.ReadDistributedAuthority(reader, ref value);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
{
|
||||||
Serializer.Read(reader, ref value);
|
Serializer.Read(reader, ref value);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Serialize a value using the best-known serialization method for a generic value.
|
/// Serialize a value using the best-known serialization method for a generic value.
|
||||||
@@ -119,22 +97,9 @@ namespace Unity.Netcode
|
|||||||
/// <param name="writer"></param>
|
/// <param name="writer"></param>
|
||||||
/// <param name="value"></param>
|
/// <param name="value"></param>
|
||||||
public static void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue)
|
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>
|
/// <summary>
|
||||||
/// Deserialize a value using the best-known serialization method for a generic value.
|
/// Deserialize a value using the best-known serialization method for a generic value.
|
||||||
@@ -157,16 +122,9 @@ namespace Unity.Netcode
|
|||||||
/// <param name="reader"></param>
|
/// <param name="reader"></param>
|
||||||
/// <param name="value"></param>
|
/// <param name="value"></param>
|
||||||
public static void ReadDelta(FastBufferReader reader, ref T value)
|
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>
|
/// <summary>
|
||||||
/// Duplicates a value using the most efficient means of creating a complete copy.
|
/// Duplicates a value using the most efficient means of creating a complete copy.
|
||||||
|
|||||||
@@ -10,21 +10,6 @@ namespace Unity.Netcode
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal class ShortSerializer : INetworkVariableSerializer<short>
|
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)
|
public void Write(FastBufferWriter writer, ref short value)
|
||||||
{
|
{
|
||||||
BytePacker.WriteValueBitPacked(writer, value);
|
BytePacker.WriteValueBitPacked(writer, value);
|
||||||
@@ -61,20 +46,6 @@ namespace Unity.Netcode
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal class UshortSerializer : INetworkVariableSerializer<ushort>
|
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)
|
public void Write(FastBufferWriter writer, ref ushort value)
|
||||||
{
|
{
|
||||||
BytePacker.WriteValueBitPacked(writer, value);
|
BytePacker.WriteValueBitPacked(writer, value);
|
||||||
@@ -111,20 +82,6 @@ namespace Unity.Netcode
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal class IntSerializer : INetworkVariableSerializer<int>
|
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)
|
public void Write(FastBufferWriter writer, ref int value)
|
||||||
{
|
{
|
||||||
BytePacker.WriteValueBitPacked(writer, value);
|
BytePacker.WriteValueBitPacked(writer, value);
|
||||||
@@ -161,20 +118,6 @@ namespace Unity.Netcode
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal class UintSerializer : INetworkVariableSerializer<uint>
|
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)
|
public void Write(FastBufferWriter writer, ref uint value)
|
||||||
{
|
{
|
||||||
BytePacker.WriteValueBitPacked(writer, value);
|
BytePacker.WriteValueBitPacked(writer, value);
|
||||||
@@ -211,20 +154,6 @@ namespace Unity.Netcode
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal class LongSerializer : INetworkVariableSerializer<long>
|
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)
|
public void Write(FastBufferWriter writer, ref long value)
|
||||||
{
|
{
|
||||||
BytePacker.WriteValueBitPacked(writer, value);
|
BytePacker.WriteValueBitPacked(writer, value);
|
||||||
@@ -261,21 +190,6 @@ namespace Unity.Netcode
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal class UlongSerializer : INetworkVariableSerializer<ulong>
|
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)
|
public void Write(FastBufferWriter writer, ref ulong value)
|
||||||
{
|
{
|
||||||
BytePacker.WriteValueBitPacked(writer, value);
|
BytePacker.WriteValueBitPacked(writer, value);
|
||||||
@@ -317,21 +231,6 @@ namespace Unity.Netcode
|
|||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
internal class UnmanagedTypeSerializer<T> : INetworkVariableSerializer<T> where T : unmanaged
|
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)
|
public void Write(FastBufferWriter writer, ref T value)
|
||||||
{
|
{
|
||||||
writer.WriteUnmanagedSafe(value);
|
writer.WriteUnmanagedSafe(value);
|
||||||
@@ -365,20 +264,6 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
internal class ListSerializer<T> : INetworkVariableSerializer<List<T>>
|
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)
|
public void Write(FastBufferWriter writer, ref List<T> value)
|
||||||
{
|
{
|
||||||
var isNull = value == null;
|
var isNull = value == null;
|
||||||
@@ -468,20 +353,6 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
internal class HashSetSerializer<T> : INetworkVariableSerializer<HashSet<T>> where T : IEquatable<T>
|
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)
|
public void Write(FastBufferWriter writer, ref HashSet<T> value)
|
||||||
{
|
{
|
||||||
var isNull = value == null;
|
var isNull = value == null;
|
||||||
@@ -563,20 +434,6 @@ namespace Unity.Netcode
|
|||||||
internal class DictionarySerializer<TKey, TVal> : INetworkVariableSerializer<Dictionary<TKey, TVal>>
|
internal class DictionarySerializer<TKey, TVal> : INetworkVariableSerializer<Dictionary<TKey, TVal>>
|
||||||
where TKey : IEquatable<TKey>
|
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)
|
public void Write(FastBufferWriter writer, ref Dictionary<TKey, TVal> value)
|
||||||
{
|
{
|
||||||
var isNull = value == null;
|
var isNull = value == null;
|
||||||
@@ -659,20 +516,6 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
internal class UnmanagedArraySerializer<T> : INetworkVariableSerializer<NativeArray<T>> where T : unmanaged
|
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)
|
public void Write(FastBufferWriter writer, ref NativeArray<T> value)
|
||||||
{
|
{
|
||||||
writer.WriteUnmanagedSafe(value);
|
writer.WriteUnmanagedSafe(value);
|
||||||
@@ -718,20 +561,6 @@ namespace Unity.Netcode
|
|||||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||||
internal class UnmanagedListSerializer<T> : INetworkVariableSerializer<NativeList<T>> where T : unmanaged
|
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)
|
public void Write(FastBufferWriter writer, ref NativeList<T> value)
|
||||||
{
|
{
|
||||||
writer.WriteUnmanagedSafe(value);
|
writer.WriteUnmanagedSafe(value);
|
||||||
@@ -775,21 +604,6 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
internal class NativeHashSetSerializer<T> : INetworkVariableSerializer<NativeHashSet<T>> where T : unmanaged, IEquatable<T>
|
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)
|
public void Write(FastBufferWriter writer, ref NativeHashSet<T> value)
|
||||||
{
|
{
|
||||||
writer.WriteValueSafe(value);
|
writer.WriteValueSafe(value);
|
||||||
@@ -835,21 +649,6 @@ namespace Unity.Netcode
|
|||||||
where TKey : unmanaged, IEquatable<TKey>
|
where TKey : unmanaged, IEquatable<TKey>
|
||||||
where TVal : unmanaged
|
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)
|
public void Write(FastBufferWriter writer, ref NativeHashMap<TKey, TVal> value)
|
||||||
{
|
{
|
||||||
writer.WriteValueSafe(value);
|
writer.WriteValueSafe(value);
|
||||||
@@ -897,21 +696,6 @@ namespace Unity.Netcode
|
|||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
internal class FixedStringSerializer<T> : INetworkVariableSerializer<T> where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
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)
|
public void Write(FastBufferWriter writer, ref T value)
|
||||||
{
|
{
|
||||||
writer.WriteValueSafe(value);
|
writer.WriteValueSafe(value);
|
||||||
@@ -1019,20 +803,6 @@ namespace Unity.Netcode
|
|||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
internal class FixedStringArraySerializer<T> : INetworkVariableSerializer<NativeArray<T>> where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
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)
|
public void Write(FastBufferWriter writer, ref NativeArray<T> value)
|
||||||
{
|
{
|
||||||
writer.WriteValueSafe(value);
|
writer.WriteValueSafe(value);
|
||||||
@@ -1083,21 +853,6 @@ namespace Unity.Netcode
|
|||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
internal class FixedStringListSerializer<T> : INetworkVariableSerializer<NativeList<T>> where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
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)
|
public void Write(FastBufferWriter writer, ref NativeList<T> value)
|
||||||
{
|
{
|
||||||
writer.WriteValueSafe(value);
|
writer.WriteValueSafe(value);
|
||||||
@@ -1145,21 +900,6 @@ namespace Unity.Netcode
|
|||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
internal class UnmanagedNetworkSerializableSerializer<T> : INetworkVariableSerializer<T> where T : unmanaged, INetworkSerializable
|
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)
|
public void Write(FastBufferWriter writer, ref T value)
|
||||||
{
|
{
|
||||||
var bufferSerializer = new BufferSerializer<BufferSerializerWriter>(new BufferSerializerWriter(writer));
|
var bufferSerializer = new BufferSerializer<BufferSerializerWriter>(new BufferSerializerWriter(writer));
|
||||||
@@ -1212,20 +952,6 @@ namespace Unity.Netcode
|
|||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
internal class UnmanagedNetworkSerializableArraySerializer<T> : INetworkVariableSerializer<NativeArray<T>> where T : unmanaged, INetworkSerializable
|
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)
|
public void Write(FastBufferWriter writer, ref NativeArray<T> value)
|
||||||
{
|
{
|
||||||
writer.WriteNetworkSerializable(value);
|
writer.WriteNetworkSerializable(value);
|
||||||
@@ -1276,21 +1002,6 @@ namespace Unity.Netcode
|
|||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
internal class UnmanagedNetworkSerializableListSerializer<T> : INetworkVariableSerializer<NativeList<T>> where T : unmanaged, INetworkSerializable
|
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)
|
public void Write(FastBufferWriter writer, ref NativeList<T> value)
|
||||||
{
|
{
|
||||||
writer.WriteNetworkSerializable(value);
|
writer.WriteNetworkSerializable(value);
|
||||||
@@ -1338,20 +1049,6 @@ namespace Unity.Netcode
|
|||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
internal class ManagedNetworkSerializableSerializer<T> : INetworkVariableSerializer<T> where T : class, INetworkSerializable, new()
|
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)
|
public void Write(FastBufferWriter writer, ref T value)
|
||||||
{
|
{
|
||||||
var bufferSerializer = new BufferSerializer<BufferSerializerWriter>(new BufferSerializerWriter(writer));
|
var bufferSerializer = new BufferSerializer<BufferSerializerWriter>(new BufferSerializerWriter(writer));
|
||||||
|
|||||||
@@ -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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
fileFormatVersion: 2
|
|
||||||
guid: 52a4ce368df54b0a8887c08f3402bcd3
|
|
||||||
timeCreated: 1718300602
|
|
||||||
@@ -1081,14 +1081,19 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
// 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)
|
||||||
|
{
|
||||||
|
sceneEvent.TargetClientId = clientId;
|
||||||
var message = new SceneEventMessage
|
var message = new SceneEventMessage
|
||||||
{
|
{
|
||||||
EventData = sceneEvent,
|
EventData = sceneEvent,
|
||||||
};
|
};
|
||||||
var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, targetClientIds);
|
var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, clientId);
|
||||||
NetworkManager.NetworkMetrics.TrackSceneEventSent(targetClientIds, (uint)SceneEventDataStore[sceneEventId].SceneEventType, SceneNameFromHash(SceneEventDataStore[sceneEventId].SceneHash), size);
|
NetworkManager.NetworkMetrics.TrackSceneEventSent(clientId, (uint)sceneEvent.SceneEventType, SceneNameFromHash(sceneEvent.SceneHash), size);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -1898,10 +1903,12 @@ namespace Unity.Netcode
|
|||||||
SendSceneEventData(sceneEventData.SceneEventId, NetworkManager.ConnectedClientsIds.Where(c => c != sessionOwner).ToArray());
|
SendSceneEventData(sceneEventData.SceneEventId, NetworkManager.ConnectedClientsIds.Where(c => c != sessionOwner).ToArray());
|
||||||
|
|
||||||
m_IsSceneEventActive = false;
|
m_IsSceneEventActive = false;
|
||||||
|
|
||||||
|
sceneEventData.SceneEventType = SceneEventType.LoadComplete;
|
||||||
//First, notify local server that the scene was loaded
|
//First, notify local server that the scene was loaded
|
||||||
OnSceneEvent?.Invoke(new SceneEvent()
|
OnSceneEvent?.Invoke(new SceneEvent()
|
||||||
{
|
{
|
||||||
SceneEventType = SceneEventType.LoadComplete,
|
SceneEventType = sceneEventData.SceneEventType,
|
||||||
LoadSceneMode = sceneEventData.LoadSceneMode,
|
LoadSceneMode = sceneEventData.LoadSceneMode,
|
||||||
SceneName = SceneNameFromHash(sceneEventData.SceneHash),
|
SceneName = SceneNameFromHash(sceneEventData.SceneHash),
|
||||||
ClientId = NetworkManager.LocalClientId,
|
ClientId = NetworkManager.LocalClientId,
|
||||||
|
|||||||
@@ -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);
|
m_PlayerObjects.Add(playerObject);
|
||||||
if (!m_PlayerObjectsTable.ContainsKey(playerObject.OwnerClientId))
|
if (!m_PlayerObjectsTable.ContainsKey(playerObject.OwnerClientId))
|
||||||
{
|
{
|
||||||
@@ -110,8 +117,9 @@ namespace Unity.Netcode
|
|||||||
if (playerNetworkClient.PlayerObject != null && m_PlayerObjects.Contains(playerNetworkClient.PlayerObject))
|
if (playerNetworkClient.PlayerObject != null && m_PlayerObjects.Contains(playerNetworkClient.PlayerObject))
|
||||||
{
|
{
|
||||||
// Just remove the previous player object but keep the assigned observers of the NetworkObject
|
// 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
|
// Now update the associated NetworkClient's player object
|
||||||
NetworkManager.ConnectionManager.ConnectedClients[playerObject.OwnerClientId].AssignPlayerObject(ref playerObject);
|
NetworkManager.ConnectionManager.ConnectedClients[playerObject.OwnerClientId].AssignPlayerObject(ref playerObject);
|
||||||
AddPlayerObject(playerObject);
|
AddPlayerObject(playerObject);
|
||||||
@@ -120,7 +128,7 @@ namespace Unity.Netcode
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Removes a player object and updates all other players' observers list
|
/// Removes a player object and updates all other players' observers list
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private void RemovePlayerObject(NetworkObject playerObject, bool keepObservers = false)
|
private void RemovePlayerObject(NetworkObject playerObject, bool destroyingObject = false)
|
||||||
{
|
{
|
||||||
if (!playerObject.IsPlayerObject)
|
if (!playerObject.IsPlayerObject)
|
||||||
{
|
{
|
||||||
@@ -141,16 +149,21 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If we want to keep the observers, then exit early
|
if (NetworkManager.ConnectionManager.ConnectedClients.ContainsKey(playerObject.OwnerClientId) && destroyingObject)
|
||||||
if (keepObservers)
|
|
||||||
{
|
{
|
||||||
return;
|
NetworkManager.ConnectionManager.ConnectedClients[playerObject.OwnerClientId].PlayerObject = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach (var player in m_PlayerObjects)
|
// If we want to keep the observers, then exit early
|
||||||
{
|
//if (keepObservers)
|
||||||
player.Observers.Remove(playerObject.OwnerClientId);
|
//{
|
||||||
}
|
// return;
|
||||||
|
//}
|
||||||
|
|
||||||
|
//foreach (var player in m_PlayerObjects)
|
||||||
|
//{
|
||||||
|
// player.Observers.Remove(playerObject.OwnerClientId);
|
||||||
|
//}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal void MarkObjectForShowingTo(NetworkObject networkObject, ulong clientId)
|
internal void MarkObjectForShowingTo(NetworkObject networkObject, ulong clientId)
|
||||||
@@ -409,28 +422,9 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
if (NetworkManager.DistributedAuthorityMode && !NetworkManager.ShutdownInProgress)
|
if (NetworkManager.DistributedAuthorityMode && !NetworkManager.ShutdownInProgress)
|
||||||
{
|
{
|
||||||
if (networkObject.IsOwnershipDistributable || networkObject.IsOwnershipTransferable)
|
Debug.LogError($"Removing ownership is invalid in Distributed Authority Mode. Use {nameof(ChangeOwnership)} instead.");
|
||||||
{
|
|
||||||
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;
|
return;
|
||||||
}
|
}
|
||||||
else
|
|
||||||
{
|
|
||||||
NetworkLog.LogError($"Only the owner is allowed to remove ownership in distributed authority mode!");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
if (!NetworkManager.DAHost)
|
|
||||||
{
|
|
||||||
Debug.LogError($"Only {nameof(NetworkObject)}s with {nameof(NetworkObject.IsOwnershipDistributable)} or {nameof(NetworkObject.IsOwnershipTransferable)} set can perform ownership changes!");
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ChangeOwnership(networkObject, NetworkManager.ServerClientId, true);
|
ChangeOwnership(networkObject, NetworkManager.ServerClientId, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -461,6 +455,18 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
if (NetworkManager.DistributedAuthorityMode)
|
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 are not authorized and this is not an approved ownership change, then check to see if we can change ownership
|
||||||
if (!isAuthorized && !isRequestApproval)
|
if (!isAuthorized && !isRequestApproval)
|
||||||
{
|
{
|
||||||
@@ -567,7 +573,6 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
networkObject.ChildNetworkBehaviours[i].UpdateNetworkProperties();
|
networkObject.ChildNetworkBehaviours[i].UpdateNetworkProperties();
|
||||||
}
|
}
|
||||||
|
|
||||||
size = NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, NetworkManager.ServerClientId);
|
size = NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, NetworkManager.ServerClientId);
|
||||||
NetworkManager.NetworkMetrics.TrackOwnershipChangeSent(NetworkManager.LocalClientId, networkObject, size);
|
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)
|
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;
|
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.
|
// - Host and clients always instantiate the override if one exists.
|
||||||
// In distributed authority mode, we alaways get the override
|
// - Server instantiates the original prefab unless:
|
||||||
if (forceOverride || NetworkManager.IsHost || NetworkManager.DistributedAuthorityMode)
|
// -- 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);
|
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)
|
if (networkObject == null)
|
||||||
{
|
{
|
||||||
Debug.LogError($"Failed to instantiate and spawn {networkPrefab.name}!");
|
Debug.LogError($"Failed to instantiate and spawn {networkPrefab.name}!");
|
||||||
@@ -738,7 +751,15 @@ namespace Unity.Netcode
|
|||||||
networkObject.IsPlayerObject = isPlayerObject;
|
networkObject.IsPlayerObject = isPlayerObject;
|
||||||
networkObject.transform.position = position;
|
networkObject.transform.position = position;
|
||||||
networkObject.transform.rotation = rotation;
|
networkObject.transform.rotation = rotation;
|
||||||
|
// If spawning as a player, then invoke SpawnAsPlayerObject
|
||||||
|
if (isPlayerObject)
|
||||||
|
{
|
||||||
|
networkObject.SpawnAsPlayerObject(ownerClientId, destroyWithScene);
|
||||||
|
}
|
||||||
|
else // Otherwise just spawn with ownership
|
||||||
|
{
|
||||||
networkObject.SpawnWithOwnership(ownerClientId, destroyWithScene);
|
networkObject.SpawnWithOwnership(ownerClientId, destroyWithScene);
|
||||||
|
}
|
||||||
return networkObject;
|
return networkObject;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -804,13 +825,34 @@ namespace Unity.Netcode
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Create prefab instance while applying any pre-assigned position and rotation values
|
// Create prefab instance while applying any pre-assigned position and rotation values
|
||||||
networkObject = UnityEngine.Object.Instantiate(networkPrefabReference).GetComponent<NetworkObject>();
|
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.position = position ?? networkObject.transform.position;
|
||||||
networkObject.transform.rotation = rotation ?? networkObject.transform.rotation;
|
networkObject.transform.rotation = rotation ?? networkObject.transform.rotation;
|
||||||
networkObject.NetworkManagerOwner = NetworkManager;
|
networkObject.NetworkManagerOwner = NetworkManager;
|
||||||
networkObject.PrefabGlobalObjectIdHash = globalObjectIdHash;
|
networkObject.PrefabGlobalObjectIdHash = prefabGlobalObjectIdHash;
|
||||||
}
|
|
||||||
}
|
|
||||||
return networkObject;
|
return networkObject;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1098,6 +1140,12 @@ namespace Unity.Netcode
|
|||||||
// then add all connected clients as observers
|
// then add all connected clients as observers
|
||||||
if (!NetworkManager.DistributedAuthorityMode && NetworkManager.IsServer && networkObject.SpawnWithObservers)
|
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
|
// Add client observers
|
||||||
for (int i = 0; i < NetworkManager.ConnectedClientsIds.Count; i++)
|
for (int i = 0; i < NetworkManager.ConnectedClientsIds.Count; i++)
|
||||||
{
|
{
|
||||||
@@ -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
|
// Notify all in-scene placed NetworkObjects have been spawned
|
||||||
foreach (var networkObject in networkObjectsToSpawn)
|
foreach (var networkObject in networkObjectsToSpawn)
|
||||||
{
|
{
|
||||||
@@ -1550,23 +1607,9 @@ namespace Unity.Netcode
|
|||||||
SpawnedObjectsList.Remove(networkObject);
|
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)
|
if (networkObject.IsPlayerObject)
|
||||||
{
|
{
|
||||||
RemovePlayerObject(networkObject);
|
RemovePlayerObject(networkObject, destroyGameObject);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Always clear out the observers list when despawned
|
// Always clear out the observers list when despawned
|
||||||
@@ -1705,6 +1748,11 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList)
|
foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList)
|
||||||
{
|
{
|
||||||
|
if (networkObject.IsOwnershipSessionOwner)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if (networkObject.IsOwnershipDistributable && !networkObject.IsOwnershipLocked)
|
if (networkObject.IsOwnershipDistributable && !networkObject.IsOwnershipLocked)
|
||||||
{
|
{
|
||||||
if (networkObject.transform.parent != null)
|
if (networkObject.transform.parent != null)
|
||||||
@@ -1715,17 +1763,15 @@ namespace Unity.Netcode
|
|||||||
continue;
|
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);
|
||||||
}
|
}
|
||||||
|
objectTypeCount[globalOjectIdHash] += 1;
|
||||||
if (!objectTypeCount.ContainsKey(networkObject.GlobalObjectIdHash))
|
|
||||||
{
|
|
||||||
objectTypeCount.Add(networkObject.GlobalObjectIdHash, 0);
|
|
||||||
}
|
|
||||||
objectTypeCount[networkObject.GlobalObjectIdHash] += 1;
|
|
||||||
|
|
||||||
// DANGO-TODO-MVP: Remove this once the service handles object distribution
|
// DANGO-TODO-MVP: Remove this once the service handles object distribution
|
||||||
if (onlyIncludeOwnedObjects && !networkObject.IsOwner)
|
if (onlyIncludeOwnedObjects && !networkObject.IsOwner)
|
||||||
@@ -1733,30 +1779,38 @@ namespace Unity.Netcode
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Divide up by prefab type (GlobalObjectIdHash) to get a better distribution of object types
|
// 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
|
// 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
|
// 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)
|
internal void DistributeNetworkObjects(ulong clientId)
|
||||||
{
|
{
|
||||||
// Distributed authority mode ownership distribution
|
if (!NetworkManager.DistributedAuthorityMode)
|
||||||
// DANGO-TODO-MVP: Remove the session owner object distribution check once the service handles object distribution
|
|
||||||
if (NetworkManager.DistributedAuthorityMode && (NetworkManager.DAHost || NetworkManager.CMBServiceConnection))
|
|
||||||
{
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (NetworkManager.SessionConfig.ServiceSideDistribution)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
// DA-NGO CMB SERVICE NOTES:
|
// DA-NGO CMB SERVICE NOTES:
|
||||||
// The most basic object distribution should be broken up into a table of spawned object types
|
// 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
|
// where each type contains a list of each client's owned objects of that type that can be
|
||||||
@@ -1824,7 +1878,7 @@ namespace Unity.Netcode
|
|||||||
if ((i % offsetCount) == 0)
|
if ((i % offsetCount) == 0)
|
||||||
{
|
{
|
||||||
ChangeOwnership(ownerList.Value[i], clientId, true);
|
ChangeOwnership(ownerList.Value[i], clientId, true);
|
||||||
if (EnableDistributeLogging)
|
//if (EnableDistributeLogging)
|
||||||
{
|
{
|
||||||
Debug.Log($"[Client-{ownerList.Key}][NetworkObjectId-{ownerList.Value[i].NetworkObjectId} Distributed to Client-{clientId}");
|
Debug.Log($"[Client-{ownerList.Key}][NetworkObjectId-{ownerList.Value[i].NetworkObjectId} Distributed to Client-{clientId}");
|
||||||
}
|
}
|
||||||
@@ -1859,7 +1913,7 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
Debug.Log(builder.ToString());
|
Debug.Log(builder.ToString());
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
internal struct DeferredDespawnObject
|
internal struct DeferredDespawnObject
|
||||||
@@ -1969,14 +2023,14 @@ namespace Unity.Netcode
|
|||||||
/// synchronizing in order to "show" (spawn) anything that might be currently hidden from
|
/// synchronizing in order to "show" (spawn) anything that might be currently hidden from
|
||||||
/// the session owner.
|
/// the session owner.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Replacement is: SynchronizeObjectsToNewlyJoinedClient
|
||||||
|
/// </remarks>
|
||||||
internal void ShowHiddenObjectsToNewlyJoinedClient(ulong newClientId)
|
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 shutdown is in progress!");
|
||||||
{
|
|
||||||
Debug.LogWarning($"[Internal Error] {nameof(ShowHiddenObjectsToNewlyJoinedClient)} invoked while !");
|
|
||||||
}
|
|
||||||
return;
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -107,6 +107,45 @@ namespace Unity.Netcode
|
|||||||
/// /// <param name="networkManager">optionally pass in NetworkManager</param>
|
/// /// <param name="networkManager">optionally pass in NetworkManager</param>
|
||||||
public abstract void Initialize(NetworkManager networkManager = null);
|
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()
|
protected virtual NetworkTopologyTypes OnCurrentTopology()
|
||||||
{
|
{
|
||||||
return NetworkTopologyTypes.ClientServer;
|
return NetworkTopologyTypes.ClientServer;
|
||||||
|
|||||||
@@ -405,6 +405,7 @@ namespace Unity.Netcode.Transports.UTP
|
|||||||
|
|
||||||
#if UTP_TRANSPORT_2_0_ABOVE
|
#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)]
|
[Obsolete("DebugSimulator is no longer supported and has no effect. Use Network Simulator from the Multiplayer Tools package.", false)]
|
||||||
|
[HideInInspector]
|
||||||
#endif
|
#endif
|
||||||
public SimulatorParameters DebugSimulator = new SimulatorParameters
|
public SimulatorParameters DebugSimulator = new SimulatorParameters
|
||||||
{
|
{
|
||||||
@@ -944,17 +945,13 @@ namespace Unity.Netcode.Transports.UTP
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void Update()
|
/// <summary>
|
||||||
|
/// Handles accepting new connections and processing transport events.
|
||||||
|
/// </summary>
|
||||||
|
protected override void OnEarlyUpdate()
|
||||||
{
|
{
|
||||||
if (m_Driver.IsCreated)
|
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)
|
if (m_ProtocolType == ProtocolType.RelayUnityTransport && m_Driver.GetRelayConnectionStatus() == RelayConnectionStatus.AllocationInvalid)
|
||||||
{
|
{
|
||||||
Debug.LogError("Transport failure! Relay allocation needs to be recreated, and NetworkManager restarted. " +
|
Debug.LogError("Transport failure! Relay allocation needs to be recreated, and NetworkManager restarted. " +
|
||||||
@@ -964,15 +961,38 @@ namespace Unity.Netcode.Transports.UTP
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
m_Driver.ScheduleUpdate().Complete();
|
||||||
|
|
||||||
|
// Process any new connections
|
||||||
while (AcceptConnection() && m_Driver.IsCreated)
|
while (AcceptConnection() && m_Driver.IsCreated)
|
||||||
{
|
{
|
||||||
;
|
;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Process any transport events (i.e. connect, disconnect, data, etc)
|
||||||
while (ProcessEvent() && m_Driver.IsCreated)
|
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 MULTIPLAYER_TOOLS_1_0_0_PRE_7
|
||||||
if (m_NetworkManager)
|
if (m_NetworkManager)
|
||||||
@@ -981,6 +1001,7 @@ namespace Unity.Netcode.Transports.UTP
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
base.OnPostLateUpdate();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnDestroy()
|
private void OnDestroy()
|
||||||
@@ -1241,6 +1262,30 @@ namespace Unity.Netcode.Transports.UTP
|
|||||||
return (ulong)ExtractRtt(ParseClientId(clientId));
|
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>
|
/// <summary>
|
||||||
/// Initializes the transport
|
/// Initializes the transport
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -1450,8 +1495,18 @@ namespace Unity.Netcode.Transports.UTP
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public override void Shutdown()
|
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)
|
if (m_Driver.IsCreated)
|
||||||
{
|
{
|
||||||
|
while (ProcessEvent() && m_Driver.IsCreated)
|
||||||
|
{
|
||||||
|
;
|
||||||
|
}
|
||||||
|
|
||||||
// Flush all send queues to the network. NGO can be configured to flush its message
|
// 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
|
// queue on shutdown. But this only calls the Send() method, which doesn't actually
|
||||||
// get anything to the network.
|
// get anything to the network.
|
||||||
@@ -1469,6 +1524,7 @@ namespace Unity.Netcode.Transports.UTP
|
|||||||
DisposeInternals();
|
DisposeInternals();
|
||||||
|
|
||||||
m_ReliableReceiveQueues.Clear();
|
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
|
// We must reset this to zero because UTP actually re-uses clientIds if there is a clean disconnect
|
||||||
m_ServerClientId = 0;
|
m_ServerClientId = 0;
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
{
|
|
||||||
"displayName": "Bootstrap",
|
|
||||||
"description": "A lightweight sample to get started"
|
|
||||||
}
|
|
||||||
@@ -87,6 +87,8 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
|||||||
return new Vector3(Random.Range(min, max), Random.Range(min, max), Random.Range(min, max));
|
return new Vector3(Random.Range(min, max), Random.Range(min, max), Random.Range(min, max));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public IntegrationTestWithApproximation(NetworkTopologyTypes networkTopologyType, HostOrServer hostOrServer) : base(networkTopologyType, hostOrServer) { }
|
||||||
|
|
||||||
public IntegrationTestWithApproximation(NetworkTopologyTypes networkTopologyType) : base(networkTopologyType) { }
|
public IntegrationTestWithApproximation(NetworkTopologyTypes networkTopologyType) : base(networkTopologyType) { }
|
||||||
|
|
||||||
public IntegrationTestWithApproximation(HostOrServer hostOrServer) : base(hostOrServer) { }
|
public IntegrationTestWithApproximation(HostOrServer hostOrServer) : base(hostOrServer) { }
|
||||||
|
|||||||
@@ -1759,6 +1759,13 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
|||||||
m_DistributedAuthority = m_NetworkTopologyType == NetworkTopologyTypes.DistributedAuthority;
|
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>
|
/// <summary>
|
||||||
/// Optional Host or Server integration tests
|
/// Optional Host or Server integration tests
|
||||||
/// Constructor that allows you To break tests up as a host
|
/// Constructor that allows you To break tests up as a host
|
||||||
|
|||||||
@@ -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)
|
public static GameObject CreateNetworkObjectPrefab(string baseName, NetworkManager server, params NetworkManager[] clients)
|
||||||
{
|
{
|
||||||
void AddNetworkPrefab(NetworkConfig config, NetworkPrefab prefab)
|
void AddNetworkPrefab(NetworkConfig config, NetworkPrefab prefab)
|
||||||
@@ -570,13 +593,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
|||||||
Assert.IsNotNull(server, prefabCreateAssertError);
|
Assert.IsNotNull(server, prefabCreateAssertError);
|
||||||
Assert.IsFalse(server.IsListening, prefabCreateAssertError);
|
Assert.IsFalse(server.IsListening, prefabCreateAssertError);
|
||||||
|
|
||||||
var gameObject = new GameObject
|
var gameObject = CreateNetworkObject(baseName, server);
|
||||||
{
|
|
||||||
name = baseName
|
|
||||||
};
|
|
||||||
var networkObject = gameObject.AddComponent<NetworkObject>();
|
|
||||||
networkObject.NetworkManagerOwner = server;
|
|
||||||
MakeNetworkObjectTestPrefab(networkObject);
|
|
||||||
var networkPrefab = new NetworkPrefab() { Prefab = gameObject };
|
var networkPrefab = new NetworkPrefab() { Prefab = gameObject };
|
||||||
|
|
||||||
// We could refactor this test framework to share a NetworkPrefabList instance, but at this point it's
|
// We could refactor this test framework to share a NetworkPrefabList instance, but at this point it's
|
||||||
|
|||||||
@@ -205,13 +205,14 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
[UnityTest]
|
[UnityTest]
|
||||||
public IEnumerator NetworkVariableDelta()
|
public IEnumerator NetworkVariableDelta()
|
||||||
{
|
{
|
||||||
|
var component = Client.LocalClient.PlayerObject.GetComponent<TestNetworkComponent>();
|
||||||
var message = new NetworkVariableDeltaMessage
|
var message = new NetworkVariableDeltaMessage
|
||||||
{
|
{
|
||||||
NetworkObjectId = 0,
|
NetworkObjectId = Client.LocalClient.PlayerObject.NetworkObjectId,
|
||||||
NetworkBehaviourIndex = 1,
|
NetworkBehaviourIndex = component.NetworkBehaviourId,
|
||||||
DeliveryMappedNetworkVariableIndex = new HashSet<int> { 2, 3, 4 },
|
DeliveryMappedNetworkVariableIndex = new HashSet<int> { 0, 1 },
|
||||||
TargetClientId = 5,
|
TargetClientId = 5,
|
||||||
NetworkBehaviour = Client.LocalClient.PlayerObject.GetComponent<TestNetworkComponent>(),
|
NetworkBehaviour = component,
|
||||||
};
|
};
|
||||||
|
|
||||||
yield return SendMessage(ref message);
|
yield return SendMessage(ref message);
|
||||||
@@ -569,7 +570,7 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
|
|
||||||
private IEnumerator SendMessage<T>(ref T message) where T : INetworkMessage
|
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);
|
var clientIds = new NativeArray<ulong>(1, Allocator.Temp);
|
||||||
clientIds[0] = k_ClientId;
|
clientIds[0] = k_ClientId;
|
||||||
@@ -625,7 +626,8 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
var writer = new FastBufferWriter(1024, Allocator.Temp);
|
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;
|
var testName = TestContext.CurrentContext.Test.Name;
|
||||||
if (!m_ExpectedMessages.ContainsKey(testName))
|
if (!m_ExpectedMessages.ContainsKey(testName))
|
||||||
|
|||||||
@@ -216,6 +216,21 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
m_ErrorLogLevel2.Append($"[Client-{client.LocalClientId} Prefab Mismatch][Expected GlobalObjectIdHash: {expectedGlobalObjectIdHash} but was {remoteNetworkClient.PlayerObject.GlobalObjectIdHash}]");
|
m_ErrorLogLevel2.Append($"[Client-{client.LocalClientId} Prefab Mismatch][Expected GlobalObjectIdHash: {expectedGlobalObjectIdHash} but was {remoteNetworkClient.PlayerObject.GlobalObjectIdHash}]");
|
||||||
success = false;
|
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;
|
return success;
|
||||||
}
|
}
|
||||||
@@ -231,6 +246,12 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
m_ErrorLogLevel1.AppendLine($"[Client-{m_ServerNetworkManager.LocalClientId}]{m_ErrorLogLevel2}");
|
m_ErrorLogLevel1.AppendLine($"[Client-{m_ServerNetworkManager.LocalClientId}]{m_ErrorLogLevel2}");
|
||||||
success = false;
|
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)
|
foreach (var client in m_ClientNetworkManagers)
|
||||||
@@ -240,6 +261,17 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
m_ErrorLogLevel1.AppendLine($"[Client-{client.LocalClientId}]{m_ErrorLogLevel2}");
|
m_ErrorLogLevel1.AppendLine($"[Client-{client.LocalClientId}]{m_ErrorLogLevel2}");
|
||||||
success = false;
|
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;
|
return success;
|
||||||
@@ -250,12 +282,19 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
return m_PlayerPrefabs[Random.Range(0, m_PlayerPrefabs.Count() - 1)].GetComponent<NetworkObject>();
|
return m_PlayerPrefabs[Random.Range(0, m_PlayerPrefabs.Count() - 1)].GetComponent<NetworkObject>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public enum PlayerSpawnTypes
|
||||||
|
{
|
||||||
|
Normal,
|
||||||
|
NetworkObject,
|
||||||
|
SpawnManager
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Validates that when a client changes their player object that all connected client instances mirror the
|
/// Validates that when a client changes their player object that all connected client instances mirror the
|
||||||
/// client's new player object.
|
/// client's new player object.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[UnityTest]
|
[UnityTest]
|
||||||
public IEnumerator ValidatePlayerObjects()
|
public IEnumerator ValidatePlayerObjects([Values] PlayerSpawnTypes playerSpawnType)
|
||||||
{
|
{
|
||||||
// Just do a quick validation for all connected client's NetworkClients
|
// Just do a quick validation for all connected client's NetworkClients
|
||||||
yield return WaitForConditionOrTimeOut(AllNetworkClientsValidated);
|
yield return WaitForConditionOrTimeOut(AllNetworkClientsValidated);
|
||||||
@@ -268,14 +307,51 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
if (m_UseHost)
|
if (m_UseHost)
|
||||||
{
|
{
|
||||||
playerPrefabToSpawn = GetRandomPlayerPrefab();
|
playerPrefabToSpawn = GetRandomPlayerPrefab();
|
||||||
|
switch (playerSpawnType)
|
||||||
|
{
|
||||||
|
case PlayerSpawnTypes.Normal:
|
||||||
|
{
|
||||||
playerInstance = SpawnPlayerObject(playerPrefabToSpawn.gameObject, m_ServerNetworkManager);
|
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);
|
m_ChangedPlayerPrefabs.Add(m_ServerNetworkManager.LocalClientId, playerPrefabToSpawn.GlobalObjectIdHash);
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach (var client in m_ClientNetworkManagers)
|
foreach (var client in m_ClientNetworkManagers)
|
||||||
{
|
{
|
||||||
playerPrefabToSpawn = GetRandomPlayerPrefab();
|
playerPrefabToSpawn = GetRandomPlayerPrefab();
|
||||||
|
var networkManager = m_DistributedAuthority ? client : m_ServerNetworkManager;
|
||||||
|
|
||||||
|
switch (playerSpawnType)
|
||||||
|
{
|
||||||
|
case PlayerSpawnTypes.Normal:
|
||||||
|
{
|
||||||
playerInstance = SpawnPlayerObject(playerPrefabToSpawn.gameObject, client);
|
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);
|
m_ChangedPlayerPrefabs.Add(client.LocalClientId, playerPrefabToSpawn.GlobalObjectIdHash);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -128,7 +128,7 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
yield return WaitForConditionOrTimeOut(ValidateObjectSpawnedOnAllClients);
|
yield return WaitForConditionOrTimeOut(ValidateObjectSpawnedOnAllClients);
|
||||||
AssertOnTimeout($"[Failed To Spawn] {firstInstance.name}: \n {m_ErrorLog}");
|
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);
|
yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients);
|
||||||
AssertOnTimeout($"[Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}");
|
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)))
|
foreach (var permissionObject in Enum.GetValues(typeof(NetworkObject.OwnershipStatus)))
|
||||||
{
|
{
|
||||||
var permission = (NetworkObject.OwnershipStatus)permissionObject;
|
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
|
// Add the status
|
||||||
firstInstance.SetOwnershipStatus(permission);
|
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);
|
yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients);
|
||||||
AssertOnTimeout($"[Add][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}");
|
AssertOnTimeout($"[Add][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}");
|
||||||
|
|
||||||
@@ -153,7 +159,7 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
firstInstance.RemoveOwnershipStatus(permission);
|
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);
|
yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients);
|
||||||
AssertOnTimeout($"[Remove][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}");
|
AssertOnTimeout($"[Remove][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}");
|
||||||
}
|
}
|
||||||
@@ -163,7 +169,7 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
firstInstance.SetOwnershipStatus(multipleFlags, true);
|
firstInstance.SetOwnershipStatus(multipleFlags, true);
|
||||||
Assert.IsTrue(firstInstance.HasOwnershipStatus(multipleFlags), $"[Set][Multi-flag Failure] Expected: {(ushort)multipleFlags} but was {(ushort)firstInstance.Ownership}!");
|
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);
|
yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients);
|
||||||
AssertOnTimeout($"[Set Multiple][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}");
|
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
|
// 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}!");
|
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);
|
yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients);
|
||||||
AssertOnTimeout($"[Set Multiple][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}");
|
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.
|
// Clear the flags, set the permissions to transferrable, and lock ownership in one pass.
|
||||||
firstInstance.SetOwnershipStatus(NetworkObject.OwnershipStatus.Transferable, true, NetworkObject.OwnershipLockActions.SetAndLock);
|
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);
|
yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients);
|
||||||
AssertOnTimeout($"[Reset][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}");
|
AssertOnTimeout($"[Reset][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}");
|
||||||
|
|
||||||
@@ -199,7 +205,7 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
$" status is {secondInstanceHelper.OwnershipPermissionsFailureStatus}!");
|
$" status is {secondInstanceHelper.OwnershipPermissionsFailureStatus}!");
|
||||||
|
|
||||||
firstInstance.SetOwnershipLock(false);
|
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);
|
yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients);
|
||||||
AssertOnTimeout($"[Unlock][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}");
|
AssertOnTimeout($"[Unlock][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}");
|
||||||
|
|
||||||
@@ -208,7 +214,7 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
// Now try to acquire ownership
|
// Now try to acquire ownership
|
||||||
secondInstance.ChangeOwnership(m_ClientNetworkManagers[1].LocalClientId);
|
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);
|
yield return WaitForConditionOrTimeOut(() => secondInstance.IsOwner);
|
||||||
AssertOnTimeout($"[Acquire Ownership Failed] Client-{m_ClientNetworkManagers[1].LocalClientId} failed to get ownership!");
|
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.
|
// Clear the flags, set the permissions to RequestRequired, and lock ownership in one pass.
|
||||||
secondInstance.SetOwnershipStatus(NetworkObject.OwnershipStatus.RequestRequired, true);
|
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);
|
yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients);
|
||||||
AssertOnTimeout($"[Unlock][Permissions Mismatch] {secondInstance.name}: \n {m_ErrorLog}");
|
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
|
// Start with a request for the client we expect to be given ownership
|
||||||
var requestStatus = firstInstance.RequestOwnership();
|
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
|
// Get the 3rd client to send a request at the "relatively" same time
|
||||||
var thirdInstance = m_ClientNetworkManagers[2].SpawnManager.SpawnedObjects[networkObjectId];
|
var thirdInstance = m_ClientNetworkManagers[2].SpawnManager.SpawnedObjects[networkObjectId];
|
||||||
@@ -248,7 +254,7 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
requestStatus = thirdInstance.RequestOwnership();
|
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)
|
// 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
|
// We expect the first requesting client to be given ownership
|
||||||
yield return WaitForConditionOrTimeOut(() => firstInstance.IsOwner);
|
yield return WaitForConditionOrTimeOut(() => firstInstance.IsOwner);
|
||||||
@@ -263,7 +269,7 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
yield return WaitForConditionOrTimeOut(() => thirdInstanceHelper.OwnershipRequestResponseStatus == NetworkObject.OwnershipRequestResponseStatus.RequestInProgress);
|
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!");
|
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);
|
yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients);
|
||||||
AssertOnTimeout($"[Unlock][Permissions Mismatch] {firstInstance.name}: \n {m_ErrorLog}");
|
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
|
// Send out a request from three clients at the same time
|
||||||
// The first one sent (and received for this test) gets ownership
|
// The first one sent (and received for this test) gets ownership
|
||||||
requestStatus = secondInstance.RequestOwnership();
|
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();
|
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();
|
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
|
// The 2nd and 3rd client should be denied and the 4th client should be approved
|
||||||
yield return WaitForConditionOrTimeOut(() =>
|
yield return WaitForConditionOrTimeOut(() =>
|
||||||
@@ -296,7 +302,7 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
yield return WaitForConditionOrTimeOut(() => ValidateAllInstancesAreOwnedByClient(secondInstance.NetworkManager.LocalClientId));
|
yield return WaitForConditionOrTimeOut(() => ValidateAllInstancesAreOwnedByClient(secondInstance.NetworkManager.LocalClientId));
|
||||||
AssertOnTimeout($"[Ownership Mismatch] {secondInstance.name}: \n {m_ErrorLog}");
|
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);
|
yield return WaitForConditionOrTimeOut(ValidatePermissionsOnAllClients);
|
||||||
AssertOnTimeout($"[Unlock][Permissions Mismatch] {secondInstance.name}: \n {m_ErrorLog}");
|
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
|
// Send out a request from all three clients
|
||||||
requestStatus = firstInstance.RequestOwnership();
|
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();
|
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();
|
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();
|
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(() =>
|
yield return WaitForConditionOrTimeOut(() =>
|
||||||
(firstInstanceHelper.OwnershipRequestResponseStatus == NetworkObject.OwnershipRequestResponseStatus.Denied) &&
|
(firstInstanceHelper.OwnershipRequestResponseStatus == NetworkObject.OwnershipRequestResponseStatus.Denied) &&
|
||||||
(thirdInstanceHelper.OwnershipRequestResponseStatus == NetworkObject.OwnershipRequestResponseStatus.Denied) &&
|
(thirdInstanceHelper.OwnershipRequestResponseStatus == NetworkObject.OwnershipRequestResponseStatus.Denied) &&
|
||||||
(fourthInstanceHelper.OwnershipRequestResponseStatus == NetworkObject.OwnershipRequestResponseStatus.Denied) &&
|
(fourthInstanceHelper.OwnershipRequestResponseStatus == NetworkObject.OwnershipRequestResponseStatus.Denied) &&
|
||||||
(daHostInstanceHelper.OwnershipRequestResponseStatus == NetworkObject.OwnershipRequestResponseStatus.Approved)
|
(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
|
internal class OwnershipPermissionsTestHelper : NetworkBehaviour
|
||||||
|
|||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: 62913c78d28137141acc47ea8f63e657
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections;
|
using System.Collections;
|
||||||
using NUnit.Framework;
|
using NUnit.Framework;
|
||||||
|
using Unity.Netcode.TestHelpers.Runtime;
|
||||||
|
using Unity.Netcode.Transports.UTP;
|
||||||
|
using Unity.Networking.Transport;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
using UnityEngine.TestTools;
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
// Verifies that removing the ownership when the default (server) is already set does not cause a Key Not Found Exception
|
||||||
|
// Distributed authority does not allow remove ownership (users are instructed to use change ownership)
|
||||||
|
if (!m_DistributedAuthority)
|
||||||
|
{
|
||||||
m_ServerNetworkManager.SpawnManager.RemoveOwnership(m_OwnershipNetworkObject);
|
m_ServerNetworkManager.SpawnManager.RemoveOwnership(m_OwnershipNetworkObject);
|
||||||
|
}
|
||||||
|
|
||||||
var serverObject = m_ServerNetworkManager.SpawnManager.SpawnedObjects[ownershipNetworkObjectId];
|
var serverObject = m_ServerNetworkManager.SpawnManager.SpawnedObjects[ownershipNetworkObjectId];
|
||||||
var clientObject = m_ClientNetworkManagers[0].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!");
|
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
|
// Verifies that removing the ownership when the default (server) is already set does not cause a Key Not Found Exception
|
||||||
|
// Distributed authority does not allow remove ownership (users are instructed to use change ownership)
|
||||||
|
if (!m_DistributedAuthority)
|
||||||
|
{
|
||||||
m_ServerNetworkManager.SpawnManager.RemoveOwnership(m_OwnershipNetworkObject);
|
m_ServerNetworkManager.SpawnManager.RemoveOwnership(m_OwnershipNetworkObject);
|
||||||
|
}
|
||||||
|
|
||||||
var serverObject = m_ServerNetworkManager.SpawnManager.SpawnedObjects[ownershipNetworkObjectId];
|
var serverObject = m_ServerNetworkManager.SpawnManager.SpawnedObjects[ownershipNetworkObjectId];
|
||||||
Assert.That(serverObject, Is.Not.Null);
|
Assert.That(serverObject, Is.Not.Null);
|
||||||
var clientObject = (NetworkObject)null;
|
var clientObject = (NetworkObject)null;
|
||||||
|
|||||||
@@ -36,13 +36,25 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
{
|
{
|
||||||
VerifyObjectIsSpawnedOnClient.ResetObjectTable();
|
VerifyObjectIsSpawnedOnClient.ResetObjectTable();
|
||||||
m_ClientNetworkTransformPrefab = CreateNetworkObjectPrefab("OwnerAuthorityTest");
|
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>();
|
var clientNetworkTransform = m_ClientNetworkTransformPrefab.AddComponent<TestClientNetworkTransform>();
|
||||||
|
clientNetworkTransform.AuthorityMode = NetworkTransform.AuthorityModes.Owner;
|
||||||
clientNetworkTransform.Interpolate = false;
|
clientNetworkTransform.Interpolate = false;
|
||||||
clientNetworkTransform.UseHalfFloatPrecision = false;
|
clientNetworkTransform.UseHalfFloatPrecision = false;
|
||||||
var rigidBody = m_ClientNetworkTransformPrefab.AddComponent<Rigidbody>();
|
var rigidBody = m_ClientNetworkTransformPrefab.AddComponent<Rigidbody>();
|
||||||
rigidBody.useGravity = false;
|
rigidBody.useGravity = false;
|
||||||
|
rigidBody.maxDepenetrationVelocity = 0;
|
||||||
|
rigidBody.mass = 100;
|
||||||
|
rigidBody.linearDamping = 100;
|
||||||
rigidBody.interpolation = RigidbodyInterpolation.None;
|
rigidBody.interpolation = RigidbodyInterpolation.None;
|
||||||
rigidBody.maxLinearVelocity = 0;
|
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
|
// 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
|
// assure they don't collide and skew the results the NetworkObjects are already synchronized
|
||||||
// with skewed results
|
// with skewed results
|
||||||
@@ -51,11 +63,22 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
m_ClientNetworkTransformPrefab.AddComponent<VerifyObjectIsSpawnedOnClient>();
|
m_ClientNetworkTransformPrefab.AddComponent<VerifyObjectIsSpawnedOnClient>();
|
||||||
|
|
||||||
m_NetworkTransformPrefab = CreateNetworkObjectPrefab("ServerAuthorityTest");
|
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 = m_NetworkTransformPrefab.AddComponent<Rigidbody>();
|
||||||
rigidBody.useGravity = false;
|
rigidBody.useGravity = false;
|
||||||
|
rigidBody.maxDepenetrationVelocity = 0;
|
||||||
|
rigidBody.linearDamping = 100;
|
||||||
|
rigidBody.mass = 100;
|
||||||
rigidBody.interpolation = RigidbodyInterpolation.None;
|
rigidBody.interpolation = RigidbodyInterpolation.None;
|
||||||
rigidBody.maxLinearVelocity = 0;
|
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
|
// 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
|
// assure they don't collide and skew the results the NetworkObjects are already synchronized
|
||||||
// with skewed results
|
// with skewed results
|
||||||
@@ -276,10 +299,12 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
};
|
};
|
||||||
if (m_MotionModel == MotionModels.UseRigidbody)
|
if (m_MotionModel == MotionModels.UseRigidbody)
|
||||||
{
|
{
|
||||||
|
TestClientNetworkTransform.EnableLogState(m_EnableVerboseDebug);
|
||||||
var ownerRigidbody = ownerInstance.GetComponent<Rigidbody>();
|
var ownerRigidbody = ownerInstance.GetComponent<Rigidbody>();
|
||||||
ownerRigidbody.Move(valueSetByOwner, rotation);
|
ownerRigidbody.Move(valueSetByOwner, rotation);
|
||||||
|
yield return new WaitForFixedUpdate();
|
||||||
ownerRigidbody.linearVelocity = Vector3.zero;
|
ownerRigidbody.linearVelocity = Vector3.zero;
|
||||||
yield return s_DefaultWaitForTick;
|
yield return new WaitForFixedUpdate();
|
||||||
ownerInstance.transform.localScale = valueSetByOwner;
|
ownerInstance.transform.localScale = valueSetByOwner;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
@@ -312,15 +337,22 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
VerifyObjectIsSpawnedOnClient.ResetObjectTable();
|
VerifyObjectIsSpawnedOnClient.ResetObjectTable();
|
||||||
if (m_DistributedAuthority)
|
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
|
else
|
||||||
{
|
{
|
||||||
m_ServerNetworkManager.SpawnManager.ChangeOwnership(serverSideInstance.GetComponent<NetworkObject>(), networkManagerNonOwner.LocalClientId, true);
|
m_ServerNetworkManager.SpawnManager.ChangeOwnership(serverSideInstance.GetComponent<NetworkObject>(), networkManagerNonOwner.LocalClientId, true);
|
||||||
}
|
|
||||||
LogNonOwnerRigidBody(3);
|
LogNonOwnerRigidBody(3);
|
||||||
yield return WaitForConditionOrTimeOut(() => nonOwnerInstance.GetComponent<NetworkObject>().OwnerClientId == networkManagerNonOwner.LocalClientId);
|
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!");
|
Assert.False(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for {networkManagerNonOwner.name}'s object instance {nonOwnerInstance.name} to change ownership!");
|
||||||
|
}
|
||||||
|
|
||||||
LogNonOwnerRigidBody(4);
|
LogNonOwnerRigidBody(4);
|
||||||
// Re-assign the ownership references and wait for the non-owner instance to be notified of ownership change
|
// 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);
|
yield return WaitForConditionOrTimeOut(() => VerifyObjectIsSpawnedOnClient.GetClientInstance(networkManagerNonOwner.LocalClientId) != null);
|
||||||
nonOwnerInstance = VerifyObjectIsSpawnedOnClient.GetClientInstance(networkManagerNonOwner.LocalClientId);
|
nonOwnerInstance = VerifyObjectIsSpawnedOnClient.GetClientInstance(networkManagerNonOwner.LocalClientId);
|
||||||
Assert.NotNull(nonOwnerInstance);
|
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
|
// 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!");
|
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" +
|
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 Position: {valueSetByOwner} | Current Position: {transformToTest.position}\n" +
|
||||||
$"Expected Rotation: {valueSetByOwner} | Current Rotation: {transformToTest.rotation.eulerAngles}\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);
|
LogNonOwnerRigidBody(5);
|
||||||
// Have the new owner change transform values and wait for those values to be applied on the non-owner side.
|
// 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>();
|
var ownerRigidbody = ownerInstance.GetComponent<Rigidbody>();
|
||||||
ownerRigidbody.Move(valueSetByOwner, rotation);
|
ownerRigidbody.Move(valueSetByOwner, rotation);
|
||||||
LogOwnerRigidBody(2);
|
LogOwnerRigidBody(2);
|
||||||
|
yield return new WaitForFixedUpdate();
|
||||||
ownerInstance.GetComponent<NetworkTransform>().LogMotion = m_EnableVerboseDebug;
|
ownerInstance.GetComponent<NetworkTransform>().LogMotion = m_EnableVerboseDebug;
|
||||||
nonOwnerInstance.GetComponent<NetworkTransform>().LogMotion = m_EnableVerboseDebug;
|
nonOwnerInstance.GetComponent<NetworkTransform>().LogMotion = m_EnableVerboseDebug;
|
||||||
ownerRigidbody.linearVelocity = Vector3.zero;
|
ownerRigidbody.linearVelocity = Vector3.zero;
|
||||||
@@ -377,10 +411,11 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
LogOwnerRigidBody(4);
|
LogOwnerRigidBody(4);
|
||||||
LogNonOwnerRigidBody(7);
|
LogNonOwnerRigidBody(7);
|
||||||
}
|
}
|
||||||
|
|
||||||
Assert.False(s_GlobalTimeoutHelper.TimedOut, $"Timed out waiting for {networkManagerNonOwner.name}'s object instance {nonOwnerInstance.name} to change its transform!\n" +
|
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 Position: {valueSetByOwner} | Current Position: {transformToTest.position}\n" +
|
||||||
$"Expected Rotation: {valueSetByOwner} | Current Rotation: {transformToTest.rotation.eulerAngles}\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
|
// The last check is to verify non-owners cannot change transform values after ownership has changed
|
||||||
nonOwnerInstance.transform.position = Vector3.zero;
|
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}");
|
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>
|
/// <summary>
|
||||||
/// NetworkTransformOwnershipTests helper behaviour
|
/// NetworkTransformOwnershipTests helper behaviour
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -457,6 +498,10 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
NetworkManagerRelativeSpawnedObjects.Clear();
|
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()
|
public override void OnGainedOwnership()
|
||||||
{
|
{
|
||||||
if (!NetworkManagerRelativeSpawnedObjects.ContainsKey(NetworkManager.LocalClientId))
|
if (!NetworkManagerRelativeSpawnedObjects.ContainsKey(NetworkManager.LocalClientId))
|
||||||
@@ -466,6 +511,10 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
base.OnGainedOwnership();
|
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()
|
public override void OnLostOwnership()
|
||||||
{
|
{
|
||||||
if (!NetworkManagerRelativeSpawnedObjects.ContainsKey(NetworkManager.LocalClientId))
|
if (!NetworkManagerRelativeSpawnedObjects.ContainsKey(NetworkManager.LocalClientId))
|
||||||
@@ -515,28 +564,57 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
[DisallowMultipleComponent]
|
[DisallowMultipleComponent]
|
||||||
internal class TestClientNetworkTransform : NetworkTransform
|
internal class TestClientNetworkTransform : NetworkTransform
|
||||||
{
|
{
|
||||||
//public override void OnNetworkSpawn()
|
public static void EnableLogState(bool enable)
|
||||||
//{
|
|
||||||
// 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()
|
|
||||||
{
|
{
|
||||||
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1012,8 +1012,7 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Test]
|
[Test]
|
||||||
// Exceptions should be thrown in DA mode with UserNetworkVariableSerialization
|
public void TestUnsupportedManagedTypesWithUserSerializationDoNotThrowExceptions()
|
||||||
public void TestUnsupportedManagedTypesWithUserSerializationDoNotThrowExceptionsInClientServerMode()
|
|
||||||
{
|
{
|
||||||
var variable = new NetworkVariable<string>();
|
var variable = new NetworkVariable<string>();
|
||||||
UserNetworkVariableSerialization<string>.ReadValue = (FastBufferReader reader, out string value) =>
|
UserNetworkVariableSerialization<string>.ReadValue = (FastBufferReader reader, out string value) =>
|
||||||
@@ -1039,10 +1038,6 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
variable.ReadField(reader);
|
variable.ReadField(reader);
|
||||||
Assert.AreEqual("012345", variable.Value);
|
Assert.AreEqual("012345", variable.Value);
|
||||||
}
|
}
|
||||||
catch (Exception)
|
|
||||||
{
|
|
||||||
Assert.True(NetworkVariableSerialization<UserNetworkVariableSerialization<string>>.IsDistributedAuthority);
|
|
||||||
}
|
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
UserNetworkVariableSerialization<string>.ReadValue = null;
|
UserNetworkVariableSerialization<string>.ReadValue = null;
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
using System.Collections;
|
using System.Collections;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
using NUnit.Framework;
|
using NUnit.Framework;
|
||||||
using Unity.Netcode.TestHelpers.Runtime;
|
using Unity.Netcode.TestHelpers.Runtime;
|
||||||
using UnityEngine;
|
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}");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
fileFormatVersion: 2
|
fileFormatVersion: 2
|
||||||
guid: 2a43005be301c9043aab7034757d4868
|
guid: 83133d71f2112db45ba626157c46e7f8
|
||||||
TextScriptImporter:
|
folderAsset: yes
|
||||||
|
DefaultImporter:
|
||||||
externalObjects: {}
|
externalObjects: {}
|
||||||
userData:
|
userData:
|
||||||
assetBundleName:
|
assetBundleName:
|
||||||
@@ -85,9 +85,14 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
private const string k_PrefabObjectName = "NetworkPrefabHandlerTestObject";
|
private const string k_PrefabObjectName = "NetworkPrefabHandlerTestObject";
|
||||||
|
|
||||||
[Test]
|
[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;
|
var testPrefabObjectName = k_PrefabObjectName;
|
||||||
|
|
||||||
Guid baseObjectID = NetworkManagerHelper.AddGameNetworkObject(testPrefabObjectName);
|
Guid baseObjectID = NetworkManagerHelper.AddGameNetworkObject(testPrefabObjectName);
|
||||||
268
Tests/Runtime/Prefabs/NetworkPrefabOverrideTests.cs
Normal file
268
Tests/Runtime/Prefabs/NetworkPrefabOverrideTests.cs
Normal 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}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
2
Tests/Runtime/Prefabs/NetworkPrefabOverrideTests.cs.meta
Normal file
2
Tests/Runtime/Prefabs/NetworkPrefabOverrideTests.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: c5e27e24bc5f783458d6a45585308f87
|
||||||
@@ -33,7 +33,7 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
if (transport)
|
if (transport)
|
||||||
{
|
{
|
||||||
transport.Shutdown();
|
transport.Shutdown();
|
||||||
UnityEngine.Object.DestroyImmediate(transport);
|
UnityEngine.Object.DestroyImmediate(transport.gameObject);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,6 +42,7 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
transportEvents?.Clear();
|
transportEvents?.Clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
UnityTransportTestComponent.CleanUp();
|
||||||
yield return null;
|
yield return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,6 +60,7 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
Assert.False(m_Clients[0].StartClient(), "Client failed to detect invalid endpoint!");
|
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, $"Network listen address ({m_Server.ConnectionData.Address}) is Invalid!");
|
||||||
netcodeLogAssert.LogWasReceived(LogType.Error, $"Target server network address ({m_Clients[0].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.
|
// Check connection with a single client.
|
||||||
@@ -161,8 +163,6 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
// Check that all clients got a Disconnect event.
|
// Check that all clients got a Disconnect event.
|
||||||
Assert.True(m_ClientsEvents.All(evs => evs.Count == 2));
|
Assert.True(m_ClientsEvents.All(evs => evs.Count == 2));
|
||||||
Assert.True(m_ClientsEvents.All(evs => evs[1].Type == NetworkEvent.Disconnect));
|
Assert.True(m_ClientsEvents.All(evs => evs[1].Type == NetworkEvent.Disconnect));
|
||||||
|
|
||||||
yield return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check client disconnection from a single client.
|
// Check client disconnection from a single client.
|
||||||
@@ -188,13 +188,11 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
{
|
{
|
||||||
InitializeTransport(out m_Server, out m_ServerEvents);
|
InitializeTransport(out m_Server, out m_ServerEvents);
|
||||||
m_Server.StartServer();
|
m_Server.StartServer();
|
||||||
|
|
||||||
for (int i = 0; i < k_NumClients; i++)
|
for (int i = 0; i < k_NumClients; i++)
|
||||||
{
|
{
|
||||||
InitializeTransport(out m_Clients[i], out m_ClientsEvents[i]);
|
InitializeTransport(out m_Clients[i], out m_ClientsEvents[i]);
|
||||||
m_Clients[i].StartClient();
|
m_Clients[i].StartClient();
|
||||||
}
|
}
|
||||||
|
|
||||||
yield return WaitForNetworkEvent(NetworkEvent.Connect, m_ClientsEvents[k_NumClients - 1]);
|
yield return WaitForNetworkEvent(NetworkEvent.Connect, m_ClientsEvents[k_NumClients - 1]);
|
||||||
|
|
||||||
// Disconnect a single client.
|
// Disconnect a single client.
|
||||||
@@ -207,14 +205,11 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
{
|
{
|
||||||
m_Clients[i].DisconnectLocalClient();
|
m_Clients[i].DisconnectLocalClient();
|
||||||
}
|
}
|
||||||
|
|
||||||
yield return WaitForNetworkEvent(NetworkEvent.Disconnect, m_ServerEvents, 5);
|
yield return WaitForNetworkEvent(NetworkEvent.Disconnect, m_ServerEvents, 5);
|
||||||
|
|
||||||
// Check that we got the correct number of Disconnect events on the server.
|
// 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 * 2, m_ServerEvents.Count);
|
||||||
Assert.AreEqual(k_NumClients, m_ServerEvents.Count(e => e.Type == NetworkEvent.Disconnect));
|
Assert.AreEqual(k_NumClients, m_ServerEvents.Count(e => e.Type == NetworkEvent.Disconnect));
|
||||||
|
|
||||||
yield return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check that server re-disconnects are no-ops.
|
// 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.
|
// Check we haven't received anything else on the client or server.
|
||||||
Assert.AreEqual(m_ServerEvents.Count, previousServerEventsCount);
|
Assert.AreEqual(m_ServerEvents.Count, previousServerEventsCount);
|
||||||
Assert.AreEqual(m_ClientsEvents[0].Count, previousClientEventsCount);
|
Assert.AreEqual(m_ClientsEvents[0].Count, previousClientEventsCount);
|
||||||
|
|
||||||
yield return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check that client re-disconnects are no-ops.
|
// 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.
|
// Check we haven't received anything else on the client or server.
|
||||||
Assert.AreEqual(m_ServerEvents.Count, previousServerEventsCount);
|
Assert.AreEqual(m_ServerEvents.Count, previousServerEventsCount);
|
||||||
Assert.AreEqual(m_ClientsEvents[0].Count, previousClientEventsCount);
|
Assert.AreEqual(m_ClientsEvents[0].Count, previousClientEventsCount);
|
||||||
|
|
||||||
yield return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check connection with different server/listen addresses.
|
// Check connection with different server/listen addresses.
|
||||||
|
|||||||
@@ -36,6 +36,24 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
Assert.Fail("Timed out while waiting for network event.");
|
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.
|
// Common code to initialize a UnityTransport that logs its events.
|
||||||
public static void InitializeTransport(out UnityTransport transport, out List<TransportEvent> events,
|
public static void InitializeTransport(out UnityTransport transport, out List<TransportEvent> events,
|
||||||
int maxPayloadSize = UnityTransport.InitialMaxPayloadSize, int maxSendQueueSize = 0, NetworkFamily family = NetworkFamily.Ipv4)
|
int maxPayloadSize = UnityTransport.InitialMaxPayloadSize, int maxSendQueueSize = 0, NetworkFamily family = NetworkFamily.Ipv4)
|
||||||
@@ -43,7 +61,7 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
var logger = new TransportEventLogger();
|
var logger = new TransportEventLogger();
|
||||||
events = logger.Events;
|
events = logger.Events;
|
||||||
|
|
||||||
transport = new GameObject().AddComponent<UnityTransport>();
|
transport = new GameObject().AddComponent<UnityTransportTestComponent>();
|
||||||
|
|
||||||
transport.OnTransportEvent += logger.HandleEvent;
|
transport.OnTransportEvent += logger.HandleEvent;
|
||||||
transport.MaxPayloadSize = maxPayloadSize;
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -60,11 +60,11 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
// Need to destroy the GameObject (all assigned components will get destroyed too)
|
// Need to destroy the GameObject (all assigned components will get destroyed too)
|
||||||
UnityEngine.Object.DestroyImmediate(m_Client2.gameObject);
|
UnityEngine.Object.DestroyImmediate(m_Client2.gameObject);
|
||||||
}
|
}
|
||||||
|
|
||||||
m_ServerEvents?.Clear();
|
m_ServerEvents?.Clear();
|
||||||
m_Client1Events?.Clear();
|
m_Client1Events?.Clear();
|
||||||
m_Client2Events?.Clear();
|
m_Client2Events?.Clear();
|
||||||
|
|
||||||
|
UnityTransportTestComponent.CleanUp();
|
||||||
yield return null;
|
yield return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -217,8 +217,6 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
|
|
||||||
Assert.AreEqual(33, m_ServerEvents[3].Data.First());
|
Assert.AreEqual(33, m_ServerEvents[3].Data.First());
|
||||||
Assert.AreEqual(10, m_ServerEvents[3].Data.Count);
|
Assert.AreEqual(10, m_ServerEvents[3].Data.Count);
|
||||||
|
|
||||||
yield return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check sending data to multiple clients.
|
// Check sending data to multiple clients.
|
||||||
@@ -260,8 +258,6 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
byte c1Data = m_Client1Events[1].Data.First();
|
byte c1Data = m_Client1Events[1].Data.First();
|
||||||
byte c2Data = m_Client2Events[1].Data.First();
|
byte c2Data = m_Client2Events[1].Data.First();
|
||||||
Assert.That((c1Data == 11 && c2Data == 22) || (c1Data == 22 && c2Data == 11));
|
Assert.That((c1Data == 11 && c2Data == 22) || (c1Data == 22 && c2Data == 11));
|
||||||
|
|
||||||
yield return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check receiving data from multiple clients.
|
// Check receiving data from multiple clients.
|
||||||
@@ -299,8 +295,6 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
byte sData1 = m_ServerEvents[2].Data.First();
|
byte sData1 = m_ServerEvents[2].Data.First();
|
||||||
byte sData2 = m_ServerEvents[3].Data.First();
|
byte sData2 = m_ServerEvents[3].Data.First();
|
||||||
Assert.That((sData1 == 11 && sData2 == 22) || (sData1 == 22 && sData2 == 11));
|
Assert.That((sData1 == 11 && sData2 == 22) || (sData1 == 22 && sData2 == 11));
|
||||||
|
|
||||||
yield return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check that we get disconnected when overflowing the reliable send queue.
|
// 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(2, m_Client1Events.Count);
|
||||||
Assert.AreEqual(NetworkEvent.Disconnect, m_Client1Events[1].Type);
|
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).
|
// 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(NetworkEvent.Data, m_ServerEvents[i].Type);
|
||||||
Assert.AreEqual(1024, m_ServerEvents[i].Data.Count);
|
Assert.AreEqual(1024, m_ServerEvents[i].Data.Count);
|
||||||
}
|
}
|
||||||
|
|
||||||
yield return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#if !UTP_TRANSPORT_2_0_ABOVE
|
#if !UTP_TRANSPORT_2_0_ABOVE
|
||||||
@@ -451,8 +441,6 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
m_Client1.Shutdown();
|
m_Client1.Shutdown();
|
||||||
|
|
||||||
yield return WaitForNetworkEvent(NetworkEvent.Data, m_ServerEvents);
|
yield return WaitForNetworkEvent(NetworkEvent.Data, m_ServerEvents);
|
||||||
|
|
||||||
yield return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[UnityTest]
|
[UnityTest]
|
||||||
@@ -472,8 +460,6 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
m_Client1.DisconnectLocalClient();
|
m_Client1.DisconnectLocalClient();
|
||||||
|
|
||||||
yield return WaitForNetworkEvent(NetworkEvent.Data, m_ServerEvents);
|
yield return WaitForNetworkEvent(NetworkEvent.Data, m_ServerEvents);
|
||||||
|
|
||||||
yield return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[UnityTest]
|
[UnityTest]
|
||||||
@@ -493,8 +479,6 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
m_Server.DisconnectRemoteClient(m_ServerEvents[0].ClientID);
|
m_Server.DisconnectRemoteClient(m_ServerEvents[0].ClientID);
|
||||||
|
|
||||||
yield return WaitForNetworkEvent(NetworkEvent.Data, m_Client1Events);
|
yield return WaitForNetworkEvent(NetworkEvent.Data, m_Client1Events);
|
||||||
|
|
||||||
yield return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[UnityTest]
|
[UnityTest]
|
||||||
@@ -514,8 +498,47 @@ namespace Unity.Netcode.RuntimeTests
|
|||||||
m_Server.Send(m_Client1.ServerClientId, data, NetworkDelivery.Reliable);
|
m_Server.Send(m_Client1.ServerClientId, data, NetworkDelivery.Reliable);
|
||||||
|
|
||||||
yield return WaitForNetworkEvent(NetworkEvent.Data, m_Client1Events);
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
{
|
|
||||||
"ErrorExceptions": [],
|
|
||||||
"WarningExceptions": []
|
|
||||||
}
|
|
||||||
30
package.json
30
package.json
@@ -2,23 +2,11 @@
|
|||||||
"name": "com.unity.netcode.gameobjects",
|
"name": "com.unity.netcode.gameobjects",
|
||||||
"displayName": "Netcode for 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.",
|
"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",
|
"unity": "6000.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"com.unity.nuget.mono-cecil": "1.11.4",
|
"com.unity.nuget.mono-cecil": "1.11.4",
|
||||||
"com.unity.transport": "2.3.0"
|
"com.unity.transport": "2.4.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 owner’s previous value, causing the last added value to be detected as a change during additions or removals. (#3081)\n- Fixed issue where a client (or server) with no write permissions for a `NetworkVariable` using a standard .NET collection type could still modify the collection which could cause various issues depending upon the modification and collection type. (#3081)\n- Fixed issue where applying the position and/or rotation to the `NetworkManager.ConnectionApprovalResponse` when connection approval and auto-spawn player prefab were enabled would not apply the position and/or rotation when the player prefab was instantiated. (#3078)\n- Fixed issue where `NetworkObject.SpawnWithObservers` was not being honored when spawning the player prefab. (#3077)\n- Fixed issue with the client count not being correct on the host or server side when a client disconnects itself from a session. (#3075)\n\n### Changed\n\n- Changed `NetworkConfig.AutoSpawnPlayerPrefabClientSide` is no longer automatically set when starting `NetworkManager`. (#3097)\n- Updated `NetworkVariableDeltaMessage` so the server now forwards delta state updates from clients immediately, instead of waiting until the end of the frame or the next network tick. (#3081)"
|
|
||||||
},
|
|
||||||
"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"
|
|
||||||
},
|
},
|
||||||
"samples": [
|
"samples": [
|
||||||
{
|
{
|
||||||
@@ -26,5 +14,17 @@
|
|||||||
"description": "A lightweight sample to get started",
|
"description": "A lightweight sample to get started",
|
||||||
"path": "Samples~/Bootstrap"
|
"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"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user