diff --git a/CHANGELOG.md b/CHANGELOG.md index 5909e66..f21849e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,10 +6,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com). -## [2.0.0-pre.1] - 2024-06-17 +## [2.0.0-pre.2] - 2024-06-17 ### Added +- Added `AnticipatedNetworkVariable`, which adds support for client anticipation of `NetworkVariable` values, allowing for more responsive gameplay. (#2957) +- Added `AnticipatedNetworkTransform`, which adds support for client anticipation of NetworkTransforms. (#2957) +- Added `NetworkVariableBase.ExceedsDirtinessThreshold` to allow network variables to throttle updates by only sending updates when the difference between the current and previous values exceeds a threshold. (This is exposed in `NetworkVariable` with the callback `NetworkVariable.CheckExceedsDirtinessThreshold`). (#2957) +- Added `NetworkVariableUpdateTraits`, which add additional throttling support: `MinSecondsBetweenUpdates` will prevent the `NetworkVariable` from sending updates more often than the specified time period (even if it exceeds the dirtiness threshold), while `MaxSecondsBetweenUpdates` will force a dirty `NetworkVariable` to send an update after the specified time period even if it has not yet exceeded the dirtiness threshold. (#2957) +- Added virtual method `NetworkVariableBase.OnInitialize` which can be used by `NetworkVariable` subclasses to add initialization code. (#2957) +- Added `NetworkTime.TickWithPartial`, which represents the current tick as a double that includes the fractional/partial tick value. (#2957) +- Added `NetworkTickSystem.AnticipationTick`, which can be helpful with implementation of client anticipation. This value represents the tick the current local client was at at the beginning of the most recent network round trip, which enables it to correlate server update ticks with the client tick that may have triggered them. (#2957) - Added event `NetworkManager.OnSessionOwnerPromoted` that is invoked when a new session owner promotion occurs. (#2948) - Added `NetworkRigidBodyBase.GetLinearVelocity` and `NetworkRigidBodyBase.SetLinearVelocity` convenience/helper methods. (#2948) - Added `NetworkRigidBodyBase.GetAngularVelocity` and `NetworkRigidBodyBase.SetAngularVelocity` convenience/helper methods. (#2948) @@ -22,6 +29,8 @@ Additional documentation and release notes are available at [Multiplayer Documen ### Changed +- Changed `NetworkAnimator` no longer requires the `Animator` component to exist on the same `GameObject`. (#2957) +- Changed `NetworkObjectReference` and `NetworkBehaviourReference` to allow null references when constructing and serializing. (#2957) - Changed the client's owned objects is now returned (`NetworkClient` and `NetworkSpawnManager`) as an array as opposed to a list for performance purposes. (#2948) - Changed `NetworkTransfrom.TryCommitTransformToServer` to be internal as it will be removed by the final 2.0.0 release. (#2948) - Changed `NetworkTransformEditor.OnEnable` to a virtual method to be able to customize a `NetworkTransform` derived class by creating a derived editor control from `NetworkTransformEditor`. (#2948) diff --git a/Editor/CodeGen/NetworkBehaviourILPP.cs b/Editor/CodeGen/NetworkBehaviourILPP.cs index fb583e2..e67ee0e 100644 --- a/Editor/CodeGen/NetworkBehaviourILPP.cs +++ b/Editor/CodeGen/NetworkBehaviourILPP.cs @@ -409,6 +409,7 @@ private void CreateNetworkVariableTypeInitializers(AssemblyDefinition assembly, } else { + m_Diagnostics.AddError($"{type}: Managed type in NetworkVariable must implement IEquatable<{type}>"); equalityMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef); } diff --git a/Editor/NetworkTransformEditor.cs b/Editor/NetworkTransformEditor.cs index 0dbab88..4affff1 100644 --- a/Editor/NetworkTransformEditor.cs +++ b/Editor/NetworkTransformEditor.cs @@ -66,6 +66,7 @@ public virtual void OnEnable() /// public override void OnInspectorGUI() { + var networkTransform = target as NetworkTransform; EditorGUILayout.LabelField("Axis to Synchronize", EditorStyles.boldLabel); { GUILayout.BeginHorizontal(); @@ -144,7 +145,10 @@ public override void OnInspectorGUI() EditorGUILayout.Space(); EditorGUILayout.LabelField("Configurations", EditorStyles.boldLabel); EditorGUILayout.PropertyField(m_InLocalSpaceProperty); - EditorGUILayout.PropertyField(m_InterpolateProperty); + if (!networkTransform.HideInterpolateValue) + { + EditorGUILayout.PropertyField(m_InterpolateProperty); + } EditorGUILayout.PropertyField(m_SlerpPosition); EditorGUILayout.PropertyField(m_UseQuaternionSynchronization); if (m_UseQuaternionSynchronization.boolValue) diff --git a/Runtime/Components/AnticipatedNetworkTransform.cs b/Runtime/Components/AnticipatedNetworkTransform.cs new file mode 100644 index 0000000..e8ae589 --- /dev/null +++ b/Runtime/Components/AnticipatedNetworkTransform.cs @@ -0,0 +1,497 @@ +using Unity.Mathematics; +using UnityEngine; + +namespace Unity.Netcode.Components +{ + +#pragma warning disable IDE0001 + /// + /// A subclass of that supports basic client anticipation - the client + /// can set a value on the belief that the server will update it to reflect the same value in a future update + /// (i.e., as the result of an RPC call). This value can then be adjusted as new updates from the server come in, + /// in three basic modes: + /// + /// + /// + /// Snap: In this mode (with set to + /// and no callback), + /// the moment a more up-to-date value is received from the authority, it will simply replace the anticipated value, + /// resulting in a "snap" to the new value if it is different from the anticipated value. + /// + /// Smooth: In this mode (with set to + /// and an callback that calls + /// from the anticipated value to the authority value with an appropriate + /// -style smooth function), when a more up-to-date value is received from the authority, + /// it will interpolate over time from an incorrect anticipated value to the correct authoritative value. + /// + /// Constant Reanticipation: In this mode (with set to + /// and an that calculates a + /// new anticipated value based on the current authoritative value), when a more up-to-date value is received from + /// the authority, user code calculates a new anticipated value, possibly calling to interpolate + /// between the previous anticipation and the new anticipation. This is useful for values that change frequently and + /// need to constantly be re-evaluated, as opposed to values that change only in response to user action and simply + /// need a one-time anticipation when the user performs that action. + /// + /// + /// + /// Note that these three modes may be combined. For example, if an callback + /// does not call either or one of the Anticipate methods, the result will be a snap to the + /// authoritative value, enabling for a callback that may conditionally call when the + /// difference between the anticipated and authoritative values is within some threshold, but fall back to + /// snap behavior if the difference is too large. + /// +#pragma warning restore IDE0001 + [DisallowMultipleComponent] + [AddComponentMenu("Netcode/Anticipated Network Transform")] + public class AnticipatedNetworkTransform : NetworkTransform + { + +#if UNITY_EDITOR + internal override bool HideInterpolateValue => true; +#endif + + public struct TransformState + { + public Vector3 Position; + public Quaternion Rotation; + public Vector3 Scale; + } + + private TransformState m_AuthoritativeTransform = new TransformState(); + private TransformState m_AnticipatedTransform = new TransformState(); + private TransformState m_PreviousAnticipatedTransform = new TransformState(); + private ulong m_LastAnticipaionCounter; + private ulong m_LastAuthorityUpdateCounter; + + private TransformState m_SmoothFrom; + private TransformState m_SmoothTo; + private float m_SmoothDuration; + private float m_CurrentSmoothTime; + + private bool m_OutstandingAuthorityChange = false; + +#if UNITY_EDITOR + private void Reset() + { + // Anticipation + smoothing is a form of interpolation, and adding NetworkTransform's buffered interpolation + // makes the anticipation get weird, so we default it to false. + Interpolate = false; + } +#endif + +#pragma warning disable IDE0001 + /// + /// Defines what the behavior should be if we receive a value from the server with an earlier associated + /// time value than the anticipation time value. + ///

+ /// If this is , the stale data will be ignored and the authoritative + /// value will not replace the anticipated value until the anticipation time is reached. + /// and will also not be invoked for this stale data. + ///

