Compare commits
2 Commits
2.0.0-exp.
...
2.0.0-pre.
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c813386c5c | ||
|
|
ed38a4dcc2 |
37
CHANGELOG.md
37
CHANGELOG.md
@@ -6,12 +6,49 @@ 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.2] - 2024-06-17
|
||||
|
||||
### Added
|
||||
|
||||
- Added `AnticipatedNetworkVariable<T>`, 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<T>` with the callback `NetworkVariable<T>.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)
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed issue when `NetworkTransform` half float precision is enabled and ownership changes the current base position was not being synchronized. (#2948)
|
||||
- Fixed issue where `OnClientConnected` not being invoked on the session owner when connecting to a new distributed authority session. (#2948)
|
||||
- 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)
|
||||
|
||||
### 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)
|
||||
|
||||
|
||||
## [2.0.0-exp.5] - 2024-06-03
|
||||
|
||||
### Added
|
||||
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed issue where SessionOwner message was being treated as a new entry for the new message indexing when it should have been ordinally sorted with the legacy message indices. (#2942)
|
||||
|
||||
### Changed
|
||||
- Changed `FastBufferReader` and `FastBufferWriter` so that they always ensure the length of items serialized is always serialized as an `uint` and added a check before casting for safe reading and writing.(#2946)
|
||||
|
||||
|
||||
## [2.0.0-exp.4] - 2024-05-31
|
||||
|
||||
### Added
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8b267eb841a574dc083ac248a95d4443
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -409,6 +409,7 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
}
|
||||
else
|
||||
{
|
||||
m_Diagnostics.AddError($"{type}: Managed type in NetworkVariable must implement IEquatable<{type}>");
|
||||
equalityMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef);
|
||||
}
|
||||
|
||||
@@ -721,7 +722,7 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
continue;
|
||||
}
|
||||
|
||||
if (networkVariableSerializationTypesTypeDef == null && netcodeTypeDef.Name == nameof(NetworkVariableSerializationTypes))
|
||||
if (networkVariableSerializationTypesTypeDef == null && netcodeTypeDef.Name == nameof(NetworkVariableSerializationTypedInitializers))
|
||||
{
|
||||
networkVariableSerializationTypesTypeDef = netcodeTypeDef;
|
||||
continue;
|
||||
@@ -1007,103 +1008,103 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
|
||||
switch (method.Name)
|
||||
{
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedByMemcpy):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpy_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpyArray):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedByMemcpyArray):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpyArray_MethodRef = method;
|
||||
break;
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpyList):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedByMemcpyList):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpyList_MethodRef = method;
|
||||
break;
|
||||
#endif
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedINetworkSerializable):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedINetworkSerializable):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializable_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedINetworkSerializableArray):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedINetworkSerializableArray):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializableArray_MethodRef = method;
|
||||
break;
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedINetworkSerializableList):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedINetworkSerializableList):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializableList_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_NativeHashSet):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_NativeHashSet):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashSet_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_NativeHashMap):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_NativeHashMap):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashMap_MethodRef = method;
|
||||
break;
|
||||
#endif
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_List):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_List):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_List_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_HashSet):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_HashSet):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_HashSet_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_Dictionary):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_Dictionary):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_Dictionary_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_ManagedINetworkSerializable):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_ManagedINetworkSerializable):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_ManagedINetworkSerializable_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_FixedString):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_FixedString):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_FixedString_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_FixedStringArray):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_FixedStringArray):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_FixedStringArray_MethodRef = method;
|
||||
break;
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_FixedStringList):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_FixedStringList):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_FixedStringList_MethodRef = method;
|
||||
break;
|
||||
#endif
|
||||
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_ManagedIEquatable):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_ManagedIEquatable):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedIEquatable_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedIEquatable):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatable_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatableArray):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedIEquatableArray):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatableArray_MethodRef = method;
|
||||
break;
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatableList):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedIEquatableList):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatableList_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_NativeHashSet):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_NativeHashSet):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashSet_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_NativeHashMap):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_NativeHashMap):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashMap_MethodRef = method;
|
||||
break;
|
||||
#endif
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_List):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_List):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_List_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_HashSet):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_HashSet):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_HashSet_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_Dictionary):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_Dictionary):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_Dictionary_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEquals):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedValueEquals):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEquals_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEqualsArray):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedValueEqualsArray):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEqualsArray_MethodRef = method;
|
||||
break;
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEqualsList):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedValueEqualsList):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEqualsList_MethodRef = method;
|
||||
break;
|
||||
#endif
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_ManagedClassEquals):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_ManagedClassEquals):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef = method;
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ namespace Unity.Netcode.Editor
|
||||
private SerializedProperty m_ProtocolVersionProperty;
|
||||
private SerializedProperty m_NetworkTransportProperty;
|
||||
private SerializedProperty m_TickRateProperty;
|
||||
#if MULTIPLAYER_SDK_INSTALLED
|
||||
#if MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
private SerializedProperty m_NetworkTopologyProperty;
|
||||
#endif
|
||||
private SerializedProperty m_ClientConnectionBufferTimeoutProperty;
|
||||
@@ -102,7 +102,7 @@ namespace Unity.Netcode.Editor
|
||||
m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion");
|
||||
m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport");
|
||||
m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate");
|
||||
#if MULTIPLAYER_SDK_INSTALLED
|
||||
#if MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
m_NetworkTopologyProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTopology");
|
||||
#endif
|
||||
m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout");
|
||||
@@ -142,7 +142,7 @@ namespace Unity.Netcode.Editor
|
||||
m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion");
|
||||
m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport");
|
||||
m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate");
|
||||
#if MULTIPLAYER_SDK_INSTALLED
|
||||
#if MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
m_NetworkTopologyProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTopology");
|
||||
#endif
|
||||
m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout");
|
||||
@@ -186,7 +186,7 @@ namespace Unity.Netcode.Editor
|
||||
|
||||
EditorGUILayout.Space();
|
||||
EditorGUILayout.LabelField("Network Settings", EditorStyles.boldLabel);
|
||||
#if MULTIPLAYER_SDK_INSTALLED
|
||||
#if MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
EditorGUILayout.PropertyField(m_NetworkTopologyProperty);
|
||||
#endif
|
||||
EditorGUILayout.PropertyField(m_ProtocolVersionProperty);
|
||||
@@ -310,20 +310,31 @@ namespace Unity.Netcode.Editor
|
||||
GUI.enabled = false;
|
||||
}
|
||||
|
||||
if (GUILayout.Button(new GUIContent("Start Host", "Starts a host instance" + buttonDisabledReasonSuffix)))
|
||||
if (m_NetworkManager.NetworkConfig.NetworkTopology == NetworkTopologyTypes.ClientServer)
|
||||
{
|
||||
m_NetworkManager.StartHost();
|
||||
if (GUILayout.Button(new GUIContent("Start Host", "Starts a host instance" + buttonDisabledReasonSuffix)))
|
||||
{
|
||||
m_NetworkManager.StartHost();
|
||||
}
|
||||
|
||||
if (GUILayout.Button(new GUIContent("Start Server", "Starts a server instance" + buttonDisabledReasonSuffix)))
|
||||
{
|
||||
m_NetworkManager.StartServer();
|
||||
}
|
||||
|
||||
if (GUILayout.Button(new GUIContent("Start Client", "Starts a client instance" + buttonDisabledReasonSuffix)))
|
||||
{
|
||||
m_NetworkManager.StartClient();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (GUILayout.Button(new GUIContent("Start Client", "Starts a distributed authority client instance" + buttonDisabledReasonSuffix)))
|
||||
{
|
||||
m_NetworkManager.StartClient();
|
||||
}
|
||||
}
|
||||
|
||||
if (GUILayout.Button(new GUIContent("Start Server", "Starts a server instance" + buttonDisabledReasonSuffix)))
|
||||
{
|
||||
m_NetworkManager.StartServer();
|
||||
}
|
||||
|
||||
if (GUILayout.Button(new GUIContent("Start Client", "Starts a client instance" + buttonDisabledReasonSuffix)))
|
||||
{
|
||||
m_NetworkManager.StartClient();
|
||||
}
|
||||
|
||||
if (!EditorApplication.isPlaying)
|
||||
{
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
using System.Collections.Generic;
|
||||
#if MULTIPLAYER_SDK_INSTALLED
|
||||
#if BYPASS_DEFAULT_ENUM_DRAWER && MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
using System.Linq;
|
||||
#endif
|
||||
using UnityEditor;
|
||||
@@ -148,7 +148,7 @@ namespace Unity.Netcode.Editor
|
||||
|
||||
// Keeping this here just in case, but it appears that in Unity 6 the visual bugs with
|
||||
// enum flags is resolved
|
||||
#if BYPASS_DEFAULT_ENUM_DRAWER && MULTIPLAYER_SDK_INSTALLED
|
||||
#if BYPASS_DEFAULT_ENUM_DRAWER && MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
[CustomPropertyDrawer(typeof(NetworkObject.OwnershipStatus))]
|
||||
public class NetworkObjectOwnership : PropertyDrawer
|
||||
{
|
||||
|
||||
@@ -30,6 +30,7 @@ namespace Unity.Netcode.Editor
|
||||
private SerializedProperty m_UseQuaternionCompression;
|
||||
private SerializedProperty m_UseHalfFloatPrecision;
|
||||
private SerializedProperty m_SlerpPosition;
|
||||
private SerializedProperty m_AuthorityMode;
|
||||
|
||||
private static int s_ToggleOffset = 45;
|
||||
private static float s_MaxRowWidth = EditorGUIUtility.labelWidth + EditorGUIUtility.fieldWidth + 5;
|
||||
@@ -38,7 +39,7 @@ namespace Unity.Netcode.Editor
|
||||
private static GUIContent s_ScaleLabel = EditorGUIUtility.TrTextContent("Scale");
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void OnEnable()
|
||||
public virtual void OnEnable()
|
||||
{
|
||||
m_UseUnreliableDeltas = serializedObject.FindProperty(nameof(NetworkTransform.UseUnreliableDeltas));
|
||||
m_SyncPositionXProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionX));
|
||||
@@ -59,12 +60,14 @@ namespace Unity.Netcode.Editor
|
||||
m_UseQuaternionCompression = serializedObject.FindProperty(nameof(NetworkTransform.UseQuaternionCompression));
|
||||
m_UseHalfFloatPrecision = serializedObject.FindProperty(nameof(NetworkTransform.UseHalfFloatPrecision));
|
||||
m_SlerpPosition = serializedObject.FindProperty(nameof(NetworkTransform.SlerpPosition));
|
||||
m_AuthorityMode = serializedObject.FindProperty(nameof(NetworkTransform.AuthorityMode));
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void OnInspectorGUI()
|
||||
{
|
||||
EditorGUILayout.LabelField("Syncing", EditorStyles.boldLabel);
|
||||
var networkTransform = target as NetworkTransform;
|
||||
EditorGUILayout.LabelField("Axis to Synchronize", EditorStyles.boldLabel);
|
||||
{
|
||||
GUILayout.BeginHorizontal();
|
||||
|
||||
@@ -126,6 +129,11 @@ namespace Unity.Netcode.Editor
|
||||
GUILayout.EndHorizontal();
|
||||
}
|
||||
|
||||
EditorGUILayout.Space();
|
||||
EditorGUILayout.LabelField("Authority", EditorStyles.boldLabel);
|
||||
{
|
||||
EditorGUILayout.PropertyField(m_AuthorityMode);
|
||||
}
|
||||
EditorGUILayout.Space();
|
||||
EditorGUILayout.LabelField("Thresholds", EditorStyles.boldLabel);
|
||||
EditorGUILayout.PropertyField(m_PositionThresholdProperty);
|
||||
@@ -137,7 +145,10 @@ namespace Unity.Netcode.Editor
|
||||
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)
|
||||
|
||||
@@ -57,7 +57,7 @@
|
||||
{
|
||||
"name": "com.unity.services.multiplayer",
|
||||
"expression": "0.2.0",
|
||||
"define": "MULTIPLAYER_SDK_INSTALLED"
|
||||
"define": "MULTIPLAYER_SERVICES_SDK_INSTALLED"
|
||||
}
|
||||
],
|
||||
"noEngineReferences": false
|
||||
|
||||
497
Runtime/Components/AnticipatedNetworkTransform.cs
Normal file
497
Runtime/Components/AnticipatedNetworkTransform.cs
Normal file
@@ -0,0 +1,497 @@
|
||||
using Unity.Mathematics;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Unity.Netcode.Components
|
||||
{
|
||||
|
||||
#pragma warning disable IDE0001
|
||||
/// <summary>
|
||||
/// A subclass of <see cref="NetworkTransform"/> 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:
|
||||
///
|
||||
/// <list type="bullet">
|
||||
///
|
||||
/// <item><b>Snap:</b> In this mode (with <see cref="StaleDataHandling"/> set to
|
||||
/// <see cref="StaleDataHandling.Ignore"/> and no <see cref="NetworkBehaviour.OnReanticipate"/> 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.</item>
|
||||
///
|
||||
/// <item><b>Smooth:</b> In this mode (with <see cref="StaleDataHandling"/> set to
|
||||
/// <see cref="Netcode.StaleDataHandling.Ignore"/> and an <see cref="NetworkBehaviour.OnReanticipate"/> callback that calls
|
||||
/// <see cref="Smooth"/> from the anticipated value to the authority value with an appropriate
|
||||
/// <see cref="Mathf.Lerp"/>-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.</item>
|
||||
///
|
||||
/// <item><b>Constant Reanticipation:</b> In this mode (with <see cref="StaleDataHandling"/> set to
|
||||
/// <see cref="Netcode.StaleDataHandling.Reanticipate"/> and an <see cref="NetworkBehaviour.OnReanticipate"/> 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 <see cref="Smooth"/> 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.</item>
|
||||
///
|
||||
/// </list>
|
||||
///
|
||||
/// Note that these three modes may be combined. For example, if an <see cref="NetworkBehaviour.OnReanticipate"/> callback
|
||||
/// does not call either <see cref="Smooth"/> or one of the Anticipate methods, the result will be a snap to the
|
||||
/// authoritative value, enabling for a callback that may conditionally call <see cref="Smooth"/> 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.
|
||||
/// </summary>
|
||||
#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
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// <br/><br/>
|
||||
/// If this is <see cref="Netcode.StaleDataHandling.Ignore"/>, the stale data will be ignored and the authoritative
|
||||
/// value will not replace the anticipated value until the anticipation time is reached. <see cref="OnAuthoritativeValueChanged"/>
|
||||
/// and <see cref="OnReanticipate"/> will also not be invoked for this stale data.
|
||||
/// <br/><br/>
|
||||
/// If this is <see cref="Netcode.StaleDataHandling.Reanticipate"/>, the stale data will replace the anticipated data and
|
||||
/// <see cref="OnAuthoritativeValueChanged"/> and <see cref="OnReanticipate"/> will be invoked.
|
||||
/// In this case, the authoritativeTime value passed to <see cref="OnReanticipate"/> will be lower than
|
||||
/// the anticipationTime value, and that callback can be used to calculate a new anticipated value.
|
||||
/// </summary>
|
||||
#pragma warning restore IDE0001
|
||||
public StaleDataHandling StaleDataHandling = StaleDataHandling.Reanticipate;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public TransformState AuthoritativeState => m_AuthoritativeTransform;
|
||||
|
||||
/// <summary>
|
||||
/// Contains the current anticipated state, which will match the values of this object's
|
||||
/// actual <see cref="MonoBehaviour.transform"/>. 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 <see cref="PreviousAnticipatedState"/>, which
|
||||
/// will NOT be overwritten in server updates.
|
||||
/// </summary>
|
||||
public TransformState AnticipatedState => m_AnticipatedTransform;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="PreviousAnticipatedState"/>
|
||||
/// </summary>
|
||||
public bool ShouldReanticipate
|
||||
{
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Holds the most recent anticipated state, whatever was
|
||||
/// most recently set using the Anticipate methods. Unlike
|
||||
/// <see cref="AnticipatedState"/>, this does not get overwritten
|
||||
/// when a server update arrives.
|
||||
/// </summary>
|
||||
public TransformState PreviousAnticipatedState => m_PreviousAnticipatedTransform;
|
||||
|
||||
/// <summary>
|
||||
/// Anticipate that, at the end of one round trip to the server, this transform will be in the given
|
||||
/// <see cref="newPosition"/>
|
||||
/// </summary>
|
||||
/// <param name="newPosition"></param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Anticipate that, at the end of one round trip to the server, this transform will have the given
|
||||
/// <see cref="newRotation"/>
|
||||
/// </summary>
|
||||
/// <param name="newRotation"></param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Anticipate that, at the end of one round trip to the server, this transform will have the given
|
||||
/// <see cref="newScale"/>
|
||||
/// </summary>
|
||||
/// <param name="newScale"></param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Anticipate that, at the end of one round trip to the server, the transform will have the given
|
||||
/// <see cref="newState"/>
|
||||
/// </summary>
|
||||
/// <param name="newState"></param>
|
||||
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<T>(ref BufferSerializer<T> 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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Interpolate between the transform represented by <see cref="from"/> to the transform represented by
|
||||
/// <see cref="to"/> over <see cref="durationSeconds"/> of real time. The duration uses
|
||||
/// <see cref="Time.deltaTime"/>, so it is affected by <see cref="Time.timeScale"/>.
|
||||
/// </summary>
|
||||
/// <param name="from"></param>
|
||||
/// <param name="to"></param>
|
||||
/// <param name="durationSeconds"></param>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Runtime/Components/AnticipatedNetworkTransform.cs.meta
Normal file
2
Runtime/Components/AnticipatedNetworkTransform.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5abfce83aadd948498d4990c645a017b
|
||||
@@ -1,8 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a9db1d18fa0117f4da5e8e65386b894a
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -186,7 +186,6 @@ namespace Unity.Netcode.Components
|
||||
/// NetworkAnimator enables remote synchronization of <see cref="UnityEngine.Animator"/> state for on network objects.
|
||||
/// </summary>
|
||||
[AddComponentMenu("Netcode/Network Animator")]
|
||||
[RequireComponent(typeof(Animator))]
|
||||
public class NetworkAnimator : NetworkBehaviour, ISerializationCallbackReceiver
|
||||
{
|
||||
[Serializable]
|
||||
|
||||
@@ -45,6 +45,9 @@ namespace Unity.Netcode.Components
|
||||
private Rigidbody m_Rigidbody;
|
||||
private Rigidbody2D m_Rigidbody2D;
|
||||
internal NetworkTransform NetworkTransform;
|
||||
private float m_TickFrequency;
|
||||
private float m_TickRate;
|
||||
|
||||
private enum InterpolationTypes
|
||||
{
|
||||
None,
|
||||
@@ -120,6 +123,129 @@ namespace Unity.Netcode.Components
|
||||
}
|
||||
}
|
||||
|
||||
internal Vector3 GetAdjustedPositionThreshold()
|
||||
{
|
||||
// Since the threshold is a measurement of unity world space units per tick, we will allow for the maximum threshold
|
||||
// to be no greater than the threshold measured in unity world space units per second
|
||||
var thresholdMax = NetworkTransform.PositionThreshold * m_TickRate;
|
||||
// Get the velocity in unity world space units per tick
|
||||
var perTickVelocity = GetLinearVelocity() * m_TickFrequency;
|
||||
// Since a rigid body can have "micro-motion" when allowed to come to rest (based on friction etc), we will allow for
|
||||
// no less than 1/10th the threshold value.
|
||||
var minThreshold = NetworkTransform.PositionThreshold * 0.1f;
|
||||
|
||||
// Finally, we adjust the threshold based on the body's current velocity
|
||||
perTickVelocity.x = Mathf.Clamp(Mathf.Abs(perTickVelocity.x), minThreshold, thresholdMax);
|
||||
perTickVelocity.y = Mathf.Clamp(Mathf.Abs(perTickVelocity.y), minThreshold, thresholdMax);
|
||||
// 2D Rigidbody only moves on x & y axis
|
||||
if (!m_IsRigidbody2D)
|
||||
{
|
||||
perTickVelocity.z = Mathf.Clamp(Mathf.Abs(perTickVelocity.z), minThreshold, thresholdMax);
|
||||
}
|
||||
|
||||
return perTickVelocity;
|
||||
}
|
||||
|
||||
internal Vector3 GetAdjustedRotationThreshold()
|
||||
{
|
||||
// Since the rotation threshold is a measurement pf degrees per tick, we get the maximum threshold
|
||||
// by calculating the threshold in degrees per second.
|
||||
var thresholdMax = NetworkTransform.RotAngleThreshold * m_TickRate;
|
||||
// Angular velocity is expressed in radians per second where as the rotation being checked is in degrees.
|
||||
// Convert the angular velocity to degrees per second and then convert that to degrees per tick.
|
||||
var rotationPerTick = (GetAngularVelocity() * Mathf.Rad2Deg) * m_TickFrequency;
|
||||
var minThreshold = NetworkTransform.RotAngleThreshold * m_TickFrequency;
|
||||
|
||||
// 2D Rigidbody only rotates around Z axis
|
||||
if (!m_IsRigidbody2D)
|
||||
{
|
||||
rotationPerTick.x = Mathf.Clamp(Mathf.Abs(rotationPerTick.x), minThreshold, thresholdMax);
|
||||
rotationPerTick.y = Mathf.Clamp(Mathf.Abs(rotationPerTick.y), minThreshold, thresholdMax);
|
||||
}
|
||||
rotationPerTick.z = Mathf.Clamp(Mathf.Abs(rotationPerTick.z), minThreshold, thresholdMax);
|
||||
|
||||
return rotationPerTick;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the linear velocity of the Rigidbody.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// For <see cref="Rigidbody2D"/>, only the x and y components of the <see cref="Vector3"/> are applied.
|
||||
/// </remarks>
|
||||
public void SetLinearVelocity(Vector3 linearVelocity)
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
m_Rigidbody2D.velocity = linearVelocity;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_Rigidbody.linearVelocity = linearVelocity;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the linear velocity of the Rigidbody.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// For <see cref="Rigidbody2D"/>, the <see cref="Vector3"/> velocity returned is only applied to the x and y components.
|
||||
/// </remarks>
|
||||
/// <returns><see cref="Vector3"/> as the linear velocity</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public Vector3 GetLinearVelocity()
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
return m_Rigidbody2D.velocity;
|
||||
}
|
||||
else
|
||||
{
|
||||
return m_Rigidbody.linearVelocity;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the angular velocity for the Rigidbody.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// For <see cref="Rigidbody2D"/>, the z component of <param name="angularVelocity"/> is only used to set the angular velocity.
|
||||
/// A quick way to pass in a 2D angular velocity component is: <see cref="Vector3.forward"/> * angularVelocity (where angularVelocity is a float)
|
||||
/// </remarks>
|
||||
/// <param name="angularVelocity">the angular velocity to apply to the body</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void SetAngularVelocity(Vector3 angularVelocity)
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
m_Rigidbody2D.angularVelocity = angularVelocity.z;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_Rigidbody.angularVelocity = angularVelocity;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the angular velocity for the Rigidbody.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// For <see cref="Rigidbody2D"/>, the z component of the <see cref="Vector3"/> returned is the angular velocity of the object.
|
||||
/// </remarks>
|
||||
/// <returns>angular velocity as a <see cref="Vector3"/></returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public Vector3 GetAngularVelocity()
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
return Vector3.forward * m_Rigidbody2D.velocity;
|
||||
}
|
||||
else
|
||||
{
|
||||
return m_Rigidbody.angularVelocity;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the position of the Rigidbody
|
||||
/// </summary>
|
||||
@@ -210,6 +336,9 @@ namespace Unity.Netcode.Components
|
||||
}
|
||||
}
|
||||
|
||||
// Used for Rigidbody only (see info on normalized below)
|
||||
private Vector4 m_QuaternionCheck = Vector4.zero;
|
||||
|
||||
/// <summary>
|
||||
/// Rotatates the Rigidbody towards a specified rotation
|
||||
/// </summary>
|
||||
@@ -227,6 +356,17 @@ namespace Unity.Netcode.Components
|
||||
}
|
||||
else
|
||||
{
|
||||
// Evidently we need to check to make sure the quaternion is a perfect
|
||||
// magnitude of 1.0f when applying the rotation to a rigid body.
|
||||
m_QuaternionCheck.x = rotation.x;
|
||||
m_QuaternionCheck.y = rotation.y;
|
||||
m_QuaternionCheck.z = rotation.z;
|
||||
m_QuaternionCheck.w = rotation.w;
|
||||
// If the magnitude is greater than 1.0f (even by a very small fractional value), then normalize the quaternion
|
||||
if (m_QuaternionCheck.magnitude != 1.0f)
|
||||
{
|
||||
rotation.Normalize();
|
||||
}
|
||||
m_Rigidbody.MoveRotation(rotation);
|
||||
}
|
||||
}
|
||||
@@ -501,6 +641,8 @@ namespace Unity.Netcode.Components
|
||||
/// <inheritdoc />
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
m_TickFrequency = 1.0f / NetworkManager.NetworkConfig.TickRate;
|
||||
m_TickRate = NetworkManager.NetworkConfig.TickRate;
|
||||
UpdateOwnershipAuthority();
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
/// <summary>
|
||||
/// Data structure used to synchronize the <see cref="NetworkTransform"/>
|
||||
@@ -920,6 +925,22 @@ namespace Unity.Netcode.Components
|
||||
#endregion
|
||||
|
||||
#region PROPERTIES AND GENERAL METHODS
|
||||
|
||||
|
||||
public enum AuthorityModes
|
||||
{
|
||||
Server,
|
||||
Owner,
|
||||
}
|
||||
#if MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
[Tooltip("Selects who has authority (sends state updates) over the transform. When the network topology is set to distributed authority, this always defaults to owner authority. If server (the default), then only server-side adjustments to the " +
|
||||
"transform will be synchronized with clients. If owner (or client), then only the owner-side adjustments to the transform will be synchronized with both the server and other clients.")]
|
||||
#else
|
||||
[Tooltip("Selects who has authority (sends state updates) over the transform. If server (the default), then only server-side adjustments to the transform will be synchronized with clients. If owner (or client), " +
|
||||
"then only the owner-side adjustments to the transform will be synchronized with both the server and other clients.")]
|
||||
#endif
|
||||
public AuthorityModes AuthorityMode;
|
||||
|
||||
/// <summary>
|
||||
/// The default position change threshold value.
|
||||
/// Any changes above this threshold will be replicated.
|
||||
@@ -1487,7 +1508,7 @@ namespace Unity.Netcode.Components
|
||||
/// </remarks>
|
||||
/// <param name="transformToCommit">the transform to be committed</param>
|
||||
/// <param name="dirtyTime">time it was marked dirty</param>
|
||||
protected void TryCommitTransformToServer(Transform transformToCommit, double dirtyTime)
|
||||
internal void TryCommitTransformToServer(Transform transformToCommit, double dirtyTime)
|
||||
{
|
||||
if (!IsSpawned)
|
||||
{
|
||||
@@ -1568,8 +1589,6 @@ namespace Unity.Netcode.Components
|
||||
// If the transform has deltas (returns dirty) or if an explicitly set state is pending
|
||||
if (m_LocalAuthoritativeNetworkState.ExplicitSet || CheckForStateChange(ref m_LocalAuthoritativeNetworkState, ref transformToCommit, synchronize))
|
||||
{
|
||||
m_LocalAuthoritativeNetworkState.LastSerializedSize = m_OldState.LastSerializedSize;
|
||||
|
||||
// If the state was explicitly set, then update the network tick to match the locally calculate tick
|
||||
if (m_LocalAuthoritativeNetworkState.ExplicitSet)
|
||||
{
|
||||
@@ -1699,9 +1718,20 @@ namespace Unity.Netcode.Components
|
||||
#if COM_UNITY_MODULES_PHYSICS
|
||||
var position = m_UseRigidbodyForMotion ? m_NetworkRigidbodyInternal.GetPosition() : InLocalSpace ? transformToUse.localPosition : transformToUse.position;
|
||||
var rotation = m_UseRigidbodyForMotion ? m_NetworkRigidbodyInternal.GetRotation() : InLocalSpace ? transformToUse.localRotation : transformToUse.rotation;
|
||||
|
||||
var positionThreshold = Vector3.one * PositionThreshold;
|
||||
var rotationThreshold = Vector3.one * RotAngleThreshold;
|
||||
|
||||
if (m_UseRigidbodyForMotion)
|
||||
{
|
||||
positionThreshold = m_NetworkRigidbodyInternal.GetAdjustedPositionThreshold();
|
||||
rotationThreshold = m_NetworkRigidbodyInternal.GetAdjustedRotationThreshold();
|
||||
}
|
||||
#else
|
||||
var position = InLocalSpace ? transformToUse.localPosition : transformToUse.position;
|
||||
var rotation = InLocalSpace ? transformToUse.localRotation : transformToUse.rotation;
|
||||
var positionThreshold = Vector3.one * PositionThreshold;
|
||||
var rotationThreshold = Vector3.one * RotAngleThreshold;
|
||||
#endif
|
||||
var rotAngles = rotation.eulerAngles;
|
||||
var scale = transformToUse.localScale;
|
||||
@@ -1828,21 +1858,21 @@ namespace Unity.Netcode.Components
|
||||
// Begin delta checks against last sent state update
|
||||
if (!UseHalfFloatPrecision)
|
||||
{
|
||||
if (SyncPositionX && (Mathf.Abs(networkState.PositionX - position.x) >= PositionThreshold || networkState.IsTeleportingNextFrame || isAxisSync))
|
||||
if (SyncPositionX && (Mathf.Abs(networkState.PositionX - position.x) >= positionThreshold.x || networkState.IsTeleportingNextFrame || isAxisSync))
|
||||
{
|
||||
networkState.PositionX = position.x;
|
||||
networkState.HasPositionX = true;
|
||||
isPositionDirty = true;
|
||||
}
|
||||
|
||||
if (SyncPositionY && (Mathf.Abs(networkState.PositionY - position.y) >= PositionThreshold || networkState.IsTeleportingNextFrame || isAxisSync))
|
||||
if (SyncPositionY && (Mathf.Abs(networkState.PositionY - position.y) >= positionThreshold.y || networkState.IsTeleportingNextFrame || isAxisSync))
|
||||
{
|
||||
networkState.PositionY = position.y;
|
||||
networkState.HasPositionY = true;
|
||||
isPositionDirty = true;
|
||||
}
|
||||
|
||||
if (SyncPositionZ && (Mathf.Abs(networkState.PositionZ - position.z) >= PositionThreshold || networkState.IsTeleportingNextFrame || isAxisSync))
|
||||
if (SyncPositionZ && (Mathf.Abs(networkState.PositionZ - position.z) >= positionThreshold.z || networkState.IsTeleportingNextFrame || isAxisSync))
|
||||
{
|
||||
networkState.PositionZ = position.z;
|
||||
networkState.HasPositionZ = true;
|
||||
@@ -1863,7 +1893,7 @@ namespace Unity.Netcode.Components
|
||||
{
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
if (Math.Abs(position[i] - m_HalfPositionState.PreviousPosition[i]) >= PositionThreshold)
|
||||
if (Math.Abs(position[i] - m_HalfPositionState.PreviousPosition[i]) >= positionThreshold[i])
|
||||
{
|
||||
isPositionDirty = i == 0 ? SyncPositionX : i == 1 ? SyncPositionY : SyncPositionZ;
|
||||
if (!isPositionDirty)
|
||||
@@ -1958,21 +1988,21 @@ namespace Unity.Netcode.Components
|
||||
|
||||
if (!UseQuaternionSynchronization)
|
||||
{
|
||||
if (SyncRotAngleX && (Mathf.Abs(Mathf.DeltaAngle(networkState.RotAngleX, rotAngles.x)) >= RotAngleThreshold || networkState.IsTeleportingNextFrame || isAxisSync))
|
||||
if (SyncRotAngleX && (Mathf.Abs(Mathf.DeltaAngle(networkState.RotAngleX, rotAngles.x)) >= rotationThreshold.x || networkState.IsTeleportingNextFrame || isAxisSync))
|
||||
{
|
||||
networkState.RotAngleX = rotAngles.x;
|
||||
networkState.HasRotAngleX = true;
|
||||
isRotationDirty = true;
|
||||
}
|
||||
|
||||
if (SyncRotAngleY && (Mathf.Abs(Mathf.DeltaAngle(networkState.RotAngleY, rotAngles.y)) >= RotAngleThreshold || networkState.IsTeleportingNextFrame || isAxisSync))
|
||||
if (SyncRotAngleY && (Mathf.Abs(Mathf.DeltaAngle(networkState.RotAngleY, rotAngles.y)) >= rotationThreshold.y || networkState.IsTeleportingNextFrame || isAxisSync))
|
||||
{
|
||||
networkState.RotAngleY = rotAngles.y;
|
||||
networkState.HasRotAngleY = true;
|
||||
isRotationDirty = true;
|
||||
}
|
||||
|
||||
if (SyncRotAngleZ && (Mathf.Abs(Mathf.DeltaAngle(networkState.RotAngleZ, rotAngles.z)) >= RotAngleThreshold || networkState.IsTeleportingNextFrame || isAxisSync))
|
||||
if (SyncRotAngleZ && (Mathf.Abs(Mathf.DeltaAngle(networkState.RotAngleZ, rotAngles.z)) >= rotationThreshold.z || networkState.IsTeleportingNextFrame || isAxisSync))
|
||||
{
|
||||
networkState.RotAngleZ = rotAngles.z;
|
||||
networkState.HasRotAngleZ = true;
|
||||
@@ -1989,7 +2019,7 @@ namespace Unity.Netcode.Components
|
||||
var previousRotation = networkState.Rotation.eulerAngles;
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
if (Mathf.Abs(Mathf.DeltaAngle(previousRotation[i], rotAngles[i])) >= RotAngleThreshold)
|
||||
if (Mathf.Abs(Mathf.DeltaAngle(previousRotation[i], rotAngles[i])) >= rotationThreshold[i])
|
||||
{
|
||||
isRotationDirty = true;
|
||||
break;
|
||||
@@ -2159,10 +2189,15 @@ namespace Unity.Netcode.Components
|
||||
|
||||
internal bool LogMotion;
|
||||
|
||||
protected virtual void OnTransformUpdated()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the authoritative state to the transform
|
||||
/// </summary>
|
||||
private void ApplyAuthoritativeState()
|
||||
protected internal void ApplyAuthoritativeState()
|
||||
{
|
||||
#if COM_UNITY_MODULES_PHYSICS
|
||||
// TODO: Make this an authority flag
|
||||
@@ -2366,6 +2401,7 @@ namespace Unity.Netcode.Components
|
||||
}
|
||||
transform.localScale = m_CurrentScale;
|
||||
}
|
||||
OnTransformUpdated();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -2577,6 +2613,8 @@ namespace Unity.Netcode.Components
|
||||
{
|
||||
AddLogEntry(ref newState, NetworkObject.OwnerClientId);
|
||||
}
|
||||
|
||||
OnTransformUpdated();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -2744,6 +2782,11 @@ namespace Unity.Netcode.Components
|
||||
|
||||
}
|
||||
|
||||
protected virtual void OnBeforeUpdateTransformState()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
internal bool LogStateUpdate;
|
||||
/// <summary>
|
||||
/// Only non-authoritative instances should invoke this method
|
||||
@@ -2784,6 +2827,10 @@ namespace Unity.Netcode.Components
|
||||
}
|
||||
Debug.Log(builder);
|
||||
}
|
||||
|
||||
// Notification prior to applying a state update
|
||||
OnBeforeUpdateTransformState();
|
||||
|
||||
// Apply the new state
|
||||
ApplyUpdatedState(newState);
|
||||
|
||||
@@ -2984,7 +3031,13 @@ namespace Unity.Netcode.Components
|
||||
return;
|
||||
}
|
||||
m_CachedNetworkObject = NetworkObject;
|
||||
if (m_CachedNetworkManager && m_CachedNetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
AuthorityMode = AuthorityModes.Owner;
|
||||
}
|
||||
CanCommitToTransform = IsServerAuthoritative() ? IsServer : IsOwner;
|
||||
|
||||
|
||||
var currentPosition = GetSpaceRelativePosition();
|
||||
var currentRotation = GetSpaceRelativeRotation();
|
||||
|
||||
@@ -3011,22 +3064,24 @@ namespace Unity.Netcode.Components
|
||||
#else
|
||||
var forUpdate = true;
|
||||
#endif
|
||||
m_LocalAuthoritativeNetworkState.SynchronizeBaseHalfFloat = false;
|
||||
|
||||
if (CanCommitToTransform)
|
||||
{
|
||||
|
||||
// Make sure authority doesn't get added to updates (no need to do this on the authority side)
|
||||
m_CachedNetworkManager.NetworkTransformRegistration(this, forUpdate, false);
|
||||
if (UseHalfFloatPrecision)
|
||||
{
|
||||
m_HalfPositionState = new NetworkDeltaPosition(currentPosition, m_CachedNetworkManager.ServerTime.Tick, math.bool3(SyncPositionX, SyncPositionY, SyncPositionZ));
|
||||
m_LocalAuthoritativeNetworkState.SynchronizeBaseHalfFloat = isOwnershipChange;
|
||||
SetState(teleportDisabled: false);
|
||||
}
|
||||
|
||||
m_CurrentPosition = currentPosition;
|
||||
m_TargetPosition = currentPosition;
|
||||
|
||||
RegisterForTickUpdate(this);
|
||||
|
||||
m_LocalAuthoritativeNetworkState.SynchronizeBaseHalfFloat = false;
|
||||
if (UseHalfFloatPrecision && isOwnershipChange && !IsServerAuthoritative() && Interpolate)
|
||||
{
|
||||
m_HalfFloatTargetTickOwnership = m_CachedNetworkManager.ServerTime.Tick;
|
||||
@@ -3038,16 +3093,13 @@ namespace Unity.Netcode.Components
|
||||
m_CachedNetworkManager.NetworkTransformRegistration(this, forUpdate, true);
|
||||
// Remove this instance from the tick update
|
||||
DeregisterForTickUpdate(this);
|
||||
|
||||
ResetInterpolatedStateToCurrentAuthoritativeState();
|
||||
m_LocalAuthoritativeNetworkState.SynchronizeBaseHalfFloat = false;
|
||||
m_CurrentPosition = currentPosition;
|
||||
m_TargetPosition = currentPosition;
|
||||
m_CurrentScale = transform.localScale;
|
||||
m_TargetScale = transform.localScale;
|
||||
m_CurrentRotation = currentRotation;
|
||||
m_TargetRotation = currentRotation.eulerAngles;
|
||||
|
||||
}
|
||||
OnInitialize(ref m_LocalAuthoritativeNetworkState);
|
||||
}
|
||||
@@ -3296,7 +3348,7 @@ namespace Unity.Netcode.Components
|
||||
{
|
||||
var serverTime = m_CachedNetworkManager.ServerTime;
|
||||
var cachedServerTime = serverTime.Time;
|
||||
var offset = (float)serverTime.TickOffset;
|
||||
//var offset = (float)serverTime.TickOffset;
|
||||
#if COM_UNITY_MODULES_PHYSICS
|
||||
var cachedDeltaTime = m_UseRigidbodyForMotion ? m_CachedNetworkManager.RealTimeProvider.FixedDeltaTime : m_CachedNetworkManager.RealTimeProvider.DeltaTime;
|
||||
#else
|
||||
@@ -3314,7 +3366,7 @@ namespace Unity.Netcode.Components
|
||||
//offset = m_NetworkTransformTickRegistration.Offset;
|
||||
//}
|
||||
|
||||
var cachedRenderTime = serverTime.TimeTicksAgo(ticksAgo, offset).Time;
|
||||
var cachedRenderTime = serverTime.TimeTicksAgo(ticksAgo).Time;
|
||||
|
||||
// Now only update the interpolators for the portions of the transform being synchronized
|
||||
if (SynchronizePosition)
|
||||
@@ -3388,28 +3440,32 @@ namespace Unity.Netcode.Components
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Override this method and return false to switch to owner authoritative mode
|
||||
/// Determines whether the <see cref="NetworkTransform"/> is <see cref="AuthorityModes.Server"/> or <see cref="AuthorityModes.Owner"/> based on the <see cref="AuthorityMode"/> property.
|
||||
/// You can override this method to control this logic.
|
||||
/// </summary>
|
||||
/// <returns>(<see cref="true"/> or <see cref="false"/>) where when false it runs as owner-client authoritative</returns>
|
||||
/// <returns><see cref="true"/> or <see cref="false"/></returns>
|
||||
protected virtual bool OnIsServerAuthoritative()
|
||||
{
|
||||
if (m_CachedNetworkManager)
|
||||
{
|
||||
return !m_CachedNetworkManager.DistributedAuthorityMode;
|
||||
}
|
||||
return true;
|
||||
return AuthorityMode == AuthorityModes.Server;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Method to determine if this <see cref="NetworkTransform"/> instance is owner or server authoritative.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Used by <see cref="NetworkRigidbody"/> to determines if this is server or owner authoritative.
|
||||
/// When using a <see cref="NetworkTopologyTypes.DistributedAuthority"/> <see cref="NetworkConfig.NetworkTopology"/>, this will always be viewed as a <see cref="AuthorityModes.Owner"/> authoritative motion model.
|
||||
/// </remarks>
|
||||
/// <returns><see cref="true"/> or <see cref="false"/></returns>
|
||||
public bool IsServerAuthoritative()
|
||||
{
|
||||
return OnIsServerAuthoritative();
|
||||
if (m_CachedNetworkManager && m_CachedNetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
return OnIsServerAuthoritative();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -3451,9 +3507,10 @@ namespace Unity.Netcode.Components
|
||||
private NetworkTransformMessage m_OutboundMessage = new NetworkTransformMessage();
|
||||
|
||||
|
||||
internal void SerializeMessage(FastBufferWriter writer, int targetVersion)
|
||||
internal int SerializeMessage(FastBufferWriter writer, int targetVersion)
|
||||
{
|
||||
var networkObject = NetworkObject;
|
||||
var position = writer.Position;
|
||||
BytePacker.WriteValueBitPacked(writer, NetworkObjectId);
|
||||
BytePacker.WriteValueBitPacked(writer, (int)NetworkBehaviourId);
|
||||
writer.WriteNetworkSerializable(m_LocalAuthoritativeNetworkState);
|
||||
@@ -3470,6 +3527,7 @@ namespace Unity.Netcode.Components
|
||||
BytePacker.WriteValuePacked(writer, targetId);
|
||||
}
|
||||
}
|
||||
return writer.Position - position;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -3482,7 +3540,7 @@ namespace Unity.Netcode.Components
|
||||
return;
|
||||
}
|
||||
|
||||
bool isServerAuthoritative = OnIsServerAuthoritative();
|
||||
bool isServerAuthoritative = IsServerAuthoritative();
|
||||
if (isServerAuthoritative && !IsServer)
|
||||
{
|
||||
Debug.LogError($"Server authoritative {nameof(NetworkTransform)} can only be updated by the server!");
|
||||
@@ -3526,6 +3584,7 @@ namespace Unity.Netcode.Components
|
||||
// Clients (owner authoritative) send messages to the server-host
|
||||
NetworkManager.MessageManager.SendMessage(ref m_OutboundMessage, networkDelivery, NetworkManager.ServerClientId);
|
||||
}
|
||||
m_LocalAuthoritativeNetworkState.LastSerializedSize = m_OutboundMessage.BytesWritten;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
@@ -1,15 +1,8 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
|
||||
public enum NetworkTopologyTypes
|
||||
{
|
||||
ClientServer,
|
||||
DistributedAuthority
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A NetworkClient
|
||||
/// </summary>
|
||||
@@ -61,9 +54,9 @@ namespace Unity.Netcode
|
||||
public NetworkObject PlayerObject;
|
||||
|
||||
/// <summary>
|
||||
/// The list of NetworkObject's owned by this client instance
|
||||
/// The NetworkObject's owned by this client instance
|
||||
/// </summary>
|
||||
public List<NetworkObject> OwnedObjects => IsConnected ? SpawnManager.GetClientOwnedObjects(ClientId) : new List<NetworkObject>();
|
||||
public NetworkObject[] OwnedObjects => IsConnected ? SpawnManager.GetClientOwnedObjects(ClientId) : new NetworkObject[] { };
|
||||
|
||||
internal NetworkSpawnManager SpawnManager { get; private set; }
|
||||
|
||||
|
||||
@@ -1229,6 +1229,8 @@ namespace Unity.Netcode
|
||||
var message = new ClientDisconnectedMessage { ClientId = clientId };
|
||||
MessageManager?.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, ConnectedClientIds);
|
||||
|
||||
// Used for testing/validation purposes only
|
||||
#if ENABLE_DAHOST_AUTOPROMOTE_SESSION_OWNER
|
||||
if (NetworkManager.DistributedAuthorityMode && !NetworkManager.ShutdownInProgress && NetworkManager.IsListening)
|
||||
{
|
||||
var newSessionOwner = NetworkManager.LocalClientId;
|
||||
@@ -1259,6 +1261,7 @@ namespace Unity.Netcode
|
||||
MessageManager?.SendMessage(ref sessionOwnerMessage, NetworkDelivery.ReliableFragmentedSequenced, ConnectedClientIds);
|
||||
NetworkManager.SetSessionOwner(newSessionOwner);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// If the client ID transport map exists
|
||||
|
||||
@@ -950,7 +950,16 @@ namespace Unity.Netcode
|
||||
// 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 @@ namespace Unity.Netcode
|
||||
// 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 @@ namespace Unity.Netcode
|
||||
networkVariable = NetworkVariableFields[k];
|
||||
if (networkVariable.IsDirty() && networkVariable.CanClientRead(targetClientId))
|
||||
{
|
||||
shouldSend = true;
|
||||
if (networkVariable.CanSend())
|
||||
{
|
||||
shouldSend = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -1057,9 +1078,16 @@ namespace Unity.Netcode
|
||||
// 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 @@ namespace Unity.Netcode
|
||||
|
||||
}
|
||||
|
||||
public virtual void OnReanticipate(double lastRoundTripTime)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The relative client identifier targeted for the serialization of this <see cref="NetworkBehaviour"/> instance.
|
||||
/// </summary>
|
||||
|
||||
@@ -11,6 +11,7 @@ namespace Unity.Netcode
|
||||
private NetworkManager m_NetworkManager;
|
||||
private NetworkConnectionManager m_ConnectionManager;
|
||||
private HashSet<NetworkObject> m_DirtyNetworkObjects = new HashSet<NetworkObject>();
|
||||
private HashSet<NetworkObject> m_PendingDirtyNetworkObjects = new HashSet<NetworkObject>();
|
||||
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
private ProfilerMarker m_NetworkBehaviourUpdate = new ProfilerMarker($"{nameof(NetworkBehaviour)}.{nameof(NetworkBehaviourUpdate)}");
|
||||
@@ -18,7 +19,7 @@ namespace Unity.Netcode
|
||||
|
||||
internal void AddForUpdate(NetworkObject networkObject)
|
||||
{
|
||||
m_DirtyNetworkObjects.Add(networkObject);
|
||||
m_PendingDirtyNetworkObjects.Add(networkObject);
|
||||
}
|
||||
|
||||
internal void NetworkBehaviourUpdate()
|
||||
@@ -28,6 +29,9 @@ namespace Unity.Netcode
|
||||
#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);
|
||||
|
||||
@@ -36,17 +36,13 @@ namespace Unity.Netcode
|
||||
|
||||
#pragma warning restore IDE1006 // restore naming rule violation check
|
||||
|
||||
internal static bool IsDistributedAuthority;
|
||||
|
||||
/// <summary>
|
||||
/// Distributed Authority Mode
|
||||
/// Returns true if the current session is running in distributed authority mode.
|
||||
/// </summary>
|
||||
public bool DistributedAuthorityMode
|
||||
{
|
||||
get
|
||||
{
|
||||
return NetworkConfig.NetworkTopology == NetworkTopologyTypes.DistributedAuthority;
|
||||
}
|
||||
}
|
||||
public bool DistributedAuthorityMode { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Distributed Authority Mode
|
||||
@@ -131,6 +127,18 @@ namespace Unity.Netcode
|
||||
|
||||
public ulong CurrentSessionOwner { get; internal set; }
|
||||
|
||||
/// <summary>
|
||||
/// Delegate declaration for <see cref="OnSessionOwnerPromoted"/>
|
||||
/// </summary>
|
||||
/// <param name="sessionOwnerPromoted">the new session owner client identifier</param>
|
||||
public delegate void OnSessionOwnerPromotedDelegateHandler(ulong sessionOwnerPromoted);
|
||||
|
||||
/// <summary>
|
||||
/// Network Topology: Distributed Authority
|
||||
/// When a new session owner is promoted, this event is triggered on all connected clients
|
||||
/// </summary>
|
||||
public event OnSessionOwnerPromotedDelegateHandler OnSessionOwnerPromoted;
|
||||
|
||||
internal void SetSessionOwner(ulong sessionOwner)
|
||||
{
|
||||
var previousSessionOwner = CurrentSessionOwner;
|
||||
@@ -151,10 +159,12 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
OnSessionOwnerPromoted?.Invoke(sessionOwner);
|
||||
}
|
||||
|
||||
// TODO: Make this internal after testing
|
||||
public void PromoteSessionOwner(ulong clientId)
|
||||
internal void PromoteSessionOwner(ulong clientId)
|
||||
{
|
||||
if (!DistributedAuthorityMode)
|
||||
{
|
||||
@@ -217,19 +227,36 @@ namespace Unity.Netcode
|
||||
#endif
|
||||
}
|
||||
|
||||
private void UpdateTopology()
|
||||
{
|
||||
var transportTopology = IsListening ? NetworkConfig.NetworkTransport.CurrentTopology() : NetworkConfig.NetworkTopology;
|
||||
if (transportTopology != NetworkConfig.NetworkTopology)
|
||||
{
|
||||
NetworkLog.LogErrorServer($"[Topology Mismatch] Transport detected an issue with the topology ({transportTopology} | {NetworkConfig.NetworkTopology}) usage or setting! Disconnecting from session.");
|
||||
Shutdown();
|
||||
}
|
||||
else
|
||||
{
|
||||
IsDistributedAuthority = DistributedAuthorityMode = transportTopology == NetworkTopologyTypes.DistributedAuthority;
|
||||
}
|
||||
}
|
||||
|
||||
public void NetworkUpdate(NetworkUpdateStage updateStage)
|
||||
{
|
||||
switch (updateStage)
|
||||
{
|
||||
case NetworkUpdateStage.EarlyUpdate:
|
||||
{
|
||||
UpdateTopology();
|
||||
ConnectionManager.ProcessPendingApprovals();
|
||||
ConnectionManager.PollAndHandleNetworkEvents();
|
||||
|
||||
DeferredMessageManager.ProcessTriggers(IDeferredNetworkMessageManager.TriggerType.OnNextFrame, 0);
|
||||
|
||||
AnticipationSystem.SetupForUpdate();
|
||||
MessageManager.ProcessIncomingMessageQueue();
|
||||
MessageManager.CleanupDisconnectedClients();
|
||||
AnticipationSystem.ProcessReanticipation();
|
||||
}
|
||||
break;
|
||||
#if COM_UNITY_MODULES_PHYSICS
|
||||
@@ -248,6 +275,7 @@ namespace Unity.Netcode
|
||||
case NetworkUpdateStage.PreUpdate:
|
||||
{
|
||||
NetworkTimeSystem.UpdateTime();
|
||||
AnticipationSystem.Update();
|
||||
}
|
||||
break;
|
||||
case NetworkUpdateStage.PreLateUpdate:
|
||||
@@ -262,6 +290,12 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
break;
|
||||
case NetworkUpdateStage.PostScriptLateUpdate:
|
||||
{
|
||||
AnticipationSystem.Sync();
|
||||
AnticipationSystem.SetupForRender();
|
||||
}
|
||||
break;
|
||||
case NetworkUpdateStage.PostLateUpdate:
|
||||
{
|
||||
// Handle deferred despawning
|
||||
@@ -501,6 +535,25 @@ namespace Unity.Netcode
|
||||
remove => ConnectionManager.OnTransportFailure -= value;
|
||||
}
|
||||
|
||||
public delegate void ReanticipateDelegate(double lastRoundTripTime);
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public event ReanticipateDelegate OnReanticipate
|
||||
{
|
||||
add => AnticipationSystem.OnReanticipate += value;
|
||||
remove => AnticipationSystem.OnReanticipate -= value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The callback to invoke during connection approval. Allows client code to decide whether or not to allow incoming client connection
|
||||
/// </summary>
|
||||
@@ -745,6 +798,8 @@ namespace Unity.Netcode
|
||||
/// </summary>
|
||||
public NetworkTickSystem NetworkTickSystem { get; private set; }
|
||||
|
||||
internal AnticipationSystem AnticipationSystem { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Used for time mocking in tests
|
||||
/// </summary>
|
||||
@@ -1012,6 +1067,8 @@ namespace Unity.Netcode
|
||||
#endif
|
||||
NetworkTransformUpdate.Clear();
|
||||
|
||||
UpdateTopology();
|
||||
|
||||
//DANGOEXP TODO: Remove this before finalizing the experimental release
|
||||
NetworkConfig.AutoSpawnPlayerPrefabClientSide = DistributedAuthorityMode;
|
||||
|
||||
@@ -1051,6 +1108,7 @@ namespace Unity.Netcode
|
||||
this.RegisterNetworkUpdate(NetworkUpdateStage.FixedUpdate);
|
||||
#endif
|
||||
this.RegisterNetworkUpdate(NetworkUpdateStage.PreUpdate);
|
||||
this.RegisterNetworkUpdate(NetworkUpdateStage.PostScriptLateUpdate);
|
||||
this.RegisterNetworkUpdate(NetworkUpdateStage.PreLateUpdate);
|
||||
this.RegisterNetworkUpdate(NetworkUpdateStage.PostLateUpdate);
|
||||
|
||||
@@ -1090,6 +1148,7 @@ namespace Unity.Netcode
|
||||
// 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);
|
||||
@@ -1191,6 +1250,17 @@ namespace Unity.Netcode
|
||||
{
|
||||
SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
|
||||
|
||||
// Notify the server that all in-scnee placed NetworkObjects are spawned at this time.
|
||||
foreach (var networkObject in SpawnManager.SpawnedObjectsList)
|
||||
{
|
||||
networkObject.InternalInSceneNetworkObjectsSpawned();
|
||||
}
|
||||
|
||||
// Notify the server that everything should be synchronized/spawned at this time.
|
||||
foreach (var networkObject in SpawnManager.SpawnedObjectsList)
|
||||
{
|
||||
networkObject.InternalNetworkSessionSynchronized();
|
||||
}
|
||||
OnServerStarted?.Invoke();
|
||||
ConnectionManager.LocalClient.IsApproved = true;
|
||||
return true;
|
||||
@@ -1337,6 +1407,17 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
|
||||
// Notify the host that all in-scnee placed NetworkObjects are spawned at this time.
|
||||
foreach (var networkObject in SpawnManager.SpawnedObjectsList)
|
||||
{
|
||||
networkObject.InternalInSceneNetworkObjectsSpawned();
|
||||
}
|
||||
|
||||
// Notify the host that everything should be synchronized/spawned at this time.
|
||||
foreach (var networkObject in SpawnManager.SpawnedObjectsList)
|
||||
{
|
||||
networkObject.InternalNetworkSessionSynchronized();
|
||||
}
|
||||
|
||||
OnServerStarted?.Invoke();
|
||||
OnClientStarted?.Invoke();
|
||||
|
||||
@@ -430,7 +430,7 @@ namespace Unity.Netcode
|
||||
/// Determines whether a NetworkObject can be distributed to other clients during
|
||||
/// a <see cref="NetworkTopologyTypes.DistributedAuthority"/> session.
|
||||
/// </summary>
|
||||
#if !MULTIPLAYER_SDK_INSTALLED
|
||||
#if !MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
[HideInInspector]
|
||||
#endif
|
||||
[SerializeField]
|
||||
|
||||
@@ -54,6 +54,12 @@ namespace Unity.Netcode
|
||||
/// </summary>
|
||||
PreLateUpdate = 6,
|
||||
/// <summary>
|
||||
/// Updated after Monobehaviour.LateUpdate, but BEFORE rendering
|
||||
/// </summary>
|
||||
// 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,
|
||||
/// <summary>
|
||||
/// Updated after the Monobehaviour.LateUpdate for all components is invoked
|
||||
/// </summary>
|
||||
PostLateUpdate = 7
|
||||
@@ -258,6 +264,18 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
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 @@ namespace Unity.Netcode
|
||||
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 @@ namespace Unity.Netcode
|
||||
else if (currentSystem.type == typeof(PreLateUpdate))
|
||||
{
|
||||
TryRemoveLoopSystem(ref currentSystem, typeof(NetworkPreLateUpdate));
|
||||
TryRemoveLoopSystem(ref currentSystem, typeof(NetworkPostScriptLateUpdate));
|
||||
}
|
||||
else if (currentSystem.type == typeof(PostLateUpdate))
|
||||
{
|
||||
|
||||
@@ -47,6 +47,8 @@ namespace Unity.Netcode
|
||||
SessionOwner = 20,
|
||||
TimeSync = 21,
|
||||
Unnamed = 22,
|
||||
AnticipationCounterSyncPingMessage = 23,
|
||||
AnticipationCounterSyncPongMessage = 24,
|
||||
}
|
||||
|
||||
|
||||
@@ -103,7 +105,9 @@ namespace Unity.Netcode
|
||||
{ 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)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b7d5c92979ad7e646a078aaf058b53a9
|
||||
@@ -243,6 +243,13 @@ namespace Unity.Netcode
|
||||
// Spawn any in-scene placed NetworkObjects
|
||||
networkManager.SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
|
||||
|
||||
// With scene management enabled and since the session owner doesn't send a Synchronize scene event synchronize itself,
|
||||
// we need to notify the session owner that all in-scnee placed NetworkObjects are spawned at this time.
|
||||
foreach (var networkObject in networkManager.SpawnManager.SpawnedObjectsList)
|
||||
{
|
||||
networkObject.InternalInSceneNetworkObjectsSpawned();
|
||||
}
|
||||
|
||||
// Spawn the local player of the session owner
|
||||
if (networkManager.AutoSpawnPlayerPrefabClientSide)
|
||||
{
|
||||
@@ -251,6 +258,17 @@ namespace Unity.Netcode
|
||||
|
||||
// Synchronize the service with the initial session owner's loaded scenes and spawned objects
|
||||
networkManager.SceneManager.SynchronizeNetworkObjects(NetworkManager.ServerClientId);
|
||||
|
||||
// With scene management enabled and since the session owner doesn't send a Synchronize scene event synchronize itself,
|
||||
// we need to notify the session owner that everything should be synchronized/spawned at this time.
|
||||
foreach (var networkObject in networkManager.SpawnManager.SpawnedObjectsList)
|
||||
{
|
||||
networkObject.InternalNetworkSessionSynchronized();
|
||||
}
|
||||
|
||||
// When scene management is enabled and since the session owner is synchronizing the service (i.e. acting like host),
|
||||
// we need to locallyh invoke the OnClientConnected callback at this point in time.
|
||||
networkManager.ConnectionManager.InvokeOnClientConnectedCallback(OwnerClientId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,8 @@ namespace Unity.Netcode
|
||||
internal NetworkTransform.NetworkTransformState State;
|
||||
private FastBufferReader m_CurrentReader;
|
||||
|
||||
internal int BytesWritten;
|
||||
|
||||
private unsafe void CopyPayload(ref FastBufferWriter writer)
|
||||
{
|
||||
writer.WriteBytesSafe(m_CurrentReader.GetUnsafePtrAtCurrentPosition(), m_CurrentReader.Length - m_CurrentReader.Position);
|
||||
@@ -30,7 +32,7 @@ namespace Unity.Netcode
|
||||
}
|
||||
else
|
||||
{
|
||||
NetworkTransform.SerializeMessage(writer, targetVersion);
|
||||
BytesWritten = NetworkTransform.SerializeMessage(writer, targetVersion);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,6 +77,7 @@ namespace Unity.Netcode
|
||||
ownerAuthoritativeServerSide = !isServerAuthoritative && networkManager.IsServer;
|
||||
|
||||
reader.ReadNetworkSerializableInPlace(ref NetworkTransform.InboundState);
|
||||
NetworkTransform.InboundState.LastSerializedSize = reader.Position - currentPosition;
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -69,7 +69,8 @@ namespace Unity.Netcode
|
||||
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
|
||||
|
||||
@@ -34,6 +34,9 @@ namespace Unity.Netcode
|
||||
internal class NetworkMessageManager : IDisposable
|
||||
{
|
||||
public bool StopProcessing = false;
|
||||
private static Type s_ConnectionApprovedType = typeof(ConnectionApprovedMessage);
|
||||
private static Type s_ConnectionRequestType = typeof(ConnectionRequestMessage);
|
||||
private static Type s_DisconnectReasonType = typeof(DisconnectReasonMessage);
|
||||
|
||||
private struct ReceiveQueueItem
|
||||
{
|
||||
@@ -524,6 +527,7 @@ namespace Unity.Netcode
|
||||
return new T().Version;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal int GetMessageVersion(Type type, ulong clientId, bool forReceive = false)
|
||||
{
|
||||
if (!m_PerClientMessageVersions.TryGetValue(clientId, out var versionMap))
|
||||
@@ -551,16 +555,20 @@ namespace Unity.Netcode
|
||||
return messageVersion;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static void ReceiveMessage<T>(FastBufferReader reader, ref NetworkContext context, NetworkMessageManager manager) where T : INetworkMessage, new()
|
||||
{
|
||||
var messageType = typeof(T);
|
||||
var message = new T();
|
||||
var messageVersion = 0;
|
||||
|
||||
// Special cases because these are the messages that carry the version info - thus the version info isn't
|
||||
// populated yet when we get these. The first part of these messages always has to be the version data
|
||||
// and can't change.
|
||||
if (typeof(T) != typeof(ConnectionRequestMessage) && typeof(T) != typeof(ConnectionApprovedMessage) && typeof(T) != typeof(DisconnectReasonMessage) && context.SenderId != manager.m_LocalClientId)
|
||||
if (messageType != s_ConnectionRequestType && messageType != s_ConnectionApprovedType && messageType != s_DisconnectReasonType && context.SenderId != manager.m_LocalClientId)
|
||||
{
|
||||
messageVersion = manager.GetMessageVersion(typeof(T), context.SenderId, true);
|
||||
messageVersion = manager.GetMessageVersion(messageType, context.SenderId, true);
|
||||
if (messageVersion < 0)
|
||||
{
|
||||
return;
|
||||
@@ -612,7 +620,7 @@ namespace Unity.Netcode
|
||||
var messageVersion = 0;
|
||||
// Special case because this is the message that carries the version info - thus the version info isn't populated yet when we get this.
|
||||
// The first part of this message always has to be the version data and can't change.
|
||||
if (typeof(TMessageType) != typeof(ConnectionRequestMessage))
|
||||
if (typeof(TMessageType) != s_ConnectionRequestType)
|
||||
{
|
||||
messageVersion = GetMessageVersion(typeof(TMessageType), clientIds[i]);
|
||||
if (messageVersion < 0)
|
||||
@@ -666,7 +674,7 @@ namespace Unity.Netcode
|
||||
|
||||
// Special case because this is the message that carries the version info - thus the version info isn't populated yet when we get this.
|
||||
// The first part of this message always has to be the version data and can't change.
|
||||
if (typeof(TMessageType) != typeof(ConnectionRequestMessage))
|
||||
if (typeof(TMessageType) != s_ConnectionRequestType)
|
||||
{
|
||||
var messageVersion = GetMessageVersion(typeof(TMessageType), clientIds[i]);
|
||||
if (messageVersion < 0)
|
||||
@@ -746,7 +754,7 @@ namespace Unity.Netcode
|
||||
// Special case because this is the message that carries the version info - thus the version info isn't
|
||||
// populated yet when we get this. The first part of this message always has to be the version data
|
||||
// and can't change.
|
||||
if (typeof(TMessageType) != typeof(ConnectionRequestMessage))
|
||||
if (typeof(TMessageType) != s_ConnectionRequestType)
|
||||
{
|
||||
messageVersion = GetMessageVersion(typeof(TMessageType), clientId);
|
||||
if (messageVersion < 0)
|
||||
|
||||
@@ -4,23 +4,37 @@ namespace Unity.Netcode
|
||||
{
|
||||
private NotServerRpcTarget m_NotServerRpcTarget;
|
||||
private ServerRpcTarget m_ServerRpcTarget;
|
||||
private NotAuthorityRpcTarget m_NotAuthorityRpcTarget;
|
||||
private AuthorityRpcTarget m_AuthorityRpcTarget;
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
m_NotServerRpcTarget.Dispose();
|
||||
m_ServerRpcTarget.Dispose();
|
||||
m_NotAuthorityRpcTarget.Dispose();
|
||||
m_AuthorityRpcTarget.Dispose();
|
||||
}
|
||||
|
||||
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
|
||||
{
|
||||
m_NotServerRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||
m_ServerRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||
if (NetworkManager.IsDistributedAuthority)
|
||||
{
|
||||
m_NotAuthorityRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||
m_AuthorityRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||
}
|
||||
else
|
||||
{
|
||||
m_NotServerRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||
m_ServerRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||
}
|
||||
}
|
||||
|
||||
internal EveryoneRpcTarget(NetworkManager manager) : base(manager)
|
||||
{
|
||||
m_NotServerRpcTarget = new NotServerRpcTarget(manager);
|
||||
m_ServerRpcTarget = new ServerRpcTarget(manager);
|
||||
m_NotAuthorityRpcTarget = new NotAuthorityRpcTarget(manager);
|
||||
m_AuthorityRpcTarget = new AuthorityRpcTarget(manager);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
392
Runtime/NetworkVariable/AnticipatedNetworkVariable.cs
Normal file
392
Runtime/NetworkVariable/AnticipatedNetworkVariable.cs
Normal file
@@ -0,0 +1,392 @@
|
||||
using System;
|
||||
using Unity.Mathematics;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
|
||||
public enum StaleDataHandling
|
||||
{
|
||||
Ignore,
|
||||
Reanticipate
|
||||
}
|
||||
|
||||
#pragma warning disable IDE0001
|
||||
/// <summary>
|
||||
/// 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:
|
||||
///
|
||||
/// <list type="bullet">
|
||||
///
|
||||
/// <item><b>Snap:</b> In this mode (with <see cref="StaleDataHandling"/> set to
|
||||
/// <see cref="Netcode.StaleDataHandling.Ignore"/> and no <see cref="NetworkBehaviour.OnReanticipate"/> 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.</item>
|
||||
///
|
||||
/// <item><b>Smooth:</b> In this mode (with <see cref="StaleDataHandling"/> set to
|
||||
/// <see cref="Netcode.StaleDataHandling.Ignore"/> and an <see cref="NetworkBehaviour.OnReanticipate"/> callback that calls
|
||||
/// <see cref="Smooth"/> from the anticipated value to the authority value with an appropriate
|
||||
/// <see cref="Mathf.Lerp"/>-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.</item>
|
||||
///
|
||||
/// <item><b>Constant Reanticipation:</b> In this mode (with <see cref="StaleDataHandling"/> set to
|
||||
/// <see cref="Netcode.StaleDataHandling.Reanticipate"/> and an <see cref="NetworkBehaviour.OnReanticipate"/> 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 <see cref="Smooth"/> 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.</item>
|
||||
///
|
||||
/// </list>
|
||||
///
|
||||
/// Note that these three modes may be combined. For example, if an <see cref="NetworkBehaviour.OnReanticipate"/> callback
|
||||
/// does not call either <see cref="Smooth"/> or <see cref="Anticipate"/>, the result will be a snap to the
|
||||
/// authoritative value, enabling for a callback that may conditionally call <see cref="Smooth"/> 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.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">the unmanaged type for <see cref="NetworkVariable{T}"/> </typeparam>
|
||||
#pragma warning restore IDE0001
|
||||
[Serializable]
|
||||
[GenerateSerializationForGenericParameter(0)]
|
||||
public class AnticipatedNetworkVariable<T> : NetworkVariableBase
|
||||
{
|
||||
[SerializeField]
|
||||
private NetworkVariable<T> 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
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// <br/><br/>
|
||||
/// If this is <see cref="Netcode.StaleDataHandling.Ignore"/>, the stale data will be ignored and the authoritative
|
||||
/// value will not replace the anticipated value until the anticipation time is reached. <see cref="OnAuthoritativeValueChanged"/>
|
||||
/// and <see cref="NetworkBehaviour.OnReanticipate"/> will also not be invoked for this stale data.
|
||||
/// <br/><br/>
|
||||
/// If this is <see cref="Netcode.StaleDataHandling.Reanticipate"/>, the stale data will replace the anticipated data and
|
||||
/// <see cref="OnAuthoritativeValueChanged"/> and <see cref="NetworkBehaviour.OnReanticipate"/> will be invoked.
|
||||
/// In this case, the authoritativeTime value passed to <see cref="NetworkBehaviour.OnReanticipate"/> will be lower than
|
||||
/// the anticipationTime value, and that callback can be used to calculate a new anticipated value.
|
||||
/// </summary>
|
||||
#pragma warning restore IDE0001
|
||||
public StaleDataHandling StaleDataHandling;
|
||||
|
||||
public delegate void OnAuthoritativeValueChangedDelegate(AnticipatedNetworkVariable<T> variable, in T previousValue, in T newValue);
|
||||
|
||||
/// <summary>
|
||||
/// Invoked any time the authoritative value changes, even when the data is stale or has been changed locally.
|
||||
/// </summary>
|
||||
public OnAuthoritativeValueChangedDelegate OnAuthoritativeValueChanged = null;
|
||||
|
||||
/// <summary>
|
||||
/// Determines if the difference between the last serialized value and the current value is large enough
|
||||
/// to serialize it again.
|
||||
/// </summary>
|
||||
public event NetworkVariable<T>.CheckExceedsDirtinessThresholdDelegate CheckExceedsDirtinessThreshold
|
||||
{
|
||||
add => m_AuthoritativeValue.CheckExceedsDirtinessThreshold += value;
|
||||
remove => m_AuthoritativeValue.CheckExceedsDirtinessThreshold -= value;
|
||||
}
|
||||
|
||||
private class AnticipatedObject : IAnticipatedObject
|
||||
{
|
||||
public AnticipatedNetworkVariable<T> 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<T>.Duplicate(m_AuthoritativeValue.Value, ref m_AnticipatedValue);
|
||||
NetworkVariableSerialization<T>.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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the current value for the variable.
|
||||
/// This is the "display value" for this variable, and is affected by <see cref="Anticipate"/> and
|
||||
/// <see cref="Smooth"/>, as well as by updates from the authority, depending on <see cref="StaleDataHandling"/>
|
||||
/// and the behavior of any <see cref="NetworkBehaviour.OnReanticipate"/> callbacks.
|
||||
/// <br /><br />
|
||||
/// 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
|
||||
/// <see cref="PreviousAnticipatedValue"/>, which
|
||||
/// will NOT be overwritten in server updates.
|
||||
/// </summary>
|
||||
public T Value => m_AnticipatedValue;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="PreviousAnticipatedState"/>
|
||||
/// </summary>
|
||||
public bool ShouldReanticipate
|
||||
{
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Holds the most recent anticipated value, whatever was
|
||||
/// most recently set using <see cref="Anticipate"/>. Unlike
|
||||
/// <see cref="Value"/>, this does not get overwritten
|
||||
/// when a server update arrives.
|
||||
/// </summary>
|
||||
public T PreviousAnticipatedValue => m_PreviousAnticipatedValue;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
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<T>.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue);
|
||||
if (CanClientWrite(m_NetworkBehaviour.NetworkManager.LocalClientId))
|
||||
{
|
||||
AuthoritativeValue = value;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma warning disable IDE0001
|
||||
/// <summary>
|
||||
/// 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 <see cref="StaleDataHandling"/> is <see cref="Netcode.StaleDataHandling.Ignore"/>.
|
||||
/// </summary>
|
||||
#pragma warning restore IDE0001
|
||||
public T AuthoritativeValue
|
||||
{
|
||||
get => m_AuthoritativeValue.Value;
|
||||
set
|
||||
{
|
||||
m_SettingAuthoritativeValue = true;
|
||||
try
|
||||
{
|
||||
m_AuthoritativeValue.Value = value;
|
||||
m_AnticipatedValue = value;
|
||||
NetworkVariableSerialization<T>.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue);
|
||||
}
|
||||
finally
|
||||
{
|
||||
m_SettingAuthoritativeValue = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A function to interpolate between two values based on a percentage.
|
||||
/// See <see cref="Mathf.Lerp"/>, <see cref="Vector3.Lerp"/>, <see cref="Vector3.Slerp"/>, and so on
|
||||
/// for examples.
|
||||
/// </summary>
|
||||
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<T>(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<T>.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<T>.Duplicate(AuthoritativeValue, ref m_AnticipatedValue);
|
||||
|
||||
m_SmoothDuration = 0;
|
||||
m_CurrentSmoothTime = 0;
|
||||
OnAuthoritativeValueChanged?.Invoke(this, previousValue, newValue);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Interpolate this variable from <see cref="from"/> to <see cref="to"/> over <see cref="durationSeconds"/> of
|
||||
/// real time. The duration uses <see cref="Time.deltaTime"/>, so it is affected by <see cref="Time.timeScale"/>.
|
||||
/// </summary>
|
||||
/// <param name="from"></param>
|
||||
/// <param name="to"></param>
|
||||
/// <param name="durationSeconds"></param>
|
||||
/// <param name="how"></param>
|
||||
public void Smooth(in T from, in T to, float durationSeconds, SmoothDelegate how)
|
||||
{
|
||||
if (durationSeconds <= 0)
|
||||
{
|
||||
NetworkVariableSerialization<T>.Duplicate(to, ref m_AnticipatedValue);
|
||||
m_SmoothDuration = 0;
|
||||
m_CurrentSmoothTime = 0;
|
||||
m_SmoothDelegate = null;
|
||||
return;
|
||||
}
|
||||
NetworkVariableSerialization<T>.Duplicate(from, ref m_AnticipatedValue);
|
||||
NetworkVariableSerialization<T>.Duplicate(from, ref m_SmoothFrom);
|
||||
NetworkVariableSerialization<T>.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<T>.Duplicate(m_AuthoritativeValue.Value, ref m_AnticipatedValue);
|
||||
NetworkVariableSerialization<T>.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue);
|
||||
}
|
||||
|
||||
public override void ReadDelta(FastBufferReader reader, bool keepDirtyDelta)
|
||||
{
|
||||
m_AuthoritativeValue.ReadDelta(reader, keepDirtyDelta);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: fc9fd5701bee8534a971eb9f49178e21
|
||||
@@ -21,6 +21,29 @@ namespace Unity.Netcode
|
||||
/// The callback to be invoked when the value gets changed
|
||||
/// </summary>
|
||||
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<T>.Duplicate(m_InternalValue, ref m_PreviousValue);
|
||||
}
|
||||
|
||||
internal override NetworkVariableType Type => NetworkVariableType.Value;
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -3,11 +3,26 @@ using UnityEngine;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Interface for network value containers
|
||||
/// </summary>
|
||||
public abstract class NetworkVariableBase : IDisposable
|
||||
{
|
||||
[SerializeField]
|
||||
internal NetworkVariableUpdateTraits UpdateTraits = default;
|
||||
|
||||
[NonSerialized]
|
||||
internal double LastUpdateSent;
|
||||
|
||||
/// <summary>
|
||||
/// The delivery type (QoS) to send data with
|
||||
/// </summary>
|
||||
@@ -52,7 +67,42 @@ namespace Unity.Netcode
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called on initialization
|
||||
/// </summary>
|
||||
public virtual void OnInitialize()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the update traits for this network variable to determine how frequently it will send updates.
|
||||
/// </summary>
|
||||
/// <param name="traits"></param>
|
||||
public void SetUpdateTraits(NetworkVariableUpdateTraits traits)
|
||||
{
|
||||
UpdateTraits = traits;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="UpdateTraits"/>' <see cref="NetworkVariableUpdateTraits.MaxSecondsBetweenUpdates"/>.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public virtual bool ExceedsDirtinessThreshold()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -125,6 +175,25 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
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 @@ namespace Unity.Netcode
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,3 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2c6ef5fdf2e94ec3b4ce8086d52700b3
|
||||
timeCreated: 1650985453
|
||||
3
Runtime/NetworkVariable/Serialization.meta
Normal file
3
Runtime/NetworkVariable/Serialization.meta
Normal file
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d960ae6c5b8241aa9e2906b709095ea1
|
||||
timeCreated: 1718215841
|
||||
99
Runtime/NetworkVariable/Serialization/FallbackSerializer.cs
Normal file
99
Runtime/NetworkVariable/Serialization/FallbackSerializer.cs
Normal file
@@ -0,0 +1,99 @@
|
||||
using System;
|
||||
using Unity.Collections;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
/// <summary>
|
||||
/// This class is instantiated for types that we can't determine ahead of time are serializable - types
|
||||
/// that don't meet any of the constraints for methods that are available on FastBufferReader and
|
||||
/// FastBufferWriter. These types may or may not be serializable through extension methods. To ensure
|
||||
/// the user has time to pass in the delegates to UserNetworkVariableSerialization, the existence
|
||||
/// of user serialization isn't checked until it's used, so if no serialization is provided, this
|
||||
/// will throw an exception when an object containing the relevant NetworkVariable is spawned.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
internal class FallbackSerializer<T> : INetworkVariableSerializer<T>
|
||||
{
|
||||
private void ThrowArgumentError()
|
||||
{
|
||||
throw new ArgumentException($"Serialization has not been generated for type {typeof(T).FullName}. This can be addressed by adding a [{nameof(GenerateSerializationForGenericParameterAttribute)}] to your generic class that serializes this value (if you are using one), adding [{nameof(GenerateSerializationForTypeAttribute)}(typeof({typeof(T).FullName})] to the class or method that is attempting to serialize it, or creating a field on a {nameof(NetworkBehaviour)} of type {nameof(NetworkVariable<T>)}. If this error continues to appear after doing one of those things and this is a type you can change, then either implement {nameof(INetworkSerializable)} or mark it as serializable by memcpy by adding {nameof(INetworkSerializeByMemcpy)} to its interface list to enable automatic serialization generation. If not, assign serialization code to {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.WriteValue)}, {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.ReadValue)}, and {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.DuplicateValue)}, or if it's serializable by memcpy (contains no pointers), wrap it in {typeof(ForceNetworkSerializeByMemcpy<>).Name}.");
|
||||
}
|
||||
|
||||
public void Write(FastBufferWriter writer, ref T value)
|
||||
{
|
||||
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
|
||||
{
|
||||
ThrowArgumentError();
|
||||
}
|
||||
UserNetworkVariableSerialization<T>.WriteValue(writer, value);
|
||||
}
|
||||
public void Read(FastBufferReader reader, ref T value)
|
||||
{
|
||||
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
|
||||
{
|
||||
ThrowArgumentError();
|
||||
}
|
||||
UserNetworkVariableSerialization<T>.ReadValue(reader, out value);
|
||||
}
|
||||
|
||||
public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue)
|
||||
{
|
||||
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
|
||||
{
|
||||
ThrowArgumentError();
|
||||
}
|
||||
|
||||
if (UserNetworkVariableSerialization<T>.WriteDelta == null || UserNetworkVariableSerialization<T>.ReadDelta == null)
|
||||
{
|
||||
UserNetworkVariableSerialization<T>.WriteValue(writer, value);
|
||||
return;
|
||||
}
|
||||
UserNetworkVariableSerialization<T>.WriteDelta(writer, value, previousValue);
|
||||
}
|
||||
|
||||
public void ReadDelta(FastBufferReader reader, ref T value)
|
||||
{
|
||||
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
|
||||
{
|
||||
ThrowArgumentError();
|
||||
}
|
||||
|
||||
if (UserNetworkVariableSerialization<T>.WriteDelta == null || UserNetworkVariableSerialization<T>.ReadDelta == null)
|
||||
{
|
||||
UserNetworkVariableSerialization<T>.ReadValue(reader, out value);
|
||||
return;
|
||||
}
|
||||
UserNetworkVariableSerialization<T>.ReadDelta(reader, ref value);
|
||||
}
|
||||
|
||||
void INetworkVariableSerializer<T>.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void Duplicate(in T value, ref T duplicatedValue)
|
||||
{
|
||||
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
|
||||
{
|
||||
ThrowArgumentError();
|
||||
}
|
||||
UserNetworkVariableSerialization<T>.DuplicateValue(value, ref duplicatedValue);
|
||||
}
|
||||
}
|
||||
|
||||
// RuntimeAccessModifiersILPP will make this `public`
|
||||
// This is just pass-through to NetworkVariableSerialization<T> but is here because I could not get ILPP
|
||||
// to generate code that would successfully call Type<T>.Method(T), but it has no problem calling Type.Method<T>(T)
|
||||
internal class RpcFallbackSerialization
|
||||
{
|
||||
public static void Write<T>(FastBufferWriter writer, ref T value)
|
||||
{
|
||||
NetworkVariableSerialization<T>.Write(writer, ref value);
|
||||
}
|
||||
|
||||
public static void Read<T>(FastBufferReader reader, ref T value)
|
||||
{
|
||||
NetworkVariableSerialization<T>.Read(reader, ref value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 288dbe7d1ff74860ae3552c034485538
|
||||
timeCreated: 1718219109
|
||||
@@ -0,0 +1,26 @@
|
||||
using Unity.Collections;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
/// <summary>
|
||||
/// Interface used by NetworkVariables to serialize them
|
||||
/// </summary>
|
||||
///
|
||||
/// <typeparam name="T"></typeparam>
|
||||
internal interface INetworkVariableSerializer<T>
|
||||
{
|
||||
// Write has to be taken by ref here because of INetworkSerializable
|
||||
// Open Instance Delegates (pointers to methods without an instance attached to them)
|
||||
// require the first parameter passed to them (the instance) to be passed by ref.
|
||||
// So foo.Bar() becomes BarDelegate(ref foo);
|
||||
// Taking T as an in parameter like we do in other places would require making a copy
|
||||
// of it to pass it as a ref parameter.,
|
||||
|
||||
public void Write(FastBufferWriter writer, ref T value);
|
||||
public void Read(FastBufferReader reader, ref T value);
|
||||
public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue);
|
||||
public void ReadDelta(FastBufferReader reader, ref T value);
|
||||
internal void ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator);
|
||||
public void Duplicate(in T value, ref T duplicatedValue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f78e258ef55f4ee89bc3f24d67b8d242
|
||||
timeCreated: 1718218205
|
||||
357
Runtime/NetworkVariable/Serialization/NetworkVariableEquality.cs
Normal file
357
Runtime/NetworkVariable/Serialization/NetworkVariableEquality.cs
Normal file
@@ -0,0 +1,357 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Unity.Collections;
|
||||
using Unity.Collections.LowLevel.Unsafe;
|
||||
using Unity.Netcode;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
internal static class NetworkVariableEquality<T>
|
||||
{
|
||||
// Compares two values of the same unmanaged type by underlying memory
|
||||
// Ignoring any overridden value checks
|
||||
// Size is fixed
|
||||
internal static unsafe bool ValueEquals<TValueType>(ref TValueType a, ref TValueType b) where TValueType : unmanaged
|
||||
{
|
||||
// get unmanaged pointers
|
||||
var aptr = UnsafeUtility.AddressOf(ref a);
|
||||
var bptr = UnsafeUtility.AddressOf(ref b);
|
||||
|
||||
// compare addresses
|
||||
return UnsafeUtility.MemCmp(aptr, bptr, sizeof(TValueType)) == 0;
|
||||
}
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
// Compares two values of the same unmanaged type by underlying memory
|
||||
// Ignoring any overridden value checks
|
||||
// Size is fixed
|
||||
internal static unsafe bool ValueEqualsList<TValueType>(ref NativeList<TValueType> a, ref NativeList<TValueType> b) where TValueType : unmanaged
|
||||
{
|
||||
if (a.IsCreated != b.IsCreated)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!a.IsCreated)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (a.Length != b.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
#if UTP_TRANSPORT_2_0_ABOVE
|
||||
var aptr = a.GetUnsafePtr();
|
||||
var bptr = b.GetUnsafePtr();
|
||||
#else
|
||||
var aptr = (TValueType*)a.GetUnsafePtr();
|
||||
var bptr = (TValueType*)b.GetUnsafePtr();
|
||||
#endif
|
||||
|
||||
return UnsafeUtility.MemCmp(aptr, bptr, sizeof(TValueType) * a.Length) == 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
// Compares two values of the same unmanaged type by underlying memory
|
||||
// Ignoring any overridden value checks
|
||||
// Size is fixed
|
||||
internal static unsafe bool ValueEqualsArray<TValueType>(ref NativeArray<TValueType> a, ref NativeArray<TValueType> b) where TValueType : unmanaged
|
||||
{
|
||||
if (a.IsCreated != b.IsCreated)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!a.IsCreated)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (a.Length != b.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var aptr = (TValueType*)a.GetUnsafePtr();
|
||||
var bptr = (TValueType*)b.GetUnsafePtr();
|
||||
return UnsafeUtility.MemCmp(aptr, bptr, sizeof(TValueType) * a.Length) == 0;
|
||||
}
|
||||
|
||||
internal static bool EqualityEqualsObject<TValueType>(ref TValueType a, ref TValueType b) where TValueType : class, IEquatable<TValueType>
|
||||
{
|
||||
if (a == null)
|
||||
{
|
||||
return b == null;
|
||||
}
|
||||
|
||||
if (b == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return a.Equals(b);
|
||||
}
|
||||
|
||||
internal static bool EqualityEquals<TValueType>(ref TValueType a, ref TValueType b) where TValueType : unmanaged, IEquatable<TValueType>
|
||||
{
|
||||
return a.Equals(b);
|
||||
}
|
||||
|
||||
internal static bool EqualityEqualsList<TValueType>(ref List<TValueType> a, ref List<TValueType> b)
|
||||
{
|
||||
if (a == null != (b == null))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (a == null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (a.Count != b.Count)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
for (var i = 0; i < a.Count; ++i)
|
||||
{
|
||||
var aItem = a[i];
|
||||
var bItem = b[i];
|
||||
if (!NetworkVariableSerialization<TValueType>.AreEqual(ref aItem, ref bItem))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
internal static bool EqualityEqualsHashSet<TValueType>(ref HashSet<TValueType> a, ref HashSet<TValueType> b) where TValueType : IEquatable<TValueType>
|
||||
{
|
||||
if (a == null != (b == null))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (a == null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (a.Count != b.Count)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var item in a)
|
||||
{
|
||||
if (!b.Contains(item))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Compares two values of the same unmanaged type by underlying memory
|
||||
// Ignoring any overridden value checks
|
||||
// Size is fixed
|
||||
internal static unsafe bool EqualityEqualsArray<TValueType>(ref NativeArray<TValueType> a, ref NativeArray<TValueType> b) where TValueType : unmanaged, IEquatable<TValueType>
|
||||
{
|
||||
if (a.IsCreated != b.IsCreated)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!a.IsCreated)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (a.Length != b.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var aptr = (TValueType*)a.GetUnsafePtr();
|
||||
var bptr = (TValueType*)b.GetUnsafePtr();
|
||||
for (var i = 0; i < a.Length; ++i)
|
||||
{
|
||||
if (!EqualityEquals(ref aptr[i], ref bptr[i]))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
internal static bool ClassEquals<TValueType>(ref TValueType a, ref TValueType b) where TValueType : class
|
||||
{
|
||||
return a == b;
|
||||
}
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
// Compares two values of the same unmanaged type by underlying memory
|
||||
// Ignoring any overridden value checks
|
||||
// Size is fixed
|
||||
internal static unsafe bool EqualityEqualsNativeList<TValueType>(ref NativeList<TValueType> a, ref NativeList<TValueType> b) where TValueType : unmanaged, IEquatable<TValueType>
|
||||
{
|
||||
if (a.IsCreated != b.IsCreated)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!a.IsCreated)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (a.Length != b.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
#if UTP_TRANSPORT_2_0_ABOVE
|
||||
var aptr = a.GetUnsafePtr();
|
||||
var bptr = b.GetUnsafePtr();
|
||||
#else
|
||||
var aptr = (TValueType*)a.GetUnsafePtr();
|
||||
var bptr = (TValueType*)b.GetUnsafePtr();
|
||||
#endif
|
||||
for (var i = 0; i < a.Length; ++i)
|
||||
{
|
||||
if (!EqualityEquals(ref aptr[i], ref bptr[i]))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
internal static bool EqualityEqualsNativeHashSet<TValueType>(ref NativeHashSet<TValueType> a, ref NativeHashSet<TValueType> b) where TValueType : unmanaged, IEquatable<TValueType>
|
||||
{
|
||||
if (a.IsCreated != b.IsCreated)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!a.IsCreated)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
#if UTP_TRANSPORT_2_0_ABOVE
|
||||
if (a.Count != b.Count)
|
||||
#else
|
||||
if (a.Count() != b.Count())
|
||||
#endif
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var item in a)
|
||||
{
|
||||
if (!b.Contains(item))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Support methods for equality of NetworkVariable collection types.
|
||||
/// Because there are multiple overloads of WriteValue/ReadValue based on different generic constraints,
|
||||
/// but there's no way to achieve the same thing with a class, this sets up various read/write schemes
|
||||
/// based on which constraints are met by `T` using reflection, which is done at module load time.
|
||||
/// </summary>
|
||||
/// <typeparam name="TKey">The type the associated NetworkVariable dictionary collection key templated on</typeparam>
|
||||
/// <typeparam name="TVal">The type the associated NetworkVariable dictionary collection value templated on</typeparam>
|
||||
internal class NetworkVariableDictionarySerialization<TKey, TVal>
|
||||
where TKey : IEquatable<TKey>
|
||||
{
|
||||
internal static bool GenericEqualsDictionary(ref Dictionary<TKey, TVal> a, ref Dictionary<TKey, TVal> b)
|
||||
{
|
||||
if (a == null != (b == null))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (a == null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (a.Count != b.Count)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var item in a)
|
||||
{
|
||||
var hasKey = b.TryGetValue(item.Key, out var val);
|
||||
if (!hasKey)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var bVal = item.Value;
|
||||
if (!NetworkVariableSerialization<TVal>.AreEqual(ref bVal, ref val))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
internal class NetworkVariableMapSerialization<TKey, TVal>
|
||||
where TKey : unmanaged, IEquatable<TKey>
|
||||
where TVal : unmanaged
|
||||
{
|
||||
internal static bool GenericEqualsNativeHashMap(ref NativeHashMap<TKey, TVal> a, ref NativeHashMap<TKey, TVal> b)
|
||||
{
|
||||
if (a.IsCreated != b.IsCreated)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!a.IsCreated)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
#if UTP_TRANSPORT_2_0_ABOVE
|
||||
if (a.Count != b.Count)
|
||||
#else
|
||||
if (a.Count() != b.Count())
|
||||
#endif
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var item in a)
|
||||
{
|
||||
var hasKey = b.TryGetValue(item.Key, out var val);
|
||||
if (!hasKey || !NetworkVariableSerialization<TVal>.AreEqual(ref item.Value, ref val))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 24b8352a975044509931bf684ccfdb82
|
||||
timeCreated: 1718219366
|
||||
@@ -0,0 +1,161 @@
|
||||
using System;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
/// <summary>
|
||||
/// Support methods for reading/writing NetworkVariables
|
||||
/// Because there are multiple overloads of WriteValue/ReadValue based on different generic constraints,
|
||||
/// but there's no way to achieve the same thing with a class, this sets up various read/write schemes
|
||||
/// based on which constraints are met by `T` using reflection, which is done at module load time.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type the associated NetworkVariable is templated on</typeparam>
|
||||
[Serializable]
|
||||
public static class NetworkVariableSerialization<T>
|
||||
{
|
||||
internal static INetworkVariableSerializer<T> Serializer = new FallbackSerializer<T>();
|
||||
|
||||
internal static bool IsDistributedAuthority => NetworkManager.IsDistributedAuthority;
|
||||
|
||||
/// <summary>
|
||||
/// The collection item type tells the CMB server how to read the bytes of each item in the collection
|
||||
/// </summary>
|
||||
/// DANGO-EXP TODO: Determine if this is distributed authority only and impacts of this in client-server
|
||||
internal static CollectionItemType Type = CollectionItemType.Unknown;
|
||||
|
||||
/// <summary>
|
||||
/// A callback to check if two values are equal.
|
||||
/// </summary>
|
||||
public delegate bool EqualsDelegate(ref T a, ref T b);
|
||||
|
||||
/// <summary>
|
||||
/// Uses the most efficient mechanism for a given type to determine if two values are equal.
|
||||
/// For types that implement <see cref="IEquatable{T}"/>, it will call the Equals() method.
|
||||
/// For unmanaged types, it will do a bytewise memory comparison.
|
||||
/// For other types, it will call the == operator.
|
||||
/// <br/>
|
||||
/// <br/>
|
||||
/// Note: If you are using this in a custom generic class, please make sure your class is
|
||||
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute"/> so that codegen can
|
||||
/// initialize the serialization mechanisms correctly. If your class is NOT
|
||||
/// generic, it is better to check their equality yourself.
|
||||
/// </summary>
|
||||
public static EqualsDelegate AreEqual { get; internal set; }
|
||||
/// <summary>
|
||||
/// Serialize a value using the best-known serialization method for a generic value.
|
||||
/// Will reliably serialize any value that is passed to it correctly with no boxing.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// Note: If you are using this in a custom generic class, please make sure your class is
|
||||
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
|
||||
/// initialize the serialization mechanisms correctly. If your class is NOT
|
||||
/// generic, it is better to use FastBufferWriter directly.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// If the codegen is unable to determine a serializer for a type,
|
||||
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.WriteValue" /> is called, which, by default,
|
||||
/// will throw an exception, unless you have assigned a user serialization callback to it at runtime.
|
||||
/// </summary>
|
||||
/// <param name="writer"></param>
|
||||
/// <param name="value"></param>
|
||||
public static void Write(FastBufferWriter writer, ref T value)
|
||||
{
|
||||
Serializer.Write(writer, ref value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserialize a value using the best-known serialization method for a generic value.
|
||||
/// Will reliably deserialize any value that is passed to it correctly with no boxing.
|
||||
/// For types whose deserialization can be determined by codegen (which is most types),
|
||||
/// GC will only be incurred if the type is a managed type and the ref value passed in is `null`,
|
||||
/// in which case a new value is created; otherwise, it will be deserialized in-place.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// Note: If you are using this in a custom generic class, please make sure your class is
|
||||
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
|
||||
/// initialize the serialization mechanisms correctly. If your class is NOT
|
||||
/// generic, it is better to use FastBufferReader directly.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// If the codegen is unable to determine a serializer for a type,
|
||||
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.ReadValue" /> is called, which, by default,
|
||||
/// will throw an exception, unless you have assigned a user deserialization callback to it at runtime.
|
||||
/// </summary>
|
||||
/// <param name="reader"></param>
|
||||
/// <param name="value"></param>
|
||||
public static void Read(FastBufferReader reader, ref T value)
|
||||
{
|
||||
Serializer.Read(reader, ref value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serialize a value using the best-known serialization method for a generic value.
|
||||
/// Will reliably serialize any value that is passed to it correctly with no boxing.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// Note: If you are using this in a custom generic class, please make sure your class is
|
||||
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
|
||||
/// initialize the serialization mechanisms correctly. If your class is NOT
|
||||
/// generic, it is better to use FastBufferWriter directly.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// If the codegen is unable to determine a serializer for a type,
|
||||
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.WriteValue" /> is called, which, by default,
|
||||
/// will throw an exception, unless you have assigned a user serialization callback to it at runtime.
|
||||
/// </summary>
|
||||
/// <param name="writer"></param>
|
||||
/// <param name="value"></param>
|
||||
public static void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue)
|
||||
{
|
||||
Serializer.WriteDelta(writer, ref value, ref previousValue);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserialize a value using the best-known serialization method for a generic value.
|
||||
/// Will reliably deserialize any value that is passed to it correctly with no boxing.
|
||||
/// For types whose deserialization can be determined by codegen (which is most types),
|
||||
/// GC will only be incurred if the type is a managed type and the ref value passed in is `null`,
|
||||
/// in which case a new value is created; otherwise, it will be deserialized in-place.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// Note: If you are using this in a custom generic class, please make sure your class is
|
||||
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
|
||||
/// initialize the serialization mechanisms correctly. If your class is NOT
|
||||
/// generic, it is better to use FastBufferReader directly.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// If the codegen is unable to determine a serializer for a type,
|
||||
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.ReadValue" /> is called, which, by default,
|
||||
/// will throw an exception, unless you have assigned a user deserialization callback to it at runtime.
|
||||
/// </summary>
|
||||
/// <param name="reader"></param>
|
||||
/// <param name="value"></param>
|
||||
public static void ReadDelta(FastBufferReader reader, ref T value)
|
||||
{
|
||||
Serializer.ReadDelta(reader, ref value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Duplicates a value using the most efficient means of creating a complete copy.
|
||||
/// For most types this is a simple assignment or memcpy.
|
||||
/// For managed types, this is will serialize and then deserialize the value to ensure
|
||||
/// a correct copy.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// Note: If you are using this in a custom generic class, please make sure your class is
|
||||
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
|
||||
/// initialize the serialization mechanisms correctly. If your class is NOT
|
||||
/// generic, it is better to duplicate it directly.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// If the codegen is unable to determine a serializer for a type,
|
||||
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.DuplicateValue" /> is called, which, by default,
|
||||
/// will throw an exception, unless you have assigned a user duplication callback to it at runtime.
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="duplicatedValue"></param>
|
||||
public static void Duplicate(in T value, ref T duplicatedValue)
|
||||
{
|
||||
Serializer.Duplicate(value, ref duplicatedValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7a943170e35746e8913dd494d79bb63d
|
||||
timeCreated: 1718215899
|
||||
325
Runtime/NetworkVariable/Serialization/TypedILPPInitializers.cs
Normal file
325
Runtime/NetworkVariable/Serialization/TypedILPPInitializers.cs
Normal file
@@ -0,0 +1,325 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Unity.Collections;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
/// <summary>
|
||||
/// This class contains initialization functions for various different types used in NetworkVariables.
|
||||
/// Generally speaking, these methods are called by a module initializer created by codegen (NetworkBehaviourILPP)
|
||||
/// and do not need to be called manually.
|
||||
///
|
||||
/// There are two types of initializers: Serializers and EqualityCheckers. Every type must have an EqualityChecker
|
||||
/// registered to it in order to be used in NetworkVariable; however, not all types need a Serializer. Types without
|
||||
/// a serializer registered will fall back to using the delegates in <see cref="UserNetworkVariableSerialization{T}"/>.
|
||||
/// If no such delegate has been registered, a type without a serializer will throw an exception on the first attempt
|
||||
/// to serialize or deserialize it. (Again, however, codegen handles this automatically and this registration doesn't
|
||||
/// typically need to be performed manually.)
|
||||
/// </summary>
|
||||
public static class NetworkVariableSerializationTypedInitializers
|
||||
{
|
||||
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
|
||||
#if UNITY_EDITOR
|
||||
[InitializeOnLoadMethod]
|
||||
#endif
|
||||
internal static void InitializeIntegerSerialization()
|
||||
{
|
||||
NetworkVariableSerialization<short>.Serializer = new ShortSerializer();
|
||||
NetworkVariableSerialization<short>.AreEqual = NetworkVariableEquality<short>.ValueEquals;
|
||||
NetworkVariableSerialization<ushort>.Serializer = new UshortSerializer();
|
||||
NetworkVariableSerialization<ushort>.AreEqual = NetworkVariableEquality<ushort>.ValueEquals;
|
||||
NetworkVariableSerialization<int>.Serializer = new IntSerializer();
|
||||
NetworkVariableSerialization<int>.AreEqual = NetworkVariableEquality<int>.ValueEquals;
|
||||
NetworkVariableSerialization<uint>.Serializer = new UintSerializer();
|
||||
NetworkVariableSerialization<uint>.AreEqual = NetworkVariableEquality<uint>.ValueEquals;
|
||||
NetworkVariableSerialization<long>.Serializer = new LongSerializer();
|
||||
NetworkVariableSerialization<long>.AreEqual = NetworkVariableEquality<long>.ValueEquals;
|
||||
NetworkVariableSerialization<ulong>.Serializer = new UlongSerializer();
|
||||
NetworkVariableSerialization<ulong>.AreEqual = NetworkVariableEquality<ulong>.ValueEquals;
|
||||
|
||||
// DANGO-EXP TODO: Determine if this is distributed authority only and impacts of this in client-server
|
||||
NetworkVariableSerialization<short>.Type = CollectionItemType.Short;
|
||||
NetworkVariableSerialization<ushort>.Type = CollectionItemType.UShort;
|
||||
NetworkVariableSerialization<int>.Type = CollectionItemType.Int;
|
||||
NetworkVariableSerialization<uint>.Type = CollectionItemType.UInt;
|
||||
NetworkVariableSerialization<long>.Type = CollectionItemType.Long;
|
||||
NetworkVariableSerialization<ulong>.Type = CollectionItemType.ULong;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registeres an unmanaged type that will be serialized by a direct memcpy into a buffer
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_UnmanagedByMemcpy<T>() where T : unmanaged
|
||||
{
|
||||
NetworkVariableSerialization<T>.Serializer = new UnmanagedTypeSerializer<T>();
|
||||
// DANGO-EXP TODO: Determine if this is distributed authority only and impacts of this in client-server
|
||||
NetworkVariableSerialization<T>.Type = CollectionItemType.Unmanaged;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registeres an unmanaged type that will be serialized by a direct memcpy into a buffer
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_UnmanagedByMemcpyArray<T>() where T : unmanaged
|
||||
{
|
||||
NetworkVariableSerialization<NativeArray<T>>.Serializer = new UnmanagedArraySerializer<T>();
|
||||
}
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
/// <summary>
|
||||
/// Registeres an unmanaged type that will be serialized by a direct memcpy into a buffer
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_UnmanagedByMemcpyList<T>() where T : unmanaged
|
||||
{
|
||||
NetworkVariableSerialization<NativeList<T>>.Serializer = new UnmanagedListSerializer<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registeres a native hash set (this generic implementation works with all types)
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_NativeHashSet<T>() where T : unmanaged, IEquatable<T>
|
||||
{
|
||||
NetworkVariableSerialization<NativeHashSet<T>>.Serializer = new NativeHashSetSerializer<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registeres a native hash set (this generic implementation works with all types)
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_NativeHashMap<TKey, TVal>()
|
||||
where TKey : unmanaged, IEquatable<TKey>
|
||||
where TVal : unmanaged
|
||||
{
|
||||
NetworkVariableSerialization<NativeHashMap<TKey, TVal>>.Serializer = new NativeHashMapSerializer<TKey, TVal>();
|
||||
}
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Registeres a native hash set (this generic implementation works with all types)
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_List<T>()
|
||||
{
|
||||
NetworkVariableSerialization<List<T>>.Serializer = new ListSerializer<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registeres a native hash set (this generic implementation works with all types)
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_HashSet<T>() where T : IEquatable<T>
|
||||
{
|
||||
NetworkVariableSerialization<HashSet<T>>.Serializer = new HashSetSerializer<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registeres a native hash set (this generic implementation works with all types)
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_Dictionary<TKey, TVal>() where TKey : IEquatable<TKey>
|
||||
{
|
||||
NetworkVariableSerialization<Dictionary<TKey, TVal>>.Serializer = new DictionarySerializer<TKey, TVal>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that implements INetworkSerializable and will be serialized through a call to
|
||||
/// NetworkSerialize
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_UnmanagedINetworkSerializable<T>() where T : unmanaged, INetworkSerializable
|
||||
{
|
||||
NetworkVariableSerialization<T>.Serializer = new UnmanagedNetworkSerializableSerializer<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that implements INetworkSerializable and will be serialized through a call to
|
||||
/// NetworkSerialize
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_UnmanagedINetworkSerializableArray<T>() where T : unmanaged, INetworkSerializable
|
||||
{
|
||||
NetworkVariableSerialization<NativeArray<T>>.Serializer = new UnmanagedNetworkSerializableArraySerializer<T>();
|
||||
}
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that implements INetworkSerializable and will be serialized through a call to
|
||||
/// NetworkSerialize
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_UnmanagedINetworkSerializableList<T>() where T : unmanaged, INetworkSerializable
|
||||
{
|
||||
NetworkVariableSerialization<NativeList<T>>.Serializer = new UnmanagedNetworkSerializableListSerializer<T>();
|
||||
}
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Registers a managed type that implements INetworkSerializable and will be serialized through a call to
|
||||
/// NetworkSerialize
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_ManagedINetworkSerializable<T>() where T : class, INetworkSerializable, new()
|
||||
{
|
||||
NetworkVariableSerialization<T>.Serializer = new ManagedNetworkSerializableSerializer<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a FixedString type that will be serialized through FastBufferReader/FastBufferWriter's FixedString
|
||||
/// serializers
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_FixedString<T>() where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
NetworkVariableSerialization<T>.Serializer = new FixedStringSerializer<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a FixedString type that will be serialized through FastBufferReader/FastBufferWriter's FixedString
|
||||
/// serializers
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_FixedStringArray<T>() where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
NetworkVariableSerialization<NativeArray<T>>.Serializer = new FixedStringArraySerializer<T>();
|
||||
}
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
/// <summary>
|
||||
/// Registers a FixedString type that will be serialized through FastBufferReader/FastBufferWriter's FixedString
|
||||
/// serializers
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_FixedStringList<T>() where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
NetworkVariableSerialization<NativeList<T>>.Serializer = new FixedStringListSerializer<T>();
|
||||
}
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Registers a managed type that will be checked for equality using T.Equals()
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_ManagedIEquatable<T>() where T : class, IEquatable<T>
|
||||
{
|
||||
NetworkVariableSerialization<T>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsObject;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using T.Equals()
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_UnmanagedIEquatable<T>() where T : unmanaged, IEquatable<T>
|
||||
{
|
||||
NetworkVariableSerialization<T>.AreEqual = NetworkVariableEquality<T>.EqualityEquals;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using T.Equals()
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_UnmanagedIEquatableArray<T>() where T : unmanaged, IEquatable<T>
|
||||
{
|
||||
NetworkVariableSerialization<NativeArray<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsArray;
|
||||
}
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using T.Equals()
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_List<T>()
|
||||
{
|
||||
NetworkVariableSerialization<List<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsList;
|
||||
}
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using T.Equals()
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_HashSet<T>() where T : IEquatable<T>
|
||||
{
|
||||
NetworkVariableSerialization<HashSet<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsHashSet;
|
||||
}
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using T.Equals()
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_Dictionary<TKey, TVal>()
|
||||
where TKey : IEquatable<TKey>
|
||||
{
|
||||
NetworkVariableSerialization<Dictionary<TKey, TVal>>.AreEqual = NetworkVariableDictionarySerialization<TKey, TVal>.GenericEqualsDictionary;
|
||||
}
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using T.Equals()
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_UnmanagedIEquatableList<T>() where T : unmanaged, IEquatable<T>
|
||||
{
|
||||
NetworkVariableSerialization<NativeList<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsNativeList;
|
||||
}
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using T.Equals()
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_NativeHashSet<T>() where T : unmanaged, IEquatable<T>
|
||||
{
|
||||
NetworkVariableSerialization<NativeHashSet<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsNativeHashSet;
|
||||
}
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using T.Equals()
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_NativeHashMap<TKey, TVal>()
|
||||
where TKey : unmanaged, IEquatable<TKey>
|
||||
where TVal : unmanaged
|
||||
{
|
||||
NetworkVariableSerialization<NativeHashMap<TKey, TVal>>.AreEqual = NetworkVariableMapSerialization<TKey, TVal>.GenericEqualsNativeHashMap;
|
||||
}
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using memcmp and only considered
|
||||
/// equal if they are bitwise equivalent in memory
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_UnmanagedValueEquals<T>() where T : unmanaged
|
||||
{
|
||||
NetworkVariableSerialization<T>.AreEqual = NetworkVariableEquality<T>.ValueEquals;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using memcmp and only considered
|
||||
/// equal if they are bitwise equivalent in memory
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_UnmanagedValueEqualsArray<T>() where T : unmanaged
|
||||
{
|
||||
NetworkVariableSerialization<NativeArray<T>>.AreEqual = NetworkVariableEquality<T>.ValueEqualsArray;
|
||||
}
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using memcmp and only considered
|
||||
/// equal if they are bitwise equivalent in memory
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_UnmanagedValueEqualsList<T>() where T : unmanaged
|
||||
{
|
||||
NetworkVariableSerialization<NativeList<T>>.AreEqual = NetworkVariableEquality<T>.ValueEqualsList;
|
||||
}
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Registers a managed type that will be checked for equality using the == operator
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_ManagedClassEquals<T>() where T : class
|
||||
{
|
||||
NetworkVariableSerialization<T>.AreEqual = NetworkVariableEquality<T>.ClassEquals;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 65bdb3e11a9a412ab5e936a9c96a3da0
|
||||
timeCreated: 1718216842
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bbfa170e9dd448bbbe381ce38d5c139d
|
||||
timeCreated: 1718216671
|
||||
@@ -0,0 +1,73 @@
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
/// <summary>
|
||||
/// This class is used to register user serialization with NetworkVariables for types
|
||||
/// that are serialized via user serialization, such as with FastBufferReader and FastBufferWriter
|
||||
/// extension methods. Finding those methods isn't achievable efficiently at runtime, so this allows
|
||||
/// users to tell NetworkVariable about those extension methods (or simply pass in a lambda)
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class UserNetworkVariableSerialization<T>
|
||||
{
|
||||
/// <summary>
|
||||
/// The write value delegate handler definition
|
||||
/// </summary>
|
||||
/// <param name="writer">The <see cref="FastBufferWriter"/> to write the value of type `T`</param>
|
||||
/// <param name="value">The value of type `T` to be written</param>
|
||||
public delegate void WriteValueDelegate(FastBufferWriter writer, in T value);
|
||||
|
||||
/// <summary>
|
||||
/// The write value delegate handler definition
|
||||
/// </summary>
|
||||
/// <param name="writer">The <see cref="FastBufferWriter"/> to write the value of type `T`</param>
|
||||
/// <param name="value">The value of type `T` to be written</param>
|
||||
public delegate void WriteDeltaDelegate(FastBufferWriter writer, in T value, in T previousValue);
|
||||
|
||||
/// <summary>
|
||||
/// The read value delegate handler definition
|
||||
/// </summary>
|
||||
/// <param name="reader">The <see cref="FastBufferReader"/> to read the value of type `T`</param>
|
||||
/// <param name="value">The value of type `T` to be read</param>
|
||||
public delegate void ReadValueDelegate(FastBufferReader reader, out T value);
|
||||
|
||||
/// <summary>
|
||||
/// The read value delegate handler definition
|
||||
/// </summary>
|
||||
/// <param name="reader">The <see cref="FastBufferReader"/> to read the value of type `T`</param>
|
||||
/// <param name="value">The value of type `T` to be read</param>
|
||||
public delegate void ReadDeltaDelegate(FastBufferReader reader, ref T value);
|
||||
|
||||
/// <summary>
|
||||
/// The read value delegate handler definition
|
||||
/// </summary>
|
||||
/// <param name="reader">The <see cref="FastBufferReader"/> to read the value of type `T`</param>
|
||||
/// <param name="value">The value of type `T` to be read</param>
|
||||
public delegate void DuplicateValueDelegate(in T value, ref T duplicatedValue);
|
||||
|
||||
/// <summary>
|
||||
/// Callback to write a value
|
||||
/// </summary>
|
||||
public static WriteValueDelegate WriteValue;
|
||||
|
||||
/// <summary>
|
||||
/// Callback to read a value
|
||||
/// </summary>
|
||||
public static ReadValueDelegate ReadValue;
|
||||
|
||||
/// <summary>
|
||||
/// Callback to write a delta between two values, based on computing the difference between the previous and
|
||||
/// current values.
|
||||
/// </summary>
|
||||
public static WriteDeltaDelegate WriteDelta;
|
||||
|
||||
/// <summary>
|
||||
/// Callback to read a delta, applying only select changes to the current value.
|
||||
/// </summary>
|
||||
public static ReadDeltaDelegate ReadDelta;
|
||||
|
||||
/// <summary>
|
||||
/// Callback to create a duplicate of a value, used to check for dirty status.
|
||||
/// </summary>
|
||||
public static DuplicateValueDelegate DuplicateValue;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b295a6756640488b9824d2ec6e26ddae
|
||||
timeCreated: 1718218272
|
||||
@@ -523,8 +523,8 @@ namespace Unity.Netcode
|
||||
/// <param name="oneByteChars">Whether or not to use one byte per character. This will only allow ASCII</param>
|
||||
public unsafe void ReadValue(out string s, bool oneByteChars = false)
|
||||
{
|
||||
ReadValue(out uint length);
|
||||
s = "".PadRight((int)length);
|
||||
ReadLength(out int length);
|
||||
s = "".PadRight(length);
|
||||
int target = s.Length;
|
||||
fixed (char* native = s)
|
||||
{
|
||||
@@ -562,18 +562,18 @@ namespace Unity.Netcode
|
||||
}
|
||||
#endif
|
||||
|
||||
if (!TryBeginReadInternal(sizeof(uint)))
|
||||
if (!TryBeginReadInternal(SizeOfLengthField()))
|
||||
{
|
||||
throw new OverflowException("Reading past the end of the buffer");
|
||||
}
|
||||
|
||||
ReadValue(out uint length);
|
||||
ReadLength(out int length);
|
||||
|
||||
if (!TryBeginReadInternal((int)length * (oneByteChars ? 1 : sizeof(char))))
|
||||
if (!TryBeginReadInternal(length * (oneByteChars ? 1 : sizeof(char))))
|
||||
{
|
||||
throw new OverflowException("Reading past the end of the buffer");
|
||||
}
|
||||
s = "".PadRight((int)length);
|
||||
s = "".PadRight(length);
|
||||
int target = s.Length;
|
||||
fixed (char* native = s)
|
||||
{
|
||||
@@ -592,6 +592,33 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static int SizeOfLengthField() => sizeof(uint);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void ReadLengthSafe(out uint length) => ReadUnmanagedSafe(out length);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void ReadLength(out uint length) => ReadUnmanaged(out length);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void ReadLengthSafe(out int length)
|
||||
{
|
||||
ReadLengthSafe(out uint temp);
|
||||
if (temp > int.MaxValue)
|
||||
{
|
||||
throw new InvalidCastException("length value outside of int32 range");
|
||||
}
|
||||
length = (int)temp;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void ReadLength(out int length)
|
||||
{
|
||||
ReadLength(out uint temp);
|
||||
length = (int)temp;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read a partial value. The value is zero-initialized and then the specified number of bytes is read into it.
|
||||
/// </summary>
|
||||
@@ -777,7 +804,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void ReadUnmanaged<T>(out T[] value) where T : unmanaged
|
||||
{
|
||||
ReadUnmanaged(out int sizeInTs);
|
||||
ReadLength(out int sizeInTs);
|
||||
int sizeInBytes = sizeInTs * sizeof(T);
|
||||
value = new T[sizeInTs];
|
||||
fixed (T* ptr = value)
|
||||
@@ -789,7 +816,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void ReadUnmanagedSafe<T>(out T[] value) where T : unmanaged
|
||||
{
|
||||
ReadUnmanagedSafe(out int sizeInTs);
|
||||
ReadLengthSafe(out int sizeInTs);
|
||||
int sizeInBytes = sizeInTs * sizeof(T);
|
||||
value = new T[sizeInTs];
|
||||
fixed (T* ptr = value)
|
||||
@@ -801,7 +828,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void ReadUnmanaged<T>(out NativeArray<T> value, Allocator allocator) where T : unmanaged
|
||||
{
|
||||
ReadUnmanaged(out int sizeInTs);
|
||||
ReadLength(out int sizeInTs);
|
||||
int sizeInBytes = sizeInTs * sizeof(T);
|
||||
value = new NativeArray<T>(sizeInTs, allocator);
|
||||
byte* bytes = (byte*)value.GetUnsafePtr();
|
||||
@@ -810,7 +837,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void ReadUnmanagedSafe<T>(out NativeArray<T> value, Allocator allocator) where T : unmanaged
|
||||
{
|
||||
ReadUnmanagedSafe(out int sizeInTs);
|
||||
ReadLengthSafe(out int sizeInTs);
|
||||
int sizeInBytes = sizeInTs * sizeof(T);
|
||||
value = new NativeArray<T>(sizeInTs, allocator);
|
||||
byte* bytes = (byte*)value.GetUnsafePtr();
|
||||
@@ -820,7 +847,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void ReadUnmanagedInPlace<T>(ref NativeList<T> value) where T : unmanaged
|
||||
{
|
||||
ReadUnmanaged(out int sizeInTs);
|
||||
ReadLength(out int sizeInTs);
|
||||
int sizeInBytes = sizeInTs * sizeof(T);
|
||||
value.Resize(sizeInTs, NativeArrayOptions.UninitializedMemory);
|
||||
byte* bytes = (byte*)value.GetUnsafePtr();
|
||||
@@ -829,7 +856,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void ReadUnmanagedSafeInPlace<T>(ref NativeList<T> value) where T : unmanaged
|
||||
{
|
||||
ReadUnmanagedSafe(out int sizeInTs);
|
||||
ReadLengthSafe(out int sizeInTs);
|
||||
int sizeInBytes = sizeInTs * sizeof(T);
|
||||
value.Resize(sizeInTs, NativeArrayOptions.UninitializedMemory);
|
||||
byte* bytes = (byte*)value.GetUnsafePtr();
|
||||
@@ -1078,7 +1105,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal void ReadValueSafeInPlace<T>(ref NativeHashSet<T> value) where T : unmanaged, IEquatable<T>
|
||||
{
|
||||
ReadUnmanagedSafe(out int length);
|
||||
ReadLengthSafe(out int length);
|
||||
value.Clear();
|
||||
for (var i = 0; i < length; ++i)
|
||||
{
|
||||
@@ -1093,7 +1120,7 @@ namespace Unity.Netcode
|
||||
where TKey : unmanaged, IEquatable<TKey>
|
||||
where TVal : unmanaged
|
||||
{
|
||||
ReadUnmanagedSafe(out int length);
|
||||
ReadLengthSafe(out int length);
|
||||
value.Clear();
|
||||
for (var i = 0; i < length; ++i)
|
||||
{
|
||||
@@ -1553,7 +1580,7 @@ namespace Unity.Netcode
|
||||
/// This method is a little difficult to use, since you have to know the size of the string before
|
||||
/// reading it, but is useful when the string is a known, fixed size. Note that the size of the
|
||||
/// string is also encoded, so the size to call TryBeginRead on is actually the fixed size (in bytes)
|
||||
/// plus sizeof(int)
|
||||
/// plus sizeof(uint)
|
||||
/// </summary>
|
||||
/// <param name="value">the value to read</param>
|
||||
/// <param name="unused">An unused parameter used for enabling overload resolution based on generic constraints</param>
|
||||
@@ -1562,7 +1589,7 @@ namespace Unity.Netcode
|
||||
public unsafe void ReadValue<T>(out T value, FastBufferWriter.ForFixedStrings unused = default)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
ReadUnmanaged(out int length);
|
||||
ReadLength(out int length);
|
||||
value = new T
|
||||
{
|
||||
Length = length
|
||||
@@ -1584,7 +1611,7 @@ namespace Unity.Netcode
|
||||
public unsafe void ReadValueSafe<T>(out T value, FastBufferWriter.ForFixedStrings unused = default)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
ReadUnmanagedSafe(out int length);
|
||||
ReadLengthSafe(out int length);
|
||||
value = new T
|
||||
{
|
||||
Length = length
|
||||
@@ -1606,7 +1633,7 @@ namespace Unity.Netcode
|
||||
public unsafe void ReadValueSafeInPlace<T>(ref T value, FastBufferWriter.ForFixedStrings unused = default)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
ReadUnmanagedSafe(out int length);
|
||||
ReadLengthSafe(out int length);
|
||||
value.Length = length;
|
||||
ReadBytesSafe(value.GetUnsafePtr(), length);
|
||||
}
|
||||
@@ -1625,7 +1652,7 @@ namespace Unity.Netcode
|
||||
public unsafe void ReadValueSafe<T>(out NativeArray<T> value, Allocator allocator)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
ReadUnmanagedSafe(out int length);
|
||||
ReadLengthSafe(out int length);
|
||||
value = new NativeArray<T>(length, allocator);
|
||||
var ptr = (T*)value.GetUnsafePtr();
|
||||
for (var i = 0; i < length; ++i)
|
||||
@@ -1647,7 +1674,7 @@ namespace Unity.Netcode
|
||||
public unsafe void ReadValueSafeTemp<T>(out NativeArray<T> value)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
ReadUnmanagedSafe(out int length);
|
||||
ReadLengthSafe(out int length);
|
||||
value = new NativeArray<T>(length, Allocator.Temp);
|
||||
var ptr = (T*)value.GetUnsafePtr();
|
||||
for (var i = 0; i < length; ++i)
|
||||
@@ -1669,7 +1696,7 @@ namespace Unity.Netcode
|
||||
public void ReadValueSafe<T>(out T[] value, FastBufferWriter.ForFixedStrings unused = default)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
ReadUnmanagedSafe(out int length);
|
||||
ReadLengthSafe(out int length);
|
||||
value = new T[length];
|
||||
for (var i = 0; i < length; ++i)
|
||||
{
|
||||
@@ -1691,7 +1718,7 @@ namespace Unity.Netcode
|
||||
public void ReadValueSafeInPlace<T>(ref NativeList<T> value)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
ReadUnmanagedSafe(out int length);
|
||||
ReadLengthSafe(out int length);
|
||||
value.Resize(length, NativeArrayOptions.UninitializedMemory);
|
||||
for (var i = 0; i < length; ++i)
|
||||
{
|
||||
|
||||
@@ -421,7 +421,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int GetWriteSize(string s, bool oneByteChars = false)
|
||||
{
|
||||
return sizeof(int) + s.Length * (oneByteChars ? sizeof(byte) : sizeof(char));
|
||||
return SizeOfLengthField() + s.Length * (oneByteChars ? sizeof(byte) : sizeof(char));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -445,7 +445,7 @@ namespace Unity.Netcode
|
||||
public void WriteNetworkSerializable<T>(T[] array, int count = -1, int offset = 0) where T : INetworkSerializable
|
||||
{
|
||||
int sizeInTs = count != -1 ? count : array.Length - offset;
|
||||
WriteValueSafe(sizeInTs);
|
||||
WriteLengthSafe(sizeInTs);
|
||||
foreach (var item in array)
|
||||
{
|
||||
WriteNetworkSerializable(item);
|
||||
@@ -462,7 +462,7 @@ namespace Unity.Netcode
|
||||
public void WriteNetworkSerializable<T>(NativeArray<T> array, int count = -1, int offset = 0) where T : unmanaged, INetworkSerializable
|
||||
{
|
||||
int sizeInTs = count != -1 ? count : array.Length - offset;
|
||||
WriteValueSafe(sizeInTs);
|
||||
WriteLengthSafe(sizeInTs);
|
||||
foreach (var item in array)
|
||||
{
|
||||
WriteNetworkSerializable(item);
|
||||
@@ -480,7 +480,7 @@ namespace Unity.Netcode
|
||||
public void WriteNetworkSerializable<T>(NativeList<T> array, int count = -1, int offset = 0) where T : unmanaged, INetworkSerializable
|
||||
{
|
||||
int sizeInTs = count != -1 ? count : array.Length - offset;
|
||||
WriteValueSafe(sizeInTs);
|
||||
WriteLengthSafe(sizeInTs);
|
||||
foreach (var item in array)
|
||||
{
|
||||
WriteNetworkSerializable(item);
|
||||
@@ -495,7 +495,7 @@ namespace Unity.Netcode
|
||||
/// <param name="oneByteChars">Whether or not to use one byte per character. This will only allow ASCII</param>
|
||||
public unsafe void WriteValue(string s, bool oneByteChars = false)
|
||||
{
|
||||
WriteValue((uint)s.Length);
|
||||
WriteLength((uint)s.Length);
|
||||
int target = s.Length;
|
||||
if (oneByteChars)
|
||||
{
|
||||
@@ -538,7 +538,7 @@ namespace Unity.Netcode
|
||||
throw new OverflowException("Writing past the end of the buffer");
|
||||
}
|
||||
|
||||
WriteValue((uint)s.Length);
|
||||
WriteLength((uint)s.Length);
|
||||
int target = s.Length;
|
||||
if (oneByteChars)
|
||||
{
|
||||
@@ -569,7 +569,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
int sizeInTs = count != -1 ? count : array.Length - offset;
|
||||
int sizeInBytes = sizeInTs * sizeof(T);
|
||||
return sizeof(int) + sizeInBytes;
|
||||
return SizeOfLengthField() + sizeInBytes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -585,7 +585,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
int sizeInTs = count != -1 ? count : array.Length - offset;
|
||||
int sizeInBytes = sizeInTs * sizeof(T);
|
||||
return sizeof(int) + sizeInBytes;
|
||||
return SizeOfLengthField() + sizeInBytes;
|
||||
}
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
@@ -602,7 +602,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
int sizeInTs = count != -1 ? count : array.Length - offset;
|
||||
int sizeInBytes = sizeInTs * sizeof(T);
|
||||
return sizeof(int) + sizeInBytes;
|
||||
return SizeOfLengthField() + sizeInBytes;
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -876,7 +876,7 @@ namespace Unity.Netcode
|
||||
public static int GetWriteSize<T>(in T value)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
return value.Length + sizeof(int);
|
||||
return SizeOfLengthField() + value.Length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -888,10 +888,10 @@ namespace Unity.Netcode
|
||||
public static int GetWriteSize<T>(in NativeArray<T> value)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
var size = sizeof(int);
|
||||
var size = SizeOfLengthField();
|
||||
foreach (var item in value)
|
||||
{
|
||||
size += sizeof(int) + item.Length;
|
||||
size += SizeOfLengthField() + item.Length;
|
||||
}
|
||||
|
||||
return size;
|
||||
@@ -907,10 +907,10 @@ namespace Unity.Netcode
|
||||
public static int GetWriteSize<T>(in NativeList<T> value)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
var size = sizeof(int);
|
||||
var size = SizeOfLengthField();
|
||||
foreach (var item in value)
|
||||
{
|
||||
size += sizeof(int) + item.Length;
|
||||
size += SizeOfLengthField() + item.Length;
|
||||
}
|
||||
|
||||
return size;
|
||||
@@ -946,10 +946,32 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static int SizeOfLengthField() => sizeof(uint);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void WriteLengthSafe(uint length) => WriteUnmanagedSafe(length);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void WriteLength(uint length) => WriteUnmanaged(length);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void WriteLengthSafe(int length)
|
||||
{
|
||||
if (length < 0)
|
||||
{
|
||||
throw new InvalidCastException("Cannot write negative length");
|
||||
}
|
||||
WriteLengthSafe((uint)length);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void WriteLength(int length) => WriteLength((uint)length);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void WriteUnmanaged<T>(T[] value) where T : unmanaged
|
||||
{
|
||||
WriteUnmanaged(value.Length);
|
||||
WriteLength(value.Length);
|
||||
fixed (T* ptr = value)
|
||||
{
|
||||
byte* bytes = (byte*)ptr;
|
||||
@@ -959,7 +981,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void WriteUnmanagedSafe<T>(T[] value) where T : unmanaged
|
||||
{
|
||||
WriteUnmanagedSafe(value.Length);
|
||||
WriteLengthSafe(value.Length);
|
||||
fixed (T* ptr = value)
|
||||
{
|
||||
byte* bytes = (byte*)ptr;
|
||||
@@ -970,7 +992,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void WriteUnmanaged<T>(NativeArray<T> value) where T : unmanaged
|
||||
{
|
||||
WriteUnmanaged(value.Length);
|
||||
WriteLength(value.Length);
|
||||
var ptr = (T*)value.GetUnsafePtr();
|
||||
{
|
||||
byte* bytes = (byte*)ptr;
|
||||
@@ -980,7 +1002,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void WriteUnmanagedSafe<T>(NativeArray<T> value) where T : unmanaged
|
||||
{
|
||||
WriteUnmanagedSafe(value.Length);
|
||||
WriteLengthSafe(value.Length);
|
||||
var ptr = (T*)value.GetUnsafePtr();
|
||||
{
|
||||
byte* bytes = (byte*)ptr;
|
||||
@@ -992,7 +1014,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void WriteUnmanaged<T>(NativeList<T> value) where T : unmanaged
|
||||
{
|
||||
WriteUnmanaged(value.Length);
|
||||
WriteLength(value.Length);
|
||||
#if UTP_TRANSPORT_2_0_ABOVE
|
||||
var ptr = value.GetUnsafePtr();
|
||||
#else
|
||||
@@ -1006,7 +1028,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void WriteUnmanagedSafe<T>(NativeList<T> value) where T : unmanaged
|
||||
{
|
||||
WriteUnmanagedSafe(value.Length);
|
||||
WriteLengthSafe(value.Length);
|
||||
#if UTP_TRANSPORT_2_0_ABOVE
|
||||
var ptr = value.GetUnsafePtr();
|
||||
#else
|
||||
@@ -1210,9 +1232,9 @@ namespace Unity.Netcode
|
||||
internal void WriteValueSafe<T>(NativeHashSet<T> value) where T : unmanaged, IEquatable<T>
|
||||
{
|
||||
#if UTP_TRANSPORT_2_0_ABOVE
|
||||
WriteUnmanagedSafe(value.Count);
|
||||
WriteLengthSafe(value.Count);
|
||||
#else
|
||||
WriteUnmanagedSafe(value.Count());
|
||||
WriteLengthSafe(value.Count());
|
||||
#endif
|
||||
foreach (var item in value)
|
||||
{
|
||||
@@ -1227,9 +1249,9 @@ namespace Unity.Netcode
|
||||
where TVal : unmanaged
|
||||
{
|
||||
#if UTP_TRANSPORT_2_0_ABOVE
|
||||
WriteUnmanagedSafe(value.Count);
|
||||
WriteLengthSafe(value.Count);
|
||||
#else
|
||||
WriteUnmanagedSafe(value.Count());
|
||||
WriteLengthSafe(value.Count());
|
||||
#endif
|
||||
foreach (var item in value)
|
||||
{
|
||||
@@ -1765,7 +1787,8 @@ namespace Unity.Netcode
|
||||
public unsafe void WriteValue<T>(in T value, ForFixedStrings unused = default)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
WriteUnmanaged(value.Length);
|
||||
// BytePacker.WriteValuePacked(this, value.Length);
|
||||
WriteLength(value.Length);
|
||||
// This avoids a copy on the string, which could be costly for FixedString4096Bytes
|
||||
// Otherwise, GetUnsafePtr() is an impure function call and will result in a copy
|
||||
// for `in` parameters.
|
||||
@@ -1787,7 +1810,7 @@ namespace Unity.Netcode
|
||||
public void WriteValue<T>(T[] value, ForFixedStrings unused = default)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
WriteUnmanaged(value.Length);
|
||||
WriteLength(value.Length);
|
||||
foreach (var str in value)
|
||||
{
|
||||
WriteValue(str);
|
||||
@@ -1806,7 +1829,7 @@ namespace Unity.Netcode
|
||||
public void WriteValue<T>(in NativeArray<T> value, ForFixedStrings unused = default)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
WriteUnmanaged(value.Length);
|
||||
WriteLength(value.Length);
|
||||
foreach (var str in value)
|
||||
{
|
||||
WriteValue(str);
|
||||
@@ -1826,7 +1849,7 @@ namespace Unity.Netcode
|
||||
public void WriteValue<T>(in NativeList<T> value, ForFixedStrings unused = default)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
WriteUnmanaged(value.Length);
|
||||
WriteLength(value.Length);
|
||||
foreach (var str in value)
|
||||
{
|
||||
WriteValue(str);
|
||||
@@ -1848,7 +1871,7 @@ namespace Unity.Netcode
|
||||
public void WriteValueSafe<T>(in T value, ForFixedStrings unused = default)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
if (!TryBeginWriteInternal(sizeof(int) + value.Length))
|
||||
if (!TryBeginWriteInternal(SizeOfLengthField() + value.Length))
|
||||
{
|
||||
throw new OverflowException("Writing past the end of the buffer");
|
||||
}
|
||||
@@ -1871,7 +1894,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
throw new OverflowException("Writing past the end of the buffer");
|
||||
}
|
||||
WriteUnmanaged(value.Length);
|
||||
WriteLength(value.Length);
|
||||
foreach (var str in value)
|
||||
{
|
||||
WriteValue(str);
|
||||
@@ -1894,7 +1917,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
throw new OverflowException("Writing past the end of the buffer");
|
||||
}
|
||||
WriteUnmanaged(value.Length);
|
||||
WriteLength(value.Length);
|
||||
foreach (var str in value)
|
||||
{
|
||||
WriteValue(str);
|
||||
@@ -1918,7 +1941,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
throw new OverflowException("Writing past the end of the buffer");
|
||||
}
|
||||
WriteUnmanaged(value.Length);
|
||||
WriteLength(value.Length);
|
||||
foreach (var str in value)
|
||||
{
|
||||
WriteValue(str);
|
||||
|
||||
@@ -11,6 +11,8 @@ namespace Unity.Netcode
|
||||
{
|
||||
private NetworkObjectReference m_NetworkObjectReference;
|
||||
private ushort m_NetworkBehaviourId;
|
||||
private static ushort s_NullId = ushort.MaxValue;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new instance of the <see cref="NetworkBehaviourReference{T}"/> struct.
|
||||
@@ -21,7 +23,9 @@ namespace Unity.Netcode
|
||||
{
|
||||
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 @@ namespace Unity.Netcode
|
||||
[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);
|
||||
|
||||
@@ -10,6 +10,7 @@ namespace Unity.Netcode
|
||||
public struct NetworkObjectReference : INetworkSerializable, IEquatable<NetworkObjectReference>
|
||||
{
|
||||
private ulong m_NetworkObjectId;
|
||||
private static ulong s_NullId = ulong.MaxValue;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="NetworkObject.NetworkObjectId"/> of the referenced <see cref="NetworkObject"/>.
|
||||
@@ -30,7 +31,8 @@ namespace Unity.Netcode
|
||||
{
|
||||
if (networkObject == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(networkObject));
|
||||
m_NetworkObjectId = s_NullId;
|
||||
return;
|
||||
}
|
||||
|
||||
if (networkObject.IsSpawned == false)
|
||||
@@ -51,10 +53,16 @@ namespace Unity.Netcode
|
||||
{
|
||||
if (gameObject == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(gameObject));
|
||||
m_NetworkObjectId = s_NullId;
|
||||
return;
|
||||
}
|
||||
|
||||
var networkObject = gameObject.GetComponent<NetworkObject>();
|
||||
if (!networkObject)
|
||||
{
|
||||
throw new ArgumentException($"Cannot create {nameof(NetworkObjectReference)} from {nameof(GameObject)} without a {nameof(NetworkObject)} component.");
|
||||
}
|
||||
|
||||
var networkObject = gameObject.GetComponent<NetworkObject>() ?? 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 @@ namespace Unity.Netcode
|
||||
/// </summary>
|
||||
/// <param name="networkObjectRef">The reference.</param>
|
||||
/// <param name="networkManager">The networkmanager. Uses <see cref="NetworkManager.Singleton"/> to resolve if null.</param>
|
||||
/// <returns>The resolves <see cref="NetworkObject"/>. Returns null if the networkobject was not found</returns>
|
||||
/// <returns>The resolved <see cref="NetworkObject"/>. Returns null if the networkobject was not found</returns>
|
||||
[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);
|
||||
|
||||
|
||||
@@ -275,17 +275,17 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a list of all NetworkObjects that belong to a client.
|
||||
/// Returns an array of all NetworkObjects that belong to a client.
|
||||
/// </summary>
|
||||
/// <param name="clientId">the client's id <see cref="NetworkManager.LocalClientId"/></param>
|
||||
/// <returns>returns the list of <see cref="NetworkObject"/>s owned by the client</returns>
|
||||
public List<NetworkObject> GetClientOwnedObjects(ulong clientId)
|
||||
/// <param name="clientId">the client's id <see cref="NetworkManager.LocalClientId"/></param>
|
||||
/// <returns>returns an array of the <see cref="NetworkObject"/>s owned by the client</returns>
|
||||
public NetworkObject[] GetClientOwnedObjects(ulong clientId)
|
||||
{
|
||||
if (!OwnershipToObjectsTable.ContainsKey(clientId))
|
||||
{
|
||||
OwnershipToObjectsTable.Add(clientId, new Dictionary<ulong, NetworkObject>());
|
||||
}
|
||||
return OwnershipToObjectsTable[clientId].Values.ToList();
|
||||
return OwnershipToObjectsTable[clientId].Values.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
100
Runtime/Timing/AnticipationSystem.cs
Normal file
100
Runtime/Timing/AnticipationSystem.cs
Normal file
@@ -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<IAnticipatedObject> AllAnticipatedObjects = new HashSet<IAnticipatedObject>();
|
||||
|
||||
internal ulong AnticipationCounter;
|
||||
|
||||
private NetworkManager m_NetworkManager;
|
||||
|
||||
public HashSet<IAnticipatedObject> ObjectsToReanticipate = new HashSet<IAnticipatedObject>();
|
||||
|
||||
public AnticipationSystem(NetworkManager manager)
|
||||
{
|
||||
m_NetworkManager = manager;
|
||||
}
|
||||
|
||||
public event NetworkManager.ReanticipateDelegate OnReanticipate;
|
||||
|
||||
private HashSet<IAnticipationEventReceiver> m_AnticipationEventReceivers = new HashSet<IAnticipationEventReceiver>();
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Runtime/Timing/AnticipationSystem.cs.meta
Normal file
2
Runtime/Timing/AnticipationSystem.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4a75eccede7ecf1408f61dd55c338e06
|
||||
@@ -24,6 +24,11 @@ namespace Unity.Netcode
|
||||
/// </summary>
|
||||
public double TickOffset => m_CachedTickOffset;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the tick, including partial tick value passed since it started.
|
||||
/// </summary>
|
||||
public double TickWithPartial => Tick + (TickOffset / m_TickInterval);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current time. This is a non fixed time value and similar to <see cref="Time.time"/>.
|
||||
/// </summary>
|
||||
|
||||
@@ -5,7 +5,9 @@ namespace Unity.Netcode
|
||||
{
|
||||
/// <summary>
|
||||
/// <see cref="NetworkTimeSystem"/> 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.
|
||||
/// </summary>
|
||||
public class NetworkTimeSystem
|
||||
{
|
||||
|
||||
@@ -106,6 +106,22 @@ namespace Unity.Netcode
|
||||
/// </summary>
|
||||
/// /// <param name="networkManager">optionally pass in NetworkManager</param>
|
||||
public abstract void Initialize(NetworkManager networkManager = null);
|
||||
|
||||
protected virtual NetworkTopologyTypes OnCurrentTopology()
|
||||
{
|
||||
return NetworkTopologyTypes.ClientServer;
|
||||
}
|
||||
|
||||
internal NetworkTopologyTypes CurrentTopology()
|
||||
{
|
||||
return OnCurrentTopology();
|
||||
}
|
||||
}
|
||||
|
||||
public enum NetworkTopologyTypes
|
||||
{
|
||||
ClientServer,
|
||||
DistributedAuthority
|
||||
}
|
||||
|
||||
#if UNITY_INCLUDE_TESTS
|
||||
|
||||
@@ -1477,6 +1477,11 @@ namespace Unity.Netcode.Transports.UTP
|
||||
}
|
||||
#endif
|
||||
|
||||
protected override NetworkTopologyTypes OnCurrentTopology()
|
||||
{
|
||||
return NetworkManager != null ? NetworkManager.NetworkConfig.NetworkTopology : NetworkTopologyTypes.ClientServer;
|
||||
}
|
||||
|
||||
private string m_ServerPrivateKey;
|
||||
private string m_ServerCertificate;
|
||||
|
||||
|
||||
@@ -15,7 +15,13 @@
|
||||
"Unity.Burst",
|
||||
"Unity.Mathematics"
|
||||
],
|
||||
"includePlatforms": [],
|
||||
"excludePlatforms": [],
|
||||
"allowUnsafeCode": true,
|
||||
"overrideReferences": false,
|
||||
"precompiledReferences": [],
|
||||
"autoReferenced": true,
|
||||
"defineConstraints": [],
|
||||
"versionDefines": [
|
||||
{
|
||||
"name": "com.unity.multiplayer.tools",
|
||||
@@ -61,6 +67,12 @@
|
||||
"name": "com.unity.modules.physics2d",
|
||||
"expression": "",
|
||||
"define": "COM_UNITY_MODULES_PHYSICS2D"
|
||||
},
|
||||
{
|
||||
"name": "com.unity.services.multiplayer",
|
||||
"expression": "0.2.0",
|
||||
"define": "MULTIPLAYER_SERVICES_SDK_INSTALLED"
|
||||
}
|
||||
]
|
||||
],
|
||||
"noEngineReferences": false
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Random = UnityEngine.Random;
|
||||
|
||||
namespace Unity.Netcode.TestHelpers.Runtime
|
||||
{
|
||||
@@ -10,6 +11,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
public ulong FromClientId;
|
||||
public ArraySegment<byte> Payload;
|
||||
public NetworkEvent Event;
|
||||
public float AvailableTime;
|
||||
}
|
||||
|
||||
private static Dictionary<ulong, Queue<MessageData>> s_MessageQueue = new Dictionary<ulong, Queue<MessageData>>();
|
||||
@@ -18,21 +20,44 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
|
||||
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<byte> 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<byte>(copy, payload.Offset, payload.Count), Event = NetworkEvent.Data });
|
||||
s_MessageQueue[clientId].Enqueue(new MessageData
|
||||
{
|
||||
FromClientId = TransportId,
|
||||
Payload = new ArraySegment<byte>(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<byte> 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<byte>();
|
||||
receiveTime = 0;
|
||||
return NetworkEvent.Nothing;
|
||||
}
|
||||
|
||||
s_MessageQueue[TransportId].Dequeue();
|
||||
clientId = data.FromClientId;
|
||||
payload = data.Payload;
|
||||
receiveTime = NetworkManager.RealTimeProvider.RealTimeSinceStartup;
|
||||
@@ -81,9 +106,28 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
{
|
||||
}
|
||||
|
||||
protected override NetworkTopologyTypes OnCurrentTopology()
|
||||
{
|
||||
return NetworkManager != null ? NetworkManager.NetworkConfig.NetworkTopology : NetworkTopologyTypes.ClientServer;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -337,6 +337,15 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
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 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the server and clients
|
||||
/// </summary>
|
||||
@@ -1880,8 +1916,21 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
/// </summary>
|
||||
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 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
if (!string.IsNullOrEmpty(methodName))
|
||||
{
|
||||
#if UNITY_2023_1_OR_NEWER
|
||||
foreach (var behaviour in Object.FindObjectsByType<NetworkBehaviour>(FindObjectsSortMode.InstanceID))
|
||||
foreach (var obj in Object.FindObjectsByType<NetworkObject>(FindObjectsSortMode.InstanceID))
|
||||
#else
|
||||
foreach (var behaviour in Object.FindObjectsOfType<NetworkBehaviour>())
|
||||
foreach (var obj in Object.FindObjectsOfType<NetworkObject>())
|
||||
#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[] { });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ using NUnit.Framework;
|
||||
using Unity.Netcode.TestHelpers.Runtime;
|
||||
using UnityEngine;
|
||||
using UnityEngine.TestTools;
|
||||
using Object = UnityEngine.Object;
|
||||
|
||||
namespace Unity.Netcode.RuntimeTests
|
||||
{
|
||||
@@ -35,7 +36,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
|
||||
m_ServerManager.OnServerStopped += onServerStopped;
|
||||
m_ServerManager.Shutdown();
|
||||
UnityEngine.Object.DestroyImmediate(gameObject);
|
||||
Object.DestroyImmediate(gameObject);
|
||||
|
||||
yield return WaitUntilManagerShutsdown();
|
||||
|
||||
@@ -92,7 +93,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
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 @@ namespace Unity.Netcode.RuntimeTests
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -358,7 +358,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
|
||||
foreach (var clientNetworkManager in m_ClientNetworkManagers)
|
||||
{
|
||||
if (clientNetworkManager.LocalClient.OwnedObjects.Count < k_NumberOfSpawnedObjects)
|
||||
if (clientNetworkManager.LocalClient.OwnedObjects.Length < k_NumberOfSpawnedObjects)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -372,7 +372,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
// Only check when we are the host
|
||||
if (m_ServerNetworkManager.IsHost)
|
||||
{
|
||||
if (m_ServerNetworkManager.LocalClient.OwnedObjects.Count < k_NumberOfSpawnedObjects)
|
||||
if (m_ServerNetworkManager.LocalClient.OwnedObjects.Length < k_NumberOfSpawnedObjects)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -380,7 +380,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
|
||||
foreach (var connectedClient in m_ServerNetworkManager.ConnectedClients)
|
||||
{
|
||||
if (connectedClient.Value.OwnedObjects.Count < k_NumberOfSpawnedObjects)
|
||||
if (connectedClient.Value.OwnedObjects.Length < k_NumberOfSpawnedObjects)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
521
Tests/Runtime/NetworkTransformAnticipationTests.cs
Normal file
521
Tests/Runtime/NetworkTransformAnticipationTests.cs
Normal file
@@ -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<AnticipatedNetworkTransform>();
|
||||
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<AnticipatedNetworkTransform>();
|
||||
m_PlayerPrefab.AddComponent<NetworkTransformAnticipationComponent>();
|
||||
}
|
||||
|
||||
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<AnticipatedNetworkTransform>();
|
||||
}
|
||||
|
||||
public AnticipatedNetworkTransform GetServerComponent()
|
||||
{
|
||||
foreach (var obj in Object.FindObjectsByType<AnticipatedNetworkTransform>(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<AnticipatedNetworkTransform>(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<NetworkTransformAnticipationComponent>();
|
||||
rpcComponent.MoveRpc(new Vector3(2, 3, 4));
|
||||
|
||||
WaitForMessageReceivedWithTimeTravel<RpcMessage>(new List<NetworkManager> { 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<NetworkTransformAnticipationComponent>().ShouldSmooth = true;
|
||||
otherClientComponent.GetComponent<NetworkTransformAnticipationComponent>().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<NetworkTransformAnticipationComponent>();
|
||||
rpcComponent.MoveRpc(serverSetPosition);
|
||||
rpcComponent.RotateRpc(serverSetRotation);
|
||||
rpcComponent.ScaleRpc(serverSetScale);
|
||||
|
||||
WaitForMessagesReceivedWithTimeTravel(new List<Type>
|
||||
{
|
||||
typeof(RpcMessage),
|
||||
typeof(RpcMessage),
|
||||
typeof(RpcMessage),
|
||||
}, new List<NetworkManager> { m_ServerNetworkManager });
|
||||
|
||||
WaitForMessageReceivedWithTimeTravel<NetworkTransformMessage>(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<NetworkTransformAnticipationComponent>().ShouldMove = true;
|
||||
otherClientComponent.GetComponent<NetworkTransformAnticipationComponent>().ShouldMove = true;
|
||||
|
||||
var serverComponent = GetServerComponent();
|
||||
serverComponent.Interpolate = false;
|
||||
serverComponent.transform.position = new Vector3(0, 1, 2);
|
||||
var rpcComponent = testComponent.GetComponent<NetworkTransformAnticipationComponent>();
|
||||
rpcComponent.MoveRpc(new Vector3(0, 1, 2));
|
||||
|
||||
WaitForMessageReceivedWithTimeTravel<RpcMessage>(new List<NetworkManager> { m_ServerNetworkManager });
|
||||
|
||||
WaitForMessageReceivedWithTimeTravel<NetworkTransformMessage>(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<NetworkTransformAnticipationComponent>();
|
||||
rpcComponent.MoveRpc(new Vector3(1, 2, 3));
|
||||
|
||||
WaitForMessageReceivedWithTimeTravel<RpcMessage>(new List<NetworkManager> { 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<NetworkTransformAnticipationComponent>();
|
||||
rpcComponent.MoveRpc(new Vector3(1, 2, 3));
|
||||
|
||||
WaitForMessageReceivedWithTimeTravel<RpcMessage>(new List<NetworkManager> { 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Tests/Runtime/NetworkTransformAnticipationTests.cs.meta
Normal file
2
Tests/Runtime/NetworkTransformAnticipationTests.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ceb074b080c27184a9f669cd68355955
|
||||
420
Tests/Runtime/NetworkVariableAnticipationTests.cs
Normal file
420
Tests/Runtime/NetworkVariableAnticipationTests.cs
Normal file
@@ -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<int> SnapOnAnticipationFailVariable = new AnticipatedNetworkVariable<int>(0, StaleDataHandling.Ignore);
|
||||
public AnticipatedNetworkVariable<float> SmoothOnAnticipationFailVariable = new AnticipatedNetworkVariable<float>(0, StaleDataHandling.Reanticipate);
|
||||
public AnticipatedNetworkVariable<float> ReanticipateOnAnticipationFailVariable = new AnticipatedNetworkVariable<float>(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<NetworkVariableAnticipationComponent>();
|
||||
}
|
||||
|
||||
public NetworkVariableAnticipationComponent GetTestComponent()
|
||||
{
|
||||
return m_ClientNetworkManagers[0].LocalClient.PlayerObject.GetComponent<NetworkVariableAnticipationComponent>();
|
||||
}
|
||||
|
||||
public NetworkVariableAnticipationComponent GetServerComponent()
|
||||
{
|
||||
foreach (var obj in Object.FindObjectsByType<NetworkVariableAnticipationComponent>(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<NetworkVariableAnticipationComponent>(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<RpcMessage>(
|
||||
new List<NetworkManager> { 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<NetworkVariableDeltaMessage>(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<RpcMessage>(
|
||||
new List<NetworkManager> { 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<NetworkVariableDeltaMessage>(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<RpcMessage>(
|
||||
new List<NetworkManager> { 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<NetworkVariableDeltaMessage>(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<RpcMessage>(new List<NetworkManager> { m_ServerNetworkManager });
|
||||
|
||||
var serverComponent = GetServerComponent();
|
||||
|
||||
Assert.AreEqual(20, serverComponent.SnapOnAnticipationFailVariable.Value);
|
||||
Assert.AreEqual(20, serverComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
|
||||
|
||||
WaitForMessageReceivedWithTimeTravel<NetworkVariableDeltaMessage>(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<NetworkVariableDeltaMessage>(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<NetworkVariableDeltaMessage>(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);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Tests/Runtime/NetworkVariableAnticipationTests.cs.meta
Normal file
2
Tests/Runtime/NetworkVariableAnticipationTests.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 74e627a9d18dcd04e9c56ab2539a6593
|
||||
@@ -386,9 +386,12 @@ namespace Unity.Netcode.RuntimeTests
|
||||
|
||||
// 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<TestClass_ReferencedOnlyByTemplateNetworkBehaviourType>
|
||||
{
|
||||
|
||||
public bool Equals(TestClass_ReferencedOnlyByTemplateNetworkBehaviourType other)
|
||||
{
|
||||
return Equals((TestClass)other);
|
||||
}
|
||||
}
|
||||
|
||||
internal class NetworkVariableTest : NetworkBehaviour
|
||||
@@ -921,7 +924,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
m_Player1OnClient1.GetComponent<ClassHavingNetworkBehaviour2>().TheVar.Value.SomeInt == m_Player1OnServer.GetComponent<ClassHavingNetworkBehaviour2>().TheVar.Value.SomeInt;
|
||||
}
|
||||
|
||||
m_Player1OnServer.GetComponent<ClassHavingNetworkBehaviour2>().TheVar.Value = new TestClass_ReferencedOnlyByTemplateNetworkBehavourType { SomeInt = k_TestUInt, SomeBool = false };
|
||||
m_Player1OnServer.GetComponent<ClassHavingNetworkBehaviour2>().TheVar.Value = new TestClass_ReferencedOnlyByTemplateNetworkBehaviourType { SomeInt = k_TestUInt, SomeBool = false };
|
||||
m_Player1OnServer.GetComponent<ClassHavingNetworkBehaviour2>().TheVar.SetDirty(true);
|
||||
|
||||
// Wait for the client-side to notify it is finished initializing and spawning.
|
||||
|
||||
@@ -903,7 +903,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
}
|
||||
|
||||
// Please do not reference TestClass_ReferencedOnlyByTemplateNetworkBehavourType anywhere other than here!
|
||||
internal class ClassHavingNetworkBehaviour2 : TemplateNetworkBehaviourType<TestClass_ReferencedOnlyByTemplateNetworkBehavourType>
|
||||
internal class ClassHavingNetworkBehaviour2 : TemplateNetworkBehaviourType<TestClass_ReferencedOnlyByTemplateNetworkBehaviourType>
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
138
Tests/Runtime/NetworkVariableTraitsTests.cs
Normal file
138
Tests/Runtime/NetworkVariableTraitsTests.cs
Normal file
@@ -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<float> TheVariable = new NetworkVariable<float>();
|
||||
}
|
||||
|
||||
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<NetworkVariableTraitsComponent>();
|
||||
}
|
||||
|
||||
public NetworkVariableTraitsComponent GetTestComponent()
|
||||
{
|
||||
return m_ClientNetworkManagers[0].LocalClient.PlayerObject.GetComponent<NetworkVariableTraitsComponent>();
|
||||
}
|
||||
|
||||
public NetworkVariableTraitsComponent GetServerComponent()
|
||||
{
|
||||
foreach (var obj in Object.FindObjectsByType<NetworkVariableTraitsComponent>(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); ;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Tests/Runtime/NetworkVariableTraitsTests.cs.meta
Normal file
2
Tests/Runtime/NetworkVariableTraitsTests.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 49f46ca2b4327464498a7465891647bb
|
||||
@@ -112,6 +112,16 @@ namespace Unity.Netcode.RuntimeTests
|
||||
protected override IEnumerator OnSetup()
|
||||
{
|
||||
WorkingUserNetworkVariableComponentBase.Reset();
|
||||
|
||||
UserNetworkVariableSerialization<MyTypeOne>.WriteValue = null;
|
||||
UserNetworkVariableSerialization<MyTypeOne>.ReadValue = null;
|
||||
UserNetworkVariableSerialization<MyTypeOne>.DuplicateValue = null;
|
||||
UserNetworkVariableSerialization<MyTypeTwo>.WriteValue = null;
|
||||
UserNetworkVariableSerialization<MyTypeTwo>.ReadValue = null;
|
||||
UserNetworkVariableSerialization<MyTypeTwo>.DuplicateValue = null;
|
||||
UserNetworkVariableSerialization<MyTypeThree>.WriteValue = null;
|
||||
UserNetworkVariableSerialization<MyTypeThree>.ReadValue = null;
|
||||
UserNetworkVariableSerialization<MyTypeThree>.DuplicateValue = null;
|
||||
return base.OnSetup();
|
||||
}
|
||||
|
||||
@@ -217,5 +227,37 @@ namespace Unity.Netcode.RuntimeTests
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
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<T>,
|
||||
// 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<MyTypeOne>.WriteValue = (FastBufferWriter writer, in MyTypeOne value) => { };
|
||||
UserNetworkVariableSerialization<MyTypeOne>.ReadValue = (FastBufferReader reader, out MyTypeOne value) => { value = new MyTypeOne(); };
|
||||
UserNetworkVariableSerialization<MyTypeOne>.DuplicateValue = (in MyTypeOne value, ref MyTypeOne duplicatedValue) =>
|
||||
{
|
||||
duplicatedValue = value;
|
||||
};
|
||||
UserNetworkVariableSerialization<MyTypeTwo>.WriteValue = (FastBufferWriter writer, in MyTypeTwo value) => { };
|
||||
UserNetworkVariableSerialization<MyTypeTwo>.ReadValue = (FastBufferReader reader, out MyTypeTwo value) => { value = new MyTypeTwo(); };
|
||||
UserNetworkVariableSerialization<MyTypeTwo>.DuplicateValue = (in MyTypeTwo value, ref MyTypeTwo duplicatedValue) =>
|
||||
{
|
||||
duplicatedValue = value;
|
||||
};
|
||||
UserNetworkVariableSerialization<MyTypeThree>.WriteValue = (FastBufferWriter writer, in MyTypeThree value) => { };
|
||||
UserNetworkVariableSerialization<MyTypeThree>.ReadValue = (FastBufferReader reader, out MyTypeThree value) => { value = new MyTypeThree(); };
|
||||
UserNetworkVariableSerialization<MyTypeThree>.DuplicateValue = (in MyTypeThree value, ref MyTypeThree duplicatedValue) =>
|
||||
{
|
||||
duplicatedValue = value;
|
||||
};
|
||||
return base.OnTearDown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,8 @@ namespace Unity.Netcode.RuntimeTests
|
||||
{
|
||||
private class TestNetworkBehaviour : NetworkBehaviour
|
||||
{
|
||||
public static bool ReceivedRPC;
|
||||
|
||||
public NetworkVariable<NetworkBehaviourReference> TestVariable = new NetworkVariable<NetworkBehaviourReference>();
|
||||
|
||||
public TestNetworkBehaviour RpcReceivedBehaviour;
|
||||
@@ -25,6 +27,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
public void SendReferenceServerRpc(NetworkBehaviourReference value)
|
||||
{
|
||||
RpcReceivedBehaviour = (TestNetworkBehaviour)value;
|
||||
ReceivedRPC = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,8 +60,43 @@ namespace Unity.Netcode.RuntimeTests
|
||||
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<TestNetworkBehaviour>();
|
||||
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 @@ namespace Unity.Netcode.RuntimeTests
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FailSerializeNullBehaviour()
|
||||
{
|
||||
Assert.Throws<ArgumentNullException>(() =>
|
||||
{
|
||||
NetworkBehaviourReference outReference = null;
|
||||
});
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
//Stop, shutdown, and destroy
|
||||
|
||||
@@ -19,6 +19,8 @@ namespace Unity.Netcode.RuntimeTests
|
||||
{
|
||||
private class TestNetworkBehaviour : NetworkBehaviour
|
||||
{
|
||||
public static bool ReceivedRPC;
|
||||
|
||||
public NetworkVariable<NetworkObjectReference> TestVariable = new NetworkVariable<NetworkObjectReference>();
|
||||
|
||||
public NetworkObject RpcReceivedNetworkObject;
|
||||
@@ -28,6 +30,7 @@ namespace Unity.Netcode.RuntimeTests
|
||||
[ServerRpc]
|
||||
public void SendReferenceServerRpc(NetworkObjectReference value)
|
||||
{
|
||||
ReceivedRPC = true;
|
||||
RpcReceivedGameObject = value;
|
||||
RpcReceivedNetworkObject = value;
|
||||
}
|
||||
@@ -150,6 +153,60 @@ namespace Unity.Netcode.RuntimeTests
|
||||
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<TestNetworkBehaviour>();
|
||||
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 @@ namespace Unity.Netcode.RuntimeTests
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FailSerializeNullNetworkObject()
|
||||
{
|
||||
Assert.Throws<ArgumentNullException>(() =>
|
||||
{
|
||||
NetworkObjectReference outReference = (NetworkObject)null;
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FailSerializeNullGameObject()
|
||||
{
|
||||
Assert.Throws<ArgumentNullException>(() =>
|
||||
{
|
||||
NetworkObjectReference outReference = (GameObject)null;
|
||||
});
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
//Stop, shutdown, and destroy
|
||||
|
||||
@@ -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-exp.5",
|
||||
"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": "### Fixed\n\n- Fixed issue where SessionOwner message was being treated as a new entry for the new message indexing when it should have been ordinally sorted with the legacy message indices. (#2942)"
|
||||
"changelog": "### Added\n\n- Added `AnticipatedNetworkVariable<T>`, 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<T>` with the callback `NetworkVariable<T>.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": "a38ece4dabc6c27e6618262e980d5de89bbda2e8"
|
||||
"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": "79e8fc8634b961f05fbc3f79e82d57c8f131c715"
|
||||
"revision": "2ecbd14351cac29ab3a18cc159c0a82513e9d241"
|
||||
},
|
||||
"samples": [
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user