com.unity.netcode.gameobjects@1.0.0-pre.8

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).

## [1.0.0-pre.8] - 2022-04-27

### Changed

- `unmanaged` structs are no longer universally accepted as RPC parameters because some structs (i.e., structs with pointers in them, such as `NativeList<T>`) can't be supported by the default memcpy struct serializer. Structs that are intended to be serialized across the network must add `INetworkSerializeByMemcpy` to the interface list (i.e., `struct Foo : INetworkSerializeByMemcpy`). This interface is empty and just serves to mark the struct as compatible with memcpy serialization. For external structs you can't edit, you can pass them to RPCs by wrapping them in `ForceNetworkSerializeByMemcpy<T>`. (#1901)

### Removed
- Removed `SIPTransport` (#1870)

- Removed `ClientNetworkTransform` from the package samples and moved to Boss Room's Utilities package which can be found [here](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Packages/com.unity.multiplayer.samples.coop/Utilities/Net/ClientAuthority/ClientNetworkTransform.cs).

### Fixed

- Fixed `NetworkTransform` generating false positive rotation delta checks when rolling over between 0 and 360 degrees. (#1890)
- Fixed client throwing an exception if it has messages in the outbound queue when processing the `NetworkEvent.Disconnect` event and is using UTP. (#1884)
- Fixed issue during client synchronization if 'ValidateSceneBeforeLoading' returned false it would halt the client synchronization process resulting in a client that was approved but not synchronized or fully connected with the server. (#1883)
- Fixed an issue where UNetTransport.StartServer would return success even if the underlying transport failed to start (#854)
- Passing generic types to RPCs no longer causes a native crash (#1901)
- Fixed an issue where calling `Shutdown` on a `NetworkManager` that was already shut down would cause an immediate shutdown the next time it was started (basically the fix makes `Shutdown` idempotent). (#1877)
This commit is contained in:
Unity Technologies
2022-04-27 00:00:00 +00:00
parent 60e2dabef4
commit add668dfd2
119 changed files with 4434 additions and 1801 deletions

View File

@@ -6,18 +6,40 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).
## [1.0.0-pre.7] - 2022-04-01
## [1.0.0-pre.8] - 2022-04-27
### Changed
- `unmanaged` structs are no longer universally accepted as RPC parameters because some structs (i.e., structs with pointers in them, such as `NativeList<T>`) can't be supported by the default memcpy struct serializer. Structs that are intended to be serialized across the network must add `INetworkSerializeByMemcpy` to the interface list (i.e., `struct Foo : INetworkSerializeByMemcpy`). This interface is empty and just serves to mark the struct as compatible with memcpy serialization. For external structs you can't edit, you can pass them to RPCs by wrapping them in `ForceNetworkSerializeByMemcpy<T>`. (#1901)
### Removed
- Removed `SIPTransport` (#1870)
- Removed `ClientNetworkTransform` from the package samples and moved to Boss Room's Utilities package which can be found [here](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Packages/com.unity.multiplayer.samples.coop/Utilities/Net/ClientAuthority/ClientNetworkTransform.cs).
### Fixed
- Fixed `NetworkTransform` generating false positive rotation delta checks when rolling over between 0 and 360 degrees. (#1890)
- Fixed client throwing an exception if it has messages in the outbound queue when processing the `NetworkEvent.Disconnect` event and is using UTP. (#1884)
- Fixed issue during client synchronization if 'ValidateSceneBeforeLoading' returned false it would halt the client synchronization process resulting in a client that was approved but not synchronized or fully connected with the server. (#1883)
- Fixed an issue where UNetTransport.StartServer would return success even if the underlying transport failed to start (#854)
- Passing generic types to RPCs no longer causes a native crash (#1901)
- Fixed an issue where calling `Shutdown` on a `NetworkManager` that was already shut down would cause an immediate shutdown the next time it was started (basically the fix makes `Shutdown` idempotent). (#1877)
## [1.0.0-pre.7] - 2022-04-06
### Added
- Added editor only check prior to entering into play mode if the currently open and active scene is in the build list and if not displays a dialog box asking the user if they would like to automatically add it prior to entering into play mode. (#1828)
- Added `UnityTransport` implementation and `com.unity.transport` package dependency (#1823)
- Added `NetworkVariableWritePermission` to `NetworkVariableBase` and implemented `Owner` client writable netvars. (#1762)
- `UnityTransport` settings can now be set programmatically. (#1845)
- `FastBufferWriter` and Reader IsInitialized property. (#1859)
- Prefabs can now be added to the network at **runtime** (i.e., from an addressable asset). If `ForceSamePrefabs` is false, this can happen after a connection has been formed. (#1882)
- When `ForceSamePrefabs` is false, a configurable delay (default 1 second, configurable via `NetworkConfig.SpawnTimeout`) has been introduced to gracefully handle race conditions where a spawn call has been received for an object whose prefab is still being loaded. (#1882)
### Changed
- Changed `NetcodeIntegrationTestHelpers` to use `UnityTransport` (#1870)
- Updated `UnityTransport` dependency on `com.unity.transport` to 1.0.0 (#1849)
### Removed
@@ -27,6 +49,7 @@ Additional documentation and release notes are available at [Multiplayer Documen
- Removed `com.unity.collections` dependency from the package (#1849)
### Fixed
- Fixed in-scene placed NetworkObjects not being found/ignored after a client disconnects and then reconnects. (#1850)
- Fixed issue where `UnityTransport` send queues were not flushed when calling `DisconnectLocalClient` or `DisconnectRemoteClient`. (#1847)
- Fixed NetworkBehaviour dependency verification check for an existing NetworkObject not searching from root parent transform relative GameObject. (#1841)
@@ -49,8 +72,6 @@ Additional documentation and release notes are available at [Multiplayer Documen
- NetworkAnimator now properly synchrhonizes all animation layers as well as runtime-adjusted weighting between them (#1765)
- Added first set of tests for NetworkAnimator - parameter syncing, trigger set / reset, override network animator (#1735)
### Changed
### Fixed
- Fixed an issue where sometimes the first client to connect to the server could see messages from the server as coming from itself. (#1683)
- Fixed an issue where clients seemed to be able to send messages to ClientId 1, but these messages would actually still go to the server (id 0) instead of that client. (#1683)

View File

@@ -4,13 +4,11 @@ using UnityEngine;
namespace Unity.Netcode
{
/// <summary>
/// Solves for incoming values that are jittered
/// Partially solves for message loss. Unclamped lerping helps hide this, but not completely
/// </summary>
/// <typeparam name="T"></typeparam>
internal abstract class BufferedLinearInterpolator<T> where T : struct
public abstract class BufferedLinearInterpolator<T> where T : struct
{
private struct BufferedItem
{
@@ -24,6 +22,10 @@ namespace Unity.Netcode
}
}
/// <summary>
/// Theres two factors affecting interpolation: buffering (set in NetworkManagers NetworkTimeSystem) and interpolation time, which is the amount of time itll take to reach the target. This is to affect the second one.
/// </summary>
public float MaximumInterpolationTime = 0.1f;
private const double k_SmallValue = 9.999999439624929E-11; // copied from Vector3's equal operator
@@ -69,6 +71,9 @@ namespace Unity.Netcode
private bool InvalidState => m_Buffer.Count == 0 && m_LifetimeConsumedCount == 0;
/// <summary>
/// Resets Interpolator to initial state
/// </summary>
public void Clear()
{
m_Buffer.Clear();
@@ -76,6 +81,9 @@ namespace Unity.Netcode
m_StartTimeConsumed = 0.0d;
}
/// <summary>
/// Teleports current interpolation value to targetValue.
/// </summary>
public void ResetTo(T targetValue, double serverTime)
{
m_LifetimeConsumedCount = 1;
@@ -89,7 +97,6 @@ namespace Unity.Netcode
Update(0, serverTime, serverTime);
}
// todo if I have value 1, 2, 3 and I'm treating 1 to 3, I shouldn't interpolate between 1 and 3, I should interpolate from 1 to 2, then from 2 to 3 to get the best path
private void TryConsumeFromBuffer(double renderTime, double serverTime)
{
@@ -205,14 +212,16 @@ namespace Unity.Netcode
}
var target = InterpolateUnclamped(m_InterpStartValue, m_InterpEndValue, t);
float maxInterpTime = 0.1f;
m_CurrentInterpValue = Interpolate(m_CurrentInterpValue, target, deltaTime / maxInterpTime); // second interpolate to smooth out extrapolation jumps
m_CurrentInterpValue = Interpolate(m_CurrentInterpValue, target, deltaTime / MaximumInterpolationTime); // second interpolate to smooth out extrapolation jumps
}
m_NbItemsReceivedThisFrame = 0;
return m_CurrentInterpValue;
}
/// <summary>
/// Add measurements to be used during interpolation. These will be buffered before being made available to be displayed as "latest value".
/// </summary>
public void AddMeasurement(T newMeasurement, double sentTime)
{
m_NbItemsReceivedThisFrame++;
@@ -239,17 +248,25 @@ namespace Unity.Netcode
}
}
/// <summary>
/// Gets latest value from the interpolator. This is updated every update as time goes by.
/// </summary>
public T GetInterpolatedValue()
{
return m_CurrentInterpValue;
}
/// <summary>
/// Method to override and adapted to the generic type. This assumes interpolation for that value will be clamped.
/// </summary>
protected abstract T Interpolate(T start, T end, float time);
/// <summary>
/// Method to override and adapted to the generic type. This assumes interpolation for that value will not be clamped.
/// </summary>
protected abstract T InterpolateUnclamped(T start, T end, float time);
}
internal class BufferedLinearInterpolatorFloat : BufferedLinearInterpolator<float>
public class BufferedLinearInterpolatorFloat : BufferedLinearInterpolator<float>
{
protected override float InterpolateUnclamped(float start, float end, float time)
{
@@ -262,7 +279,7 @@ namespace Unity.Netcode
}
}
internal class BufferedLinearInterpolatorQuaternion : BufferedLinearInterpolator<Quaternion>
public class BufferedLinearInterpolatorQuaternion : BufferedLinearInterpolator<Quaternion>
{
protected override Quaternion InterpolateUnclamped(Quaternion start, Quaternion end, float time)
{

View File

@@ -15,11 +15,11 @@ namespace Unity.Netcode.Components
internal struct AnimationMessage : INetworkSerializable
{
// state hash per layer. if non-zero, then Play() this animation, skipping transitions
public int StateHash;
public float NormalizedTime;
public int Layer;
public float Weight;
public byte[] Parameters;
internal int StateHash;
internal float NormalizedTime;
internal int Layer;
internal float Weight;
internal byte[] Parameters;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
@@ -33,8 +33,8 @@ namespace Unity.Netcode.Components
internal struct AnimationTriggerMessage : INetworkSerializable
{
public int Hash;
public bool Reset;
internal int Hash;
internal bool Reset;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
@@ -57,7 +57,7 @@ namespace Unity.Netcode.Components
private bool m_SendMessagesAllowed = false;
// Animators only support up to 32 params
public static int K_MaxAnimationParams = 32;
private const int k_MaxAnimationParams = 32;
private int[] m_TransitionHash;
private int[] m_AnimationHash;
@@ -65,21 +65,21 @@ namespace Unity.Netcode.Components
private unsafe struct AnimatorParamCache
{
public int Hash;
public int Type;
public fixed byte Value[4]; // this is a max size of 4 bytes
internal int Hash;
internal int Type;
internal fixed byte Value[4]; // this is a max size of 4 bytes
}
// 128 bytes per Animator
private FastBufferWriter m_ParameterWriter = new FastBufferWriter(K_MaxAnimationParams * sizeof(float), Allocator.Persistent);
private FastBufferWriter m_ParameterWriter = new FastBufferWriter(k_MaxAnimationParams * sizeof(float), Allocator.Persistent);
private NativeArray<AnimatorParamCache> m_CachedAnimatorParameters;
// We cache these values because UnsafeUtility.EnumToInt uses direct IL that allows a non-boxing conversion
private struct AnimationParamEnumWrapper
{
public static readonly int AnimatorControllerParameterInt;
public static readonly int AnimatorControllerParameterFloat;
public static readonly int AnimatorControllerParameterBool;
internal static readonly int AnimatorControllerParameterInt;
internal static readonly int AnimatorControllerParameterFloat;
internal static readonly int AnimatorControllerParameterBool;
static AnimationParamEnumWrapper()
{

View File

@@ -5,77 +5,97 @@ namespace Unity.Netcode.Components
{
/// <summary>
/// NetworkRigidbody allows for the use of <see cref="Rigidbody"/> on network objects. By controlling the kinematic
/// mode of the rigidbody and disabling it on all peers but the authoritative one.
/// mode of the <see cref="Rigidbody"/> and disabling it on all peers but the authoritative one.
/// </summary>
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(NetworkTransform))]
public class NetworkRigidbody : NetworkBehaviour
{
/// <summary>
/// Determines if we are server (true) or owner (false) authoritative
/// </summary>
private bool m_IsServerAuthoritative;
private Rigidbody m_Rigidbody;
private NetworkTransform m_NetworkTransform;
private bool m_OriginalKinematic;
private RigidbodyInterpolation m_OriginalInterpolation;
// Used to cache the authority state of this rigidbody during the last frame
// Used to cache the authority state of this Rigidbody during the last frame
private bool m_IsAuthority;
/// <summary>
/// Gets a bool value indicating whether this <see cref="NetworkRigidbody"/> on this peer currently holds authority.
/// </summary>
private bool HasAuthority => m_NetworkTransform.CanCommitToTransform;
private void Awake()
{
m_Rigidbody = GetComponent<Rigidbody>();
m_NetworkTransform = GetComponent<NetworkTransform>();
}
private void FixedUpdate()
{
if (NetworkManager.IsListening)
{
if (HasAuthority != m_IsAuthority)
{
m_IsAuthority = HasAuthority;
UpdateRigidbodyKinematicMode();
}
}
}
// Puts the rigidbody in a kinematic non-interpolated mode on everyone but the server.
private void UpdateRigidbodyKinematicMode()
{
if (m_IsAuthority == false)
{
m_OriginalKinematic = m_Rigidbody.isKinematic;
m_Rigidbody.isKinematic = true;
m_IsServerAuthoritative = m_NetworkTransform.IsServerAuthoritative();
m_Rigidbody = GetComponent<Rigidbody>();
m_OriginalInterpolation = m_Rigidbody.interpolation;
// Set interpolation to none, the NetworkTransform component interpolates the position of the object.
m_Rigidbody.interpolation = RigidbodyInterpolation.None;
// Set interpolation to none if NetworkTransform is handling interpolation, otherwise it sets it to the original value
m_Rigidbody.interpolation = m_NetworkTransform.Interpolate ? RigidbodyInterpolation.None : m_OriginalInterpolation;
// Turn off physics for the rigid body until spawned, otherwise
// clients can run fixed update before the first full
// NetworkTransform update
m_Rigidbody.isKinematic = true;
}
/// <summary>
/// For owner authoritative (i.e. ClientNetworkTransform)
/// we adjust our authority when we gain ownership
/// </summary>
public override void OnGainedOwnership()
{
UpdateOwnershipAuthority();
}
/// <summary>
/// For owner authoritative(i.e. ClientNetworkTransform)
/// we adjust our authority when we have lost ownership
/// </summary>
public override void OnLostOwnership()
{
UpdateOwnershipAuthority();
}
/// <summary>
/// Sets the authority differently depending upon
/// whether it is server or owner authoritative
/// </summary>
private void UpdateOwnershipAuthority()
{
if (m_IsServerAuthoritative)
{
m_IsAuthority = NetworkManager.IsServer;
}
else
{
// Resets the rigidbody back to it's non replication only state. Happens on shutdown and when authority is lost
m_Rigidbody.isKinematic = m_OriginalKinematic;
m_Rigidbody.interpolation = m_OriginalInterpolation;
m_IsAuthority = IsOwner;
}
// If you have authority then you are not kinematic
m_Rigidbody.isKinematic = !m_IsAuthority;
// Set interpolation of the Rigidbody based on authority
// With authority: let local transform handle interpolation
// Without authority: let the NetworkTransform handle interpolation
m_Rigidbody.interpolation = m_IsAuthority ? m_OriginalInterpolation : RigidbodyInterpolation.None;
}
/// <inheritdoc />
public override void OnNetworkSpawn()
{
m_IsAuthority = HasAuthority;
m_OriginalKinematic = m_Rigidbody.isKinematic;
m_OriginalInterpolation = m_Rigidbody.interpolation;
UpdateRigidbodyKinematicMode();
UpdateOwnershipAuthority();
}
/// <inheritdoc />
public override void OnNetworkDespawn()
{
UpdateRigidbodyKinematicMode();
m_Rigidbody.interpolation = m_OriginalInterpolation;
// Turn off physics for the rigid body until spawned, otherwise
// non-owners can run fixed updates before the first full
// NetworkTransform update and physics will be applied (i.e. gravity, etc)
m_Rigidbody.isKinematic = true;
}
}
}

View File

@@ -15,9 +15,10 @@ namespace Unity.Netcode.Components
[DefaultExecutionOrder(100000)] // this is needed to catch the update time after the transform was updated by user scripts
public class NetworkTransform : NetworkBehaviour
{
public const float PositionThresholdDefault = .001f;
public const float RotAngleThresholdDefault = .01f;
public const float ScaleThresholdDefault = .01f;
public const float PositionThresholdDefault = 0.001f;
public const float RotAngleThresholdDefault = 0.01f;
public const float ScaleThresholdDefault = 0.01f;
public delegate (Vector3 pos, Quaternion rotOut, Vector3 scale) OnClientRequestChangeDelegate(Vector3 pos, Quaternion rot, Vector3 scale);
public OnClientRequestChangeDelegate OnClientRequestChange;
@@ -38,7 +39,7 @@ namespace Unity.Netcode.Components
// 11-15: <unused>
private ushort m_Bitset;
public bool InLocalSpace
internal bool InLocalSpace
{
get => (m_Bitset & (1 << k_InLocalSpaceBit)) != 0;
set
@@ -49,7 +50,7 @@ namespace Unity.Netcode.Components
}
// Position
public bool HasPositionX
internal bool HasPositionX
{
get => (m_Bitset & (1 << k_PositionXBit)) != 0;
set
@@ -59,7 +60,7 @@ namespace Unity.Netcode.Components
}
}
public bool HasPositionY
internal bool HasPositionY
{
get => (m_Bitset & (1 << k_PositionYBit)) != 0;
set
@@ -69,7 +70,7 @@ namespace Unity.Netcode.Components
}
}
public bool HasPositionZ
internal bool HasPositionZ
{
get => (m_Bitset & (1 << k_PositionZBit)) != 0;
set
@@ -80,7 +81,7 @@ namespace Unity.Netcode.Components
}
// RotAngles
public bool HasRotAngleX
internal bool HasRotAngleX
{
get => (m_Bitset & (1 << k_RotAngleXBit)) != 0;
set
@@ -90,7 +91,7 @@ namespace Unity.Netcode.Components
}
}
public bool HasRotAngleY
internal bool HasRotAngleY
{
get => (m_Bitset & (1 << k_RotAngleYBit)) != 0;
set
@@ -100,7 +101,7 @@ namespace Unity.Netcode.Components
}
}
public bool HasRotAngleZ
internal bool HasRotAngleZ
{
get => (m_Bitset & (1 << k_RotAngleZBit)) != 0;
set
@@ -111,7 +112,7 @@ namespace Unity.Netcode.Components
}
// Scale
public bool HasScaleX
internal bool HasScaleX
{
get => (m_Bitset & (1 << k_ScaleXBit)) != 0;
set
@@ -121,7 +122,7 @@ namespace Unity.Netcode.Components
}
}
public bool HasScaleY
internal bool HasScaleY
{
get => (m_Bitset & (1 << k_ScaleYBit)) != 0;
set
@@ -131,7 +132,7 @@ namespace Unity.Netcode.Components
}
}
public bool HasScaleZ
internal bool HasScaleZ
{
get => (m_Bitset & (1 << k_ScaleZBit)) != 0;
set
@@ -141,7 +142,7 @@ namespace Unity.Netcode.Components
}
}
public bool IsTeleportingNextFrame
internal bool IsTeleportingNextFrame
{
get => (m_Bitset & (1 << k_TeleportingBit)) != 0;
set
@@ -151,12 +152,12 @@ namespace Unity.Netcode.Components
}
}
public float PositionX, PositionY, PositionZ;
public float RotAngleX, RotAngleY, RotAngleZ;
public float ScaleX, ScaleY, ScaleZ;
public double SentTime;
internal float PositionX, PositionY, PositionZ;
internal float RotAngleX, RotAngleY, RotAngleZ;
internal float ScaleX, ScaleY, ScaleZ;
internal double SentTime;
public Vector3 Position
internal Vector3 Position
{
get { return new Vector3(PositionX, PositionY, PositionZ); }
set
@@ -167,7 +168,7 @@ namespace Unity.Netcode.Components
}
}
public Vector3 Rotation
internal Vector3 Rotation
{
get { return new Vector3(RotAngleX, RotAngleY, RotAngleZ); }
set
@@ -178,7 +179,7 @@ namespace Unity.Netcode.Components
}
}
public Vector3 Scale
internal Vector3 Scale
{
get { return new Vector3(ScaleX, ScaleY, ScaleZ); }
set
@@ -249,7 +250,10 @@ namespace Unity.Netcode.Components
public bool SyncScaleX = true, SyncScaleY = true, SyncScaleZ = true;
public float PositionThreshold = PositionThresholdDefault;
[Range(0.001f, 360.0f)]
public float RotAngleThreshold = RotAngleThresholdDefault;
public float ScaleThreshold = ScaleThresholdDefault;
/// <summary>
@@ -280,8 +284,6 @@ namespace Unity.Netcode.Components
private NetworkTransformState m_LocalAuthoritativeNetworkState;
private NetworkTransformState m_PrevNetworkState;
private const int k_DebugDrawLineTime = 10;
private bool m_HasSentLastValue = false; // used to send one last value, so clients can make the difference between lost replication data (clients extrapolate) and no more data to send.
@@ -390,6 +392,16 @@ namespace Unity.Netcode.Components
m_ScaleZInterpolator.ResetTo(m_LocalAuthoritativeNetworkState.ScaleZ, serverTime);
}
/// <summary>
/// Will apply the transform to the LocalAuthoritativeNetworkState and get detailed isDirty information returned.
/// </summary>
/// <param name="transform">transform to apply</param>
/// <returns>bool isDirty, bool isPositionDirty, bool isRotationDirty, bool isScaleDirty</returns>
internal (bool isDirty, bool isPositionDirty, bool isRotationDirty, bool isScaleDirty) ApplyLocalNetworkState(Transform transform)
{
return ApplyTransformToNetworkStateWithInfo(ref m_LocalAuthoritativeNetworkState, m_CachedNetworkManager.LocalTime.Time, transform);
}
// updates `NetworkState` properties if they need to and returns a `bool` indicating whether or not there was any changes made
// returned boolean would be useful to change encapsulating `NetworkVariable<NetworkState>`'s dirty state, e.g. ReplNetworkState.SetDirty(isDirty);
internal bool ApplyTransformToNetworkState(ref NetworkTransformState networkState, double dirtyTime, Transform transformToUse)
@@ -450,7 +462,7 @@ namespace Unity.Netcode.Components
}
if (SyncRotAngleX &&
Mathf.Abs(networkState.RotAngleX - rotAngles.x) > RotAngleThreshold)
Mathf.Abs(Mathf.DeltaAngle(networkState.RotAngleX, rotAngles.x)) > RotAngleThreshold)
{
networkState.RotAngleX = rotAngles.x;
networkState.HasRotAngleX = true;
@@ -458,7 +470,7 @@ namespace Unity.Netcode.Components
}
if (SyncRotAngleY &&
Mathf.Abs(networkState.RotAngleY - rotAngles.y) > RotAngleThreshold)
Mathf.Abs(Mathf.DeltaAngle(networkState.RotAngleY, rotAngles.y)) > RotAngleThreshold)
{
networkState.RotAngleY = rotAngles.y;
networkState.HasRotAngleY = true;
@@ -466,7 +478,7 @@ namespace Unity.Netcode.Components
}
if (SyncRotAngleZ &&
Mathf.Abs(networkState.RotAngleZ - rotAngles.z) > RotAngleThreshold)
Mathf.Abs(Mathf.DeltaAngle(networkState.RotAngleZ, rotAngles.z)) > RotAngleThreshold)
{
networkState.RotAngleZ = rotAngles.z;
networkState.HasRotAngleZ = true;
@@ -509,8 +521,6 @@ namespace Unity.Netcode.Components
private void ApplyInterpolatedNetworkStateToTransform(NetworkTransformState networkState, Transform transformToUpdate)
{
m_PrevNetworkState = networkState;
var interpolatedPosition = InLocalSpace ? transformToUpdate.localPosition : transformToUpdate.position;
// todo: we should store network state w/ quats vs. euler angles
@@ -587,8 +597,6 @@ namespace Unity.Netcode.Components
{
transformToUpdate.position = interpolatedPosition;
}
m_PrevNetworkState.Position = interpolatedPosition;
}
// RotAngles Apply
@@ -602,15 +610,12 @@ namespace Unity.Netcode.Components
{
transformToUpdate.rotation = Quaternion.Euler(interpolatedRotAngles);
}
m_PrevNetworkState.Rotation = interpolatedRotAngles;
}
// Scale Apply
if (SyncScaleX || SyncScaleY || SyncScaleZ)
{
transformToUpdate.localScale = interpolatedScale;
m_PrevNetworkState.Scale = interpolatedScale;
}
}
@@ -790,8 +795,6 @@ namespace Unity.Netcode.Components
}
}
#region state set
/// <summary>
/// Directly sets a state on the authoritative transform.
/// This will override any changes made previously to the transform
@@ -851,7 +854,6 @@ namespace Unity.Netcode.Components
m_Transform.localScale = scale;
m_LocalAuthoritativeNetworkState.IsTeleportingNextFrame = shouldTeleport;
}
#endregion
// todo this is currently in update, to be able to catch any transform changes. A FixedUpdate mode could be added to be less intense, but it'd be
// conditional to users only making transform update changes in FixedUpdate.
@@ -879,8 +881,6 @@ namespace Unity.Netcode.Components
{
TryCommitTransformToServer(m_Transform, m_CachedNetworkManager.LocalTime.Time);
}
m_PrevNetworkState = m_LocalAuthoritativeNetworkState;
}
// apply interpolated value
@@ -904,36 +904,10 @@ namespace Unity.Netcode.Components
if (!CanCommitToTransform)
{
#if NGO_TRANSFORM_DEBUG
if (m_CachedNetworkManager.LogLevel == LogLevel.Developer)
{
// TODO: This should be a component gizmo - not some debug draw based on log level
var interpolatedPosition = new Vector3(m_PositionXInterpolator.GetInterpolatedValue(), m_PositionYInterpolator.GetInterpolatedValue(), m_PositionZInterpolator.GetInterpolatedValue());
Debug.DrawLine(interpolatedPosition, interpolatedPosition + Vector3.up, Color.magenta, k_DebugDrawLineTime, false);
// try to update previously consumed NetworkState
// if we have any changes, that means made some updates locally
// we apply the latest ReplNetworkState again to revert our changes
var oldStateDirtyInfo = ApplyTransformToNetworkStateWithInfo(ref m_PrevNetworkState, 0, m_Transform);
// there are several bugs in this code, as we the message is dumped out under odd circumstances
// For Matt, it would trigger when an object's rotation was perturbed by colliding with another
// object vs. explicitly rotating it
if (oldStateDirtyInfo.isPositionDirty || oldStateDirtyInfo.isScaleDirty || (oldStateDirtyInfo.isRotationDirty && SyncRotAngleX && SyncRotAngleY && SyncRotAngleZ))
{
// ignoring rotation dirty since quaternions will mess with euler angles, making this impossible to determine if the change to a single axis comes
// from an unauthorized transform change or euler to quaternion conversion artifacts.
var dirtyField = oldStateDirtyInfo.isPositionDirty ? "position" : oldStateDirtyInfo.isRotationDirty ? "rotation" : "scale";
Debug.LogWarning($"A local change to {dirtyField} without authority detected, reverting back to latest interpolated network state!", this);
}
}
#endif
// Apply updated interpolated value
ApplyInterpolatedNetworkStateToTransform(m_ReplicatedNetworkState.Value, m_Transform);
}
}
m_LocalAuthoritativeNetworkState.IsTeleportingNextFrame = false;
}
@@ -960,5 +934,22 @@ namespace Unity.Netcode.Components
TryCommitValuesToServer(newPosition, newRotationEuler, newScale, m_CachedNetworkManager.LocalTime.Time);
m_LocalAuthoritativeNetworkState.IsTeleportingNextFrame = false;
}
/// <summary>
/// Override this and return false to follow the owner authoritative
/// Otherwise, it defaults to server authoritative
/// </summary>
protected virtual bool OnIsServerAuthoritatitive()
{
return true;
}
/// <summary>
/// Used by <see cref="NetworkRigidbody"/> to determines if this is server or owner authoritative.
/// </summary>
internal bool IsServerAuthoritative()
{
return OnIsServerAuthoritatitive();
}
}
}

View File

@@ -1,31 +0,0 @@
# About Netcode for GameObjects
Unity Netcode for GameObjects is a high-level networking library built to abstract networking. This allows developers to focus on the game rather than low level protocols and networking frameworks.
## Guides
See guides below to install Unity Netcode for GameObjects, set up your project, and get started with your first networked game:
* [Documentation](https://docs-multiplayer.unity3d.com/docs/getting-started/about-mlapi)
* [Installation](https://docs-multiplayer.unity3d.com/docs/migration/install)
* [First Steps](https://docs-multiplayer.unity3d.com/docs/tutorials/helloworld/helloworldintro)
* [API Reference](https://docs-multiplayer.unity3d.com/docs/mlapi-api/introduction)
# Technical details
## Requirements
This version of Netcode for GameObjects is compatible with the following Unity versions and platforms:
* 2020.3 and later
* Windows, Mac, Linux platforms
## Document revision history
|Date|Reason|
|---|---|
|March 10, 2021|Document created. Matches package version 0.1.0|
|June 1, 2021|Update and add links for additional content. Matches patch version 0.1.0 and hotfixes.|
|June 3, 2021|Update document to acknowledge Unity min version change. Matches package version 0.2.0|
|August 5, 2021|Update product/package name|
|September 9,2021|Updated the links and name of the file.|

35
Documentation~/index.md Normal file
View File

@@ -0,0 +1,35 @@
# About Netcode for GameObjects
Netcode for GameObjects is a Unity package that provides networking capabilities to GameObject & MonoBehaviour workflows.
## Guides
See guides below to install Unity Netcode for GameObjects, set up your project, and get started with your first networked game:
- [Documentation](https://docs-multiplayer.unity3d.com/netcode/current/about)
- [Installation](https://docs-multiplayer.unity3d.com/netcode/current/migration/install)
- [First Steps](https://docs-multiplayer.unity3d.com/netcode/current/tutorials/helloworld/helloworldintro)
- [API Reference](https://docs-multiplayer.unity3d.com/netcode/current/api/introduction)
# Technical details
## Requirements
Netcode for GameObjects targets the following Unity versions:
- Unity 2020.3, 2021.1, 2021.2 and 2021.3
On the following runtime platforms:
- Windows, MacOS, and Linux
- iOS and Android
- Most closed platforms, such as consoles. Contact us for more information about specific closed platforms.
## Document revision history
|Date|Reason|
|---|---|
|March 10, 2021|Document created. Matches package version 0.1.0|
|June 1, 2021|Update and add links for additional content. Matches patch version 0.1.0 and hotfixes.|
|June 3, 2021|Update document to acknowledge Unity min version change. Matches package version 0.2.0|
|August 5, 2021|Update product/package name|
|September 9,2021|Updated the links and name of the file.|
|April 20, 2022|Updated links|

View File

@@ -27,6 +27,7 @@ namespace Unity.Netcode.Editor.CodeGen
public static readonly string ServerRpcSendParams_FullName = typeof(ServerRpcSendParams).FullName;
public static readonly string ServerRpcReceiveParams_FullName = typeof(ServerRpcReceiveParams).FullName;
public static readonly string INetworkSerializable_FullName = typeof(INetworkSerializable).FullName;
public static readonly string INetworkSerializeByMemcpy_FullName = typeof(INetworkSerializeByMemcpy).FullName;
public static readonly string UnityColor_FullName = typeof(Color).FullName;
public static readonly string UnityColor32_FullName = typeof(Color32).FullName;
public static readonly string UnityVector2_FullName = typeof(Vector2).FullName;
@@ -77,6 +78,35 @@ namespace Unity.Netcode.Editor.CodeGen
return false;
}
public static string FullNameWithGenericParameters(this TypeReference typeReference, GenericParameter[] contextGenericParameters, TypeReference[] contextGenericParameterTypes)
{
var name = typeReference.FullName;
if (typeReference.HasGenericParameters)
{
name += "<";
for (var i = 0; i < typeReference.Resolve().GenericParameters.Count; ++i)
{
if (i != 0)
{
name += ", ";
}
for (var j = 0; j < contextGenericParameters.Length; ++j)
{
if (typeReference.GenericParameters[i].FullName == contextGenericParameters[i].FullName)
{
name += contextGenericParameterTypes[i].FullName;
break;
}
}
}
name += ">";
}
return name;
}
public static bool HasInterface(this TypeReference typeReference, string interfaceTypeFullName)
{
if (typeReference.IsArray)

View File

@@ -24,6 +24,30 @@ namespace Unity.Netcode.Editor.CodeGen
private readonly List<DiagnosticMessage> m_Diagnostics = new List<DiagnosticMessage>();
private TypeReference ResolveGenericType(TypeReference type, List<TypeReference> typeStack)
{
var genericName = type.Name;
var lastType = (GenericInstanceType)typeStack[typeStack.Count - 1];
var resolvedType = lastType.Resolve();
typeStack.RemoveAt(typeStack.Count - 1);
for (var i = 0; i < resolvedType.GenericParameters.Count; ++i)
{
var parameter = resolvedType.GenericParameters[i];
if (parameter.Name == genericName)
{
var underlyingType = lastType.GenericArguments[i];
if (underlyingType.Resolve() == null)
{
return ResolveGenericType(underlyingType, typeStack);
}
return underlyingType;
}
}
return null;
}
public override ILPostProcessResult Process(ICompiledAssembly compiledAssembly)
{
if (!WillProcess(compiledAssembly))
@@ -31,7 +55,6 @@ namespace Unity.Netcode.Editor.CodeGen
return null;
}
m_Diagnostics.Clear();
// read
@@ -50,16 +73,128 @@ namespace Unity.Netcode.Editor.CodeGen
{
if (ImportReferences(mainModule))
{
var types = mainModule.GetTypes()
.Where(t => t.Resolve().HasInterface(CodeGenHelpers.INetworkSerializable_FullName) && !t.Resolve().IsAbstract && t.Resolve().IsValueType)
// Initialize all the delegates for various NetworkVariable types to ensure they can be serailized
// Find all types we know we're going to want to serialize.
// The list of these types includes:
// - Non-generic INetworkSerializable types
// - Non-Generic INetworkSerializeByMemcpy types
// - Enums that are not declared within generic types
// We can't process generic types because, to initialize a generic, we need a value
// for `T` to initialize it with.
var networkSerializableTypes = mainModule.GetTypes()
.Where(t => t.Resolve().HasInterface(CodeGenHelpers.INetworkSerializable_FullName) && !t.Resolve().IsAbstract && !t.Resolve().HasGenericParameters && t.Resolve().IsValueType)
.ToList();
// process `INetworkMessage` types
if (types.Count == 0)
var structTypes = mainModule.GetTypes()
.Where(t => t.Resolve().HasInterface(CodeGenHelpers.INetworkSerializeByMemcpy_FullName) && !t.Resolve().IsAbstract && !t.Resolve().HasGenericParameters && t.Resolve().IsValueType)
.ToList();
var enumTypes = mainModule.GetTypes()
.Where(t => t.Resolve().IsEnum && !t.Resolve().IsAbstract && !t.Resolve().HasGenericParameters && t.Resolve().IsValueType)
.ToList();
// Now, to support generics, we have to do an extra pass.
// We look for any type that's a NetworkBehaviour type
// Then we look through all the fields in that type, finding any field whose type is
// descended from `NetworkVariableSerialization`. Then we check `NetworkVariableSerialization`'s
// `T` value, and if it's a generic, then we know it was missed in the above sweep and needs
// to be initialized. Now we have a full generic instance rather than a generic definition,
// so we can validly generate an initializer for that particular instance of the generic type.
var networkSerializableTypesSet = new HashSet<TypeReference>(networkSerializableTypes);
var structTypesSet = new HashSet<TypeReference>(structTypes);
var enumTypesSet = new HashSet<TypeReference>(enumTypes);
var typeStack = new List<TypeReference>();
foreach (var type in mainModule.GetTypes())
{
// Check if it's a NetworkBehaviour
if (type.IsSubclassOf(CodeGenHelpers.NetworkBehaviour_FullName))
{
// Iterate fields looking for NetworkVariableSerialization fields
foreach (var field in type.Fields)
{
// Get the field type and its base type
var fieldType = field.FieldType;
var baseType = fieldType.Resolve().BaseType;
if (baseType == null)
{
continue;
}
// This type stack is used for resolving NetworkVariableSerialization's T value
// When looking at base types, we get the type definition rather than the
// type reference... which means that we get the generic definition with an
// undefined T rather than the instance with the type filled in.
// We then have to walk backward back down the type stack to resolve what T
// is.
typeStack.Clear();
typeStack.Add(fieldType);
// Iterate through the base types until we get to Object.
// Object is the base for everything so we'll stop when we hit that.
while (baseType.Name != mainModule.TypeSystem.Object.Name)
{
// If we've found a NetworkVariableSerialization type...
if (baseType.IsGenericInstance && baseType.Resolve() == m_NetworkVariableSerializationType)
{
// Then we need to figure out what T is
var genericType = (GenericInstanceType)baseType;
var underlyingType = genericType.GenericArguments[0];
if (underlyingType.Resolve() == null)
{
underlyingType = ResolveGenericType(underlyingType, typeStack);
}
// If T is generic...
if (underlyingType.IsGenericInstance)
{
// Then we pick the correct set to add it to and set it up
// for initialization.
if (underlyingType.HasInterface(CodeGenHelpers.INetworkSerializable_FullName))
{
networkSerializableTypesSet.Add(underlyingType);
}
if (underlyingType.HasInterface(CodeGenHelpers.INetworkSerializeByMemcpy_FullName))
{
structTypesSet.Add(underlyingType);
}
if (underlyingType.Resolve().IsEnum)
{
enumTypesSet.Add(underlyingType);
}
}
break;
}
typeStack.Add(baseType);
baseType = baseType.Resolve().BaseType;
}
}
}
// We'll also avoid some confusion by ensuring users only choose one of the two
// serialization schemes - by method OR by memcpy, not both. We'll also do a cursory
// check that INetworkSerializeByMemcpy types are unmanaged.
else if (type.HasInterface(CodeGenHelpers.INetworkSerializeByMemcpy_FullName))
{
if (type.HasInterface(CodeGenHelpers.INetworkSerializable_FullName))
{
m_Diagnostics.AddError($"{nameof(INetworkSerializeByMemcpy)} types may not implement {nameof(INetworkSerializable)} - choose one or the other.");
}
if (!type.IsValueType)
{
m_Diagnostics.AddError($"{nameof(INetworkSerializeByMemcpy)} types must be unmanaged types.");
}
}
}
if (networkSerializableTypes.Count + structTypes.Count + enumTypes.Count == 0)
{
return null;
}
CreateModuleInitializer(assemblyDefinition, types);
// Finally we add to the module initializer some code to initialize the delegates in
// NetworkVariableSerialization<T> for all necessary values of T, by calling initialization
// methods in NetworkVariableHelpers.
CreateModuleInitializer(assemblyDefinition, networkSerializableTypesSet.ToList(), structTypesSet.ToList(), enumTypesSet.ToList());
}
else
{
@@ -94,9 +229,15 @@ namespace Unity.Netcode.Editor.CodeGen
return new ILPostProcessResult(new InMemoryAssembly(pe.ToArray(), pdb.ToArray()), m_Diagnostics);
}
private MethodReference m_InitializeDelegates_MethodRef;
private MethodReference m_InitializeDelegatesNetworkSerializable_MethodRef;
private MethodReference m_InitializeDelegatesStruct_MethodRef;
private MethodReference m_InitializeDelegatesEnum_MethodRef;
private const string k_InitializeMethodName = nameof(NetworkVariableHelper.InitializeDelegates);
private TypeDefinition m_NetworkVariableSerializationType;
private const string k_InitializeNetworkSerializableMethodName = nameof(NetworkVariableHelper.InitializeDelegatesNetworkSerializable);
private const string k_InitializeStructMethodName = nameof(NetworkVariableHelper.InitializeDelegatesStruct);
private const string k_InitializeEnumMethodName = nameof(NetworkVariableHelper.InitializeDelegatesEnum);
private bool ImportReferences(ModuleDefinition moduleDefinition)
{
@@ -106,11 +247,18 @@ namespace Unity.Netcode.Editor.CodeGen
{
switch (methodInfo.Name)
{
case k_InitializeMethodName:
m_InitializeDelegates_MethodRef = moduleDefinition.ImportReference(methodInfo);
case k_InitializeNetworkSerializableMethodName:
m_InitializeDelegatesNetworkSerializable_MethodRef = moduleDefinition.ImportReference(methodInfo);
break;
case k_InitializeStructMethodName:
m_InitializeDelegatesStruct_MethodRef = moduleDefinition.ImportReference(methodInfo);
break;
case k_InitializeEnumMethodName:
m_InitializeDelegatesEnum_MethodRef = moduleDefinition.ImportReference(methodInfo);
break;
}
}
m_NetworkVariableSerializationType = moduleDefinition.ImportReference(typeof(NetworkVariableSerialization<>)).Resolve();
return true;
}
@@ -139,7 +287,7 @@ namespace Unity.Netcode.Editor.CodeGen
// C# (that attribute doesn't exist in Unity, but the static module constructor still works)
// https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.moduleinitializerattribute?view=net-5.0
// https://web.archive.org/web/20100212140402/http://blogs.msdn.com/junfeng/archive/2005/11/19/494914.aspx
private void CreateModuleInitializer(AssemblyDefinition assembly, List<TypeDefinition> networkSerializableTypes)
private void CreateModuleInitializer(AssemblyDefinition assembly, List<TypeReference> networkSerializableTypes, List<TypeReference> structTypes, List<TypeReference> enumTypes)
{
foreach (var typeDefinition in assembly.MainModule.Types)
{
@@ -151,9 +299,23 @@ namespace Unity.Netcode.Editor.CodeGen
var instructions = new List<Instruction>();
foreach (var type in structTypes)
{
var method = new GenericInstanceMethod(m_InitializeDelegatesStruct_MethodRef);
method.GenericArguments.Add(type);
instructions.Add(processor.Create(OpCodes.Call, method));
}
foreach (var type in networkSerializableTypes)
{
var method = new GenericInstanceMethod(m_InitializeDelegates_MethodRef);
var method = new GenericInstanceMethod(m_InitializeDelegatesNetworkSerializable_MethodRef);
method.GenericArguments.Add(type);
instructions.Add(processor.Create(OpCodes.Call, method));
}
foreach (var type in enumTypes)
{
var method = new GenericInstanceMethod(m_InitializeDelegatesEnum_MethodRef);
method.GenericArguments.Add(type);
instructions.Add(processor.Create(OpCodes.Call, method));
}

View File

@@ -509,6 +509,12 @@ namespace Unity.Netcode.Editor.CodeGen
isValid = false;
}
if (methodDefinition.HasGenericParameters)
{
m_Diagnostics.AddError(methodDefinition, "RPC method must not be generic!");
isValid = false;
}
if (methodDefinition.ReturnType != methodDefinition.Module.TypeSystem.Void)
{
m_Diagnostics.AddError(methodDefinition, "RPC method must return `void`!");
@@ -533,6 +539,10 @@ namespace Unity.Netcode.Editor.CodeGen
{
rpcAttribute = customAttribute;
}
else
{
return null;
}
}
}
@@ -575,7 +585,7 @@ namespace Unity.Netcode.Editor.CodeGen
var checkType = paramType.Resolve();
if (paramType.IsArray)
{
checkType = paramType.GetElementType().Resolve();
checkType = ((ArrayType)paramType).ElementType.Resolve();
}
if ((parameters[0].ParameterType.Resolve() == checkType ||
@@ -584,6 +594,12 @@ namespace Unity.Netcode.Editor.CodeGen
return method;
}
if (parameters[0].ParameterType == paramType ||
(parameters[0].ParameterType == paramType.MakeByReferenceType() && parameters[0].IsIn))
{
return method;
}
if (method.HasGenericParameters && method.GenericParameters.Count == 1)
{
if (method.GenericParameters[0].HasConstraints)
@@ -593,8 +609,9 @@ namespace Unity.Netcode.Editor.CodeGen
{
var resolvedConstraint = constraint.Resolve();
if ((resolvedConstraint.IsInterface && !checkType.HasInterface(resolvedConstraint.FullName)) ||
(resolvedConstraint.IsClass && !checkType.Resolve().IsSubclassOf(resolvedConstraint.FullName)) ||
var resolvedConstraintName = resolvedConstraint.FullNameWithGenericParameters(new[] { method.GenericParameters[0] }, new[] { checkType });
if ((resolvedConstraint.IsInterface && !checkType.HasInterface(resolvedConstraintName)) ||
(resolvedConstraint.IsClass && !checkType.Resolve().IsSubclassOf(resolvedConstraintName)) ||
(resolvedConstraint.Name == "ValueType" && !checkType.IsValueType))
{
meetsConstraints = false;
@@ -605,7 +622,14 @@ namespace Unity.Netcode.Editor.CodeGen
if (meetsConstraints)
{
var instanceMethod = new GenericInstanceMethod(method);
instanceMethod.GenericArguments.Add(checkType);
if (paramType.IsArray)
{
instanceMethod.GenericArguments.Add(((ArrayType)paramType).ElementType);
}
else
{
instanceMethod.GenericArguments.Add(paramType);
}
return instanceMethod;
}
}
@@ -653,13 +677,7 @@ namespace Unity.Netcode.Editor.CodeGen
}
}
// Try NetworkSerializable first because INetworkSerializable may also be valid for WriteValueSafe
// and that would cause boxing if so.
var typeMethod = GetFastBufferWriterWriteMethod("WriteNetworkSerializable", paramType);
if (typeMethod == null)
{
typeMethod = GetFastBufferWriterWriteMethod(k_WriteValueMethodName, paramType);
}
var typeMethod = GetFastBufferWriterWriteMethod(k_WriteValueMethodName, paramType);
if (typeMethod != null)
{
methodRef = m_MainModule.ImportReference(typeMethod);
@@ -699,28 +717,52 @@ namespace Unity.Netcode.Editor.CodeGen
var checkType = paramType.Resolve();
if (paramType.IsArray)
{
checkType = paramType.GetElementType().Resolve();
checkType = ((ArrayType)paramType).ElementType.Resolve();
}
if (methodParam.Resolve() == checkType.Resolve() || methodParam.Resolve() == checkType.MakeByReferenceType().Resolve())
{
return method;
}
if (methodParam.Resolve() == paramType || methodParam.Resolve() == paramType.MakeByReferenceType().Resolve())
{
return method;
}
if (method.HasGenericParameters && method.GenericParameters.Count == 1)
{
if (method.GenericParameters[0].HasConstraints)
{
var meetsConstraints = true;
foreach (var constraint in method.GenericParameters[0].Constraints)
{
var resolvedConstraint = constraint.Resolve();
if ((resolvedConstraint.IsInterface && checkType.HasInterface(resolvedConstraint.FullName)) ||
(resolvedConstraint.IsClass && checkType.Resolve().IsSubclassOf(resolvedConstraint.FullName)))
var resolvedConstraintName = resolvedConstraint.FullNameWithGenericParameters(new[] { method.GenericParameters[0] }, new[] { checkType });
if ((resolvedConstraint.IsInterface && !checkType.HasInterface(resolvedConstraintName)) ||
(resolvedConstraint.IsClass && !checkType.Resolve().IsSubclassOf(resolvedConstraintName)) ||
(resolvedConstraint.Name == "ValueType" && !checkType.IsValueType))
{
meetsConstraints = false;
break;
}
}
if (meetsConstraints)
{
var instanceMethod = new GenericInstanceMethod(method);
instanceMethod.GenericArguments.Add(checkType);
return instanceMethod;
if (paramType.IsArray)
{
instanceMethod.GenericArguments.Add(((ArrayType)paramType).ElementType);
}
else
{
instanceMethod.GenericArguments.Add(paramType);
}
return instanceMethod;
}
}
}
@@ -751,13 +793,7 @@ namespace Unity.Netcode.Editor.CodeGen
}
}
// Try NetworkSerializable first because INetworkSerializable may also be valid for ReadValueSafe
// and that would cause boxing if so.
var typeMethod = GetFastBufferReaderReadMethod("ReadNetworkSerializable", paramType);
if (typeMethod == null)
{
typeMethod = GetFastBufferReaderReadMethod(k_ReadValueMethodName, paramType);
}
var typeMethod = GetFastBufferReaderReadMethod(k_ReadValueMethodName, paramType);
if (typeMethod != null)
{
methodRef = m_MainModule.ImportReference(typeMethod);
@@ -1003,6 +1039,17 @@ namespace Unity.Netcode.Editor.CodeGen
// bufferWriter.WriteValueSafe(isSet);
instructions.Add(processor.Create(OpCodes.Ldloca, bufWriterLocIdx));
instructions.Add(processor.Create(OpCodes.Ldloca, isSetLocalIndex));
for (var i = 1; i < boolMethodRef.Parameters.Count; ++i)
{
var param = boolMethodRef.Parameters[i];
methodDefinition.Body.Variables.Add(new VariableDefinition(param.ParameterType));
int overloadParamLocalIdx = methodDefinition.Body.Variables.Count - 1;
instructions.Add(processor.Create(OpCodes.Ldloca, overloadParamLocalIdx));
instructions.Add(processor.Create(OpCodes.Initobj, param.ParameterType));
instructions.Add(processor.Create(OpCodes.Ldloc, overloadParamLocalIdx));
}
instructions.Add(processor.Create(OpCodes.Call, boolMethodRef));
// if(isSet) {
@@ -1055,11 +1102,38 @@ namespace Unity.Netcode.Editor.CodeGen
{
instructions.Add(processor.Create(OpCodes.Ldc_I4_0));
}
else
{
if (isExtensionMethod && methodRef.Parameters.Count > 2)
{
for (var i = 2; i < methodRef.Parameters.Count; ++i)
{
var param = methodRef.Parameters[i];
methodDefinition.Body.Variables.Add(new VariableDefinition(param.ParameterType));
int overloadParamLocalIdx = methodDefinition.Body.Variables.Count - 1;
instructions.Add(processor.Create(OpCodes.Ldloca, overloadParamLocalIdx));
instructions.Add(processor.Create(OpCodes.Initobj, param.ParameterType));
instructions.Add(processor.Create(OpCodes.Ldloc, overloadParamLocalIdx));
}
}
else if (!isExtensionMethod && methodRef.Parameters.Count > 1)
{
for (var i = 1; i < methodRef.Parameters.Count; ++i)
{
var param = methodRef.Parameters[i];
methodDefinition.Body.Variables.Add(new VariableDefinition(param.ParameterType));
int overloadParamLocalIdx = methodDefinition.Body.Variables.Count - 1;
instructions.Add(processor.Create(OpCodes.Ldloca, overloadParamLocalIdx));
instructions.Add(processor.Create(OpCodes.Initobj, param.ParameterType));
instructions.Add(processor.Create(OpCodes.Ldloc, overloadParamLocalIdx));
}
}
}
instructions.Add(processor.Create(OpCodes.Call, methodRef));
}
else
{
m_Diagnostics.AddError(methodDefinition, $"Don't know how to serialize {paramType.Name} - implement {nameof(INetworkSerializable)} or add an extension method for {nameof(FastBufferWriter)}.{k_WriteValueMethodName} to define serialization.");
m_Diagnostics.AddError(methodDefinition, $"Don't know how to serialize {paramType.Name} - implement {nameof(INetworkSerializable)}, tag memcpyable struct with {nameof(INetworkSerializeByMemcpy)}, or add an extension method for {nameof(FastBufferWriter)}.{k_WriteValueMethodName} to define serialization.");
continue;
}
@@ -1298,6 +1372,17 @@ namespace Unity.Netcode.Editor.CodeGen
int isSetLocalIndex = rpcHandler.Body.Variables.Count - 1;
processor.Emit(OpCodes.Ldarga, 1);
processor.Emit(OpCodes.Ldloca, isSetLocalIndex);
for (var i = 1; i < boolMethodRef.Parameters.Count; ++i)
{
var param = boolMethodRef.Parameters[i];
rpcHandler.Body.Variables.Add(new VariableDefinition(param.ParameterType));
int overloadParamLocalIdx = rpcHandler.Body.Variables.Count - 1;
processor.Emit(OpCodes.Ldloca, overloadParamLocalIdx);
processor.Emit(OpCodes.Initobj, param.ParameterType);
processor.Emit(OpCodes.Ldloc, overloadParamLocalIdx);
}
processor.Emit(OpCodes.Call, boolMethodRef);
// paramType param = null;
@@ -1331,11 +1416,38 @@ namespace Unity.Netcode.Editor.CodeGen
{
processor.Emit(OpCodes.Ldc_I4_0);
}
else
{
if (isExtensionMethod && methodRef.Parameters.Count > 2)
{
for (var i = 2; i < methodRef.Parameters.Count; ++i)
{
var param = methodRef.Parameters[i];
rpcHandler.Body.Variables.Add(new VariableDefinition(param.ParameterType));
int overloadParamLocalIdx = rpcHandler.Body.Variables.Count - 1;
processor.Emit(OpCodes.Ldloca, overloadParamLocalIdx);
processor.Emit(OpCodes.Initobj, param.ParameterType);
processor.Emit(OpCodes.Ldloc, overloadParamLocalIdx);
}
}
else if (!isExtensionMethod && methodRef.Parameters.Count > 1)
{
for (var i = 1; i < methodRef.Parameters.Count; ++i)
{
var param = methodRef.Parameters[i];
rpcHandler.Body.Variables.Add(new VariableDefinition(param.ParameterType));
int overloadParamLocalIdx = rpcHandler.Body.Variables.Count - 1;
processor.Emit(OpCodes.Ldloca, overloadParamLocalIdx);
processor.Emit(OpCodes.Initobj, param.ParameterType);
processor.Emit(OpCodes.Ldloc, overloadParamLocalIdx);
}
}
}
processor.Emit(OpCodes.Call, methodRef);
}
else
{
m_Diagnostics.AddError(methodDefinition, $"Don't know how to deserialize {paramType.Name} - implement {nameof(INetworkSerializable)} or add an extension method for {nameof(FastBufferReader)}.{k_ReadValueMethodName} to define serialization.");
m_Diagnostics.AddError(methodDefinition, $"Don't know how to serialize {paramType.Name} - implement {nameof(INetworkSerializable)}, tag memcpyable struct with {nameof(INetworkSerializeByMemcpy)}, or add an extension method for {nameof(FastBufferWriter)}.{k_WriteValueMethodName} to define serialization.");
continue;
}

View File

@@ -107,7 +107,15 @@ namespace Unity.Netcode.Editor.CodeGen
{
foreach (var methodDefinition in typeDefinition.Methods)
{
if (methodDefinition.Name == nameof(NetworkVariableHelper.InitializeDelegates))
if (methodDefinition.Name == nameof(NetworkVariableHelper.InitializeDelegatesEnum))
{
methodDefinition.IsPublic = true;
}
if (methodDefinition.Name == nameof(NetworkVariableHelper.InitializeDelegatesStruct))
{
methodDefinition.IsPublic = true;
}
if (methodDefinition.Name == nameof(NetworkVariableHelper.InitializeDelegatesNetworkSerializable))
{
methodDefinition.IsPublic = true;
}

View File

@@ -363,7 +363,7 @@ namespace Unity.Netcode.Editor
const string getToolsText = "Access additional tools for multiplayer development by installing the Multiplayer Tools package in the Package Manager.";
const string openDocsButtonText = "Open Docs";
const string dismissButtonText = "Dismiss";
const string targetUrl = "https://docs-multiplayer.unity3d.com/docs/tools/install-tools";
const string targetUrl = "https://docs-multiplayer.unity3d.com/netcode/current/tools/install-tools";
const string infoIconName = "console.infoicon";
if (PlayerPrefs.GetInt(InstallMultiplayerToolsTipDismissedPlayerPrefKey, 0) != 0)

View File

@@ -1,12 +1,16 @@
# Netcode for GameObjects
[![Forums](https://img.shields.io/badge/unity--forums-multiplayer-blue)](https://forum.unity.com/forums/multiplayer.26/) [![Discord](https://img.shields.io/discord/449263083769036810.svg?label=discord&logo=discord&color=informational)](https://discord.gg/FM8SE9E)
[![Website](https://img.shields.io/badge/docs-website-informational.svg)](https://docs-multiplayer.unity3d.com/) [![Api](https://img.shields.io/badge/docs-api-informational.svg)](https://docs-multiplayer.unity3d.com/docs/mlapi-api/introduction)
[![Manual](https://img.shields.io/badge/docs-manual-informational.svg)](https://docs-multiplayer.unity3d.com/netcode/current/about) [![API](https://img.shields.io/badge/docs-api-informational.svg)](https://docs-multiplayer.unity3d.com/netcode/current/api/introduction)
Netcode for GameObjects provides networking capabilities to GameObject & MonoBehaviour Unity workflows. The framework is interoperable with many low-level transports, including the official [Unity Transport Package](https://docs-multiplayer.unity3d.com/transport/1.0.0/introduction).
Netcode for GameObjects is a Unity package that provides networking capabilities to GameObject & MonoBehaviour workflows. The framework is interoperable with many low-level transports, including the official [Unity Transport Package](https://docs-multiplayer.unity3d.com/transport/current/about).
### Getting Started
Visit the [Multiplayer Docs Site](https://docs-multiplayer.unity3d.com/) for package & API documentation, as well as information about several samples which leverage the Netcode for GameObjects package.
You can also jump right into our [Hello World](https://docs-multiplayer.unity3d.com/netcode/current/tutorials/helloworld/helloworldintro) guide for a taste of how to use the framework for basic networked tasks.
### Community and Feedback
For general questions, networking advice or discussions about Netcode for GameObjects, please join our [Discord Community](https://discord.gg/FM8SE9E) or create a post in the [Unity Multiplayer Forum](https://forum.unity.com/forums/multiplayer.26/).

View File

@@ -5,6 +5,7 @@ using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Unity.Netcode.Editor.CodeGen")]
[assembly: InternalsVisibleTo("Unity.Netcode.Editor")]
[assembly: InternalsVisibleTo("TestProject.EditorTests")]
[assembly: InternalsVisibleTo("Unity.Netcode.Editor.CodeGen")]
#endif
[assembly: InternalsVisibleTo("TestProject.ToolsIntegration.RuntimeTests")]
[assembly: InternalsVisibleTo("TestProject.RuntimeTests")]

View File

@@ -128,10 +128,10 @@ namespace Unity.Netcode
public int LoadSceneTimeOut = 120;
/// <summary>
/// The amount of time a message should be buffered for without being consumed. If it is not consumed within this time, it will be dropped.
/// The amount of time a message should be buffered if the asset or object needed to process it doesn't exist yet. If the asset is not added/object is not spawned within this time, it will be dropped.
/// </summary>
[Tooltip("The amount of time a message should be buffered for without being consumed. If it is not consumed within this time, it will be dropped")]
public float MessageBufferTimeout = 20f;
[Tooltip("The amount of time a message should be buffered if the asset or object needed to process it doesn't exist yet. If the asset is not added/object is not spawned within this time, it will be dropped")]
public float SpawnTimeout = 1f;
/// <summary>
/// Whether or not to enable network logs.

View File

@@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
namespace Unity.Netcode
{
/// <summary>
/// This class is used to support testable code by allowing any supported component used by NetworkManager to be replaced
/// with a mock component or a test version that overloads certain methods to change or record their behavior.
/// Components currently supported by ComponentFactory:
/// - IDeferredMessageManager
/// </summary>
internal static class ComponentFactory
{
internal delegate object CreateObjectDelegate(NetworkManager networkManager);
private static Dictionary<Type, CreateObjectDelegate> s_Delegates = new Dictionary<Type, CreateObjectDelegate>();
/// <summary>
/// Instantiates an instance of a given interface
/// </summary>
/// <param name="networkManager">The network manager</param>
/// <typeparam name="T">The interface to instantiate it with</typeparam>
/// <returns></returns>
public static T Create<T>(NetworkManager networkManager)
{
return (T)s_Delegates[typeof(T)](networkManager);
}
/// <summary>
/// Overrides the default creation logic for a given interface type
/// </summary>
/// <param name="creator">The factory delegate to create the instance</param>
/// <typeparam name="T">The interface type to override</typeparam>
public static void Register<T>(CreateObjectDelegate creator)
{
s_Delegates[typeof(T)] = creator;
}
/// <summary>
/// Reverts the creation logic for a given interface type to the default logic
/// </summary>
/// <typeparam name="T">The interface type to revert</typeparam>
public static void Deregister<T>()
{
s_Delegates.Remove(typeof(T));
SetDefaults();
}
/// <summary>
/// Initializes the default creation logic for all supported component types
/// </summary>
public static void SetDefaults()
{
SetDefault<IDeferredMessageManager>(networkManager => new DeferredMessageManager(networkManager));
}
private static void SetDefault<T>(CreateObjectDelegate creator)
{
if (!s_Delegates.ContainsKey(typeof(T)))
{
s_Delegates[typeof(T)] = creator;
}
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: fda4c0eb89644fcea5416bbf98ea0ba0
timeCreated: 1649966562

View File

@@ -122,7 +122,7 @@ namespace Unity.Netcode
return !m_NetworkManager.m_StopProcessingMessages;
}
public bool OnVerifyCanReceive(ulong senderId, Type messageType)
public bool OnVerifyCanReceive(ulong senderId, Type messageType, FastBufferReader messageContent, ref NetworkContext context)
{
if (m_NetworkManager.PendingClients.TryGetValue(senderId, out PendingClient client) &&
(client.ConnectionState == PendingClient.State.PendingApproval || (client.ConnectionState == PendingClient.State.PendingConnection && messageType != typeof(ConnectionRequestMessage))))
@@ -223,6 +223,8 @@ namespace Unity.Netcode
/// </summary>
public NetworkSpawnManager SpawnManager { get; private set; }
internal IDeferredMessageManager DeferredMessageManager { get; private set; }
public CustomMessagingManager CustomMessagingManager { get; private set; }
public NetworkSceneManager SceneManager { get; private set; }
@@ -484,6 +486,253 @@ namespace Unity.Netcode
}
}
#endif
/// <summary>
/// Adds a new prefab to the network prefab list.
/// This can be any GameObject with a NetworkObject component, from any source (addressables, asset
/// bundles, Resource.Load, dynamically created, etc)
///
/// There are three limitations to this method:
/// - If you have NetworkConfig.ForceSamePrefabs enabled, you can only do this before starting
/// networking, and the server and all connected clients must all have the same exact set of prefabs
/// added via this method before connecting
/// - Adding a prefab on the server does not automatically add it on the client - it's up to you
/// to make sure the client and server are synchronized via whatever method makes sense for your game
/// (RPCs, configs, deterministic loading, etc)
/// - If the server sends a Spawn message to a client that has not yet added a prefab for, the spawn message
/// and any other relevant messages will be held for a configurable time (default 1 second, configured via
/// NetworkConfig.SpawnTimeout) before an error is logged. This is intented to enable the SDK to gracefully
/// handle unexpected conditions (slow disks, slow network, etc) that slow down asset loading. This timeout
/// should not be relied on and code shouldn't be written around it - your code should be written so that
/// the asset is expected to be loaded before it's needed.
/// </summary>
/// <param name="prefab"></param>
/// <exception cref="Exception"></exception>
public void AddNetworkPrefab(GameObject prefab)
{
if (IsListening && NetworkConfig.ForceSamePrefabs)
{
throw new Exception($"All prefabs must be registered before starting {nameof(NetworkManager)} when {nameof(NetworkConfig.ForceSamePrefabs)} is enabled.");
}
var networkObject = prefab.GetComponent<NetworkObject>();
if (!networkObject)
{
throw new Exception($"All {nameof(NetworkPrefab)}s must contain a {nameof(NetworkObject)} component.");
}
var networkPrefab = new NetworkPrefab { Prefab = prefab };
NetworkConfig.NetworkPrefabs.Add(networkPrefab);
if (IsListening)
{
var sourcePrefabGlobalObjectIdHash = (uint)0;
var targetPrefabGlobalObjectIdHash = (uint)0;
if (!ShouldAddPrefab(networkPrefab, out sourcePrefabGlobalObjectIdHash, out targetPrefabGlobalObjectIdHash))
{
NetworkConfig.NetworkPrefabs.Remove(networkPrefab);
return;
}
if (!AddPrefabRegistration(networkPrefab, sourcePrefabGlobalObjectIdHash, targetPrefabGlobalObjectIdHash))
{
NetworkConfig.NetworkPrefabs.Remove(networkPrefab);
return;
}
DeferredMessageManager.ProcessTriggers(IDeferredMessageManager.TriggerType.OnAddPrefab, networkObject.GlobalObjectIdHash);
}
}
private bool ShouldAddPrefab(NetworkPrefab networkPrefab, out uint sourcePrefabGlobalObjectIdHash, out uint targetPrefabGlobalObjectIdHash, int index = -1)
{
sourcePrefabGlobalObjectIdHash = 0;
targetPrefabGlobalObjectIdHash = 0;
var networkObject = (NetworkObject)null;
if (networkPrefab == null || (networkPrefab.Prefab == null && networkPrefab.Override == NetworkPrefabOverride.None))
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error)
{
NetworkLog.LogWarning(
$"{nameof(NetworkPrefab)} cannot be null ({nameof(NetworkPrefab)} at index: {index})");
}
return false;
}
else if (networkPrefab.Override == NetworkPrefabOverride.None)
{
networkObject = networkPrefab.Prefab.GetComponent<NetworkObject>();
if (networkObject == null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error)
{
NetworkLog.LogWarning($"{PrefabDebugHelper(networkPrefab)} is missing " +
$"a {nameof(NetworkObject)} component (entry will be ignored).");
}
return false;
}
// Otherwise get the GlobalObjectIdHash value
sourcePrefabGlobalObjectIdHash = networkObject.GlobalObjectIdHash;
}
else // Validate Overrides
{
// Validate source prefab override values first
switch (networkPrefab.Override)
{
case NetworkPrefabOverride.Hash:
{
if (networkPrefab.SourceHashToOverride == 0)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error)
{
NetworkLog.LogWarning($"{nameof(NetworkPrefab)} {nameof(NetworkPrefab.SourceHashToOverride)} is zero " +
"(entry will be ignored).");
}
return false;
}
sourcePrefabGlobalObjectIdHash = networkPrefab.SourceHashToOverride;
break;
}
case NetworkPrefabOverride.Prefab:
{
if (networkPrefab.SourcePrefabToOverride == null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error)
{
NetworkLog.LogWarning($"{nameof(NetworkPrefab)} {nameof(NetworkPrefab.SourcePrefabToOverride)} is null (entry will be ignored).");
}
Debug.LogWarning($"{nameof(NetworkPrefab)} override entry {networkPrefab.SourceHashToOverride} will be removed and ignored.");
return false;
}
else
{
networkObject = networkPrefab.SourcePrefabToOverride.GetComponent<NetworkObject>();
if (networkObject == null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error)
{
NetworkLog.LogWarning($"{nameof(NetworkPrefab)} ({networkPrefab.SourcePrefabToOverride.name}) " +
$"is missing a {nameof(NetworkObject)} component (entry will be ignored).");
}
Debug.LogWarning($"{nameof(NetworkPrefab)} override entry (\"{networkPrefab.SourcePrefabToOverride.name}\") will be removed and ignored.");
return false;
}
sourcePrefabGlobalObjectIdHash = networkObject.GlobalObjectIdHash;
}
break;
}
}
// Validate target prefab override values next
if (networkPrefab.OverridingTargetPrefab == null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error)
{
NetworkLog.LogWarning($"{nameof(NetworkPrefab)} {nameof(NetworkPrefab.OverridingTargetPrefab)} is null!");
}
switch (networkPrefab.Override)
{
case NetworkPrefabOverride.Hash:
{
Debug.LogWarning($"{nameof(NetworkPrefab)} override entry {networkPrefab.SourceHashToOverride} will be removed and ignored.");
break;
}
case NetworkPrefabOverride.Prefab:
{
Debug.LogWarning($"{nameof(NetworkPrefab)} override entry ({networkPrefab.SourcePrefabToOverride.name}) will be removed and ignored.");
break;
}
}
return false;
}
else
{
targetPrefabGlobalObjectIdHash = networkPrefab.OverridingTargetPrefab.GetComponent<NetworkObject>().GlobalObjectIdHash;
}
}
return true;
}
internal bool AddPrefabRegistration(NetworkPrefab networkPrefab, uint sourcePrefabGlobalObjectIdHash, uint targetPrefabGlobalObjectIdHash)
{
// Assign the appropriate GlobalObjectIdHash to the appropriate NetworkPrefab
if (!NetworkConfig.NetworkPrefabOverrideLinks.ContainsKey(sourcePrefabGlobalObjectIdHash))
{
if (networkPrefab.Override == NetworkPrefabOverride.None)
{
NetworkConfig.NetworkPrefabOverrideLinks.Add(sourcePrefabGlobalObjectIdHash, networkPrefab);
}
else
{
if (!NetworkConfig.OverrideToNetworkPrefab.ContainsKey(targetPrefabGlobalObjectIdHash))
{
switch (networkPrefab.Override)
{
case NetworkPrefabOverride.Prefab:
{
NetworkConfig.NetworkPrefabOverrideLinks.Add(sourcePrefabGlobalObjectIdHash, networkPrefab);
NetworkConfig.OverrideToNetworkPrefab.Add(targetPrefabGlobalObjectIdHash, sourcePrefabGlobalObjectIdHash);
}
break;
case NetworkPrefabOverride.Hash:
{
NetworkConfig.NetworkPrefabOverrideLinks.Add(sourcePrefabGlobalObjectIdHash, networkPrefab);
NetworkConfig.OverrideToNetworkPrefab.Add(targetPrefabGlobalObjectIdHash, sourcePrefabGlobalObjectIdHash);
}
break;
}
}
else
{
var networkObject = networkPrefab.Prefab.GetComponent<NetworkObject>();
// This can happen if a user tries to make several GlobalObjectIdHash values point to the same target
Debug.LogError($"{nameof(NetworkPrefab)} (\"{networkObject.name}\") has a duplicate {nameof(NetworkObject.GlobalObjectIdHash)} target entry value of: {targetPrefabGlobalObjectIdHash}! Removing entry from list!");
return false;
}
}
}
else
{
var networkObject = networkPrefab.Prefab.GetComponent<NetworkObject>();
// This should never happen, but in the case it somehow does log an error and remove the duplicate entry
Debug.LogError($"{nameof(NetworkPrefab)} ({networkObject.name}) has a duplicate {nameof(NetworkObject.GlobalObjectIdHash)} source entry value of: {sourcePrefabGlobalObjectIdHash}! Removing entry from list!");
return false;
}
return true;
}
private void InitializePrefabs(int startIdx = 0)
{
// This is used to remove entries not needed or invalid
var removeEmptyPrefabs = new List<int>();
// Build the NetworkPrefabOverrideLinks dictionary
for (int i = startIdx; i < NetworkConfig.NetworkPrefabs.Count; i++)
{
var sourcePrefabGlobalObjectIdHash = (uint)0;
var targetPrefabGlobalObjectIdHash = (uint)0;
if (!ShouldAddPrefab(NetworkConfig.NetworkPrefabs[i], out sourcePrefabGlobalObjectIdHash, out targetPrefabGlobalObjectIdHash, i))
{
removeEmptyPrefabs.Add(i);
continue;
}
if (!AddPrefabRegistration(NetworkConfig.NetworkPrefabs[i], sourcePrefabGlobalObjectIdHash, targetPrefabGlobalObjectIdHash))
{
removeEmptyPrefabs.Add(i);
continue;
}
}
// Clear out anything that is invalid or not used (for invalid entries we already logged warnings to the user earlier)
// Iterate backwards so indices don't shift as we remove
for (int i = removeEmptyPrefabs.Count - 1; i >= 0; i--)
{
NetworkConfig.NetworkPrefabs.RemoveAt(removeEmptyPrefabs[i]);
}
removeEmptyPrefabs.Clear();
}
private void Initialize(bool server)
{
@@ -494,6 +743,8 @@ namespace Unity.Netcode
return;
}
ComponentFactory.SetDefaults();
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer)
{
NetworkLog.LogInfo(nameof(Initialize));
@@ -524,6 +775,8 @@ namespace Unity.Netcode
// Create spawn manager instance
SpawnManager = new NetworkSpawnManager(this);
DeferredMessageManager = ComponentFactory.Create<IDeferredMessageManager>(this);
CustomMessagingManager = new CustomMessagingManager(this);
SceneManager = new NetworkSceneManager(this);
@@ -573,171 +826,11 @@ namespace Unity.Netcode
this.RegisterNetworkUpdate(NetworkUpdateStage.PreUpdate);
// This is used to remove entries not needed or invalid
var removeEmptyPrefabs = new List<int>();
// Always clear our prefab override links before building
NetworkConfig.NetworkPrefabOverrideLinks.Clear();
NetworkConfig.OverrideToNetworkPrefab.Clear();
// Build the NetworkPrefabOverrideLinks dictionary
for (int i = 0; i < NetworkConfig.NetworkPrefabs.Count; i++)
{
var sourcePrefabGlobalObjectIdHash = (uint)0;
var targetPrefabGlobalObjectIdHash = (uint)0;
var networkObject = (NetworkObject)null;
if (NetworkConfig.NetworkPrefabs[i] == null || (NetworkConfig.NetworkPrefabs[i].Prefab == null && NetworkConfig.NetworkPrefabs[i].Override == NetworkPrefabOverride.None))
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error)
{
NetworkLog.LogWarning(
$"{nameof(NetworkPrefab)} cannot be null ({nameof(NetworkPrefab)} at index: {i})");
}
removeEmptyPrefabs.Add(i);
continue;
}
else if (NetworkConfig.NetworkPrefabs[i].Override == NetworkPrefabOverride.None)
{
var networkPrefab = NetworkConfig.NetworkPrefabs[i];
networkObject = networkPrefab.Prefab.GetComponent<NetworkObject>();
if (networkObject == null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error)
{
NetworkLog.LogWarning($"{PrefabDebugHelper(networkPrefab)} is missing " +
$"a {nameof(NetworkObject)} component (entry will be ignored).");
}
removeEmptyPrefabs.Add(i);
continue;
}
// Otherwise get the GlobalObjectIdHash value
sourcePrefabGlobalObjectIdHash = networkObject.GlobalObjectIdHash;
}
else // Validate Overrides
{
// Validate source prefab override values first
switch (NetworkConfig.NetworkPrefabs[i].Override)
{
case NetworkPrefabOverride.Hash:
{
if (NetworkConfig.NetworkPrefabs[i].SourceHashToOverride == 0)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error)
{
NetworkLog.LogWarning($"{nameof(NetworkPrefab)} {nameof(NetworkPrefab.SourceHashToOverride)} is zero " +
"(entry will be ignored).");
}
removeEmptyPrefabs.Add(i);
continue;
}
sourcePrefabGlobalObjectIdHash = NetworkConfig.NetworkPrefabs[i].SourceHashToOverride;
break;
}
case NetworkPrefabOverride.Prefab:
{
if (NetworkConfig.NetworkPrefabs[i].SourcePrefabToOverride == null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error)
{
NetworkLog.LogWarning($"{nameof(NetworkPrefab)} {nameof(NetworkPrefab.SourcePrefabToOverride)} is null (entry will be ignored).");
}
Debug.LogWarning($"{nameof(NetworkPrefab)} override entry {NetworkConfig.NetworkPrefabs[i].SourceHashToOverride} will be removed and ignored.");
removeEmptyPrefabs.Add(i);
continue;
}
else
{
networkObject = NetworkConfig.NetworkPrefabs[i].SourcePrefabToOverride.GetComponent<NetworkObject>();
if (networkObject == null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error)
{
NetworkLog.LogWarning($"{nameof(NetworkPrefab)} ({NetworkConfig.NetworkPrefabs[i].SourcePrefabToOverride.name}) " +
$"is missing a {nameof(NetworkObject)} component (entry will be ignored).");
}
Debug.LogWarning($"{nameof(NetworkPrefab)} override entry (\"{NetworkConfig.NetworkPrefabs[i].SourcePrefabToOverride.name}\") will be removed and ignored.");
removeEmptyPrefabs.Add(i);
continue;
}
sourcePrefabGlobalObjectIdHash = networkObject.GlobalObjectIdHash;
}
break;
}
}
// Validate target prefab override values next
if (NetworkConfig.NetworkPrefabs[i].OverridingTargetPrefab == null)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error)
{
NetworkLog.LogWarning($"{nameof(NetworkPrefab)} {nameof(NetworkPrefab.OverridingTargetPrefab)} is null!");
}
removeEmptyPrefabs.Add(i);
switch (NetworkConfig.NetworkPrefabs[i].Override)
{
case NetworkPrefabOverride.Hash:
{
Debug.LogWarning($"{nameof(NetworkPrefab)} override entry {NetworkConfig.NetworkPrefabs[i].SourceHashToOverride} will be removed and ignored.");
break;
}
case NetworkPrefabOverride.Prefab:
{
Debug.LogWarning($"{nameof(NetworkPrefab)} override entry ({NetworkConfig.NetworkPrefabs[i].SourcePrefabToOverride.name}) will be removed and ignored.");
break;
}
}
continue;
}
else
{
targetPrefabGlobalObjectIdHash = NetworkConfig.NetworkPrefabs[i].OverridingTargetPrefab.GetComponent<NetworkObject>().GlobalObjectIdHash;
}
}
// Assign the appropriate GlobalObjectIdHash to the appropriate NetworkPrefab
if (!NetworkConfig.NetworkPrefabOverrideLinks.ContainsKey(sourcePrefabGlobalObjectIdHash))
{
if (NetworkConfig.NetworkPrefabs[i].Override == NetworkPrefabOverride.None)
{
NetworkConfig.NetworkPrefabOverrideLinks.Add(sourcePrefabGlobalObjectIdHash, NetworkConfig.NetworkPrefabs[i]);
}
else
{
if (!NetworkConfig.OverrideToNetworkPrefab.ContainsKey(targetPrefabGlobalObjectIdHash))
{
switch (NetworkConfig.NetworkPrefabs[i].Override)
{
case NetworkPrefabOverride.Prefab:
{
NetworkConfig.NetworkPrefabOverrideLinks.Add(sourcePrefabGlobalObjectIdHash, NetworkConfig.NetworkPrefabs[i]);
NetworkConfig.OverrideToNetworkPrefab.Add(targetPrefabGlobalObjectIdHash, sourcePrefabGlobalObjectIdHash);
}
break;
case NetworkPrefabOverride.Hash:
{
NetworkConfig.NetworkPrefabOverrideLinks.Add(sourcePrefabGlobalObjectIdHash, NetworkConfig.NetworkPrefabs[i]);
NetworkConfig.OverrideToNetworkPrefab.Add(targetPrefabGlobalObjectIdHash, sourcePrefabGlobalObjectIdHash);
}
break;
}
}
else
{
// This can happen if a user tries to make several GlobalObjectIdHash values point to the same target
Debug.LogError($"{nameof(NetworkPrefab)} (\"{networkObject.name}\") has a duplicate {nameof(NetworkObject.GlobalObjectIdHash)} target entry value of: {targetPrefabGlobalObjectIdHash}! Removing entry from list!");
removeEmptyPrefabs.Add(i);
}
}
}
else
{
// This should never happen, but in the case it somehow does log an error and remove the duplicate entry
Debug.LogError($"{nameof(NetworkPrefab)} ({networkObject.name}) has a duplicate {nameof(NetworkObject.GlobalObjectIdHash)} source entry value of: {sourcePrefabGlobalObjectIdHash}! Removing entry from list!");
removeEmptyPrefabs.Add(i);
}
}
InitializePrefabs();
// If we have a player prefab, then we need to verify it is in the list of NetworkPrefabOverrideLinks for client side spawning.
if (NetworkConfig.PlayerPrefab != null)
@@ -764,15 +857,6 @@ namespace Unity.Netcode
}
}
// Clear out anything that is invalid or not used (for invalid entries we already logged warnings to the user earlier)
// Iterate backwards so indices don't shift as we remove
for (int i = removeEmptyPrefabs.Count - 1; i >= 0; i--)
{
NetworkConfig.NetworkPrefabs.RemoveAt(removeEmptyPrefabs[i]);
}
removeEmptyPrefabs.Clear();
NetworkConfig.NetworkTransport.OnTransportEvent += HandleRawTransportPoll;
NetworkConfig.NetworkTransport.Initialize(this);
@@ -930,7 +1014,9 @@ namespace Unity.Netcode
return false;
}
if (NetworkConfig.ConnectionApproval)
// Only if it is starting as a server or host do we need to check this
// Clients don't invoke the ConnectionApprovalCallback
if (NetworkConfig.ConnectionApproval && type != StartType.Client)
{
if (ConnectionApprovalCallback == null)
{
@@ -985,6 +1071,7 @@ namespace Unity.Netcode
private void Awake()
{
UnityEngine.SceneManagement.SceneManager.sceneUnloaded += OnSceneUnloaded;
NetworkVariableHelper.InitializeAllBaseDelegates();
}
/// <summary>
@@ -1081,9 +1168,14 @@ namespace Unity.Netcode
NetworkLog.LogInfo(nameof(Shutdown));
}
// If we're not running, don't start shutting down, it would only cause an immediate
// shutdown the next time the manager is started.
if (IsServer || IsClient)
{
m_ShuttingDown = true;
m_StopProcessingMessages = discardMessageQueue;
}
}
internal void ShutdownInternal()
{
@@ -1165,13 +1257,17 @@ namespace Unity.Netcode
if (SpawnManager != null)
{
SpawnManager.CleanupAllTriggers();
SpawnManager.DespawnAndDestroyNetworkObjects();
SpawnManager.ServerResetShudownStateForSceneObjects();
SpawnManager = null;
}
if (DeferredMessageManager != null)
{
DeferredMessageManager.CleanupAllTriggers();
}
if (SceneManager != null)
{
// Let the NetworkSceneManager clean up its two SceneEvenData instances
@@ -1287,7 +1383,7 @@ namespace Unity.Netcode
NetworkObject.VerifyParentingStatus();
}
SpawnManager.CleanupStaleTriggers();
DeferredMessageManager.CleanupStaleTriggers();
if (m_ShuttingDown)
{
@@ -1415,11 +1511,6 @@ namespace Unity.Netcode
break;
case NetworkEvent.Data:
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer)
{
NetworkLog.LogInfo($"Incoming Data From {clientId}: {payload.Count} bytes");
}
clientId = TransportIdToClientId(clientId);
HandleIncomingData(clientId, payload, receiveTime);
@@ -1444,7 +1535,11 @@ namespace Unity.Netcode
}
else
{
Shutdown();
// We must pass true here and not process any sends messages
// as we are no longer connected and thus there is no one to
// send any messages to and this will cause an exception within
// UnityTransport as the client ID is no longer valid.
Shutdown(true);
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
s_TransportDisconnect.End();

View File

@@ -826,7 +826,7 @@ namespace Unity.Netcode
internal struct SceneObject
{
public struct HeaderData
public struct HeaderData : INetworkSerializeByMemcpy
{
public ulong NetworkObjectId;
public ulong OwnerClientId;
@@ -845,7 +845,7 @@ namespace Unity.Netcode
public ulong ParentObjectId;
//If(Metadata.HasTransform)
public struct TransformData
public struct TransformData : INetworkSerializeByMemcpy
{
public Vector3 Position;
public Quaternion Rotation;

View File

@@ -3,7 +3,7 @@ namespace Unity.Netcode
/// <summary>
/// Header placed at the start of each message batch
/// </summary>
internal struct BatchHeader
internal struct BatchHeader : INetworkSerializeByMemcpy
{
/// <summary>
/// Total number of messages in the batch.

View File

@@ -0,0 +1,149 @@
using System.Collections.Generic;
using Unity.Collections;
using Time = UnityEngine.Time;
namespace Unity.Netcode
{
internal class DeferredMessageManager : IDeferredMessageManager
{
protected struct TriggerData
{
public FastBufferReader Reader;
public MessageHeader Header;
public ulong SenderId;
public float Timestamp;
public int SerializedHeaderSize;
}
protected struct TriggerInfo
{
public float Expiry;
public NativeList<TriggerData> TriggerData;
}
protected readonly Dictionary<IDeferredMessageManager.TriggerType, Dictionary<ulong, TriggerInfo>> m_Triggers = new Dictionary<IDeferredMessageManager.TriggerType, Dictionary<ulong, TriggerInfo>>();
private readonly NetworkManager m_NetworkManager;
internal DeferredMessageManager(NetworkManager networkManager)
{
m_NetworkManager = networkManager;
}
/// <summary>
/// Defers processing of a message until the moment a specific networkObjectId is spawned.
/// This is to handle situations where an RPC or other object-specific message arrives before the spawn does,
/// either due to it being requested in OnNetworkSpawn before the spawn call has been executed
///
/// There is a one second maximum lifetime of triggers to avoid memory leaks. After one second has passed
/// without the requested object ID being spawned, the triggers for it are automatically deleted.
/// </summary>
public virtual unsafe void DeferMessage(IDeferredMessageManager.TriggerType trigger, ulong key, FastBufferReader reader, ref NetworkContext context)
{
if (!m_Triggers.TryGetValue(trigger, out var triggers))
{
triggers = new Dictionary<ulong, TriggerInfo>();
m_Triggers[trigger] = triggers;
}
if (!triggers.TryGetValue(key, out var triggerInfo))
{
triggerInfo = new TriggerInfo
{
Expiry = Time.realtimeSinceStartup + m_NetworkManager.NetworkConfig.SpawnTimeout,
TriggerData = new NativeList<TriggerData>(Allocator.Persistent)
};
triggers[key] = triggerInfo;
}
triggerInfo.TriggerData.Add(new TriggerData
{
Reader = new FastBufferReader(reader.GetUnsafePtr(), Allocator.Persistent, reader.Length),
Header = context.Header,
Timestamp = context.Timestamp,
SenderId = context.SenderId,
SerializedHeaderSize = context.SerializedHeaderSize
});
}
/// <summary>
/// Cleans up any trigger that's existed for more than a second.
/// These triggers were probably for situations where a request was received after a despawn rather than before a spawn.
/// </summary>
public virtual unsafe void CleanupStaleTriggers()
{
foreach (var kvp in m_Triggers)
{
ulong* staleKeys = stackalloc ulong[kvp.Value.Count];
int index = 0;
foreach (var kvp2 in kvp.Value)
{
if (kvp2.Value.Expiry < Time.realtimeSinceStartup)
{
staleKeys[index++] = kvp2.Key;
PurgeTrigger(kvp.Key, kvp2.Key, kvp2.Value);
}
}
for (var i = 0; i < index; ++i)
{
kvp.Value.Remove(staleKeys[i]);
}
}
}
protected virtual void PurgeTrigger(IDeferredMessageManager.TriggerType triggerType, ulong key, TriggerInfo triggerInfo)
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
{
NetworkLog.LogWarning($"Deferred messages were received for a trigger of type {triggerType} with key {key}, but that trigger was not received within within {m_NetworkManager.NetworkConfig.SpawnTimeout} second(s).");
}
foreach (var data in triggerInfo.TriggerData)
{
data.Reader.Dispose();
}
triggerInfo.TriggerData.Dispose();
}
public virtual void ProcessTriggers(IDeferredMessageManager.TriggerType trigger, ulong key)
{
if (m_Triggers.TryGetValue(trigger, out var triggers))
{
// This must happen after InvokeBehaviourNetworkSpawn, otherwise ClientRPCs and other messages can be
// processed before the object is fully spawned. This must be the last thing done in the spawn process.
if (triggers.TryGetValue(key, out var triggerInfo))
{
foreach (var deferredMessage in triggerInfo.TriggerData)
{
// Reader will be disposed within HandleMessage
m_NetworkManager.MessagingSystem.HandleMessage(deferredMessage.Header, deferredMessage.Reader, deferredMessage.SenderId, deferredMessage.Timestamp, deferredMessage.SerializedHeaderSize);
}
triggerInfo.TriggerData.Dispose();
triggers.Remove(key);
}
}
}
/// <summary>
/// Cleans up any trigger that's existed for more than a second.
/// These triggers were probably for situations where a request was received after a despawn rather than before a spawn.
/// </summary>
public virtual void CleanupAllTriggers()
{
foreach (var kvp in m_Triggers)
{
foreach (var kvp2 in kvp.Value)
{
foreach (var data in kvp2.Value.TriggerData)
{
data.Reader.Dispose();
}
kvp2.Value.TriggerData.Dispose();
}
}
m_Triggers.Clear();
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: ac7f57f7d16a46e2aba65558e873727f
timeCreated: 1649799187

View File

@@ -0,0 +1,35 @@
namespace Unity.Netcode
{
internal interface IDeferredMessageManager
{
internal enum TriggerType
{
OnSpawn,
OnAddPrefab,
}
/// <summary>
/// Defers processing of a message until the moment a specific networkObjectId is spawned.
/// This is to handle situations where an RPC or other object-specific message arrives before the spawn does,
/// either due to it being requested in OnNetworkSpawn before the spawn call has been executed
///
/// There is a one second maximum lifetime of triggers to avoid memory leaks. After one second has passed
/// without the requested object ID being spawned, the triggers for it are automatically deleted.
/// </summary>
void DeferMessage(TriggerType trigger, ulong key, FastBufferReader reader, ref NetworkContext context);
/// <summary>
/// Cleans up any trigger that's existed for more than a second.
/// These triggers were probably for situations where a request was received after a despawn rather than before a spawn.
/// </summary>
void CleanupStaleTriggers();
void ProcessTriggers(TriggerType trigger, ulong key);
/// <summary>
/// Cleans up any trigger that's existed for more than a second.
/// These triggers were probably for situations where a request was received after a despawn rather than before a spawn.
/// </summary>
void CleanupAllTriggers();
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7fb73a029c314763a04ebb015a07664d
timeCreated: 1649966331

View File

@@ -91,8 +91,10 @@ namespace Unity.Netcode
/// </summary>
/// <param name="senderId">The source clientId</param>
/// <param name="messageType">The type of the message</param>
/// <param name="messageContent">The FastBufferReader containing the message</param>
/// <param name="context">The NetworkContext the message is being processed in</param>
/// <returns></returns>
bool OnVerifyCanReceive(ulong senderId, Type messageType);
bool OnVerifyCanReceive(ulong senderId, Type messageType, FastBufferReader messageContent, ref NetworkContext context);
/// <summary>
/// Called after a message is serialized, but before it's handled.

View File

@@ -3,7 +3,7 @@ namespace Unity.Netcode
/// <summary>
/// This is the header data that's serialized to the network when sending an <see cref="INetworkMessage"/>
/// </summary>
internal struct MessageHeader
internal struct MessageHeader : INetworkSerializeByMemcpy
{
/// <summary>
/// The byte representation of the message type. This is automatically assigned to each message

View File

@@ -1,6 +1,6 @@
namespace Unity.Netcode
{
internal struct ChangeOwnershipMessage : INetworkMessage
internal struct ChangeOwnershipMessage : INetworkMessage, INetworkSerializeByMemcpy
{
public ulong NetworkObjectId;
public ulong OwnerClientId;
@@ -20,7 +20,7 @@ namespace Unity.Netcode
reader.ReadValueSafe(out this);
if (!networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId))
{
networkManager.SpawnManager.TriggerOnSpawn(NetworkObjectId, reader, ref context);
networkManager.DeferredMessageManager.DeferMessage(IDeferredMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context);
return false;
}

View File

@@ -19,6 +19,11 @@ namespace Unity.Netcode
}
ObjectInfo.Deserialize(reader);
if (!networkManager.NetworkConfig.ForceSamePrefabs && !networkManager.SpawnManager.HasPrefab(ObjectInfo.Header.IsSceneObject, ObjectInfo.Header.Hash))
{
networkManager.DeferredMessageManager.DeferMessage(IDeferredMessageManager.TriggerType.OnAddPrefab, ObjectInfo.Header.Hash, reader, ref context);
return false;
}
m_ReceivedNetworkVariableData = reader;
return true;

View File

@@ -1,6 +1,6 @@
namespace Unity.Netcode
{
internal struct DestroyObjectMessage : INetworkMessage
internal struct DestroyObjectMessage : INetworkMessage, INetworkSerializeByMemcpy
{
public ulong NetworkObjectId;
@@ -16,7 +16,14 @@ namespace Unity.Netcode
{
return false;
}
reader.ReadValueSafe(out this);
if (!networkManager.SpawnManager.SpawnedObjects.TryGetValue(NetworkObjectId, out var networkObject))
{
networkManager.DeferredMessageManager.DeferMessage(IDeferredMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context);
return false;
}
return true;
}

View File

@@ -54,6 +54,14 @@ namespace Unity.Netcode
networkVariable.CanClientRead(TargetClientId) &&
(NetworkBehaviour.NetworkManager.IsServer || networkVariable.CanClientWrite(NetworkBehaviour.NetworkManager.LocalClientId));
// 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
if (networkVariable.WritePerm == NetworkVariableWritePermission.Owner &&
networkVariable.OwnerClientId() == TargetClientId)
{
shouldWrite = false;
}
if (NetworkBehaviour.NetworkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
{
if (!shouldWrite)
@@ -225,7 +233,7 @@ namespace Unity.Netcode
}
else
{
networkManager.SpawnManager.TriggerOnSpawn(NetworkObjectId, m_ReceivedNetworkVariableData, ref context);
networkManager.DeferredMessageManager.DeferMessage(IDeferredMessageManager.TriggerType.OnSpawn, NetworkObjectId, m_ReceivedNetworkVariableData, ref context);
}
}
}

View File

@@ -48,7 +48,7 @@ namespace Unity.Netcode
if (!networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId))
{
networkManager.SpawnManager.TriggerOnSpawn(NetworkObjectId, reader, ref context);
networkManager.DeferredMessageManager.DeferMessage(IDeferredMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context);
return false;
}

View File

@@ -30,7 +30,7 @@ namespace Unity.Netcode
var networkManager = (NetworkManager)context.SystemOwner;
if (!networkManager.SpawnManager.SpawnedObjects.ContainsKey(metadata.NetworkObjectId))
{
networkManager.SpawnManager.TriggerOnSpawn(metadata.NetworkObjectId, reader, ref context);
networkManager.DeferredMessageManager.DeferMessage(IDeferredMessageManager.TriggerType.OnSpawn, metadata.NetworkObjectId, reader, ref context);
return false;
}
@@ -83,7 +83,7 @@ namespace Unity.Netcode
}
}
internal struct RpcMetadata
internal struct RpcMetadata : INetworkSerializeByMemcpy
{
public ulong NetworkObjectId;
public ushort NetworkBehaviourId;

View File

@@ -1,6 +1,6 @@
namespace Unity.Netcode
{
internal struct TimeSyncMessage : INetworkMessage
internal struct TimeSyncMessage : INetworkMessage, INetworkSerializeByMemcpy
{
public int Tick;

View File

@@ -136,6 +136,11 @@ namespace Unity.Netcode
m_Hooks.Add(hooks);
}
public void Unhook(INetworkHooks hooks)
{
m_Hooks.Remove(hooks);
}
private void RegisterMessageType(MessageWithHandler messageWithHandler)
{
m_MessageHandlers[m_HighMessageType] = messageWithHandler.Handler;
@@ -208,11 +213,11 @@ namespace Unity.Netcode
}
}
private bool CanReceive(ulong clientId, Type messageType)
private bool CanReceive(ulong clientId, Type messageType, FastBufferReader messageContent, ref NetworkContext context)
{
for (var hookIdx = 0; hookIdx < m_Hooks.Count; ++hookIdx)
{
if (!m_Hooks[hookIdx].OnVerifyCanReceive(clientId, messageType))
if (!m_Hooks[hookIdx].OnVerifyCanReceive(clientId, messageType, messageContent, ref context))
{
return false;
}
@@ -240,7 +245,7 @@ namespace Unity.Netcode
};
var type = m_ReverseTypeMap[header.MessageType];
if (!CanReceive(senderId, type))
if (!CanReceive(senderId, type, reader, ref context))
{
reader.Dispose();
return;

View File

@@ -52,7 +52,7 @@ namespace Unity.Netcode
return true;
}
public bool OnVerifyCanReceive(ulong senderId, Type messageType)
public bool OnVerifyCanReceive(ulong senderId, Type messageType, FastBufferReader messageContent, ref NetworkContext context)
{
return true;
}

View File

@@ -8,7 +8,7 @@ namespace Unity.Netcode
/// Event based NetworkVariable container for syncing Lists
/// </summary>
/// <typeparam name="T">The type for the list</typeparam>
public class NetworkList<T> : NetworkVariableBase where T : unmanaged, IEquatable<T>
public class NetworkList<T> : NetworkVariableSerialization<T> where T : unmanaged, IEquatable<T>
{
private NativeList<T> m_List = new NativeList<T>(64, Allocator.Persistent);
private NativeList<NetworkListEvent<T>> m_DirtyEvents = new NativeList<NetworkListEvent<T>>(64, Allocator.Persistent);
@@ -72,18 +72,18 @@ namespace Unity.Netcode
{
case NetworkListEvent<T>.EventType.Add:
{
NetworkVariable<T>.Write(writer, m_DirtyEvents[i].Value);
Write(writer, m_DirtyEvents[i].Value);
}
break;
case NetworkListEvent<T>.EventType.Insert:
{
writer.WriteValueSafe(m_DirtyEvents[i].Index);
NetworkVariable<T>.Write(writer, m_DirtyEvents[i].Value);
Write(writer, m_DirtyEvents[i].Value);
}
break;
case NetworkListEvent<T>.EventType.Remove:
{
NetworkVariable<T>.Write(writer, m_DirtyEvents[i].Value);
Write(writer, m_DirtyEvents[i].Value);
}
break;
case NetworkListEvent<T>.EventType.RemoveAt:
@@ -94,7 +94,7 @@ namespace Unity.Netcode
case NetworkListEvent<T>.EventType.Value:
{
writer.WriteValueSafe(m_DirtyEvents[i].Index);
NetworkVariable<T>.Write(writer, m_DirtyEvents[i].Value);
Write(writer, m_DirtyEvents[i].Value);
}
break;
case NetworkListEvent<T>.EventType.Clear:
@@ -112,7 +112,7 @@ namespace Unity.Netcode
writer.WriteValueSafe((ushort)m_List.Length);
for (int i = 0; i < m_List.Length; i++)
{
NetworkVariable<T>.Write(writer, m_List[i]);
Write(writer, m_List[i]);
}
}
@@ -123,7 +123,7 @@ namespace Unity.Netcode
reader.ReadValueSafe(out ushort count);
for (int i = 0; i < count; i++)
{
NetworkVariable<T>.Read(reader, out T value);
Read(reader, out T value);
m_List.Add(value);
}
}
@@ -139,7 +139,7 @@ namespace Unity.Netcode
{
case NetworkListEvent<T>.EventType.Add:
{
NetworkVariable<T>.Read(reader, out T value);
Read(reader, out T value);
m_List.Add(value);
if (OnListChanged != null)
@@ -166,7 +166,7 @@ namespace Unity.Netcode
case NetworkListEvent<T>.EventType.Insert:
{
reader.ReadValueSafe(out int index);
NetworkVariable<T>.Read(reader, out T value);
Read(reader, out T value);
m_List.InsertRangeWithBeginEnd(index, index + 1);
m_List[index] = value;
@@ -193,7 +193,7 @@ namespace Unity.Netcode
break;
case NetworkListEvent<T>.EventType.Remove:
{
NetworkVariable<T>.Read(reader, out T value);
Read(reader, out T value);
int index = m_List.IndexOf(value);
if (index == -1)
{
@@ -253,7 +253,7 @@ namespace Unity.Netcode
case NetworkListEvent<T>.EventType.Value:
{
reader.ReadValueSafe(out int index);
NetworkVariable<T>.Read(reader, out T value);
Read(reader, out T value);
if (index >= m_List.Length)
{
throw new Exception("Shouldn't be here, index is higher than list length");

View File

@@ -9,55 +9,8 @@ namespace Unity.Netcode
/// A variable that can be synchronized over the network.
/// </summary>
[Serializable]
public class NetworkVariable<T> : NetworkVariableBase where T : unmanaged
public class NetworkVariable<T> : NetworkVariableSerialization<T> where T : unmanaged
{
// Functions that know how to serialize INetworkSerializable
internal static void WriteNetworkSerializable<TForMethod>(FastBufferWriter writer, in TForMethod value)
where TForMethod : INetworkSerializable, new()
{
writer.WriteNetworkSerializable(value);
}
internal static void ReadNetworkSerializable<TForMethod>(FastBufferReader reader, out TForMethod value)
where TForMethod : INetworkSerializable, new()
{
reader.ReadNetworkSerializable(out value);
}
// Functions that serialize other types
private static void WriteValue<TForMethod>(FastBufferWriter writer, in TForMethod value)
where TForMethod : unmanaged
{
writer.WriteValueSafe(value);
}
private static void ReadValue<TForMethod>(FastBufferReader reader, out TForMethod value)
where TForMethod : unmanaged
{
reader.ReadValueSafe(out value);
}
internal delegate void WriteDelegate<TForMethod>(FastBufferWriter writer, in TForMethod value);
internal delegate void ReadDelegate<TForMethod>(FastBufferReader reader, out TForMethod value);
// These static delegates provide the right implementation for writing and reading a particular network variable type.
// For most types, these default to WriteValue() and ReadValue(), which perform simple memcpy operations.
//
// INetworkSerializableILPP will generate startup code that will set it to WriteNetworkSerializable()
// and ReadNetworkSerializable() for INetworkSerializable types, which will call NetworkSerialize().
//
// In the future we may be able to use this to provide packing implementations for floats and integers to optimize bandwidth usage.
//
// The reason this is done is to avoid runtime reflection and boxing in NetworkVariable - without this,
// NetworkVariable would need to do a `var is INetworkSerializable` check, and then cast to INetworkSerializable,
// *both* of which would cause a boxing allocation. Alternatively, NetworkVariable could have been split into
// NetworkVariable and NetworkSerializableVariable or something like that, which would have caused a poor
// user experience and an API that's easier to get wrong than right. This is a bit ugly on the implementation
// side, but it gets the best achievable user experience and performance.
internal static WriteDelegate<T> Write = WriteValue;
internal static ReadDelegate<T> Read = ReadValue;
/// <summary>
/// Delegate type for value changed event
/// </summary>
@@ -143,6 +96,11 @@ 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)
{
// 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;
Read(reader, out m_InternalValue);

View File

@@ -94,6 +94,14 @@ namespace Unity.Netcode
}
}
/// <summary>
/// Returns the ClientId of the owning client
/// </summary>
internal ulong OwnerClientId()
{
return m_NetworkBehaviour.NetworkObject.OwnerClientId;
}
/// <summary>
/// Writes the dirty changes, that is, the changes since the variable was last dirty, to the writer
/// </summary>

View File

@@ -1,3 +1,6 @@
using System;
using UnityEngine;
namespace Unity.Netcode
{
public class NetworkVariableHelper
@@ -13,10 +16,62 @@ namespace Unity.Netcode
// side, but it gets the best achievable user experience and performance.
//
// RuntimeAccessModifiersILPP will make this `public`
internal static void InitializeDelegates<T>() where T : unmanaged, INetworkSerializable
internal static void InitializeDelegatesNetworkSerializable<T>() where T : unmanaged, INetworkSerializable
{
NetworkVariable<T>.Write = NetworkVariable<T>.WriteNetworkSerializable;
NetworkVariable<T>.Read = NetworkVariable<T>.ReadNetworkSerializable;
NetworkVariableSerialization<T>.SetWriteDelegate(NetworkVariableSerialization<T>.WriteNetworkSerializable);
NetworkVariableSerialization<T>.SetReadDelegate(NetworkVariableSerialization<T>.ReadNetworkSerializable);
}
internal static void InitializeDelegatesStruct<T>() where T : unmanaged, INetworkSerializeByMemcpy
{
NetworkVariableSerialization<T>.SetWriteDelegate(NetworkVariableSerialization<T>.WriteStruct);
NetworkVariableSerialization<T>.SetReadDelegate(NetworkVariableSerialization<T>.ReadStruct);
}
internal static void InitializeDelegatesEnum<T>() where T : unmanaged, Enum
{
NetworkVariableSerialization<T>.SetWriteDelegate(NetworkVariableSerialization<T>.WriteEnum);
NetworkVariableSerialization<T>.SetReadDelegate(NetworkVariableSerialization<T>.ReadEnum);
}
internal static void InitializeDelegatesPrimitive<T>() where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T>
{
NetworkVariableSerialization<T>.SetWriteDelegate(NetworkVariableSerialization<T>.WritePrimitive);
NetworkVariableSerialization<T>.SetReadDelegate(NetworkVariableSerialization<T>.ReadPrimitive);
}
internal static void InitializeAllBaseDelegates()
{
// Built-in C# types, serialized through a generic method
InitializeDelegatesPrimitive<bool>();
InitializeDelegatesPrimitive<byte>();
InitializeDelegatesPrimitive<sbyte>();
InitializeDelegatesPrimitive<char>();
InitializeDelegatesPrimitive<decimal>();
InitializeDelegatesPrimitive<float>();
InitializeDelegatesPrimitive<double>();
InitializeDelegatesPrimitive<short>();
InitializeDelegatesPrimitive<ushort>();
InitializeDelegatesPrimitive<int>();
InitializeDelegatesPrimitive<uint>();
InitializeDelegatesPrimitive<long>();
InitializeDelegatesPrimitive<ulong>();
// Built-in Unity types, serialized with specific overloads because they're structs without ISerializeByMemcpy attached
NetworkVariableSerialization<Vector2>.SetWriteDelegate((FastBufferWriter writer, in Vector2 value) => { writer.WriteValueSafe(value); });
NetworkVariableSerialization<Vector3>.SetWriteDelegate((FastBufferWriter writer, in Vector3 value) => { writer.WriteValueSafe(value); });
NetworkVariableSerialization<Vector4>.SetWriteDelegate((FastBufferWriter writer, in Vector4 value) => { writer.WriteValueSafe(value); });
NetworkVariableSerialization<Quaternion>.SetWriteDelegate((FastBufferWriter writer, in Quaternion value) => { writer.WriteValueSafe(value); });
NetworkVariableSerialization<Color>.SetWriteDelegate((FastBufferWriter writer, in Color value) => { writer.WriteValueSafe(value); });
NetworkVariableSerialization<Color32>.SetWriteDelegate((FastBufferWriter writer, in Color32 value) => { writer.WriteValueSafe(value); });
NetworkVariableSerialization<Ray>.SetWriteDelegate((FastBufferWriter writer, in Ray value) => { writer.WriteValueSafe(value); });
NetworkVariableSerialization<Ray2D>.SetWriteDelegate((FastBufferWriter writer, in Ray2D value) => { writer.WriteValueSafe(value); });
NetworkVariableSerialization<Vector2>.SetReadDelegate((FastBufferReader reader, out Vector2 value) => { reader.ReadValueSafe(out value); });
NetworkVariableSerialization<Vector3>.SetReadDelegate((FastBufferReader reader, out Vector3 value) => { reader.ReadValueSafe(out value); });
NetworkVariableSerialization<Vector4>.SetReadDelegate((FastBufferReader reader, out Vector4 value) => { reader.ReadValueSafe(out value); });
NetworkVariableSerialization<Quaternion>.SetReadDelegate((FastBufferReader reader, out Quaternion value) => { reader.ReadValueSafe(out value); });
NetworkVariableSerialization<Color>.SetReadDelegate((FastBufferReader reader, out Color value) => { reader.ReadValueSafe(out value); });
NetworkVariableSerialization<Color32>.SetReadDelegate((FastBufferReader reader, out Color32 value) => { reader.ReadValueSafe(out value); });
NetworkVariableSerialization<Ray>.SetReadDelegate((FastBufferReader reader, out Ray value) => { reader.ReadValueSafe(out value); });
NetworkVariableSerialization<Ray2D>.SetReadDelegate((FastBufferReader reader, out Ray2D value) => { reader.ReadValueSafe(out value); });
}
}
}

View File

@@ -0,0 +1,169 @@
using System;
namespace Unity.Netcode
{
/// <summary>
/// Support methods for reading/writing NetworkVariables
/// Because there are multiple overloads of WriteValue/ReadValue based on different generic constraints,
/// but there's no way to achieve the same thing with a class, this includes various read/write delegates
/// based on which constraints are met by `T`. These constraints are set up by `NetworkVariableHelpers`,
/// which is invoked by code generated by ILPP during module load.
/// (As it turns out, IL has support for a module initializer that C# doesn't expose.)
/// This installs the correct delegate for each `T` to ensure that each type is serialized properly.
///
/// Any type that inherits from `NetworkVariableSerialization<T>` will implicitly result in any `T`
/// passed to it being picked up and initialized by ILPP.
///
/// The methods here, despite being static, are `protected` specifically to ensure that anything that
/// wants access to them has to inherit from this base class, thus enabling ILPP to find and initialize it.
/// </summary>
[Serializable]
public abstract class NetworkVariableSerialization<T> : NetworkVariableBase where T : unmanaged
{
// Functions that know how to serialize INetworkSerializable
internal static void WriteNetworkSerializable<TForMethod>(FastBufferWriter writer, in TForMethod value)
where TForMethod : unmanaged, INetworkSerializable
{
writer.WriteNetworkSerializable(value);
}
internal static void ReadNetworkSerializable<TForMethod>(FastBufferReader reader, out TForMethod value)
where TForMethod : unmanaged, INetworkSerializable
{
reader.ReadNetworkSerializable(out value);
}
// Functions that serialize structs
internal static void WriteStruct<TForMethod>(FastBufferWriter writer, in TForMethod value)
where TForMethod : unmanaged, INetworkSerializeByMemcpy
{
writer.WriteValueSafe(value);
}
internal static void ReadStruct<TForMethod>(FastBufferReader reader, out TForMethod value)
where TForMethod : unmanaged, INetworkSerializeByMemcpy
{
reader.ReadValueSafe(out value);
}
// Functions that serialize enums
internal static void WriteEnum<TForMethod>(FastBufferWriter writer, in TForMethod value)
where TForMethod : unmanaged, Enum
{
writer.WriteValueSafe(value);
}
internal static void ReadEnum<TForMethod>(FastBufferReader reader, out TForMethod value)
where TForMethod : unmanaged, Enum
{
reader.ReadValueSafe(out value);
}
// Functions that serialize other types
internal static void WritePrimitive<TForMethod>(FastBufferWriter writer, in TForMethod value)
where TForMethod : unmanaged, IComparable, IConvertible, IComparable<TForMethod>, IEquatable<TForMethod>
{
writer.WriteValueSafe(value);
}
internal static void ReadPrimitive<TForMethod>(FastBufferReader reader, out TForMethod value)
where TForMethod : unmanaged, IComparable, IConvertible, IComparable<TForMethod>, IEquatable<TForMethod>
{
reader.ReadValueSafe(out value);
}
// Should never be reachable at runtime. All calls to this should be replaced with the correct
// call above by ILPP.
private static void WriteValue<TForMethod>(FastBufferWriter writer, in TForMethod value)
where TForMethod : unmanaged
{
if (value is INetworkSerializable)
{
typeof(NetworkVariableHelper).GetMethod(nameof(NetworkVariableHelper.InitializeDelegatesNetworkSerializable)).MakeGenericMethod(typeof(TForMethod)).Invoke(null, null);
}
else if (value is INetworkSerializeByMemcpy)
{
typeof(NetworkVariableHelper).GetMethod(nameof(NetworkVariableHelper.InitializeDelegatesStruct)).MakeGenericMethod(typeof(TForMethod)).Invoke(null, null);
}
else if (value is Enum)
{
typeof(NetworkVariableHelper).GetMethod(nameof(NetworkVariableHelper.InitializeDelegatesEnum)).MakeGenericMethod(typeof(TForMethod)).Invoke(null, null);
}
else
{
throw new Exception($"Type {typeof(T).FullName} is not serializable - it must implement either INetworkSerializable or ISerializeByMemcpy");
}
NetworkVariableSerialization<TForMethod>.Write(writer, value);
}
private static void ReadValue<TForMethod>(FastBufferReader reader, out TForMethod value)
where TForMethod : unmanaged
{
if (typeof(INetworkSerializable).IsAssignableFrom(typeof(TForMethod)))
{
typeof(NetworkVariableHelper).GetMethod(nameof(NetworkVariableHelper.InitializeDelegatesNetworkSerializable)).MakeGenericMethod(typeof(TForMethod)).Invoke(null, null);
}
else if (typeof(INetworkSerializeByMemcpy).IsAssignableFrom(typeof(TForMethod)))
{
typeof(NetworkVariableHelper).GetMethod(nameof(NetworkVariableHelper.InitializeDelegatesStruct)).MakeGenericMethod(typeof(TForMethod)).Invoke(null, null);
}
else if (typeof(Enum).IsAssignableFrom(typeof(TForMethod)))
{
typeof(NetworkVariableHelper).GetMethod(nameof(NetworkVariableHelper.InitializeDelegatesEnum)).MakeGenericMethod(typeof(TForMethod)).Invoke(null, null);
}
else
{
throw new Exception($"Type {typeof(T).FullName} is not serializable - it must implement either INetworkSerializable or ISerializeByMemcpy");
}
NetworkVariableSerialization<TForMethod>.Read(reader, out value);
}
protected internal delegate void WriteDelegate<TForMethod>(FastBufferWriter writer, in TForMethod value);
protected internal delegate void ReadDelegate<TForMethod>(FastBufferReader reader, out TForMethod value);
// These static delegates provide the right implementation for writing and reading a particular network variable type.
// For most types, these default to WriteValue() and ReadValue(), which perform simple memcpy operations.
//
// INetworkSerializableILPP will generate startup code that will set it to WriteNetworkSerializable()
// and ReadNetworkSerializable() for INetworkSerializable types, which will call NetworkSerialize().
//
// In the future we may be able to use this to provide packing implementations for floats and integers to optimize bandwidth usage.
//
// The reason this is done is to avoid runtime reflection and boxing in NetworkVariable - without this,
// NetworkVariable would need to do a `var is INetworkSerializable` check, and then cast to INetworkSerializable,
// *both* of which would cause a boxing allocation. Alternatively, NetworkVariable could have been split into
// NetworkVariable and NetworkSerializableVariable or something like that, which would have caused a poor
// user experience and an API that's easier to get wrong than right. This is a bit ugly on the implementation
// side, but it gets the best achievable user experience and performance.
private static WriteDelegate<T> s_Write = WriteValue;
private static ReadDelegate<T> s_Read = ReadValue;
protected static void Write(FastBufferWriter writer, in T value)
{
s_Write(writer, value);
}
protected static void Read(FastBufferReader reader, out T value)
{
s_Read(reader, out value);
}
internal static void SetWriteDelegate(WriteDelegate<T> write)
{
s_Write = write;
}
internal static void SetReadDelegate(ReadDelegate<T> read)
{
s_Read = read;
}
protected NetworkVariableSerialization(
NetworkVariableReadPermission readPerm = DefaultReadPerm,
NetworkVariableWritePermission writePerm = DefaultWritePerm)
: base(readPerm, writePerm)
{
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2c6ef5fdf2e94ec3b4ce8086d52700b3
timeCreated: 1650985453

View File

@@ -82,7 +82,7 @@ namespace Unity.Netcode
return true;
}
public bool OnVerifyCanReceive(ulong senderId, Type messageType)
public bool OnVerifyCanReceive(ulong senderId, Type messageType, FastBufferReader messageContent, ref NetworkContext context)
{
return true;
}

View File

@@ -1446,12 +1446,9 @@ namespace Unity.Netcode
var loadSceneMode = sceneHash == sceneEventData.SceneHash ? sceneEventData.LoadSceneMode : LoadSceneMode.Additive;
// Always check to see if the scene needs to be validated
if (!ValidateSceneBeforeLoading(sceneHash, loadSceneMode))
{
EndSceneEvent(sceneEventId);
return;
}
// Store the sceneHandle and hash
sceneEventData.ClientSceneHandle = sceneHandle;
sceneEventData.ClientSceneHash = sceneHash;
// If this is the beginning of the synchronization event, then send client a notification that synchronization has begun
if (sceneHash == sceneEventData.SceneHash)
@@ -1468,9 +1465,16 @@ namespace Unity.Netcode
ScenePlacedObjects.Clear();
}
// Store the sceneHandle and hash
sceneEventData.ClientSceneHandle = sceneHandle;
sceneEventData.ClientSceneHash = sceneHash;
// Always check to see if the scene needs to be validated
if (!ValidateSceneBeforeLoading(sceneHash, loadSceneMode))
{
HandleClientSceneEvent(sceneEventId);
if (m_NetworkManager.LogLevel == LogLevel.Developer)
{
NetworkLog.LogInfo($"Client declined to load the scene {sceneName}, continuing with synchronization.");
}
return;
}
var shouldPassThrough = false;
var sceneLoad = (AsyncOperation)null;
@@ -1746,7 +1750,9 @@ namespace Unity.Netcode
// NetworkObjects
m_NetworkManager.InvokeOnClientConnectedCallback(clientId);
if (sceneEventData.ClientNeedsReSynchronization() && !DisableReSynchronization)
// Check to see if the client needs to resynchronize and before sending the message make sure the client is still connected to avoid
// a potential crash within the MessageSystem (i.e. sending to a client that no longer exists)
if (sceneEventData.ClientNeedsReSynchronization() && !DisableReSynchronization && m_NetworkManager.ConnectedClients.ContainsKey(clientId))
{
sceneEventData.SceneEventType = SceneEventType.ReSynchronize;
SendSceneEventData(sceneEventId, new ulong[] { clientId });

View File

@@ -91,7 +91,7 @@ namespace Unity.Netcode
{
internal SceneEventType SceneEventType;
internal LoadSceneMode LoadSceneMode;
internal Guid SceneEventProgressId;
internal ForceNetworkSerializeByMemcpy<Guid> SceneEventProgressId;
internal uint SceneEventId;

View File

@@ -1,3 +1,6 @@
using System;
using UnityEngine;
namespace Unity.Netcode
{
/// <summary>
@@ -7,7 +10,7 @@ namespace Unity.Netcode
/// 1. The BufferSerializer cannot outlive the FBR/FBW it wraps or using it will cause a crash
/// 2. The BufferSerializer must always be passed by reference and can't be copied
///
/// Ref structs help enforce both of those rules: they can't out live the stack context in which they were
/// Ref structs help enforce both of those rules: they can't ref live the stack context in which they were
/// created, and they're always passed by reference no matter what.
///
/// BufferSerializer doesn't wrapp FastBufferReader or FastBufferWriter directly because it can't.
@@ -58,168 +61,63 @@ namespace Unity.Netcode
return m_Implementation.GetFastBufferWriter();
}
/// <summary>
/// Serialize an INetworkSerializable
///
/// Throws OverflowException if the end of the buffer has been reached.
/// Write buffers will grow up to the maximum allowable message size before throwing OverflowException.
/// </summary>
/// <param name="value">Value to serialize</param>
public void SerializeNetworkSerializable<T>(ref T value) where T : INetworkSerializable, new()
{
m_Implementation.SerializeNetworkSerializable(ref value);
}
public void SerializeValue(ref string s, bool oneByteChars = false) => m_Implementation.SerializeValue(ref s, oneByteChars);
public void SerializeValue(ref byte value) => m_Implementation.SerializeValue(ref value);
public void SerializeValue<T>(ref T value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => m_Implementation.SerializeValue(ref value);
public void SerializeValue<T>(ref T[] value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => m_Implementation.SerializeValue(ref value);
public void SerializeValue<T>(ref T value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum => m_Implementation.SerializeValue(ref value);
public void SerializeValue<T>(ref T[] value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum => m_Implementation.SerializeValue(ref value);
public void SerializeValue<T>(ref T value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => m_Implementation.SerializeValue(ref value);
public void SerializeValue<T>(ref T[] value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => m_Implementation.SerializeValue(ref value);
public void SerializeValue<T>(ref T value, FastBufferWriter.ForNetworkSerializable unused = default) where T : INetworkSerializable, new() => m_Implementation.SerializeValue(ref value);
public void SerializeValue<T>(ref T[] value, FastBufferWriter.ForNetworkSerializable unused = default) where T : INetworkSerializable, new() => m_Implementation.SerializeValue(ref value);
public void SerializeValue(ref Vector2 value) => m_Implementation.SerializeValue(ref value);
public void SerializeValue(ref Vector2[] value) => m_Implementation.SerializeValue(ref value);
public void SerializeValue(ref Vector3 value) => m_Implementation.SerializeValue(ref value);
public void SerializeValue(ref Vector3[] value) => m_Implementation.SerializeValue(ref value);
public void SerializeValue(ref Vector4 value) => m_Implementation.SerializeValue(ref value);
public void SerializeValue(ref Vector4[] value) => m_Implementation.SerializeValue(ref value);
public void SerializeValue(ref Quaternion value) => m_Implementation.SerializeValue(ref value);
public void SerializeValue(ref Quaternion[] value) => m_Implementation.SerializeValue(ref value);
public void SerializeValue(ref Color value) => m_Implementation.SerializeValue(ref value);
public void SerializeValue(ref Color[] value) => m_Implementation.SerializeValue(ref value);
public void SerializeValue(ref Color32 value) => m_Implementation.SerializeValue(ref value);
public void SerializeValue(ref Color32[] value) => m_Implementation.SerializeValue(ref value);
public void SerializeValue(ref Ray value) => m_Implementation.SerializeValue(ref value);
public void SerializeValue(ref Ray[] value) => m_Implementation.SerializeValue(ref value);
public void SerializeValue(ref Ray2D value) => m_Implementation.SerializeValue(ref value);
public void SerializeValue(ref Ray2D[] value) => m_Implementation.SerializeValue(ref value);
/// <summary>
/// Serialize a string.
///
/// Note: Will ALWAYS allocate a new string when reading.
///
/// Throws OverflowException if the end of the buffer has been reached.
/// Write buffers will grow up to the maximum allowable message size before throwing OverflowException.
/// </summary>
/// <param name="s">Value to serialize</param>
/// <param name="oneByteChars">
/// If true, will truncate each char to one byte.
/// This is slower than two-byte chars, but uses less bandwidth.
/// </param>
public void SerializeValue(ref string s, bool oneByteChars = false)
{
m_Implementation.SerializeValue(ref s, oneByteChars);
}
public void SerializeNetworkSerializable<T>(ref T value) where T : INetworkSerializable, new() => m_Implementation.SerializeNetworkSerializable(ref value);
/// <summary>
/// Serialize an array value.
///
/// Note: Will ALWAYS allocate a new array when reading.
/// If you have a statically-sized array that you know is large enough, it's recommended to
/// serialize the size yourself and iterate serializing array members.
///
/// (This is because C# doesn't allow setting an array's length value, so deserializing
/// into an existing array of larger size would result in an array that doesn't have as many values
/// as its Length indicates it should.)
///
/// Throws OverflowException if the end of the buffer has been reached.
/// Write buffers will grow up to the maximum allowable message size before throwing OverflowException.
/// </summary>
/// <param name="array">Value to serialize</param>
public void SerializeValue<T>(ref T[] array) where T : unmanaged
{
m_Implementation.SerializeValue(ref array);
}
/// <summary>
/// Serialize a single byte
///
/// Throws OverflowException if the end of the buffer has been reached.
/// Write buffers will grow up to the maximum allowable message size before throwing OverflowException.
/// </summary>
/// <param name="value">Value to serialize</param>
public void SerializeValue(ref byte value)
{
m_Implementation.SerializeValue(ref value);
}
/// <summary>
/// Serialize an unmanaged type. Supports basic value types as well as structs.
/// The provided type will be copied to/from the buffer as it exists in memory.
///
/// Throws OverflowException if the end of the buffer has been reached.
/// Write buffers will grow up to the maximum allowable message size before throwing OverflowException.
/// </summary>
/// <param name="value">Value to serialize</param>
public void SerializeValue<T>(ref T value) where T : unmanaged
{
m_Implementation.SerializeValue(ref value);
}
/// <summary>
/// Allows faster serialization by batching bounds checking.
/// When you know you will be writing multiple fields back-to-back and you know the total size,
/// you can call PreCheck() once on the total size, and then follow it with calls to
/// SerializeValuePreChecked() for faster serialization. Write buffers will grow during PreCheck()
/// if needed.
///
/// PreChecked serialization operations will throw OverflowException in editor and development builds if you
/// go past the point you've marked using PreCheck(). In release builds, OverflowException will not be thrown
/// for performance reasons, since the point of using PreCheck is to avoid bounds checking in the following
/// operations in release builds.
///
/// To get the correct size to check for, use FastBufferWriter.GetWriteSize(value) or
/// FastBufferWriter.GetWriteSize&lt;type&gt;()
/// </summary>
/// <param name="amount">Number of bytes you plan to read or write</param>
/// <returns>True if the read/write can proceed, false otherwise.</returns>
public bool PreCheck(int amount)
{
return m_Implementation.PreCheck(amount);
}
/// <summary>
/// Serialize a string.
///
/// Note: Will ALWAYS allocate a new string when reading.
///
/// Using the PreChecked versions of these functions requires calling PreCheck() ahead of time, and they should only
/// be called if PreCheck() returns true. This is an efficiency option, as it allows you to PreCheck() multiple
/// serialization operations in one function call instead of having to do bounds checking on every call.
/// </summary>
/// <param name="s">Value to serialize</param>
/// <param name="oneByteChars">
/// If true, will truncate each char to one byte.
/// This is slower than two-byte chars, but uses less bandwidth.
/// </param>
public void SerializeValuePreChecked(ref string s, bool oneByteChars = false)
{
m_Implementation.SerializeValuePreChecked(ref s, oneByteChars);
}
/// <summary>
/// Serialize an array value.
///
/// Note: Will ALWAYS allocate a new array when reading.
/// If you have a statically-sized array that you know is large enough, it's recommended to
/// serialize the size yourself and iterate serializing array members.
///
/// (This is because C# doesn't allow setting an array's length value, so deserializing
/// into an existing array of larger size would result in an array that doesn't have as many values
/// as its Length indicates it should.)
///
/// Using the PreChecked versions of these functions requires calling PreCheck() ahead of time, and they should only
/// be called if PreCheck() returns true. This is an efficiency option, as it allows you to PreCheck() multiple
/// serialization operations in one function call instead of having to do bounds checking on every call.
/// </summary>
/// <param name="array">Value to serialize</param>
public void SerializeValuePreChecked<T>(ref T[] array) where T : unmanaged
{
m_Implementation.SerializeValuePreChecked(ref array);
}
/// <summary>
/// Serialize a single byte
///
/// Using the PreChecked versions of these functions requires calling PreCheck() ahead of time, and they should only
/// be called if PreCheck() returns true. This is an efficiency option, as it allows you to PreCheck() multiple
/// serialization operations in one function call instead of having to do bounds checking on every call.
/// </summary>
/// <param name="value">Value to serialize</param>
public void SerializeValuePreChecked(ref byte value)
{
m_Implementation.SerializeValuePreChecked(ref value);
}
/// <summary>
/// Serialize an unmanaged type. Supports basic value types as well as structs.
/// The provided type will be copied to/from the buffer as it exists in memory.
///
/// Using the PreChecked versions of these functions requires calling PreCheck() ahead of time, and they should only
/// be called if PreCheck() returns true. This is an efficiency option, as it allows you to PreCheck() multiple
/// serialization operations in one function call instead of having to do bounds checking on every call.
/// </summary>
/// <param name="value">Value to serialize</param>
public void SerializeValuePreChecked<T>(ref T value) where T : unmanaged
{
m_Implementation.SerializeValuePreChecked(ref value);
}
public void SerializeValuePreChecked(ref string s, bool oneByteChars = false) => m_Implementation.SerializeValuePreChecked(ref s, oneByteChars);
public void SerializeValuePreChecked(ref byte value) => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked<T>(ref T value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked<T>(ref T[] value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked<T>(ref T value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked<T>(ref T[] value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked<T>(ref T value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked<T>(ref T[] value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked(ref Vector2 value) => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked(ref Vector2[] value) => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked(ref Vector3 value) => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked(ref Vector3[] value) => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked(ref Vector4 value) => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked(ref Vector4[] value) => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked(ref Quaternion value) => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked(ref Quaternion[] value) => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked(ref Color value) => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked(ref Color[] value) => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked(ref Color32 value) => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked(ref Color32[] value) => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked(ref Ray value) => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked(ref Ray[] value) => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked(ref Ray2D value) => m_Implementation.SerializeValuePreChecked(ref value);
public void SerializeValuePreChecked(ref Ray2D[] value) => m_Implementation.SerializeValuePreChecked(ref value);
}
}

View File

@@ -1,4 +1,5 @@
using System;
using UnityEngine;
namespace Unity.Netcode
{
@@ -24,54 +25,63 @@ namespace Unity.Netcode
throw new InvalidOperationException("Cannot retrieve a FastBufferWriter from a serializer where IsWriter = false");
}
public void SerializeValue(ref string s, bool oneByteChars = false)
{
m_Reader.ReadValueSafe(out s, oneByteChars);
}
public void SerializeValue(ref string s, bool oneByteChars = false) => m_Reader.ReadValueSafe(out s, oneByteChars);
public void SerializeValue(ref byte value) => m_Reader.ReadByteSafe(out value);
public void SerializeValue<T>(ref T value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => m_Reader.ReadValueSafe(out value);
public void SerializeValue<T>(ref T[] value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => m_Reader.ReadValueSafe(out value);
public void SerializeValue<T>(ref T value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum => m_Reader.ReadValueSafe(out value);
public void SerializeValue<T>(ref T[] value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum => m_Reader.ReadValueSafe(out value);
public void SerializeValue<T>(ref T value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => m_Reader.ReadValueSafe(out value);
public void SerializeValue<T>(ref T[] value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => m_Reader.ReadValueSafe(out value);
public void SerializeValue<T>(ref T value, FastBufferWriter.ForNetworkSerializable unused = default) where T : INetworkSerializable, new() => m_Reader.ReadValue(out value);
public void SerializeValue<T>(ref T[] value, FastBufferWriter.ForNetworkSerializable unused = default) where T : INetworkSerializable, new() => m_Reader.ReadValue(out value);
public void SerializeValue(ref Vector2 value) => m_Reader.ReadValueSafe(out value);
public void SerializeValue(ref Vector2[] value) => m_Reader.ReadValueSafe(out value);
public void SerializeValue(ref Vector3 value) => m_Reader.ReadValueSafe(out value);
public void SerializeValue(ref Vector3[] value) => m_Reader.ReadValueSafe(out value);
public void SerializeValue(ref Vector4 value) => m_Reader.ReadValueSafe(out value);
public void SerializeValue(ref Vector4[] value) => m_Reader.ReadValueSafe(out value);
public void SerializeValue(ref Quaternion value) => m_Reader.ReadValueSafe(out value);
public void SerializeValue(ref Quaternion[] value) => m_Reader.ReadValueSafe(out value);
public void SerializeValue(ref Color value) => m_Reader.ReadValueSafe(out value);
public void SerializeValue(ref Color[] value) => m_Reader.ReadValueSafe(out value);
public void SerializeValue(ref Color32 value) => m_Reader.ReadValueSafe(out value);
public void SerializeValue(ref Color32[] value) => m_Reader.ReadValueSafe(out value);
public void SerializeValue(ref Ray value) => m_Reader.ReadValueSafe(out value);
public void SerializeValue(ref Ray[] value) => m_Reader.ReadValueSafe(out value);
public void SerializeValue(ref Ray2D value) => m_Reader.ReadValueSafe(out value);
public void SerializeValue(ref Ray2D[] value) => m_Reader.ReadValueSafe(out value);
public void SerializeValue<T>(ref T[] array) where T : unmanaged
{
m_Reader.ReadValueSafe(out array);
}
public void SerializeValue(ref byte value)
{
m_Reader.ReadByteSafe(out value);
}
public void SerializeValue<T>(ref T value) where T : unmanaged
{
m_Reader.ReadValueSafe(out value);
}
public void SerializeNetworkSerializable<T>(ref T value) where T : INetworkSerializable, new()
{
m_Reader.ReadNetworkSerializable(out value);
}
public void SerializeNetworkSerializable<T>(ref T value) where T : INetworkSerializable, new() => m_Reader.ReadNetworkSerializable(out value);
public bool PreCheck(int amount)
{
return m_Reader.TryBeginRead(amount);
}
public void SerializeValuePreChecked(ref string s, bool oneByteChars = false)
{
m_Reader.ReadValue(out s, oneByteChars);
}
public void SerializeValuePreChecked<T>(ref T[] array) where T : unmanaged
{
m_Reader.ReadValue(out array);
}
public void SerializeValuePreChecked(ref byte value)
{
m_Reader.ReadValue(out value);
}
public void SerializeValuePreChecked<T>(ref T value) where T : unmanaged
{
m_Reader.ReadValue(out value);
}
public void SerializeValuePreChecked(ref string s, bool oneByteChars = false) => m_Reader.ReadValue(out s, oneByteChars);
public void SerializeValuePreChecked(ref byte value) => m_Reader.ReadByte(out value);
public void SerializeValuePreChecked<T>(ref T value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked<T>(ref T[] value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked<T>(ref T value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked<T>(ref T[] value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked<T>(ref T value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked<T>(ref T[] value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked(ref Vector2 value) => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked(ref Vector2[] value) => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked(ref Vector3 value) => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked(ref Vector3[] value) => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked(ref Vector4 value) => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked(ref Vector4[] value) => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked(ref Quaternion value) => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked(ref Quaternion[] value) => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked(ref Color value) => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked(ref Color[] value) => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked(ref Color32 value) => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked(ref Color32[] value) => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked(ref Ray value) => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked(ref Ray[] value) => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked(ref Ray2D value) => m_Reader.ReadValue(out value);
public void SerializeValuePreChecked(ref Ray2D[] value) => m_Reader.ReadValue(out value);
}
}

View File

@@ -1,4 +1,5 @@
using System;
using UnityEngine;
namespace Unity.Netcode
{
@@ -24,25 +25,32 @@ namespace Unity.Netcode
return m_Writer;
}
public void SerializeValue(ref string s, bool oneByteChars = false)
{
m_Writer.WriteValueSafe(s, oneByteChars);
}
public void SerializeValue<T>(ref T[] array) where T : unmanaged
{
m_Writer.WriteValueSafe(array);
}
public void SerializeValue(ref byte value)
{
m_Writer.WriteByteSafe(value);
}
public void SerializeValue<T>(ref T value) where T : unmanaged
{
m_Writer.WriteValueSafe(value);
}
public void SerializeValue(ref string s, bool oneByteChars = false) => m_Writer.WriteValueSafe(s, oneByteChars);
public void SerializeValue(ref byte value) => m_Writer.WriteByteSafe(value);
public void SerializeValue<T>(ref T value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => m_Writer.WriteValueSafe(value);
public void SerializeValue<T>(ref T[] value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => m_Writer.WriteValueSafe(value);
public void SerializeValue<T>(ref T value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum => m_Writer.WriteValueSafe(value);
public void SerializeValue<T>(ref T[] value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum => m_Writer.WriteValueSafe(value);
public void SerializeValue<T>(ref T value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => m_Writer.WriteValueSafe(value);
public void SerializeValue<T>(ref T[] value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => m_Writer.WriteValueSafe(value);
public void SerializeValue<T>(ref T value, FastBufferWriter.ForNetworkSerializable unused = default) where T : INetworkSerializable, new() => m_Writer.WriteValue(value);
public void SerializeValue<T>(ref T[] value, FastBufferWriter.ForNetworkSerializable unused = default) where T : INetworkSerializable, new() => m_Writer.WriteValue(value);
public void SerializeValue(ref Vector2 value) => m_Writer.WriteValueSafe(value);
public void SerializeValue(ref Vector2[] value) => m_Writer.WriteValueSafe(value);
public void SerializeValue(ref Vector3 value) => m_Writer.WriteValueSafe(value);
public void SerializeValue(ref Vector3[] value) => m_Writer.WriteValueSafe(value);
public void SerializeValue(ref Vector4 value) => m_Writer.WriteValueSafe(value);
public void SerializeValue(ref Vector4[] value) => m_Writer.WriteValueSafe(value);
public void SerializeValue(ref Quaternion value) => m_Writer.WriteValueSafe(value);
public void SerializeValue(ref Quaternion[] value) => m_Writer.WriteValueSafe(value);
public void SerializeValue(ref Color value) => m_Writer.WriteValueSafe(value);
public void SerializeValue(ref Color[] value) => m_Writer.WriteValueSafe(value);
public void SerializeValue(ref Color32 value) => m_Writer.WriteValueSafe(value);
public void SerializeValue(ref Color32[] value) => m_Writer.WriteValueSafe(value);
public void SerializeValue(ref Ray value) => m_Writer.WriteValueSafe(value);
public void SerializeValue(ref Ray[] value) => m_Writer.WriteValueSafe(value);
public void SerializeValue(ref Ray2D value) => m_Writer.WriteValueSafe(value);
public void SerializeValue(ref Ray2D[] value) => m_Writer.WriteValueSafe(value);
public void SerializeNetworkSerializable<T>(ref T value) where T : INetworkSerializable, new()
{
@@ -54,24 +62,30 @@ namespace Unity.Netcode
return m_Writer.TryBeginWrite(amount);
}
public void SerializeValuePreChecked(ref string s, bool oneByteChars = false)
{
m_Writer.WriteValue(s, oneByteChars);
}
public void SerializeValuePreChecked(ref string s, bool oneByteChars = false) => m_Writer.WriteValue(s, oneByteChars);
public void SerializeValuePreChecked(ref byte value) => m_Writer.WriteByte(value);
public void SerializeValuePreChecked<T>(ref T value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => m_Writer.WriteValue(value);
public void SerializeValuePreChecked<T>(ref T[] value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => m_Writer.WriteValue(value);
public void SerializeValuePreChecked<T>(ref T[] array) where T : unmanaged
{
m_Writer.WriteValue(array);
}
public void SerializeValuePreChecked(ref byte value)
{
m_Writer.WriteByte(value);
}
public void SerializeValuePreChecked<T>(ref T value) where T : unmanaged
{
m_Writer.WriteValue(value);
}
public void SerializeValuePreChecked<T>(ref T value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum => m_Writer.WriteValue(value);
public void SerializeValuePreChecked<T>(ref T[] value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum => m_Writer.WriteValue(value);
public void SerializeValuePreChecked<T>(ref T value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => m_Writer.WriteValue(value);
public void SerializeValuePreChecked<T>(ref T[] value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => m_Writer.WriteValue(value);
public void SerializeValuePreChecked(ref Vector2 value) => m_Writer.WriteValue(value);
public void SerializeValuePreChecked(ref Vector2[] value) => m_Writer.WriteValue(value);
public void SerializeValuePreChecked(ref Vector3 value) => m_Writer.WriteValue(value);
public void SerializeValuePreChecked(ref Vector3[] value) => m_Writer.WriteValue(value);
public void SerializeValuePreChecked(ref Vector4 value) => m_Writer.WriteValue(value);
public void SerializeValuePreChecked(ref Vector4[] value) => m_Writer.WriteValue(value);
public void SerializeValuePreChecked(ref Quaternion value) => m_Writer.WriteValue(value);
public void SerializeValuePreChecked(ref Quaternion[] value) => m_Writer.WriteValue(value);
public void SerializeValuePreChecked(ref Color value) => m_Writer.WriteValue(value);
public void SerializeValuePreChecked(ref Color[] value) => m_Writer.WriteValue(value);
public void SerializeValuePreChecked(ref Color32 value) => m_Writer.WriteValue(value);
public void SerializeValuePreChecked(ref Color32[] value) => m_Writer.WriteValue(value);
public void SerializeValuePreChecked(ref Ray value) => m_Writer.WriteValue(value);
public void SerializeValuePreChecked(ref Ray[] value) => m_Writer.WriteValue(value);
public void SerializeValuePreChecked(ref Ray2D value) => m_Writer.WriteValue(value);
public void SerializeValuePreChecked(ref Ray2D[] value) => m_Writer.WriteValue(value);
}
}

View File

@@ -2,6 +2,7 @@ using System;
using System.Runtime.CompilerServices;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;
namespace Unity.Netcode
{
@@ -195,6 +196,30 @@ namespace Unity.Netcode
Handle = CreateHandle(writer.GetUnsafePtr(), length == -1 ? writer.Length : length, offset, allocator);
}
/// <summary>
/// Create a FastBufferReader from another existing FastBufferReader. This is typically used when you
/// want to change the allocator that a reader is allocated to - for example, upgrading a Temp reader to
/// a Persistent one to be processed later.
///
/// A new buffer will be created using the given allocator and the value will be copied in.
/// FastBufferReader will then own the data.
///
/// The exception to this is when the allocator passed in is Allocator.None. In this scenario,
/// ownership of the data remains with the caller and the reader will point at it directly.
/// When created with Allocator.None, FastBufferReader will allocate some internal data using
/// Allocator.Temp, so it should be treated as if it's a ref struct and not allowed to outlive
/// the context in which it was created (it should neither be returned from that function nor
/// stored anywhere in heap memory).
/// </summary>
/// <param name="reader">The reader to copy from</param>
/// <param name="allocator">The allocator to use</param>
/// <param name="length">The number of bytes to copy (all if this is -1)</param>
/// <param name="offset">The offset of the buffer to start copying from</param>
public unsafe FastBufferReader(FastBufferReader reader, Allocator allocator, int length = -1, int offset = 0)
{
Handle = CreateHandle(reader.GetUnsafePtr(), length == -1 ? reader.Length : length, offset, allocator);
}
/// <summary>
/// Frees the allocated buffer
/// </summary>
@@ -492,61 +517,6 @@ namespace Unity.Netcode
}
}
/// <summary>
/// Writes an unmanaged array
/// NOTE: ALLOCATES
/// </summary>
/// <param name="array">Stores the read array</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void ReadValue<T>(out T[] array) where T : unmanaged
{
ReadValue(out int sizeInTs);
int sizeInBytes = sizeInTs * sizeof(T);
array = new T[sizeInTs];
fixed (T* native = array)
{
byte* bytes = (byte*)(native);
ReadBytes(bytes, sizeInBytes);
}
}
/// <summary>
/// Reads an unmanaged array
/// NOTE: ALLOCATES
///
/// "Safe" version - automatically performs bounds checking. Less efficient than bounds checking
/// for multiple reads at once by calling TryBeginRead.
/// </summary>
/// <param name="array">Stores the read array</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void ReadValueSafe<T>(out T[] array) where T : unmanaged
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (Handle->InBitwiseContext)
{
throw new InvalidOperationException(
"Cannot use BufferReader in bytewise mode while in a bitwise context.");
}
#endif
if (!TryBeginReadInternal(sizeof(int)))
{
throw new OverflowException("Reading past the end of the buffer");
}
ReadValue(out int sizeInTs);
int sizeInBytes = sizeInTs * sizeof(T);
if (!TryBeginReadInternal(sizeInBytes))
{
throw new OverflowException("Reading past the end of the buffer");
}
array = new T[sizeInTs];
fixed (T* native = array)
{
byte* bytes = (byte*)(native);
ReadBytes(bytes, sizeInBytes);
}
}
/// <summary>
/// Read a partial value. The value is zero-initialized and then the specified number of bytes is read into it.
/// </summary>
@@ -711,69 +681,155 @@ namespace Unity.Netcode
}
}
/// <summary>
/// Read a value of any unmanaged type to the buffer.
/// It will be copied from the buffer exactly as it existed in memory on the writing end.
/// </summary>
/// <param name="value">The read value</param>
/// <typeparam name="T">Any unmanaged type</typeparam>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void ReadValue<T>(out T value) where T : unmanaged
private unsafe void ReadUnmanaged<T>(out T value) where T : unmanaged
{
int len = sizeof(T);
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (Handle->InBitwiseContext)
{
throw new InvalidOperationException(
"Cannot use BufferReader in bytewise mode while in a bitwise context.");
}
if (Handle->Position + len > Handle->AllowedReadMark)
{
throw new OverflowException($"Attempted to read without first calling {nameof(TryBeginRead)}()");
}
#endif
fixed (T* ptr = &value)
{
UnsafeUtility.MemCpy((byte*)ptr, Handle->BufferPointer + Handle->Position, len);
byte* bytes = (byte*)ptr;
ReadBytes(bytes, sizeof(T));
}
Handle->Position += len;
}
/// <summary>
/// Read a value of any unmanaged type to the buffer.
/// It will be copied from the buffer exactly as it existed in memory on the writing end.
///
/// "Safe" version - automatically performs bounds checking. Less efficient than bounds checking
/// for multiple reads at once by calling TryBeginRead.
/// </summary>
/// <param name="value">The read value</param>
/// <typeparam name="T">Any unmanaged type</typeparam>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void ReadValueSafe<T>(out T value) where T : unmanaged
private unsafe void ReadUnmanagedSafe<T>(out T value) where T : unmanaged
{
int len = sizeof(T);
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (Handle->InBitwiseContext)
{
throw new InvalidOperationException(
"Cannot use BufferReader in bytewise mode while in a bitwise context.");
}
#endif
if (!TryBeginReadInternal(len))
{
throw new OverflowException("Reading past the end of the buffer");
}
fixed (T* ptr = &value)
{
UnsafeUtility.MemCpy((byte*)ptr, Handle->BufferPointer + Handle->Position, len);
byte* bytes = (byte*)ptr;
ReadBytesSafe(bytes, sizeof(T));
}
Handle->Position += len;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private unsafe void ReadUnmanaged<T>(out T[] value) where T : unmanaged
{
ReadUnmanaged(out int sizeInTs);
int sizeInBytes = sizeInTs * sizeof(T);
value = new T[sizeInTs];
fixed (T* ptr = value)
{
byte* bytes = (byte*)ptr;
ReadBytes(bytes, sizeInBytes);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private unsafe void ReadUnmanagedSafe<T>(out T[] value) where T : unmanaged
{
ReadUnmanagedSafe(out int sizeInTs);
int sizeInBytes = sizeInTs * sizeof(T);
value = new T[sizeInTs];
fixed (T* ptr = value)
{
byte* bytes = (byte*)ptr;
ReadBytesSafe(bytes, sizeInBytes);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue<T>(out T value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue<T>(out T[] value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe<T>(out T value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe<T>(out T[] value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue<T>(out T value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue<T>(out T[] value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe<T>(out T value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe<T>(out T[] value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue<T>(out T value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue<T>(out T[] value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe<T>(out T value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe<T>(out T[] value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue<T>(out T value, FastBufferWriter.ForNetworkSerializable unused = default) where T : INetworkSerializable, new() => ReadNetworkSerializable(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue<T>(out T[] value, FastBufferWriter.ForNetworkSerializable unused = default) where T : INetworkSerializable, new() => ReadNetworkSerializable(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe<T>(out T value, FastBufferWriter.ForNetworkSerializable unused = default) where T : INetworkSerializable, new() => ReadNetworkSerializable(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe<T>(out T[] value, FastBufferWriter.ForNetworkSerializable unused = default) where T : INetworkSerializable, new() => ReadNetworkSerializable(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue(out Vector2 value) => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue(out Vector2[] value) => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue(out Vector3 value) => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue(out Vector3[] value) => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue(out Vector4 value) => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue(out Vector4[] value) => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue(out Quaternion value) => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue(out Quaternion[] value) => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue(out Color value) => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue(out Color[] value) => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue(out Color32 value) => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue(out Color32[] value) => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue(out Ray value) => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue(out Ray[] value) => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue(out Ray2D value) => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValue(out Ray2D[] value) => ReadUnmanaged(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe(out Vector2 value) => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe(out Vector2[] value) => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe(out Vector3 value) => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe(out Vector3[] value) => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe(out Vector4 value) => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe(out Vector4[] value) => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe(out Quaternion value) => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe(out Quaternion[] value) => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe(out Color value) => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe(out Color[] value) => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe(out Color32 value) => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe(out Color32[] value) => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe(out Ray value) => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe(out Ray[] value) => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe(out Ray2D value) => ReadUnmanagedSafe(out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadValueSafe(out Ray2D[] value) => ReadUnmanagedSafe(out value);
}
}

View File

@@ -2,6 +2,7 @@ using System;
using System.Runtime.CompilerServices;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;
namespace Unity.Netcode
{
@@ -528,60 +529,6 @@ namespace Unity.Netcode
return sizeof(int) + sizeInBytes;
}
/// <summary>
/// Writes an unmanaged array
/// </summary>
/// <param name="array">The array to write</param>
/// <param name="count">The amount of elements to write</param>
/// <param name="offset">Where in the array to start</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void WriteValue<T>(T[] array, int count = -1, int offset = 0) where T : unmanaged
{
int sizeInTs = count != -1 ? count : array.Length - offset;
int sizeInBytes = sizeInTs * sizeof(T);
WriteValue(sizeInTs);
fixed (T* native = array)
{
byte* bytes = (byte*)(native + offset);
WriteBytes(bytes, sizeInBytes);
}
}
/// <summary>
/// Writes an unmanaged array
///
/// "Safe" version - automatically performs bounds checking. Less efficient than bounds checking
/// for multiple writes at once by calling TryBeginWrite.
/// </summary>
/// <param name="array">The array to write</param>
/// <param name="count">The amount of elements to write</param>
/// <param name="offset">Where in the array to start</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void WriteValueSafe<T>(T[] array, int count = -1, int offset = 0) where T : unmanaged
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (Handle->InBitwiseContext)
{
throw new InvalidOperationException(
"Cannot use BufferWriter in bytewise mode while in a bitwise context.");
}
#endif
int sizeInTs = count != -1 ? count : array.Length - offset;
int sizeInBytes = sizeInTs * sizeof(T);
if (!TryBeginWriteInternal(sizeInBytes + sizeof(int)))
{
throw new OverflowException("Writing past the end of the buffer");
}
WriteValue(sizeInTs);
fixed (T* native = array)
{
byte* bytes = (byte*)(native + offset);
WriteBytes(bytes, sizeInBytes);
}
}
/// <summary>
/// Write a partial value. The specified number of bytes is written from the value and the rest is ignored.
/// </summary>
@@ -790,68 +737,170 @@ namespace Unity.Netcode
return sizeof(T);
}
/// <summary>
/// Write a value of any unmanaged type (including unmanaged structs) to the buffer.
/// It will be copied into the buffer exactly as it exists in memory.
/// </summary>
/// <param name="value">The value to copy</param>
/// <typeparam name="T">Any unmanaged type</typeparam>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void WriteValue<T>(in T value) where T : unmanaged
private unsafe void WriteUnmanaged<T>(in T value) where T : unmanaged
{
int len = sizeof(T);
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (Handle->InBitwiseContext)
{
throw new InvalidOperationException(
"Cannot use BufferWriter in bytewise mode while in a bitwise context.");
}
if (Handle->Position + len > Handle->AllowedWriteMark)
{
throw new OverflowException($"Attempted to write without first calling {nameof(TryBeginWrite)}()");
}
#endif
fixed (T* ptr = &value)
{
UnsafeUtility.MemCpy(Handle->BufferPointer + Handle->Position, (byte*)ptr, len);
byte* bytes = (byte*)ptr;
WriteBytes(bytes, sizeof(T));
}
Handle->Position += len;
}
/// <summary>
/// Write a value of any unmanaged type (including unmanaged structs) to the buffer.
/// It will be copied into the buffer exactly as it exists in memory.
///
/// "Safe" version - automatically performs bounds checking. Less efficient than bounds checking
/// for multiple writes at once by calling TryBeginWrite.
/// </summary>
/// <param name="value">The value to copy</param>
/// <typeparam name="T">Any unmanaged type</typeparam>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void WriteValueSafe<T>(in T value) where T : unmanaged
private unsafe void WriteUnmanagedSafe<T>(in T value) where T : unmanaged
{
int len = sizeof(T);
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (Handle->InBitwiseContext)
{
throw new InvalidOperationException(
"Cannot use BufferWriter in bytewise mode while in a bitwise context.");
}
#endif
if (!TryBeginWriteInternal(len))
{
throw new OverflowException("Writing past the end of the buffer");
}
fixed (T* ptr = &value)
{
UnsafeUtility.MemCpy(Handle->BufferPointer + Handle->Position, (byte*)ptr, len);
byte* bytes = (byte*)ptr;
WriteBytesSafe(bytes, sizeof(T));
}
Handle->Position += len;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private unsafe void WriteUnmanaged<T>(T[] value) where T : unmanaged
{
WriteUnmanaged(value.Length);
fixed (T* ptr = value)
{
byte* bytes = (byte*)ptr;
WriteBytes(bytes, sizeof(T) * value.Length);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private unsafe void WriteUnmanagedSafe<T>(T[] value) where T : unmanaged
{
WriteUnmanagedSafe(value.Length);
fixed (T* ptr = value)
{
byte* bytes = (byte*)ptr;
WriteBytesSafe(bytes, sizeof(T) * value.Length);
}
}
// These structs enable overloading of WriteValue with different generic constraints.
// The compiler's actually able to distinguish between overloads based on generic constraints.
// But at the bytecode level, the constraints aren't included in the method signature.
// By adding a second parameter with a defaulted value, the signatures of each generic are different,
// thus allowing overloads of methods based on the first parameter meeting constraints.
public struct ForPrimitives
{
}
public struct ForEnums
{
}
public struct ForStructs
{
}
public struct ForNetworkSerializable
{
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue<T>(in T value, ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue<T>(T[] value, ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe<T>(in T value, ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe<T>(T[] value, ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T> => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue<T>(in T value, ForEnums unused = default) where T : unmanaged, Enum => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue<T>(T[] value, ForEnums unused = default) where T : unmanaged, Enum => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe<T>(in T value, ForEnums unused = default) where T : unmanaged, Enum => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe<T>(T[] value, ForEnums unused = default) where T : unmanaged, Enum => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue<T>(in T value, ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue<T>(T[] value, ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe<T>(in T value, ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe<T>(T[] value, ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue<T>(in T value, ForNetworkSerializable unused = default) where T : INetworkSerializable => WriteNetworkSerializable(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue<T>(T[] value, ForNetworkSerializable unused = default) where T : INetworkSerializable => WriteNetworkSerializable(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe<T>(in T value, ForNetworkSerializable unused = default) where T : INetworkSerializable => WriteNetworkSerializable(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe<T>(T[] value, ForNetworkSerializable unused = default) where T : INetworkSerializable => WriteNetworkSerializable(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue(in Vector2 value) => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue(Vector2[] value) => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue(in Vector3 value) => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue(Vector3[] value) => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue(in Vector4 value) => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue(Vector4[] value) => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue(in Quaternion value) => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue(Quaternion[] value) => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue(in Color value) => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue(Color[] value) => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue(in Color32 value) => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue(Color32[] value) => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue(in Ray value) => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue(Ray[] value) => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue(in Ray2D value) => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValue(Ray2D[] value) => WriteUnmanaged(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe(in Vector2 value) => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe(Vector2[] value) => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe(in Vector3 value) => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe(Vector3[] value) => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe(in Vector4 value) => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe(Vector4[] value) => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe(in Quaternion value) => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe(Quaternion[] value) => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe(in Color value) => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe(Color[] value) => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe(in Color32 value) => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe(Color32[] value) => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe(in Ray value) => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe(Ray[] value) => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe(in Ray2D value) => WriteUnmanagedSafe(value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteValueSafe(Ray2D[] value) => WriteUnmanagedSafe(value);
}
}

View File

@@ -0,0 +1,37 @@
using System;
namespace Unity.Netcode
{
/// <summary>
/// This is a wrapper that adds `INetworkSerializeByMemcpy` support to existing structs that the developer
/// doesn't have the ability to modify (for example, external structs like `Guid`).
/// </summary>
/// <typeparam name="T"></typeparam>
public struct ForceNetworkSerializeByMemcpy<T> : INetworkSerializeByMemcpy, IEquatable<ForceNetworkSerializeByMemcpy<T>> where T : unmanaged, IEquatable<T>
{
public T Value;
public ForceNetworkSerializeByMemcpy(T value)
{
Value = value;
}
public static implicit operator T(ForceNetworkSerializeByMemcpy<T> container) => container.Value;
public static implicit operator ForceNetworkSerializeByMemcpy<T>(T underlyingValue) => new ForceNetworkSerializeByMemcpy<T> { Value = underlyingValue };
public bool Equals(ForceNetworkSerializeByMemcpy<T> other)
{
return Value.Equals(other.Value);
}
public override bool Equals(object obj)
{
return obj is ForceNetworkSerializeByMemcpy<T> other && Equals(other);
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d56016695cd44430a345671f7d56b18e
timeCreated: 1647635768

View File

@@ -0,0 +1,15 @@
namespace Unity.Netcode
{
/// <summary>
/// This interface is a "tag" that can be applied to a struct to mark that struct as being serializable
/// by memcpy. It's up to the developer of the struct to analyze the struct's contents and ensure it
/// is actually serializable by memcpy. This requires all of the members of the struct to be
/// `unmanaged` Plain-Old-Data values - if your struct contains a pointer (or a type that contains a pointer,
/// like `NativeList<T>`), it should be serialized via `INetworkSerializable` or via
/// `FastBufferReader`/`FastBufferWriter` extension methods.
/// </summary>
public interface INetworkSerializeByMemcpy
{
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 11b763f46b18465cbffb1972d737a83e
timeCreated: 1647635592

View File

@@ -1,3 +1,6 @@
using System;
using UnityEngine;
namespace Unity.Netcode
{
public interface IReaderWriter
@@ -9,17 +12,60 @@ namespace Unity.Netcode
FastBufferWriter GetFastBufferWriter();
void SerializeValue(ref string s, bool oneByteChars = false);
void SerializeValue<T>(ref T[] array) where T : unmanaged;
void SerializeValue(ref byte value);
void SerializeValue<T>(ref T value) where T : unmanaged;
void SerializeValue<T>(ref T value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T>;
void SerializeValue<T>(ref T[] value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T>;
void SerializeValue<T>(ref T value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum;
void SerializeValue<T>(ref T[] value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum;
void SerializeValue<T>(ref T value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy;
void SerializeValue<T>(ref T[] value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy;
void SerializeValue<T>(ref T value, FastBufferWriter.ForNetworkSerializable unused = default) where T : INetworkSerializable, new();
void SerializeValue<T>(ref T[] value, FastBufferWriter.ForNetworkSerializable unused = default) where T : INetworkSerializable, new();
void SerializeValue(ref Vector2 value);
void SerializeValue(ref Vector2[] value);
void SerializeValue(ref Vector3 value);
void SerializeValue(ref Vector3[] value);
void SerializeValue(ref Vector4 value);
void SerializeValue(ref Vector4[] value);
void SerializeValue(ref Quaternion value);
void SerializeValue(ref Quaternion[] value);
void SerializeValue(ref Color value);
void SerializeValue(ref Color[] value);
void SerializeValue(ref Color32 value);
void SerializeValue(ref Color32[] value);
void SerializeValue(ref Ray value);
void SerializeValue(ref Ray[] value);
void SerializeValue(ref Ray2D value);
void SerializeValue(ref Ray2D[] value);
// Has to have a different name to avoid conflicting with "where T: unmananged"
void SerializeNetworkSerializable<T>(ref T value) where T : INetworkSerializable, new();
bool PreCheck(int amount);
void SerializeValuePreChecked(ref string s, bool oneByteChars = false);
void SerializeValuePreChecked<T>(ref T[] array) where T : unmanaged;
void SerializeValuePreChecked(ref byte value);
void SerializeValuePreChecked<T>(ref T value) where T : unmanaged;
void SerializeValuePreChecked<T>(ref T value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T>;
void SerializeValuePreChecked<T>(ref T[] value, FastBufferWriter.ForPrimitives unused = default) where T : unmanaged, IComparable, IConvertible, IComparable<T>, IEquatable<T>;
void SerializeValuePreChecked<T>(ref T value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum;
void SerializeValuePreChecked<T>(ref T[] value, FastBufferWriter.ForEnums unused = default) where T : unmanaged, Enum;
void SerializeValuePreChecked<T>(ref T value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy;
void SerializeValuePreChecked<T>(ref T[] value, FastBufferWriter.ForStructs unused = default) where T : unmanaged, INetworkSerializeByMemcpy;
void SerializeValuePreChecked(ref Vector2 value);
void SerializeValuePreChecked(ref Vector2[] value);
void SerializeValuePreChecked(ref Vector3 value);
void SerializeValuePreChecked(ref Vector3[] value);
void SerializeValuePreChecked(ref Vector4 value);
void SerializeValuePreChecked(ref Vector4[] value);
void SerializeValuePreChecked(ref Quaternion value);
void SerializeValuePreChecked(ref Quaternion[] value);
void SerializeValuePreChecked(ref Color value);
void SerializeValuePreChecked(ref Color[] value);
void SerializeValuePreChecked(ref Color32 value);
void SerializeValuePreChecked(ref Color32[] value);
void SerializeValuePreChecked(ref Ray value);
void SerializeValuePreChecked(ref Ray[] value);
void SerializeValuePreChecked(ref Ray2D value);
void SerializeValuePreChecked(ref Ray2D[] value);
}
}

View File

@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Unity.Collections;
using UnityEngine;
namespace Unity.Netcode
@@ -136,23 +135,6 @@ namespace Unity.Netcode
return OwnershipToObjectsTable[clientId].Values.ToList();
}
private struct TriggerData
{
public FastBufferReader Reader;
public MessageHeader Header;
public ulong SenderId;
public float Timestamp;
public int SerializedHeaderSize;
}
private struct TriggerInfo
{
public float Expiry;
public NativeList<TriggerData> TriggerData;
}
private readonly Dictionary<ulong, TriggerInfo> m_Triggers = new Dictionary<ulong, TriggerInfo>();
/// <summary>
/// Gets the NetworkManager associated with this SpawnManager.
/// </summary>
@@ -209,87 +191,6 @@ namespace Unity.Netcode
return null;
}
/// <summary>
/// Defers processing of a message until the moment a specific networkObjectId is spawned.
/// This is to handle situations where an RPC or other object-specific message arrives before the spawn does,
/// either due to it being requested in OnNetworkSpawn before the spawn call has been executed
///
/// There is a one second maximum lifetime of triggers to avoid memory leaks. After one second has passed
/// without the requested object ID being spawned, the triggers for it are automatically deleted.
/// </summary>
internal unsafe void TriggerOnSpawn(ulong networkObjectId, FastBufferReader reader, ref NetworkContext context)
{
if (!m_Triggers.ContainsKey(networkObjectId))
{
m_Triggers[networkObjectId] = new TriggerInfo
{
Expiry = Time.realtimeSinceStartup + 1,
TriggerData = new NativeList<TriggerData>(Allocator.Persistent)
};
}
m_Triggers[networkObjectId].TriggerData.Add(new TriggerData
{
Reader = new FastBufferReader(reader.GetUnsafePtr(), Allocator.Persistent, reader.Length),
Header = context.Header,
Timestamp = context.Timestamp,
SenderId = context.SenderId,
SerializedHeaderSize = context.SerializedHeaderSize
});
}
/// <summary>
/// Cleans up any trigger that's existed for more than a second.
/// These triggers were probably for situations where a request was received after a despawn rather than before a spawn.
/// </summary>
internal unsafe void CleanupStaleTriggers()
{
ulong* staleKeys = stackalloc ulong[m_Triggers.Count()];
int index = 0;
foreach (var kvp in m_Triggers)
{
if (kvp.Value.Expiry < Time.realtimeSinceStartup)
{
staleKeys[index++] = kvp.Key;
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
{
NetworkLog.LogWarning($"Deferred messages were received for {nameof(NetworkObject)} #{kvp.Key}, but it did not spawn within 1 second.");
}
foreach (var data in kvp.Value.TriggerData)
{
data.Reader.Dispose();
}
kvp.Value.TriggerData.Dispose();
}
}
for (var i = 0; i < index; ++i)
{
m_Triggers.Remove(staleKeys[i]);
}
}
/// <summary>
/// Cleans up any trigger that's existed for more than a second.
/// These triggers were probably for situations where a request was received after a despawn rather than before a spawn.
/// </summary>
internal void CleanupAllTriggers()
{
foreach (var kvp in m_Triggers)
{
foreach (var data in kvp.Value.TriggerData)
{
data.Reader.Dispose();
}
kvp.Value.TriggerData.Dispose();
}
m_Triggers.Clear();
}
internal void RemoveOwnership(NetworkObject networkObject)
{
if (!NetworkManager.IsServer)
@@ -382,6 +283,33 @@ namespace Unity.Netcode
}
}
internal bool HasPrefab(bool isSceneObject, uint globalObjectIdHash)
{
if (!NetworkManager.NetworkConfig.EnableSceneManagement || !isSceneObject)
{
if (NetworkManager.PrefabHandler.ContainsHandler(globalObjectIdHash))
{
return true;
}
if (NetworkManager.NetworkConfig.NetworkPrefabOverrideLinks.TryGetValue(globalObjectIdHash, out var networkPrefab))
{
switch (networkPrefab.Override)
{
default:
case NetworkPrefabOverride.None:
return networkPrefab.Prefab != null;
case NetworkPrefabOverride.Hash:
case NetworkPrefabOverride.Prefab:
return networkPrefab.OverridingTargetPrefab != null;
}
}
return false;
}
var networkObject = NetworkManager.SceneManager.GetSceneRelativeInSceneNetworkObject(globalObjectIdHash);
return networkObject != null;
}
/// <summary>
/// Should only run on the client
/// </summary>
@@ -612,20 +540,7 @@ namespace Unity.Netcode
networkObject.InvokeBehaviourNetworkSpawn();
// This must happen after InvokeBehaviourNetworkSpawn, otherwise ClientRPCs and other messages can be
// processed before the object is fully spawned. This must be the last thing done in the spawn process.
if (m_Triggers.ContainsKey(networkId))
{
var triggerInfo = m_Triggers[networkId];
foreach (var trigger in triggerInfo.TriggerData)
{
// Reader will be disposed within HandleMessage
NetworkManager.MessagingSystem.HandleMessage(trigger.Header, trigger.Reader, trigger.SenderId, trigger.Timestamp, trigger.SerializedHeaderSize);
}
triggerInfo.TriggerData.Dispose();
m_Triggers.Remove(networkId);
}
NetworkManager.DeferredMessageManager.ProcessTriggers(IDeferredMessageManager.TriggerType.OnSpawn, networkId);
// propagate the IsSceneObject setting to child NetworkObjects
var children = networkObject.GetComponentsInChildren<NetworkObject>();

View File

@@ -81,7 +81,10 @@ namespace Unity.Netcode
: this(tickRate)
{
Assert.IsTrue(tickOffset < 1d / tickRate);
this += tick * m_TickInterval + tickOffset;
m_CachedTickOffset = tickOffset;
m_CachedTick = tick;
m_TimeSec = tick * m_TickInterval + tickOffset;
}
/// <summary>

View File

@@ -205,8 +205,8 @@ namespace Unity.Netcode.Transports.UNET
public override bool StartServer()
{
var topology = new HostTopology(GetConfig(), MaxConnections);
UnityEngine.Networking.NetworkTransport.AddHost(topology, ServerListenPort, null);
return true;
// Undocumented, but AddHost returns -1 in case of any type of failure. See UNET::NetLibraryManager::AddHost
return -1 != UnityEngine.Networking.NetworkTransport.AddHost(topology, ServerListenPort, null);
}
public override void DisconnectRemoteClient(ulong clientId)

View File

@@ -195,7 +195,7 @@ MonoBehaviour:
NetworkIdRecycleDelay: 120
RpcHashSize: 0
LoadSceneTimeOut: 120
MessageBufferTimeout: 20
SpawnTimeout: 1
EnableNetworkLogs: 1
--- !u!114 &1114774668
MonoBehaviour:

View File

@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 3106ae882c6ec416d855a44c97eeaeef
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,4 +0,0 @@
{
"displayName": "ClientNetworkTransform",
"description": "A sample to demonstrate how client-driven NetworkTransform can be implemented"
}

View File

@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 6b1ef235ca94b4bbd9a6456f44c69188
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 03def738b58f746408d456f1f8c99264
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 749af92bd75b44951b56ea583f3f10b5
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,8 +0,0 @@
{
"name": "ClientNetworkTransform",
"rootNamespace": "Unity.Netcode.Samples",
"references": [
"Unity.Netcode.Runtime",
"Unity.Netcode.Components"
]
}

View File

@@ -1,7 +0,0 @@
fileFormatVersion: 2
guid: 78ac2a8d1365141f68da5d0a9e10dbc6
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,40 +0,0 @@
using Unity.Netcode.Components;
using UnityEngine;
namespace Unity.Netcode.Samples
{
/// <summary>
/// Used for syncing a transform with client side changes. This includes host. Pure server as owner isn't supported by this. Please use NetworkTransform
/// for transforms that'll always be owned by the server.
/// </summary>
[DisallowMultipleComponent]
public class ClientNetworkTransform : NetworkTransform
{
/// <summary>
/// Used to determine who can write to this transform. Owner client only.
/// Changing this value alone will not allow you to create a NetworkTransform which can be written to by clients.
/// We're using RPCs to send updated values from client to server. Netcode doesn't support client side network variable writing.
/// This imposes state to the server. This is putting trust on your clients. Make sure no security-sensitive features use this transform.
/// </summary>
// This is public to make sure that users don't depend on this IsClient && IsOwner check in their code. If this logic changes in the future, we can make it invisible here
public override void OnNetworkSpawn()
{
base.OnNetworkSpawn();
CanCommitToTransform = IsOwner;
}
protected override void Update()
{
CanCommitToTransform = IsOwner;
base.Update();
if (NetworkManager.Singleton != null && (NetworkManager.Singleton.IsConnectedClient || NetworkManager.Singleton.IsListening))
{
if (CanCommitToTransform)
{
TryCommitTransformToServer(transform, NetworkManager.LocalTime.Time);
}
}
}
}
}

View File

@@ -50,7 +50,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
return true;
}
public bool OnVerifyCanReceive(ulong senderId, Type messageType)
public bool OnVerifyCanReceive(ulong senderId, Type messageType, FastBufferReader messageContent, ref NetworkContext context)
{
return true;
}

View File

@@ -79,6 +79,15 @@ namespace Unity.Netcode.TestHelpers.Runtime
protected const uint k_DefaultTickRate = 30;
protected abstract int NumberOfClients { get; }
/// <summary>
/// Set this to false to create the clients first.
/// Note: If you are using scene placed NetworkObjects or doing any form of scene testing and
/// get prefab hash id "soft synchronization" errors, then set this to false and run your test
/// again. This is a work-around until we can resolve some issues with NetworkManagerOwner and
/// NetworkManager.Singleton.
/// </summary>
protected bool m_CreateServerFirst = true;
public enum NetworkManagerInstatiationMode
{
PerTest, // This will create and destroy new NetworkManagers for each test within a child derived class
@@ -108,8 +117,6 @@ namespace Unity.Netcode.TestHelpers.Runtime
protected bool m_UseHost = true;
protected int m_TargetFrameRate = 60;
protected NetcodeIntegrationTestHelpers.InstanceTransport m_NetworkTransport = NetcodeIntegrationTestHelpers.InstanceTransport.SIP;
private NetworkManagerInstatiationMode m_NetworkManagerInstatiationMode;
private bool m_EnableVerboseDebug;
@@ -252,7 +259,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
CreatePlayerPrefab();
// Create multiple NetworkManager instances
if (!NetcodeIntegrationTestHelpers.Create(numberOfClients, out NetworkManager server, out NetworkManager[] clients, m_TargetFrameRate, m_NetworkTransport))
if (!NetcodeIntegrationTestHelpers.Create(numberOfClients, out NetworkManager server, out NetworkManager[] clients, m_TargetFrameRate, m_CreateServerFirst))
{
Debug.LogError("Failed to create instances");
Assert.Fail("Failed to create instances");
@@ -558,6 +565,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
}
if (CanDestroyNetworkObject(networkObject))
{
networkObject.NetworkManagerOwner = m_ServerNetworkManager;
// Destroy the GameObject that holds the NetworkObject component
Object.DestroyImmediate(networkObject.gameObject);
}
@@ -668,6 +676,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
var gameObject = new GameObject();
gameObject.name = baseName;
var networkObject = gameObject.AddComponent<NetworkObject>();
networkObject.NetworkManagerOwner = m_ServerNetworkManager;
NetcodeIntegrationTestHelpers.MakeNetworkObjectTestPrefab(networkObject);
var networkPrefab = new NetworkPrefab() { Prefab = gameObject };
m_ServerNetworkManager.NetworkConfig.NetworkPrefabs.Add(networkPrefab);

View File

@@ -30,10 +30,16 @@ namespace Unity.Netcode.TestHelpers.Runtime
public MessageHandleCheck Check;
public bool Result;
}
internal class MessageReceiveCheckWithResult
{
public Type CheckType;
public bool Result;
}
private class MultiInstanceHooks : INetworkHooks
{
public Dictionary<Type, List<MessageHandleCheckWithResult>> HandleChecks = new Dictionary<Type, List<MessageHandleCheckWithResult>>();
public List<MessageReceiveCheckWithResult> ReceiveChecks = new List<MessageReceiveCheckWithResult>();
public static bool CheckForMessageOfType<T>(object receivedMessage) where T : INetworkMessage
{
@@ -50,6 +56,15 @@ namespace Unity.Netcode.TestHelpers.Runtime
public void OnBeforeReceiveMessage(ulong senderId, Type messageType, int messageSizeBytes)
{
foreach (var check in ReceiveChecks)
{
if (check.CheckType == messageType)
{
check.Result = true;
ReceiveChecks.Remove(check);
break;
}
}
}
public void OnAfterReceiveMessage(ulong senderId, Type messageType, int messageSizeBytes)
@@ -77,7 +92,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
return true;
}
public bool OnVerifyCanReceive(ulong senderId, Type messageType)
public bool OnVerifyCanReceive(ulong senderId, Type messageType, FastBufferReader messageContent, ref NetworkContext context)
{
return true;
}
@@ -107,12 +122,6 @@ namespace Unity.Netcode.TestHelpers.Runtime
public static List<NetworkManager> NetworkManagerInstances => s_NetworkManagerInstances;
public enum InstanceTransport
{
SIP,
UTP
}
internal static IntegrationTestSceneHandler ClientSceneHandler = null;
/// <summary>
@@ -162,20 +171,32 @@ namespace Unity.Netcode.TestHelpers.Runtime
}
}
/// <summary>
/// Create the correct NetworkTransport, attach it to the game object and return it.
/// Default value is SIPTransport.
/// </summary>
internal static NetworkTransport CreateInstanceTransport(InstanceTransport instanceTransport, GameObject go)
public static NetworkManager CreateServer()
{
switch (instanceTransport)
// Create gameObject
var go = new GameObject("NetworkManager - Server");
// Create networkManager component
var server = go.AddComponent<NetworkManager>();
NetworkManagerInstances.Insert(0, server);
// Create transport
var unityTransport = go.AddComponent<UnityTransport>();
// We need to increase this buffer size for tests that spawn a bunch of things
unityTransport.MaxPayloadSize = 256000;
unityTransport.MaxSendQueueSize = 1024 * 1024;
// Allow 4 connection attempts that each will time out after 500ms
unityTransport.MaxConnectAttempts = 4;
unityTransport.ConnectTimeoutMS = 500;
// Set the NetworkConfig
server.NetworkConfig = new NetworkConfig()
{
case InstanceTransport.SIP:
return go.AddComponent<SIPTransport>();
default:
case InstanceTransport.UTP:
return go.AddComponent<UnityTransport>();
}
// Set transport
NetworkTransport = unityTransport
};
return server;
}
/// <summary>
@@ -185,24 +206,22 @@ namespace Unity.Netcode.TestHelpers.Runtime
/// <param name="server">The server NetworkManager</param>
/// <param name="clients">The clients NetworkManagers</param>
/// <param name="targetFrameRate">The targetFrameRate of the Unity engine to use while the multi instance helper is running. Will be reset on shutdown.</param>
public static bool Create(int clientCount, out NetworkManager server, out NetworkManager[] clients, int targetFrameRate = 60, InstanceTransport instanceTransport = InstanceTransport.SIP)
/// <param name="serverFirst">This determines if the server or clients will be instantiated first (defaults to server first)</param>
public static bool Create(int clientCount, out NetworkManager server, out NetworkManager[] clients, int targetFrameRate = 60, bool serverFirst = true)
{
s_NetworkManagerInstances = new List<NetworkManager>();
CreateNewClients(clientCount, out clients, instanceTransport);
// Create gameObject
var go = new GameObject("NetworkManager - Server");
// Create networkManager component
server = go.AddComponent<NetworkManager>();
NetworkManagerInstances.Insert(0, server);
// Set the NetworkConfig
server.NetworkConfig = new NetworkConfig()
server = null;
if (serverFirst)
{
// Set transport
NetworkTransport = CreateInstanceTransport(instanceTransport, go)
};
server = CreateServer();
}
CreateNewClients(clientCount, out clients);
if (!serverFirst)
{
server = CreateServer();
}
s_OriginalTargetFrameRate = Application.targetFrameRate;
Application.targetFrameRate = targetFrameRate;
@@ -215,7 +234,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
/// </summary>
/// <param name="clientCount">The amount of clients</param>
/// <param name="clients"></param>
public static bool CreateNewClients(int clientCount, out NetworkManager[] clients, InstanceTransport instanceTransport = InstanceTransport.SIP)
public static bool CreateNewClients(int clientCount, out NetworkManager[] clients)
{
clients = new NetworkManager[clientCount];
var activeSceneName = SceneManager.GetActiveScene().name;
@@ -226,11 +245,14 @@ namespace Unity.Netcode.TestHelpers.Runtime
// Create networkManager component
clients[i] = go.AddComponent<NetworkManager>();
// Create transport
var unityTransport = go.AddComponent<UnityTransport>();
// Set the NetworkConfig
clients[i].NetworkConfig = new NetworkConfig()
{
// Set transport
NetworkTransport = CreateInstanceTransport(instanceTransport, go)
NetworkTransport = unityTransport
};
}
@@ -273,7 +295,10 @@ namespace Unity.Netcode.TestHelpers.Runtime
// Destroy the network manager instances
foreach (var networkManager in NetworkManagerInstances)
{
Object.DestroyImmediate(networkManager.gameObject);
if (networkManager.gameObject != null)
{
Object.Destroy(networkManager.gameObject);
}
}
NetworkManagerInstances.Clear();
@@ -697,7 +722,35 @@ namespace Unity.Netcode.TestHelpers.Runtime
/// </summary>
/// <param name="result">The result. If null, it will fail if the predicate is not met</param>
/// <param name="timeout">The max time in seconds to wait for</param>
internal static IEnumerator WaitForMessageOfType<T>(NetworkManager toBeReceivedBy, ResultWrapper<bool> result = null, float timeout = 0.5f) where T : INetworkMessage
internal static IEnumerator WaitForMessageOfTypeReceived<T>(NetworkManager toBeReceivedBy, ResultWrapper<bool> result = null, float timeout = 0.5f) where T : INetworkMessage
{
var hooks = s_Hooks[toBeReceivedBy];
var check = new MessageReceiveCheckWithResult { CheckType = typeof(T) };
hooks.ReceiveChecks.Add(check);
if (result == null)
{
result = new ResultWrapper<bool>();
}
var startTime = Time.realtimeSinceStartup;
while (!check.Result && Time.realtimeSinceStartup - startTime < timeout)
{
yield return null;
}
var res = check.Result;
result.Result = res;
Assert.True(result.Result, $"Expected message {typeof(T).Name} was not received within {timeout}s.");
}
/// <summary>
/// Waits for a message of the given type to be received
/// </summary>
/// <param name="result">The result. If null, it will fail if the predicate is not met</param>
/// <param name="timeout">The max time in seconds to wait for</param>
internal static IEnumerator WaitForMessageOfTypeHandled<T>(NetworkManager toBeReceivedBy, ResultWrapper<bool> result = null, float timeout = 0.5f) where T : INetworkMessage
{
var hooks = s_Hooks[toBeReceivedBy];
if (!hooks.HandleChecks.ContainsKey(typeof(T)))
@@ -712,7 +765,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
}
yield return ExecuteWaitForHook(check, result, timeout);
Assert.True(result.Result, $"Expected message {typeof(T).Name} was not received within {timeout}s.");
Assert.True(result.Result, $"Expected message {typeof(T).Name} was not handled within {timeout}s.");
}
/// <summary>
@@ -721,7 +774,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
/// <param name="requirement">Called for each received message to check if it's the right one</param>
/// <param name="result">The result. If null, it will fail if the predicate is not met</param>
/// <param name="timeout">The max time in seconds to wait for</param>
internal static IEnumerator WaitForMessageMeetingRequirement<T>(NetworkManager toBeReceivedBy, MessageHandleCheck requirement, ResultWrapper<bool> result = null, float timeout = DefaultTimeout)
internal static IEnumerator WaitForMessageMeetingRequirementHandled<T>(NetworkManager toBeReceivedBy, MessageHandleCheck requirement, ResultWrapper<bool> result = null, float timeout = DefaultTimeout)
{
var hooks = s_Hooks[toBeReceivedBy];
if (!hooks.HandleChecks.ContainsKey(typeof(T)))
@@ -736,7 +789,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
}
yield return ExecuteWaitForHook(check, result, timeout);
Assert.True(result.Result, $"Expected message meeting user requirements was not received within {timeout}s.");
Assert.True(result.Result, $"Expected message meeting user requirements was not handled within {timeout}s.");
}
private static IEnumerator ExecuteWaitForHook(MessageHandleCheckWithResult check, ResultWrapper<bool> result, float timeout)

View File

@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using UnityEngine;
using NUnit.Framework;
using Unity.Netcode.Transports.UTP;
namespace Unity.Netcode.TestHelpers.Runtime
{
@@ -67,11 +68,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
Debug.Log($"{nameof(NetworkManager)} Instantiated.");
// NOTE: For now we only use SIPTransport for tests until UnityTransport
// has been verified working in nightly builds
// TODO-MTT-2486: Provide support for other transports once tested and verified
// working on consoles.
var sipTransport = NetworkManagerGameObject.AddComponent<SIPTransport>();
var unityTransport = NetworkManagerGameObject.AddComponent<UnityTransport>();
if (networkConfig == null)
{
networkConfig = new NetworkConfig
@@ -81,7 +78,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
}
NetworkManagerObject.NetworkConfig = networkConfig;
NetworkManagerObject.NetworkConfig.NetworkTransport = sipTransport;
NetworkManagerObject.NetworkConfig.NetworkTransport = unityTransport;
// Starts the network manager in the mode specified
StartNetworkManagerMode(managerMode);

View File

@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: d764f651f0e54e8281952933cc49be97
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,267 +0,0 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Unity.Netcode.TestHelpers.Runtime
{
/// <summary>
/// SIPTransport (SIngleProcessTransport)
/// is a NetworkTransport designed to be used with multiple network instances in a single process
/// it's designed for the netcode in a way where no networking stack has to be available
/// it's designed for testing purposes and it's not designed with speed in mind
/// </summary>
public class SIPTransport : TestingNetworkTransport
{
private struct Event
{
public NetworkEvent Type;
public ulong ConnectionId;
public ArraySegment<byte> Data;
}
private class Peer
{
public ulong ConnectionId;
public SIPTransport Transport;
public Queue<Event> IncomingBuffer = new Queue<Event>();
}
private readonly Dictionary<ulong, Peer> m_Peers = new Dictionary<ulong, Peer>();
private ulong m_ClientsCounter = 1;
private static Peer s_Server;
private Peer m_LocalConnection;
public override ulong ServerClientId => 0;
public ulong LocalClientId;
public override void DisconnectLocalClient()
{
if (m_LocalConnection != null)
{
// Inject local disconnect
m_LocalConnection.IncomingBuffer.Enqueue(new Event
{
Type = NetworkEvent.Disconnect,
ConnectionId = m_LocalConnection.ConnectionId,
Data = new ArraySegment<byte>()
});
if (s_Server != null && m_LocalConnection != null)
{
// Remove the connection
s_Server.Transport.m_Peers.Remove(m_LocalConnection.ConnectionId);
}
if (m_LocalConnection.ConnectionId == ServerClientId)
{
StopServer();
}
// Remove the local connection
m_LocalConnection = null;
}
}
// Called by server
public override void DisconnectRemoteClient(ulong clientId)
{
if (m_Peers.ContainsKey(clientId))
{
// Inject disconnect into remote
m_Peers[clientId].IncomingBuffer.Enqueue(new Event
{
Type = NetworkEvent.Disconnect,
ConnectionId = clientId,
Data = new ArraySegment<byte>()
});
// Inject local disconnect
m_LocalConnection.IncomingBuffer.Enqueue(new Event
{
Type = NetworkEvent.Disconnect,
ConnectionId = clientId,
Data = new ArraySegment<byte>()
});
// Remove the local connection on remote
m_Peers[clientId].Transport.m_LocalConnection = null;
// Remove connection on server
m_Peers.Remove(clientId);
}
}
public override ulong GetCurrentRtt(ulong clientId)
{
// Always returns 50ms
return 50;
}
public override void Initialize(NetworkManager networkManager = null)
{
}
private void StopServer()
{
s_Server = null;
m_Peers.Remove(ServerClientId);
m_LocalConnection = null;
}
public override void Shutdown()
{
// Inject disconnects to all the remotes
foreach (KeyValuePair<ulong, Peer> onePeer in m_Peers)
{
onePeer.Value.IncomingBuffer.Enqueue(new Event
{
Type = NetworkEvent.Disconnect,
ConnectionId = LocalClientId,
Data = new ArraySegment<byte>()
});
}
if (m_LocalConnection != null && m_LocalConnection.ConnectionId == ServerClientId)
{
StopServer();
}
// TODO: Cleanup
}
public override bool StartClient()
{
if (s_Server == null)
{
// No server
Debug.LogError("No server");
return false;
}
if (m_LocalConnection != null)
{
// Already connected
Debug.LogError("Already connected");
return false;
}
// Generate an Id for the server that represents this client
ulong serverConnectionId = ++s_Server.Transport.m_ClientsCounter;
LocalClientId = serverConnectionId;
// Create local connection
m_LocalConnection = new Peer()
{
ConnectionId = serverConnectionId,
Transport = this,
IncomingBuffer = new Queue<Event>()
};
// Add the server as a local connection
m_Peers.Add(ServerClientId, s_Server);
// Add local connection as a connection on the server
s_Server.Transport.m_Peers.Add(serverConnectionId, m_LocalConnection);
// Sends a connect message to the server
s_Server.Transport.m_LocalConnection.IncomingBuffer.Enqueue(new Event()
{
Type = NetworkEvent.Connect,
ConnectionId = serverConnectionId,
Data = new ArraySegment<byte>()
});
// Send a local connect message
m_LocalConnection.IncomingBuffer.Enqueue(new Event
{
Type = NetworkEvent.Connect,
ConnectionId = ServerClientId,
Data = new ArraySegment<byte>()
});
return true;
}
public override bool StartServer()
{
if (s_Server != null)
{
// Can only have one server
Debug.LogError("Server already started");
return false;
}
if (m_LocalConnection != null)
{
// Already connected
Debug.LogError("Already connected");
return false;
}
// Create local connection
m_LocalConnection = new Peer()
{
ConnectionId = ServerClientId,
Transport = this,
IncomingBuffer = new Queue<Event>()
};
// Set the local connection as the server
s_Server = m_LocalConnection;
m_Peers.Add(ServerClientId, s_Server);
return true;
}
public override void Send(ulong clientId, ArraySegment<byte> payload, NetworkDelivery networkDelivery)
{
if (m_LocalConnection != null)
{
// Create copy since netcode wants the byte array back straight after the method call.
// Hard on GC.
byte[] copy = new byte[payload.Count];
Buffer.BlockCopy(payload.Array, payload.Offset, copy, 0, payload.Count);
if (m_Peers.ContainsKey(clientId))
{
m_Peers[clientId].IncomingBuffer.Enqueue(new Event
{
Type = NetworkEvent.Data,
ConnectionId = m_LocalConnection.ConnectionId,
Data = new ArraySegment<byte>(copy)
});
}
}
}
public override NetworkEvent PollEvent(out ulong clientId, out ArraySegment<byte> payload, out float receiveTime)
{
if (m_LocalConnection != null)
{
if (m_LocalConnection.IncomingBuffer.Count == 0)
{
clientId = 0;
payload = new ArraySegment<byte>();
receiveTime = 0;
return NetworkEvent.Nothing;
}
var peerEvent = m_LocalConnection.IncomingBuffer.Dequeue();
clientId = peerEvent.ConnectionId;
payload = peerEvent.Data;
receiveTime = 0;
return peerEvent.Type;
}
clientId = 0;
payload = new ArraySegment<byte>();
receiveTime = 0;
return NetworkEvent.Nothing;
}
}
}

View File

@@ -1,3 +0,0 @@
fileFormatVersion: 2
guid: 1fd1b14eba874a189f13f12d343c331c
timeCreated: 1620145176

View File

@@ -367,5 +367,5 @@ MonoBehaviour:
NetworkIdRecycleDelay: 120
RpcHashSize: 0
LoadSceneTimeOut: 120
MessageBufferTimeout: 20
SpawnTimeout: 20
EnableNetworkLogs: 1

View File

@@ -4,6 +4,7 @@ using NUnit.Framework;
using UnityEditor;
using UnityEditor.Build.Reporting;
using UnityEngine;
using UnityEngine.TestTools;
namespace Unity.Netcode.EditorTests
{
@@ -16,13 +17,25 @@ namespace Unity.Netcode.EditorTests
{
var execAssembly = Assembly.GetExecutingAssembly();
var packagePath = UnityEditor.PackageManager.PackageInfo.FindForAssembly(execAssembly).assetPath;
var buildTarget = EditorUserBuildSettings.activeBuildTarget;
var buildTargetGroup = BuildPipeline.GetBuildTargetGroup(buildTarget);
var buildTargetSupported = BuildPipeline.IsBuildTargetSupported(buildTargetGroup, buildTarget);
var buildReport = BuildPipeline.BuildPlayer(
new[] { Path.Combine(packagePath, DefaultBuildScenePath) },
Path.Combine(Path.GetDirectoryName(Application.dataPath), "Builds", nameof(BuildTests)),
EditorUserBuildSettings.activeBuildTarget,
buildTarget,
BuildOptions.None
);
if (buildTargetSupported)
{
Assert.AreEqual(BuildResult.Succeeded, buildReport.summary.result);
}
else
{
LogAssert.Expect(LogType.Error, "Error building player because build target was unsupported");
}
}
}
}

View File

@@ -9,7 +9,7 @@ namespace Unity.Netcode.EditorTests
{
public class MessageReceivingTests
{
private struct TestMessage : INetworkMessage
private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy
{
public int A;
public int B;

View File

@@ -5,7 +5,7 @@ namespace Unity.Netcode.EditorTests
{
public class MessageRegistrationTests
{
private struct TestMessageOne : INetworkMessage
private struct TestMessageOne : INetworkMessage, INetworkSerializeByMemcpy
{
public int A;
public int B;
@@ -25,7 +25,7 @@ namespace Unity.Netcode.EditorTests
}
}
private struct TestMessageTwo : INetworkMessage
private struct TestMessageTwo : INetworkMessage, INetworkSerializeByMemcpy
{
public int A;
public int B;
@@ -64,7 +64,7 @@ namespace Unity.Netcode.EditorTests
}
}
private struct TestMessageThree : INetworkMessage
private struct TestMessageThree : INetworkMessage, INetworkSerializeByMemcpy
{
public int A;
public int B;
@@ -97,7 +97,7 @@ namespace Unity.Netcode.EditorTests
};
}
}
private struct TestMessageFour : INetworkMessage
private struct TestMessageFour : INetworkMessage, INetworkSerializeByMemcpy
{
public int A;
public int B;
@@ -173,8 +173,6 @@ namespace Unity.Netcode.EditorTests
MessagingSystem.MessageHandler handlerThree = MessagingSystem.ReceiveMessage<TestMessageThree>;
MessagingSystem.MessageHandler handlerFour = MessagingSystem.ReceiveMessage<TestMessageFour>;
var foundHandlerOne = systemOne.MessageHandlers[systemOne.GetMessageType(typeof(TestMessageOne))];
Assert.AreEqual(handlerOne, systemOne.MessageHandlers[systemOne.GetMessageType(typeof(TestMessageOne))]);
Assert.AreEqual(handlerTwo, systemOne.MessageHandlers[systemOne.GetMessageType(typeof(TestMessageTwo))]);
Assert.AreEqual(handlerThree, systemTwo.MessageHandlers[systemTwo.GetMessageType(typeof(TestMessageThree))]);

View File

@@ -8,7 +8,7 @@ namespace Unity.Netcode.EditorTests
{
public class MessageSendingTests
{
private struct TestMessage : INetworkMessage
private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy
{
public int A;
public int B;

View File

@@ -58,7 +58,7 @@ namespace Unity.Netcode.EditorTests
C
};
protected struct TestStruct
protected struct TestStruct : INetworkSerializeByMemcpy
{
public byte A;
public short B;
@@ -80,7 +80,6 @@ namespace Unity.Netcode.EditorTests
}
#endregion
protected abstract void RunTypeTest<T>(T valueToTest) where T : unmanaged;
protected abstract void RunTypeTestSafe<T>(T valueToTest) where T : unmanaged;
@@ -114,11 +113,8 @@ namespace Unity.Netcode.EditorTests
#endregion
public void BaseTypeTest(Type testType, WriteType writeType)
{
var random = new Random();
void RunTypeTestLocal<T>(T val, WriteType wt) where T : unmanaged
private void RunTestWithWriteType<T>(T val, WriteType wt, FastBufferWriter.ForPrimitives _ = default) where T : unmanaged
{
switch (wt)
{
@@ -131,126 +127,130 @@ namespace Unity.Netcode.EditorTests
}
}
public void BaseTypeTest(Type testType, WriteType writeType)
{
var random = new Random();
if (testType == typeof(byte))
{
RunTypeTestLocal((byte)random.Next(), writeType);
RunTestWithWriteType((byte)random.Next(), writeType);
}
else if (testType == typeof(sbyte))
{
RunTypeTestLocal((sbyte)random.Next(), writeType);
RunTestWithWriteType((sbyte)random.Next(), writeType);
}
else if (testType == typeof(short))
{
RunTypeTestLocal((short)random.Next(), writeType);
RunTestWithWriteType((short)random.Next(), writeType);
}
else if (testType == typeof(ushort))
{
RunTypeTestLocal((ushort)random.Next(), writeType);
RunTestWithWriteType((ushort)random.Next(), writeType);
}
else if (testType == typeof(int))
{
RunTypeTestLocal((int)random.Next(), writeType);
RunTestWithWriteType((int)random.Next(), writeType);
}
else if (testType == typeof(uint))
{
RunTypeTestLocal((uint)random.Next(), writeType);
RunTestWithWriteType((uint)random.Next(), writeType);
}
else if (testType == typeof(long))
{
RunTypeTestLocal(((long)random.Next() << 32) + random.Next(), writeType);
RunTestWithWriteType(((long)random.Next() << 32) + random.Next(), writeType);
}
else if (testType == typeof(ulong))
{
RunTypeTestLocal(((ulong)random.Next() << 32) + (ulong)random.Next(), writeType);
RunTestWithWriteType(((ulong)random.Next() << 32) + (ulong)random.Next(), writeType);
}
else if (testType == typeof(bool))
{
RunTypeTestLocal(true, writeType);
RunTestWithWriteType(true, writeType);
}
else if (testType == typeof(char))
{
RunTypeTestLocal('a', writeType);
RunTypeTestLocal('\u263a', writeType);
RunTestWithWriteType('a', writeType);
RunTestWithWriteType('\u263a', writeType);
}
else if (testType == typeof(float))
{
RunTypeTestLocal((float)random.NextDouble(), writeType);
RunTestWithWriteType((float)random.NextDouble(), writeType);
}
else if (testType == typeof(double))
{
RunTypeTestLocal(random.NextDouble(), writeType);
RunTestWithWriteType(random.NextDouble(), writeType);
}
else if (testType == typeof(ByteEnum))
{
RunTypeTestLocal(ByteEnum.C, writeType);
RunTestWithWriteType(ByteEnum.C, writeType);
}
else if (testType == typeof(SByteEnum))
{
RunTypeTestLocal(SByteEnum.C, writeType);
RunTestWithWriteType(SByteEnum.C, writeType);
}
else if (testType == typeof(ShortEnum))
{
RunTypeTestLocal(ShortEnum.C, writeType);
RunTestWithWriteType(ShortEnum.C, writeType);
}
else if (testType == typeof(UShortEnum))
{
RunTypeTestLocal(UShortEnum.C, writeType);
RunTestWithWriteType(UShortEnum.C, writeType);
}
else if (testType == typeof(IntEnum))
{
RunTypeTestLocal(IntEnum.C, writeType);
RunTestWithWriteType(IntEnum.C, writeType);
}
else if (testType == typeof(UIntEnum))
{
RunTypeTestLocal(UIntEnum.C, writeType);
RunTestWithWriteType(UIntEnum.C, writeType);
}
else if (testType == typeof(LongEnum))
{
RunTypeTestLocal(LongEnum.C, writeType);
RunTestWithWriteType(LongEnum.C, writeType);
}
else if (testType == typeof(ULongEnum))
{
RunTypeTestLocal(ULongEnum.C, writeType);
RunTestWithWriteType(ULongEnum.C, writeType);
}
else if (testType == typeof(Vector2))
{
RunTypeTestLocal(new Vector2((float)random.NextDouble(), (float)random.NextDouble()), writeType);
RunTestWithWriteType(new Vector2((float)random.NextDouble(), (float)random.NextDouble()), writeType);
}
else if (testType == typeof(Vector3))
{
RunTypeTestLocal(new Vector3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()), writeType);
RunTestWithWriteType(new Vector3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()), writeType);
}
else if (testType == typeof(Vector4))
{
RunTypeTestLocal(new Vector4((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()), writeType);
RunTestWithWriteType(new Vector4((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()), writeType);
}
else if (testType == typeof(Quaternion))
{
RunTypeTestLocal(new Quaternion((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()), writeType);
RunTestWithWriteType(new Quaternion((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()), writeType);
}
else if (testType == typeof(Color))
{
RunTypeTestLocal(new Color((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()), writeType);
RunTestWithWriteType(new Color((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()), writeType);
}
else if (testType == typeof(Color32))
{
RunTypeTestLocal(new Color32((byte)random.Next(), (byte)random.Next(), (byte)random.Next(), (byte)random.Next()), writeType);
RunTestWithWriteType(new Color32((byte)random.Next(), (byte)random.Next(), (byte)random.Next(), (byte)random.Next()), writeType);
}
else if (testType == typeof(Ray))
{
RunTypeTestLocal(new Ray(
RunTestWithWriteType(new Ray(
new Vector3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()),
new Vector3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble())), writeType);
}
else if (testType == typeof(Ray2D))
{
RunTypeTestLocal(new Ray2D(
RunTestWithWriteType(new Ray2D(
new Vector2((float)random.NextDouble(), (float)random.NextDouble()),
new Vector2((float)random.NextDouble(), (float)random.NextDouble())), writeType);
}
else if (testType == typeof(TestStruct))
{
RunTypeTestLocal(GetTestStruct(), writeType);
RunTestWithWriteType(GetTestStruct(), writeType);
}
else
{

View File

@@ -1,4 +1,5 @@
using System;
using System.Reflection;
using NUnit.Framework;
using Unity.Collections;
using UnityEngine;
@@ -51,6 +52,184 @@ namespace Unity.Netcode.EditorTests
return reader;
}
private void RunWriteMethod<T>(string methodName, FastBufferWriter writer, in T value) where T : unmanaged
{
MethodInfo method = typeof(FastBufferWriter).GetMethod(methodName, new[] { typeof(T).MakeByRefType() });
if (method == null)
{
foreach (var candidateMethod in typeof(FastBufferWriter).GetMethods())
{
if (candidateMethod.Name == methodName && candidateMethod.IsGenericMethodDefinition)
{
if (candidateMethod.GetParameters().Length == 0 || (candidateMethod.GetParameters().Length > 1 && !candidateMethod.GetParameters()[1].HasDefaultValue))
{
continue;
}
if (candidateMethod.GetParameters()[0].ParameterType.IsArray)
{
continue;
}
try
{
method = candidateMethod.MakeGenericMethod(typeof(T));
break;
}
catch (ArgumentException)
{
continue;
}
}
}
}
Assert.NotNull(method);
object[] args = new object[method.GetParameters().Length];
args[0] = value;
for (var i = 1; i < args.Length; ++i)
{
args[i] = method.GetParameters()[i].DefaultValue;
}
method.Invoke(writer, args);
}
private void RunWriteMethod<T>(string methodName, FastBufferWriter writer, in T[] value) where T : unmanaged
{
MethodInfo method = typeof(FastBufferWriter).GetMethod(methodName, new[] { typeof(T[]) });
if (method == null)
{
foreach (var candidateMethod in typeof(FastBufferWriter).GetMethods())
{
if (candidateMethod.Name == methodName && candidateMethod.IsGenericMethodDefinition)
{
if (candidateMethod.GetParameters().Length == 0 || (candidateMethod.GetParameters().Length > 1 && !candidateMethod.GetParameters()[1].HasDefaultValue))
{
continue;
}
if (!candidateMethod.GetParameters()[0].ParameterType.IsArray)
{
continue;
}
try
{
method = candidateMethod.MakeGenericMethod(typeof(T));
break;
}
catch (ArgumentException)
{
continue;
}
}
}
}
Assert.NotNull(method);
object[] args = new object[method.GetParameters().Length];
args[0] = value;
for (var i = 1; i < args.Length; ++i)
{
args[i] = method.GetParameters()[i].DefaultValue;
}
method.Invoke(writer, args);
}
private void RunReadMethod<T>(string methodName, FastBufferReader reader, out T value) where T : unmanaged
{
MethodInfo method = typeof(FastBufferReader).GetMethod(methodName, new[] { typeof(T).MakeByRefType() });
if (method == null)
{
foreach (var candidateMethod in typeof(FastBufferReader).GetMethods())
{
if (candidateMethod.Name == methodName && candidateMethod.IsGenericMethodDefinition)
{
if (candidateMethod.GetParameters().Length == 0 || (candidateMethod.GetParameters().Length > 1 && !candidateMethod.GetParameters()[1].HasDefaultValue))
{
continue;
}
if (candidateMethod.GetParameters()[0].ParameterType.IsArray)
{
continue;
}
try
{
method = candidateMethod.MakeGenericMethod(typeof(T));
break;
}
catch (ArgumentException)
{
continue;
}
}
}
}
value = new T();
Assert.NotNull(method);
object[] args = new object[method.GetParameters().Length];
args[0] = value;
for (var i = 1; i < args.Length; ++i)
{
args[i] = method.GetParameters()[i].DefaultValue;
}
method.Invoke(reader, args);
value = (T)args[0];
}
private void RunReadMethod<T>(string methodName, FastBufferReader reader, out T[] value) where T : unmanaged
{
MethodInfo method = null;
try
{
method = typeof(FastBufferReader).GetMethod(methodName, new[] { typeof(T[]).MakeByRefType() });
}
catch (AmbiguousMatchException)
{
// skip.
}
if (method == null)
{
foreach (var candidateMethod in typeof(FastBufferReader).GetMethods())
{
if (candidateMethod.Name == methodName && candidateMethod.IsGenericMethodDefinition)
{
if (candidateMethod.GetParameters().Length == 0 || (candidateMethod.GetParameters().Length > 1 && !candidateMethod.GetParameters()[1].HasDefaultValue))
{
continue;
}
if (!candidateMethod.GetParameters()[0].ParameterType.HasElementType || !candidateMethod.GetParameters()[0].ParameterType.GetElementType().IsArray)
{
continue;
}
try
{
method = candidateMethod.MakeGenericMethod(typeof(T));
break;
}
catch (ArgumentException)
{
continue;
}
}
}
}
Assert.NotNull(method);
value = new T[] { };
object[] args = new object[method.GetParameters().Length];
args[0] = value;
for (var i = 1; i < args.Length; ++i)
{
args[i] = method.GetParameters()[i].DefaultValue;
}
method.Invoke(reader, args);
value = (T[])args[0];
}
#endregion
#region Generic Checks
@@ -66,14 +245,14 @@ namespace Unity.Netcode.EditorTests
var failMessage = $"RunTypeTest failed with type {typeof(T)} and value {valueToTest}";
writer.WriteValue(valueToTest);
RunWriteMethod(nameof(FastBufferWriter.WriteValue), writer, valueToTest);
var reader = CommonChecks(writer, valueToTest, writeSize, failMessage);
using (reader)
{
Assert.IsTrue(reader.TryBeginRead(FastBufferWriter.GetWriteSize<T>()));
reader.ReadValue(out T result);
RunReadMethod(nameof(FastBufferReader.ReadValue), reader, out T result);
Assert.AreEqual(valueToTest, result);
}
}
@@ -89,14 +268,14 @@ namespace Unity.Netcode.EditorTests
var failMessage = $"RunTypeTest failed with type {typeof(T)} and value {valueToTest}";
writer.WriteValueSafe(valueToTest);
RunWriteMethod(nameof(FastBufferWriter.WriteValueSafe), writer, valueToTest);
var reader = CommonChecks(writer, valueToTest, writeSize, failMessage);
using (reader)
{
reader.ReadValueSafe(out T result);
RunReadMethod(nameof(FastBufferReader.ReadValueSafe), reader, out T result);
Assert.AreEqual(valueToTest, result);
}
}
@@ -121,7 +300,7 @@ namespace Unity.Netcode.EditorTests
Assert.AreEqual(sizeof(int) + sizeof(T) * valueToTest.Length, writeSize);
Assert.IsTrue(writer.TryBeginWrite(writeSize + 2), "Writer denied write permission");
writer.WriteValue(valueToTest);
RunWriteMethod(nameof(FastBufferWriter.WriteValue), writer, valueToTest);
WriteCheckBytes(writer, writeSize);
@@ -131,7 +310,7 @@ namespace Unity.Netcode.EditorTests
VerifyPositionAndLength(reader, writer.Length);
Assert.IsTrue(reader.TryBeginRead(writeSize));
reader.ReadValue(out T[] result);
RunReadMethod(nameof(FastBufferReader.ReadValue), reader, out T[] result);
VerifyArrayEquality(valueToTest, result, 0);
VerifyCheckBytes(reader, writeSize);
@@ -147,7 +326,7 @@ namespace Unity.Netcode.EditorTests
{
Assert.AreEqual(sizeof(int) + sizeof(T) * valueToTest.Length, writeSize);
writer.WriteValueSafe(valueToTest);
RunWriteMethod(nameof(FastBufferWriter.WriteValueSafe), writer, valueToTest);
WriteCheckBytes(writer, writeSize);
@@ -156,7 +335,7 @@ namespace Unity.Netcode.EditorTests
{
VerifyPositionAndLength(reader, writer.Length);
reader.ReadValueSafe(out T[] result);
RunReadMethod(nameof(FastBufferReader.ReadValueSafe), reader, out T[] result);
VerifyArrayEquality(valueToTest, result, 0);
VerifyCheckBytes(reader, writeSize);

View File

@@ -1,4 +1,5 @@
using System;
using System.Reflection;
using NUnit.Framework;
using Unity.Collections;
using UnityEngine;
@@ -10,6 +11,7 @@ namespace Unity.Netcode.EditorTests
{
#region Common Checks
private void WriteCheckBytes(FastBufferWriter writer, int writeSize, string failMessage = "")
{
Assert.IsTrue(writer.TryBeginWrite(2), "Writer denied write permission");
@@ -63,9 +65,94 @@ namespace Unity.Netcode.EditorTests
VerifyTypedEquality(valueToTest, writer.GetUnsafePtr());
}
#endregion
#region Generic Checks
private void RunMethod<T>(string methodName, FastBufferWriter writer, in T value) where T : unmanaged
{
MethodInfo method = typeof(FastBufferWriter).GetMethod(methodName, new[] { typeof(T).MakeByRefType() });
if (method == null)
{
foreach (var candidateMethod in typeof(FastBufferWriter).GetMethods())
{
if (candidateMethod.Name == methodName && candidateMethod.IsGenericMethodDefinition)
{
if (candidateMethod.GetParameters().Length == 0 || (candidateMethod.GetParameters().Length > 1 && !candidateMethod.GetParameters()[1].HasDefaultValue))
{
continue;
}
if (candidateMethod.GetParameters()[0].ParameterType.IsArray)
{
continue;
}
try
{
method = candidateMethod.MakeGenericMethod(typeof(T));
break;
}
catch (ArgumentException)
{
continue;
}
}
}
}
Assert.NotNull(method);
object[] args = new object[method.GetParameters().Length];
args[0] = value;
for (var i = 1; i < args.Length; ++i)
{
args[i] = method.GetParameters()[i].DefaultValue;
}
method.Invoke(writer, args);
}
private void RunMethod<T>(string methodName, FastBufferWriter writer, in T[] value) where T : unmanaged
{
MethodInfo method = typeof(FastBufferWriter).GetMethod(methodName, new[] { typeof(T[]) });
if (method == null)
{
foreach (var candidateMethod in typeof(FastBufferWriter).GetMethods())
{
if (candidateMethod.Name == methodName && candidateMethod.IsGenericMethodDefinition)
{
if (candidateMethod.GetParameters().Length == 0 || (candidateMethod.GetParameters().Length > 1 && !candidateMethod.GetParameters()[1].HasDefaultValue))
{
continue;
}
if (!candidateMethod.GetParameters()[0].ParameterType.IsArray)
{
continue;
}
try
{
method = candidateMethod.MakeGenericMethod(typeof(T));
break;
}
catch (ArgumentException)
{
continue;
}
}
}
}
Assert.NotNull(method);
object[] args = new object[method.GetParameters().Length];
args[0] = value;
for (var i = 1; i < args.Length; ++i)
{
args[i] = method.GetParameters()[i].DefaultValue;
}
method.Invoke(writer, args);
}
protected override unsafe void RunTypeTest<T>(T valueToTest)
{
var writeSize = FastBufferWriter.GetWriteSize(valueToTest);
@@ -82,7 +169,7 @@ namespace Unity.Netcode.EditorTests
var failMessage = $"RunTypeTest failed with type {typeof(T)} and value {valueToTest}";
writer.WriteValue(valueToTest);
RunMethod(nameof(FastBufferWriter.WriteValue), writer, valueToTest);
CommonChecks(writer, valueToTest, writeSize, failMessage);
}
@@ -98,7 +185,7 @@ namespace Unity.Netcode.EditorTests
var failMessage = $"RunTypeTest failed with type {typeof(T)} and value {valueToTest}";
writer.WriteValueSafe(valueToTest);
RunMethod(nameof(FastBufferWriter.WriteValueSafe), writer, valueToTest);
CommonChecks(writer, valueToTest, writeSize, failMessage);
}
@@ -129,7 +216,7 @@ namespace Unity.Netcode.EditorTests
Assert.AreEqual(sizeof(int) + sizeof(T) * valueToTest.Length, writeSize);
Assert.IsTrue(writer.TryBeginWrite(writeSize + 2), "Writer denied write permission");
writer.WriteValue(valueToTest);
RunMethod(nameof(FastBufferWriter.WriteValue), writer, valueToTest);
VerifyPositionAndLength(writer, writeSize);
WriteCheckBytes(writer, writeSize);
@@ -150,7 +237,7 @@ namespace Unity.Netcode.EditorTests
Assert.AreEqual(sizeof(int) + sizeof(T) * valueToTest.Length, writeSize);
writer.WriteValueSafe(valueToTest);
RunMethod(nameof(FastBufferWriter.WriteValueSafe), writer, valueToTest);
VerifyPositionAndLength(writer, writeSize);
WriteCheckBytes(writer, writeSize);

View File

@@ -0,0 +1,49 @@
#if UNITY_UNET_PRESENT
#pragma warning disable 618 // disable is obsolete
using NUnit.Framework;
using Unity.Netcode.Transports.UNET;
using UnityEngine;
using UnityEngine.TestTools;
namespace Unity.Netcode.EditorTests
{
public class UNetTransportTests
{
[Test]
public void StartServerReturnsFalseOnFailure()
{
UNetTransport unet1 = null;
UNetTransport unet2 = null;
try
{
// Arrange
// We're expecting an error from UNET, but don't care to validate the specific message
LogAssert.ignoreFailingMessages = true;
var go = new GameObject();
unet1 = go.AddComponent<UNetTransport>();
unet1.ServerListenPort = 1;
unet1.Initialize();
unet1.StartServer();
unet2 = go.AddComponent<UNetTransport>();
unet2.ServerListenPort = 1;
unet2.Initialize();
// Act
var result = unet2.StartServer();
// Assert
Assert.IsFalse(result, "UNET fails to initialize against port already in use");
}
finally
{
unet1?.Shutdown();
unet2?.Shutdown();
}
}
}
}
#pragma warning restore 618
#endif

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 54c9647dc784a46bca664910f182491e
guid: 6e328ef8f7c9b46538253a1b39dc8a97
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@@ -24,6 +24,11 @@
"name": "com.unity.multiplayer.tools",
"expression": "",
"define": "MULTIPLAYER_TOOLS"
},
{
"name": "Unity",
"expression": "(0,2022.2.0a5)",
"define": "UNITY_UNET_PRESENT"
}
]
}

View File

@@ -3,11 +3,7 @@ using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
using Unity.Netcode.TestHelpers.Runtime;
#if UNITY_UNET_PRESENT
using Unity.Netcode.Transports.UNET;
#else
using Unity.Netcode.Transports.UTP;
#endif
namespace Unity.Netcode.RuntimeTests
{
@@ -26,15 +22,13 @@ namespace Unity.Netcode.RuntimeTests
m_NetworkManagerGameObject = new GameObject();
m_ClientNetworkManager = m_NetworkManagerGameObject.AddComponent<NetworkManager>();
m_ClientNetworkManager.NetworkConfig = new NetworkConfig();
#if UNITY_UNET_PRESENT
m_TimeoutHelper = new TimeoutHelper(30);
m_ClientNetworkManager.NetworkConfig.NetworkTransport = m_NetworkManagerGameObject.AddComponent<UNetTransport>();
#else
// Default is 1000ms per connection attempt and 60 connection attempts (60s)
// Currently there is no easy way to set these values other than in-editor
m_TimeoutHelper = new TimeoutHelper(70);
m_ClientNetworkManager.NetworkConfig.NetworkTransport = m_NetworkManagerGameObject.AddComponent<UnityTransport>();
#endif
var unityTransport = m_NetworkManagerGameObject.AddComponent<UnityTransport>();
unityTransport.ConnectTimeoutMS = 1000;
unityTransport.MaxConnectAttempts = 1;
m_TimeoutHelper = new TimeoutHelper(2);
m_ClientNetworkManager.NetworkConfig.NetworkTransport = unityTransport;
}
[UnityTest]
@@ -46,10 +40,9 @@ namespace Unity.Netcode.RuntimeTests
// Only start the client (so it will timeout)
m_ClientNetworkManager.StartClient();
#if !UNITY_UNET_PRESENT
// Unity Transport throws an error when it times out
LogAssert.Expect(LogType.Error, "Failed to connect to server.");
#endif
yield return NetcodeIntegrationTest.WaitForConditionOrTimeOut(() => m_WasDisconnected, m_TimeoutHelper);
Assert.False(m_TimeoutHelper.TimedOut, "Timed out waiting for client to timeout waiting to connect!");

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b3d771dc2a334464ad96e8c66ac776cc
timeCreated: 1650295945

View File

@@ -9,6 +9,8 @@ namespace Unity.Netcode.RuntimeTests
{
public class DisconnectTests
{
private bool m_ClientDisconnected;
[UnityTest]
public IEnumerator RemoteDisconnectPlayerObjectCleanup()
{
@@ -38,11 +40,14 @@ namespace Unity.Netcode.RuntimeTests
yield return NetcodeIntegrationTestHelpers.WaitForClientConnectedToServer(server);
// disconnect the remote client
m_ClientDisconnected = false;
server.DisconnectClient(clients[0].LocalClientId);
clients[0].OnClientDisconnectCallback += OnClientDisconnectCallback;
var timeoutHelper = new TimeoutHelper();
yield return NetcodeIntegrationTest.WaitForConditionOrTimeOut(() => m_ClientDisconnected, timeoutHelper);
// wait 1 frame because destroys are delayed
var nextFrameNumber = Time.frameCount + 1;
yield return new WaitUntil(() => Time.frameCount >= nextFrameNumber);
// We need to do this to remove other associated client properties/values from NetcodeIntegrationTestHelpers
NetcodeIntegrationTestHelpers.StopOneClient(clients[0]);
// ensure the object was destroyed
Assert.False(server.SpawnManager.SpawnedObjects.Any(x => x.Value.IsPlayerObject && x.Value.OwnerClientId == clients[0].LocalClientId));
@@ -50,5 +55,10 @@ namespace Unity.Netcode.RuntimeTests
// cleanup
NetcodeIntegrationTestHelpers.Destroy();
}
private void OnClientDisconnectCallback(ulong obj)
{
m_ClientDisconnected = true;
}
}
}

View File

@@ -27,7 +27,7 @@ namespace Unity.Netcode.RuntimeTests
public IEnumerator NamedMessageIsReceivedOnClientWithContent()
{
var messageName = Guid.NewGuid().ToString();
var messageContent = Guid.NewGuid();
var messageContent = new ForceNetworkSerializeByMemcpy<Guid>(Guid.NewGuid());
var writer = new FastBufferWriter(1300, Allocator.Temp);
using (writer)
{
@@ -39,7 +39,7 @@ namespace Unity.Netcode.RuntimeTests
}
ulong receivedMessageSender = 0;
var receivedMessageContent = new Guid();
var receivedMessageContent = new ForceNetworkSerializeByMemcpy<Guid>(new Guid());
FirstClient.CustomMessagingManager.RegisterNamedMessageHandler(
messageName,
(ulong sender, FastBufferReader reader) =>
@@ -51,7 +51,7 @@ namespace Unity.Netcode.RuntimeTests
yield return new WaitForSeconds(0.2f);
Assert.AreEqual(messageContent, receivedMessageContent);
Assert.AreEqual(messageContent.Value, receivedMessageContent.Value);
Assert.AreEqual(m_ServerNetworkManager.LocalClientId, receivedMessageSender);
}
@@ -59,7 +59,7 @@ namespace Unity.Netcode.RuntimeTests
public IEnumerator NamedMessageIsReceivedOnMultipleClientsWithContent()
{
var messageName = Guid.NewGuid().ToString();
var messageContent = Guid.NewGuid();
var messageContent = new ForceNetworkSerializeByMemcpy<Guid>(Guid.NewGuid());
var writer = new FastBufferWriter(1300, Allocator.Temp);
using (writer)
{
@@ -71,7 +71,7 @@ namespace Unity.Netcode.RuntimeTests
}
ulong firstReceivedMessageSender = 0;
var firstReceivedMessageContent = new Guid();
var firstReceivedMessageContent = new ForceNetworkSerializeByMemcpy<Guid>(new Guid());
FirstClient.CustomMessagingManager.RegisterNamedMessageHandler(
messageName,
(ulong sender, FastBufferReader reader) =>
@@ -82,7 +82,7 @@ namespace Unity.Netcode.RuntimeTests
});
ulong secondReceivedMessageSender = 0;
var secondReceivedMessageContent = new Guid();
var secondReceivedMessageContent = new ForceNetworkSerializeByMemcpy<Guid>(new Guid());
SecondClient.CustomMessagingManager.RegisterNamedMessageHandler(
messageName,
(ulong sender, FastBufferReader reader) =>
@@ -94,10 +94,10 @@ namespace Unity.Netcode.RuntimeTests
yield return new WaitForSeconds(0.2f);
Assert.AreEqual(messageContent, firstReceivedMessageContent);
Assert.AreEqual(messageContent.Value, firstReceivedMessageContent.Value);
Assert.AreEqual(m_ServerNetworkManager.LocalClientId, firstReceivedMessageSender);
Assert.AreEqual(messageContent, secondReceivedMessageContent);
Assert.AreEqual(messageContent.Value, secondReceivedMessageContent.Value);
Assert.AreEqual(m_ServerNetworkManager.LocalClientId, secondReceivedMessageSender);
}
@@ -105,7 +105,7 @@ namespace Unity.Netcode.RuntimeTests
public IEnumerator WhenSendingNamedMessageToAll_AllClientsReceiveIt()
{
var messageName = Guid.NewGuid().ToString();
var messageContent = Guid.NewGuid();
var messageContent = new ForceNetworkSerializeByMemcpy<Guid>(Guid.NewGuid());
var writer = new FastBufferWriter(1300, Allocator.Temp);
using (writer)
{
@@ -114,7 +114,7 @@ namespace Unity.Netcode.RuntimeTests
}
ulong firstReceivedMessageSender = 0;
var firstReceivedMessageContent = new Guid();
var firstReceivedMessageContent = new ForceNetworkSerializeByMemcpy<Guid>(new Guid());
FirstClient.CustomMessagingManager.RegisterNamedMessageHandler(
messageName,
(ulong sender, FastBufferReader reader) =>
@@ -125,7 +125,7 @@ namespace Unity.Netcode.RuntimeTests
});
ulong secondReceivedMessageSender = 0;
var secondReceivedMessageContent = new Guid();
var secondReceivedMessageContent = new ForceNetworkSerializeByMemcpy<Guid>(new Guid());
SecondClient.CustomMessagingManager.RegisterNamedMessageHandler(
messageName,
(ulong sender, FastBufferReader reader) =>
@@ -137,10 +137,10 @@ namespace Unity.Netcode.RuntimeTests
yield return new WaitForSeconds(0.2f);
Assert.AreEqual(messageContent, firstReceivedMessageContent);
Assert.AreEqual(messageContent.Value, firstReceivedMessageContent.Value);
Assert.AreEqual(m_ServerNetworkManager.LocalClientId, firstReceivedMessageSender);
Assert.AreEqual(messageContent, secondReceivedMessageContent);
Assert.AreEqual(messageContent.Value, secondReceivedMessageContent.Value);
Assert.AreEqual(m_ServerNetworkManager.LocalClientId, secondReceivedMessageSender);
}
@@ -148,7 +148,7 @@ namespace Unity.Netcode.RuntimeTests
public void WhenSendingNamedMessageToNullClientList_ArgumentNullExceptionIsThrown()
{
var messageName = Guid.NewGuid().ToString();
var messageContent = Guid.NewGuid();
var messageContent = new ForceNetworkSerializeByMemcpy<Guid>(Guid.NewGuid());
var writer = new FastBufferWriter(1300, Allocator.Temp);
using (writer)
{

View File

@@ -19,7 +19,7 @@ namespace Unity.Netcode.RuntimeTests
[UnityTest]
public IEnumerator UnnamedMessageIsReceivedOnClientWithContent()
{
var messageContent = Guid.NewGuid();
var messageContent = new ForceNetworkSerializeByMemcpy<Guid>(Guid.NewGuid());
var writer = new FastBufferWriter(1300, Allocator.Temp);
using (writer)
{
@@ -30,7 +30,7 @@ namespace Unity.Netcode.RuntimeTests
}
ulong receivedMessageSender = 0;
var receivedMessageContent = new Guid();
var receivedMessageContent = new ForceNetworkSerializeByMemcpy<Guid>(new Guid());
FirstClient.CustomMessagingManager.OnUnnamedMessage +=
(ulong sender, FastBufferReader reader) =>
{
@@ -41,14 +41,14 @@ namespace Unity.Netcode.RuntimeTests
yield return new WaitForSeconds(0.2f);
Assert.AreEqual(messageContent, receivedMessageContent);
Assert.AreEqual(messageContent.Value, receivedMessageContent.Value);
Assert.AreEqual(m_ServerNetworkManager.LocalClientId, receivedMessageSender);
}
[UnityTest]
public IEnumerator UnnamedMessageIsReceivedOnMultipleClientsWithContent()
{
var messageContent = Guid.NewGuid();
var messageContent = new ForceNetworkSerializeByMemcpy<Guid>(Guid.NewGuid());
var writer = new FastBufferWriter(1300, Allocator.Temp);
using (writer)
{
@@ -59,7 +59,7 @@ namespace Unity.Netcode.RuntimeTests
}
ulong firstReceivedMessageSender = 0;
var firstReceivedMessageContent = new Guid();
var firstReceivedMessageContent = new ForceNetworkSerializeByMemcpy<Guid>(new Guid());
FirstClient.CustomMessagingManager.OnUnnamedMessage +=
(ulong sender, FastBufferReader reader) =>
{
@@ -69,7 +69,7 @@ namespace Unity.Netcode.RuntimeTests
};
ulong secondReceivedMessageSender = 0;
var secondReceivedMessageContent = new Guid();
var secondReceivedMessageContent = new ForceNetworkSerializeByMemcpy<Guid>(new Guid());
SecondClient.CustomMessagingManager.OnUnnamedMessage +=
(ulong sender, FastBufferReader reader) =>
{
@@ -80,17 +80,17 @@ namespace Unity.Netcode.RuntimeTests
yield return new WaitForSeconds(0.2f);
Assert.AreEqual(messageContent, firstReceivedMessageContent);
Assert.AreEqual(messageContent.Value, firstReceivedMessageContent.Value);
Assert.AreEqual(m_ServerNetworkManager.LocalClientId, firstReceivedMessageSender);
Assert.AreEqual(messageContent, secondReceivedMessageContent);
Assert.AreEqual(messageContent.Value, secondReceivedMessageContent.Value);
Assert.AreEqual(m_ServerNetworkManager.LocalClientId, secondReceivedMessageSender);
}
[UnityTest]
public IEnumerator WhenSendingUnnamedMessageToAll_AllClientsReceiveIt()
{
var messageContent = Guid.NewGuid();
var messageContent = new ForceNetworkSerializeByMemcpy<Guid>(Guid.NewGuid());
var writer = new FastBufferWriter(1300, Allocator.Temp);
using (writer)
{
@@ -99,7 +99,7 @@ namespace Unity.Netcode.RuntimeTests
}
ulong firstReceivedMessageSender = 0;
var firstReceivedMessageContent = new Guid();
var firstReceivedMessageContent = new ForceNetworkSerializeByMemcpy<Guid>(new Guid());
FirstClient.CustomMessagingManager.OnUnnamedMessage +=
(ulong sender, FastBufferReader reader) =>
{
@@ -109,7 +109,7 @@ namespace Unity.Netcode.RuntimeTests
};
ulong secondReceivedMessageSender = 0;
var secondReceivedMessageContent = new Guid();
var secondReceivedMessageContent = new ForceNetworkSerializeByMemcpy<Guid>(new Guid());
SecondClient.CustomMessagingManager.OnUnnamedMessage +=
(ulong sender, FastBufferReader reader) =>
{
@@ -120,17 +120,17 @@ namespace Unity.Netcode.RuntimeTests
yield return new WaitForSeconds(0.2f);
Assert.AreEqual(messageContent, firstReceivedMessageContent);
Assert.AreEqual(messageContent.Value, firstReceivedMessageContent.Value);
Assert.AreEqual(m_ServerNetworkManager.LocalClientId, firstReceivedMessageSender);
Assert.AreEqual(messageContent, secondReceivedMessageContent);
Assert.AreEqual(messageContent.Value, secondReceivedMessageContent.Value);
Assert.AreEqual(m_ServerNetworkManager.LocalClientId, secondReceivedMessageSender);
}
[Test]
public void WhenSendingNamedMessageToNullClientList_ArgumentNullExceptionIsThrown()
{
var messageContent = Guid.NewGuid();
var messageContent = new ForceNetworkSerializeByMemcpy<Guid>(Guid.NewGuid());
var writer = new FastBufferWriter(1300, Allocator.Temp);
using (writer)
{

View File

@@ -27,12 +27,12 @@ namespace Unity.Netcode.RuntimeTests.Metrics
{
var waitForMetricValues = new WaitForEventMetricValues<NetworkMessageEvent>(ServerMetrics.Dispatcher, NetworkMetricTypes.NetworkMessageSent);
var messageName = Guid.NewGuid();
var messageName = new ForceNetworkSerializeByMemcpy<Guid>(Guid.NewGuid());
using (var writer = new FastBufferWriter(1300, Allocator.Temp))
{
writer.WriteValueSafe(messageName);
Server.CustomMessagingManager.SendNamedMessage(messageName.ToString(), FirstClient.LocalClientId, writer);
Server.CustomMessagingManager.SendNamedMessage(messageName.Value.ToString(), FirstClient.LocalClientId, writer);
}
yield return waitForMetricValues.WaitForMetricsReceived();
@@ -47,12 +47,12 @@ namespace Unity.Netcode.RuntimeTests.Metrics
public IEnumerator TrackNetworkMessageSentMetricToMultipleClients()
{
var waitForMetricValues = new WaitForEventMetricValues<NetworkMessageEvent>(ServerMetrics.Dispatcher, NetworkMetricTypes.NetworkMessageSent);
var messageName = Guid.NewGuid();
var messageName = new ForceNetworkSerializeByMemcpy<Guid>(Guid.NewGuid());
using (var writer = new FastBufferWriter(1300, Allocator.Temp))
{
writer.WriteValueSafe(messageName);
Server.CustomMessagingManager.SendNamedMessage(messageName.ToString(), new List<ulong> { FirstClient.LocalClientId, SecondClient.LocalClientId }, writer);
Server.CustomMessagingManager.SendNamedMessage(messageName.Value.ToString(), new List<ulong> { FirstClient.LocalClientId, SecondClient.LocalClientId }, writer);
}
@@ -65,10 +65,10 @@ namespace Unity.Netcode.RuntimeTests.Metrics
[UnityTest]
public IEnumerator TrackNetworkMessageReceivedMetric()
{
var messageName = Guid.NewGuid();
var messageName = new ForceNetworkSerializeByMemcpy<Guid>(Guid.NewGuid());
LogAssert.Expect(LogType.Log, $"Received from {Server.LocalClientId}");
FirstClient.CustomMessagingManager.RegisterNamedMessageHandler(messageName.ToString(), (ulong sender, FastBufferReader payload) =>
FirstClient.CustomMessagingManager.RegisterNamedMessageHandler(messageName.Value.ToString(), (ulong sender, FastBufferReader payload) =>
{
Debug.Log($"Received from {sender}");
});
@@ -79,7 +79,7 @@ namespace Unity.Netcode.RuntimeTests.Metrics
{
writer.WriteValueSafe(messageName);
Server.CustomMessagingManager.SendNamedMessage(messageName.ToString(), FirstClient.LocalClientId, writer);
Server.CustomMessagingManager.SendNamedMessage(messageName.Value.ToString(), FirstClient.LocalClientId, writer);
}
yield return waitForMetricValues.WaitForMetricsReceived();
@@ -94,12 +94,12 @@ namespace Unity.Netcode.RuntimeTests.Metrics
{
var waitForMetricValues = new WaitForEventMetricValues<NamedMessageEvent>(ServerMetrics.Dispatcher, NetworkMetricTypes.NamedMessageSent);
var messageName = Guid.NewGuid();
var messageName = new ForceNetworkSerializeByMemcpy<Guid>(Guid.NewGuid());
using (var writer = new FastBufferWriter(1300, Allocator.Temp))
{
writer.WriteValueSafe(messageName);
Server.CustomMessagingManager.SendNamedMessage(messageName.ToString(), FirstClient.LocalClientId, writer);
Server.CustomMessagingManager.SendNamedMessage(messageName.Value.ToString(), FirstClient.LocalClientId, writer);
}
@@ -109,7 +109,7 @@ namespace Unity.Netcode.RuntimeTests.Metrics
Assert.AreEqual(1, namedMessageSentMetricValues.Count);
var namedMessageSent = namedMessageSentMetricValues.First();
Assert.AreEqual(messageName.ToString(), namedMessageSent.Name);
Assert.AreEqual(messageName.Value.ToString(), namedMessageSent.Name);
Assert.AreEqual(FirstClient.LocalClientId, namedMessageSent.Connection.Id);
Assert.AreEqual(FastBufferWriter.GetWriteSize(messageName) + k_NamedMessageOverhead, namedMessageSent.BytesCount);
}
@@ -118,12 +118,12 @@ namespace Unity.Netcode.RuntimeTests.Metrics
public IEnumerator TrackNamedMessageSentMetricToMultipleClients()
{
var waitForMetricValues = new WaitForEventMetricValues<NamedMessageEvent>(ServerMetrics.Dispatcher, NetworkMetricTypes.NamedMessageSent);
var messageName = Guid.NewGuid();
var messageName = new ForceNetworkSerializeByMemcpy<Guid>(Guid.NewGuid());
using (var writer = new FastBufferWriter(1300, Allocator.Temp))
{
writer.WriteValueSafe(messageName);
Server.CustomMessagingManager.SendNamedMessage(messageName.ToString(), new List<ulong> { FirstClient.LocalClientId, SecondClient.LocalClientId }, writer);
Server.CustomMessagingManager.SendNamedMessage(messageName.Value.ToString(), new List<ulong> { FirstClient.LocalClientId, SecondClient.LocalClientId }, writer);
}
@@ -131,7 +131,7 @@ namespace Unity.Netcode.RuntimeTests.Metrics
var namedMessageSentMetricValues = waitForMetricValues.AssertMetricValuesHaveBeenFound();
Assert.AreEqual(2, namedMessageSentMetricValues.Count);
Assert.That(namedMessageSentMetricValues.Select(x => x.Name), Has.All.EqualTo(messageName.ToString()));
Assert.That(namedMessageSentMetricValues.Select(x => x.Name), Has.All.EqualTo(messageName.Value.ToString()));
Assert.That(namedMessageSentMetricValues.Select(x => x.BytesCount), Has.All.EqualTo(FastBufferWriter.GetWriteSize(messageName) + k_NamedMessageOverhead));
}
@@ -139,12 +139,12 @@ namespace Unity.Netcode.RuntimeTests.Metrics
public IEnumerator TrackNamedMessageSentMetricToSelf()
{
var waitForMetricValues = new WaitForEventMetricValues<NamedMessageEvent>(ServerMetrics.Dispatcher, NetworkMetricTypes.NamedMessageSent);
var messageName = Guid.NewGuid();
var messageName = new ForceNetworkSerializeByMemcpy<Guid>(Guid.NewGuid());
using (var writer = new FastBufferWriter(1300, Allocator.Temp))
{
writer.WriteValueSafe(messageName);
Server.CustomMessagingManager.SendNamedMessage(messageName.ToString(), Server.LocalClientId, writer);
Server.CustomMessagingManager.SendNamedMessage(messageName.Value.ToString(), Server.LocalClientId, writer);
}
yield return waitForMetricValues.WaitForMetricsReceived();
@@ -157,10 +157,10 @@ namespace Unity.Netcode.RuntimeTests.Metrics
{
var waitForMetricValues = new WaitForEventMetricValues<NamedMessageEvent>(FirstClientMetrics.Dispatcher, NetworkMetricTypes.NamedMessageReceived);
var messageName = Guid.NewGuid();
var messageName = new ForceNetworkSerializeByMemcpy<Guid>(Guid.NewGuid());
LogAssert.Expect(LogType.Log, $"Received from {Server.LocalClientId}");
FirstClient.CustomMessagingManager.RegisterNamedMessageHandler(messageName.ToString(), (ulong sender, FastBufferReader payload) =>
FirstClient.CustomMessagingManager.RegisterNamedMessageHandler(messageName.Value.ToString(), (ulong sender, FastBufferReader payload) =>
{
Debug.Log($"Received from {sender}");
});
@@ -169,7 +169,7 @@ namespace Unity.Netcode.RuntimeTests.Metrics
{
writer.WriteValueSafe(messageName);
Server.CustomMessagingManager.SendNamedMessage(messageName.ToString(), FirstClient.LocalClientId, writer);
Server.CustomMessagingManager.SendNamedMessage(messageName.Value.ToString(), FirstClient.LocalClientId, writer);
}
@@ -179,7 +179,7 @@ namespace Unity.Netcode.RuntimeTests.Metrics
Assert.AreEqual(1, namedMessageReceivedValues.Count);
var namedMessageReceived = namedMessageReceivedValues.First();
Assert.AreEqual(messageName.ToString(), namedMessageReceived.Name);
Assert.AreEqual(messageName.Value.ToString(), namedMessageReceived.Name);
Assert.AreEqual(Server.LocalClientId, namedMessageReceived.Connection.Id);
Assert.AreEqual(FastBufferWriter.GetWriteSize(messageName) + k_NamedMessageOverhead, namedMessageReceived.BytesCount);
}
@@ -187,7 +187,7 @@ namespace Unity.Netcode.RuntimeTests.Metrics
[UnityTest]
public IEnumerator TrackUnnamedMessageSentMetric()
{
var message = Guid.NewGuid();
var message = new ForceNetworkSerializeByMemcpy<Guid>(Guid.NewGuid());
using (var writer = new FastBufferWriter(1300, Allocator.Temp))
{
writer.WriteValueSafe(message);
@@ -211,7 +211,7 @@ namespace Unity.Netcode.RuntimeTests.Metrics
[UnityTest]
public IEnumerator TrackUnnamedMessageSentMetricToMultipleClients()
{
var message = Guid.NewGuid();
var message = new ForceNetworkSerializeByMemcpy<Guid>(Guid.NewGuid());
var waitForMetricValues = new WaitForEventMetricValues<UnnamedMessageEvent>(ServerMetrics.Dispatcher, NetworkMetricTypes.UnnamedMessageSent);
using (var writer = new FastBufferWriter(1300, Allocator.Temp))
{
@@ -236,7 +236,7 @@ namespace Unity.Netcode.RuntimeTests.Metrics
public IEnumerator TrackUnnamedMessageSentMetricToSelf()
{
var waitForMetricValues = new WaitForEventMetricValues<UnnamedMessageEvent>(ServerMetrics.Dispatcher, NetworkMetricTypes.UnnamedMessageSent);
var messageName = Guid.NewGuid();
var messageName = new ForceNetworkSerializeByMemcpy<Guid>(Guid.NewGuid());
using (var writer = new FastBufferWriter(1300, Allocator.Temp))
{
writer.WriteValueSafe(messageName);
@@ -252,7 +252,7 @@ namespace Unity.Netcode.RuntimeTests.Metrics
[UnityTest]
public IEnumerator TrackUnnamedMessageReceivedMetric()
{
var message = Guid.NewGuid();
var message = new ForceNetworkSerializeByMemcpy<Guid>(Guid.NewGuid());
var waitForMetricValues = new WaitForEventMetricValues<UnnamedMessageEvent>(FirstClientMetrics.Dispatcher, NetworkMetricTypes.UnnamedMessageReceived);
using (var writer = new FastBufferWriter(1300, Allocator.Temp))
{

View File

@@ -24,11 +24,6 @@ namespace Unity.Netcode.RuntimeTests.Metrics
: base(HostOrServer.Server)
{}
protected override void OnOneTimeSetup()
{
m_NetworkTransport = NetcodeIntegrationTestHelpers.InstanceTransport.UTP;
}
protected override void OnServerAndClientsCreated()
{
var clientTransport = (UnityTransport)m_ClientNetworkManagers[0].NetworkConfig.NetworkTransport;

View File

@@ -12,13 +12,6 @@ namespace Unity.Netcode.RuntimeTests.Metrics
{
internal class PacketMetricsTests : SingleClientMetricTestBase
{
protected override void OnOneTimeSetup()
{
m_NetworkTransport = NetcodeIntegrationTestHelpers.InstanceTransport.UTP;
base.OnOneTimeSetup();
}
[UnityTest]
public IEnumerator TrackPacketSentMetric()
{

View File

@@ -40,15 +40,6 @@ namespace Unity.Netcode.RuntimeTests.Metrics
m_ClientCount = numberOfClients == ClientCount.OneClient ? 1 : 2;
}
/// <summary>
/// Note: We are using the OnOneTimeSetup to select the transport to use for
/// this test set.
/// </summary>
protected override void OnOneTimeSetup()
{
m_NetworkTransport = NetcodeIntegrationTestHelpers.InstanceTransport.UTP;
}
[UnityTest]
public IEnumerator TrackRttMetricServerToClient()
{

View File

@@ -16,6 +16,12 @@ namespace Unity.Netcode.RuntimeTests.Metrics
private static readonly int k_ServerLogSentMessageOverhead = 2 + k_MessageHeaderSize;
private static readonly int k_ServerLogReceivedMessageOverhead = 2;
protected override IEnumerator OnSetup()
{
m_CreateServerFirst = false;
return base.OnSetup();
}
[UnityTest]
public IEnumerator TrackServerLogSentMetric()
{

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