+ /// If this is , the stale data will replace the anticipated data and + /// and will be invoked. + /// In this case, the authoritativeTime value passed to will be lower than + /// the anticipationTime value, and that callback can be used to calculate a new anticipated value. + ///
+#pragma warning restore IDE0001 + public StaleDataHandling StaleDataHandling = StaleDataHandling.Reanticipate; + + /// + /// Contains the current state of this transform on the server side. + /// Note that, on the server side, this gets updated at the end of the frame, and will not immediately reflect + /// changes to the transform. + /// + public TransformState AuthoritativeState => m_AuthoritativeTransform; + + /// + /// Contains the current anticipated state, which will match the values of this object's + /// actual . When a server + /// update arrives, this value will be overwritten by the new + /// server value (unless stale data handling is set to "Ignore" + /// and the update is determined to be stale). This value will + /// be duplicated in , which + /// will NOT be overwritten in server updates. + /// + public TransformState AnticipatedState => m_AnticipatedTransform; + + /// + /// Indicates whether this transform currently needs + /// reanticipation. If this is true, the anticipated value + /// has been overwritten by the authoritative value from the + /// server; the previous anticipated value is stored in + /// + public bool ShouldReanticipate + { + get; + private set; + } + + /// + /// Holds the most recent anticipated state, whatever was + /// most recently set using the Anticipate methods. Unlike + /// , this does not get overwritten + /// when a server update arrives. + /// + public TransformState PreviousAnticipatedState => m_PreviousAnticipatedTransform; + + /// + /// Anticipate that, at the end of one round trip to the server, this transform will be in the given + /// + /// + /// + public void AnticipateMove(Vector3 newPosition) + { + if (NetworkManager.ShutdownInProgress || !NetworkManager.IsListening) + { + return; + } + transform.position = newPosition; + m_AnticipatedTransform.Position = newPosition; + if (CanCommitToTransform) + { + m_AuthoritativeTransform.Position = newPosition; + } + + m_PreviousAnticipatedTransform = m_AnticipatedTransform; + + m_LastAnticipaionCounter = NetworkManager.AnticipationSystem.AnticipationCounter; + + m_SmoothDuration = 0; + m_CurrentSmoothTime = 0; + } + + /// + /// Anticipate that, at the end of one round trip to the server, this transform will have the given + /// + /// + /// + public void AnticipateRotate(Quaternion newRotation) + { + if (NetworkManager.ShutdownInProgress || !NetworkManager.IsListening) + { + return; + } + transform.rotation = newRotation; + m_AnticipatedTransform.Rotation = newRotation; + if (CanCommitToTransform) + { + m_AuthoritativeTransform.Rotation = newRotation; + } + + m_PreviousAnticipatedTransform = m_AnticipatedTransform; + + m_LastAnticipaionCounter = NetworkManager.AnticipationSystem.AnticipationCounter; + + m_SmoothDuration = 0; + m_CurrentSmoothTime = 0; + } + + /// + /// Anticipate that, at the end of one round trip to the server, this transform will have the given + /// + /// + /// + public void AnticipateScale(Vector3 newScale) + { + if (NetworkManager.ShutdownInProgress || !NetworkManager.IsListening) + { + return; + } + transform.localScale = newScale; + m_AnticipatedTransform.Scale = newScale; + if (CanCommitToTransform) + { + m_AuthoritativeTransform.Scale = newScale; + } + + m_PreviousAnticipatedTransform = m_AnticipatedTransform; + + m_LastAnticipaionCounter = NetworkManager.AnticipationSystem.AnticipationCounter; + + m_SmoothDuration = 0; + m_CurrentSmoothTime = 0; + } + + /// + /// Anticipate that, at the end of one round trip to the server, the transform will have the given + /// + /// + /// + public void AnticipateState(TransformState newState) + { + if (NetworkManager.ShutdownInProgress || !NetworkManager.IsListening) + { + return; + } + var transform_ = transform; + transform_.position = newState.Position; + transform_.rotation = newState.Rotation; + transform_.localScale = newState.Scale; + m_AnticipatedTransform = newState; + if (CanCommitToTransform) + { + m_AuthoritativeTransform = newState; + } + + m_PreviousAnticipatedTransform = m_AnticipatedTransform; + + m_SmoothDuration = 0; + m_CurrentSmoothTime = 0; + } + + public override void OnUpdate() + { + // If not spawned or this instance has authority, exit early + if (!IsSpawned) + { + return; + } + // Do not call the base class implementation... + // AnticipatedNetworkTransform applies its authoritative state immediately rather than waiting for update + // This is because AnticipatedNetworkTransforms may need to reference each other in reanticipating + // and we will want all reanticipation done before anything else wants to reference the transform in + // OnUpdate() + //base.Update(); + + if (m_CurrentSmoothTime < m_SmoothDuration) + { + m_CurrentSmoothTime += NetworkManager.RealTimeProvider.DeltaTime; + var transform_ = transform; + var pct = math.min(m_CurrentSmoothTime / m_SmoothDuration, 1f); + + m_AnticipatedTransform = new TransformState + { + Position = Vector3.Lerp(m_SmoothFrom.Position, m_SmoothTo.Position, pct), + Rotation = Quaternion.Slerp(m_SmoothFrom.Rotation, m_SmoothTo.Rotation, pct), + Scale = Vector3.Lerp(m_SmoothFrom.Scale, m_SmoothTo.Scale, pct) + }; + m_PreviousAnticipatedTransform = m_AnticipatedTransform; + if (!CanCommitToTransform) + { + transform_.position = m_AnticipatedTransform.Position; + transform_.localScale = m_AnticipatedTransform.Scale; + transform_.rotation = m_AnticipatedTransform.Rotation; + } + } + } + + internal class AnticipatedObject : IAnticipationEventReceiver, IAnticipatedObject + { + public AnticipatedNetworkTransform Transform; + + + public void SetupForRender() + { + if (Transform.CanCommitToTransform) + { + var transform_ = Transform.transform; + Transform.m_AuthoritativeTransform = new TransformState + { + Position = transform_.position, + Rotation = transform_.rotation, + Scale = transform_.localScale + }; + if (Transform.m_CurrentSmoothTime >= Transform.m_SmoothDuration) + { + // If we've had a call to Smooth() we'll continue interpolating. + // Otherwise we'll go ahead and make the visual and actual locations + // match. + Transform.m_AnticipatedTransform = Transform.m_AuthoritativeTransform; + } + + transform_.position = Transform.m_AnticipatedTransform.Position; + transform_.rotation = Transform.m_AnticipatedTransform.Rotation; + transform_.localScale = Transform.m_AnticipatedTransform.Scale; + } + } + + public void SetupForUpdate() + { + if (Transform.CanCommitToTransform) + { + var transform_ = Transform.transform; + transform_.position = Transform.m_AuthoritativeTransform.Position; + transform_.rotation = Transform.m_AuthoritativeTransform.Rotation; + transform_.localScale = Transform.m_AuthoritativeTransform.Scale; + } + } + + public void Update() + { + // No need to do this, it's handled by NetworkTransform.OnUpdate + } + + public void ResetAnticipation() + { + Transform.ShouldReanticipate = false; + } + + public NetworkObject OwnerObject => Transform.NetworkObject; + } + + private AnticipatedObject m_AnticipatedObject = null; + + private void ResetAnticipatedState() + { + var transform_ = transform; + m_AuthoritativeTransform = new TransformState + { + Position = transform_.position, + Rotation = transform_.rotation, + Scale = transform_.localScale + }; + m_AnticipatedTransform = m_AuthoritativeTransform; + m_PreviousAnticipatedTransform = m_AnticipatedTransform; + + m_SmoothDuration = 0; + m_CurrentSmoothTime = 0; + } + + protected override void OnSynchronize(ref BufferSerializer serializer) + { + base.OnSynchronize(ref serializer); + if (!CanCommitToTransform) + { + m_OutstandingAuthorityChange = true; + ApplyAuthoritativeState(); + ResetAnticipatedState(); + } + } + + public override void OnNetworkSpawn() + { + base.OnNetworkSpawn(); + m_OutstandingAuthorityChange = true; + ApplyAuthoritativeState(); + ResetAnticipatedState(); + + m_AnticipatedObject = new AnticipatedObject { Transform = this }; + NetworkManager.AnticipationSystem.RegisterForAnticipationEvents(m_AnticipatedObject); + NetworkManager.AnticipationSystem.AllAnticipatedObjects.Add(m_AnticipatedObject); + } + + public override void OnNetworkDespawn() + { + if (m_AnticipatedObject != null) + { + NetworkManager.AnticipationSystem.DeregisterForAnticipationEvents(m_AnticipatedObject); + NetworkManager.AnticipationSystem.AllAnticipatedObjects.Remove(m_AnticipatedObject); + NetworkManager.AnticipationSystem.ObjectsToReanticipate.Remove(m_AnticipatedObject); + m_AnticipatedObject = null; + } + ResetAnticipatedState(); + + base.OnNetworkDespawn(); + } + + public override void OnDestroy() + { + if (m_AnticipatedObject != null) + { + NetworkManager.AnticipationSystem.DeregisterForAnticipationEvents(m_AnticipatedObject); + NetworkManager.AnticipationSystem.AllAnticipatedObjects.Remove(m_AnticipatedObject); + NetworkManager.AnticipationSystem.ObjectsToReanticipate.Remove(m_AnticipatedObject); + m_AnticipatedObject = null; + } + + base.OnDestroy(); + } + + /// + /// Interpolate between the transform represented by to the transform represented by + /// over of real time. The duration uses + /// , so it is affected by . + /// + /// + /// + /// + public void Smooth(TransformState from, TransformState to, float durationSeconds) + { + var transform_ = transform; + if (durationSeconds <= 0) + { + m_AnticipatedTransform = to; + m_PreviousAnticipatedTransform = m_AnticipatedTransform; + transform_.position = to.Position; + transform_.rotation = to.Rotation; + transform_.localScale = to.Scale; + m_SmoothDuration = 0; + m_CurrentSmoothTime = 0; + return; + } + m_AnticipatedTransform = from; + m_PreviousAnticipatedTransform = m_AnticipatedTransform; + + if (!CanCommitToTransform) + { + transform_.position = from.Position; + transform_.rotation = from.Rotation; + transform_.localScale = from.Scale; + } + + m_SmoothFrom = from; + m_SmoothTo = to; + m_SmoothDuration = durationSeconds; + m_CurrentSmoothTime = 0; + } + + protected override void OnBeforeUpdateTransformState() + { + // this is called when new data comes from the server + m_LastAuthorityUpdateCounter = NetworkManager.AnticipationSystem.LastAnticipationAck; + m_OutstandingAuthorityChange = true; + } + + protected override void OnNetworkTransformStateUpdated(ref NetworkTransformState oldState, ref NetworkTransformState newState) + { + base.OnNetworkTransformStateUpdated(ref oldState, ref newState); + ApplyAuthoritativeState(); + } + + protected override void OnTransformUpdated() + { + if (CanCommitToTransform || m_AnticipatedObject == null) + { + return; + } + // this is called pretty much every frame and will change the transform + // If we've overridden the transform with an anticipated state, we need to be able to change it back + // to the anticipated state (while updating the authority state accordingly) or else + // mark this transform for reanticipation + var transform_ = transform; + + var previousAnticipatedTransform = m_AnticipatedTransform; + + // Update authority state to catch any possible interpolation data + m_AuthoritativeTransform.Position = transform_.position; + m_AuthoritativeTransform.Rotation = transform_.rotation; + m_AuthoritativeTransform.Scale = transform_.localScale; + + if (!m_OutstandingAuthorityChange) + { + // Keep the anticipated value unchanged, we have no updates from the server at all. + transform_.position = previousAnticipatedTransform.Position; + transform_.localScale = previousAnticipatedTransform.Scale; + transform_.rotation = previousAnticipatedTransform.Rotation; + return; + } + + if (StaleDataHandling == StaleDataHandling.Ignore && m_LastAnticipaionCounter > m_LastAuthorityUpdateCounter) + { + // Keep the anticipated value unchanged because it is more recent than the authoritative one. + transform_.position = previousAnticipatedTransform.Position; + transform_.localScale = previousAnticipatedTransform.Scale; + transform_.rotation = previousAnticipatedTransform.Rotation; + return; + } + + m_SmoothDuration = 0; + m_CurrentSmoothTime = 0; + m_OutstandingAuthorityChange = false; + m_AnticipatedTransform = m_AuthoritativeTransform; + + ShouldReanticipate = true; + NetworkManager.AnticipationSystem.ObjectsToReanticipate.Add(m_AnticipatedObject); + } + } +} diff --git a/Runtime/Components/AnticipatedNetworkTransform.cs.meta b/Runtime/Components/AnticipatedNetworkTransform.cs.meta new file mode 100644 index 0000000..bb48f93 --- /dev/null +++ b/Runtime/Components/AnticipatedNetworkTransform.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 5abfce83aadd948498d4990c645a017b \ No newline at end of file diff --git a/Runtime/Components/Messages.meta b/Runtime/Components/Messages.meta deleted file mode 100644 index fcf8b73..0000000 --- a/Runtime/Components/Messages.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: a9db1d18fa0117f4da5e8e65386b894a -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/Components/NetworkAnimator.cs b/Runtime/Components/NetworkAnimator.cs index 73555e2..a1e3ccd 100644 --- a/Runtime/Components/NetworkAnimator.cs +++ b/Runtime/Components/NetworkAnimator.cs @@ -186,7 +186,6 @@ internal NetworkAnimatorStateChangeHandler(NetworkAnimator networkAnimator) /// NetworkAnimator enables remote synchronization of state for on network objects. /// [AddComponentMenu("Netcode/Network Animator")] - [RequireComponent(typeof(Animator))] public class NetworkAnimator : NetworkBehaviour, ISerializationCallbackReceiver { [Serializable] diff --git a/Runtime/Components/NetworkTransform.cs b/Runtime/Components/NetworkTransform.cs index db3e9b8..7518ee2 100644 --- a/Runtime/Components/NetworkTransform.cs +++ b/Runtime/Components/NetworkTransform.cs @@ -17,6 +17,11 @@ namespace Unity.Netcode.Components [AddComponentMenu("Netcode/Network Transform")] public class NetworkTransform : NetworkBehaviour { + +#if UNITY_EDITOR + internal virtual bool HideInterpolateValue => false; +#endif + #region NETWORK TRANSFORM STATE /// /// Data structure used to synchronize the @@ -2184,10 +2189,15 @@ internal void UpdatePositionInterpolator(Vector3 position, double time, bool res internal bool LogMotion; + protected virtual void OnTransformUpdated() + { + + } + /// /// Applies the authoritative state to the transform /// - private void ApplyAuthoritativeState() + protected internal void ApplyAuthoritativeState() { #if COM_UNITY_MODULES_PHYSICS // TODO: Make this an authority flag @@ -2391,6 +2401,7 @@ private void ApplyAuthoritativeState() } transform.localScale = m_CurrentScale; } + OnTransformUpdated(); } /// @@ -2602,6 +2613,8 @@ private void ApplyTeleportingState(NetworkTransformState newState) { AddLogEntry(ref newState, NetworkObject.OwnerClientId); } + + OnTransformUpdated(); } /// @@ -2769,6 +2782,11 @@ protected virtual void OnNetworkTransformStateUpdated(ref NetworkTransformState } + protected virtual void OnBeforeUpdateTransformState() + { + + } + internal bool LogStateUpdate; /// /// Only non-authoritative instances should invoke this method @@ -2809,6 +2827,10 @@ private void OnNetworkStateChanged(NetworkTransformState oldState, NetworkTransf } Debug.Log(builder); } + + // Notification prior to applying a state update + OnBeforeUpdateTransformState(); + // Apply the new state ApplyUpdatedState(newState); diff --git a/Runtime/Core/NetworkBehaviour.cs b/Runtime/Core/NetworkBehaviour.cs index 5b53f1a..b093531 100644 --- a/Runtime/Core/NetworkBehaviour.cs +++ b/Runtime/Core/NetworkBehaviour.cs @@ -950,7 +950,16 @@ internal void PostNetworkVariableWrite(bool forced = false) // during OnNetworkSpawn has been sent and needs to be cleared for (int i = 0; i < NetworkVariableFields.Count; i++) { - NetworkVariableFields[i].ResetDirty(); + var networkVariable = NetworkVariableFields[i]; + if (networkVariable.IsDirty()) + { + if (networkVariable.CanSend()) + { + networkVariable.UpdateLastSentTime(); + networkVariable.ResetDirty(); + networkVariable.SetDirty(false); + } + } } } else @@ -958,7 +967,16 @@ internal void PostNetworkVariableWrite(bool forced = false) // mark any variables we wrote as no longer dirty for (int i = 0; i < NetworkVariableIndexesToReset.Count; i++) { - NetworkVariableFields[NetworkVariableIndexesToReset[i]].ResetDirty(); + var networkVariable = NetworkVariableFields[NetworkVariableIndexesToReset[i]]; + if (networkVariable.IsDirty()) + { + if (networkVariable.CanSend()) + { + networkVariable.UpdateLastSentTime(); + networkVariable.ResetDirty(); + networkVariable.SetDirty(false); + } + } } } @@ -1001,7 +1019,10 @@ internal void NetworkVariableUpdate(ulong targetClientId) networkVariable = NetworkVariableFields[k]; if (networkVariable.IsDirty() && networkVariable.CanClientRead(targetClientId)) { - shouldSend = true; + if (networkVariable.CanSend()) + { + shouldSend = true; + } break; } } @@ -1057,9 +1078,16 @@ private bool CouldHaveDirtyNetworkVariables() // TODO: There should be a better way by reading one dirty variable vs. 'n' for (int i = 0; i < NetworkVariableFields.Count; i++) { - if (NetworkVariableFields[i].IsDirty()) + var networkVariable = NetworkVariableFields[i]; + if (networkVariable.IsDirty()) { - return true; + if (networkVariable.CanSend()) + { + return true; + } + // If it's dirty but can't be sent yet, we have to keep monitoring it until one of the + // conditions blocking its send changes. + NetworkManager.BehaviourUpdater.AddForUpdate(NetworkObject); } } @@ -1268,6 +1296,11 @@ protected virtual void OnSynchronize(ref BufferSerializer serializer) wher } + public virtual void OnReanticipate(double lastRoundTripTime) + { + + } + /// /// The relative client identifier targeted for the serialization of this instance. /// diff --git a/Runtime/Core/NetworkBehaviourUpdater.cs b/Runtime/Core/NetworkBehaviourUpdater.cs index e190702..7bf2030 100644 --- a/Runtime/Core/NetworkBehaviourUpdater.cs +++ b/Runtime/Core/NetworkBehaviourUpdater.cs @@ -11,6 +11,7 @@ public class NetworkBehaviourUpdater private NetworkManager m_NetworkManager; private NetworkConnectionManager m_ConnectionManager; private HashSet m_DirtyNetworkObjects = new HashSet(); + private HashSet m_PendingDirtyNetworkObjects = new HashSet(); #if DEVELOPMENT_BUILD || UNITY_EDITOR private ProfilerMarker m_NetworkBehaviourUpdate = new ProfilerMarker($"{nameof(NetworkBehaviour)}.{nameof(NetworkBehaviourUpdate)}"); @@ -18,7 +19,7 @@ public class NetworkBehaviourUpdater internal void AddForUpdate(NetworkObject networkObject) { - m_DirtyNetworkObjects.Add(networkObject); + m_PendingDirtyNetworkObjects.Add(networkObject); } internal void NetworkBehaviourUpdate() @@ -28,6 +29,9 @@ internal void NetworkBehaviourUpdate() #endif try { + m_DirtyNetworkObjects.UnionWith(m_PendingDirtyNetworkObjects); + m_PendingDirtyNetworkObjects.Clear(); + // NetworkObject references can become null, when hidden or despawned. Once NUll, there is no point // trying to process them, even if they were previously marked as dirty. m_DirtyNetworkObjects.RemoveWhere((sobj) => sobj == null); diff --git a/Runtime/Core/NetworkManager.cs b/Runtime/Core/NetworkManager.cs index b956cfa..f7880d1 100644 --- a/Runtime/Core/NetworkManager.cs +++ b/Runtime/Core/NetworkManager.cs @@ -253,8 +253,10 @@ public void NetworkUpdate(NetworkUpdateStage updateStage) DeferredMessageManager.ProcessTriggers(IDeferredNetworkMessageManager.TriggerType.OnNextFrame, 0); + AnticipationSystem.SetupForUpdate(); MessageManager.ProcessIncomingMessageQueue(); MessageManager.CleanupDisconnectedClients(); + AnticipationSystem.ProcessReanticipation(); } break; #if COM_UNITY_MODULES_PHYSICS @@ -273,6 +275,7 @@ public void NetworkUpdate(NetworkUpdateStage updateStage) case NetworkUpdateStage.PreUpdate: { NetworkTimeSystem.UpdateTime(); + AnticipationSystem.Update(); } break; case NetworkUpdateStage.PreLateUpdate: @@ -287,6 +290,12 @@ public void NetworkUpdate(NetworkUpdateStage updateStage) } } break; + case NetworkUpdateStage.PostScriptLateUpdate: + { + AnticipationSystem.Sync(); + AnticipationSystem.SetupForRender(); + } + break; case NetworkUpdateStage.PostLateUpdate: { // Handle deferred despawning @@ -526,6 +535,25 @@ public event Action OnTransportFailure remove => ConnectionManager.OnTransportFailure -= value; } + public delegate void ReanticipateDelegate(double lastRoundTripTime); + + /// + /// This callback is called after all individual OnReanticipate calls on AnticipatedNetworkVariable + /// and AnticipatedNetworkTransform values have been invoked. The first parameter is a hash set of + /// all the variables that have been changed on this frame (you can detect a particular variable by + /// checking if the set contains it), while the second parameter is a set of all anticipated network + /// transforms that have been changed. Both are passed as their base class type. + /// + /// The third parameter is the local time corresponding to the current authoritative server state + /// (i.e., to determine the amount of time that needs to be re-simulated, you will use + /// NetworkManager.LocalTime.Time - authorityTime). + /// + public event ReanticipateDelegate OnReanticipate + { + add => AnticipationSystem.OnReanticipate += value; + remove => AnticipationSystem.OnReanticipate -= value; + } + /// /// The callback to invoke during connection approval. Allows client code to decide whether or not to allow incoming client connection /// @@ -770,6 +798,8 @@ public NetworkPrefabHandler PrefabHandler /// public NetworkTickSystem NetworkTickSystem { get; private set; } + internal AnticipationSystem AnticipationSystem { get; private set; } + /// /// Used for time mocking in tests /// @@ -1078,6 +1108,7 @@ internal void Initialize(bool server) this.RegisterNetworkUpdate(NetworkUpdateStage.FixedUpdate); #endif this.RegisterNetworkUpdate(NetworkUpdateStage.PreUpdate); + this.RegisterNetworkUpdate(NetworkUpdateStage.PostScriptLateUpdate); this.RegisterNetworkUpdate(NetworkUpdateStage.PreLateUpdate); this.RegisterNetworkUpdate(NetworkUpdateStage.PostLateUpdate); @@ -1117,6 +1148,7 @@ internal void Initialize(bool server) // The remaining systems can then be initialized NetworkTimeSystem = server ? NetworkTimeSystem.ServerTimeSystem() : new NetworkTimeSystem(1.0 / NetworkConfig.TickRate); NetworkTickSystem = NetworkTimeSystem.Initialize(this); + AnticipationSystem = new AnticipationSystem(this); // Create spawn manager instance SpawnManager = new NetworkSpawnManager(this); diff --git a/Runtime/Core/NetworkUpdateLoop.cs b/Runtime/Core/NetworkUpdateLoop.cs index cd47065..5f60e74 100644 --- a/Runtime/Core/NetworkUpdateLoop.cs +++ b/Runtime/Core/NetworkUpdateLoop.cs @@ -54,6 +54,12 @@ public enum NetworkUpdateStage : byte /// PreLateUpdate = 6, /// + /// Updated after Monobehaviour.LateUpdate, but BEFORE rendering + /// + // Yes, these numbers are out of order due to backward compatibility requirements. + // The enum values are listed in the order they will be called. + PostScriptLateUpdate = 8, + /// /// Updated after the Monobehaviour.LateUpdate for all components is invoked /// PostLateUpdate = 7 @@ -258,6 +264,18 @@ public static PlayerLoopSystem CreateLoopSystem() } } + internal struct NetworkPostScriptLateUpdate + { + public static PlayerLoopSystem CreateLoopSystem() + { + return new PlayerLoopSystem + { + type = typeof(NetworkPostScriptLateUpdate), + updateDelegate = () => RunNetworkUpdateStage(NetworkUpdateStage.PostScriptLateUpdate) + }; + } + } + internal struct NetworkPostLateUpdate { public static PlayerLoopSystem CreateLoopSystem() @@ -399,6 +417,7 @@ internal static void RegisterLoopSystems() else if (currentSystem.type == typeof(PreLateUpdate)) { TryAddLoopSystem(ref currentSystem, NetworkPreLateUpdate.CreateLoopSystem(), typeof(PreLateUpdate.ScriptRunBehaviourLateUpdate), LoopSystemPosition.Before); + TryAddLoopSystem(ref currentSystem, NetworkPostScriptLateUpdate.CreateLoopSystem(), typeof(PreLateUpdate.ScriptRunBehaviourLateUpdate), LoopSystemPosition.After); } else if (currentSystem.type == typeof(PostLateUpdate)) { @@ -440,6 +459,7 @@ internal static void UnregisterLoopSystems() else if (currentSystem.type == typeof(PreLateUpdate)) { TryRemoveLoopSystem(ref currentSystem, typeof(NetworkPreLateUpdate)); + TryRemoveLoopSystem(ref currentSystem, typeof(NetworkPostScriptLateUpdate)); } else if (currentSystem.type == typeof(PostLateUpdate)) { diff --git a/Runtime/Messaging/ILPPMessageProvider.cs b/Runtime/Messaging/ILPPMessageProvider.cs index e51009b..b7f90f6 100644 --- a/Runtime/Messaging/ILPPMessageProvider.cs +++ b/Runtime/Messaging/ILPPMessageProvider.cs @@ -47,6 +47,8 @@ internal enum NetworkMessageTypes : uint SessionOwner = 20, TimeSync = 21, Unnamed = 22, + AnticipationCounterSyncPingMessage = 23, + AnticipationCounterSyncPongMessage = 24, } @@ -103,7 +105,9 @@ internal enum NetworkMessageTypes : uint { typeof(ServerRpcMessage), NetworkMessageTypes.ServerRpc }, { typeof(TimeSyncMessage), NetworkMessageTypes.TimeSync }, { typeof(UnnamedMessage), NetworkMessageTypes.Unnamed }, - { typeof(SessionOwnerMessage), NetworkMessageTypes.SessionOwner } + { typeof(SessionOwnerMessage), NetworkMessageTypes.SessionOwner }, + { typeof(AnticipationCounterSyncPingMessage), NetworkMessageTypes.AnticipationCounterSyncPingMessage}, + { typeof(AnticipationCounterSyncPongMessage), NetworkMessageTypes.AnticipationCounterSyncPongMessage}, }; // Assure the type to lookup table count and NetworkMessageType enum count matches (i.e. to catch human error when adding new messages) diff --git a/Runtime/Messaging/Messages/AnticipationCounterSyncPingMessage.cs b/Runtime/Messaging/Messages/AnticipationCounterSyncPingMessage.cs new file mode 100644 index 0000000..b9cdfe7 --- /dev/null +++ b/Runtime/Messaging/Messages/AnticipationCounterSyncPingMessage.cs @@ -0,0 +1,70 @@ +namespace Unity.Netcode +{ + internal struct AnticipationCounterSyncPingMessage : INetworkMessage + { + public int Version => 0; + + public ulong Counter; + public double Time; + + public void Serialize(FastBufferWriter writer, int targetVersion) + { + BytePacker.WriteValuePacked(writer, Counter); + writer.WriteValueSafe(Time); + } + + public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) + { + var networkManager = (NetworkManager)context.SystemOwner; + if (!networkManager.IsServer) + { + return false; + } + ByteUnpacker.ReadValuePacked(reader, out Counter); + reader.ReadValueSafe(out Time); + return true; + } + + public void Handle(ref NetworkContext context) + { + var networkManager = (NetworkManager)context.SystemOwner; + if (networkManager.IsListening && !networkManager.ShutdownInProgress && networkManager.ConnectedClients.ContainsKey(context.SenderId)) + { + var message = new AnticipationCounterSyncPongMessage { Counter = Counter, Time = Time }; + networkManager.MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, context.SenderId); + } + } + } + internal struct AnticipationCounterSyncPongMessage : INetworkMessage + { + public int Version => 0; + + public ulong Counter; + public double Time; + + public void Serialize(FastBufferWriter writer, int targetVersion) + { + BytePacker.WriteValuePacked(writer, Counter); + writer.WriteValueSafe(Time); + } + + public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) + { + var networkManager = (NetworkManager)context.SystemOwner; + if (!networkManager.IsClient) + { + return false; + } + ByteUnpacker.ReadValuePacked(reader, out Counter); + reader.ReadValueSafe(out Time); + return true; + } + + public void Handle(ref NetworkContext context) + { + var networkManager = (NetworkManager)context.SystemOwner; + networkManager.AnticipationSystem.LastAnticipationAck = Counter; + networkManager.AnticipationSystem.LastAnticipationAckTime = Time; + } + } +} diff --git a/Runtime/Messaging/Messages/AnticipationCounterSyncPingMessage.cs.meta b/Runtime/Messaging/Messages/AnticipationCounterSyncPingMessage.cs.meta new file mode 100644 index 0000000..f4abc89 --- /dev/null +++ b/Runtime/Messaging/Messages/AnticipationCounterSyncPingMessage.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b7d5c92979ad7e646a078aaf058b53a9 \ No newline at end of file diff --git a/Runtime/Messaging/Messages/NetworkVariableDeltaMessage.cs b/Runtime/Messaging/Messages/NetworkVariableDeltaMessage.cs index 4ca9c64..de73302 100644 --- a/Runtime/Messaging/Messages/NetworkVariableDeltaMessage.cs +++ b/Runtime/Messaging/Messages/NetworkVariableDeltaMessage.cs @@ -69,7 +69,8 @@ public void Serialize(FastBufferWriter writer, int targetVersion) var networkVariable = NetworkBehaviour.NetworkVariableFields[i]; var shouldWrite = networkVariable.IsDirty() && networkVariable.CanClientRead(TargetClientId) && - (networkManager.IsServer || networkVariable.CanClientWrite(networkManager.LocalClientId)); + (networkManager.IsServer || networkVariable.CanClientWrite(networkManager.LocalClientId)) && + networkVariable.CanSend(); // Prevent the server from writing to the client that owns a given NetworkVariable // Allowing the write would send an old value to the client and cause jitter diff --git a/Runtime/NetworkVariable/AnticipatedNetworkVariable.cs b/Runtime/NetworkVariable/AnticipatedNetworkVariable.cs new file mode 100644 index 0000000..2a08293 --- /dev/null +++ b/Runtime/NetworkVariable/AnticipatedNetworkVariable.cs @@ -0,0 +1,392 @@ +using System; +using Unity.Mathematics; +using UnityEngine; + +namespace Unity.Netcode +{ + + public enum StaleDataHandling + { + Ignore, + Reanticipate + } + +#pragma warning disable IDE0001 + /// + /// A variable that can be synchronized over the network. + /// This version supports basic client anticipation - the client can set a value on the belief that the server + /// will update it to reflect the same value in a future update (i.e., as the result of an RPC call). + /// This value can then be adjusted as new updates from the server come in, in three basic modes: + /// + /// + /// + /// Snap: In this mode (with set to + /// and no callback), + /// the moment a more up-to-date value is received from the authority, it will simply replace the anticipated value, + /// resulting in a "snap" to the new value if it is different from the anticipated value. + /// + /// Smooth: In this mode (with set to + /// and an callback that calls + /// from the anticipated value to the authority value with an appropriate + /// -style smooth function), when a more up-to-date value is received from the authority, + /// it will interpolate over time from an incorrect anticipated value to the correct authoritative value. + /// + /// Constant Reanticipation: In this mode (with set to + /// and an that calculates a + /// new anticipated value based on the current authoritative value), when a more up-to-date value is received from + /// the authority, user code calculates a new anticipated value, possibly calling to interpolate + /// between the previous anticipation and the new anticipation. This is useful for values that change frequently and + /// need to constantly be re-evaluated, as opposed to values that change only in response to user action and simply + /// need a one-time anticipation when the user performs that action. + /// + /// + /// + /// Note that these three modes may be combined. For example, if an callback + /// does not call either or , the result will be a snap to the + /// authoritative value, enabling for a callback that may conditionally call when the + /// difference between the anticipated and authoritative values is within some threshold, but fall back to + /// snap behavior if the difference is too large. + /// + /// the unmanaged type for +#pragma warning restore IDE0001 + [Serializable] + [GenerateSerializationForGenericParameter(0)] + public class AnticipatedNetworkVariable : NetworkVariableBase + { + [SerializeField] + private NetworkVariable m_AuthoritativeValue; + private T m_AnticipatedValue; + private T m_PreviousAnticipatedValue; + private ulong m_LastAuthorityUpdateCounter = 0; + private ulong m_LastAnticipationCounter = 0; + private bool m_IsDisposed = false; + private bool m_SettingAuthoritativeValue = false; + + private T m_SmoothFrom; + private T m_SmoothTo; + private float m_SmoothDuration; + private float m_CurrentSmoothTime; + private bool m_HasSmoothValues; + +#pragma warning disable IDE0001 + /// + /// Defines what the behavior should be if we receive a value from the server with an earlier associated + /// time value than the anticipation time value. + ///

