1
0

TestPair.Timing.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #nullable enable
  2. namespace Content.IntegrationTests.Pair;
  3. // This partial class contains methods for running the server/client pairs for some number of ticks
  4. public sealed partial class TestPair
  5. {
  6. /// <summary>
  7. /// Runs the server-client pair in sync
  8. /// </summary>
  9. /// <param name="ticks">How many ticks to run them for</param>
  10. public async Task RunTicksSync(int ticks)
  11. {
  12. for (var i = 0; i < ticks; i++)
  13. {
  14. await Server.WaitRunTicks(1);
  15. await Client.WaitRunTicks(1);
  16. }
  17. }
  18. /// <summary>
  19. /// Convert a time interval to some number of ticks.
  20. /// </summary>
  21. public int SecondsToTicks(float seconds)
  22. {
  23. return (int) Math.Ceiling(seconds / Server.Timing.TickPeriod.TotalSeconds);
  24. }
  25. /// <summary>
  26. /// Run the server & client in sync for some amount of time
  27. /// </summary>
  28. public async Task RunSeconds(float seconds)
  29. {
  30. await RunTicksSync(SecondsToTicks(seconds));
  31. }
  32. /// <summary>
  33. /// Runs the server-client pair in sync, but also ensures they are both idle each tick.
  34. /// </summary>
  35. /// <param name="runTicks">How many ticks to run</param>
  36. public async Task ReallyBeIdle(int runTicks = 25)
  37. {
  38. for (var i = 0; i < runTicks; i++)
  39. {
  40. await Client.WaitRunTicks(1);
  41. await Server.WaitRunTicks(1);
  42. for (var idleCycles = 0; idleCycles < 4; idleCycles++)
  43. {
  44. await Client.WaitIdleAsync();
  45. await Server.WaitIdleAsync();
  46. }
  47. }
  48. }
  49. /// <summary>
  50. /// Run the server/clients until the ticks are synchronized.
  51. /// By default the client will be one tick ahead of the server.
  52. /// </summary>
  53. public async Task SyncTicks(int targetDelta = 1)
  54. {
  55. var sTick = (int)Server.Timing.CurTick.Value;
  56. var cTick = (int)Client.Timing.CurTick.Value;
  57. var delta = cTick - sTick;
  58. if (delta == targetDelta)
  59. return;
  60. if (delta > targetDelta)
  61. await Server.WaitRunTicks(delta - targetDelta);
  62. else
  63. await Client.WaitRunTicks(targetDelta - delta);
  64. sTick = (int)Server.Timing.CurTick.Value;
  65. cTick = (int)Client.Timing.CurTick.Value;
  66. delta = cTick - sTick;
  67. Assert.That(delta, Is.EqualTo(targetDelta));
  68. }
  69. }