LocalPredictionPlayerInputTests.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <CommonBenchmarkSetup.h>
  9. #include <CommonHierarchySetup.h>
  10. #include <MockInterfaces.h>
  11. #include <AzCore/UnitTest/TestTypes.h>
  12. #include <AzCore/UnitTest/UnitTest.h>
  13. #include <AzCore/Name/NameDictionary.h>
  14. #include <AzCore/Name/Name.h>
  15. #include <AzCore/RTTI/BehaviorContext.h>
  16. #include <AzCore/Time/ITime.h>
  17. #include <AzFramework/Components/TransformComponent.h>
  18. #include <AzFramework/Spawnable/SpawnableSystemComponent.h>
  19. #include <AzNetworking/UdpTransport/UdpPacketHeader.h>
  20. #include <AzNetworking/Framework/NetworkingSystemComponent.h>
  21. #include <AzTest/AzTest.h>
  22. #include <MultiplayerSystemComponent.h>
  23. #include <IMultiplayerConnectionMock.h>
  24. #include <IMultiplayerSpawnerMock.h>
  25. #include <ConnectionData/ServerToClientConnectionData.h>
  26. #include <ReplicationWindows/ServerToClientReplicationWindow.h>
  27. #include <Multiplayer/Components/LocalPredictionPlayerInputComponent.h>
  28. #include <Multiplayer/Components/NetBindComponent.h>
  29. #include <Multiplayer/MultiplayerConstants.h>
  30. #include <Multiplayer/Session/SessionConfig.h>
  31. #include <Tests/TestMultiplayerComponent.h>
  32. namespace Multiplayer
  33. {
  34. class LocalPredictionPlayerInputTests : public LeakDetectionFixture
  35. {
  36. public:
  37. void SetUp() override
  38. {
  39. AZ::NameDictionary::Create();
  40. m_ComponentApplicationRequests = AZStd::make_unique<BenchmarkComponentApplicationRequests>();
  41. AZ::Interface<AZ::ComponentApplicationRequests>::Register(m_ComponentApplicationRequests.get());
  42. m_console.reset(aznew AZ::Console());
  43. AZ::Interface<AZ::IConsole>::Register(m_console.get());
  44. m_console->LinkDeferredFunctors(AZ::ConsoleFunctorBase::GetDeferredHead());
  45. m_timeSystem.reset();
  46. m_timeSystem = AZStd::make_unique<::testing::NiceMock<AZ::MockTimeSystem>>();
  47. // For convenience, reroute these methods to all return m_mockElapsedTime so that our tests can
  48. // precisely control the passing of time.
  49. ON_CALL(*m_timeSystem, GetElapsedTimeUs())
  50. .WillByDefault([this]() { return AZ::TimeMsToUs(m_mockElapsedTime); });
  51. ON_CALL(*m_timeSystem, GetRealElapsedTimeUs())
  52. .WillByDefault([this]() { return AZ::TimeMsToUs(m_mockElapsedTime); });
  53. ON_CALL(*m_timeSystem, GetElapsedTimeMs())
  54. .WillByDefault([this]() { return m_mockElapsedTime; });
  55. ON_CALL(*m_timeSystem, GetRealElapsedTimeMs())
  56. .WillByDefault([this]() { return m_mockElapsedTime; });
  57. // register components involved in testing
  58. m_serializeContext = AZStd::make_unique<AZ::SerializeContext>();
  59. m_behaviorContext = AZStd::make_unique<AZ::BehaviorContext>();
  60. m_transformDescriptor.reset(AzFramework::TransformComponent::CreateDescriptor());
  61. m_transformDescriptor->Reflect(m_serializeContext.get());
  62. m_netBindDescriptor.reset(NetBindComponent::CreateDescriptor());
  63. m_netBindDescriptor->Reflect(m_serializeContext.get());
  64. m_netTransformDescriptor.reset(NetworkTransformComponent::CreateDescriptor());
  65. m_netTransformDescriptor->Reflect(m_serializeContext.get());
  66. m_localPredictionDescriptor.reset(LocalPredictionPlayerInputComponent::CreateDescriptor());
  67. m_localPredictionDescriptor->Reflect(m_serializeContext.get());
  68. m_testMultiplayerComponentDescriptor.reset(MultiplayerTest::TestMultiplayerComponent::CreateDescriptor());
  69. m_testMultiplayerComponentDescriptor->Reflect(m_serializeContext.get());
  70. m_testInputDriverComponentDescriptor.reset(MultiplayerTest::TestInputDriverComponent::CreateDescriptor());
  71. m_testInputDriverComponentDescriptor->Reflect(m_serializeContext.get());
  72. m_netComponent = new AzNetworking::NetworkingSystemComponent();
  73. m_mpComponent = new Multiplayer::MultiplayerSystemComponent();
  74. m_mpComponent->Reflect(m_serializeContext.get());
  75. m_mpComponent->Reflect(m_behaviorContext.get());
  76. m_mpComponent->Activate();
  77. m_eventScheduler = new AZ::EventSchedulerSystemComponent();
  78. m_eventScheduler->Reflect(m_serializeContext.get());
  79. m_eventScheduler->Activate();
  80. m_playerEntity = AZStd::make_unique<AZ::Entity>(AZ::EntityId(1), "Test");
  81. m_playerNetworkEntityTracker = AZStd::make_unique<NetworkEntityTracker>();
  82. m_playerEntity->CreateComponent<AzFramework::TransformComponent>();
  83. m_playerEntity->CreateComponent<NetworkTransformComponent>();
  84. m_playerEntity->CreateComponent<MultiplayerTest::TestMultiplayerComponent>();
  85. m_playerEntity->CreateComponent<MultiplayerTest::TestInputDriverComponent>();
  86. m_localPredictionComponent = m_playerEntity->CreateComponent<LocalPredictionPlayerInputComponent>();
  87. }
  88. void ActivatePlayerEntity(NetEntityRole role)
  89. {
  90. const auto playerNetBindComponent = m_playerEntity->CreateComponent<NetBindComponent>();
  91. playerNetBindComponent->PreInit(
  92. m_playerEntity.get(), PrefabEntityId{ AZ::Name("test"), 1 }, NetEntityId{ 1 }, role);
  93. m_playerNetworkEntityTracker->RegisterNetBindComponent(m_playerEntity.get(), playerNetBindComponent);
  94. m_playerEntity->Init();
  95. m_playerEntity->Activate();
  96. }
  97. void TearDown() override
  98. {
  99. m_playerEntity->Deactivate();
  100. m_playerNetworkEntityTracker.reset();
  101. m_mpComponent->Deactivate();
  102. m_eventScheduler->Deactivate();
  103. m_localPredictionComponent = nullptr;
  104. m_playerEntity.reset();
  105. delete m_mpComponent;
  106. delete m_netComponent;
  107. delete m_eventScheduler;
  108. AZ::Interface<AZ::IConsole>::Unregister(m_console.get());
  109. m_console.reset();
  110. m_timeSystem.reset();
  111. AZ::Interface<AZ::ComponentApplicationRequests>::Unregister(m_ComponentApplicationRequests.get());
  112. m_ComponentApplicationRequests.reset();
  113. AZ::NameDictionary::Destroy();
  114. m_testInputDriverComponentDescriptor.reset();
  115. m_testMultiplayerComponentDescriptor.reset();
  116. m_localPredictionDescriptor.reset();
  117. m_transformDescriptor.reset();
  118. m_netTransformDescriptor.reset();
  119. m_netBindDescriptor.reset();
  120. m_serializeContext.reset();
  121. m_behaviorContext.reset();
  122. }
  123. AZStd::unique_ptr<AZ::SerializeContext> m_serializeContext;
  124. AZStd::unique_ptr<AZ::BehaviorContext> m_behaviorContext;
  125. AZStd::unique_ptr<AZ::ComponentDescriptor> m_transformDescriptor;
  126. AZStd::unique_ptr<AZ::ComponentDescriptor> m_netBindDescriptor;
  127. AZStd::unique_ptr<AZ::ComponentDescriptor> m_netTransformDescriptor;
  128. AZStd::unique_ptr<AZ::ComponentDescriptor> m_localPredictionDescriptor;
  129. AZStd::unique_ptr<AZ::ComponentDescriptor> m_testMultiplayerComponentDescriptor;
  130. AZStd::unique_ptr<AZ::ComponentDescriptor> m_testInputDriverComponentDescriptor;
  131. AZStd::unique_ptr<AZ::IConsole> m_console;
  132. AZStd::unique_ptr<::testing::NiceMock<AZ::MockTimeSystem>> m_timeSystem;
  133. AZ::TimeMs m_mockElapsedTime = AZ::TimeMs(0);
  134. AzNetworking::NetworkingSystemComponent* m_netComponent = nullptr;
  135. Multiplayer::MultiplayerSystemComponent* m_mpComponent = nullptr;
  136. AZ::EventSchedulerSystemComponent* m_eventScheduler = nullptr;
  137. Multiplayer::LocalPredictionPlayerInputComponent* m_localPredictionComponent = nullptr;
  138. AZStd::unique_ptr<BenchmarkComponentApplicationRequests> m_ComponentApplicationRequests;
  139. AZStd::unique_ptr<AZ::Entity> m_playerEntity;
  140. AZStd::unique_ptr<NetworkEntityTracker> m_playerNetworkEntityTracker;
  141. IMultiplayerSpawnerMock m_mpSpawnerMock;
  142. };
  143. TEST_F(LocalPredictionPlayerInputTests, TestChildController)
  144. {
  145. ActivatePlayerEntity(NetEntityRole::Autonomous);
  146. m_mpComponent->InitializeMultiplayer(MultiplayerAgentType::DedicatedServer);
  147. EXPECT_EQ(m_mpComponent->GetAgentType(), MultiplayerAgentType::DedicatedServer);
  148. MultiplayerController* parentController = m_localPredictionComponent->GetController();
  149. LocalPredictionPlayerInputComponentController* controllerPtr =
  150. dynamic_cast<LocalPredictionPlayerInputComponentController*>(parentController);
  151. LocalPredictionPlayerInputComponentController childCotroller(*controllerPtr);
  152. }
  153. TEST_F(LocalPredictionPlayerInputTests, TestUpdateAutonomous)
  154. {
  155. ActivatePlayerEntity(NetEntityRole::Autonomous);
  156. m_mpComponent->InitializeMultiplayer(MultiplayerAgentType::DedicatedServer);
  157. EXPECT_EQ(m_mpComponent->GetAgentType(), MultiplayerAgentType::DedicatedServer);
  158. LocalPredictionPlayerInputComponentController* controller =
  159. dynamic_cast<LocalPredictionPlayerInputComponentController*>(m_localPredictionComponent->GetController());
  160. controller->ForceEnableAutonomousUpdate();
  161. m_mockElapsedTime = AZ::TimeMs(1000);
  162. m_eventScheduler->OnTick(1000, AZ::ScriptTimePoint());
  163. controller->ForceDisableAutonomousUpdate();
  164. }
  165. TEST_F(LocalPredictionPlayerInputTests, TestHandleSendClientInput)
  166. {
  167. ActivatePlayerEntity(NetEntityRole::Autonomous);
  168. m_mpComponent->InitializeMultiplayer(MultiplayerAgentType::DedicatedServer);
  169. EXPECT_EQ(m_mpComponent->GetAgentType(), MultiplayerAgentType::DedicatedServer);
  170. ::testing::NiceMock<IMultiplayerConnectionMock> connection(
  171. ConnectionId{ 1 }, IpAddress("127.0.0.1", DefaultServerPort, ProtocolType::Udp), ConnectionRole::Connector);
  172. ServerToClientConnectionData connectionUserData(&connection, *m_mpComponent);
  173. connection.SetUserData(&connectionUserData);
  174. Multiplayer::NetworkInputArray netInputArray;
  175. netInputArray[0].SetHostBlendFactor(0.8f);
  176. netInputArray[0].SetHostTimeMs(AZ::TimeMs(1));
  177. netInputArray[0].SetHostFrameId(HostFrameId(1));
  178. AZ::HashValue32 dummyHash = AZ::HashValue32(0);
  179. LocalPredictionPlayerInputComponentController* controller =
  180. dynamic_cast<LocalPredictionPlayerInputComponentController*>(m_localPredictionComponent->GetController());
  181. controller->HandleSendClientInput(nullptr, netInputArray, dummyHash);
  182. controller->HandleSendClientInput(&connection, netInputArray, dummyHash);
  183. netInputArray[0].SetClientInputId(ClientInputId(1));
  184. // Force update to increment client input ID
  185. m_mockElapsedTime = AZ::TimeMs(1000);
  186. controller->HandleSendClientInput(&connection, netInputArray, dummyHash);
  187. // Force update to update banked time
  188. m_mockElapsedTime = AZ::TimeMs(1010);
  189. m_eventScheduler->OnTick(1000, AZ::ScriptTimePoint());
  190. EXPECT_EQ(controller->GetInputFrameId(netInputArray[0]), netInputArray[0].GetHostFrameId());
  191. }
  192. TEST_F(LocalPredictionPlayerInputTests, TestHandleSendClientInputCorrection)
  193. {
  194. ActivatePlayerEntity(NetEntityRole::Autonomous);
  195. m_mpComponent->InitializeMultiplayer(MultiplayerAgentType::DedicatedServer);
  196. EXPECT_EQ(m_mpComponent->GetAgentType(), MultiplayerAgentType::DedicatedServer);
  197. AzNetworking::PacketEncodingBuffer buffer;
  198. LocalPredictionPlayerInputComponentController* controller =
  199. dynamic_cast<LocalPredictionPlayerInputComponentController*>(m_localPredictionComponent->GetController());
  200. // Sending an input correction with a host frame id that hasn't been generated yet client-side should produce an error.
  201. AZ_TEST_START_TRACE_SUPPRESSION;
  202. controller->HandleSendClientInputCorrection(nullptr, HostFrameId(1), ClientInputId(1), buffer);
  203. AZ_TEST_STOP_TRACE_SUPPRESSION(1);
  204. ::testing::NiceMock<IMultiplayerConnectionMock> connection(
  205. ConnectionId{ 1 }, IpAddress("127.0.0.1", DefaultServerPort, ProtocolType::Udp), ConnectionRole::Connector);
  206. ServerToClientConnectionData connectionUserData(&connection, *m_mpComponent);
  207. connection.SetUserData(&connectionUserData);
  208. // Force update to increment client input id
  209. controller->ForceEnableAutonomousUpdate();
  210. m_mockElapsedTime = AZ::TimeMs(1000);
  211. m_eventScheduler->OnTick(100, AZ::ScriptTimePoint());
  212. // Input corrections with a host frame id <= current host frame id should both be processed and generate no errors.
  213. controller->HandleSendClientInputCorrection(&connection, HostFrameId(1), ClientInputId(0), buffer);
  214. controller->HandleSendClientInputCorrection(&connection, HostFrameId(1), ClientInputId(1), buffer);
  215. }
  216. TEST_F(LocalPredictionPlayerInputTests, TestHandleSendMigrateClientInput)
  217. {
  218. ActivatePlayerEntity(NetEntityRole::Autonomous);
  219. m_mpComponent->InitializeMultiplayer(MultiplayerAgentType::DedicatedServer);
  220. EXPECT_EQ(m_mpComponent->GetAgentType(), MultiplayerAgentType::DedicatedServer);
  221. ::testing::NiceMock<IMultiplayerConnectionMock> connection(
  222. ConnectionId{ 1 }, IpAddress("127.0.0.1", DefaultServerPort, ProtocolType::Udp), ConnectionRole::Connector);
  223. ServerToClientConnectionData connectionUserData(&connection, *m_mpComponent);
  224. connection.SetUserData(&connectionUserData);
  225. Multiplayer::NetworkInputArray netInputArray;
  226. netInputArray[0].SetHostBlendFactor(0.8f);
  227. netInputArray[0].SetHostTimeMs(AZ::TimeMs(1));
  228. netInputArray[0].SetHostFrameId(HostFrameId(1));
  229. Multiplayer::NetworkInputMigrationVector netMigrationVector;
  230. netMigrationVector.PushBack(netInputArray[0]);
  231. LocalPredictionPlayerInputComponentController* controller =
  232. dynamic_cast<LocalPredictionPlayerInputComponentController*>(m_localPredictionComponent->GetController());
  233. controller->OnDeactivate(EntityIsMigrating::False);
  234. controller->OnActivate(EntityIsMigrating::True);
  235. controller->HandleSendMigrateClientInput(&connection, netMigrationVector);
  236. controller->HandleSendMigrateClientInput(&connection, netMigrationVector);
  237. controller->OnDeactivate(EntityIsMigrating::False);
  238. controller->OnActivate(EntityIsMigrating::True);
  239. controller->HandleSendMigrateClientInput(nullptr, netMigrationVector);
  240. }
  241. TEST_F(LocalPredictionPlayerInputTests, TestHandleSendClientInputWithIdWraparound)
  242. {
  243. // The ClientInputId is defined as uint16_t, so the values in it can wrap around in <20 minutes at 60 fps.
  244. // There was a bug with HandleSendClientInput where it would stop processing inputs correctly once the ClientInputId
  245. // reached the max uint16_t value and wrapped around to 0. This unit test verifies that there are no regressions
  246. // and the processing happens correctly during the wraparound.
  247. //
  248. // This also verifies a secondary regression in which ProcessInput would get called multiple times on the very
  249. // first input handled if the latest ClientInputId received was anything other than 0, even if the other entries
  250. // in the array were all identical. The correct behavior is that it should only process multiple entries if there
  251. // are actually multiple different entries in the array.
  252. // For this test, set the player as authority-only, so that UpdateAutonomous never gets called.
  253. // Otherwise, we'll get ProcessInput callbacks both from the "client" and the "server", which will make the test logic
  254. // more confusing and harder to validate.
  255. ActivatePlayerEntity(NetEntityRole::Authority);
  256. m_mpComponent->InitializeMultiplayer(MultiplayerAgentType::DedicatedServer);
  257. EXPECT_EQ(m_mpComponent->GetAgentType(), MultiplayerAgentType::DedicatedServer);
  258. ::testing::NiceMock<IMultiplayerConnectionMock> connection(
  259. ConnectionId{ 1 }, IpAddress("127.0.0.1", DefaultServerPort, ProtocolType::Udp), ConnectionRole::Connector);
  260. ServerToClientConnectionData connectionUserData(&connection, *m_mpComponent);
  261. connection.SetUserData(&connectionUserData);
  262. // Initialize the starting time to an arbitrary value
  263. m_mockElapsedTime = AZ::TimeMs(1000);
  264. // Verify that we don't get any calls to CreateInput, since we're running as authority-only.
  265. auto createInputCallback = [](
  266. [[maybe_unused]] NetEntityId netEntityId,
  267. [[maybe_unused]] Multiplayer::NetworkInput& input,
  268. [[maybe_unused]] float deltaTime)
  269. {
  270. AZ_Assert(false, "CreateInput should not be called when the player entity is set to authority-only.");
  271. };
  272. // On each call to ProcessInput, verify that the ClientInputId and HostFrameId is the same one we're trying to process.
  273. // Also, track the total number of times called to avoid a "false positive" of appearing successful if it never gets called
  274. // or if it gets called multiple times in the same frame unexpectedly.
  275. size_t numProcessedInputs = 0;
  276. ClientInputId expectedInputId;
  277. HostFrameId hostFrameId = HostFrameId(0);
  278. auto processInputCallback =
  279. [&expectedInputId, &hostFrameId, &numProcessedInputs](
  280. [[maybe_unused]] NetEntityId netEntityId,
  281. Multiplayer::NetworkInput& input,
  282. [[maybe_unused]] float deltaTime)
  283. {
  284. EXPECT_EQ(static_cast<uint32_t>(input.GetHostFrameId()), static_cast<uint32_t>(hostFrameId));
  285. EXPECT_EQ(static_cast<uint32_t>(input.GetClientInputId()), static_cast<uint32_t>(expectedInputId));
  286. numProcessedInputs++;
  287. };
  288. // Set the callbacks for creating and processing input so that we can validate that input processing behaves correctly when
  289. // the client Ids wrap around.
  290. m_playerEntity->FindComponent<MultiplayerTest::TestMultiplayerComponent>()->m_createInputCallback = createInputCallback;
  291. m_playerEntity->FindComponent<MultiplayerTest::TestMultiplayerComponent>()->m_processInputCallback = processInputCallback;
  292. LocalPredictionPlayerInputComponentController* controller =
  293. dynamic_cast<LocalPredictionPlayerInputComponentController*>(m_localPredictionComponent->GetController());
  294. // Since we're not doing anything with the inputs, the hash value won't be used for anything.
  295. constexpr AZ::HashValue32 dummyHash = AZ::HashValue32(0);
  296. // Pick starting and ending ClientInputId values to process that will wrap around through 0.
  297. constexpr ClientInputId StartingLargeInputId =
  298. ClientInputId{ AZStd::numeric_limits<AZStd::underlying_type<ClientInputId>::type>::max() - 10 };
  299. constexpr ClientInputId EndingWraparoundInputId = ClientInputId{ 10 };
  300. Multiplayer::NetworkInputArray netInputArray;
  301. // Initialize all the history in netInputArray to the same entry so that all entries are valid and match expectations
  302. // on the first call to HandleSendClientInput. (It always assumes that *all* entries in the array are valid)
  303. for (uint32_t index = 0; index < Multiplayer::NetworkInputArray::MaxElements; index++)
  304. {
  305. netInputArray[index].SetClientInputId(StartingLargeInputId);
  306. netInputArray[index].SetHostFrameId(hostFrameId);
  307. netInputArray[index].SetHostBlendFactor(0.8f);
  308. netInputArray[index].SetHostTimeMs(AZ::TimeMs(1));
  309. }
  310. // Loop through each client id and handle our mocked inputs.
  311. for (expectedInputId = StartingLargeInputId; expectedInputId != EndingWraparoundInputId; expectedInputId++, hostFrameId++)
  312. {
  313. // On each iteration, bump our inputs back one in the array to preserve an accurate history of entries.
  314. for (uint32_t index = 1; index < Multiplayer::NetworkInputArray::MaxElements; index++)
  315. {
  316. netInputArray[index] = netInputArray[index - 1];
  317. }
  318. // Set the latest entry to the current client input ID and host frame ID.
  319. netInputArray[0].SetClientInputId(expectedInputId);
  320. netInputArray[0].SetHostFrameId(hostFrameId);
  321. // Handle the mocked input. This should call ProcessInput to process only the latest entry in the array,
  322. // which inside the callback above will verify that we've been given the current expectedInputId to process.
  323. controller->HandleSendClientInput(&connection, netInputArray, dummyHash);
  324. m_mockElapsedTime += AZ::TimeMs(10);
  325. // Force UpdateBankedTime to get called. Without this, the client inputs would eventually stop processing because
  326. // the banked time will get too large and the test will fail.
  327. m_eventScheduler->OnTick(1000, AZ::ScriptTimePoint());
  328. m_mockElapsedTime += AZ::TimeMs(10);
  329. }
  330. // Verify that ProcessInput actually got called the correct number of times.
  331. constexpr size_t TotalExpectedProcessedInputs = static_cast<size_t>(EndingWraparoundInputId - StartingLargeInputId);
  332. EXPECT_EQ(numProcessedInputs, TotalExpectedProcessedInputs);
  333. }
  334. TEST_F(LocalPredictionPlayerInputTests, TestHandleSendClientInputCorrectionWithIdWraparound)
  335. {
  336. // The ClientInputId is defined as uint16_t, so the values in it can wrap around in <20 minutes at 60 fps.
  337. // There was a bug with HandleSendClientInputCorrection where it would only process input corrections if the
  338. // id was strictly <= the current id. This means that input corrections that wrapped around (ex: a correction of 65530
  339. // when we're currently on 10) would never process.
  340. // This unit test verifies that there are no regressions and the correction processing happens correctly during the wraparound.
  341. ActivatePlayerEntity(NetEntityRole::Autonomous);
  342. m_mpComponent->InitializeMultiplayer(MultiplayerAgentType::DedicatedServer);
  343. EXPECT_EQ(m_mpComponent->GetAgentType(), MultiplayerAgentType::DedicatedServer);
  344. LocalPredictionPlayerInputComponentController* controller =
  345. dynamic_cast<LocalPredictionPlayerInputComponentController*>(m_localPredictionComponent->GetController());
  346. // Force update to increment client input id
  347. controller->ForceEnableAutonomousUpdate();
  348. // Create a mock connection.
  349. ::testing::NiceMock<IMultiplayerConnectionMock> connection(
  350. ConnectionId{ 1 }, IpAddress("127.0.0.1", DefaultServerPort, ProtocolType::Udp), ConnectionRole::Connector);
  351. ServerToClientConnectionData connectionUserData(&connection, *m_mpComponent);
  352. connection.SetUserData(&connectionUserData);
  353. // Track the number of inputs that we create so that we can verify that we've created our desired starting condition
  354. // for the test, where we've got an input history that spans the wraparound.
  355. uint64_t numCreatedInputs = 0;
  356. auto createInputCallback = [&numCreatedInputs](
  357. [[maybe_unused]] NetEntityId netEntityId,
  358. [[maybe_unused]] Multiplayer::NetworkInput& input,
  359. [[maybe_unused]] float deltaTime)
  360. {
  361. numCreatedInputs++;
  362. };
  363. m_playerEntity->FindComponent<MultiplayerTest::TestMultiplayerComponent>()->m_createInputCallback = createInputCallback;
  364. // We want to generate (65535 + 10) inputs, so that we have a wrapped-around input history with both large and small ids in it.
  365. // If we set the elapsed time to (65535 + 10) * (cl_inputRateMs), we should get our desired number of inputs created.
  366. // Set the cl_InputRateMs to an arbitrary but nice round number for testing.
  367. constexpr int ArbitraryInputRateMs = 10;
  368. AZ::Interface<AZ::IConsole>::Get()->PerformCommand("cl_InputRateMs", { AZStd::string::format("%d", ArbitraryInputRateMs) });
  369. // Turn off desync debugging and delta serialization so that generating (65535 + 10) inputs doesn't take obnoxiously long.
  370. AZ::Interface<AZ::IConsole>::Get()->PerformCommand("cl_EnableDesyncDebugging", {"false"});
  371. AZ::Interface<AZ::IConsole>::Get()->PerformCommand("net_useInputDeltaSerialization", { "false" });
  372. constexpr uint64_t desiredInputCount = AZStd::numeric_limits<AZStd::underlying_type<ClientInputId>::type>::max() + 10;
  373. m_mockElapsedTime += AZ::TimeMs(desiredInputCount * ArbitraryInputRateMs);
  374. m_eventScheduler->OnTick(100, AZ::ScriptTimePoint());
  375. EXPECT_EQ(numCreatedInputs, desiredInputCount);
  376. // We'll request a correction from a little before the wraparound, so that HandleSendClientInputCorrection will replay through
  377. // the wraparound to the last input we created above.
  378. constexpr ClientInputId LargeCorrectionInputId =
  379. ClientInputId{ AZStd::numeric_limits<AZStd::underlying_type<ClientInputId>::type>::max() - 10 };
  380. uint64_t numInputCorrectionsProcessed = 0;
  381. // The first processed input id is one past the the correction
  382. ClientInputId expectedCorrectionId = LargeCorrectionInputId + ClientInputId(1);
  383. auto processInputCallback = [&numInputCorrectionsProcessed, &expectedCorrectionId](
  384. [[maybe_unused]] NetEntityId netEntityId,
  385. Multiplayer::NetworkInput& input,
  386. [[maybe_unused]] float deltaTime)
  387. {
  388. EXPECT_EQ(static_cast<uint32_t>(input.GetClientInputId()), static_cast<uint32_t>(expectedCorrectionId));
  389. numInputCorrectionsProcessed++;
  390. expectedCorrectionId++;
  391. };
  392. m_playerEntity->FindComponent<MultiplayerTest::TestMultiplayerComponent>()->m_processInputCallback = processInputCallback;
  393. AzNetworking::PacketEncodingBuffer buffer;
  394. controller->HandleSendClientInputCorrection(&connection, HostFrameId(0), ClientInputId(LargeCorrectionInputId), buffer);
  395. // The total number of corrections processed should be the number of inputs generated *past* the id we sent in the correction for
  396. EXPECT_EQ(numInputCorrectionsProcessed, desiredInputCount - static_cast<uint64_t>(LargeCorrectionInputId));
  397. }
  398. } // namespace Multiplayer