Initial Commit

This commit is contained in:
Sebastian Cabrera 2021-08-02 05:44:37 -04:00
parent 53eb92e9af
commit 270ab7d11f
15341 changed files with 700234 additions and 0 deletions

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d656bc8bb2502584ab6883d254d64782
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 48b252004f20b4e28a4025ef8d0237fe
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,129 @@
using System;
using System.Collections.Generic;
using System.Text;
using MLAPI.Messaging;
using MLAPI.Serialization;
using MLAPI.Transports;
using NUnit.Framework;
namespace MLAPI.EditorTests
{
public class RpcBatcherTests
{
[Test]
public void SendWithThreshold()
{
const int k_BatchThreshold = 256;
const int k_QueueItemCount = 128;
var sendBatcher = new RpcBatcher();
var sendStreamQueue = new Queue<NetworkBuffer>();
for (int i = 0; i < k_QueueItemCount; ++i)
{
var randomData = Encoding.ASCII.GetBytes(Guid.NewGuid().ToString());
var queueItem = new RpcFrameQueueItem
{
NetworkId = 123,
ClientNetworkIds = new ulong[] { 123 },
NetworkChannel = NetworkChannel.ChannelUnused + 123,
QueueItemType = i % 2 == 0 ? RpcQueueContainer.QueueItemType.ServerRpc : RpcQueueContainer.QueueItemType.ClientRpc,
MessageData = new ArraySegment<byte>(randomData, 0, randomData.Length)
};
sendBatcher.QueueItem(queueItem);
sendBatcher.SendItems(k_BatchThreshold,
(networkId, sendStream) =>
{
var queueStream = new NetworkBuffer();
sendStream.Buffer.CopyTo(queueStream);
sendStreamQueue.Enqueue(queueStream);
});
}
// batch the rest
sendBatcher.SendItems( /* thresholdBytes = */ 0,
(networkId, sendStream) =>
{
var queueStream = new NetworkBuffer();
sendStream.Buffer.CopyTo(queueStream);
sendStreamQueue.Enqueue(queueStream);
});
var recvBatcher = new RpcBatcher();
var recvItemCounter = 0;
foreach (var recvStream in sendStreamQueue)
{
recvStream.Position = 0;
// todo: revisit
// The following line is sub-optimal
// The stream returned by SendItems() includes:
// - 8 bits for the MLAPI message types.
// ReceiveItems expects those to have been stripped by the receive code.
// In order to replicate this behaviour, we'll read 8 bits before calling ReceiveItems()
recvStream.ReadByte();
recvBatcher.ReceiveItems(recvStream, (stream, type, id, time) => ++recvItemCounter, default, default, default);
}
Assert.AreEqual(k_QueueItemCount, recvItemCounter);
}
[Test]
public void SendWithoutThreshold()
{
const int k_BatchThreshold = 0;
const int k_QueueItemCount = 128;
var sendBatcher = new RpcBatcher();
var sendStreamQueue = new Queue<NetworkBuffer>();
for (int i = 0; i < k_QueueItemCount; ++i)
{
var randomData = Encoding.ASCII.GetBytes(Guid.NewGuid().ToString());
var queueItem = new RpcFrameQueueItem
{
NetworkId = 123,
ClientNetworkIds = new ulong[] { 123 },
NetworkChannel = NetworkChannel.ChannelUnused + 123,
QueueItemType = i % 2 == 0 ? RpcQueueContainer.QueueItemType.ServerRpc : RpcQueueContainer.QueueItemType.ClientRpc,
MessageData = new ArraySegment<byte>(randomData, 0, randomData.Length)
};
sendBatcher.QueueItem(queueItem);
sendBatcher.SendItems(k_BatchThreshold,
(networkId, sendStream) =>
{
var queueStream = new NetworkBuffer();
sendStream.Buffer.CopyTo(queueStream);
sendStreamQueue.Enqueue(queueStream);
});
}
// batch the rest
sendBatcher.SendItems( /* thresholdBytes = */ 0,
(networkId, sendStream) =>
{
var queueStream = new NetworkBuffer();
sendStream.Buffer.CopyTo(queueStream);
sendStreamQueue.Enqueue(queueStream);
});
var recvBatcher = new RpcBatcher();
var recvItemCounter = 0;
foreach (var recvStream in sendStreamQueue)
{
recvStream.Position = 0;
// todo: revisit
// The following line is sub-optimal
// The stream returned by SendItems() includes:
// - 8 bits for the MLAPI message types.
// ReceiveItems expects those to have been stripped by the receive code.
// In order to replicate this behaviour, we'll read 8 bits before calling ReceiveItems()
recvStream.ReadByte();
recvBatcher.ReceiveItems(recvStream, (stream, type, id, time) => ++recvItemCounter, default, default, default);
}
Assert.AreEqual(k_QueueItemCount, recvItemCounter);
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1b2fcaa08dc7f4bb5a6a3bc089a01b85
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,13 @@
{
"name": "Unity.Multiplayer.MLAPI.EditorTests",
"references": [
"Unity.Multiplayer.MLAPI.Runtime"
],
"optionalUnityReferences": [
"TestAssemblies"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": []
}

View file

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 072b82e2b7c1dcf439827d3fbc4f52a1
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 9d3a545f9ce7b074c95a3b1c3101dee9
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,439 @@
using System;
using System.Collections;
using System.Linq;
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using UnityEngine.LowLevel;
using UnityEngine.PlayerLoop;
namespace MLAPI.RuntimeTests
{
public class NetworkUpdateLoopTests
{
[Test]
public void RegisterCustomLoopInTheMiddle()
{
// caching the current PlayerLoop (to prevent side-effects on other tests)
var cachedPlayerLoop = PlayerLoop.GetCurrentPlayerLoop();
{
// since current PlayerLoop already took NetworkUpdateLoop systems inside,
// we are going to swap it with the default PlayerLoop temporarily for testing
PlayerLoop.SetPlayerLoop(PlayerLoop.GetDefaultPlayerLoop());
NetworkUpdateLoop.RegisterLoopSystems();
var curPlayerLoop = PlayerLoop.GetCurrentPlayerLoop();
int initSubsystemCount = curPlayerLoop.subSystemList[0].subSystemList.Length;
var newInitSubsystems = new PlayerLoopSystem[initSubsystemCount + 1];
Array.Copy(curPlayerLoop.subSystemList[0].subSystemList, newInitSubsystems, initSubsystemCount);
newInitSubsystems[initSubsystemCount] = new PlayerLoopSystem { type = typeof(NetworkUpdateLoopTests) };
curPlayerLoop.subSystemList[0].subSystemList = newInitSubsystems;
PlayerLoop.SetPlayerLoop(curPlayerLoop);
NetworkUpdateLoop.UnregisterLoopSystems();
// our custom `PlayerLoopSystem` with the type of `NetworkUpdateLoopTests` should still exist
Assert.AreEqual(typeof(NetworkUpdateLoopTests), PlayerLoop.GetCurrentPlayerLoop().subSystemList[0].subSystemList.Last().type);
}
// replace the current PlayerLoop with the cached PlayerLoop after the test
PlayerLoop.SetPlayerLoop(cachedPlayerLoop);
}
[UnityTest]
public IEnumerator RegisterAndUnregisterSystems()
{
// caching the current PlayerLoop (it will have NetworkUpdateLoop systems registered)
var cachedPlayerLoop = PlayerLoop.GetCurrentPlayerLoop();
{
// since current PlayerLoop already took NetworkUpdateLoop systems inside,
// we are going to swap it with the default PlayerLoop temporarily for testing
PlayerLoop.SetPlayerLoop(PlayerLoop.GetDefaultPlayerLoop());
var oldPlayerLoop = PlayerLoop.GetCurrentPlayerLoop();
NetworkUpdateLoop.RegisterLoopSystems();
int nextFrameNumber = Time.frameCount + 1;
yield return new WaitUntil(() => Time.frameCount >= nextFrameNumber);
NetworkUpdateLoop.UnregisterLoopSystems();
var newPlayerLoop = PlayerLoop.GetCurrentPlayerLoop();
// recursively compare old and new PlayerLoop systems and their subsystems
AssertAreEqualPlayerLoopSystems(newPlayerLoop, oldPlayerLoop);
}
// replace the current PlayerLoop with the cached PlayerLoop after the test
PlayerLoop.SetPlayerLoop(cachedPlayerLoop);
}
private void AssertAreEqualPlayerLoopSystems(PlayerLoopSystem leftPlayerLoop, PlayerLoopSystem rightPlayerLoop)
{
Assert.AreEqual(leftPlayerLoop.type, rightPlayerLoop.type);
Assert.AreEqual(leftPlayerLoop.subSystemList?.Length ?? 0, rightPlayerLoop.subSystemList?.Length ?? 0);
for (int i = 0; i < (leftPlayerLoop.subSystemList?.Length ?? 0); i++)
{
AssertAreEqualPlayerLoopSystems(leftPlayerLoop.subSystemList[i], rightPlayerLoop.subSystemList[i]);
}
}
[Test]
public void UpdateStageSystems()
{
var currentPlayerLoop = PlayerLoop.GetCurrentPlayerLoop();
for (int i = 0; i < currentPlayerLoop.subSystemList.Length; i++)
{
var playerLoopSystem = currentPlayerLoop.subSystemList[i];
var subsystems = playerLoopSystem.subSystemList.ToList();
if (playerLoopSystem.type == typeof(Initialization))
{
Assert.True(
subsystems.Exists(s => s.type == typeof(NetworkUpdateLoop.NetworkInitialization)),
nameof(NetworkUpdateLoop.NetworkInitialization));
}
else if (playerLoopSystem.type == typeof(EarlyUpdate))
{
Assert.True(
subsystems.Exists(s => s.type == typeof(NetworkUpdateLoop.NetworkEarlyUpdate)),
nameof(NetworkUpdateLoop.NetworkEarlyUpdate));
}
else if (playerLoopSystem.type == typeof(FixedUpdate))
{
Assert.True(
subsystems.Exists(s => s.type == typeof(NetworkUpdateLoop.NetworkFixedUpdate)),
nameof(NetworkUpdateLoop.NetworkFixedUpdate));
}
else if (playerLoopSystem.type == typeof(PreUpdate))
{
Assert.True(
subsystems.Exists(s => s.type == typeof(NetworkUpdateLoop.NetworkPreUpdate)),
nameof(NetworkUpdateLoop.NetworkPreUpdate));
}
else if (playerLoopSystem.type == typeof(Update))
{
Assert.True(
subsystems.Exists(s => s.type == typeof(NetworkUpdateLoop.NetworkUpdate)),
nameof(NetworkUpdateLoop.NetworkUpdate));
}
else if (playerLoopSystem.type == typeof(PreLateUpdate))
{
Assert.True(
subsystems.Exists(s => s.type == typeof(NetworkUpdateLoop.NetworkPreLateUpdate)),
nameof(NetworkUpdateLoop.NetworkPreLateUpdate));
}
else if (playerLoopSystem.type == typeof(PostLateUpdate))
{
Assert.True(
subsystems.Exists(s => s.type == typeof(NetworkUpdateLoop.NetworkPostLateUpdate)),
nameof(NetworkUpdateLoop.NetworkPostLateUpdate));
}
}
}
private struct NetworkUpdateCallbacks
{
public Action OnInitialization;
public Action OnEarlyUpdate;
public Action OnFixedUpdate;
public Action OnPreUpdate;
public Action OnUpdate;
public Action OnPreLateUpdate;
public Action OnPostLateUpdate;
}
private class MyPlainScript : IDisposable, INetworkUpdateSystem
{
public NetworkUpdateCallbacks UpdateCallbacks;
public void Initialize()
{
this.RegisterNetworkUpdate(NetworkUpdateStage.EarlyUpdate);
this.RegisterNetworkUpdate(NetworkUpdateStage.PreLateUpdate);
}
public void NetworkUpdate(NetworkUpdateStage updateStage)
{
switch (updateStage)
{
case NetworkUpdateStage.Initialization:
UpdateCallbacks.OnInitialization();
break;
case NetworkUpdateStage.EarlyUpdate:
UpdateCallbacks.OnEarlyUpdate();
break;
case NetworkUpdateStage.FixedUpdate:
UpdateCallbacks.OnFixedUpdate();
break;
case NetworkUpdateStage.PreUpdate:
UpdateCallbacks.OnPreUpdate();
break;
case NetworkUpdateStage.Update:
UpdateCallbacks.OnUpdate();
break;
case NetworkUpdateStage.PreLateUpdate:
UpdateCallbacks.OnPreLateUpdate();
break;
case NetworkUpdateStage.PostLateUpdate:
UpdateCallbacks.OnPostLateUpdate();
break;
}
}
public void Dispose()
{
this.UnregisterAllNetworkUpdates();
}
}
[UnityTest]
public IEnumerator UpdateStagesPlain()
{
const int kNetInitializationIndex = 0;
const int kNetEarlyUpdateIndex = 1;
const int kNetFixedUpdateIndex = 2;
const int kNetPreUpdateIndex = 3;
const int kNetUpdateIndex = 4;
const int kNetPreLateUpdateIndex = 5;
const int kNetPostLateUpdateIndex = 6;
int[] netUpdates = new int[7];
bool isTesting = false;
using (var plainScript = new MyPlainScript())
{
plainScript.UpdateCallbacks = new NetworkUpdateCallbacks
{
OnInitialization = () =>
{
if (isTesting)
{
netUpdates[kNetInitializationIndex]++;
}
},
OnEarlyUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetEarlyUpdateIndex]++;
}
},
OnFixedUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetFixedUpdateIndex]++;
}
},
OnPreUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetPreUpdateIndex]++;
}
},
OnUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetUpdateIndex]++;
}
},
OnPreLateUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetPreLateUpdateIndex]++;
}
},
OnPostLateUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetPostLateUpdateIndex]++;
}
}
};
plainScript.Initialize();
int nextFrameNumber = Time.frameCount + 1;
yield return new WaitUntil(() => Time.frameCount >= nextFrameNumber);
isTesting = true;
const int kRunTotalFrames = 16;
int waitFrameNumber = Time.frameCount + kRunTotalFrames;
yield return new WaitUntil(() => Time.frameCount >= waitFrameNumber);
Assert.AreEqual(0, netUpdates[kNetInitializationIndex]);
Assert.AreEqual(kRunTotalFrames, netUpdates[kNetEarlyUpdateIndex]);
Assert.AreEqual(0, netUpdates[kNetFixedUpdateIndex]);
Assert.AreEqual(0, netUpdates[kNetPreUpdateIndex]);
Assert.AreEqual(0, netUpdates[kNetUpdateIndex]);
Assert.AreEqual(kRunTotalFrames, netUpdates[kNetPreLateUpdateIndex]);
Assert.AreEqual(0, netUpdates[kNetPostLateUpdateIndex]);
}
}
private struct MonoBehaviourCallbacks
{
public Action OnFixedUpdate;
public Action OnUpdate;
public Action OnLateUpdate;
}
private class MyGameScript : MonoBehaviour, INetworkUpdateSystem
{
public NetworkUpdateCallbacks UpdateCallbacks;
public MonoBehaviourCallbacks BehaviourCallbacks;
private void Awake()
{
this.RegisterNetworkUpdate(NetworkUpdateStage.FixedUpdate);
this.RegisterNetworkUpdate(NetworkUpdateStage.PreUpdate);
this.RegisterNetworkUpdate(NetworkUpdateStage.PreLateUpdate);
this.RegisterNetworkUpdate(NetworkUpdateStage.PostLateUpdate);
// intentionally try to register for 'PreUpdate' stage twice
// it should be ignored and the instance should not be registered twice
// otherwise test would fail because it would call 'OnPreUpdate()' twice
// which would ultimately increment 'netUpdates[idx]' integer twice
// and cause 'Assert.AreEqual()' to fail the test
this.RegisterNetworkUpdate(NetworkUpdateStage.PreUpdate);
}
public void NetworkUpdate(NetworkUpdateStage updateStage)
{
switch (updateStage)
{
case NetworkUpdateStage.FixedUpdate:
UpdateCallbacks.OnFixedUpdate();
break;
case NetworkUpdateStage.PreUpdate:
UpdateCallbacks.OnPreUpdate();
break;
case NetworkUpdateStage.PreLateUpdate:
UpdateCallbacks.OnPreLateUpdate();
break;
case NetworkUpdateStage.PostLateUpdate:
UpdateCallbacks.OnPostLateUpdate();
break;
}
}
private void FixedUpdate()
{
BehaviourCallbacks.OnFixedUpdate();
}
private void Update()
{
BehaviourCallbacks.OnUpdate();
}
private void LateUpdate()
{
BehaviourCallbacks.OnLateUpdate();
}
private void OnDestroy()
{
this.UnregisterAllNetworkUpdates();
}
}
[UnityTest]
public IEnumerator UpdateStagesMixed()
{
const int kNetFixedUpdateIndex = 0;
const int kNetPreUpdateIndex = 1;
const int kNetPreLateUpdateIndex = 2;
const int kNetPostLateUpdateIndex = 3;
int[] netUpdates = new int[4];
const int kMonoFixedUpdateIndex = 0;
const int kMonoUpdateIndex = 1;
const int kMonoLateUpdateIndex = 2;
int[] monoUpdates = new int[3];
bool isTesting = false;
{
var gameObject = new GameObject($"{nameof(NetworkUpdateLoopTests)}.{nameof(UpdateStagesMixed)} (Dummy)");
var gameScript = gameObject.AddComponent<MyGameScript>();
gameScript.UpdateCallbacks = new NetworkUpdateCallbacks
{
OnFixedUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetFixedUpdateIndex]++;
Assert.AreEqual(monoUpdates[kMonoFixedUpdateIndex] + 1, netUpdates[kNetFixedUpdateIndex]);
}
},
OnPreUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetPreUpdateIndex]++;
Assert.AreEqual(monoUpdates[kMonoUpdateIndex] + 1, netUpdates[kNetPreUpdateIndex]);
}
},
OnPreLateUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetPreLateUpdateIndex]++;
Assert.AreEqual(monoUpdates[kMonoLateUpdateIndex] + 1, netUpdates[kNetPreLateUpdateIndex]);
}
},
OnPostLateUpdate = () =>
{
if (isTesting)
{
netUpdates[kNetPostLateUpdateIndex]++;
Assert.AreEqual(netUpdates[kNetPostLateUpdateIndex], netUpdates[kNetPreLateUpdateIndex]);
}
}
};
gameScript.BehaviourCallbacks = new MonoBehaviourCallbacks
{
OnFixedUpdate = () =>
{
if (isTesting)
{
monoUpdates[kMonoFixedUpdateIndex]++;
Assert.AreEqual(netUpdates[kNetFixedUpdateIndex], monoUpdates[kMonoFixedUpdateIndex]);
}
},
OnUpdate = () =>
{
if (isTesting)
{
monoUpdates[kMonoUpdateIndex]++;
Assert.AreEqual(netUpdates[kNetPreUpdateIndex], monoUpdates[kMonoUpdateIndex]);
}
},
OnLateUpdate = () =>
{
if (isTesting)
{
monoUpdates[kMonoLateUpdateIndex]++;
Assert.AreEqual(netUpdates[kNetPreLateUpdateIndex], monoUpdates[kMonoLateUpdateIndex]);
}
}
};
int nextFrameNumber = Time.frameCount + 1;
yield return new WaitUntil(() => Time.frameCount >= nextFrameNumber);
isTesting = true;
const int kRunTotalFrames = 16;
int waitFrameNumber = Time.frameCount + kRunTotalFrames;
yield return new WaitUntil(() => Time.frameCount >= waitFrameNumber);
Assert.AreEqual(kRunTotalFrames, netUpdates[kNetPreUpdateIndex]);
Assert.AreEqual(netUpdates[kNetPreUpdateIndex], monoUpdates[kMonoUpdateIndex]);
GameObject.DestroyImmediate(gameObject);
}
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ffdb76de4852b3447b8cd673f0ca3ade
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,195 @@
using System;
using System.Collections.Generic;
using UnityEngine;
using MLAPI.Messaging;
namespace MLAPI.RuntimeTests
{
/// <summary>
/// Used in conjunction with the RpcQueueTest to validate:
/// - Sending and Receiving pipeline to validate that both sending and receiving pipelines are functioning properly.
/// - Usage of the ServerRpcParams.Send.UpdateStage and ClientRpcParams.Send.UpdateStage functionality.
/// - Rpcs receive will be invoked at the appropriate NetworkUpdateStage.
/// </summary>
public class RpcPipelineTestComponent : NetworkBehaviour
{
/// <summary>
/// Allows the external RPCQueueTest to begin testing or stop it
/// </summary>
public bool PingSelfEnabled;
/// <summary>
/// How many times will we iterate through the various NetworkUpdateStage values?
/// (defaults to 2)
/// </summary>
public int MaxIterations = 2;
// Start is called before the first frame update
private void Start()
{
m_ServerParams.Send.UpdateStage = NetworkUpdateStage.Initialization;
m_ClientParams.Send.UpdateStage = NetworkUpdateStage.Update;
m_ServerParams.Receive.UpdateStage = NetworkUpdateStage.Initialization;
m_ClientParams.Receive.UpdateStage = NetworkUpdateStage.Initialization;
m_MaxStagesSent = (Enum.GetValues(typeof(NetworkUpdateStage)).Length) * MaxIterations;
//Start out with this being true (for first sequence)
m_ClientReceivedRpc = true;
}
/// <summary>
/// Determine if we have iterated over more than our maximum stages we want to test
/// </summary>
/// <returns>true or false (did we exceed the max iterations or not?)</returns>
public bool ExceededMaxIterations()
{
if (m_StagesSent.Count > m_MaxStagesSent && m_MaxStagesSent > 0)
{
return true;
}
return false;
}
/// <summary>
/// Returns back whether the test has completed the total number of iterations
/// </summary>
/// <returns></returns>
public bool IsTestComplete()
{
if (m_Counter >= MaxIterations)
{
return true;
}
return false;
}
private bool m_ClientReceivedRpc;
private int m_Counter = 0;
private int m_MaxStagesSent = 0;
private ServerRpcParams m_ServerParams;
private ClientRpcParams m_ClientParams;
private NetworkUpdateStage m_LastUpdateStage;
// Update is called once per frame
private void Update()
{
if (NetworkManager.Singleton.IsListening && PingSelfEnabled && m_ClientReceivedRpc)
{
//Reset this for the next sequence of rpcs
m_ClientReceivedRpc = false;
//As long as testing isn't completed, keep testing
if (!IsTestComplete() && m_StagesSent.Count < m_MaxStagesSent)
{
m_LastUpdateStage = m_ServerParams.Send.UpdateStage;
m_StagesSent.Add(m_LastUpdateStage);
PingMySelfServerRpc(m_StagesSent.Count, m_ServerParams);
switch (m_ServerParams.Send.UpdateStage)
{
case NetworkUpdateStage.Initialization:
m_ServerParams.Send.UpdateStage = NetworkUpdateStage.EarlyUpdate;
break;
case NetworkUpdateStage.EarlyUpdate:
m_ServerParams.Send.UpdateStage = NetworkUpdateStage.FixedUpdate;
break;
case NetworkUpdateStage.FixedUpdate:
m_ServerParams.Send.UpdateStage = NetworkUpdateStage.PreUpdate;
break;
case NetworkUpdateStage.PreUpdate:
m_ServerParams.Send.UpdateStage = NetworkUpdateStage.Update;
break;
case NetworkUpdateStage.Update:
m_ServerParams.Send.UpdateStage = NetworkUpdateStage.PreLateUpdate;
break;
case NetworkUpdateStage.PreLateUpdate:
m_ServerParams.Send.UpdateStage = NetworkUpdateStage.PostLateUpdate;
break;
case NetworkUpdateStage.PostLateUpdate:
m_ServerParams.Send.UpdateStage = NetworkUpdateStage.Initialization;
break;
}
}
}
}
private readonly List<NetworkUpdateStage> m_ServerStagesReceived = new List<NetworkUpdateStage>();
private readonly List<NetworkUpdateStage> m_ClientStagesReceived = new List<NetworkUpdateStage>();
private readonly List<NetworkUpdateStage> m_StagesSent = new List<NetworkUpdateStage>();
/// <summary>
/// Assures all update stages were in alginment with one another
/// </summary>
/// <returns>true or false</returns>
public bool ValidateUpdateStages()
{
var validated = false;
if (m_ServerStagesReceived.Count == m_ClientStagesReceived.Count && m_ClientStagesReceived.Count == m_StagesSent.Count)
{
for (int i = 0; i < m_StagesSent.Count; i++)
{
var currentStage = m_StagesSent[i];
if (m_ServerStagesReceived[i] != currentStage)
{
Debug.Log($"ServerRpc Update Stage ({m_ServerStagesReceived[i]}) is not equal to the current update stage ({currentStage})");
return validated;
}
if (m_ClientStagesReceived[i] != currentStage)
{
Debug.Log($"ClientRpc Update Stage ({m_ClientStagesReceived[i]}) is not equal to the current update stage ({currentStage})");
return validated;
}
}
validated = true;
}
return validated;
}
/// <summary>
/// Server side RPC for testing
/// </summary>
/// <param name="parameters">server rpc parameters</param>
[ServerRpc]
private void PingMySelfServerRpc(int currentCount, ServerRpcParams parameters = default)
{
Debug.Log($"{nameof(PingMySelfServerRpc)}: [HostClient][ServerRpc][{currentCount}] invoked during the {parameters.Receive.UpdateStage} stage.");
m_ClientParams.Send.UpdateStage = parameters.Receive.UpdateStage;
m_ServerStagesReceived.Add(parameters.Receive.UpdateStage);
PingMySelfClientRpc(currentCount, m_ClientParams);
}
/// <summary>
/// Client Side RPC called by PingMySelfServerRPC to validate both Client->Server and Server-Client pipeline is working
/// </summary>
/// <param name="parameters">client rpc parameters</param>
[ClientRpc]
private void PingMySelfClientRpc(int currentCount, ClientRpcParams parameters = default)
{
Debug.Log($"{nameof(PingMySelfClientRpc)}: [HostServer][ClientRpc][{currentCount}] invoked during the {parameters.Receive.UpdateStage} stage. (previous output line should confirm this)");
m_ClientStagesReceived.Add(parameters.Receive.UpdateStage);
//If we reached the last update state, then go ahead and increment our iteration counter
if (parameters.Receive.UpdateStage == NetworkUpdateStage.PostLateUpdate)
{
m_Counter++;
}
m_ClientReceivedRpc = true;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e946a6fdcfcb9dd48b76b38871c0a77b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,106 @@
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.TestTools;
using NUnit.Framework;
using MLAPI.SceneManagement;
using MLAPI.Transports.UNET;
namespace MLAPI.RuntimeTests
{
/// <summary>
/// The RpcQueue unit tests to validate:
/// - Sending and Receiving pipeline to validate that both sending and receiving pipelines are functioning properly.
/// - Usage of the ServerRpcParams.Send.UpdateStage and ClientRpcParams.Send.UpdateStage functionality.
/// - Rpcs receive will be invoked at the appropriate NetworkUpdateStage.
/// Requires: RpcPipelineTestComponent
/// </summary>
public class RpcQueueTests
{
private NetworkManager m_NetworkManager;
/// <summary>
/// Tests the egress and ingress RPC queue functionality
/// ** This does not include any of the MLAPI to Transport code **
/// </summary>
/// <returns>IEnumerator</returns>
[UnityTest]
public IEnumerator RpcQueueUnitTest()
{
var networkManagerObject = new GameObject(nameof(NetworkManager));
m_NetworkManager = networkManagerObject.AddComponent<NetworkManager>();
var unetTransport = networkManagerObject.AddComponent<UNetTransport>();
m_NetworkManager.NetworkConfig = new Configuration.NetworkConfig
{
CreatePlayerPrefab = false,
AllowRuntimeSceneChanges = true,
EnableSceneManagement = false
};
unetTransport.ConnectAddress = "127.0.0.1";
unetTransport.ConnectPort = 7777;
unetTransport.ServerListenPort = 7777;
unetTransport.MessageBufferSize = 65535;
unetTransport.MaxConnections = 100;
unetTransport.MessageSendMode = UNetTransport.SendMode.Immediately;
m_NetworkManager.NetworkConfig.NetworkTransport = unetTransport;
var currentActiveScene = SceneManager.GetActiveScene();
var instantiatedNetworkManager = false;
var testsAreComplete = false;
var testsAreValidated = false;
var exceededMaximumStageIterations = false;
//Add our test scene name
NetworkSceneManager.AddRuntimeSceneName(currentActiveScene.name, 0);
//Create the player object that we will spawn as a host
var playerObject = new GameObject("RpcTestObject");
playerObject.AddComponent<NetworkObject>();
var rpcPipelineTestComponent = playerObject.AddComponent<RpcPipelineTestComponent>();
instantiatedNetworkManager = true;
Debug.Log("NetworkManager Instantiated.");
//Start as host mode as loopback only works in hostmode
NetworkManager.Singleton.StartHost();
Debug.Log("Host Started.");
//Enable the simple ping test
rpcPipelineTestComponent.PingSelfEnabled = true;
Debug.Log("Running RPC Queue Tests...");
//Wait for the rpc pipeline test to complete or if we exceeded the maximum iterations bail
while (!testsAreComplete && !exceededMaximumStageIterations)
{
//Wait for 20ms
yield return new WaitForSeconds(0.02f);
testsAreComplete = rpcPipelineTestComponent.IsTestComplete();
exceededMaximumStageIterations = rpcPipelineTestComponent.ExceededMaxIterations();
}
if (!exceededMaximumStageIterations)
{
testsAreValidated = rpcPipelineTestComponent.ValidateUpdateStages();
}
//Stop pinging
rpcPipelineTestComponent.PingSelfEnabled = false;
Debug.Log("RPC Queue Testing completed.");
//Stop the host
NetworkManager.Singleton.StopHost();
//Shutdown the NetworkManager
NetworkManager.Singleton.Shutdown();
Debug.Log($"Exiting status => {nameof(testsAreComplete)}: {testsAreComplete} - {nameof(testsAreValidated)}: {testsAreValidated} - {nameof(instantiatedNetworkManager)}: {instantiatedNetworkManager} - {nameof(exceededMaximumStageIterations)}: {exceededMaximumStageIterations}");
Assert.IsTrue(testsAreComplete && testsAreValidated && instantiatedNetworkManager);
GameObject.DestroyImmediate(playerObject);
GameObject.DestroyImmediate(networkManagerObject);
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9a96d73d8acaa2a4aadc4e6be8b10c7b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,51 @@
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
namespace MLAPI.RuntimeTests
{
public class TickSystemTests: IDisposable
{
private NetworkTickSystem m_TickSystem = null;
private float m_TestDuration = 3.0f;
private float m_SleepInterval = 0.001f;
private float m_TickInterval = 0.010f;
public void Dispose()
{
m_TickSystem.Dispose();
m_TickSystem = null;
NetworkUpdateLoop.UnregisterLoopSystems();
}
[UnityTest]
public IEnumerator VerifyTickSystem()
{
m_TickSystem = new NetworkTickSystem(m_TickInterval);
var startTick = m_TickSystem.GetTick();
var startTime = Time.unscaledTime;
var lastTick = startTick;
do
{
var currentTick = m_TickSystem.GetTick();
Assert.IsTrue(currentTick >= lastTick); // check monotonicity of ticks
lastTick = currentTick;
yield return new WaitForSeconds(m_SleepInterval);
} while (Time.unscaledTime - startTime <= m_TestDuration);
var endTick = m_TickSystem.GetTick();
var endTime = Time.unscaledTime;
var elapsedTicks = endTick - startTick;
var elapsedTime = endTime - startTime;
var elapsedTicksExpected = (int)(elapsedTime / m_TickInterval);
Assert.Less(Math.Abs(elapsedTicksExpected - elapsedTicks), 2); // +/- 1 is OK
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ecdade6f4bf4c47d09eecf31314cd374
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,11 @@
{
"name": "Unity.Multiplayer.MLAPI.RuntimeTests",
"references": [
"Unity.Multiplayer.MLAPI.Runtime"
],
"optionalUnityReferences": [
"TestAssemblies"
],
"includePlatforms": [],
"excludePlatforms": []
}

View file

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 0d0243c226d5dab4fb5d34006a1ad53b
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant: