ServerCube.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Serialization;
  5. using Random = UnityEngine.Random;
  6. namespace Mirror.Examples.LagCompensationDemo
  7. {
  8. public class ServerCube : MonoBehaviour
  9. {
  10. [Header("Components")]
  11. public ClientCube client;
  12. [FormerlySerializedAs("collider")]
  13. public BoxCollider col;
  14. [Header("Movement")]
  15. public float distance = 10;
  16. public float speed = 3;
  17. Vector3 start;
  18. [Header("Snapshot Interpolation")]
  19. [Tooltip("Send N snapshots per second. Multiples of frame rate make sense.")]
  20. public int sendRate = 30; // in Hz. easier to work with as int for EMA. easier to display '30' than '0.333333333'
  21. public float sendInterval => 1f / sendRate;
  22. float lastSendTime;
  23. [Header("Lag Compensation")]
  24. public LagCompensationSettings lagCompensationSettings = new LagCompensationSettings();
  25. double lastCaptureTime;
  26. // lag compensation history of <timestamp, capture>
  27. Queue<KeyValuePair<double, Capture2D>> history = new Queue<KeyValuePair<double, Capture2D>>();
  28. public Color historyColor = Color.white;
  29. // store latest lag compensation result to show a visual indicator
  30. [Header("Debug")]
  31. public double resultDuration = 0.5;
  32. double resultTime;
  33. Capture2D resultBefore;
  34. Capture2D resultAfter;
  35. Capture2D resultInterpolated;
  36. [Header("Latency Simulation")]
  37. [Tooltip("Latency in seconds")]
  38. public float latency = 0.05f; // 50 ms
  39. [Tooltip("Latency jitter, randomly added to latency.")]
  40. [Range(0, 1)] public float jitter = 0.05f;
  41. [Tooltip("Packet loss in %")]
  42. [Range(0, 1)] public float loss = 0.1f;
  43. [Tooltip("Scramble % of unreliable messages, just like over the real network. Mirror unreliable is unordered.")]
  44. [Range(0, 1)] public float scramble = 0.1f;
  45. // random
  46. // UnityEngine.Random.value is [0, 1] with both upper and lower bounds inclusive
  47. // but we need the upper bound to be exclusive, so using System.Random instead.
  48. // => NextDouble() is NEVER < 0 so loss=0 never drops!
  49. // => NextDouble() is ALWAYS < 1 so loss=1 always drops!
  50. System.Random random = new System.Random();
  51. // hold on to snapshots for a little while before delivering
  52. // <deliveryTime, snapshot>
  53. List<(double, Snapshot3D)> queue = new List<(double, Snapshot3D)>();
  54. // latency simulation:
  55. // always a fixed value + some jitter.
  56. float SimulateLatency() => latency + Random.value * jitter;
  57. // this is the average without randomness. for lag compensation math.
  58. // in a real game, use rtt instead.
  59. float AverageLatency() => latency + 0.5f * jitter;
  60. void Start()
  61. {
  62. start = transform.position;
  63. }
  64. void Update()
  65. {
  66. // move on XY plane
  67. float x = Mathf.PingPong(Time.time * speed, distance);
  68. transform.position = new Vector3(start.x + x, start.y, start.z);
  69. // broadcast snapshots every interval
  70. if (Time.time >= lastSendTime + sendInterval)
  71. {
  72. Send(transform.position);
  73. lastSendTime = Time.time;
  74. }
  75. Flush();
  76. // capture lag compensation snapshots every interval.
  77. // NetworkTime.localTime because Unity 2019 doesn't have 'double' time yet.
  78. if (NetworkTime.localTime >= lastCaptureTime + lagCompensationSettings.captureInterval)
  79. {
  80. lastCaptureTime = NetworkTime.localTime;
  81. Capture();
  82. }
  83. }
  84. void Send(Vector3 position)
  85. {
  86. // create snapshot
  87. // Unity 2019 doesn't have Time.timeAsDouble yet
  88. Snapshot3D snap = new Snapshot3D(NetworkTime.localTime, 0, position);
  89. // simulate packet loss
  90. bool drop = random.NextDouble() < loss;
  91. if (!drop)
  92. {
  93. // simulate scramble (Random.Next is < max, so +1)
  94. bool doScramble = random.NextDouble() < scramble;
  95. int last = queue.Count;
  96. int index = doScramble ? random.Next(0, last + 1) : last;
  97. // simulate latency
  98. float simulatedLatency = SimulateLatency();
  99. // Unity 2019 doesn't have Time.timeAsDouble yet
  100. double deliveryTime = NetworkTime.localTime + simulatedLatency;
  101. queue.Insert(index, (deliveryTime, snap));
  102. }
  103. }
  104. void Flush()
  105. {
  106. // flush ready snapshots to client
  107. for (int i = 0; i < queue.Count; ++i)
  108. {
  109. (double deliveryTime, Snapshot3D snap) = queue[i];
  110. // Unity 2019 doesn't have Time.timeAsDouble yet
  111. if (NetworkTime.localTime >= deliveryTime)
  112. {
  113. client.OnMessage(snap);
  114. queue.RemoveAt(i);
  115. --i;
  116. }
  117. }
  118. }
  119. void Capture()
  120. {
  121. // capture current state
  122. Capture2D capture = new Capture2D(NetworkTime.localTime, transform.position, col.size);
  123. // insert into history
  124. LagCompensation.Insert(history, lagCompensationSettings.historyLimit, NetworkTime.localTime, capture);
  125. }
  126. // client says: "I was clicked here, at this time."
  127. // server needs to rollback to validate.
  128. // timestamp is the client's snapshot interpolated timeline!
  129. public bool CmdClicked(Vector2 position)
  130. {
  131. // never trust the client: estimate client time instead.
  132. // https://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking
  133. // the estimation is very good. the error is as low as ~6ms for the demo.
  134. double rtt = AverageLatency() * 2; // the function needs rtt, which is latency * 2
  135. double estimatedTime = LagCompensation.EstimateTime(NetworkTime.localTime, rtt, client.bufferTime);
  136. // compare estimated time with actual client time for debugging
  137. double error = Math.Abs(estimatedTime - client.localTimeline);
  138. Debug.Log($"CmdClicked: serverTime={NetworkTime.localTime:F3} clientTime={client.localTimeline:F3} estimatedTime={estimatedTime:F3} estimationError={error:F3} position={position}");
  139. // sample the history to get the nearest snapshots around 'timestamp'
  140. if (LagCompensation.Sample(history, estimatedTime, lagCompensationSettings.captureInterval, out resultBefore, out resultAfter, out double t))
  141. {
  142. // interpolate to get a decent estimation at exactly 'timestamp'
  143. resultInterpolated = Capture2D.Interpolate(resultBefore, resultAfter, t);
  144. resultTime = NetworkTime.localTime;
  145. // check if there really was a cube at that time and position
  146. Bounds bounds = new Bounds(resultInterpolated.position, resultInterpolated.size);
  147. if (bounds.Contains(position))
  148. {
  149. return true;
  150. }
  151. else Debug.Log($"CmdClicked: interpolated={resultInterpolated} doesn't contain {position}");
  152. }
  153. else Debug.Log($"CmdClicked: history doesn't contain {estimatedTime:F3}");
  154. return false;
  155. }
  156. void OnDrawGizmos()
  157. {
  158. // should we apply special colors to an active result?
  159. bool showResult = NetworkTime.localTime <= resultTime + resultDuration;
  160. // draw interpoalted result first.
  161. // history meshcubes should write over it for better visibility.
  162. if (showResult)
  163. {
  164. Gizmos.color = Color.black;
  165. Gizmos.DrawCube(resultInterpolated.position, resultInterpolated.size);
  166. }
  167. // draw history
  168. Gizmos.color = historyColor;
  169. LagCompensation.DrawGizmos(history);
  170. // draw result samples after. useful to see the selection process.
  171. if (showResult)
  172. {
  173. Gizmos.color = Color.cyan;
  174. Gizmos.DrawWireCube(resultBefore.position, resultBefore.size);
  175. Gizmos.DrawWireCube(resultAfter.position, resultAfter.size);
  176. }
  177. }
  178. }
  179. }