+ /// If this is , the stale data will be ignored and the authoritative + /// value will not replace the anticipated value until the anticipation time is reached. + /// and will also not be invoked for this stale data. + ///

+ /// If this is , the stale data will replace the anticipated data and + /// and will be invoked. + /// In this case, the authoritativeTime value passed to will be lower than + /// the anticipationTime value, and that callback can be used to calculate a new anticipated value. + ///
+#pragma warning restore IDE0001 + public StaleDataHandling StaleDataHandling; + + public delegate void OnAuthoritativeValueChangedDelegate(AnticipatedNetworkVariable variable, in T previousValue, in T newValue); + + /// + /// Invoked any time the authoritative value changes, even when the data is stale or has been changed locally. + /// + public OnAuthoritativeValueChangedDelegate OnAuthoritativeValueChanged = null; + + /// + /// Determines if the difference between the last serialized value and the current value is large enough + /// to serialize it again. + /// + public event NetworkVariable.CheckExceedsDirtinessThresholdDelegate CheckExceedsDirtinessThreshold + { + add => m_AuthoritativeValue.CheckExceedsDirtinessThreshold += value; + remove => m_AuthoritativeValue.CheckExceedsDirtinessThreshold -= value; + } + + private class AnticipatedObject : IAnticipatedObject + { + public AnticipatedNetworkVariable Variable; + + public void Update() + { + Variable.Update(); + } + + public void ResetAnticipation() + { + Variable.ShouldReanticipate = false; + } + + public NetworkObject OwnerObject => Variable.m_NetworkBehaviour.NetworkObject; + } + + private AnticipatedObject m_AnticipatedObject; + + public override void OnInitialize() + { + m_AuthoritativeValue.Initialize(m_NetworkBehaviour); + NetworkVariableSerialization.Duplicate(m_AuthoritativeValue.Value, ref m_AnticipatedValue); + NetworkVariableSerialization.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue); + if (m_NetworkBehaviour != null && m_NetworkBehaviour.NetworkManager != null && m_NetworkBehaviour.NetworkManager.AnticipationSystem != null) + { + m_AnticipatedObject = new AnticipatedObject { Variable = this }; + m_NetworkBehaviour.NetworkManager.AnticipationSystem.AllAnticipatedObjects.Add(m_AnticipatedObject); + } + } + + public override bool ExceedsDirtinessThreshold() + { + return m_AuthoritativeValue.ExceedsDirtinessThreshold(); + } + + /// + /// Retrieves the current value for the variable. + /// This is the "display value" for this variable, and is affected by and + /// , as well as by updates from the authority, depending on + /// and the behavior of any callbacks. + ///

