com.unity.netcode.gameobjects@2.0.0-exp.4

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-exp.4] - 2024-05-31

### Added

- Added `NetworkRigidbodyBase.AttachToFixedJoint` and `NetworkRigidbodyBase.DetachFromFixedJoint` to replace parenting for rigid bodies that have `NetworkRigidbodyBase.UseRigidBodyForMotion` enabled. (#2933)
- Added `NetworkBehaviour.OnNetworkPreSpawn` and `NetworkBehaviour.OnNetworkPostSpawn` methods that provide the ability to handle pre and post spawning actions during the `NetworkObject` spawn sequence. (#2912)
- Added a client-side only `NetworkBehaviour.OnNetworkSessionSynchronized` convenience method that is invoked on all `NetworkBehaviour`s after a newly joined client has finished synchronizing with the network session in progress. (#2912)
- Added `NetworkBehaviour.OnInSceneObjectsSpawned` convenience method that is invoked when all in-scene `NetworkObject`s have been spawned after a scene has been loaded or upon a host or server starting. (#2912)

### Fixed

- Fixed issue where non-authoritative rigid bodies with `NetworkRigidbodyBase.UseRigidBodyForMotion` enabled would constantly log errors about the renderTime being before `StartTimeConsumed`. (#2933)
- Fixed issue where in-scene placed NetworkObjects could be destroyed if a client disconnects early and/or before approval. (#2924)
- Fixed issue where a `NetworkObject` component's associated `NetworkBehaviour` components would not be detected if scene loading is disabled in the editor and the currently loaded scene has in-scene placed `NetworkObject`s. (#2912)
- Fixed issue where an in-scene placed `NetworkObject` with `NetworkTransform` that is also parented under a `GameObject` would not properly synchronize when the parent `GameObject` had a world space position other than 0,0,0. (#2898)

### Changed

- Change all the access modifiers of test class from Public to Internal (#2930)
- Changed messages are now sorted by enum values as opposed to ordinally sorting the messages by their type name. (#2929)
- Changed `NetworkClient.SessionModeTypes` to `NetworkClient.NetworkTopologyTypes`. (#2875)
- Changed `NetworkClient.SessionModeType` to `NetworkClient.NetworkTopologyType`. (#2875)
- Changed `NetworkConfig.SessionMode` to `NeworkConfig.NetworkTopology`. (#2875)
This commit is contained in:
Unity Technologies
2024-05-31 00:00:00 +00:00
parent 143a6cbd34
commit 63c7e4c78a
177 changed files with 1792 additions and 820 deletions

View File

@@ -6,6 +6,30 @@ 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). Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).
## [2.0.0-exp.4] - 2024-05-31
### Added
- Added `NetworkRigidbodyBase.AttachToFixedJoint` and `NetworkRigidbodyBase.DetachFromFixedJoint` to replace parenting for rigid bodies that have `NetworkRigidbodyBase.UseRigidBodyForMotion` enabled. (#2933)
- Added `NetworkBehaviour.OnNetworkPreSpawn` and `NetworkBehaviour.OnNetworkPostSpawn` methods that provide the ability to handle pre and post spawning actions during the `NetworkObject` spawn sequence. (#2912)
- Added a client-side only `NetworkBehaviour.OnNetworkSessionSynchronized` convenience method that is invoked on all `NetworkBehaviour`s after a newly joined client has finished synchronizing with the network session in progress. (#2912)
- Added `NetworkBehaviour.OnInSceneObjectsSpawned` convenience method that is invoked when all in-scene `NetworkObject`s have been spawned after a scene has been loaded or upon a host or server starting. (#2912)
### Fixed
- Fixed issue where non-authoritative rigid bodies with `NetworkRigidbodyBase.UseRigidBodyForMotion` enabled would constantly log errors about the renderTime being before `StartTimeConsumed`. (#2933)
- Fixed issue where in-scene placed NetworkObjects could be destroyed if a client disconnects early and/or before approval. (#2924)
- Fixed issue where a `NetworkObject` component's associated `NetworkBehaviour` components would not be detected if scene loading is disabled in the editor and the currently loaded scene has in-scene placed `NetworkObject`s. (#2912)
- Fixed issue where an in-scene placed `NetworkObject` with `NetworkTransform` that is also parented under a `GameObject` would not properly synchronize when the parent `GameObject` had a world space position other than 0,0,0. (#2898)
### Changed
- Change all the access modifiers of test class from Public to Internal (#2930)
- Changed messages are now sorted by enum values as opposed to ordinally sorting the messages by their type name. (#2929)
- Changed `NetworkClient.SessionModeTypes` to `NetworkClient.NetworkTopologyTypes`. (#2875)
- Changed `NetworkClient.SessionModeType` to `NetworkClient.NetworkTopologyType`. (#2875)
- Changed `NetworkConfig.SessionMode` to `NeworkConfig.NetworkTopology`. (#2875)
## [2.0.0-exp.2] - 2024-04-02 ## [2.0.0-exp.2] - 2024-04-02
### Added ### Added
@@ -52,7 +76,7 @@ Additional documentation and release notes are available at [Multiplayer Documen
- Added distributed authority mode specific `NetworkObject.OnDeferredDespawnComplete` callback handler that can be used to further control when deferring the despawning of a `NetworkObject` on non-authoritative instances. (#2863) - Added distributed authority mode specific `NetworkObject.OnDeferredDespawnComplete` callback handler that can be used to further control when deferring the despawning of a `NetworkObject` on non-authoritative instances. (#2863)
- Added `NetworkClient.SessionModeType` as one way to determine the current session mode of the network session a client is connected to. (#2863) - Added `NetworkClient.SessionModeType` as one way to determine the current session mode of the network session a client is connected to. (#2863)
- Added distributed authority mode specific `NetworkClient.IsSessionOwner` property to determine if the current local client is the current session owner of a distributed authority session. (#2863) - Added distributed authority mode specific `NetworkClient.IsSessionOwner` property to determine if the current local client is the current session owner of a distributed authority session. (#2863)
- Added distributed authority mode specific client side spawning capabilities. When running in distributed authority mode, clients can instantiate and spawn `NetworkObject` instances (the local client is authomatically the owner of the spawned object). (#2863) - Added distributed authority mode specific client side spawning capabilities. When running in distributed authority mode, clients can instantiate and spawn `NetworkObject` instances (the local client is automatically the owner of the spawned object). (#2863)
- This is useful to better visually synchronize owner authoritative motion models and newly spawned `NetworkObject` instances (i.e. projectiles for example). - This is useful to better visually synchronize owner authoritative motion models and newly spawned `NetworkObject` instances (i.e. projectiles for example).
- Added distributed authority mode specific client side player spawning capabilities. Clients will automatically spawn their associated player object locally. (#2863) - Added distributed authority mode specific client side player spawning capabilities. Clients will automatically spawn their associated player object locally. (#2863)
- Added distributed authority mode specific `NetworkConfig.AutoSpawnPlayerPrefabClientSide` property (default is true) to provide control over the automatic spawning of player prefabs on the local client side. (#2863) - Added distributed authority mode specific `NetworkConfig.AutoSpawnPlayerPrefabClientSide` property (default is true) to provide control over the automatic spawning of player prefabs on the local client side. (#2863)
@@ -79,6 +103,36 @@ Additional documentation and release notes are available at [Multiplayer Documen
- Changed `NetworkTransform` to now use `NetworkTransformMessage` as opposed to named messages for NetworkTransformState updates. (#2810) - Changed `NetworkTransform` to now use `NetworkTransformMessage` as opposed to named messages for NetworkTransformState updates. (#2810)
- Changed `CustomMessageManager` so it no longer attempts to register or "unregister" a null or empty string and will log an error if this condition occurs. (#2807) - Changed `CustomMessageManager` so it no longer attempts to register or "unregister" a null or empty string and will log an error if this condition occurs. (#2807)
## [1.9.1] - 2024-04-18
### Added
- Added `AnticipatedNetworkVariable<T>`, which adds support for client anticipation of NetworkVariable values, allowing for more responsive game play (#2820)
- Added `AnticipatedNetworkTransform`, which adds support for client anticipation of `NetworkTransform`s (#2820)
- Added `NetworkVariableBase.ExceedsDirtinessThreshold` to allow network variables to throttle updates by only sending updates when the difference between the current and previous values exceeds a threshold. (This is exposed in NetworkVariable<T> with the callback NetworkVariable<T>.CheckExceedsDirtinessThreshold) (#2820)
- Added `NetworkVariableUpdateTraits`, which add additional throttling support: `MinSecondsBetweenUpdates` will prevent the `NetworkVariable` from sending updates more often than the specified time period (even if it exceeds the dirtiness threshold), while `MaxSecondsBetweenUpdates` will force a dirty `NetworkVariable` to send an update after the specified time period even if it has not yet exceeded the dirtiness threshold. (#2820)
- Added virtual method `NetworkVariableBase.OnInitialize()` which can be used by `NetworkVariable` subclasses to add initialization code (#2820)
- Added virtual method `NetworkVariableBase.Update()`, which is called once per frame to support behaviors such as interpolation between an anticipated value and an authoritative one. (#2820)
- Added `NetworkTime.TickWithPartial`, which represents the current tick as a double that includes the fractional/partial tick value. (#2820)
- `NetworkVariable` now includes built-in support for `NativeHashSet`, `NativeHashMap`, `List`, `HashSet`, and `Dictionary` (#2813)
- `NetworkVariable` now includes delta compression for collection values (`NativeList`, `NativeArray`, `NativeHashSet`, `NativeHashMap`, `List`, `HashSet`, `Dictionary`, and `FixedString` types) to save bandwidth by only sending the values that changed. (Note: For `NativeList`, `NativeArray`, and `List`, this algorithm works differently than that used in `NetworkList`. This algorithm will use less bandwidth for "set" and "add" operations, but `NetworkList` is more bandwidth-efficient if you are performing frequent "insert" operations.) (#2813)
- `UserNetworkVariableSerialization` now has optional callbacks for `WriteDelta` and `ReadDelta`. If both are provided, they will be used for all serialization operations on NetworkVariables of that type except for the first one for each client. If either is missing, the existing `Write` and `Read` will always be used. (#2813)
- Network variables wrapping `INetworkSerializable` types can perform delta serialization by setting `UserNetworkVariableSerialization<T>.WriteDelta` and `UserNetworkVariableSerialization<T>.ReadDelta` for those types. The built-in `INetworkSerializable` serializer will continue to be used for all other serialization operations, but if those callbacks are set, it will call into them on all but the initial serialization to perform delta serialization. (This could be useful if you have a large struct where most values do not change regularly and you want to send only the fields that did change.) (#2813)
### Fixed
- Fixed issue where `NetworkTransformEditor` would throw and exception if you excluded the physics package. (#2871)
- Fixed issue where `NetworkTransform` could not properly synchronize its base position when using half float precision. (#2845)
- Fixed issue where the host was not invoking `OnClientDisconnectCallback` for its own local client when internally shutting down. (#2822)
- Fixed issue where NetworkTransform could potentially attempt to "unregister" a named message prior to it being registered. (#2807)
- Fixed issue where in-scene placed `NetworkObject`s with complex nested children `NetworkObject`s (more than one child in depth) would not synchronize properly if WorldPositionStays was set to true. (#2796)
### Changed
- Changed `NetworkObjectReference` and `NetworkBehaviourReference` to allow null references when constructing and serializing. (#2874)
- Changed `NetworkAnimator` no longer requires the `Animator` component to exist on the same `GameObject`. (#2872)
- Changed `NetworkTransform` to now use `NetworkTransformMessage` as opposed to named messages for NetworkTransformState updates. (#2810)
- Changed `CustomMessageManager` so it no longer attempts to register or "unregister" a null or empty string and will log an error if this condition occurs. (#2807)
## [1.8.1] - 2024-02-05 ## [1.8.1] - 2024-02-05
### Fixed ### Fixed

View File

@@ -1,15 +0,0 @@
using System.Runtime.CompilerServices;
#if UNITY_EDITOR
[assembly: InternalsVisibleTo("Unity.Netcode.Editor")]
[assembly: InternalsVisibleTo("Unity.Netcode.Editor.CodeGen")]
#endif // UNITY_EDITOR
#if UNITY_INCLUDE_TESTS
[assembly: InternalsVisibleTo("Unity.Netcode.RuntimeTests")]
[assembly: InternalsVisibleTo("TestProject.RuntimeTests")]
#if UNITY_EDITOR
[assembly: InternalsVisibleTo("Unity.Netcode.EditorTests")]
[assembly: InternalsVisibleTo("TestProject.EditorTests")]
#endif // UNITY_EDITOR
#endif // UNITY_INCLUDE_TESTS

View File

@@ -1,205 +0,0 @@
using Unity.Netcode.Components;
using UnityEngine;
namespace Unity.Netcode
{
/// <summary>
/// NetworkTransform State Update Message
/// </summary>
internal struct NetworkTransformMessage : INetworkMessage
{
public int Version => 0;
public ulong NetworkObjectId;
public int NetworkBehaviourId;
// This is only used when serializing but not serialized
public bool DistributedAuthorityMode;
// Might get removed
public ulong[] TargetIds;
private int GetTargetIdLength()
{
if (TargetIds != null)
{
return TargetIds.Length;
}
return 0;
}
public NetworkTransform.NetworkTransformState State;
private NetworkTransform m_ReceiverNetworkTransform;
private FastBufferReader m_CurrentReader;
private unsafe void CopyPayload(ref FastBufferWriter writer)
{
writer.WriteBytesSafe(m_CurrentReader.GetUnsafePtrAtCurrentPosition(), m_CurrentReader.Length - m_CurrentReader.Position);
}
public void Serialize(FastBufferWriter writer, int targetVersion)
{
if (m_CurrentReader.IsInitialized)
{
CopyPayload(ref writer);
}
else
{
BytePacker.WriteValueBitPacked(writer, NetworkObjectId);
BytePacker.WriteValueBitPacked(writer, NetworkBehaviourId);
writer.WriteNetworkSerializable(State);
if (DistributedAuthorityMode)
{
var length = GetTargetIdLength();
BytePacker.WriteValuePacked(writer, length);
// If no target ids, then just exit early (DAHost specific)
if (length == 0)
{
return;
}
foreach (var target in TargetIds)
{
BytePacker.WriteValuePacked(writer, target);
}
}
}
}
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
var networkManager = context.SystemOwner as NetworkManager;
if (networkManager == null)
{
Debug.LogError($"[{nameof(NetworkTransformMessage)}] System owner context was not of type {nameof(NetworkManager)}!");
return false;
}
var currentPosition = reader.Position;
ByteUnpacker.ReadValueBitPacked(reader, out NetworkObjectId);
var isSpawnedLocally = networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId);
// Only defer if the NetworkObject is not spawned yet and the local NetworkManager is not running as a DAHost.
if (!isSpawnedLocally && !networkManager.DAHost)
{
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context);
return false;
}
// While the below check and assignment might seem out of place, this is specific to running in DAHost mode when a NetworkObject is
// hidden from the DAHost but is visible to other clients. Since the DAHost needs to forward updates to the clients, we ignore processing
// this message locally
var networkObject = (NetworkObject)null;
var isServerAuthoritative = false;
var ownerAuthoritativeServerSide = false;
// Get the behaviour index
ByteUnpacker.ReadValueBitPacked(reader, out NetworkBehaviourId);
// Deserialize the state
reader.ReadNetworkSerializableInPlace(ref State);
if (networkManager.DistributedAuthorityMode)
{
var targetCount = 0;
ByteUnpacker.ReadValueBitPacked(reader, out targetCount);
if (targetCount > 0)
{
TargetIds = new ulong[targetCount];
}
var targetId = (ulong)0;
for (int i = 0; i < targetCount; i++)
{
ByteUnpacker.ReadValueBitPacked(reader, out targetId);
TargetIds[i] = targetId;
}
}
if (isSpawnedLocally)
{
networkObject = networkManager.SpawnManager.SpawnedObjects[NetworkObjectId];
// Get the target NetworkTransform
m_ReceiverNetworkTransform = networkObject.ChildNetworkBehaviours[NetworkBehaviourId] as NetworkTransform;
isServerAuthoritative = m_ReceiverNetworkTransform.IsServerAuthoritative();
ownerAuthoritativeServerSide = !isServerAuthoritative && networkManager.IsServer;
}
else
{
// If we are the DAHost and the NetworkObject is hidden from the host we still need to forward this message
ownerAuthoritativeServerSide = networkManager.DAHost && !isSpawnedLocally;
}
if (ownerAuthoritativeServerSide)
{
var ownerClientId = (ulong)0;
if (networkObject != null)
{
ownerClientId = networkObject.OwnerClientId;
if (ownerClientId == NetworkManager.ServerClientId)
{
// Ownership must have changed, ignore any additional pending messages that might have
// come from a previous owner client.
return true;
}
}
else if (networkManager.DAHost)
{
// Specific to distributed authority mode, the only sender of state updates will be the owner
ownerClientId = context.SenderId;
}
var networkDelivery = State.IsReliableStateUpdate() ? NetworkDelivery.ReliableSequenced : NetworkDelivery.UnreliableSequenced;
// Forward the state update if there are any remote clients to foward it to
if (networkManager.ConnectionManager.ConnectedClientsList.Count > (networkManager.IsHost ? 2 : 1))
{
var clientCount = networkManager.DistributedAuthorityMode ? GetTargetIdLength() : networkManager.ConnectionManager.ConnectedClientsList.Count;
if (clientCount == 0)
{
return true;
}
// This is only to copy the existing and already serialized struct for forwarding purposes only.
// This will not include any changes made to this struct at this particular stage of processing the message.
var currentMessage = this;
// Create a new reader that replicates this message
currentMessage.m_CurrentReader = new FastBufferReader(reader, Collections.Allocator.None);
// Rewind the new reader to the beginning of the message's payload
currentMessage.m_CurrentReader.Seek(currentPosition);
// Forward the message to all connected clients that are observers of the associated NetworkObject
for (int i = 0; i < clientCount; i++)
{
var clientId = networkManager.DistributedAuthorityMode ? TargetIds[i] : networkManager.ConnectionManager.ConnectedClientsList[i].ClientId;
if (NetworkManager.ServerClientId == clientId || (!isServerAuthoritative && clientId == ownerClientId) ||
(!networkManager.DistributedAuthorityMode && !networkObject.Observers.Contains(clientId)))
{
continue;
}
networkManager.MessageManager.SendMessage(ref currentMessage, networkDelivery, clientId);
}
// Dispose of the reader used for forwarding
currentMessage.m_CurrentReader.Dispose();
}
}
return true;
}
public void Handle(ref NetworkContext context)
{
var networkManager = context.SystemOwner as NetworkManager;
// Only if the local NetworkManager instance is running as the DAHost we just exit if there is no local
// NetworkTransform component to apply the state update to (i.e. it is hidden from the DAHost and it
// just forwarded the state update to any other connected client)
if (networkManager.DAHost && m_ReceiverNetworkTransform == null)
{
return;
}
if (m_ReceiverNetworkTransform == null)
{
Debug.LogError($"[{nameof(NetworkTransformMessage)}][Dropped] Reciever {nameof(NetworkTransform)} was not set!");
return;
}
m_ReceiverNetworkTransform.TransformStateUpdate(ref State, context.SenderId);
}
}
}

View File

@@ -1,27 +0,0 @@
{
"name": "Unity.Netcode.Components",
"rootNamespace": "Unity.Netcode.Components",
"references": [
"Unity.Netcode.Runtime",
"Unity.Collections",
"Unity.Mathematics"
],
"allowUnsafeCode": true,
"versionDefines": [
{
"name": "com.unity.modules.animation",
"expression": "",
"define": "COM_UNITY_MODULES_ANIMATION"
},
{
"name": "com.unity.modules.physics",
"expression": "",
"define": "COM_UNITY_MODULES_PHYSICS"
},
{
"name": "com.unity.modules.physics2d",
"expression": "",
"define": "COM_UNITY_MODULES_PHYSICS2D"
}
]
}

View File

@@ -27,7 +27,8 @@ namespace Unity.Netcode.Editor.CodeGen
public override ILPPInterface GetInstance() => this; public override ILPPInterface GetInstance() => this;
public override bool WillProcess(ICompiledAssembly compiledAssembly) => compiledAssembly.References.Any(filePath => Path.GetFileNameWithoutExtension(filePath) == CodeGenHelpers.RuntimeAssemblyName); public override bool WillProcess(ICompiledAssembly compiledAssembly) => compiledAssembly.Name == CodeGenHelpers.RuntimeAssemblyName ||
compiledAssembly.References.Any(filePath => Path.GetFileNameWithoutExtension(filePath) == CodeGenHelpers.RuntimeAssemblyName);
private readonly List<DiagnosticMessage> m_Diagnostics = new List<DiagnosticMessage>(); private readonly List<DiagnosticMessage> m_Diagnostics = new List<DiagnosticMessage>();

View File

@@ -30,7 +30,9 @@ namespace Unity.Netcode.Editor
private SerializedProperty m_ProtocolVersionProperty; private SerializedProperty m_ProtocolVersionProperty;
private SerializedProperty m_NetworkTransportProperty; private SerializedProperty m_NetworkTransportProperty;
private SerializedProperty m_TickRateProperty; private SerializedProperty m_TickRateProperty;
private SerializedProperty m_SessionModeProperty; #if MULTIPLAYER_SDK_INSTALLED
private SerializedProperty m_NetworkTopologyProperty;
#endif
private SerializedProperty m_ClientConnectionBufferTimeoutProperty; private SerializedProperty m_ClientConnectionBufferTimeoutProperty;
private SerializedProperty m_ConnectionApprovalProperty; private SerializedProperty m_ConnectionApprovalProperty;
private SerializedProperty m_EnsureNetworkVariableLengthSafetyProperty; private SerializedProperty m_EnsureNetworkVariableLengthSafetyProperty;
@@ -43,6 +45,9 @@ namespace Unity.Netcode.Editor
private SerializedProperty m_LoadSceneTimeOutProperty; private SerializedProperty m_LoadSceneTimeOutProperty;
private SerializedProperty m_PrefabsList; private SerializedProperty m_PrefabsList;
private SerializedProperty m_NetworkProfileMetrics;
private SerializedProperty m_NetworkMessageMetrics;
private NetworkManager m_NetworkManager; private NetworkManager m_NetworkManager;
private bool m_Initialized; private bool m_Initialized;
@@ -97,7 +102,9 @@ namespace Unity.Netcode.Editor
m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion"); m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion");
m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport"); m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport");
m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate"); m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate");
m_SessionModeProperty = m_NetworkConfigProperty.FindPropertyRelative("SessionMode"); #if MULTIPLAYER_SDK_INSTALLED
m_NetworkTopologyProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTopology");
#endif
m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout"); m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout");
m_ConnectionApprovalProperty = m_NetworkConfigProperty.FindPropertyRelative("ConnectionApproval"); m_ConnectionApprovalProperty = m_NetworkConfigProperty.FindPropertyRelative("ConnectionApproval");
m_EnsureNetworkVariableLengthSafetyProperty = m_NetworkConfigProperty.FindPropertyRelative("EnsureNetworkVariableLengthSafety"); m_EnsureNetworkVariableLengthSafetyProperty = m_NetworkConfigProperty.FindPropertyRelative("EnsureNetworkVariableLengthSafety");
@@ -109,6 +116,11 @@ namespace Unity.Netcode.Editor
m_SpawnTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("SpawnTimeout"); m_SpawnTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("SpawnTimeout");
m_LoadSceneTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("LoadSceneTimeOut"); m_LoadSceneTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("LoadSceneTimeOut");
m_NetworkProfileMetrics = m_NetworkConfigProperty.FindPropertyRelative("NetworkProfileMetrics");
#if MULTIPLAYER_TOOLS
m_NetworkMessageMetrics = m_NetworkConfigProperty.FindPropertyRelative("NetworkMessageMetrics");
#endif
m_RpcHashSizeProperty = m_NetworkConfigProperty.FindPropertyRelative("RpcHashSize"); m_RpcHashSizeProperty = m_NetworkConfigProperty.FindPropertyRelative("RpcHashSize");
m_PrefabsList = m_NetworkConfigProperty m_PrefabsList = m_NetworkConfigProperty
@@ -130,7 +142,9 @@ namespace Unity.Netcode.Editor
m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion"); m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion");
m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport"); m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport");
m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate"); m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate");
m_SessionModeProperty = m_NetworkConfigProperty.FindPropertyRelative("SessionMode"); #if MULTIPLAYER_SDK_INSTALLED
m_NetworkTopologyProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTopology");
#endif
m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout"); m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout");
m_ConnectionApprovalProperty = m_NetworkConfigProperty.FindPropertyRelative("ConnectionApproval"); m_ConnectionApprovalProperty = m_NetworkConfigProperty.FindPropertyRelative("ConnectionApproval");
m_EnsureNetworkVariableLengthSafetyProperty = m_NetworkConfigProperty.FindPropertyRelative("EnsureNetworkVariableLengthSafety"); m_EnsureNetworkVariableLengthSafetyProperty = m_NetworkConfigProperty.FindPropertyRelative("EnsureNetworkVariableLengthSafety");
@@ -143,6 +157,11 @@ namespace Unity.Netcode.Editor
m_SpawnTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("SpawnTimeout"); m_SpawnTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("SpawnTimeout");
m_LoadSceneTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("LoadSceneTimeOut"); m_LoadSceneTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("LoadSceneTimeOut");
m_NetworkProfileMetrics = m_NetworkConfigProperty.FindPropertyRelative("NetworkProfilingMetrics");
#if MULTIPLAYER_TOOLS
m_NetworkMessageMetrics = m_NetworkConfigProperty.FindPropertyRelative("NetworkMessageMetrics");
#endif
m_RpcHashSizeProperty = m_NetworkConfigProperty.FindPropertyRelative("RpcHashSize"); m_RpcHashSizeProperty = m_NetworkConfigProperty.FindPropertyRelative("RpcHashSize");
m_PrefabsList = m_NetworkConfigProperty m_PrefabsList = m_NetworkConfigProperty
.FindPropertyRelative(nameof(NetworkConfig.Prefabs)) .FindPropertyRelative(nameof(NetworkConfig.Prefabs))
@@ -164,9 +183,12 @@ namespace Unity.Netcode.Editor
serializedObject.Update(); serializedObject.Update();
EditorGUILayout.PropertyField(m_RunInBackgroundProperty); EditorGUILayout.PropertyField(m_RunInBackgroundProperty);
EditorGUILayout.PropertyField(m_LogLevelProperty); EditorGUILayout.PropertyField(m_LogLevelProperty);
EditorGUILayout.PropertyField(m_SessionModeProperty);
EditorGUILayout.Space(); EditorGUILayout.Space();
EditorGUILayout.LabelField("Network Settings", EditorStyles.boldLabel); EditorGUILayout.LabelField("Network Settings", EditorStyles.boldLabel);
#if MULTIPLAYER_SDK_INSTALLED
EditorGUILayout.PropertyField(m_NetworkTopologyProperty);
#endif
EditorGUILayout.PropertyField(m_ProtocolVersionProperty); EditorGUILayout.PropertyField(m_ProtocolVersionProperty);
EditorGUILayout.PropertyField(m_NetworkTransportProperty); EditorGUILayout.PropertyField(m_NetworkTransportProperty);
if (m_NetworkTransportProperty.objectReferenceValue == null) if (m_NetworkTransportProperty.objectReferenceValue == null)
@@ -200,6 +222,11 @@ namespace Unity.Netcode.Editor
} }
EditorGUILayout.PropertyField(m_RpcHashSizeProperty); EditorGUILayout.PropertyField(m_RpcHashSizeProperty);
EditorGUILayout.PropertyField(m_NetworkProfileMetrics);
#if MULTIPLAYER_TOOLS
EditorGUILayout.PropertyField(m_NetworkMessageMetrics);
#endif
EditorGUILayout.Space(); EditorGUILayout.Space();
EditorGUILayout.LabelField("Prefab Settings", EditorStyles.boldLabel); EditorGUILayout.LabelField("Prefab Settings", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_ForceSamePrefabsProperty); EditorGUILayout.PropertyField(m_ForceSamePrefabsProperty);

View File

@@ -1,5 +1,7 @@
using System.Collections.Generic; using System.Collections.Generic;
#if MULTIPLAYER_SDK_INSTALLED
using System.Linq; using System.Linq;
#endif
using UnityEditor; using UnityEditor;
using UnityEngine; using UnityEngine;
@@ -144,7 +146,9 @@ namespace Unity.Netcode.Editor
} }
} }
// Keeping this here just in case, but it appears that in Unity 6 the visual bugs with
// enum flags is resolved
#if BYPASS_DEFAULT_ENUM_DRAWER && MULTIPLAYER_SDK_INSTALLED
[CustomPropertyDrawer(typeof(NetworkObject.OwnershipStatus))] [CustomPropertyDrawer(typeof(NetworkObject.OwnershipStatus))]
public class NetworkObjectOwnership : PropertyDrawer public class NetworkObjectOwnership : PropertyDrawer
{ {
@@ -188,4 +192,5 @@ namespace Unity.Netcode.Editor
EditorGUI.EndProperty(); EditorGUI.EndProperty();
} }
} }
#endif
} }

View File

@@ -53,6 +53,11 @@
"name": "com.unity.transport", "name": "com.unity.transport",
"expression": "2.0", "expression": "2.0",
"define": "UTP_TRANSPORT_2_0_ABOVE" "define": "UTP_TRANSPORT_2_0_ABOVE"
},
{
"name": "com.unity.services.multiplayer",
"expression": "0.2.0",
"define": "MULTIPLAYER_SDK_INSTALLED"
} }
], ],
"noEngineReferences": false "noEngineReferences": false

View File

@@ -1,6 +1,7 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: 3b8ed52f1b5c64994af4c4e0aa4b6c4b guid: 2e42215d00468b549bbc69ebf8a74a1e
AssemblyDefinitionImporter: folderAsset: yes
DefaultImporter:
externalObjects: {} externalObjects: {}
userData: userData:
assetBundleName: assetBundleName:

View File

@@ -195,7 +195,9 @@ namespace Unity.Netcode
double range = m_EndTimeConsumed - m_StartTimeConsumed; double range = m_EndTimeConsumed - m_StartTimeConsumed;
if (range > k_SmallValue) if (range > k_SmallValue)
{ {
t = (float)((renderTime - m_StartTimeConsumed) / range); var rangeFactor = 1.0f / (float)range;
t = ((float)renderTime - (float)m_StartTimeConsumed) * rangeFactor;
if (t < 0.0f) if (t < 0.0f)
{ {

View File

@@ -32,9 +32,13 @@ namespace Unity.Netcode.Components
/// </summary> /// </summary>
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{ {
HalfVector3.NetworkSerialize(serializer); if (!SynchronizeBase)
if (SynchronizeBase)
{ {
HalfVector3.NetworkSerialize(serializer);
}
else
{
serializer.SerializeValue(ref DeltaPosition);
serializer.SerializeValue(ref CurrentBasePosition); serializer.SerializeValue(ref CurrentBasePosition);
} }
} }

View File

@@ -23,6 +23,7 @@ namespace Unity.Netcode.Components
/// extrapolation and <see cref="NetworkTransform.Interpolate"/> is enabled, then non-authoritative instances will automatically be adjusted to use Rigidbody /// extrapolation and <see cref="NetworkTransform.Interpolate"/> is enabled, then non-authoritative instances will automatically be adjusted to use Rigidbody
/// interpolation while the authoritative instance will still use extrapolation. /// interpolation while the authoritative instance will still use extrapolation.
/// </remarks> /// </remarks>
[Tooltip("When enabled and a NetworkTransform component is attached, the NetworkTransform will use the rigid body for motion and detecting changes in state.")]
public bool UseRigidBodyForMotion; public bool UseRigidBodyForMotion;
/// <summary> /// <summary>
@@ -43,7 +44,7 @@ namespace Unity.Netcode.Components
private bool m_IsAuthority; private bool m_IsAuthority;
private Rigidbody m_Rigidbody; private Rigidbody m_Rigidbody;
private Rigidbody2D m_Rigidbody2D; private Rigidbody2D m_Rigidbody2D;
private NetworkTransform m_NetworkTransform; internal NetworkTransform NetworkTransform;
private enum InterpolationTypes private enum InterpolationTypes
{ {
None, None,
@@ -85,7 +86,7 @@ namespace Unity.Netcode.Components
RigidbodyType = rigidbodyType; RigidbodyType = rigidbodyType;
m_Rigidbody2D = rigidbody2D; m_Rigidbody2D = rigidbody2D;
m_Rigidbody = rigidbody; m_Rigidbody = rigidbody;
m_NetworkTransform = networkTransform; NetworkTransform = networkTransform;
if (m_IsRigidbody2D && m_Rigidbody2D == null) if (m_IsRigidbody2D && m_Rigidbody2D == null)
{ {
@@ -99,14 +100,14 @@ namespace Unity.Netcode.Components
SetOriginalInterpolation(); SetOriginalInterpolation();
if (m_NetworkTransform == null) if (NetworkTransform == null)
{ {
m_NetworkTransform = GetComponent<NetworkTransform>(); NetworkTransform = GetComponent<NetworkTransform>();
} }
if (m_NetworkTransform != null) if (NetworkTransform != null)
{ {
m_NetworkTransform.RegisterRigidbody(this); NetworkTransform.RegisterRigidbody(this);
} }
else else
{ {
@@ -218,7 +219,11 @@ namespace Unity.Netcode.Components
{ {
if (m_IsRigidbody2D) if (m_IsRigidbody2D)
{ {
m_Rigidbody2D.MoveRotation(rotation); var quaternion = Quaternion.identity;
var angles = quaternion.eulerAngles;
angles.z = m_Rigidbody2D.rotation;
quaternion.eulerAngles = angles;
m_Rigidbody2D.MoveRotation(quaternion);
} }
else else
{ {
@@ -381,7 +386,7 @@ namespace Unity.Netcode.Components
if (UseRigidBodyForMotion) if (UseRigidBodyForMotion)
{ {
// Only if the NetworkTransform is set to interpolate do we need to check for extrapolation // Only if the NetworkTransform is set to interpolate do we need to check for extrapolation
if (m_NetworkTransform.Interpolate && m_OriginalInterpolation == InterpolationTypes.Extrapolate) if (NetworkTransform.Interpolate && m_OriginalInterpolation == InterpolationTypes.Extrapolate)
{ {
if (IsKinematic()) if (IsKinematic())
{ {
@@ -402,7 +407,7 @@ namespace Unity.Netcode.Components
} }
else else
{ {
SetInterpolation(m_IsAuthority ? m_OriginalInterpolation : (m_NetworkTransform.Interpolate ? InterpolationTypes.None : m_OriginalInterpolation)); SetInterpolation(m_IsAuthority ? m_OriginalInterpolation : (NetworkTransform.Interpolate ? InterpolationTypes.None : m_OriginalInterpolation));
} }
} }
@@ -477,7 +482,7 @@ namespace Unity.Netcode.Components
} }
else else
{ {
if (m_NetworkTransform.IsServerAuthoritative()) if (NetworkTransform.IsServerAuthoritative())
{ {
m_IsAuthority = NetworkManager.IsServer; m_IsAuthority = NetworkManager.IsServer;
} }
@@ -502,6 +507,12 @@ namespace Unity.Netcode.Components
/// <inheritdoc /> /// <inheritdoc />
public override void OnNetworkDespawn() public override void OnNetworkDespawn()
{ {
if (UseRigidBodyForMotion && HasAuthority)
{
DetachFromFixedJoint();
NetworkRigidbodyConnections.Clear();
}
// If we are automatically handling the kinematic state... // If we are automatically handling the kinematic state...
if (AutoUpdateKinematicState || AutoSetKinematicOnDespawn) if (AutoUpdateKinematicState || AutoSetKinematicOnDespawn)
{ {
@@ -513,21 +524,197 @@ namespace Unity.Netcode.Components
SetInterpolation(m_OriginalInterpolation); SetInterpolation(m_OriginalInterpolation);
} }
// TODO: Possibly provide a NetworkJoint that allows for more options than fixed.
// Rigidbodies do not have the concept of "local space", and as such using a fixed joint will hold the object
// in place relative to the parent so jitter/stutter does not occur.
// Alternately, users can affix the fixed joint to a child GameObject (without a rigid body) of the parent NetworkObject
// and then add a NetworkTransform to that in order to get the parented child NetworkObject to move around in "local space"
public FixedJoint FixedJoint { get; private set; }
public FixedJoint2D FixedJoint2D { get; private set; }
internal System.Collections.Generic.List<NetworkRigidbodyBase> NetworkRigidbodyConnections = new System.Collections.Generic.List<NetworkRigidbodyBase>();
internal NetworkRigidbodyBase ParentBody;
private bool m_FixedJoint2DUsingGravity;
private bool m_OriginalGravitySetting;
private float m_OriginalGravityScale;
/// <summary> /// <summary>
/// When <see cref="UseRigidBodyForMotion"/> is enabled, the <see cref="NetworkTransform"/> will update Kinematic instances using /// When using a custom <see cref="NetworkRigidbodyBase"/>, this virtual method is invoked when the
/// the Rigidbody's move methods allowing Rigidbody interpolation settings to be taken into consideration by the physics simulation. /// <see cref="FixedJoint"/> is created in the event any additional adjustments are needed.
/// </summary>
protected virtual void OnFixedJointCreated()
{
}
/// <summary>
/// When using a custom <see cref="NetworkRigidbodyBase"/>, this virtual method is invoked when the
/// <see cref="FixedJoint2D"/> is created in the event any additional adjustments are needed.
/// </summary>
protected virtual void OnFixedJoint2DCreated()
{
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyFixedJoint2D(NetworkRigidbodyBase bodyToConnect, Vector3 position, float connectedMassScale = 0.0f, float massScale = 1.0f, bool useGravity = false, bool zeroVelocity = true)
{
transform.position = position;
m_Rigidbody2D.position = position;
m_OriginalGravitySetting = bodyToConnect.m_Rigidbody.useGravity;
m_FixedJoint2DUsingGravity = useGravity;
if (!useGravity)
{
m_OriginalGravityScale = m_Rigidbody2D.gravityScale;
m_Rigidbody2D.gravityScale = 0.0f;
}
if (zeroVelocity)
{
m_Rigidbody2D.velocity = Vector2.zero;
m_Rigidbody2D.angularVelocity = 0.0f;
}
FixedJoint2D = gameObject.AddComponent<FixedJoint2D>();
FixedJoint2D.connectedBody = bodyToConnect.m_Rigidbody2D;
OnFixedJoint2DCreated();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyFixedJoint(NetworkRigidbodyBase bodyToConnectTo, Vector3 position, float connectedMassScale = 0.0f, float massScale = 1.0f, bool useGravity = false, bool zeroVelocity = true)
{
transform.position = position;
m_Rigidbody.position = position;
if (zeroVelocity)
{
m_Rigidbody.linearVelocity = Vector3.zero;
m_Rigidbody.angularVelocity = Vector3.zero;
}
m_OriginalGravitySetting = m_Rigidbody.useGravity;
m_Rigidbody.useGravity = useGravity;
FixedJoint = gameObject.AddComponent<FixedJoint>();
FixedJoint.connectedBody = bodyToConnectTo.m_Rigidbody;
FixedJoint.connectedMassScale = connectedMassScale;
FixedJoint.massScale = massScale;
OnFixedJointCreated();
}
/// <summary>
/// Authority Only:
/// When invoked and not already attached to a fixed joint, this will connect two rigid bodies with <see cref="UseRigidBodyForMotion"/> enabled.
/// Invoke this method on the rigid body you wish to attach to another (i.e. weapon to player, sticky bomb to player/object, etc).
/// <seealso cref="FixedJoint"/>
/// <seealso cref="FixedJoint2D"/>
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// This will update the associated <see cref="NetworkTransform"/> during FixedUpdate which also avoids the added expense of adding /// Parenting relative:
/// a FixedUpdate to all <see cref="NetworkTransform"/> instances where some might not be using a Rigidbody. /// - This instance can be viewed as the child.
/// - The <param name="objectToConnectTo"/> can be viewed as the parent.
/// <br/>
/// This is the recommended way, as opposed to parenting, to attached/detatch two rigid bodies to one another when <see cref="UseRigidBodyForMotion"/> is enabled.
/// For more details on using <see cref="UnityEngine.FixedJoint"/> and <see cref="UnityEngine.FixedJoint2D"/>.
/// <br/>
/// This provides a simple joint solution between two rigid bodies and serves as an example. You can add different joint types by creating a customized/derived
/// version of <see cref="NetworkRigidbodyBase"/>.
/// </remarks> /// </remarks>
private void FixedUpdate() /// <param name="objectToConnectTo">The target object to attach to.</param>
/// <param name="positionOfConnection">The position of the connection (i.e. where you want the object to be affixed).</param>
/// <param name="connectedMassScale">The target object's mass scale relative to this object being attached.</param>
/// <param name="massScale">This object's mass scale relative to the target object's.</param>
/// <param name="useGravity">Determines if this object will have gravity applied to it along with the object you are connecting this one to (the default is to not use gravity for this object)</param>
/// <param name="zeroVelocity">When true (the default), both linear and angular velocities of this object are set to zero.</param>
/// <param name="teleportObject">When true (the default), this object will teleport itself to the position of connection.</param>
/// <returns>true (success) false (failed)</returns>
public bool AttachToFixedJoint(NetworkRigidbodyBase objectToConnectTo, Vector3 positionOfConnection, float connectedMassScale = 0.0f, float massScale = 1.0f, bool useGravity = false, bool zeroVelocity = true, bool teleportObject = true)
{ {
if (!IsSpawned || m_NetworkTransform == null || !UseRigidBodyForMotion) if (!UseRigidBodyForMotion)
{ {
return; Debug.LogError($"[{GetType().Name}] {name} does not have {nameof(UseRigidBodyForMotion)} set! Either enable {nameof(UseRigidBodyForMotion)} on this component or do not use a {nameof(FixedJoint)} when parenting under a {nameof(NetworkObject)}.");
return false;
}
if (IsKinematic())
{
Debug.LogError($"[{GetType().Name}] {name} is currently kinematic! You cannot use a {nameof(FixedJoint)} with Kinematic bodies!");
return false;
}
if (objectToConnectTo != null)
{
if (m_IsRigidbody2D)
{
ApplyFixedJoint2D(objectToConnectTo, positionOfConnection, connectedMassScale, massScale, useGravity, zeroVelocity);
}
else
{
ApplyFixedJoint(objectToConnectTo, positionOfConnection, connectedMassScale, massScale, useGravity, zeroVelocity);
}
ParentBody = objectToConnectTo;
ParentBody.NetworkRigidbodyConnections.Add(this);
if (teleportObject)
{
NetworkTransform.SetState(teleportDisabled: false);
}
return true;
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void RemoveFromParentBody()
{
ParentBody.NetworkRigidbodyConnections.Remove(this);
ParentBody = null;
}
/// <summary>
/// Authority Only:
/// When invoked and already connected to an object via <see cref="FixedJoint"/> or <see cref="FixedJoint2D"/> (depending upon the type of rigid body),
/// this will detach from the fixed joint and destroy the fixed joint component.
/// </summary>
/// <remarks>
/// This is the recommended way, as opposed to parenting, to attached/detatch two rigid bodies to one another when <see cref="UseRigidBodyForMotion"/> is enabled.
/// </remarks>
public void DetachFromFixedJoint()
{
if (!HasAuthority)
{
Debug.LogError($"[{name}] Only authority can invoke {nameof(DetachFromFixedJoint)}!");
}
if (UseRigidBodyForMotion)
{
if (m_IsRigidbody2D)
{
if (FixedJoint2D != null)
{
if (!m_FixedJoint2DUsingGravity)
{
FixedJoint2D.connectedBody.gravityScale = m_OriginalGravityScale;
}
FixedJoint2D.connectedBody = null;
Destroy(FixedJoint2D);
FixedJoint2D = null;
ResetInterpolation();
RemoveFromParentBody();
}
}
else
{
if (FixedJoint != null)
{
FixedJoint.connectedBody = null;
m_Rigidbody.useGravity = m_OriginalGravitySetting;
Destroy(FixedJoint);
FixedJoint = null;
ResetInterpolation();
RemoveFromParentBody();
}
}
} }
m_NetworkTransform.OnFixedUpdate();
} }
} }
} }

View File

@@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Text; using System.Text;
using Unity.Mathematics; using Unity.Mathematics;
@@ -16,7 +15,6 @@ namespace Unity.Netcode.Components
/// </summary> /// </summary>
[DisallowMultipleComponent] [DisallowMultipleComponent]
[AddComponentMenu("Netcode/Network Transform")] [AddComponentMenu("Netcode/Network Transform")]
[DefaultExecutionOrder(100000)] // this is needed to catch the update time after the transform was updated by user scripts
public class NetworkTransform : NetworkBehaviour public class NetworkTransform : NetworkBehaviour
{ {
#region NETWORK TRANSFORM STATE #region NETWORK TRANSFORM STATE
@@ -1186,12 +1184,6 @@ namespace Unity.Netcode.Components
/// </summary> /// </summary>
public bool CanCommitToTransform { get; protected set; } public bool CanCommitToTransform { get; protected set; }
/// <summary>
/// Internally used by <see cref="NetworkTransform"/> to keep track of whether this <see cref="NetworkBehaviour"/> derived class instance
/// was instantiated on the server side or not.
/// </summary>
protected bool m_CachedIsServer; // Note: we no longer use this and are only keeping it until we decide to deprecate it
/// <summary> /// <summary>
/// Internally used by <see cref="NetworkTransform"/> to keep track of the <see cref="NetworkManager"/> instance assigned to this /// Internally used by <see cref="NetworkTransform"/> to keep track of the <see cref="NetworkManager"/> instance assigned to this
/// this <see cref="NetworkBehaviour"/> derived class instance. /// this <see cref="NetworkBehaviour"/> derived class instance.
@@ -1564,6 +1556,14 @@ namespace Unity.Netcode.Components
NetworkLog.LogError($"[{name}] is trying to commit the transform without authority!"); NetworkLog.LogError($"[{name}] is trying to commit the transform without authority!");
return; return;
} }
#if COM_UNITY_MODULES_PHYSICS
// TODO: Make this an authority flag
// For now, just synchronize with the NetworkRigidbodyBase UseRigidBodyForMotion
if (m_NetworkRigidbodyInternal != null)
{
m_UseRigidbodyForMotion = m_NetworkRigidbodyInternal.UseRigidBodyForMotion;
}
#endif
// If the transform has deltas (returns dirty) or if an explicitly set state is pending // 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)) if (m_LocalAuthoritativeNetworkState.ExplicitSet || CheckForStateChange(ref m_LocalAuthoritativeNetworkState, ref transformToCommit, synchronize))
@@ -1609,6 +1609,17 @@ namespace Unity.Netcode.Components
{ {
m_DeltaSynch = true; m_DeltaSynch = true;
} }
#if COM_UNITY_MODULES_PHYSICS
// We handle updating attached bodies when the "parent" body has a state update in order to keep their delta state updates tick synchronized.
if (m_UseRigidbodyForMotion && m_NetworkRigidbodyInternal.NetworkRigidbodyConnections.Count > 0)
{
foreach (var childRigidbody in m_NetworkRigidbodyInternal.NetworkRigidbodyConnections)
{
childRigidbody.NetworkTransform.OnNetworkTick(true);
}
}
#endif
} }
} }
@@ -1696,6 +1707,26 @@ namespace Unity.Netcode.Components
var scale = transformToUse.localScale; var scale = transformToUse.localScale;
networkState.IsSynchronizing = isSynchronization; networkState.IsSynchronizing = isSynchronization;
// All of the checks below, up to the delta position checking portion, are to determine if the
// authority changed a property during runtime that requires a full synchronizing.
#if COM_UNITY_MODULES_PHYSICS
if (InLocalSpace != networkState.InLocalSpace && !m_UseRigidbodyForMotion)
#else
if (InLocalSpace != networkState.InLocalSpace)
#endif
{
networkState.InLocalSpace = InLocalSpace;
isDirty = true;
networkState.IsTeleportingNextFrame = true;
}
#if COM_UNITY_MODULES_PHYSICS
else if (InLocalSpace && m_UseRigidbodyForMotion)
{
// TODO: Provide more options than just FixedJoint
Debug.LogError($"[Rigidbody] WHen using a Rigidbody for motion, you cannot use {nameof(InLocalSpace)}! If parenting, use the integrated FixedJoint or use a Joint on Authority side.");
}
#endif
// Check for parenting when synchronizing and/or teleporting // Check for parenting when synchronizing and/or teleporting
if (isSynchronization || networkState.IsTeleportingNextFrame) if (isSynchronization || networkState.IsTeleportingNextFrame)
{ {
@@ -1705,11 +1736,13 @@ namespace Unity.Netcode.Components
// values are applied. // values are applied.
var hasParentNetworkObject = false; var hasParentNetworkObject = false;
var parentNetworkObject = (NetworkObject)null;
// If the NetworkObject belonging to this NetworkTransform instance has a parent // If the NetworkObject belonging to this NetworkTransform instance has a parent
// (i.e. this handles nested NetworkTransforms under a parent at some layer above) // (i.e. this handles nested NetworkTransforms under a parent at some layer above)
if (NetworkObject.transform.parent != null) if (NetworkObject.transform.parent != null)
{ {
var parentNetworkObject = NetworkObject.transform.parent.GetComponent<NetworkObject>(); parentNetworkObject = NetworkObject.transform.parent.GetComponent<NetworkObject>();
// In-scene placed NetworkObjects parented under a GameObject with no // In-scene placed NetworkObjects parented under a GameObject with no
// NetworkObject preserve their lossyScale when synchronizing. // NetworkObject preserve their lossyScale when synchronizing.
@@ -1730,28 +1763,25 @@ namespace Unity.Netcode.Components
// the NetworkTransform is using world or local space synchronization. // the NetworkTransform is using world or local space synchronization.
// WorldPositionStays: (always use world space) // WorldPositionStays: (always use world space)
// !WorldPositionStays: (always use local space) // !WorldPositionStays: (always use local space)
if (isSynchronization) // Exception: If it is an in-scene placed NetworkObject and it is parented under a GameObject
// then always use local space unless AutoObjectParentSync is disabled and the NetworkTransform
// is synchronizing in world space.
if (isSynchronization && networkState.IsParented)
{ {
if (NetworkObject.WorldPositionStays()) var parentedUnderGameObject = NetworkObject.transform.parent != null && !parentNetworkObject && NetworkObject.IsSceneObject.Value;
if (NetworkObject.WorldPositionStays() && (!parentedUnderGameObject || (parentedUnderGameObject && !NetworkObject.AutoObjectParentSync && !InLocalSpace)))
{ {
position = transformToUse.position; position = transformToUse.position;
networkState.InLocalSpace = false;
} }
else else
{ {
position = transformToUse.localPosition; position = transformToUse.localPosition;
networkState.InLocalSpace = true;
} }
} }
} }
// All of the checks below, up to the delta position checking portion, are to determine if the
// authority changed a property during runtime that requires a full synchronizing.
if (InLocalSpace != networkState.InLocalSpace)
{
networkState.InLocalSpace = InLocalSpace;
isDirty = true;
networkState.IsTeleportingNextFrame = true;
}
if (Interpolate != networkState.UseInterpolation) if (Interpolate != networkState.UseInterpolation)
{ {
networkState.UseInterpolation = Interpolate; networkState.UseInterpolation = Interpolate;
@@ -1968,7 +1998,7 @@ namespace Unity.Netcode.Components
} }
if (isRotationDirty) if (isRotationDirty)
{ {
networkState.Rotation = InLocalSpace ? transformToUse.localRotation : transformToUse.rotation; networkState.Rotation = rotation;
networkState.HasRotAngleX = true; networkState.HasRotAngleX = true;
networkState.HasRotAngleY = true; networkState.HasRotAngleY = true;
networkState.HasRotAngleZ = true; networkState.HasRotAngleZ = true;
@@ -2067,15 +2097,31 @@ namespace Unity.Netcode.Components
/// Authority subscribes to network tick events and will invoke /// Authority subscribes to network tick events and will invoke
/// <see cref="OnUpdateAuthoritativeState(ref Transform)"/> each network tick. /// <see cref="OnUpdateAuthoritativeState(ref Transform)"/> each network tick.
/// </summary> /// </summary>
private void OnNetworkTick() private void OnNetworkTick(bool isCalledFromParent = false)
{ {
// If not active, then ignore the update
if (!gameObject.activeInHierarchy)
{
return;
}
// As long as we are still authority // As long as we are still authority
if (CanCommitToTransform) if (CanCommitToTransform)
{ {
if (m_CachedNetworkManager.DistributedAuthorityMode && !IsOwner) if (m_CachedNetworkManager.DistributedAuthorityMode && !IsOwner)
{ {
Debug.LogError($"Non-owner Client-{m_CachedNetworkManager.LocalClientId} is being updated by network tick still!!!!"); Debug.LogError($"Non-owner Client-{m_CachedNetworkManager.LocalClientId} is being updated by network tick still!!!!");
return;
} }
#if COM_UNITY_MODULES_PHYSICS
// Let the parent handle the updating of this to keep the two synchronized
if (!isCalledFromParent && m_UseRigidbodyForMotion && m_NetworkRigidbodyInternal.ParentBody != null && !m_LocalAuthoritativeNetworkState.IsTeleportingNextFrame)
{
return;
}
#endif
// Update any changes to the transform // Update any changes to the transform
var transformSource = transform; var transformSource = transform;
OnUpdateAuthoritativeState(ref transformSource); OnUpdateAuthoritativeState(ref transformSource);
@@ -2087,9 +2133,8 @@ namespace Unity.Netcode.Components
#endif #endif
} }
else // If we are no longer authority, unsubscribe to the tick event else // If we are no longer authority, unsubscribe to the tick event
if (NetworkManager != null && NetworkManager.NetworkTickSystem != null)
{ {
NetworkManager.NetworkTickSystem.Tick -= OnNetworkTick; DeregisterForTickUpdate(this);
} }
} }
#endregion #endregion
@@ -2119,6 +2164,14 @@ namespace Unity.Netcode.Components
/// </summary> /// </summary>
private void ApplyAuthoritativeState() private void ApplyAuthoritativeState()
{ {
#if COM_UNITY_MODULES_PHYSICS
// TODO: Make this an authority flag
// For now, just synchronize with the NetworkRigidbodyBase UseRigidBodyForMotion
if (m_NetworkRigidbodyInternal != null)
{
m_UseRigidbodyForMotion = m_NetworkRigidbodyInternal.UseRigidBodyForMotion;
}
#endif
var networkState = m_LocalAuthoritativeNetworkState; var networkState = m_LocalAuthoritativeNetworkState;
// The m_CurrentPosition, m_CurrentRotation, and m_CurrentScale values are continually updated // The m_CurrentPosition, m_CurrentRotation, and m_CurrentScale values are continually updated
// at the end of this method and assure that when not interpolating the non-authoritative side // at the end of this method and assure that when not interpolating the non-authoritative side
@@ -2842,12 +2895,6 @@ namespace Unity.Netcode.Components
/// <inheritdoc/> /// <inheritdoc/>
public override void OnNetworkSpawn() public override void OnNetworkSpawn()
{ {
///////////////////////////////////////////////////////////////
// NOTE: Legacy and no longer used (candidates for deprecation)
m_CachedIsServer = IsServer;
///////////////////////////////////////////////////////////////
// Started using this again to avoid the getter processing cost of NetworkBehaviour.NetworkManager
m_CachedNetworkManager = NetworkManager; m_CachedNetworkManager = NetworkManager;
Initialize(); Initialize();
@@ -2860,6 +2907,13 @@ namespace Unity.Netcode.Components
private void CleanUpOnDestroyOrDespawn() private void CleanUpOnDestroyOrDespawn()
{ {
#if COM_UNITY_MODULES_PHYSICS
var forUpdate = !m_UseRigidbodyForMotion;
#else
var forUpdate = true;
#endif
NetworkManager?.NetworkTransformRegistration(this, forUpdate, false);
DeregisterForTickUpdate(this); DeregisterForTickUpdate(this);
CanCommitToTransform = false; CanCommitToTransform = false;
} }
@@ -2918,7 +2972,7 @@ namespace Unity.Netcode.Components
m_ScaleInterpolator.ResetTo(transform.localScale, serverTime); m_ScaleInterpolator.ResetTo(transform.localScale, serverTime);
m_RotationInterpolator.ResetTo(rotation, serverTime); m_RotationInterpolator.ResetTo(rotation, serverTime);
} }
private NetworkObject m_CachedNetworkObject;
/// <summary> /// <summary>
/// The internal initialzation method to allow for internal API adjustments /// The internal initialzation method to allow for internal API adjustments
/// </summary> /// </summary>
@@ -2929,7 +2983,7 @@ namespace Unity.Netcode.Components
{ {
return; return;
} }
m_CachedNetworkObject = NetworkObject;
CanCommitToTransform = IsServerAuthoritative() ? IsServer : IsOwner; CanCommitToTransform = IsServerAuthoritative() ? IsServer : IsOwner;
var currentPosition = GetSpaceRelativePosition(); var currentPosition = GetSpaceRelativePosition();
var currentRotation = GetSpaceRelativeRotation(); var currentRotation = GetSpaceRelativeRotation();
@@ -2952,10 +3006,17 @@ namespace Unity.Netcode.Components
m_NetworkRigidbodyInternal.SetPosition(currentPosition); m_NetworkRigidbodyInternal.SetPosition(currentPosition);
m_NetworkRigidbodyInternal.SetRotation(currentRotation); m_NetworkRigidbodyInternal.SetRotation(currentRotation);
} }
var forUpdate = !m_UseRigidbodyForMotion;
#else
var forUpdate = true;
#endif #endif
if (CanCommitToTransform) 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) if (UseHalfFloatPrecision)
{ {
m_HalfPositionState = new NetworkDeltaPosition(currentPosition, m_CachedNetworkManager.ServerTime.Tick, math.bool3(SyncPositionX, SyncPositionY, SyncPositionZ)); m_HalfPositionState = new NetworkDeltaPosition(currentPosition, m_CachedNetworkManager.ServerTime.Tick, math.bool3(SyncPositionX, SyncPositionY, SyncPositionZ));
@@ -2973,6 +3034,8 @@ namespace Unity.Netcode.Components
} }
else else
{ {
// Non-authority needs to be added to updates for interpolation and applying state purposes
m_CachedNetworkManager.NetworkTransformRegistration(this, forUpdate, true);
// Remove this instance from the tick update // Remove this instance from the tick update
DeregisterForTickUpdate(this); DeregisterForTickUpdate(this);
@@ -3233,7 +3296,7 @@ namespace Unity.Netcode.Components
{ {
var serverTime = m_CachedNetworkManager.ServerTime; var serverTime = m_CachedNetworkManager.ServerTime;
var cachedServerTime = serverTime.Time; var cachedServerTime = serverTime.Time;
var offset = 0f; var offset = (float)serverTime.TickOffset;
#if COM_UNITY_MODULES_PHYSICS #if COM_UNITY_MODULES_PHYSICS
var cachedDeltaTime = m_UseRigidbodyForMotion ? m_CachedNetworkManager.RealTimeProvider.FixedDeltaTime : m_CachedNetworkManager.RealTimeProvider.DeltaTime; var cachedDeltaTime = m_UseRigidbodyForMotion ? m_CachedNetworkManager.RealTimeProvider.FixedDeltaTime : m_CachedNetworkManager.RealTimeProvider.DeltaTime;
#else #else
@@ -3242,16 +3305,14 @@ namespace Unity.Netcode.Components
// With owner authoritative mode, non-authority clients can lag behind // With owner authoritative mode, non-authority clients can lag behind
// by more than 1 tick period of time. The current "solution" for now // by more than 1 tick period of time. The current "solution" for now
// is to make their cachedRenderTime run 2 ticks behind. // is to make their cachedRenderTime run 2 ticks behind.
#if COM_UNITY_MODULES_PHYSICS var ticksAgo = (!IsServerAuthoritative() && !IsServer) || m_CachedNetworkManager.DistributedAuthorityMode ? 2 : 1;
var ticksAgo = (!IsServerAuthoritative() && !IsServer) || m_UseRigidbodyForMotion ? 2 : 1; // TODO: We need an RTT that updates regularly and not only when the client sends packets
#else //if (m_CachedNetworkManager.DistributedAuthorityMode)
var ticksAgo = (!IsServerAuthoritative() && !IsServer) ? 2 : 1; //{
#endif //ticksAgo = m_CachedNetworkManager.CMBServiceConnection ? 2 : 3;
if (m_CachedNetworkManager.DistributedAuthorityMode) //ticksAgo = Mathf.Max(ticksAgo, (int)m_NetworkTransformTickRegistration.TicksAgo);
{ //offset = m_NetworkTransformTickRegistration.Offset;
ticksAgo = Mathf.Max(ticksAgo, (int)m_NetworkTransformTickRegistration.TicksAgo); //}
offset = m_NetworkTransformTickRegistration.Offset;
}
var cachedRenderTime = serverTime.TimeTicksAgo(ticksAgo, offset).Time; var cachedRenderTime = serverTime.TimeTicksAgo(ticksAgo, offset).Time;
@@ -3282,7 +3343,7 @@ namespace Unity.Netcode.Components
/// If you override this method, be sure that: /// If you override this method, be sure that:
/// - Non-authority always invokes this base class method. /// - Non-authority always invokes this base class method.
/// </remarks> /// </remarks>
protected virtual void Update() public virtual void OnUpdate()
{ {
// If not spawned or this instance has authority, exit early // If not spawned or this instance has authority, exit early
#if COM_UNITY_MODULES_PHYSICS #if COM_UNITY_MODULES_PHYSICS
@@ -3303,11 +3364,12 @@ namespace Unity.Netcode.Components
#if COM_UNITY_MODULES_PHYSICS #if COM_UNITY_MODULES_PHYSICS
/// <summary> /// <summary>
/// When paired with a NetworkRigidbody and NetworkRigidbody.UseRigidBodyForMotion is enabled, /// When paired with a NetworkRigidbody and NetworkRigidbody.UseRigidBodyForMotion is enabled,
/// this will be invoked during <see cref="NetworkRigidbody.FixedUpdate"/>. /// this will be invoked during <see cref="NetworkRigidbody.FixedUpdate"/>.
/// </summary> /// </summary>
internal void OnFixedUpdate() public virtual void OnFixedUpdate()
{ {
// If not spawned or this instance has authority, exit early // If not spawned or this instance has authority, exit early
if (!m_UseRigidbodyForMotion || !IsSpawned || CanCommitToTransform) if (!m_UseRigidbodyForMotion || !IsSpawned || CanCommitToTransform)
@@ -3353,32 +3415,69 @@ namespace Unity.Netcode.Components
#endregion #endregion
#region MESSAGE HANDLING #region MESSAGE HANDLING
internal NetworkTransformState InboundState = new NetworkTransformState();
internal NetworkTransformState OutboundState
{
get
{
return m_LocalAuthoritativeNetworkState;
}
}
/// <summary> /// <summary>
/// Invoked by <see cref="NetworkTransformMessage"/> to update the transform state /// Invoked by <see cref="NetworkTransformMessage"/> to update the transform state
/// </summary> /// </summary>
/// <param name="networkTransformState"></param> /// <param name="networkTransformState"></param>
internal void TransformStateUpdate(ref NetworkTransformState networkTransformState, ulong senderId) internal void TransformStateUpdate(ulong senderId)
{ {
if (CanCommitToTransform) if (CanCommitToTransform)
{ {
Debug.LogError($"Authority receiving transform update from Client-{senderId}!"); // TODO: Investigate where this state should be applied or just discarded.
// For now, discard the state if we assumed ownership.
return;
} }
// Store the previous/old state // Store the previous/old state
m_OldState = m_LocalAuthoritativeNetworkState; m_OldState = m_LocalAuthoritativeNetworkState;
// Assign the new incoming state // Assign the new incoming state
m_LocalAuthoritativeNetworkState = networkTransformState; m_LocalAuthoritativeNetworkState = InboundState;
// Apply the state update // Apply the state update
OnNetworkStateChanged(m_OldState, m_LocalAuthoritativeNetworkState); OnNetworkStateChanged(m_OldState, m_LocalAuthoritativeNetworkState);
} }
// Used to send outbound messages
private NetworkTransformMessage m_OutboundMessage = new NetworkTransformMessage();
internal void SerializeMessage(FastBufferWriter writer, int targetVersion)
{
var networkObject = NetworkObject;
BytePacker.WriteValueBitPacked(writer, NetworkObjectId);
BytePacker.WriteValueBitPacked(writer, (int)NetworkBehaviourId);
writer.WriteNetworkSerializable(m_LocalAuthoritativeNetworkState);
if (m_CachedNetworkManager.DistributedAuthorityMode)
{
BytePacker.WriteValuePacked(writer, networkObject.Observers.Count - 1);
foreach (var targetId in networkObject.Observers)
{
if (OwnerClientId == targetId)
{
continue;
}
BytePacker.WriteValuePacked(writer, targetId);
}
}
}
/// <summary> /// <summary>
/// Invoked by the authoritative instance to sends a <see cref="NetworkTransformMessage"/> containing the <see cref="NetworkTransformState"/> /// Invoked by the authoritative instance to sends a <see cref="NetworkTransformMessage"/> containing the <see cref="NetworkTransformState"/>
/// </summary> /// </summary>
private void UpdateTransformState() private void UpdateTransformState()
{ {
if (m_CachedNetworkManager.ShutdownInProgress) if (m_CachedNetworkManager.ShutdownInProgress || (m_CachedNetworkManager.DistributedAuthorityMode && m_CachedNetworkObject.Observers.Count - 1 == 0))
{ {
return; return;
} }
@@ -3393,17 +3492,7 @@ namespace Unity.Netcode.Components
Debug.LogError($"Owner authoritative {nameof(NetworkTransform)} can only be updated by the owner!"); Debug.LogError($"Owner authoritative {nameof(NetworkTransform)} can only be updated by the owner!");
} }
var customMessageManager = m_CachedNetworkManager.CustomMessagingManager; var customMessageManager = m_CachedNetworkManager.CustomMessagingManager;
m_OutboundMessage.NetworkTransform = this;
var networkTransformMessage = new NetworkTransformMessage()
{
NetworkObjectId = NetworkObjectId,
NetworkBehaviourId = NetworkBehaviourId,
State = m_LocalAuthoritativeNetworkState,
DistributedAuthorityMode = m_CachedNetworkManager.DistributedAuthorityMode,
// Don't populate if we are the DAHost as we send directly to each client
TargetIds = m_CachedNetworkManager.DistributedAuthorityMode && !m_CachedNetworkManager.DAHost ? NetworkObject.Observers.Where((c) => c != m_CachedNetworkManager.LocalClientId).ToArray() : null,
};
// Determine what network delivery method to use: // Determine what network delivery method to use:
// When to send reliable packets: // When to send reliable packets:
@@ -3429,13 +3518,13 @@ namespace Unity.Netcode.Components
{ {
continue; continue;
} }
NetworkManager.MessageManager.SendMessage(ref networkTransformMessage, networkDelivery, clientId); NetworkManager.MessageManager.SendMessage(ref m_OutboundMessage, networkDelivery, clientId);
} }
} }
else else
{ {
// Clients (owner authoritative) send messages to the server-host // Clients (owner authoritative) send messages to the server-host
NetworkManager.MessageManager.SendMessage(ref networkTransformMessage, networkDelivery, NetworkManager.ServerClientId); NetworkManager.MessageManager.SendMessage(ref m_OutboundMessage, networkDelivery, NetworkManager.ServerClientId);
} }
} }
#endregion #endregion
@@ -3509,7 +3598,9 @@ namespace Unity.Netcode.Components
internal float TicksAgoInSeconds() internal float TicksAgoInSeconds()
{ {
return Mathf.Max(1.0f, TicksAgo) * m_TickFrequency; return 2 * m_TickFrequency;
// TODO: We need an RTT that updates regularly and not just when the client sends packets
//return Mathf.Max(1.0f, TicksAgo) * m_TickFrequency;
} }
/// <summary> /// <summary>
@@ -3518,25 +3609,26 @@ namespace Unity.Netcode.Components
/// </summary> /// </summary>
private void TickUpdate() private void TickUpdate()
{ {
if (m_UnityTransport != null) // TODO: We need an RTT that updates regularly and not just when the client sends packets
{ //if (m_UnityTransport != null)
// Determine the desired ticks ago by the RTT (this really should be the combination of the //{
// authority and non-authority 1/2 RTT but in the end anything beyond 300ms is considered very poor // // Determine the desired ticks ago by the RTT (this really should be the combination of the
// network quality so latent interpolation is going to be expected). // // authority and non-authority 1/2 RTT but in the end anything beyond 300ms is considered very poor
var rtt = Mathf.Max(m_TickInMS, m_UnityTransport.GetCurrentRtt(NetworkManager.ServerClientId)); // // network quality so latent interpolation is going to be expected).
m_TicksAgoSamples[m_TickSampleIndex] = Mathf.Max(1, (int)(rtt * m_TickFrequency)); // var rtt = Mathf.Max(m_TickInMS, m_UnityTransport.GetCurrentRtt(NetworkManager.ServerClientId));
var tickAgoSum = 0.0f; // m_TicksAgoSamples[m_TickSampleIndex] = Mathf.Max(1, (int)(rtt * m_TickFrequency));
foreach (var tickAgo in m_TicksAgoSamples) // var tickAgoSum = 0.0f;
{ // foreach (var tickAgo in m_TicksAgoSamples)
tickAgoSum += tickAgo; // {
} // tickAgoSum += tickAgo;
m_PreviousTicksAgo = TicksAgo; // }
TicksAgo = Mathf.Lerp(m_PreviousTicksAgo, tickAgoSum / m_TickRate, m_TickFrequency); // m_PreviousTicksAgo = TicksAgo;
m_TickSampleIndex = (m_TickSampleIndex + 1) % m_TickRate; // TicksAgo = Mathf.Lerp(m_PreviousTicksAgo, tickAgoSum / m_TickRate, m_TickFrequency);
// Get the partial tick value for when this is all calculated to provide an offset for determining // m_TickSampleIndex = (m_TickSampleIndex + 1) % m_TickRate;
// the relative starting interpolation point for the next update // // Get the partial tick value for when this is all calculated to provide an offset for determining
Offset = m_OffsetTickFrequency * (Mathf.Max(2, TicksAgo) - (int)TicksAgo); // // the relative starting interpolation point for the next update
} // Offset = m_OffsetTickFrequency * (Mathf.Max(2, TicksAgo) - (int)TicksAgo);
//}
// TODO FIX: The local NetworkTickSystem can invoke with the same network tick as before // TODO FIX: The local NetworkTickSystem can invoke with the same network tick as before
if (m_NetworkManager.ServerTime.Tick <= m_LastTick) if (m_NetworkManager.ServerTime.Tick <= m_LastTick)
@@ -3556,13 +3648,13 @@ namespace Unity.Netcode.Components
private UnityTransport m_UnityTransport; private UnityTransport m_UnityTransport;
private float m_TickFrequency; private float m_TickFrequency;
private float m_OffsetTickFrequency; //private float m_OffsetTickFrequency;
private ulong m_TickInMS; //private ulong m_TickInMS;
private int m_TickSampleIndex; //private int m_TickSampleIndex;
private int m_TickRate; private int m_TickRate;
public float TicksAgo { get; private set; } public float TicksAgo { get; private set; }
public float Offset { get; private set; } //public float Offset { get; private set; }
private float m_PreviousTicksAgo; //private float m_PreviousTicksAgo;
private List<float> m_TicksAgoSamples = new List<float>(); private List<float> m_TicksAgoSamples = new List<float>();
@@ -3573,19 +3665,19 @@ namespace Unity.Netcode.Components
networkManager.NetworkTickSystem.Tick += m_NetworkTickUpdate; networkManager.NetworkTickSystem.Tick += m_NetworkTickUpdate;
m_TickRate = (int)m_NetworkManager.NetworkConfig.TickRate; m_TickRate = (int)m_NetworkManager.NetworkConfig.TickRate;
m_TickFrequency = 1.0f / m_TickRate; m_TickFrequency = 1.0f / m_TickRate;
// For the offset, it uses the fractional remainder of the tick to determine the offset. //// For the offset, it uses the fractional remainder of the tick to determine the offset.
// In order to keep within tick boundaries, we increment the tick rate by 1 to assure it //// In order to keep within tick boundaries, we increment the tick rate by 1 to assure it
// will always be < the tick frequency. //// will always be < the tick frequency.
m_OffsetTickFrequency = 1.0f / (m_TickRate + 1); //m_OffsetTickFrequency = 1.0f / (m_TickRate + 1);
m_TickInMS = (ulong)(1000 * m_TickFrequency); //m_TickInMS = (ulong)(1000 * m_TickFrequency);
m_UnityTransport = m_NetworkManager.NetworkConfig.NetworkTransport as UnityTransport; //m_UnityTransport = m_NetworkManager.NetworkConfig.NetworkTransport as UnityTransport;
// Fill the sample with a starting value of 1 //// Fill the sample with a starting value of 1
for (int i = 0; i < m_TickRate; i++) //for (int i = 0; i < m_TickRate; i++)
{ //{
m_TicksAgoSamples.Add(1f); // m_TicksAgoSamples.Add(1f);
} //}
TicksAgo = 1f; TicksAgo = 2f;
m_PreviousTicksAgo = 1f; //m_PreviousTicksAgo = 1f;
if (networkManager.IsServer) if (networkManager.IsServer)
{ {
networkManager.OnServerStopped += OnNetworkManagerStopped; networkManager.OnServerStopped += OnNetworkManagerStopped;

View File

@@ -14,7 +14,7 @@ namespace Unity.Netcode
/// M = 1.0f (which M * M would still yield 1.0f) /// M = 1.0f (which M * M would still yield 1.0f)
/// w*w = M*M - (x*x + y*y + z*z) or Mathf.Sqrt(1.0f - (x*x + y*y + z*z)) /// w*w = M*M - (x*x + y*y + z*z) or Mathf.Sqrt(1.0f - (x*x + y*y + z*z))
/// w = Math.Sqrt(1.0f - (x*x + y*y + z*z)) /// w = Math.Sqrt(1.0f - (x*x + y*y + z*z))
/// Using the largest the number avoids potential loss of precision in the smallest three values. /// Using the largest number avoids potential loss of precision in the smallest three values.
/// </remarks> /// </remarks>
public static class QuaternionCompressor public static class QuaternionCompressor
{ {

View File

@@ -149,8 +149,8 @@ namespace Unity.Netcode
/// </summary> /// </summary>
public const int RttWindowSize = 64; // number of slots to use for RTT computations (max number of in-flight packets) public const int RttWindowSize = 64; // number of slots to use for RTT computations (max number of in-flight packets)
[Tooltip("Determines if the network session will run in client-server or distributed authority mode.")] [Tooltip("Determines whether to use the client-server or distributed authority network topology.")]
public SessionModeTypes SessionMode; public NetworkTopologyTypes NetworkTopology;
[HideInInspector] [HideInInspector]
public bool UseCMBService; public bool UseCMBService;
@@ -158,6 +158,12 @@ namespace Unity.Netcode
[Tooltip("When enabled (default), the player prefab will automatically be spawned (client-side) upon the client being approved and synchronized.")] [Tooltip("When enabled (default), the player prefab will automatically be spawned (client-side) upon the client being approved and synchronized.")]
public bool AutoSpawnPlayerPrefabClientSide = true; public bool AutoSpawnPlayerPrefabClientSide = true;
#if MULTIPLAYER_TOOLS
public bool NetworkMessageMetrics = true;
#endif
public bool NetworkProfilingMetrics = true;
/// <summary> /// <summary>
/// Returns a base64 encoded version of the configuration /// Returns a base64 encoded version of the configuration
/// </summary> /// </summary>

View File

@@ -4,7 +4,7 @@ using UnityEngine;
namespace Unity.Netcode namespace Unity.Netcode
{ {
public enum SessionModeTypes public enum NetworkTopologyTypes
{ {
ClientServer, ClientServer,
DistributedAuthority DistributedAuthority
@@ -41,7 +41,7 @@ namespace Unity.Netcode
/// </summary> /// </summary>
internal bool IsApproved { get; set; } internal bool IsApproved { get; set; }
public SessionModeTypes SessionModeType { get; internal set; } public NetworkTopologyTypes NetworkTopologyType { get; internal set; }
public bool DAHost { get; internal set; } public bool DAHost { get; internal set; }
@@ -77,9 +77,9 @@ namespace Unity.Netcode
if (networkManager != null) if (networkManager != null)
{ {
SpawnManager = networkManager.SpawnManager; SpawnManager = networkManager.SpawnManager;
SessionModeType = networkManager.NetworkConfig.SessionMode; NetworkTopologyType = networkManager.NetworkConfig.NetworkTopology;
if (SessionModeType == SessionModeTypes.DistributedAuthority) if (NetworkTopologyType == NetworkTopologyTypes.DistributedAuthority)
{ {
DAHost = IsClient && IsServer; DAHost = IsClient && IsServer;

View File

@@ -660,16 +660,69 @@ namespace Unity.Netcode
/// <param name="despawnTick">the future network tick that the <see cref="NetworkObject"/> will be despawned on non-authoritative instances</param> /// <param name="despawnTick">the future network tick that the <see cref="NetworkObject"/> will be despawned on non-authoritative instances</param>
public virtual void OnDeferringDespawn(int despawnTick) { } public virtual void OnDeferringDespawn(int despawnTick) { }
/// Gets called after the <see cref="NetworkObject"/> is spawned. No NetworkBehaviours associated with the NetworkObject will have had <see cref="OnNetworkSpawn"/> invoked yet.
/// A reference to <see cref="NetworkManager"/> is passed in as a parameter to determine the context of execution (IsServer/IsClient)
/// </summary>
/// <remarks>
/// <param name="networkManager">a ref to the <see cref="NetworkManager"/> since this is not yet set on the <see cref="NetworkBehaviour"/></param>
/// The <see cref="NetworkBehaviour"/> will not have anything assigned to it at this point in time.
/// Settings like ownership, NetworkBehaviourId, NetworkManager, and most other spawn related properties will not be set.
/// This can be used to handle things like initializing/instantiating a NetworkVariable or the like.
/// </remarks>
protected virtual void OnNetworkPreSpawn(ref NetworkManager networkManager) { }
/// <summary> /// <summary>
/// Gets called when the <see cref="NetworkObject"/> gets spawned, message handlers are ready to be registered and the network is setup. /// Gets called when the <see cref="NetworkObject"/> gets spawned, message handlers are ready to be registered and the network is setup.
/// </summary> /// </summary>
public virtual void OnNetworkSpawn() { } public virtual void OnNetworkSpawn() { }
/// <summary>
/// Gets called after the <see cref="NetworkObject"/> is spawned. All NetworkBehaviours associated with the NetworkObject will have had <see cref="OnNetworkSpawn"/> invoked.
/// </summary>
/// <remarks>
/// Will be invoked on each <see cref="NetworkBehaviour"/> associated with the <see cref="NetworkObject"/> being spawned.
/// All associated <see cref="NetworkBehaviour"/> components will have had <see cref="OnNetworkSpawn"/> invoked on the spawned <see cref="NetworkObject"/>.
/// </remarks>
protected virtual void OnNetworkPostSpawn() { }
/// <summary>
/// [Client-Side Only]
/// When a new client joins it is synchronized with all spawned NetworkObjects and scenes loaded for the session joined. At the end of the synchronization process, when all
/// <see cref="NetworkObject"/>s and scenes (if scene management is enabled) have finished synchronizing, all NetworkBehaviour components associated with spawned <see cref="NetworkObject"/>s
/// will have this method invoked.
/// </summary>
/// <remarks>
/// This can be used to handle post synchronization actions where you might need to access a different NetworkObject and/or NetworkBehaviour not local to the current NetworkObject context.
/// This is only invoked on clients during a client-server network topology session.
/// </remarks>
protected virtual void OnNetworkSessionSynchronized() { }
/// <summary>
/// [Client & Server Side]
/// When a scene is loaded an in-scene placed NetworkObjects are all spawned, this method is invoked on all of the newly spawned in-scene placed NetworkObjects.
/// </summary>
/// <remarks>
/// This can be used to handle post scene loaded actions for in-scene placed NetworkObjcts where you might need to access a different NetworkObject and/or NetworkBehaviour not local to the current NetworkObject context.
/// </remarks>
protected virtual void OnInSceneObjectsSpawned() { }
/// <summary> /// <summary>
/// Gets called when the <see cref="NetworkObject"/> gets despawned. Is called both on the server and clients. /// Gets called when the <see cref="NetworkObject"/> gets despawned. Is called both on the server and clients.
/// </summary> /// </summary>
public virtual void OnNetworkDespawn() { } public virtual void OnNetworkDespawn() { }
internal void NetworkPreSpawn(ref NetworkManager networkManager)
{
try
{
OnNetworkPreSpawn(ref networkManager);
}
catch (Exception e)
{
Debug.LogException(e);
}
}
internal void InternalOnNetworkSpawn() internal void InternalOnNetworkSpawn()
{ {
IsSpawned = true; IsSpawned = true;
@@ -699,6 +752,42 @@ namespace Unity.Netcode
} }
} }
internal void NetworkPostSpawn()
{
try
{
OnNetworkPostSpawn();
}
catch (Exception e)
{
Debug.LogException(e);
}
}
internal void NetworkSessionSynchronized()
{
try
{
OnNetworkSessionSynchronized();
}
catch (Exception e)
{
Debug.LogException(e);
}
}
internal void InSceneNetworkObjectsSpawned()
{
try
{
OnInSceneObjectsSpawned();
}
catch (Exception e)
{
Debug.LogException(e);
}
}
internal void InternalOnNetworkDespawn() internal void InternalOnNetworkDespawn()
{ {
IsSpawned = false; IsSpawned = false;

View File

@@ -8,6 +8,7 @@ using UnityEditor;
#endif #endif
using UnityEngine.SceneManagement; using UnityEngine.SceneManagement;
using Debug = UnityEngine.Debug; using Debug = UnityEngine.Debug;
using Unity.Netcode.Components;
namespace Unity.Netcode namespace Unity.Netcode
{ {
@@ -43,7 +44,7 @@ namespace Unity.Netcode
{ {
get get
{ {
return NetworkConfig.SessionMode == SessionModeTypes.DistributedAuthority; return NetworkConfig.NetworkTopology == NetworkTopologyTypes.DistributedAuthority;
} }
} }
@@ -177,6 +178,45 @@ namespace Unity.Netcode
} }
} }
internal Dictionary<ulong, NetworkTransform> NetworkTransformUpdate = new Dictionary<ulong, NetworkTransform>();
#if COM_UNITY_MODULES_PHYSICS
internal Dictionary<ulong, NetworkTransform> NetworkTransformFixedUpdate = new Dictionary<ulong, NetworkTransform>();
#endif
internal void NetworkTransformRegistration(NetworkTransform networkTransform, bool forUpdate = true, bool register = true)
{
if (forUpdate)
{
if (register)
{
if (!NetworkTransformUpdate.ContainsKey(networkTransform.NetworkObjectId))
{
NetworkTransformUpdate.Add(networkTransform.NetworkObjectId, networkTransform);
}
}
else
{
NetworkTransformUpdate.Remove(networkTransform.NetworkObjectId);
}
}
#if COM_UNITY_MODULES_PHYSICS
else
{
if (register)
{
if (!NetworkTransformFixedUpdate.ContainsKey(networkTransform.NetworkObjectId))
{
NetworkTransformFixedUpdate.Add(networkTransform.NetworkObjectId, networkTransform);
}
}
else
{
NetworkTransformFixedUpdate.Remove(networkTransform.NetworkObjectId);
}
}
#endif
}
public void NetworkUpdate(NetworkUpdateStage updateStage) public void NetworkUpdate(NetworkUpdateStage updateStage)
{ {
switch (updateStage) switch (updateStage)
@@ -192,11 +232,36 @@ namespace Unity.Netcode
MessageManager.CleanupDisconnectedClients(); MessageManager.CleanupDisconnectedClients();
} }
break; break;
#if COM_UNITY_MODULES_PHYSICS
case NetworkUpdateStage.FixedUpdate:
{
foreach (var networkTransformEntry in NetworkTransformFixedUpdate)
{
if (networkTransformEntry.Value.gameObject.activeInHierarchy && networkTransformEntry.Value.IsSpawned)
{
networkTransformEntry.Value.OnFixedUpdate();
}
}
}
break;
#endif
case NetworkUpdateStage.PreUpdate: case NetworkUpdateStage.PreUpdate:
{ {
NetworkTimeSystem.UpdateTime(); NetworkTimeSystem.UpdateTime();
} }
break; break;
case NetworkUpdateStage.PreLateUpdate:
{
// Non-physics based non-authority NetworkTransforms update their states after all other components
foreach (var networkTransformEntry in NetworkTransformUpdate)
{
if (networkTransformEntry.Value.gameObject.activeInHierarchy && networkTransformEntry.Value.IsSpawned)
{
networkTransformEntry.Value.OnUpdate();
}
}
}
break;
case NetworkUpdateStage.PostLateUpdate: case NetworkUpdateStage.PostLateUpdate:
{ {
// Handle deferred despawning // Handle deferred despawning
@@ -942,6 +1007,10 @@ namespace Unity.Netcode
internal void Initialize(bool server) internal void Initialize(bool server)
{ {
#if COM_UNITY_MODULES_PHYSICS
NetworkTransformFixedUpdate.Clear();
#endif
NetworkTransformUpdate.Clear();
//DANGOEXP TODO: Remove this before finalizing the experimental release //DANGOEXP TODO: Remove this before finalizing the experimental release
NetworkConfig.AutoSpawnPlayerPrefabClientSide = DistributedAuthorityMode; NetworkConfig.AutoSpawnPlayerPrefabClientSide = DistributedAuthorityMode;
@@ -978,7 +1047,11 @@ namespace Unity.Netcode
} }
this.RegisterNetworkUpdate(NetworkUpdateStage.EarlyUpdate); this.RegisterNetworkUpdate(NetworkUpdateStage.EarlyUpdate);
#if COM_UNITY_MODULES_PHYSICS
this.RegisterNetworkUpdate(NetworkUpdateStage.FixedUpdate);
#endif
this.RegisterNetworkUpdate(NetworkUpdateStage.PreUpdate); this.RegisterNetworkUpdate(NetworkUpdateStage.PreUpdate);
this.RegisterNetworkUpdate(NetworkUpdateStage.PreLateUpdate);
this.RegisterNetworkUpdate(NetworkUpdateStage.PostLateUpdate); this.RegisterNetworkUpdate(NetworkUpdateStage.PostLateUpdate);
// ComponentFactory needs to set its defaults next // ComponentFactory needs to set its defaults next
@@ -994,11 +1067,17 @@ namespace Unity.Netcode
MessageManager.Hook(new NetworkManagerHooks(this)); MessageManager.Hook(new NetworkManagerHooks(this));
#if DEVELOPMENT_BUILD || UNITY_EDITOR #if DEVELOPMENT_BUILD || UNITY_EDITOR
if (NetworkConfig.NetworkProfilingMetrics)
{
MessageManager.Hook(new ProfilingHooks()); MessageManager.Hook(new ProfilingHooks());
}
#endif #endif
#if MULTIPLAYER_TOOLS #if MULTIPLAYER_TOOLS
if (NetworkConfig.NetworkMessageMetrics)
{
MessageManager.Hook(new MetricHooks(this)); MessageManager.Hook(new MetricHooks(this));
}
#endif #endif
// Assures there is a server message queue available // Assures there is a server message queue available

View File

@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using Unity.Netcode.Components;
#if UNITY_EDITOR #if UNITY_EDITOR
using UnityEditor; using UnityEditor;
#if UNITY_2021_2_OR_NEWER #if UNITY_2021_2_OR_NEWER
@@ -14,6 +15,7 @@ using UnityEngine;
using UnityEngine.SceneManagement; using UnityEngine.SceneManagement;
namespace Unity.Netcode namespace Unity.Netcode
{ {
/// <summary> /// <summary>
@@ -55,6 +57,34 @@ namespace Unity.Netcode
} }
} }
/// <summary>
/// All <see cref="NetworkTransform"></see> component instances associated with a <see cref="NetworkObject"/> component instance.
/// </summary>
/// <remarks>
/// When parented, all child <see cref="NetworkTransform"/> component instances under a <see cref="NetworkObject"/> component instance that do not have
/// another <see cref="NetworkObject"/> component instance will be associated with the initial component instance. This list does not contain any parented
/// children <see cref="NetworkObject"/> instances with one or more <see cref="NetworkTransform"/> component instance(s).
/// </remarks>
public List<NetworkTransform> NetworkTransforms { get; private set; }
#if COM_UNITY_MODULES_PHYSICS
/// <summary>
/// All <see cref="NetworkRigidbodyBase"></see> component instances associated with a <see cref="NetworkObject"/> component instance.
/// NOTE: This is only available if a physics package is included. If not, then this will not be available!
/// </summary>
/// <remarks>
/// When parented, all child <see cref="NetworkRigidbodyBase"/> component instances under a <see cref="NetworkObject"/> component instance that do not have
/// another <see cref="NetworkObject"/> component instance will be associated with the initial component instance. This list does not contain any parented
/// child <see cref="NetworkObject"/> instances with one or more <see cref="NetworkTransform"/> component instance(s).
/// </remarks>
public List<NetworkRigidbodyBase> NetworkRigidbodies { get; private set; }
#endif
/// <summary>
/// The current parent <see cref="NetworkObject"/> component instance to this <see cref="NetworkObject"/> component instance. When there is no parent then
/// this will be <see cref="null"/>.
/// </summary>
public NetworkObject CurrentParent { get; private set; }
#if UNITY_EDITOR #if UNITY_EDITOR
private const string k_GlobalIdTemplate = "GlobalObjectId_V1-{0}-{1}-{2}-{3}"; private const string k_GlobalIdTemplate = "GlobalObjectId_V1-{0}-{1}-{2}-{3}";
@@ -398,8 +428,11 @@ namespace Unity.Netcode
/// <summary> /// <summary>
/// Determines whether a NetworkObject can be distributed to other clients during /// Determines whether a NetworkObject can be distributed to other clients during
/// a <see cref="SessionModeTypes.DistributedAuthority"/> session. /// a <see cref="NetworkTopologyTypes.DistributedAuthority"/> session.
/// </summary> /// </summary>
#if !MULTIPLAYER_SDK_INSTALLED
[HideInInspector]
#endif
[SerializeField] [SerializeField]
internal OwnershipStatus Ownership = OwnershipStatus.Distributable; internal OwnershipStatus Ownership = OwnershipStatus.Distributable;
@@ -1894,7 +1927,6 @@ namespace Unity.Netcode
internal bool InternalTrySetParent(NetworkObject parent, bool worldPositionStays = true) internal bool InternalTrySetParent(NetworkObject parent, bool worldPositionStays = true)
{ {
if (parent != null && (IsSpawned ^ parent.IsSpawned)) if (parent != null && (IsSpawned ^ parent.IsSpawned))
{ {
if (NetworkManager != null && !NetworkManager.ShutdownInProgress) if (NetworkManager != null && !NetworkManager.ShutdownInProgress)
@@ -1907,10 +1939,12 @@ namespace Unity.Netcode
if (parent == null) if (parent == null)
{ {
CurrentParent = null;
transform.SetParent(null, worldPositionStays); transform.SetParent(null, worldPositionStays);
} }
else else
{ {
CurrentParent = parent;
transform.SetParent(parent.transform, worldPositionStays); transform.SetParent(parent.transform, worldPositionStays);
} }
@@ -2209,6 +2243,18 @@ namespace Unity.Netcode
} }
} }
internal void InvokeBehaviourNetworkPreSpawn()
{
var networkManager = NetworkManager;
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
{
if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy)
{
ChildNetworkBehaviours[i].NetworkPreSpawn(ref networkManager);
}
}
}
internal void InvokeBehaviourNetworkSpawn() internal void InvokeBehaviourNetworkSpawn()
{ {
NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId); NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId);
@@ -2238,6 +2284,42 @@ namespace Unity.Netcode
} }
} }
internal void InvokeBehaviourNetworkPostSpawn()
{
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
{
if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy)
{
ChildNetworkBehaviours[i].NetworkPostSpawn();
}
}
}
internal void InternalNetworkSessionSynchronized()
{
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
{
if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy)
{
ChildNetworkBehaviours[i].NetworkSessionSynchronized();
}
}
}
internal void InternalInSceneNetworkObjectsSpawned()
{
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
{
if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy)
{
ChildNetworkBehaviours[i].InSceneNetworkObjectsSpawned();
}
}
}
internal void InvokeBehaviourNetworkDespawn() internal void InvokeBehaviourNetworkDespawn()
{ {
NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId, true); NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId, true);
@@ -2271,6 +2353,25 @@ namespace Unity.Netcode
if (networkBehaviours[i].NetworkObject == this) if (networkBehaviours[i].NetworkObject == this)
{ {
m_ChildNetworkBehaviours.Add(networkBehaviours[i]); m_ChildNetworkBehaviours.Add(networkBehaviours[i]);
var type = networkBehaviours[i].GetType();
if (type.IsInstanceOfType(typeof(NetworkTransform)) || type.IsSubclassOf(typeof(NetworkTransform)))
{
if (NetworkTransforms == null)
{
NetworkTransforms = new List<NetworkTransform>();
}
NetworkTransforms.Add(networkBehaviours[i] as NetworkTransform);
}
#if COM_UNITY_MODULES_PHYSICS
else if (type.IsSubclassOf(typeof(NetworkRigidbodyBase)))
{
if (NetworkRigidbodies == null)
{
NetworkRigidbodies = new List<NetworkRigidbodyBase>();
}
NetworkRigidbodies.Add(networkBehaviours[i] as NetworkRigidbodyBase);
}
#endif
} }
} }
@@ -2862,6 +2963,9 @@ namespace Unity.Netcode
// in order to be able to determine which NetworkVariables the client will be allowed to read. // in order to be able to determine which NetworkVariables the client will be allowed to read.
networkObject.OwnerClientId = sceneObject.OwnerClientId; networkObject.OwnerClientId = sceneObject.OwnerClientId;
// Special Case: Invoke NetworkBehaviour.OnPreSpawn methods here before SynchronizeNetworkBehaviours
networkObject.InvokeBehaviourNetworkPreSpawn();
// Synchronize NetworkBehaviours // Synchronize NetworkBehaviours
var bufferSerializer = new BufferSerializer<BufferSerializerReader>(new BufferSerializerReader(reader)); var bufferSerializer = new BufferSerializer<BufferSerializerReader>(new BufferSerializerReader(reader));
networkObject.SynchronizeNetworkBehaviours(ref bufferSerializer, networkManager.LocalClientId); networkObject.SynchronizeNetworkBehaviours(ref bufferSerializer, networkManager.LocalClientId);
@@ -3051,6 +3155,11 @@ namespace Unity.Netcode
private void Awake() private void Awake()
{ {
m_ChildNetworkBehaviours = null;
NetworkTransforms?.Clear();
#if COM_UNITY_MODULES_PHYSICS
NetworkRigidbodies?.Clear();
#endif
SetCachedParent(transform.parent); SetCachedParent(transform.parent);
SceneOrigin = gameObject.scene; SceneOrigin = gameObject.scene;
} }

View File

@@ -63,16 +63,39 @@ namespace Unity.Netcode
/// <param name="networkDelivery">The delivery type (QoS) to send data with</param> /// <param name="networkDelivery">The delivery type (QoS) to send data with</param>
public void SendUnnamedMessage(IReadOnlyList<ulong> clientIds, FastBufferWriter messageBuffer, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced) public void SendUnnamedMessage(IReadOnlyList<ulong> clientIds, FastBufferWriter messageBuffer, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced)
{ {
if (!m_NetworkManager.IsServer)
{
throw new InvalidOperationException("Can not send unnamed messages to multiple users as a client");
}
if (clientIds == null) if (clientIds == null)
{ {
throw new ArgumentNullException(nameof(clientIds), "You must pass in a valid clientId List"); throw new ArgumentNullException(nameof(clientIds), "You must pass in a valid clientId List!");
} }
if (!m_NetworkManager.DistributedAuthorityMode && !m_NetworkManager.IsServer)
{
if (clientIds.Count > 1 || (clientIds.Count == 1 && clientIds[0] != NetworkManager.ServerClientId))
{
Debug.LogError("Clients cannot send unnamed messages to other clients!");
return;
}
else if (clientIds.Count == 1)
{
SendUnnamedMessage(clientIds[0], messageBuffer, networkDelivery);
}
}
else if (m_NetworkManager.DistributedAuthorityMode && !m_NetworkManager.DAHost)
{
if (clientIds.Count > 1)
{
Debug.LogError("Sending an unnamed message to multiple clients is not yet supported in distributed authority.");
return;
}
}
if (clientIds.Count == 0)
{
Debug.LogError($"{nameof(clientIds)} is empty! No clients to send to.");
return;
}
if (m_NetworkManager.IsHost) if (m_NetworkManager.IsHost)
{ {
for (var i = 0; i < clientIds.Count; ++i) for (var i = 0; i < clientIds.Count; ++i)
@@ -203,6 +226,14 @@ namespace Unity.Netcode
var hash32 = XXHash.Hash32(name); var hash32 = XXHash.Hash32(name);
var hash64 = XXHash.Hash64(name); var hash64 = XXHash.Hash64(name);
if (m_NetworkManager.LogLevel <= LogLevel.Developer)
{
if (m_MessageHandlerNameLookup32.ContainsKey(hash32) || m_MessageHandlerNameLookup64.ContainsKey(hash64))
{
Debug.LogWarning($"Registering {name} named message over existing registration! Your previous registration's callback is being overwritten!");
}
}
m_NamedMessageHandlers32[hash32] = callback; m_NamedMessageHandlers32[hash32] = callback;
m_NamedMessageHandlers64[hash64] = callback; m_NamedMessageHandlers64[hash64] = callback;
@@ -303,14 +334,37 @@ namespace Unity.Netcode
/// <param name="networkDelivery">The delivery type (QoS) to send data with</param> /// <param name="networkDelivery">The delivery type (QoS) to send data with</param>
public void SendNamedMessage(string messageName, IReadOnlyList<ulong> clientIds, FastBufferWriter messageStream, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced) public void SendNamedMessage(string messageName, IReadOnlyList<ulong> clientIds, FastBufferWriter messageStream, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced)
{ {
if (!m_NetworkManager.IsServer)
{
throw new InvalidOperationException("Can not send unnamed messages to multiple users as a client");
}
if (clientIds == null) if (clientIds == null)
{ {
throw new ArgumentNullException(nameof(clientIds), "You must pass in a valid clientId List"); throw new ArgumentNullException(nameof(clientIds), "Client list is null! You must pass in a valid clientId list to send a named message.");
}
if (!m_NetworkManager.DistributedAuthorityMode && !m_NetworkManager.IsServer)
{
if (clientIds.Count > 1 || (clientIds.Count == 1 && clientIds[0] != NetworkManager.ServerClientId))
{
Debug.LogError("Clients cannot send named messages to other clients!");
return;
}
else if (clientIds.Count == 1)
{
SendNamedMessage(messageName, clientIds[0], messageStream, networkDelivery);
return;
}
}
else if (m_NetworkManager.DistributedAuthorityMode && !m_NetworkManager.DAHost)
{
if (clientIds.Count > 1)
{
Debug.LogError("Sending a named message to multiple clients is not yet supported in distributed authority.");
return;
}
}
if (clientIds.Count == 0)
{
Debug.LogError($"{nameof(clientIds)} is empty! No clients to send the named message {messageName} to!");
return;
} }
ulong hash = 0; ulong hash = 0;

View File

@@ -1,3 +1,4 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
#if UNITY_EDITOR #if UNITY_EDITOR
using UnityEditor; using UnityEditor;
@@ -12,9 +13,117 @@ namespace Unity.Netcode
internal static readonly List<NetworkMessageManager.MessageWithHandler> __network_message_types = new List<NetworkMessageManager.MessageWithHandler>(); internal static readonly List<NetworkMessageManager.MessageWithHandler> __network_message_types = new List<NetworkMessageManager.MessageWithHandler>();
#pragma warning restore IDE1006 // restore naming rule violation check #pragma warning restore IDE1006 // restore naming rule violation check
/// <summary>
/// Enum representing the different types of messages that can be sent over the network.
/// The values cannot be changed, as they are used to serialize and deserialize messages.
/// Adding new messages should be done by adding new values to the end of the enum
/// using the next free value.
/// </summary>
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/// Add any new Message types to this table at the END with incremented index value
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
internal enum NetworkMessageTypes : uint
{
ConnectionApproved = 0,
ConnectionRequest = 1,
ChangeOwnership = 2,
ClientConnected = 3,
ClientDisconnected = 4,
ClientRpc = 5,
CreateObject = 6,
DestroyObject = 7,
DisconnectReason = 8,
ForwardClientRpc = 9,
ForwardServerRpc = 10,
NamedMessage = 11,
NetworkTransformMessage = 12,
NetworkVariableDelta = 13,
ParentSync = 14,
Proxy = 15,
Rpc = 16,
SceneEvent = 17,
ServerLog = 18,
ServerRpc = 19,
TimeSync = 20,
Unnamed = 21,
SessionOwner = 22
}
// Enable this for integration tests that need no message types defined
internal static bool IntegrationTestNoMessages;
public List<NetworkMessageManager.MessageWithHandler> GetMessages() public List<NetworkMessageManager.MessageWithHandler> GetMessages()
{ {
return __network_message_types; // return no message types when defined for integration tests
if (IntegrationTestNoMessages)
{
return new List<NetworkMessageManager.MessageWithHandler>();
}
var messageTypeCount = Enum.GetValues(typeof(NetworkMessageTypes)).Length;
// Assure the allowed types count is the same as our NetworkMessageType enum count
if (__network_message_types.Count != messageTypeCount)
{
throw new Exception($"Allowed types is not equal to the number of message type indices! Allowed Count: {__network_message_types.Count} | Index Count: {messageTypeCount}");
}
// Populate with blanks to be replaced later
var adjustedMessageTypes = new List<NetworkMessageManager.MessageWithHandler>();
var blank = new NetworkMessageManager.MessageWithHandler();
for (int i = 0; i < messageTypeCount; i++)
{
adjustedMessageTypes.Add(blank);
}
// Create a type to enum index lookup table
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Add new Message types to this table paired with its new NetworkMessageTypes enum
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
var messageTypes = new Dictionary<Type, NetworkMessageTypes>
{
{ typeof(ConnectionApprovedMessage), NetworkMessageTypes.ConnectionApproved }, // This MUST be first
{ typeof(ConnectionRequestMessage), NetworkMessageTypes.ConnectionRequest }, // This MUST be second
{ typeof(ChangeOwnershipMessage), NetworkMessageTypes.ChangeOwnership },
{ typeof(ClientConnectedMessage), NetworkMessageTypes.ClientConnected },
{ typeof(ClientDisconnectedMessage), NetworkMessageTypes.ClientDisconnected },
{ typeof(ClientRpcMessage), NetworkMessageTypes.ClientRpc },
{ typeof(CreateObjectMessage), NetworkMessageTypes.CreateObject },
{ typeof(DestroyObjectMessage), NetworkMessageTypes.DestroyObject },
{ typeof(DisconnectReasonMessage), NetworkMessageTypes.DisconnectReason },
{ typeof(ForwardClientRpcMessage), NetworkMessageTypes.ForwardClientRpc },
{ typeof(ForwardServerRpcMessage), NetworkMessageTypes.ForwardServerRpc },
{ typeof(NamedMessage), NetworkMessageTypes.NamedMessage },
{ typeof(NetworkTransformMessage), NetworkMessageTypes.NetworkTransformMessage },
{ typeof(NetworkVariableDeltaMessage), NetworkMessageTypes.NetworkVariableDelta },
{ typeof(ParentSyncMessage), NetworkMessageTypes.ParentSync },
{ typeof(ProxyMessage), NetworkMessageTypes.Proxy },
{ typeof(RpcMessage), NetworkMessageTypes.Rpc },
{ typeof(SceneEventMessage), NetworkMessageTypes.SceneEvent },
{ typeof(ServerLogMessage), NetworkMessageTypes.ServerLog },
{ typeof(ServerRpcMessage), NetworkMessageTypes.ServerRpc },
{ typeof(TimeSyncMessage), NetworkMessageTypes.TimeSync },
{ typeof(UnnamedMessage), NetworkMessageTypes.Unnamed },
{ typeof(SessionOwnerMessage), NetworkMessageTypes.SessionOwner }
};
// Assure the type to lookup table count and NetworkMessageType enum count matches (i.e. to catch human error when adding new messages)
if (messageTypes.Count != messageTypeCount)
{
throw new Exception($"Message type to Message type index count mistmatch! Table Count: {messageTypes.Count} | Index Count: {messageTypeCount}");
}
// Now order the allowed types list based on the order of the NetworkMessageType enum
foreach (var messageHandler in __network_message_types)
{
if (!messageTypes.ContainsKey(messageHandler.MessageType))
{
throw new Exception($"Missing message type from lookup table: {messageHandler.MessageType}");
}
adjustedMessageTypes[(int)messageTypes[messageHandler.MessageType]] = messageHandler;
}
// return the NetworkMessageType enum ordered list
return adjustedMessageTypes;
} }
#if UNITY_EDITOR #if UNITY_EDITOR

View File

@@ -5,6 +5,8 @@ namespace Unity.Netcode
{ {
public int Version => 0; public int Version => 0;
private const string k_Name = "ChangeOwnershipMessage";
public ulong NetworkObjectId; public ulong NetworkObjectId;
public ulong OwnerClientId; public ulong OwnerClientId;
// DANGOEXP TODO: Remove these notes or change their format // DANGOEXP TODO: Remove these notes or change their format
@@ -199,7 +201,7 @@ namespace Unity.Netcode
// authority of the NetworkObject in question. // authority of the NetworkObject in question.
if (!networkManager.DAHost && !networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId)) if (!networkManager.DAHost && !networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId))
{ {
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, GetType().Name); networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, k_Name);
return false; return false;
} }
return true; return true;

View File

@@ -222,6 +222,12 @@ namespace Unity.Netcode
} }
// When scene management is disabled we notify after everything is synchronized // When scene management is disabled we notify after everything is synchronized
networkManager.ConnectionManager.InvokeOnClientConnectedCallback(context.SenderId); networkManager.ConnectionManager.InvokeOnClientConnectedCallback(context.SenderId);
// For convenience, notify all NetworkBehaviours that synchronization is complete.
foreach (var networkObject in networkManager.SpawnManager.SpawnedObjectsList)
{
networkObject.InternalNetworkSessionSynchronized();
}
} }
else else
{ {
@@ -230,6 +236,10 @@ namespace Unity.Netcode
// Mark the client being connected // Mark the client being connected
networkManager.IsConnectedClient = true; networkManager.IsConnectedClient = true;
networkManager.SceneManager.IsRestoringSession = IsRestoredSession;
if (!IsRestoredSession)
{
// Spawn any in-scene placed NetworkObjects // Spawn any in-scene placed NetworkObjects
networkManager.SpawnManager.ServerSpawnSceneObjectsOnStartSweep(); networkManager.SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
@@ -238,10 +248,12 @@ namespace Unity.Netcode
{ {
networkManager.ConnectionManager.CreateAndSpawnPlayer(OwnerClientId); networkManager.ConnectionManager.CreateAndSpawnPlayer(OwnerClientId);
} }
// Synchronize the service with the initial session owner's loaded scenes and spawned objects // Synchronize the service with the initial session owner's loaded scenes and spawned objects
networkManager.SceneManager.SynchronizeNetworkObjects(NetworkManager.ServerClientId); networkManager.SceneManager.SynchronizeNetworkObjects(NetworkManager.ServerClientId);
} }
} }
}
ConnectedClientIds.Dispose(); ConnectedClientIds.Dispose();
} }
} }

View File

@@ -7,6 +7,8 @@ namespace Unity.Netcode
{ {
public int Version => 0; public int Version => 0;
private const string k_Name = "CreateObjectMessage";
public NetworkObject.SceneObject ObjectInfo; public NetworkObject.SceneObject ObjectInfo;
private FastBufferReader m_ReceivedNetworkVariableData; private FastBufferReader m_ReceivedNetworkVariableData;
@@ -161,7 +163,7 @@ namespace Unity.Netcode
if (!networkManager.NetworkConfig.ForceSamePrefabs && !networkManager.SpawnManager.HasPrefab(ObjectInfo)) if (!networkManager.NetworkConfig.ForceSamePrefabs && !networkManager.SpawnManager.HasPrefab(ObjectInfo))
{ {
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnAddPrefab, ObjectInfo.Hash, reader, ref context, GetType().Name); networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnAddPrefab, ObjectInfo.Hash, reader, ref context, k_Name);
return false; return false;
} }
m_ReceivedNetworkVariableData = reader; m_ReceivedNetworkVariableData = reader;

View File

@@ -6,6 +6,8 @@ namespace Unity.Netcode
{ {
public int Version => 0; public int Version => 0;
private const string k_Name = "DestroyObjectMessage";
public ulong NetworkObjectId; public ulong NetworkObjectId;
public bool DestroyGameObject; public bool DestroyGameObject;
private byte m_DestroyFlags; private byte m_DestroyFlags;
@@ -84,7 +86,7 @@ namespace Unity.Netcode
// Client-Server mode we always defer where in distributed authority mode we only defer if it is not a targeted destroy // Client-Server mode we always defer where in distributed authority mode we only defer if it is not a targeted destroy
if (!networkManager.DistributedAuthorityMode || (networkManager.DistributedAuthorityMode && !IsTargetedDestroy)) if (!networkManager.DistributedAuthorityMode || (networkManager.DistributedAuthorityMode && !IsTargetedDestroy))
{ {
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, GetType().Name); networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, k_Name);
} }
} }
return true; return true;

View File

@@ -0,0 +1,190 @@
using Unity.Netcode.Components;
using UnityEngine;
namespace Unity.Netcode
{
/// <summary>
/// NetworkTransform State Update Message
/// </summary>
internal struct NetworkTransformMessage : INetworkMessage
{
public int Version => 0;
private const string k_Name = "NetworkTransformMessage";
internal NetworkTransform NetworkTransform;
// Only used for DAHost
internal NetworkTransform.NetworkTransformState State;
private FastBufferReader m_CurrentReader;
private unsafe void CopyPayload(ref FastBufferWriter writer)
{
writer.WriteBytesSafe(m_CurrentReader.GetUnsafePtrAtCurrentPosition(), m_CurrentReader.Length - m_CurrentReader.Position);
}
public void Serialize(FastBufferWriter writer, int targetVersion)
{
if (m_CurrentReader.IsInitialized)
{
CopyPayload(ref writer);
}
else
{
NetworkTransform.SerializeMessage(writer, targetVersion);
}
}
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
var networkManager = context.SystemOwner as NetworkManager;
if (networkManager == null)
{
Debug.LogError($"[{nameof(NetworkTransformMessage)}] System owner context was not of type {nameof(NetworkManager)}!");
return false;
}
var currentPosition = reader.Position;
var networkObjectId = (ulong)0;
var networkBehaviourId = 0;
ByteUnpacker.ReadValueBitPacked(reader, out networkObjectId);
var isSpawnedLocally = networkManager.SpawnManager.SpawnedObjects.ContainsKey(networkObjectId);
// Only defer if the NetworkObject is not spawned yet and the local NetworkManager is not running as a DAHost.
if (!isSpawnedLocally && !networkManager.DAHost)
{
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, networkObjectId, reader, ref context, k_Name);
return false;
}
// While the below check and assignment might seem out of place, this is specific to running in DAHost mode when a NetworkObject is
// hidden from the DAHost but is visible to other clients. Since the DAHost needs to forward updates to the clients, we ignore processing
// this message locally
var networkObject = (NetworkObject)null;
var isServerAuthoritative = false;
var ownerAuthoritativeServerSide = false;
// Get the behaviour index
ByteUnpacker.ReadValueBitPacked(reader, out networkBehaviourId);
if (isSpawnedLocally)
{
networkObject = networkManager.SpawnManager.SpawnedObjects[networkObjectId];
// Get the target NetworkTransform
NetworkTransform = networkObject.ChildNetworkBehaviours[networkBehaviourId] as NetworkTransform;
isServerAuthoritative = NetworkTransform.IsServerAuthoritative();
ownerAuthoritativeServerSide = !isServerAuthoritative && networkManager.IsServer;
reader.ReadNetworkSerializableInPlace(ref NetworkTransform.InboundState);
}
else
{
// Deserialize the state
reader.ReadNetworkSerializableInPlace(ref State);
}
unsafe
{
if (ownerAuthoritativeServerSide)
{
var targetCount = 1;
if (networkManager.DistributedAuthorityMode && networkManager.DAHost)
{
ByteUnpacker.ReadValueBitPacked(reader, out targetCount);
}
var targetIds = stackalloc ulong[targetCount];
if (networkManager.DistributedAuthorityMode && networkManager.DAHost)
{
var targetId = (ulong)0;
for (int i = 0; i < targetCount; i++)
{
ByteUnpacker.ReadValueBitPacked(reader, out targetId);
targetIds[i] = targetId;
}
if (!isSpawnedLocally)
{
// If we are the DAHost and the NetworkObject is hidden from the host we still need to forward this message
ownerAuthoritativeServerSide = networkManager.DAHost && !isSpawnedLocally;
}
}
var ownerClientId = (ulong)0;
if (networkObject != null)
{
ownerClientId = networkObject.OwnerClientId;
if (ownerClientId == NetworkManager.ServerClientId)
{
// Ownership must have changed, ignore any additional pending messages that might have
// come from a previous owner client.
return true;
}
}
else if (networkManager.DAHost)
{
// Specific to distributed authority mode, the only sender of state updates will be the owner
ownerClientId = context.SenderId;
}
var networkDelivery = State.IsReliableStateUpdate() ? NetworkDelivery.ReliableSequenced : NetworkDelivery.UnreliableSequenced;
// Forward the state update if there are any remote clients to foward it to
if (networkManager.ConnectionManager.ConnectedClientsList.Count > (networkManager.IsHost ? 2 : 1))
{
var clientCount = networkManager.DistributedAuthorityMode ? targetCount : networkManager.ConnectionManager.ConnectedClientsList.Count;
if (clientCount == 0)
{
return true;
}
// This is only to copy the existing and already serialized struct for forwarding purposes only.
// This will not include any changes made to this struct at this particular stage of processing the message.
var currentMessage = this;
// Create a new reader that replicates this message
currentMessage.m_CurrentReader = new FastBufferReader(reader, Collections.Allocator.None);
// Rewind the new reader to the beginning of the message's payload
currentMessage.m_CurrentReader.Seek(currentPosition);
// Forward the message to all connected clients that are observers of the associated NetworkObject
for (int i = 0; i < clientCount; i++)
{
var clientId = networkManager.DistributedAuthorityMode ? targetIds[i] : networkManager.ConnectionManager.ConnectedClientsList[i].ClientId;
if (NetworkManager.ServerClientId == clientId || (!isServerAuthoritative && clientId == ownerClientId) ||
(!networkManager.DistributedAuthorityMode && !networkObject.Observers.Contains(clientId)))
{
continue;
}
networkManager.MessageManager.SendMessage(ref currentMessage, networkDelivery, clientId);
}
// Dispose of the reader used for forwarding
currentMessage.m_CurrentReader.Dispose();
}
}
}
return true;
}
public void Handle(ref NetworkContext context)
{
var networkManager = context.SystemOwner as NetworkManager;
// Only if the local NetworkManager instance is running as the DAHost we just exit if there is no local
// NetworkTransform component to apply the state update to (i.e. it is hidden from the DAHost and it
// just forwarded the state update to any other connected client)
if (networkManager.DAHost && NetworkTransform == null)
{
return;
}
if (NetworkTransform == null)
{
Debug.LogError($"[{nameof(NetworkTransformMessage)}][Dropped] Reciever {nameof(NetworkTransform)} was not set!");
return;
}
NetworkTransform.TransformStateUpdate(context.SenderId);
}
}
}

View File

@@ -23,6 +23,8 @@ namespace Unity.Netcode
private FastBufferReader m_ReceivedNetworkVariableData; private FastBufferReader m_ReceivedNetworkVariableData;
private const string k_Name = "NetworkVariableDeltaMessage";
// DANGO-TODO: Made some modifications here that overlap/won't play nice with EnsureNetworkVariableLenghtSafety. // DANGO-TODO: Made some modifications here that overlap/won't play nice with EnsureNetworkVariableLenghtSafety.
// Worth either merging or more cleanly separating these codepaths. // Worth either merging or more cleanly separating these codepaths.
public void Serialize(FastBufferWriter writer, int targetVersion) public void Serialize(FastBufferWriter writer, int targetVersion)
@@ -296,7 +298,7 @@ namespace Unity.Netcode
// DANGO-TODO: Fix me! // DANGO-TODO: Fix me!
// When a client-spawned NetworkObject is despawned by the owner client, the owner client will still get messages for deltas and cause this to // When a client-spawned NetworkObject is despawned by the owner client, the owner client will still get messages for deltas and cause this to
// log a warning. The issue is primarily how NetworkVariables handle updating and will require some additional re-factoring. // log a warning. The issue is primarily how NetworkVariables handle updating and will require some additional re-factoring.
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, m_ReceivedNetworkVariableData, ref context, GetType().Name); networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, m_ReceivedNetworkVariableData, ref context, k_Name);
} }
} }
} }

View File

@@ -6,6 +6,8 @@ namespace Unity.Netcode
{ {
public int Version => 0; public int Version => 0;
private const string k_Name = "DestroyObjectMessage";
public ulong NetworkObjectId; public ulong NetworkObjectId;
private byte m_BitField; private byte m_BitField;
@@ -92,7 +94,7 @@ namespace Unity.Netcode
// If the target NetworkObject does not exist =or= the target latest parent does not exist then defer the message // If the target NetworkObject does not exist =or= the target latest parent does not exist then defer the message
if (!networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId) || (LatestParent.HasValue && !networkManager.SpawnManager.SpawnedObjects.ContainsKey(LatestParent.Value))) if (!networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId) || (LatestParent.HasValue && !networkManager.SpawnManager.SpawnedObjects.ContainsKey(LatestParent.Value)))
{ {
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, GetType().Name); networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, k_Name);
return false; return false;
} }
return true; return true;

View File

@@ -99,6 +99,8 @@ namespace Unity.Netcode
public FastBufferWriter WriteBuffer; public FastBufferWriter WriteBuffer;
public FastBufferReader ReadBuffer; public FastBufferReader ReadBuffer;
private const string k_Name = "ServerRpcMessage";
public unsafe void Serialize(FastBufferWriter writer, int targetVersion) public unsafe void Serialize(FastBufferWriter writer, int targetVersion)
{ {
RpcMessageHelpers.Serialize(ref writer, ref Metadata, ref WriteBuffer); RpcMessageHelpers.Serialize(ref writer, ref Metadata, ref WriteBuffer);
@@ -106,7 +108,7 @@ namespace Unity.Netcode
public unsafe bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) public unsafe bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{ {
return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, GetType().Name); return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, k_Name);
} }
public void Handle(ref NetworkContext context) public void Handle(ref NetworkContext context)
@@ -134,6 +136,8 @@ namespace Unity.Netcode
public FastBufferWriter WriteBuffer; public FastBufferWriter WriteBuffer;
public FastBufferReader ReadBuffer; public FastBufferReader ReadBuffer;
private const string k_Name = "ClientRpcMessage";
public void Serialize(FastBufferWriter writer, int targetVersion) public void Serialize(FastBufferWriter writer, int targetVersion)
{ {
RpcMessageHelpers.Serialize(ref writer, ref Metadata, ref WriteBuffer); RpcMessageHelpers.Serialize(ref writer, ref Metadata, ref WriteBuffer);
@@ -141,7 +145,7 @@ namespace Unity.Netcode
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion) public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{ {
return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, GetType().Name); return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, k_Name);
} }
public void Handle(ref NetworkContext context) public void Handle(ref NetworkContext context)
@@ -169,6 +173,8 @@ namespace Unity.Netcode
public FastBufferWriter WriteBuffer; public FastBufferWriter WriteBuffer;
public FastBufferReader ReadBuffer; public FastBufferReader ReadBuffer;
private const string k_Name = "RpcMessage";
public unsafe void Serialize(FastBufferWriter writer, int targetVersion) public unsafe void Serialize(FastBufferWriter writer, int targetVersion)
{ {
BytePacker.WriteValuePacked(writer, SenderClientId); BytePacker.WriteValuePacked(writer, SenderClientId);
@@ -179,7 +185,7 @@ namespace Unity.Netcode
{ {
ByteUnpacker.ReadValuePacked(reader, out SenderClientId); ByteUnpacker.ReadValuePacked(reader, out SenderClientId);
return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, GetType().Name); return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, k_Name);
} }
public void Handle(ref NetworkContext context) public void Handle(ref NetworkContext context)

View File

@@ -120,49 +120,20 @@ namespace Unity.Netcode
public VersionGetter GetVersion; public VersionGetter GetVersion;
} }
internal List<MessageWithHandler> PrioritizeMessageOrder(List<MessageWithHandler> allowedTypes)
{
var prioritizedTypes = new List<MessageWithHandler>();
// First pass puts the priority message in the first indices
// Those are the messages that must be delivered in order to allow re-ordering the others later
foreach (var t in allowedTypes)
{
if (t.MessageType.FullName == typeof(ConnectionRequestMessage).FullName ||
t.MessageType.FullName == typeof(ConnectionApprovedMessage).FullName)
{
prioritizedTypes.Add(t);
}
}
foreach (var t in allowedTypes)
{
if (t.MessageType.FullName != typeof(ConnectionRequestMessage).FullName &&
t.MessageType.FullName != typeof(ConnectionApprovedMessage).FullName)
{
prioritizedTypes.Add(t);
}
}
return prioritizedTypes;
}
public NetworkMessageManager(INetworkMessageSender sender, object owner, INetworkMessageProvider provider = null) public NetworkMessageManager(INetworkMessageSender sender, object owner, INetworkMessageProvider provider = null)
{ {
try try
{ {
m_Sender = sender; m_Sender = sender;
m_Owner = owner; m_Owner = owner;
if (provider == null) if (provider == null)
{ {
provider = new ILPPMessageProvider(); provider = new ILPPMessageProvider();
} }
// Get the presorted message types returned by the provider
var allowedTypes = provider.GetMessages(); var allowedTypes = provider.GetMessages();
allowedTypes.Sort((a, b) => string.CompareOrdinal(a.MessageType.FullName, b.MessageType.FullName));
allowedTypes = PrioritizeMessageOrder(allowedTypes);
foreach (var type in allowedTypes) foreach (var type in allowedTypes)
{ {
RegisterMessageType(type); RegisterMessageType(type);

View File

@@ -425,7 +425,7 @@ namespace Unity.Netcode
/// <summary> /// <summary>
/// Returns the currently loaded scenes that are synchronized with the session owner or server depending upon the selected /// Returns the currently loaded scenes that are synchronized with the session owner or server depending upon the selected
/// NetworkManager session mode. /// network topology.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// The <see cref="SceneManager"/> scenes loaded returns all scenes loaded where this returns only the scenes that have been /// The <see cref="SceneManager"/> scenes loaded returns all scenes loaded where this returns only the scenes that have been
@@ -444,6 +444,7 @@ namespace Unity.Netcode
internal Dictionary<int, int> ServerSceneHandleToClientSceneHandle = new Dictionary<int, int>(); internal Dictionary<int, int> ServerSceneHandleToClientSceneHandle = new Dictionary<int, int>();
internal Dictionary<int, int> ClientSceneHandleToServerSceneHandle = new Dictionary<int, int>(); internal Dictionary<int, int> ClientSceneHandleToServerSceneHandle = new Dictionary<int, int>();
internal bool IsRestoringSession;
/// <summary> /// <summary>
/// Add the client to server (and vice versa) scene handle lookup. /// Add the client to server (and vice versa) scene handle lookup.
/// Add the client-side handle to scene entry in the HandleToScene table. /// Add the client-side handle to scene entry in the HandleToScene table.
@@ -455,7 +456,7 @@ namespace Unity.Netcode
{ {
ServerSceneHandleToClientSceneHandle.Add(serverHandle, clientHandle); ServerSceneHandleToClientSceneHandle.Add(serverHandle, clientHandle);
} }
else else if (!IsRestoringSession)
{ {
return false; return false;
} }
@@ -464,7 +465,7 @@ namespace Unity.Netcode
{ {
ClientSceneHandleToServerSceneHandle.Add(clientHandle, serverHandle); ClientSceneHandleToServerSceneHandle.Add(clientHandle, serverHandle);
} }
else else if (!IsRestoringSession)
{ {
return false; return false;
} }
@@ -1045,7 +1046,7 @@ namespace Unity.Netcode
/// <param name="targetClientIds">array of client identifiers to receive the scene event message</param> /// <param name="targetClientIds">array of client identifiers to receive the scene event message</param>
private void SendSceneEventData(uint sceneEventId, ulong[] targetClientIds) private void SendSceneEventData(uint sceneEventId, ulong[] targetClientIds)
{ {
if (targetClientIds.Length == 0) if (targetClientIds.Length == 0 && !NetworkManager.DistributedAuthorityMode)
{ {
// This would be the Host/Server with no clients connected // This would be the Host/Server with no clients connected
// Silently return as there is nothing to be done // Silently return as there is nothing to be done
@@ -1056,6 +1057,16 @@ namespace Unity.Netcode
if (NetworkManager.DistributedAuthorityMode && !NetworkManager.DAHost) if (NetworkManager.DistributedAuthorityMode && !NetworkManager.DAHost)
{ {
if (NetworkManager.DistributedAuthorityMode && HasSceneAuthority())
{
sceneEvent.TargetClientId = NetworkManager.ServerClientId;
var message = new SceneEventMessage
{
EventData = sceneEvent,
};
var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, NetworkManager.ServerClientId);
NetworkManager.NetworkMetrics.TrackSceneEventSent(NetworkManager.ServerClientId, (uint)sceneEvent.SceneEventType, SceneNameFromHash(sceneEvent.SceneHash), size);
}
foreach (var clientId in targetClientIds) foreach (var clientId in targetClientIds)
{ {
sceneEvent.TargetClientId = clientId; sceneEvent.TargetClientId = clientId;
@@ -1859,6 +1870,17 @@ namespace Unity.Netcode
} }
} }
foreach (var keyValuePairByGlobalObjectIdHash in ScenePlacedObjects)
{
foreach (var keyValuePairBySceneHandle in keyValuePairByGlobalObjectIdHash.Value)
{
if (!keyValuePairBySceneHandle.Value.IsPlayerObject)
{
keyValuePairBySceneHandle.Value.InternalInSceneNetworkObjectsSpawned();
}
}
}
// Add any despawned when spawned in-scene placed NetworkObjects to the scene event data // Add any despawned when spawned in-scene placed NetworkObjects to the scene event data
sceneEventData.AddDespawnedInSceneNetworkObjects(); sceneEventData.AddDespawnedInSceneNetworkObjects();
@@ -2413,6 +2435,18 @@ namespace Unity.Netcode
{ {
NetworkLog.LogInfo($"[Client-{NetworkManager.LocalClientId}][Scene Management Enabled] Synchronization complete!"); NetworkLog.LogInfo($"[Client-{NetworkManager.LocalClientId}][Scene Management Enabled] Synchronization complete!");
} }
// For convenience, notify all NetworkBehaviours that synchronization is complete.
foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList)
{
networkObject.InternalNetworkSessionSynchronized();
}
if (NetworkManager.DistributedAuthorityMode && HasSceneAuthority() && IsRestoringSession)
{
IsRestoringSession = false;
PostSynchronizationSceneUnloading = m_OriginalPostSynchronizationSceneUnloading;
}
EndSceneEvent(sceneEventId); EndSceneEvent(sceneEventId);
} }
break; break;
@@ -2599,6 +2633,8 @@ namespace Unity.Netcode
/// </summary> /// </summary>
internal bool SkipSceneHandling; internal bool SkipSceneHandling;
private bool m_OriginalPostSynchronizationSceneUnloading;
/// <summary> /// <summary>
/// Both Client and Server: Incoming scene event entry point /// Both Client and Server: Incoming scene event entry point
/// </summary> /// </summary>
@@ -2672,6 +2708,12 @@ namespace Unity.Netcode
// Only if ClientSynchronizationMode is Additive and the client receives a synchronize scene event // Only if ClientSynchronizationMode is Additive and the client receives a synchronize scene event
if (ClientSynchronizationMode == LoadSceneMode.Additive) if (ClientSynchronizationMode == LoadSceneMode.Additive)
{ {
if (NetworkManager.DistributedAuthorityMode && HasSceneAuthority() && IsRestoringSession && clientId == NetworkManager.ServerClientId)
{
m_OriginalPostSynchronizationSceneUnloading = PostSynchronizationSceneUnloading;
PostSynchronizationSceneUnloading = true;
}
// Check for scenes already loaded and create a table of scenes already loaded (SceneEntries) that will be // Check for scenes already loaded and create a table of scenes already loaded (SceneEntries) that will be
// used if the server is synchronizing the same scenes (i.e. if a matching scene is already loaded on the // used if the server is synchronizing the same scenes (i.e. if a matching scene is already loaded on the
// client side, then that scene will be used as opposed to loading another scene). This allows for clients // client side, then that scene will be used as opposed to loading another scene). This allows for clients

View File

@@ -839,7 +839,7 @@ namespace Unity.Netcode
{ {
// is not packed! // is not packed!
InternalBuffer.ReadValueSafe(out ushort newObjectsCount); InternalBuffer.ReadValueSafe(out ushort newObjectsCount);
var sceneObjects = new List<NetworkObject>();
for (ushort i = 0; i < newObjectsCount; i++) for (ushort i = 0; i < newObjectsCount; i++)
{ {
var sceneObject = new NetworkObject.SceneObject(); var sceneObject = new NetworkObject.SceneObject();
@@ -851,10 +851,22 @@ namespace Unity.Netcode
m_NetworkManager.SceneManager.SetTheSceneBeingSynchronized(sceneObject.NetworkSceneHandle); m_NetworkManager.SceneManager.SetTheSceneBeingSynchronized(sceneObject.NetworkSceneHandle);
} }
NetworkObject.AddSceneObject(sceneObject, InternalBuffer, m_NetworkManager); var networkObject = NetworkObject.AddSceneObject(sceneObject, InternalBuffer, m_NetworkManager);
if (sceneObject.IsSceneObject)
{
sceneObjects.Add(networkObject);
}
} }
// Now deserialize the despawned in-scene placed NetworkObjects list (if any) // Now deserialize the despawned in-scene placed NetworkObjects list (if any)
DeserializeDespawnedInScenePlacedNetworkObjects(); DeserializeDespawnedInScenePlacedNetworkObjects();
// Notify all newly spawned in-scene placed NetworkObjects that all in-scene placed
// NetworkObjects have been spawned.
foreach (var networkObject in sceneObjects)
{
networkObject.InternalInSceneNetworkObjectsSpawned();
}
} }
finally finally
{ {
@@ -1122,6 +1134,15 @@ namespace Unity.Netcode
UnityEngine.Debug.Log(builder.ToString()); UnityEngine.Debug.Log(builder.ToString());
} }
// Notify that all in-scene placed NetworkObjects have been spawned
foreach (var networkObject in m_NetworkObjectsSync)
{
if (networkObject.IsSceneObject.HasValue && networkObject.IsSceneObject.Value)
{
networkObject.InternalInSceneNetworkObjectsSpawned();
}
}
// Now deserialize the despawned in-scene placed NetworkObjects list (if any) // Now deserialize the despawned in-scene placed NetworkObjects list (if any)
DeserializeDespawnedInScenePlacedNetworkObjects(); DeserializeDespawnedInScenePlacedNetworkObjects();

View File

@@ -810,20 +810,27 @@ namespace Unity.Netcode
networkObject.DontDestroyWithOwner = sceneObject.DontDestroyWithOwner; networkObject.DontDestroyWithOwner = sceneObject.DontDestroyWithOwner;
networkObject.Ownership = (NetworkObject.OwnershipStatus)sceneObject.OwnershipFlags; networkObject.Ownership = (NetworkObject.OwnershipStatus)sceneObject.OwnershipFlags;
var nonNetworkObjectParent = false;
// SPECIAL CASE FOR IN-SCENE PLACED: (only when the parent has a NetworkObject) // SPECIAL CASE FOR IN-SCENE PLACED: (only when the parent has a NetworkObject)
// This is a special case scenario where a late joining client has joined and loaded one or // This is a special case scenario where a late joining client has joined and loaded one or
// more scenes that contain nested in-scene placed NetworkObject children yet the server's // more scenes that contain nested in-scene placed NetworkObject children yet the server's
// synchronization information does not indicate the NetworkObject in question has a parent. // synchronization information does not indicate the NetworkObject in question has a parent.
// Under this scenario, we want to remove the parent before spawning and setting the transform values. // Under this scenario, we want to remove the parent before spawning and setting the transform values.
if (sceneObject.IsSceneObject && !sceneObject.HasParent && networkObject.transform.parent != null) if (sceneObject.IsSceneObject && networkObject.transform.parent != null)
{ {
var parentNetworkObject = networkObject.transform.parent.GetComponent<NetworkObject>();
// if the in-scene placed NetworkObject has a parent NetworkObject but the synchronization information does not // if the in-scene placed NetworkObject has a parent NetworkObject but the synchronization information does not
// include parenting, then we need to force the removal of that parent // include parenting, then we need to force the removal of that parent
if (networkObject.transform.parent.GetComponent<NetworkObject>() != null) if (!sceneObject.HasParent && parentNetworkObject)
{ {
// remove the parent // remove the parent
networkObject.ApplyNetworkParenting(true, true); networkObject.ApplyNetworkParenting(true, true);
} }
else if (sceneObject.HasParent && !parentNetworkObject)
{
nonNetworkObjectParent = true;
}
} }
// Set the transform unless we were spawned by a prefab handler // Set the transform unless we were spawned by a prefab handler
@@ -833,7 +840,7 @@ namespace Unity.Netcode
{ {
// If world position stays is true or we have auto object parent synchronization disabled // If world position stays is true or we have auto object parent synchronization disabled
// then we want to apply the position and rotation values world space relative // then we want to apply the position and rotation values world space relative
if (worldPositionStays || !networkObject.AutoObjectParentSync) if ((worldPositionStays && !nonNetworkObjectParent) || !networkObject.AutoObjectParentSync)
{ {
networkObject.transform.position = position; networkObject.transform.position = position;
networkObject.transform.rotation = rotation; networkObject.transform.rotation = rotation;
@@ -917,6 +924,8 @@ namespace Unity.Netcode
Debug.LogError("Spawning NetworkObjects with nested NetworkObjects is only supported for scene objects. Child NetworkObjects will not be spawned over the network!"); Debug.LogError("Spawning NetworkObjects with nested NetworkObjects is only supported for scene objects. Child NetworkObjects will not be spawned over the network!");
} }
} }
// Invoke NetworkBehaviour.OnPreSpawn methods
networkObject.InvokeBehaviourNetworkPreSpawn();
// DANGO-TODO: It would be nice to allow users to specify which clients are observers prior to spawning // DANGO-TODO: It would be nice to allow users to specify which clients are observers prior to spawning
// For now, this is the best place I could find to add all connected clients as observers for newly // For now, this is the best place I could find to add all connected clients as observers for newly
@@ -957,12 +966,18 @@ namespace Unity.Netcode
} }
} }
SpawnNetworkObjectLocallyCommon(networkObject, networkId, sceneObject, playerObject, ownerClientId, destroyWithScene); SpawnNetworkObjectLocallyCommon(networkObject, networkId, sceneObject, playerObject, ownerClientId, destroyWithScene);
// Invoke NetworkBehaviour.OnPostSpawn methods
networkObject.InvokeBehaviourNetworkPostSpawn();
} }
/// <summary> /// <summary>
/// This is only invoked to instantiate a serialized NetworkObject via /// This is only invoked to instantiate a serialized NetworkObject via
/// <see cref="NetworkObject.AddSceneObject(in NetworkObject.SceneObject, FastBufferReader, NetworkManager, bool)"/> /// <see cref="NetworkObject.AddSceneObject(in NetworkObject.SceneObject, FastBufferReader, NetworkManager, bool)"/>
/// </summary> /// </summary>
/// <remarks>
/// IMPORTANT: Pre spawn methods need to be invoked from within <see cref="NetworkObject.AddSceneObject"/>.
/// </remarks>
internal void SpawnNetworkObjectLocally(NetworkObject networkObject, in NetworkObject.SceneObject sceneObject, bool destroyWithScene) internal void SpawnNetworkObjectLocally(NetworkObject networkObject, in NetworkObject.SceneObject sceneObject, bool destroyWithScene)
{ {
if (networkObject == null) if (networkObject == null)
@@ -975,7 +990,11 @@ namespace Unity.Netcode
throw new SpawnStateException($"[{networkObject.name}] Object-{networkObject.NetworkObjectId} is already spawned!"); throw new SpawnStateException($"[{networkObject.name}] Object-{networkObject.NetworkObjectId} is already spawned!");
} }
// Do not invoke Pre spawn here (SynchronizeNetworkBehaviours needs to be invoked prior to this)
SpawnNetworkObjectLocallyCommon(networkObject, sceneObject.NetworkObjectId, sceneObject.IsSceneObject, sceneObject.IsPlayerObject, sceneObject.OwnerClientId, destroyWithScene); SpawnNetworkObjectLocallyCommon(networkObject, sceneObject.NetworkObjectId, sceneObject.IsSceneObject, sceneObject.IsPlayerObject, sceneObject.OwnerClientId, destroyWithScene);
// It is ok to invoke NetworkBehaviour.OnPostSpawn methods
networkObject.InvokeBehaviourNetworkPostSpawn();
} }
private void SpawnNetworkObjectLocallyCommon(NetworkObject networkObject, ulong networkId, bool sceneObject, bool playerObject, ulong ownerClientId, bool destroyWithScene) private void SpawnNetworkObjectLocallyCommon(NetworkObject networkObject, ulong networkId, bool sceneObject, bool playerObject, ulong ownerClientId, bool destroyWithScene)
@@ -1226,7 +1245,7 @@ namespace Unity.Netcode
{ {
// If it is an in-scene placed NetworkObject then just despawn and let it be destroyed when the scene // If it is an in-scene placed NetworkObject then just despawn and let it be destroyed when the scene
// is unloaded. Otherwise, despawn and destroy it. // is unloaded. Otherwise, despawn and destroy it.
var shouldDestroy = !(networkObjects[i].IsSceneObject != null && networkObjects[i].IsSceneObject.Value); var shouldDestroy = !(networkObjects[i].IsSceneObject == null || (networkObjects[i].IsSceneObject != null && networkObjects[i].IsSceneObject.Value));
// If we are going to destroy this NetworkObject, check for any in-scene placed children that need to be removed // If we are going to destroy this NetworkObject, check for any in-scene placed children that need to be removed
if (shouldDestroy) if (shouldDestroy)
@@ -1307,6 +1326,7 @@ namespace Unity.Netcode
var networkObjects = UnityEngine.Object.FindObjectsOfType<NetworkObject>(); var networkObjects = UnityEngine.Object.FindObjectsOfType<NetworkObject>();
#endif #endif
var isConnectedCMBService = NetworkManager.CMBServiceConnection; var isConnectedCMBService = NetworkManager.CMBServiceConnection;
var networkObjectsToSpawn = new List<NetworkObject>();
for (int i = 0; i < networkObjects.Length; i++) for (int i = 0; i < networkObjects.Length; i++)
{ {
if (networkObjects[i].NetworkManager == NetworkManager) if (networkObjects[i].NetworkManager == NetworkManager)
@@ -1323,9 +1343,17 @@ namespace Unity.Netcode
} }
SpawnNetworkObjectLocally(networkObjects[i], GetNetworkObjectId(), true, false, ownerId, true); SpawnNetworkObjectLocally(networkObjects[i], GetNetworkObjectId(), true, false, ownerId, true);
networkObjectsToSpawn.Add(networkObjects[i]);
} }
} }
} }
// Notify all in-scene placed NetworkObjects have been spawned
foreach (var networkObject in networkObjectsToSpawn)
{
networkObject.InternalInSceneNetworkObjectsSpawned();
}
networkObjectsToSpawn.Clear();
} }
internal void OnDespawnObject(NetworkObject networkObject, bool destroyGameObject, bool modeDestroy = false) internal void OnDespawnObject(NetworkObject networkObject, bool destroyGameObject, bool modeDestroy = false)

View File

@@ -426,10 +426,11 @@ namespace Unity.Netcode.Transports.UTP
internal static event Action<int> TransportDisposed; internal static event Action<int> TransportDisposed;
internal NetworkDriver NetworkDriver => m_Driver; internal NetworkDriver NetworkDriver => m_Driver;
protected NetworkDriver m_Driver;
private PacketLossCache m_PacketLossCache = new PacketLossCache(); private PacketLossCache m_PacketLossCache = new PacketLossCache();
private State m_State = State.Disconnected; private State m_State = State.Disconnected;
private NetworkDriver m_Driver;
private NetworkSettings m_NetworkSettings; private NetworkSettings m_NetworkSettings;
private ulong m_ServerClientId; private ulong m_ServerClientId;
@@ -554,12 +555,17 @@ namespace Unity.Netcode.Transports.UTP
return false; return false;
} }
var serverConnection = m_Driver.Connect(serverEndpoint); var serverConnection = Connect(serverEndpoint);
m_ServerClientId = ParseClientId(serverConnection); m_ServerClientId = ParseClientId(serverConnection);
return true; return true;
} }
protected virtual NetworkConnection Connect(NetworkEndpoint serverEndpoint)
{
return m_Driver.Connect(serverEndpoint);
}
private bool ServerBindAndListen(NetworkEndpoint endPoint) private bool ServerBindAndListen(NetworkEndpoint endPoint)
{ {
// Verify the endpoint is valid before proceeding // Verify the endpoint is valid before proceeding

View File

@@ -46,6 +46,21 @@
"name": "Unity", "name": "Unity",
"expression": "2023", "expression": "2023",
"define": "UNITY_DEDICATED_SERVER_ARGUMENTS_PRESENT" "define": "UNITY_DEDICATED_SERVER_ARGUMENTS_PRESENT"
},
{
"name": "com.unity.modules.animation",
"expression": "",
"define": "COM_UNITY_MODULES_ANIMATION"
},
{
"name": "com.unity.modules.physics",
"expression": "",
"define": "COM_UNITY_MODULES_PHYSICS"
},
{
"name": "com.unity.modules.physics2d",
"expression": "",
"define": "COM_UNITY_MODULES_PHYSICS2D"
} }
] ]
} }

View File

@@ -87,7 +87,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
return new Vector3(Random.Range(min, max), Random.Range(min, max), Random.Range(min, max)); return new Vector3(Random.Range(min, max), Random.Range(min, max), Random.Range(min, max));
} }
public IntegrationTestWithApproximation(SessionModeTypes sessionModeType) : base(sessionModeType) { } public IntegrationTestWithApproximation(NetworkTopologyTypes networkTopologyType) : base(networkTopologyType) { }
public IntegrationTestWithApproximation(HostOrServer hostOrServer) : base(hostOrServer) { } public IntegrationTestWithApproximation(HostOrServer hostOrServer) : base(hostOrServer) { }

View File

@@ -139,21 +139,21 @@ namespace Unity.Netcode.TestHelpers.Runtime
protected bool m_UseHost = true; protected bool m_UseHost = true;
protected bool m_DistributedAuthority; protected bool m_DistributedAuthority;
protected SessionModeTypes m_SessionModeType = SessionModeTypes.ClientServer; protected NetworkTopologyTypes m_NetworkTopologyType = NetworkTopologyTypes.ClientServer;
protected virtual bool UseCMBService() protected virtual bool UseCMBService()
{ {
return false; return false;
} }
protected virtual SessionModeTypes OnGetSessionmode() protected virtual NetworkTopologyTypes OnGetNetworkTopologyType()
{ {
return m_SessionModeType; return m_NetworkTopologyType;
} }
protected void SetDistributedAuthorityProperties(NetworkManager networkManager) protected void SetDistributedAuthorityProperties(NetworkManager networkManager)
{ {
networkManager.NetworkConfig.SessionMode = m_SessionModeType; networkManager.NetworkConfig.NetworkTopology = m_NetworkTopologyType;
networkManager.NetworkConfig.AutoSpawnPlayerPrefabClientSide = m_DistributedAuthority; networkManager.NetworkConfig.AutoSpawnPlayerPrefabClientSide = m_DistributedAuthority;
networkManager.NetworkConfig.UseCMBService = UseCMBService() && m_DistributedAuthority; networkManager.NetworkConfig.UseCMBService = UseCMBService() && m_DistributedAuthority;
} }
@@ -1567,7 +1567,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
Assert.IsFalse(m_ServerNetworkManager.IsListening, prefabCreateAssertError); Assert.IsFalse(m_ServerNetworkManager.IsListening, prefabCreateAssertError);
var prefabObject = NetcodeIntegrationTestHelpers.CreateNetworkObjectPrefab(baseName, m_ServerNetworkManager, m_ClientNetworkManagers); var prefabObject = NetcodeIntegrationTestHelpers.CreateNetworkObjectPrefab(baseName, m_ServerNetworkManager, m_ClientNetworkManagers);
// DANGO-TODO: Ownership flags could require us to change this // DANGO-TODO: Ownership flags could require us to change this
// For testing purposes, we default to true for the distribute ownership property when in distirbuted authority session mode. // For testing purposes, we default to true for the distribute ownership property when in a distirbuted authority network topology.
prefabObject.GetComponent<NetworkObject>().Ownership |= NetworkObject.OwnershipStatus.Distributable; prefabObject.GetComponent<NetworkObject>().Ownership |= NetworkObject.OwnershipStatus.Distributable;
return prefabObject; return prefabObject;
} }
@@ -1605,7 +1605,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
var newInstance = Object.Instantiate(prefabNetworkObject.gameObject); var newInstance = Object.Instantiate(prefabNetworkObject.gameObject);
var networkObjectToSpawn = newInstance.GetComponent<NetworkObject>(); var networkObjectToSpawn = newInstance.GetComponent<NetworkObject>();
if (owner.NetworkConfig.SessionMode == SessionModeTypes.DistributedAuthority) if (owner.NetworkConfig.NetworkTopology == NetworkTopologyTypes.DistributedAuthority)
{ {
networkObjectToSpawn.NetworkManagerOwner = owner; // Required to assure the client does the spawning networkObjectToSpawn.NetworkManagerOwner = owner; // Required to assure the client does the spawning
if (isPlayerObject) if (isPlayerObject)
@@ -1687,15 +1687,15 @@ namespace Unity.Netcode.TestHelpers.Runtime
/// </summary> /// </summary>
public NetcodeIntegrationTest() public NetcodeIntegrationTest()
{ {
m_SessionModeType = OnGetSessionmode(); m_NetworkTopologyType = OnGetNetworkTopologyType();
m_DistributedAuthority = OnGetSessionmode() == SessionModeTypes.DistributedAuthority; m_DistributedAuthority = m_NetworkTopologyType == NetworkTopologyTypes.DistributedAuthority;
NetworkMessageManager.EnableMessageOrderConsoleLog = false; NetworkMessageManager.EnableMessageOrderConsoleLog = false;
} }
public NetcodeIntegrationTest(SessionModeTypes sessionMode) public NetcodeIntegrationTest(NetworkTopologyTypes networkTopologyType)
{ {
m_SessionModeType = sessionMode; m_NetworkTopologyType = networkTopologyType;
m_DistributedAuthority = OnGetSessionmode() == SessionModeTypes.DistributedAuthority; m_DistributedAuthority = m_NetworkTopologyType == NetworkTopologyTypes.DistributedAuthority;
} }
/// <summary> /// <summary>
@@ -1717,8 +1717,8 @@ namespace Unity.Netcode.TestHelpers.Runtime
public NetcodeIntegrationTest(HostOrServer hostOrServer) public NetcodeIntegrationTest(HostOrServer hostOrServer)
{ {
m_UseHost = hostOrServer == HostOrServer.Host || hostOrServer == HostOrServer.DAHost; m_UseHost = hostOrServer == HostOrServer.Host || hostOrServer == HostOrServer.DAHost;
m_SessionModeType = hostOrServer == HostOrServer.DAHost ? SessionModeTypes.DistributedAuthority : SessionModeTypes.ClientServer; m_NetworkTopologyType = hostOrServer == HostOrServer.DAHost ? NetworkTopologyTypes.DistributedAuthority : NetworkTopologyTypes.ClientServer;
m_DistributedAuthority = OnGetSessionmode() == SessionModeTypes.DistributedAuthority; m_DistributedAuthority = OnGetNetworkTopologyType() == NetworkTopologyTypes.DistributedAuthority;
} }
/// <summary> /// <summary>

View File

@@ -378,7 +378,8 @@ namespace Unity.Netcode.TestHelpers.Runtime
{ {
// If VerifySceneBeforeLoading is not already set, then go ahead and set it so the host/server // If VerifySceneBeforeLoading is not already set, then go ahead and set it so the host/server
// will not try to synchronize clients to the TestRunner scene. We only need to do this for the server. // will not try to synchronize clients to the TestRunner scene. We only need to do this for the server.
if (networkManager.IsServer && networkManager.SceneManager.VerifySceneBeforeLoading == null) // All clients in distributed authority mode, should have this registered (since any one client can become the session owner).
if ((networkManager.IsServer && networkManager.SceneManager.VerifySceneBeforeLoading == null) || networkManager.DistributedAuthorityMode)
{ {
networkManager.SceneManager.VerifySceneBeforeLoading = VerifySceneIsValidForClientsToLoad; networkManager.SceneManager.VerifySceneBeforeLoading = VerifySceneIsValidForClientsToLoad;

View File

@@ -2,7 +2,7 @@ using NUnit.Framework;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class ArithmeticTests internal class ArithmeticTests
{ {
[Test] [Test]
public void TestCeil() public void TestCeil()

View File

@@ -8,7 +8,7 @@ using UnityEngine;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class BuildTests internal class BuildTests
{ {
public const string DefaultBuildScenePath = "Tests/Editor/Build/BuildTestScene.unity"; public const string DefaultBuildScenePath = "Tests/Editor/Build/BuildTestScene.unity";

View File

@@ -3,7 +3,7 @@ using Unity.Collections;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class DisconnectMessageTests internal class DisconnectMessageTests
{ {
[Test] [Test]
public void EmptyDisconnectReason() public void EmptyDisconnectReason()

View File

@@ -3,7 +3,7 @@ using NUnit.Framework;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class InterpolatorTests internal class InterpolatorTests
{ {
private const float k_Precision = 0.00000001f; private const float k_Precision = 0.00000001f;
private const int k_MockTickRate = 1; private const int k_MockTickRate = 1;

View File

@@ -3,7 +3,7 @@ using NUnit.Framework;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class DisconnectOnSendTests internal class DisconnectOnSendTests
{ {
private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy
{ {

View File

@@ -10,7 +10,7 @@ using UnityEngine.TestTools;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class MessageCorruptionTests internal class MessageCorruptionTests
{ {
private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy

View File

@@ -7,7 +7,7 @@ using Unity.Collections.LowLevel.Unsafe;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class MessageReceivingTests internal class MessageReceivingTests
{ {
private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy
{ {

View File

@@ -3,7 +3,7 @@ using NUnit.Framework;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class MessageRegistrationTests internal class MessageRegistrationTests
{ {
private struct TestMessageOne : INetworkMessage, INetworkSerializeByMemcpy private struct TestMessageOne : INetworkMessage, INetworkSerializeByMemcpy
{ {
@@ -191,77 +191,5 @@ namespace Unity.Netcode.EditorTests
Assert.AreEqual(handlerFour, systemThree.MessageHandlers[systemThree.GetMessageType(typeof(TestMessageFour))]); Assert.AreEqual(handlerFour, systemThree.MessageHandlers[systemThree.GetMessageType(typeof(TestMessageFour))]);
} }
} }
internal class AAAEarlyLexicographicNetworkMessage : INetworkMessage
{
public void Serialize(FastBufferWriter writer, int targetVersion)
{
}
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
return true;
}
public void Handle(ref NetworkContext context)
{
}
public int Version => 0;
}
#pragma warning disable IDE1006
internal class zzzLateLexicographicNetworkMessage : AAAEarlyLexicographicNetworkMessage
{
}
#pragma warning restore IDE1006
internal class OrderingMessageProvider : INetworkMessageProvider
{
public List<NetworkMessageManager.MessageWithHandler> GetMessages()
{
var listMessages = new List<NetworkMessageManager.MessageWithHandler>();
var messageWithHandler = new NetworkMessageManager.MessageWithHandler
{
MessageType = typeof(zzzLateLexicographicNetworkMessage),
GetVersion = NetworkMessageManager.CreateMessageAndGetVersion<zzzLateLexicographicNetworkMessage>
};
listMessages.Add(messageWithHandler);
messageWithHandler.MessageType = typeof(ConnectionRequestMessage);
messageWithHandler.GetVersion = NetworkMessageManager.CreateMessageAndGetVersion<ConnectionRequestMessage>;
listMessages.Add(messageWithHandler);
messageWithHandler.MessageType = typeof(ConnectionApprovedMessage);
messageWithHandler.GetVersion = NetworkMessageManager.CreateMessageAndGetVersion<ConnectionApprovedMessage>;
listMessages.Add(messageWithHandler);
messageWithHandler.MessageType = typeof(AAAEarlyLexicographicNetworkMessage);
messageWithHandler.GetVersion = NetworkMessageManager.CreateMessageAndGetVersion<AAAEarlyLexicographicNetworkMessage>;
listMessages.Add(messageWithHandler);
return listMessages;
}
}
[Test]
public void MessagesGetPrioritizedCorrectly()
{
var sender = new NopMessageSender();
var provider = new OrderingMessageProvider();
using var messageManager = new NetworkMessageManager(sender, null, provider);
// the 2 priority messages should appear first, in lexicographic order
Assert.AreEqual(messageManager.MessageTypes[0], typeof(ConnectionApprovedMessage));
Assert.AreEqual(messageManager.MessageTypes[1], typeof(ConnectionRequestMessage));
// the other should follow after
Assert.AreEqual(messageManager.MessageTypes[2], typeof(AAAEarlyLexicographicNetworkMessage));
Assert.AreEqual(messageManager.MessageTypes[3], typeof(zzzLateLexicographicNetworkMessage));
// there should not be any extras
Assert.AreEqual(messageManager.MessageHandlerCount, 4);
}
} }
} }

View File

@@ -10,7 +10,7 @@ using Random = System.Random;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class MessageSendingTests internal class MessageSendingTests
{ {
private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy
{ {

View File

@@ -5,7 +5,7 @@ using NUnit.Framework.Internal;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class MessageVersioningTests internal class MessageVersioningTests
{ {
public static int SentVersion; public static int SentVersion;
public static int ReceivedVersion; public static int ReceivedVersion;

View File

@@ -8,7 +8,7 @@ using Unity.Multiplayer.Tools.NetStats;
namespace Unity.Netcode.EditorTests.Metrics namespace Unity.Netcode.EditorTests.Metrics
{ {
public class NetworkMetricsRegistrationTests internal class NetworkMetricsRegistrationTests
{ {
private static Type[] s_MetricTypes = AppDomain.CurrentDomain.GetAssemblies() private static Type[] s_MetricTypes = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x => x.GetTypes()) .SelectMany(x => x.GetTypes())

View File

@@ -4,7 +4,7 @@ using Object = UnityEngine.Object;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class NetworkBehaviourTests internal class NetworkBehaviourTests
{ {
[Test] [Test]
public void HasNetworkObjectTest() public void HasNetworkObjectTest()
@@ -66,12 +66,12 @@ namespace Unity.Netcode.EditorTests
// Note: in order to repro https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues/1078 // Note: in order to repro https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues/1078
// this child class must be defined before its parent to assure it is processed first by ILPP // this child class must be defined before its parent to assure it is processed first by ILPP
public class DerivedNetworkBehaviour : EmptyNetworkBehaviour internal class DerivedNetworkBehaviour : EmptyNetworkBehaviour
{ {
} }
public class EmptyNetworkBehaviour : NetworkBehaviour internal class EmptyNetworkBehaviour : NetworkBehaviour
{ {
} }

View File

@@ -9,8 +9,20 @@ using UnityEngine.TestTools;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class NetworkManagerConfigurationTests internal class NetworkManagerConfigurationTests
{ {
[SetUp]
public void OnSetup()
{
ILPPMessageProvider.IntegrationTestNoMessages = true;
}
[TearDown]
public void OnTearDown()
{
ILPPMessageProvider.IntegrationTestNoMessages = false;
}
/// <summary> /// <summary>
/// Does a simple check to make sure the nested network manager will /// Does a simple check to make sure the nested network manager will
/// notify the user when in the editor. This is just a unit test to /// notify the user when in the editor. This is just a unit test to

View File

@@ -6,7 +6,7 @@ using UnityEngine.TestTools;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class NetworkObjectTests internal class NetworkObjectTests
{ {
[Test] [Test]
public void NetworkManagerOverrideTest() public void NetworkManagerOverrideTest()
@@ -146,12 +146,12 @@ namespace Unity.Netcode.EditorTests
public int NetworkBehaviourIndex; public int NetworkBehaviourIndex;
} }
public class EmptyNetworkBehaviour : NetworkBehaviour internal class EmptyNetworkBehaviour : NetworkBehaviour
{ {
} }
public class EmptyMonoBehaviour : MonoBehaviour internal class EmptyMonoBehaviour : MonoBehaviour
{ {
} }

View File

@@ -5,7 +5,7 @@ using UnityEngine;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class NetworkPrefabProcessorTests internal class NetworkPrefabProcessorTests
{ {
private NetcodeForGameObjectsProjectSettings m_Settings; private NetcodeForGameObjectsProjectSettings m_Settings;
private bool m_EditorDefaultPrefabSetting; private bool m_EditorDefaultPrefabSetting;

View File

@@ -3,9 +3,9 @@ using UnityEngine;
namespace Unity.Netcode.EditorTests.NetworkVar namespace Unity.Netcode.EditorTests.NetworkVar
{ {
public class NetworkVarTests internal class NetworkVarTests
{ {
public class NetworkVarComponent : NetworkBehaviour internal class NetworkVarComponent : NetworkBehaviour
{ {
public NetworkVariable<int> NetworkVariable = new NetworkVariable<int>(); public NetworkVariable<int> NetworkVariable = new NetworkVariable<int>();
} }

View File

@@ -6,7 +6,7 @@ using Random = System.Random;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public abstract class BaseFastBufferReaderWriterTest internal abstract class BaseFastBufferReaderWriterTest
{ {
protected enum ByteEnum : byte protected enum ByteEnum : byte
{ {

View File

@@ -2,7 +2,7 @@ using NUnit.Framework;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class BitCounterTests internal class BitCounterTests
{ {
[Test] [Test]
public void WhenCountingUsedBitsIn64BitValue_ResultMatchesHighBitSetPlusOne([Range(0, 63)] int highBit) public void WhenCountingUsedBitsIn64BitValue_ResultMatchesHighBitSetPlusOne([Range(0, 63)] int highBit)

View File

@@ -4,7 +4,7 @@ using Unity.Collections;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class BitReaderTests internal class BitReaderTests
{ {
[Test] [Test]
public void TestReadingOneBit() public void TestReadingOneBit()

View File

@@ -4,7 +4,7 @@ using Unity.Collections;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class BitWriterTests internal class BitWriterTests
{ {
[Test] [Test]
public unsafe void TestWritingOneBit() public unsafe void TestWritingOneBit()

View File

@@ -5,7 +5,7 @@ using Random = System.Random;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class BufferSerializerTests internal class BufferSerializerTests
{ {
[Test] [Test]
public void TestIsReaderIsWriter() public void TestIsReaderIsWriter()

View File

@@ -8,7 +8,7 @@ using Random = System.Random;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class BytePackerTests internal class BytePackerTests
{ {
private enum ByteEnum : byte private enum ByteEnum : byte
{ {

View File

@@ -7,7 +7,7 @@ using Random = System.Random;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class FastBufferReaderTests : BaseFastBufferReaderWriterTest internal class FastBufferReaderTests : BaseFastBufferReaderWriterTest
{ {
private void WriteCheckBytes(FastBufferWriter writer, int writeSize, string failMessage = "") private void WriteCheckBytes(FastBufferWriter writer, int writeSize, string failMessage = "")
{ {

View File

@@ -8,7 +8,7 @@ using Random = System.Random;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class FastBufferWriterTests : BaseFastBufferReaderWriterTest internal class FastBufferWriterTests : BaseFastBufferReaderWriterTest
{ {
private void WriteCheckBytes(FastBufferWriter writer, int writeSize, string failMessage = "") private void WriteCheckBytes(FastBufferWriter writer, int writeSize, string failMessage = "")
{ {

View File

@@ -3,7 +3,7 @@ using Unity.Collections;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class UserBitReaderAndBitWriterTests_NCCBUG175 internal class UserBitReaderAndBitWriterTests_NCCBUG175
{ {
[Test] [Test]

View File

@@ -7,7 +7,7 @@ namespace Unity.Netcode.EditorTests
/// <summary> /// <summary>
/// Tests for running a <see cref="NetworkTimeSystem"/> as a client. /// Tests for running a <see cref="NetworkTimeSystem"/> as a client.
/// </summary> /// </summary>
public class ClientNetworkTimeSystemTests internal class ClientNetworkTimeSystemTests
{ {
private const double k_AcceptableRttOffset = 0.03d; // 30ms offset is fine private const double k_AcceptableRttOffset = 0.03d; // 30ms offset is fine

View File

@@ -7,7 +7,7 @@ using Random = System.Random;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class NetworkTimeTests internal class NetworkTimeTests
{ {
[Test] [Test]
[TestCase(0d, 0u)] [TestCase(0d, 0u)]

View File

@@ -3,7 +3,7 @@ using UnityEngine;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class ServerNetworkTimeSystemTests internal class ServerNetworkTimeSystemTests
{ {
/// <summary> /// <summary>

View File

@@ -7,7 +7,7 @@ namespace Unity.Netcode.EditorTests
/// <summary> /// <summary>
/// Helper functions for timing related tests. Allows to get a set of time steps and simulate time advancing without the need of a full playmode test. /// Helper functions for timing related tests. Allows to get a set of time steps and simulate time advancing without the need of a full playmode test.
/// </summary> /// </summary>
public static class TimingTestHelper internal static class TimingTestHelper
{ {
public static List<float> GetRandomTimeSteps(float totalDuration, float min, float max, int seed) public static List<float> GetRandomTimeSteps(float totalDuration, float min, float max, int seed)
{ {

View File

@@ -8,7 +8,7 @@ using Unity.Networking.Transport;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class BatchedReceiveQueueTests internal class BatchedReceiveQueueTests
{ {
[Test] [Test]
public void BatchedReceiveQueue_EmptyReader() public void BatchedReceiveQueue_EmptyReader()

View File

@@ -8,7 +8,7 @@ using Unity.Networking.Transport;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class BatchedSendQueueTests internal class BatchedSendQueueTests
{ {
private const int k_TestQueueCapacity = 16 * 1024; private const int k_TestQueueCapacity = 16 * 1024;
private const int k_TestMessageSize = 1020; private const int k_TestMessageSize = 1020;

View File

@@ -7,7 +7,7 @@ using UnityEngine.TestTools;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class UNetTransportTests internal class UNetTransportTests
{ {
[Test] [Test]
public void StartServerReturnsFalseOnFailure() public void StartServerReturnsFalseOnFailure()

View File

@@ -5,8 +5,20 @@ using UnityEngine.TestTools;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class UnityTransportTests internal class UnityTransportTests
{ {
[SetUp]
public void OnSetup()
{
ILPPMessageProvider.IntegrationTestNoMessages = true;
}
[TearDown]
public void OnTearDown()
{
ILPPMessageProvider.IntegrationTestNoMessages = false;
}
// Check that starting an IPv4 server succeeds. // Check that starting an IPv4 server succeeds.
[Test] [Test]
public void UnityTransport_BasicInitServer_IPv4() public void UnityTransport_BasicInitServer_IPv4()

View File

@@ -2,7 +2,7 @@ using NUnit.Framework;
namespace Unity.Netcode.EditorTests namespace Unity.Netcode.EditorTests
{ {
public class XXHashTests internal class XXHashTests
{ {
[Test] [Test]
public void TestXXHash32Short() public void TestXXHash32Short()

View File

@@ -7,9 +7,9 @@ using Object = UnityEngine.Object;
namespace Unity.Netcode.RuntimeTests namespace Unity.Netcode.RuntimeTests
{ {
public class AddNetworkPrefabTest : NetcodeIntegrationTest internal class AddNetworkPrefabTest : NetcodeIntegrationTest
{ {
public class EmptyComponent : NetworkBehaviour internal class EmptyComponent : NetworkBehaviour
{ {
} }

View File

@@ -7,7 +7,7 @@ using UnityEngine.TestTools;
namespace Unity.Netcode.RuntimeTests namespace Unity.Netcode.RuntimeTests
{ {
public class ClientApprovalDenied : NetcodeIntegrationTest internal class ClientApprovalDenied : NetcodeIntegrationTest
{ {
protected override int NumberOfClients => 2; protected override int NumberOfClients => 2;
private bool m_ApproveConnection = true; private bool m_ApproveConnection = true;

View File

@@ -7,7 +7,7 @@ using UnityEngine.TestTools;
namespace Unity.Netcode.RuntimeTests namespace Unity.Netcode.RuntimeTests
{ {
public class ClientOnlyConnectionTests internal class ClientOnlyConnectionTests
{ {
private NetworkManager m_ClientNetworkManager; private NetworkManager m_ClientNetworkManager;
private GameObject m_NetworkManagerGameObject; private GameObject m_NetworkManagerGameObject;

View File

@@ -9,7 +9,7 @@ namespace Unity.Netcode.RuntimeTests
/// - Sending and Receiving a continually growing buffer up to (MaximumBufferSize) /// - Sending and Receiving a continually growing buffer up to (MaximumBufferSize)
/// - Default maximum buffer size is 1MB /// - Default maximum buffer size is 1MB
/// </summary> /// </summary>
public class BufferDataValidationComponent : NetworkBehaviour internal class BufferDataValidationComponent : NetworkBehaviour
{ {
/// <summary> /// <summary>
/// Allows the external RPCQueueTest to begin testing or stop it /// Allows the external RPCQueueTest to begin testing or stop it

View File

@@ -6,7 +6,7 @@ using UnityEngine;
namespace Unity.Netcode.RuntimeTests namespace Unity.Netcode.RuntimeTests
{ {
public class EmbeddedManagedNetworkSerializableType : INetworkSerializable internal class EmbeddedManagedNetworkSerializableType : INetworkSerializable
{ {
public int Int; public int Int;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
@@ -14,7 +14,7 @@ namespace Unity.Netcode.RuntimeTests
serializer.SerializeValue(ref Int); serializer.SerializeValue(ref Int);
} }
} }
public class ManagedNetworkSerializableType : INetworkSerializable, IEquatable<ManagedNetworkSerializableType> internal class ManagedNetworkSerializableType : INetworkSerializable, IEquatable<ManagedNetworkSerializableType>
{ {
public string Str = ""; public string Str = "";
public int[] Ints = Array.Empty<int>(); public int[] Ints = Array.Empty<int>();
@@ -104,7 +104,7 @@ namespace Unity.Netcode.RuntimeTests
return 0; return 0;
} }
} }
public struct UnmanagedNetworkSerializableType : INetworkSerializable, IEquatable<UnmanagedNetworkSerializableType> internal struct UnmanagedNetworkSerializableType : INetworkSerializable, IEquatable<UnmanagedNetworkSerializableType>
{ {
public FixedString32Bytes Str; public FixedString32Bytes Str;
public int Int; public int Int;
@@ -143,7 +143,7 @@ namespace Unity.Netcode.RuntimeTests
} }
public struct UnmanagedTemplateNetworkSerializableType<T> : INetworkSerializable where T : unmanaged, INetworkSerializable internal struct UnmanagedTemplateNetworkSerializableType<T> : INetworkSerializable where T : unmanaged, INetworkSerializable
{ {
public T Value; public T Value;
@@ -153,7 +153,7 @@ namespace Unity.Netcode.RuntimeTests
} }
} }
public struct ManagedTemplateNetworkSerializableType<T> : INetworkSerializable where T : class, INetworkSerializable, new() internal struct ManagedTemplateNetworkSerializableType<T> : INetworkSerializable where T : class, INetworkSerializable, new()
{ {
public T Value; public T Value;

View File

@@ -1,6 +1,6 @@
namespace Unity.Netcode.RuntimeTests namespace Unity.Netcode.RuntimeTests
{ {
public class NetworkVisibilityComponent : NetworkBehaviour internal class NetworkVisibilityComponent : NetworkBehaviour
{ {
public void Hide() public void Hide()
{ {

View File

@@ -8,7 +8,7 @@ using UnityEngine.TestTools;
namespace Unity.Netcode.RuntimeTests namespace Unity.Netcode.RuntimeTests
{ {
public class ConnectionApprovalTests internal class ConnectionApprovalTests
{ {
private Guid m_ValidationToken; private Guid m_ValidationToken;
private bool m_IsValidated; private bool m_IsValidated;

View File

@@ -9,7 +9,7 @@ namespace Unity.Netcode.RuntimeTests
{ {
[TestFixture(ApprovalTimedOutTypes.ServerDoesNotRespond)] [TestFixture(ApprovalTimedOutTypes.ServerDoesNotRespond)]
[TestFixture(ApprovalTimedOutTypes.ClientDoesNotRequest)] [TestFixture(ApprovalTimedOutTypes.ClientDoesNotRequest)]
public class ConnectionApprovalTimeoutTests : NetcodeIntegrationTest internal class ConnectionApprovalTimeoutTests : NetcodeIntegrationTest
{ {
protected override int NumberOfClients => 1; protected override int NumberOfClients => 1;

Some files were not shown because too many files have changed in this diff Show More