diff --git a/com.unity.netcode.gameobjects/Editor/NetworkManagerRelayIntegration.cs b/com.unity.netcode.gameobjects/Editor/NetworkManagerRelayIntegration.cs index a3cfd36d7a..d9d48c003f 100644 --- a/com.unity.netcode.gameobjects/Editor/NetworkManagerRelayIntegration.cs +++ b/com.unity.netcode.gameobjects/Editor/NetworkManagerRelayIntegration.cs @@ -1,4 +1,4 @@ -#if UNITY_2022_3_OR_NEWER && (RELAY_SDK_INSTALLED && !UNITY_WEBGL ) || (RELAY_SDK_INSTALLED && UNITY_WEBGL && UTP_TRANSPORT_2_0_ABOVE) +#if UNITY_2022_3_OR_NEWER && (RELAY_SDK_INSTALLED && !UNITY_WEBGL ) || (RELAY_SDK_INSTALLED && UNITY_WEBGL) using System; using System.Threading.Tasks; using Unity.Netcode.Transports.UTP; @@ -109,9 +109,7 @@ private static UnityTransport GetUnityTransport(NetworkManager networkManager, s { transport = networkManager.gameObject.AddComponent(); } -#if UTP_TRANSPORT_2_0_ABOVE transport.UseWebSockets = connectionType.StartsWith("ws"); // Probably should be part of SetRelayServerData, but not possible at this point -#endif networkManager.NetworkConfig.NetworkTransport = transport; // Force using UnityTransport return transport; } diff --git a/com.unity.netcode.gameobjects/Editor/com.unity.netcode.editor.asmdef b/com.unity.netcode.gameobjects/Editor/com.unity.netcode.editor.asmdef index e80328cfad..490c1b2d55 100644 --- a/com.unity.netcode.gameobjects/Editor/com.unity.netcode.editor.asmdef +++ b/com.unity.netcode.gameobjects/Editor/com.unity.netcode.editor.asmdef @@ -49,11 +49,6 @@ "expression": "1.0", "define": "RELAY_SDK_INSTALLED" }, - { - "name": "com.unity.transport", - "expression": "2.0", - "define": "UTP_TRANSPORT_2_0_ABOVE" - }, { "name": "com.unity.services.multiplayer", "expression": "0.2.0", diff --git a/com.unity.netcode.gameobjects/Runtime/Messaging/NetworkMessageManager.cs b/com.unity.netcode.gameobjects/Runtime/Messaging/NetworkMessageManager.cs index 661fbd74f5..8401ed147a 100644 --- a/com.unity.netcode.gameobjects/Runtime/Messaging/NetworkMessageManager.cs +++ b/com.unity.netcode.gameobjects/Runtime/Messaging/NetworkMessageManager.cs @@ -808,11 +808,7 @@ internal unsafe int SendMessage(ref T message, NetworkDelivery delivery, in N internal unsafe int SendMessage(ref T message, NetworkDelivery delivery, in NativeList clientIds) where T : INetworkMessage { -#if UTP_TRANSPORT_2_0_ABOVE return SendMessage(ref message, delivery, new PointerListWrapper(clientIds.GetUnsafePtr(), clientIds.Length)); -#else - return SendMessage(ref message, delivery, new PointerListWrapper((ulong*)clientIds.GetUnsafePtr(), clientIds.Length)); -#endif } internal unsafe void ProcessSendQueues() diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Serialization/CollectionSerializationUtility.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Serialization/CollectionSerializationUtility.cs index 912bcf94a0..e8c61ceea7 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Serialization/CollectionSerializationUtility.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Serialization/CollectionSerializationUtility.cs @@ -505,13 +505,8 @@ public static void WriteNativeListDelta(FastBufferWriter writer, ref NativeLi writer.WriteValueSafe(changes); unsafe { -#if UTP_TRANSPORT_2_0_ABOVE var ptr = value.GetUnsafePtr(); var prevPtr = previousValue.GetUnsafePtr(); -#else - var ptr = (T*)value.GetUnsafePtr(); - var prevPtr = (T*)previousValue.GetUnsafePtr(); -#endif for (int i = 0; i < value.Length; ++i) { if (changes.IsSet(i)) @@ -554,11 +549,7 @@ public static void ReadNativeListDelta(FastBufferReader reader, ref NativeLis unsafe { -#if UTP_TRANSPORT_2_0_ABOVE var ptr = value.GetUnsafePtr(); -#else - var ptr = (T*)value.GetUnsafePtr(); -#endif for (var i = 0; i < value.Length; ++i) { if (changes.IsSet(i)) @@ -601,11 +592,8 @@ public static unsafe void WriteNativeHashSetDelta(FastBufferWriter writer, re ++removedCount; } } -#if UTP_TRANSPORT_2_0_ABOVE + if (addedCount + removedCount >= value.Count) -#else - if (addedCount + removedCount >= value.Count()) -#endif { writer.WriteByteSafe(1); writer.WriteValueSafe(value); @@ -655,15 +643,10 @@ public static unsafe void WriteNativeHashMapDelta(FastBufferWriter w where TVal : unmanaged { // See WriteDictionary; this is the same algorithm, adjusted for the NativeHashMap API -#if UTP_TRANSPORT_2_0_ABOVE var added = stackalloc KVPair[value.Count]; var changed = stackalloc KVPair[value.Count]; var removed = stackalloc KVPair[previousValue.Count]; -#else - var added = stackalloc KeyValue[value.Count()]; - var changed = stackalloc KeyValue[value.Count()]; - var removed = stackalloc KeyValue[previousValue.Count()]; -#endif + var addedCount = 0; var changedCount = 0; var removedCount = 0; @@ -692,11 +675,7 @@ public static unsafe void WriteNativeHashMapDelta(FastBufferWriter w } } -#if UTP_TRANSPORT_2_0_ABOVE if (addedCount + removedCount + changedCount >= value.Count) -#else - if (addedCount + removedCount + changedCount >= value.Count()) -#endif { writer.WriteByteSafe(1); writer.WriteValueSafe(value); diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Serialization/NetworkVariableEquality.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Serialization/NetworkVariableEquality.cs index c8aecb3869..6b0a3c08c0 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Serialization/NetworkVariableEquality.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Serialization/NetworkVariableEquality.cs @@ -42,13 +42,8 @@ internal static unsafe bool ValueEqualsList(ref NativeList(ref NativeList< return false; } -#if UTP_TRANSPORT_2_0_ABOVE var aptr = a.GetUnsafePtr(); var bptr = b.GetUnsafePtr(); -#else - var aptr = (TValueType*)a.GetUnsafePtr(); - var bptr = (TValueType*)b.GetUnsafePtr(); -#endif + for (var i = 0; i < a.Length; ++i) { if (!EqualityEquals(ref aptr[i], ref bptr[i])) @@ -246,11 +237,7 @@ internal static bool EqualityEqualsNativeHashSet(ref NativeHashSet a, return true; } -#if UTP_TRANSPORT_2_0_ABOVE if (a.Count != b.Count) -#else - if (a.Count() != b.Count()) -#endif { return false; } diff --git a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Serialization/ResizableBitVector.cs b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Serialization/ResizableBitVector.cs index b4b4b76e83..03f351d501 100644 --- a/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Serialization/ResizableBitVector.cs +++ b/com.unity.netcode.gameobjects/Runtime/NetworkVariable/Serialization/ResizableBitVector.cs @@ -95,19 +95,11 @@ public unsafe void NetworkSerialize(BufferSerializer serializer) where T : { if (serializer.IsReader) { -#if UTP_TRANSPORT_2_0_ABOVE serializer.GetFastBufferReader().ReadBytesSafe(ptr, length); -#else - serializer.GetFastBufferReader().ReadBytesSafe((byte*)ptr, length); -#endif } else { -#if UTP_TRANSPORT_2_0_ABOVE serializer.GetFastBufferWriter().WriteBytesSafe(ptr, length); -#else - serializer.GetFastBufferWriter().WriteBytesSafe((byte*)ptr, length); -#endif } } } diff --git a/com.unity.netcode.gameobjects/Runtime/Serialization/FastBufferWriter.cs b/com.unity.netcode.gameobjects/Runtime/Serialization/FastBufferWriter.cs index addd102981..381c92f625 100644 --- a/com.unity.netcode.gameobjects/Runtime/Serialization/FastBufferWriter.cs +++ b/com.unity.netcode.gameobjects/Runtime/Serialization/FastBufferWriter.cs @@ -772,11 +772,7 @@ public unsafe void WriteBytes(NativeArray value, int size = -1, int offset [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void WriteBytes(NativeList value, int size = -1, int offset = 0) { -#if UTP_TRANSPORT_2_0_ABOVE byte* ptr = value.GetUnsafePtr(); -#else - byte* ptr = (byte*)value.GetUnsafePtr(); -#endif WriteBytes(ptr, size == -1 ? value.Length : size, offset); } @@ -820,11 +816,7 @@ public unsafe void WriteBytesSafe(NativeArray value, int size = -1, int of [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void WriteBytesSafe(NativeList value, int size = -1, int offset = 0) { -#if UTP_TRANSPORT_2_0_ABOVE byte* ptr = value.GetUnsafePtr(); -#else - byte* ptr = (byte*)value.GetUnsafePtr(); -#endif WriteBytesSafe(ptr, size == -1 ? value.Length : size, offset); } @@ -1015,11 +1007,7 @@ internal unsafe void WriteUnmanagedSafe(NativeArray value) where T : unman internal unsafe void WriteUnmanaged(NativeList value) where T : unmanaged { WriteLength(value.Length); -#if UTP_TRANSPORT_2_0_ABOVE var ptr = value.GetUnsafePtr(); -#else - var ptr = (T*)value.GetUnsafePtr(); -#endif { byte* bytes = (byte*)ptr; WriteBytes(bytes, sizeof(T) * value.Length); @@ -1029,11 +1017,7 @@ internal unsafe void WriteUnmanaged(NativeList value) where T : unmanaged internal unsafe void WriteUnmanagedSafe(NativeList value) where T : unmanaged { WriteLengthSafe(value.Length); -#if UTP_TRANSPORT_2_0_ABOVE var ptr = value.GetUnsafePtr(); -#else - var ptr = (T*)value.GetUnsafePtr(); -#endif { byte* bytes = (byte*)ptr; WriteBytesSafe(bytes, sizeof(T) * value.Length); @@ -1231,11 +1215,7 @@ public void WriteValue(NativeList value, ForGeneric unused = default) wher [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void WriteValueSafe(NativeHashSet value) where T : unmanaged, IEquatable { -#if UTP_TRANSPORT_2_0_ABOVE WriteLengthSafe(value.Count); -#else - WriteLengthSafe(value.Count()); -#endif foreach (var item in value) { var iReffable = item; @@ -1248,11 +1228,7 @@ internal void WriteValueSafe(NativeHashMap value) where TKey : unmanaged, IEquatable where TVal : unmanaged { -#if UTP_TRANSPORT_2_0_ABOVE WriteLengthSafe(value.Count); -#else - WriteLengthSafe(value.Count()); -#endif foreach (var item in value) { (var key, var val) = (item.Key, item.Value); diff --git a/com.unity.netcode.gameobjects/Runtime/Transports/UTP/BatchedReceiveQueue.cs b/com.unity.netcode.gameobjects/Runtime/Transports/UTP/BatchedReceiveQueue.cs index e0cdeebb49..5551c8062f 100644 --- a/com.unity.netcode.gameobjects/Runtime/Transports/UTP/BatchedReceiveQueue.cs +++ b/com.unity.netcode.gameobjects/Runtime/Transports/UTP/BatchedReceiveQueue.cs @@ -1,9 +1,7 @@ using System; -using Unity.Networking.Transport; -#if UTP_TRANSPORT_2_0_ABOVE using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; -#endif +using Unity.Networking.Transport; namespace Unity.Netcode.Transports.UTP { @@ -29,11 +27,7 @@ public BatchedReceiveQueue(DataStreamReader reader) { fixed (byte* dataPtr = m_Data) { -#if UTP_TRANSPORT_2_0_ABOVE reader.ReadBytesUnsafe(dataPtr, reader.Length); -#else - reader.ReadBytes(dataPtr, reader.Length); -#endif } } @@ -70,11 +64,7 @@ public void PushReader(DataStreamReader reader) { fixed (byte* dataPtr = m_Data) { -#if UTP_TRANSPORT_2_0_ABOVE reader.ReadBytesUnsafe(dataPtr + m_Offset + m_Length, reader.Length); -#else - reader.ReadBytes(dataPtr + m_Offset + m_Length, reader.Length); -#endif } } diff --git a/com.unity.netcode.gameobjects/Runtime/Transports/UTP/BatchedSendQueue.cs b/com.unity.netcode.gameobjects/Runtime/Transports/UTP/BatchedSendQueue.cs index 9e71f36459..cb56bf0026 100644 --- a/com.unity.netcode.gameobjects/Runtime/Transports/UTP/BatchedSendQueue.cs +++ b/com.unity.netcode.gameobjects/Runtime/Transports/UTP/BatchedSendQueue.cs @@ -94,11 +94,7 @@ public void Dispose() /// Write a raw buffer to a DataStreamWriter. private unsafe void WriteBytes(ref DataStreamWriter writer, byte* data, int length) { -#if UTP_TRANSPORT_2_0_ABOVE writer.WriteBytesUnsafe(data, length); -#else - writer.WriteBytes(data, length); -#endif } /// Append data at the tail of the queue. No safety checks. @@ -106,11 +102,7 @@ private void AppendDataAtTail(ArraySegment data) { unsafe { -#if UTP_TRANSPORT_2_0_ABOVE var writer = new DataStreamWriter(m_Data.GetUnsafePtr() + TailIndex, Capacity - TailIndex); -#else - var writer = new DataStreamWriter((byte*)m_Data.GetUnsafePtr() + TailIndex, Capacity - TailIndex); -#endif writer.WriteInt(data.Count); @@ -149,11 +141,7 @@ public bool PushMessage(ArraySegment message) { unsafe { -#if UTP_TRANSPORT_2_0_ABOVE UnsafeUtility.MemMove(m_Data.GetUnsafePtr(), m_Data.GetUnsafePtr() + HeadIndex, Length); -#else - UnsafeUtility.MemMove(m_Data.GetUnsafePtr(), (byte*)m_Data.GetUnsafePtr() + HeadIndex, Length); -#endif } TailIndex = Length; @@ -239,11 +227,7 @@ public int FillWriterWithMessages(ref DataStreamWriter writer, int softMaxBytes if (bytesToWrite > softMaxBytes && bytesToWrite <= writer.Capacity) { writer.WriteInt(messageLength); -#if UTP_TRANSPORT_2_0_ABOVE WriteBytes(ref writer, m_Data.GetUnsafePtr() + reader.GetBytesRead(), messageLength); -#else - WriteBytes(ref writer, (byte*)m_Data.GetUnsafePtr() + reader.GetBytesRead(), messageLength); -#endif return bytesToWrite; } @@ -260,11 +244,7 @@ public int FillWriterWithMessages(ref DataStreamWriter writer, int softMaxBytes if (bytesWritten + bytesToWrite <= softMaxBytes) { writer.WriteInt(messageLength); -#if UTP_TRANSPORT_2_0_ABOVE WriteBytes(ref writer, m_Data.GetUnsafePtr() + reader.GetBytesRead(), messageLength); -#else - WriteBytes(ref writer, (byte*)m_Data.GetUnsafePtr() + reader.GetBytesRead(), messageLength); -#endif readerOffset += bytesToWrite; bytesWritten += bytesToWrite; @@ -308,11 +288,7 @@ public int FillWriterWithBytes(ref DataStreamWriter writer, int maxBytes = 0) unsafe { -#if UTP_TRANSPORT_2_0_ABOVE WriteBytes(ref writer, m_Data.GetUnsafePtr() + HeadIndex, copyLength); -#else - WriteBytes(ref writer, (byte*)m_Data.GetUnsafePtr() + HeadIndex, copyLength); -#endif } return copyLength; diff --git a/com.unity.netcode.gameobjects/Runtime/Transports/UTP/UnityTransport.cs b/com.unity.netcode.gameobjects/Runtime/Transports/UTP/UnityTransport.cs index f08e3cebaa..3bd74f7aab 100644 --- a/com.unity.netcode.gameobjects/Runtime/Transports/UTP/UnityTransport.cs +++ b/com.unity.netcode.gameobjects/Runtime/Transports/UTP/UnityTransport.cs @@ -7,23 +7,17 @@ using System; using System.Collections.Generic; -using UnityEngine; -using NetcodeNetworkEvent = Unity.Netcode.NetworkEvent; -using TransportNetworkEvent = Unity.Networking.Transport.NetworkEvent; using Unity.Burst; -using Unity.Collections.LowLevel.Unsafe; using Unity.Collections; +using Unity.Collections.LowLevel.Unsafe; using Unity.Jobs; using Unity.Networking.Transport; using Unity.Networking.Transport.Relay; -using Unity.Networking.Transport.Utilities; -#if UTP_TRANSPORT_2_0_ABOVE using Unity.Networking.Transport.TLS; -#endif - -#if !UTP_TRANSPORT_2_0_ABOVE -using NetworkEndpoint = Unity.Networking.Transport.NetworkEndPoint; -#endif +using Unity.Networking.Transport.Utilities; +using UnityEngine; +using NetcodeNetworkEvent = Unity.Netcode.NetworkEvent; +using TransportNetworkEvent = Unity.Networking.Transport.NetworkEvent; namespace Unity.Netcode.Transports.UTP { @@ -166,29 +160,30 @@ private enum State [SerializeField] private ProtocolType m_ProtocolType; -#if UTP_TRANSPORT_2_0_ABOVE [Tooltip("Per default the client/server will communicate over UDP. Set to true to communicate with WebSocket.")] [SerializeField] private bool m_UseWebSockets = false; + /// Whether to use WebSockets as the protocol of communication. Default is UDP. public bool UseWebSockets { get => m_UseWebSockets; set => m_UseWebSockets = value; } - /// - /// Per default the client/server communication will not be encrypted. Select true to enable DTLS for UDP and TLS for Websocket. - /// [Tooltip("Per default the client/server communication will not be encrypted. Select true to enable DTLS for UDP and TLS for Websocket.")] [SerializeField] private bool m_UseEncryption = false; + + /// + /// Whether to use encryption (default is false). Note that unless using Unity Relay, encryption requires + /// providing certificate information with and . + /// public bool UseEncryption { get => m_UseEncryption; set => m_UseEncryption = value; } -#endif [Tooltip("The maximum amount of packets that can be in the internal send/receive queues. Basically this is how many packets can be sent/received in a single update/frame.")] [SerializeField] @@ -406,10 +401,8 @@ public struct SimulatorParameters /// - packet drop rate (packet loss) /// -#if UTP_TRANSPORT_2_0_ABOVE [Obsolete("DebugSimulator is no longer supported and has no effect. Use Network Simulator from the Multiplayer Tools package.", false)] [HideInInspector] -#endif public SimulatorParameters DebugSimulator = new SimulatorParameters { PacketDelayMS = 0, @@ -732,11 +725,7 @@ public void SetConnectionData(NetworkEndpoint endPoint, NetworkEndpoint listenEn /// Packet delay in milliseconds. /// Packet jitter in milliseconds. /// Packet drop percentage. - -#if UTP_TRANSPORT_2_0_ABOVE [Obsolete("SetDebugSimulatorParameters is no longer supported and has no effect. Use Network Simulator from the Multiplayer Tools package.", false)] -#endif - public void SetDebugSimulatorParameters(int packetDelay, int packetJitter, int dropRate) { if (m_Driver.IsCreated) @@ -1068,11 +1057,7 @@ private void ExtractNetworkMetricsFromPipeline(NetworkPipeline pipeline, Network //Don't need to dispose of the buffers, they are filled with data pointers. m_Driver.GetPipelineBuffers(pipeline, -#if UTP_TRANSPORT_2_0_ABOVE NetworkPipelineStageId.Get(), -#else - NetworkPipelineStageCollection.GetStageId(typeof(NetworkMetricsPipelineStage)), -#endif networkConnection, out _, out _, @@ -1099,11 +1084,7 @@ private int ExtractRtt(NetworkConnection networkConnection) } m_Driver.GetPipelineBuffers(m_ReliableSequencedPipeline, -#if UTP_TRANSPORT_2_0_ABOVE NetworkPipelineStageId.Get(), -#else - NetworkPipelineStageCollection.GetStageId(typeof(ReliableSequencedPipelineStage)), -#endif networkConnection, out _, out _, @@ -1125,11 +1106,7 @@ private float ExtractPacketLoss(NetworkConnection networkConnection) } m_Driver.GetPipelineBuffers(m_ReliableSequencedPipeline, -#if UTP_TRANSPORT_2_0_ABOVE NetworkPipelineStageId.Get(), -#else - NetworkPipelineStageCollection.GetStageId(typeof(ReliableSequencedPipelineStage)), -#endif networkConnection, out _, out _, @@ -1342,18 +1319,9 @@ public override void Initialize(NetworkManager networkManager = null) // we sometimes notice a lot of useless resends, especially if using Relay. (We can // only do this with UTP 2.0 because 1.X doesn't support that parameter.) m_NetworkSettings.WithReliableStageParameters( - windowSize: 64 -#if UTP_TRANSPORT_2_0_ABOVE - , + windowSize: 64, maximumResendTime: m_ProtocolType == ProtocolType.RelayUnityTransport ? 750 : 500 -#endif ); - -#if !UTP_TRANSPORT_2_0_ABOVE && !UNITY_WEBGL - m_NetworkSettings.WithBaselibNetworkInterfaceParameters( - receiveQueueCapacity: m_MaxPacketQueueSize, - sendQueueCapacity: m_MaxPacketQueueSize); -#endif } /// @@ -1553,8 +1521,7 @@ public override void Shutdown() m_ServerClientId = 0; } -#if UTP_TRANSPORT_2_0_ABOVE - private void ConfigureSimulatorForUtp2() + private void ConfigureSimulator() { // As DebugSimulator is deprecated, the 'packetDelayMs', 'packetJitterMs' and 'packetDropPercentage' // parameters are set to the default and are supposed to be changed using Network Simulator tool instead. @@ -1570,19 +1537,7 @@ private void ConfigureSimulatorForUtp2() m_NetworkSettings.WithNetworkSimulatorParameters(); } -#else - private void ConfigureSimulatorForUtp1() - { - m_NetworkSettings.WithSimulatorStageParameters( - maxPacketCount: 300, // TODO Is there any way to compute a better value? - maxPacketSize: NetworkParameterConstants.MTU, - packetDelayMs: DebugSimulator.PacketDelayMS, - packetJitterMs: DebugSimulator.PacketJitterMS, - packetDropPercentage: DebugSimulator.PacketDropRate, - randomSeed: DebugSimulatorRandomSeed ?? (uint)System.Diagnostics.Stopwatch.GetTimestamp() - ); - } -#endif + /// protected override NetworkTopologyTypes OnCurrentTopology() { @@ -1641,24 +1596,15 @@ public void CreateDriver(UnityTransport transport, out NetworkDriver driver, out NetworkPipeline unreliableSequencedFragmentedPipeline, out NetworkPipeline reliableSequencedPipeline) { -#if MULTIPLAYER_TOOLS_1_0_0_PRE_7 && !UTP_TRANSPORT_2_0_ABOVE - NetworkPipelineStageCollection.RegisterPipelineStage(new NetworkMetricsPipelineStage()); -#endif - -#if UTP_TRANSPORT_2_0_ABOVE && UNITY_MP_TOOLS_NETSIM_IMPLEMENTATION_ENABLED - ConfigureSimulatorForUtp2(); -#elif !UTP_TRANSPORT_2_0_ABOVE && (UNITY_EDITOR || DEVELOPMENT_BUILD) - ConfigureSimulatorForUtp1(); +#if UNITY_MP_TOOLS_NETSIM_IMPLEMENTATION_ENABLED + ConfigureSimulator(); #endif - m_NetworkSettings.WithNetworkConfigParameters( maxConnectAttempts: transport.m_MaxConnectAttempts, connectTimeoutMS: transport.m_ConnectTimeoutMS, disconnectTimeoutMS: transport.m_DisconnectTimeoutMS, -#if UTP_TRANSPORT_2_0_ABOVE sendQueueCapacity: m_MaxPacketQueueSize, receiveQueueCapacity: m_MaxPacketQueueSize, -#endif heartbeatTimeoutMS: transport.m_HeartbeatTimeoutMS); #if UNITY_WEBGL && !UNITY_EDITOR @@ -1683,7 +1629,6 @@ public void CreateDriver(UnityTransport transport, out NetworkDriver driver, } #endif -#if UTP_TRANSPORT_2_0_ABOVE if (m_UseEncryption) { if (m_ProtocolType == ProtocolType.RelayUnityTransport) @@ -1725,9 +1670,7 @@ public void CreateDriver(UnityTransport transport, out NetworkDriver driver, } } } -#endif -#if UTP_TRANSPORT_2_1_ABOVE if (m_ProtocolType == ProtocolType.RelayUnityTransport) { if (m_UseWebSockets && m_RelayServerData.IsWebSocket == 0) @@ -1740,9 +1683,7 @@ public void CreateDriver(UnityTransport transport, out NetworkDriver driver, Debug.LogError("Relay server data indicates usage of WebSockets, but \"Use WebSockets\" checkbox isn't checked under \"Unity Transport\" component."); } } -#endif -#if UTP_TRANSPORT_2_0_ABOVE if (m_UseWebSockets) { driver = NetworkDriver.Create(new WebSocketNetworkInterface(), m_NetworkSettings); @@ -1756,88 +1697,18 @@ public void CreateDriver(UnityTransport transport, out NetworkDriver driver, driver = NetworkDriver.Create(new UDPNetworkInterface(), m_NetworkSettings); #endif } -#else - driver = NetworkDriver.Create(m_NetworkSettings); -#endif -#if MULTIPLAYER_TOOLS_1_0_0_PRE_7 && UTP_TRANSPORT_2_0_ABOVE +#if MULTIPLAYER_TOOLS_1_0_0_PRE_7 driver.RegisterPipelineStage(new NetworkMetricsPipelineStage()); #endif -#if !UTP_TRANSPORT_2_0_ABOVE - SetupPipelinesForUtp1(driver, + SetupPipelines(driver, out unreliableFragmentedPipeline, out unreliableSequencedFragmentedPipeline, out reliableSequencedPipeline); -#else - SetupPipelinesForUtp2(driver, - out unreliableFragmentedPipeline, - out unreliableSequencedFragmentedPipeline, - out reliableSequencedPipeline); -#endif } -#if !UTP_TRANSPORT_2_0_ABOVE - private void SetupPipelinesForUtp1(NetworkDriver driver, - out NetworkPipeline unreliableFragmentedPipeline, - out NetworkPipeline unreliableSequencedFragmentedPipeline, - out NetworkPipeline reliableSequencedPipeline) - { -#if UNITY_EDITOR || DEVELOPMENT_BUILD - if (DebugSimulator.PacketDelayMS > 0 || DebugSimulator.PacketDropRate > 0) - { - unreliableFragmentedPipeline = driver.CreatePipeline( - typeof(FragmentationPipelineStage), - typeof(SimulatorPipelineStage), - typeof(SimulatorPipelineStageInSend) -#if MULTIPLAYER_TOOLS_1_0_0_PRE_7 - , typeof(NetworkMetricsPipelineStage) -#endif - ); - unreliableSequencedFragmentedPipeline = driver.CreatePipeline( - typeof(FragmentationPipelineStage), - typeof(UnreliableSequencedPipelineStage), - typeof(SimulatorPipelineStage), - typeof(SimulatorPipelineStageInSend) -#if MULTIPLAYER_TOOLS_1_0_0_PRE_7 - , typeof(NetworkMetricsPipelineStage) -#endif - ); - reliableSequencedPipeline = driver.CreatePipeline( - typeof(ReliableSequencedPipelineStage), - typeof(SimulatorPipelineStage), - typeof(SimulatorPipelineStageInSend) -#if MULTIPLAYER_TOOLS_1_0_0_PRE_7 - , typeof(NetworkMetricsPipelineStage) -#endif - ); - } - else -#endif - { - unreliableFragmentedPipeline = driver.CreatePipeline( - typeof(FragmentationPipelineStage) -#if MULTIPLAYER_TOOLS_1_0_0_PRE_7 - , typeof(NetworkMetricsPipelineStage) -#endif - ); - unreliableSequencedFragmentedPipeline = driver.CreatePipeline( - typeof(FragmentationPipelineStage), - typeof(UnreliableSequencedPipelineStage) -#if MULTIPLAYER_TOOLS_1_0_0_PRE_7 - , typeof(NetworkMetricsPipelineStage) -#endif - ); - reliableSequencedPipeline = driver.CreatePipeline( - typeof(ReliableSequencedPipelineStage) -#if MULTIPLAYER_TOOLS_1_0_0_PRE_7 - , typeof(NetworkMetricsPipelineStage) -#endif - ); - } - } -#else - private void SetupPipelinesForUtp2(NetworkDriver driver, + private void SetupPipelines(NetworkDriver driver, out NetworkPipeline unreliableFragmentedPipeline, out NetworkPipeline unreliableSequencedFragmentedPipeline, out NetworkPipeline reliableSequencedPipeline) @@ -1874,9 +1745,8 @@ private void SetupPipelinesForUtp2(NetworkDriver driver, #endif ); } -#endif - // -------------- Utility Types ------------------------------------------------------------------------------- + // -------------- Utility Types ------------------------------------------------------------------------------- /// /// Cached information about reliability mode with a certain client diff --git a/com.unity.netcode.gameobjects/Runtime/com.unity.netcode.runtime.asmdef b/com.unity.netcode.gameobjects/Runtime/com.unity.netcode.runtime.asmdef index f1ff7ec13c..d68a562768 100644 --- a/com.unity.netcode.gameobjects/Runtime/com.unity.netcode.runtime.asmdef +++ b/com.unity.netcode.gameobjects/Runtime/com.unity.netcode.runtime.asmdef @@ -38,16 +38,6 @@ "expression": "1.0.0-pre.7", "define": "MULTIPLAYER_TOOLS_1_0_0_PRE_7" }, - { - "name": "com.unity.transport", - "expression": "2.0.0-exp", - "define": "UTP_TRANSPORT_2_0_ABOVE" - }, - { - "name": "com.unity.transport", - "expression": "2.1.0", - "define": "UTP_TRANSPORT_2_1_ABOVE" - }, { "name": "Unity", "expression": "2023", diff --git a/com.unity.netcode.gameobjects/Tests/Editor/Serialization/FastBufferWriterTests.cs b/com.unity.netcode.gameobjects/Tests/Editor/Serialization/FastBufferWriterTests.cs index 98d423169e..53673d5742 100644 --- a/com.unity.netcode.gameobjects/Tests/Editor/Serialization/FastBufferWriterTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Editor/Serialization/FastBufferWriterTests.cs @@ -311,11 +311,7 @@ private unsafe void VerifyArrayEquality(NativeList value, byte* unsafePtr, { int* sizeValue = (int*)(unsafePtr + offset); Assert.AreEqual(value.Length, *sizeValue); -#if UTP_TRANSPORT_2_0_ABOVE var asTPointer = value.GetUnsafePtr(); -#else - var asTPointer = (T*)value.GetUnsafePtr(); -#endif var underlyingTArray = (T*)(unsafePtr + sizeof(int) + offset); for (var i = 0; i < value.Length; ++i) { diff --git a/com.unity.netcode.gameobjects/Tests/Editor/Transports/BatchedReceiveQueueTests.cs b/com.unity.netcode.gameobjects/Tests/Editor/Transports/BatchedReceiveQueueTests.cs index fef8a3b646..97671f906f 100644 --- a/com.unity.netcode.gameobjects/Tests/Editor/Transports/BatchedReceiveQueueTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Editor/Transports/BatchedReceiveQueueTests.cs @@ -2,9 +2,6 @@ using NUnit.Framework; using Unity.Collections; using Unity.Netcode.Transports.UTP; -#if !UTP_TRANSPORT_2_0_ABOVE -using Unity.Networking.Transport; -#endif namespace Unity.Netcode.EditorTests { diff --git a/com.unity.netcode.gameobjects/Tests/Editor/Transports/BatchedSendQueueTests.cs b/com.unity.netcode.gameobjects/Tests/Editor/Transports/BatchedSendQueueTests.cs index 3ad4de1aa8..f27bef95d3 100644 --- a/com.unity.netcode.gameobjects/Tests/Editor/Transports/BatchedSendQueueTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Editor/Transports/BatchedSendQueueTests.cs @@ -2,9 +2,6 @@ using NUnit.Framework; using Unity.Collections; using Unity.Netcode.Transports.UTP; -#if !UTP_TRANSPORT_2_0_ABOVE -using Unity.Networking.Transport; -#endif namespace Unity.Netcode.EditorTests { diff --git a/com.unity.netcode.gameobjects/Tests/Editor/Transports/UnityTransportTests.cs b/com.unity.netcode.gameobjects/Tests/Editor/Transports/UnityTransportTests.cs index 3bf49b64fb..87ffbdb418 100644 --- a/com.unity.netcode.gameobjects/Tests/Editor/Transports/UnityTransportTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Editor/Transports/UnityTransportTests.cs @@ -169,7 +169,6 @@ public void UnityTransport_StartClientFailsWithBadAddress() transport.Shutdown(); } -#if UTP_TRANSPORT_2_0_ABOVE [Test] public void UnityTransport_EmptySecurityStringsShouldThrow([Values("", null)] string cert, [Values("", null)] string secret) { @@ -202,6 +201,5 @@ public void UnityTransport_EmptySecurityStringsShouldThrow([Values("", null)] st } } } -#endif } } diff --git a/com.unity.netcode.gameobjects/Tests/Editor/com.unity.netcode.editortests.asmdef b/com.unity.netcode.gameobjects/Tests/Editor/com.unity.netcode.editortests.asmdef index 56d2377536..b2c942a948 100644 --- a/com.unity.netcode.gameobjects/Tests/Editor/com.unity.netcode.editortests.asmdef +++ b/com.unity.netcode.gameobjects/Tests/Editor/com.unity.netcode.editortests.asmdef @@ -33,11 +33,6 @@ "name": "Unity", "expression": "(0,2022.2.0a5)", "define": "UNITY_UNET_PRESENT" - }, - { - "name": "com.unity.transport", - "expression": "2.0.0-exp", - "define": "UTP_TRANSPORT_2_0_ABOVE" } ] } diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/DistributedAuthority/DistributedAuthorityCodecTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/DistributedAuthority/DistributedAuthorityCodecTests.cs index 2947b5830f..af69df9aa8 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/DistributedAuthority/DistributedAuthorityCodecTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/DistributedAuthority/DistributedAuthorityCodecTests.cs @@ -7,9 +7,7 @@ using Unity.Collections; using Unity.Netcode.TestHelpers.Runtime; using Unity.Netcode.Transports.UTP; -#if UTP_TRANSPORT_2_0_ABOVE using Unity.Networking.Transport; -#endif using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.TestTools; @@ -73,9 +71,6 @@ public void TestAuthorityRpc(byte[] _) protected override void OnOneTimeSetup() { // Prevents the tests from running if no CMB Service is detected -#if !UTP_TRANSPORT_2_0_ABOVE - Assert.Ignore("ignoring DA codec tests because UTP transport must be 2.0"); -#else if (!CanConnectToServer(m_TransportHost, k_TransportPort)) { var shouldFail = Environment.GetEnvironmentVariable("ENSURE_CODEC_TESTS"); @@ -88,7 +83,6 @@ protected override void OnOneTimeSetup() Assert.Fail($"Failed to connect to the rust echo-server at {m_TransportHost}:{k_TransportPort}"); } } -#endif base.OnOneTimeSetup(); } @@ -611,7 +605,6 @@ private IEnumerator SendMessage(ref T message) where T : INetworkMessage return m_ClientCodecHook.WaitForMessageReceived(message); } -#if UTP_TRANSPORT_2_0_ABOVE private static bool CanConnectToServer(string host, ushort port, double timeoutMs = 100) { var address = Dns.GetHostAddresses(host).First(); @@ -636,7 +629,6 @@ private static bool CanConnectToServer(string host, ushort port, double timeoutM driver.Disconnect(connection); return true; } -#endif } internal class CodecTestHooks : INetworkHooks diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/Metrics/PacketLossMetricsTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/Metrics/PacketLossMetricsTests.cs index f02c0b2467..2956f48fda 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/Metrics/PacketLossMetricsTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/Metrics/PacketLossMetricsTests.cs @@ -7,9 +7,7 @@ using Unity.Netcode.TestHelpers.Runtime; using Unity.Netcode.TestHelpers.Runtime.Metrics; using Unity.Netcode.Transports.UTP; -#if UTP_TRANSPORT_2_0_ABOVE using Unity.Networking.Transport.Utilities; -#endif using UnityEngine.TestTools; namespace Unity.Netcode.RuntimeTests.Metrics @@ -28,9 +26,6 @@ public PacketLossMetricsTests() protected override void OnServerAndClientsCreated() { var clientTransport = (UnityTransport)m_ClientNetworkManagers[0].NetworkConfig.NetworkTransport; -#if !UTP_TRANSPORT_2_0_ABOVE - clientTransport.SetDebugSimulatorParameters(0, 0, m_PacketLossRate); -#endif // Determined through trial and error. With both UTP 1.2 and 2.0, this random seed // results in an effective packet loss percentage between 22% and 28%. Future UTP @@ -68,12 +63,10 @@ public IEnumerator TrackPacketLossAsClient() double packetLossRateMaxrange = (m_PacketLossRate + m_PacketLossRangeDelta) / 100d; var clientNetworkManager = m_ClientNetworkManagers[0]; -#if UTP_TRANSPORT_2_0_ABOVE var clientTransport = (UnityTransport)clientNetworkManager.NetworkConfig.NetworkTransport; clientTransport.NetworkDriver.CurrentSettings.TryGet(out var parameters); parameters.PacketDropPercentage = m_PacketLossRate; clientTransport.NetworkDriver.ModifySimulatorStageParameters(parameters); -#endif var waitForPacketLossMetric = new WaitForGaugeMetricValues((clientNetworkManager.NetworkMetrics as NetworkMetrics).Dispatcher, NetworkMetricTypes.PacketLoss, diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformPacketLossTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformPacketLossTests.cs deleted file mode 100644 index 480905c68b..0000000000 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformPacketLossTests.cs +++ /dev/null @@ -1,501 +0,0 @@ -// TODO: Rewrite test to use the tools package. Debug simulator not available in UTP 2.X. -#if !UTP_TRANSPORT_2_0_ABOVE -using System.Collections; -using NUnit.Framework; -using Unity.Netcode.Components; -using UnityEngine; -using UnityEngine.TestTools; - -namespace Unity.Netcode.RuntimeTests -{ - /// - /// Integration tests for NetworkTransform that will test both - /// server and host operating modes and will test both authoritative - /// models for each operating mode when packet loss and latency is - /// present. - /// - [TestFixture(HostOrServer.DAHost, Authority.OwnerAuthority, RotationCompression.None, Rotation.Euler, Precision.Full)] - [TestFixture(HostOrServer.DAHost, Authority.OwnerAuthority, RotationCompression.None, Rotation.Euler, Precision.Half)] - [TestFixture(HostOrServer.DAHost, Authority.OwnerAuthority, RotationCompression.None, Rotation.Quaternion, Precision.Full)] - [TestFixture(HostOrServer.DAHost, Authority.OwnerAuthority, RotationCompression.None, Rotation.Quaternion, Precision.Half)] - [TestFixture(HostOrServer.DAHost, Authority.OwnerAuthority, RotationCompression.QuaternionCompress, Rotation.Quaternion, Precision.Full)] - [TestFixture(HostOrServer.DAHost, Authority.OwnerAuthority, RotationCompression.QuaternionCompress, Rotation.Quaternion, Precision.Half)] - [TestFixture(HostOrServer.Host, Authority.ServerAuthority, RotationCompression.None, Rotation.Euler, Precision.Full)] - [TestFixture(HostOrServer.Host, Authority.ServerAuthority, RotationCompression.None, Rotation.Euler, Precision.Half)] - [TestFixture(HostOrServer.Host, Authority.ServerAuthority, RotationCompression.None, Rotation.Quaternion, Precision.Full)] - [TestFixture(HostOrServer.Host, Authority.ServerAuthority, RotationCompression.None, Rotation.Quaternion, Precision.Half)] - [TestFixture(HostOrServer.Host, Authority.ServerAuthority, RotationCompression.QuaternionCompress, Rotation.Quaternion, Precision.Full)] - [TestFixture(HostOrServer.Host, Authority.ServerAuthority, RotationCompression.QuaternionCompress, Rotation.Quaternion, Precision.Half)] - internal class NetworkTransformPacketLossTests : NetworkTransformBase - { - private const int k_Latency = 50; - private const int k_PacketLoss = 2; - - private Vector3 m_RandomPosition; - private Vector3 m_TeleportOffset = new Vector3(-1024f, 0f, 0f); - private bool m_Teleported; - - /// - /// Constructor - /// - /// Determines if we are running as a server or host - /// Determines if we are using server or owner authority - public NetworkTransformPacketLossTests(HostOrServer testWithHost, Authority authority, RotationCompression rotationCompression, Rotation rotation, Precision precision) : - base(testWithHost, authority, rotationCompression, rotation, precision) - { } - - protected override void OnServerAndClientsCreated() - { - base.OnServerAndClientsCreated(); - - var unityTransport = m_ServerNetworkManager.NetworkConfig.NetworkTransport as Transports.UTP.UnityTransport; - unityTransport.SetDebugSimulatorParameters(k_Latency, 0, k_PacketLoss); - } - - /// - /// Handles validating all children of the test objects have matching local and global space vaues. - /// - private IEnumerator AllChildrenLocalTransformValuesMatch(bool useSubChild, ChildrenTransformCheckType checkType) - { - // We don't assert on timeout here because we want to log this information during PostAllChildrenLocalTransformValuesMatch - yield return WaitForConditionOrTimeOut(() => AllInstancesKeptLocalTransformValues(useSubChild)); - var success = true; - if (s_GlobalTimeoutHelper.TimedOut) - { - var waitForMs = new WaitForSeconds(0.0025f); - if (m_Precision == Precision.Half) - { - m_CurrentHalfPrecision = 0.2156f; - } - // If we timed out, then wait for a full range of ticks to assure all data has been synchronized before declaring this a failed test. - for (int j = 0; j < m_ServerNetworkManager.NetworkConfig.TickRate; j++) - { - m_InfoMessage.Clear(); - m_InfoMessage.AppendLine($"[{checkType}][{useSubChild}] Timed out waiting for all children to have the correct local space values:\n"); - var instances = useSubChild ? ChildObjectComponent.SubInstances : ChildObjectComponent.Instances; - success = PostAllChildrenLocalTransformValuesMatch(useSubChild); - yield return waitForMs; - } - } - - if (!success) - { - Assert.True(success, m_InfoMessage.ToString()); - } - } - - /// - /// Validates that transform values remain the same when a NetworkTransform is - /// parented under another NetworkTransform under all of the possible axial conditions - /// as well as when the parent has a varying scale. - /// - [UnityTest] - public IEnumerator ParentedNetworkTransformTest([Values] Interpolation interpolation, [Values] bool worldPositionStays, [Values(0.5f, 1.0f, 5.0f)] float scale) - { - ChildObjectComponent.EnableChildLog = m_EnableVerboseDebug; - if (m_EnableVerboseDebug) - { - ChildObjectComponent.TestCount++; - } - // Get the NetworkManager that will have authority in order to spawn with the correct authority - var isServerAuthority = m_Authority == Authority.ServerAuthority; - var authorityNetworkManager = m_ServerNetworkManager; - if (!isServerAuthority) - { - authorityNetworkManager = m_ClientNetworkManagers[0]; - } - - // Spawn a parent and children - ChildObjectComponent.HasSubChild = true; - var serverSideParent = SpawnObject(m_ParentObject.gameObject, authorityNetworkManager).GetComponent(); - var serverSideChild = SpawnObject(m_ChildObject.gameObject, authorityNetworkManager).GetComponent(); - var serverSideSubChild = SpawnObject(m_SubChildObject.gameObject, authorityNetworkManager).GetComponent(); - - yield return s_DefaultWaitForTick; - yield return s_DefaultWaitForTick; - yield return s_DefaultWaitForTick; - yield return s_DefaultWaitForTick; - - // Assure all of the child object instances are spawned before proceeding to parenting - yield return WaitForConditionOrTimeOut(AllChildObjectInstancesAreSpawned); - AssertOnTimeout("Timed out waiting for all child instances to be spawned!"); - - // Get the authority parent and child instances - m_AuthorityParentObject = NetworkTransformTestComponent.AuthorityInstance.NetworkObject; - m_AuthorityChildObject = ChildObjectComponent.AuthorityInstance.NetworkObject; - m_AuthoritySubChildObject = ChildObjectComponent.AuthoritySubInstance.NetworkObject; - - // The child NetworkTransform will use world space when world position stays and - // local space when world position does not stay when parenting. - ChildObjectComponent.AuthorityInstance.InLocalSpace = !worldPositionStays; - ChildObjectComponent.AuthorityInstance.UseHalfFloatPrecision = m_Precision == Precision.Half; - ChildObjectComponent.AuthorityInstance.UseQuaternionSynchronization = m_Rotation == Rotation.Quaternion; - ChildObjectComponent.AuthorityInstance.UseQuaternionCompression = m_RotationCompression == RotationCompression.QuaternionCompress; - - ChildObjectComponent.AuthoritySubInstance.InLocalSpace = !worldPositionStays; - ChildObjectComponent.AuthoritySubInstance.UseHalfFloatPrecision = m_Precision == Precision.Half; - ChildObjectComponent.AuthoritySubInstance.UseQuaternionSynchronization = m_Rotation == Rotation.Quaternion; - ChildObjectComponent.AuthoritySubInstance.UseQuaternionCompression = m_RotationCompression == RotationCompression.QuaternionCompress; - - // Set whether we are interpolating or not - m_AuthorityParentNetworkTransform = m_AuthorityParentObject.GetComponent(); - m_AuthorityParentNetworkTransform.Interpolate = interpolation == Interpolation.EnableInterpolate; - m_AuthorityChildNetworkTransform = m_AuthorityChildObject.GetComponent(); - m_AuthorityChildNetworkTransform.Interpolate = interpolation == Interpolation.EnableInterpolate; - m_AuthoritySubChildNetworkTransform = m_AuthoritySubChildObject.GetComponent(); - m_AuthoritySubChildNetworkTransform.Interpolate = interpolation == Interpolation.EnableInterpolate; - - - // Apply a scale to the parent object to make sure the scale on the child is properly updated on - // non-authority instances. - var halfScale = scale * 0.5f; - m_AuthorityParentObject.transform.localScale = GetRandomVector3(scale - halfScale, scale + halfScale); - m_AuthorityChildObject.transform.localScale = GetRandomVector3(scale - halfScale, scale + halfScale); - m_AuthoritySubChildObject.transform.localScale = GetRandomVector3(scale - halfScale, scale + halfScale); - - // Allow one tick for authority to update these changes - - yield return WaitForConditionOrTimeOut(PositionRotationScaleMatches); - - AssertOnTimeout("All transform values did not match prior to parenting!"); - - // Parent the child under the parent with the current world position stays setting - Assert.True(serverSideChild.TrySetParent(serverSideParent.transform, worldPositionStays), "[Server-Side Child] Failed to set child's parent!"); - - // Parent the sub-child under the child with the current world position stays setting - Assert.True(serverSideSubChild.TrySetParent(serverSideChild.transform, worldPositionStays), "[Server-Side SubChild] Failed to set sub-child's parent!"); - - // This waits for all child instances to be parented - yield return WaitForConditionOrTimeOut(AllChildObjectInstancesHaveChild); - AssertOnTimeout("Timed out waiting for all instances to have parented a child!"); - var latencyWait = new WaitForSeconds(k_Latency * 0.003f); - // Wait for at least 3x designated latency period - yield return latencyWait; - - // This validates each child instance has preserved their local space values - yield return AllChildrenLocalTransformValuesMatch(false, ChildrenTransformCheckType.Connected_Clients); - - // This validates each sub-child instance has preserved their local space values - yield return AllChildrenLocalTransformValuesMatch(true, ChildrenTransformCheckType.Connected_Clients); - - // Verify that a late joining client will synchronize to the parented NetworkObjects properly - yield return CreateAndStartNewClient(); - - // Assure all of the child object instances are spawned (basically for the newly connected client) - yield return WaitForConditionOrTimeOut(AllChildObjectInstancesAreSpawned); - AssertOnTimeout("Timed out waiting for all child instances to be spawned!"); - - // This waits for all child instances to be parented - yield return WaitForConditionOrTimeOut(AllChildObjectInstancesHaveChild); - AssertOnTimeout("Timed out waiting for all instances to have parented a child!"); - - // Wait for at least 3x designated latency period - yield return latencyWait; - - // This validates each child instance has preserved their local space values - yield return AllChildrenLocalTransformValuesMatch(false, ChildrenTransformCheckType.Late_Join_Client); - - // This validates each sub-child instance has preserved their local space values - yield return AllChildrenLocalTransformValuesMatch(true, ChildrenTransformCheckType.Late_Join_Client); - } - - /// - /// This validates that multiple changes can occur within the same tick or over - /// several ticks while still keeping non-authoritative instances synchronized. - /// - /// - /// When testing < 3 axis: Interpolation is disabled and only 3 delta updates are applied per unique test - /// When testing 3 axis: Interpolation is enabled, sometimes an axis is intentionally excluded during a - /// delta update, and it runs through 8 delta updates per unique test. - /// - [UnityTest] - public IEnumerator NetworkTransformMultipleChangesOverTime([Values] TransformSpace testLocalTransform, [Values] Axis axis) - { - yield return s_DefaultWaitForTick; - // Just test for OverrideState.Update (they are already being tested for functionality in normal NetworkTransformTests) - var overideState = OverrideState.Update; - var tickRelativeTime = new WaitForSeconds(1.0f / m_ServerNetworkManager.NetworkConfig.TickRate); - m_AuthoritativeTransform.InLocalSpace = testLocalTransform == TransformSpace.Local; - bool axisX = axis == Axis.X || axis == Axis.XY || axis == Axis.XZ || axis == Axis.XYZ; - bool axisY = axis == Axis.Y || axis == Axis.XY || axis == Axis.YZ || axis == Axis.XYZ; - bool axisZ = axis == Axis.Z || axis == Axis.XZ || axis == Axis.YZ || axis == Axis.XYZ; - - var axisCount = axisX ? 1 : 0; - axisCount += axisY ? 1 : 0; - axisCount += axisZ ? 1 : 0; - - m_AuthoritativeTransform.StatePushed = false; - // Enable interpolation when all 3 axis are selected to make sure we are synchronizing properly - // when interpolation is enabled. - m_AuthoritativeTransform.Interpolate = axisCount == 3 ? true : false; - - m_CurrentAxis = axis; - - // Authority dictates what is synchronized and what the precision is going to be - // so we only need to set this on the authoritative side. - m_AuthoritativeTransform.UseHalfFloatPrecision = m_Precision == Precision.Half; - m_AuthoritativeTransform.UseQuaternionSynchronization = m_Rotation == Rotation.Quaternion; - m_AuthoritativeTransform.UseQuaternionCompression = m_RotationCompression == RotationCompression.QuaternionCompress; - - m_AuthoritativeTransform.SyncPositionX = axisX; - m_AuthoritativeTransform.SyncPositionY = axisY; - m_AuthoritativeTransform.SyncPositionZ = axisZ; - - if (!m_AuthoritativeTransform.UseQuaternionSynchronization) - { - m_AuthoritativeTransform.SyncRotAngleX = axisX; - m_AuthoritativeTransform.SyncRotAngleY = axisY; - m_AuthoritativeTransform.SyncRotAngleZ = axisZ; - } - else - { - // This is not required for usage (setting the value should not matter when quaternion synchronization is enabled) - // but is required for this test so we don't get a failure on an axis that is marked to not be synchronized when - // validating the authority's values on non-authority instances. - m_AuthoritativeTransform.SyncRotAngleX = true; - m_AuthoritativeTransform.SyncRotAngleY = true; - m_AuthoritativeTransform.SyncRotAngleZ = true; - } - - m_AuthoritativeTransform.SyncScaleX = axisX; - m_AuthoritativeTransform.SyncScaleY = axisY; - m_AuthoritativeTransform.SyncScaleZ = axisZ; - - var positionStart = GetRandomVector3(0.25f, 1.75f); - var rotationStart = GetRandomVector3(1f, 15f); - var scaleStart = GetRandomVector3(0.25f, 2.0f); - var position = positionStart; - var rotation = rotationStart; - var scale = scaleStart; - var success = false; - - - // Wait for the deltas to be pushed - yield return WaitForConditionOrTimeOut(() => m_AuthoritativeTransform.StatePushed); - - // Just in case we drop the first few state updates - if (s_GlobalTimeoutHelper.TimedOut) - { - // Set the local state to not reflect the authority state's local space settings - // to trigger the state update (it would eventually get there, but this is an integration test) - var state = m_AuthoritativeTransform.LocalAuthoritativeNetworkState; - state.InLocalSpace = !m_AuthoritativeTransform.InLocalSpace; - m_AuthoritativeTransform.LocalAuthoritativeNetworkState = state; - // Wait for the deltas to be pushed - yield return WaitForConditionOrTimeOut(() => m_AuthoritativeTransform.StatePushed); - } - AssertOnTimeout("State was never pushed!"); - - // Allow the precision settings to propagate first as changing precision - // causes a teleport event to occur - yield return s_DefaultWaitForTick; - yield return s_DefaultWaitForTick; - yield return s_DefaultWaitForTick; - yield return s_DefaultWaitForTick; - yield return s_DefaultWaitForTick; - var iterations = axisCount == 3 ? k_PositionRotationScaleIterations3Axis : k_PositionRotationScaleIterations; - - // Move and rotate within the same tick, validate the non-authoritative instance updates - // to each set of changes. Repeat several times. - for (int i = 0; i < iterations; i++) - { - // Always reset this per delta update pass - m_AxisExcluded = false; - var deltaPositionDelta = GetRandomVector3(-1.5f, 1.5f); - var deltaRotationDelta = GetRandomVector3(-3.5f, 3.5f); - var deltaScaleDelta = GetRandomVector3(-0.5f, 0.5f); - - m_NonAuthoritativeTransform.StateUpdated = false; - m_AuthoritativeTransform.StatePushed = false; - - // With two or more axis, excluding one of them while chaging another will validate that - // full precision updates are maintaining their target state value(s) to interpolate towards - if (axisCount == 3) - { - position += RandomlyExcludeAxis(deltaPositionDelta); - rotation += RandomlyExcludeAxis(deltaRotationDelta); - scale += RandomlyExcludeAxis(deltaScaleDelta); - } - else - { - position += deltaPositionDelta; - rotation += deltaRotationDelta; - scale += deltaScaleDelta; - } - - // Apply delta between ticks - MoveRotateAndScaleAuthority(position, rotation, scale, overideState); - - // Wait for the deltas to be pushed (unlike the original test, we don't wait for state to be updated as that could be dropped here) - yield return WaitForConditionOrTimeOut(() => m_AuthoritativeTransform.StatePushed); - AssertOnTimeout($"[Non-Interpolate {i}] Timed out waiting for state to be pushed ({m_AuthoritativeTransform.StatePushed})!"); - - // For 3 axis, we will skip validating that the non-authority interpolates to its target point at least once. - // This will validate that non-authoritative updates are maintaining their target state axis values if only 2 - // of the axis are being updated to assure interpolation maintains the targeted axial value per axis. - // For 2 and 1 axis tests we always validate per delta update - if (m_AxisExcluded || axisCount < 3) - { - // Wait for deltas to synchronize on non-authoritative side - yield return WaitForConditionOrTimeOut(PositionRotationScaleMatches); - // Provide additional debug info about what failed (if it fails) - if (s_GlobalTimeoutHelper.TimedOut) - { - Debug.Log("[Synch Issue Start - 1]"); - // If we timed out, then wait for a full range of ticks (plus 1) to assure it sent synchronization data. - for (int j = 0; j < m_ServerNetworkManager.NetworkConfig.TickRate * 2; j++) - { - success = PositionRotationScaleMatches(); - if (success) - { - // If we matched, then something was dropped and recovered when synchronized - break; - } - yield return s_DefaultWaitForTick; - } - - // Only if we still didn't match - if (!success) - { - m_EnableVerboseDebug = true; - success = PositionRotationScaleMatches(); - m_EnableVerboseDebug = false; - Debug.Log("[Synch Issue END - 1]"); - AssertOnTimeout($"[Non-Interpolate {i}] Timed out waiting for non-authority to match authority's position or rotation"); - } - } - } - } - - if (axisCount == 3) - { - // As a final test, wait for deltas to synchronize on non-authoritative side to assure it interpolates to the correct values - yield return WaitForConditionOrTimeOut(PositionRotationScaleMatches); - // Provide additional debug info about what failed (if it fails) - if (s_GlobalTimeoutHelper.TimedOut) - { - Debug.Log("[Synch Issue Start - 2]"); - // If we timed out, then wait for a full range of ticks (plus 1) to assure it sent synchronization data. - for (int j = 0; j < m_ServerNetworkManager.NetworkConfig.TickRate * 2; j++) - { - success = PositionRotationScaleMatches(); - if (success) - { - // If we matched, then something was dropped and recovered when synchronized - break; - } - yield return s_DefaultWaitForTick; - } - - // Only if we still didn't match - if (!success) - { - m_EnableVerboseDebug = true; - PositionRotationScaleMatches(); - m_EnableVerboseDebug = false; - Debug.Log("[Synch Issue END - 2]"); - AssertOnTimeout("Timed out waiting for non-authority to match authority's position or rotation"); - - } - } - - } - } - - /// - /// Tests changing all axial values one at a time with packet loss - /// These tests are performed: - /// - While in local space and world space - /// - While interpolation is enabled and disabled - /// - [UnityTest] - public IEnumerator TestAuthoritativeTransformChangeOneAtATime([Values] TransformSpace testLocalTransform, [Values] Interpolation interpolation) - { - // Just test for OverrideState.Update (they are already being tested for functionality in normal NetworkTransformTests) - m_AuthoritativeTransform.Interpolate = interpolation == Interpolation.EnableInterpolate; - m_AuthoritativeTransform.InLocalSpace = testLocalTransform == TransformSpace.Local; - m_AuthoritativeTransform.UseQuaternionCompression = m_RotationCompression == RotationCompression.QuaternionCompress; - m_AuthoritativeTransform.UseHalfFloatPrecision = m_Precision == Precision.Half; - m_AuthoritativeTransform.UseQuaternionSynchronization = m_Rotation == Rotation.Quaternion; - m_NonAuthoritativeTransform.Interpolate = interpolation == Interpolation.EnableInterpolate; - - - // test position - var authPlayerTransform = m_AuthoritativeTransform.transform; - - Assert.AreEqual(Vector3.zero, m_NonAuthoritativeTransform.transform.position, "server side pos should be zero at first"); // sanity check - - m_AuthoritativeTransform.transform.position = GetRandomVector3(2f, 30f); - - yield return WaitForConditionOrTimeOut(() => PositionsMatch()); - AssertOnTimeout($"Timed out waiting for positions to match {m_AuthoritativeTransform.transform.position} | {m_NonAuthoritativeTransform.transform.position}"); - - // test rotation - Assert.AreEqual(Quaternion.identity, m_NonAuthoritativeTransform.transform.rotation, "wrong initial value for rotation"); // sanity check - - m_AuthoritativeTransform.transform.rotation = Quaternion.Euler(GetRandomVector3(5, 60)); // using euler angles instead of quaternions directly to really see issues users might encounter - - // Make sure the values match - yield return WaitForConditionOrTimeOut(() => RotationsMatch()); - AssertOnTimeout($"Timed out waiting for rotations to match"); - - m_AuthoritativeTransform.StatePushed = false; - m_AuthoritativeTransform.transform.localScale = GetRandomVector3(1, 6); - - // Make sure the scale values match - yield return WaitForConditionOrTimeOut(() => ScaleValuesMatch()); - AssertOnTimeout($"Timed out waiting for scale values to match"); - } - - [UnityTest] - public IEnumerator TestSameFrameDeltaStateAndTeleport([Values] TransformSpace testLocalTransform, [Values] Interpolation interpolation) - { - m_AuthoritativeTransform.Interpolate = interpolation == Interpolation.EnableInterpolate; - - m_NonAuthoritativeTransform.Interpolate = interpolation == Interpolation.EnableInterpolate; - - m_AuthoritativeTransform.InLocalSpace = testLocalTransform == TransformSpace.Local; - - // test position - var authPlayerTransform = m_AuthoritativeTransform.transform; - - Assert.AreEqual(Vector3.zero, m_NonAuthoritativeTransform.transform.position, "server side pos should be zero at first"); // sanity check - - m_AuthoritativeTransform.AuthorityPushedTransformState += OnAuthorityPushedTransformState; - m_RandomPosition = GetRandomVector3(2f, 30f); - m_AuthoritativeTransform.transform.position = m_RandomPosition; - m_Teleported = false; - yield return WaitForConditionOrTimeOut(() => m_Teleported); - AssertOnTimeout($"Timed out waiting for random position to be pushed!"); - - yield return WaitForConditionOrTimeOut(() => PositionsMatch()); - AssertOnTimeout($"Timed out waiting for positions to match {m_AuthoritativeTransform.transform.position} | {m_NonAuthoritativeTransform.transform.position}"); - - var authPosition = m_AuthoritativeTransform.GetSpaceRelativePosition(); - var nonAuthPosition = m_NonAuthoritativeTransform.GetSpaceRelativePosition(); - - var finalPosition = m_TeleportOffset + m_RandomPosition; - Assert.True(Approximately(authPosition, finalPosition), $"Authority did not set its position ({authPosition}) to the teleport position ({finalPosition})!"); - Assert.True(Approximately(nonAuthPosition, finalPosition), $"NonAuthority did not set its position ({nonAuthPosition}) to the teleport position ({finalPosition})!"); - } - - /// - /// For the TestSameFrameDeltaStateAndTeleport test, we want to teleport on the same frame that we had a delta state update when - /// using unreliable delta state updates (i.e. we want the unreliable packet to be sent first and then the teleport to be sent on - /// the next tick. Store off both states when invoked - /// - /// - private void OnAuthorityPushedTransformState(ref NetworkTransform.NetworkTransformState networkTransformState) - { - // Match the first position update - if (Approximately(m_RandomPosition, networkTransformState.GetPosition())) - { - // Teleport to the m_RandomPosition plus the - m_AuthoritativeTransform.SetState(m_TeleportOffset + m_RandomPosition, null, null, false); - m_AuthoritativeTransform.AuthorityPushedTransformState -= OnAuthorityPushedTransformState; - m_Teleported = true; - } - } - } -} -#endif diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformPacketLossTests.cs.meta b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformPacketLossTests.cs.meta deleted file mode 100644 index c363dc6cc9..0000000000 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkTransform/NetworkTransformPacketLossTests.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: e0f584e8eb891d5459373e96e54fe821 -timeCreated: 1620872927 \ No newline at end of file diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariable/NetworkVariableTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariable/NetworkVariableTests.cs index 28d1def735..35718a474a 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariable/NetworkVariableTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/NetworkVariable/NetworkVariableTests.cs @@ -3939,11 +3939,7 @@ public string NativeHashMapStr(NativeHashMap list) for (var i = 0; i < changed2Removes; ++i) { -#if UTP_TRANSPORT_2_0_ABOVE var which = rand.Next(changed2.Count); -#else - var which = rand.Next(changed2.Count()); -#endif T toRemove = default; foreach (var check in changed2) { @@ -4016,11 +4012,7 @@ public string NativeHashMapStr(NativeHashMap list) for (var i = 0; i < changed2Removes; ++i) { -#if UTP_TRANSPORT_2_0_ABOVE var which = rand.Next(changed2.Count); -#else - var which = rand.Next(changed2.Count()); -#endif TKey toRemove = default; foreach (var check in changed2) { @@ -4037,11 +4029,7 @@ public string NativeHashMapStr(NativeHashMap list) for (var i = 0; i < changed2Changes; ++i) { -#if UTP_TRANSPORT_2_0_ABOVE var which = rand.Next(changed2.Count); -#else - var which = rand.Next(changed2.Count()); -#endif TKey key = default; foreach (var check in changed2) { diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/Transports/UnityTransportDriverClient.cs b/com.unity.netcode.gameobjects/Tests/Runtime/Transports/UnityTransportDriverClient.cs index ef8ca268e4..b0ed59dccc 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/Transports/UnityTransportDriverClient.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/Transports/UnityTransportDriverClient.cs @@ -64,11 +64,7 @@ private void OnDestroy() public void Connect() { -#if UTP_TRANSPORT_2_0_ABOVE var endpoint = NetworkEndpoint.LoopbackIpv4; -#else - var endpoint = NetworkEndPoint.LoopbackIpv4; -#endif endpoint.Port = 7777; m_Connection = m_Driver.Connect(endpoint); diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/Transports/UnityTransportTests.cs b/com.unity.netcode.gameobjects/Tests/Runtime/Transports/UnityTransportTests.cs index 711a4f3bef..4cd33fcc9b 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/Transports/UnityTransportTests.cs +++ b/com.unity.netcode.gameobjects/Tests/Runtime/Transports/UnityTransportTests.cs @@ -367,63 +367,6 @@ public IEnumerator SendCompletesOnUnreliableSendQueueOverflow() } } -#if !UTP_TRANSPORT_2_0_ABOVE - // Check that simulator parameters are effective. We only check with the drop rate, because - // that's easy to check and we only really want to make sure the simulator parameters are - // configured properly (the simulator pipeline stage is already well-tested in UTP). - [UnityTest] - [UnityPlatform(include = new[] { RuntimePlatform.OSXEditor, RuntimePlatform.WindowsEditor, RuntimePlatform.LinuxEditor })] - public IEnumerator SimulatorParametersAreEffective() - { - InitializeTransport(out m_Server, out m_ServerEvents); - InitializeTransport(out m_Client1, out m_Client1Events); - - m_Server.SetDebugSimulatorParameters(0, 0, 100); - - m_Server.StartServer(); - m_Client1.StartClient(); - - yield return WaitForNetworkEvent(NetworkEvent.Connect, m_Client1Events); - - var data = new ArraySegment(new byte[] { 42 }); - m_Client1.Send(m_Client1.ServerClientId, data, NetworkDelivery.Reliable); - - yield return new WaitForSeconds(MaxNetworkEventWaitTime); - - Assert.AreEqual(1, m_ServerEvents.Count); - - yield return null; - } - - // Check that RTT is reported correctly. - [UnityTest] - [UnityPlatform(include = new[] { RuntimePlatform.OSXEditor, RuntimePlatform.WindowsEditor, RuntimePlatform.LinuxEditor })] - public IEnumerator CurrentRttReportedCorrectly() - { - const int simulatedRtt = 25; - - InitializeTransport(out m_Server, out m_ServerEvents); - InitializeTransport(out m_Client1, out m_Client1Events); - - m_Server.SetDebugSimulatorParameters(simulatedRtt, 0, 0); - - m_Server.StartServer(); - m_Client1.StartClient(); - - yield return WaitForNetworkEvent(NetworkEvent.Connect, m_Client1Events); - - var data = new ArraySegment(new byte[] { 42 }); - m_Client1.Send(m_Client1.ServerClientId, data, NetworkDelivery.Reliable); - - yield return WaitForNetworkEvent(NetworkEvent.Data, m_ServerEvents, - timeout: MaxNetworkEventWaitTime + (2 * simulatedRtt)); - - Assert.GreaterOrEqual(m_Client1.GetCurrentRtt(m_Client1.ServerClientId), simulatedRtt); - - yield return null; - } -#endif - [UnityTest] public IEnumerator SendQueuesFlushedOnShutdown([ValueSource("k_DeliveryParameters")] NetworkDelivery delivery) { diff --git a/com.unity.netcode.gameobjects/Tests/Runtime/com.unity.netcode.runtimetests.asmdef b/com.unity.netcode.gameobjects/Tests/Runtime/com.unity.netcode.runtimetests.asmdef index 72d85ca4c5..ce8ab1c7eb 100644 --- a/com.unity.netcode.gameobjects/Tests/Runtime/com.unity.netcode.runtimetests.asmdef +++ b/com.unity.netcode.gameobjects/Tests/Runtime/com.unity.netcode.runtimetests.asmdef @@ -48,11 +48,6 @@ "name": "com.unity.modules.physics", "expression": "", "define": "COM_UNITY_MODULES_PHYSICS" - }, - { - "name": "com.unity.transport", - "expression": "2.0.0-exp", - "define": "UTP_TRANSPORT_2_0_ABOVE" } ], "noEngineReferences": false diff --git a/testproject/Assets/Tests/Runtime/NetworkSceneManager/NetworkSceneManagerFixValidationTests.cs b/testproject/Assets/Tests/Runtime/NetworkSceneManager/NetworkSceneManagerFixValidationTests.cs deleted file mode 100644 index e6c5f550bb..0000000000 --- a/testproject/Assets/Tests/Runtime/NetworkSceneManager/NetworkSceneManagerFixValidationTests.cs +++ /dev/null @@ -1,325 +0,0 @@ -// TODO: Rewrite test to use the tools package. Debug simulator not available in UTP 2.X. -#if !UTP_TRANSPORT_2_0_ABOVE -using System.Collections; -using System.Collections.Generic; -using NUnit.Framework; -using Unity.Netcode; -using Unity.Netcode.TestHelpers.Runtime; -using Unity.Netcode.Transports.UTP; -using UnityEngine; -using UnityEngine.SceneManagement; -using UnityEngine.TestTools; -using Object = UnityEngine.Object; - -namespace TestProject.RuntimeTests -{ - /// - /// Use this test group for validating NetworkSceneManager fixes. - /// - public class NetworkSceneManagerFixValidationTests : NetcodeIntegrationTest - { - - private const string k_SceneToLoad = "UnitTestBaseScene"; - private const string k_AdditiveScene1 = "InSceneNetworkObject"; - private const string k_AdditiveScene2 = "AdditiveSceneMultiInstance"; - - protected override int NumberOfClients => 2; - - private bool m_CanStart; - private bool m_NoLatency; - - private Scene m_OriginalActiveScene; - - protected override IEnumerator OnSetup() - { - m_OriginalActiveScene = SceneManager.GetActiveScene(); - return base.OnSetup(); - } - - protected override bool CanStartServerAndClients() - { - return m_CanStart; - } - - /// - /// This validation test verifies that the NetworkSceneManager will not crash if - /// the SpawnManager.SpawnedObjectsList contains destroyed and invalid NetworkObjects. - /// - [Test] - public void DDOLPopulateWithNullNetworkObjectsValidation([Values] bool useHost) - { - var gameObject = new GameObject(); - var networkObject = gameObject.AddComponent(); - NetcodeIntegrationTestHelpers.MakeNetworkObjectTestPrefab(networkObject); - - m_ServerNetworkManager.NetworkConfig.Prefabs.Add(new NetworkPrefab() { Prefab = gameObject }); - - foreach (var clientNetworkManager in m_ClientNetworkManagers) - { - clientNetworkManager.NetworkConfig.Prefabs.Add(new NetworkPrefab() { Prefab = gameObject }); - } - - // Start the host and clients - if (!NetcodeIntegrationTestHelpers.Start(useHost, m_ServerNetworkManager, new NetworkManager[] { })) - { - Debug.LogError("Failed to start instances"); - Assert.Fail("Failed to start instances"); - } - - // Spawn some NetworkObjects - var spawnedNetworkObjects = new List(); - for (int i = 0; i < 10; i++) - { - var instance = Object.Instantiate(gameObject); - var instanceNetworkObject = instance.GetComponent(); - instanceNetworkObject.NetworkManagerOwner = m_ServerNetworkManager; - instanceNetworkObject.Spawn(); - spawnedNetworkObjects.Add(instance); - } - - // Add a bogus entry to the SpawnManager - m_ServerNetworkManager.SpawnManager.SpawnedObjectsList.Add(null); - - // Verify moving all NetworkObjects into the DDOL when some might be invalid will not crash - m_ServerNetworkManager.SceneManager.MoveObjectsToDontDestroyOnLoad(); - - // Verify moving all NetworkObjects from DDOL back into the active scene will not crash even if some are invalid - m_ServerNetworkManager.SceneManager.MoveObjectsFromDontDestroyOnLoadToScene(SceneManager.GetActiveScene()); - - // Now remove the invalid object - m_ServerNetworkManager.SpawnManager.SpawnedObjectsList.Remove(null); - - // As long as there are no exceptions this test passes - } - - protected override void OnServerAndClientsCreated() - { - if (m_NoLatency) - { - return; - } - - // Apply a 500ms latency on packets (primarily for ClientDisconnectsDuringSeneLoadingValidation) - var serverTransport = m_ServerNetworkManager.GetComponent(); - serverTransport.SetDebugSimulatorParameters(500, 0, 0); - - foreach (var clientNetworkManager in m_ClientNetworkManagers) - { - var clientTransport = m_ServerNetworkManager.GetComponent(); - clientTransport.SetDebugSimulatorParameters(500, 0, 0); - } - } - - protected override IEnumerator OnServerAndClientsConnected() - { - m_ServerNetworkManager.SceneManager.OnLoadEventCompleted += SceneManager_OnLoadEventCompleted; - return base.OnServerAndClientsConnected(); - } - - private void SceneManager_OnLoadEventCompleted(string sceneName, LoadSceneMode loadSceneMode, List clientsCompleted, List clientsTimedOut) - { - if (sceneName == k_SceneToLoad) - { - m_ServerNetworkManager.SceneManager.OnLoadEventCompleted -= SceneManager_OnLoadEventCompleted; - m_SceneLoadEventCompleted = true; - - // Verify that the disconnected client is in the clients that timed out list - Assert.IsTrue(clientsTimedOut.Contains(m_FirstClientId), $"Client-id({m_FirstClientId}) was not found in the clients that timed out list that has a count of ({clientsTimedOut.Count}) entries!"); - } - } - - private bool m_SceneLoadEventCompleted; - private bool m_ClientDisconnectedOnLoad; - private ulong m_FirstClientId; - - [UnityTest] - public IEnumerator ClientDisconnectsDuringSeneLoadingValidation() - { - m_CanStart = true; - yield return StartServerAndClients(); - - // Do some preparation for the client we will be disconnecting. - m_FirstClientId = m_ClientNetworkManagers[0].LocalClientId; - if (m_ClientNetworkManagers[0].SceneManager.VerifySceneBeforeLoading != null) - { - m_OriginalVerifyScene = m_ClientNetworkManagers[0].SceneManager.VerifySceneBeforeLoading; - } - m_ClientNetworkManagers[0].SceneManager.VerifySceneBeforeLoading = VerifySceneBeforeLoading; - - // We use this to verify that the loading scene event doesn't take NetworkConfig.LoadSceneTimeOut to complete - var timeEventStarted = Time.realtimeSinceStartup; - var disconnectedClientName = m_ClientNetworkManagers[0].name; - - // Start to load the scene - m_ServerNetworkManager.SceneManager.LoadScene(k_SceneToLoad, LoadSceneMode.Additive); - yield return WaitForConditionOrTimeOut(() => m_SceneLoadEventCompleted); - AssertOnTimeout("Timed out waiting for the load scene event to be completed!"); - - // Verify the client disconnected when it was just about to start the load event - Assert.True(m_ClientDisconnectedOnLoad, $"{disconnectedClientName} did not disconnect!"); - - // Verify it didn't take as long as the NetworkConfig.LoadSceneTimeOut period to complete the event - var timeToComplete = Time.realtimeSinceStartup - timeEventStarted; - Assert.True(timeToComplete < m_ServerNetworkManager.NetworkConfig.LoadSceneTimeOut, "Server scene loading event timed out!"); - - // Verification that the disconnected client was in the timeout list is done in SceneManager_OnLoadEventCompleted - } - - private NetworkSceneManager.VerifySceneBeforeLoadingDelegateHandler m_OriginalVerifyScene; - - /// - /// The client that disconnects during the scene event will have this override that will: - /// - Set m_ClientDisconnectedOnLoad - /// - Stop/Disconnect the client - /// - Return false (i.e. don't load this scene) as we are simulating the client disconnected - /// right as the scene event started - /// - private bool VerifySceneBeforeLoading(int sceneIndex, string sceneName, LoadSceneMode loadSceneMode) - { - if (sceneName == k_SceneToLoad) - { - m_ClientDisconnectedOnLoad = true; - NetcodeIntegrationTestHelpers.StopOneClient(m_ClientNetworkManagers[0]); - IntegrationTestSceneHandler.NetworkManagers.Remove(m_ClientNetworkManagers[0]); - return false; - } - if (m_OriginalVerifyScene != null) - { - return m_OriginalVerifyScene.Invoke(sceneIndex, sceneName, loadSceneMode); - } - return true; - } - - - private Scene m_FirstScene; - private Scene m_SecondScene; - private Scene m_ThirdScene; - - private bool m_SceneUnloadedEventCompleted; - - - [UnityTest] - public IEnumerator InitialActiveSceneUnload() - { - SceneManager.sceneLoaded += SceneManager_sceneLoaded; - SceneManager.LoadScene(k_SceneToLoad, LoadSceneMode.Additive); - - yield return WaitForConditionOrTimeOut(FirstSceneIsLoaded); - AssertOnTimeout($"Failed to load scene {k_SceneToLoad}!"); - - // Now set the "first scene" as the active scene prior to starting the server and clients - SceneManager.SetActiveScene(m_FirstScene); - m_NoLatency = true; - m_CanStart = true; - - yield return StartServerAndClients(); - - var serverSceneManager = m_ServerNetworkManager.SceneManager; - serverSceneManager.OnSceneEvent += ServerSceneManager_OnSceneEvent; - m_SceneLoadEventCompleted = false; - serverSceneManager.LoadScene(k_AdditiveScene1, LoadSceneMode.Additive); - - yield return WaitForConditionOrTimeOut(SecondSceneIsLoaded); - AssertOnTimeout($"[Load Event] Failure in loading scene {k_AdditiveScene1} (locally or on client side)!"); - - // Since we have to keep the test running scene active, we mimic the "auto assignment" of - // the active scene prior to unloading the first scene in order to validate this test scenario. - SceneManager.SetActiveScene(m_SecondScene); - - yield return s_DefaultWaitForTick; - - // Now unload the "first" scene which, if this was the only scene loaded prior to loading the second scene, - // would automatically make the second scene the currently active scene - m_SceneUnloadedEventCompleted = false; - serverSceneManager.UnloadScene(m_FirstScene); - yield return WaitForConditionOrTimeOut(SceneUnloadEventCompleted); - AssertOnTimeout($"[Unload Event] Failure in unloading scene {m_FirstScene} (locally or on client side)!"); - - // Now load the third scene, and if no time out occurs then we have validated this test! - m_SceneLoadEventCompleted = false; - serverSceneManager.LoadScene(k_AdditiveScene2, LoadSceneMode.Additive); - yield return WaitForConditionOrTimeOut(ThirdSceneIsLoaded); - AssertOnTimeout($"[Load Event] Failure in loading scene {k_AdditiveScene2} (locally or on client side)!"); - serverSceneManager.OnSceneEvent -= ServerSceneManager_OnSceneEvent; - } - - private void ServerSceneManager_OnSceneEvent(SceneEvent sceneEvent) - { - if (sceneEvent.ClientId != m_ServerNetworkManager.LocalClientId) - { - return; - } - - if (sceneEvent.SceneEventType == SceneEventType.LoadComplete) - { - if (sceneEvent.Scene.name == k_AdditiveScene1) - { - m_SecondScene = sceneEvent.Scene; - } - else if (sceneEvent.Scene.name == k_AdditiveScene2) - { - m_ThirdScene = sceneEvent.Scene; - } - } - - if (sceneEvent.SceneEventType == SceneEventType.LoadEventCompleted) - { - if (sceneEvent.SceneName == k_AdditiveScene1 || sceneEvent.SceneName == k_AdditiveScene2) - { - m_SceneLoadEventCompleted = true; - } - } - - if (sceneEvent.SceneEventType == SceneEventType.UnloadEventCompleted) - { - if (sceneEvent.SceneName == k_SceneToLoad || sceneEvent.SceneName == k_AdditiveScene1 || sceneEvent.SceneName == k_AdditiveScene2) - { - m_SceneUnloadedEventCompleted = true; - } - } - } - - private bool SceneUnloadEventCompleted() - { - return m_SceneUnloadedEventCompleted; - } - - private bool FirstSceneIsLoaded() - { - return m_FirstScene.IsValid() && m_FirstScene.isLoaded; - } - - private bool SecondSceneIsLoaded() - { - return m_SecondScene.IsValid() && m_SecondScene.isLoaded && m_SceneLoadEventCompleted; - } - - private bool ThirdSceneIsLoaded() - { - return m_ThirdScene.IsValid() && m_ThirdScene.isLoaded && m_SceneLoadEventCompleted; - } - - private void SceneManager_sceneLoaded(Scene scene, LoadSceneMode mode) - { - if (scene.name == k_SceneToLoad && mode == LoadSceneMode.Additive) - { - m_FirstScene = scene; - SceneManager.sceneLoaded -= SceneManager_sceneLoaded; - } - } - - protected override IEnumerator OnTearDown() - { - m_CanStart = false; - m_NoLatency = false; - - if (m_OriginalActiveScene != SceneManager.GetActiveScene()) - { - SceneManager.SetActiveScene(m_OriginalActiveScene); - } - - return base.OnTearDown(); - } - } -} -#endif diff --git a/testproject/Assets/Tests/Runtime/NetworkSceneManager/NetworkSceneManagerFixValidationTests.cs.meta b/testproject/Assets/Tests/Runtime/NetworkSceneManager/NetworkSceneManagerFixValidationTests.cs.meta deleted file mode 100644 index 9e35df982a..0000000000 --- a/testproject/Assets/Tests/Runtime/NetworkSceneManager/NetworkSceneManagerFixValidationTests.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 501dfd0e05e51184e8938bba980d3f88 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/testproject/Assets/Tests/Runtime/testproject.runtimetests.asmdef b/testproject/Assets/Tests/Runtime/testproject.runtimetests.asmdef index 80fb79d2d3..17af49a925 100644 --- a/testproject/Assets/Tests/Runtime/testproject.runtimetests.asmdef +++ b/testproject/Assets/Tests/Runtime/testproject.runtimetests.asmdef @@ -37,11 +37,6 @@ "name": "com.unity.addressables", "expression": "", "define": "TESTPROJECT_USE_ADDRESSABLES" - }, - { - "name": "com.unity.transport", - "expression": "2.0.0-exp", - "define": "UTP_TRANSPORT_2_0_ABOVE" } ], "noEngineReferences": false