+ /// When a server update arrives, this value will be overwritten + /// by the new server value (unless stale data handling is set + /// to "Ignore" and the update is determined to be stale). + /// This value will be duplicated in + /// , which + /// will NOT be overwritten in server updates. + ///
+ public T Value => m_AnticipatedValue; + + /// + /// Indicates whether this variable currently needs + /// reanticipation. If this is true, the anticipated value + /// has been overwritten by the authoritative value from the + /// server; the previous anticipated value is stored in + /// + public bool ShouldReanticipate + { + get; + private set; + } + + /// + /// Holds the most recent anticipated value, whatever was + /// most recently set using . Unlike + /// , this does not get overwritten + /// when a server update arrives. + /// + public T PreviousAnticipatedValue => m_PreviousAnticipatedValue; + + /// + /// Sets the current value of the variable on the expectation that the authority will set the variable + /// to the same value within one network round trip (i.e., in response to an RPC). + /// + /// + public void Anticipate(T value) + { + if (m_NetworkBehaviour.NetworkManager.ShutdownInProgress || !m_NetworkBehaviour.NetworkManager.IsListening) + { + return; + } + m_SmoothDuration = 0; + m_CurrentSmoothTime = 0; + m_LastAnticipationCounter = m_NetworkBehaviour.NetworkManager.AnticipationSystem.AnticipationCounter; + m_AnticipatedValue = value; + NetworkVariableSerialization.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue); + if (CanClientWrite(m_NetworkBehaviour.NetworkManager.LocalClientId)) + { + AuthoritativeValue = value; + } + } + +#pragma warning disable IDE0001 + /// + /// Retrieves or sets the underlying authoritative value. + /// Note that only a client or server with write permissions to this variable may set this value. + /// When this variable has been anticipated, this value will alawys return the most recent authoritative + /// state, which is updated even if is . + /// +#pragma warning restore IDE0001 + public T AuthoritativeValue + { + get => m_AuthoritativeValue.Value; + set + { + m_SettingAuthoritativeValue = true; + try + { + m_AuthoritativeValue.Value = value; + m_AnticipatedValue = value; + NetworkVariableSerialization.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue); + } + finally + { + m_SettingAuthoritativeValue = false; + } + } + } + + /// + /// A function to interpolate between two values based on a percentage. + /// See , , , and so on + /// for examples. + /// + public delegate T SmoothDelegate(T authoritativeValue, T anticipatedValue, float amount); + + private SmoothDelegate m_SmoothDelegate = null; + + public AnticipatedNetworkVariable(T value = default, + StaleDataHandling staleDataHandling = StaleDataHandling.Ignore) + : base() + { + StaleDataHandling = staleDataHandling; + m_AuthoritativeValue = new NetworkVariable(value) + { + OnValueChanged = OnValueChangedInternal + }; + } + + public void Update() + { + if (m_CurrentSmoothTime < m_SmoothDuration) + { + m_CurrentSmoothTime += m_NetworkBehaviour.NetworkManager.RealTimeProvider.DeltaTime; + var pct = math.min(m_CurrentSmoothTime / m_SmoothDuration, 1f); + m_AnticipatedValue = m_SmoothDelegate(m_SmoothFrom, m_SmoothTo, pct); + NetworkVariableSerialization.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue); + } + } + + public override void Dispose() + { + if (m_IsDisposed) + { + return; + } + + if (m_NetworkBehaviour != null && m_NetworkBehaviour.NetworkManager != null && m_NetworkBehaviour.NetworkManager.AnticipationSystem != null) + { + if (m_AnticipatedObject != null) + { + m_NetworkBehaviour.NetworkManager.AnticipationSystem.AllAnticipatedObjects.Remove(m_AnticipatedObject); + m_NetworkBehaviour.NetworkManager.AnticipationSystem.ObjectsToReanticipate.Remove(m_AnticipatedObject); + m_AnticipatedObject = null; + } + } + + m_IsDisposed = true; + + m_AuthoritativeValue.Dispose(); + if (m_AnticipatedValue is IDisposable anticipatedValueDisposable) + { + anticipatedValueDisposable.Dispose(); + } + + m_AnticipatedValue = default; + if (m_PreviousAnticipatedValue is IDisposable previousValueDisposable) + { + previousValueDisposable.Dispose(); + m_PreviousAnticipatedValue = default; + } + + if (m_HasSmoothValues) + { + if (m_SmoothFrom is IDisposable smoothFromDisposable) + { + smoothFromDisposable.Dispose(); + m_SmoothFrom = default; + } + if (m_SmoothTo is IDisposable smoothToDisposable) + { + smoothToDisposable.Dispose(); + m_SmoothTo = default; + } + + m_HasSmoothValues = false; + } + } + + ~AnticipatedNetworkVariable() + { + Dispose(); + } + + private void OnValueChangedInternal(T previousValue, T newValue) + { + if (!m_SettingAuthoritativeValue) + { + m_LastAuthorityUpdateCounter = m_NetworkBehaviour.NetworkManager.AnticipationSystem.LastAnticipationAck; + if (StaleDataHandling == StaleDataHandling.Ignore && m_LastAnticipationCounter > m_LastAuthorityUpdateCounter) + { + // Keep the anticipated value unchanged because it is more recent than the authoritative one. + return; + } + + + ShouldReanticipate = true; + m_NetworkBehaviour.NetworkManager.AnticipationSystem.ObjectsToReanticipate.Add(m_AnticipatedObject); + } + + NetworkVariableSerialization.Duplicate(AuthoritativeValue, ref m_AnticipatedValue); + + m_SmoothDuration = 0; + m_CurrentSmoothTime = 0; + OnAuthoritativeValueChanged?.Invoke(this, previousValue, newValue); + } + + /// + /// Interpolate this variable from to over of + /// real time. The duration uses , so it is affected by . + /// + /// + /// + /// + /// + public void Smooth(in T from, in T to, float durationSeconds, SmoothDelegate how) + { + if (durationSeconds <= 0) + { + NetworkVariableSerialization.Duplicate(to, ref m_AnticipatedValue); + m_SmoothDuration = 0; + m_CurrentSmoothTime = 0; + m_SmoothDelegate = null; + return; + } + NetworkVariableSerialization.Duplicate(from, ref m_AnticipatedValue); + NetworkVariableSerialization.Duplicate(from, ref m_SmoothFrom); + NetworkVariableSerialization.Duplicate(to, ref m_SmoothTo); + m_SmoothDuration = durationSeconds; + m_CurrentSmoothTime = 0; + m_SmoothDelegate = how; + m_HasSmoothValues = true; + } + + public override bool IsDirty() + { + return m_AuthoritativeValue.IsDirty(); + } + + public override void ResetDirty() + { + m_AuthoritativeValue.ResetDirty(); + } + + public override void WriteDelta(FastBufferWriter writer) + { + m_AuthoritativeValue.WriteDelta(writer); + } + + public override void WriteField(FastBufferWriter writer) + { + m_AuthoritativeValue.WriteField(writer); + } + + public override void ReadField(FastBufferReader reader) + { + m_AuthoritativeValue.ReadField(reader); + NetworkVariableSerialization.Duplicate(m_AuthoritativeValue.Value, ref m_AnticipatedValue); + NetworkVariableSerialization.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue); + } + + public override void ReadDelta(FastBufferReader reader, bool keepDirtyDelta) + { + m_AuthoritativeValue.ReadDelta(reader, keepDirtyDelta); + } + } +} diff --git a/Runtime/NetworkVariable/AnticipatedNetworkVariable.cs.meta b/Runtime/NetworkVariable/AnticipatedNetworkVariable.cs.meta new file mode 100644 index 0000000..d3fe734 --- /dev/null +++ b/Runtime/NetworkVariable/AnticipatedNetworkVariable.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: fc9fd5701bee8534a971eb9f49178e21 \ No newline at end of file diff --git a/Runtime/NetworkVariable/NetworkVariable.cs b/Runtime/NetworkVariable/NetworkVariable.cs index cf4d36e..121f7e6 100644 --- a/Runtime/NetworkVariable/NetworkVariable.cs +++ b/Runtime/NetworkVariable/NetworkVariable.cs @@ -21,6 +21,29 @@ public class NetworkVariable : NetworkVariableBase /// The callback to be invoked when the value gets changed ///
public OnValueChangedDelegate OnValueChanged; + + public delegate bool CheckExceedsDirtinessThresholdDelegate(in T previousValue, in T newValue); + + public CheckExceedsDirtinessThresholdDelegate CheckExceedsDirtinessThreshold; + + public override bool ExceedsDirtinessThreshold() + { + if (CheckExceedsDirtinessThreshold != null && m_HasPreviousValue) + { + return CheckExceedsDirtinessThreshold(m_PreviousValue, m_InternalValue); + } + + return true; + } + + public override void OnInitialize() + { + base.OnInitialize(); + + m_HasPreviousValue = true; + NetworkVariableSerialization.Duplicate(m_InternalValue, ref m_PreviousValue); + } + internal override NetworkVariableType Type => NetworkVariableType.Value; /// diff --git a/Runtime/NetworkVariable/NetworkVariableBase.cs b/Runtime/NetworkVariable/NetworkVariableBase.cs index e142fe9..034d730 100644 --- a/Runtime/NetworkVariable/NetworkVariableBase.cs +++ b/Runtime/NetworkVariable/NetworkVariableBase.cs @@ -3,11 +3,26 @@ namespace Unity.Netcode { + public struct NetworkVariableUpdateTraits + { + [Tooltip("The minimum amount of time that must pass between sending updates. If this amount of time has not passed since the last update, dirtiness will be ignored.")] + public float MinSecondsBetweenUpdates; + + [Tooltip("The maximum amount of time that a variable can be dirty without sending an update. If this amount of time has passed since the last update, an update will be sent even if the dirtiness threshold has not been met.")] + public float MaxSecondsBetweenUpdates; + } + /// /// Interface for network value containers /// public abstract class NetworkVariableBase : IDisposable { + [SerializeField] + internal NetworkVariableUpdateTraits UpdateTraits = default; + + [NonSerialized] + internal double LastUpdateSent; + /// /// The delivery type (QoS) to send data with /// @@ -52,7 +67,42 @@ public void Initialize(NetworkBehaviour networkBehaviour) m_InternalNetworkManager = m_NetworkBehaviour.NetworkObject?.NetworkManager; // When in distributed authority mode, there is no such thing as server write permissions InternalWritePerm = m_InternalNetworkManager.DistributedAuthorityMode ? NetworkVariableWritePermission.Owner : InternalWritePerm; + + if (m_NetworkBehaviour.NetworkManager.NetworkTimeSystem != null) + { + UpdateLastSentTime(); + } } + + OnInitialize(); + } + + /// + /// Called on initialization + /// + public virtual void OnInitialize() + { + + } + + /// + /// Sets the update traits for this network variable to determine how frequently it will send updates. + /// + /// + public void SetUpdateTraits(NetworkVariableUpdateTraits traits) + { + UpdateTraits = traits; + } + + /// + /// Check whether or not this variable has changed significantly enough to send an update. + /// If not, no update will be sent even if the variable is dirty, unless the time since last update exceeds + /// the ' . + /// + /// + public virtual bool ExceedsDirtinessThreshold() + { + return true; } /// @@ -125,6 +175,25 @@ public virtual void SetDirty(bool isDirty) } } + internal bool CanSend() + { + var timeSinceLastUpdate = m_NetworkBehaviour.NetworkManager.NetworkTimeSystem.LocalTime - LastUpdateSent; + return + ( + UpdateTraits.MaxSecondsBetweenUpdates > 0 && + timeSinceLastUpdate >= UpdateTraits.MaxSecondsBetweenUpdates + ) || + ( + timeSinceLastUpdate >= UpdateTraits.MinSecondsBetweenUpdates && + ExceedsDirtinessThreshold() + ); + } + + internal void UpdateLastSentTime() + { + LastUpdateSent = m_NetworkBehaviour.NetworkManager.NetworkTimeSystem.LocalTime; + } + internal static bool IgnoreInitializeWarning; protected void MarkNetworkBehaviourDirty() @@ -147,6 +216,17 @@ protected void MarkNetworkBehaviourDirty() } return; } + + if (!m_NetworkBehaviour.NetworkManager.IsListening) + { + if (m_NetworkBehaviour.NetworkManager.LogLevel <= LogLevel.Developer) + { + Debug.LogWarning($"NetworkVariable is written to after the NetworkManager has already shutdown! " + + "Are you modifying a NetworkVariable within a NetworkBehaviour.OnDestroy or NetworkBehaviour.OnDespawn method?"); + } + return; + } + m_NetworkBehaviour.NetworkManager.BehaviourUpdater?.AddForUpdate(m_NetworkBehaviour.NetworkObject); } diff --git a/Runtime/Serialization/NetworkBehaviourReference.cs b/Runtime/Serialization/NetworkBehaviourReference.cs index ab2a886..5d8f9c7 100644 --- a/Runtime/Serialization/NetworkBehaviourReference.cs +++ b/Runtime/Serialization/NetworkBehaviourReference.cs @@ -11,6 +11,8 @@ public struct NetworkBehaviourReference : INetworkSerializable, IEquatable /// Creates a new instance of the struct. @@ -21,7 +23,9 @@ public NetworkBehaviourReference(NetworkBehaviour networkBehaviour) { if (networkBehaviour == null) { - throw new ArgumentNullException(nameof(networkBehaviour)); + m_NetworkObjectReference = new NetworkObjectReference((NetworkObject)null); + m_NetworkBehaviourId = s_NullId; + return; } if (networkBehaviour.NetworkObject == null) { @@ -60,6 +64,11 @@ public bool TryGet(out T networkBehaviour, NetworkManager networkManager = nu [MethodImpl(MethodImplOptions.AggressiveInlining)] private static NetworkBehaviour GetInternal(NetworkBehaviourReference networkBehaviourRef, NetworkManager networkManager = null) { + if (networkBehaviourRef.m_NetworkBehaviourId == s_NullId) + { + return null; + } + if (networkBehaviourRef.m_NetworkObjectReference.TryGet(out NetworkObject networkObject, networkManager)) { return networkObject.GetNetworkBehaviourAtOrderIndex(networkBehaviourRef.m_NetworkBehaviourId); diff --git a/Runtime/Serialization/NetworkObjectReference.cs b/Runtime/Serialization/NetworkObjectReference.cs index dc91044..60dcf04 100644 --- a/Runtime/Serialization/NetworkObjectReference.cs +++ b/Runtime/Serialization/NetworkObjectReference.cs @@ -10,6 +10,7 @@ namespace Unity.Netcode public struct NetworkObjectReference : INetworkSerializable, IEquatable { private ulong m_NetworkObjectId; + private static ulong s_NullId = ulong.MaxValue; /// /// The of the referenced . @@ -30,7 +31,8 @@ public NetworkObjectReference(NetworkObject networkObject) { if (networkObject == null) { - throw new ArgumentNullException(nameof(networkObject)); + m_NetworkObjectId = s_NullId; + return; } if (networkObject.IsSpawned == false) @@ -51,10 +53,16 @@ public NetworkObjectReference(GameObject gameObject) { if (gameObject == null) { - throw new ArgumentNullException(nameof(gameObject)); + m_NetworkObjectId = s_NullId; + return; + } + + var networkObject = gameObject.GetComponent(); + if (!networkObject) + { + throw new ArgumentException($"Cannot create {nameof(NetworkObjectReference)} from {nameof(GameObject)} without a {nameof(NetworkObject)} component."); } - var networkObject = gameObject.GetComponent() ?? throw new ArgumentException($"Cannot create {nameof(NetworkObjectReference)} from {nameof(GameObject)} without a {nameof(NetworkObject)} component."); if (networkObject.IsSpawned == false) { throw new ArgumentException($"{nameof(NetworkObjectReference)} can only be created from spawned {nameof(NetworkObject)}s."); @@ -80,10 +88,14 @@ public bool TryGet(out NetworkObject networkObject, NetworkManager networkManage /// /// The reference. /// The networkmanager. Uses to resolve if null. - /// The resolves . Returns null if the networkobject was not found + /// The resolved . Returns null if the networkobject was not found [MethodImpl(MethodImplOptions.AggressiveInlining)] private static NetworkObject Resolve(NetworkObjectReference networkObjectRef, NetworkManager networkManager = null) { + if (networkObjectRef.m_NetworkObjectId == s_NullId) + { + return null; + } networkManager = networkManager ?? NetworkManager.Singleton; networkManager.SpawnManager.SpawnedObjects.TryGetValue(networkObjectRef.m_NetworkObjectId, out NetworkObject networkObject); diff --git a/Runtime/Timing/AnticipationSystem.cs b/Runtime/Timing/AnticipationSystem.cs new file mode 100644 index 0000000..b61afd4 --- /dev/null +++ b/Runtime/Timing/AnticipationSystem.cs @@ -0,0 +1,100 @@ +using System.Collections.Generic; + +namespace Unity.Netcode +{ + internal interface IAnticipationEventReceiver + { + public void SetupForUpdate(); + public void SetupForRender(); + } + + internal interface IAnticipatedObject + { + public void Update(); + public void ResetAnticipation(); + public NetworkObject OwnerObject { get; } + } + + internal class AnticipationSystem + { + internal ulong LastAnticipationAck; + internal double LastAnticipationAckTime; + + internal HashSet AllAnticipatedObjects = new HashSet(); + + internal ulong AnticipationCounter; + + private NetworkManager m_NetworkManager; + + public HashSet ObjectsToReanticipate = new HashSet(); + + public AnticipationSystem(NetworkManager manager) + { + m_NetworkManager = manager; + } + + public event NetworkManager.ReanticipateDelegate OnReanticipate; + + private HashSet m_AnticipationEventReceivers = new HashSet(); + + public void RegisterForAnticipationEvents(IAnticipationEventReceiver receiver) + { + m_AnticipationEventReceivers.Add(receiver); + } + public void DeregisterForAnticipationEvents(IAnticipationEventReceiver receiver) + { + m_AnticipationEventReceivers.Remove(receiver); + } + + public void SetupForUpdate() + { + foreach (var receiver in m_AnticipationEventReceivers) + { + receiver.SetupForUpdate(); + } + } + + public void SetupForRender() + { + foreach (var receiver in m_AnticipationEventReceivers) + { + receiver.SetupForRender(); + } + } + + public void ProcessReanticipation() + { + var lastRoundTripTime = m_NetworkManager.LocalTime.Time - LastAnticipationAckTime; + foreach (var item in ObjectsToReanticipate) + { + foreach (var behaviour in item.OwnerObject.ChildNetworkBehaviours) + { + behaviour.OnReanticipate(lastRoundTripTime); + } + item.ResetAnticipation(); + } + + ObjectsToReanticipate.Clear(); + OnReanticipate?.Invoke(lastRoundTripTime); + } + + public void Update() + { + foreach (var item in AllAnticipatedObjects) + { + item.Update(); + } + } + + public void Sync() + { + if (AllAnticipatedObjects.Count != 0 && !m_NetworkManager.ShutdownInProgress && !m_NetworkManager.ConnectionManager.LocalClient.IsServer && m_NetworkManager.ConnectionManager.LocalClient.IsConnected) + { + var message = new AnticipationCounterSyncPingMessage { Counter = AnticipationCounter, Time = m_NetworkManager.LocalTime.Time }; + m_NetworkManager.MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, NetworkManager.ServerClientId); + } + + ++AnticipationCounter; + } + } +} diff --git a/Runtime/Timing/AnticipationSystem.cs.meta b/Runtime/Timing/AnticipationSystem.cs.meta new file mode 100644 index 0000000..9dc824c --- /dev/null +++ b/Runtime/Timing/AnticipationSystem.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 4a75eccede7ecf1408f61dd55c338e06 \ No newline at end of file diff --git a/Runtime/Timing/NetworkTime.cs b/Runtime/Timing/NetworkTime.cs index 71e3349..7352c8e 100644 --- a/Runtime/Timing/NetworkTime.cs +++ b/Runtime/Timing/NetworkTime.cs @@ -24,6 +24,11 @@ public struct NetworkTime /// public double TickOffset => m_CachedTickOffset; + /// + /// Gets the tick, including partial tick value passed since it started. + /// + public double TickWithPartial => Tick + (TickOffset / m_TickInterval); + /// /// Gets the current time. This is a non fixed time value and similar to . /// diff --git a/Runtime/Timing/NetworkTimeSystem.cs b/Runtime/Timing/NetworkTimeSystem.cs index 16a3c4e..4dbd85a 100644 --- a/Runtime/Timing/NetworkTimeSystem.cs +++ b/Runtime/Timing/NetworkTimeSystem.cs @@ -5,7 +5,9 @@ namespace Unity.Netcode { /// /// is a standalone system which can be used to run a network time simulation. - /// The network time system maintains both a local and a server time. The local time is based on + /// The network time system maintains both a local and a server time. The local time is based on the server time + /// as last received from the server plus an offset based on the current RTT - in other words, it is a best-guess + /// effort at predicting what the server tick will be when a given network action is processed on the server. /// public class NetworkTimeSystem { diff --git a/TestHelpers/Runtime/MockTransport.cs b/TestHelpers/Runtime/MockTransport.cs index 4ff644e..587f299 100644 --- a/TestHelpers/Runtime/MockTransport.cs +++ b/TestHelpers/Runtime/MockTransport.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Random = UnityEngine.Random; namespace Unity.Netcode.TestHelpers.Runtime { @@ -10,6 +11,7 @@ private struct MessageData public ulong FromClientId; public ArraySegment Payload; public NetworkEvent Event; + public float AvailableTime; } private static Dictionary> s_MessageQueue = new Dictionary>(); @@ -18,21 +20,44 @@ private struct MessageData public static ulong HighTransportId = 0; public ulong TransportId = 0; + public float SimulatedLatencySeconds; + public float PacketDropRate; + public float LatencyJitter; public NetworkManager NetworkManager; public override void Send(ulong clientId, ArraySegment payload, NetworkDelivery networkDelivery) { + if (Random.Range(0, 1) < PacketDropRate) + { + return; + } var copy = new byte[payload.Array.Length]; Array.Copy(payload.Array, copy, payload.Array.Length); - s_MessageQueue[clientId].Enqueue(new MessageData { FromClientId = TransportId, Payload = new ArraySegment(copy, payload.Offset, payload.Count), Event = NetworkEvent.Data }); + s_MessageQueue[clientId].Enqueue(new MessageData + { + FromClientId = TransportId, + Payload = new ArraySegment(copy, payload.Offset, payload.Count), + Event = NetworkEvent.Data, + AvailableTime = + NetworkManager.RealTimeProvider.UnscaledTime + SimulatedLatencySeconds + Random.Range(-LatencyJitter, LatencyJitter) + }); } public override NetworkEvent PollEvent(out ulong clientId, out ArraySegment payload, out float receiveTime) { if (s_MessageQueue[TransportId].Count > 0) { - var data = s_MessageQueue[TransportId].Dequeue(); + var data = s_MessageQueue[TransportId].Peek(); + if (data.AvailableTime > NetworkManager.RealTimeProvider.UnscaledTime) + { + clientId = 0; + payload = new ArraySegment(); + receiveTime = 0; + return NetworkEvent.Nothing; + } + + s_MessageQueue[TransportId].Dequeue(); clientId = data.FromClientId; payload = data.Payload; receiveTime = NetworkManager.RealTimeProvider.RealTimeSinceStartup; @@ -90,5 +115,19 @@ public override void Initialize(NetworkManager networkManager = null) { NetworkManager = networkManager; } + + public static void Reset() + { + s_MessageQueue.Clear(); + HighTransportId = 0; + } + + public static void ClearQueues() + { + foreach (var kvp in s_MessageQueue) + { + kvp.Value.Clear(); + } + } } } diff --git a/TestHelpers/Runtime/NetcodeIntegrationTest.cs b/TestHelpers/Runtime/NetcodeIntegrationTest.cs index 3537df2..a091e43 100644 --- a/TestHelpers/Runtime/NetcodeIntegrationTest.cs +++ b/TestHelpers/Runtime/NetcodeIntegrationTest.cs @@ -337,6 +337,15 @@ public IEnumerator SetUp() NetcodeLogAssert = new NetcodeLogAssert(); if (m_EnableTimeTravel) { + if (m_NetworkManagerInstatiationMode == NetworkManagerInstatiationMode.AllTests) + { + MockTransport.ClearQueues(); + } + else + { + MockTransport.Reset(); + } + // Setup the frames per tick for time travel advance to next tick ConfigureFramesPerTick(); } @@ -636,6 +645,33 @@ protected void StopOneClientWithTimeTravel(NetworkManager networkManager, bool d Assert.True(WaitForConditionOrTimeOutWithTimeTravel(() => !networkManager.IsConnectedClient)); } + protected void SetTimeTravelSimulatedLatency(float latencySeconds) + { + ((MockTransport)m_ServerNetworkManager.NetworkConfig.NetworkTransport).SimulatedLatencySeconds = latencySeconds; + foreach (var client in m_ClientNetworkManagers) + { + ((MockTransport)client.NetworkConfig.NetworkTransport).SimulatedLatencySeconds = latencySeconds; + } + } + + protected void SetTimeTravelSimulatedDropRate(float dropRatePercent) + { + ((MockTransport)m_ServerNetworkManager.NetworkConfig.NetworkTransport).PacketDropRate = dropRatePercent; + foreach (var client in m_ClientNetworkManagers) + { + ((MockTransport)client.NetworkConfig.NetworkTransport).PacketDropRate = dropRatePercent; + } + } + + protected void SetTimeTravelSimulatedLatencyJitter(float jitterSeconds) + { + ((MockTransport)m_ServerNetworkManager.NetworkConfig.NetworkTransport).LatencyJitter = jitterSeconds; + foreach (var client in m_ClientNetworkManagers) + { + ((MockTransport)client.NetworkConfig.NetworkTransport).LatencyJitter = jitterSeconds; + } + } + /// /// Creates the server and clients /// @@ -1880,8 +1916,21 @@ public static void TimeTravelToNextTick() /// public static void SimulateOneFrame() { - foreach (NetworkUpdateStage stage in Enum.GetValues(typeof(NetworkUpdateStage))) + foreach (NetworkUpdateStage updateStage in Enum.GetValues(typeof(NetworkUpdateStage))) { + var stage = updateStage; + // These two are out of order numerically due to backward compatibility + // requirements. We have to swap them to maintain correct execution + // order. + if (stage == NetworkUpdateStage.PostScriptLateUpdate) + { + stage = NetworkUpdateStage.PostLateUpdate; + } + else if (stage == NetworkUpdateStage.PostLateUpdate) + { + stage = NetworkUpdateStage.PostScriptLateUpdate; + } + NetworkUpdateLoop.RunNetworkUpdateStage(stage); string methodName = string.Empty; switch (stage) @@ -1900,13 +1949,18 @@ public static void SimulateOneFrame() if (!string.IsNullOrEmpty(methodName)) { #if UNITY_2023_1_OR_NEWER - foreach (var behaviour in Object.FindObjectsByType(FindObjectsSortMode.InstanceID)) + foreach (var obj in Object.FindObjectsByType(FindObjectsSortMode.InstanceID)) #else - foreach (var behaviour in Object.FindObjectsOfType()) + foreach (var obj in Object.FindObjectsOfType()) #endif { - var method = behaviour.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); - method?.Invoke(behaviour, new object[] { }); + var method = obj.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); + method?.Invoke(obj, new object[] { }); + foreach (var behaviour in obj.ChildNetworkBehaviours) + { + var behaviourMethod = behaviour.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); + behaviourMethod?.Invoke(behaviour, new object[] { }); + } } } } diff --git a/Tests/Runtime/NetworkManagerEventsTests.cs b/Tests/Runtime/NetworkManagerEventsTests.cs index 1b872f9..195e8b3 100644 --- a/Tests/Runtime/NetworkManagerEventsTests.cs +++ b/Tests/Runtime/NetworkManagerEventsTests.cs @@ -4,6 +4,7 @@ using Unity.Netcode.TestHelpers.Runtime; using UnityEngine; using UnityEngine.TestTools; +using Object = UnityEngine.Object; namespace Unity.Netcode.RuntimeTests { @@ -35,7 +36,7 @@ public IEnumerator OnServerStoppedCalledWhenServerStops() m_ServerManager.OnServerStopped += onServerStopped; m_ServerManager.Shutdown(); - UnityEngine.Object.DestroyImmediate(gameObject); + Object.DestroyImmediate(gameObject); yield return WaitUntilManagerShutsdown(); @@ -92,7 +93,7 @@ public IEnumerator OnClientAndServerStoppedCalledWhenHostStops() m_ServerManager.OnServerStopped += onServerStopped; m_ServerManager.OnClientStopped += onClientStopped; m_ServerManager.Shutdown(); - UnityEngine.Object.DestroyImmediate(gameObject); + Object.DestroyImmediate(gameObject); yield return WaitUntilManagerShutsdown(); @@ -228,6 +229,18 @@ in NetworkTimeSystem.Sync */ public virtual IEnumerator Teardown() { NetcodeIntegrationTestHelpers.Destroy(); + if (m_ServerManager != null) + { + m_ServerManager.ShutdownInternal(); + Object.DestroyImmediate(m_ServerManager); + m_ServerManager = null; + } + if (m_ClientManager != null) + { + m_ClientManager.ShutdownInternal(); + Object.DestroyImmediate(m_ClientManager); + m_ClientManager = null; + } yield return null; } } diff --git a/Tests/Runtime/NetworkTransformAnticipationTests.cs b/Tests/Runtime/NetworkTransformAnticipationTests.cs new file mode 100644 index 0000000..44530a7 --- /dev/null +++ b/Tests/Runtime/NetworkTransformAnticipationTests.cs @@ -0,0 +1,521 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; +using Unity.Netcode.Components; +using Unity.Netcode.TestHelpers.Runtime; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace Unity.Netcode.RuntimeTests +{ + internal class NetworkTransformAnticipationComponent : NetworkBehaviour + { + [Rpc(SendTo.Server)] + public void MoveRpc(Vector3 newPosition) + { + transform.position = newPosition; + } + + [Rpc(SendTo.Server)] + public void ScaleRpc(Vector3 newScale) + { + transform.localScale = newScale; + } + + [Rpc(SendTo.Server)] + public void RotateRpc(Quaternion newRotation) + { + transform.rotation = newRotation; + } + + public bool ShouldSmooth = false; + public bool ShouldMove = false; + + public override void OnReanticipate(double lastRoundTripTime) + { + var transform_ = GetComponent(); + if (transform_.ShouldReanticipate) + { + if (ShouldSmooth) + { + transform_.Smooth(transform_.PreviousAnticipatedState, transform_.AuthoritativeState, 1); + } + + if (ShouldMove) + { + transform_.AnticipateMove(transform_.AuthoritativeState.Position + new Vector3(0, 5, 0)); + + } + } + } + } + + internal class NetworkTransformAnticipationTests : NetcodeIntegrationTest + { + protected override int NumberOfClients => 2; + + protected override bool m_EnableTimeTravel => true; + protected override bool m_SetupIsACoroutine => false; + protected override bool m_TearDownIsACoroutine => false; + + protected override void OnPlayerPrefabGameObjectCreated() + { + m_PlayerPrefab.AddComponent(); + m_PlayerPrefab.AddComponent(); + } + + protected override void OnTimeTravelServerAndClientsConnected() + { + var serverComponent = GetServerComponent(); + var testComponent = GetTestComponent(); + var otherClientComponent = GetOtherClientComponent(); + + serverComponent.transform.position = Vector3.zero; + serverComponent.transform.localScale = Vector3.one; + serverComponent.transform.rotation = Quaternion.LookRotation(Vector3.forward); + testComponent.transform.position = Vector3.zero; + testComponent.transform.localScale = Vector3.one; + testComponent.transform.rotation = Quaternion.LookRotation(Vector3.forward); + otherClientComponent.transform.position = Vector3.zero; + otherClientComponent.transform.localScale = Vector3.one; + otherClientComponent.transform.rotation = Quaternion.LookRotation(Vector3.forward); + } + + public AnticipatedNetworkTransform GetTestComponent() + { + return m_ClientNetworkManagers[0].LocalClient.PlayerObject.GetComponent(); + } + + public AnticipatedNetworkTransform GetServerComponent() + { + foreach (var obj in Object.FindObjectsByType(FindObjectsSortMode.None)) + { + if (obj.NetworkManager == m_ServerNetworkManager && obj.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId) + { + return obj; + } + } + + return null; + } + + public AnticipatedNetworkTransform GetOtherClientComponent() + { + foreach (var obj in Object.FindObjectsByType(FindObjectsSortMode.None)) + { + if (obj.NetworkManager == m_ClientNetworkManagers[1] && obj.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId) + { + return obj; + } + } + + return null; + } + + [Test] + public void WhenAnticipating_ValueChangesImmediately() + { + var testComponent = GetTestComponent(); + + testComponent.AnticipateMove(new Vector3(0, 1, 2)); + testComponent.AnticipateScale(new Vector3(1, 2, 3)); + testComponent.AnticipateRotate(Quaternion.LookRotation(new Vector3(2, 3, 4))); + + Assert.AreEqual(new Vector3(0, 1, 2), testComponent.transform.position); + Assert.AreEqual(new Vector3(1, 2, 3), testComponent.transform.localScale); + Assert.AreEqual(Quaternion.LookRotation(new Vector3(2, 3, 4)), testComponent.transform.rotation); + + Assert.AreEqual(new Vector3(0, 1, 2), testComponent.AnticipatedState.Position); + Assert.AreEqual(new Vector3(1, 2, 3), testComponent.AnticipatedState.Scale); + Assert.AreEqual(Quaternion.LookRotation(new Vector3(2, 3, 4)), testComponent.AnticipatedState.Rotation); + + } + + [Test] + public void WhenAnticipating_AuthoritativeValueDoesNotChange() + { + var testComponent = GetTestComponent(); + + var startPosition = testComponent.transform.position; + var startScale = testComponent.transform.localScale; + var startRotation = testComponent.transform.rotation; + + testComponent.AnticipateMove(new Vector3(0, 1, 2)); + testComponent.AnticipateScale(new Vector3(1, 2, 3)); + testComponent.AnticipateRotate(Quaternion.LookRotation(new Vector3(2, 3, 4))); + + Assert.AreEqual(startPosition, testComponent.AuthoritativeState.Position); + Assert.AreEqual(startScale, testComponent.AuthoritativeState.Scale); + Assert.AreEqual(startRotation, testComponent.AuthoritativeState.Rotation); + } + + [Test] + public void WhenAnticipating_ServerDoesNotChange() + { + var testComponent = GetTestComponent(); + + var startPosition = testComponent.transform.position; + var startScale = testComponent.transform.localScale; + var startRotation = testComponent.transform.rotation; + + testComponent.AnticipateMove(new Vector3(0, 1, 2)); + testComponent.AnticipateScale(new Vector3(1, 2, 3)); + testComponent.AnticipateRotate(Quaternion.LookRotation(new Vector3(2, 3, 4))); + + var serverComponent = GetServerComponent(); + + Assert.AreEqual(startPosition, serverComponent.AuthoritativeState.Position); + Assert.AreEqual(startScale, serverComponent.AuthoritativeState.Scale); + Assert.AreEqual(startRotation, serverComponent.AuthoritativeState.Rotation); + Assert.AreEqual(startPosition, serverComponent.AnticipatedState.Position); + Assert.AreEqual(startScale, serverComponent.AnticipatedState.Scale); + Assert.AreEqual(startRotation, serverComponent.AnticipatedState.Rotation); + + TimeTravel(2, 120); + + Assert.AreEqual(startPosition, serverComponent.AuthoritativeState.Position); + Assert.AreEqual(startScale, serverComponent.AuthoritativeState.Scale); + Assert.AreEqual(startRotation, serverComponent.AuthoritativeState.Rotation); + Assert.AreEqual(startPosition, serverComponent.AnticipatedState.Position); + Assert.AreEqual(startScale, serverComponent.AnticipatedState.Scale); + Assert.AreEqual(startRotation, serverComponent.AnticipatedState.Rotation); + } + + [Test] + public void WhenAnticipating_OtherClientDoesNotChange() + { + var testComponent = GetTestComponent(); + + var startPosition = testComponent.transform.position; + var startScale = testComponent.transform.localScale; + var startRotation = testComponent.transform.rotation; + + testComponent.AnticipateMove(new Vector3(0, 1, 2)); + testComponent.AnticipateScale(new Vector3(1, 2, 3)); + testComponent.AnticipateRotate(Quaternion.LookRotation(new Vector3(2, 3, 4))); + + var otherClientComponent = GetOtherClientComponent(); + + Assert.AreEqual(startPosition, otherClientComponent.AuthoritativeState.Position); + Assert.AreEqual(startScale, otherClientComponent.AuthoritativeState.Scale); + Assert.AreEqual(startRotation, otherClientComponent.AuthoritativeState.Rotation); + Assert.AreEqual(startPosition, otherClientComponent.AnticipatedState.Position); + Assert.AreEqual(startScale, otherClientComponent.AnticipatedState.Scale); + Assert.AreEqual(startRotation, otherClientComponent.AnticipatedState.Rotation); + + TimeTravel(2, 120); + + Assert.AreEqual(startPosition, otherClientComponent.AuthoritativeState.Position); + Assert.AreEqual(startScale, otherClientComponent.AuthoritativeState.Scale); + Assert.AreEqual(startRotation, otherClientComponent.AuthoritativeState.Rotation); + Assert.AreEqual(startPosition, otherClientComponent.AnticipatedState.Position); + Assert.AreEqual(startScale, otherClientComponent.AnticipatedState.Scale); + Assert.AreEqual(startRotation, otherClientComponent.AnticipatedState.Rotation); + } + + [Test] + public void WhenServerChangesSnapValue_ValuesAreUpdated() + { + var testComponent = GetTestComponent(); + var serverComponent = GetServerComponent(); + serverComponent.Interpolate = false; + + testComponent.AnticipateMove(new Vector3(0, 1, 2)); + testComponent.AnticipateScale(new Vector3(1, 2, 3)); + testComponent.AnticipateRotate(Quaternion.LookRotation(new Vector3(2, 3, 4))); + + var rpcComponent = testComponent.GetComponent(); + rpcComponent.MoveRpc(new Vector3(2, 3, 4)); + + WaitForMessageReceivedWithTimeTravel(new List { m_ServerNetworkManager }); + var otherClientComponent = GetOtherClientComponent(); + + WaitForConditionOrTimeOutWithTimeTravel(() => testComponent.AuthoritativeState.Position == serverComponent.transform.position && otherClientComponent.AuthoritativeState.Position == serverComponent.transform.position); + + Assert.AreEqual(serverComponent.transform.position, testComponent.transform.position); + Assert.AreEqual(serverComponent.transform.position, testComponent.AnticipatedState.Position); + Assert.AreEqual(serverComponent.transform.position, testComponent.AuthoritativeState.Position); + + Assert.AreEqual(serverComponent.transform.position, otherClientComponent.transform.position); + Assert.AreEqual(serverComponent.transform.position, otherClientComponent.AnticipatedState.Position); + Assert.AreEqual(serverComponent.transform.position, otherClientComponent.AuthoritativeState.Position); + } + + public void AssertQuaternionsAreEquivalent(Quaternion a, Quaternion b) + { + var aAngles = a.eulerAngles; + var bAngles = b.eulerAngles; + Assert.AreEqual(aAngles.x, bAngles.x, 0.001, $"Quaternions were not equal. Expected: {a}, but was {b}"); + Assert.AreEqual(aAngles.y, bAngles.y, 0.001, $"Quaternions were not equal. Expected: {a}, but was {b}"); + Assert.AreEqual(aAngles.z, bAngles.z, 0.001, $"Quaternions were not equal. Expected: {a}, but was {b}"); + } + public void AssertVectorsAreEquivalent(Vector3 a, Vector3 b) + { + Assert.AreEqual(a.x, b.x, 0.001, $"Vectors were not equal. Expected: {a}, but was {b}"); + Assert.AreEqual(a.y, b.y, 0.001, $"Vectors were not equal. Expected: {a}, but was {b}"); + Assert.AreEqual(a.z, b.z, 0.001, $"Vectors were not equal. Expected: {a}, but was {b}"); + } + + [Test] + public void WhenServerChangesSmoothValue_ValuesAreLerped() + { + var testComponent = GetTestComponent(); + var otherClientComponent = GetOtherClientComponent(); + + testComponent.StaleDataHandling = StaleDataHandling.Ignore; + otherClientComponent.StaleDataHandling = StaleDataHandling.Ignore; + + var serverComponent = GetServerComponent(); + serverComponent.Interpolate = false; + + testComponent.GetComponent().ShouldSmooth = true; + otherClientComponent.GetComponent().ShouldSmooth = true; + + var startPosition = testComponent.transform.position; + var startScale = testComponent.transform.localScale; + var startRotation = testComponent.transform.rotation; + var anticipePosition = new Vector3(0, 1, 2); + var anticipeScale = new Vector3(1, 2, 3); + var anticipeRotation = Quaternion.LookRotation(new Vector3(2, 3, 4)); + var serverSetPosition = new Vector3(3, 4, 5); + var serverSetScale = new Vector3(4, 5, 6); + var serverSetRotation = Quaternion.LookRotation(new Vector3(5, 6, 7)); + + testComponent.AnticipateMove(anticipePosition); + testComponent.AnticipateScale(anticipeScale); + testComponent.AnticipateRotate(anticipeRotation); + + var rpcComponent = testComponent.GetComponent(); + rpcComponent.MoveRpc(serverSetPosition); + rpcComponent.RotateRpc(serverSetRotation); + rpcComponent.ScaleRpc(serverSetScale); + + WaitForMessagesReceivedWithTimeTravel(new List + { + typeof(RpcMessage), + typeof(RpcMessage), + typeof(RpcMessage), + }, new List { m_ServerNetworkManager }); + + WaitForMessageReceivedWithTimeTravel(m_ClientNetworkManagers.ToList()); + + var percentChanged = 1f / 60f; + + AssertVectorsAreEquivalent(Vector3.Lerp(anticipePosition, serverSetPosition, percentChanged), testComponent.transform.position); + AssertVectorsAreEquivalent(Vector3.Lerp(anticipeScale, serverSetScale, percentChanged), testComponent.transform.localScale); + AssertQuaternionsAreEquivalent(Quaternion.Slerp(anticipeRotation, serverSetRotation, percentChanged), testComponent.transform.rotation); + + AssertVectorsAreEquivalent(Vector3.Lerp(anticipePosition, serverSetPosition, percentChanged), testComponent.AnticipatedState.Position); + AssertVectorsAreEquivalent(Vector3.Lerp(anticipeScale, serverSetScale, percentChanged), testComponent.AnticipatedState.Scale); + AssertQuaternionsAreEquivalent(Quaternion.Slerp(anticipeRotation, serverSetRotation, percentChanged), testComponent.AnticipatedState.Rotation); + + AssertVectorsAreEquivalent(serverSetPosition, testComponent.AuthoritativeState.Position); + AssertVectorsAreEquivalent(serverSetScale, testComponent.AuthoritativeState.Scale); + AssertQuaternionsAreEquivalent(serverSetRotation, testComponent.AuthoritativeState.Rotation); + + AssertVectorsAreEquivalent(Vector3.Lerp(startPosition, serverSetPosition, percentChanged), otherClientComponent.transform.position); + AssertVectorsAreEquivalent(Vector3.Lerp(startScale, serverSetScale, percentChanged), otherClientComponent.transform.localScale); + AssertQuaternionsAreEquivalent(Quaternion.Slerp(startRotation, serverSetRotation, percentChanged), otherClientComponent.transform.rotation); + + AssertVectorsAreEquivalent(Vector3.Lerp(startPosition, serverSetPosition, percentChanged), otherClientComponent.AnticipatedState.Position); + AssertVectorsAreEquivalent(Vector3.Lerp(startScale, serverSetScale, percentChanged), otherClientComponent.AnticipatedState.Scale); + AssertQuaternionsAreEquivalent(Quaternion.Slerp(startRotation, serverSetRotation, percentChanged), otherClientComponent.AnticipatedState.Rotation); + + AssertVectorsAreEquivalent(serverSetPosition, otherClientComponent.AuthoritativeState.Position); + AssertVectorsAreEquivalent(serverSetScale, otherClientComponent.AuthoritativeState.Scale); + AssertQuaternionsAreEquivalent(serverSetRotation, otherClientComponent.AuthoritativeState.Rotation); + + for (var i = 1; i < 60; ++i) + { + TimeTravel(1f / 60f, 1); + percentChanged = 1f / 60f * (i + 1); + + AssertVectorsAreEquivalent(Vector3.Lerp(anticipePosition, serverSetPosition, percentChanged), testComponent.transform.position); + AssertVectorsAreEquivalent(Vector3.Lerp(anticipeScale, serverSetScale, percentChanged), testComponent.transform.localScale); + AssertQuaternionsAreEquivalent(Quaternion.Slerp(anticipeRotation, serverSetRotation, percentChanged), testComponent.transform.rotation); + + AssertVectorsAreEquivalent(Vector3.Lerp(anticipePosition, serverSetPosition, percentChanged), testComponent.AnticipatedState.Position); + AssertVectorsAreEquivalent(Vector3.Lerp(anticipeScale, serverSetScale, percentChanged), testComponent.AnticipatedState.Scale); + AssertQuaternionsAreEquivalent(Quaternion.Slerp(anticipeRotation, serverSetRotation, percentChanged), testComponent.AnticipatedState.Rotation); + + AssertVectorsAreEquivalent(serverSetPosition, testComponent.AuthoritativeState.Position); + AssertVectorsAreEquivalent(serverSetScale, testComponent.AuthoritativeState.Scale); + AssertQuaternionsAreEquivalent(serverSetRotation, testComponent.AuthoritativeState.Rotation); + + AssertVectorsAreEquivalent(Vector3.Lerp(startPosition, serverSetPosition, percentChanged), otherClientComponent.transform.position); + AssertVectorsAreEquivalent(Vector3.Lerp(startScale, serverSetScale, percentChanged), otherClientComponent.transform.localScale); + AssertQuaternionsAreEquivalent(Quaternion.Slerp(startRotation, serverSetRotation, percentChanged), otherClientComponent.transform.rotation); + + AssertVectorsAreEquivalent(Vector3.Lerp(startPosition, serverSetPosition, percentChanged), otherClientComponent.AnticipatedState.Position); + AssertVectorsAreEquivalent(Vector3.Lerp(startScale, serverSetScale, percentChanged), otherClientComponent.AnticipatedState.Scale); + AssertQuaternionsAreEquivalent(Quaternion.Slerp(startRotation, serverSetRotation, percentChanged), otherClientComponent.AnticipatedState.Rotation); + + AssertVectorsAreEquivalent(serverSetPosition, otherClientComponent.AuthoritativeState.Position); + AssertVectorsAreEquivalent(serverSetScale, otherClientComponent.AuthoritativeState.Scale); + AssertQuaternionsAreEquivalent(serverSetRotation, otherClientComponent.AuthoritativeState.Rotation); + } + TimeTravel(1f / 60f, 1); + + AssertVectorsAreEquivalent(serverSetPosition, testComponent.transform.position); + AssertVectorsAreEquivalent(serverSetScale, testComponent.transform.localScale); + AssertQuaternionsAreEquivalent(serverSetRotation, testComponent.transform.rotation); + + AssertVectorsAreEquivalent(serverSetPosition, testComponent.AnticipatedState.Position); + AssertVectorsAreEquivalent(serverSetScale, testComponent.AnticipatedState.Scale); + AssertQuaternionsAreEquivalent(serverSetRotation, testComponent.AnticipatedState.Rotation); + + AssertVectorsAreEquivalent(serverSetPosition, testComponent.AuthoritativeState.Position); + AssertVectorsAreEquivalent(serverSetScale, testComponent.AuthoritativeState.Scale); + AssertQuaternionsAreEquivalent(serverSetRotation, testComponent.AuthoritativeState.Rotation); + + AssertVectorsAreEquivalent(serverSetPosition, otherClientComponent.transform.position); + AssertVectorsAreEquivalent(serverSetScale, otherClientComponent.transform.localScale); + AssertQuaternionsAreEquivalent(serverSetRotation, otherClientComponent.transform.rotation); + + AssertVectorsAreEquivalent(serverSetPosition, otherClientComponent.AnticipatedState.Position); + AssertVectorsAreEquivalent(serverSetScale, otherClientComponent.AnticipatedState.Scale); + AssertQuaternionsAreEquivalent(serverSetRotation, otherClientComponent.AnticipatedState.Rotation); + + AssertVectorsAreEquivalent(serverSetPosition, otherClientComponent.AuthoritativeState.Position); + AssertVectorsAreEquivalent(serverSetScale, otherClientComponent.AuthoritativeState.Scale); + AssertQuaternionsAreEquivalent(serverSetRotation, otherClientComponent.AuthoritativeState.Rotation); + } + + [Test] + public void WhenServerChangesReanticipeValue_ValuesAreReanticiped() + { + var testComponent = GetTestComponent(); + var otherClientComponent = GetOtherClientComponent(); + + testComponent.GetComponent().ShouldMove = true; + otherClientComponent.GetComponent().ShouldMove = true; + + var serverComponent = GetServerComponent(); + serverComponent.Interpolate = false; + serverComponent.transform.position = new Vector3(0, 1, 2); + var rpcComponent = testComponent.GetComponent(); + rpcComponent.MoveRpc(new Vector3(0, 1, 2)); + + WaitForMessageReceivedWithTimeTravel(new List { m_ServerNetworkManager }); + + WaitForMessageReceivedWithTimeTravel(m_ClientNetworkManagers.ToList()); + + Assert.AreEqual(new Vector3(0, 6, 2), testComponent.transform.position); + Assert.AreEqual(new Vector3(0, 6, 2), testComponent.AnticipatedState.Position); + Assert.AreEqual(new Vector3(0, 1, 2), testComponent.AuthoritativeState.Position); + + Assert.AreEqual(new Vector3(0, 6, 2), otherClientComponent.transform.position); + Assert.AreEqual(new Vector3(0, 6, 2), otherClientComponent.AnticipatedState.Position); + Assert.AreEqual(new Vector3(0, 1, 2), otherClientComponent.AuthoritativeState.Position); + } + + [Test] + public void WhenStaleDataArrivesToIgnoreVariable_ItIsIgnored([Values(10u, 30u, 60u)] uint tickRate, [Values(0u, 1u, 2u)] uint skipFrames) + { + m_ServerNetworkManager.NetworkConfig.TickRate = tickRate; + m_ServerNetworkManager.NetworkTickSystem.TickRate = tickRate; + + for (var i = 0; i < skipFrames; ++i) + { + TimeTravel(1 / 60f, 1); + } + + var serverComponent = GetServerComponent(); + serverComponent.Interpolate = false; + + var testComponent = GetTestComponent(); + testComponent.StaleDataHandling = StaleDataHandling.Ignore; + testComponent.Interpolate = false; + + var otherClientComponent = GetOtherClientComponent(); + otherClientComponent.StaleDataHandling = StaleDataHandling.Ignore; + otherClientComponent.Interpolate = false; + + var rpcComponent = testComponent.GetComponent(); + rpcComponent.MoveRpc(new Vector3(1, 2, 3)); + + WaitForMessageReceivedWithTimeTravel(new List { m_ServerNetworkManager }); + + testComponent.AnticipateMove(new Vector3(0, 5, 0)); + rpcComponent.MoveRpc(new Vector3(4, 5, 6)); + + // Depending on tick rate, one of these two things will happen. + // The assertions are different based on this... either the tick rate is slow enough that the second RPC is received + // before the next update and we move to 4, 5, 6, or the tick rate is fast enough that the next update is sent out + // before the RPC is received and we get the update for the move to 1, 2, 3. Both are valid, what we want to assert + // here is that the anticipated state never becomes 1, 2, 3. + WaitForConditionOrTimeOutWithTimeTravel(() => testComponent.AuthoritativeState.Position == new Vector3(1, 2, 3) || testComponent.AuthoritativeState.Position == new Vector3(4, 5, 6)); + + if (testComponent.AnticipatedState.Position == new Vector3(4, 5, 6)) + { + // Anticiped client received this data for a time earlier than its anticipation, and should have prioritized the anticiped value + Assert.AreEqual(new Vector3(4, 5, 6), testComponent.transform.position); + Assert.AreEqual(new Vector3(4, 5, 6), testComponent.AnticipatedState.Position); + // However, the authoritative value still gets updated + Assert.AreEqual(new Vector3(4, 5, 6), testComponent.AuthoritativeState.Position); + + // Other client got the server value and had made no anticipation, so it applies it to the anticiped value as well. + Assert.AreEqual(new Vector3(4, 5, 6), otherClientComponent.transform.position); + Assert.AreEqual(new Vector3(4, 5, 6), otherClientComponent.AnticipatedState.Position); + Assert.AreEqual(new Vector3(4, 5, 6), otherClientComponent.AuthoritativeState.Position); + } + else + { + // Anticiped client received this data for a time earlier than its anticipation, and should have prioritized the anticiped value + Assert.AreEqual(new Vector3(0, 5, 0), testComponent.transform.position); + Assert.AreEqual(new Vector3(0, 5, 0), testComponent.AnticipatedState.Position); + // However, the authoritative value still gets updated + Assert.AreEqual(new Vector3(1, 2, 3), testComponent.AuthoritativeState.Position); + + // Other client got the server value and had made no anticipation, so it applies it to the anticiped value as well. + Assert.AreEqual(new Vector3(1, 2, 3), otherClientComponent.transform.position); + Assert.AreEqual(new Vector3(1, 2, 3), otherClientComponent.AnticipatedState.Position); + Assert.AreEqual(new Vector3(1, 2, 3), otherClientComponent.AuthoritativeState.Position); + } + } + + + [Test] + public void WhenNonStaleDataArrivesToIgnoreVariable_ItIsNotIgnored([Values(10u, 30u, 60u)] uint tickRate, [Values(0u, 1u, 2u)] uint skipFrames) + { + m_ServerNetworkManager.NetworkConfig.TickRate = tickRate; + m_ServerNetworkManager.NetworkTickSystem.TickRate = tickRate; + + for (var i = 0; i < skipFrames; ++i) + { + TimeTravel(1 / 60f, 1); + } + + var serverComponent = GetServerComponent(); + serverComponent.Interpolate = false; + + var testComponent = GetTestComponent(); + testComponent.StaleDataHandling = StaleDataHandling.Ignore; + testComponent.Interpolate = false; + + var otherClientComponent = GetOtherClientComponent(); + otherClientComponent.StaleDataHandling = StaleDataHandling.Ignore; + otherClientComponent.Interpolate = false; + + testComponent.AnticipateMove(new Vector3(0, 5, 0)); + var rpcComponent = testComponent.GetComponent(); + rpcComponent.MoveRpc(new Vector3(1, 2, 3)); + + WaitForMessageReceivedWithTimeTravel(new List { m_ServerNetworkManager }); + + WaitForConditionOrTimeOutWithTimeTravel(() => testComponent.AuthoritativeState.Position == serverComponent.transform.position && otherClientComponent.AuthoritativeState.Position == serverComponent.transform.position); + + // Anticiped client received this data for a time earlier than its anticipation, and should have prioritized the anticiped value + Assert.AreEqual(new Vector3(1, 2, 3), testComponent.transform.position); + Assert.AreEqual(new Vector3(1, 2, 3), testComponent.AnticipatedState.Position); + // However, the authoritative value still gets updated + Assert.AreEqual(new Vector3(1, 2, 3), testComponent.AuthoritativeState.Position); + + // Other client got the server value and had made no anticipation, so it applies it to the anticiped value as well. + Assert.AreEqual(new Vector3(1, 2, 3), otherClientComponent.transform.position); + Assert.AreEqual(new Vector3(1, 2, 3), otherClientComponent.AnticipatedState.Position); + Assert.AreEqual(new Vector3(1, 2, 3), otherClientComponent.AuthoritativeState.Position); + } + } +} diff --git a/Tests/Runtime/NetworkTransformAnticipationTests.cs.meta b/Tests/Runtime/NetworkTransformAnticipationTests.cs.meta new file mode 100644 index 0000000..ae75b6b --- /dev/null +++ b/Tests/Runtime/NetworkTransformAnticipationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: ceb074b080c27184a9f669cd68355955 \ No newline at end of file diff --git a/Tests/Runtime/NetworkVariableAnticipationTests.cs b/Tests/Runtime/NetworkVariableAnticipationTests.cs new file mode 100644 index 0000000..c436275 --- /dev/null +++ b/Tests/Runtime/NetworkVariableAnticipationTests.cs @@ -0,0 +1,420 @@ +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; +using Unity.Netcode.TestHelpers.Runtime; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace Unity.Netcode.RuntimeTests +{ + internal class NetworkVariableAnticipationComponent : NetworkBehaviour + { + public AnticipatedNetworkVariable SnapOnAnticipationFailVariable = new AnticipatedNetworkVariable(0, StaleDataHandling.Ignore); + public AnticipatedNetworkVariable SmoothOnAnticipationFailVariable = new AnticipatedNetworkVariable(0, StaleDataHandling.Reanticipate); + public AnticipatedNetworkVariable ReanticipateOnAnticipationFailVariable = new AnticipatedNetworkVariable(0, StaleDataHandling.Reanticipate); + + public override void OnReanticipate(double lastRoundTripTime) + { + if (SmoothOnAnticipationFailVariable.ShouldReanticipate) + { + if (Mathf.Abs(SmoothOnAnticipationFailVariable.AuthoritativeValue - SmoothOnAnticipationFailVariable.PreviousAnticipatedValue) > Mathf.Epsilon) + { + SmoothOnAnticipationFailVariable.Smooth(SmoothOnAnticipationFailVariable.PreviousAnticipatedValue, SmoothOnAnticipationFailVariable.AuthoritativeValue, 1, Mathf.Lerp); + } + } + + if (ReanticipateOnAnticipationFailVariable.ShouldReanticipate) + { + // Would love to test some stuff about anticipation based on time, but that is difficult to test accurately. + // This reanticipating variable will just always anticipate a value 5 higher than the server value. + ReanticipateOnAnticipationFailVariable.Anticipate(ReanticipateOnAnticipationFailVariable.AuthoritativeValue + 5); + } + } + + public bool SnapRpcResponseReceived = false; + + [Rpc(SendTo.Server)] + public void SetSnapValueRpc(int i, RpcParams rpcParams = default) + { + SnapOnAnticipationFailVariable.AuthoritativeValue = i; + SetSnapValueResponseRpc(RpcTarget.Single(rpcParams.Receive.SenderClientId, RpcTargetUse.Temp)); + } + + [Rpc(SendTo.SpecifiedInParams)] + public void SetSnapValueResponseRpc(RpcParams rpcParams) + { + SnapRpcResponseReceived = true; + } + + [Rpc(SendTo.Server)] + public void SetSmoothValueRpc(float f) + { + SmoothOnAnticipationFailVariable.AuthoritativeValue = f; + } + + [Rpc(SendTo.Server)] + public void SetReanticipateValueRpc(float f) + { + ReanticipateOnAnticipationFailVariable.AuthoritativeValue = f; + } + } + + internal class NetworkVariableAnticipationTests : NetcodeIntegrationTest + { + protected override int NumberOfClients => 2; + + protected override bool m_EnableTimeTravel => true; + protected override bool m_SetupIsACoroutine => false; + protected override bool m_TearDownIsACoroutine => false; + + protected override void OnPlayerPrefabGameObjectCreated() + { + m_PlayerPrefab.AddComponent(); + } + + public NetworkVariableAnticipationComponent GetTestComponent() + { + return m_ClientNetworkManagers[0].LocalClient.PlayerObject.GetComponent(); + } + + public NetworkVariableAnticipationComponent GetServerComponent() + { + foreach (var obj in Object.FindObjectsByType(FindObjectsSortMode.None)) + { + if (obj.NetworkManager == m_ServerNetworkManager && obj.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId) + { + return obj; + } + } + + return null; + } + + public NetworkVariableAnticipationComponent GetOtherClientComponent() + { + foreach (var obj in Object.FindObjectsByType(FindObjectsSortMode.None)) + { + if (obj.NetworkManager == m_ClientNetworkManagers[1] && obj.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId) + { + return obj; + } + } + + return null; + } + + [Test] + public void WhenAnticipating_ValueChangesImmediately() + { + var testComponent = GetTestComponent(); + + testComponent.SnapOnAnticipationFailVariable.Anticipate(10); + testComponent.SmoothOnAnticipationFailVariable.Anticipate(15); + testComponent.ReanticipateOnAnticipationFailVariable.Anticipate(20); + + Assert.AreEqual(10, testComponent.SnapOnAnticipationFailVariable.Value); + Assert.AreEqual(15, testComponent.SmoothOnAnticipationFailVariable.Value); + Assert.AreEqual(20, testComponent.ReanticipateOnAnticipationFailVariable.Value); + } + + [Test] + public void WhenAnticipating_AuthoritativeValueDoesNotChange() + { + var testComponent = GetTestComponent(); + + testComponent.SnapOnAnticipationFailVariable.Anticipate(10); + testComponent.SmoothOnAnticipationFailVariable.Anticipate(15); + testComponent.ReanticipateOnAnticipationFailVariable.Anticipate(20); + + Assert.AreEqual(0, testComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + Assert.AreEqual(0, testComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue); + Assert.AreEqual(0, testComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue); + } + + [Test] + public void WhenAnticipating_ServerDoesNotChange() + { + var testComponent = GetTestComponent(); + + testComponent.SnapOnAnticipationFailVariable.Anticipate(10); + testComponent.SmoothOnAnticipationFailVariable.Anticipate(15); + testComponent.ReanticipateOnAnticipationFailVariable.Anticipate(20); + + var serverComponent = GetServerComponent(); + + Assert.AreEqual(0, serverComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + Assert.AreEqual(0, serverComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue); + Assert.AreEqual(0, serverComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue); + Assert.AreEqual(0, serverComponent.SnapOnAnticipationFailVariable.Value); + Assert.AreEqual(0, serverComponent.SmoothOnAnticipationFailVariable.Value); + Assert.AreEqual(0, serverComponent.ReanticipateOnAnticipationFailVariable.Value); + + TimeTravel(2, 120); + + Assert.AreEqual(0, serverComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + Assert.AreEqual(0, serverComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue); + Assert.AreEqual(0, serverComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue); + Assert.AreEqual(0, serverComponent.SnapOnAnticipationFailVariable.Value); + Assert.AreEqual(0, serverComponent.SmoothOnAnticipationFailVariable.Value); + Assert.AreEqual(0, serverComponent.ReanticipateOnAnticipationFailVariable.Value); + } + + [Test] + public void WhenAnticipating_OtherClientDoesNotChange() + { + var testComponent = GetTestComponent(); + + testComponent.SnapOnAnticipationFailVariable.Anticipate(10); + testComponent.SmoothOnAnticipationFailVariable.Anticipate(15); + testComponent.ReanticipateOnAnticipationFailVariable.Anticipate(20); + + var otherClientComponent = GetOtherClientComponent(); + + Assert.AreEqual(0, otherClientComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + Assert.AreEqual(0, otherClientComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue); + Assert.AreEqual(0, otherClientComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue); + Assert.AreEqual(0, otherClientComponent.SnapOnAnticipationFailVariable.Value); + Assert.AreEqual(0, otherClientComponent.SmoothOnAnticipationFailVariable.Value); + Assert.AreEqual(0, otherClientComponent.ReanticipateOnAnticipationFailVariable.Value); + + TimeTravel(2, 120); + + Assert.AreEqual(0, otherClientComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + Assert.AreEqual(0, otherClientComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue); + Assert.AreEqual(0, otherClientComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue); + Assert.AreEqual(0, otherClientComponent.SnapOnAnticipationFailVariable.Value); + Assert.AreEqual(0, otherClientComponent.SmoothOnAnticipationFailVariable.Value); + Assert.AreEqual(0, otherClientComponent.ReanticipateOnAnticipationFailVariable.Value); + } + + [Test] + public void WhenServerChangesSnapValue_ValuesAreUpdated() + { + var testComponent = GetTestComponent(); + + testComponent.SnapOnAnticipationFailVariable.Anticipate(10); + + Assert.AreEqual(10, testComponent.SnapOnAnticipationFailVariable.Value); + Assert.AreEqual(0, testComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + + testComponent.SetSnapValueRpc(10); + + WaitForMessageReceivedWithTimeTravel( + new List { m_ServerNetworkManager } + ); + + var serverComponent = GetServerComponent(); + Assert.AreEqual(10, serverComponent.SnapOnAnticipationFailVariable.Value); + Assert.AreEqual(10, serverComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + + var otherClientComponent = GetOtherClientComponent(); + Assert.AreEqual(0, otherClientComponent.SnapOnAnticipationFailVariable.Value); + Assert.AreEqual(0, otherClientComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + + WaitForMessageReceivedWithTimeTravel(m_ClientNetworkManagers.ToList()); + + Assert.AreEqual(10, testComponent.SnapOnAnticipationFailVariable.Value); + Assert.AreEqual(10, testComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + + Assert.AreEqual(10, otherClientComponent.SnapOnAnticipationFailVariable.Value); + Assert.AreEqual(10, otherClientComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + } + + [Test] + public void WhenServerChangesSmoothValue_ValuesAreLerped() + { + var testComponent = GetTestComponent(); + + testComponent.SmoothOnAnticipationFailVariable.Anticipate(15); + + Assert.AreEqual(15, testComponent.SmoothOnAnticipationFailVariable.Value, Mathf.Epsilon); + Assert.AreEqual(0, testComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon); + + // Set to a different value to simulate a anticipation failure - will lerp between the anticipated value + // and the actual one + testComponent.SetSmoothValueRpc(20); + + WaitForMessageReceivedWithTimeTravel( + new List { m_ServerNetworkManager } + ); + + var serverComponent = GetServerComponent(); + Assert.AreEqual(20, serverComponent.SmoothOnAnticipationFailVariable.Value, Mathf.Epsilon); + Assert.AreEqual(20, serverComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon); + + var otherClientComponent = GetOtherClientComponent(); + Assert.AreEqual(0, otherClientComponent.SmoothOnAnticipationFailVariable.Value, Mathf.Epsilon); + Assert.AreEqual(0, otherClientComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon); + + WaitForMessageReceivedWithTimeTravel(m_ClientNetworkManagers.ToList()); + + Assert.AreEqual(15 + 1f / 60f * 5, testComponent.SmoothOnAnticipationFailVariable.Value, Mathf.Epsilon); + Assert.AreEqual(20, testComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon); + + Assert.AreEqual(0 + 1f / 60f * 20, otherClientComponent.SmoothOnAnticipationFailVariable.Value, Mathf.Epsilon); + Assert.AreEqual(20, otherClientComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon); + + for (var i = 1; i < 60; ++i) + { + TimeTravel(1f / 60f, 1); + + Assert.AreEqual(15 + 1f / 60f * 5 * (i + 1), testComponent.SmoothOnAnticipationFailVariable.Value, 0.00001); + Assert.AreEqual(20, testComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon); + + Assert.AreEqual(0 + 1f / 60f * 20 * (i + 1), otherClientComponent.SmoothOnAnticipationFailVariable.Value, 0.00001); + Assert.AreEqual(20, otherClientComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon); + } + TimeTravel(1f / 60f, 1); + Assert.AreEqual(20, testComponent.SmoothOnAnticipationFailVariable.Value, Mathf.Epsilon); + Assert.AreEqual(20, otherClientComponent.SmoothOnAnticipationFailVariable.Value, Mathf.Epsilon); + } + + [Test] + public void WhenServerChangesReanticipateValue_ValuesAreReanticipated() + { + var testComponent = GetTestComponent(); + + testComponent.ReanticipateOnAnticipationFailVariable.Anticipate(15); + + Assert.AreEqual(15, testComponent.ReanticipateOnAnticipationFailVariable.Value, Mathf.Epsilon); + Assert.AreEqual(0, testComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon); + + // Set to a different value to simulate a anticipation failure - will lerp between the anticipated value + // and the actual one + testComponent.SetReanticipateValueRpc(20); + + WaitForMessageReceivedWithTimeTravel( + new List { m_ServerNetworkManager } + ); + + var serverComponent = GetServerComponent(); + Assert.AreEqual(20, serverComponent.ReanticipateOnAnticipationFailVariable.Value, Mathf.Epsilon); + Assert.AreEqual(20, serverComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon); + + var otherClientComponent = GetOtherClientComponent(); + Assert.AreEqual(0, otherClientComponent.ReanticipateOnAnticipationFailVariable.Value, Mathf.Epsilon); + Assert.AreEqual(0, otherClientComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon); + + WaitForMessageReceivedWithTimeTravel(m_ClientNetworkManagers.ToList()); + + Assert.AreEqual(25, testComponent.ReanticipateOnAnticipationFailVariable.Value, Mathf.Epsilon); + Assert.AreEqual(20, testComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon); + + Assert.AreEqual(25, otherClientComponent.ReanticipateOnAnticipationFailVariable.Value, Mathf.Epsilon); + Assert.AreEqual(20, otherClientComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon); + } + + [Test] + public void WhenNonStaleDataArrivesToIgnoreVariable_ItIsNotIgnored([Values(10u, 30u, 60u)] uint tickRate, [Values(0u, 1u, 2u)] uint skipFrames) + { + m_ServerNetworkManager.NetworkConfig.TickRate = tickRate; + m_ServerNetworkManager.NetworkTickSystem.TickRate = tickRate; + + for (var i = 0; i < skipFrames; ++i) + { + TimeTravel(1 / 60f, 1); + } + var testComponent = GetTestComponent(); + testComponent.SnapOnAnticipationFailVariable.Anticipate(10); + + Assert.AreEqual(10, testComponent.SnapOnAnticipationFailVariable.Value); + Assert.AreEqual(0, testComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + testComponent.SetSnapValueRpc(20); + WaitForMessageReceivedWithTimeTravel(new List { m_ServerNetworkManager }); + + var serverComponent = GetServerComponent(); + + Assert.AreEqual(20, serverComponent.SnapOnAnticipationFailVariable.Value); + Assert.AreEqual(20, serverComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + + WaitForMessageReceivedWithTimeTravel(m_ClientNetworkManagers.ToList()); + + // Both values get updated + Assert.AreEqual(20, testComponent.SnapOnAnticipationFailVariable.Value); + Assert.AreEqual(20, testComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + + // Other client got the server value and had made no anticipation, so it applies it to the anticipated value as well. + var otherClientComponent = GetOtherClientComponent(); + Assert.AreEqual(20, otherClientComponent.SnapOnAnticipationFailVariable.Value); + Assert.AreEqual(20, otherClientComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + } + + [Test] + public void WhenStaleDataArrivesToIgnoreVariable_ItIsIgnored([Values(10u, 30u, 60u)] uint tickRate, [Values(0u, 1u, 2u)] uint skipFrames) + { + m_ServerNetworkManager.NetworkConfig.TickRate = tickRate; + m_ServerNetworkManager.NetworkTickSystem.TickRate = tickRate; + + for (var i = 0; i < skipFrames; ++i) + { + TimeTravel(1 / 60f, 1); + } + var testComponent = GetTestComponent(); + testComponent.SnapOnAnticipationFailVariable.Anticipate(10); + + Assert.AreEqual(10, testComponent.SnapOnAnticipationFailVariable.Value); + Assert.AreEqual(0, testComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + + testComponent.SetSnapValueRpc(30); + + var serverComponent = GetServerComponent(); + serverComponent.SnapOnAnticipationFailVariable.AuthoritativeValue = 20; + + Assert.AreEqual(20, serverComponent.SnapOnAnticipationFailVariable.Value); + Assert.AreEqual(20, serverComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + + WaitForMessageReceivedWithTimeTravel(m_ClientNetworkManagers.ToList()); + + if (testComponent.SnapRpcResponseReceived) + { + // In this case the tick rate is slow enough that the RPC was received and processed, so we check that. + Assert.AreEqual(30, testComponent.SnapOnAnticipationFailVariable.Value); + Assert.AreEqual(30, testComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + + var otherClientComponent = GetOtherClientComponent(); + Assert.AreEqual(30, otherClientComponent.SnapOnAnticipationFailVariable.Value); + Assert.AreEqual(30, otherClientComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + } + else + { + // In this case, we got an update before the RPC was processed, so we should have ignored it. + // Anticipated client received this data for a tick earlier than its anticipation, and should have prioritized the anticipated value + Assert.AreEqual(10, testComponent.SnapOnAnticipationFailVariable.Value); + // However, the authoritative value still gets updated + Assert.AreEqual(20, testComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + + // Other client got the server value and had made no anticipation, so it applies it to the anticipated value as well. + var otherClientComponent = GetOtherClientComponent(); + Assert.AreEqual(20, otherClientComponent.SnapOnAnticipationFailVariable.Value); + Assert.AreEqual(20, otherClientComponent.SnapOnAnticipationFailVariable.AuthoritativeValue); + } + } + + [Test] + public void WhenStaleDataArrivesToReanticipatedVariable_ItIsAppliedAndReanticipated() + { + var testComponent = GetTestComponent(); + testComponent.ReanticipateOnAnticipationFailVariable.Anticipate(10); + + Assert.AreEqual(10, testComponent.ReanticipateOnAnticipationFailVariable.Value); + Assert.AreEqual(0, testComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue); + + var serverComponent = GetServerComponent(); + serverComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue = 20; + + Assert.AreEqual(20, serverComponent.ReanticipateOnAnticipationFailVariable.Value); + Assert.AreEqual(20, serverComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue); + + WaitForMessageReceivedWithTimeTravel(m_ClientNetworkManagers.ToList()); + + Assert.AreEqual(25, testComponent.ReanticipateOnAnticipationFailVariable.Value); + // However, the authoritative value still gets updated + Assert.AreEqual(20, testComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue); + + // Other client got the server value and had made no anticipation, so it applies it to the anticipated value as well. + var otherClientComponent = GetOtherClientComponent(); + Assert.AreEqual(25, otherClientComponent.ReanticipateOnAnticipationFailVariable.Value); + Assert.AreEqual(20, otherClientComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue); + } + } +} diff --git a/Tests/Runtime/NetworkVariableAnticipationTests.cs.meta b/Tests/Runtime/NetworkVariableAnticipationTests.cs.meta new file mode 100644 index 0000000..357da56 --- /dev/null +++ b/Tests/Runtime/NetworkVariableAnticipationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 74e627a9d18dcd04e9c56ab2539a6593 \ No newline at end of file diff --git a/Tests/Runtime/NetworkVariableTests.cs b/Tests/Runtime/NetworkVariableTests.cs index 83b4633..e59fad1 100644 --- a/Tests/Runtime/NetworkVariableTests.cs +++ b/Tests/Runtime/NetworkVariableTests.cs @@ -386,9 +386,12 @@ public override int GetHashCode() // Used just to create a NetworkVariable in the templated NetworkBehaviour type that isn't referenced anywhere else // Please do not reference this class anywhere else! - internal class TestClass_ReferencedOnlyByTemplateNetworkBehavourType : TestClass + internal class TestClass_ReferencedOnlyByTemplateNetworkBehaviourType : TestClass, IEquatable { - + public bool Equals(TestClass_ReferencedOnlyByTemplateNetworkBehaviourType other) + { + return Equals((TestClass)other); + } } internal class NetworkVariableTest : NetworkBehaviour @@ -921,7 +924,7 @@ bool VerifyClass() m_Player1OnClient1.GetComponent().TheVar.Value.SomeInt == m_Player1OnServer.GetComponent().TheVar.Value.SomeInt; } - m_Player1OnServer.GetComponent().TheVar.Value = new TestClass_ReferencedOnlyByTemplateNetworkBehavourType { SomeInt = k_TestUInt, SomeBool = false }; + m_Player1OnServer.GetComponent().TheVar.Value = new TestClass_ReferencedOnlyByTemplateNetworkBehaviourType { SomeInt = k_TestUInt, SomeBool = false }; m_Player1OnServer.GetComponent().TheVar.SetDirty(true); // Wait for the client-side to notify it is finished initializing and spawning. diff --git a/Tests/Runtime/NetworkVariableTestsHelperTypes.cs b/Tests/Runtime/NetworkVariableTestsHelperTypes.cs index 004de73..f50811b 100644 --- a/Tests/Runtime/NetworkVariableTestsHelperTypes.cs +++ b/Tests/Runtime/NetworkVariableTestsHelperTypes.cs @@ -903,7 +903,7 @@ internal class ClassHavingNetworkBehaviour : IntermediateNetworkBehavior + internal class ClassHavingNetworkBehaviour2 : TemplateNetworkBehaviourType { } diff --git a/Tests/Runtime/NetworkVariableTraitsTests.cs b/Tests/Runtime/NetworkVariableTraitsTests.cs new file mode 100644 index 0000000..66c326c --- /dev/null +++ b/Tests/Runtime/NetworkVariableTraitsTests.cs @@ -0,0 +1,138 @@ +using NUnit.Framework; +using Unity.Netcode.TestHelpers.Runtime; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace Unity.Netcode.RuntimeTests +{ + internal class NetworkVariableTraitsComponent : NetworkBehaviour + { + public NetworkVariable TheVariable = new NetworkVariable(); + } + + internal class NetworkVariableTraitsTests : NetcodeIntegrationTest + { + protected override int NumberOfClients => 2; + + protected override bool m_EnableTimeTravel => true; + protected override bool m_SetupIsACoroutine => false; + protected override bool m_TearDownIsACoroutine => false; + + protected override void OnPlayerPrefabGameObjectCreated() + { + m_PlayerPrefab.AddComponent(); + } + + public NetworkVariableTraitsComponent GetTestComponent() + { + return m_ClientNetworkManagers[0].LocalClient.PlayerObject.GetComponent(); + } + + public NetworkVariableTraitsComponent GetServerComponent() + { + foreach (var obj in Object.FindObjectsByType(FindObjectsSortMode.None)) + { + if (obj.NetworkManager == m_ServerNetworkManager && obj.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId) + { + return obj; + } + } + + return null; + } + + [Test] + public void WhenNewValueIsLessThanThreshold_VariableIsNotSerialized() + { + var serverComponent = GetServerComponent(); + var testComponent = GetTestComponent(); + serverComponent.TheVariable.CheckExceedsDirtinessThreshold = (in float value, in float newValue) => Mathf.Abs(newValue - value) >= 0.1; + + serverComponent.TheVariable.Value = 0.05f; + + TimeTravel(2, 120); + + Assert.AreEqual(0.05f, serverComponent.TheVariable.Value); ; + Assert.AreEqual(0, testComponent.TheVariable.Value); ; + } + [Test] + public void WhenNewValueIsGreaterThanThreshold_VariableIsSerialized() + { + var serverComponent = GetServerComponent(); + var testComponent = GetTestComponent(); + serverComponent.TheVariable.CheckExceedsDirtinessThreshold = (in float value, in float newValue) => Mathf.Abs(newValue - value) >= 0.1; + + serverComponent.TheVariable.Value = 0.15f; + + TimeTravel(2, 120); + + Assert.AreEqual(0.15f, serverComponent.TheVariable.Value); ; + Assert.AreEqual(0.15f, testComponent.TheVariable.Value); ; + } + + [Test] + public void WhenNewValueIsLessThanThresholdButMaxTimeHasPassed_VariableIsSerialized() + { + var serverComponent = GetServerComponent(); + var testComponent = GetTestComponent(); + serverComponent.TheVariable.CheckExceedsDirtinessThreshold = (in float value, in float newValue) => Mathf.Abs(newValue - value) >= 0.1; + serverComponent.TheVariable.SetUpdateTraits(new NetworkVariableUpdateTraits { MaxSecondsBetweenUpdates = 2 }); + serverComponent.TheVariable.LastUpdateSent = m_ServerNetworkManager.NetworkTimeSystem.LocalTime; + + serverComponent.TheVariable.Value = 0.05f; + + TimeTravel(1 / 60f * 119, 119); + + Assert.AreEqual(0.05f, serverComponent.TheVariable.Value); ; + Assert.AreEqual(0, testComponent.TheVariable.Value); ; + + TimeTravel(1 / 60f * 4, 4); + + Assert.AreEqual(0.05f, serverComponent.TheVariable.Value); ; + Assert.AreEqual(0.05f, testComponent.TheVariable.Value); ; + } + + [Test] + public void WhenNewValueIsGreaterThanThresholdButMinTimeHasNotPassed_VariableIsNotSerialized() + { + var serverComponent = GetServerComponent(); + var testComponent = GetTestComponent(); + serverComponent.TheVariable.CheckExceedsDirtinessThreshold = (in float value, in float newValue) => Mathf.Abs(newValue - value) >= 0.1; + serverComponent.TheVariable.SetUpdateTraits(new NetworkVariableUpdateTraits { MinSecondsBetweenUpdates = 2 }); + serverComponent.TheVariable.LastUpdateSent = m_ServerNetworkManager.NetworkTimeSystem.LocalTime; + + serverComponent.TheVariable.Value = 0.15f; + + TimeTravel(1 / 60f * 119, 119); + + Assert.AreEqual(0.15f, serverComponent.TheVariable.Value); ; + Assert.AreEqual(0, testComponent.TheVariable.Value); ; + + TimeTravel(1 / 60f * 4, 4); + + Assert.AreEqual(0.15f, serverComponent.TheVariable.Value); ; + Assert.AreEqual(0.15f, testComponent.TheVariable.Value); ; + } + + [Test] + public void WhenNoThresholdIsSetButMinTimeHasNotPassed_VariableIsNotSerialized() + { + var serverComponent = GetServerComponent(); + var testComponent = GetTestComponent(); + serverComponent.TheVariable.SetUpdateTraits(new NetworkVariableUpdateTraits { MinSecondsBetweenUpdates = 2 }); + serverComponent.TheVariable.LastUpdateSent = m_ServerNetworkManager.NetworkTimeSystem.LocalTime; + + serverComponent.TheVariable.Value = 0.15f; + + TimeTravel(1 / 60f * 119, 119); + + Assert.AreEqual(0.15f, serverComponent.TheVariable.Value); ; + Assert.AreEqual(0, testComponent.TheVariable.Value); ; + + TimeTravel(1 / 60f * 4, 4); + + Assert.AreEqual(0.15f, serverComponent.TheVariable.Value); ; + Assert.AreEqual(0.15f, testComponent.TheVariable.Value); ; + } + } +} diff --git a/Tests/Runtime/NetworkVariableTraitsTests.cs.meta b/Tests/Runtime/NetworkVariableTraitsTests.cs.meta new file mode 100644 index 0000000..3bfb25d --- /dev/null +++ b/Tests/Runtime/NetworkVariableTraitsTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 49f46ca2b4327464498a7465891647bb \ No newline at end of file diff --git a/Tests/Runtime/NetworkVariableUserSerializableTypesTests.cs b/Tests/Runtime/NetworkVariableUserSerializableTypesTests.cs index 3c61d92..c261bdf 100644 --- a/Tests/Runtime/NetworkVariableUserSerializableTypesTests.cs +++ b/Tests/Runtime/NetworkVariableUserSerializableTypesTests.cs @@ -112,6 +112,16 @@ public NetworkVariableUserSerializableTypesTests() protected override IEnumerator OnSetup() { WorkingUserNetworkVariableComponentBase.Reset(); + + UserNetworkVariableSerialization.WriteValue = null; + UserNetworkVariableSerialization.ReadValue = null; + UserNetworkVariableSerialization.DuplicateValue = null; + UserNetworkVariableSerialization.WriteValue = null; + UserNetworkVariableSerialization.ReadValue = null; + UserNetworkVariableSerialization.DuplicateValue = null; + UserNetworkVariableSerialization.WriteValue = null; + UserNetworkVariableSerialization.ReadValue = null; + UserNetworkVariableSerialization.DuplicateValue = null; return base.OnSetup(); } @@ -217,5 +227,37 @@ public void WhenUsingAUserSerializableNetworkVariableWithoutUserSerialization_Re } ); } + + protected override IEnumerator OnTearDown() + { + // These have to get set to SOMETHING, otherwise we will get an exception thrown because Object.Destroy() + // calls __initializeNetworkVariables, and the network variable initialization attempts to call FallbackSerializer, + // which throws an exception if any of these values are null. They don't have to DO anything, they just have to + // be non-null to keep the test from failing during teardown. + // None of this is related to what's being tested above, and in reality, these values being null is an invalid + // use case. But one of the tests is explicitly testing that invalid use case, and the values are being set + // to null in OnSetup to ensure test isolation. This wouldn't be a situation a user would have to think about + // in a real world use case. + UserNetworkVariableSerialization.WriteValue = (FastBufferWriter writer, in MyTypeOne value) => { }; + UserNetworkVariableSerialization.ReadValue = (FastBufferReader reader, out MyTypeOne value) => { value = new MyTypeOne(); }; + UserNetworkVariableSerialization.DuplicateValue = (in MyTypeOne value, ref MyTypeOne duplicatedValue) => + { + duplicatedValue = value; + }; + UserNetworkVariableSerialization.WriteValue = (FastBufferWriter writer, in MyTypeTwo value) => { }; + UserNetworkVariableSerialization.ReadValue = (FastBufferReader reader, out MyTypeTwo value) => { value = new MyTypeTwo(); }; + UserNetworkVariableSerialization.DuplicateValue = (in MyTypeTwo value, ref MyTypeTwo duplicatedValue) => + { + duplicatedValue = value; + }; + UserNetworkVariableSerialization.WriteValue = (FastBufferWriter writer, in MyTypeThree value) => { }; + UserNetworkVariableSerialization.ReadValue = (FastBufferReader reader, out MyTypeThree value) => { value = new MyTypeThree(); }; + UserNetworkVariableSerialization.DuplicateValue = (in MyTypeThree value, ref MyTypeThree duplicatedValue) => + { + duplicatedValue = value; + }; + return base.OnTearDown(); + } } } + diff --git a/Tests/Runtime/Serialization/NetworkBehaviourReferenceTests.cs b/Tests/Runtime/Serialization/NetworkBehaviourReferenceTests.cs index c3f63b9..6b7d497 100644 --- a/Tests/Runtime/Serialization/NetworkBehaviourReferenceTests.cs +++ b/Tests/Runtime/Serialization/NetworkBehaviourReferenceTests.cs @@ -17,6 +17,8 @@ internal class NetworkBehaviourReferenceTests : IDisposable { private class TestNetworkBehaviour : NetworkBehaviour { + public static bool ReceivedRPC; + public NetworkVariable TestVariable = new NetworkVariable(); public TestNetworkBehaviour RpcReceivedBehaviour; @@ -25,6 +27,7 @@ private class TestNetworkBehaviour : NetworkBehaviour public void SendReferenceServerRpc(NetworkBehaviourReference value) { RpcReceivedBehaviour = (TestNetworkBehaviour)value; + ReceivedRPC = true; } } @@ -57,8 +60,43 @@ public IEnumerator TestRpc() Assert.AreEqual(testNetworkBehaviour, testNetworkBehaviour.RpcReceivedBehaviour); } + [UnityTest] + public IEnumerator TestSerializeNull([Values] bool initializeWithNull) + { + TestNetworkBehaviour.ReceivedRPC = false; + using var networkObjectContext = UnityObjectContext.CreateNetworkObject(); + var testNetworkBehaviour = networkObjectContext.Object.gameObject.AddComponent(); + networkObjectContext.Object.Spawn(); + using var otherObjectContext = UnityObjectContext.CreateNetworkObject(); + otherObjectContext.Object.Spawn(); + // If not initializing with null, then use the default constructor with no assigned NetworkBehaviour + if (!initializeWithNull) + { + testNetworkBehaviour.SendReferenceServerRpc(new NetworkBehaviourReference()); + } + else // Otherwise, initialize and pass in null as the reference + { + testNetworkBehaviour.SendReferenceServerRpc(new NetworkBehaviourReference(null)); + } + + // wait for rpc completion + float t = 0; + while (!TestNetworkBehaviour.ReceivedRPC) + { + t += Time.deltaTime; + if (t > 5f) + { + new AssertionException("RPC with NetworkBehaviour reference hasn't been received"); + } + + yield return null; + } + + // validate + Assert.AreEqual(null, testNetworkBehaviour.RpcReceivedBehaviour); + } [UnityTest] public IEnumerator TestRpcImplicitNetworkBehaviour() @@ -131,15 +169,6 @@ public void FailSerializeGameObjectWithoutNetworkObject() }); } - [Test] - public void FailSerializeNullBehaviour() - { - Assert.Throws(() => - { - NetworkBehaviourReference outReference = null; - }); - } - public void Dispose() { //Stop, shutdown, and destroy diff --git a/Tests/Runtime/Serialization/NetworkObjectReferenceTests.cs b/Tests/Runtime/Serialization/NetworkObjectReferenceTests.cs index 084e4d5..ab347f4 100644 --- a/Tests/Runtime/Serialization/NetworkObjectReferenceTests.cs +++ b/Tests/Runtime/Serialization/NetworkObjectReferenceTests.cs @@ -19,6 +19,8 @@ internal class NetworkObjectReferenceTests : IDisposable { private class TestNetworkBehaviour : NetworkBehaviour { + public static bool ReceivedRPC; + public NetworkVariable TestVariable = new NetworkVariable(); public NetworkObject RpcReceivedNetworkObject; @@ -28,6 +30,7 @@ private class TestNetworkBehaviour : NetworkBehaviour [ServerRpc] public void SendReferenceServerRpc(NetworkObjectReference value) { + ReceivedRPC = true; RpcReceivedGameObject = value; RpcReceivedNetworkObject = value; } @@ -150,6 +153,60 @@ public void TestTryGet() Assert.AreEqual(networkObject, result); } + public enum NetworkObjectConstructorTypes + { + None, + NullNetworkObject, + NullGameObject + } + + [UnityTest] + public IEnumerator TestSerializeNull([Values] NetworkObjectConstructorTypes networkObjectConstructorTypes) + { + TestNetworkBehaviour.ReceivedRPC = false; + using var networkObjectContext = UnityObjectContext.CreateNetworkObject(); + var testNetworkBehaviour = networkObjectContext.Object.gameObject.AddComponent(); + networkObjectContext.Object.Spawn(); + + switch (networkObjectConstructorTypes) + { + case NetworkObjectConstructorTypes.None: + { + testNetworkBehaviour.SendReferenceServerRpc(new NetworkObjectReference()); + break; + } + case NetworkObjectConstructorTypes.NullNetworkObject: + { + testNetworkBehaviour.SendReferenceServerRpc(new NetworkObjectReference((NetworkObject)null)); + break; + } + case NetworkObjectConstructorTypes.NullGameObject: + { + testNetworkBehaviour.SendReferenceServerRpc(new NetworkObjectReference((GameObject)null)); + break; + } + } + + + // wait for rpc completion + float t = 0; + while (!TestNetworkBehaviour.ReceivedRPC) + { + + t += Time.deltaTime; + if (t > 5f) + { + new AssertionException("RPC with NetworkBehaviour reference hasn't been received"); + } + + yield return null; + } + + // validate + Assert.AreEqual(null, testNetworkBehaviour.RpcReceivedNetworkObject); + Assert.AreEqual(null, testNetworkBehaviour.RpcReceivedGameObject); + } + [UnityTest] public IEnumerator TestRpc() { @@ -305,24 +362,6 @@ public void FailSerializeGameObjectWithoutNetworkObject() }); } - [Test] - public void FailSerializeNullNetworkObject() - { - Assert.Throws(() => - { - NetworkObjectReference outReference = (NetworkObject)null; - }); - } - - [Test] - public void FailSerializeNullGameObject() - { - Assert.Throws(() => - { - NetworkObjectReference outReference = (GameObject)null; - }); - } - public void Dispose() { //Stop, shutdown, and destroy diff --git a/package.json b/package.json index 74a942e..59b31c6 100644 --- a/package.json +++ b/package.json @@ -2,23 +2,23 @@ "name": "com.unity.netcode.gameobjects", "displayName": "Netcode for GameObjects", "description": "Netcode for GameObjects is a high-level netcode SDK that provides networking capabilities to GameObject/MonoBehaviour workflows within Unity and sits on top of underlying transport layer.", - "version": "2.0.0-pre.1", + "version": "2.0.0-pre.2", "unity": "6000.0", "dependencies": { "com.unity.nuget.mono-cecil": "1.11.4", "com.unity.transport": "2.2.1" }, "_upm": { - "changelog": "### Added\n\n- Added event `NetworkManager.OnSessionOwnerPromoted` that is invoked when a new session owner promotion occurs. (#2948)\n- Added `NetworkRigidBodyBase.GetLinearVelocity` and `NetworkRigidBodyBase.SetLinearVelocity` convenience/helper methods. (#2948)\n- Added `NetworkRigidBodyBase.GetAngularVelocity` and `NetworkRigidBodyBase.SetAngularVelocity` convenience/helper methods. (#2948)\n\n### Fixed\n\n- Fixed issue when `NetworkTransform` half float precision is enabled and ownership changes the current base position was not being synchronized. (#2948)\n- Fixed issue where `OnClientConnected` not being invoked on the session owner when connecting to a new distributed authority session. (#2948)\n- Fixed issue where Rigidbody micro-motion (i.e. relatively small velocities) would result in non-authority instances slightly stuttering as the body would come to a rest (i.e. no motion). Now, the threshold value can increase at higher velocities and can decrease slightly below the provided threshold to account for this. (#2948)\n\n### Changed\n\n- Changed the client's owned objects is now returned (`NetworkClient` and `NetworkSpawnManager`) as an array as opposed to a list for performance purposes. (#2948)\n- Changed `NetworkTransfrom.TryCommitTransformToServer` to be internal as it will be removed by the final 2.0.0 release. (#2948)\n- Changed `NetworkTransformEditor.OnEnable` to a virtual method to be able to customize a `NetworkTransform` derived class by creating a derived editor control from `NetworkTransformEditor`. (#2948)" + "changelog": "### Added\n\n- Added `AnticipatedNetworkVariable`, which adds support for client anticipation of `NetworkVariable` values, allowing for more responsive gameplay. (#2957)\n- Added `AnticipatedNetworkTransform`, which adds support for client anticipation of NetworkTransforms. (#2957)\n- Added `NetworkVariableBase.ExceedsDirtinessThreshold` to allow network variables to throttle updates by only sending updates when the difference between the current and previous values exceeds a threshold. (This is exposed in `NetworkVariable` with the callback `NetworkVariable.CheckExceedsDirtinessThreshold`). (#2957)\n- Added `NetworkVariableUpdateTraits`, which add additional throttling support: `MinSecondsBetweenUpdates` will prevent the `NetworkVariable` from sending updates more often than the specified time period (even if it exceeds the dirtiness threshold), while `MaxSecondsBetweenUpdates` will force a dirty `NetworkVariable` to send an update after the specified time period even if it has not yet exceeded the dirtiness threshold. (#2957)\n- Added virtual method `NetworkVariableBase.OnInitialize` which can be used by `NetworkVariable` subclasses to add initialization code. (#2957)\n- Added `NetworkTime.TickWithPartial`, which represents the current tick as a double that includes the fractional/partial tick value. (#2957)\n- Added `NetworkTickSystem.AnticipationTick`, which can be helpful with implementation of client anticipation. This value represents the tick the current local client was at at the beginning of the most recent network round trip, which enables it to correlate server update ticks with the client tick that may have triggered them. (#2957)\n- Added event `NetworkManager.OnSessionOwnerPromoted` that is invoked when a new session owner promotion occurs. (#2948)\n- Added `NetworkRigidBodyBase.GetLinearVelocity` and `NetworkRigidBodyBase.SetLinearVelocity` convenience/helper methods. (#2948)\n- Added `NetworkRigidBodyBase.GetAngularVelocity` and `NetworkRigidBodyBase.SetAngularVelocity` convenience/helper methods. (#2948)\n\n### Fixed\n\n- Fixed issue when `NetworkTransform` half float precision is enabled and ownership changes the current base position was not being synchronized. (#2948)\n- Fixed issue where `OnClientConnected` not being invoked on the session owner when connecting to a new distributed authority session. (#2948)\n- Fixed issue where Rigidbody micro-motion (i.e. relatively small velocities) would result in non-authority instances slightly stuttering as the body would come to a rest (i.e. no motion). Now, the threshold value can increase at higher velocities and can decrease slightly below the provided threshold to account for this. (#2948)\n\n### Changed\n\n- Changed `NetworkAnimator` no longer requires the `Animator` component to exist on the same `GameObject`. (#2957)\n- Changed `NetworkObjectReference` and `NetworkBehaviourReference` to allow null references when constructing and serializing. (#2957)\n- Changed the client's owned objects is now returned (`NetworkClient` and `NetworkSpawnManager`) as an array as opposed to a list for performance purposes. (#2948)\n- Changed `NetworkTransfrom.TryCommitTransformToServer` to be internal as it will be removed by the final 2.0.0 release. (#2948)\n- Changed `NetworkTransformEditor.OnEnable` to a virtual method to be able to customize a `NetworkTransform` derived class by creating a derived editor control from `NetworkTransformEditor`. (#2948)" }, "upmCi": { - "footprint": "18101c69b1634ca6a71617efbaf53473b389e8ec" + "footprint": "dffe7543c19c2670755cc7da27e1d4522c9414a9" }, "documentationUrl": "https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@2.0/manual/index.html", "repository": { "url": "https://github.com/Unity-Technologies/com.unity.netcode.gameobjects.git", "type": "git", - "revision": "ba4102f8ded1ed3f18c5b0604bd39a846437e9b6" + "revision": "2ecbd14351cac29ab3a18cc159c0a82513e9d241" }, "samples": [ {