From ed38a4dcc25e964dec031398a6b3c4bf945b79a8 Mon Sep 17 00:00:00 2001
From: Unity Technologies <@unity>
Date: Mon, 17 Jun 2024 00:00:00 +0000
Subject: [PATCH] com.unity.netcode.gameobjects@2.0.0-pre.1 The format is based
on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project
adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).
## [2.0.0-pre.1] - 2024-06-17
### Added
- 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 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)
---
CHANGELOG.md | 28 +
Components.meta | 8 -
Editor/CodeGen/NetworkBehaviourILPP.cs | 58 +-
Editor/NetworkManagerEditor.cs | 37 +-
Editor/NetworkObjectEditor.cs | 4 +-
Editor/NetworkTransformEditor.cs | 11 +-
Editor/com.unity.netcode.editor.asmdef | 2 +-
Runtime/Components/NetworkRigidBodyBase.cs | 142 ++
Runtime/Components/NetworkTransform.cs | 95 +-
Runtime/Connection/NetworkClient.cs | 11 +-
.../Connection/NetworkConnectionManager.cs | 3 +
Runtime/Core/NetworkManager.cs | 65 +-
Runtime/Core/NetworkObject.cs | 2 +-
.../Messages/ConnectionApprovedMessage.cs | 18 +
.../Messages/NetworkTransformMessage.cs | 5 +-
Runtime/Messaging/NetworkMessageManager.cs | 18 +-
.../Messaging/RpcTargets/EveryoneRpcTarget.cs | 18 +-
.../NetworkVariableSerialization.cs | 2065 -----------------
.../NetworkVariableSerialization.cs.meta | 3 -
Runtime/NetworkVariable/Serialization.meta | 3 +
.../CollectionSerializationUtility.cs | 0
.../CollectionSerializationUtility.cs.meta | 0
.../Serialization/FallbackSerializer.cs | 99 +
.../Serialization/FallbackSerializer.cs.meta | 3 +
.../INetworkVariableSerializer.cs | 26 +
.../INetworkVariableSerializer.cs.meta | 3 +
.../Serialization/NetworkVariableEquality.cs | 357 +++
.../NetworkVariableEquality.cs.meta | 3 +
.../NetworkVariableSerialization.cs | 161 ++
.../NetworkVariableSerialization.cs.meta | 3 +
.../{ => Serialization}/ResizableBitVector.cs | 0
.../ResizableBitVector.cs.meta | 0
.../Serialization/TypedILPPInitializers.cs | 325 +++
.../TypedILPPInitializers.cs.meta | 3 +
.../TypedSerializerImplementations.cs | 1120 +++++++++
.../TypedSerializerImplementations.cs.meta | 3 +
.../UserNetworkVariableSerialization.cs | 73 +
.../UserNetworkVariableSerialization.cs.meta | 3 +
Runtime/Serialization/FastBufferReader.cs | 71 +-
Runtime/Serialization/FastBufferWriter.cs | 87 +-
Runtime/Spawning/NetworkSpawnManager.cs | 10 +-
Runtime/Transports/NetworkTransport.cs | 16 +
Runtime/Transports/UTP/UnityTransport.cs | 5 +
Runtime/com.unity.netcode.runtime.asmdef | 16 +-
TestHelpers/Runtime/MockTransport.cs | 5 +
.../NetworkObjectOwnershipTests.cs | 6 +-
package.json | 8 +-
47 files changed, 2756 insertions(+), 2246 deletions(-)
delete mode 100644 Components.meta
delete mode 100644 Runtime/NetworkVariable/NetworkVariableSerialization.cs
delete mode 100644 Runtime/NetworkVariable/NetworkVariableSerialization.cs.meta
create mode 100644 Runtime/NetworkVariable/Serialization.meta
rename Runtime/NetworkVariable/{ => Serialization}/CollectionSerializationUtility.cs (100%)
rename Runtime/NetworkVariable/{ => Serialization}/CollectionSerializationUtility.cs.meta (100%)
create mode 100644 Runtime/NetworkVariable/Serialization/FallbackSerializer.cs
create mode 100644 Runtime/NetworkVariable/Serialization/FallbackSerializer.cs.meta
create mode 100644 Runtime/NetworkVariable/Serialization/INetworkVariableSerializer.cs
create mode 100644 Runtime/NetworkVariable/Serialization/INetworkVariableSerializer.cs.meta
create mode 100644 Runtime/NetworkVariable/Serialization/NetworkVariableEquality.cs
create mode 100644 Runtime/NetworkVariable/Serialization/NetworkVariableEquality.cs.meta
create mode 100644 Runtime/NetworkVariable/Serialization/NetworkVariableSerialization.cs
create mode 100644 Runtime/NetworkVariable/Serialization/NetworkVariableSerialization.cs.meta
rename Runtime/NetworkVariable/{ => Serialization}/ResizableBitVector.cs (100%)
rename Runtime/NetworkVariable/{ => Serialization}/ResizableBitVector.cs.meta (100%)
create mode 100644 Runtime/NetworkVariable/Serialization/TypedILPPInitializers.cs
create mode 100644 Runtime/NetworkVariable/Serialization/TypedILPPInitializers.cs.meta
create mode 100644 Runtime/NetworkVariable/Serialization/TypedSerializerImplementations.cs
create mode 100644 Runtime/NetworkVariable/Serialization/TypedSerializerImplementations.cs.meta
create mode 100644 Runtime/NetworkVariable/Serialization/UserNetworkVariableSerialization.cs
create mode 100644 Runtime/NetworkVariable/Serialization/UserNetworkVariableSerialization.cs.meta
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 02c15ec..5909e66 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,12 +6,40 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).
+## [2.0.0-pre.1] - 2024-06-17
+
+### Added
+
+- 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 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
diff --git a/Components.meta b/Components.meta
deleted file mode 100644
index d4eb0da..0000000
--- a/Components.meta
+++ /dev/null
@@ -1,8 +0,0 @@
-fileFormatVersion: 2
-guid: 8b267eb841a574dc083ac248a95d4443
-folderAsset: yes
-DefaultImporter:
- externalObjects: {}
- userData:
- assetBundleName:
- assetBundleVariant:
diff --git a/Editor/CodeGen/NetworkBehaviourILPP.cs b/Editor/CodeGen/NetworkBehaviourILPP.cs
index f750f78..fb583e2 100644
--- a/Editor/CodeGen/NetworkBehaviourILPP.cs
+++ b/Editor/CodeGen/NetworkBehaviourILPP.cs
@@ -721,7 +721,7 @@ private bool ImportReferences(ModuleDefinition moduleDefinition, string[] assemb
continue;
}
- if (networkVariableSerializationTypesTypeDef == null && netcodeTypeDef.Name == nameof(NetworkVariableSerializationTypes))
+ if (networkVariableSerializationTypesTypeDef == null && netcodeTypeDef.Name == nameof(NetworkVariableSerializationTypedInitializers))
{
networkVariableSerializationTypesTypeDef = netcodeTypeDef;
continue;
@@ -1007,103 +1007,103 @@ private bool ImportReferences(ModuleDefinition moduleDefinition, string[] assemb
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;
}
diff --git a/Editor/NetworkManagerEditor.cs b/Editor/NetworkManagerEditor.cs
index f420592..0db3a65 100644
--- a/Editor/NetworkManagerEditor.cs
+++ b/Editor/NetworkManagerEditor.cs
@@ -30,7 +30,7 @@ public class NetworkManagerEditor : UnityEditor.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 @@ private void Initialize()
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 @@ private void CheckNullProperties()
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 @@ public override void OnInspectorGUI()
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,21 +310,32 @@ public override void OnInspectorGUI()
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 Server", "Starts a server instance" + buttonDisabledReasonSuffix)))
+ {
+ m_NetworkManager.StartServer();
+ }
- if (GUILayout.Button(new GUIContent("Start Client", "Starts a client instance" + buttonDisabledReasonSuffix)))
+ if (GUILayout.Button(new GUIContent("Start Client", "Starts a client instance" + buttonDisabledReasonSuffix)))
+ {
+ m_NetworkManager.StartClient();
+ }
+ }
+ else
{
- m_NetworkManager.StartClient();
+ if (GUILayout.Button(new GUIContent("Start Client", "Starts a distributed authority client instance" + buttonDisabledReasonSuffix)))
+ {
+ m_NetworkManager.StartClient();
+ }
}
+
if (!EditorApplication.isPlaying)
{
GUI.enabled = true;
diff --git a/Editor/NetworkObjectEditor.cs b/Editor/NetworkObjectEditor.cs
index 9975482..ef6ea58 100644
--- a/Editor/NetworkObjectEditor.cs
+++ b/Editor/NetworkObjectEditor.cs
@@ -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 @@ private void OnDestroy()
// 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
{
diff --git a/Editor/NetworkTransformEditor.cs b/Editor/NetworkTransformEditor.cs
index 4e7831d..0dbab88 100644
--- a/Editor/NetworkTransformEditor.cs
+++ b/Editor/NetworkTransformEditor.cs
@@ -30,6 +30,7 @@ public class NetworkTransformEditor : UnityEditor.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 @@ public class NetworkTransformEditor : UnityEditor.Editor
private static GUIContent s_ScaleLabel = EditorGUIUtility.TrTextContent("Scale");
///
- public void OnEnable()
+ public virtual void OnEnable()
{
m_UseUnreliableDeltas = serializedObject.FindProperty(nameof(NetworkTransform.UseUnreliableDeltas));
m_SyncPositionXProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionX));
@@ -59,12 +60,13 @@ public void OnEnable()
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));
}
///
public override void OnInspectorGUI()
{
- EditorGUILayout.LabelField("Syncing", EditorStyles.boldLabel);
+ EditorGUILayout.LabelField("Axis to Synchronize", EditorStyles.boldLabel);
{
GUILayout.BeginHorizontal();
@@ -126,6 +128,11 @@ public override void OnInspectorGUI()
GUILayout.EndHorizontal();
}
+ EditorGUILayout.Space();
+ EditorGUILayout.LabelField("Authority", EditorStyles.boldLabel);
+ {
+ EditorGUILayout.PropertyField(m_AuthorityMode);
+ }
EditorGUILayout.Space();
EditorGUILayout.LabelField("Thresholds", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_PositionThresholdProperty);
diff --git a/Editor/com.unity.netcode.editor.asmdef b/Editor/com.unity.netcode.editor.asmdef
index fb85b90..e80328c 100644
--- a/Editor/com.unity.netcode.editor.asmdef
+++ b/Editor/com.unity.netcode.editor.asmdef
@@ -57,7 +57,7 @@
{
"name": "com.unity.services.multiplayer",
"expression": "0.2.0",
- "define": "MULTIPLAYER_SDK_INSTALLED"
+ "define": "MULTIPLAYER_SERVICES_SDK_INSTALLED"
}
],
"noEngineReferences": false
diff --git a/Runtime/Components/NetworkRigidBodyBase.cs b/Runtime/Components/NetworkRigidBodyBase.cs
index c2a24eb..17ebaf7 100644
--- a/Runtime/Components/NetworkRigidBodyBase.cs
+++ b/Runtime/Components/NetworkRigidBodyBase.cs
@@ -45,6 +45,9 @@ public abstract class NetworkRigidbodyBase : NetworkBehaviour
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 @@ protected void Initialize(RigidbodyTypes rigidbodyType, NetworkTransform network
}
}
+ 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;
+ }
+
+ ///
+ /// Sets the linear velocity of the Rigidbody.
+ ///
+ ///
+ /// For , only the x and y components of the are applied.
+ ///
+ public void SetLinearVelocity(Vector3 linearVelocity)
+ {
+ if (m_IsRigidbody2D)
+ {
+ m_Rigidbody2D.velocity = linearVelocity;
+ }
+ else
+ {
+ m_Rigidbody.linearVelocity = linearVelocity;
+ }
+ }
+
+ ///
+ /// Gets the linear velocity of the Rigidbody.
+ ///
+ ///
+ /// For , the velocity returned is only applied to the x and y components.
+ ///
+ /// as the linear velocity
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Vector3 GetLinearVelocity()
+ {
+ if (m_IsRigidbody2D)
+ {
+ return m_Rigidbody2D.velocity;
+ }
+ else
+ {
+ return m_Rigidbody.linearVelocity;
+ }
+ }
+
+ ///
+ /// Sets the angular velocity for the Rigidbody.
+ ///
+ ///
+ /// For , the z component of is only used to set the angular velocity.
+ /// A quick way to pass in a 2D angular velocity component is: * angularVelocity (where angularVelocity is a float)
+ ///
+ /// the angular velocity to apply to the body
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public void SetAngularVelocity(Vector3 angularVelocity)
+ {
+ if (m_IsRigidbody2D)
+ {
+ m_Rigidbody2D.angularVelocity = angularVelocity.z;
+ }
+ else
+ {
+ m_Rigidbody.angularVelocity = angularVelocity;
+ }
+ }
+
+ ///
+ /// Gets the angular velocity for the Rigidbody.
+ ///
+ ///
+ /// For , the z component of the returned is the angular velocity of the object.
+ ///
+ /// angular velocity as a
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Vector3 GetAngularVelocity()
+ {
+ if (m_IsRigidbody2D)
+ {
+ return Vector3.forward * m_Rigidbody2D.velocity;
+ }
+ else
+ {
+ return m_Rigidbody.angularVelocity;
+ }
+ }
+
///
/// Gets the position of the Rigidbody
///
@@ -210,6 +336,9 @@ public void ApplyCurrentTransform()
}
}
+ // Used for Rigidbody only (see info on normalized below)
+ private Vector4 m_QuaternionCheck = Vector4.zero;
+
///
/// Rotatates the Rigidbody towards a specified rotation
///
@@ -227,6 +356,17 @@ public void MoveRotation(Quaternion rotation)
}
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 @@ internal void UpdateOwnershipAuthority()
///
public override void OnNetworkSpawn()
{
+ m_TickFrequency = 1.0f / NetworkManager.NetworkConfig.TickRate;
+ m_TickRate = NetworkManager.NetworkConfig.TickRate;
UpdateOwnershipAuthority();
}
diff --git a/Runtime/Components/NetworkTransform.cs b/Runtime/Components/NetworkTransform.cs
index 5635194..db3e9b8 100644
--- a/Runtime/Components/NetworkTransform.cs
+++ b/Runtime/Components/NetworkTransform.cs
@@ -920,6 +920,22 @@ public void NetworkSerialize(BufferSerializer serializer) where T : IReade
#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;
+
///
/// The default position change threshold value.
/// Any changes above this threshold will be replicated.
@@ -1487,7 +1503,7 @@ protected override void OnSynchronize(ref BufferSerializer serializer)
///
/// the transform to be committed
/// time it was marked dirty
- protected void TryCommitTransformToServer(Transform transformToCommit, double dirtyTime)
+ internal void TryCommitTransformToServer(Transform transformToCommit, double dirtyTime)
{
if (!IsSpawned)
{
@@ -1568,8 +1584,6 @@ private void TryCommitTransform(ref Transform transformToCommit, bool synchroniz
// 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 +1713,20 @@ private bool CheckForStateChange(ref NetworkTransformState networkState, ref Tra
#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 +1853,21 @@ private bool CheckForStateChange(ref NetworkTransformState networkState, ref Tra
// 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 +1888,7 @@ private bool CheckForStateChange(ref NetworkTransformState networkState, ref Tra
{
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 +1983,21 @@ private bool CheckForStateChange(ref NetworkTransformState networkState, ref Tra
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 +2014,7 @@ private bool CheckForStateChange(ref NetworkTransformState networkState, ref Tra
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;
@@ -2984,7 +3009,13 @@ private void InternalInitialization(bool isOwnershipChange = false)
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 +3042,24 @@ private void InternalInitialization(bool isOwnershipChange = false)
#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 +3071,13 @@ private void InternalInitialization(bool isOwnershipChange = false)
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 +3326,7 @@ private void UpdateInterpolation()
{
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 +3344,7 @@ private void UpdateInterpolation()
//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 +3418,32 @@ public virtual void OnFixedUpdate()
#endif
///
- /// Override this method and return false to switch to owner authoritative mode
+ /// Determines whether the is or based on the property.
+ /// You can override this method to control this logic.
///
- /// ( or ) where when false it runs as owner-client authoritative
+ /// or
protected virtual bool OnIsServerAuthoritative()
{
- if (m_CachedNetworkManager)
- {
- return !m_CachedNetworkManager.DistributedAuthorityMode;
- }
- return true;
+ return AuthorityMode == AuthorityModes.Server;
}
///
/// Method to determine if this instance is owner or server authoritative.
///
///
- /// Used by to determines if this is server or owner authoritative.
+ /// When using a , this will always be viewed as a authoritative motion model.
///
/// or
public bool IsServerAuthoritative()
{
- return OnIsServerAuthoritative();
+ if (m_CachedNetworkManager && m_CachedNetworkManager.DistributedAuthorityMode)
+ {
+ return false;
+ }
+ else
+ {
+ return OnIsServerAuthoritative();
+ }
}
#endregion
@@ -3451,9 +3485,10 @@ internal void TransformStateUpdate(ulong senderId)
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 +3505,7 @@ internal void SerializeMessage(FastBufferWriter writer, int targetVersion)
BytePacker.WriteValuePacked(writer, targetId);
}
}
+ return writer.Position - position;
}
///
@@ -3482,7 +3518,7 @@ private void UpdateTransformState()
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 +3562,7 @@ private void UpdateTransformState()
// 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
diff --git a/Runtime/Connection/NetworkClient.cs b/Runtime/Connection/NetworkClient.cs
index 8cee4e0..ff6ed61 100644
--- a/Runtime/Connection/NetworkClient.cs
+++ b/Runtime/Connection/NetworkClient.cs
@@ -1,15 +1,8 @@
-using System.Collections.Generic;
using UnityEngine;
namespace Unity.Netcode
{
- public enum NetworkTopologyTypes
- {
- ClientServer,
- DistributedAuthority
- }
-
///
/// A NetworkClient
///
@@ -61,9 +54,9 @@ public class NetworkClient
public NetworkObject PlayerObject;
///
- /// The list of NetworkObject's owned by this client instance
+ /// The NetworkObject's owned by this client instance
///
- public List OwnedObjects => IsConnected ? SpawnManager.GetClientOwnedObjects(ClientId) : new List();
+ public NetworkObject[] OwnedObjects => IsConnected ? SpawnManager.GetClientOwnedObjects(ClientId) : new NetworkObject[] { };
internal NetworkSpawnManager SpawnManager { get; private set; }
diff --git a/Runtime/Connection/NetworkConnectionManager.cs b/Runtime/Connection/NetworkConnectionManager.cs
index cb19efe..722fbb2 100644
--- a/Runtime/Connection/NetworkConnectionManager.cs
+++ b/Runtime/Connection/NetworkConnectionManager.cs
@@ -1229,6 +1229,8 @@ internal void OnClientDisconnectFromServer(ulong clientId)
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 @@ internal void OnClientDisconnectFromServer(ulong clientId)
MessageManager?.SendMessage(ref sessionOwnerMessage, NetworkDelivery.ReliableFragmentedSequenced, ConnectedClientIds);
NetworkManager.SetSessionOwner(newSessionOwner);
}
+#endif
}
// If the client ID transport map exists
diff --git a/Runtime/Core/NetworkManager.cs b/Runtime/Core/NetworkManager.cs
index 340eced..b956cfa 100644
--- a/Runtime/Core/NetworkManager.cs
+++ b/Runtime/Core/NetworkManager.cs
@@ -36,17 +36,13 @@ public class NetworkManager : MonoBehaviour, INetworkUpdateSystem
#pragma warning restore IDE1006 // restore naming rule violation check
+ internal static bool IsDistributedAuthority;
+
///
/// Distributed Authority Mode
/// Returns true if the current session is running in distributed authority mode.
///
- public bool DistributedAuthorityMode
- {
- get
- {
- return NetworkConfig.NetworkTopology == NetworkTopologyTypes.DistributedAuthority;
- }
- }
+ public bool DistributedAuthorityMode { get; private set; }
///
/// Distributed Authority Mode
@@ -131,6 +127,18 @@ public bool DAHost
public ulong CurrentSessionOwner { get; internal set; }
+ ///
+ /// Delegate declaration for
+ ///
+ /// the new session owner client identifier
+ public delegate void OnSessionOwnerPromotedDelegateHandler(ulong sessionOwnerPromoted);
+
+ ///
+ /// Network Topology: Distributed Authority
+ /// When a new session owner is promoted, this event is triggered on all connected clients
+ ///
+ public event OnSessionOwnerPromotedDelegateHandler OnSessionOwnerPromoted;
+
internal void SetSessionOwner(ulong sessionOwner)
{
var previousSessionOwner = CurrentSessionOwner;
@@ -151,10 +159,12 @@ internal void SetSessionOwner(ulong sessionOwner)
}
}
}
+
+ OnSessionOwnerPromoted?.Invoke(sessionOwner);
}
// TODO: Make this internal after testing
- public void PromoteSessionOwner(ulong clientId)
+ internal void PromoteSessionOwner(ulong clientId)
{
if (!DistributedAuthorityMode)
{
@@ -217,12 +227,27 @@ internal void NetworkTransformRegistration(NetworkTransform networkTransform, bo
#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();
@@ -1012,6 +1037,8 @@ internal void Initialize(bool server)
#endif
NetworkTransformUpdate.Clear();
+ UpdateTopology();
+
//DANGOEXP TODO: Remove this before finalizing the experimental release
NetworkConfig.AutoSpawnPlayerPrefabClientSide = DistributedAuthorityMode;
@@ -1191,6 +1218,17 @@ public bool StartServer()
{
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 +1375,17 @@ private void HostServerInitialize()
}
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();
diff --git a/Runtime/Core/NetworkObject.cs b/Runtime/Core/NetworkObject.cs
index 3e7ae26..b927722 100644
--- a/Runtime/Core/NetworkObject.cs
+++ b/Runtime/Core/NetworkObject.cs
@@ -430,7 +430,7 @@ public void DeferDespawn(int tickOffset, bool destroy = true)
/// Determines whether a NetworkObject can be distributed to other clients during
/// a session.
///
-#if !MULTIPLAYER_SDK_INSTALLED
+#if !MULTIPLAYER_SERVICES_SDK_INSTALLED
[HideInInspector]
#endif
[SerializeField]
diff --git a/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs b/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs
index 89eee0c..82eef24 100644
--- a/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs
+++ b/Runtime/Messaging/Messages/ConnectionApprovedMessage.cs
@@ -243,6 +243,13 @@ public void Handle(ref NetworkContext context)
// 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 @@ public void Handle(ref NetworkContext context)
// 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);
}
}
}
diff --git a/Runtime/Messaging/Messages/NetworkTransformMessage.cs b/Runtime/Messaging/Messages/NetworkTransformMessage.cs
index 3fbd869..56f25f2 100644
--- a/Runtime/Messaging/Messages/NetworkTransformMessage.cs
+++ b/Runtime/Messaging/Messages/NetworkTransformMessage.cs
@@ -17,6 +17,8 @@ internal struct NetworkTransformMessage : INetworkMessage
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 @@ public void Serialize(FastBufferWriter writer, int targetVersion)
}
else
{
- NetworkTransform.SerializeMessage(writer, targetVersion);
+ BytesWritten = NetworkTransform.SerializeMessage(writer, targetVersion);
}
}
@@ -75,6 +77,7 @@ public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int
ownerAuthoritativeServerSide = !isServerAuthoritative && networkManager.IsServer;
reader.ReadNetworkSerializableInPlace(ref NetworkTransform.InboundState);
+ NetworkTransform.InboundState.LastSerializedSize = reader.Position - currentPosition;
}
else
{
diff --git a/Runtime/Messaging/NetworkMessageManager.cs b/Runtime/Messaging/NetworkMessageManager.cs
index b455c9b..d42251e 100644
--- a/Runtime/Messaging/NetworkMessageManager.cs
+++ b/Runtime/Messaging/NetworkMessageManager.cs
@@ -34,6 +34,9 @@ public InvalidMessageStructureException(string issue) : base(issue)
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 @@ internal void CleanupDisconnectedClients()
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 @@ internal int GetMessageVersion(Type type, ulong clientId, bool forReceive = fals
return messageVersion;
}
+
+
public static void ReceiveMessage(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 @@ internal int SendMessage(ref TMessageType messa
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 @@ internal unsafe int SendPreSerializedMessage(in FastBufferWriter t
// 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 @@ internal unsafe int SendPreSerializedMessage(in FastBufferWriter t
// 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)
diff --git a/Runtime/Messaging/RpcTargets/EveryoneRpcTarget.cs b/Runtime/Messaging/RpcTargets/EveryoneRpcTarget.cs
index b0ae738..7b2089f 100644
--- a/Runtime/Messaging/RpcTargets/EveryoneRpcTarget.cs
+++ b/Runtime/Messaging/RpcTargets/EveryoneRpcTarget.cs
@@ -4,23 +4,37 @@ internal class EveryoneRpcTarget : BaseRpcTarget
{
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);
}
}
}
diff --git a/Runtime/NetworkVariable/NetworkVariableSerialization.cs b/Runtime/NetworkVariable/NetworkVariableSerialization.cs
deleted file mode 100644
index df7c3b9..0000000
--- a/Runtime/NetworkVariable/NetworkVariableSerialization.cs
+++ /dev/null
@@ -1,2065 +0,0 @@
-using System;
-using System.Collections.Generic;
-using Unity.Collections;
-using Unity.Collections.LowLevel.Unsafe;
-using Unity.Mathematics;
-using UnityEditor;
-using UnityEngine;
-
-namespace Unity.Netcode
-{
- ///
- /// Interface used by NetworkVariables to serialize them
- ///
- ///
- internal interface INetworkVariableSerializer
- {
- // 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);
- }
-
- ///
- /// Packing serializer for shorts
- ///
- internal class ShortSerializer : INetworkVariableSerializer
- {
- public void Write(FastBufferWriter writer, ref short value)
- {
- BytePacker.WriteValueBitPacked(writer, value);
- }
- public void Read(FastBufferReader reader, ref short value)
- {
- ByteUnpacker.ReadValueBitPacked(reader, out value);
- }
-
- public void WriteDelta(FastBufferWriter writer, ref short value, ref short previousValue)
- {
- Write(writer, ref value);
- }
- public void ReadDelta(FastBufferReader reader, ref short value)
- {
- Read(reader, ref value);
- }
-
- void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out short value, Allocator allocator)
- {
- throw new NotImplementedException();
- }
-
- public void Duplicate(in short value, ref short duplicatedValue)
- {
- duplicatedValue = value;
- }
- }
-
- ///
- /// Packing serializer for shorts
- ///
- internal class UshortSerializer : INetworkVariableSerializer
- {
- public void Write(FastBufferWriter writer, ref ushort value)
- {
- BytePacker.WriteValueBitPacked(writer, value);
- }
- public void Read(FastBufferReader reader, ref ushort value)
- {
- ByteUnpacker.ReadValueBitPacked(reader, out value);
- }
-
- public void WriteDelta(FastBufferWriter writer, ref ushort value, ref ushort previousValue)
- {
- Write(writer, ref value);
- }
- public void ReadDelta(FastBufferReader reader, ref ushort value)
- {
- Read(reader, ref value);
- }
-
- void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out ushort value, Allocator allocator)
- {
- throw new NotImplementedException();
- }
-
- public void Duplicate(in ushort value, ref ushort duplicatedValue)
- {
- duplicatedValue = value;
- }
- }
-
- ///
- /// Packing serializer for ints
- ///
- internal class IntSerializer : INetworkVariableSerializer
- {
- public void Write(FastBufferWriter writer, ref int value)
- {
- BytePacker.WriteValueBitPacked(writer, value);
- }
- public void Read(FastBufferReader reader, ref int value)
- {
- ByteUnpacker.ReadValueBitPacked(reader, out value);
- }
-
- public void WriteDelta(FastBufferWriter writer, ref int value, ref int previousValue)
- {
- Write(writer, ref value);
- }
- public void ReadDelta(FastBufferReader reader, ref int value)
- {
- Read(reader, ref value);
- }
-
- void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out int value, Allocator allocator)
- {
- throw new NotImplementedException();
- }
-
- public void Duplicate(in int value, ref int duplicatedValue)
- {
- duplicatedValue = value;
- }
- }
-
- ///
- /// Packing serializer for ints
- ///
- internal class UintSerializer : INetworkVariableSerializer
- {
- public void Write(FastBufferWriter writer, ref uint value)
- {
- BytePacker.WriteValueBitPacked(writer, value);
- }
- public void Read(FastBufferReader reader, ref uint value)
- {
- ByteUnpacker.ReadValueBitPacked(reader, out value);
- }
-
- public void WriteDelta(FastBufferWriter writer, ref uint value, ref uint previousValue)
- {
- Write(writer, ref value);
- }
- public void ReadDelta(FastBufferReader reader, ref uint value)
- {
- Read(reader, ref value);
- }
-
- void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out uint value, Allocator allocator)
- {
- throw new NotImplementedException();
- }
-
- public void Duplicate(in uint value, ref uint duplicatedValue)
- {
- duplicatedValue = value;
- }
- }
-
- ///
- /// Packing serializer for longs
- ///
- internal class LongSerializer : INetworkVariableSerializer
- {
- public void Write(FastBufferWriter writer, ref long value)
- {
- BytePacker.WriteValueBitPacked(writer, value);
- }
- public void Read(FastBufferReader reader, ref long value)
- {
- ByteUnpacker.ReadValueBitPacked(reader, out value);
- }
-
- public void WriteDelta(FastBufferWriter writer, ref long value, ref long previousValue)
- {
- Write(writer, ref value);
- }
- public void ReadDelta(FastBufferReader reader, ref long value)
- {
- Read(reader, ref value);
- }
-
- void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out long value, Allocator allocator)
- {
- throw new NotImplementedException();
- }
-
- public void Duplicate(in long value, ref long duplicatedValue)
- {
- duplicatedValue = value;
- }
- }
-
- ///
- /// Packing serializer for longs
- ///
- internal class UlongSerializer : INetworkVariableSerializer
- {
- public void Write(FastBufferWriter writer, ref ulong value)
- {
- BytePacker.WriteValueBitPacked(writer, value);
- }
- public void Read(FastBufferReader reader, ref ulong value)
- {
- ByteUnpacker.ReadValueBitPacked(reader, out value);
- }
-
- public void WriteDelta(FastBufferWriter writer, ref ulong value, ref ulong previousValue)
- {
- Write(writer, ref value);
- }
- public void ReadDelta(FastBufferReader reader, ref ulong value)
- {
- Read(reader, ref value);
- }
-
- void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out ulong value, Allocator allocator)
- {
- throw new NotImplementedException();
- }
-
- public void Duplicate(in ulong value, ref ulong duplicatedValue)
- {
- duplicatedValue = value;
- }
- }
-
- ///
- /// Basic serializer for unmanaged types.
- /// This covers primitives, built-in unity types, and IForceSerializeByMemcpy
- /// Since all of those ultimately end up calling WriteUnmanagedSafe, this simplifies things
- /// by calling that directly - thus preventing us from having to have a specific T that meets
- /// the specific constraints that the various generic WriteValue calls require.
- ///
- ///
- internal class UnmanagedTypeSerializer : INetworkVariableSerializer where T : unmanaged
- {
- public void Write(FastBufferWriter writer, ref T value)
- {
- writer.WriteUnmanagedSafe(value);
- }
- public void Read(FastBufferReader reader, ref T value)
- {
- reader.ReadUnmanagedSafe(out value);
- }
-
- public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue)
- {
- Write(writer, ref value);
- }
- public void ReadDelta(FastBufferReader reader, ref T value)
- {
- Read(reader, ref value);
- }
-
- void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator)
- {
- throw new NotImplementedException();
- }
-
- public void Duplicate(in T value, ref T duplicatedValue)
- {
- duplicatedValue = value;
- }
- }
-
- internal class ListSerializer : INetworkVariableSerializer>
- {
- public void Write(FastBufferWriter writer, ref List value)
- {
- bool isNull = value == null;
- writer.WriteValueSafe(isNull);
- if (!isNull)
- {
- BytePacker.WriteValuePacked(writer, value.Count);
- foreach (var item in value)
- {
- var reffable = item;
- NetworkVariableSerialization.Write(writer, ref reffable);
- }
- }
- }
- public void Read(FastBufferReader reader, ref List value)
- {
- reader.ReadValueSafe(out bool isNull);
- if (isNull)
- {
- value = null;
- }
- else
- {
- if (value == null)
- {
- value = new List();
- }
-
- ByteUnpacker.ReadValuePacked(reader, out int len);
- if (len < value.Count)
- {
- value.RemoveRange(len, value.Count - len);
- }
- for (var i = 0; i < len; ++i)
- {
- // Read in place where possible
- if (i < value.Count)
- {
- T item = value[i];
- NetworkVariableSerialization.Read(reader, ref item);
- value[i] = item;
- }
- else
- {
- T item = default;
- NetworkVariableSerialization.Read(reader, ref item);
- value.Add(item);
- }
- }
- }
- }
-
- public void WriteDelta(FastBufferWriter writer, ref List value, ref List previousValue)
- {
- CollectionSerializationUtility.WriteListDelta(writer, ref value, ref previousValue);
- }
- public void ReadDelta(FastBufferReader reader, ref List value)
- {
- CollectionSerializationUtility.ReadListDelta(reader, ref value);
- }
-
- void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out List value, Allocator allocator)
- {
- throw new NotImplementedException();
- }
-
- public void Duplicate(in List value, ref List duplicatedValue)
- {
- if (duplicatedValue == null)
- {
- duplicatedValue = new List();
- }
-
- duplicatedValue.Clear();
- foreach (var item in value)
- {
- duplicatedValue.Add(item);
- }
- }
- }
-
- internal class HashSetSerializer : INetworkVariableSerializer> where T : IEquatable
- {
- public void Write(FastBufferWriter writer, ref HashSet value)
- {
- bool isNull = value == null;
- writer.WriteValueSafe(isNull);
- if (!isNull)
- {
- writer.WriteValueSafe(value.Count);
- foreach (var item in value)
- {
- var reffable = item;
- NetworkVariableSerialization.Write(writer, ref reffable);
- }
- }
- }
- public void Read(FastBufferReader reader, ref HashSet value)
- {
- reader.ReadValueSafe(out bool isNull);
- if (isNull)
- {
- value = null;
- }
- else
- {
- if (value == null)
- {
- value = new HashSet();
- }
- else
- {
- value.Clear();
- }
- reader.ReadValueSafe(out int len);
- for (var i = 0; i < len; ++i)
- {
- T item = default;
- NetworkVariableSerialization.Read(reader, ref item);
- value.Add(item);
- }
- }
- }
-
- public void WriteDelta(FastBufferWriter writer, ref HashSet value, ref HashSet previousValue)
- {
- CollectionSerializationUtility.WriteHashSetDelta(writer, ref value, ref previousValue);
- }
- public void ReadDelta(FastBufferReader reader, ref HashSet value)
- {
- CollectionSerializationUtility.ReadHashSetDelta(reader, ref value);
- }
-
- void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out HashSet value, Allocator allocator)
- {
- throw new NotImplementedException();
- }
-
- public void Duplicate(in HashSet value, ref HashSet duplicatedValue)
- {
- if (duplicatedValue == null)
- {
- duplicatedValue = new HashSet();
- }
-
- duplicatedValue.Clear();
- foreach (var item in value)
- {
- duplicatedValue.Add(item);
- }
- }
- }
-
-
- internal class DictionarySerializer : INetworkVariableSerializer>
- where TKey : IEquatable
- {
- public void Write(FastBufferWriter writer, ref Dictionary value)
- {
- bool isNull = value == null;
- writer.WriteValueSafe(isNull);
- if (!isNull)
- {
- writer.WriteValueSafe(value.Count);
- foreach (var item in value)
- {
- (var key, var val) = (item.Key, item.Value);
- NetworkVariableSerialization.Write(writer, ref key);
- NetworkVariableSerialization.Write(writer, ref val);
- }
- }
- }
- public void Read(FastBufferReader reader, ref Dictionary value)
- {
- reader.ReadValueSafe(out bool isNull);
- if (isNull)
- {
- value = null;
- }
- else
- {
- if (value == null)
- {
- value = new Dictionary();
- }
- else
- {
- value.Clear();
- }
- reader.ReadValueSafe(out int len);
- for (var i = 0; i < len; ++i)
- {
- (TKey key, TVal val) = (default, default);
- NetworkVariableSerialization.Read(reader, ref key);
- NetworkVariableSerialization.Read(reader, ref val);
- value.Add(key, val);
- }
- }
- }
-
- public void WriteDelta(FastBufferWriter writer, ref Dictionary value, ref Dictionary previousValue)
- {
- CollectionSerializationUtility.WriteDictionaryDelta(writer, ref value, ref previousValue);
- }
- public void ReadDelta(FastBufferReader reader, ref Dictionary value)
- {
- CollectionSerializationUtility.ReadDictionaryDelta(reader, ref value);
- }
-
- void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out Dictionary value, Allocator allocator)
- {
- throw new NotImplementedException();
- }
-
- public void Duplicate(in Dictionary value, ref Dictionary duplicatedValue)
- {
- if (duplicatedValue == null)
- {
- duplicatedValue = new Dictionary();
- }
-
- duplicatedValue.Clear();
- foreach (var item in value)
- {
- duplicatedValue.Add(item.Key, item.Value);
- }
- }
- }
-
- internal class UnmanagedArraySerializer : INetworkVariableSerializer> where T : unmanaged
- {
- public void Write(FastBufferWriter writer, ref NativeArray value)
- {
- writer.WriteUnmanagedSafe(value);
- }
- public void Read(FastBufferReader reader, ref NativeArray value)
- {
- value.Dispose();
- reader.ReadUnmanagedSafe(out value, Allocator.Persistent);
- }
-
- public void WriteDelta(FastBufferWriter writer, ref NativeArray value, ref NativeArray previousValue)
- {
- CollectionSerializationUtility.WriteNativeArrayDelta(writer, ref value, ref previousValue);
- }
- public void ReadDelta(FastBufferReader reader, ref NativeArray value)
- {
- CollectionSerializationUtility.ReadNativeArrayDelta(reader, ref value);
- }
-
- void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeArray value, Allocator allocator)
- {
- reader.ReadUnmanagedSafe(out value, allocator);
- }
-
- public void Duplicate(in NativeArray value, ref NativeArray duplicatedValue)
- {
- if (!duplicatedValue.IsCreated || duplicatedValue.Length != value.Length)
- {
- if (duplicatedValue.IsCreated)
- {
- duplicatedValue.Dispose();
- }
-
- duplicatedValue = new NativeArray(value.Length, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
- }
-
- duplicatedValue.CopyFrom(value);
- }
- }
-
-#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
- internal class UnmanagedListSerializer : INetworkVariableSerializer> where T : unmanaged
- {
- public void Write(FastBufferWriter writer, ref NativeList value)
- {
- writer.WriteUnmanagedSafe(value);
- }
- public void Read(FastBufferReader reader, ref NativeList value)
- {
- reader.ReadUnmanagedSafeInPlace(ref value);
- }
-
- public void WriteDelta(FastBufferWriter writer, ref NativeList value, ref NativeList previousValue)
- {
- CollectionSerializationUtility.WriteNativeListDelta(writer, ref value, ref previousValue);
- }
- public void ReadDelta(FastBufferReader reader, ref NativeList value)
- {
- CollectionSerializationUtility.ReadNativeListDelta(reader, ref value);
- }
-
- void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeList value, Allocator allocator)
- {
- throw new NotImplementedException();
- }
-
- public void Duplicate(in NativeList value, ref NativeList duplicatedValue)
- {
- if (!duplicatedValue.IsCreated)
- {
- duplicatedValue = new NativeList(value.Length, Allocator.Persistent);
- }
- else if (value.Length != duplicatedValue.Length)
- {
- duplicatedValue.ResizeUninitialized(value.Length);
- }
-
- duplicatedValue.CopyFrom(value);
- }
- }
-
-
- internal class NativeHashSetSerializer : INetworkVariableSerializer> where T : unmanaged, IEquatable
- {
- public void Write(FastBufferWriter writer, ref NativeHashSet value)
- {
- writer.WriteValueSafe(value);
- }
- public void Read(FastBufferReader reader, ref NativeHashSet value)
- {
- reader.ReadValueSafeInPlace(ref value);
- }
-
- public void WriteDelta(FastBufferWriter writer, ref NativeHashSet value, ref NativeHashSet previousValue)
- {
- CollectionSerializationUtility.WriteNativeHashSetDelta(writer, ref value, ref previousValue);
- }
- public void ReadDelta(FastBufferReader reader, ref NativeHashSet value)
- {
- CollectionSerializationUtility.ReadNativeHashSetDelta(reader, ref value);
- }
-
- void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeHashSet value, Allocator allocator)
- {
- throw new NotImplementedException();
- }
-
- public void Duplicate(in NativeHashSet value, ref NativeHashSet duplicatedValue)
- {
- if (!duplicatedValue.IsCreated)
- {
- duplicatedValue = new NativeHashSet(value.Capacity, Allocator.Persistent);
- }
-
- duplicatedValue.Clear();
- foreach (var item in value)
- {
- duplicatedValue.Add(item);
- }
- }
- }
-
-
- internal class NativeHashMapSerializer : INetworkVariableSerializer>
- where TKey : unmanaged, IEquatable
- where TVal : unmanaged
- {
- public void Write(FastBufferWriter writer, ref NativeHashMap value)
- {
- writer.WriteValueSafe(value);
- }
- public void Read(FastBufferReader reader, ref NativeHashMap value)
- {
- reader.ReadValueSafeInPlace(ref value);
- }
-
- public void WriteDelta(FastBufferWriter writer, ref NativeHashMap value, ref NativeHashMap previousValue)
- {
- CollectionSerializationUtility.WriteNativeHashMapDelta(writer, ref value, ref previousValue);
- }
- public void ReadDelta(FastBufferReader reader, ref NativeHashMap value)
- {
- CollectionSerializationUtility.ReadNativeHashMapDelta(reader, ref value);
- }
-
- void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeHashMap value, Allocator allocator)
- {
- throw new NotImplementedException();
- }
-
- public void Duplicate(in NativeHashMap value, ref NativeHashMap duplicatedValue)
- {
- if (!duplicatedValue.IsCreated)
- {
- duplicatedValue = new NativeHashMap(value.Capacity, Allocator.Persistent);
- }
-
- duplicatedValue.Clear();
- foreach (var item in value)
- {
- duplicatedValue.Add(item.Key, item.Value);
- }
- }
- }
-#endif
-
- ///
- /// Serializer for FixedStrings
- ///
- ///
- internal class FixedStringSerializer : INetworkVariableSerializer where T : unmanaged, INativeList, IUTF8Bytes
- {
- public void Write(FastBufferWriter writer, ref T value)
- {
- writer.WriteValueSafe(value);
- }
- public void Read(FastBufferReader reader, ref T value)
- {
- reader.ReadValueSafeInPlace(ref value);
- }
-
- // Because of how strings are generally used, it is likely that most strings will still write as full strings
- // instead of deltas. This actually adds one byte to the data to encode that it was serialized in full.
- // But the potential savings from a small change to a large string are valuable enough to be worth that extra
- // byte.
- public unsafe void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue)
- {
- using var changes = new ResizableBitVector(Allocator.Temp);
- int minLength = math.min(value.Length, previousValue.Length);
- var numChanges = 0;
- for (var i = 0; i < minLength; ++i)
- {
- var val = value[i];
- var prevVal = previousValue[i];
- if (!NetworkVariableSerialization.AreEqual(ref val, ref prevVal))
- {
- ++numChanges;
- changes.Set(i);
- }
- }
-
- for (var i = previousValue.Length; i < value.Length; ++i)
- {
- ++numChanges;
- changes.Set(i);
- }
-
- if (changes.GetSerializedSize() + FastBufferWriter.GetWriteSize() * numChanges > FastBufferWriter.GetWriteSize() * value.Length)
- {
- writer.WriteByteSafe(1);
- writer.WriteValueSafe(value);
- return;
- }
- writer.WriteByte(0);
- BytePacker.WriteValuePacked(writer, value.Length);
- writer.WriteValueSafe(changes);
- unsafe
- {
- byte* ptr = value.GetUnsafePtr();
- byte* prevPtr = previousValue.GetUnsafePtr();
- for (int i = 0; i < value.Length; ++i)
- {
- if (changes.IsSet(i))
- {
- if (i < previousValue.Length)
- {
- NetworkVariableSerialization.WriteDelta(writer, ref ptr[i], ref prevPtr[i]);
- }
- else
- {
- NetworkVariableSerialization.Write(writer, ref ptr[i]);
- }
- }
- }
- }
- }
- public unsafe void ReadDelta(FastBufferReader reader, ref T value)
- {
- // Writing can use the NativeArray logic as it is, but reading is a little different.
- // Using the NativeArray logic for reading would result in length changes allocating a new NativeArray,
- // which is not what we want for FixedString. With FixedString, the actual size of the data does not change,
- // only an in-memory "length" value - so if the length changes, the only thing we want to do is change
- // that value, and otherwise read everything in-place.
- reader.ReadByteSafe(out byte full);
- if (full == 1)
- {
- reader.ReadValueSafeInPlace(ref value);
- return;
- }
- ByteUnpacker.ReadValuePacked(reader, out int length);
- var changes = new ResizableBitVector(Allocator.Temp);
- using var toDispose = changes;
- {
- reader.ReadNetworkSerializableInPlace(ref changes);
-
- value.Length = length;
-
- byte* ptr = value.GetUnsafePtr();
- for (var i = 0; i < value.Length; ++i)
- {
- if (changes.IsSet(i))
- {
- reader.ReadByte(out ptr[i]);
- }
- }
- }
- }
-
- void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator)
- {
- throw new NotImplementedException();
- }
-
- public void Duplicate(in T value, ref T duplicatedValue)
- {
- duplicatedValue = value;
- }
- }
-
- ///
- /// Serializer for FixedStrings
- ///
- ///
- internal class FixedStringArraySerializer : INetworkVariableSerializer> where T : unmanaged, INativeList, IUTF8Bytes
- {
- public void Write(FastBufferWriter writer, ref NativeArray value)
- {
- writer.WriteValueSafe(value);
- }
- public void Read(FastBufferReader reader, ref NativeArray value)
- {
- value.Dispose();
- reader.ReadValueSafe(out value, Allocator.Persistent);
- }
-
-
- public void WriteDelta(FastBufferWriter writer, ref NativeArray value, ref NativeArray previousValue)
- {
- CollectionSerializationUtility.WriteNativeArrayDelta(writer, ref value, ref previousValue);
- }
- public void ReadDelta(FastBufferReader reader, ref NativeArray value)
- {
- CollectionSerializationUtility.ReadNativeArrayDelta(reader, ref value);
- }
-
- void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeArray value, Allocator allocator)
- {
- reader.ReadValueSafe(out value, allocator);
- }
-
- public void Duplicate(in NativeArray value, ref NativeArray duplicatedValue)
- {
- if (!duplicatedValue.IsCreated || duplicatedValue.Length != value.Length)
- {
- if (duplicatedValue.IsCreated)
- {
- duplicatedValue.Dispose();
- }
-
- duplicatedValue = new NativeArray(value.Length, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
- }
-
- duplicatedValue.CopyFrom(value);
- }
- }
-
-#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
- ///
- /// Serializer for FixedStrings
- ///
- ///
- internal class FixedStringListSerializer : INetworkVariableSerializer> where T : unmanaged, INativeList, IUTF8Bytes
- {
- public void Write(FastBufferWriter writer, ref NativeList value)
- {
- writer.WriteValueSafe(value);
- }
- public void Read(FastBufferReader reader, ref NativeList value)
- {
- reader.ReadValueSafeInPlace(ref value);
- }
-
- public void WriteDelta(FastBufferWriter writer, ref NativeList value, ref NativeList previousValue)
- {
- CollectionSerializationUtility.WriteNativeListDelta(writer, ref value, ref previousValue);
- }
- public void ReadDelta(FastBufferReader reader, ref NativeList value)
- {
- CollectionSerializationUtility.ReadNativeListDelta(reader, ref value);
- }
-
- void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeList value, Allocator allocator)
- {
- throw new NotImplementedException();
- }
-
- public void Duplicate(in NativeList value, ref NativeList duplicatedValue)
- {
- if (!duplicatedValue.IsCreated)
- {
- duplicatedValue = new NativeList(value.Length, Allocator.Persistent);
- }
- else if (value.Length != duplicatedValue.Length)
- {
- duplicatedValue.ResizeUninitialized(value.Length);
- }
-
- duplicatedValue.CopyFrom(value);
- }
- }
-#endif
-
- ///
- /// Serializer for unmanaged INetworkSerializable types
- ///
- ///
- internal class UnmanagedNetworkSerializableSerializer : INetworkVariableSerializer where T : unmanaged, INetworkSerializable
- {
- public void Write(FastBufferWriter writer, ref T value)
- {
- var bufferSerializer = new BufferSerializer(new BufferSerializerWriter(writer));
- value.NetworkSerialize(bufferSerializer);
- }
- public void Read(FastBufferReader reader, ref T value)
- {
- var bufferSerializer = new BufferSerializer(new BufferSerializerReader(reader));
- value.NetworkSerialize(bufferSerializer);
- }
-
- public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue)
- {
- if (UserNetworkVariableSerialization.WriteDelta != null && UserNetworkVariableSerialization.ReadDelta != null)
- {
- UserNetworkVariableSerialization.WriteDelta(writer, value, previousValue);
- return;
- }
- Write(writer, ref value);
- }
- public void ReadDelta(FastBufferReader reader, ref T value)
- {
- if (UserNetworkVariableSerialization.WriteDelta != null && UserNetworkVariableSerialization.ReadDelta != null)
- {
- UserNetworkVariableSerialization.ReadDelta(reader, ref value);
- return;
- }
- Read(reader, ref value);
- }
-
- void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator)
- {
- throw new NotImplementedException();
- }
-
- public void Duplicate(in T value, ref T duplicatedValue)
- {
- duplicatedValue = value;
- }
- }
-
- ///
- /// Serializer for unmanaged INetworkSerializable types
- ///
- ///
- internal class UnmanagedNetworkSerializableArraySerializer : INetworkVariableSerializer> where T : unmanaged, INetworkSerializable
- {
- public void Write(FastBufferWriter writer, ref NativeArray value)
- {
- writer.WriteNetworkSerializable(value);
- }
- public void Read(FastBufferReader reader, ref NativeArray value)
- {
- value.Dispose();
- reader.ReadNetworkSerializable(out value, Allocator.Persistent);
- }
-
-
- public void WriteDelta(FastBufferWriter writer, ref NativeArray value, ref NativeArray previousValue)
- {
- CollectionSerializationUtility.WriteNativeArrayDelta(writer, ref value, ref previousValue);
- }
- public void ReadDelta(FastBufferReader reader, ref NativeArray value)
- {
- CollectionSerializationUtility.ReadNativeArrayDelta(reader, ref value);
- }
-
- void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeArray value, Allocator allocator)
- {
- reader.ReadNetworkSerializable(out value, allocator);
- }
-
- public void Duplicate(in NativeArray value, ref NativeArray duplicatedValue)
- {
- if (!duplicatedValue.IsCreated || duplicatedValue.Length != value.Length)
- {
- if (duplicatedValue.IsCreated)
- {
- duplicatedValue.Dispose();
- }
-
- duplicatedValue = new NativeArray(value.Length, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
- }
-
- duplicatedValue.CopyFrom(value);
- }
- }
-
-#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
- ///
- /// Serializer for unmanaged INetworkSerializable types
- ///
- ///
- internal class UnmanagedNetworkSerializableListSerializer : INetworkVariableSerializer> where T : unmanaged, INetworkSerializable
- {
- public void Write(FastBufferWriter writer, ref NativeList value)
- {
- writer.WriteNetworkSerializable(value);
- }
- public void Read(FastBufferReader reader, ref NativeList value)
- {
- reader.ReadNetworkSerializableInPlace(ref value);
- }
-
- public void WriteDelta(FastBufferWriter writer, ref NativeList value, ref NativeList previousValue)
- {
- CollectionSerializationUtility.WriteNativeListDelta(writer, ref value, ref previousValue);
- }
- public void ReadDelta(FastBufferReader reader, ref NativeList value)
- {
- CollectionSerializationUtility.ReadNativeListDelta(reader, ref value);
- }
-
- void INetworkVariableSerializer>.ReadWithAllocator(FastBufferReader reader, out NativeList value, Allocator allocator)
- {
- throw new NotImplementedException();
- }
-
- public void Duplicate(in NativeList value, ref NativeList duplicatedValue)
- {
- if (!duplicatedValue.IsCreated)
- {
- duplicatedValue = new NativeList(value.Length, Allocator.Persistent);
- }
- else if (value.Length != duplicatedValue.Length)
- {
- duplicatedValue.ResizeUninitialized(value.Length);
- }
-
- duplicatedValue.CopyFrom(value);
- }
- }
-#endif
-
- ///
- /// Serializer for managed INetworkSerializable types, which differs from the unmanaged implementation in that it
- /// has to be null-aware
- ///
- internal class ManagedNetworkSerializableSerializer : INetworkVariableSerializer where T : class, INetworkSerializable, new()
- {
- public void Write(FastBufferWriter writer, ref T value)
- {
- var bufferSerializer = new BufferSerializer(new BufferSerializerWriter(writer));
- bool isNull = (value == null);
- bufferSerializer.SerializeValue(ref isNull);
- if (!isNull)
- {
- value.NetworkSerialize(bufferSerializer);
- }
- }
- public void Read(FastBufferReader reader, ref T value)
- {
- var bufferSerializer = new BufferSerializer(new BufferSerializerReader(reader));
- bool isNull = false;
- bufferSerializer.SerializeValue(ref isNull);
- if (isNull)
- {
- value = null;
- }
- else
- {
- if (value == null)
- {
- value = new T();
- }
- value.NetworkSerialize(bufferSerializer);
- }
- }
-
- public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue)
- {
- if (UserNetworkVariableSerialization.WriteDelta != null && UserNetworkVariableSerialization.ReadDelta != null)
- {
- UserNetworkVariableSerialization.WriteDelta(writer, value, previousValue);
- return;
- }
- Write(writer, ref value);
- }
- public void ReadDelta(FastBufferReader reader, ref T value)
- {
- if (UserNetworkVariableSerialization.WriteDelta != null && UserNetworkVariableSerialization.ReadDelta != null)
- {
- UserNetworkVariableSerialization.ReadDelta(reader, ref value);
- return;
- }
- Read(reader, ref value);
- }
-
- void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator)
- {
- throw new NotImplementedException();
- }
-
- public void Duplicate(in T value, ref T duplicatedValue)
- {
- using var writer = new FastBufferWriter(256, Allocator.Temp, int.MaxValue);
- var refValue = value;
- Write(writer, ref refValue);
-
- using var reader = new FastBufferReader(writer, Allocator.None);
- Read(reader, ref duplicatedValue);
- }
- }
-
- ///
- /// 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)
- ///
- ///
- public class UserNetworkVariableSerialization
- {
- ///
- /// The write value delegate handler definition
- ///
- /// The to write the value of type `T`
- /// The value of type `T` to be written
- public delegate void WriteValueDelegate(FastBufferWriter writer, in T value);
-
- ///
- /// The write value delegate handler definition
- ///
- /// The to write the value of type `T`
- /// The value of type `T` to be written
- public delegate void WriteDeltaDelegate(FastBufferWriter writer, in T value, in T previousValue);
-
- ///
- /// The read value delegate handler definition
- ///
- /// The to read the value of type `T`
- /// The value of type `T` to be read
- public delegate void ReadValueDelegate(FastBufferReader reader, out T value);
-
- ///
- /// The read value delegate handler definition
- ///
- /// The to read the value of type `T`
- /// The value of type `T` to be read
- public delegate void ReadDeltaDelegate(FastBufferReader reader, ref T value);
-
- ///
- /// The read value delegate handler definition
- ///
- /// The to read the value of type `T`
- /// The value of type `T` to be read
- public delegate void DuplicateValueDelegate(in T value, ref T duplicatedValue);
-
- ///
- /// Callback to write a value
- ///
- public static WriteValueDelegate WriteValue;
-
- ///
- /// Callback to read a value
- ///
- public static ReadValueDelegate ReadValue;
-
- ///
- /// Callback to write a delta between two values, based on computing the difference between the previous and
- /// current values.
- ///
- public static WriteDeltaDelegate WriteDelta;
-
- ///
- /// Callback to read a delta, applying only select changes to the current value.
- ///
- public static ReadDeltaDelegate ReadDelta;
-
- ///
- /// Callback to create a duplicate of a value, used to check for dirty status.
- ///
- public static DuplicateValueDelegate DuplicateValue;
- }
-
- ///
- /// 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.
- ///
- ///
- internal class FallbackSerializer : INetworkVariableSerializer
- {
- 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)}. 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)}.{nameof(UserNetworkVariableSerialization.WriteValue)}, {nameof(UserNetworkVariableSerialization)}.{nameof(UserNetworkVariableSerialization.ReadValue)}, and {nameof(UserNetworkVariableSerialization)}.{nameof(UserNetworkVariableSerialization.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.ReadValue == null || UserNetworkVariableSerialization.WriteValue == null || UserNetworkVariableSerialization.DuplicateValue == null)
- {
- ThrowArgumentError();
- }
- UserNetworkVariableSerialization.WriteValue(writer, value);
- }
- public void Read(FastBufferReader reader, ref T value)
- {
- if (UserNetworkVariableSerialization.ReadValue == null || UserNetworkVariableSerialization.WriteValue == null || UserNetworkVariableSerialization.DuplicateValue == null)
- {
- ThrowArgumentError();
- }
- UserNetworkVariableSerialization.ReadValue(reader, out value);
- }
-
- public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue)
- {
- if (UserNetworkVariableSerialization.ReadValue == null || UserNetworkVariableSerialization.WriteValue == null || UserNetworkVariableSerialization.DuplicateValue == null)
- {
- ThrowArgumentError();
- }
-
- if (UserNetworkVariableSerialization.WriteDelta == null || UserNetworkVariableSerialization.ReadDelta == null)
- {
- UserNetworkVariableSerialization.WriteValue(writer, value);
- return;
- }
- UserNetworkVariableSerialization.WriteDelta(writer, value, previousValue);
- }
-
- public void ReadDelta(FastBufferReader reader, ref T value)
- {
- if (UserNetworkVariableSerialization.ReadValue == null || UserNetworkVariableSerialization.WriteValue == null || UserNetworkVariableSerialization.DuplicateValue == null)
- {
- ThrowArgumentError();
- }
-
- if (UserNetworkVariableSerialization.WriteDelta == null || UserNetworkVariableSerialization.ReadDelta == null)
- {
- UserNetworkVariableSerialization.ReadValue(reader, out value);
- return;
- }
- UserNetworkVariableSerialization.ReadDelta(reader, ref value);
- }
-
- void INetworkVariableSerializer.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator)
- {
- throw new NotImplementedException();
- }
-
- public void Duplicate(in T value, ref T duplicatedValue)
- {
- if (UserNetworkVariableSerialization.ReadValue == null || UserNetworkVariableSerialization.WriteValue == null || UserNetworkVariableSerialization.DuplicateValue == null)
- {
- ThrowArgumentError();
- }
- UserNetworkVariableSerialization.DuplicateValue(value, ref duplicatedValue);
- }
- }
-
- ///
- /// 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 .
- /// 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.)
- ///
- public static class NetworkVariableSerializationTypes
- {
- [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
-#if UNITY_EDITOR
- [InitializeOnLoadMethod]
-#endif
- internal static void InitializeIntegerSerialization()
- {
- NetworkVariableSerialization.Serializer = new ShortSerializer();
- NetworkVariableSerialization.AreEqual = NetworkVariableSerialization.ValueEquals;
- NetworkVariableSerialization.Serializer = new UshortSerializer();
- NetworkVariableSerialization.AreEqual = NetworkVariableSerialization.ValueEquals;
- NetworkVariableSerialization.Serializer = new IntSerializer();
- NetworkVariableSerialization