3 Commits

Author SHA1 Message Date
Unity Technologies
eab996f3ac com.unity.netcode.gameobjects@2.0.0-pre.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-pre.4] - 2024-08-21

### Added

- Added `NetworkVariable.CheckDirtyState` that is to be used in tandem with collections in order to detect whether the collection or an item within the collection has changed. (#3004)

### Fixed

- Fixed issue where nested `NetworkTransform` components were not getting updated. (#3016)
- Fixed issue by adding null checks in `NetworkVariableBase.CanClientRead` and `NetworkVariableBase.CanClientWrite` methods to ensure safe access to `NetworkBehaviour`. (#3012)
- Fixed issue where `FixedStringSerializer<T>` was using `NetworkVariableSerialization<byte>.AreEqual` to determine if two bytes were equal causes an exception to be thrown due to no byte serializer having been defined. (#3009)
- Fixed Issue where a state with dual triggers, inbound and outbound, could cause a false layer to layer state transition message to be sent to non-authority `NetworkAnimator` instances and cause a warning message to be logged. (#3008)
- Fixed issue using collections within `NetworkVariable` where the collection would not detect changes to items or nested items. (#3004)
- Fixed issue where `List`, `Dictionary`, and `HashSet` collections would not uniquely duplicate nested collections. (#3004)
- Fixed issue where `NotAuthorityTarget` would include the service observer in the list of targets to send the RPC to as opposed to excluding the service observer as it should. (#3000)
- Fixed issue where `ProxyRpcTargetGroup` could attempt to send a message if there were no targets to send to. (#3000)

### Changed

- Changed `NetworkAnimator` to automatically switch to owner authoritative mode when using a distributed authority network topology. (#3021)
- Changed permissions exception thrown in `NetworkList` to exiting early with a logged error that is now a unified permissions message within `NetworkVariableBase`. (#3004)
- Changed permissions exception thrown in `NetworkVariable.Value` to exiting early with a logged error that is now a unified permissions message within `NetworkVariableBase`. (#3004)
2024-08-21 00:00:00 +00:00
Unity Technologies
a813ba0dd6 com.unity.netcode.gameobjects@2.0.0-pre.3
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).

## [2.0.0-pre.3] - 2024-07-23

### Added
- Added: `UnityTransport.GetNetworkDriver` and `UnityTransport.GetLocalEndpoint` methods to expose the driver and local endpoint being used. (#2978)

### Fixed

- Fixed issue where deferred despawn was causing GC allocations when converting an `IEnumerable` to a list. (#2983)
- Fixed issue where the realtime network stats monitor was not able to display RPC traffic in release builds due to those stats being only available in development builds or the editor. (#2979)
- Fixed issue where `NetworkManager.ScenesLoaded` was not being updated if `PostSynchronizationSceneUnloading` was set and any loaded scenes not used during synchronization were unloaded. (#2971)
- Fixed issue where `Rigidbody2d` under Unity 6000.0.11f1 has breaking changes where `velocity` is now `linearVelocity` and `isKinematic` is replaced by `bodyType`. (#2971)
- Fixed issue where `NetworkSpawnManager.InstantiateAndSpawn` and `NetworkObject.InstantiateAndSpawn` were not honoring the ownerClientId parameter when using a client-server network topology. (#2968)
- Fixed issue where internal delta serialization could not have a byte serializer defined when serializing deltas for other types. Added `[GenerateSerializationForType(typeof(byte))]` to both the `NetworkVariable` and `AnticipatedNetworkVariable` classes to assure a byte serializer is defined.(#2962)
- Fixed issue when scene management was disabled and the session owner would still try to synchronize a late joining client. (#2962)
- Fixed issue when using a distributed authority network topology where it would allow a session owner to spawn a `NetworkObject` prior to being approved. Now, an error message is logged and the `NetworkObject` will not be spawned prior to the client being approved.  (#2962)
- Fixed issue where attempting to spawn during `NetworkBehaviour.OnInSceneObjectsSpawned` and `NetworkBehaviour.OnNetworkSessionSynchronized` notifications would throw a collection modified exception.  (#2962)

### Changed

- Changed logic where clients can now set the `NetworkSceneManager` client synchronization mode when using a distributed authority network topology. (#2985)
2024-07-23 00:00:00 +00:00
Unity Technologies
c813386c5c com.unity.netcode.gameobjects@2.0.0-pre.2
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).

## [2.0.0-pre.2] - 2024-06-17

### Added

- Added `AnticipatedNetworkVariable<T>`, which adds support for client anticipation of `NetworkVariable` values, allowing for more responsive gameplay. (#2957)
- Added `AnticipatedNetworkTransform`, which adds support for client anticipation of NetworkTransforms. (#2957)
- Added `NetworkVariableBase.ExceedsDirtinessThreshold` to allow network variables to throttle updates by only sending updates when the difference between the current and previous values exceeds a threshold. (This is exposed in `NetworkVariable<T>` with the callback `NetworkVariable<T>.CheckExceedsDirtinessThreshold`). (#2957)
- Added `NetworkVariableUpdateTraits`, which add additional throttling support: `MinSecondsBetweenUpdates` will prevent the `NetworkVariable` from sending updates more often than the specified time period (even if it exceeds the dirtiness threshold), while `MaxSecondsBetweenUpdates` will force a dirty `NetworkVariable` to send an update after the specified time period even if it has not yet exceeded the dirtiness threshold. (#2957)
- Added virtual method `NetworkVariableBase.OnInitialize` which can be used by `NetworkVariable` subclasses to add initialization code. (#2957)
- Added `NetworkTime.TickWithPartial`, which represents the current tick as a double that includes the fractional/partial tick value. (#2957)
- Added `NetworkTickSystem.AnticipationTick`, which can be helpful with implementation of client anticipation. This value represents the tick the current local client was at at the beginning of the most recent network round trip, which enables it to correlate server update ticks with the client tick that may have triggered them. (#2957)
- Added event `NetworkManager.OnSessionOwnerPromoted` that is invoked when a new session owner promotion occurs. (#2948)
- Added `NetworkRigidBodyBase.GetLinearVelocity` and `NetworkRigidBodyBase.SetLinearVelocity` convenience/helper methods. (#2948)
- Added `NetworkRigidBodyBase.GetAngularVelocity` and `NetworkRigidBodyBase.SetAngularVelocity` convenience/helper methods. (#2948)

### Fixed

- Fixed issue when `NetworkTransform` half float precision is enabled and ownership changes the current base position was not being synchronized. (#2948)
- Fixed issue where `OnClientConnected` not being invoked on the session owner when connecting to a new distributed authority session. (#2948)
- Fixed issue where Rigidbody micro-motion (i.e. relatively small velocities) would result in non-authority instances slightly stuttering as the body would come to a rest (i.e. no motion). Now, the threshold value can increase at higher velocities and can decrease slightly below the provided threshold to account for this. (#2948)

### Changed

- Changed `NetworkAnimator` no longer requires the `Animator` component to exist on the same `GameObject`. (#2957)
- Changed `NetworkObjectReference` and `NetworkBehaviourReference` to allow null references when constructing and serializing. (#2957)
- Changed the client's owned objects is now returned (`NetworkClient` and `NetworkSpawnManager`) as an array as opposed to a list for performance purposes. (#2948)
- Changed `NetworkTransfrom.TryCommitTransformToServer` to be internal as it will be removed by the final 2.0.0 release. (#2948)
- Changed `NetworkTransformEditor.OnEnable` to a virtual method to be able to customize a `NetworkTransform` derived class by creating a derived editor control from `NetworkTransformEditor`. (#2948)
2024-06-17 00:00:00 +00:00
90 changed files with 7630 additions and 1191 deletions

View File

@@ -6,10 +6,63 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).
## [2.0.0-pre.1] - 2024-06-17
## [2.0.0-pre.4] - 2024-08-21
### Added
- Added `NetworkVariable.CheckDirtyState` that is to be used in tandem with collections in order to detect whether the collection or an item within the collection has changed. (#3004)
### Fixed
- Fixed issue where nested `NetworkTransform` components were not getting updated. (#3016)
- Fixed issue by adding null checks in `NetworkVariableBase.CanClientRead` and `NetworkVariableBase.CanClientWrite` methods to ensure safe access to `NetworkBehaviour`. (#3012)
- Fixed issue where `FixedStringSerializer<T>` was using `NetworkVariableSerialization<byte>.AreEqual` to determine if two bytes were equal causes an exception to be thrown due to no byte serializer having been defined. (#3009)
- Fixed Issue where a state with dual triggers, inbound and outbound, could cause a false layer to layer state transition message to be sent to non-authority `NetworkAnimator` instances and cause a warning message to be logged. (#3008)
- Fixed issue using collections within `NetworkVariable` where the collection would not detect changes to items or nested items. (#3004)
- Fixed issue where `List`, `Dictionary`, and `HashSet` collections would not uniquely duplicate nested collections. (#3004)
- Fixed issue where `NotAuthorityTarget` would include the service observer in the list of targets to send the RPC to as opposed to excluding the service observer as it should. (#3000)
- Fixed issue where `ProxyRpcTargetGroup` could attempt to send a message if there were no targets to send to. (#3000)
### Changed
- Changed `NetworkAnimator` to automatically switch to owner authoritative mode when using a distributed authority network topology. (#3021)
- Changed permissions exception thrown in `NetworkList` to exiting early with a logged error that is now a unified permissions message within `NetworkVariableBase`. (#3004)
- Changed permissions exception thrown in `NetworkVariable.Value` to exiting early with a logged error that is now a unified permissions message within `NetworkVariableBase`. (#3004)
## [2.0.0-pre.3] - 2024-07-23
### Added
- Added: `UnityTransport.GetNetworkDriver` and `UnityTransport.GetLocalEndpoint` methods to expose the driver and local endpoint being used. (#2978)
### Fixed
- Fixed issue where deferred despawn was causing GC allocations when converting an `IEnumerable` to a list. (#2983)
- Fixed issue where the realtime network stats monitor was not able to display RPC traffic in release builds due to those stats being only available in development builds or the editor. (#2979)
- Fixed issue where `NetworkManager.ScenesLoaded` was not being updated if `PostSynchronizationSceneUnloading` was set and any loaded scenes not used during synchronization were unloaded. (#2971)
- Fixed issue where `Rigidbody2d` under Unity 6000.0.11f1 has breaking changes where `velocity` is now `linearVelocity` and `isKinematic` is replaced by `bodyType`. (#2971)
- Fixed issue where `NetworkSpawnManager.InstantiateAndSpawn` and `NetworkObject.InstantiateAndSpawn` were not honoring the ownerClientId parameter when using a client-server network topology. (#2968)
- Fixed issue where internal delta serialization could not have a byte serializer defined when serializing deltas for other types. Added `[GenerateSerializationForType(typeof(byte))]` to both the `NetworkVariable` and `AnticipatedNetworkVariable` classes to assure a byte serializer is defined.(#2962)
- Fixed issue when scene management was disabled and the session owner would still try to synchronize a late joining client. (#2962)
- Fixed issue when using a distributed authority network topology where it would allow a session owner to spawn a `NetworkObject` prior to being approved. Now, an error message is logged and the `NetworkObject` will not be spawned prior to the client being approved. (#2962)
- Fixed issue where attempting to spawn during `NetworkBehaviour.OnInSceneObjectsSpawned` and `NetworkBehaviour.OnNetworkSessionSynchronized` notifications would throw a collection modified exception. (#2962)
### Changed
- Changed logic where clients can now set the `NetworkSceneManager` client synchronization mode when using a distributed authority network topology. (#2985)
## [2.0.0-pre.2] - 2024-06-17
### Added
- Added `AnticipatedNetworkVariable<T>`, which adds support for client anticipation of `NetworkVariable` values, allowing for more responsive gameplay. (#2957)
- Added `AnticipatedNetworkTransform`, which adds support for client anticipation of NetworkTransforms. (#2957)
- Added `NetworkVariableBase.ExceedsDirtinessThreshold` to allow network variables to throttle updates by only sending updates when the difference between the current and previous values exceeds a threshold. (This is exposed in `NetworkVariable<T>` with the callback `NetworkVariable<T>.CheckExceedsDirtinessThreshold`). (#2957)
- Added `NetworkVariableUpdateTraits`, which add additional throttling support: `MinSecondsBetweenUpdates` will prevent the `NetworkVariable` from sending updates more often than the specified time period (even if it exceeds the dirtiness threshold), while `MaxSecondsBetweenUpdates` will force a dirty `NetworkVariable` to send an update after the specified time period even if it has not yet exceeded the dirtiness threshold. (#2957)
- Added virtual method `NetworkVariableBase.OnInitialize` which can be used by `NetworkVariable` subclasses to add initialization code. (#2957)
- Added `NetworkTime.TickWithPartial`, which represents the current tick as a double that includes the fractional/partial tick value. (#2957)
- Added `NetworkTickSystem.AnticipationTick`, which can be helpful with implementation of client anticipation. This value represents the tick the current local client was at at the beginning of the most recent network round trip, which enables it to correlate server update ticks with the client tick that may have triggered them. (#2957)
- Added event `NetworkManager.OnSessionOwnerPromoted` that is invoked when a new session owner promotion occurs. (#2948)
- Added `NetworkRigidBodyBase.GetLinearVelocity` and `NetworkRigidBodyBase.SetLinearVelocity` convenience/helper methods. (#2948)
- Added `NetworkRigidBodyBase.GetAngularVelocity` and `NetworkRigidBodyBase.SetAngularVelocity` convenience/helper methods. (#2948)
@@ -22,6 +75,8 @@ Additional documentation and release notes are available at [Multiplayer Documen
### Changed
- Changed `NetworkAnimator` no longer requires the `Animator` component to exist on the same `GameObject`. (#2957)
- Changed `NetworkObjectReference` and `NetworkBehaviourReference` to allow null references when constructing and serializing. (#2957)
- Changed the client's owned objects is now returned (`NetworkClient` and `NetworkSpawnManager`) as an array as opposed to a list for performance purposes. (#2948)
- Changed `NetworkTransfrom.TryCommitTransformToServer` to be internal as it will be removed by the final 2.0.0 release. (#2948)
- Changed `NetworkTransformEditor.OnEnable` to a virtual method to be able to customize a `NetworkTransform` derived class by creating a derived editor control from `NetworkTransformEditor`. (#2948)

View File

@@ -409,6 +409,7 @@ namespace Unity.Netcode.Editor.CodeGen
}
else
{
m_Diagnostics.AddError($"{type}: Managed type in NetworkVariable must implement IEquatable<{type}>");
equalityMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef);
}

View File

@@ -66,6 +66,7 @@ namespace Unity.Netcode.Editor
/// <inheritdoc/>
public override void OnInspectorGUI()
{
var networkTransform = target as NetworkTransform;
EditorGUILayout.LabelField("Axis to Synchronize", EditorStyles.boldLabel);
{
GUILayout.BeginHorizontal();
@@ -144,7 +145,10 @@ namespace Unity.Netcode.Editor
EditorGUILayout.Space();
EditorGUILayout.LabelField("Configurations", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_InLocalSpaceProperty);
if (!networkTransform.HideInterpolateValue)
{
EditorGUILayout.PropertyField(m_InterpolateProperty);
}
EditorGUILayout.PropertyField(m_SlerpPosition);
EditorGUILayout.PropertyField(m_UseQuaternionSynchronization);
if (m_UseQuaternionSynchronization.boolValue)

View File

@@ -0,0 +1,501 @@
using Unity.Mathematics;
using UnityEngine;
namespace Unity.Netcode.Components
{
#pragma warning disable IDE0001
/// <summary>
/// A subclass of <see cref="NetworkTransform"/> that supports basic client anticipation - the client
/// can set a value on the belief that the server will update it to reflect the same value in a future update
/// (i.e., as the result of an RPC call). This value can then be adjusted as new updates from the server come in,
/// in three basic modes:
///
/// <list type="bullet">
///
/// <item><b>Snap:</b> In this mode (with <see cref="StaleDataHandling"/> set to
/// <see cref="StaleDataHandling.Ignore"/> and no <see cref="NetworkBehaviour.OnReanticipate"/> callback),
/// the moment a more up-to-date value is received from the authority, it will simply replace the anticipated value,
/// resulting in a "snap" to the new value if it is different from the anticipated value.</item>
///
/// <item><b>Smooth:</b> In this mode (with <see cref="StaleDataHandling"/> set to
/// <see cref="Netcode.StaleDataHandling.Ignore"/> and an <see cref="NetworkBehaviour.OnReanticipate"/> callback that calls
/// <see cref="Smooth"/> from the anticipated value to the authority value with an appropriate
/// <see cref="Mathf.Lerp"/>-style smooth function), when a more up-to-date value is received from the authority,
/// it will interpolate over time from an incorrect anticipated value to the correct authoritative value.</item>
///
/// <item><b>Constant Reanticipation:</b> In this mode (with <see cref="StaleDataHandling"/> set to
/// <see cref="Netcode.StaleDataHandling.Reanticipate"/> and an <see cref="NetworkBehaviour.OnReanticipate"/> that calculates a
/// new anticipated value based on the current authoritative value), when a more up-to-date value is received from
/// the authority, user code calculates a new anticipated value, possibly calling <see cref="Smooth"/> to interpolate
/// between the previous anticipation and the new anticipation. This is useful for values that change frequently and
/// need to constantly be re-evaluated, as opposed to values that change only in response to user action and simply
/// need a one-time anticipation when the user performs that action.</item>
///
/// </list>
///
/// Note that these three modes may be combined. For example, if an <see cref="NetworkBehaviour.OnReanticipate"/> callback
/// does not call either <see cref="Smooth"/> or one of the Anticipate methods, the result will be a snap to the
/// authoritative value, enabling for a callback that may conditionally call <see cref="Smooth"/> when the
/// difference between the anticipated and authoritative values is within some threshold, but fall back to
/// snap behavior if the difference is too large.
/// </summary>
#pragma warning restore IDE0001
[DisallowMultipleComponent]
[AddComponentMenu("Netcode/Anticipated Network Transform")]
public class AnticipatedNetworkTransform : NetworkTransform
{
#if UNITY_EDITOR
internal override bool HideInterpolateValue => true;
#endif
public struct TransformState
{
public Vector3 Position;
public Quaternion Rotation;
public Vector3 Scale;
}
private TransformState m_AuthoritativeTransform = new TransformState();
private TransformState m_AnticipatedTransform = new TransformState();
private TransformState m_PreviousAnticipatedTransform = new TransformState();
private ulong m_LastAnticipaionCounter;
private ulong m_LastAuthorityUpdateCounter;
private TransformState m_SmoothFrom;
private TransformState m_SmoothTo;
private float m_SmoothDuration;
private float m_CurrentSmoothTime;
private bool m_OutstandingAuthorityChange = false;
#if UNITY_EDITOR
private void Reset()
{
// Anticipation + smoothing is a form of interpolation, and adding NetworkTransform's buffered interpolation
// makes the anticipation get weird, so we default it to false.
Interpolate = false;
}
#endif
#pragma warning disable IDE0001
/// <summary>
/// Defines what the behavior should be if we receive a value from the server with an earlier associated
/// time value than the anticipation time value.
/// <br/><br/>
/// If this is <see cref="Netcode.StaleDataHandling.Ignore"/>, the stale data will be ignored and the authoritative
/// value will not replace the anticipated value until the anticipation time is reached. <see cref="OnAuthoritativeValueChanged"/>
/// and <see cref="OnReanticipate"/> will also not be invoked for this stale data.
/// <br/><br/>
/// If this is <see cref="Netcode.StaleDataHandling.Reanticipate"/>, the stale data will replace the anticipated data and
/// <see cref="OnAuthoritativeValueChanged"/> and <see cref="OnReanticipate"/> will be invoked.
/// In this case, the authoritativeTime value passed to <see cref="OnReanticipate"/> will be lower than
/// the anticipationTime value, and that callback can be used to calculate a new anticipated value.
/// </summary>
#pragma warning restore IDE0001
public StaleDataHandling StaleDataHandling = StaleDataHandling.Reanticipate;
/// <summary>
/// Contains the current state of this transform on the server side.
/// Note that, on the server side, this gets updated at the end of the frame, and will not immediately reflect
/// changes to the transform.
/// </summary>
public TransformState AuthoritativeState => m_AuthoritativeTransform;
/// <summary>
/// Contains the current anticipated state, which will match the values of this object's
/// actual <see cref="MonoBehaviour.transform"/>. When a server
/// update arrives, this value will be overwritten by the new
/// server value (unless stale data handling is set to "Ignore"
/// and the update is determined to be stale). This value will
/// be duplicated in <see cref="PreviousAnticipatedState"/>, which
/// will NOT be overwritten in server updates.
/// </summary>
public TransformState AnticipatedState => m_AnticipatedTransform;
/// <summary>
/// Indicates whether this transform currently needs
/// reanticipation. If this is true, the anticipated value
/// has been overwritten by the authoritative value from the
/// server; the previous anticipated value is stored in <see cref="PreviousAnticipatedState"/>
/// </summary>
public bool ShouldReanticipate
{
get;
private set;
}
/// <summary>
/// Holds the most recent anticipated state, whatever was
/// most recently set using the Anticipate methods. Unlike
/// <see cref="AnticipatedState"/>, this does not get overwritten
/// when a server update arrives.
/// </summary>
public TransformState PreviousAnticipatedState => m_PreviousAnticipatedTransform;
/// <summary>
/// Anticipate that, at the end of one round trip to the server, this transform will be in the given
/// <see cref="newPosition"/>
/// </summary>
/// <param name="newPosition"></param>
public void AnticipateMove(Vector3 newPosition)
{
if (NetworkManager.ShutdownInProgress || !NetworkManager.IsListening)
{
return;
}
transform.position = newPosition;
m_AnticipatedTransform.Position = newPosition;
if (CanCommitToTransform)
{
m_AuthoritativeTransform.Position = newPosition;
}
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
m_LastAnticipaionCounter = NetworkManager.AnticipationSystem.AnticipationCounter;
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
}
/// <summary>
/// Anticipate that, at the end of one round trip to the server, this transform will have the given
/// <see cref="newRotation"/>
/// </summary>
/// <param name="newRotation"></param>
public void AnticipateRotate(Quaternion newRotation)
{
if (NetworkManager.ShutdownInProgress || !NetworkManager.IsListening)
{
return;
}
transform.rotation = newRotation;
m_AnticipatedTransform.Rotation = newRotation;
if (CanCommitToTransform)
{
m_AuthoritativeTransform.Rotation = newRotation;
}
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
m_LastAnticipaionCounter = NetworkManager.AnticipationSystem.AnticipationCounter;
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
}
/// <summary>
/// Anticipate that, at the end of one round trip to the server, this transform will have the given
/// <see cref="newScale"/>
/// </summary>
/// <param name="newScale"></param>
public void AnticipateScale(Vector3 newScale)
{
if (NetworkManager.ShutdownInProgress || !NetworkManager.IsListening)
{
return;
}
transform.localScale = newScale;
m_AnticipatedTransform.Scale = newScale;
if (CanCommitToTransform)
{
m_AuthoritativeTransform.Scale = newScale;
}
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
m_LastAnticipaionCounter = NetworkManager.AnticipationSystem.AnticipationCounter;
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
}
/// <summary>
/// Anticipate that, at the end of one round trip to the server, the transform will have the given
/// <see cref="newState"/>
/// </summary>
/// <param name="newState"></param>
public void AnticipateState(TransformState newState)
{
if (NetworkManager.ShutdownInProgress || !NetworkManager.IsListening)
{
return;
}
var transform_ = transform;
transform_.position = newState.Position;
transform_.rotation = newState.Rotation;
transform_.localScale = newState.Scale;
m_AnticipatedTransform = newState;
if (CanCommitToTransform)
{
m_AuthoritativeTransform = newState;
}
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
}
public override void OnUpdate()
{
// If not spawned or this instance has authority, exit early
if (!IsSpawned)
{
return;
}
// Do not call the base class implementation...
// AnticipatedNetworkTransform applies its authoritative state immediately rather than waiting for update
// This is because AnticipatedNetworkTransforms may need to reference each other in reanticipating
// and we will want all reanticipation done before anything else wants to reference the transform in
// OnUpdate()
//base.Update();
if (m_CurrentSmoothTime < m_SmoothDuration)
{
m_CurrentSmoothTime += NetworkManager.RealTimeProvider.DeltaTime;
var transform_ = transform;
var pct = math.min(m_CurrentSmoothTime / m_SmoothDuration, 1f);
m_AnticipatedTransform = new TransformState
{
Position = Vector3.Lerp(m_SmoothFrom.Position, m_SmoothTo.Position, pct),
Rotation = Quaternion.Slerp(m_SmoothFrom.Rotation, m_SmoothTo.Rotation, pct),
Scale = Vector3.Lerp(m_SmoothFrom.Scale, m_SmoothTo.Scale, pct)
};
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
if (!CanCommitToTransform)
{
transform_.position = m_AnticipatedTransform.Position;
transform_.localScale = m_AnticipatedTransform.Scale;
transform_.rotation = m_AnticipatedTransform.Rotation;
}
}
}
internal class AnticipatedObject : IAnticipationEventReceiver, IAnticipatedObject
{
public AnticipatedNetworkTransform Transform;
public void SetupForRender()
{
if (Transform.CanCommitToTransform)
{
var transform_ = Transform.transform;
Transform.m_AuthoritativeTransform = new TransformState
{
Position = transform_.position,
Rotation = transform_.rotation,
Scale = transform_.localScale
};
if (Transform.m_CurrentSmoothTime >= Transform.m_SmoothDuration)
{
// If we've had a call to Smooth() we'll continue interpolating.
// Otherwise we'll go ahead and make the visual and actual locations
// match.
Transform.m_AnticipatedTransform = Transform.m_AuthoritativeTransform;
}
transform_.position = Transform.m_AnticipatedTransform.Position;
transform_.rotation = Transform.m_AnticipatedTransform.Rotation;
transform_.localScale = Transform.m_AnticipatedTransform.Scale;
}
}
public void SetupForUpdate()
{
if (Transform.CanCommitToTransform)
{
var transform_ = Transform.transform;
transform_.position = Transform.m_AuthoritativeTransform.Position;
transform_.rotation = Transform.m_AuthoritativeTransform.Rotation;
transform_.localScale = Transform.m_AuthoritativeTransform.Scale;
}
}
public void Update()
{
// No need to do this, it's handled by NetworkTransform.OnUpdate
}
public void ResetAnticipation()
{
Transform.ShouldReanticipate = false;
}
public NetworkObject OwnerObject => Transform.NetworkObject;
}
private AnticipatedObject m_AnticipatedObject = null;
private void ResetAnticipatedState()
{
var transform_ = transform;
m_AuthoritativeTransform = new TransformState
{
Position = transform_.position,
Rotation = transform_.rotation,
Scale = transform_.localScale
};
m_AnticipatedTransform = m_AuthoritativeTransform;
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
}
protected override void OnSynchronize<T>(ref BufferSerializer<T> serializer)
{
base.OnSynchronize(ref serializer);
if (!CanCommitToTransform)
{
m_OutstandingAuthorityChange = true;
ApplyAuthoritativeState();
ResetAnticipatedState();
}
}
public override void OnNetworkSpawn()
{
if (NetworkManager.DistributedAuthorityMode)
{
Debug.LogWarning($"This component is not currently supported in distributed authority.");
}
base.OnNetworkSpawn();
m_OutstandingAuthorityChange = true;
ApplyAuthoritativeState();
ResetAnticipatedState();
m_AnticipatedObject = new AnticipatedObject { Transform = this };
NetworkManager.AnticipationSystem.RegisterForAnticipationEvents(m_AnticipatedObject);
NetworkManager.AnticipationSystem.AllAnticipatedObjects.Add(m_AnticipatedObject);
}
public override void OnNetworkDespawn()
{
if (m_AnticipatedObject != null)
{
NetworkManager.AnticipationSystem.DeregisterForAnticipationEvents(m_AnticipatedObject);
NetworkManager.AnticipationSystem.AllAnticipatedObjects.Remove(m_AnticipatedObject);
NetworkManager.AnticipationSystem.ObjectsToReanticipate.Remove(m_AnticipatedObject);
m_AnticipatedObject = null;
}
ResetAnticipatedState();
base.OnNetworkDespawn();
}
public override void OnDestroy()
{
if (m_AnticipatedObject != null)
{
NetworkManager.AnticipationSystem.DeregisterForAnticipationEvents(m_AnticipatedObject);
NetworkManager.AnticipationSystem.AllAnticipatedObjects.Remove(m_AnticipatedObject);
NetworkManager.AnticipationSystem.ObjectsToReanticipate.Remove(m_AnticipatedObject);
m_AnticipatedObject = null;
}
base.OnDestroy();
}
/// <summary>
/// Interpolate between the transform represented by <see cref="from"/> to the transform represented by
/// <see cref="to"/> over <see cref="durationSeconds"/> of real time. The duration uses
/// <see cref="Time.deltaTime"/>, so it is affected by <see cref="Time.timeScale"/>.
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
/// <param name="durationSeconds"></param>
public void Smooth(TransformState from, TransformState to, float durationSeconds)
{
var transform_ = transform;
if (durationSeconds <= 0)
{
m_AnticipatedTransform = to;
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
transform_.position = to.Position;
transform_.rotation = to.Rotation;
transform_.localScale = to.Scale;
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
return;
}
m_AnticipatedTransform = from;
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
if (!CanCommitToTransform)
{
transform_.position = from.Position;
transform_.rotation = from.Rotation;
transform_.localScale = from.Scale;
}
m_SmoothFrom = from;
m_SmoothTo = to;
m_SmoothDuration = durationSeconds;
m_CurrentSmoothTime = 0;
}
protected override void OnBeforeUpdateTransformState()
{
// this is called when new data comes from the server
m_LastAuthorityUpdateCounter = NetworkManager.AnticipationSystem.LastAnticipationAck;
m_OutstandingAuthorityChange = true;
}
protected override void OnNetworkTransformStateUpdated(ref NetworkTransformState oldState, ref NetworkTransformState newState)
{
base.OnNetworkTransformStateUpdated(ref oldState, ref newState);
ApplyAuthoritativeState();
}
protected override void OnTransformUpdated()
{
if (CanCommitToTransform || m_AnticipatedObject == null)
{
return;
}
// this is called pretty much every frame and will change the transform
// If we've overridden the transform with an anticipated state, we need to be able to change it back
// to the anticipated state (while updating the authority state accordingly) or else
// mark this transform for reanticipation
var transform_ = transform;
var previousAnticipatedTransform = m_AnticipatedTransform;
// Update authority state to catch any possible interpolation data
m_AuthoritativeTransform.Position = transform_.position;
m_AuthoritativeTransform.Rotation = transform_.rotation;
m_AuthoritativeTransform.Scale = transform_.localScale;
if (!m_OutstandingAuthorityChange)
{
// Keep the anticipated value unchanged, we have no updates from the server at all.
transform_.position = previousAnticipatedTransform.Position;
transform_.localScale = previousAnticipatedTransform.Scale;
transform_.rotation = previousAnticipatedTransform.Rotation;
return;
}
if (StaleDataHandling == StaleDataHandling.Ignore && m_LastAnticipaionCounter > m_LastAuthorityUpdateCounter)
{
// Keep the anticipated value unchanged because it is more recent than the authoritative one.
transform_.position = previousAnticipatedTransform.Position;
transform_.localScale = previousAnticipatedTransform.Scale;
transform_.rotation = previousAnticipatedTransform.Rotation;
return;
}
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
m_OutstandingAuthorityChange = false;
m_AnticipatedTransform = m_AuthoritativeTransform;
ShouldReanticipate = true;
NetworkManager.AnticipationSystem.ObjectsToReanticipate.Add(m_AnticipatedObject);
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5abfce83aadd948498d4990c645a017b

View File

@@ -8,7 +8,7 @@ namespace Unity.Netcode.Components
/// Half float precision <see cref="Vector3"/>.
/// </summary>
/// <remarks>
/// The Vector3T<ushort> values are half float values returned by <see cref="Mathf.FloatToHalf(float)"/> for each
/// The Vector3T&lt;ushort&gt; values are half float values returned by <see cref="Mathf.FloatToHalf(float)"/> for each
/// individual axis and the 16 bits of the half float are stored as <see cref="ushort"/> values since C# does not have
/// a half float type.
/// </remarks>

View File

@@ -8,7 +8,7 @@ namespace Unity.Netcode.Components
/// Half Precision <see cref="Vector4"/> that can also be used to convert a <see cref="Quaternion"/> to half precision.
/// </summary>
/// <remarks>
/// The Vector4T<ushort> values are half float values returned by <see cref="Mathf.FloatToHalf(float)"/> for each
/// The Vector4T&lt;ushort&gt; values are half float values returned by <see cref="Mathf.FloatToHalf(float)"/> for each
/// individual axis and the 16 bits of the half float are stored as <see cref="ushort"/> values since C# does not have
/// a half float type.
/// </remarks>

View File

@@ -5,7 +5,7 @@ using UnityEngine;
namespace Unity.Netcode
{
/// <summary>
/// Solves for incoming values that are jittered
/// Solves for incoming values that are jittered.
/// Partially solves for message loss. Unclamped lerping helps hide this, but not completely
/// </summary>
/// <typeparam name="T">The type of interpolated value</typeparam>

View File

@@ -186,7 +186,6 @@ namespace Unity.Netcode.Components
/// NetworkAnimator enables remote synchronization of <see cref="UnityEngine.Animator"/> state for on network objects.
/// </summary>
[AddComponentMenu("Netcode/Network Animator")]
[RequireComponent(typeof(Animator))]
public class NetworkAnimator : NetworkBehaviour, ISerializationCallbackReceiver
{
[Serializable]
@@ -499,9 +498,13 @@ namespace Unity.Netcode.Components
/// <summary>
/// Override this method and return false to switch to owner authoritative mode
/// </summary>
/// <remarks>
/// When using a distributed authority network topology, this will default to
/// owner authoritative.
/// </remarks>
protected virtual bool OnIsServerAuthoritative()
{
return true;
return NetworkManager ? !NetworkManager.DistributedAuthorityMode : true;
}
// Animators only support up to 32 parameters
@@ -852,7 +855,12 @@ namespace Unity.Netcode.Components
stateChangeDetected = true;
//Debug.Log($"[Cross-Fade] To-Hash: {nt.fullPathHash} | TI-Duration: ({tt.duration}) | TI-Norm: ({tt.normalizedTime}) | From-Hash: ({m_AnimationHash[layer]}) | SI-FPHash: ({st.fullPathHash}) | SI-Norm: ({st.normalizedTime})");
}
else if (!tt.anyState && tt.fullPathHash != m_TransitionHash[layer])
// If we are not transitioned into the "any state" and the animator transition isn't a full path hash (layer to layer) and our pre-built destination state to transition does not contain the
// current layer (i.e. transitioning into a state from another layer) =or= we do contain the layer and the layer contains state to transition to is contained within our pre-built destination
// state then we can handle this transition as a non-cross fade state transition between layers.
// Otherwise, if we don't enter into this then this is a "trigger transition to some state that is now being transitioned back to the Idle state via trigger" or "Dual Triggers" IDLE<-->State.
else if (!tt.anyState && tt.fullPathHash != m_TransitionHash[layer] && (!m_DestinationStateToTransitioninfo.ContainsKey(layer) ||
(m_DestinationStateToTransitioninfo.ContainsKey(layer) && m_DestinationStateToTransitioninfo[layer].ContainsKey(nt.fullPathHash))))
{
// first time in this transition for this layer
m_TransitionHash[layer] = tt.fullPathHash;
@@ -861,6 +869,10 @@ namespace Unity.Netcode.Components
animState.CrossFade = false;
animState.Transition = true;
animState.NormalizedTime = tt.normalizedTime;
if (m_DestinationStateToTransitioninfo.ContainsKey(layer) && m_DestinationStateToTransitioninfo[layer].ContainsKey(nt.fullPathHash))
{
animState.DestinationStateHash = nt.fullPathHash;
}
stateChangeDetected = true;
//Debug.Log($"[Transition] TI-Duration: ({tt.duration}) | TI-Norm: ({tt.normalizedTime}) | From-Hash: ({m_AnimationHash[layer]}) |SI-FPHash: ({st.fullPathHash}) | SI-Norm: ({st.normalizedTime})");
}

View File

@@ -177,7 +177,11 @@ namespace Unity.Netcode.Components
{
if (m_IsRigidbody2D)
{
#if COM_UNITY_MODULES_PHYSICS2D_LINEAR
m_Rigidbody2D.linearVelocity = linearVelocity;
#else
m_Rigidbody2D.velocity = linearVelocity;
#endif
}
else
{
@@ -197,7 +201,11 @@ namespace Unity.Netcode.Components
{
if (m_IsRigidbody2D)
{
#if COM_UNITY_MODULES_PHYSICS2D_LINEAR
return m_Rigidbody2D.linearVelocity;
#else
return m_Rigidbody2D.velocity;
#endif
}
else
{
@@ -238,7 +246,7 @@ namespace Unity.Netcode.Components
{
if (m_IsRigidbody2D)
{
return Vector3.forward * m_Rigidbody2D.velocity;
return Vector3.forward * m_Rigidbody2D.angularVelocity;
}
else
{
@@ -481,7 +489,7 @@ namespace Unity.Netcode.Components
{
if (m_IsRigidbody2D)
{
return m_Rigidbody2D.isKinematic;
return m_Rigidbody2D.bodyType == RigidbodyType2D.Kinematic;
}
else
{
@@ -510,7 +518,7 @@ namespace Unity.Netcode.Components
{
if (m_IsRigidbody2D)
{
m_Rigidbody2D.isKinematic = isKinematic;
m_Rigidbody2D.bodyType = isKinematic ? RigidbodyType2D.Kinematic : RigidbodyType2D.Dynamic;
}
else
{
@@ -715,7 +723,11 @@ namespace Unity.Netcode.Components
if (zeroVelocity)
{
#if COM_UNITY_MODULES_PHYSICS2D_LINEAR
m_Rigidbody2D.linearVelocity = Vector2.zero;
#else
m_Rigidbody2D.velocity = Vector2.zero;
#endif
m_Rigidbody2D.angularVelocity = 0.0f;
}

View File

@@ -17,6 +17,11 @@ namespace Unity.Netcode.Components
[AddComponentMenu("Netcode/Network Transform")]
public class NetworkTransform : NetworkBehaviour
{
#if UNITY_EDITOR
internal virtual bool HideInterpolateValue => false;
#endif
#region NETWORK TRANSFORM STATE
/// <summary>
/// Data structure used to synchronize the <see cref="NetworkTransform"/>
@@ -2184,10 +2189,15 @@ namespace Unity.Netcode.Components
internal bool LogMotion;
protected virtual void OnTransformUpdated()
{
}
/// <summary>
/// Applies the authoritative state to the transform
/// </summary>
private void ApplyAuthoritativeState()
protected internal void ApplyAuthoritativeState()
{
#if COM_UNITY_MODULES_PHYSICS
// TODO: Make this an authority flag
@@ -2391,6 +2401,7 @@ namespace Unity.Netcode.Components
}
transform.localScale = m_CurrentScale;
}
OnTransformUpdated();
}
/// <summary>
@@ -2602,6 +2613,8 @@ namespace Unity.Netcode.Components
{
AddLogEntry(ref newState, NetworkObject.OwnerClientId);
}
OnTransformUpdated();
}
/// <summary>
@@ -2769,6 +2782,11 @@ namespace Unity.Netcode.Components
}
protected virtual void OnBeforeUpdateTransformState()
{
}
internal bool LogStateUpdate;
/// <summary>
/// Only non-authoritative instances should invoke this method
@@ -2809,6 +2827,10 @@ namespace Unity.Netcode.Components
}
Debug.Log(builder);
}
// Notification prior to applying a state update
OnBeforeUpdateTransformState();
// Apply the new state
ApplyUpdatedState(newState);
@@ -2938,7 +2960,10 @@ namespace Unity.Netcode.Components
#else
var forUpdate = true;
#endif
NetworkManager?.NetworkTransformRegistration(this, forUpdate, false);
if (m_CachedNetworkObject != null)
{
NetworkManager?.NetworkTransformRegistration(m_CachedNetworkObject, forUpdate, false);
}
DeregisterForTickUpdate(this);
CanCommitToTransform = false;
}
@@ -3047,7 +3072,7 @@ namespace Unity.Netcode.Components
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);
m_CachedNetworkManager.NetworkTransformRegistration(NetworkObject, forUpdate, false);
if (UseHalfFloatPrecision)
{
m_HalfPositionState = new NetworkDeltaPosition(currentPosition, m_CachedNetworkManager.ServerTime.Tick, math.bool3(SyncPositionX, SyncPositionY, SyncPositionZ));
@@ -3068,7 +3093,7 @@ namespace Unity.Netcode.Components
else
{
// Non-authority needs to be added to updates for interpolation and applying state purposes
m_CachedNetworkManager.NetworkTransformRegistration(this, forUpdate, true);
m_CachedNetworkManager.NetworkTransformRegistration(NetworkObject, forUpdate, true);
// Remove this instance from the tick update
DeregisterForTickUpdate(this);
ResetInterpolatedStateToCurrentAuthoritativeState();
@@ -3513,7 +3538,7 @@ namespace Unity.Netcode.Components
/// </summary>
private void UpdateTransformState()
{
if (m_CachedNetworkManager.ShutdownInProgress || (m_CachedNetworkManager.DistributedAuthorityMode && m_CachedNetworkObject.Observers.Count - 1 == 0))
if (m_CachedNetworkManager.ShutdownInProgress || (m_CachedNetworkManager.DistributedAuthorityMode && !m_CachedNetworkManager.CMBServiceConnection && m_CachedNetworkObject.Observers.Count - 1 == 0))
{
return;
}

View File

@@ -159,9 +159,21 @@ namespace Unity.Netcode
public bool AutoSpawnPlayerPrefabClientSide = true;
#if MULTIPLAYER_TOOLS
/// <summary>
/// Controls whether network messaging metrics will be gathered. (defaults to true)
/// There is a slight performance cost to having this enabled, and can increase in processing time based on network message traffic.
/// </summary>
/// <remarks>
/// The Realtime Network Stats Monitoring tool requires this to be enabled.
/// </remarks>
[Tooltip("Enable (default) if you want to gather messaging metrics. Realtime Network Stats Monitor requires this to be enabled. Disabling this can improve performance in release builds.")]
public bool NetworkMessageMetrics = true;
#endif
/// <summary>
/// When enabled (default, this enables network profiling information. This does come with a per message processing cost.
/// Network profiling information is automatically disabled in release builds.
/// </summary>
[Tooltip("Enable (default) if you want to profile network messages with development builds and defaults to being disabled in release builds. When disabled, network messaging profiling will be disabled in development builds.")]
public bool NetworkProfilingMetrics = true;
/// <summary>

View File

@@ -15,7 +15,7 @@ namespace Unity.Netcode
}
/// <summary>
/// The base class to override to write network code. Inherits MonoBehaviour
/// The base class to override to write network code. Inherits MonoBehaviour.
/// </summary>
public abstract class NetworkBehaviour : MonoBehaviour
{
@@ -27,7 +27,7 @@ namespace Unity.Netcode
// RuntimeAccessModifiersILPP will make this `public`
internal static readonly Dictionary<Type, Dictionary<uint, RpcReceiveHandler>> __rpc_func_table = new Dictionary<Type, Dictionary<uint, RpcReceiveHandler>>();
#if DEVELOPMENT_BUILD || UNITY_EDITOR
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
// RuntimeAccessModifiersILPP will make this `public`
internal static readonly Dictionary<Type, Dictionary<uint, string>> __rpc_name_table = new Dictionary<Type, Dictionary<uint, string>>();
#endif
@@ -124,7 +124,7 @@ namespace Unity.Netcode
}
bufferWriter.Dispose();
#if DEVELOPMENT_BUILD || UNITY_EDITOR
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
if (__rpc_name_table[GetType()].TryGetValue(rpcMethodId, out var rpcMethodName))
{
NetworkManager.NetworkMetrics.TrackRpcSent(
@@ -252,7 +252,7 @@ namespace Unity.Netcode
}
bufferWriter.Dispose();
#if DEVELOPMENT_BUILD || UNITY_EDITOR
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
if (__rpc_name_table[GetType()].TryGetValue(rpcMethodId, out var rpcMethodName))
{
if (clientRpcParams.Send.TargetClientIds != null)
@@ -410,8 +410,8 @@ namespace Unity.Netcode
}
/// <summary>
/// Gets the NetworkManager that owns this NetworkBehaviour instance
/// See note around `NetworkObject` for how there is a chicken / egg problem when we are not initialized
/// Gets the NetworkManager that owns this NetworkBehaviour instance.
/// See `NetworkObject` note for how there is a chicken/egg problem when not initialized.
/// </summary>
public NetworkManager NetworkManager
{
@@ -439,38 +439,40 @@ namespace Unity.Netcode
/// <see cref="Unity.Netcode.RpcTarget.Not(NativeArray{ulong})"/>,
/// <see cref="Unity.Netcode.RpcTarget.Not(NativeList{ulong})"/>,
/// <see cref="Unity.Netcode.RpcTarget.Not(ulong[])"/>, and
/// <see cref="Unity.Netcode.RpcTarget.Not{T}(T)"/>
/// <see cref="Unity.Netcode.RpcTarget.Not{T}(T)"/>.
/// </summary>
#pragma warning restore IDE0001
public RpcTarget RpcTarget => NetworkManager.RpcTarget;
/// <summary>
/// If a NetworkObject is assigned, it will return whether or not this NetworkObject
/// is the local player object. If no NetworkObject is assigned it will always return false.
/// If a NetworkObject is assigned, returns whether the NetworkObject
/// is the local player object. If no NetworkObject is assigned, returns false.
/// </summary>
public bool IsLocalPlayer { get; private set; }
/// <summary>
/// Gets if the object is owned by the local player or if the object is the local player object
/// Gets whether the object is owned by the local player or if the object is the local player object.
/// </summary>
public bool IsOwner { get; internal set; }
/// <summary>
/// Gets if we are executing as server
/// Gets whether executing as a server.
/// </summary>
public bool IsServer { get; private set; }
/// <summary>
/// Determines if the local client has authority over the associated NetworkObject
/// Client-Server: This will return true if IsServer or IsHost
/// Distributed Authority: This will return true if IsOwner
/// Determines if the local client has authority over the associated NetworkObject.
/// <list type="bullet">
/// <item>In client-server contexts: returns true if `IsServer` or `IsHost`.</item>
/// <item>In distributed authority contexts: returns true if `IsOwner`.</item>
/// </list>
/// </summary>
public bool HasAuthority { get; internal set; }
internal NetworkClient LocalClient { get; private set; }
/// <summary>
/// Gets if the client is the distributed authority mode session owner
/// Gets whether the client is the distributed authority mode session owner.
/// </summary>
public bool IsSessionOwner
{
@@ -486,29 +488,29 @@ namespace Unity.Netcode
}
/// <summary>
/// Gets if the server (local or remote) is a host - i.e., also a client
/// Gets whether the server (local or remote) is a host.
/// </summary>
public bool ServerIsHost { get; private set; }
/// <summary>
/// Gets if we are executing as client
/// Gets whether executing as a client.
/// </summary>
public bool IsClient { get; private set; }
/// <summary>
/// Gets if we are executing as Host, I.E Server and Client
/// Gets whether executing as a host (both server and client).
/// </summary>
public bool IsHost { get; private set; }
/// <summary>
/// Gets Whether or not the object has a owner
/// Gets whether the object has an owner.
/// </summary>
public bool IsOwnedByServer { get; internal set; }
/// <summary>
/// Used to determine if it is safe to access NetworkObject and NetworkManager from within a NetworkBehaviour component
/// Primarily useful when checking NetworkObject/NetworkManager properties within FixedUpate
/// Determines whether it's safe to access a NetworkObject and NetworkManager from within a NetworkBehaviour component.
/// Primarily useful when checking NetworkObject or NetworkManager properties within FixedUpate.
/// </summary>
public bool IsSpawned { get; internal set; }
@@ -528,7 +530,7 @@ namespace Unity.Netcode
/// the warning below. This is why IsBehaviourEditable had to be created. Matt was going to re-do
/// how NetworkObject works but it was close to the release and too risky to change
/// <summary>
/// Gets the NetworkObject that owns this NetworkBehaviour instance
/// Gets the NetworkObject that owns this NetworkBehaviour instance.
/// </summary>
public NetworkObject NetworkObject
{
@@ -567,19 +569,19 @@ namespace Unity.Netcode
}
/// <summary>
/// Gets whether or not this NetworkBehaviour instance has a NetworkObject owner.
/// Gets whether this NetworkBehaviour instance has a NetworkObject owner.
/// </summary>
public bool HasNetworkObject => NetworkObject != null;
private NetworkObject m_NetworkObject = null;
/// <summary>
/// Gets the NetworkId of the NetworkObject that owns this NetworkBehaviour
/// Gets the NetworkId of the NetworkObject that owns this NetworkBehaviour instance.
/// </summary>
public ulong NetworkObjectId { get; internal set; }
/// <summary>
/// Gets NetworkId for this NetworkBehaviour from the owner NetworkObject
/// Gets NetworkId for this NetworkBehaviour from the owner NetworkObject.
/// </summary>
public ushort NetworkBehaviourId { get; internal set; }
@@ -589,7 +591,7 @@ namespace Unity.Netcode
internal ushort NetworkBehaviourIdCache = 0;
/// <summary>
/// Returns a the NetworkBehaviour with a given BehaviourId for the current NetworkObject
/// Returns the NetworkBehaviour with a given BehaviourId for the current NetworkObject.
/// </summary>
/// <param name="behaviourId">The behaviourId to return</param>
/// <returns>Returns NetworkBehaviour with given behaviourId</returns>
@@ -599,7 +601,7 @@ namespace Unity.Netcode
}
/// <summary>
/// Gets the ClientId that owns the NetworkObject
/// Gets the ClientId that owns this NetworkObject.
/// </summary>
public ulong OwnerClientId { get; internal set; }
@@ -651,28 +653,29 @@ namespace Unity.Netcode
}
/// <summary>
/// Distributed Authority Mode Only
/// Only for use in distributed authority mode.
/// Invoked only on the authority instance when a <see cref="NetworkObject"/> is deferring its despawn on non-authoritative instances.
/// </summary>
/// <remarks>
/// See also: <see cref="NetworkObject.DeferDespawn(int, bool)"/>
/// </remarks>
/// <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) { }
/// <summary>
/// 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)
/// A reference to <see cref="NetworkManager"/> is passed in as a parameter to determine the context of execution (`IsServer` or `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>
/// <remarks>
/// 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.
/// Settings like ownership, NetworkBehaviourId, NetworkManager, and most other spawn-related properties will not be set.
/// This can be used to handle things like initializing a NetworkVariable.
/// </remarks>
protected virtual void OnNetworkPreSpawn(ref NetworkManager networkManager) { }
/// <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 set up.
/// </summary>
public virtual void OnNetworkSpawn() { }
@@ -686,28 +689,28 @@ namespace Unity.Netcode
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
/// This method is only available client-side.
/// When a new client joins it's 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 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.
/// When a scene is loaded and in-scene placed NetworkObjects are finished spawning, this method is invoked on all of the newly spawned in-scene placed NetworkObjects.
/// This method runs both client and server side.
/// </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.
/// This method 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>
/// 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. This method runs both client and server side.
/// </summary>
public virtual void OnNetworkDespawn() { }
@@ -803,7 +806,8 @@ namespace Unity.Netcode
}
/// <summary>
/// Gets called when the local client gains ownership of this object
/// In client-server contexts, this method is invoked on both the server and the local client of the owner when <see cref="Netcode.NetworkObject"/> ownership is assigned.
/// <para>In distributed authority contexts, this method is only invoked on the local client that has been assigned ownership of the associated <see cref="Netcode.NetworkObject"/>.</para>
/// </summary>
public virtual void OnGainedOwnership() { }
@@ -814,8 +818,8 @@ namespace Unity.Netcode
}
/// <summary>
/// Invoked on all clients, override this method to be notified of any
/// ownership changes (even if the instance was niether the previous or
/// Invoked on all clients. Override this method to be notified of any
/// ownership changes (even if the instance was neither the previous or
/// newly assigned current owner).
/// </summary>
/// <param name="previous">the previous owner</param>
@@ -831,7 +835,9 @@ namespace Unity.Netcode
}
/// <summary>
/// Gets called when we loose ownership of this object
/// In client-server contexts, this method is invoked on the local client when it loses ownership of the associated <see cref="Netcode.NetworkObject"/>
/// and on the server when any client loses ownership.
/// <para>In distributed authority contexts, this method is only invoked on the local client that has lost ownership of the associated <see cref="Netcode.NetworkObject"/>.</para>
/// </summary>
public virtual void OnLostOwnership() { }
@@ -842,7 +848,7 @@ namespace Unity.Netcode
}
/// <summary>
/// Gets called when the parent NetworkObject of this NetworkBehaviour's NetworkObject has changed
/// Gets called when the parent NetworkObject of this NetworkBehaviour's NetworkObject has changed.
/// </summary>
/// <param name="parentNetworkObject">the new <see cref="NetworkObject"/> parent</param>
public virtual void OnNetworkObjectParentChanged(NetworkObject parentNetworkObject) { }
@@ -877,7 +883,7 @@ namespace Unity.Netcode
#pragma warning restore IDE1006 // restore naming rule violation check
{
__rpc_func_table[GetType()][hash] = handler;
#if DEVELOPMENT_BUILD || UNITY_EDITOR
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
__rpc_name_table[GetType()][hash] = rpcMethodName;
#endif
}
@@ -903,7 +909,7 @@ namespace Unity.Netcode
if (!__rpc_func_table.ContainsKey(GetType()))
{
__rpc_func_table[GetType()] = new Dictionary<uint, RpcReceiveHandler>();
#if UNITY_EDITOR || DEVELOPMENT_BUILD
#if UNITY_EDITOR || DEVELOPMENT_BUILD || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
__rpc_name_table[GetType()] = new Dictionary<uint, string>();
#endif
__initializeRpcs();
@@ -950,7 +956,16 @@ namespace Unity.Netcode
// during OnNetworkSpawn has been sent and needs to be cleared
for (int i = 0; i < NetworkVariableFields.Count; i++)
{
NetworkVariableFields[i].ResetDirty();
var networkVariable = NetworkVariableFields[i];
if (networkVariable.IsDirty())
{
if (networkVariable.CanSend())
{
networkVariable.UpdateLastSentTime();
networkVariable.ResetDirty();
networkVariable.SetDirty(false);
}
}
}
}
else
@@ -958,7 +973,16 @@ namespace Unity.Netcode
// mark any variables we wrote as no longer dirty
for (int i = 0; i < NetworkVariableIndexesToReset.Count; i++)
{
NetworkVariableFields[NetworkVariableIndexesToReset[i]].ResetDirty();
var networkVariable = NetworkVariableFields[NetworkVariableIndexesToReset[i]];
if (networkVariable.IsDirty())
{
if (networkVariable.CanSend())
{
networkVariable.UpdateLastSentTime();
networkVariable.ResetDirty();
networkVariable.SetDirty(false);
}
}
}
}
@@ -1000,8 +1024,11 @@ namespace Unity.Netcode
{
networkVariable = NetworkVariableFields[k];
if (networkVariable.IsDirty() && networkVariable.CanClientRead(targetClientId))
{
if (networkVariable.CanSend())
{
shouldSend = true;
}
break;
}
}
@@ -1057,10 +1084,17 @@ namespace Unity.Netcode
// TODO: There should be a better way by reading one dirty variable vs. 'n'
for (int i = 0; i < NetworkVariableFields.Count; i++)
{
if (NetworkVariableFields[i].IsDirty())
var networkVariable = NetworkVariableFields[i];
if (networkVariable.IsDirty())
{
if (networkVariable.CanSend())
{
return true;
}
// If it's dirty but can't be sent yet, we have to keep monitoring it until one of the
// conditions blocking its send changes.
NetworkManager.BehaviourUpdater.AddForUpdate(NetworkObject);
}
}
return false;
@@ -1084,31 +1118,38 @@ namespace Unity.Netcode
/// </remarks>
internal void WriteNetworkVariableData(FastBufferWriter writer, ulong targetClientId)
{
// Create any values that require accessing the NetworkManager locally (it is expensive to access it in NetworkBehaviour)
var networkManager = NetworkManager;
if (networkManager.DistributedAuthorityMode)
var distributedAuthority = networkManager.DistributedAuthorityMode;
var ensureLengthSafety = networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety;
// Always write the NetworkVariable count even if zero for distributed authority (used by comb server)
if (distributedAuthority)
{
writer.WriteValueSafe((ushort)NetworkVariableFields.Count);
}
// Exit early if there are no NetworkVariables
if (NetworkVariableFields.Count == 0)
{
return;
}
// DANGO-TODO: Made some modifications here that overlap/won't play nice with EnsureNetworkVariableLenghtSafety.
// Worth either merging or more cleanly separating these codepaths.
for (int j = 0; j < NetworkVariableFields.Count; j++)
{
// Note: In distributed authority mode, all clients can read
// Client-Server: Try to write values only for clients that have read permissions.
// Distributed Authority: All clients have read permissions, always try to write the value.
if (NetworkVariableFields[j].CanClientRead(targetClientId))
{
if (networkManager.DistributedAuthorityMode)
// Write additional NetworkVariable information when length safety is enabled or when in distributed authority mode
if (ensureLengthSafety || distributedAuthority)
{
// Write the type being serialized for distributed authority (only for comb-server)
if (distributedAuthority)
{
writer.WriteValueSafe(NetworkVariableFields[j].Type);
}
if (networkManager.DistributedAuthorityMode || networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
{
var writePos = writer.Position;
// Note: This value can't be packed because we don't know how large it will be in advance
// we reserve space for it, then write the data, then come back and fill in the space
@@ -1120,18 +1161,19 @@ namespace Unity.Netcode
NetworkVariableFields[j].WriteField(writer);
var size = writer.Position - startPos;
writer.Seek(writePos);
// Write the NetworkVariable value
writer.WriteValueSafe((ushort)size);
writer.Seek(startPos + size);
}
else
else // Client-Server Only: Should only ever be invoked when using a client-server NetworkTopology
{
// Write the NetworkVariable value
NetworkVariableFields[j].WriteField(writer);
}
}
else
else if (ensureLengthSafety)
{
// Only if EnsureNetworkVariableLengthSafety, otherwise just skip
if (networkManager.DistributedAuthorityMode || networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
// Client-Server Only: If the client cannot read this field, then skip it but write a 0 for this NetworkVariable's position
{
writer.WriteValueSafe((ushort)0);
}
@@ -1149,75 +1191,78 @@ namespace Unity.Netcode
/// </remarks>
internal void SetNetworkVariableData(FastBufferReader reader, ulong clientId)
{
// Stack cache any values that requires accessing the NetworkManager (it is expensive to access it in NetworkBehaviour)
var networkManager = NetworkManager;
if (networkManager.DistributedAuthorityMode)
var distributedAuthority = networkManager.DistributedAuthorityMode;
var ensureLengthSafety = networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety;
// Always read the NetworkVariable count when in distributed authority (sanity check if comb-server matches what client has locally)
if (distributedAuthority)
{
reader.ReadValueSafe(out ushort variableCount);
if (variableCount != NetworkVariableFields.Count)
{
Debug.LogError("NetworkVariable count mismatch.");
Debug.LogError($"[{name}][NetworkObjectId: {NetworkObjectId}][NetworkBehaviourId: {NetworkBehaviourId}] NetworkVariable count mismatch! (Read: {variableCount} vs. Expected: {NetworkVariableFields.Count})");
return;
}
}
// Exit early if nothing else to read
if (NetworkVariableFields.Count == 0)
{
return;
}
// DANGO-TODO: Made some modifications here that overlap/won't play nice with EnsureNetworkVariableLenghtSafety.
// Worth either merging or more cleanly separating these codepaths.
for (int j = 0; j < NetworkVariableFields.Count; j++)
{
var varSize = (ushort)0;
var readStartPos = 0;
if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
// Client-Server: Clients that only have read permissions will try to read the value
// Distributed Authority: All clients have read permissions, always try to read the value
if (NetworkVariableFields[j].CanClientRead(clientId))
{
if (ensureLengthSafety || distributedAuthority)
{
// Read the type being serialized and discard it (for now) when in a distributed authority network topology (only used by comb-server)
if (distributedAuthority)
{
reader.ReadValueSafe(out NetworkVariableType _);
}
reader.ReadValueSafe(out varSize);
if (varSize == 0)
{
Debug.LogError($"[{name}][NetworkObjectId: {NetworkObjectId}][NetworkBehaviourId: {NetworkBehaviourId}][{NetworkVariableFields[j].Name}] Expected non-zero size readable NetworkVariable! (Skipping)");
continue;
}
readStartPos = reader.Position;
}
else // If the client cannot read this field, then skip it
if (!NetworkVariableFields[j].CanClientRead(clientId))
}
else // Client-Server Only: If the client cannot read this field, then skip it
{
if (networkManager.DistributedAuthorityMode)
// If skipping and length safety, then fill in a 0 size for this one spot
if (ensureLengthSafety)
{
reader.ReadValueSafe(out ushort size);
if (size != 0)
{
Debug.LogError("Expected zero size");
Debug.LogError($"[{name}][NetworkObjectId: {NetworkObjectId}][NetworkBehaviourId: {NetworkBehaviourId}][{NetworkVariableFields[j].Name}] Expected zero size for non-readable NetworkVariable when EnsureNetworkVariableLengthSafety is enabled! (Skipping)");
}
}
continue;
}
if (networkManager.DistributedAuthorityMode)
{
// Explicit setting of the NetworkVariableType is only needed for CMB Runtime
reader.ReadValueSafe(out NetworkVariableType _);
reader.ReadValueSafe(out ushort size);
var start_marker = reader.Position;
// Read the NetworkVarible value
NetworkVariableFields[j].ReadField(reader);
if (reader.Position - start_marker != size)
{
Debug.LogError("Mismatched network variable size");
}
}
else
{
NetworkVariableFields[j].ReadField(reader);
}
if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
// When EnsureNetworkVariableLengthSafety or DistributedAuthorityMode always do a bounds check
if (ensureLengthSafety || distributedAuthority)
{
if (reader.Position > (readStartPos + varSize))
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
{
NetworkLog.LogWarning($"Var data read too far. {reader.Position - (readStartPos + varSize)} bytes.");
NetworkLog.LogWarning($"[{name}][NetworkObjectId: {NetworkObjectId}][NetworkBehaviourId: {NetworkBehaviourId}][{NetworkVariableFields[j].Name}] NetworkVariable data read too big. {reader.Position - (readStartPos + varSize)} bytes.");
}
reader.Seek(readStartPos + varSize);
@@ -1226,7 +1271,7 @@ namespace Unity.Netcode
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
{
NetworkLog.LogWarning($"Var data read too little. {(readStartPos + varSize) - reader.Position} bytes.");
NetworkLog.LogWarning($"[{name}][NetworkObjectId: {NetworkObjectId}][NetworkBehaviourId: {NetworkBehaviourId}][{NetworkVariableFields[j].Name}] NetworkVariable data read too small. {(readStartPos + varSize) - reader.Position} bytes.");
}
reader.Seek(readStartPos + varSize);
@@ -1236,7 +1281,7 @@ namespace Unity.Netcode
}
/// <summary>
/// Gets the local instance of a object with a given NetworkId
/// Gets the local instance of a NetworkObject with a given NetworkId.
/// </summary>
/// <param name="networkId"></param>
/// <returns></returns>
@@ -1247,14 +1292,14 @@ namespace Unity.Netcode
/// <summary>
/// Override this method if your derived NetworkBehaviour requires custom synchronization data.
/// Note: Use of this method is only for the initial client synchronization of NetworkBehaviours
/// Use of this method is only for the initial client synchronization of NetworkBehaviours
/// and will increase the payload size for client synchronization and dynamically spawned
/// <see cref="NetworkObject"/>s.
/// </summary>
/// <remarks>
/// When serializing (writing) this will be invoked during the client synchronization period and
/// When serializing (writing), this method is invoked during the client synchronization period and
/// when spawning new NetworkObjects.
/// When deserializing (reading), this will be invoked prior to the NetworkBehaviour's associated
/// When deserializing (reading), this method is invoked prior to the NetworkBehaviour's associated
/// NetworkObject being spawned.
/// </remarks>
/// <param name="serializer">The serializer to use to read and write the data.</param>
@@ -1268,14 +1313,19 @@ namespace Unity.Netcode
}
public virtual void OnReanticipate(double lastRoundTripTime)
{
}
/// <summary>
/// The relative client identifier targeted for the serialization of this <see cref="NetworkBehaviour"/> instance.
/// </summary>
/// <remarks>
/// This value will be set prior to <see cref="OnSynchronize{T}(ref BufferSerializer{T})"/> being invoked.
/// This value is set prior to <see cref="OnSynchronize{T}(ref BufferSerializer{T})"/> being invoked.
/// For writing (server-side), this is useful to know which client will receive the serialized data.
/// For reading (client-side), this will be the <see cref="NetworkManager.LocalClientId"/>.
/// When synchronization of this instance is complete, this value will be reset to 0
/// When synchronization of this instance is complete, this value is reset to 0.
/// </remarks>
protected ulong m_TargetIdBeingSynchronized { get; private set; }
@@ -1398,9 +1448,8 @@ namespace Unity.Netcode
/// <summary>
/// Invoked when the <see cref="GameObject"/> the <see cref="NetworkBehaviour"/> is attached to.
/// NOTE: If you override this, you will want to always invoke this base class version of this
/// <see cref="OnDestroy"/> method!!
/// Invoked when the <see cref="GameObject"/> the <see cref="NetworkBehaviour"/> is attached to is destroyed.
/// If you override this, you must always invoke the base class version of this <see cref="OnDestroy"/> method.
/// </summary>
public virtual void OnDestroy()
{

View File

@@ -11,6 +11,7 @@ namespace Unity.Netcode
private NetworkManager m_NetworkManager;
private NetworkConnectionManager m_ConnectionManager;
private HashSet<NetworkObject> m_DirtyNetworkObjects = new HashSet<NetworkObject>();
private HashSet<NetworkObject> m_PendingDirtyNetworkObjects = new HashSet<NetworkObject>();
#if DEVELOPMENT_BUILD || UNITY_EDITOR
private ProfilerMarker m_NetworkBehaviourUpdate = new ProfilerMarker($"{nameof(NetworkBehaviour)}.{nameof(NetworkBehaviourUpdate)}");
@@ -18,7 +19,7 @@ namespace Unity.Netcode
internal void AddForUpdate(NetworkObject networkObject)
{
m_DirtyNetworkObjects.Add(networkObject);
m_PendingDirtyNetworkObjects.Add(networkObject);
}
internal void NetworkBehaviourUpdate()
@@ -28,6 +29,9 @@ namespace Unity.Netcode
#endif
try
{
m_DirtyNetworkObjects.UnionWith(m_PendingDirtyNetworkObjects);
m_PendingDirtyNetworkObjects.Clear();
// NetworkObject references can become null, when hidden or despawned. Once NUll, there is no point
// trying to process them, even if they were previously marked as dirty.
m_DirtyNetworkObjects.RemoveWhere((sobj) => sobj == null);

View File

@@ -8,7 +8,6 @@ using UnityEditor;
#endif
using UnityEngine.SceneManagement;
using Debug = UnityEngine.Debug;
using Unity.Netcode.Components;
namespace Unity.Netcode
{
@@ -29,13 +28,40 @@ namespace Unity.Netcode
// RuntimeAccessModifiersILPP will make this `public`
internal static readonly Dictionary<uint, RpcReceiveHandler> __rpc_func_table = new Dictionary<uint, RpcReceiveHandler>();
#if DEVELOPMENT_BUILD || UNITY_EDITOR
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
// RuntimeAccessModifiersILPP will make this `public`
internal static readonly Dictionary<uint, string> __rpc_name_table = new Dictionary<uint, string>();
#endif
#pragma warning restore IDE1006 // restore naming rule violation check
#if DEVELOPMENT_BUILD || UNITY_EDITOR
private static List<Type> s_SerializedType = new List<Type>();
// This is used to control the serialized type not optimized messaging for integration test purposes
internal static bool DisableNotOptimizedSerializedType;
/// <summary>
/// Until all serialized types are optimized for the distributed authority network topology,
/// this will handle the notification to the user that the type being serialized is not yet
/// optimized but will only log the message once to prevent log spamming.
/// </summary>
internal static void LogSerializedTypeNotOptimized<T>()
{
if (DisableNotOptimizedSerializedType)
{
return;
}
var type = typeof(T);
if (!s_SerializedType.Contains(type))
{
s_SerializedType.Add(type);
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer)
{
Debug.LogWarning($"[{type.Name}] Serialized type has not been optimized for use with Distributed Authority!");
}
}
}
#endif
internal static bool IsDistributedAuthority;
/// <summary>
@@ -188,25 +214,25 @@ namespace Unity.Netcode
}
}
internal Dictionary<ulong, NetworkTransform> NetworkTransformUpdate = new Dictionary<ulong, NetworkTransform>();
internal Dictionary<ulong, NetworkObject> NetworkTransformUpdate = new Dictionary<ulong, NetworkObject>();
#if COM_UNITY_MODULES_PHYSICS
internal Dictionary<ulong, NetworkTransform> NetworkTransformFixedUpdate = new Dictionary<ulong, NetworkTransform>();
internal Dictionary<ulong, NetworkObject> NetworkTransformFixedUpdate = new Dictionary<ulong, NetworkObject>();
#endif
internal void NetworkTransformRegistration(NetworkTransform networkTransform, bool forUpdate = true, bool register = true)
internal void NetworkTransformRegistration(NetworkObject networkObject, bool onUpdate = true, bool register = true)
{
if (forUpdate)
if (onUpdate)
{
if (register)
{
if (!NetworkTransformUpdate.ContainsKey(networkTransform.NetworkObjectId))
if (!NetworkTransformUpdate.ContainsKey(networkObject.NetworkObjectId))
{
NetworkTransformUpdate.Add(networkTransform.NetworkObjectId, networkTransform);
NetworkTransformUpdate.Add(networkObject.NetworkObjectId, networkObject);
}
}
else
{
NetworkTransformUpdate.Remove(networkTransform.NetworkObjectId);
NetworkTransformUpdate.Remove(networkObject.NetworkObjectId);
}
}
#if COM_UNITY_MODULES_PHYSICS
@@ -214,14 +240,14 @@ namespace Unity.Netcode
{
if (register)
{
if (!NetworkTransformFixedUpdate.ContainsKey(networkTransform.NetworkObjectId))
if (!NetworkTransformFixedUpdate.ContainsKey(networkObject.NetworkObjectId))
{
NetworkTransformFixedUpdate.Add(networkTransform.NetworkObjectId, networkTransform);
NetworkTransformFixedUpdate.Add(networkObject.NetworkObjectId, networkObject);
}
}
else
{
NetworkTransformFixedUpdate.Remove(networkTransform.NetworkObjectId);
NetworkTransformFixedUpdate.Remove(networkObject.NetworkObjectId);
}
}
#endif
@@ -253,18 +279,30 @@ namespace Unity.Netcode
DeferredMessageManager.ProcessTriggers(IDeferredNetworkMessageManager.TriggerType.OnNextFrame, 0);
AnticipationSystem.SetupForUpdate();
MessageManager.ProcessIncomingMessageQueue();
MessageManager.CleanupDisconnectedClients();
AnticipationSystem.ProcessReanticipation();
}
break;
#if COM_UNITY_MODULES_PHYSICS
case NetworkUpdateStage.FixedUpdate:
{
foreach (var networkTransformEntry in NetworkTransformFixedUpdate)
foreach (var networkObjectEntry in NetworkTransformFixedUpdate)
{
if (networkTransformEntry.Value.gameObject.activeInHierarchy && networkTransformEntry.Value.IsSpawned)
// if not active or not spawned then skip
if (!networkObjectEntry.Value.gameObject.activeInHierarchy || !networkObjectEntry.Value.IsSpawned)
{
networkTransformEntry.Value.OnFixedUpdate();
continue;
}
foreach (var networkTransformEntry in networkObjectEntry.Value.NetworkTransforms)
{
// only update if enabled
if (networkTransformEntry.enabled)
{
networkTransformEntry.OnFixedUpdate();
}
}
}
}
@@ -273,19 +311,36 @@ namespace Unity.Netcode
case NetworkUpdateStage.PreUpdate:
{
NetworkTimeSystem.UpdateTime();
AnticipationSystem.Update();
}
break;
case NetworkUpdateStage.PreLateUpdate:
{
// Non-physics based non-authority NetworkTransforms update their states after all other components
foreach (var networkTransformEntry in NetworkTransformUpdate)
foreach (var networkObjectEntry in NetworkTransformUpdate)
{
if (networkTransformEntry.Value.gameObject.activeInHierarchy && networkTransformEntry.Value.IsSpawned)
// if not active or not spawned then skip
if (!networkObjectEntry.Value.gameObject.activeInHierarchy || !networkObjectEntry.Value.IsSpawned)
{
networkTransformEntry.Value.OnUpdate();
continue;
}
foreach (var networkTransformEntry in networkObjectEntry.Value.NetworkTransforms)
{
// only update if enabled
if (networkTransformEntry.enabled)
{
networkTransformEntry.OnUpdate();
}
}
}
}
break;
case NetworkUpdateStage.PostScriptLateUpdate:
{
AnticipationSystem.Sync();
AnticipationSystem.SetupForRender();
}
break;
case NetworkUpdateStage.PostLateUpdate:
{
@@ -526,6 +581,25 @@ namespace Unity.Netcode
remove => ConnectionManager.OnTransportFailure -= value;
}
public delegate void ReanticipateDelegate(double lastRoundTripTime);
/// <summary>
/// This callback is called after all individual OnReanticipate calls on AnticipatedNetworkVariable
/// and AnticipatedNetworkTransform values have been invoked. The first parameter is a hash set of
/// all the variables that have been changed on this frame (you can detect a particular variable by
/// checking if the set contains it), while the second parameter is a set of all anticipated network
/// transforms that have been changed. Both are passed as their base class type.
///
/// The third parameter is the local time corresponding to the current authoritative server state
/// (i.e., to determine the amount of time that needs to be re-simulated, you will use
/// NetworkManager.LocalTime.Time - authorityTime).
/// </summary>
public event ReanticipateDelegate OnReanticipate
{
add => AnticipationSystem.OnReanticipate += value;
remove => AnticipationSystem.OnReanticipate -= value;
}
/// <summary>
/// The callback to invoke during connection approval. Allows client code to decide whether or not to allow incoming client connection
/// </summary>
@@ -770,6 +844,8 @@ namespace Unity.Netcode
/// </summary>
public NetworkTickSystem NetworkTickSystem { get; private set; }
internal AnticipationSystem AnticipationSystem { get; private set; }
/// <summary>
/// Used for time mocking in tests
/// </summary>
@@ -1032,6 +1108,13 @@ namespace Unity.Netcode
internal void Initialize(bool server)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (!DisableNotOptimizedSerializedType)
{
s_SerializedType.Clear();
}
#endif
#if COM_UNITY_MODULES_PHYSICS
NetworkTransformFixedUpdate.Clear();
#endif
@@ -1078,6 +1161,7 @@ namespace Unity.Netcode
this.RegisterNetworkUpdate(NetworkUpdateStage.FixedUpdate);
#endif
this.RegisterNetworkUpdate(NetworkUpdateStage.PreUpdate);
this.RegisterNetworkUpdate(NetworkUpdateStage.PostScriptLateUpdate);
this.RegisterNetworkUpdate(NetworkUpdateStage.PreLateUpdate);
this.RegisterNetworkUpdate(NetworkUpdateStage.PostLateUpdate);
@@ -1117,6 +1201,7 @@ namespace Unity.Netcode
// The remaining systems can then be initialized
NetworkTimeSystem = server ? NetworkTimeSystem.ServerTimeSystem() : new NetworkTimeSystem(1.0 / NetworkConfig.TickRate);
NetworkTickSystem = NetworkTimeSystem.Initialize(this);
AnticipationSystem = new AnticipationSystem(this);
// Create spawn manager instance
SpawnManager = new NetworkSpawnManager(this);
@@ -1218,17 +1303,8 @@ namespace Unity.Netcode
{
SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
// Notify the server that all in-scnee placed NetworkObjects are spawned at this time.
foreach (var networkObject in SpawnManager.SpawnedObjectsList)
{
networkObject.InternalInSceneNetworkObjectsSpawned();
}
// Notify the server that everything should be synchronized/spawned at this time.
foreach (var networkObject in SpawnManager.SpawnedObjectsList)
{
networkObject.InternalNetworkSessionSynchronized();
}
SpawnManager.NotifyNetworkObjectsSynchronized();
OnServerStarted?.Invoke();
ConnectionManager.LocalClient.IsApproved = true;
return true;
@@ -1375,17 +1451,9 @@ namespace Unity.Netcode
}
SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
// Notify the host that all in-scnee placed NetworkObjects are spawned at this time.
foreach (var networkObject in SpawnManager.SpawnedObjectsList)
{
networkObject.InternalInSceneNetworkObjectsSpawned();
}
// Notify the host that everything should be synchronized/spawned at this time.
foreach (var networkObject in SpawnManager.SpawnedObjectsList)
{
networkObject.InternalNetworkSessionSynchronized();
}
SpawnManager.NotifyNetworkObjectsSynchronized();
OnServerStarted?.Invoke();
OnClientStarted?.Invoke();

View File

@@ -540,8 +540,8 @@ namespace Unity.Netcode
/// permission failure status codes will be returned via <see cref="OnOwnershipPermissionsFailure"/>.
/// <see cref="Locked"/>: The <see cref="NetworkObject"/> is locked and ownership cannot be acquired.
/// <see cref="RequestRequired"/>: The <see cref="NetworkObject"/> requires an ownership request via <see cref="RequestOwnership"/>.
/// <see cref="RequestInProgress"/>: The <see cref="NetworkObject"/> already is processing an ownership request and ownership cannot be acquired at this time.
/// <see cref="NotTransferrable": The <see cref="NetworkObject"/> does not have the <see cref="OwnershipStatus.Transferable"/> flag set and ownership cannot be acquired.
/// <see cref="RequestInProgress"/>: The <see cref="NetworkObject"/> is already processing an ownership request and ownership cannot be acquired at this time.
/// <see cref="NotTransferrable"/>: The <see cref="NetworkObject"/> does not have the <see cref="OwnershipStatus.Transferable"/> flag set and ownership cannot be acquired.
/// </summary>
public enum OwnershipPermissionsFailureStatus
{
@@ -1547,6 +1547,11 @@ namespace Unity.Netcode
if (NetworkManager.DistributedAuthorityMode)
{
if (NetworkManager.LocalClient == null || !NetworkManager.IsConnectedClient || !NetworkManager.ConnectionManager.LocalClient.IsApproved)
{
Debug.LogError($"Cannot spawn {name} until the client is fully connected to the session!");
return;
}
if (NetworkManager.NetworkConfig.EnableSceneManagement)
{
NetworkSceneHandle = NetworkManager.SceneManager.ClientSceneHandleToServerSceneHandle[gameObject.scene.handle];
@@ -1638,7 +1643,7 @@ namespace Unity.Netcode
return null;
}
ownerClientId = networkManager.DistributedAuthorityMode ? networkManager.LocalClientId : NetworkManager.ServerClientId;
ownerClientId = networkManager.DistributedAuthorityMode ? networkManager.LocalClientId : ownerClientId;
// We only need to check for authority when running in client-server mode
if (!networkManager.IsServer && !networkManager.DistributedAuthorityMode)
{
@@ -2354,7 +2359,7 @@ namespace Unity.Netcode
{
m_ChildNetworkBehaviours.Add(networkBehaviours[i]);
var type = networkBehaviours[i].GetType();
if (type.IsInstanceOfType(typeof(NetworkTransform)) || type.IsSubclassOf(typeof(NetworkTransform)))
if (type == typeof(NetworkTransform) || type.IsInstanceOfType(typeof(NetworkTransform)) || type.IsSubclassOf(typeof(NetworkTransform)))
{
if (NetworkTransforms == null)
{
@@ -2436,10 +2441,10 @@ namespace Unity.Netcode
if (NetworkManager.DistributedAuthorityMode)
{
var readerPosition = reader.Position;
reader.ReadValueSafe(out ushort behaviorCount);
if (behaviorCount != ChildNetworkBehaviours.Count)
reader.ReadValueSafe(out ushort behaviourCount);
if (behaviourCount != ChildNetworkBehaviours.Count)
{
Debug.LogError($"Network Behavior Count Mismatch! [{readerPosition}][{reader.Position}]");
Debug.LogError($"[{name}] Network Behavior Count Mismatch! [In: {behaviourCount} vs Local: {ChildNetworkBehaviours.Count}][StartReaderPos: {readerPosition}] CurrentReaderPos: {reader.Position}]");
return false;
}
}

View File

@@ -54,6 +54,12 @@ namespace Unity.Netcode
/// </summary>
PreLateUpdate = 6,
/// <summary>
/// Updated after Monobehaviour.LateUpdate, but BEFORE rendering
/// </summary>
// Yes, these numbers are out of order due to backward compatibility requirements.
// The enum values are listed in the order they will be called.
PostScriptLateUpdate = 8,
/// <summary>
/// Updated after the Monobehaviour.LateUpdate for all components is invoked
/// </summary>
PostLateUpdate = 7
@@ -258,6 +264,18 @@ namespace Unity.Netcode
}
}
internal struct NetworkPostScriptLateUpdate
{
public static PlayerLoopSystem CreateLoopSystem()
{
return new PlayerLoopSystem
{
type = typeof(NetworkPostScriptLateUpdate),
updateDelegate = () => RunNetworkUpdateStage(NetworkUpdateStage.PostScriptLateUpdate)
};
}
}
internal struct NetworkPostLateUpdate
{
public static PlayerLoopSystem CreateLoopSystem()
@@ -399,6 +417,7 @@ namespace Unity.Netcode
else if (currentSystem.type == typeof(PreLateUpdate))
{
TryAddLoopSystem(ref currentSystem, NetworkPreLateUpdate.CreateLoopSystem(), typeof(PreLateUpdate.ScriptRunBehaviourLateUpdate), LoopSystemPosition.Before);
TryAddLoopSystem(ref currentSystem, NetworkPostScriptLateUpdate.CreateLoopSystem(), typeof(PreLateUpdate.ScriptRunBehaviourLateUpdate), LoopSystemPosition.After);
}
else if (currentSystem.type == typeof(PostLateUpdate))
{
@@ -440,6 +459,7 @@ namespace Unity.Netcode
else if (currentSystem.type == typeof(PreLateUpdate))
{
TryRemoveLoopSystem(ref currentSystem, typeof(NetworkPreLateUpdate));
TryRemoveLoopSystem(ref currentSystem, typeof(NetworkPostScriptLateUpdate));
}
else if (currentSystem.type == typeof(PostLateUpdate))
{

View File

@@ -47,6 +47,8 @@ namespace Unity.Netcode
SessionOwner = 20,
TimeSync = 21,
Unnamed = 22,
AnticipationCounterSyncPingMessage = 23,
AnticipationCounterSyncPongMessage = 24,
}
@@ -103,7 +105,9 @@ namespace Unity.Netcode
{ typeof(ServerRpcMessage), NetworkMessageTypes.ServerRpc },
{ typeof(TimeSyncMessage), NetworkMessageTypes.TimeSync },
{ typeof(UnnamedMessage), NetworkMessageTypes.Unnamed },
{ typeof(SessionOwnerMessage), NetworkMessageTypes.SessionOwner }
{ typeof(SessionOwnerMessage), NetworkMessageTypes.SessionOwner },
{ typeof(AnticipationCounterSyncPingMessage), NetworkMessageTypes.AnticipationCounterSyncPingMessage},
{ typeof(AnticipationCounterSyncPongMessage), NetworkMessageTypes.AnticipationCounterSyncPongMessage},
};
// Assure the type to lookup table count and NetworkMessageType enum count matches (i.e. to catch human error when adding new messages)

View File

@@ -0,0 +1,70 @@
namespace Unity.Netcode
{
internal struct AnticipationCounterSyncPingMessage : INetworkMessage
{
public int Version => 0;
public ulong Counter;
public double Time;
public void Serialize(FastBufferWriter writer, int targetVersion)
{
BytePacker.WriteValuePacked(writer, Counter);
writer.WriteValueSafe(Time);
}
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
var networkManager = (NetworkManager)context.SystemOwner;
if (!networkManager.IsServer)
{
return false;
}
ByteUnpacker.ReadValuePacked(reader, out Counter);
reader.ReadValueSafe(out Time);
return true;
}
public void Handle(ref NetworkContext context)
{
var networkManager = (NetworkManager)context.SystemOwner;
if (networkManager.IsListening && !networkManager.ShutdownInProgress && networkManager.ConnectedClients.ContainsKey(context.SenderId))
{
var message = new AnticipationCounterSyncPongMessage { Counter = Counter, Time = Time };
networkManager.MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, context.SenderId);
}
}
}
internal struct AnticipationCounterSyncPongMessage : INetworkMessage
{
public int Version => 0;
public ulong Counter;
public double Time;
public void Serialize(FastBufferWriter writer, int targetVersion)
{
BytePacker.WriteValuePacked(writer, Counter);
writer.WriteValueSafe(Time);
}
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
var networkManager = (NetworkManager)context.SystemOwner;
if (!networkManager.IsClient)
{
return false;
}
ByteUnpacker.ReadValuePacked(reader, out Counter);
reader.ReadValueSafe(out Time);
return true;
}
public void Handle(ref NetworkContext context)
{
var networkManager = (NetworkManager)context.SystemOwner;
networkManager.AnticipationSystem.LastAnticipationAck = Counter;
networkManager.AnticipationSystem.LastAnticipationAckTime = Time;
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: b7d5c92979ad7e646a078aaf058b53a9

View File

@@ -31,7 +31,7 @@ namespace Unity.Netcode
public void Handle(ref NetworkContext context)
{
var networkManager = (NetworkManager)context.SystemOwner;
if ((ShouldSynchronize || networkManager.CMBServiceConnection) && networkManager.DistributedAuthorityMode && networkManager.LocalClient.IsSessionOwner)
if (ShouldSynchronize && networkManager.NetworkConfig.EnableSceneManagement && networkManager.DistributedAuthorityMode && networkManager.LocalClient.IsSessionOwner)
{
networkManager.SceneManager.SynchronizeNetworkObjects(ClientId);
}

View File

@@ -224,10 +224,7 @@ namespace Unity.Netcode
networkManager.ConnectionManager.InvokeOnClientConnectedCallback(context.SenderId);
// For convenience, notify all NetworkBehaviours that synchronization is complete.
foreach (var networkObject in networkManager.SpawnManager.SpawnedObjectsList)
{
networkObject.InternalNetworkSessionSynchronized();
}
networkManager.SpawnManager.NotifyNetworkObjectsSynchronized();
}
else
{
@@ -240,16 +237,12 @@ namespace Unity.Netcode
if (!IsRestoredSession)
{
// Synchronize the service with the initial session owner's loaded scenes and spawned objects
networkManager.SceneManager.SynchronizeNetworkObjects(NetworkManager.ServerClientId);
// Spawn any in-scene placed NetworkObjects
networkManager.SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
// With scene management enabled and since the session owner doesn't send a Synchronize scene event synchronize itself,
// we need to notify the session owner that all in-scnee placed NetworkObjects are spawned at this time.
foreach (var networkObject in networkManager.SpawnManager.SpawnedObjectsList)
{
networkObject.InternalInSceneNetworkObjectsSpawned();
}
// Spawn the local player of the session owner
if (networkManager.AutoSpawnPlayerPrefabClientSide)
{
@@ -261,10 +254,7 @@ namespace Unity.Netcode
// With scene management enabled and since the session owner doesn't send a Synchronize scene event synchronize itself,
// we need to notify the session owner that everything should be synchronized/spawned at this time.
foreach (var networkObject in networkManager.SpawnManager.SpawnedObjectsList)
{
networkObject.InternalNetworkSessionSynchronized();
}
networkManager.SpawnManager.NotifyNetworkObjectsSynchronized();
// When scene management is enabled and since the session owner is synchronizing the service (i.e. acting like host),
// we need to locallyh invoke the OnClientConnected callback at this point in time.

View File

@@ -25,8 +25,6 @@ namespace Unity.Netcode
private const string k_Name = "NetworkVariableDeltaMessage";
// DANGO-TODO: Made some modifications here that overlap/won't play nice with EnsureNetworkVariableLenghtSafety.
// Worth either merging or more cleanly separating these codepaths.
public void Serialize(FastBufferWriter writer, int targetVersion)
{
if (!writer.TryBeginWrite(FastBufferWriter.GetWriteSize(NetworkObjectId) + FastBufferWriter.GetWriteSize(NetworkBehaviourIndex)))
@@ -69,7 +67,8 @@ namespace Unity.Netcode
var networkVariable = NetworkBehaviour.NetworkVariableFields[i];
var shouldWrite = networkVariable.IsDirty() &&
networkVariable.CanClientRead(TargetClientId) &&
(networkManager.IsServer || networkVariable.CanClientWrite(networkManager.LocalClientId));
(networkManager.IsServer || networkVariable.CanClientWrite(networkManager.LocalClientId)) &&
networkVariable.CanSend();
// Prevent the server from writing to the client that owns a given NetworkVariable
// Allowing the write would send an old value to the client and cause jitter
@@ -125,10 +124,6 @@ namespace Unity.Netcode
}
else
{
// DANGO-TODO:
// Complex types with custom type serialization (either registered custom types or INetworkSerializable implementations) will be problematic
// Non-complex types always provide a full state update per delta
// DANGO-TODO: Add NetworkListEvent<T>.EventType awareness to the cloud-state server
if (networkManager.DistributedAuthorityMode)
{
var size_marker = writer.Position;
@@ -166,8 +161,6 @@ namespace Unity.Netcode
return true;
}
// DANGO-TODO: Made some modifications here that overlap/won't play nice with EnsureNetworkVariableLenghtSafety.
// Worth either merging or more cleanly separating these codepaths.
public void Handle(ref NetworkContext context)
{
var networkManager = (NetworkManager)context.SystemOwner;

View File

@@ -41,7 +41,7 @@ namespace Unity.Netcode
payload = new FastBufferReader(reader.GetUnsafePtrAtCurrentPosition(), Allocator.None, reader.Length - reader.Position);
#if DEVELOPMENT_BUILD || UNITY_EDITOR
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
if (NetworkBehaviour.__rpc_name_table[networkBehaviour.GetType()].TryGetValue(metadata.NetworkRpcMethodId, out var rpcMethodName))
{
networkManager.NetworkMetrics.TrackRpcReceived(

View File

@@ -36,12 +36,12 @@ namespace Unity.Netcode
private protected void SendMessageToClient(NetworkBehaviour behaviour, ulong clientId, ref RpcMessage message, NetworkDelivery delivery)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
var size =
#endif
behaviour.NetworkManager.MessageManager.SendMessage(ref message, delivery, clientId);
#if DEVELOPMENT_BUILD || UNITY_EDITOR
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
{
behaviour.NetworkManager.NetworkMetrics.TrackRpcSent(

View File

@@ -46,7 +46,7 @@ namespace Unity.Netcode
message.Handle(ref context);
length = tempBuffer.Length;
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
{
networkManager.NetworkMetrics.TrackRpcSent(

View File

@@ -29,6 +29,12 @@ namespace Unity.Netcode
{
continue;
}
// The CMB-Service holds ID 0 and should not be added to the targets
if (clientId == NetworkManager.ServerClientId && m_NetworkManager.CMBServiceConnection)
{
continue;
}
m_GroupSendTarget.Add(clientId);
}
}
@@ -41,6 +47,12 @@ namespace Unity.Netcode
continue;
}
// The CMB-Service holds ID 0 and should not be added to the targets
if (clientId == NetworkManager.ServerClientId && m_NetworkManager.CMBServiceConnection)
{
continue;
}
if (clientId == m_NetworkManager.LocalClientId)
{
m_LocalSendRpcTarget.Send(behaviour, ref message, delivery, rpcParams);

View File

@@ -17,13 +17,18 @@ namespace Unity.Netcode
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
{
// If there are no targets then don't attempt to send anything.
if (TargetClientIds.Length == 0 && Ids.Count == 0)
{
return;
}
var proxyMessage = new ProxyMessage { Delivery = delivery, TargetClientIds = TargetClientIds.AsArray(), WrappedMessage = message };
#if DEVELOPMENT_BUILD || UNITY_EDITOR
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
var size =
#endif
behaviour.NetworkManager.MessageManager.SendMessage(ref proxyMessage, delivery, NetworkManager.ServerClientId);
#if DEVELOPMENT_BUILD || UNITY_EDITOR
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
{
foreach (var clientId in TargetClientIds)

View File

@@ -0,0 +1,392 @@
using System;
using Unity.Mathematics;
using UnityEngine;
namespace Unity.Netcode
{
public enum StaleDataHandling
{
Ignore,
Reanticipate
}
#pragma warning disable IDE0001
/// <summary>
/// A variable that can be synchronized over the network.
/// This version supports basic client anticipation - the client can set a value on the belief that the server
/// will update it to reflect the same value in a future update (i.e., as the result of an RPC call).
/// This value can then be adjusted as new updates from the server come in, in three basic modes:
///
/// <list type="bullet">
///
/// <item><b>Snap:</b> In this mode (with <see cref="StaleDataHandling"/> set to
/// <see cref="Netcode.StaleDataHandling.Ignore"/> and no <see cref="NetworkBehaviour.OnReanticipate"/> callback),
/// the moment a more up-to-date value is received from the authority, it will simply replace the anticipated value,
/// resulting in a "snap" to the new value if it is different from the anticipated value.</item>
///
/// <item><b>Smooth:</b> In this mode (with <see cref="StaleDataHandling"/> set to
/// <see cref="Netcode.StaleDataHandling.Ignore"/> and an <see cref="NetworkBehaviour.OnReanticipate"/> callback that calls
/// <see cref="Smooth"/> from the anticipated value to the authority value with an appropriate
/// <see cref="Mathf.Lerp"/>-style smooth function), when a more up-to-date value is received from the authority,
/// it will interpolate over time from an incorrect anticipated value to the correct authoritative value.</item>
///
/// <item><b>Constant Reanticipation:</b> In this mode (with <see cref="StaleDataHandling"/> set to
/// <see cref="Netcode.StaleDataHandling.Reanticipate"/> and an <see cref="NetworkBehaviour.OnReanticipate"/> that calculates a
/// new anticipated value based on the current authoritative value), when a more up-to-date value is received from
/// the authority, user code calculates a new anticipated value, possibly calling <see cref="Smooth"/> to interpolate
/// between the previous anticipation and the new anticipation. This is useful for values that change frequently and
/// need to constantly be re-evaluated, as opposed to values that change only in response to user action and simply
/// need a one-time anticipation when the user performs that action.</item>
///
/// </list>
///
/// Note that these three modes may be combined. For example, if an <see cref="NetworkBehaviour.OnReanticipate"/> callback
/// does not call either <see cref="Smooth"/> or <see cref="Anticipate"/>, the result will be a snap to the
/// authoritative value, enabling for a callback that may conditionally call <see cref="Smooth"/> when the
/// difference between the anticipated and authoritative values is within some threshold, but fall back to
/// snap behavior if the difference is too large.
/// </summary>
/// <typeparam name="T">the unmanaged type for <see cref="NetworkVariable{T}"/> </typeparam>
#pragma warning restore IDE0001
[Serializable]
[GenerateSerializationForGenericParameter(0)]
public class AnticipatedNetworkVariable<T> : NetworkVariableBase
{
[SerializeField]
private NetworkVariable<T> m_AuthoritativeValue;
private T m_AnticipatedValue;
private T m_PreviousAnticipatedValue;
private ulong m_LastAuthorityUpdateCounter = 0;
private ulong m_LastAnticipationCounter = 0;
private bool m_IsDisposed = false;
private bool m_SettingAuthoritativeValue = false;
private T m_SmoothFrom;
private T m_SmoothTo;
private float m_SmoothDuration;
private float m_CurrentSmoothTime;
private bool m_HasSmoothValues;
#pragma warning disable IDE0001
/// <summary>
/// Defines what the behavior should be if we receive a value from the server with an earlier associated
/// time value than the anticipation time value.
/// <br/><br/>
/// If this is <see cref="Netcode.StaleDataHandling.Ignore"/>, the stale data will be ignored and the authoritative
/// value will not replace the anticipated value until the anticipation time is reached. <see cref="OnAuthoritativeValueChanged"/>
/// and <see cref="NetworkBehaviour.OnReanticipate"/> will also not be invoked for this stale data.
/// <br/><br/>
/// If this is <see cref="Netcode.StaleDataHandling.Reanticipate"/>, the stale data will replace the anticipated data and
/// <see cref="OnAuthoritativeValueChanged"/> and <see cref="NetworkBehaviour.OnReanticipate"/> will be invoked.
/// In this case, the authoritativeTime value passed to <see cref="NetworkBehaviour.OnReanticipate"/> will be lower than
/// the anticipationTime value, and that callback can be used to calculate a new anticipated value.
/// </summary>
#pragma warning restore IDE0001
public StaleDataHandling StaleDataHandling;
public delegate void OnAuthoritativeValueChangedDelegate(AnticipatedNetworkVariable<T> variable, in T previousValue, in T newValue);
/// <summary>
/// Invoked any time the authoritative value changes, even when the data is stale or has been changed locally.
/// </summary>
public OnAuthoritativeValueChangedDelegate OnAuthoritativeValueChanged = null;
/// <summary>
/// Determines if the difference between the last serialized value and the current value is large enough
/// to serialize it again.
/// </summary>
public event NetworkVariable<T>.CheckExceedsDirtinessThresholdDelegate CheckExceedsDirtinessThreshold
{
add => m_AuthoritativeValue.CheckExceedsDirtinessThreshold += value;
remove => m_AuthoritativeValue.CheckExceedsDirtinessThreshold -= value;
}
private class AnticipatedObject : IAnticipatedObject
{
public AnticipatedNetworkVariable<T> Variable;
public void Update()
{
Variable.Update();
}
public void ResetAnticipation()
{
Variable.ShouldReanticipate = false;
}
public NetworkObject OwnerObject => Variable.m_NetworkBehaviour.NetworkObject;
}
private AnticipatedObject m_AnticipatedObject;
public override void OnInitialize()
{
m_AuthoritativeValue.Initialize(m_NetworkBehaviour);
NetworkVariableSerialization<T>.Duplicate(m_AuthoritativeValue.Value, ref m_AnticipatedValue);
NetworkVariableSerialization<T>.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue);
if (m_NetworkBehaviour != null && m_NetworkBehaviour.NetworkManager != null && m_NetworkBehaviour.NetworkManager.AnticipationSystem != null)
{
m_AnticipatedObject = new AnticipatedObject { Variable = this };
m_NetworkBehaviour.NetworkManager.AnticipationSystem.AllAnticipatedObjects.Add(m_AnticipatedObject);
}
}
public override bool ExceedsDirtinessThreshold()
{
return m_AuthoritativeValue.ExceedsDirtinessThreshold();
}
/// <summary>
/// Retrieves the current value for the variable.
/// This is the "display value" for this variable, and is affected by <see cref="Anticipate"/> and
/// <see cref="Smooth"/>, as well as by updates from the authority, depending on <see cref="StaleDataHandling"/>
/// and the behavior of any <see cref="NetworkBehaviour.OnReanticipate"/> callbacks.
/// <br /><br />
/// When a server update arrives, this value will be overwritten
/// by the new server value (unless stale data handling is set
/// to "Ignore" and the update is determined to be stale).
/// This value will be duplicated in
/// <see cref="PreviousAnticipatedValue"/>, which
/// will NOT be overwritten in server updates.
/// </summary>
public T Value => m_AnticipatedValue;
/// <summary>
/// Indicates whether this variable currently needs
/// reanticipation. If this is true, the anticipated value
/// has been overwritten by the authoritative value from the
/// server; the previous anticipated value is stored in <see cref="PreviousAnticipatedState"/>
/// </summary>
public bool ShouldReanticipate
{
get;
private set;
}
/// <summary>
/// Holds the most recent anticipated value, whatever was
/// most recently set using <see cref="Anticipate"/>. Unlike
/// <see cref="Value"/>, this does not get overwritten
/// when a server update arrives.
/// </summary>
public T PreviousAnticipatedValue => m_PreviousAnticipatedValue;
/// <summary>
/// Sets the current value of the variable on the expectation that the authority will set the variable
/// to the same value within one network round trip (i.e., in response to an RPC).
/// </summary>
/// <param name="value"></param>
public void Anticipate(T value)
{
if (m_NetworkBehaviour.NetworkManager.ShutdownInProgress || !m_NetworkBehaviour.NetworkManager.IsListening)
{
return;
}
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
m_LastAnticipationCounter = m_NetworkBehaviour.NetworkManager.AnticipationSystem.AnticipationCounter;
m_AnticipatedValue = value;
NetworkVariableSerialization<T>.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue);
if (CanClientWrite(m_NetworkBehaviour.NetworkManager.LocalClientId))
{
AuthoritativeValue = value;
}
}
#pragma warning disable IDE0001
/// <summary>
/// Retrieves or sets the underlying authoritative value.
/// Note that only a client or server with write permissions to this variable may set this value.
/// When this variable has been anticipated, this value will alawys return the most recent authoritative
/// state, which is updated even if <see cref="StaleDataHandling"/> is <see cref="Netcode.StaleDataHandling.Ignore"/>.
/// </summary>
#pragma warning restore IDE0001
public T AuthoritativeValue
{
get => m_AuthoritativeValue.Value;
set
{
m_SettingAuthoritativeValue = true;
try
{
m_AuthoritativeValue.Value = value;
m_AnticipatedValue = value;
NetworkVariableSerialization<T>.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue);
}
finally
{
m_SettingAuthoritativeValue = false;
}
}
}
/// <summary>
/// A function to interpolate between two values based on a percentage.
/// See <see cref="Mathf.Lerp"/>, <see cref="Vector3.Lerp"/>, <see cref="Vector3.Slerp"/>, and so on
/// for examples.
/// </summary>
public delegate T SmoothDelegate(T authoritativeValue, T anticipatedValue, float amount);
private SmoothDelegate m_SmoothDelegate = null;
public AnticipatedNetworkVariable(T value = default,
StaleDataHandling staleDataHandling = StaleDataHandling.Ignore)
: base()
{
StaleDataHandling = staleDataHandling;
m_AuthoritativeValue = new NetworkVariable<T>(value)
{
OnValueChanged = OnValueChangedInternal
};
}
public void Update()
{
if (m_CurrentSmoothTime < m_SmoothDuration)
{
m_CurrentSmoothTime += m_NetworkBehaviour.NetworkManager.RealTimeProvider.DeltaTime;
var pct = math.min(m_CurrentSmoothTime / m_SmoothDuration, 1f);
m_AnticipatedValue = m_SmoothDelegate(m_SmoothFrom, m_SmoothTo, pct);
NetworkVariableSerialization<T>.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue);
}
}
public override void Dispose()
{
if (m_IsDisposed)
{
return;
}
if (m_NetworkBehaviour != null && m_NetworkBehaviour.NetworkManager != null && m_NetworkBehaviour.NetworkManager.AnticipationSystem != null)
{
if (m_AnticipatedObject != null)
{
m_NetworkBehaviour.NetworkManager.AnticipationSystem.AllAnticipatedObjects.Remove(m_AnticipatedObject);
m_NetworkBehaviour.NetworkManager.AnticipationSystem.ObjectsToReanticipate.Remove(m_AnticipatedObject);
m_AnticipatedObject = null;
}
}
m_IsDisposed = true;
m_AuthoritativeValue.Dispose();
if (m_AnticipatedValue is IDisposable anticipatedValueDisposable)
{
anticipatedValueDisposable.Dispose();
}
m_AnticipatedValue = default;
if (m_PreviousAnticipatedValue is IDisposable previousValueDisposable)
{
previousValueDisposable.Dispose();
m_PreviousAnticipatedValue = default;
}
if (m_HasSmoothValues)
{
if (m_SmoothFrom is IDisposable smoothFromDisposable)
{
smoothFromDisposable.Dispose();
m_SmoothFrom = default;
}
if (m_SmoothTo is IDisposable smoothToDisposable)
{
smoothToDisposable.Dispose();
m_SmoothTo = default;
}
m_HasSmoothValues = false;
}
}
~AnticipatedNetworkVariable()
{
Dispose();
}
private void OnValueChangedInternal(T previousValue, T newValue)
{
if (!m_SettingAuthoritativeValue)
{
m_LastAuthorityUpdateCounter = m_NetworkBehaviour.NetworkManager.AnticipationSystem.LastAnticipationAck;
if (StaleDataHandling == StaleDataHandling.Ignore && m_LastAnticipationCounter > m_LastAuthorityUpdateCounter)
{
// Keep the anticipated value unchanged because it is more recent than the authoritative one.
return;
}
ShouldReanticipate = true;
m_NetworkBehaviour.NetworkManager.AnticipationSystem.ObjectsToReanticipate.Add(m_AnticipatedObject);
}
NetworkVariableSerialization<T>.Duplicate(AuthoritativeValue, ref m_AnticipatedValue);
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
OnAuthoritativeValueChanged?.Invoke(this, previousValue, newValue);
}
/// <summary>
/// Interpolate this variable from <see cref="from"/> to <see cref="to"/> over <see cref="durationSeconds"/> of
/// real time. The duration uses <see cref="Time.deltaTime"/>, so it is affected by <see cref="Time.timeScale"/>.
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
/// <param name="durationSeconds"></param>
/// <param name="how"></param>
public void Smooth(in T from, in T to, float durationSeconds, SmoothDelegate how)
{
if (durationSeconds <= 0)
{
NetworkVariableSerialization<T>.Duplicate(to, ref m_AnticipatedValue);
m_SmoothDuration = 0;
m_CurrentSmoothTime = 0;
m_SmoothDelegate = null;
return;
}
NetworkVariableSerialization<T>.Duplicate(from, ref m_AnticipatedValue);
NetworkVariableSerialization<T>.Duplicate(from, ref m_SmoothFrom);
NetworkVariableSerialization<T>.Duplicate(to, ref m_SmoothTo);
m_SmoothDuration = durationSeconds;
m_CurrentSmoothTime = 0;
m_SmoothDelegate = how;
m_HasSmoothValues = true;
}
public override bool IsDirty()
{
return m_AuthoritativeValue.IsDirty();
}
public override void ResetDirty()
{
m_AuthoritativeValue.ResetDirty();
}
public override void WriteDelta(FastBufferWriter writer)
{
m_AuthoritativeValue.WriteDelta(writer);
}
public override void WriteField(FastBufferWriter writer)
{
m_AuthoritativeValue.WriteField(writer);
}
public override void ReadField(FastBufferReader reader)
{
m_AuthoritativeValue.ReadField(reader);
NetworkVariableSerialization<T>.Duplicate(m_AuthoritativeValue.Value, ref m_AnticipatedValue);
NetworkVariableSerialization<T>.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue);
}
public override void ReadDelta(FastBufferReader reader, bool keepDirtyDelta)
{
m_AuthoritativeValue.ReadDelta(reader, keepDirtyDelta);
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: fc9fd5701bee8534a971eb9f49178e21

View File

@@ -94,18 +94,18 @@ namespace Unity.Netcode
{
case NetworkListEvent<T>.EventType.Add:
{
NetworkVariableSerialization<T>.Write(writer, ref element.Value);
NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
}
break;
case NetworkListEvent<T>.EventType.Insert:
{
BytePacker.WriteValueBitPacked(writer, element.Index);
NetworkVariableSerialization<T>.Write(writer, ref element.Value);
NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
}
break;
case NetworkListEvent<T>.EventType.Remove:
{
NetworkVariableSerialization<T>.Write(writer, ref element.Value);
NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
}
break;
case NetworkListEvent<T>.EventType.RemoveAt:
@@ -116,7 +116,7 @@ namespace Unity.Netcode
case NetworkListEvent<T>.EventType.Value:
{
BytePacker.WriteValueBitPacked(writer, element.Index);
NetworkVariableSerialization<T>.Write(writer, ref element.Value);
NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
}
break;
case NetworkListEvent<T>.EventType.Clear:
@@ -133,13 +133,13 @@ namespace Unity.Netcode
{
if (m_NetworkManager.DistributedAuthorityMode)
{
writer.WriteValueSafe(NetworkVariableSerialization<T>.Type);
if (NetworkVariableSerialization<T>.Type == CollectionItemType.Unmanaged)
writer.WriteValueSafe(NetworkVariableSerialization<T>.Serializer.Type);
if (NetworkVariableSerialization<T>.Serializer.Type == NetworkVariableType.Unmanaged)
{
// Write the size of the unmanaged serialized type as it has a fixed size. This allows the CMB runtime to correctly read the unmanged type.
var placeholder = new T();
var startPos = writer.Position;
NetworkVariableSerialization<T>.Write(writer, ref placeholder);
NetworkVariableSerialization<T>.Serializer.Write(writer, ref placeholder);
var size = writer.Position - startPos;
writer.Seek(startPos);
BytePacker.WriteValueBitPacked(writer, size);
@@ -148,7 +148,7 @@ namespace Unity.Netcode
writer.WriteValueSafe((ushort)m_List.Length);
for (int i = 0; i < m_List.Length; i++)
{
NetworkVariableSerialization<T>.Write(writer, ref m_List.ElementAt(i));
NetworkVariableSerialization<T>.Serializer.Write(writer, ref m_List.ElementAt(i));
}
}
@@ -158,9 +158,9 @@ namespace Unity.Netcode
m_List.Clear();
if (m_NetworkManager.DistributedAuthorityMode)
{
// Collection item type is used by the CMB rust service, drop value here.
reader.ReadValueSafe(out CollectionItemType type);
if (type == CollectionItemType.Unmanaged)
SerializationTools.ReadType(reader, NetworkVariableSerialization<T>.Serializer);
// Collection item type is used by the DA server, drop value here.
if (NetworkVariableSerialization<T>.Serializer.Type == NetworkVariableType.Unmanaged)
{
ByteUnpacker.ReadValueBitPacked(reader, out int _);
}
@@ -169,7 +169,7 @@ namespace Unity.Netcode
for (int i = 0; i < count; i++)
{
var value = new T();
NetworkVariableSerialization<T>.Read(reader, ref value);
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
m_List.Add(value);
}
}
@@ -186,7 +186,7 @@ namespace Unity.Netcode
case NetworkListEvent<T>.EventType.Add:
{
var value = new T();
NetworkVariableSerialization<T>.Read(reader, ref value);
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
m_List.Add(value);
if (OnListChanged != null)
@@ -215,7 +215,7 @@ namespace Unity.Netcode
{
ByteUnpacker.ReadValueBitPacked(reader, out int index);
var value = new T();
NetworkVariableSerialization<T>.Read(reader, ref value);
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
if (index < m_List.Length)
{
@@ -252,7 +252,7 @@ namespace Unity.Netcode
case NetworkListEvent<T>.EventType.Remove:
{
var value = new T();
NetworkVariableSerialization<T>.Read(reader, ref value);
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
int index = m_List.IndexOf(value);
if (index == -1)
{
@@ -315,7 +315,7 @@ namespace Unity.Netcode
{
ByteUnpacker.ReadValueBitPacked(reader, out int index);
var value = new T();
NetworkVariableSerialization<T>.Read(reader, ref value);
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
if (index >= m_List.Length)
{
throw new Exception("Shouldn't be here, index is higher than list length");
@@ -393,7 +393,8 @@ namespace Unity.Netcode
// check write permissions
if (!CanClientWrite(m_NetworkManager.LocalClientId))
{
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
LogWritePermissionError();
return;
}
m_List.Add(item);
@@ -414,7 +415,8 @@ namespace Unity.Netcode
// check write permissions
if (!CanClientWrite(m_NetworkManager.LocalClientId))
{
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
LogWritePermissionError();
return;
}
m_List.Clear();
@@ -440,7 +442,8 @@ namespace Unity.Netcode
// check write permissions
if (!CanClientWrite(m_NetworkManager.LocalClientId))
{
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
LogWritePermissionError();
return false;
}
int index = m_List.IndexOf(item);
@@ -475,7 +478,8 @@ namespace Unity.Netcode
// check write permissions
if (!CanClientWrite(m_NetworkManager.LocalClientId))
{
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
LogWritePermissionError();
return;
}
if (index < m_List.Length)
@@ -520,6 +524,8 @@ namespace Unity.Netcode
HandleAddListEvent(listEvent);
}
/// <inheritdoc />
public T this[int index]
{
@@ -529,7 +535,8 @@ namespace Unity.Netcode
// check write permissions
if (!CanClientWrite(m_NetworkManager.LocalClientId))
{
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
LogWritePermissionError();
return;
}
var previousValue = m_List[index];

View File

@@ -21,6 +21,29 @@ namespace Unity.Netcode
/// The callback to be invoked when the value gets changed
/// </summary>
public OnValueChangedDelegate OnValueChanged;
public delegate bool CheckExceedsDirtinessThresholdDelegate(in T previousValue, in T newValue);
public CheckExceedsDirtinessThresholdDelegate CheckExceedsDirtinessThreshold;
public override bool ExceedsDirtinessThreshold()
{
if (CheckExceedsDirtinessThreshold != null && m_HasPreviousValue)
{
return CheckExceedsDirtinessThreshold(m_PreviousValue, m_InternalValue);
}
return true;
}
public override void OnInitialize()
{
base.OnInitialize();
m_HasPreviousValue = true;
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_PreviousValue);
}
internal override NetworkVariableType Type => NetworkVariableType.Value;
/// <summary>
@@ -71,25 +94,57 @@ namespace Unity.Netcode
/// <summary>
/// The value of the NetworkVariable container
/// </summary>
/// <remarks>
/// When assigning collections to <see cref="Value"/>, unless it is a completely new collection this will not
/// detect any deltas with most managed collection classes since assignment of one collection value to another
/// is actually just a reference to the collection itself. <br />
/// To detect deltas in a collection, you should invoke <see cref="CheckDirtyState"/> after making modifications to the collection.
/// </remarks>
public virtual T Value
{
get => m_InternalValue;
set
{
// Compare bitwise
if (NetworkVariableSerialization<T>.AreEqual(ref m_InternalValue, ref value))
if (m_NetworkManager && !CanClientWrite(m_NetworkManager.LocalClientId))
{
LogWritePermissionError();
return;
}
if (m_NetworkManager && !CanClientWrite(m_NetworkManager.LocalClientId))
// Compare the Value being applied to the current value
if (!NetworkVariableSerialization<T>.AreEqual(ref m_InternalValue, ref value))
{
throw new InvalidOperationException($"[Client-{m_NetworkManager.LocalClientId}][{m_NetworkBehaviour.name}][{Name}] Write permissions ({WritePerm}) for this client instance is not allowed!");
T previousValue = m_InternalValue;
m_InternalValue = value;
SetDirty(true);
m_IsDisposed = false;
OnValueChanged?.Invoke(previousValue, m_InternalValue);
}
}
}
Set(value);
/// <summary>
/// Invoke this method to check if a collection's items are dirty.
/// The default behavior is to exit early if the <see cref="NetworkVariable{T}"/> is already dirty.
/// </summary>
/// <param name="forceCheck"> when true, this check will force a full item collection check even if the NetworkVariable is already dirty</param>
/// <remarks>
/// This is to be used as a way to check if a <see cref="NetworkVariable{T}"/> containing a managed collection has any changees to the collection items.<br />
/// If you invoked this when a collection is dirty, it will not trigger the <see cref="OnValueChanged"/> unless you set <param name="forceCheck"/> to true. <br />
/// </remarks>
public bool CheckDirtyState(bool forceCheck = false)
{
var isDirty = base.IsDirty();
// Compare the previous with the current if not dirty or forcing a check.
if ((!isDirty || forceCheck) && !NetworkVariableSerialization<T>.AreEqual(ref m_PreviousValue, ref m_InternalValue))
{
SetDirty(true);
OnValueChanged?.Invoke(m_PreviousValue, m_InternalValue);
m_IsDisposed = false;
isDirty = true;
}
return isDirty;
}
internal ref T RefValue()
@@ -170,19 +225,6 @@ namespace Unity.Netcode
base.ResetDirty();
}
/// <summary>
/// Sets the <see cref="Value"/>, marks the <see cref="NetworkVariable{T}"/> dirty, and invokes the <see cref="OnValueChanged"/> callback
/// if there are subscribers to that event.
/// </summary>
/// <param name="value">the new value of type `T` to be set/></param>
private protected void Set(T value)
{
SetDirty(true);
T previousValue = m_InternalValue;
m_InternalValue = value;
OnValueChanged?.Invoke(previousValue, m_InternalValue);
}
/// <summary>
/// Writes the variable to the writer
/// </summary>
@@ -199,20 +241,22 @@ namespace Unity.Netcode
/// <param name="keepDirtyDelta">Whether or not the container should keep the dirty delta, or mark the delta as consumed</param>
public override void ReadDelta(FastBufferReader reader, bool keepDirtyDelta)
{
// In order to get managed collections to properly have a previous and current value, we have to
// duplicate the collection at this point before making any modifications to the current.
m_HasPreviousValue = true;
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_PreviousValue);
NetworkVariableSerialization<T>.ReadDelta(reader, ref m_InternalValue);
// todo:
// keepDirtyDelta marks a variable received as dirty and causes the server to send the value to clients
// In a prefect world, whether a variable was A) modified locally or B) received and needs retransmit
// would be stored in different fields
T previousValue = m_InternalValue;
NetworkVariableSerialization<T>.ReadDelta(reader, ref m_InternalValue);
if (keepDirtyDelta)
{
SetDirty(true);
}
OnValueChanged?.Invoke(previousValue, m_InternalValue);
OnValueChanged?.Invoke(m_PreviousValue, m_InternalValue);
}
/// <inheritdoc />

View File

@@ -3,11 +3,26 @@ using UnityEngine;
namespace Unity.Netcode
{
public struct NetworkVariableUpdateTraits
{
[Tooltip("The minimum amount of time that must pass between sending updates. If this amount of time has not passed since the last update, dirtiness will be ignored.")]
public float MinSecondsBetweenUpdates;
[Tooltip("The maximum amount of time that a variable can be dirty without sending an update. If this amount of time has passed since the last update, an update will be sent even if the dirtiness threshold has not been met.")]
public float MaxSecondsBetweenUpdates;
}
/// <summary>
/// Interface for network value containers
/// </summary>
public abstract class NetworkVariableBase : IDisposable
{
[SerializeField]
internal NetworkVariableUpdateTraits UpdateTraits = default;
[NonSerialized]
internal double LastUpdateSent;
/// <summary>
/// The delivery type (QoS) to send data with
/// </summary>
@@ -20,7 +35,17 @@ namespace Unity.Netcode
private NetworkManager m_InternalNetworkManager;
internal virtual NetworkVariableType Type => NetworkVariableType.Custom;
internal virtual NetworkVariableType Type => NetworkVariableType.Unknown;
internal string GetWritePermissionError()
{
return $"|Client-{m_NetworkManager.LocalClientId}|{m_NetworkBehaviour.name}|{Name}| Write permissions ({WritePerm}) for this client instance is not allowed!";
}
internal void LogWritePermissionError()
{
Debug.LogError(GetWritePermissionError());
}
private protected NetworkManager m_NetworkManager
{
@@ -52,9 +77,44 @@ namespace Unity.Netcode
m_InternalNetworkManager = m_NetworkBehaviour.NetworkObject?.NetworkManager;
// When in distributed authority mode, there is no such thing as server write permissions
InternalWritePerm = m_InternalNetworkManager.DistributedAuthorityMode ? NetworkVariableWritePermission.Owner : InternalWritePerm;
if (m_NetworkBehaviour.NetworkManager.NetworkTimeSystem != null)
{
UpdateLastSentTime();
}
}
OnInitialize();
}
/// <summary>
/// Called on initialization
/// </summary>
public virtual void OnInitialize()
{
}
/// <summary>
/// Sets the update traits for this network variable to determine how frequently it will send updates.
/// </summary>
/// <param name="traits"></param>
public void SetUpdateTraits(NetworkVariableUpdateTraits traits)
{
UpdateTraits = traits;
}
/// <summary>
/// Check whether or not this variable has changed significantly enough to send an update.
/// If not, no update will be sent even if the variable is dirty, unless the time since last update exceeds
/// the <see cref="UpdateTraits"/>' <see cref="NetworkVariableUpdateTraits.MaxSecondsBetweenUpdates"/>.
/// </summary>
/// <returns></returns>
public virtual bool ExceedsDirtinessThreshold()
{
return true;
}
/// <summary>
/// The default read permissions
/// </summary>
@@ -125,6 +185,25 @@ namespace Unity.Netcode
}
}
internal bool CanSend()
{
var timeSinceLastUpdate = m_NetworkBehaviour.NetworkManager.NetworkTimeSystem.LocalTime - LastUpdateSent;
return
(
UpdateTraits.MaxSecondsBetweenUpdates > 0 &&
timeSinceLastUpdate >= UpdateTraits.MaxSecondsBetweenUpdates
) ||
(
timeSinceLastUpdate >= UpdateTraits.MinSecondsBetweenUpdates &&
ExceedsDirtinessThreshold()
);
}
internal void UpdateLastSentTime()
{
LastUpdateSent = m_NetworkBehaviour.NetworkManager.NetworkTimeSystem.LocalTime;
}
internal static bool IgnoreInitializeWarning;
protected void MarkNetworkBehaviourDirty()
@@ -147,6 +226,17 @@ namespace Unity.Netcode
}
return;
}
if (!m_NetworkBehaviour.NetworkManager.IsListening)
{
if (m_NetworkBehaviour.NetworkManager.LogLevel <= LogLevel.Developer)
{
Debug.LogWarning($"NetworkVariable is written to after the NetworkManager has already shutdown! " +
"Are you modifying a NetworkVariable within a NetworkBehaviour.OnDestroy or NetworkBehaviour.OnDespawn method?");
}
return;
}
m_NetworkBehaviour.NetworkManager.BehaviourUpdater?.AddForUpdate(m_NetworkBehaviour.NetworkObject);
}
@@ -174,6 +264,11 @@ namespace Unity.Netcode
/// <returns>Whether or not the client has permission to read</returns>
public bool CanClientRead(ulong clientId)
{
if (!m_NetworkBehaviour)
{
return false;
}
// When in distributed authority mode, everyone can read (but only the owner can write)
if (m_NetworkManager != null && m_NetworkManager.DistributedAuthorityMode)
{
@@ -196,6 +291,11 @@ namespace Unity.Netcode
/// <returns>Whether or not the client has permission to write</returns>
public bool CanClientWrite(ulong clientId)
{
if (!m_NetworkBehaviour)
{
return false;
}
switch (WritePerm)
{
default:
@@ -231,7 +331,6 @@ namespace Unity.Netcode
/// </summary>
/// <param name="reader">The stream to read the state from</param>
public abstract void ReadField(FastBufferReader reader);
/// <summary>
/// Reads delta from the reader and applies them to the internal value
/// </summary>
@@ -247,47 +346,4 @@ namespace Unity.Netcode
m_InternalNetworkManager = null;
}
}
/// <summary>
/// Enum representing the different types of Network Variables.
/// </summary>
public enum NetworkVariableType : byte
{
/// <summary>
/// Value
/// Used for all of the basic NetworkVariables that contain a single value
/// </summary>
Value = 0,
/// <summary>
/// Custom
/// For any custom implemented extension of the NetworkVariableBase
/// </summary>
Custom = 1,
/// <summary>
/// NetworkList
/// </summary>
NetworkList = 2
}
public enum CollectionItemType : byte
{
/// <summary>
/// For any type that is not valid inside a NetworkVariable collection
/// </summary>
Unknown = 0,
/// <summary>
/// The following types are valid types inside of NetworkVariable collections
/// </summary>
Short = 1,
UShort = 2,
Int = 3,
UInt = 4,
Long = 5,
ULong = 6,
Unmanaged = 7,
}
}

View File

@@ -0,0 +1,40 @@
#if UNITY_EDITOR
#endif
namespace Unity.Netcode
{
/// <summary>
/// Enum representing the different types of Network Variables that can be sent over the network.
/// The values cannot be changed, as they are used to serialize and deserialize variables on the DA server.
/// Adding new variables should be done by adding new values to the end of the enum
/// using the next free value.
/// </summary>
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/// Add any new Variable types to this table at the END with incremented index value
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
internal enum NetworkVariableType : byte
{
/// <summary>
/// Value
/// Used for all of the basic NetworkVariables that contain a single value
/// </summary>
Value = 0,
/// <summary>
/// For any type that is not known at runtime
/// </summary>
Unknown = 1,
/// <summary>
/// NetworkList
/// </summary>
NetworkList = 2,
// The following types are valid types inside of NetworkVariable collections
Short = 11,
UShort = 12,
Int = 13,
UInt = 14,
Long = 15,
ULong = 16,
Unmanaged = 17,
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: df4a4005f1c842669f94a404019400ed
timeCreated: 1718292058

View File

@@ -14,6 +14,9 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class FallbackSerializer<T> : INetworkVariableSerializer<T>
{
public NetworkVariableType Type => NetworkVariableType.Unknown;
public bool IsDistributedAuthorityOptimized => true;
private void ThrowArgumentError()
{
throw new ArgumentException($"Serialization has not been generated for type {typeof(T).FullName}. This can be addressed by adding a [{nameof(GenerateSerializationForGenericParameterAttribute)}] to your generic class that serializes this value (if you are using one), adding [{nameof(GenerateSerializationForTypeAttribute)}(typeof({typeof(T).FullName})] to the class or method that is attempting to serialize it, or creating a field on a {nameof(NetworkBehaviour)} of type {nameof(NetworkVariable<T>)}. If this error continues to appear after doing one of those things and this is a type you can change, then either implement {nameof(INetworkSerializable)} or mark it as serializable by memcpy by adding {nameof(INetworkSerializeByMemcpy)} to its interface list to enable automatic serialization generation. If not, assign serialization code to {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.WriteValue)}, {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.ReadValue)}, and {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.DuplicateValue)}, or if it's serializable by memcpy (contains no pointers), wrap it in {typeof(ForceNetworkSerializeByMemcpy<>).Name}.");
@@ -79,6 +82,11 @@ namespace Unity.Netcode
}
UserNetworkVariableSerialization<T>.DuplicateValue(value, ref duplicatedValue);
}
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value) => ThrowArgumentError();
public void ReadDistributedAuthority(FastBufferReader reader, ref T value) => ThrowArgumentError();
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => ThrowArgumentError();
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => ThrowArgumentError();
}
// RuntimeAccessModifiersILPP will make this `public`

View File

@@ -3,11 +3,27 @@ using Unity.Collections;
namespace Unity.Netcode
{
/// <summary>
/// Interface used by NetworkVariables to serialize them
/// Interface used by NetworkVariables to serialize them with additional information for the DA runtime
/// </summary>
///
/// <typeparam name="T"></typeparam>
internal interface INetworkVariableSerializer<T>
internal interface IDistributedAuthoritySerializer<T>
{
/// <summary>
/// The Type tells the DA server how to parse this type.
/// The user should never be able to override this value, as it is meaningful for the DA server
/// </summary>
public NetworkVariableType Type { get; }
public bool IsDistributedAuthorityOptimized { get; }
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value);
public void ReadDistributedAuthority(FastBufferReader reader, ref T value);
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value);
}
/// <typeparam name="T"></typeparam>
internal interface INetworkVariableSerializer<T> : IDistributedAuthoritySerializer<T>
{
// Write has to be taken by ref here because of INetworkSerializable
// Open Instance Delegates (pointers to methods without an instance attached to them)

View File

@@ -16,12 +16,6 @@ namespace Unity.Netcode
internal static bool IsDistributedAuthority => NetworkManager.IsDistributedAuthority;
/// <summary>
/// The collection item type tells the CMB server how to read the bytes of each item in the collection
/// </summary>
/// DANGO-EXP TODO: Determine if this is distributed authority only and impacts of this in client-server
internal static CollectionItemType Type = CollectionItemType.Unknown;
/// <summary>
/// A callback to check if two values are equal.
/// </summary>
@@ -58,9 +52,22 @@ namespace Unity.Netcode
/// <param name="writer"></param>
/// <param name="value"></param>
public static void Write(FastBufferWriter writer, ref T value)
{
if (IsDistributedAuthority)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (!NetworkManager.DisableNotOptimizedSerializedType && !Serializer.IsDistributedAuthorityOptimized)
{
NetworkManager.LogSerializedTypeNotOptimized<T>();
}
#endif
Serializer.WriteDistributedAuthority(writer, ref value);
}
else
{
Serializer.Write(writer, ref value);
}
}
/// <summary>
/// Deserialize a value using the best-known serialization method for a generic value.
@@ -83,9 +90,16 @@ namespace Unity.Netcode
/// <param name="reader"></param>
/// <param name="value"></param>
public static void Read(FastBufferReader reader, ref T value)
{
if (IsDistributedAuthority)
{
Serializer.ReadDistributedAuthority(reader, ref value);
}
else
{
Serializer.Read(reader, ref value);
}
}
/// <summary>
/// Serialize a value using the best-known serialization method for a generic value.
@@ -105,9 +119,22 @@ namespace Unity.Netcode
/// <param name="writer"></param>
/// <param name="value"></param>
public static void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue)
{
if (IsDistributedAuthority)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (!NetworkManager.DisableNotOptimizedSerializedType && !Serializer.IsDistributedAuthorityOptimized)
{
NetworkManager.LogSerializedTypeNotOptimized<T>();
}
#endif
Serializer.WriteDeltaDistributedAuthority(writer, ref value, ref previousValue);
}
else
{
Serializer.WriteDelta(writer, ref value, ref previousValue);
}
}
/// <summary>
/// Deserialize a value using the best-known serialization method for a generic value.
@@ -130,9 +157,16 @@ namespace Unity.Netcode
/// <param name="reader"></param>
/// <param name="value"></param>
public static void ReadDelta(FastBufferReader reader, ref T value)
{
if (IsDistributedAuthority)
{
Serializer.ReadDeltaDistributedAuthority(reader, ref value);
}
else
{
Serializer.ReadDelta(reader, ref value);
}
}
/// <summary>
/// Duplicates a value using the most efficient means of creating a complete copy.

View File

@@ -38,14 +38,6 @@ namespace Unity.Netcode
NetworkVariableSerialization<long>.AreEqual = NetworkVariableEquality<long>.ValueEquals;
NetworkVariableSerialization<ulong>.Serializer = new UlongSerializer();
NetworkVariableSerialization<ulong>.AreEqual = NetworkVariableEquality<ulong>.ValueEquals;
// DANGO-EXP TODO: Determine if this is distributed authority only and impacts of this in client-server
NetworkVariableSerialization<short>.Type = CollectionItemType.Short;
NetworkVariableSerialization<ushort>.Type = CollectionItemType.UShort;
NetworkVariableSerialization<int>.Type = CollectionItemType.Int;
NetworkVariableSerialization<uint>.Type = CollectionItemType.UInt;
NetworkVariableSerialization<long>.Type = CollectionItemType.Long;
NetworkVariableSerialization<ulong>.Type = CollectionItemType.ULong;
}
/// <summary>
@@ -55,8 +47,6 @@ namespace Unity.Netcode
public static void InitializeSerializer_UnmanagedByMemcpy<T>() where T : unmanaged
{
NetworkVariableSerialization<T>.Serializer = new UnmanagedTypeSerializer<T>();
// DANGO-EXP TODO: Determine if this is distributed authority only and impacts of this in client-server
NetworkVariableSerialization<T>.Type = CollectionItemType.Unmanaged;
}
/// <summary>

View File

@@ -10,6 +10,21 @@ namespace Unity.Netcode
/// </summary>
internal class ShortSerializer : INetworkVariableSerializer<short>
{
public NetworkVariableType Type => NetworkVariableType.Short;
public bool IsDistributedAuthorityOptimized => true;
public void WriteDistributedAuthority(FastBufferWriter writer, ref short value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref short value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref short value, ref short previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref short value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref short value)
{
BytePacker.WriteValueBitPacked(writer, value);
@@ -46,6 +61,20 @@ namespace Unity.Netcode
/// </summary>
internal class UshortSerializer : INetworkVariableSerializer<ushort>
{
public NetworkVariableType Type => NetworkVariableType.UShort;
public bool IsDistributedAuthorityOptimized => true;
public void WriteDistributedAuthority(FastBufferWriter writer, ref ushort value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref ushort value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref ushort value, ref ushort previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref ushort value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref ushort value)
{
BytePacker.WriteValueBitPacked(writer, value);
@@ -82,6 +111,20 @@ namespace Unity.Netcode
/// </summary>
internal class IntSerializer : INetworkVariableSerializer<int>
{
public NetworkVariableType Type => NetworkVariableType.Int;
public bool IsDistributedAuthorityOptimized => true;
public void WriteDistributedAuthority(FastBufferWriter writer, ref int value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref int value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref int value, ref int previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref int value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref int value)
{
BytePacker.WriteValueBitPacked(writer, value);
@@ -118,6 +161,20 @@ namespace Unity.Netcode
/// </summary>
internal class UintSerializer : INetworkVariableSerializer<uint>
{
public NetworkVariableType Type => NetworkVariableType.UInt;
public bool IsDistributedAuthorityOptimized => true;
public void WriteDistributedAuthority(FastBufferWriter writer, ref uint value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref uint value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref uint value, ref uint previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref uint value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref uint value)
{
BytePacker.WriteValueBitPacked(writer, value);
@@ -154,6 +211,20 @@ namespace Unity.Netcode
/// </summary>
internal class LongSerializer : INetworkVariableSerializer<long>
{
public NetworkVariableType Type => NetworkVariableType.Long;
public bool IsDistributedAuthorityOptimized => true;
public void WriteDistributedAuthority(FastBufferWriter writer, ref long value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref long value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref long value, ref long previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref long value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref long value)
{
BytePacker.WriteValueBitPacked(writer, value);
@@ -190,6 +261,21 @@ namespace Unity.Netcode
/// </summary>
internal class UlongSerializer : INetworkVariableSerializer<ulong>
{
public NetworkVariableType Type => NetworkVariableType.ULong;
public bool IsDistributedAuthorityOptimized => true;
public void WriteDistributedAuthority(FastBufferWriter writer, ref ulong value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref ulong value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref ulong value, ref ulong previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref ulong value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref ulong value)
{
BytePacker.WriteValueBitPacked(writer, value);
@@ -231,6 +317,21 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class UnmanagedTypeSerializer<T> : INetworkVariableSerializer<T> where T : unmanaged
{
public NetworkVariableType Type => NetworkVariableType.Unmanaged;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref T value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref T value)
{
writer.WriteUnmanagedSafe(value);
@@ -264,6 +365,20 @@ namespace Unity.Netcode
internal class ListSerializer<T> : INetworkVariableSerializer<List<T>>
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref List<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref List<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref List<T> value, ref List<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref List<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref List<T> value)
{
var isNull = value == null;
@@ -343,13 +458,30 @@ namespace Unity.Netcode
duplicatedValue.Clear();
foreach (var item in value)
{
duplicatedValue.Add(item);
// This handles the nested list scenario List<List<T>>
T subValue = default;
NetworkVariableSerialization<T>.Duplicate(item, ref subValue);
duplicatedValue.Add(subValue);
}
}
}
internal class HashSetSerializer<T> : INetworkVariableSerializer<HashSet<T>> where T : IEquatable<T>
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref HashSet<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref HashSet<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref HashSet<T> value, ref HashSet<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref HashSet<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref HashSet<T> value)
{
var isNull = value == null;
@@ -419,6 +551,9 @@ namespace Unity.Netcode
duplicatedValue.Clear();
foreach (var item in value)
{
// Handles nested HashSets
T subValue = default;
NetworkVariableSerialization<T>.Duplicate(item, ref subValue);
duplicatedValue.Add(item);
}
}
@@ -428,6 +563,20 @@ namespace Unity.Netcode
internal class DictionarySerializer<TKey, TVal> : INetworkVariableSerializer<Dictionary<TKey, TVal>>
where TKey : IEquatable<TKey>
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref Dictionary<TKey, TVal> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref Dictionary<TKey, TVal> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref Dictionary<TKey, TVal> value, ref Dictionary<TKey, TVal> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref Dictionary<TKey, TVal> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref Dictionary<TKey, TVal> value)
{
var isNull = value == null;
@@ -498,13 +647,32 @@ namespace Unity.Netcode
duplicatedValue.Clear();
foreach (var item in value)
{
duplicatedValue.Add(item.Key, item.Value);
// Handles nested dictionaries
TKey subKey = default;
TVal subValue = default;
NetworkVariableSerialization<TKey>.Duplicate(item.Key, ref subKey);
NetworkVariableSerialization<TVal>.Duplicate(item.Value, ref subValue);
duplicatedValue.Add(subKey, subValue);
}
}
}
internal class UnmanagedArraySerializer<T> : INetworkVariableSerializer<NativeArray<T>> where T : unmanaged
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value, ref NativeArray<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeArray<T> value)
{
writer.WriteUnmanagedSafe(value);
@@ -550,6 +718,20 @@ namespace Unity.Netcode
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
internal class UnmanagedListSerializer<T> : INetworkVariableSerializer<NativeList<T>> where T : unmanaged
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeList<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value, ref NativeList<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeList<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeList<T> value)
{
writer.WriteUnmanagedSafe(value);
@@ -593,6 +775,21 @@ namespace Unity.Netcode
internal class NativeHashSetSerializer<T> : INetworkVariableSerializer<NativeHashSet<T>> where T : unmanaged, IEquatable<T>
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeHashSet<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeHashSet<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeHashSet<T> value, ref NativeHashSet<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeHashSet<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeHashSet<T> value)
{
writer.WriteValueSafe(value);
@@ -638,6 +835,21 @@ namespace Unity.Netcode
where TKey : unmanaged, IEquatable<TKey>
where TVal : unmanaged
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeHashMap<TKey, TVal> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeHashMap<TKey, TVal> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeHashMap<TKey, TVal> value, ref NativeHashMap<TKey, TVal> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeHashMap<TKey, TVal> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeHashMap<TKey, TVal> value)
{
writer.WriteValueSafe(value);
@@ -685,7 +897,20 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class FixedStringSerializer<T> : INetworkVariableSerializer<T> where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
// The item type can only be bytes for fixedStrings, so the DA runtime doesn't need details on it
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref T value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref T value)
{
@@ -710,7 +935,7 @@ namespace Unity.Netcode
{
var val = value[i];
var prevVal = previousValue[i];
if (!NetworkVariableSerialization<byte>.AreEqual(ref val, ref prevVal))
if (val != prevVal)
{
++numChanges;
changes.Set(i);
@@ -731,23 +956,15 @@ namespace Unity.Netcode
return;
}
writer.WriteByte(0); // Flag that we're sending a delta
writer.WriteByteSafe(0); // Flag that we're sending a delta
BytePacker.WriteValuePacked(writer, value.Length);
writer.WriteValueSafe(changes);
var ptr = value.GetUnsafePtr();
var prevPtr = previousValue.GetUnsafePtr();
for (var i = 0; i < value.Length; ++i)
{
if (changes.IsSet(i))
{
if (i < previousValue.Length)
{
NetworkVariableSerialization<byte>.WriteDelta(writer, ref ptr[i], ref prevPtr[i]);
}
else
{
NetworkVariableSerialization<byte>.Write(writer, ref ptr[i]);
}
writer.WriteByteSafe(ptr[i]);
}
}
}
@@ -779,7 +996,7 @@ namespace Unity.Netcode
{
if (changes.IsSet(i))
{
reader.ReadByte(out ptr[i]);
reader.ReadByteSafe(out ptr[i]);
}
}
}
@@ -802,6 +1019,20 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class FixedStringArraySerializer<T> : INetworkVariableSerializer<NativeArray<T>> where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value, ref NativeArray<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeArray<T> value)
{
writer.WriteValueSafe(value);
@@ -852,6 +1083,21 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class FixedStringListSerializer<T> : INetworkVariableSerializer<NativeList<T>> where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeList<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value, ref NativeList<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeList<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeList<T> value)
{
writer.WriteValueSafe(value);
@@ -899,6 +1145,21 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class UnmanagedNetworkSerializableSerializer<T> : INetworkVariableSerializer<T> where T : unmanaged, INetworkSerializable
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref T value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref T value)
{
var bufferSerializer = new BufferSerializer<BufferSerializerWriter>(new BufferSerializerWriter(writer));
@@ -951,6 +1212,20 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class UnmanagedNetworkSerializableArraySerializer<T> : INetworkVariableSerializer<NativeArray<T>> where T : unmanaged, INetworkSerializable
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value, ref NativeArray<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeArray<T> value)
{
writer.WriteNetworkSerializable(value);
@@ -1001,6 +1276,21 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class UnmanagedNetworkSerializableListSerializer<T> : INetworkVariableSerializer<NativeList<T>> where T : unmanaged, INetworkSerializable
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeList<T> value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value, ref NativeList<T> previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeList<T> value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref NativeList<T> value)
{
writer.WriteNetworkSerializable(value);
@@ -1048,6 +1338,20 @@ namespace Unity.Netcode
/// <typeparam name="T"></typeparam>
internal class ManagedNetworkSerializableSerializer<T> : INetworkVariableSerializer<T> where T : class, INetworkSerializable, new()
{
public NetworkVariableType Type => NetworkVariableType.Value;
public bool IsDistributedAuthorityOptimized => false;
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value)
{
Write(writer, ref value);
}
public void ReadDistributedAuthority(FastBufferReader reader, ref T value)
{
Read(reader, ref value);
}
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => Write(writer, ref value);
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => Read(reader, ref value);
public void Write(FastBufferWriter writer, ref T value)
{
var bufferSerializer = new BufferSerializer<BufferSerializerWriter>(new BufferSerializerWriter(writer));

View File

@@ -0,0 +1,54 @@
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
namespace Unity.Netcode
{
internal static class SerializationTools
{
public delegate void WriteDelegate<T>(FastBufferWriter writer, ref T value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteWithSize<T>(WriteDelegate<T> writeMethod, FastBufferWriter writer, ref T value)
{
var writePos = writer.Position;
// Note: This value can't be packed because we don't know how large it will be in advance
// we reserve space for it, then write the data, then come back and fill in the space
// to pack here, we'd have to write data to a temporary buffer and copy it in - which
// isn't worth possibly saving one byte if and only if the data is less than 63 bytes long...
// The way we do packing, any value > 63 in a ushort will use the full 2 bytes to represent.
writer.WriteValueSafe((ushort)0);
var startPos = writer.Position;
writeMethod(writer, ref value);
var size = writer.Position - startPos;
writer.Seek(writePos);
writer.WriteValueSafe((ushort)size);
writer.Seek(startPos + size);
}
public delegate void ReadDelegate<T>(FastBufferReader writer, ref T value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ReadWithSize<T>(ReadDelegate<T> readMethod, FastBufferReader reader, ref T value)
{
reader.ReadValueSafe(out ushort _);
readMethod(reader, ref value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteType(FastBufferWriter writer, NetworkVariableType type) => writer.WriteValueSafe(type);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ReadType<T>(FastBufferReader reader, INetworkVariableSerializer<T> serializer)
{
reader.ReadValueSafe(out NetworkVariableType type);
if (type != serializer.Type)
{
throw new SerializationException();
}
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 52a4ce368df54b0a8887c08f3402bcd3
timeCreated: 1718300602

View File

@@ -227,6 +227,11 @@ namespace Unity.Netcode
foreach (var sceneToUnload in m_ScenesToUnload)
{
SceneManager.UnloadSceneAsync(sceneToUnload);
// Update the ScenesLoaded when we unload scenes
if (sceneManager.ScenesLoaded.ContainsKey(sceneToUnload.handle))
{
sceneManager.ScenesLoaded.Remove(sceneToUnload.handle);
}
}
}
@@ -328,8 +333,9 @@ namespace Unity.Netcode
public void SetClientSynchronizationMode(ref NetworkManager networkManager, LoadSceneMode mode)
{
var sceneManager = networkManager.SceneManager;
// Don't let non-authority set this value
if ((!networkManager.DistributedAuthorityMode && !networkManager.IsServer) || (networkManager.DistributedAuthorityMode && !networkManager.LocalClient.IsSessionOwner))
// In client-server, we don't let client's set this value.
// In distributed authority, since session owner can be promoted clients can set this value
if (!networkManager.DistributedAuthorityMode && !networkManager.IsServer)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
{
@@ -338,7 +344,7 @@ namespace Unity.Netcode
return;
}
else // Warn users if they are changing this after there are clients already connected and synchronized
if (networkManager.ConnectedClientsIds.Count > (networkManager.IsHost ? 1 : 0) && sceneManager.ClientSynchronizationMode != mode)
if (!networkManager.DistributedAuthorityMode && networkManager.ConnectedClientsIds.Count > (networkManager.IsHost ? 1 : 0) && sceneManager.ClientSynchronizationMode != mode)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
{

View File

@@ -774,6 +774,7 @@ namespace Unity.Netcode
/// <summary>
/// This setting changes how clients handle scene loading when initially synchronizing with the server.<br />
/// The server or host should set this value as clients will automatically be synchronized with the server (or host) side.
/// </summary>
/// <remarks>
/// <b>LoadSceneMode.Single:</b> All currently loaded scenes on the client will be unloaded and the
/// server's currently active scene will be loaded in single mode on the client unless it was already
@@ -2406,16 +2407,6 @@ namespace Unity.Netcode
NetworkManager.ConnectionManager.CreateAndSpawnPlayer(NetworkManager.LocalClientId);
}
// Client is now synchronized and fully "connected". This also means the client can send "RPCs" at this time
NetworkManager.ConnectionManager.InvokeOnClientConnectedCallback(NetworkManager.LocalClientId);
// Notify the client that they have finished synchronizing
OnSceneEvent?.Invoke(new SceneEvent()
{
SceneEventType = sceneEventData.SceneEventType,
ClientId = NetworkManager.LocalClientId, // Client sent this to the server
});
// Process any SceneEventType.ObjectSceneChanged messages that
// were deferred while synchronizing and migrate the associated
// NetworkObjects to their newly assigned scenes.
@@ -2429,6 +2420,16 @@ namespace Unity.Netcode
SceneManagerHandler.UnloadUnassignedScenes(NetworkManager);
}
// Client is now synchronized and fully "connected". This also means the client can send "RPCs" at this time
NetworkManager.ConnectionManager.InvokeOnClientConnectedCallback(NetworkManager.LocalClientId);
// Notify the client that they have finished synchronizing
OnSceneEvent?.Invoke(new SceneEvent()
{
SceneEventType = sceneEventData.SceneEventType,
ClientId = NetworkManager.LocalClientId, // Client sent this to the server
});
OnSynchronizeComplete?.Invoke(NetworkManager.LocalClientId);
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer)
@@ -2436,10 +2437,7 @@ namespace Unity.Netcode
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();
}
NetworkManager.SpawnManager.NotifyNetworkObjectsSynchronized();
if (NetworkManager.DistributedAuthorityMode && HasSceneAuthority() && IsRestoringSession)
{

View File

@@ -11,6 +11,8 @@ namespace Unity.Netcode
{
private NetworkObjectReference m_NetworkObjectReference;
private ushort m_NetworkBehaviourId;
private static ushort s_NullId = ushort.MaxValue;
/// <summary>
/// Creates a new instance of the <see cref="NetworkBehaviourReference{T}"/> struct.
@@ -21,7 +23,9 @@ namespace Unity.Netcode
{
if (networkBehaviour == null)
{
throw new ArgumentNullException(nameof(networkBehaviour));
m_NetworkObjectReference = new NetworkObjectReference((NetworkObject)null);
m_NetworkBehaviourId = s_NullId;
return;
}
if (networkBehaviour.NetworkObject == null)
{
@@ -60,6 +64,11 @@ namespace Unity.Netcode
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static NetworkBehaviour GetInternal(NetworkBehaviourReference networkBehaviourRef, NetworkManager networkManager = null)
{
if (networkBehaviourRef.m_NetworkBehaviourId == s_NullId)
{
return null;
}
if (networkBehaviourRef.m_NetworkObjectReference.TryGet(out NetworkObject networkObject, networkManager))
{
return networkObject.GetNetworkBehaviourAtOrderIndex(networkBehaviourRef.m_NetworkBehaviourId);

View File

@@ -10,6 +10,7 @@ namespace Unity.Netcode
public struct NetworkObjectReference : INetworkSerializable, IEquatable<NetworkObjectReference>
{
private ulong m_NetworkObjectId;
private static ulong s_NullId = ulong.MaxValue;
/// <summary>
/// The <see cref="NetworkObject.NetworkObjectId"/> of the referenced <see cref="NetworkObject"/>.
@@ -30,7 +31,8 @@ namespace Unity.Netcode
{
if (networkObject == null)
{
throw new ArgumentNullException(nameof(networkObject));
m_NetworkObjectId = s_NullId;
return;
}
if (networkObject.IsSpawned == false)
@@ -51,10 +53,16 @@ namespace Unity.Netcode
{
if (gameObject == null)
{
throw new ArgumentNullException(nameof(gameObject));
m_NetworkObjectId = s_NullId;
return;
}
var networkObject = gameObject.GetComponent<NetworkObject>();
if (!networkObject)
{
throw new ArgumentException($"Cannot create {nameof(NetworkObjectReference)} from {nameof(GameObject)} without a {nameof(NetworkObject)} component.");
}
var networkObject = gameObject.GetComponent<NetworkObject>() ?? throw new ArgumentException($"Cannot create {nameof(NetworkObjectReference)} from {nameof(GameObject)} without a {nameof(NetworkObject)} component.");
if (networkObject.IsSpawned == false)
{
throw new ArgumentException($"{nameof(NetworkObjectReference)} can only be created from spawned {nameof(NetworkObject)}s.");
@@ -80,10 +88,14 @@ namespace Unity.Netcode
/// </summary>
/// <param name="networkObjectRef">The reference.</param>
/// <param name="networkManager">The networkmanager. Uses <see cref="NetworkManager.Singleton"/> to resolve if null.</param>
/// <returns>The resolves <see cref="NetworkObject"/>. Returns null if the networkobject was not found</returns>
/// <returns>The resolved <see cref="NetworkObject"/>. Returns null if the networkobject was not found</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static NetworkObject Resolve(NetworkObjectReference networkObjectRef, NetworkManager networkManager = null)
{
if (networkObjectRef.m_NetworkObjectId == s_NullId)
{
return null;
}
networkManager = networkManager ?? NetworkManager.Singleton;
networkManager.SpawnManager.SpawnedObjects.TryGetValue(networkObjectRef.m_NetworkObjectId, out NetworkObject networkObject);

View File

@@ -643,7 +643,7 @@ namespace Unity.Netcode
return null;
}
ownerClientId = NetworkManager.DistributedAuthorityMode ? NetworkManager.LocalClientId : NetworkManager.ServerClientId;
ownerClientId = NetworkManager.DistributedAuthorityMode ? NetworkManager.LocalClientId : ownerClientId;
// We only need to check for authority when running in client-server mode
if (!NetworkManager.IsServer && !NetworkManager.DistributedAuthorityMode)
{
@@ -1820,11 +1820,14 @@ namespace Unity.Netcode
return;
}
var currentTick = serverTime.Tick;
var deferredCallbackObjects = DeferredDespawnObjects.Where((c) => c.HasDeferredDespawnCheck);
var deferredCallbackCount = deferredCallbackObjects.Count();
for (int i = 0; i < deferredCallbackCount - 1; i++)
var deferredCallbackCount = DeferredDespawnObjects.Count();
for (int i = 0; i < deferredCallbackCount; i++)
{
var deferredObjectEntry = deferredCallbackObjects.ElementAt(i);
var deferredObjectEntry = DeferredDespawnObjects[i];
if (!deferredObjectEntry.HasDeferredDespawnCheck)
{
continue;
}
var networkObject = SpawnedObjects[deferredObjectEntry.NetworkObjectId];
// Double check to make sure user did not remove the callback
if (networkObject.OnDeferredDespawnComplete != null)
@@ -1849,9 +1852,15 @@ namespace Unity.Netcode
}
}
var despawnObjects = DeferredDespawnObjects.Where((c) => c.TickToDespawn < currentTick).ToList();
foreach (var deferredObjectEntry in despawnObjects)
// Parse backwards so we can remove objects as we parse through them
for (int i = DeferredDespawnObjects.Count - 1; i >= 0; i--)
{
var deferredObjectEntry = DeferredDespawnObjects[i];
if (deferredObjectEntry.TickToDespawn >= currentTick)
{
continue;
}
if (!SpawnedObjects.ContainsKey(deferredObjectEntry.NetworkObjectId))
{
DeferredDespawnObjects.Remove(deferredObjectEntry);
@@ -1863,5 +1872,16 @@ namespace Unity.Netcode
DeferredDespawnObjects.Remove(deferredObjectEntry);
}
}
internal void NotifyNetworkObjectsSynchronized()
{
// Users could spawn NetworkObjects during these notifications.
// Create a separate list from the hashset to avoid list modification errors.
var spawnedObjects = SpawnedObjectsList.ToList();
foreach (var networkObject in spawnedObjects)
{
networkObject.InternalNetworkSessionSynchronized();
}
}
}
}

View File

@@ -0,0 +1,100 @@
using System.Collections.Generic;
namespace Unity.Netcode
{
internal interface IAnticipationEventReceiver
{
public void SetupForUpdate();
public void SetupForRender();
}
internal interface IAnticipatedObject
{
public void Update();
public void ResetAnticipation();
public NetworkObject OwnerObject { get; }
}
internal class AnticipationSystem
{
internal ulong LastAnticipationAck;
internal double LastAnticipationAckTime;
internal HashSet<IAnticipatedObject> AllAnticipatedObjects = new HashSet<IAnticipatedObject>();
internal ulong AnticipationCounter;
private NetworkManager m_NetworkManager;
public HashSet<IAnticipatedObject> ObjectsToReanticipate = new HashSet<IAnticipatedObject>();
public AnticipationSystem(NetworkManager manager)
{
m_NetworkManager = manager;
}
public event NetworkManager.ReanticipateDelegate OnReanticipate;
private HashSet<IAnticipationEventReceiver> m_AnticipationEventReceivers = new HashSet<IAnticipationEventReceiver>();
public void RegisterForAnticipationEvents(IAnticipationEventReceiver receiver)
{
m_AnticipationEventReceivers.Add(receiver);
}
public void DeregisterForAnticipationEvents(IAnticipationEventReceiver receiver)
{
m_AnticipationEventReceivers.Remove(receiver);
}
public void SetupForUpdate()
{
foreach (var receiver in m_AnticipationEventReceivers)
{
receiver.SetupForUpdate();
}
}
public void SetupForRender()
{
foreach (var receiver in m_AnticipationEventReceivers)
{
receiver.SetupForRender();
}
}
public void ProcessReanticipation()
{
var lastRoundTripTime = m_NetworkManager.LocalTime.Time - LastAnticipationAckTime;
foreach (var item in ObjectsToReanticipate)
{
foreach (var behaviour in item.OwnerObject.ChildNetworkBehaviours)
{
behaviour.OnReanticipate(lastRoundTripTime);
}
item.ResetAnticipation();
}
ObjectsToReanticipate.Clear();
OnReanticipate?.Invoke(lastRoundTripTime);
}
public void Update()
{
foreach (var item in AllAnticipatedObjects)
{
item.Update();
}
}
public void Sync()
{
if (AllAnticipatedObjects.Count != 0 && !m_NetworkManager.ShutdownInProgress && !m_NetworkManager.ConnectionManager.LocalClient.IsServer && m_NetworkManager.ConnectionManager.LocalClient.IsConnected)
{
var message = new AnticipationCounterSyncPingMessage { Counter = AnticipationCounter, Time = m_NetworkManager.LocalTime.Time };
m_NetworkManager.MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, NetworkManager.ServerClientId);
}
++AnticipationCounter;
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4a75eccede7ecf1408f61dd55c338e06

View File

@@ -24,6 +24,11 @@ namespace Unity.Netcode
/// </summary>
public double TickOffset => m_CachedTickOffset;
/// <summary>
/// Gets the tick, including partial tick value passed since it started.
/// </summary>
public double TickWithPartial => Tick + (TickOffset / m_TickInterval);
/// <summary>
/// Gets the current time. This is a non fixed time value and similar to <see cref="Time.time"/>.
/// </summary>

View File

@@ -5,7 +5,9 @@ namespace Unity.Netcode
{
/// <summary>
/// <see cref="NetworkTimeSystem"/> is a standalone system which can be used to run a network time simulation.
/// The network time system maintains both a local and a server time. The local time is based on
/// The network time system maintains both a local and a server time. The local time is based on the server time
/// as last received from the server plus an offset based on the current RTT - in other words, it is a best-guess
/// effort at predicting what the server tick will be when a given network action is processed on the server.
/// </summary>
public class NetworkTimeSystem
{

View File

@@ -428,6 +428,31 @@ namespace Unity.Netcode.Transports.UTP
protected NetworkDriver m_Driver;
/// <summary>
/// Gets a reference to the <see cref="Networking.Transport.NetworkDriver"/>.
/// </summary>
/// <returns>ref <see cref="Networking.Transport.NetworkDriver"/></returns>
public ref NetworkDriver GetNetworkDriver()
{
return ref m_Driver;
}
/// <summary>
/// Gets the local sytem's <see cref="NetworkEndpoint"/> that is assigned for the current network session.
/// </summary>
/// <remarks>
/// If the driver is not created it will return an invalid <see cref="NetworkEndpoint"/>.
/// </remarks>
/// <returns><see cref="NetworkEndpoint"/></returns>
public NetworkEndpoint GetLocalEndpoint()
{
if (m_Driver.IsCreated)
{
return m_Driver.GetLocalEndpoint();
}
return new NetworkEndpoint();
}
private PacketLossCache m_PacketLossCache = new PacketLossCache();
private State m_State = State.Disconnected;
@@ -450,7 +475,10 @@ namespace Unity.Netcode.Transports.UTP
private RelayServerData m_RelayServerData;
internal NetworkManager NetworkManager;
/// <summary>
/// NetworkManager associated to this transport instance
/// </summary>
protected NetworkManager m_NetworkManager;
private IRealTimeProvider m_RealTimeProvider;
@@ -795,10 +823,10 @@ namespace Unity.Netcode.Transports.UTP
}
var mtu = 0;
if (NetworkManager)
if (m_NetworkManager)
{
var ngoClientId = NetworkManager.ConnectionManager.TransportIdToClientId(sendTarget.ClientId);
mtu = NetworkManager.GetPeerMTU(ngoClientId);
var ngoClientId = m_NetworkManager.ConnectionManager.TransportIdToClientId(sendTarget.ClientId);
mtu = m_NetworkManager.GetPeerMTU(ngoClientId);
}
new SendBatchedMessagesJob
@@ -947,7 +975,7 @@ namespace Unity.Netcode.Transports.UTP
}
#if MULTIPLAYER_TOOLS_1_0_0_PRE_7
if (NetworkManager)
if (m_NetworkManager)
{
ExtractNetworkMetrics();
}
@@ -963,16 +991,16 @@ namespace Unity.Netcode.Transports.UTP
#if MULTIPLAYER_TOOLS_1_0_0_PRE_7
private void ExtractNetworkMetrics()
{
if (NetworkManager.IsServer)
if (m_NetworkManager.IsServer)
{
var ngoConnectionIds = NetworkManager.ConnectedClients.Keys;
var ngoConnectionIds = m_NetworkManager.ConnectedClients.Keys;
foreach (var ngoConnectionId in ngoConnectionIds)
{
if (ngoConnectionId == 0 && NetworkManager.IsHost)
if (ngoConnectionId == 0 && m_NetworkManager.IsHost)
{
continue;
}
var transportClientId = NetworkManager.ConnectionManager.ClientIdToTransportId(ngoConnectionId);
var transportClientId = m_NetworkManager.ConnectionManager.ClientIdToTransportId(ngoConnectionId);
ExtractNetworkMetricsForClient(transportClientId);
}
}
@@ -992,10 +1020,10 @@ namespace Unity.Netcode.Transports.UTP
ExtractNetworkMetricsFromPipeline(m_UnreliableSequencedFragmentedPipeline, networkConnection);
ExtractNetworkMetricsFromPipeline(m_ReliableSequencedPipeline, networkConnection);
var rttValue = NetworkManager.IsServer ? 0 : ExtractRtt(networkConnection);
var rttValue = m_NetworkManager.IsServer ? 0 : ExtractRtt(networkConnection);
NetworkMetrics.UpdateRttToServer(rttValue);
var packetLoss = NetworkManager.IsServer ? 0 : ExtractPacketLoss(networkConnection);
var packetLoss = m_NetworkManager.IsServer ? 0 : ExtractPacketLoss(networkConnection);
NetworkMetrics.UpdatePacketLoss(packetLoss);
}
@@ -1199,9 +1227,9 @@ namespace Unity.Netcode.Transports.UTP
// use the transport client ID) or from a user (which will be using the NGO client ID).
// So we just try both cases (ExtractRtt returns 0 for invalid connections).
if (NetworkManager != null)
if (m_NetworkManager != null)
{
var transportId = NetworkManager.ConnectionManager.ClientIdToTransportId(clientId);
var transportId = m_NetworkManager.ConnectionManager.ClientIdToTransportId(clientId);
var rtt = ExtractRtt(ParseClientId(transportId));
if (rtt > 0)
@@ -1221,14 +1249,14 @@ namespace Unity.Netcode.Transports.UTP
{
Debug.Assert(sizeof(ulong) == UnsafeUtility.SizeOf<NetworkConnection>(), "Netcode connection id size does not match UTP connection id size");
NetworkManager = networkManager;
m_NetworkManager = networkManager;
if (NetworkManager && NetworkManager.PortOverride.Overidden)
if (m_NetworkManager && m_NetworkManager.PortOverride.Overidden)
{
ConnectionData.Port = NetworkManager.PortOverride.Value;
ConnectionData.Port = m_NetworkManager.PortOverride.Value;
}
m_RealTimeProvider = NetworkManager ? NetworkManager.RealTimeProvider : new RealTimeProvider();
m_RealTimeProvider = m_NetworkManager ? m_NetworkManager.RealTimeProvider : new RealTimeProvider();
m_NetworkSettings = new NetworkSettings(Allocator.Persistent);
@@ -1322,7 +1350,7 @@ namespace Unity.Netcode.Transports.UTP
// provide any reliability guarantees anymore. Disconnect the client since at
// this point they're bound to become desynchronized.
var ngoClientId = NetworkManager?.ConnectionManager.TransportIdToClientId(clientId) ?? clientId;
var ngoClientId = m_NetworkManager?.ConnectionManager.TransportIdToClientId(clientId) ?? clientId;
Debug.LogError($"Couldn't add payload of size {payload.Count} to reliable send queue. " +
$"Closing connection {ngoClientId} as reliability guarantees can't be maintained.");
@@ -1479,7 +1507,7 @@ namespace Unity.Netcode.Transports.UTP
protected override NetworkTopologyTypes OnCurrentTopology()
{
return NetworkManager != null ? NetworkManager.NetworkConfig.NetworkTopology : NetworkTopologyTypes.ClientServer;
return m_NetworkManager != null ? m_NetworkManager.NetworkConfig.NetworkTopology : NetworkTopologyTypes.ClientServer;
}
private string m_ServerPrivateKey;
@@ -1555,7 +1583,7 @@ namespace Unity.Netcode.Transports.UTP
heartbeatTimeoutMS: transport.m_HeartbeatTimeoutMS);
#if UNITY_WEBGL && !UNITY_EDITOR
if (NetworkManager.IsServer && m_ProtocolType != ProtocolType.RelayUnityTransport)
if (m_NetworkManager.IsServer && m_ProtocolType != ProtocolType.RelayUnityTransport)
{
throw new Exception("WebGL as a server is not supported by Unity Transport, outside the Editor.");
}
@@ -1577,7 +1605,7 @@ namespace Unity.Netcode.Transports.UTP
}
else
{
if (NetworkManager.IsServer)
if (m_NetworkManager.IsServer)
{
if (string.IsNullOrEmpty(m_ServerCertificate) || string.IsNullOrEmpty(m_ServerPrivateKey))
{

View File

@@ -72,6 +72,11 @@
"name": "com.unity.services.multiplayer",
"expression": "0.2.0",
"define": "MULTIPLAYER_SERVICES_SDK_INSTALLED"
},
{
"name": "Unity",
"expression": "6000.0.11f1",
"define": "COM_UNITY_MODULES_PHYSICS2D_LINEAR"
}
],
"noEngineReferences": false

View File

@@ -677,6 +677,11 @@ namespace Unity.Netcode.TestHelpers.Runtime
foreach (var sceneToUnload in m_ScenesToUnload)
{
SceneManager.UnloadSceneAsync(sceneToUnload.Key);
// Update the ScenesLoaded when we unload scenes
if (sceneManager.ScenesLoaded.ContainsKey(sceneToUnload.Key.handle))
{
sceneManager.ScenesLoaded.Remove(sceneToUnload.Key.handle);
}
}
}
@@ -795,8 +800,9 @@ namespace Unity.Netcode.TestHelpers.Runtime
var sceneManager = networkManager.SceneManager;
// Don't let client's set this value
if (!networkManager.IsServer)
// In client-server, we don't let client's set this value.
// In dsitributed authority, since session owner can be promoted clients can set this value
if (!networkManager.DistributedAuthorityMode && !networkManager.IsServer)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
{
@@ -804,7 +810,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
}
return;
}
else if (networkManager.ConnectedClientsIds.Count > (networkManager.IsHost ? 1 : 0) && sceneManager.ClientSynchronizationMode != mode)
else if (!networkManager.DistributedAuthorityMode && networkManager.ConnectedClientsIds.Count > (networkManager.IsHost ? 1 : 0) && sceneManager.ClientSynchronizationMode != mode)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
{

View File

@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using Random = UnityEngine.Random;
namespace Unity.Netcode.TestHelpers.Runtime
{
@@ -10,6 +11,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
public ulong FromClientId;
public ArraySegment<byte> Payload;
public NetworkEvent Event;
public float AvailableTime;
}
private static Dictionary<ulong, Queue<MessageData>> s_MessageQueue = new Dictionary<ulong, Queue<MessageData>>();
@@ -18,21 +20,44 @@ namespace Unity.Netcode.TestHelpers.Runtime
public static ulong HighTransportId = 0;
public ulong TransportId = 0;
public float SimulatedLatencySeconds;
public float PacketDropRate;
public float LatencyJitter;
public NetworkManager NetworkManager;
public override void Send(ulong clientId, ArraySegment<byte> payload, NetworkDelivery networkDelivery)
{
if (Random.Range(0, 1) < PacketDropRate)
{
return;
}
var copy = new byte[payload.Array.Length];
Array.Copy(payload.Array, copy, payload.Array.Length);
s_MessageQueue[clientId].Enqueue(new MessageData { FromClientId = TransportId, Payload = new ArraySegment<byte>(copy, payload.Offset, payload.Count), Event = NetworkEvent.Data });
s_MessageQueue[clientId].Enqueue(new MessageData
{
FromClientId = TransportId,
Payload = new ArraySegment<byte>(copy, payload.Offset, payload.Count),
Event = NetworkEvent.Data,
AvailableTime =
NetworkManager.RealTimeProvider.UnscaledTime + SimulatedLatencySeconds + Random.Range(-LatencyJitter, LatencyJitter)
});
}
public override NetworkEvent PollEvent(out ulong clientId, out ArraySegment<byte> payload, out float receiveTime)
{
if (s_MessageQueue[TransportId].Count > 0)
{
var data = s_MessageQueue[TransportId].Dequeue();
var data = s_MessageQueue[TransportId].Peek();
if (data.AvailableTime > NetworkManager.RealTimeProvider.UnscaledTime)
{
clientId = 0;
payload = new ArraySegment<byte>();
receiveTime = 0;
return NetworkEvent.Nothing;
}
s_MessageQueue[TransportId].Dequeue();
clientId = data.FromClientId;
payload = data.Payload;
receiveTime = NetworkManager.RealTimeProvider.RealTimeSinceStartup;
@@ -90,5 +115,19 @@ namespace Unity.Netcode.TestHelpers.Runtime
{
NetworkManager = networkManager;
}
public static void Reset()
{
s_MessageQueue.Clear();
HighTransportId = 0;
}
public static void ClearQueues()
{
foreach (var kvp in s_MessageQueue)
{
kvp.Value.Clear();
}
}
}
}

View File

@@ -303,6 +303,11 @@ namespace Unity.Netcode.TestHelpers.Runtime
OnOneTimeSetup();
VerboseDebug($"Exiting {nameof(OneTimeSetup)}");
#if DEVELOPMENT_BUILD || UNITY_EDITOR
// Default to not log the serialized type not optimized warning message when testing.
NetworkManager.DisableNotOptimizedSerializedType = true;
#endif
}
/// <summary>
@@ -337,6 +342,15 @@ namespace Unity.Netcode.TestHelpers.Runtime
NetcodeLogAssert = new NetcodeLogAssert();
if (m_EnableTimeTravel)
{
if (m_NetworkManagerInstatiationMode == NetworkManagerInstatiationMode.AllTests)
{
MockTransport.ClearQueues();
}
else
{
MockTransport.Reset();
}
// Setup the frames per tick for time travel advance to next tick
ConfigureFramesPerTick();
}
@@ -636,6 +650,33 @@ namespace Unity.Netcode.TestHelpers.Runtime
Assert.True(WaitForConditionOrTimeOutWithTimeTravel(() => !networkManager.IsConnectedClient));
}
protected void SetTimeTravelSimulatedLatency(float latencySeconds)
{
((MockTransport)m_ServerNetworkManager.NetworkConfig.NetworkTransport).SimulatedLatencySeconds = latencySeconds;
foreach (var client in m_ClientNetworkManagers)
{
((MockTransport)client.NetworkConfig.NetworkTransport).SimulatedLatencySeconds = latencySeconds;
}
}
protected void SetTimeTravelSimulatedDropRate(float dropRatePercent)
{
((MockTransport)m_ServerNetworkManager.NetworkConfig.NetworkTransport).PacketDropRate = dropRatePercent;
foreach (var client in m_ClientNetworkManagers)
{
((MockTransport)client.NetworkConfig.NetworkTransport).PacketDropRate = dropRatePercent;
}
}
protected void SetTimeTravelSimulatedLatencyJitter(float jitterSeconds)
{
((MockTransport)m_ServerNetworkManager.NetworkConfig.NetworkTransport).LatencyJitter = jitterSeconds;
foreach (var client in m_ClientNetworkManagers)
{
((MockTransport)client.NetworkConfig.NetworkTransport).LatencyJitter = jitterSeconds;
}
}
/// <summary>
/// Creates the server and clients
/// </summary>
@@ -1880,8 +1921,21 @@ namespace Unity.Netcode.TestHelpers.Runtime
/// </summary>
public static void SimulateOneFrame()
{
foreach (NetworkUpdateStage stage in Enum.GetValues(typeof(NetworkUpdateStage)))
foreach (NetworkUpdateStage updateStage in Enum.GetValues(typeof(NetworkUpdateStage)))
{
var stage = updateStage;
// These two are out of order numerically due to backward compatibility
// requirements. We have to swap them to maintain correct execution
// order.
if (stage == NetworkUpdateStage.PostScriptLateUpdate)
{
stage = NetworkUpdateStage.PostLateUpdate;
}
else if (stage == NetworkUpdateStage.PostLateUpdate)
{
stage = NetworkUpdateStage.PostScriptLateUpdate;
}
NetworkUpdateLoop.RunNetworkUpdateStage(stage);
string methodName = string.Empty;
switch (stage)
@@ -1900,13 +1954,18 @@ namespace Unity.Netcode.TestHelpers.Runtime
if (!string.IsNullOrEmpty(methodName))
{
#if UNITY_2023_1_OR_NEWER
foreach (var behaviour in Object.FindObjectsByType<NetworkBehaviour>(FindObjectsSortMode.InstanceID))
foreach (var obj in Object.FindObjectsByType<NetworkObject>(FindObjectsSortMode.InstanceID))
#else
foreach (var behaviour in Object.FindObjectsOfType<NetworkBehaviour>())
foreach (var obj in Object.FindObjectsOfType<NetworkObject>())
#endif
{
var method = behaviour.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
method?.Invoke(behaviour, new object[] { });
var method = obj.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
method?.Invoke(obj, new object[] { });
foreach (var behaviour in obj.ChildNetworkBehaviours)
{
var behaviourMethod = behaviour.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
behaviourMethod?.Invoke(behaviour, new object[] { });
}
}
}
}

View File

@@ -620,7 +620,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
/// Similar to WaitForClientConnected, this waits for multiple clients to be connected.
/// </summary>
/// <param name="clients">The clients to be connected</param>
/// <param name="result">The result. If null, it will automatically assert<</param>
/// <param name="result">The result. If null, it will automatically assert</param>
/// <param name="maxFrames">The max frames to wait for</param>
/// <returns></returns>
public static IEnumerator WaitForClientsConnected(NetworkManager[] clients, ResultWrapper<bool> result = null, float timeout = DefaultTimeout)

View File

@@ -8,8 +8,10 @@ namespace Unity.Netcode.TestHelpers.Runtime
/// delegate handler. It then will expose that single delegate invocation
/// to anything that registers for this NetworkVariableHelper's instance's OnValueChanged event.
/// This allows us to register any NetworkVariable type as well as there are basically two "types of types":
/// IEquatable<T>
/// ValueType
/// <list type="bullet">
/// <item>IEquatable&lt;T&gt;</item>
/// <item>ValueType</item>
/// </list>
/// From both we can then at least determine if the value indeed changed
/// </summary>
/// <typeparam name="T"></typeparam>
@@ -20,7 +22,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
public event OnMyValueChangedDelegateHandler OnValueChanged;
/// <summary>
/// IEquatable<T> Equals Check
/// IEquatable&lt;T&gt; Equals Check
/// </summary>
private void CheckVariableChanged(IEquatable<T> previous, IEquatable<T> next)
{

View File

@@ -38,11 +38,7 @@ namespace Unity.Netcode.RuntimeTests
internal class TestNetworkComponent : NetworkBehaviour
{
public NetworkList<int> MyNetworkList = new NetworkList<int>(new List<int> { 1, 2, 3 });
[Rpc(SendTo.NotAuthority)]
public void TestNotAuthorityRpc(byte[] _)
{
}
public NetworkVariable<int> MyNetworkVar = new NetworkVariable<int>(3);
[Rpc(SendTo.Authority)]
public void TestAuthorityRpc(byte[] _)
@@ -87,7 +83,7 @@ namespace Unity.Netcode.RuntimeTests
Client.LogLevel = LogLevel.Developer;
// Validate we are in distributed authority mode with client side spawning and using CMB Service
Assert.True(Client.DistributedAuthorityMode, "Distributed authority is not set!");
Assert.True(Client.NetworkConfig.NetworkTopology == NetworkTopologyTypes.DistributedAuthority, "Distributed authority topology is not set!");
Assert.True(Client.AutoSpawnPlayerPrefabClientSide, "Client side spawning is not set!");
Assert.True(Client.CMBServiceConnection, "CMBServiceConnection is not set!");
@@ -101,6 +97,9 @@ namespace Unity.Netcode.RuntimeTests
protected override IEnumerator OnStartedServerAndClients()
{
// Validate the NetworkManager are in distributed authority mode
Assert.True(Client.DistributedAuthorityMode, "Distributed authority is not set!");
// Register hooks after starting clients and server (in this case just the one client)
// We do this at this point in time because the MessageManager exists (happens within the same call stack when starting NetworkManagers)
m_ClientCodecHook = new CodecTestHooks();
@@ -219,12 +218,44 @@ namespace Unity.Netcode.RuntimeTests
}
[UnityTest]
public IEnumerator NotAuthorityRpc()
public IEnumerator NetworkVariableDelta_WithValueUpdate()
{
Client.LocalClient.PlayerObject.GetComponent<TestNetworkComponent>().TestNotAuthorityRpc(new byte[] { 1, 2, 3, 4 });
var networkObj = CreateNetworkObjectPrefab("TestObject");
networkObj.AddComponent<TestNetworkComponent>();
var instance = SpawnObject(networkObj, Client);
yield return m_ClientCodecHook.WaitForMessageReceived<CreateObjectMessage>();
var component = instance.GetComponent<TestNetworkComponent>();
// Universal Rpcs are sent as a ProxyMessage (which contains an RpcMessage)
yield return m_ClientCodecHook.WaitForMessageReceived<ProxyMessage>();
var newValue = 5;
component.MyNetworkVar.Value = newValue;
yield return m_ClientCodecHook.WaitForMessageReceived<NetworkVariableDeltaMessage>();
Assert.AreEqual(newValue, component.MyNetworkVar.Value);
}
[UnityTest]
public IEnumerator NetworkListDelta_WithValueUpdate()
{
var networkObj = CreateNetworkObjectPrefab("TestObject");
networkObj.AddComponent<TestNetworkComponent>();
var instance = SpawnObject(networkObj, Client);
yield return m_ClientCodecHook.WaitForMessageReceived<CreateObjectMessage>();
var component = instance.GetComponent<TestNetworkComponent>();
component.MyNetworkList.Add(5);
yield return m_ClientCodecHook.WaitForMessageReceived<NetworkVariableDeltaMessage>();
component.MyNetworkList.Add(6);
component.MyNetworkList.Add(7);
yield return m_ClientCodecHook.WaitForMessageReceived<NetworkVariableDeltaMessage>();
component.MyNetworkList.Insert(1, 8);
yield return m_ClientCodecHook.WaitForMessageReceived<NetworkVariableDeltaMessage>();
component.MyNetworkList.Insert(8, 11);
yield return m_ClientCodecHook.WaitForMessageReceived<NetworkVariableDeltaMessage>();
component.MyNetworkList.Remove(6);
yield return m_ClientCodecHook.WaitForMessageReceived<NetworkVariableDeltaMessage>();
component.MyNetworkList.RemoveAt(2);
yield return m_ClientCodecHook.WaitForMessageReceived<NetworkVariableDeltaMessage>();
component.MyNetworkList.Clear();
yield return m_ClientCodecHook.WaitForMessageReceived<NetworkVariableDeltaMessage>();
}
[UnityTest]

View File

@@ -0,0 +1,97 @@
using System.Collections;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using Unity.Netcode.TestHelpers.Runtime;
namespace Unity.Netcode.RuntimeTests
{
/// <summary>
/// This test validates PR-3000 where it would invoke
/// TODO:
/// We really need to get the service running during tests
/// so we can validate these issues. While this test does
/// partially validate it we still need to manually validate
/// with a service connection.
/// </summary>
[TestFixture(HostOrServer.Host)]
[TestFixture(HostOrServer.DAHost)]
public class RpcProxyMessageTesting : NetcodeIntegrationTest
{
protected override int NumberOfClients => 2;
private List<RpcProxyText> m_ProxyTestInstances = new List<RpcProxyText>();
private StringBuilder m_ValidationLogger = new StringBuilder();
public RpcProxyMessageTesting(HostOrServer hostOrServer) : base(hostOrServer) { }
protected override IEnumerator OnSetup()
{
m_ProxyTestInstances.Clear();
return base.OnSetup();
}
protected override void OnCreatePlayerPrefab()
{
m_PlayerPrefab.AddComponent<RpcProxyText>();
base.OnCreatePlayerPrefab();
}
private bool ValidateRpcProxyRpcs()
{
m_ValidationLogger.Clear();
foreach (var proxy in m_ProxyTestInstances)
{
if (proxy.ReceivedRpc.Count < NumberOfClients)
{
m_ValidationLogger.AppendLine($"Not all clients received RPC from Client-{proxy.OwnerClientId}!");
}
foreach (var clientId in proxy.ReceivedRpc)
{
if (clientId == proxy.OwnerClientId)
{
m_ValidationLogger.AppendLine($"Client-{proxy.OwnerClientId} sent itself an Rpc!");
}
}
}
return m_ValidationLogger.Length == 0;
}
public IEnumerator ProxyDoesNotInvokeOnSender()
{
m_ProxyTestInstances.Add(m_ServerNetworkManager.LocalClient.PlayerObject.GetComponent<RpcProxyText>());
foreach (var client in m_ClientNetworkManagers)
{
m_ProxyTestInstances.Add(client.LocalClient.PlayerObject.GetComponent<RpcProxyText>());
}
foreach (var clientProxyTest in m_ProxyTestInstances)
{
clientProxyTest.SendToEveryOneButMe();
}
yield return WaitForConditionOrTimeOut(ValidateRpcProxyRpcs);
AssertOnTimeout(m_ValidationLogger.ToString());
}
public class RpcProxyText : NetworkBehaviour
{
public List<ulong> ReceivedRpc = new List<ulong>();
public void SendToEveryOneButMe()
{
var baseTarget = NetworkManager.DistributedAuthorityMode ? RpcTarget.NotAuthority : RpcTarget.NotMe;
TestRpc(baseTarget);
}
[Rpc(SendTo.SpecifiedInParams)]
private void TestRpc(RpcParams rpcParams = default)
{
ReceivedRpc.Add(rpcParams.Receive.SenderClientId);
}
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 22d1d751fe245f7419f8393090c27106

View File

@@ -4,6 +4,7 @@ using NUnit.Framework;
using Unity.Netcode.TestHelpers.Runtime;
using UnityEngine;
using UnityEngine.TestTools;
using Object = UnityEngine.Object;
namespace Unity.Netcode.RuntimeTests
{
@@ -35,7 +36,7 @@ namespace Unity.Netcode.RuntimeTests
m_ServerManager.OnServerStopped += onServerStopped;
m_ServerManager.Shutdown();
UnityEngine.Object.DestroyImmediate(gameObject);
Object.DestroyImmediate(gameObject);
yield return WaitUntilManagerShutsdown();
@@ -92,7 +93,7 @@ namespace Unity.Netcode.RuntimeTests
m_ServerManager.OnServerStopped += onServerStopped;
m_ServerManager.OnClientStopped += onClientStopped;
m_ServerManager.Shutdown();
UnityEngine.Object.DestroyImmediate(gameObject);
Object.DestroyImmediate(gameObject);
yield return WaitUntilManagerShutsdown();
@@ -228,6 +229,18 @@ namespace Unity.Netcode.RuntimeTests
public virtual IEnumerator Teardown()
{
NetcodeIntegrationTestHelpers.Destroy();
if (m_ServerManager != null)
{
m_ServerManager.ShutdownInternal();
Object.DestroyImmediate(m_ServerManager);
m_ServerManager = null;
}
if (m_ClientManager != null)
{
m_ClientManager.ShutdownInternal();
Object.DestroyImmediate(m_ClientManager);
m_ClientManager = null;
}
yield return null;
}
}

View File

@@ -0,0 +1,521 @@
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Unity.Netcode.Components;
using Unity.Netcode.TestHelpers.Runtime;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Unity.Netcode.RuntimeTests
{
internal class NetworkTransformAnticipationComponent : NetworkBehaviour
{
[Rpc(SendTo.Server)]
public void MoveRpc(Vector3 newPosition)
{
transform.position = newPosition;
}
[Rpc(SendTo.Server)]
public void ScaleRpc(Vector3 newScale)
{
transform.localScale = newScale;
}
[Rpc(SendTo.Server)]
public void RotateRpc(Quaternion newRotation)
{
transform.rotation = newRotation;
}
public bool ShouldSmooth = false;
public bool ShouldMove = false;
public override void OnReanticipate(double lastRoundTripTime)
{
var transform_ = GetComponent<AnticipatedNetworkTransform>();
if (transform_.ShouldReanticipate)
{
if (ShouldSmooth)
{
transform_.Smooth(transform_.PreviousAnticipatedState, transform_.AuthoritativeState, 1);
}
if (ShouldMove)
{
transform_.AnticipateMove(transform_.AuthoritativeState.Position + new Vector3(0, 5, 0));
}
}
}
}
internal class NetworkTransformAnticipationTests : NetcodeIntegrationTest
{
protected override int NumberOfClients => 2;
protected override bool m_EnableTimeTravel => true;
protected override bool m_SetupIsACoroutine => false;
protected override bool m_TearDownIsACoroutine => false;
protected override void OnPlayerPrefabGameObjectCreated()
{
m_PlayerPrefab.AddComponent<AnticipatedNetworkTransform>();
m_PlayerPrefab.AddComponent<NetworkTransformAnticipationComponent>();
}
protected override void OnTimeTravelServerAndClientsConnected()
{
var serverComponent = GetServerComponent();
var testComponent = GetTestComponent();
var otherClientComponent = GetOtherClientComponent();
serverComponent.transform.position = Vector3.zero;
serverComponent.transform.localScale = Vector3.one;
serverComponent.transform.rotation = Quaternion.LookRotation(Vector3.forward);
testComponent.transform.position = Vector3.zero;
testComponent.transform.localScale = Vector3.one;
testComponent.transform.rotation = Quaternion.LookRotation(Vector3.forward);
otherClientComponent.transform.position = Vector3.zero;
otherClientComponent.transform.localScale = Vector3.one;
otherClientComponent.transform.rotation = Quaternion.LookRotation(Vector3.forward);
}
public AnticipatedNetworkTransform GetTestComponent()
{
return m_ClientNetworkManagers[0].LocalClient.PlayerObject.GetComponent<AnticipatedNetworkTransform>();
}
public AnticipatedNetworkTransform GetServerComponent()
{
foreach (var obj in Object.FindObjectsByType<AnticipatedNetworkTransform>(FindObjectsSortMode.None))
{
if (obj.NetworkManager == m_ServerNetworkManager && obj.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId)
{
return obj;
}
}
return null;
}
public AnticipatedNetworkTransform GetOtherClientComponent()
{
foreach (var obj in Object.FindObjectsByType<AnticipatedNetworkTransform>(FindObjectsSortMode.None))
{
if (obj.NetworkManager == m_ClientNetworkManagers[1] && obj.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId)
{
return obj;
}
}
return null;
}
[Test]
public void WhenAnticipating_ValueChangesImmediately()
{
var testComponent = GetTestComponent();
testComponent.AnticipateMove(new Vector3(0, 1, 2));
testComponent.AnticipateScale(new Vector3(1, 2, 3));
testComponent.AnticipateRotate(Quaternion.LookRotation(new Vector3(2, 3, 4)));
Assert.AreEqual(new Vector3(0, 1, 2), testComponent.transform.position);
Assert.AreEqual(new Vector3(1, 2, 3), testComponent.transform.localScale);
Assert.AreEqual(Quaternion.LookRotation(new Vector3(2, 3, 4)), testComponent.transform.rotation);
Assert.AreEqual(new Vector3(0, 1, 2), testComponent.AnticipatedState.Position);
Assert.AreEqual(new Vector3(1, 2, 3), testComponent.AnticipatedState.Scale);
Assert.AreEqual(Quaternion.LookRotation(new Vector3(2, 3, 4)), testComponent.AnticipatedState.Rotation);
}
[Test]
public void WhenAnticipating_AuthoritativeValueDoesNotChange()
{
var testComponent = GetTestComponent();
var startPosition = testComponent.transform.position;
var startScale = testComponent.transform.localScale;
var startRotation = testComponent.transform.rotation;
testComponent.AnticipateMove(new Vector3(0, 1, 2));
testComponent.AnticipateScale(new Vector3(1, 2, 3));
testComponent.AnticipateRotate(Quaternion.LookRotation(new Vector3(2, 3, 4)));
Assert.AreEqual(startPosition, testComponent.AuthoritativeState.Position);
Assert.AreEqual(startScale, testComponent.AuthoritativeState.Scale);
Assert.AreEqual(startRotation, testComponent.AuthoritativeState.Rotation);
}
[Test]
public void WhenAnticipating_ServerDoesNotChange()
{
var testComponent = GetTestComponent();
var startPosition = testComponent.transform.position;
var startScale = testComponent.transform.localScale;
var startRotation = testComponent.transform.rotation;
testComponent.AnticipateMove(new Vector3(0, 1, 2));
testComponent.AnticipateScale(new Vector3(1, 2, 3));
testComponent.AnticipateRotate(Quaternion.LookRotation(new Vector3(2, 3, 4)));
var serverComponent = GetServerComponent();
Assert.AreEqual(startPosition, serverComponent.AuthoritativeState.Position);
Assert.AreEqual(startScale, serverComponent.AuthoritativeState.Scale);
Assert.AreEqual(startRotation, serverComponent.AuthoritativeState.Rotation);
Assert.AreEqual(startPosition, serverComponent.AnticipatedState.Position);
Assert.AreEqual(startScale, serverComponent.AnticipatedState.Scale);
Assert.AreEqual(startRotation, serverComponent.AnticipatedState.Rotation);
TimeTravel(2, 120);
Assert.AreEqual(startPosition, serverComponent.AuthoritativeState.Position);
Assert.AreEqual(startScale, serverComponent.AuthoritativeState.Scale);
Assert.AreEqual(startRotation, serverComponent.AuthoritativeState.Rotation);
Assert.AreEqual(startPosition, serverComponent.AnticipatedState.Position);
Assert.AreEqual(startScale, serverComponent.AnticipatedState.Scale);
Assert.AreEqual(startRotation, serverComponent.AnticipatedState.Rotation);
}
[Test]
public void WhenAnticipating_OtherClientDoesNotChange()
{
var testComponent = GetTestComponent();
var startPosition = testComponent.transform.position;
var startScale = testComponent.transform.localScale;
var startRotation = testComponent.transform.rotation;
testComponent.AnticipateMove(new Vector3(0, 1, 2));
testComponent.AnticipateScale(new Vector3(1, 2, 3));
testComponent.AnticipateRotate(Quaternion.LookRotation(new Vector3(2, 3, 4)));
var otherClientComponent = GetOtherClientComponent();
Assert.AreEqual(startPosition, otherClientComponent.AuthoritativeState.Position);
Assert.AreEqual(startScale, otherClientComponent.AuthoritativeState.Scale);
Assert.AreEqual(startRotation, otherClientComponent.AuthoritativeState.Rotation);
Assert.AreEqual(startPosition, otherClientComponent.AnticipatedState.Position);
Assert.AreEqual(startScale, otherClientComponent.AnticipatedState.Scale);
Assert.AreEqual(startRotation, otherClientComponent.AnticipatedState.Rotation);
TimeTravel(2, 120);
Assert.AreEqual(startPosition, otherClientComponent.AuthoritativeState.Position);
Assert.AreEqual(startScale, otherClientComponent.AuthoritativeState.Scale);
Assert.AreEqual(startRotation, otherClientComponent.AuthoritativeState.Rotation);
Assert.AreEqual(startPosition, otherClientComponent.AnticipatedState.Position);
Assert.AreEqual(startScale, otherClientComponent.AnticipatedState.Scale);
Assert.AreEqual(startRotation, otherClientComponent.AnticipatedState.Rotation);
}
[Test]
public void WhenServerChangesSnapValue_ValuesAreUpdated()
{
var testComponent = GetTestComponent();
var serverComponent = GetServerComponent();
serverComponent.Interpolate = false;
testComponent.AnticipateMove(new Vector3(0, 1, 2));
testComponent.AnticipateScale(new Vector3(1, 2, 3));
testComponent.AnticipateRotate(Quaternion.LookRotation(new Vector3(2, 3, 4)));
var rpcComponent = testComponent.GetComponent<NetworkTransformAnticipationComponent>();
rpcComponent.MoveRpc(new Vector3(2, 3, 4));
WaitForMessageReceivedWithTimeTravel<RpcMessage>(new List<NetworkManager> { m_ServerNetworkManager });
var otherClientComponent = GetOtherClientComponent();
WaitForConditionOrTimeOutWithTimeTravel(() => testComponent.AuthoritativeState.Position == serverComponent.transform.position && otherClientComponent.AuthoritativeState.Position == serverComponent.transform.position);
Assert.AreEqual(serverComponent.transform.position, testComponent.transform.position);
Assert.AreEqual(serverComponent.transform.position, testComponent.AnticipatedState.Position);
Assert.AreEqual(serverComponent.transform.position, testComponent.AuthoritativeState.Position);
Assert.AreEqual(serverComponent.transform.position, otherClientComponent.transform.position);
Assert.AreEqual(serverComponent.transform.position, otherClientComponent.AnticipatedState.Position);
Assert.AreEqual(serverComponent.transform.position, otherClientComponent.AuthoritativeState.Position);
}
public void AssertQuaternionsAreEquivalent(Quaternion a, Quaternion b)
{
var aAngles = a.eulerAngles;
var bAngles = b.eulerAngles;
Assert.AreEqual(aAngles.x, bAngles.x, 0.001, $"Quaternions were not equal. Expected: {a}, but was {b}");
Assert.AreEqual(aAngles.y, bAngles.y, 0.001, $"Quaternions were not equal. Expected: {a}, but was {b}");
Assert.AreEqual(aAngles.z, bAngles.z, 0.001, $"Quaternions were not equal. Expected: {a}, but was {b}");
}
public void AssertVectorsAreEquivalent(Vector3 a, Vector3 b)
{
Assert.AreEqual(a.x, b.x, 0.001, $"Vectors were not equal. Expected: {a}, but was {b}");
Assert.AreEqual(a.y, b.y, 0.001, $"Vectors were not equal. Expected: {a}, but was {b}");
Assert.AreEqual(a.z, b.z, 0.001, $"Vectors were not equal. Expected: {a}, but was {b}");
}
[Test]
public void WhenServerChangesSmoothValue_ValuesAreLerped()
{
var testComponent = GetTestComponent();
var otherClientComponent = GetOtherClientComponent();
testComponent.StaleDataHandling = StaleDataHandling.Ignore;
otherClientComponent.StaleDataHandling = StaleDataHandling.Ignore;
var serverComponent = GetServerComponent();
serverComponent.Interpolate = false;
testComponent.GetComponent<NetworkTransformAnticipationComponent>().ShouldSmooth = true;
otherClientComponent.GetComponent<NetworkTransformAnticipationComponent>().ShouldSmooth = true;
var startPosition = testComponent.transform.position;
var startScale = testComponent.transform.localScale;
var startRotation = testComponent.transform.rotation;
var anticipePosition = new Vector3(0, 1, 2);
var anticipeScale = new Vector3(1, 2, 3);
var anticipeRotation = Quaternion.LookRotation(new Vector3(2, 3, 4));
var serverSetPosition = new Vector3(3, 4, 5);
var serverSetScale = new Vector3(4, 5, 6);
var serverSetRotation = Quaternion.LookRotation(new Vector3(5, 6, 7));
testComponent.AnticipateMove(anticipePosition);
testComponent.AnticipateScale(anticipeScale);
testComponent.AnticipateRotate(anticipeRotation);
var rpcComponent = testComponent.GetComponent<NetworkTransformAnticipationComponent>();
rpcComponent.MoveRpc(serverSetPosition);
rpcComponent.RotateRpc(serverSetRotation);
rpcComponent.ScaleRpc(serverSetScale);
WaitForMessagesReceivedWithTimeTravel(new List<Type>
{
typeof(RpcMessage),
typeof(RpcMessage),
typeof(RpcMessage),
}, new List<NetworkManager> { m_ServerNetworkManager });
WaitForMessageReceivedWithTimeTravel<NetworkTransformMessage>(m_ClientNetworkManagers.ToList());
var percentChanged = 1f / 60f;
AssertVectorsAreEquivalent(Vector3.Lerp(anticipePosition, serverSetPosition, percentChanged), testComponent.transform.position);
AssertVectorsAreEquivalent(Vector3.Lerp(anticipeScale, serverSetScale, percentChanged), testComponent.transform.localScale);
AssertQuaternionsAreEquivalent(Quaternion.Slerp(anticipeRotation, serverSetRotation, percentChanged), testComponent.transform.rotation);
AssertVectorsAreEquivalent(Vector3.Lerp(anticipePosition, serverSetPosition, percentChanged), testComponent.AnticipatedState.Position);
AssertVectorsAreEquivalent(Vector3.Lerp(anticipeScale, serverSetScale, percentChanged), testComponent.AnticipatedState.Scale);
AssertQuaternionsAreEquivalent(Quaternion.Slerp(anticipeRotation, serverSetRotation, percentChanged), testComponent.AnticipatedState.Rotation);
AssertVectorsAreEquivalent(serverSetPosition, testComponent.AuthoritativeState.Position);
AssertVectorsAreEquivalent(serverSetScale, testComponent.AuthoritativeState.Scale);
AssertQuaternionsAreEquivalent(serverSetRotation, testComponent.AuthoritativeState.Rotation);
AssertVectorsAreEquivalent(Vector3.Lerp(startPosition, serverSetPosition, percentChanged), otherClientComponent.transform.position);
AssertVectorsAreEquivalent(Vector3.Lerp(startScale, serverSetScale, percentChanged), otherClientComponent.transform.localScale);
AssertQuaternionsAreEquivalent(Quaternion.Slerp(startRotation, serverSetRotation, percentChanged), otherClientComponent.transform.rotation);
AssertVectorsAreEquivalent(Vector3.Lerp(startPosition, serverSetPosition, percentChanged), otherClientComponent.AnticipatedState.Position);
AssertVectorsAreEquivalent(Vector3.Lerp(startScale, serverSetScale, percentChanged), otherClientComponent.AnticipatedState.Scale);
AssertQuaternionsAreEquivalent(Quaternion.Slerp(startRotation, serverSetRotation, percentChanged), otherClientComponent.AnticipatedState.Rotation);
AssertVectorsAreEquivalent(serverSetPosition, otherClientComponent.AuthoritativeState.Position);
AssertVectorsAreEquivalent(serverSetScale, otherClientComponent.AuthoritativeState.Scale);
AssertQuaternionsAreEquivalent(serverSetRotation, otherClientComponent.AuthoritativeState.Rotation);
for (var i = 1; i < 60; ++i)
{
TimeTravel(1f / 60f, 1);
percentChanged = 1f / 60f * (i + 1);
AssertVectorsAreEquivalent(Vector3.Lerp(anticipePosition, serverSetPosition, percentChanged), testComponent.transform.position);
AssertVectorsAreEquivalent(Vector3.Lerp(anticipeScale, serverSetScale, percentChanged), testComponent.transform.localScale);
AssertQuaternionsAreEquivalent(Quaternion.Slerp(anticipeRotation, serverSetRotation, percentChanged), testComponent.transform.rotation);
AssertVectorsAreEquivalent(Vector3.Lerp(anticipePosition, serverSetPosition, percentChanged), testComponent.AnticipatedState.Position);
AssertVectorsAreEquivalent(Vector3.Lerp(anticipeScale, serverSetScale, percentChanged), testComponent.AnticipatedState.Scale);
AssertQuaternionsAreEquivalent(Quaternion.Slerp(anticipeRotation, serverSetRotation, percentChanged), testComponent.AnticipatedState.Rotation);
AssertVectorsAreEquivalent(serverSetPosition, testComponent.AuthoritativeState.Position);
AssertVectorsAreEquivalent(serverSetScale, testComponent.AuthoritativeState.Scale);
AssertQuaternionsAreEquivalent(serverSetRotation, testComponent.AuthoritativeState.Rotation);
AssertVectorsAreEquivalent(Vector3.Lerp(startPosition, serverSetPosition, percentChanged), otherClientComponent.transform.position);
AssertVectorsAreEquivalent(Vector3.Lerp(startScale, serverSetScale, percentChanged), otherClientComponent.transform.localScale);
AssertQuaternionsAreEquivalent(Quaternion.Slerp(startRotation, serverSetRotation, percentChanged), otherClientComponent.transform.rotation);
AssertVectorsAreEquivalent(Vector3.Lerp(startPosition, serverSetPosition, percentChanged), otherClientComponent.AnticipatedState.Position);
AssertVectorsAreEquivalent(Vector3.Lerp(startScale, serverSetScale, percentChanged), otherClientComponent.AnticipatedState.Scale);
AssertQuaternionsAreEquivalent(Quaternion.Slerp(startRotation, serverSetRotation, percentChanged), otherClientComponent.AnticipatedState.Rotation);
AssertVectorsAreEquivalent(serverSetPosition, otherClientComponent.AuthoritativeState.Position);
AssertVectorsAreEquivalent(serverSetScale, otherClientComponent.AuthoritativeState.Scale);
AssertQuaternionsAreEquivalent(serverSetRotation, otherClientComponent.AuthoritativeState.Rotation);
}
TimeTravel(1f / 60f, 1);
AssertVectorsAreEquivalent(serverSetPosition, testComponent.transform.position);
AssertVectorsAreEquivalent(serverSetScale, testComponent.transform.localScale);
AssertQuaternionsAreEquivalent(serverSetRotation, testComponent.transform.rotation);
AssertVectorsAreEquivalent(serverSetPosition, testComponent.AnticipatedState.Position);
AssertVectorsAreEquivalent(serverSetScale, testComponent.AnticipatedState.Scale);
AssertQuaternionsAreEquivalent(serverSetRotation, testComponent.AnticipatedState.Rotation);
AssertVectorsAreEquivalent(serverSetPosition, testComponent.AuthoritativeState.Position);
AssertVectorsAreEquivalent(serverSetScale, testComponent.AuthoritativeState.Scale);
AssertQuaternionsAreEquivalent(serverSetRotation, testComponent.AuthoritativeState.Rotation);
AssertVectorsAreEquivalent(serverSetPosition, otherClientComponent.transform.position);
AssertVectorsAreEquivalent(serverSetScale, otherClientComponent.transform.localScale);
AssertQuaternionsAreEquivalent(serverSetRotation, otherClientComponent.transform.rotation);
AssertVectorsAreEquivalent(serverSetPosition, otherClientComponent.AnticipatedState.Position);
AssertVectorsAreEquivalent(serverSetScale, otherClientComponent.AnticipatedState.Scale);
AssertQuaternionsAreEquivalent(serverSetRotation, otherClientComponent.AnticipatedState.Rotation);
AssertVectorsAreEquivalent(serverSetPosition, otherClientComponent.AuthoritativeState.Position);
AssertVectorsAreEquivalent(serverSetScale, otherClientComponent.AuthoritativeState.Scale);
AssertQuaternionsAreEquivalent(serverSetRotation, otherClientComponent.AuthoritativeState.Rotation);
}
[Test]
public void WhenServerChangesReanticipeValue_ValuesAreReanticiped()
{
var testComponent = GetTestComponent();
var otherClientComponent = GetOtherClientComponent();
testComponent.GetComponent<NetworkTransformAnticipationComponent>().ShouldMove = true;
otherClientComponent.GetComponent<NetworkTransformAnticipationComponent>().ShouldMove = true;
var serverComponent = GetServerComponent();
serverComponent.Interpolate = false;
serverComponent.transform.position = new Vector3(0, 1, 2);
var rpcComponent = testComponent.GetComponent<NetworkTransformAnticipationComponent>();
rpcComponent.MoveRpc(new Vector3(0, 1, 2));
WaitForMessageReceivedWithTimeTravel<RpcMessage>(new List<NetworkManager> { m_ServerNetworkManager });
WaitForMessageReceivedWithTimeTravel<NetworkTransformMessage>(m_ClientNetworkManagers.ToList());
Assert.AreEqual(new Vector3(0, 6, 2), testComponent.transform.position);
Assert.AreEqual(new Vector3(0, 6, 2), testComponent.AnticipatedState.Position);
Assert.AreEqual(new Vector3(0, 1, 2), testComponent.AuthoritativeState.Position);
Assert.AreEqual(new Vector3(0, 6, 2), otherClientComponent.transform.position);
Assert.AreEqual(new Vector3(0, 6, 2), otherClientComponent.AnticipatedState.Position);
Assert.AreEqual(new Vector3(0, 1, 2), otherClientComponent.AuthoritativeState.Position);
}
[Test]
public void WhenStaleDataArrivesToIgnoreVariable_ItIsIgnored([Values(10u, 30u, 60u)] uint tickRate, [Values(0u, 1u, 2u)] uint skipFrames)
{
m_ServerNetworkManager.NetworkConfig.TickRate = tickRate;
m_ServerNetworkManager.NetworkTickSystem.TickRate = tickRate;
for (var i = 0; i < skipFrames; ++i)
{
TimeTravel(1 / 60f, 1);
}
var serverComponent = GetServerComponent();
serverComponent.Interpolate = false;
var testComponent = GetTestComponent();
testComponent.StaleDataHandling = StaleDataHandling.Ignore;
testComponent.Interpolate = false;
var otherClientComponent = GetOtherClientComponent();
otherClientComponent.StaleDataHandling = StaleDataHandling.Ignore;
otherClientComponent.Interpolate = false;
var rpcComponent = testComponent.GetComponent<NetworkTransformAnticipationComponent>();
rpcComponent.MoveRpc(new Vector3(1, 2, 3));
WaitForMessageReceivedWithTimeTravel<RpcMessage>(new List<NetworkManager> { m_ServerNetworkManager });
testComponent.AnticipateMove(new Vector3(0, 5, 0));
rpcComponent.MoveRpc(new Vector3(4, 5, 6));
// Depending on tick rate, one of these two things will happen.
// The assertions are different based on this... either the tick rate is slow enough that the second RPC is received
// before the next update and we move to 4, 5, 6, or the tick rate is fast enough that the next update is sent out
// before the RPC is received and we get the update for the move to 1, 2, 3. Both are valid, what we want to assert
// here is that the anticipated state never becomes 1, 2, 3.
WaitForConditionOrTimeOutWithTimeTravel(() => testComponent.AuthoritativeState.Position == new Vector3(1, 2, 3) || testComponent.AuthoritativeState.Position == new Vector3(4, 5, 6));
if (testComponent.AnticipatedState.Position == new Vector3(4, 5, 6))
{
// Anticiped client received this data for a time earlier than its anticipation, and should have prioritized the anticiped value
Assert.AreEqual(new Vector3(4, 5, 6), testComponent.transform.position);
Assert.AreEqual(new Vector3(4, 5, 6), testComponent.AnticipatedState.Position);
// However, the authoritative value still gets updated
Assert.AreEqual(new Vector3(4, 5, 6), testComponent.AuthoritativeState.Position);
// Other client got the server value and had made no anticipation, so it applies it to the anticiped value as well.
Assert.AreEqual(new Vector3(4, 5, 6), otherClientComponent.transform.position);
Assert.AreEqual(new Vector3(4, 5, 6), otherClientComponent.AnticipatedState.Position);
Assert.AreEqual(new Vector3(4, 5, 6), otherClientComponent.AuthoritativeState.Position);
}
else
{
// Anticiped client received this data for a time earlier than its anticipation, and should have prioritized the anticiped value
Assert.AreEqual(new Vector3(0, 5, 0), testComponent.transform.position);
Assert.AreEqual(new Vector3(0, 5, 0), testComponent.AnticipatedState.Position);
// However, the authoritative value still gets updated
Assert.AreEqual(new Vector3(1, 2, 3), testComponent.AuthoritativeState.Position);
// Other client got the server value and had made no anticipation, so it applies it to the anticiped value as well.
Assert.AreEqual(new Vector3(1, 2, 3), otherClientComponent.transform.position);
Assert.AreEqual(new Vector3(1, 2, 3), otherClientComponent.AnticipatedState.Position);
Assert.AreEqual(new Vector3(1, 2, 3), otherClientComponent.AuthoritativeState.Position);
}
}
[Test]
public void WhenNonStaleDataArrivesToIgnoreVariable_ItIsNotIgnored([Values(10u, 30u, 60u)] uint tickRate, [Values(0u, 1u, 2u)] uint skipFrames)
{
m_ServerNetworkManager.NetworkConfig.TickRate = tickRate;
m_ServerNetworkManager.NetworkTickSystem.TickRate = tickRate;
for (var i = 0; i < skipFrames; ++i)
{
TimeTravel(1 / 60f, 1);
}
var serverComponent = GetServerComponent();
serverComponent.Interpolate = false;
var testComponent = GetTestComponent();
testComponent.StaleDataHandling = StaleDataHandling.Ignore;
testComponent.Interpolate = false;
var otherClientComponent = GetOtherClientComponent();
otherClientComponent.StaleDataHandling = StaleDataHandling.Ignore;
otherClientComponent.Interpolate = false;
testComponent.AnticipateMove(new Vector3(0, 5, 0));
var rpcComponent = testComponent.GetComponent<NetworkTransformAnticipationComponent>();
rpcComponent.MoveRpc(new Vector3(1, 2, 3));
WaitForMessageReceivedWithTimeTravel<RpcMessage>(new List<NetworkManager> { m_ServerNetworkManager });
WaitForConditionOrTimeOutWithTimeTravel(() => testComponent.AuthoritativeState.Position == serverComponent.transform.position && otherClientComponent.AuthoritativeState.Position == serverComponent.transform.position);
// Anticiped client received this data for a time earlier than its anticipation, and should have prioritized the anticiped value
Assert.AreEqual(new Vector3(1, 2, 3), testComponent.transform.position);
Assert.AreEqual(new Vector3(1, 2, 3), testComponent.AnticipatedState.Position);
// However, the authoritative value still gets updated
Assert.AreEqual(new Vector3(1, 2, 3), testComponent.AuthoritativeState.Position);
// Other client got the server value and had made no anticipation, so it applies it to the anticiped value as well.
Assert.AreEqual(new Vector3(1, 2, 3), otherClientComponent.transform.position);
Assert.AreEqual(new Vector3(1, 2, 3), otherClientComponent.AnticipatedState.Position);
Assert.AreEqual(new Vector3(1, 2, 3), otherClientComponent.AuthoritativeState.Position);
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ceb074b080c27184a9f669cd68355955

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: a9db1d18fa0117f4da5e8e65386b894a
guid: 7b4da27c6efa9684893f85f5d3ad80e6
folderAsset: yes
DefaultImporter:
externalObjects: {}

View File

@@ -0,0 +1,420 @@
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Unity.Netcode.TestHelpers.Runtime;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Unity.Netcode.RuntimeTests
{
internal class NetworkVariableAnticipationComponent : NetworkBehaviour
{
public AnticipatedNetworkVariable<int> SnapOnAnticipationFailVariable = new AnticipatedNetworkVariable<int>(0, StaleDataHandling.Ignore);
public AnticipatedNetworkVariable<float> SmoothOnAnticipationFailVariable = new AnticipatedNetworkVariable<float>(0, StaleDataHandling.Reanticipate);
public AnticipatedNetworkVariable<float> ReanticipateOnAnticipationFailVariable = new AnticipatedNetworkVariable<float>(0, StaleDataHandling.Reanticipate);
public override void OnReanticipate(double lastRoundTripTime)
{
if (SmoothOnAnticipationFailVariable.ShouldReanticipate)
{
if (Mathf.Abs(SmoothOnAnticipationFailVariable.AuthoritativeValue - SmoothOnAnticipationFailVariable.PreviousAnticipatedValue) > Mathf.Epsilon)
{
SmoothOnAnticipationFailVariable.Smooth(SmoothOnAnticipationFailVariable.PreviousAnticipatedValue, SmoothOnAnticipationFailVariable.AuthoritativeValue, 1, Mathf.Lerp);
}
}
if (ReanticipateOnAnticipationFailVariable.ShouldReanticipate)
{
// Would love to test some stuff about anticipation based on time, but that is difficult to test accurately.
// This reanticipating variable will just always anticipate a value 5 higher than the server value.
ReanticipateOnAnticipationFailVariable.Anticipate(ReanticipateOnAnticipationFailVariable.AuthoritativeValue + 5);
}
}
public bool SnapRpcResponseReceived = false;
[Rpc(SendTo.Server)]
public void SetSnapValueRpc(int i, RpcParams rpcParams = default)
{
SnapOnAnticipationFailVariable.AuthoritativeValue = i;
SetSnapValueResponseRpc(RpcTarget.Single(rpcParams.Receive.SenderClientId, RpcTargetUse.Temp));
}
[Rpc(SendTo.SpecifiedInParams)]
public void SetSnapValueResponseRpc(RpcParams rpcParams)
{
SnapRpcResponseReceived = true;
}
[Rpc(SendTo.Server)]
public void SetSmoothValueRpc(float f)
{
SmoothOnAnticipationFailVariable.AuthoritativeValue = f;
}
[Rpc(SendTo.Server)]
public void SetReanticipateValueRpc(float f)
{
ReanticipateOnAnticipationFailVariable.AuthoritativeValue = f;
}
}
internal class NetworkVariableAnticipationTests : NetcodeIntegrationTest
{
protected override int NumberOfClients => 2;
protected override bool m_EnableTimeTravel => true;
protected override bool m_SetupIsACoroutine => false;
protected override bool m_TearDownIsACoroutine => false;
protected override void OnPlayerPrefabGameObjectCreated()
{
m_PlayerPrefab.AddComponent<NetworkVariableAnticipationComponent>();
}
public NetworkVariableAnticipationComponent GetTestComponent()
{
return m_ClientNetworkManagers[0].LocalClient.PlayerObject.GetComponent<NetworkVariableAnticipationComponent>();
}
public NetworkVariableAnticipationComponent GetServerComponent()
{
foreach (var obj in Object.FindObjectsByType<NetworkVariableAnticipationComponent>(FindObjectsSortMode.None))
{
if (obj.NetworkManager == m_ServerNetworkManager && obj.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId)
{
return obj;
}
}
return null;
}
public NetworkVariableAnticipationComponent GetOtherClientComponent()
{
foreach (var obj in Object.FindObjectsByType<NetworkVariableAnticipationComponent>(FindObjectsSortMode.None))
{
if (obj.NetworkManager == m_ClientNetworkManagers[1] && obj.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId)
{
return obj;
}
}
return null;
}
[Test]
public void WhenAnticipating_ValueChangesImmediately()
{
var testComponent = GetTestComponent();
testComponent.SnapOnAnticipationFailVariable.Anticipate(10);
testComponent.SmoothOnAnticipationFailVariable.Anticipate(15);
testComponent.ReanticipateOnAnticipationFailVariable.Anticipate(20);
Assert.AreEqual(10, testComponent.SnapOnAnticipationFailVariable.Value);
Assert.AreEqual(15, testComponent.SmoothOnAnticipationFailVariable.Value);
Assert.AreEqual(20, testComponent.ReanticipateOnAnticipationFailVariable.Value);
}
[Test]
public void WhenAnticipating_AuthoritativeValueDoesNotChange()
{
var testComponent = GetTestComponent();
testComponent.SnapOnAnticipationFailVariable.Anticipate(10);
testComponent.SmoothOnAnticipationFailVariable.Anticipate(15);
testComponent.ReanticipateOnAnticipationFailVariable.Anticipate(20);
Assert.AreEqual(0, testComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
Assert.AreEqual(0, testComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue);
Assert.AreEqual(0, testComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue);
}
[Test]
public void WhenAnticipating_ServerDoesNotChange()
{
var testComponent = GetTestComponent();
testComponent.SnapOnAnticipationFailVariable.Anticipate(10);
testComponent.SmoothOnAnticipationFailVariable.Anticipate(15);
testComponent.ReanticipateOnAnticipationFailVariable.Anticipate(20);
var serverComponent = GetServerComponent();
Assert.AreEqual(0, serverComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
Assert.AreEqual(0, serverComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue);
Assert.AreEqual(0, serverComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue);
Assert.AreEqual(0, serverComponent.SnapOnAnticipationFailVariable.Value);
Assert.AreEqual(0, serverComponent.SmoothOnAnticipationFailVariable.Value);
Assert.AreEqual(0, serverComponent.ReanticipateOnAnticipationFailVariable.Value);
TimeTravel(2, 120);
Assert.AreEqual(0, serverComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
Assert.AreEqual(0, serverComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue);
Assert.AreEqual(0, serverComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue);
Assert.AreEqual(0, serverComponent.SnapOnAnticipationFailVariable.Value);
Assert.AreEqual(0, serverComponent.SmoothOnAnticipationFailVariable.Value);
Assert.AreEqual(0, serverComponent.ReanticipateOnAnticipationFailVariable.Value);
}
[Test]
public void WhenAnticipating_OtherClientDoesNotChange()
{
var testComponent = GetTestComponent();
testComponent.SnapOnAnticipationFailVariable.Anticipate(10);
testComponent.SmoothOnAnticipationFailVariable.Anticipate(15);
testComponent.ReanticipateOnAnticipationFailVariable.Anticipate(20);
var otherClientComponent = GetOtherClientComponent();
Assert.AreEqual(0, otherClientComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
Assert.AreEqual(0, otherClientComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue);
Assert.AreEqual(0, otherClientComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue);
Assert.AreEqual(0, otherClientComponent.SnapOnAnticipationFailVariable.Value);
Assert.AreEqual(0, otherClientComponent.SmoothOnAnticipationFailVariable.Value);
Assert.AreEqual(0, otherClientComponent.ReanticipateOnAnticipationFailVariable.Value);
TimeTravel(2, 120);
Assert.AreEqual(0, otherClientComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
Assert.AreEqual(0, otherClientComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue);
Assert.AreEqual(0, otherClientComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue);
Assert.AreEqual(0, otherClientComponent.SnapOnAnticipationFailVariable.Value);
Assert.AreEqual(0, otherClientComponent.SmoothOnAnticipationFailVariable.Value);
Assert.AreEqual(0, otherClientComponent.ReanticipateOnAnticipationFailVariable.Value);
}
[Test]
public void WhenServerChangesSnapValue_ValuesAreUpdated()
{
var testComponent = GetTestComponent();
testComponent.SnapOnAnticipationFailVariable.Anticipate(10);
Assert.AreEqual(10, testComponent.SnapOnAnticipationFailVariable.Value);
Assert.AreEqual(0, testComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
testComponent.SetSnapValueRpc(10);
WaitForMessageReceivedWithTimeTravel<RpcMessage>(
new List<NetworkManager> { m_ServerNetworkManager }
);
var serverComponent = GetServerComponent();
Assert.AreEqual(10, serverComponent.SnapOnAnticipationFailVariable.Value);
Assert.AreEqual(10, serverComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
var otherClientComponent = GetOtherClientComponent();
Assert.AreEqual(0, otherClientComponent.SnapOnAnticipationFailVariable.Value);
Assert.AreEqual(0, otherClientComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
WaitForMessageReceivedWithTimeTravel<NetworkVariableDeltaMessage>(m_ClientNetworkManagers.ToList());
Assert.AreEqual(10, testComponent.SnapOnAnticipationFailVariable.Value);
Assert.AreEqual(10, testComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
Assert.AreEqual(10, otherClientComponent.SnapOnAnticipationFailVariable.Value);
Assert.AreEqual(10, otherClientComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
}
[Test]
public void WhenServerChangesSmoothValue_ValuesAreLerped()
{
var testComponent = GetTestComponent();
testComponent.SmoothOnAnticipationFailVariable.Anticipate(15);
Assert.AreEqual(15, testComponent.SmoothOnAnticipationFailVariable.Value, Mathf.Epsilon);
Assert.AreEqual(0, testComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon);
// Set to a different value to simulate a anticipation failure - will lerp between the anticipated value
// and the actual one
testComponent.SetSmoothValueRpc(20);
WaitForMessageReceivedWithTimeTravel<RpcMessage>(
new List<NetworkManager> { m_ServerNetworkManager }
);
var serverComponent = GetServerComponent();
Assert.AreEqual(20, serverComponent.SmoothOnAnticipationFailVariable.Value, Mathf.Epsilon);
Assert.AreEqual(20, serverComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon);
var otherClientComponent = GetOtherClientComponent();
Assert.AreEqual(0, otherClientComponent.SmoothOnAnticipationFailVariable.Value, Mathf.Epsilon);
Assert.AreEqual(0, otherClientComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon);
WaitForMessageReceivedWithTimeTravel<NetworkVariableDeltaMessage>(m_ClientNetworkManagers.ToList());
Assert.AreEqual(15 + 1f / 60f * 5, testComponent.SmoothOnAnticipationFailVariable.Value, Mathf.Epsilon);
Assert.AreEqual(20, testComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon);
Assert.AreEqual(0 + 1f / 60f * 20, otherClientComponent.SmoothOnAnticipationFailVariable.Value, Mathf.Epsilon);
Assert.AreEqual(20, otherClientComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon);
for (var i = 1; i < 60; ++i)
{
TimeTravel(1f / 60f, 1);
Assert.AreEqual(15 + 1f / 60f * 5 * (i + 1), testComponent.SmoothOnAnticipationFailVariable.Value, 0.00001);
Assert.AreEqual(20, testComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon);
Assert.AreEqual(0 + 1f / 60f * 20 * (i + 1), otherClientComponent.SmoothOnAnticipationFailVariable.Value, 0.00001);
Assert.AreEqual(20, otherClientComponent.SmoothOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon);
}
TimeTravel(1f / 60f, 1);
Assert.AreEqual(20, testComponent.SmoothOnAnticipationFailVariable.Value, Mathf.Epsilon);
Assert.AreEqual(20, otherClientComponent.SmoothOnAnticipationFailVariable.Value, Mathf.Epsilon);
}
[Test]
public void WhenServerChangesReanticipateValue_ValuesAreReanticipated()
{
var testComponent = GetTestComponent();
testComponent.ReanticipateOnAnticipationFailVariable.Anticipate(15);
Assert.AreEqual(15, testComponent.ReanticipateOnAnticipationFailVariable.Value, Mathf.Epsilon);
Assert.AreEqual(0, testComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon);
// Set to a different value to simulate a anticipation failure - will lerp between the anticipated value
// and the actual one
testComponent.SetReanticipateValueRpc(20);
WaitForMessageReceivedWithTimeTravel<RpcMessage>(
new List<NetworkManager> { m_ServerNetworkManager }
);
var serverComponent = GetServerComponent();
Assert.AreEqual(20, serverComponent.ReanticipateOnAnticipationFailVariable.Value, Mathf.Epsilon);
Assert.AreEqual(20, serverComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon);
var otherClientComponent = GetOtherClientComponent();
Assert.AreEqual(0, otherClientComponent.ReanticipateOnAnticipationFailVariable.Value, Mathf.Epsilon);
Assert.AreEqual(0, otherClientComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon);
WaitForMessageReceivedWithTimeTravel<NetworkVariableDeltaMessage>(m_ClientNetworkManagers.ToList());
Assert.AreEqual(25, testComponent.ReanticipateOnAnticipationFailVariable.Value, Mathf.Epsilon);
Assert.AreEqual(20, testComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon);
Assert.AreEqual(25, otherClientComponent.ReanticipateOnAnticipationFailVariable.Value, Mathf.Epsilon);
Assert.AreEqual(20, otherClientComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue, Mathf.Epsilon);
}
[Test]
public void WhenNonStaleDataArrivesToIgnoreVariable_ItIsNotIgnored([Values(10u, 30u, 60u)] uint tickRate, [Values(0u, 1u, 2u)] uint skipFrames)
{
m_ServerNetworkManager.NetworkConfig.TickRate = tickRate;
m_ServerNetworkManager.NetworkTickSystem.TickRate = tickRate;
for (var i = 0; i < skipFrames; ++i)
{
TimeTravel(1 / 60f, 1);
}
var testComponent = GetTestComponent();
testComponent.SnapOnAnticipationFailVariable.Anticipate(10);
Assert.AreEqual(10, testComponent.SnapOnAnticipationFailVariable.Value);
Assert.AreEqual(0, testComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
testComponent.SetSnapValueRpc(20);
WaitForMessageReceivedWithTimeTravel<RpcMessage>(new List<NetworkManager> { m_ServerNetworkManager });
var serverComponent = GetServerComponent();
Assert.AreEqual(20, serverComponent.SnapOnAnticipationFailVariable.Value);
Assert.AreEqual(20, serverComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
WaitForMessageReceivedWithTimeTravel<NetworkVariableDeltaMessage>(m_ClientNetworkManagers.ToList());
// Both values get updated
Assert.AreEqual(20, testComponent.SnapOnAnticipationFailVariable.Value);
Assert.AreEqual(20, testComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
// Other client got the server value and had made no anticipation, so it applies it to the anticipated value as well.
var otherClientComponent = GetOtherClientComponent();
Assert.AreEqual(20, otherClientComponent.SnapOnAnticipationFailVariable.Value);
Assert.AreEqual(20, otherClientComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
}
[Test]
public void WhenStaleDataArrivesToIgnoreVariable_ItIsIgnored([Values(10u, 30u, 60u)] uint tickRate, [Values(0u, 1u, 2u)] uint skipFrames)
{
m_ServerNetworkManager.NetworkConfig.TickRate = tickRate;
m_ServerNetworkManager.NetworkTickSystem.TickRate = tickRate;
for (var i = 0; i < skipFrames; ++i)
{
TimeTravel(1 / 60f, 1);
}
var testComponent = GetTestComponent();
testComponent.SnapOnAnticipationFailVariable.Anticipate(10);
Assert.AreEqual(10, testComponent.SnapOnAnticipationFailVariable.Value);
Assert.AreEqual(0, testComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
testComponent.SetSnapValueRpc(30);
var serverComponent = GetServerComponent();
serverComponent.SnapOnAnticipationFailVariable.AuthoritativeValue = 20;
Assert.AreEqual(20, serverComponent.SnapOnAnticipationFailVariable.Value);
Assert.AreEqual(20, serverComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
WaitForMessageReceivedWithTimeTravel<NetworkVariableDeltaMessage>(m_ClientNetworkManagers.ToList());
if (testComponent.SnapRpcResponseReceived)
{
// In this case the tick rate is slow enough that the RPC was received and processed, so we check that.
Assert.AreEqual(30, testComponent.SnapOnAnticipationFailVariable.Value);
Assert.AreEqual(30, testComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
var otherClientComponent = GetOtherClientComponent();
Assert.AreEqual(30, otherClientComponent.SnapOnAnticipationFailVariable.Value);
Assert.AreEqual(30, otherClientComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
}
else
{
// In this case, we got an update before the RPC was processed, so we should have ignored it.
// Anticipated client received this data for a tick earlier than its anticipation, and should have prioritized the anticipated value
Assert.AreEqual(10, testComponent.SnapOnAnticipationFailVariable.Value);
// However, the authoritative value still gets updated
Assert.AreEqual(20, testComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
// Other client got the server value and had made no anticipation, so it applies it to the anticipated value as well.
var otherClientComponent = GetOtherClientComponent();
Assert.AreEqual(20, otherClientComponent.SnapOnAnticipationFailVariable.Value);
Assert.AreEqual(20, otherClientComponent.SnapOnAnticipationFailVariable.AuthoritativeValue);
}
}
[Test]
public void WhenStaleDataArrivesToReanticipatedVariable_ItIsAppliedAndReanticipated()
{
var testComponent = GetTestComponent();
testComponent.ReanticipateOnAnticipationFailVariable.Anticipate(10);
Assert.AreEqual(10, testComponent.ReanticipateOnAnticipationFailVariable.Value);
Assert.AreEqual(0, testComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue);
var serverComponent = GetServerComponent();
serverComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue = 20;
Assert.AreEqual(20, serverComponent.ReanticipateOnAnticipationFailVariable.Value);
Assert.AreEqual(20, serverComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue);
WaitForMessageReceivedWithTimeTravel<NetworkVariableDeltaMessage>(m_ClientNetworkManagers.ToList());
Assert.AreEqual(25, testComponent.ReanticipateOnAnticipationFailVariable.Value);
// However, the authoritative value still gets updated
Assert.AreEqual(20, testComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue);
// Other client got the server value and had made no anticipation, so it applies it to the anticipated value as well.
var otherClientComponent = GetOtherClientComponent();
Assert.AreEqual(25, otherClientComponent.ReanticipateOnAnticipationFailVariable.Value);
Assert.AreEqual(20, otherClientComponent.ReanticipateOnAnticipationFailVariable.AuthoritativeValue);
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 74e627a9d18dcd04e9c56ab2539a6593

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7d01969a8bbbd7146a24490a5190ea7e

View File

@@ -0,0 +1,165 @@
#if !NGO_MINIMALPROJECT
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Unity.Netcode.TestHelpers.Runtime;
using UnityEngine;
using UnityEngine.TestTools;
namespace Unity.Netcode.RuntimeTests
{
[TestFixtureSource(nameof(TestDataSource))]
internal class NetworkVariableInheritanceTests : NetcodeIntegrationTest
{
public NetworkVariableInheritanceTests(HostOrServer hostOrServer)
: base(hostOrServer)
{
}
protected override int NumberOfClients => 2;
public static IEnumerable<TestFixtureData> TestDataSource() =>
Enum.GetValues(typeof(HostOrServer)).OfType<HostOrServer>().Select(x => new TestFixtureData(x));
internal class ComponentA : NetworkBehaviour
{
public NetworkVariable<int> PublicFieldA = new NetworkVariable<int>(1);
protected NetworkVariable<int> m_ProtectedFieldA = new NetworkVariable<int>(2);
private NetworkVariable<int> m_PrivateFieldA = new NetworkVariable<int>(3);
public void ChangeValuesA(int pub, int pro, int pri)
{
PublicFieldA.Value = pub;
m_ProtectedFieldA.Value = pro;
m_PrivateFieldA.Value = pri;
}
public bool CompareValuesA(ComponentA other)
{
return PublicFieldA.Value == other.PublicFieldA.Value &&
m_ProtectedFieldA.Value == other.m_ProtectedFieldA.Value &&
m_PrivateFieldA.Value == other.m_PrivateFieldA.Value;
}
}
internal class ComponentB : ComponentA
{
public NetworkVariable<int> PublicFieldB = new NetworkVariable<int>(11);
protected NetworkVariable<int> m_ProtectedFieldB = new NetworkVariable<int>(22);
private NetworkVariable<int> m_PrivateFieldB = new NetworkVariable<int>(33);
public void ChangeValuesB(int pub, int pro, int pri)
{
PublicFieldB.Value = pub;
m_ProtectedFieldB.Value = pro;
m_PrivateFieldB.Value = pri;
}
public bool CompareValuesB(ComponentB other)
{
return PublicFieldB.Value == other.PublicFieldB.Value &&
m_ProtectedFieldB.Value == other.m_ProtectedFieldB.Value &&
m_PrivateFieldB.Value == other.m_PrivateFieldB.Value;
}
}
internal class ComponentC : ComponentB
{
public NetworkVariable<int> PublicFieldC = new NetworkVariable<int>(111);
protected NetworkVariable<int> m_ProtectedFieldC = new NetworkVariable<int>(222);
private NetworkVariable<int> m_PrivateFieldC = new NetworkVariable<int>(333);
public void ChangeValuesC(int pub, int pro, int pri)
{
PublicFieldC.Value = pub;
m_ProtectedFieldA.Value = pro;
m_PrivateFieldC.Value = pri;
}
public bool CompareValuesC(ComponentC other)
{
return PublicFieldC.Value == other.PublicFieldC.Value &&
m_ProtectedFieldC.Value == other.m_ProtectedFieldC.Value &&
m_PrivateFieldC.Value == other.m_PrivateFieldC.Value;
}
}
private GameObject m_TestObjectPrefab;
private ulong m_TestObjectId = 0;
protected override void OnOneTimeSetup()
{
NetworkVariableBase.IgnoreInitializeWarning = true;
base.OnOneTimeSetup();
}
protected override void OnOneTimeTearDown()
{
NetworkVariableBase.IgnoreInitializeWarning = false;
base.OnOneTimeTearDown();
}
protected override void OnServerAndClientsCreated()
{
m_TestObjectPrefab = CreateNetworkObjectPrefab($"[{nameof(NetworkVariableInheritanceTests)}.{nameof(m_TestObjectPrefab)}]");
m_TestObjectPrefab.AddComponent<ComponentA>();
m_TestObjectPrefab.AddComponent<ComponentB>();
m_TestObjectPrefab.AddComponent<ComponentC>();
}
protected override IEnumerator OnServerAndClientsConnected()
{
var serverTestObject = SpawnObject(m_TestObjectPrefab, m_ServerNetworkManager).GetComponent<NetworkObject>();
m_TestObjectId = serverTestObject.NetworkObjectId;
var serverTestComponentA = serverTestObject.GetComponent<ComponentA>();
var serverTestComponentB = serverTestObject.GetComponent<ComponentB>();
var serverTestComponentC = serverTestObject.GetComponent<ComponentC>();
serverTestComponentA.ChangeValuesA(1000, 2000, 3000);
serverTestComponentB.ChangeValuesA(1000, 2000, 3000);
serverTestComponentB.ChangeValuesB(1100, 2200, 3300);
serverTestComponentC.ChangeValuesA(1000, 2000, 3000);
serverTestComponentC.ChangeValuesB(1100, 2200, 3300);
serverTestComponentC.ChangeValuesC(1110, 2220, 3330);
yield return WaitForTicks(m_ServerNetworkManager, 2);
}
private bool CheckTestObjectComponentValuesOnAll()
{
var serverTestObject = m_ServerNetworkManager.SpawnManager.SpawnedObjects[m_TestObjectId];
var serverTestComponentA = serverTestObject.GetComponent<ComponentA>();
var serverTestComponentB = serverTestObject.GetComponent<ComponentB>();
var serverTestComponentC = serverTestObject.GetComponent<ComponentC>();
foreach (var clientNetworkManager in m_ClientNetworkManagers)
{
var clientTestObject = clientNetworkManager.SpawnManager.SpawnedObjects[m_TestObjectId];
var clientTestComponentA = clientTestObject.GetComponent<ComponentA>();
var clientTestComponentB = clientTestObject.GetComponent<ComponentB>();
var clientTestComponentC = clientTestObject.GetComponent<ComponentC>();
if (!serverTestComponentA.CompareValuesA(clientTestComponentA) ||
!serverTestComponentB.CompareValuesA(clientTestComponentB) ||
!serverTestComponentB.CompareValuesB(clientTestComponentB) ||
!serverTestComponentC.CompareValuesA(clientTestComponentC) ||
!serverTestComponentC.CompareValuesB(clientTestComponentC) ||
!serverTestComponentC.CompareValuesC(clientTestComponentC))
{
return false;
}
}
return true;
}
[UnityTest]
public IEnumerator TestInheritedFields()
{
yield return WaitForConditionOrTimeOut(CheckTestObjectComponentValuesOnAll);
Assert.IsFalse(s_GlobalTimeoutHelper.TimedOut, nameof(CheckTestObjectComponentValuesOnAll));
}
}
}
#endif

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 41d4aef8f33a8eb4e87879075f868e66

View File

@@ -0,0 +1,306 @@
#if !NGO_MINIMALPROJECT
using System;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using Unity.Netcode.TestHelpers.Runtime;
using UnityEngine;
using UnityEngine.TestTools;
using Random = UnityEngine.Random;
namespace Unity.Netcode.RuntimeTests
{
[TestFixtureSource(nameof(TestDataSource))]
internal class NetworkVariablePermissionTests : NetcodeIntegrationTest
{
public static IEnumerable<TestFixtureData> TestDataSource()
{
NetworkVariableBase.IgnoreInitializeWarning = true;
foreach (HostOrServer hostOrServer in Enum.GetValues(typeof(HostOrServer)))
{
// DANGO-EXP TODO: Add support for distributed authority mode
if (hostOrServer == HostOrServer.DAHost)
{
continue;
}
yield return new TestFixtureData(hostOrServer);
}
NetworkVariableBase.IgnoreInitializeWarning = false;
}
protected override int NumberOfClients => 3;
public NetworkVariablePermissionTests(HostOrServer hostOrServer) : base(hostOrServer) { }
private GameObject m_TestObjPrefab;
private ulong m_TestObjId = 0;
protected override void OnServerAndClientsCreated()
{
m_TestObjPrefab = CreateNetworkObjectPrefab($"[{nameof(NetworkVariablePermissionTests)}.{nameof(m_TestObjPrefab)}]");
var testComp = m_TestObjPrefab.AddComponent<NetVarPermTestComp>();
}
protected override IEnumerator OnServerAndClientsConnected()
{
m_TestObjId = SpawnObject(m_TestObjPrefab, m_ServerNetworkManager).GetComponent<NetworkObject>().NetworkObjectId;
yield return null;
}
private IEnumerator WaitForPositionsAreEqual(NetworkVariable<Vector3> netvar, Vector3 expected)
{
yield return WaitForConditionOrTimeOut(() => netvar.Value == expected);
Assert.IsFalse(s_GlobalTimeoutHelper.TimedOut);
}
private IEnumerator WaitForOwnerWritableAreEqualOnAll()
{
yield return WaitForConditionOrTimeOut(CheckOwnerWritableAreEqualOnAll);
Assert.IsFalse(s_GlobalTimeoutHelper.TimedOut);
}
private bool CheckOwnerWritableAreEqualOnAll()
{
var testObjServer = m_ServerNetworkManager.SpawnManager.SpawnedObjects[m_TestObjId];
var testCompServer = testObjServer.GetComponent<NetVarPermTestComp>();
foreach (var clientNetworkManager in m_ClientNetworkManagers)
{
var testObjClient = clientNetworkManager.SpawnManager.SpawnedObjects[m_TestObjId];
var testCompClient = testObjClient.GetComponent<NetVarPermTestComp>();
if (testObjServer.OwnerClientId != testObjClient.OwnerClientId ||
testCompServer.OwnerWritable_Position.Value != testCompClient.OwnerWritable_Position.Value ||
testCompServer.OwnerWritable_Position.ReadPerm != testCompClient.OwnerWritable_Position.ReadPerm ||
testCompServer.OwnerWritable_Position.WritePerm != testCompClient.OwnerWritable_Position.WritePerm)
{
return false;
}
}
return true;
}
private IEnumerator WaitForServerWritableAreEqualOnAll()
{
yield return WaitForConditionOrTimeOut(CheckServerWritableAreEqualOnAll);
Assert.IsFalse(s_GlobalTimeoutHelper.TimedOut);
}
private bool CheckServerWritableAreEqualOnAll()
{
var testObjServer = m_ServerNetworkManager.SpawnManager.SpawnedObjects[m_TestObjId];
var testCompServer = testObjServer.GetComponent<NetVarPermTestComp>();
foreach (var clientNetworkManager in m_ClientNetworkManagers)
{
var testObjClient = clientNetworkManager.SpawnManager.SpawnedObjects[m_TestObjId];
var testCompClient = testObjClient.GetComponent<NetVarPermTestComp>();
if (testCompServer.ServerWritable_Position.Value != testCompClient.ServerWritable_Position.Value ||
testCompServer.ServerWritable_Position.ReadPerm != testCompClient.ServerWritable_Position.ReadPerm ||
testCompServer.ServerWritable_Position.WritePerm != testCompClient.ServerWritable_Position.WritePerm)
{
return false;
}
}
return true;
}
private bool CheckOwnerReadWriteAreEqualOnOwnerAndServer()
{
var testObjServer = m_ServerNetworkManager.SpawnManager.SpawnedObjects[m_TestObjId];
var testCompServer = testObjServer.GetComponent<NetVarPermTestComp>();
foreach (var clientNetworkManager in m_ClientNetworkManagers)
{
var testObjClient = clientNetworkManager.SpawnManager.SpawnedObjects[m_TestObjId];
var testCompClient = testObjClient.GetComponent<NetVarPermTestComp>();
if (testObjServer.OwnerClientId == testObjClient.OwnerClientId &&
testCompServer.OwnerReadWrite_Position.Value == testCompClient.ServerWritable_Position.Value &&
testCompServer.OwnerReadWrite_Position.ReadPerm == testCompClient.ServerWritable_Position.ReadPerm &&
testCompServer.OwnerReadWrite_Position.WritePerm == testCompClient.ServerWritable_Position.WritePerm)
{
return true;
}
}
return false;
}
private bool CheckOwnerReadWriteAreNotEqualOnNonOwnerClients(NetVarPermTestComp ownerReadWriteObject)
{
foreach (var clientNetworkManager in m_ClientNetworkManagers)
{
var testObjClient = clientNetworkManager.SpawnManager.SpawnedObjects[m_TestObjId];
var testCompClient = testObjClient.GetComponent<NetVarPermTestComp>();
if (testObjClient.OwnerClientId != ownerReadWriteObject.OwnerClientId ||
ownerReadWriteObject.OwnerReadWrite_Position.Value == testCompClient.ServerWritable_Position.Value ||
ownerReadWriteObject.OwnerReadWrite_Position.ReadPerm != testCompClient.ServerWritable_Position.ReadPerm ||
ownerReadWriteObject.OwnerReadWrite_Position.WritePerm != testCompClient.ServerWritable_Position.WritePerm)
{
return false;
}
}
return true;
}
[UnityTest]
public IEnumerator ServerChangesOwnerWritableNetVar()
{
yield return WaitForOwnerWritableAreEqualOnAll();
var testObjServer = m_ServerNetworkManager.SpawnManager.SpawnedObjects[m_TestObjId];
var testCompServer = testObjServer.GetComponent<NetVarPermTestComp>();
var oldValue = testCompServer.OwnerWritable_Position.Value;
var newValue = oldValue + new Vector3(Random.Range(0, 100.0f), Random.Range(0, 100.0f), Random.Range(0, 100.0f));
testCompServer.OwnerWritable_Position.Value = newValue;
yield return WaitForPositionsAreEqual(testCompServer.OwnerWritable_Position, newValue);
yield return WaitForOwnerWritableAreEqualOnAll();
}
[UnityTest]
public IEnumerator ServerChangesServerWritableNetVar()
{
yield return WaitForServerWritableAreEqualOnAll();
var testObjServer = m_ServerNetworkManager.SpawnManager.SpawnedObjects[m_TestObjId];
var testCompServer = testObjServer.GetComponent<NetVarPermTestComp>();
var oldValue = testCompServer.ServerWritable_Position.Value;
var newValue = oldValue + new Vector3(Random.Range(0, 100.0f), Random.Range(0, 100.0f), Random.Range(0, 100.0f));
testCompServer.ServerWritable_Position.Value = newValue;
yield return WaitForPositionsAreEqual(testCompServer.ServerWritable_Position, newValue);
yield return WaitForServerWritableAreEqualOnAll();
}
[UnityTest]
public IEnumerator ClientChangesOwnerWritableNetVar()
{
yield return WaitForOwnerWritableAreEqualOnAll();
var testObjServer = m_ServerNetworkManager.SpawnManager.SpawnedObjects[m_TestObjId];
int clientManagerIndex = m_ClientNetworkManagers.Length - 1;
var newOwnerClientId = m_ClientNetworkManagers[clientManagerIndex].LocalClientId;
testObjServer.ChangeOwnership(newOwnerClientId);
yield return WaitForTicks(m_ServerNetworkManager, 2);
yield return WaitForOwnerWritableAreEqualOnAll();
var testObjClient = m_ClientNetworkManagers[clientManagerIndex].SpawnManager.SpawnedObjects[m_TestObjId];
var testCompClient = testObjClient.GetComponent<NetVarPermTestComp>();
var oldValue = testCompClient.OwnerWritable_Position.Value;
var newValue = oldValue + new Vector3(Random.Range(0, 100.0f), Random.Range(0, 100.0f), Random.Range(0, 100.0f));
testCompClient.OwnerWritable_Position.Value = newValue;
yield return WaitForPositionsAreEqual(testCompClient.OwnerWritable_Position, newValue);
yield return WaitForOwnerWritableAreEqualOnAll();
}
/// <summary>
/// This tests the scenario where a client owner has both read and write
/// permissions set. The server should be the only instance that can read
/// the NetworkVariable. ServerCannotChangeOwnerWritableNetVar performs
/// the same check to make sure the server cannot write to a client owner
/// NetworkVariable with owner write permissions.
/// </summary>
[UnityTest]
public IEnumerator ClientOwnerWithReadWriteChangesNetVar()
{
yield return WaitForOwnerWritableAreEqualOnAll();
var testObjServer = m_ServerNetworkManager.SpawnManager.SpawnedObjects[m_TestObjId];
int clientManagerIndex = m_ClientNetworkManagers.Length - 1;
var newOwnerClientId = m_ClientNetworkManagers[clientManagerIndex].LocalClientId;
testObjServer.ChangeOwnership(newOwnerClientId);
yield return WaitForTicks(m_ServerNetworkManager, 2);
yield return WaitForOwnerWritableAreEqualOnAll();
var testObjClient = m_ClientNetworkManagers[clientManagerIndex].SpawnManager.SpawnedObjects[m_TestObjId];
var testCompClient = testObjClient.GetComponent<NetVarPermTestComp>();
var oldValue = testCompClient.OwnerReadWrite_Position.Value;
var newValue = oldValue + new Vector3(Random.Range(0, 100.0f), Random.Range(0, 100.0f), Random.Range(0, 100.0f));
testCompClient.OwnerWritable_Position.Value = newValue;
yield return WaitForPositionsAreEqual(testCompClient.OwnerWritable_Position, newValue);
// Verify the client owner and server match
yield return CheckOwnerReadWriteAreEqualOnOwnerAndServer();
// Verify the non-owner clients do not have the same Value but do have the same permissions
yield return CheckOwnerReadWriteAreNotEqualOnNonOwnerClients(testCompClient);
}
[UnityTest]
public IEnumerator ClientCannotChangeServerWritableNetVar()
{
yield return WaitForServerWritableAreEqualOnAll();
var testObjServer = m_ServerNetworkManager.SpawnManager.SpawnedObjects[m_TestObjId];
var testCompServer = testObjServer.GetComponent<NetVarPermTestComp>();
int clientManagerIndex = m_ClientNetworkManagers.Length - 1;
var newOwnerClientId = m_ClientNetworkManagers[clientManagerIndex].LocalClientId;
testObjServer.ChangeOwnership(newOwnerClientId);
yield return WaitForTicks(m_ServerNetworkManager, 2);
yield return WaitForServerWritableAreEqualOnAll();
var testObjClient = m_ClientNetworkManagers[clientManagerIndex].SpawnManager.SpawnedObjects[m_TestObjId];
var testCompClient = testObjClient.GetComponent<NetVarPermTestComp>();
var oldValue = testCompClient.ServerWritable_Position.Value;
var newValue = oldValue + new Vector3(Random.Range(0, 100.0f), Random.Range(0, 100.0f), Random.Range(0, 100.0f));
LogAssert.Expect(LogType.Error, testCompClient.ServerWritable_Position.GetWritePermissionError());
testCompClient.ServerWritable_Position.Value = newValue;
yield return WaitForPositionsAreEqual(testCompServer.ServerWritable_Position, oldValue);
yield return WaitForServerWritableAreEqualOnAll();
testCompServer.ServerWritable_Position.Value = newValue;
yield return WaitForPositionsAreEqual(testCompServer.ServerWritable_Position, newValue);
yield return WaitForServerWritableAreEqualOnAll();
}
[UnityTest]
public IEnumerator ServerCannotChangeOwnerWritableNetVar()
{
yield return WaitForOwnerWritableAreEqualOnAll();
var testObjServer = m_ServerNetworkManager.SpawnManager.SpawnedObjects[m_TestObjId];
var testCompServer = testObjServer.GetComponent<NetVarPermTestComp>();
int clientManagerIndex = m_ClientNetworkManagers.Length - 1;
var newOwnerClientId = m_ClientNetworkManagers[clientManagerIndex].LocalClientId;
testObjServer.ChangeOwnership(newOwnerClientId);
yield return WaitForTicks(m_ServerNetworkManager, 4);
yield return WaitForOwnerWritableAreEqualOnAll();
var oldValue = testCompServer.OwnerWritable_Position.Value;
var newValue = oldValue + new Vector3(Random.Range(0, 100.0f), Random.Range(0, 100.0f), Random.Range(0, 100.0f));
LogAssert.Expect(LogType.Error, testCompServer.OwnerWritable_Position.GetWritePermissionError());
testCompServer.OwnerWritable_Position.Value = newValue;
yield return WaitForPositionsAreEqual(testCompServer.OwnerWritable_Position, oldValue);
yield return WaitForOwnerWritableAreEqualOnAll();
var testObjClient = m_ClientNetworkManagers[clientManagerIndex].SpawnManager.SpawnedObjects[m_TestObjId];
var testCompClient = testObjClient.GetComponent<NetVarPermTestComp>();
testCompClient.OwnerWritable_Position.Value = newValue;
yield return WaitForPositionsAreEqual(testCompClient.OwnerWritable_Position, newValue);
yield return WaitForOwnerWritableAreEqualOnAll();
}
}
}
#endif

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 60d49d322bef8ff4ebb8c4abf57e18e3

View File

@@ -903,7 +903,7 @@ namespace Unity.Netcode.RuntimeTests
}
// Please do not reference TestClass_ReferencedOnlyByTemplateNetworkBehavourType anywhere other than here!
internal class ClassHavingNetworkBehaviour2 : TemplateNetworkBehaviourType<TestClass_ReferencedOnlyByTemplateNetworkBehavourType>
internal class ClassHavingNetworkBehaviour2 : TemplateNetworkBehaviourType<TestClass_ReferencedOnlyByTemplateNetworkBehaviourType>
{
}

View File

@@ -0,0 +1,138 @@
using NUnit.Framework;
using Unity.Netcode.TestHelpers.Runtime;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Unity.Netcode.RuntimeTests
{
internal class NetworkVariableTraitsComponent : NetworkBehaviour
{
public NetworkVariable<float> TheVariable = new NetworkVariable<float>();
}
internal class NetworkVariableTraitsTests : NetcodeIntegrationTest
{
protected override int NumberOfClients => 2;
protected override bool m_EnableTimeTravel => true;
protected override bool m_SetupIsACoroutine => false;
protected override bool m_TearDownIsACoroutine => false;
protected override void OnPlayerPrefabGameObjectCreated()
{
m_PlayerPrefab.AddComponent<NetworkVariableTraitsComponent>();
}
public NetworkVariableTraitsComponent GetTestComponent()
{
return m_ClientNetworkManagers[0].LocalClient.PlayerObject.GetComponent<NetworkVariableTraitsComponent>();
}
public NetworkVariableTraitsComponent GetServerComponent()
{
foreach (var obj in Object.FindObjectsByType<NetworkVariableTraitsComponent>(FindObjectsSortMode.None))
{
if (obj.NetworkManager == m_ServerNetworkManager && obj.OwnerClientId == m_ClientNetworkManagers[0].LocalClientId)
{
return obj;
}
}
return null;
}
[Test]
public void WhenNewValueIsLessThanThreshold_VariableIsNotSerialized()
{
var serverComponent = GetServerComponent();
var testComponent = GetTestComponent();
serverComponent.TheVariable.CheckExceedsDirtinessThreshold = (in float value, in float newValue) => Mathf.Abs(newValue - value) >= 0.1;
serverComponent.TheVariable.Value = 0.05f;
TimeTravel(2, 120);
Assert.AreEqual(0.05f, serverComponent.TheVariable.Value); ;
Assert.AreEqual(0, testComponent.TheVariable.Value); ;
}
[Test]
public void WhenNewValueIsGreaterThanThreshold_VariableIsSerialized()
{
var serverComponent = GetServerComponent();
var testComponent = GetTestComponent();
serverComponent.TheVariable.CheckExceedsDirtinessThreshold = (in float value, in float newValue) => Mathf.Abs(newValue - value) >= 0.1;
serverComponent.TheVariable.Value = 0.15f;
TimeTravel(2, 120);
Assert.AreEqual(0.15f, serverComponent.TheVariable.Value); ;
Assert.AreEqual(0.15f, testComponent.TheVariable.Value); ;
}
[Test]
public void WhenNewValueIsLessThanThresholdButMaxTimeHasPassed_VariableIsSerialized()
{
var serverComponent = GetServerComponent();
var testComponent = GetTestComponent();
serverComponent.TheVariable.CheckExceedsDirtinessThreshold = (in float value, in float newValue) => Mathf.Abs(newValue - value) >= 0.1;
serverComponent.TheVariable.SetUpdateTraits(new NetworkVariableUpdateTraits { MaxSecondsBetweenUpdates = 2 });
serverComponent.TheVariable.LastUpdateSent = m_ServerNetworkManager.NetworkTimeSystem.LocalTime;
serverComponent.TheVariable.Value = 0.05f;
TimeTravel(1 / 60f * 119, 119);
Assert.AreEqual(0.05f, serverComponent.TheVariable.Value); ;
Assert.AreEqual(0, testComponent.TheVariable.Value); ;
TimeTravel(1 / 60f * 4, 4);
Assert.AreEqual(0.05f, serverComponent.TheVariable.Value); ;
Assert.AreEqual(0.05f, testComponent.TheVariable.Value); ;
}
[Test]
public void WhenNewValueIsGreaterThanThresholdButMinTimeHasNotPassed_VariableIsNotSerialized()
{
var serverComponent = GetServerComponent();
var testComponent = GetTestComponent();
serverComponent.TheVariable.CheckExceedsDirtinessThreshold = (in float value, in float newValue) => Mathf.Abs(newValue - value) >= 0.1;
serverComponent.TheVariable.SetUpdateTraits(new NetworkVariableUpdateTraits { MinSecondsBetweenUpdates = 2 });
serverComponent.TheVariable.LastUpdateSent = m_ServerNetworkManager.NetworkTimeSystem.LocalTime;
serverComponent.TheVariable.Value = 0.15f;
TimeTravel(1 / 60f * 119, 119);
Assert.AreEqual(0.15f, serverComponent.TheVariable.Value); ;
Assert.AreEqual(0, testComponent.TheVariable.Value); ;
TimeTravel(1 / 60f * 4, 4);
Assert.AreEqual(0.15f, serverComponent.TheVariable.Value); ;
Assert.AreEqual(0.15f, testComponent.TheVariable.Value); ;
}
[Test]
public void WhenNoThresholdIsSetButMinTimeHasNotPassed_VariableIsNotSerialized()
{
var serverComponent = GetServerComponent();
var testComponent = GetTestComponent();
serverComponent.TheVariable.SetUpdateTraits(new NetworkVariableUpdateTraits { MinSecondsBetweenUpdates = 2 });
serverComponent.TheVariable.LastUpdateSent = m_ServerNetworkManager.NetworkTimeSystem.LocalTime;
serverComponent.TheVariable.Value = 0.15f;
TimeTravel(1 / 60f * 119, 119);
Assert.AreEqual(0.15f, serverComponent.TheVariable.Value); ;
Assert.AreEqual(0, testComponent.TheVariable.Value); ;
TimeTravel(1 / 60f * 4, 4);
Assert.AreEqual(0.15f, serverComponent.TheVariable.Value); ;
Assert.AreEqual(0.15f, testComponent.TheVariable.Value); ;
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 49f46ca2b4327464498a7465891647bb

View File

@@ -112,6 +112,16 @@ namespace Unity.Netcode.RuntimeTests
protected override IEnumerator OnSetup()
{
WorkingUserNetworkVariableComponentBase.Reset();
UserNetworkVariableSerialization<MyTypeOne>.WriteValue = null;
UserNetworkVariableSerialization<MyTypeOne>.ReadValue = null;
UserNetworkVariableSerialization<MyTypeOne>.DuplicateValue = null;
UserNetworkVariableSerialization<MyTypeTwo>.WriteValue = null;
UserNetworkVariableSerialization<MyTypeTwo>.ReadValue = null;
UserNetworkVariableSerialization<MyTypeTwo>.DuplicateValue = null;
UserNetworkVariableSerialization<MyTypeThree>.WriteValue = null;
UserNetworkVariableSerialization<MyTypeThree>.ReadValue = null;
UserNetworkVariableSerialization<MyTypeThree>.DuplicateValue = null;
return base.OnSetup();
}
@@ -217,5 +227,37 @@ namespace Unity.Netcode.RuntimeTests
}
);
}
protected override IEnumerator OnTearDown()
{
// These have to get set to SOMETHING, otherwise we will get an exception thrown because Object.Destroy()
// calls __initializeNetworkVariables, and the network variable initialization attempts to call FallbackSerializer<T>,
// which throws an exception if any of these values are null. They don't have to DO anything, they just have to
// be non-null to keep the test from failing during teardown.
// None of this is related to what's being tested above, and in reality, these values being null is an invalid
// use case. But one of the tests is explicitly testing that invalid use case, and the values are being set
// to null in OnSetup to ensure test isolation. This wouldn't be a situation a user would have to think about
// in a real world use case.
UserNetworkVariableSerialization<MyTypeOne>.WriteValue = (FastBufferWriter writer, in MyTypeOne value) => { };
UserNetworkVariableSerialization<MyTypeOne>.ReadValue = (FastBufferReader reader, out MyTypeOne value) => { value = new MyTypeOne(); };
UserNetworkVariableSerialization<MyTypeOne>.DuplicateValue = (in MyTypeOne value, ref MyTypeOne duplicatedValue) =>
{
duplicatedValue = value;
};
UserNetworkVariableSerialization<MyTypeTwo>.WriteValue = (FastBufferWriter writer, in MyTypeTwo value) => { };
UserNetworkVariableSerialization<MyTypeTwo>.ReadValue = (FastBufferReader reader, out MyTypeTwo value) => { value = new MyTypeTwo(); };
UserNetworkVariableSerialization<MyTypeTwo>.DuplicateValue = (in MyTypeTwo value, ref MyTypeTwo duplicatedValue) =>
{
duplicatedValue = value;
};
UserNetworkVariableSerialization<MyTypeThree>.WriteValue = (FastBufferWriter writer, in MyTypeThree value) => { };
UserNetworkVariableSerialization<MyTypeThree>.ReadValue = (FastBufferReader reader, out MyTypeThree value) => { value = new MyTypeThree(); };
UserNetworkVariableSerialization<MyTypeThree>.DuplicateValue = (in MyTypeThree value, ref MyTypeThree duplicatedValue) =>
{
duplicatedValue = value;
};
return base.OnTearDown();
}
}
}

View File

@@ -1,4 +1,3 @@
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.Netcode.TestHelpers.Runtime;
@@ -50,7 +49,6 @@ namespace Unity.Netcode.RuntimeTests
public override void OnNetworkSpawn()
{
Objects[CurrentlySpawning, NetworkManager.LocalClientId] = GetComponent<OwnerPermissionObject>();
//Debug.Log($"Object index ({CurrentlySpawning}) spawned on client {NetworkManager.LocalClientId}");
}
private void Awake()
@@ -85,6 +83,8 @@ namespace Unity.Netcode.RuntimeTests
}
}
internal class OwnerPermissionHideTests : NetcodeIntegrationTest
{
protected override int NumberOfClients => 2;
@@ -130,70 +130,44 @@ namespace Unity.Netcode.RuntimeTests
for (var clientWriting = 0; clientWriting < 3; clientWriting++)
{
// ==== Server-writable NetworkVariable ====
var gotException = false;
VerboseDebug($"Writing to server-write variable on object {objectIndex} on client {clientWriting}");
try
{
nextValueToWrite++;
OwnerPermissionObject.Objects[objectIndex, clientWriting].MyNetworkVariableServer.Value = nextValueToWrite;
}
catch (Exception)
if (clientWriting != serverIndex)
{
gotException = true;
LogAssert.Expect(LogType.Error, OwnerPermissionObject.Objects[objectIndex, clientWriting].MyNetworkVariableServer.GetWritePermissionError());
}
// Verify server-owned netvar can only be written by server
Debug.Assert(gotException == (clientWriting != serverIndex));
OwnerPermissionObject.Objects[objectIndex, clientWriting].MyNetworkVariableServer.Value = nextValueToWrite;
// ==== Owner-writable NetworkVariable ====
gotException = false;
VerboseDebug($"Writing to owner-write variable on object {objectIndex} on client {clientWriting}");
try
{
nextValueToWrite++;
OwnerPermissionObject.Objects[objectIndex, clientWriting].MyNetworkVariableOwner.Value = nextValueToWrite;
}
catch (Exception)
if (clientWriting != objectIndex)
{
gotException = true;
LogAssert.Expect(LogType.Error, OwnerPermissionObject.Objects[objectIndex, clientWriting].MyNetworkVariableOwner.GetWritePermissionError());
}
// Verify client-owned netvar can only be written by owner
Debug.Assert(gotException == (clientWriting != objectIndex));
OwnerPermissionObject.Objects[objectIndex, clientWriting].MyNetworkVariableOwner.Value = nextValueToWrite;
// ==== Server-writable NetworkList ====
gotException = false;
VerboseDebug($"Writing to [Add] server-write NetworkList on object {objectIndex} on client {clientWriting}");
try
{
nextValueToWrite++;
OwnerPermissionObject.Objects[objectIndex, clientWriting].MyNetworkListServer.Add(nextValueToWrite);
}
catch (Exception)
if (clientWriting != serverIndex)
{
gotException = true;
LogAssert.Expect(LogType.Error, OwnerPermissionObject.Objects[objectIndex, clientWriting].MyNetworkListServer.GetWritePermissionError());
}
// Verify server-owned networkList can only be written by server
Debug.Assert(gotException == (clientWriting != serverIndex));
OwnerPermissionObject.Objects[objectIndex, clientWriting].MyNetworkListServer.Add(nextValueToWrite);
// ==== Owner-writable NetworkList ====
gotException = false;
VerboseDebug($"Writing to [Add] owner-write NetworkList on object {objectIndex} on client {clientWriting}");
try
{
nextValueToWrite++;
OwnerPermissionObject.Objects[objectIndex, clientWriting].MyNetworkListOwner.Add(nextValueToWrite);
}
catch (Exception)
if (clientWriting != objectIndex)
{
gotException = true;
LogAssert.Expect(LogType.Error, OwnerPermissionObject.Objects[objectIndex, clientWriting].MyNetworkListOwner.GetWritePermissionError());
}
// Verify client-owned networkList can only be written by owner
Debug.Assert(gotException == (clientWriting != objectIndex));
OwnerPermissionObject.Objects[objectIndex, clientWriting].MyNetworkListOwner.Add(nextValueToWrite);
yield return WaitForTicks(m_ServerNetworkManager, 5);
yield return WaitForTicks(m_ClientNetworkManagers[0], 5);

View File

@@ -17,6 +17,8 @@ namespace Unity.Netcode.RuntimeTests
{
private class TestNetworkBehaviour : NetworkBehaviour
{
public static bool ReceivedRPC;
public NetworkVariable<NetworkBehaviourReference> TestVariable = new NetworkVariable<NetworkBehaviourReference>();
public TestNetworkBehaviour RpcReceivedBehaviour;
@@ -25,6 +27,7 @@ namespace Unity.Netcode.RuntimeTests
public void SendReferenceServerRpc(NetworkBehaviourReference value)
{
RpcReceivedBehaviour = (TestNetworkBehaviour)value;
ReceivedRPC = true;
}
}
@@ -57,8 +60,43 @@ namespace Unity.Netcode.RuntimeTests
Assert.AreEqual(testNetworkBehaviour, testNetworkBehaviour.RpcReceivedBehaviour);
}
[UnityTest]
public IEnumerator TestSerializeNull([Values] bool initializeWithNull)
{
TestNetworkBehaviour.ReceivedRPC = false;
using var networkObjectContext = UnityObjectContext.CreateNetworkObject();
var testNetworkBehaviour = networkObjectContext.Object.gameObject.AddComponent<TestNetworkBehaviour>();
networkObjectContext.Object.Spawn();
using var otherObjectContext = UnityObjectContext.CreateNetworkObject();
otherObjectContext.Object.Spawn();
// If not initializing with null, then use the default constructor with no assigned NetworkBehaviour
if (!initializeWithNull)
{
testNetworkBehaviour.SendReferenceServerRpc(new NetworkBehaviourReference());
}
else // Otherwise, initialize and pass in null as the reference
{
testNetworkBehaviour.SendReferenceServerRpc(new NetworkBehaviourReference(null));
}
// wait for rpc completion
float t = 0;
while (!TestNetworkBehaviour.ReceivedRPC)
{
t += Time.deltaTime;
if (t > 5f)
{
new AssertionException("RPC with NetworkBehaviour reference hasn't been received");
}
yield return null;
}
// validate
Assert.AreEqual(null, testNetworkBehaviour.RpcReceivedBehaviour);
}
[UnityTest]
public IEnumerator TestRpcImplicitNetworkBehaviour()
@@ -131,15 +169,6 @@ namespace Unity.Netcode.RuntimeTests
});
}
[Test]
public void FailSerializeNullBehaviour()
{
Assert.Throws<ArgumentNullException>(() =>
{
NetworkBehaviourReference outReference = null;
});
}
public void Dispose()
{
//Stop, shutdown, and destroy

View File

@@ -19,6 +19,8 @@ namespace Unity.Netcode.RuntimeTests
{
private class TestNetworkBehaviour : NetworkBehaviour
{
public static bool ReceivedRPC;
public NetworkVariable<NetworkObjectReference> TestVariable = new NetworkVariable<NetworkObjectReference>();
public NetworkObject RpcReceivedNetworkObject;
@@ -28,6 +30,7 @@ namespace Unity.Netcode.RuntimeTests
[ServerRpc]
public void SendReferenceServerRpc(NetworkObjectReference value)
{
ReceivedRPC = true;
RpcReceivedGameObject = value;
RpcReceivedNetworkObject = value;
}
@@ -150,6 +153,60 @@ namespace Unity.Netcode.RuntimeTests
Assert.AreEqual(networkObject, result);
}
public enum NetworkObjectConstructorTypes
{
None,
NullNetworkObject,
NullGameObject
}
[UnityTest]
public IEnumerator TestSerializeNull([Values] NetworkObjectConstructorTypes networkObjectConstructorTypes)
{
TestNetworkBehaviour.ReceivedRPC = false;
using var networkObjectContext = UnityObjectContext.CreateNetworkObject();
var testNetworkBehaviour = networkObjectContext.Object.gameObject.AddComponent<TestNetworkBehaviour>();
networkObjectContext.Object.Spawn();
switch (networkObjectConstructorTypes)
{
case NetworkObjectConstructorTypes.None:
{
testNetworkBehaviour.SendReferenceServerRpc(new NetworkObjectReference());
break;
}
case NetworkObjectConstructorTypes.NullNetworkObject:
{
testNetworkBehaviour.SendReferenceServerRpc(new NetworkObjectReference((NetworkObject)null));
break;
}
case NetworkObjectConstructorTypes.NullGameObject:
{
testNetworkBehaviour.SendReferenceServerRpc(new NetworkObjectReference((GameObject)null));
break;
}
}
// wait for rpc completion
float t = 0;
while (!TestNetworkBehaviour.ReceivedRPC)
{
t += Time.deltaTime;
if (t > 5f)
{
new AssertionException("RPC with NetworkBehaviour reference hasn't been received");
}
yield return null;
}
// validate
Assert.AreEqual(null, testNetworkBehaviour.RpcReceivedNetworkObject);
Assert.AreEqual(null, testNetworkBehaviour.RpcReceivedGameObject);
}
[UnityTest]
public IEnumerator TestRpc()
{
@@ -305,24 +362,6 @@ namespace Unity.Netcode.RuntimeTests
});
}
[Test]
public void FailSerializeNullNetworkObject()
{
Assert.Throws<ArgumentNullException>(() =>
{
NetworkObjectReference outReference = (NetworkObject)null;
});
}
[Test]
public void FailSerializeNullGameObject()
{
Assert.Throws<ArgumentNullException>(() =>
{
NetworkObjectReference outReference = (GameObject)null;
});
}
public void Dispose()
{
//Stop, shutdown, and destroy

View File

@@ -2,23 +2,23 @@
"name": "com.unity.netcode.gameobjects",
"displayName": "Netcode for GameObjects",
"description": "Netcode for GameObjects is a high-level netcode SDK that provides networking capabilities to GameObject/MonoBehaviour workflows within Unity and sits on top of underlying transport layer.",
"version": "2.0.0-pre.1",
"version": "2.0.0-pre.4",
"unity": "6000.0",
"dependencies": {
"com.unity.nuget.mono-cecil": "1.11.4",
"com.unity.transport": "2.2.1"
"com.unity.transport": "2.3.0"
},
"_upm": {
"changelog": "### Added\n\n- Added event `NetworkManager.OnSessionOwnerPromoted` that is invoked when a new session owner promotion occurs. (#2948)\n- Added `NetworkRigidBodyBase.GetLinearVelocity` and `NetworkRigidBodyBase.SetLinearVelocity` convenience/helper methods. (#2948)\n- Added `NetworkRigidBodyBase.GetAngularVelocity` and `NetworkRigidBodyBase.SetAngularVelocity` convenience/helper methods. (#2948)\n\n### Fixed\n\n- Fixed issue when `NetworkTransform` half float precision is enabled and ownership changes the current base position was not being synchronized. (#2948)\n- Fixed issue where `OnClientConnected` not being invoked on the session owner when connecting to a new distributed authority session. (#2948)\n- Fixed issue where Rigidbody micro-motion (i.e. relatively small velocities) would result in non-authority instances slightly stuttering as the body would come to a rest (i.e. no motion). Now, the threshold value can increase at higher velocities and can decrease slightly below the provided threshold to account for this. (#2948)\n\n### Changed\n\n- Changed the client's owned objects is now returned (`NetworkClient` and `NetworkSpawnManager`) as an array as opposed to a list for performance purposes. (#2948)\n- Changed `NetworkTransfrom.TryCommitTransformToServer` to be internal as it will be removed by the final 2.0.0 release. (#2948)\n- Changed `NetworkTransformEditor.OnEnable` to a virtual method to be able to customize a `NetworkTransform` derived class by creating a derived editor control from `NetworkTransformEditor`. (#2948)"
"changelog": "### Added\n\n- Added `NetworkVariable.CheckDirtyState` that is to be used in tandem with collections in order to detect whether the collection or an item within the collection has changed. (#3004)\n\n### Fixed\n\n- Fixed issue where nested `NetworkTransform` components were not getting updated. (#3016)\n- Fixed issue by adding null checks in `NetworkVariableBase.CanClientRead` and `NetworkVariableBase.CanClientWrite` methods to ensure safe access to `NetworkBehaviour`. (#3012)\n- Fixed issue where `FixedStringSerializer<T>` was using `NetworkVariableSerialization<byte>.AreEqual` to determine if two bytes were equal causes an exception to be thrown due to no byte serializer having been defined. (#3009)\n- Fixed Issue where a state with dual triggers, inbound and outbound, could cause a false layer to layer state transition message to be sent to non-authority `NetworkAnimator` instances and cause a warning message to be logged. (#3008)\n- Fixed issue using collections within `NetworkVariable` where the collection would not detect changes to items or nested items. (#3004)\n- Fixed issue where `List`, `Dictionary`, and `HashSet` collections would not uniquely duplicate nested collections. (#3004)\n- Fixed issue where `NotAuthorityTarget` would include the service observer in the list of targets to send the RPC to as opposed to excluding the service observer as it should. (#3000)\n- Fixed issue where `ProxyRpcTargetGroup` could attempt to send a message if there were no targets to send to. (#3000)\n\n### Changed\n\n- Changed `NetworkAnimator` to automatically switch to owner authoritative mode when using a distributed authority network topology. (#3021)\n- Changed permissions exception thrown in `NetworkList` to exiting early with a logged error that is now a unified permissions message within `NetworkVariableBase`. (#3004)\n- Changed permissions exception thrown in `NetworkVariable.Value` to exiting early with a logged error that is now a unified permissions message within `NetworkVariableBase`. (#3004)"
},
"upmCi": {
"footprint": "18101c69b1634ca6a71617efbaf53473b389e8ec"
"footprint": "48286e9f7b0e053fe7f7b524bafc69a99c2906fc"
},
"documentationUrl": "https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@2.0/manual/index.html",
"repository": {
"url": "https://github.com/Unity-Technologies/com.unity.netcode.gameobjects.git",
"type": "git",
"revision": "ba4102f8ded1ed3f18c5b0604bd39a846437e9b6"
"revision": "2802dfcd13c3be1ac356191cc87d1559203d2db3"
},
"samples": [
{