com.unity.netcode.gameobjects@2.0.0-exp.2
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.0.0-exp.2] - 2024-04-02 ### Added - Added updates to all internal messages to account for a distributed authority network session connection. (#2863) - Added `NetworkRigidbodyBase` that provides users with a more customizable network rigidbody, handles both `Rigidbody` and `Rigidbody2D`, and provides an option to make `NetworkTransform` use the rigid body for motion. (#2863) - For a customized `NetworkRigidbodyBase` class: - `NetworkRigidbodyBase.AutoUpdateKinematicState` provides control on whether the kinematic setting will be automatically set or not when ownership changes. - `NetworkRigidbodyBase.AutoSetKinematicOnDespawn` provides control on whether isKinematic will automatically be set to true when the associated `NetworkObject` is despawned. - `NetworkRigidbodyBase.Initialize` is a protected method that, when invoked, will initialize the instance. This includes options to: - Set whether using a `RigidbodyTypes.Rigidbody` or `RigidbodyTypes.Rigidbody2D`. - Includes additional optional parameters to set the `NetworkTransform`, `Rigidbody`, and `Rigidbody2d` to use. - Provides additional public methods: - `NetworkRigidbodyBase.GetPosition` to return the position of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). - `NetworkRigidbodyBase.GetRotation` to return the rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). - `NetworkRigidbodyBase.MovePosition` to move to the position of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). - `NetworkRigidbodyBase.MoveRotation` to move to the rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). - `NetworkRigidbodyBase.Move` to move to the position and rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). - `NetworkRigidbodyBase.Move` to move to the position and rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). - `NetworkRigidbodyBase.SetPosition` to set the position of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). - `NetworkRigidbodyBase.SetRotation` to set the rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting). - `NetworkRigidbodyBase.ApplyCurrentTransform` to set the position and rotation of the `Rigidbody` or `Rigidbody2d` based on the associated `GameObject` transform (depending upon its initialized setting). - `NetworkRigidbodyBase.WakeIfSleeping` to wake up the rigid body if sleeping. - `NetworkRigidbodyBase.SleepRigidbody` to put the rigid body to sleep. - `NetworkRigidbodyBase.IsKinematic` to determine if the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting) is currently kinematic. - `NetworkRigidbodyBase.SetIsKinematic` to set the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting) current kinematic state. - `NetworkRigidbodyBase.ResetInterpolation` to reset the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting) back to its original interpolation value when initialized. - Now includes a `MonoBehaviour.FixedUpdate` implementation that will update the assigned `NetworkTransform` when `NetworkRigidbodyBase.UseRigidBodyForMotion` is true. (#2863) - Added `RigidbodyContactEventManager` that provides a more optimized way to process collision enter and collision stay events as opposed to the `Monobehaviour` approach. (#2863) - Can be used in client-server and distributed authority modes, but is particularly useful in distributed authority. - Added rigid body motion updates to `NetworkTransform` which allows users to set interolation on rigid bodies. (#2863) - Extrapolation is only allowed on authoritative instances, but custom class derived from `NetworkRigidbodyBase` or `NetworkRigidbody` or `NetworkRigidbody2D` automatically switches non-authoritative instances to interpolation if set to extrapolation. - Added distributed authority mode support to `NetworkAnimator`. (#2863) - Added session mode selection to `NetworkManager` inspector view. (#2863) - Added distributed authority permissions feature. (#2863) - Added distributed authority mode specific `NetworkObject` permissions flags (Distributable, Transferable, and RequestRequired). (#2863) - Added distributed authority mode specific `NetworkObject.SetOwnershipStatus` method that applies one or more `NetworkObject` instance's ownership flags. If updated when spawned, the ownership permission changes are synchronized with the other connected clients. (#2863) - Added distributed authority mode specific `NetworkObject.RemoveOwnershipStatus` method that removes one or more `NetworkObject` instance's ownership flags. If updated when spawned, the ownership permission changes are synchronized with the other connected clients. (#2863) - Added distributed authority mode specific `NetworkObject.HasOwnershipStatus` method that will return (true or false) whether one or more ownership flags is set. (#2863) - Added distributed authority mode specific `NetworkObject.SetOwnershipLock` method that locks ownership of a `NetworkObject` to prevent ownership from changing until the current owner releases the lock. (#2863) - Added distributed authority mode specific `NetworkObject.RequestOwnership` method that sends an ownership request to the current owner of a spawned `NetworkObject` instance. (#2863) - Added distributed authority mode specific `NetworkObject.OnOwnershipRequested` callback handler that is invoked on the owner/authoritative side when a non-owner requests ownership. Depending upon the boolean returned value depends upon whether the request is approved or denied. (#2863) - Added distributed authority mode specific `NetworkObject.OnOwnershipRequestResponse` callback handler that is invoked when a non-owner's request has been processed. This callback includes a `NetworkObjet.OwnershipRequestResponseStatus` response parameter that describes whether the request was approved or the reason why it was not approved. (#2863) - Added distributed authority mode specific `NetworkObject.DeferDespawn` method that defers the despawning of `NetworkObject` instances on non-authoritative clients based on the tick offset parameter. (#2863) - Added distributed authority mode specific `NetworkObject.OnDeferredDespawnComplete` callback handler that can be used to further control when deferring the despawning of a `NetworkObject` on non-authoritative instances. (#2863) - Added `NetworkClient.SessionModeType` as one way to determine the current session mode of the network session a client is connected to. (#2863) - Added distributed authority mode specific `NetworkClient.IsSessionOwner` property to determine if the current local client is the current session owner of a distributed authority session. (#2863) - Added distributed authority mode specific client side spawning capabilities. When running in distributed authority mode, clients can instantiate and spawn `NetworkObject` instances (the local client is authomatically the owner of the spawned object). (#2863) - This is useful to better visually synchronize owner authoritative motion models and newly spawned `NetworkObject` instances (i.e. projectiles for example). - Added distributed authority mode specific client side player spawning capabilities. Clients will automatically spawn their associated player object locally. (#2863) - Added distributed authority mode specific `NetworkConfig.AutoSpawnPlayerPrefabClientSide` property (default is true) to provide control over the automatic spawning of player prefabs on the local client side. (#2863) - Added distributed authority mode specific `NetworkManager.OnFetchLocalPlayerPrefabToSpawn` callback that, when assigned, will allow the local client to provide the player prefab to be spawned for the local client. (#2863) - This is only invoked if the `NetworkConfig.AutoSpawnPlayerPrefabClientSide` property is set to true. - Added distributed authority mode specific `NetworkBehaviour.HasAuthority` property that determines if the local client has authority over the associated `NetworkObject` instance (typical use case is within a `NetworkBehaviour` script much like that of `IsServer` or `IsClient`). (#2863) - Added distributed authority mode specific `NetworkBehaviour.IsSessionOwner` property that determines if the local client is the session owner (typical use case would be to determine if the local client can has scene management authority within a `NetworkBehaviour` script). (#2863) - Added support for distributed authority mode scene management where the currently assigned session owner can start scene events (i.e. scene loading and scene unloading). (#2863) ### Fixed - Fixed issue where the host was not invoking `OnClientDisconnectCallback` for its own local client when internally shutting down. (#2822) - Fixed issue where NetworkTransform could potentially attempt to "unregister" a named message prior to it being registered. (#2807) - Fixed issue where in-scene placed `NetworkObject`s with complex nested children `NetworkObject`s (more than one child in depth) would not synchronize properly if WorldPositionStays was set to true. (#2796) ### Changed - Changed client side awareness of other clients is now the same as a server or host. (#2863) - Changed `NetworkManager.ConnectedClients` can now be accessed by both server and clients. (#2863) - Changed `NetworkManager.ConnectedClientsList` can now be accessed by both server and clients. (#2863) - Changed `NetworkTransform` defaults to owner authoritative when connected to a distributed authority session. (#2863) - Changed `NetworkVariable` defaults to owner write and everyone read permissions when connected to a distributed authority session (even if declared with server read or write permissions). (#2863) - Changed `NetworkObject` no longer implements the `MonoBehaviour.Update` method in order to determine whether a `NetworkObject` instance has been migrated to a different scene. Instead, only `NetworkObjects` with the `SceneMigrationSynchronization` property set will be updated internally during the `NetworkUpdateStage.PostLateUpdate` by `NetworkManager`. (#2863) - Changed `NetworkManager` inspector view layout where properties are now organized by category. (#2863) - Changed `NetworkTransform` to now use `NetworkTransformMessage` as opposed to named messages for NetworkTransformState updates. (#2810) - Changed `CustomMessageManager` so it no longer attempts to register or "unregister" a null or empty string and will log an error if this condition occurs. (#2807)
This commit is contained in:
@@ -4,6 +4,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using NUnit.Framework;
|
||||
using Unity.Netcode.RuntimeTests;
|
||||
using Unity.Netcode.Transports.UTP;
|
||||
@@ -29,6 +30,13 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
protected static WaitForSecondsRealtime s_DefaultWaitForTick = new WaitForSecondsRealtime(1.0f / k_DefaultTickRate);
|
||||
|
||||
public NetcodeLogAssert NetcodeLogAssert;
|
||||
public enum SceneManagementState
|
||||
{
|
||||
SceneManagementEnabled,
|
||||
SceneManagementDisabled
|
||||
}
|
||||
|
||||
private StringBuilder m_InternalErrorLog = new StringBuilder();
|
||||
|
||||
/// <summary>
|
||||
/// Registered list of all NetworkObjects spawned.
|
||||
@@ -112,7 +120,8 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
public enum HostOrServer
|
||||
{
|
||||
Host,
|
||||
Server
|
||||
Server,
|
||||
DAHost
|
||||
}
|
||||
|
||||
protected GameObject m_PlayerPrefab;
|
||||
@@ -129,6 +138,26 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
protected Dictionary<ulong, Dictionary<ulong, NetworkObject>> m_PlayerNetworkObjects = new Dictionary<ulong, Dictionary<ulong, NetworkObject>>();
|
||||
|
||||
protected bool m_UseHost = true;
|
||||
protected bool m_DistributedAuthority;
|
||||
protected SessionModeTypes m_SessionModeType = SessionModeTypes.ClientServer;
|
||||
|
||||
protected virtual bool UseCMBService()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
protected virtual SessionModeTypes OnGetSessionmode()
|
||||
{
|
||||
return m_SessionModeType;
|
||||
}
|
||||
|
||||
protected void SetDistributedAuthorityProperties(NetworkManager networkManager)
|
||||
{
|
||||
networkManager.NetworkConfig.SessionMode = m_SessionModeType;
|
||||
networkManager.NetworkConfig.AutoSpawnPlayerPrefabClientSide = m_DistributedAuthority;
|
||||
networkManager.NetworkConfig.UseCMBService = UseCMBService() && m_DistributedAuthority;
|
||||
}
|
||||
|
||||
protected int m_TargetFrameRate = 60;
|
||||
|
||||
private NetworkManagerInstatiationMode m_NetworkManagerInstatiationMode;
|
||||
@@ -338,6 +367,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
else
|
||||
{
|
||||
yield return StartServerAndClients();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -367,6 +397,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
m_PlayerPrefab = new GameObject("Player");
|
||||
OnPlayerPrefabGameObjectCreated();
|
||||
NetworkObject networkObject = m_PlayerPrefab.AddComponent<NetworkObject>();
|
||||
networkObject.IsSceneObject = false;
|
||||
|
||||
// Make it a prefab
|
||||
NetcodeIntegrationTestHelpers.MakeNetworkObjectTestPrefab(networkObject);
|
||||
@@ -455,6 +486,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
{
|
||||
var networkManager = NetcodeIntegrationTestHelpers.CreateNewClient(m_ClientNetworkManagers.Length, m_EnableTimeTravel);
|
||||
networkManager.NetworkConfig.PlayerPrefab = m_PlayerPrefab;
|
||||
SetDistributedAuthorityProperties(networkManager);
|
||||
|
||||
// Notification that the new client (NetworkManager) has been created
|
||||
// in the event any modifications need to be made before starting the client
|
||||
@@ -483,12 +515,64 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
Object.DestroyImmediate(networkManager.gameObject);
|
||||
}
|
||||
|
||||
AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for the new client to be connected!");
|
||||
AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for the new client to be connected!\n {m_InternalErrorLog}");
|
||||
ClientNetworkManagerPostStart(networkManager);
|
||||
if (networkManager.DistributedAuthorityMode)
|
||||
{
|
||||
yield return WaitForConditionOrTimeOut(() => AllPlayerObjectClonesSpawned(networkManager));
|
||||
AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for all sessions to spawn Client-{networkManager.LocalClientId}'s player object!");
|
||||
}
|
||||
|
||||
VerboseDebug($"[{networkManager.name}] Created and connected!");
|
||||
}
|
||||
}
|
||||
|
||||
private bool AllPlayerObjectClonesSpawned(NetworkManager joinedClient)
|
||||
{
|
||||
m_InternalErrorLog.Clear();
|
||||
// Continue to populate the PlayerObjects list until all player object (local and clone) are found
|
||||
ClientNetworkManagerPostStart(joinedClient);
|
||||
|
||||
var playerObjectRelative = m_ServerNetworkManager.SpawnManager.PlayerObjects.Where((c) => c.OwnerClientId == joinedClient.LocalClientId).FirstOrDefault();
|
||||
if (playerObjectRelative == null)
|
||||
{
|
||||
m_InternalErrorLog.Append($"[AllPlayerObjectClonesSpawned][Server-Side] Joining Client-{joinedClient.LocalClientId} was not populated in the {nameof(NetworkSpawnManager.PlayerObjects)} list!");
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Go ahead and create an entry for this new client
|
||||
if (!m_PlayerNetworkObjects[m_ServerNetworkManager.LocalClientId].ContainsKey(joinedClient.LocalClientId))
|
||||
{
|
||||
m_PlayerNetworkObjects[m_ServerNetworkManager.LocalClientId].Add(joinedClient.LocalClientId, playerObjectRelative);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var clientNetworkManager in m_ClientNetworkManagers)
|
||||
{
|
||||
if (clientNetworkManager.LocalClientId == joinedClient.LocalClientId)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
playerObjectRelative = clientNetworkManager.SpawnManager.PlayerObjects.Where((c) => c.OwnerClientId == joinedClient.LocalClientId).FirstOrDefault();
|
||||
if (playerObjectRelative == null)
|
||||
{
|
||||
m_InternalErrorLog.Append($"[AllPlayerObjectClonesSpawned][Client-{clientNetworkManager.LocalClientId}] Client-{joinedClient.LocalClientId} was not populated in the {nameof(NetworkSpawnManager.PlayerObjects)} list!");
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Go ahead and create an entry for this new client
|
||||
if (!m_PlayerNetworkObjects[clientNetworkManager.LocalClientId].ContainsKey(joinedClient.LocalClientId))
|
||||
{
|
||||
m_PlayerNetworkObjects[clientNetworkManager.LocalClientId].Add(joinedClient.LocalClientId, playerObjectRelative);
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This will create, start, and connect a new client while in the middle of an
|
||||
/// integration test.
|
||||
@@ -497,6 +581,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
{
|
||||
var networkManager = NetcodeIntegrationTestHelpers.CreateNewClient(m_ClientNetworkManagers.Length, m_EnableTimeTravel);
|
||||
networkManager.NetworkConfig.PlayerPrefab = m_PlayerPrefab;
|
||||
SetDistributedAuthorityProperties(networkManager);
|
||||
|
||||
// Notification that the new client (NetworkManager) has been created
|
||||
// in the event any modifications need to be made before starting the client
|
||||
@@ -534,7 +619,10 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
protected IEnumerator StopOneClient(NetworkManager networkManager, bool destroy = false)
|
||||
{
|
||||
NetcodeIntegrationTestHelpers.StopOneClient(networkManager, destroy);
|
||||
AddRemoveNetworkManager(networkManager, false);
|
||||
if (destroy)
|
||||
{
|
||||
AddRemoveNetworkManager(networkManager, false);
|
||||
}
|
||||
yield return WaitForConditionOrTimeOut(() => !networkManager.IsConnectedClient);
|
||||
}
|
||||
|
||||
@@ -581,9 +669,12 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
// Set the player prefab for the server and clients
|
||||
m_ServerNetworkManager.NetworkConfig.PlayerPrefab = m_PlayerPrefab;
|
||||
|
||||
SetDistributedAuthorityProperties(m_ServerNetworkManager);
|
||||
|
||||
foreach (var client in m_ClientNetworkManagers)
|
||||
{
|
||||
client.NetworkConfig.PlayerPrefab = m_PlayerPrefab;
|
||||
SetDistributedAuthorityProperties(client);
|
||||
}
|
||||
|
||||
// Provides opportunity to allow child derived classes to
|
||||
@@ -730,22 +821,27 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
|
||||
// Start the instances and pass in our SceneManagerInitialization action that is invoked immediately after host-server
|
||||
// is started and after each client is started.
|
||||
if (!NetcodeIntegrationTestHelpers.Start(m_UseHost, m_ServerNetworkManager, m_ClientNetworkManagers))
|
||||
|
||||
// When using the CMBService, don't start the server.
|
||||
bool startServer = !(UseCMBService() && m_DistributedAuthority);
|
||||
if (!NetcodeIntegrationTestHelpers.Start(m_UseHost, startServer, m_ServerNetworkManager, m_ClientNetworkManagers))
|
||||
{
|
||||
Debug.LogError("Failed to start instances");
|
||||
Assert.Fail("Failed to start instances");
|
||||
}
|
||||
|
||||
// When scene management is enabled, we need to re-apply the scenes populated list since we have overriden the ISceneManagerHandler
|
||||
// imeplementation at this point. This assures any pre-loaded scenes will be automatically assigned to the server and force clients
|
||||
// imeplementation at this point. This assures any pre-loaded scenes will be automatically assigned to the server and force clients
|
||||
// to load their own scenes.
|
||||
if (m_ServerNetworkManager.NetworkConfig.EnableSceneManagement)
|
||||
{
|
||||
var scenesLoaded = m_ServerNetworkManager.SceneManager.ScenesLoaded;
|
||||
m_ServerNetworkManager.SceneManager.SceneManagerHandler.PopulateLoadedScenes(ref scenesLoaded, m_ServerNetworkManager);
|
||||
if (startServer)
|
||||
{
|
||||
var scenesLoaded = m_ServerNetworkManager.SceneManager.ScenesLoaded;
|
||||
m_ServerNetworkManager.SceneManager.SceneManagerHandler.PopulateLoadedScenes(ref scenesLoaded, m_ServerNetworkManager);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (LogAllMessages)
|
||||
{
|
||||
EnableMessageLogging();
|
||||
@@ -762,7 +858,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
// Wait for all clients to connect
|
||||
yield return WaitForClientsConnectedOrTimeOut();
|
||||
|
||||
AssertOnTimeout($"{nameof(StartServerAndClients)} timed out waiting for all clients to be connected!");
|
||||
AssertOnTimeout($"{nameof(StartServerAndClients)} timed out waiting for all clients to be connected!\n {m_InternalErrorLog}");
|
||||
|
||||
if (m_UseHost || m_ServerNetworkManager.IsHost)
|
||||
{
|
||||
@@ -783,9 +879,25 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
m_PlayerNetworkObjects[playerNetworkObject.NetworkManager.LocalClientId].Add(m_ServerNetworkManager.LocalClientId, playerNetworkObject);
|
||||
}
|
||||
}
|
||||
|
||||
if (m_DistributedAuthority)
|
||||
{
|
||||
//yield return WaitForConditionOrTimeOut(AllClientPlayersSpawned);
|
||||
//AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for all sessions to spawn all player objects!");
|
||||
foreach (var networkManager in m_ClientNetworkManagers)
|
||||
{
|
||||
if (networkManager.DistributedAuthorityMode)
|
||||
{
|
||||
yield return WaitForConditionOrTimeOut(() => AllPlayerObjectClonesSpawned(networkManager));
|
||||
AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for all sessions to spawn Client-{networkManager.LocalClientId}'s player object!\n {m_InternalErrorLog}");
|
||||
}
|
||||
}
|
||||
if (m_ServerNetworkManager != null)
|
||||
{
|
||||
yield return WaitForConditionOrTimeOut(() => AllPlayerObjectClonesSpawned(m_ServerNetworkManager));
|
||||
AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for all sessions to spawn Client-{m_ServerNetworkManager.LocalClientId}'s player object!\n {m_InternalErrorLog}");
|
||||
}
|
||||
}
|
||||
ClientNetworkManagerPostStartInit();
|
||||
|
||||
// Notification that at this time the server and client(s) are instantiated,
|
||||
// started, and connected on both sides.
|
||||
yield return OnServerAndClientsConnected();
|
||||
@@ -807,7 +919,9 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
|
||||
// Start the instances and pass in our SceneManagerInitialization action that is invoked immediately after host-server
|
||||
// is started and after each client is started.
|
||||
if (!NetcodeIntegrationTestHelpers.Start(m_UseHost, m_ServerNetworkManager, m_ClientNetworkManagers))
|
||||
// When using the CMBService, don't start the server.
|
||||
var usingCMBService = UseCMBService() && m_DistributedAuthority;
|
||||
if (!NetcodeIntegrationTestHelpers.Start(m_UseHost, !usingCMBService, m_ServerNetworkManager, m_ClientNetworkManagers))
|
||||
{
|
||||
Debug.LogError("Failed to start instances");
|
||||
Assert.Fail("Failed to start instances");
|
||||
@@ -857,6 +971,24 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
}
|
||||
}
|
||||
|
||||
if (m_DistributedAuthority)
|
||||
{
|
||||
|
||||
foreach (var networkManager in m_ClientNetworkManagers)
|
||||
{
|
||||
if (networkManager.DistributedAuthorityMode)
|
||||
{
|
||||
WaitForConditionOrTimeOutWithTimeTravel(() => AllPlayerObjectClonesSpawned(m_ServerNetworkManager));
|
||||
AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for all sessions to spawn Client-{networkManager.LocalClientId}'s player object!");
|
||||
}
|
||||
}
|
||||
if (m_ServerNetworkManager != null)
|
||||
{
|
||||
WaitForConditionOrTimeOutWithTimeTravel(() => AllPlayerObjectClonesSpawned(m_ServerNetworkManager));
|
||||
AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for all sessions to spawn Client-{m_ServerNetworkManager.LocalClientId}'s player object!");
|
||||
}
|
||||
}
|
||||
|
||||
ClientNetworkManagerPostStartInit();
|
||||
|
||||
// Notification that at this time the server and client(s) are instantiated,
|
||||
@@ -965,6 +1097,45 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
VerboseDebug($"Exiting {nameof(ShutdownAndCleanUp)}");
|
||||
}
|
||||
|
||||
protected IEnumerator CoroutineShutdownAndCleanUp()
|
||||
{
|
||||
VerboseDebug($"Entering {nameof(ShutdownAndCleanUp)}");
|
||||
// Shutdown and clean up both of our NetworkManager instances
|
||||
try
|
||||
{
|
||||
DeRegisterSceneManagerHandler();
|
||||
|
||||
NetcodeIntegrationTestHelpers.Destroy();
|
||||
|
||||
m_PlayerNetworkObjects.Clear();
|
||||
s_GlobalNetworkObjects.Clear();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw e;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (m_PlayerPrefab != null)
|
||||
{
|
||||
Object.DestroyImmediate(m_PlayerPrefab);
|
||||
m_PlayerPrefab = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Allow time for NetworkManagers to fully shutdown
|
||||
yield return s_DefaultWaitForTick;
|
||||
|
||||
// Cleanup any remaining NetworkObjects
|
||||
DestroySceneNetworkObjects();
|
||||
|
||||
UnloadRemainingScenes();
|
||||
|
||||
// reset the m_ServerWaitForTick for the next test to initialize
|
||||
s_DefaultWaitForTick = new WaitForSecondsRealtime(1.0f / k_DefaultTickRate);
|
||||
VerboseDebug($"Exiting {nameof(ShutdownAndCleanUp)}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Note: For <see cref="NetworkManagerInstatiationMode.PerTest"/> mode
|
||||
/// this is called before ShutdownAndCleanUp.
|
||||
@@ -994,7 +1165,14 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
|
||||
if (m_NetworkManagerInstatiationMode == NetworkManagerInstatiationMode.PerTest)
|
||||
{
|
||||
ShutdownAndCleanUp();
|
||||
if (m_TearDownIsACoroutine)
|
||||
{
|
||||
yield return CoroutineShutdownAndCleanUp();
|
||||
}
|
||||
else
|
||||
{
|
||||
ShutdownAndCleanUp();
|
||||
}
|
||||
}
|
||||
|
||||
if (m_EnableTimeTravel)
|
||||
@@ -1230,11 +1408,35 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
/// <param name="clientsToCheck">An array of clients to be checked</param>
|
||||
protected IEnumerator WaitForClientsConnectedOrTimeOut(NetworkManager[] clientsToCheck)
|
||||
{
|
||||
var remoteClientCount = clientsToCheck.Length;
|
||||
var serverClientCount = m_ServerNetworkManager.IsHost ? remoteClientCount + 1 : remoteClientCount;
|
||||
yield return WaitForConditionOrTimeOut(() => CheckClientsConnected(clientsToCheck));
|
||||
}
|
||||
|
||||
yield return WaitForConditionOrTimeOut(() => clientsToCheck.Where((c) => c.IsConnectedClient).Count() == remoteClientCount &&
|
||||
m_ServerNetworkManager.ConnectedClients.Count == serverClientCount);
|
||||
/// <summary>
|
||||
/// Validation for clients connected that includes additional information for easier troubleshooting purposes.
|
||||
/// </summary>
|
||||
private bool CheckClientsConnected(NetworkManager[] clientsToCheck)
|
||||
{
|
||||
m_InternalErrorLog.Clear();
|
||||
var allClientsConnected = true;
|
||||
|
||||
for (int i = 0; i < clientsToCheck.Length; i++)
|
||||
{
|
||||
if (!clientsToCheck[i].IsConnectedClient)
|
||||
{
|
||||
allClientsConnected = false;
|
||||
m_InternalErrorLog.AppendLine($"[Client-{i + 1}] Client is not connected!");
|
||||
}
|
||||
}
|
||||
var expectedCount = m_ServerNetworkManager.IsHost ? clientsToCheck.Length + 1 : clientsToCheck.Length;
|
||||
var currentCount = m_ServerNetworkManager.ConnectedClients.Count;
|
||||
|
||||
if (currentCount != expectedCount)
|
||||
{
|
||||
allClientsConnected = false;
|
||||
m_InternalErrorLog.AppendLine($"[Server-Side] Expected {expectedCount} clients to connect but only {currentCount} connected!");
|
||||
}
|
||||
|
||||
return allClientsConnected;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -1286,7 +1488,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
// Used to determine if all clients received the CreateObjectMessage
|
||||
var hooks = new MessageHooksConditional(messageHookEntriesForSpawn);
|
||||
yield return WaitForConditionOrTimeOut(hooks);
|
||||
Assert.False(s_GlobalTimeoutHelper.TimedOut);
|
||||
AssertOnTimeout($"Timed out waiting for message type {typeof(T).Name}!");
|
||||
}
|
||||
|
||||
internal IEnumerator WaitForMessagesReceived(List<Type> messagesInOrder, List<NetworkManager> waitForReceivedBy, ReceiptType type = ReceiptType.Handled)
|
||||
@@ -1306,7 +1508,12 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
// Used to determine if all clients received the CreateObjectMessage
|
||||
var hooks = new MessageHooksConditional(messageHookEntriesForSpawn);
|
||||
yield return WaitForConditionOrTimeOut(hooks);
|
||||
Assert.False(s_GlobalTimeoutHelper.TimedOut);
|
||||
var stringBuilder = new StringBuilder();
|
||||
foreach (var messageType in messagesInOrder)
|
||||
{
|
||||
stringBuilder.Append($"{messageType.Name},");
|
||||
}
|
||||
AssertOnTimeout($"Timed out waiting for message types: {stringBuilder}!");
|
||||
}
|
||||
|
||||
|
||||
@@ -1323,7 +1530,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
|
||||
// Used to determine if all clients received the CreateObjectMessage
|
||||
var hooks = new MessageHooksConditional(messageHookEntriesForSpawn);
|
||||
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(hooks));
|
||||
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(hooks), $"[Message Not Recieved] {hooks.GetHooksStillWaiting()}");
|
||||
}
|
||||
|
||||
internal void WaitForMessagesReceivedWithTimeTravel(List<Type> messagesInOrder, List<NetworkManager> waitForReceivedBy, ReceiptType type = ReceiptType.Handled)
|
||||
@@ -1342,7 +1549,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
|
||||
// Used to determine if all clients received the CreateObjectMessage
|
||||
var hooks = new MessageHooksConditional(messageHookEntriesForSpawn);
|
||||
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(hooks));
|
||||
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(hooks), $"[Messages Not Recieved] {hooks.GetHooksStillWaiting()}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -1358,8 +1565,11 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
$"but before {nameof(OnStartedServerAndClients)}!";
|
||||
Assert.IsNotNull(m_ServerNetworkManager, prefabCreateAssertError);
|
||||
Assert.IsFalse(m_ServerNetworkManager.IsListening, prefabCreateAssertError);
|
||||
|
||||
return NetcodeIntegrationTestHelpers.CreateNetworkObjectPrefab(baseName, m_ServerNetworkManager, m_ClientNetworkManagers);
|
||||
var prefabObject = NetcodeIntegrationTestHelpers.CreateNetworkObjectPrefab(baseName, m_ServerNetworkManager, m_ClientNetworkManagers);
|
||||
// DANGO-TODO: Ownership flags could require us to change this
|
||||
// For testing purposes, we default to true for the distribute ownership property when in distirbuted authority session mode.
|
||||
prefabObject.GetComponent<NetworkObject>().Ownership |= NetworkObject.OwnershipStatus.Distributable;
|
||||
return prefabObject;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -1372,6 +1582,16 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
return SpawnObject(prefabNetworkObject, owner, destroyWithScene);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Overloaded method <see cref="SpawnObject(NetworkObject, NetworkManager, bool)"/>
|
||||
/// </summary>
|
||||
protected GameObject SpawnPlayerObject(GameObject prefabGameObject, NetworkManager owner, bool destroyWithScene = false)
|
||||
{
|
||||
var prefabNetworkObject = prefabGameObject.GetComponent<NetworkObject>();
|
||||
Assert.IsNotNull(prefabNetworkObject, $"{nameof(GameObject)} {prefabGameObject.name} does not have a {nameof(NetworkObject)} component!");
|
||||
return SpawnObject(prefabNetworkObject, owner, destroyWithScene, true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Spawn a NetworkObject prefab instance
|
||||
/// </summary>
|
||||
@@ -1379,28 +1599,57 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
/// <param name="owner">the owner of the instance</param>
|
||||
/// <param name="destroyWithScene">default is false</param>
|
||||
/// <returns>GameObject instance spawned</returns>
|
||||
private GameObject SpawnObject(NetworkObject prefabNetworkObject, NetworkManager owner, bool destroyWithScene = false)
|
||||
private GameObject SpawnObject(NetworkObject prefabNetworkObject, NetworkManager owner, bool destroyWithScene = false, bool isPlayerObject = false)
|
||||
{
|
||||
Assert.IsTrue(prefabNetworkObject.GlobalObjectIdHash > 0, $"{nameof(GameObject)} {prefabNetworkObject.name} has a {nameof(NetworkObject.GlobalObjectIdHash)} value of 0! Make sure to make it a valid prefab before trying to spawn!");
|
||||
var newInstance = Object.Instantiate(prefabNetworkObject.gameObject);
|
||||
var networkObjectToSpawn = newInstance.GetComponent<NetworkObject>();
|
||||
networkObjectToSpawn.NetworkManagerOwner = m_ServerNetworkManager; // Required to assure the server does the spawning
|
||||
if (owner == m_ServerNetworkManager)
|
||||
|
||||
if (owner.NetworkConfig.SessionMode == SessionModeTypes.DistributedAuthority)
|
||||
{
|
||||
if (m_UseHost)
|
||||
networkObjectToSpawn.NetworkManagerOwner = owner; // Required to assure the client does the spawning
|
||||
if (isPlayerObject)
|
||||
{
|
||||
networkObjectToSpawn.SpawnWithOwnership(owner.LocalClientId, destroyWithScene);
|
||||
networkObjectToSpawn.SpawnAsPlayerObject(owner.LocalClientId, destroyWithScene);
|
||||
}
|
||||
else
|
||||
{
|
||||
networkObjectToSpawn.Spawn(destroyWithScene);
|
||||
networkObjectToSpawn.SpawnWithOwnership(owner.LocalClientId, destroyWithScene);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
networkObjectToSpawn.SpawnWithOwnership(owner.LocalClientId, destroyWithScene);
|
||||
networkObjectToSpawn.NetworkManagerOwner = m_ServerNetworkManager; // Required to assure the server does the spawning
|
||||
if (owner == m_ServerNetworkManager)
|
||||
{
|
||||
if (m_UseHost)
|
||||
{
|
||||
if (isPlayerObject)
|
||||
{
|
||||
networkObjectToSpawn.SpawnAsPlayerObject(owner.LocalClientId, destroyWithScene);
|
||||
}
|
||||
else
|
||||
{
|
||||
networkObjectToSpawn.SpawnWithOwnership(owner.LocalClientId, destroyWithScene);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
networkObjectToSpawn.Spawn(destroyWithScene);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (isPlayerObject)
|
||||
{
|
||||
networkObjectToSpawn.SpawnAsPlayerObject(owner.LocalClientId, destroyWithScene);
|
||||
}
|
||||
else
|
||||
{
|
||||
networkObjectToSpawn.SpawnWithOwnership(owner.LocalClientId, destroyWithScene);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return newInstance;
|
||||
}
|
||||
|
||||
@@ -1438,6 +1687,15 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
/// </summary>
|
||||
public NetcodeIntegrationTest()
|
||||
{
|
||||
m_SessionModeType = OnGetSessionmode();
|
||||
m_DistributedAuthority = OnGetSessionmode() == SessionModeTypes.DistributedAuthority;
|
||||
NetworkMessageManager.EnableMessageOrderConsoleLog = false;
|
||||
}
|
||||
|
||||
public NetcodeIntegrationTest(SessionModeTypes sessionMode)
|
||||
{
|
||||
m_SessionModeType = sessionMode;
|
||||
m_DistributedAuthority = OnGetSessionmode() == SessionModeTypes.DistributedAuthority;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -1458,7 +1716,9 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
/// <param name="hostOrServer"></param>
|
||||
public NetcodeIntegrationTest(HostOrServer hostOrServer)
|
||||
{
|
||||
m_UseHost = hostOrServer == HostOrServer.Host ? true : false;
|
||||
m_UseHost = hostOrServer == HostOrServer.Host || hostOrServer == HostOrServer.DAHost;
|
||||
m_SessionModeType = hostOrServer == HostOrServer.DAHost ? SessionModeTypes.DistributedAuthority : SessionModeTypes.ClientServer;
|
||||
m_DistributedAuthority = OnGetSessionmode() == SessionModeTypes.DistributedAuthority;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -1489,7 +1749,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
}
|
||||
}
|
||||
|
||||
private System.Text.StringBuilder m_WaitForLog = new System.Text.StringBuilder();
|
||||
private StringBuilder m_WaitForLog = new StringBuilder();
|
||||
|
||||
private void LogWaitForMessages()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user