Compare commits
9 Commits
2.0.0-pre.
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| fe746bf2a3 | |||
|
|
8fe07bbad2 | ||
| 2e3ccb45b7 | |||
| 76d8157fc7 | |||
| 11e10acc00 | |||
| 887ec37b67 | |||
|
|
016788c21e | ||
|
|
48c6a6121c | ||
|
|
eab996f3ac |
1
.signature
Normal file
1
.signature
Normal file
@@ -0,0 +1 @@
|
||||
{"timestamp":1734331212,"signature":"mMrBXdBegYd6TPqNVci9OkWh1H10YU8Ug8KlSpiyNzbXlS5z7O7Rdif3gvTdXK0O07HWmIuszcUoljQIaxkGAYq2g9A85IcvhbWsAAqxjSEZfQPsxFZlJQ9PqU4tfMItk7K1VP1YfcBxitxPHcUeO2IwBYVLx51gg6X/0qHWtkifmZ/cBbGTBNEYE+m7KfRYUyu23kOPMGOCBeULivZO9y/2A0qXkMeBiPo3KQFU6481n4GV6fahyLrG2llfM8xtW8YeouPyt/IMD86at8eeY+E5mW0iXGms9IMLf/DH6vjJnuSEfgMXfjcGnRO0m+RP+ig8HzjbPVty7oAOgfm6Oc1frOP4Cmudk97fIEzC10B0lj2uzFudT5UVPk4Hr6Mf/2ka0m+XTdRNHVRyOYBcHsJQYf0HKW/4jJPwWrSCSk2uE0fPn1sTvMb+i4pXCn7J700b7NMLPFJaWeb6kA2e3v8w5FybshFZWCU6fyLWGn1AR60u0BxL88Hx4VO5UjnJ","publicKey":"LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQm9qQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FZOEFNSUlCaWdLQ0FZRUFzdUhXYUhsZ0I1cVF4ZEJjTlJKSAordHR4SmoxcVY1NTdvMlZaRE1XaXhYRVBkRTBEMVFkT1JIRXNSS1RscmplUXlERU83ZlNQS0ZwZ1A3MU5TTnJCCkFHM2NFSU45aHNQVDhOVmllZmdWem5QTkVMenFkVmdEbFhpb2VpUnV6OERKWFgvblpmU1JWKytwbk9ySTRibG4KS0twelJlNW14OTc1SjhxZ1FvRktKT0NNRlpHdkJMR2MxSzZZaEIzOHJFODZCZzgzbUovWjBEYkVmQjBxZm13cgo2ZDVFUXFsd0E5Y3JZT1YyV1VpWXprSnBLNmJZNzRZNmM1TmpBcEFKeGNiaTFOaDlRVEhUcU44N0ZtMDF0R1ZwCjVNd1pXSWZuYVRUemEvTGZLelR5U0pka0tldEZMVGdkYXpMYlpzUEE2aHBSK0FJRTJhc0tLTi84UUk1N3UzU2cKL2xyMnZKS1IvU2l5eEN1Q20vQWJkYnJMbXk0WjlSdm1jMGdpclA4T0lLQWxBRWZ2TzV5Z2hSKy8vd1RpTFlzUQp1SllDM0V2UE16ZGdKUzdGR2FscnFLZzlPTCsxVzROY05yNWdveVdSUUJ0cktKaWlTZEJVWmVxb0RvSUY5NHpCCndGbzJJT1JFdXFqcU51M3diMWZIM3p1dGdtalFra3IxVjJhd3hmcExLWlROQWdNQkFBRT0KLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tCg"}
|
||||
128
CHANGELOG.md
128
CHANGELOG.md
@@ -6,6 +6,126 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
|
||||
|
||||
Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).
|
||||
|
||||
|
||||
## [2.2.0] - 2024-12-12
|
||||
|
||||
### Added
|
||||
|
||||
- Added `NetworkObject.OwnershipStatus.SessionOwner` to allow Network Objects to be distributable and only owned by the Session Owner. This flag will override all other `OwnershipStatus` flags. (#3175)
|
||||
- Added `UnityTransport.GetEndpoint` method to provide a way to obtain `NetworkEndpoint` information of a connection via client identifier. (#3130)
|
||||
- Added `NetworkTransport.OnEarlyUpdate` and `NetworkTransport.OnPostLateUpdate` methods to provide more control over handling transport related events at the start and end of each frame. (#3113)
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed issue where the server, host, or session owner would not populate the in-scene place `NetworkObject` table if the scene was loaded prior to starting the `NetworkManager`. (#3177)
|
||||
- Fixed issue where the `NetworkObjectIdHash` value could be incorrect when entering play mode while still in prefab edit mode with pending changes and using MPPM. (#3162)
|
||||
- Fixed issue where a sever only `NetworkManager` instance would spawn the actual `NetworkPrefab`'s `GameObject` as opposed to creating an instance of it. (#3160)
|
||||
- Fixed issue where only the session owner (as opposed to all clients) would handle spawning prefab overrides properly when using a distributed authority network topology. (#3160)
|
||||
- Fixed issue where an exception was thrown when calling `NetworkManager.Shutdown` after calling `UnityTransport.Shutdown`. (#3118)
|
||||
- Fixed issue where `NetworkList` properties on in-scene placed `NetworkObject`s could cause small memory leaks when entering playmode. (#3147)
|
||||
- Fixed in-scene `NertworkObject` synchronization issue when loading a scene with currently connected clients connected to a session created by a `NetworkManager` started as a server (i.e. not as a host). (#3133)
|
||||
- Fixed issue where a `NetworkManager` started as a server would not add itself as an observer to in-scene placed `NetworkObject`s instantiated and spawned by a scene loading event. (#3133)
|
||||
- Fixed issue where spawning a player using `NetworkObject.InstantiateAndSpawn` or `NetworkSpawnManager.InstantiateAndSpawn` would not update the `NetworkSpawnManager.PlayerObjects` or assign the newly spawned player to the `NetworkClient.PlayerObject`. (#3122)
|
||||
- Fixed issue where queued UnitTransport (NetworkTransport) message batches were being sent on the next frame. They are now sent at the end of the frame during `PostLateUpdate`. (#3113)
|
||||
- Fixed issue where `NotOwnerRpcTarget` or `OwnerRpcTarget` were not using their replacements `NotAuthorityRpcTarget` and `AuthorityRpcTarget` which would invoke a warning. (#3111)
|
||||
- Fixed issue where client is removed as an observer from spawned objects when their player instance is despawned. (#3110)
|
||||
- Fixed issue where `NetworkAnimator` would statically allocate write buffer space for `Animator` parameters that could cause a write error if the number of parameters exceeded the space allocated. (#3108)
|
||||
|
||||
### Changed
|
||||
|
||||
- In-scene placed `NetworkObject`s have been made distributable when balancing object distribution after a connection event. (#3175)
|
||||
- Optimised `NetworkVariable` and `NetworkTransform` related packets when in Distributed Authority mode.
|
||||
- The Debug Simulator section of the Unity Transport component was removed. This section was not functional anymore and users are now recommended to use the more featureful [Network Simulator](https://docs-multiplayer.unity3d.com/tools/current/tools-network-simulator/) tool from the Multiplayer Tools package instead. (#3121)
|
||||
|
||||
## [2.1.1] - 2024-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- Added ability to edit the `NetworkConfig.AutoSpawnPlayerPrefabClientSide` within the inspector view. (#3097)
|
||||
- Added `IContactEventHandlerWithInfo` that derives from `IContactEventHandler` that can be updated per frame to provide `ContactEventHandlerInfo` information to the `RigidbodyContactEventManager` when processing collisions. (#3094)
|
||||
- `ContactEventHandlerInfo.ProvideNonRigidBodyContactEvents`: When set to true, non-`Rigidbody` collisions with the registered `Rigidbody` will generate contact event notifications. (#3094)
|
||||
- `ContactEventHandlerInfo.HasContactEventPriority`: When set to true, the `Rigidbody` will be prioritized as the instance that generates the event if the `Rigidbody` colliding does not have priority. (#3094)
|
||||
- Added a static `NetworkManager.OnInstantiated` event notification to be able to track when a new `NetworkManager` instance has been instantiated. (#3088)
|
||||
- Added a static `NetworkManager.OnDestroying` event notification to be able to track when an existing `NetworkManager` instance is being destroyed. (#3088)
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed issue where `NetworkPrefabProcessor` would not mark the prefab list as dirty and prevent saving the `DefaultNetworkPrefabs` asset when only imports or only deletes were detected.(#3103)
|
||||
- Fixed an issue where nested `NetworkTransform` components in owner authoritative mode cleared their initial settings on the server, causing improper synchronization. (#3099)
|
||||
- Fixed issue with service not getting synchronized with in-scene placed `NetworkObject` instances when a session owner starts a `SceneEventType.Load` event. (#3096)
|
||||
- Fixed issue with the in-scene network prefab instance update menu tool where it was not properly updating scenes when invoked on the root prefab instance. (#3092)
|
||||
- Fixed an issue where newly synchronizing clients would always receive current `NetworkVariable` values, potentially causing issues with collections if there were pending updates. Now, pending state updates serialize previous values to avoid duplicates on new clients. (#3081)
|
||||
- Fixed issue where changing ownership would mark every `NetworkVariable` dirty. Now, it will only mark any `NetworkVariable` with owner read permissions as dirty and will send/flush any pending updates to all clients prior to sending the change in ownership message. (#3081)
|
||||
- Fixed an issue where transferring ownership of `NetworkVariable` collections didn't update the new owner’s previous value, causing the last added value to be detected as a change during additions or removals. (#3081)
|
||||
- Fixed issue where a client (or server) with no write permissions for a `NetworkVariable` using a standard .NET collection type could still modify the collection which could cause various issues depending upon the modification and collection type. (#3081)
|
||||
- Fixed issue where applying the position and/or rotation to the `NetworkManager.ConnectionApprovalResponse` when connection approval and auto-spawn player prefab were enabled would not apply the position and/or rotation when the player prefab was instantiated. (#3078)
|
||||
- Fixed issue where `NetworkObject.SpawnWithObservers` was not being honored when spawning the player prefab. (#3077)
|
||||
- Fixed issue with the client count not being correct on the host or server side when a client disconnects itself from a session. (#3075)
|
||||
|
||||
### Changed
|
||||
|
||||
- Changed `NetworkConfig.AutoSpawnPlayerPrefabClientSide` is no longer automatically set when starting `NetworkManager`. (#3097)
|
||||
- Updated `NetworkVariableDeltaMessage` so the server now forwards delta state updates from clients immediately, instead of waiting until the end of the frame or the next network tick. (#3081)
|
||||
|
||||
## [2.0.0] - 2024-09-12
|
||||
|
||||
### Added
|
||||
|
||||
- Added tooltips for all of the `NetworkObject` component's properties. (#3052)
|
||||
- Added message size validation to named and unnamed message sending functions for better error messages. (#3049)
|
||||
- Added "Check for NetworkObject Component" property to the Multiplayer->Netcode for GameObjects project settings. When disabled, this will bypass the in-editor `NetworkObject` check on `NetworkBehaviour` components. (#3031)
|
||||
- Added `NetworkTransform.SwitchTransformSpaceWhenParented` property that, when enabled, will handle the world to local, local to world, and local to local transform space transitions when interpolation is enabled. (#3013)
|
||||
- Added `NetworkTransform.TickSyncChildren` that, when enabled, will tick synchronize nested and/or child `NetworkTransform` components to eliminate any potential visual jittering that could occur if the `NetworkTransform` instances get into a state where their state updates are landing on different network ticks. (#3013)
|
||||
- Added `NetworkObject.AllowOwnerToParent` property to provide the ability to allow clients to parent owned objects when running in a client-server network topology. (#3013)
|
||||
- Added `NetworkObject.SyncOwnerTransformWhenParented` property to provide a way to disable applying the server's transform information in the parenting message on the client owner instance which can be useful for owner authoritative motion models. (#3013)
|
||||
- Added `NetcodeEditorBase` editor helper class to provide easier modification and extension of the SDK's components. (#3013)
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed issue where `NetworkAnimator` would send updates to non-observer clients. (#3057)
|
||||
- Fixed issue where an exception could occur when receiving a universal RPC for a `NetworkObject` that has been despawned. (#3052)
|
||||
- Fixed issue where a NetworkObject hidden from a client that is then promoted to be session owner was not being synchronized with newly joining clients.(#3051)
|
||||
- Fixed issue where clients could have a wrong time delta on `NetworkVariableBase` which could prevent from sending delta state updates. (#3045)
|
||||
- Fixed issue where setting a prefab hash value during connection approval but not having a player prefab assigned could cause an exception when spawning a player. (#3042)
|
||||
- Fixed issue where the `NetworkSpawnManager.HandleNetworkObjectShow` could throw an exception if one of the `NetworkObject` components to show was destroyed during the same frame. (#3030)
|
||||
- Fixed issue where the `NetworkManagerHelper` was continuing to check for hierarchy changes when in play mode. (#3026)
|
||||
- Fixed issue with newly/late joined clients and `NetworkTransform` synchronization of parented `NetworkObject` instances. (#3013)
|
||||
- Fixed issue with smooth transitions between transform spaces when interpolation is enabled (requires `NetworkTransform.SwitchTransformSpaceWhenParented` to be enabled). (#3013)
|
||||
|
||||
### Changed
|
||||
|
||||
- Changed `NetworkTransformEditor` now uses `NetworkTransform` as the base type class to assure it doesn't display a foldout group when using the base `NetworkTransform` component class. (#3052)
|
||||
- Changed `NetworkAnimator.Awake` is now a protected virtual method. (#3052)
|
||||
- Changed when invoking `NetworkManager.ConnectionManager.DisconnectClient` during a distributed authority session a more appropriate message is logged. (#3052)
|
||||
- Changed `NetworkTransformEditor` so it now derives from `NetcodeEditorBase`. (#3013)
|
||||
- Changed `NetworkRigidbodyBaseEditor` so it now derives from `NetcodeEditorBase`. (#3013)
|
||||
- Changed `NetworkManagerEditor` so it now derives from `NetcodeEditorBase`. (#3013)
|
||||
|
||||
|
||||
## [2.0.0-pre.4] - 2024-08-21
|
||||
|
||||
### Added
|
||||
|
||||
- Added `NetworkVariable.CheckDirtyState` that is to be used in tandem with collections in order to detect whether the collection or an item within the collection has changed. (#3004)
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed issue where nested `NetworkTransform` components were not getting updated. (#3016)
|
||||
- Fixed issue by adding null checks in `NetworkVariableBase.CanClientRead` and `NetworkVariableBase.CanClientWrite` methods to ensure safe access to `NetworkBehaviour`. (#3012)
|
||||
- Fixed issue where `FixedStringSerializer<T>` was using `NetworkVariableSerialization<byte>.AreEqual` to determine if two bytes were equal causes an exception to be thrown due to no byte serializer having been defined. (#3009)
|
||||
- Fixed Issue where a state with dual triggers, inbound and outbound, could cause a false layer to layer state transition message to be sent to non-authority `NetworkAnimator` instances and cause a warning message to be logged. (#3008)
|
||||
- Fixed issue using collections within `NetworkVariable` where the collection would not detect changes to items or nested items. (#3004)
|
||||
- Fixed issue where `List`, `Dictionary`, and `HashSet` collections would not uniquely duplicate nested collections. (#3004)
|
||||
- Fixed issue where `NotAuthorityTarget` would include the service observer in the list of targets to send the RPC to as opposed to excluding the service observer as it should. (#3000)
|
||||
- Fixed issue where `ProxyRpcTargetGroup` could attempt to send a message if there were no targets to send to. (#3000)
|
||||
|
||||
### Changed
|
||||
|
||||
- Changed `NetworkAnimator` to automatically switch to owner authoritative mode when using a distributed authority network topology. (#3021)
|
||||
- Changed permissions exception thrown in `NetworkList` to exiting early with a logged error that is now a unified permissions message within `NetworkVariableBase`. (#3004)
|
||||
- Changed permissions exception thrown in `NetworkVariable.Value` to exiting early with a logged error that is now a unified permissions message within `NetworkVariableBase`. (#3004)
|
||||
|
||||
|
||||
## [2.0.0-pre.3] - 2024-07-23
|
||||
|
||||
### Added
|
||||
@@ -98,8 +218,8 @@ Additional documentation and release notes are available at [Multiplayer Documen
|
||||
## [2.0.0-exp.2] - 2024-04-02
|
||||
|
||||
### Added
|
||||
- Added updates to all internal messages to account for a distributed authority network session connection. (#2863)
|
||||
- Added `NetworkRigidbodyBase` that provides users with a more customizable network rigidbody, handles both `Rigidbody` and `Rigidbody2D`, and provides an option to make `NetworkTransform` use the rigid body for motion. (#2863)
|
||||
- Added updates to all internal messages to account for a distributed authority network session connection. (#2863)
|
||||
- Added `NetworkRigidbodyBase` that provides users with a more customizable network rigidbody, handles both `Rigidbody` and `Rigidbody2D`, and provides an option to make `NetworkTransform` use the rigid body for motion. (#2863)
|
||||
- For a customized `NetworkRigidbodyBase` class:
|
||||
- `NetworkRigidbodyBase.AutoUpdateKinematicState` provides control on whether the kinematic setting will be automatically set or not when ownership changes.
|
||||
- `NetworkRigidbodyBase.AutoSetKinematicOnDespawn` provides control on whether isKinematic will automatically be set to true when the associated `NetworkObject` is despawned.
|
||||
@@ -235,6 +355,7 @@ Additional documentation and release notes are available at [Multiplayer Documen
|
||||
- Fixed issue where you could not have multiple source network prefab overrides targeting the same network prefab as their override. (#2710)
|
||||
|
||||
### Changed
|
||||
|
||||
- Changed the server or host shutdown so it will now perform a "soft shutdown" when `NetworkManager.Shutdown` is invoked. This will send a disconnect notification to all connected clients and the server-host will wait for all connected clients to disconnect or timeout after a 5 second period before completing the shutdown process. (#2789)
|
||||
- Changed `OnClientDisconnectedCallback` will now return the assigned client identifier on the local client side if the client was approved and assigned one prior to being disconnected. (#2789)
|
||||
- Changed `NetworkTransform.SetState` (and related methods) now are cumulative during a fractional tick period and sent on the next pending tick. (#2777)
|
||||
@@ -247,6 +368,7 @@ Additional documentation and release notes are available at [Multiplayer Documen
|
||||
- Changed in-scene placed `NetworkObject`s now set their `IsSceneObject` value when generating their `GlobalObjectIdHash` value. (#2710)
|
||||
- Changed the default `NetworkConfig.SpawnTimeout` value from 1.0s to 10.0s. (#2710)
|
||||
|
||||
|
||||
## [1.7.1] - 2023-11-15
|
||||
|
||||
### Added
|
||||
@@ -354,7 +476,7 @@ Additional documentation and release notes are available at [Multiplayer Documen
|
||||
- Fixed issue where invalid endpoint addresses were not being detected and returning false from NGO UnityTransport. (#2496)
|
||||
- Fixed some errors that could occur if a connection is lost and the loss is detected when attempting to write to the socket. (#2495)
|
||||
|
||||
## Changed
|
||||
### Changed
|
||||
|
||||
- Adding network prefabs before NetworkManager initialization is now supported. (#2565)
|
||||
- Connecting clients being synchronized now switch to the server's active scene before spawning and synchronizing NetworkObjects. (#2532)
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace Unity.Netcode.Editor.Configuration
|
||||
internal class NetcodeForGameObjectsEditorSettings
|
||||
{
|
||||
internal const string AutoAddNetworkObjectIfNoneExists = "AutoAdd-NetworkObject-When-None-Exist";
|
||||
internal const string CheckForNetworkObject = "NetworkBehaviour-Check-For-NetworkObject";
|
||||
internal const string InstallMultiplayerToolsTipDismissedPlayerPrefKey = "Netcode_Tip_InstallMPTools_Dismissed";
|
||||
|
||||
internal static int GetNetcodeInstallMultiplayerToolTips()
|
||||
@@ -28,7 +29,7 @@ namespace Unity.Netcode.Editor.Configuration
|
||||
{
|
||||
return EditorPrefs.GetBool(AutoAddNetworkObjectIfNoneExists);
|
||||
}
|
||||
|
||||
// Default for this is false
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -36,5 +37,20 @@ namespace Unity.Netcode.Editor.Configuration
|
||||
{
|
||||
EditorPrefs.SetBool(AutoAddNetworkObjectIfNoneExists, autoAddSetting);
|
||||
}
|
||||
|
||||
internal static bool GetCheckForNetworkObjectSetting()
|
||||
{
|
||||
if (EditorPrefs.HasKey(CheckForNetworkObject))
|
||||
{
|
||||
return EditorPrefs.GetBool(CheckForNetworkObject);
|
||||
}
|
||||
// Default for this is true
|
||||
return true;
|
||||
}
|
||||
|
||||
internal static void SetCheckForNetworkObjectSetting(bool checkForNetworkObject)
|
||||
{
|
||||
EditorPrefs.SetBool(CheckForNetworkObject, checkForNetworkObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,6 +81,7 @@ namespace Unity.Netcode.Editor.Configuration
|
||||
|
||||
internal static NetcodeSettingsLabel NetworkObjectsSectionLabel;
|
||||
internal static NetcodeSettingsToggle AutoAddNetworkObjectToggle;
|
||||
internal static NetcodeSettingsToggle CheckForNetworkObjectToggle;
|
||||
internal static NetcodeSettingsLabel MultiplayerToolsLabel;
|
||||
internal static NetcodeSettingsToggle MultiplayerToolTipStatusToggle;
|
||||
|
||||
@@ -103,6 +104,11 @@ namespace Unity.Netcode.Editor.Configuration
|
||||
AutoAddNetworkObjectToggle = new NetcodeSettingsToggle("Auto-Add NetworkObject Component", "When enabled, NetworkObject components are automatically added to GameObjects when NetworkBehaviour components are added first.", 20);
|
||||
}
|
||||
|
||||
if (CheckForNetworkObjectToggle == null)
|
||||
{
|
||||
CheckForNetworkObjectToggle = new NetcodeSettingsToggle("Check for NetworkObject Component", "When disabled, the automatic check on NetworkBehaviours for an associated NetworkObject component will not be performed and Auto-Add NetworkObject Component will be disabled.", 20);
|
||||
}
|
||||
|
||||
if (MultiplayerToolsLabel == null)
|
||||
{
|
||||
MultiplayerToolsLabel = new NetcodeSettingsLabel("Multiplayer Tools", 20);
|
||||
@@ -120,7 +126,9 @@ namespace Unity.Netcode.Editor.Configuration
|
||||
CheckForInitialize();
|
||||
|
||||
var autoAddNetworkObjectSetting = NetcodeForGameObjectsEditorSettings.GetAutoAddNetworkObjectSetting();
|
||||
var checkForNetworkObjectSetting = NetcodeForGameObjectsEditorSettings.GetCheckForNetworkObjectSetting();
|
||||
var multiplayerToolsTipStatus = NetcodeForGameObjectsEditorSettings.GetNetcodeInstallMultiplayerToolTips() == 0;
|
||||
|
||||
var settings = NetcodeForGameObjectsProjectSettings.instance;
|
||||
var generateDefaultPrefabs = settings.GenerateDefaultNetworkPrefabs;
|
||||
var networkPrefabsPath = settings.TempNetworkPrefabsPath;
|
||||
@@ -134,7 +142,13 @@ namespace Unity.Netcode.Editor.Configuration
|
||||
{
|
||||
GUILayout.BeginVertical("Box");
|
||||
NetworkObjectsSectionLabel.DrawLabel();
|
||||
autoAddNetworkObjectSetting = AutoAddNetworkObjectToggle.DrawToggle(autoAddNetworkObjectSetting);
|
||||
|
||||
autoAddNetworkObjectSetting = AutoAddNetworkObjectToggle.DrawToggle(autoAddNetworkObjectSetting, checkForNetworkObjectSetting);
|
||||
checkForNetworkObjectSetting = CheckForNetworkObjectToggle.DrawToggle(checkForNetworkObjectSetting);
|
||||
if (autoAddNetworkObjectSetting && !checkForNetworkObjectSetting)
|
||||
{
|
||||
autoAddNetworkObjectSetting = false;
|
||||
}
|
||||
GUILayout.EndVertical();
|
||||
|
||||
GUILayout.BeginVertical("Box");
|
||||
@@ -184,6 +198,7 @@ namespace Unity.Netcode.Editor.Configuration
|
||||
if (EditorGUI.EndChangeCheck())
|
||||
{
|
||||
NetcodeForGameObjectsEditorSettings.SetAutoAddNetworkObjectSetting(autoAddNetworkObjectSetting);
|
||||
NetcodeForGameObjectsEditorSettings.SetCheckForNetworkObjectSetting(checkForNetworkObjectSetting);
|
||||
NetcodeForGameObjectsEditorSettings.SetNetcodeInstallMultiplayerToolTips(multiplayerToolsTipStatus ? 0 : 1);
|
||||
settings.GenerateDefaultNetworkPrefabs = generateDefaultPrefabs;
|
||||
settings.TempNetworkPrefabsPath = networkPrefabsPath;
|
||||
@@ -213,10 +228,13 @@ namespace Unity.Netcode.Editor.Configuration
|
||||
{
|
||||
private GUIContent m_ToggleContent;
|
||||
|
||||
public bool DrawToggle(bool currentSetting)
|
||||
public bool DrawToggle(bool currentSetting, bool enabled = true)
|
||||
{
|
||||
EditorGUIUtility.labelWidth = m_LabelSize;
|
||||
return EditorGUILayout.Toggle(m_ToggleContent, currentSetting, m_LayoutWidth);
|
||||
GUI.enabled = enabled;
|
||||
var returnValue = EditorGUILayout.Toggle(m_ToggleContent, currentSetting, m_LayoutWidth);
|
||||
GUI.enabled = true;
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
public NetcodeSettingsToggle(string labelText, string toolTip, float layoutOffset)
|
||||
|
||||
@@ -132,7 +132,7 @@ namespace Unity.Netcode.Editor.Configuration
|
||||
|
||||
// Process the imported and deleted assets
|
||||
var markDirty = ProcessImportedAssets(importedAssets);
|
||||
markDirty &= ProcessDeletedAssets(deletedAssets);
|
||||
markDirty |= ProcessDeletedAssets(deletedAssets);
|
||||
|
||||
if (markDirty)
|
||||
{
|
||||
|
||||
62
Editor/NetcodeEditorBase.cs
Normal file
62
Editor/NetcodeEditorBase.cs
Normal file
@@ -0,0 +1,62 @@
|
||||
using System;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Unity.Netcode.Editor
|
||||
{
|
||||
/// <summary>
|
||||
/// The base Netcode Editor helper class to display derived <see cref="MonoBehaviour"/> based components <br />
|
||||
/// where each child generation's properties will be displayed within a FoldoutHeaderGroup.
|
||||
/// </summary>
|
||||
[CanEditMultipleObjects]
|
||||
public partial class NetcodeEditorBase<TT> : UnityEditor.Editor where TT : MonoBehaviour
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public virtual void OnEnable()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Helper method to draw the properties of the specified child type <typeparamref name="T"/> component within a FoldoutHeaderGroup.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The specific child type that should have its properties drawn.</typeparam>
|
||||
/// <param name="type">The component type of the <see cref="UnityEditor.Editor.target"/>.</param>
|
||||
/// <param name="displayProperties">The <see cref="Action"/> to invoke that will draw the type <typeparamref name="T"/> properties.</param>
|
||||
/// <param name="expanded">The <typeparamref name="T"/> current expanded property value</param>
|
||||
/// <param name="setExpandedProperty">The <see cref="Action{bool}"/> invoked to apply the updated <paramref name="expanded"/> value.</param>
|
||||
protected void DrawFoldOutGroup<T>(Type type, Action displayProperties, bool expanded, Action<bool> setExpandedProperty)
|
||||
{
|
||||
var baseClass = target as TT;
|
||||
EditorGUI.BeginChangeCheck();
|
||||
serializedObject.Update();
|
||||
var currentClass = typeof(T);
|
||||
if (type.IsSubclassOf(currentClass) || (!type.IsSubclassOf(currentClass) && currentClass.IsSubclassOf(typeof(TT))))
|
||||
{
|
||||
var expandedValue = EditorGUILayout.BeginFoldoutHeaderGroup(expanded, $"{currentClass.Name} Properties");
|
||||
if (expandedValue)
|
||||
{
|
||||
EditorGUILayout.EndFoldoutHeaderGroup();
|
||||
displayProperties.Invoke();
|
||||
}
|
||||
else
|
||||
{
|
||||
EditorGUILayout.EndFoldoutHeaderGroup();
|
||||
}
|
||||
EditorGUILayout.Space();
|
||||
setExpandedProperty.Invoke(expandedValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
displayProperties.Invoke();
|
||||
}
|
||||
serializedObject.ApplyModifiedProperties();
|
||||
EditorGUI.EndChangeCheck();
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void OnInspectorGUI()
|
||||
{
|
||||
serializedObject.ApplyModifiedProperties();
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Editor/NetcodeEditorBase.cs.meta
Normal file
2
Editor/NetcodeEditorBase.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4ce97256a2d80f94bb340e13c71a24b8
|
||||
@@ -301,9 +301,8 @@ namespace Unity.Netcode.Editor
|
||||
|
||||
expanded = false;
|
||||
}
|
||||
|
||||
serializedObject.ApplyModifiedProperties();
|
||||
EditorGUI.EndChangeCheck();
|
||||
serializedObject.ApplyModifiedProperties();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -352,6 +351,12 @@ namespace Unity.Netcode.Editor
|
||||
return;
|
||||
}
|
||||
|
||||
// If this automatic check is disabled, then do not perform this check.
|
||||
if (!NetcodeForGameObjectsEditorSettings.GetCheckForNetworkObjectSetting())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Now get the root parent transform to the current GameObject (or itself)
|
||||
var rootTransform = GetRootParentTransform(gameObject.transform);
|
||||
if (!rootTransform.TryGetComponent<NetworkManager>(out var networkManager))
|
||||
|
||||
@@ -13,7 +13,7 @@ namespace Unity.Netcode.Editor
|
||||
/// </summary>
|
||||
[CustomEditor(typeof(NetworkManager), true)]
|
||||
[CanEditMultipleObjects]
|
||||
public class NetworkManagerEditor : UnityEditor.Editor
|
||||
public class NetworkManagerEditor : NetcodeEditorBase<NetworkManager>
|
||||
{
|
||||
private static GUIStyle s_CenteredWordWrappedLabelStyle;
|
||||
private static GUIStyle s_HelpBoxStyle;
|
||||
@@ -31,6 +31,7 @@ namespace Unity.Netcode.Editor
|
||||
private SerializedProperty m_NetworkTransportProperty;
|
||||
private SerializedProperty m_TickRateProperty;
|
||||
#if MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
private SerializedProperty m_AutoSpawnPlayerPrefabClientSide;
|
||||
private SerializedProperty m_NetworkTopologyProperty;
|
||||
#endif
|
||||
private SerializedProperty m_ClientConnectionBufferTimeoutProperty;
|
||||
@@ -104,6 +105,11 @@ namespace Unity.Netcode.Editor
|
||||
m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate");
|
||||
#if MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
m_NetworkTopologyProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTopology");
|
||||
// Only display the auto spawn property when the distributed authority network topology is selected
|
||||
if (m_NetworkManager.NetworkConfig.NetworkTopology == NetworkTopologyTypes.DistributedAuthority)
|
||||
{
|
||||
m_AutoSpawnPlayerPrefabClientSide = m_NetworkConfigProperty.FindPropertyRelative("AutoSpawnPlayerPrefabClientSide");
|
||||
}
|
||||
#endif
|
||||
m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout");
|
||||
m_ConnectionApprovalProperty = m_NetworkConfigProperty.FindPropertyRelative("ConnectionApproval");
|
||||
@@ -120,8 +126,6 @@ namespace Unity.Netcode.Editor
|
||||
#if MULTIPLAYER_TOOLS
|
||||
m_NetworkMessageMetrics = m_NetworkConfigProperty.FindPropertyRelative("NetworkMessageMetrics");
|
||||
#endif
|
||||
|
||||
|
||||
m_RpcHashSizeProperty = m_NetworkConfigProperty.FindPropertyRelative("RpcHashSize");
|
||||
m_PrefabsList = m_NetworkConfigProperty
|
||||
.FindPropertyRelative(nameof(NetworkConfig.Prefabs))
|
||||
@@ -144,6 +148,11 @@ namespace Unity.Netcode.Editor
|
||||
m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate");
|
||||
#if MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
m_NetworkTopologyProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTopology");
|
||||
// Only display the auto spawn property when the distributed authority network topology is selected
|
||||
if (m_NetworkManager.NetworkConfig.NetworkTopology == NetworkTopologyTypes.DistributedAuthority)
|
||||
{
|
||||
m_AutoSpawnPlayerPrefabClientSide = m_NetworkConfigProperty.FindPropertyRelative("AutoSpawnPlayerPrefabClientSide");
|
||||
}
|
||||
#endif
|
||||
m_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout");
|
||||
m_ConnectionApprovalProperty = m_NetworkConfigProperty.FindPropertyRelative("ConnectionApproval");
|
||||
@@ -168,23 +177,16 @@ namespace Unity.Netcode.Editor
|
||||
.FindPropertyRelative(nameof(NetworkPrefabs.NetworkPrefabsLists));
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void OnInspectorGUI()
|
||||
private void DisplayNetworkManagerProperties()
|
||||
{
|
||||
Initialize();
|
||||
CheckNullProperties();
|
||||
|
||||
#if !MULTIPLAYER_TOOLS
|
||||
DrawInstallMultiplayerToolsTip();
|
||||
#endif
|
||||
|
||||
if (!m_NetworkManager.IsServer && !m_NetworkManager.IsClient)
|
||||
{
|
||||
serializedObject.Update();
|
||||
|
||||
EditorGUILayout.PropertyField(m_RunInBackgroundProperty);
|
||||
EditorGUILayout.PropertyField(m_LogLevelProperty);
|
||||
|
||||
EditorGUILayout.Space();
|
||||
|
||||
EditorGUILayout.LabelField("Network Settings", EditorStyles.boldLabel);
|
||||
#if MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
EditorGUILayout.PropertyField(m_NetworkTopologyProperty);
|
||||
@@ -230,8 +232,17 @@ namespace Unity.Netcode.Editor
|
||||
EditorGUILayout.Space();
|
||||
EditorGUILayout.LabelField("Prefab Settings", EditorStyles.boldLabel);
|
||||
EditorGUILayout.PropertyField(m_ForceSamePrefabsProperty);
|
||||
#if MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
// Only display the auto spawn property when the distributed authority network topology is selected
|
||||
if (m_NetworkManager.NetworkConfig.NetworkTopology == NetworkTopologyTypes.DistributedAuthority)
|
||||
{
|
||||
EditorGUILayout.PropertyField(m_AutoSpawnPlayerPrefabClientSide, new GUIContent("Auto Spawn Player Prefab"));
|
||||
}
|
||||
#endif
|
||||
EditorGUILayout.PropertyField(m_PlayerPrefabProperty, new GUIContent("Default Player Prefab"));
|
||||
|
||||
|
||||
|
||||
if (m_NetworkManager.NetworkConfig.HasOldPrefabList())
|
||||
{
|
||||
EditorGUILayout.HelpBox("Network Prefabs serialized in old format. Migrate to new format to edit the list.", MessageType.Info);
|
||||
@@ -298,49 +309,51 @@ namespace Unity.Netcode.Editor
|
||||
}
|
||||
|
||||
serializedObject.ApplyModifiedProperties();
|
||||
}
|
||||
}
|
||||
|
||||
private void DisplayCallToActionButtons()
|
||||
{
|
||||
if (!m_NetworkManager.IsServer && !m_NetworkManager.IsClient)
|
||||
{
|
||||
string buttonDisabledReasonSuffix = "";
|
||||
|
||||
// Start buttons below
|
||||
if (!EditorApplication.isPlaying)
|
||||
{
|
||||
string buttonDisabledReasonSuffix = "";
|
||||
buttonDisabledReasonSuffix = ". This can only be done in play mode";
|
||||
GUI.enabled = false;
|
||||
}
|
||||
|
||||
if (!EditorApplication.isPlaying)
|
||||
if (m_NetworkManager.NetworkConfig.NetworkTopology == NetworkTopologyTypes.ClientServer)
|
||||
{
|
||||
if (GUILayout.Button(new GUIContent("Start Host", "Starts a host instance" + buttonDisabledReasonSuffix)))
|
||||
{
|
||||
buttonDisabledReasonSuffix = ". This can only be done in play mode";
|
||||
GUI.enabled = false;
|
||||
m_NetworkManager.StartHost();
|
||||
}
|
||||
|
||||
if (m_NetworkManager.NetworkConfig.NetworkTopology == NetworkTopologyTypes.ClientServer)
|
||||
if (GUILayout.Button(new GUIContent("Start Server", "Starts a server instance" + buttonDisabledReasonSuffix)))
|
||||
{
|
||||
if (GUILayout.Button(new GUIContent("Start Host", "Starts a host instance" + buttonDisabledReasonSuffix)))
|
||||
{
|
||||
m_NetworkManager.StartHost();
|
||||
}
|
||||
|
||||
if (GUILayout.Button(new GUIContent("Start Server", "Starts a server instance" + buttonDisabledReasonSuffix)))
|
||||
{
|
||||
m_NetworkManager.StartServer();
|
||||
}
|
||||
|
||||
if (GUILayout.Button(new GUIContent("Start Client", "Starts a client instance" + buttonDisabledReasonSuffix)))
|
||||
{
|
||||
m_NetworkManager.StartClient();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (GUILayout.Button(new GUIContent("Start Client", "Starts a distributed authority client instance" + buttonDisabledReasonSuffix)))
|
||||
{
|
||||
m_NetworkManager.StartClient();
|
||||
}
|
||||
m_NetworkManager.StartServer();
|
||||
}
|
||||
|
||||
|
||||
if (!EditorApplication.isPlaying)
|
||||
if (GUILayout.Button(new GUIContent("Start Client", "Starts a client instance" + buttonDisabledReasonSuffix)))
|
||||
{
|
||||
GUI.enabled = true;
|
||||
m_NetworkManager.StartClient();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (GUILayout.Button(new GUIContent("Start Client", "Starts a distributed authority client instance" + buttonDisabledReasonSuffix)))
|
||||
{
|
||||
m_NetworkManager.StartClient();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (!EditorApplication.isPlaying)
|
||||
{
|
||||
GUI.enabled = true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -368,6 +381,21 @@ namespace Unity.Netcode.Editor
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void OnInspectorGUI()
|
||||
{
|
||||
var networkManager = target as NetworkManager;
|
||||
Initialize();
|
||||
CheckNullProperties();
|
||||
#if !MULTIPLAYER_TOOLS
|
||||
DrawInstallMultiplayerToolsTip();
|
||||
#endif
|
||||
void SetExpanded(bool expanded) { networkManager.NetworkManagerExpanded = expanded; };
|
||||
DrawFoldOutGroup<NetworkManager>(networkManager.GetType(), DisplayNetworkManagerProperties, networkManager.NetworkManagerExpanded, SetExpanded);
|
||||
DisplayCallToActionButtons();
|
||||
base.OnInspectorGUI();
|
||||
}
|
||||
|
||||
private static void DrawInstallMultiplayerToolsTip()
|
||||
{
|
||||
const string getToolsText = "Access additional tools for multiplayer development by installing the Multiplayer Tools package in the Package Manager.";
|
||||
|
||||
@@ -61,6 +61,12 @@ namespace Unity.Netcode.Editor
|
||||
{
|
||||
s_LastKnownNetworkManagerParents.Clear();
|
||||
ScenesInBuildActiveSceneCheck();
|
||||
EditorApplication.hierarchyChanged -= EditorApplication_hierarchyChanged;
|
||||
break;
|
||||
}
|
||||
case PlayModeStateChange.EnteredEditMode:
|
||||
{
|
||||
EditorApplication.hierarchyChanged += EditorApplication_hierarchyChanged;
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -110,6 +116,12 @@ namespace Unity.Netcode.Editor
|
||||
/// </summary>
|
||||
private static void EditorApplication_hierarchyChanged()
|
||||
{
|
||||
if (Application.isPlaying)
|
||||
{
|
||||
EditorApplication.hierarchyChanged -= EditorApplication_hierarchyChanged;
|
||||
return;
|
||||
}
|
||||
|
||||
var allNetworkManagers = Resources.FindObjectsOfTypeAll<NetworkManager>();
|
||||
foreach (var networkManager in allNetworkManagers)
|
||||
{
|
||||
|
||||
@@ -88,6 +88,14 @@ namespace Unity.Netcode.Editor
|
||||
|
||||
while (observerClientIds.MoveNext())
|
||||
{
|
||||
if (!m_NetworkObject.NetworkManager.ConnectedClients.ContainsKey(observerClientIds.Current))
|
||||
{
|
||||
if ((observerClientIds.Current == 0 && m_NetworkObject.NetworkManager.IsHost) || observerClientIds.Current > 0)
|
||||
{
|
||||
Debug.LogWarning($"Client-{observerClientIds.Current} is listed as an observer but is not connected!");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (m_NetworkObject.NetworkManager.ConnectedClients[observerClientIds.Current].PlayerObject != null)
|
||||
{
|
||||
EditorGUILayout.ObjectField($"ClientId: {observerClientIds.Current}", m_NetworkObject.NetworkManager.ConnectedClients[observerClientIds.Current].PlayerObject, typeof(GameObject), false);
|
||||
@@ -107,6 +115,10 @@ namespace Unity.Netcode.Editor
|
||||
EditorGUI.BeginChangeCheck();
|
||||
serializedObject.UpdateIfRequiredOrScript();
|
||||
DrawPropertiesExcluding(serializedObject, k_HiddenFields);
|
||||
if (m_NetworkObject.IsOwnershipSessionOwner)
|
||||
{
|
||||
m_NetworkObject.Ownership = NetworkObject.OwnershipStatus.SessionOwner;
|
||||
}
|
||||
serializedObject.ApplyModifiedProperties();
|
||||
EditorGUI.EndChangeCheck();
|
||||
|
||||
@@ -186,8 +198,8 @@ namespace Unity.Netcode.Editor
|
||||
// The below can cause visual anomalies and/or throws an exception within the EditorGUI itself (index out of bounds of the array). and has
|
||||
// The visual anomaly is when you select one field it is set in the drop down but then the flags selection in the popup menu selects more items
|
||||
// even though if you exit the popup menu the flag setting is correct.
|
||||
//var ownership = (NetworkObject.OwnershipStatus)EditorGUI.EnumFlagsField(position, label, (NetworkObject.OwnershipStatus)property.enumValueFlag);
|
||||
//property.enumValueFlag = (int)ownership;
|
||||
// var ownership = (NetworkObject.OwnershipStatus)EditorGUI.EnumFlagsField(position, label, (NetworkObject.OwnershipStatus)property.enumValueFlag);
|
||||
// property.enumValueFlag = (int)ownership;
|
||||
EditorGUI.EndDisabledGroup();
|
||||
EditorGUI.EndProperty();
|
||||
}
|
||||
|
||||
42
Editor/NetworkRigidbodyBaseEditor.cs
Normal file
42
Editor/NetworkRigidbodyBaseEditor.cs
Normal file
@@ -0,0 +1,42 @@
|
||||
#if COM_UNITY_MODULES_PHYSICS || COM_UNITY_MODULES_PHYSICS2D
|
||||
using Unity.Netcode.Components;
|
||||
using UnityEditor;
|
||||
|
||||
namespace Unity.Netcode.Editor
|
||||
{
|
||||
[CustomEditor(typeof(NetworkRigidbodyBase), true)]
|
||||
[CanEditMultipleObjects]
|
||||
public class NetworkRigidbodyBaseEditor : NetcodeEditorBase<NetworkBehaviour>
|
||||
{
|
||||
private SerializedProperty m_UseRigidBodyForMotion;
|
||||
private SerializedProperty m_AutoUpdateKinematicState;
|
||||
private SerializedProperty m_AutoSetKinematicOnDespawn;
|
||||
|
||||
|
||||
public override void OnEnable()
|
||||
{
|
||||
m_UseRigidBodyForMotion = serializedObject.FindProperty(nameof(NetworkRigidbodyBase.UseRigidBodyForMotion));
|
||||
m_AutoUpdateKinematicState = serializedObject.FindProperty(nameof(NetworkRigidbodyBase.AutoUpdateKinematicState));
|
||||
m_AutoSetKinematicOnDespawn = serializedObject.FindProperty(nameof(NetworkRigidbodyBase.AutoSetKinematicOnDespawn));
|
||||
|
||||
base.OnEnable();
|
||||
}
|
||||
|
||||
private void DisplayNetworkRigidbodyProperties()
|
||||
{
|
||||
EditorGUILayout.PropertyField(m_UseRigidBodyForMotion);
|
||||
EditorGUILayout.PropertyField(m_AutoUpdateKinematicState);
|
||||
EditorGUILayout.PropertyField(m_AutoSetKinematicOnDespawn);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void OnInspectorGUI()
|
||||
{
|
||||
var networkRigidbodyBase = target as NetworkRigidbodyBase;
|
||||
void SetExpanded(bool expanded) { networkRigidbodyBase.NetworkRigidbodyBaseExpanded = expanded; };
|
||||
DrawFoldOutGroup<NetworkRigidbodyBase>(networkRigidbodyBase.GetType(), DisplayNetworkRigidbodyProperties, networkRigidbodyBase.NetworkRigidbodyBaseExpanded, SetExpanded);
|
||||
base.OnInspectorGUI();
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
2
Editor/NetworkRigidbodyBaseEditor.cs.meta
Normal file
2
Editor/NetworkRigidbodyBaseEditor.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 06561c57f81a6354f8bb16076f1de3a9
|
||||
@@ -8,8 +8,11 @@ namespace Unity.Netcode.Editor
|
||||
/// The <see cref="CustomEditor"/> for <see cref="NetworkTransform"/>
|
||||
/// </summary>
|
||||
[CustomEditor(typeof(NetworkTransform), true)]
|
||||
public class NetworkTransformEditor : UnityEditor.Editor
|
||||
[CanEditMultipleObjects]
|
||||
public class NetworkTransformEditor : NetcodeEditorBase<NetworkTransform>
|
||||
{
|
||||
private SerializedProperty m_SwitchTransformSpaceWhenParented;
|
||||
private SerializedProperty m_TickSyncChildren;
|
||||
private SerializedProperty m_UseUnreliableDeltas;
|
||||
private SerializedProperty m_SyncPositionXProperty;
|
||||
private SerializedProperty m_SyncPositionYProperty;
|
||||
@@ -39,8 +42,10 @@ namespace Unity.Netcode.Editor
|
||||
private static GUIContent s_ScaleLabel = EditorGUIUtility.TrTextContent("Scale");
|
||||
|
||||
/// <inheritdoc/>
|
||||
public virtual void OnEnable()
|
||||
public override void OnEnable()
|
||||
{
|
||||
m_SwitchTransformSpaceWhenParented = serializedObject.FindProperty(nameof(NetworkTransform.SwitchTransformSpaceWhenParented));
|
||||
m_TickSyncChildren = serializedObject.FindProperty(nameof(NetworkTransform.TickSyncChildren));
|
||||
m_UseUnreliableDeltas = serializedObject.FindProperty(nameof(NetworkTransform.UseUnreliableDeltas));
|
||||
m_SyncPositionXProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionX));
|
||||
m_SyncPositionYProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionY));
|
||||
@@ -61,10 +66,10 @@ namespace Unity.Netcode.Editor
|
||||
m_UseHalfFloatPrecision = serializedObject.FindProperty(nameof(NetworkTransform.UseHalfFloatPrecision));
|
||||
m_SlerpPosition = serializedObject.FindProperty(nameof(NetworkTransform.SlerpPosition));
|
||||
m_AuthorityMode = serializedObject.FindProperty(nameof(NetworkTransform.AuthorityMode));
|
||||
base.OnEnable();
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void OnInspectorGUI()
|
||||
private void DisplayNetworkTransformProperties()
|
||||
{
|
||||
var networkTransform = target as NetworkTransform;
|
||||
EditorGUILayout.LabelField("Axis to Synchronize", EditorStyles.boldLabel);
|
||||
@@ -141,9 +146,15 @@ namespace Unity.Netcode.Editor
|
||||
EditorGUILayout.PropertyField(m_ScaleThresholdProperty);
|
||||
EditorGUILayout.Space();
|
||||
EditorGUILayout.LabelField("Delivery", EditorStyles.boldLabel);
|
||||
EditorGUILayout.PropertyField(m_TickSyncChildren);
|
||||
EditorGUILayout.PropertyField(m_UseUnreliableDeltas);
|
||||
EditorGUILayout.Space();
|
||||
EditorGUILayout.LabelField("Configurations", EditorStyles.boldLabel);
|
||||
EditorGUILayout.PropertyField(m_SwitchTransformSpaceWhenParented);
|
||||
if (m_SwitchTransformSpaceWhenParented.boolValue)
|
||||
{
|
||||
m_TickSyncChildren.boolValue = true;
|
||||
}
|
||||
EditorGUILayout.PropertyField(m_InLocalSpaceProperty);
|
||||
if (!networkTransform.HideInterpolateValue)
|
||||
{
|
||||
@@ -163,8 +174,7 @@ namespace Unity.Netcode.Editor
|
||||
|
||||
#if COM_UNITY_MODULES_PHYSICS
|
||||
// if rigidbody is present but network rigidbody is not present
|
||||
var go = ((NetworkTransform)target).gameObject;
|
||||
if (go.TryGetComponent<Rigidbody>(out _) && go.TryGetComponent<NetworkRigidbody>(out _) == false)
|
||||
if (networkTransform.TryGetComponent<Rigidbody>(out _) && networkTransform.TryGetComponent<NetworkRigidbody>(out _) == false)
|
||||
{
|
||||
EditorGUILayout.HelpBox("This GameObject contains a Rigidbody but no NetworkRigidbody.\n" +
|
||||
"Add a NetworkRigidbody component to improve Rigidbody synchronization.", MessageType.Warning);
|
||||
@@ -172,14 +182,23 @@ namespace Unity.Netcode.Editor
|
||||
#endif // COM_UNITY_MODULES_PHYSICS
|
||||
|
||||
#if COM_UNITY_MODULES_PHYSICS2D
|
||||
if (go.TryGetComponent<Rigidbody2D>(out _) && go.TryGetComponent<NetworkRigidbody2D>(out _) == false)
|
||||
if (networkTransform.TryGetComponent<Rigidbody2D>(out _) && networkTransform.TryGetComponent<NetworkRigidbody2D>(out _) == false)
|
||||
{
|
||||
EditorGUILayout.HelpBox("This GameObject contains a Rigidbody2D but no NetworkRigidbody2D.\n" +
|
||||
"Add a NetworkRigidbody2D component to improve Rigidbody2D synchronization.", MessageType.Warning);
|
||||
}
|
||||
#endif // COM_UNITY_MODULES_PHYSICS2D
|
||||
}
|
||||
|
||||
serializedObject.ApplyModifiedProperties();
|
||||
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void OnInspectorGUI()
|
||||
{
|
||||
var networkTransform = target as NetworkTransform;
|
||||
void SetExpanded(bool expanded) { networkTransform.NetworkTransformExpanded = expanded; };
|
||||
DrawFoldOutGroup<NetworkTransform>(networkTransform.GetType(), DisplayNetworkTransformProperties, networkTransform.NetworkTransformExpanded, SetExpanded);
|
||||
base.OnInspectorGUI();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,16 +34,6 @@
|
||||
"expression": "",
|
||||
"define": "COM_UNITY_MODULES_ANIMATION"
|
||||
},
|
||||
{
|
||||
"name": "com.unity.modules.physics",
|
||||
"expression": "",
|
||||
"define": "COM_UNITY_MODULES_PHYSICS"
|
||||
},
|
||||
{
|
||||
"name": "com.unity.modules.physics2d",
|
||||
"expression": "",
|
||||
"define": "COM_UNITY_MODULES_PHYSICS2D"
|
||||
},
|
||||
{
|
||||
"name": "com.unity.services.relay",
|
||||
"expression": "1.0",
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
Unity Companion License (UCL License)
|
||||
|
||||
com.unity.netcode.gameobjects copyright © 2021-2024 Unity Technologies
|
||||
com.unity.netcode.gameobjects copyright © 2024 Unity Technologies
|
||||
Licensed under the Unity Companion License for Unity-dependent projects (see https://unity3d.com/legal/licenses/unity_companion_license).
|
||||
Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. Please review the license for details on these and other terms and conditions.
|
||||
|
||||
|
||||
|
||||
@@ -1,501 +0,0 @@
|
||||
using Unity.Mathematics;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Unity.Netcode.Components
|
||||
{
|
||||
|
||||
#pragma warning disable IDE0001
|
||||
/// <summary>
|
||||
/// A subclass of <see cref="NetworkTransform"/> that supports basic client anticipation - the client
|
||||
/// can set a value on the belief that the server will update it to reflect the same value in a future update
|
||||
/// (i.e., as the result of an RPC call). This value can then be adjusted as new updates from the server come in,
|
||||
/// in three basic modes:
|
||||
///
|
||||
/// <list type="bullet">
|
||||
///
|
||||
/// <item><b>Snap:</b> In this mode (with <see cref="StaleDataHandling"/> set to
|
||||
/// <see cref="StaleDataHandling.Ignore"/> and no <see cref="NetworkBehaviour.OnReanticipate"/> callback),
|
||||
/// the moment a more up-to-date value is received from the authority, it will simply replace the anticipated value,
|
||||
/// resulting in a "snap" to the new value if it is different from the anticipated value.</item>
|
||||
///
|
||||
/// <item><b>Smooth:</b> In this mode (with <see cref="StaleDataHandling"/> set to
|
||||
/// <see cref="Netcode.StaleDataHandling.Ignore"/> and an <see cref="NetworkBehaviour.OnReanticipate"/> callback that calls
|
||||
/// <see cref="Smooth"/> from the anticipated value to the authority value with an appropriate
|
||||
/// <see cref="Mathf.Lerp"/>-style smooth function), when a more up-to-date value is received from the authority,
|
||||
/// it will interpolate over time from an incorrect anticipated value to the correct authoritative value.</item>
|
||||
///
|
||||
/// <item><b>Constant Reanticipation:</b> In this mode (with <see cref="StaleDataHandling"/> set to
|
||||
/// <see cref="Netcode.StaleDataHandling.Reanticipate"/> and an <see cref="NetworkBehaviour.OnReanticipate"/> that calculates a
|
||||
/// new anticipated value based on the current authoritative value), when a more up-to-date value is received from
|
||||
/// the authority, user code calculates a new anticipated value, possibly calling <see cref="Smooth"/> to interpolate
|
||||
/// between the previous anticipation and the new anticipation. This is useful for values that change frequently and
|
||||
/// need to constantly be re-evaluated, as opposed to values that change only in response to user action and simply
|
||||
/// need a one-time anticipation when the user performs that action.</item>
|
||||
///
|
||||
/// </list>
|
||||
///
|
||||
/// Note that these three modes may be combined. For example, if an <see cref="NetworkBehaviour.OnReanticipate"/> callback
|
||||
/// does not call either <see cref="Smooth"/> or one of the Anticipate methods, the result will be a snap to the
|
||||
/// authoritative value, enabling for a callback that may conditionally call <see cref="Smooth"/> when the
|
||||
/// difference between the anticipated and authoritative values is within some threshold, but fall back to
|
||||
/// snap behavior if the difference is too large.
|
||||
/// </summary>
|
||||
#pragma warning restore IDE0001
|
||||
[DisallowMultipleComponent]
|
||||
[AddComponentMenu("Netcode/Anticipated Network Transform")]
|
||||
public class AnticipatedNetworkTransform : NetworkTransform
|
||||
{
|
||||
|
||||
#if UNITY_EDITOR
|
||||
internal override bool HideInterpolateValue => true;
|
||||
#endif
|
||||
|
||||
public struct TransformState
|
||||
{
|
||||
public Vector3 Position;
|
||||
public Quaternion Rotation;
|
||||
public Vector3 Scale;
|
||||
}
|
||||
|
||||
private TransformState m_AuthoritativeTransform = new TransformState();
|
||||
private TransformState m_AnticipatedTransform = new TransformState();
|
||||
private TransformState m_PreviousAnticipatedTransform = new TransformState();
|
||||
private ulong m_LastAnticipaionCounter;
|
||||
private ulong m_LastAuthorityUpdateCounter;
|
||||
|
||||
private TransformState m_SmoothFrom;
|
||||
private TransformState m_SmoothTo;
|
||||
private float m_SmoothDuration;
|
||||
private float m_CurrentSmoothTime;
|
||||
|
||||
private bool m_OutstandingAuthorityChange = false;
|
||||
|
||||
#if UNITY_EDITOR
|
||||
private void Reset()
|
||||
{
|
||||
// Anticipation + smoothing is a form of interpolation, and adding NetworkTransform's buffered interpolation
|
||||
// makes the anticipation get weird, so we default it to false.
|
||||
Interpolate = false;
|
||||
}
|
||||
#endif
|
||||
|
||||
#pragma warning disable IDE0001
|
||||
/// <summary>
|
||||
/// Defines what the behavior should be if we receive a value from the server with an earlier associated
|
||||
/// time value than the anticipation time value.
|
||||
/// <br/><br/>
|
||||
/// If this is <see cref="Netcode.StaleDataHandling.Ignore"/>, the stale data will be ignored and the authoritative
|
||||
/// value will not replace the anticipated value until the anticipation time is reached. <see cref="OnAuthoritativeValueChanged"/>
|
||||
/// and <see cref="OnReanticipate"/> will also not be invoked for this stale data.
|
||||
/// <br/><br/>
|
||||
/// If this is <see cref="Netcode.StaleDataHandling.Reanticipate"/>, the stale data will replace the anticipated data and
|
||||
/// <see cref="OnAuthoritativeValueChanged"/> and <see cref="OnReanticipate"/> will be invoked.
|
||||
/// In this case, the authoritativeTime value passed to <see cref="OnReanticipate"/> will be lower than
|
||||
/// the anticipationTime value, and that callback can be used to calculate a new anticipated value.
|
||||
/// </summary>
|
||||
#pragma warning restore IDE0001
|
||||
public StaleDataHandling StaleDataHandling = StaleDataHandling.Reanticipate;
|
||||
|
||||
/// <summary>
|
||||
/// Contains the current state of this transform on the server side.
|
||||
/// Note that, on the server side, this gets updated at the end of the frame, and will not immediately reflect
|
||||
/// changes to the transform.
|
||||
/// </summary>
|
||||
public TransformState AuthoritativeState => m_AuthoritativeTransform;
|
||||
|
||||
/// <summary>
|
||||
/// Contains the current anticipated state, which will match the values of this object's
|
||||
/// actual <see cref="MonoBehaviour.transform"/>. When a server
|
||||
/// update arrives, this value will be overwritten by the new
|
||||
/// server value (unless stale data handling is set to "Ignore"
|
||||
/// and the update is determined to be stale). This value will
|
||||
/// be duplicated in <see cref="PreviousAnticipatedState"/>, which
|
||||
/// will NOT be overwritten in server updates.
|
||||
/// </summary>
|
||||
public TransformState AnticipatedState => m_AnticipatedTransform;
|
||||
|
||||
/// <summary>
|
||||
/// Indicates whether this transform currently needs
|
||||
/// reanticipation. If this is true, the anticipated value
|
||||
/// has been overwritten by the authoritative value from the
|
||||
/// server; the previous anticipated value is stored in <see cref="PreviousAnticipatedState"/>
|
||||
/// </summary>
|
||||
public bool ShouldReanticipate
|
||||
{
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Holds the most recent anticipated state, whatever was
|
||||
/// most recently set using the Anticipate methods. Unlike
|
||||
/// <see cref="AnticipatedState"/>, this does not get overwritten
|
||||
/// when a server update arrives.
|
||||
/// </summary>
|
||||
public TransformState PreviousAnticipatedState => m_PreviousAnticipatedTransform;
|
||||
|
||||
/// <summary>
|
||||
/// Anticipate that, at the end of one round trip to the server, this transform will be in the given
|
||||
/// <see cref="newPosition"/>
|
||||
/// </summary>
|
||||
/// <param name="newPosition"></param>
|
||||
public void AnticipateMove(Vector3 newPosition)
|
||||
{
|
||||
if (NetworkManager.ShutdownInProgress || !NetworkManager.IsListening)
|
||||
{
|
||||
return;
|
||||
}
|
||||
transform.position = newPosition;
|
||||
m_AnticipatedTransform.Position = newPosition;
|
||||
if (CanCommitToTransform)
|
||||
{
|
||||
m_AuthoritativeTransform.Position = newPosition;
|
||||
}
|
||||
|
||||
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
|
||||
|
||||
m_LastAnticipaionCounter = NetworkManager.AnticipationSystem.AnticipationCounter;
|
||||
|
||||
m_SmoothDuration = 0;
|
||||
m_CurrentSmoothTime = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Anticipate that, at the end of one round trip to the server, this transform will have the given
|
||||
/// <see cref="newRotation"/>
|
||||
/// </summary>
|
||||
/// <param name="newRotation"></param>
|
||||
public void AnticipateRotate(Quaternion newRotation)
|
||||
{
|
||||
if (NetworkManager.ShutdownInProgress || !NetworkManager.IsListening)
|
||||
{
|
||||
return;
|
||||
}
|
||||
transform.rotation = newRotation;
|
||||
m_AnticipatedTransform.Rotation = newRotation;
|
||||
if (CanCommitToTransform)
|
||||
{
|
||||
m_AuthoritativeTransform.Rotation = newRotation;
|
||||
}
|
||||
|
||||
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
|
||||
|
||||
m_LastAnticipaionCounter = NetworkManager.AnticipationSystem.AnticipationCounter;
|
||||
|
||||
m_SmoothDuration = 0;
|
||||
m_CurrentSmoothTime = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Anticipate that, at the end of one round trip to the server, this transform will have the given
|
||||
/// <see cref="newScale"/>
|
||||
/// </summary>
|
||||
/// <param name="newScale"></param>
|
||||
public void AnticipateScale(Vector3 newScale)
|
||||
{
|
||||
if (NetworkManager.ShutdownInProgress || !NetworkManager.IsListening)
|
||||
{
|
||||
return;
|
||||
}
|
||||
transform.localScale = newScale;
|
||||
m_AnticipatedTransform.Scale = newScale;
|
||||
if (CanCommitToTransform)
|
||||
{
|
||||
m_AuthoritativeTransform.Scale = newScale;
|
||||
}
|
||||
|
||||
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
|
||||
|
||||
m_LastAnticipaionCounter = NetworkManager.AnticipationSystem.AnticipationCounter;
|
||||
|
||||
m_SmoothDuration = 0;
|
||||
m_CurrentSmoothTime = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Anticipate that, at the end of one round trip to the server, the transform will have the given
|
||||
/// <see cref="newState"/>
|
||||
/// </summary>
|
||||
/// <param name="newState"></param>
|
||||
public void AnticipateState(TransformState newState)
|
||||
{
|
||||
if (NetworkManager.ShutdownInProgress || !NetworkManager.IsListening)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var transform_ = transform;
|
||||
transform_.position = newState.Position;
|
||||
transform_.rotation = newState.Rotation;
|
||||
transform_.localScale = newState.Scale;
|
||||
m_AnticipatedTransform = newState;
|
||||
if (CanCommitToTransform)
|
||||
{
|
||||
m_AuthoritativeTransform = newState;
|
||||
}
|
||||
|
||||
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
|
||||
|
||||
m_SmoothDuration = 0;
|
||||
m_CurrentSmoothTime = 0;
|
||||
}
|
||||
|
||||
public override void OnUpdate()
|
||||
{
|
||||
// If not spawned or this instance has authority, exit early
|
||||
if (!IsSpawned)
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Do not call the base class implementation...
|
||||
// AnticipatedNetworkTransform applies its authoritative state immediately rather than waiting for update
|
||||
// This is because AnticipatedNetworkTransforms may need to reference each other in reanticipating
|
||||
// and we will want all reanticipation done before anything else wants to reference the transform in
|
||||
// OnUpdate()
|
||||
//base.Update();
|
||||
|
||||
if (m_CurrentSmoothTime < m_SmoothDuration)
|
||||
{
|
||||
m_CurrentSmoothTime += NetworkManager.RealTimeProvider.DeltaTime;
|
||||
var transform_ = transform;
|
||||
var pct = math.min(m_CurrentSmoothTime / m_SmoothDuration, 1f);
|
||||
|
||||
m_AnticipatedTransform = new TransformState
|
||||
{
|
||||
Position = Vector3.Lerp(m_SmoothFrom.Position, m_SmoothTo.Position, pct),
|
||||
Rotation = Quaternion.Slerp(m_SmoothFrom.Rotation, m_SmoothTo.Rotation, pct),
|
||||
Scale = Vector3.Lerp(m_SmoothFrom.Scale, m_SmoothTo.Scale, pct)
|
||||
};
|
||||
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
|
||||
if (!CanCommitToTransform)
|
||||
{
|
||||
transform_.position = m_AnticipatedTransform.Position;
|
||||
transform_.localScale = m_AnticipatedTransform.Scale;
|
||||
transform_.rotation = m_AnticipatedTransform.Rotation;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal class AnticipatedObject : IAnticipationEventReceiver, IAnticipatedObject
|
||||
{
|
||||
public AnticipatedNetworkTransform Transform;
|
||||
|
||||
|
||||
public void SetupForRender()
|
||||
{
|
||||
if (Transform.CanCommitToTransform)
|
||||
{
|
||||
var transform_ = Transform.transform;
|
||||
Transform.m_AuthoritativeTransform = new TransformState
|
||||
{
|
||||
Position = transform_.position,
|
||||
Rotation = transform_.rotation,
|
||||
Scale = transform_.localScale
|
||||
};
|
||||
if (Transform.m_CurrentSmoothTime >= Transform.m_SmoothDuration)
|
||||
{
|
||||
// If we've had a call to Smooth() we'll continue interpolating.
|
||||
// Otherwise we'll go ahead and make the visual and actual locations
|
||||
// match.
|
||||
Transform.m_AnticipatedTransform = Transform.m_AuthoritativeTransform;
|
||||
}
|
||||
|
||||
transform_.position = Transform.m_AnticipatedTransform.Position;
|
||||
transform_.rotation = Transform.m_AnticipatedTransform.Rotation;
|
||||
transform_.localScale = Transform.m_AnticipatedTransform.Scale;
|
||||
}
|
||||
}
|
||||
|
||||
public void SetupForUpdate()
|
||||
{
|
||||
if (Transform.CanCommitToTransform)
|
||||
{
|
||||
var transform_ = Transform.transform;
|
||||
transform_.position = Transform.m_AuthoritativeTransform.Position;
|
||||
transform_.rotation = Transform.m_AuthoritativeTransform.Rotation;
|
||||
transform_.localScale = Transform.m_AuthoritativeTransform.Scale;
|
||||
}
|
||||
}
|
||||
|
||||
public void Update()
|
||||
{
|
||||
// No need to do this, it's handled by NetworkTransform.OnUpdate
|
||||
}
|
||||
|
||||
public void ResetAnticipation()
|
||||
{
|
||||
Transform.ShouldReanticipate = false;
|
||||
}
|
||||
|
||||
public NetworkObject OwnerObject => Transform.NetworkObject;
|
||||
}
|
||||
|
||||
private AnticipatedObject m_AnticipatedObject = null;
|
||||
|
||||
private void ResetAnticipatedState()
|
||||
{
|
||||
var transform_ = transform;
|
||||
m_AuthoritativeTransform = new TransformState
|
||||
{
|
||||
Position = transform_.position,
|
||||
Rotation = transform_.rotation,
|
||||
Scale = transform_.localScale
|
||||
};
|
||||
m_AnticipatedTransform = m_AuthoritativeTransform;
|
||||
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
|
||||
|
||||
m_SmoothDuration = 0;
|
||||
m_CurrentSmoothTime = 0;
|
||||
}
|
||||
|
||||
protected override void OnSynchronize<T>(ref BufferSerializer<T> serializer)
|
||||
{
|
||||
base.OnSynchronize(ref serializer);
|
||||
if (!CanCommitToTransform)
|
||||
{
|
||||
m_OutstandingAuthorityChange = true;
|
||||
ApplyAuthoritativeState();
|
||||
ResetAnticipatedState();
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
if (NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
Debug.LogWarning($"This component is not currently supported in distributed authority.");
|
||||
}
|
||||
base.OnNetworkSpawn();
|
||||
m_OutstandingAuthorityChange = true;
|
||||
ApplyAuthoritativeState();
|
||||
ResetAnticipatedState();
|
||||
|
||||
m_AnticipatedObject = new AnticipatedObject { Transform = this };
|
||||
NetworkManager.AnticipationSystem.RegisterForAnticipationEvents(m_AnticipatedObject);
|
||||
NetworkManager.AnticipationSystem.AllAnticipatedObjects.Add(m_AnticipatedObject);
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn()
|
||||
{
|
||||
if (m_AnticipatedObject != null)
|
||||
{
|
||||
NetworkManager.AnticipationSystem.DeregisterForAnticipationEvents(m_AnticipatedObject);
|
||||
NetworkManager.AnticipationSystem.AllAnticipatedObjects.Remove(m_AnticipatedObject);
|
||||
NetworkManager.AnticipationSystem.ObjectsToReanticipate.Remove(m_AnticipatedObject);
|
||||
m_AnticipatedObject = null;
|
||||
}
|
||||
ResetAnticipatedState();
|
||||
|
||||
base.OnNetworkDespawn();
|
||||
}
|
||||
|
||||
public override void OnDestroy()
|
||||
{
|
||||
if (m_AnticipatedObject != null)
|
||||
{
|
||||
NetworkManager.AnticipationSystem.DeregisterForAnticipationEvents(m_AnticipatedObject);
|
||||
NetworkManager.AnticipationSystem.AllAnticipatedObjects.Remove(m_AnticipatedObject);
|
||||
NetworkManager.AnticipationSystem.ObjectsToReanticipate.Remove(m_AnticipatedObject);
|
||||
m_AnticipatedObject = null;
|
||||
}
|
||||
|
||||
base.OnDestroy();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Interpolate between the transform represented by <see cref="from"/> to the transform represented by
|
||||
/// <see cref="to"/> over <see cref="durationSeconds"/> of real time. The duration uses
|
||||
/// <see cref="Time.deltaTime"/>, so it is affected by <see cref="Time.timeScale"/>.
|
||||
/// </summary>
|
||||
/// <param name="from"></param>
|
||||
/// <param name="to"></param>
|
||||
/// <param name="durationSeconds"></param>
|
||||
public void Smooth(TransformState from, TransformState to, float durationSeconds)
|
||||
{
|
||||
var transform_ = transform;
|
||||
if (durationSeconds <= 0)
|
||||
{
|
||||
m_AnticipatedTransform = to;
|
||||
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
|
||||
transform_.position = to.Position;
|
||||
transform_.rotation = to.Rotation;
|
||||
transform_.localScale = to.Scale;
|
||||
m_SmoothDuration = 0;
|
||||
m_CurrentSmoothTime = 0;
|
||||
return;
|
||||
}
|
||||
m_AnticipatedTransform = from;
|
||||
m_PreviousAnticipatedTransform = m_AnticipatedTransform;
|
||||
|
||||
if (!CanCommitToTransform)
|
||||
{
|
||||
transform_.position = from.Position;
|
||||
transform_.rotation = from.Rotation;
|
||||
transform_.localScale = from.Scale;
|
||||
}
|
||||
|
||||
m_SmoothFrom = from;
|
||||
m_SmoothTo = to;
|
||||
m_SmoothDuration = durationSeconds;
|
||||
m_CurrentSmoothTime = 0;
|
||||
}
|
||||
|
||||
protected override void OnBeforeUpdateTransformState()
|
||||
{
|
||||
// this is called when new data comes from the server
|
||||
m_LastAuthorityUpdateCounter = NetworkManager.AnticipationSystem.LastAnticipationAck;
|
||||
m_OutstandingAuthorityChange = true;
|
||||
}
|
||||
|
||||
protected override void OnNetworkTransformStateUpdated(ref NetworkTransformState oldState, ref NetworkTransformState newState)
|
||||
{
|
||||
base.OnNetworkTransformStateUpdated(ref oldState, ref newState);
|
||||
ApplyAuthoritativeState();
|
||||
}
|
||||
|
||||
protected override void OnTransformUpdated()
|
||||
{
|
||||
if (CanCommitToTransform || m_AnticipatedObject == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
// this is called pretty much every frame and will change the transform
|
||||
// If we've overridden the transform with an anticipated state, we need to be able to change it back
|
||||
// to the anticipated state (while updating the authority state accordingly) or else
|
||||
// mark this transform for reanticipation
|
||||
var transform_ = transform;
|
||||
|
||||
var previousAnticipatedTransform = m_AnticipatedTransform;
|
||||
|
||||
// Update authority state to catch any possible interpolation data
|
||||
m_AuthoritativeTransform.Position = transform_.position;
|
||||
m_AuthoritativeTransform.Rotation = transform_.rotation;
|
||||
m_AuthoritativeTransform.Scale = transform_.localScale;
|
||||
|
||||
if (!m_OutstandingAuthorityChange)
|
||||
{
|
||||
// Keep the anticipated value unchanged, we have no updates from the server at all.
|
||||
transform_.position = previousAnticipatedTransform.Position;
|
||||
transform_.localScale = previousAnticipatedTransform.Scale;
|
||||
transform_.rotation = previousAnticipatedTransform.Rotation;
|
||||
return;
|
||||
}
|
||||
|
||||
if (StaleDataHandling == StaleDataHandling.Ignore && m_LastAnticipaionCounter > m_LastAuthorityUpdateCounter)
|
||||
{
|
||||
// Keep the anticipated value unchanged because it is more recent than the authoritative one.
|
||||
transform_.position = previousAnticipatedTransform.Position;
|
||||
transform_.localScale = previousAnticipatedTransform.Scale;
|
||||
transform_.rotation = previousAnticipatedTransform.Rotation;
|
||||
return;
|
||||
}
|
||||
|
||||
m_SmoothDuration = 0;
|
||||
m_CurrentSmoothTime = 0;
|
||||
m_OutstandingAuthorityChange = false;
|
||||
m_AnticipatedTransform = m_AuthoritativeTransform;
|
||||
|
||||
ShouldReanticipate = true;
|
||||
NetworkManager.AnticipationSystem.ObjectsToReanticipate.Add(m_AnticipatedObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5abfce83aadd948498d4990c645a017b
|
||||
@@ -12,7 +12,7 @@ namespace Unity.Netcode
|
||||
public abstract class BufferedLinearInterpolator<T> where T : struct
|
||||
{
|
||||
internal float MaxInterpolationBound = 3.0f;
|
||||
private struct BufferedItem
|
||||
protected internal struct BufferedItem
|
||||
{
|
||||
public T Item;
|
||||
public double TimeSent;
|
||||
@@ -31,14 +31,16 @@ namespace Unity.Netcode
|
||||
|
||||
private const double k_SmallValue = 9.999999439624929E-11; // copied from Vector3's equal operator
|
||||
|
||||
private T m_InterpStartValue;
|
||||
private T m_CurrentInterpValue;
|
||||
private T m_InterpEndValue;
|
||||
protected internal T m_InterpStartValue;
|
||||
protected internal T m_CurrentInterpValue;
|
||||
protected internal T m_InterpEndValue;
|
||||
|
||||
private double m_EndTimeConsumed;
|
||||
private double m_StartTimeConsumed;
|
||||
|
||||
private readonly List<BufferedItem> m_Buffer = new List<BufferedItem>(k_BufferCountLimit);
|
||||
protected internal readonly List<BufferedItem> m_Buffer = new List<BufferedItem>(k_BufferCountLimit);
|
||||
|
||||
|
||||
|
||||
// Buffer consumption scenarios
|
||||
// Perfect case consumption
|
||||
@@ -73,6 +75,21 @@ namespace Unity.Netcode
|
||||
|
||||
private bool InvalidState => m_Buffer.Count == 0 && m_LifetimeConsumedCount == 0;
|
||||
|
||||
internal bool EndOfBuffer => m_Buffer.Count == 0;
|
||||
|
||||
internal bool InLocalSpace;
|
||||
|
||||
protected internal virtual void OnConvertTransformSpace(Transform transform, bool inLocalSpace)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
internal void ConvertTransformSpace(Transform transform, bool inLocalSpace)
|
||||
{
|
||||
OnConvertTransformSpace(transform, inLocalSpace);
|
||||
InLocalSpace = inLocalSpace;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets interpolator to initial state
|
||||
/// </summary>
|
||||
@@ -351,6 +368,35 @@ namespace Unity.Netcode
|
||||
return Quaternion.Lerp(start, end, time);
|
||||
}
|
||||
}
|
||||
|
||||
private Quaternion ConvertToNewTransformSpace(Transform transform, Quaternion rotation, bool inLocalSpace)
|
||||
{
|
||||
if (inLocalSpace)
|
||||
{
|
||||
return Quaternion.Inverse(transform.rotation) * rotation;
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
return transform.rotation * rotation;
|
||||
}
|
||||
}
|
||||
|
||||
protected internal override void OnConvertTransformSpace(Transform transform, bool inLocalSpace)
|
||||
{
|
||||
for (int i = 0; i < m_Buffer.Count; i++)
|
||||
{
|
||||
var entry = m_Buffer[i];
|
||||
entry.Item = ConvertToNewTransformSpace(transform, entry.Item, inLocalSpace);
|
||||
m_Buffer[i] = entry;
|
||||
}
|
||||
|
||||
m_InterpStartValue = ConvertToNewTransformSpace(transform, m_InterpStartValue, inLocalSpace);
|
||||
m_CurrentInterpValue = ConvertToNewTransformSpace(transform, m_CurrentInterpValue, inLocalSpace);
|
||||
m_InterpEndValue = ConvertToNewTransformSpace(transform, m_InterpEndValue, inLocalSpace);
|
||||
|
||||
base.OnConvertTransformSpace(transform, inLocalSpace);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -388,5 +434,34 @@ namespace Unity.Netcode
|
||||
return Vector3.Lerp(start, end, time);
|
||||
}
|
||||
}
|
||||
|
||||
private Vector3 ConvertToNewTransformSpace(Transform transform, Vector3 position, bool inLocalSpace)
|
||||
{
|
||||
if (inLocalSpace)
|
||||
{
|
||||
return transform.InverseTransformPoint(position);
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
return transform.TransformPoint(position);
|
||||
}
|
||||
}
|
||||
|
||||
protected internal override void OnConvertTransformSpace(Transform transform, bool inLocalSpace)
|
||||
{
|
||||
for (int i = 0; i < m_Buffer.Count; i++)
|
||||
{
|
||||
var entry = m_Buffer[i];
|
||||
entry.Item = ConvertToNewTransformSpace(transform, entry.Item, inLocalSpace);
|
||||
m_Buffer[i] = entry;
|
||||
}
|
||||
|
||||
m_InterpStartValue = ConvertToNewTransformSpace(transform, m_InterpStartValue, inLocalSpace);
|
||||
m_CurrentInterpValue = ConvertToNewTransformSpace(transform, m_CurrentInterpValue, inLocalSpace);
|
||||
m_InterpEndValue = ConvertToNewTransformSpace(transform, m_InterpEndValue, inLocalSpace);
|
||||
|
||||
base.OnConvertTransformSpace(transform, inLocalSpace);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -230,6 +230,7 @@ namespace Unity.Netcode.Components
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#if UNITY_EDITOR
|
||||
private void ParseStateMachineStates(int layerIndex, ref AnimatorController animatorController, ref AnimatorStateMachine stateMachine)
|
||||
{
|
||||
@@ -263,7 +264,6 @@ namespace Unity.Netcode.Components
|
||||
{
|
||||
case AnimatorControllerParameterType.Trigger:
|
||||
{
|
||||
|
||||
if (transition.destinationStateMachine != null)
|
||||
{
|
||||
var destinationStateMachine = transition.destinationStateMachine;
|
||||
@@ -297,18 +297,12 @@ namespace Unity.Netcode.Components
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Creates the TransitionStateInfoList table
|
||||
/// </summary>
|
||||
private void BuildTransitionStateInfoList()
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
if (UnityEditor.EditorApplication.isUpdating || UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (m_Animator == null)
|
||||
{
|
||||
return;
|
||||
@@ -326,9 +320,18 @@ namespace Unity.Netcode.Components
|
||||
var stateMachine = animatorController.layers[x].stateMachine;
|
||||
ParseStateMachineStates(x, ref animatorController, ref stateMachine);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// In-Editor Only
|
||||
/// Virtual OnValidate method for custom derived NetworkAnimator classes.
|
||||
/// </summary>
|
||||
protected virtual void OnValidate()
|
||||
{
|
||||
BuildTransitionStateInfoList();
|
||||
}
|
||||
#endif
|
||||
|
||||
public void OnAfterDeserialize()
|
||||
{
|
||||
BuildDestinationToTransitionInfoTable();
|
||||
@@ -336,7 +339,7 @@ namespace Unity.Netcode.Components
|
||||
|
||||
public void OnBeforeSerialize()
|
||||
{
|
||||
BuildTransitionStateInfoList();
|
||||
// Do nothing when serializing (handled during OnValidate)
|
||||
}
|
||||
|
||||
internal struct AnimationState : INetworkSerializable
|
||||
@@ -419,8 +422,8 @@ namespace Unity.Netcode.Components
|
||||
internal bool HasBeenProcessed;
|
||||
|
||||
// This is preallocated/populated in OnNetworkSpawn for all instances in the event ownership or
|
||||
// authority changes. When serializing, IsDirtyCount determines how many AnimationState entries
|
||||
// should be serialized from the list. When deserializing the list is created and populated with
|
||||
// authority changes. When serializing, IsDirtyCount determines how many AnimationState entries
|
||||
// should be serialized from the list. When deserializing the list is created and populated with
|
||||
// only the number of AnimationStates received which is dictated by the deserialized IsDirtyCount.
|
||||
internal List<AnimationState> AnimationStates;
|
||||
|
||||
@@ -496,17 +499,17 @@ namespace Unity.Netcode.Components
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Override this method and return false to switch to owner authoritative mode
|
||||
/// Override this method and return false to switch to owner authoritative mode.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// When using a distributed authority network topology, this will default to
|
||||
/// owner authoritative.
|
||||
/// </remarks>
|
||||
protected virtual bool OnIsServerAuthoritative()
|
||||
{
|
||||
return true;
|
||||
return NetworkManager ? !NetworkManager.DistributedAuthorityMode : true;
|
||||
}
|
||||
|
||||
// Animators only support up to 32 parameters
|
||||
// TODO: Look into making this a range limited property
|
||||
private const int k_MaxAnimationParams = 32;
|
||||
|
||||
private int[] m_TransitionHash;
|
||||
private int[] m_AnimationHash;
|
||||
private float[] m_LayerWeights;
|
||||
@@ -530,7 +533,7 @@ namespace Unity.Netcode.Components
|
||||
}
|
||||
|
||||
// 128 bytes per Animator
|
||||
private FastBufferWriter m_ParameterWriter = new FastBufferWriter(k_MaxAnimationParams * sizeof(float), Allocator.Persistent);
|
||||
private FastBufferWriter m_ParameterWriter;
|
||||
|
||||
private NativeArray<AnimatorParamCache> m_CachedAnimatorParameters;
|
||||
|
||||
@@ -580,8 +583,16 @@ namespace Unity.Netcode.Components
|
||||
base.OnDestroy();
|
||||
}
|
||||
|
||||
private void Awake()
|
||||
protected virtual void Awake()
|
||||
{
|
||||
if (!m_Animator)
|
||||
{
|
||||
#if !UNITY_EDITOR
|
||||
Debug.LogError($"{nameof(NetworkAnimator)} {name} does not have an {nameof(UnityEngine.Animator)} assigned to it. The {nameof(NetworkAnimator)} will not initialize properly.");
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
|
||||
int layers = m_Animator.layerCount;
|
||||
// Initializing the below arrays for everyone handles an issue
|
||||
// when running in owner authoritative mode and the owner changes.
|
||||
@@ -611,6 +622,9 @@ namespace Unity.Netcode.Components
|
||||
}
|
||||
}
|
||||
|
||||
// The total initialization size calculated for the m_ParameterWriter write buffer.
|
||||
var totalParameterSize = sizeof(uint);
|
||||
|
||||
// Build our reference parameter values to detect when they change
|
||||
var parameters = m_Animator.parameters;
|
||||
m_CachedAnimatorParameters = new NativeArray<AnimatorParamCache>(parameters.Length, Allocator.Persistent);
|
||||
@@ -651,7 +665,37 @@ namespace Unity.Netcode.Components
|
||||
}
|
||||
|
||||
m_CachedAnimatorParameters[i] = cacheParam;
|
||||
|
||||
// Calculate parameter sizes (index + type size)
|
||||
switch (parameter.type)
|
||||
{
|
||||
case AnimatorControllerParameterType.Int:
|
||||
{
|
||||
totalParameterSize += sizeof(int) * 2;
|
||||
break;
|
||||
}
|
||||
case AnimatorControllerParameterType.Bool:
|
||||
case AnimatorControllerParameterType.Trigger:
|
||||
{
|
||||
// Bool is serialized to 1 byte
|
||||
totalParameterSize += sizeof(int) + 1;
|
||||
break;
|
||||
}
|
||||
case AnimatorControllerParameterType.Float:
|
||||
{
|
||||
totalParameterSize += sizeof(int) + sizeof(float);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (m_ParameterWriter.IsInitialized)
|
||||
{
|
||||
m_ParameterWriter.Dispose();
|
||||
}
|
||||
|
||||
// Create our parameter write buffer for serialization
|
||||
m_ParameterWriter = new FastBufferWriter(totalParameterSize, Allocator.Persistent);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -693,7 +737,7 @@ namespace Unity.Netcode.Components
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wries all parameter and state information needed to initially synchronize a client
|
||||
/// Writes all parameter and state information needed to initially synchronize a client
|
||||
/// </summary>
|
||||
private void WriteSynchronizationData<T>(ref BufferSerializer<T> serializer) where T : IReaderWriter
|
||||
{
|
||||
@@ -768,8 +812,10 @@ namespace Unity.Netcode.Components
|
||||
}
|
||||
}
|
||||
|
||||
animationState.Transition = isInTransition; // The only time this could be set to true
|
||||
animationState.StateHash = stateHash; // When a transition, this is the originating/starting state
|
||||
// The only time this could be set to true
|
||||
animationState.Transition = isInTransition;
|
||||
// When a transition, this is the originating/starting state
|
||||
animationState.StateHash = stateHash;
|
||||
animationState.NormalizedTime = normalizedTime;
|
||||
animationState.Layer = layer;
|
||||
animationState.Weight = m_LayerWeights[layer];
|
||||
@@ -843,7 +889,8 @@ namespace Unity.Netcode.Components
|
||||
{
|
||||
m_TransitionHash[layer] = nt.fullPathHash;
|
||||
m_AnimationHash[layer] = 0;
|
||||
animState.DestinationStateHash = nt.fullPathHash; // Next state is the destination state for cross fade
|
||||
// Next state is the destination state for cross fade
|
||||
animState.DestinationStateHash = nt.fullPathHash;
|
||||
animState.CrossFade = true;
|
||||
animState.Transition = true;
|
||||
animState.Duration = tt.duration;
|
||||
@@ -851,15 +898,25 @@ namespace Unity.Netcode.Components
|
||||
stateChangeDetected = true;
|
||||
//Debug.Log($"[Cross-Fade] To-Hash: {nt.fullPathHash} | TI-Duration: ({tt.duration}) | TI-Norm: ({tt.normalizedTime}) | From-Hash: ({m_AnimationHash[layer]}) | SI-FPHash: ({st.fullPathHash}) | SI-Norm: ({st.normalizedTime})");
|
||||
}
|
||||
else if (!tt.anyState && tt.fullPathHash != m_TransitionHash[layer])
|
||||
// If we are not transitioned into the "any state" and the animator transition isn't a full path hash (layer to layer) and our pre-built destination state to transition does not contain the
|
||||
// current layer (i.e. transitioning into a state from another layer) =or= we do contain the layer and the layer contains state to transition to is contained within our pre-built destination
|
||||
// state then we can handle this transition as a non-cross fade state transition between layers.
|
||||
// Otherwise, if we don't enter into this then this is a "trigger transition to some state that is now being transitioned back to the Idle state via trigger" or "Dual Triggers" IDLE<-->State.
|
||||
else if (!tt.anyState && tt.fullPathHash != m_TransitionHash[layer] && (!m_DestinationStateToTransitioninfo.ContainsKey(layer) ||
|
||||
(m_DestinationStateToTransitioninfo.ContainsKey(layer) && m_DestinationStateToTransitioninfo[layer].ContainsKey(nt.fullPathHash))))
|
||||
{
|
||||
// first time in this transition for this layer
|
||||
m_TransitionHash[layer] = tt.fullPathHash;
|
||||
m_AnimationHash[layer] = 0;
|
||||
animState.StateHash = tt.fullPathHash; // Transitioning from state
|
||||
// Transitioning from state
|
||||
animState.StateHash = tt.fullPathHash;
|
||||
animState.CrossFade = false;
|
||||
animState.Transition = true;
|
||||
animState.NormalizedTime = tt.normalizedTime;
|
||||
if (m_DestinationStateToTransitioninfo.ContainsKey(layer) && m_DestinationStateToTransitioninfo[layer].ContainsKey(nt.fullPathHash))
|
||||
{
|
||||
animState.DestinationStateHash = nt.fullPathHash;
|
||||
}
|
||||
stateChangeDetected = true;
|
||||
//Debug.Log($"[Transition] TI-Duration: ({tt.duration}) | TI-Norm: ({tt.normalizedTime}) | From-Hash: ({m_AnimationHash[layer]}) |SI-FPHash: ({st.fullPathHash}) | SI-Norm: ({st.normalizedTime})");
|
||||
}
|
||||
@@ -939,8 +996,14 @@ namespace Unity.Netcode.Components
|
||||
{
|
||||
// Just notify all remote clients and not the local server
|
||||
m_ClientSendList.Clear();
|
||||
m_ClientSendList.AddRange(NetworkManager.ConnectedClientsIds);
|
||||
m_ClientSendList.Remove(NetworkManager.LocalClientId);
|
||||
foreach (var clientId in NetworkManager.ConnectedClientsIds)
|
||||
{
|
||||
if (clientId == NetworkManager.LocalClientId || !NetworkObject.Observers.Contains(clientId))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
m_ClientSendList.Add(clientId);
|
||||
}
|
||||
m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList;
|
||||
SendAnimStateClientRpc(m_AnimationMessage, m_ClientRpcParams);
|
||||
}
|
||||
@@ -1062,7 +1125,7 @@ namespace Unity.Netcode.Components
|
||||
{
|
||||
writer.Seek(0);
|
||||
writer.Truncate();
|
||||
// Write how many parameter entries we are going to write
|
||||
// Write out how many parameter entries to read
|
||||
BytePacker.WriteValuePacked(writer, (uint)m_ParametersToUpdate.Count);
|
||||
foreach (var parameterIndex in m_ParametersToUpdate)
|
||||
{
|
||||
@@ -1211,10 +1274,11 @@ namespace Unity.Netcode.Components
|
||||
NetworkLog.LogError($"[DestinationState To Transition Info] Layer ({animationState.Layer}) sub-table does not contain destination state ({animationState.DestinationStateHash})!");
|
||||
}
|
||||
}
|
||||
else if (NetworkManager.LogLevel == LogLevel.Developer)
|
||||
{
|
||||
NetworkLog.LogError($"[DestinationState To Transition Info] Layer ({animationState.Layer}) does not exist!");
|
||||
}
|
||||
// For reference, it is valid to have no transition information
|
||||
//else if (NetworkManager.LogLevel == LogLevel.Developer)
|
||||
//{
|
||||
// NetworkLog.LogError($"[DestinationState To Transition Info] Layer ({animationState.Layer}) does not exist!");
|
||||
//}
|
||||
}
|
||||
else if (animationState.Transition && animationState.CrossFade)
|
||||
{
|
||||
@@ -1251,9 +1315,15 @@ namespace Unity.Netcode.Components
|
||||
if (NetworkManager.ConnectedClientsIds.Count > (IsHost ? 2 : 1))
|
||||
{
|
||||
m_ClientSendList.Clear();
|
||||
m_ClientSendList.AddRange(NetworkManager.ConnectedClientsIds);
|
||||
m_ClientSendList.Remove(serverRpcParams.Receive.SenderClientId);
|
||||
m_ClientSendList.Remove(NetworkManager.ServerClientId);
|
||||
foreach (var clientId in NetworkManager.ConnectedClientsIds)
|
||||
{
|
||||
if (clientId == serverRpcParams.Receive.SenderClientId || clientId == NetworkManager.ServerClientId || !NetworkObject.Observers.Contains(clientId))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
m_ClientSendList.Add(clientId);
|
||||
}
|
||||
|
||||
m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList;
|
||||
m_NetworkAnimatorStateChangeHandler.SendParameterUpdate(parametersUpdate, m_ClientRpcParams);
|
||||
}
|
||||
@@ -1308,9 +1378,14 @@ namespace Unity.Netcode.Components
|
||||
if (NetworkManager.ConnectedClientsIds.Count > (IsHost ? 2 : 1))
|
||||
{
|
||||
m_ClientSendList.Clear();
|
||||
m_ClientSendList.AddRange(NetworkManager.ConnectedClientsIds);
|
||||
m_ClientSendList.Remove(serverRpcParams.Receive.SenderClientId);
|
||||
m_ClientSendList.Remove(NetworkManager.ServerClientId);
|
||||
foreach (var clientId in NetworkManager.ConnectedClientsIds)
|
||||
{
|
||||
if (clientId == serverRpcParams.Receive.SenderClientId || clientId == NetworkManager.ServerClientId || !NetworkObject.Observers.Contains(clientId))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
m_ClientSendList.Add(clientId);
|
||||
}
|
||||
m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList;
|
||||
m_NetworkAnimatorStateChangeHandler.SendAnimationUpdate(animationMessage, m_ClientRpcParams);
|
||||
}
|
||||
@@ -1377,9 +1452,14 @@ namespace Unity.Netcode.Components
|
||||
InternalSetTrigger(animationTriggerMessage.Hash, animationTriggerMessage.IsTriggerSet);
|
||||
|
||||
m_ClientSendList.Clear();
|
||||
m_ClientSendList.AddRange(NetworkManager.ConnectedClientsIds);
|
||||
m_ClientSendList.Remove(NetworkManager.ServerClientId);
|
||||
|
||||
foreach (var clientId in NetworkManager.ConnectedClientsIds)
|
||||
{
|
||||
if (clientId == NetworkManager.ServerClientId || !NetworkObject.Observers.Contains(clientId))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
m_ClientSendList.Add(clientId);
|
||||
}
|
||||
if (IsServerAuthoritative())
|
||||
{
|
||||
m_NetworkAnimatorStateChangeHandler.QueueTriggerUpdateToClient(animationTriggerMessage, m_ClientRpcParams);
|
||||
@@ -1401,7 +1481,7 @@ namespace Unity.Netcode.Components
|
||||
|
||||
/// <summary>
|
||||
/// Distributed Authority: Internally-called RPC client receiving function to update a trigger when the server wants to forward
|
||||
/// a trigger for a client to play / reset
|
||||
/// a trigger to a client
|
||||
/// </summary>
|
||||
/// <param name="animationTriggerMessage">the payload containing the trigger data to apply</param>
|
||||
[Rpc(SendTo.NotAuthority)]
|
||||
@@ -1412,7 +1492,7 @@ namespace Unity.Netcode.Components
|
||||
|
||||
/// <summary>
|
||||
/// Client Server: Internally-called RPC client receiving function to update a trigger when the server wants to forward
|
||||
/// a trigger for a client to play / reset
|
||||
/// a trigger to a client
|
||||
/// </summary>
|
||||
/// <param name="animationTriggerMessage">the payload containing the trigger data to apply</param>
|
||||
/// <param name="clientRpcParams">unused</param>
|
||||
@@ -1478,7 +1558,7 @@ namespace Unity.Netcode.Components
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets the trigger for the associated animation. See <see cref="SetTrigger(string)">SetTrigger</see> for more on how triggers are special
|
||||
/// Resets the trigger for the associated animation. See <see cref="SetTrigger(string)">SetTrigger</see> for more on how triggers are special
|
||||
/// </summary>
|
||||
/// <param name="triggerName">The string name of the trigger to reset</param>
|
||||
public void ResetTrigger(string triggerName)
|
||||
@@ -1494,4 +1574,5 @@ namespace Unity.Netcode.Components
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // COM_UNITY_MODULES_ANIMATION
|
||||
// COM_UNITY_MODULES_ANIMATION
|
||||
#endif
|
||||
|
||||
@@ -1,876 +0,0 @@
|
||||
#if COM_UNITY_MODULES_PHYSICS
|
||||
using System.Runtime.CompilerServices;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Unity.Netcode.Components
|
||||
{
|
||||
/// <summary>
|
||||
/// NetworkRigidbodyBase is a unified <see cref="Rigidbody"/> and <see cref="Rigidbody2D"/> integration that helps to synchronize physics motion, collision, and interpolation
|
||||
/// when used with a <see cref="NetworkTransform"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// For a customizable netcode Rigidbody, create your own component from this class and use <see cref="Initialize(RigidbodyTypes, NetworkTransform, Rigidbody2D, Rigidbody)"/>
|
||||
/// during instantiation (i.e. invoked from within the Awake method). You can re-initialize after having initialized but only when the <see cref="NetworkObject"/> is not spawned.
|
||||
/// </remarks>
|
||||
public abstract class NetworkRigidbodyBase : NetworkBehaviour
|
||||
{
|
||||
/// <summary>
|
||||
/// When enabled, the associated <see cref="NetworkTransform"/> will use the Rigidbody/Rigidbody2D to apply and synchronize changes in position, rotation, and
|
||||
/// allows for the use of Rigidbody interpolation/extrapolation.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If <see cref="NetworkTransform.Interpolate"/> is enabled, non-authoritative instances can only use Rigidbody interpolation. If a network prefab is set to
|
||||
/// extrapolation and <see cref="NetworkTransform.Interpolate"/> is enabled, then non-authoritative instances will automatically be adjusted to use Rigidbody
|
||||
/// interpolation while the authoritative instance will still use extrapolation.
|
||||
/// </remarks>
|
||||
[Tooltip("When enabled and a NetworkTransform component is attached, the NetworkTransform will use the rigid body for motion and detecting changes in state.")]
|
||||
public bool UseRigidBodyForMotion;
|
||||
|
||||
/// <summary>
|
||||
/// When enabled (default), automatically set the Kinematic state of the Rigidbody based on ownership.
|
||||
/// When disabled, Kinematic state needs to be set by external script(s).
|
||||
/// </summary>
|
||||
public bool AutoUpdateKinematicState = true;
|
||||
|
||||
/// <summary>
|
||||
/// Primarily applies to the <see cref="AutoUpdateKinematicState"/> property when disabled but you still want
|
||||
/// the Rigidbody to be automatically set to Kinematic when despawned.
|
||||
/// </summary>
|
||||
public bool AutoSetKinematicOnDespawn = true;
|
||||
|
||||
// Determines if this is a Rigidbody or Rigidbody2D implementation
|
||||
private bool m_IsRigidbody2D => RigidbodyType == RigidbodyTypes.Rigidbody2D;
|
||||
// Used to cache the authority state of this Rigidbody during the last frame
|
||||
private bool m_IsAuthority;
|
||||
private Rigidbody m_Rigidbody;
|
||||
private Rigidbody2D m_Rigidbody2D;
|
||||
internal NetworkTransform NetworkTransform;
|
||||
private float m_TickFrequency;
|
||||
private float m_TickRate;
|
||||
|
||||
private enum InterpolationTypes
|
||||
{
|
||||
None,
|
||||
Interpolate,
|
||||
Extrapolate
|
||||
}
|
||||
private InterpolationTypes m_OriginalInterpolation;
|
||||
|
||||
/// <summary>
|
||||
/// Used to define the type of Rigidbody implemented.
|
||||
/// <see cref=""/>
|
||||
/// </summary>
|
||||
public enum RigidbodyTypes
|
||||
{
|
||||
Rigidbody,
|
||||
Rigidbody2D,
|
||||
}
|
||||
|
||||
public RigidbodyTypes RigidbodyType { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the networked Rigidbody based on the <see cref="RigidbodyTypes"/>
|
||||
/// passed in as a parameter.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Cannot be initialized while the associated <see cref="NetworkObject"/> is spawned.
|
||||
/// </remarks>
|
||||
/// <param name="rigidbodyType">type of rigid body being initialized</param>
|
||||
/// <param name="rigidbody2D">(optional) The <see cref="Rigidbody2D"/> to be used</param>
|
||||
/// <param name="rigidbody">(optional) The <see cref="Rigidbody"/> to be used</param>
|
||||
protected void Initialize(RigidbodyTypes rigidbodyType, NetworkTransform networkTransform = null, Rigidbody2D rigidbody2D = null, Rigidbody rigidbody = null)
|
||||
{
|
||||
// Don't initialize if already spawned
|
||||
if (IsSpawned)
|
||||
{
|
||||
Debug.LogError($"[{name}] Attempting to initialize while spawned is not allowed.");
|
||||
return;
|
||||
}
|
||||
RigidbodyType = rigidbodyType;
|
||||
m_Rigidbody2D = rigidbody2D;
|
||||
m_Rigidbody = rigidbody;
|
||||
NetworkTransform = networkTransform;
|
||||
|
||||
if (m_IsRigidbody2D && m_Rigidbody2D == null)
|
||||
{
|
||||
m_Rigidbody2D = GetComponent<Rigidbody2D>();
|
||||
|
||||
}
|
||||
else if (m_Rigidbody == null)
|
||||
{
|
||||
m_Rigidbody = GetComponent<Rigidbody>();
|
||||
}
|
||||
|
||||
SetOriginalInterpolation();
|
||||
|
||||
if (NetworkTransform == null)
|
||||
{
|
||||
NetworkTransform = GetComponent<NetworkTransform>();
|
||||
}
|
||||
|
||||
if (NetworkTransform != null)
|
||||
{
|
||||
NetworkTransform.RegisterRigidbody(this);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new System.Exception($"[Missing {nameof(NetworkTransform)}] No {nameof(NetworkTransform)} is assigned or can be found during initialization!");
|
||||
}
|
||||
|
||||
if (AutoUpdateKinematicState)
|
||||
{
|
||||
SetIsKinematic(true);
|
||||
}
|
||||
}
|
||||
|
||||
internal Vector3 GetAdjustedPositionThreshold()
|
||||
{
|
||||
// Since the threshold is a measurement of unity world space units per tick, we will allow for the maximum threshold
|
||||
// to be no greater than the threshold measured in unity world space units per second
|
||||
var thresholdMax = NetworkTransform.PositionThreshold * m_TickRate;
|
||||
// Get the velocity in unity world space units per tick
|
||||
var perTickVelocity = GetLinearVelocity() * m_TickFrequency;
|
||||
// Since a rigid body can have "micro-motion" when allowed to come to rest (based on friction etc), we will allow for
|
||||
// no less than 1/10th the threshold value.
|
||||
var minThreshold = NetworkTransform.PositionThreshold * 0.1f;
|
||||
|
||||
// Finally, we adjust the threshold based on the body's current velocity
|
||||
perTickVelocity.x = Mathf.Clamp(Mathf.Abs(perTickVelocity.x), minThreshold, thresholdMax);
|
||||
perTickVelocity.y = Mathf.Clamp(Mathf.Abs(perTickVelocity.y), minThreshold, thresholdMax);
|
||||
// 2D Rigidbody only moves on x & y axis
|
||||
if (!m_IsRigidbody2D)
|
||||
{
|
||||
perTickVelocity.z = Mathf.Clamp(Mathf.Abs(perTickVelocity.z), minThreshold, thresholdMax);
|
||||
}
|
||||
|
||||
return perTickVelocity;
|
||||
}
|
||||
|
||||
internal Vector3 GetAdjustedRotationThreshold()
|
||||
{
|
||||
// Since the rotation threshold is a measurement pf degrees per tick, we get the maximum threshold
|
||||
// by calculating the threshold in degrees per second.
|
||||
var thresholdMax = NetworkTransform.RotAngleThreshold * m_TickRate;
|
||||
// Angular velocity is expressed in radians per second where as the rotation being checked is in degrees.
|
||||
// Convert the angular velocity to degrees per second and then convert that to degrees per tick.
|
||||
var rotationPerTick = (GetAngularVelocity() * Mathf.Rad2Deg) * m_TickFrequency;
|
||||
var minThreshold = NetworkTransform.RotAngleThreshold * m_TickFrequency;
|
||||
|
||||
// 2D Rigidbody only rotates around Z axis
|
||||
if (!m_IsRigidbody2D)
|
||||
{
|
||||
rotationPerTick.x = Mathf.Clamp(Mathf.Abs(rotationPerTick.x), minThreshold, thresholdMax);
|
||||
rotationPerTick.y = Mathf.Clamp(Mathf.Abs(rotationPerTick.y), minThreshold, thresholdMax);
|
||||
}
|
||||
rotationPerTick.z = Mathf.Clamp(Mathf.Abs(rotationPerTick.z), minThreshold, thresholdMax);
|
||||
|
||||
return rotationPerTick;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the linear velocity of the Rigidbody.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// For <see cref="Rigidbody2D"/>, only the x and y components of the <see cref="Vector3"/> are applied.
|
||||
/// </remarks>
|
||||
public void SetLinearVelocity(Vector3 linearVelocity)
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
#if COM_UNITY_MODULES_PHYSICS2D_LINEAR
|
||||
m_Rigidbody2D.linearVelocity = linearVelocity;
|
||||
#else
|
||||
m_Rigidbody2D.velocity = linearVelocity;
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
m_Rigidbody.linearVelocity = linearVelocity;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the linear velocity of the Rigidbody.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// For <see cref="Rigidbody2D"/>, the <see cref="Vector3"/> velocity returned is only applied to the x and y components.
|
||||
/// </remarks>
|
||||
/// <returns><see cref="Vector3"/> as the linear velocity</returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public Vector3 GetLinearVelocity()
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
#if COM_UNITY_MODULES_PHYSICS2D_LINEAR
|
||||
return m_Rigidbody2D.linearVelocity;
|
||||
#else
|
||||
return m_Rigidbody2D.velocity;
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
return m_Rigidbody.linearVelocity;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the angular velocity for the Rigidbody.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// For <see cref="Rigidbody2D"/>, the z component of <param name="angularVelocity"/> is only used to set the angular velocity.
|
||||
/// A quick way to pass in a 2D angular velocity component is: <see cref="Vector3.forward"/> * angularVelocity (where angularVelocity is a float)
|
||||
/// </remarks>
|
||||
/// <param name="angularVelocity">the angular velocity to apply to the body</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void SetAngularVelocity(Vector3 angularVelocity)
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
m_Rigidbody2D.angularVelocity = angularVelocity.z;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_Rigidbody.angularVelocity = angularVelocity;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the angular velocity for the Rigidbody.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// For <see cref="Rigidbody2D"/>, the z component of the <see cref="Vector3"/> returned is the angular velocity of the object.
|
||||
/// </remarks>
|
||||
/// <returns>angular velocity as a <see cref="Vector3"/></returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public Vector3 GetAngularVelocity()
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
return Vector3.forward * m_Rigidbody2D.angularVelocity;
|
||||
}
|
||||
else
|
||||
{
|
||||
return m_Rigidbody.angularVelocity;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the position of the Rigidbody
|
||||
/// </summary>
|
||||
/// <returns><see cref="Vector3"/></returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public Vector3 GetPosition()
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
return m_Rigidbody2D.position;
|
||||
}
|
||||
else
|
||||
{
|
||||
return m_Rigidbody.position;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the rotation of the Rigidbody
|
||||
/// </summary>
|
||||
/// <returns><see cref="Quaternion"/></returns>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public Quaternion GetRotation()
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
var quaternion = Quaternion.identity;
|
||||
var angles = quaternion.eulerAngles;
|
||||
angles.z = m_Rigidbody2D.rotation;
|
||||
quaternion.eulerAngles = angles;
|
||||
return quaternion;
|
||||
}
|
||||
else
|
||||
{
|
||||
return m_Rigidbody.rotation;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves the rigid body
|
||||
/// </summary>
|
||||
/// <param name="position">The <see cref="Vector3"/> position to move towards</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void MovePosition(Vector3 position)
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
m_Rigidbody2D.MovePosition(position);
|
||||
}
|
||||
else
|
||||
{
|
||||
m_Rigidbody.MovePosition(position);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Directly applies a position (like teleporting)
|
||||
/// </summary>
|
||||
/// <param name="position"><see cref="Vector3"/> position to apply to the Rigidbody</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void SetPosition(Vector3 position)
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
m_Rigidbody2D.position = position;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_Rigidbody.position = position;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the rotation and position of the <see cref="GameObject"/>'s <see cref="Transform"/>
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void ApplyCurrentTransform()
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
m_Rigidbody2D.position = transform.position;
|
||||
m_Rigidbody2D.rotation = transform.eulerAngles.z;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_Rigidbody.position = transform.position;
|
||||
m_Rigidbody.rotation = transform.rotation;
|
||||
}
|
||||
}
|
||||
|
||||
// Used for Rigidbody only (see info on normalized below)
|
||||
private Vector4 m_QuaternionCheck = Vector4.zero;
|
||||
|
||||
/// <summary>
|
||||
/// Rotatates the Rigidbody towards a specified rotation
|
||||
/// </summary>
|
||||
/// <param name="rotation">The rotation expressed as a <see cref="Quaternion"/></param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void MoveRotation(Quaternion rotation)
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
var quaternion = Quaternion.identity;
|
||||
var angles = quaternion.eulerAngles;
|
||||
angles.z = m_Rigidbody2D.rotation;
|
||||
quaternion.eulerAngles = angles;
|
||||
m_Rigidbody2D.MoveRotation(quaternion);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Evidently we need to check to make sure the quaternion is a perfect
|
||||
// magnitude of 1.0f when applying the rotation to a rigid body.
|
||||
m_QuaternionCheck.x = rotation.x;
|
||||
m_QuaternionCheck.y = rotation.y;
|
||||
m_QuaternionCheck.z = rotation.z;
|
||||
m_QuaternionCheck.w = rotation.w;
|
||||
// If the magnitude is greater than 1.0f (even by a very small fractional value), then normalize the quaternion
|
||||
if (m_QuaternionCheck.magnitude != 1.0f)
|
||||
{
|
||||
rotation.Normalize();
|
||||
}
|
||||
m_Rigidbody.MoveRotation(rotation);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies a rotation to the Rigidbody
|
||||
/// </summary>
|
||||
/// <param name="rotation">The rotation to apply expressed as a <see cref="Quaternion"/></param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void SetRotation(Quaternion rotation)
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
m_Rigidbody2D.rotation = rotation.eulerAngles.z;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_Rigidbody.rotation = rotation;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the original interpolation of the Rigidbody while taking the Rigidbody type into consideration
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void SetOriginalInterpolation()
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
switch (m_Rigidbody2D.interpolation)
|
||||
{
|
||||
case RigidbodyInterpolation2D.None:
|
||||
{
|
||||
m_OriginalInterpolation = InterpolationTypes.None;
|
||||
break;
|
||||
}
|
||||
case RigidbodyInterpolation2D.Interpolate:
|
||||
{
|
||||
m_OriginalInterpolation = InterpolationTypes.Interpolate;
|
||||
break;
|
||||
}
|
||||
case RigidbodyInterpolation2D.Extrapolate:
|
||||
{
|
||||
m_OriginalInterpolation = InterpolationTypes.Extrapolate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (m_Rigidbody.interpolation)
|
||||
{
|
||||
case RigidbodyInterpolation.None:
|
||||
{
|
||||
m_OriginalInterpolation = InterpolationTypes.None;
|
||||
break;
|
||||
}
|
||||
case RigidbodyInterpolation.Interpolate:
|
||||
{
|
||||
m_OriginalInterpolation = InterpolationTypes.Interpolate;
|
||||
break;
|
||||
}
|
||||
case RigidbodyInterpolation.Extrapolate:
|
||||
{
|
||||
m_OriginalInterpolation = InterpolationTypes.Extrapolate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wakes the Rigidbody if it is sleeping
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void WakeIfSleeping()
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
if (m_Rigidbody2D.IsSleeping())
|
||||
{
|
||||
m_Rigidbody2D.WakeUp();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (m_Rigidbody.IsSleeping())
|
||||
{
|
||||
m_Rigidbody.WakeUp();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts the Rigidbody to sleep
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void SleepRigidbody()
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
m_Rigidbody2D.Sleep();
|
||||
}
|
||||
else
|
||||
{
|
||||
m_Rigidbody.Sleep();
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public bool IsKinematic()
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
return m_Rigidbody2D.bodyType == RigidbodyType2D.Kinematic;
|
||||
}
|
||||
else
|
||||
{
|
||||
return m_Rigidbody.isKinematic;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the kinematic state of the Rigidbody and handles updating the Rigidbody's
|
||||
/// interpolation setting based on the Kinematic state.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// When using the Rigidbody for <see cref="NetworkTransform"/> motion, this automatically
|
||||
/// adjusts from extrapolation to interpolation if:
|
||||
/// - The Rigidbody was originally set to extrapolation
|
||||
/// - The NetworkTransform is set to interpolate
|
||||
/// When the two above conditions are true:
|
||||
/// - When switching from non-kinematic to kinematic this will automatically
|
||||
/// switch the Rigidbody from extrapolation to interpolate.
|
||||
/// - When switching from kinematic to non-kinematic this will automatically
|
||||
/// switch the Rigidbody from interpolation back to extrapolation.
|
||||
/// </remarks>
|
||||
/// <param name="isKinematic"></param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void SetIsKinematic(bool isKinematic)
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
m_Rigidbody2D.bodyType = isKinematic ? RigidbodyType2D.Kinematic : RigidbodyType2D.Dynamic;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_Rigidbody.isKinematic = isKinematic;
|
||||
}
|
||||
|
||||
// If we are not spawned, then exit early
|
||||
if (!IsSpawned)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (UseRigidBodyForMotion)
|
||||
{
|
||||
// Only if the NetworkTransform is set to interpolate do we need to check for extrapolation
|
||||
if (NetworkTransform.Interpolate && m_OriginalInterpolation == InterpolationTypes.Extrapolate)
|
||||
{
|
||||
if (IsKinematic())
|
||||
{
|
||||
// If not already set to interpolate then set the Rigidbody to interpolate
|
||||
if (m_Rigidbody.interpolation == RigidbodyInterpolation.Extrapolate)
|
||||
{
|
||||
// Sleep until the next fixed update when switching from extrapolation to interpolation
|
||||
SleepRigidbody();
|
||||
SetInterpolation(InterpolationTypes.Interpolate);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Switch it back to the original interpolation if non-kinematic (doesn't require sleep).
|
||||
SetInterpolation(m_OriginalInterpolation);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
SetInterpolation(m_IsAuthority ? m_OriginalInterpolation : (NetworkTransform.Interpolate ? InterpolationTypes.None : m_OriginalInterpolation));
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void SetInterpolation(InterpolationTypes interpolationType)
|
||||
{
|
||||
switch (interpolationType)
|
||||
{
|
||||
case InterpolationTypes.None:
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
m_Rigidbody2D.interpolation = RigidbodyInterpolation2D.None;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_Rigidbody.interpolation = RigidbodyInterpolation.None;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case InterpolationTypes.Interpolate:
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
m_Rigidbody2D.interpolation = RigidbodyInterpolation2D.Interpolate;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_Rigidbody.interpolation = RigidbodyInterpolation.Interpolate;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case InterpolationTypes.Extrapolate:
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
m_Rigidbody2D.interpolation = RigidbodyInterpolation2D.Extrapolate;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_Rigidbody.interpolation = RigidbodyInterpolation.Extrapolate;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public void ResetInterpolation()
|
||||
{
|
||||
SetInterpolation(m_OriginalInterpolation);
|
||||
}
|
||||
|
||||
protected override void OnOwnershipChanged(ulong previous, ulong current)
|
||||
{
|
||||
UpdateOwnershipAuthority();
|
||||
base.OnOwnershipChanged(previous, current);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the authority based on whether it is server or owner authoritative
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Distributed authority sessions will always be owner authoritative.
|
||||
/// </remarks>
|
||||
internal void UpdateOwnershipAuthority()
|
||||
{
|
||||
if (NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
// When in distributed authority mode, always use HasAuthority
|
||||
m_IsAuthority = HasAuthority;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (NetworkTransform.IsServerAuthoritative())
|
||||
{
|
||||
m_IsAuthority = NetworkManager.IsServer;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_IsAuthority = IsOwner;
|
||||
}
|
||||
}
|
||||
|
||||
if (AutoUpdateKinematicState)
|
||||
{
|
||||
SetIsKinematic(!m_IsAuthority);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
m_TickFrequency = 1.0f / NetworkManager.NetworkConfig.TickRate;
|
||||
m_TickRate = NetworkManager.NetworkConfig.TickRate;
|
||||
UpdateOwnershipAuthority();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void OnNetworkDespawn()
|
||||
{
|
||||
if (UseRigidBodyForMotion && HasAuthority)
|
||||
{
|
||||
DetachFromFixedJoint();
|
||||
NetworkRigidbodyConnections.Clear();
|
||||
}
|
||||
|
||||
// If we are automatically handling the kinematic state...
|
||||
if (AutoUpdateKinematicState || AutoSetKinematicOnDespawn)
|
||||
{
|
||||
// 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)
|
||||
SetIsKinematic(true);
|
||||
}
|
||||
SetInterpolation(m_OriginalInterpolation);
|
||||
}
|
||||
|
||||
// TODO: Possibly provide a NetworkJoint that allows for more options than fixed.
|
||||
// Rigidbodies do not have the concept of "local space", and as such using a fixed joint will hold the object
|
||||
// in place relative to the parent so jitter/stutter does not occur.
|
||||
// Alternately, users can affix the fixed joint to a child GameObject (without a rigid body) of the parent NetworkObject
|
||||
// and then add a NetworkTransform to that in order to get the parented child NetworkObject to move around in "local space"
|
||||
public FixedJoint FixedJoint { get; private set; }
|
||||
public FixedJoint2D FixedJoint2D { get; private set; }
|
||||
|
||||
internal System.Collections.Generic.List<NetworkRigidbodyBase> NetworkRigidbodyConnections = new System.Collections.Generic.List<NetworkRigidbodyBase>();
|
||||
internal NetworkRigidbodyBase ParentBody;
|
||||
|
||||
private bool m_FixedJoint2DUsingGravity;
|
||||
private bool m_OriginalGravitySetting;
|
||||
private float m_OriginalGravityScale;
|
||||
|
||||
/// <summary>
|
||||
/// When using a custom <see cref="NetworkRigidbodyBase"/>, this virtual method is invoked when the
|
||||
/// <see cref="FixedJoint"/> is created in the event any additional adjustments are needed.
|
||||
/// </summary>
|
||||
protected virtual void OnFixedJointCreated()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When using a custom <see cref="NetworkRigidbodyBase"/>, this virtual method is invoked when the
|
||||
/// <see cref="FixedJoint2D"/> is created in the event any additional adjustments are needed.
|
||||
/// </summary>
|
||||
protected virtual void OnFixedJoint2DCreated()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void ApplyFixedJoint2D(NetworkRigidbodyBase bodyToConnect, Vector3 position, float connectedMassScale = 0.0f, float massScale = 1.0f, bool useGravity = false, bool zeroVelocity = true)
|
||||
{
|
||||
transform.position = position;
|
||||
m_Rigidbody2D.position = position;
|
||||
m_OriginalGravitySetting = bodyToConnect.m_Rigidbody.useGravity;
|
||||
m_FixedJoint2DUsingGravity = useGravity;
|
||||
|
||||
if (!useGravity)
|
||||
{
|
||||
m_OriginalGravityScale = m_Rigidbody2D.gravityScale;
|
||||
m_Rigidbody2D.gravityScale = 0.0f;
|
||||
}
|
||||
|
||||
if (zeroVelocity)
|
||||
{
|
||||
#if COM_UNITY_MODULES_PHYSICS2D_LINEAR
|
||||
m_Rigidbody2D.linearVelocity = Vector2.zero;
|
||||
#else
|
||||
m_Rigidbody2D.velocity = Vector2.zero;
|
||||
#endif
|
||||
m_Rigidbody2D.angularVelocity = 0.0f;
|
||||
}
|
||||
|
||||
FixedJoint2D = gameObject.AddComponent<FixedJoint2D>();
|
||||
FixedJoint2D.connectedBody = bodyToConnect.m_Rigidbody2D;
|
||||
OnFixedJoint2DCreated();
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void ApplyFixedJoint(NetworkRigidbodyBase bodyToConnectTo, Vector3 position, float connectedMassScale = 0.0f, float massScale = 1.0f, bool useGravity = false, bool zeroVelocity = true)
|
||||
{
|
||||
transform.position = position;
|
||||
m_Rigidbody.position = position;
|
||||
if (zeroVelocity)
|
||||
{
|
||||
m_Rigidbody.linearVelocity = Vector3.zero;
|
||||
m_Rigidbody.angularVelocity = Vector3.zero;
|
||||
}
|
||||
m_OriginalGravitySetting = m_Rigidbody.useGravity;
|
||||
m_Rigidbody.useGravity = useGravity;
|
||||
FixedJoint = gameObject.AddComponent<FixedJoint>();
|
||||
FixedJoint.connectedBody = bodyToConnectTo.m_Rigidbody;
|
||||
FixedJoint.connectedMassScale = connectedMassScale;
|
||||
FixedJoint.massScale = massScale;
|
||||
OnFixedJointCreated();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Authority Only:
|
||||
/// When invoked and not already attached to a fixed joint, this will connect two rigid bodies with <see cref="UseRigidBodyForMotion"/> enabled.
|
||||
/// Invoke this method on the rigid body you wish to attach to another (i.e. weapon to player, sticky bomb to player/object, etc).
|
||||
/// <seealso cref="FixedJoint"/>
|
||||
/// <seealso cref="FixedJoint2D"/>
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Parenting relative:
|
||||
/// - This instance can be viewed as the child.
|
||||
/// - The <param name="objectToConnectTo"/> can be viewed as the parent.
|
||||
/// <br/>
|
||||
/// This is the recommended way, as opposed to parenting, to attached/detatch two rigid bodies to one another when <see cref="UseRigidBodyForMotion"/> is enabled.
|
||||
/// For more details on using <see cref="UnityEngine.FixedJoint"/> and <see cref="UnityEngine.FixedJoint2D"/>.
|
||||
/// <br/>
|
||||
/// This provides a simple joint solution between two rigid bodies and serves as an example. You can add different joint types by creating a customized/derived
|
||||
/// version of <see cref="NetworkRigidbodyBase"/>.
|
||||
/// </remarks>
|
||||
/// <param name="objectToConnectTo">The target object to attach to.</param>
|
||||
/// <param name="positionOfConnection">The position of the connection (i.e. where you want the object to be affixed).</param>
|
||||
/// <param name="connectedMassScale">The target object's mass scale relative to this object being attached.</param>
|
||||
/// <param name="massScale">This object's mass scale relative to the target object's.</param>
|
||||
/// <param name="useGravity">Determines if this object will have gravity applied to it along with the object you are connecting this one to (the default is to not use gravity for this object)</param>
|
||||
/// <param name="zeroVelocity">When true (the default), both linear and angular velocities of this object are set to zero.</param>
|
||||
/// <param name="teleportObject">When true (the default), this object will teleport itself to the position of connection.</param>
|
||||
/// <returns>true (success) false (failed)</returns>
|
||||
public bool AttachToFixedJoint(NetworkRigidbodyBase objectToConnectTo, Vector3 positionOfConnection, float connectedMassScale = 0.0f, float massScale = 1.0f, bool useGravity = false, bool zeroVelocity = true, bool teleportObject = true)
|
||||
{
|
||||
if (!UseRigidBodyForMotion)
|
||||
{
|
||||
Debug.LogError($"[{GetType().Name}] {name} does not have {nameof(UseRigidBodyForMotion)} set! Either enable {nameof(UseRigidBodyForMotion)} on this component or do not use a {nameof(FixedJoint)} when parenting under a {nameof(NetworkObject)}.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (IsKinematic())
|
||||
{
|
||||
Debug.LogError($"[{GetType().Name}] {name} is currently kinematic! You cannot use a {nameof(FixedJoint)} with Kinematic bodies!");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (objectToConnectTo != null)
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
ApplyFixedJoint2D(objectToConnectTo, positionOfConnection, connectedMassScale, massScale, useGravity, zeroVelocity);
|
||||
}
|
||||
else
|
||||
{
|
||||
ApplyFixedJoint(objectToConnectTo, positionOfConnection, connectedMassScale, massScale, useGravity, zeroVelocity);
|
||||
}
|
||||
|
||||
ParentBody = objectToConnectTo;
|
||||
ParentBody.NetworkRigidbodyConnections.Add(this);
|
||||
if (teleportObject)
|
||||
{
|
||||
NetworkTransform.SetState(teleportDisabled: false);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void RemoveFromParentBody()
|
||||
{
|
||||
ParentBody.NetworkRigidbodyConnections.Remove(this);
|
||||
ParentBody = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Authority Only:
|
||||
/// When invoked and already connected to an object via <see cref="FixedJoint"/> or <see cref="FixedJoint2D"/> (depending upon the type of rigid body),
|
||||
/// this will detach from the fixed joint and destroy the fixed joint component.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This is the recommended way, as opposed to parenting, to attached/detatch two rigid bodies to one another when <see cref="UseRigidBodyForMotion"/> is enabled.
|
||||
/// </remarks>
|
||||
public void DetachFromFixedJoint()
|
||||
{
|
||||
if (!HasAuthority)
|
||||
{
|
||||
Debug.LogError($"[{name}] Only authority can invoke {nameof(DetachFromFixedJoint)}!");
|
||||
}
|
||||
if (UseRigidBodyForMotion)
|
||||
{
|
||||
if (m_IsRigidbody2D)
|
||||
{
|
||||
if (FixedJoint2D != null)
|
||||
{
|
||||
if (!m_FixedJoint2DUsingGravity)
|
||||
{
|
||||
FixedJoint2D.connectedBody.gravityScale = m_OriginalGravityScale;
|
||||
}
|
||||
FixedJoint2D.connectedBody = null;
|
||||
Destroy(FixedJoint2D);
|
||||
FixedJoint2D = null;
|
||||
ResetInterpolation();
|
||||
RemoveFromParentBody();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (FixedJoint != null)
|
||||
{
|
||||
FixedJoint.connectedBody = null;
|
||||
m_Rigidbody.useGravity = m_OriginalGravitySetting;
|
||||
Destroy(FixedJoint);
|
||||
FixedJoint = null;
|
||||
ResetInterpolation();
|
||||
RemoveFromParentBody();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // COM_UNITY_MODULES_PHYSICS
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8c4434f0563fb7f42b3b2993c97ae81a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,21 +0,0 @@
|
||||
#if COM_UNITY_MODULES_PHYSICS
|
||||
using UnityEngine;
|
||||
|
||||
namespace Unity.Netcode.Components
|
||||
{
|
||||
/// <summary>
|
||||
/// NetworkRigidbody allows for the use of <see cref="Rigidbody"/> on network objects. By controlling the kinematic
|
||||
/// mode of the <see cref="Rigidbody"/> and disabling it on all peers but the authoritative one.
|
||||
/// </summary>
|
||||
[RequireComponent(typeof(NetworkTransform))]
|
||||
[RequireComponent(typeof(Rigidbody))]
|
||||
[AddComponentMenu("Netcode/Network Rigidbody")]
|
||||
public class NetworkRigidbody : NetworkRigidbodyBase
|
||||
{
|
||||
protected virtual void Awake()
|
||||
{
|
||||
Initialize(RigidbodyTypes.Rigidbody);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // COM_UNITY_MODULES_PHYSICS
|
||||
@@ -1,11 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f6c0be61502bb534f922ebb746851216
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,21 +0,0 @@
|
||||
#if COM_UNITY_MODULES_PHYSICS2D
|
||||
using UnityEngine;
|
||||
|
||||
namespace Unity.Netcode.Components
|
||||
{
|
||||
/// <summary>
|
||||
/// NetworkRigidbody allows for the use of <see cref="Rigidbody2D"/> on network objects. By controlling the kinematic
|
||||
/// mode of the rigidbody and disabling it on all peers but the authoritative one.
|
||||
/// </summary>
|
||||
[RequireComponent(typeof(NetworkTransform))]
|
||||
[RequireComponent(typeof(Rigidbody2D))]
|
||||
[AddComponentMenu("Netcode/Network Rigidbody 2D")]
|
||||
public class NetworkRigidbody2D : NetworkRigidbodyBase
|
||||
{
|
||||
protected virtual void Awake()
|
||||
{
|
||||
Initialize(RigidbodyTypes.Rigidbody2D);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // COM_UNITY_MODULES_PHYSICS2D
|
||||
@@ -1,11 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 80d7c879794dfda4687da0e400131852
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,13 +6,70 @@ using UnityEngine;
|
||||
|
||||
namespace Unity.Netcode.Components
|
||||
{
|
||||
/// <summary>
|
||||
/// Information a <see cref="Rigidbody"/> returns to <see cref="RigidbodyContactEventManager"/> via <see cref="IContactEventHandlerWithInfo.GetContactEventHandlerInfo"/> <br />
|
||||
/// if the <see cref="Rigidbody"/> registers itself with <see cref="IContactEventHandlerWithInfo"/> as opposed to <see cref="IContactEventHandler"/>.
|
||||
/// </summary>
|
||||
public struct ContactEventHandlerInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// When set to true, the <see cref="RigidbodyContactEventManager"/> will include non-Rigidbody based contact events.<br />
|
||||
/// When the <see cref="RigidbodyContactEventManager"/> invokes the <see cref="IContactEventHandler.ContactEvent"/> it will return null in place <br />
|
||||
/// of the collidingBody parameter if the contact event occurred with a collider that is not registered with the <see cref="RigidbodyContactEventManager"/>.
|
||||
/// </summary>
|
||||
public bool ProvideNonRigidBodyContactEvents;
|
||||
/// <summary>
|
||||
/// When set to true, the <see cref="RigidbodyContactEventManager"/> will prioritize invoking <see cref="IContactEventHandler.ContactEvent(ulong, Vector3, Rigidbody, Vector3, bool, Vector3)"/> <br /></br>
|
||||
/// if it is the 2nd colliding body in the contact pair being processed. With distributed authority, setting this value to true when a <see cref="NetworkObject"/> is owned by the local client <br />
|
||||
/// will assure <see cref="IContactEventHandler.ContactEvent(ulong, Vector3, Rigidbody, Vector3, bool, Vector3)"/> is only invoked on the authoritative side.
|
||||
/// </summary>
|
||||
public bool HasContactEventPriority;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Default implementation required to register a <see cref="Rigidbody"/> with a <see cref="RigidbodyContactEventManager"/> instance.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Recommended to implement this method on a <see cref="NetworkBehaviour"/> component
|
||||
/// </remarks>
|
||||
public interface IContactEventHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// Should return a <see cref="Rigidbody"/>.
|
||||
/// </summary>
|
||||
Rigidbody GetRigidbody();
|
||||
|
||||
/// <summary>
|
||||
/// Invoked by the <see cref="RigidbodyContactEventManager"/> instance.
|
||||
/// </summary>
|
||||
/// <param name="eventId">A unique contact event identifier.</param>
|
||||
/// <param name="averagedCollisionNormal">The average normal of the collision between two colliders.</param>
|
||||
/// <param name="collidingBody">If not null, this will be a registered <see cref="Rigidbody"/> that was part of the collision contact event.</param>
|
||||
/// <param name="contactPoint">The world space location of the contact event.</param>
|
||||
/// <param name="hasCollisionStay">Will be set if this is a collision stay contact event (i.e. it is not the first contact event and continually has contact)</param>
|
||||
/// <param name="averagedCollisionStayNormal">The average normal of the collision stay contact over time.</param>
|
||||
void ContactEvent(ulong eventId, Vector3 averagedCollisionNormal, Rigidbody collidingBody, Vector3 contactPoint, bool hasCollisionStay = false, Vector3 averagedCollisionStayNormal = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This is an extended version of <see cref="IContactEventHandler"/> and can be used to register a <see cref="Rigidbody"/> with a <see cref="RigidbodyContactEventManager"/> instance.<br />
|
||||
/// This provides additional <see cref="ContactEventHandlerInfo"/> information to the <see cref="RigidbodyContactEventManager"/> for each set of contact events it is processing.
|
||||
/// </summary>
|
||||
public interface IContactEventHandlerWithInfo : IContactEventHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// Invoked by <see cref="RigidbodyContactEventManager"/> for each set of contact events it is processing (prior to processing).
|
||||
/// </summary>
|
||||
/// <returns><see cref="ContactEventHandlerInfo"/></returns>
|
||||
ContactEventHandlerInfo GetContactEventHandlerInfo();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add this component to an in-scene placed GameObject to provide faster collision event processing between <see cref="Rigidbody"/> instances and optionally static colliders.
|
||||
/// <see cref="IContactEventHandler"/><br />
|
||||
/// <see cref="IContactEventHandlerWithInfo"/><br />
|
||||
/// <see cref="ContactEventHandlerInfo"/><br />
|
||||
/// </summary>
|
||||
[AddComponentMenu("Netcode/Rigidbody Contact Event Manager")]
|
||||
public class RigidbodyContactEventManager : MonoBehaviour
|
||||
{
|
||||
@@ -34,6 +91,7 @@ namespace Unity.Netcode.Components
|
||||
|
||||
private readonly Dictionary<int, Rigidbody> m_RigidbodyMapping = new Dictionary<int, Rigidbody>();
|
||||
private readonly Dictionary<int, IContactEventHandler> m_HandlerMapping = new Dictionary<int, IContactEventHandler>();
|
||||
private readonly Dictionary<int, ContactEventHandlerInfo> m_HandlerInfo = new Dictionary<int, ContactEventHandlerInfo>();
|
||||
|
||||
private void OnEnable()
|
||||
{
|
||||
@@ -49,6 +107,15 @@ namespace Unity.Netcode.Components
|
||||
Instance = this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Any <see cref="IContactEventHandler"/> implementation can register a <see cref="Rigidbody"/> to be handled by this <see cref="RigidbodyContactEventManager"/> instance.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// You should enable <see cref="Collider.providesContacts"/> for each <see cref="Collider"/> associated with the <see cref="Rigidbody"/> being registered.<br/>
|
||||
/// You can enable this during run time or within the editor's inspector view.
|
||||
/// </remarks>
|
||||
/// <param name="contactEventHandler"><see cref="IContactEventHandler"/> or <see cref="IContactEventHandlerWithInfo"/></param>
|
||||
/// <param name="register">true to register and false to remove from being registered</param>
|
||||
public void RegisterHandler(IContactEventHandler contactEventHandler, bool register = true)
|
||||
{
|
||||
var rigidbody = contactEventHandler.GetRigidbody();
|
||||
@@ -64,6 +131,22 @@ namespace Unity.Netcode.Components
|
||||
{
|
||||
m_HandlerMapping.Add(instanceId, contactEventHandler);
|
||||
}
|
||||
|
||||
if (!m_HandlerInfo.ContainsKey(instanceId))
|
||||
{
|
||||
var handlerInfo = new ContactEventHandlerInfo()
|
||||
{
|
||||
HasContactEventPriority = true,
|
||||
ProvideNonRigidBodyContactEvents = false,
|
||||
};
|
||||
var handlerWithInfo = contactEventHandler as IContactEventHandlerWithInfo;
|
||||
|
||||
if (handlerWithInfo != null)
|
||||
{
|
||||
handlerInfo = handlerWithInfo.GetContactEventHandlerInfo();
|
||||
}
|
||||
m_HandlerInfo.Add(instanceId, handlerInfo);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -88,25 +171,98 @@ namespace Unity.Netcode.Components
|
||||
|
||||
private void ProcessCollisions()
|
||||
{
|
||||
foreach (var contactEventHandler in m_HandlerMapping)
|
||||
{
|
||||
var handlerWithInfo = contactEventHandler.Value as IContactEventHandlerWithInfo;
|
||||
|
||||
if (handlerWithInfo != null)
|
||||
{
|
||||
m_HandlerInfo[contactEventHandler.Key] = handlerWithInfo.GetContactEventHandlerInfo();
|
||||
}
|
||||
else
|
||||
{
|
||||
var info = m_HandlerInfo[contactEventHandler.Key];
|
||||
info.HasContactEventPriority = !m_RigidbodyMapping[contactEventHandler.Key].isKinematic;
|
||||
m_HandlerInfo[contactEventHandler.Key] = info;
|
||||
}
|
||||
}
|
||||
|
||||
ContactEventHandlerInfo contactEventHandlerInfo0;
|
||||
ContactEventHandlerInfo contactEventHandlerInfo1;
|
||||
|
||||
// Process all collisions
|
||||
for (int i = 0; i < m_Count; i++)
|
||||
{
|
||||
var thisInstanceID = m_ResultsArray[i].ThisInstanceID;
|
||||
var otherInstanceID = m_ResultsArray[i].OtherInstanceID;
|
||||
var rb0Valid = thisInstanceID != 0 && m_RigidbodyMapping.ContainsKey(thisInstanceID);
|
||||
var rb1Valid = otherInstanceID != 0 && m_RigidbodyMapping.ContainsKey(otherInstanceID);
|
||||
// Only notify registered rigid bodies.
|
||||
if (!rb0Valid || !rb1Valid || !m_HandlerMapping.ContainsKey(thisInstanceID))
|
||||
var contactHandler0 = (IContactEventHandler)null;
|
||||
var contactHandler1 = (IContactEventHandler)null;
|
||||
var preferredContactHandler = (IContactEventHandler)null;
|
||||
var preferredContactHandlerNonRigidbody = false;
|
||||
var preferredRigidbody = (Rigidbody)null;
|
||||
var otherContactHandler = (IContactEventHandler)null;
|
||||
var otherRigidbody = (Rigidbody)null;
|
||||
|
||||
var otherContactHandlerNonRigidbody = false;
|
||||
|
||||
if (m_RigidbodyMapping.ContainsKey(thisInstanceID))
|
||||
{
|
||||
contactHandler0 = m_HandlerMapping[thisInstanceID];
|
||||
contactEventHandlerInfo0 = m_HandlerInfo[thisInstanceID];
|
||||
if (contactEventHandlerInfo0.HasContactEventPriority)
|
||||
{
|
||||
preferredContactHandler = contactHandler0;
|
||||
preferredContactHandlerNonRigidbody = contactEventHandlerInfo0.ProvideNonRigidBodyContactEvents;
|
||||
preferredRigidbody = m_RigidbodyMapping[thisInstanceID];
|
||||
}
|
||||
else
|
||||
{
|
||||
otherContactHandler = contactHandler0;
|
||||
otherContactHandlerNonRigidbody = contactEventHandlerInfo0.ProvideNonRigidBodyContactEvents;
|
||||
otherRigidbody = m_RigidbodyMapping[thisInstanceID];
|
||||
}
|
||||
}
|
||||
|
||||
if (m_RigidbodyMapping.ContainsKey(otherInstanceID))
|
||||
{
|
||||
contactHandler1 = m_HandlerMapping[otherInstanceID];
|
||||
contactEventHandlerInfo1 = m_HandlerInfo[otherInstanceID];
|
||||
if (contactEventHandlerInfo1.HasContactEventPriority && preferredContactHandler == null)
|
||||
{
|
||||
preferredContactHandler = contactHandler1;
|
||||
preferredContactHandlerNonRigidbody = contactEventHandlerInfo1.ProvideNonRigidBodyContactEvents;
|
||||
preferredRigidbody = m_RigidbodyMapping[otherInstanceID];
|
||||
}
|
||||
else
|
||||
{
|
||||
otherContactHandler = contactHandler1;
|
||||
otherContactHandlerNonRigidbody = contactEventHandlerInfo1.ProvideNonRigidBodyContactEvents;
|
||||
otherRigidbody = m_RigidbodyMapping[otherInstanceID];
|
||||
}
|
||||
}
|
||||
|
||||
if (preferredContactHandler == null && otherContactHandler != null)
|
||||
{
|
||||
preferredContactHandler = otherContactHandler;
|
||||
preferredContactHandlerNonRigidbody = otherContactHandlerNonRigidbody;
|
||||
preferredRigidbody = otherRigidbody;
|
||||
otherContactHandler = null;
|
||||
otherContactHandlerNonRigidbody = false;
|
||||
otherRigidbody = null;
|
||||
}
|
||||
|
||||
if (preferredContactHandler == null || (preferredContactHandler != null && otherContactHandler == null && !preferredContactHandlerNonRigidbody))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (m_ResultsArray[i].HasCollisionStay)
|
||||
{
|
||||
m_HandlerMapping[thisInstanceID].ContactEvent(m_EventId, m_ResultsArray[i].AverageNormal, m_RigidbodyMapping[otherInstanceID], m_ResultsArray[i].ContactPoint, m_ResultsArray[i].HasCollisionStay, m_ResultsArray[i].AverageCollisionStayNormal);
|
||||
preferredContactHandler.ContactEvent(m_EventId, m_ResultsArray[i].AverageNormal, otherRigidbody, m_ResultsArray[i].ContactPoint, m_ResultsArray[i].HasCollisionStay, m_ResultsArray[i].AverageCollisionStayNormal);
|
||||
}
|
||||
else
|
||||
{
|
||||
m_HandlerMapping[thisInstanceID].ContactEvent(m_EventId, m_ResultsArray[i].AverageNormal, m_RigidbodyMapping[otherInstanceID], m_ResultsArray[i].ContactPoint);
|
||||
preferredContactHandler.ContactEvent(m_EventId, m_ResultsArray[i].AverageNormal, otherRigidbody, m_ResultsArray[i].ContactPoint);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,14 @@ namespace Unity.Netcode
|
||||
[Serializable]
|
||||
public class NetworkConfig
|
||||
{
|
||||
// Clamp spawn time outs to prevent dropping messages during scene events
|
||||
// Note: The legacy versions of NGO defaulted to 1s which was too low. As
|
||||
// well, the SpawnTimeOut is now being clamped to within this recommended
|
||||
// range both via UI and when NetworkManager is validated.
|
||||
internal const float MinSpawnTimeout = 10.0f;
|
||||
// Clamp spawn time outs to no more than 1 hour (really that is a bit high)
|
||||
internal const float MaxSpawnTimeout = 3600.0f;
|
||||
|
||||
/// <summary>
|
||||
/// The protocol version. Different versions doesn't talk to each other.
|
||||
/// </summary>
|
||||
@@ -132,6 +140,8 @@ namespace Unity.Netcode
|
||||
/// The amount of time a message will be held (deferred) if the destination NetworkObject needed to process the message doesn't exist yet. If the NetworkObject is not spawned within this time period, all deferred messages for that NetworkObject will be dropped.
|
||||
/// </summary>
|
||||
[Tooltip("The amount of time a message will be held (deferred) if the destination NetworkObject needed to process the message doesn't exist yet. If the NetworkObject is not spawned within this time period, all deferred messages for that NetworkObject will be dropped.")]
|
||||
|
||||
[Range(MinSpawnTimeout, MaxSpawnTimeout)]
|
||||
public float SpawnTimeout = 10f;
|
||||
|
||||
/// <summary>
|
||||
@@ -176,6 +186,21 @@ namespace Unity.Netcode
|
||||
[Tooltip("Enable (default) if you want to profile network messages with development builds and defaults to being disabled in release builds. When disabled, network messaging profiling will be disabled in development builds.")]
|
||||
public bool NetworkProfilingMetrics = true;
|
||||
|
||||
/// <summary>
|
||||
/// Invoked by <see cref="NetworkManager"/> when it is validated.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Used to check for potential legacy values that have already been serialized and/or
|
||||
/// runtime modifications to a property outside of the recommended range.
|
||||
/// For each property checked below, provide a brief description of the reason.
|
||||
/// </remarks>
|
||||
internal void OnValidate()
|
||||
{
|
||||
// Legacy NGO versions defaulted this value to 1 second that has since been determiend
|
||||
// any range less than 10 seconds can lead to dropped messages during scene events.
|
||||
SpawnTimeout = Mathf.Clamp(SpawnTimeout, MinSpawnTimeout, MaxSpawnTimeout);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a base64 encoded version of the configuration
|
||||
/// </summary>
|
||||
|
||||
58
Runtime/Configuration/SessionConfig.cs
Normal file
58
Runtime/Configuration/SessionConfig.cs
Normal file
@@ -0,0 +1,58 @@
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
internal class SessionConfig
|
||||
{
|
||||
/// <summary>
|
||||
/// The running list of session versions
|
||||
/// </summary>
|
||||
public const uint NoFeatureCompatibility = 0;
|
||||
public const uint BypassFeatureCompatible = 1;
|
||||
public const uint ServerDistributionCompatible = 2;
|
||||
|
||||
// The most current session version (!!!!set this when you increment!!!!!)
|
||||
public static uint PackageSessionVersion => ServerDistributionCompatible;
|
||||
|
||||
internal uint SessionVersion;
|
||||
|
||||
public bool ServiceSideDistribution;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Service to client
|
||||
/// Set when the client receives a <see cref="ConnectionApprovedMessage"/>
|
||||
/// </summary>
|
||||
/// <param name="serviceConfig">the session's settings</param>
|
||||
public SessionConfig(ServiceConfig serviceConfig)
|
||||
{
|
||||
SessionVersion = serviceConfig.SessionVersion;
|
||||
ServiceSideDistribution = serviceConfig.ServerRedistribution;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Can be used to directly set the version.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If a client connects that does not support session configuration then
|
||||
/// this will be invoked. The default values set in the constructor should
|
||||
/// assume that no features are available.
|
||||
/// Can also be used for mock/integration testing version handling.
|
||||
/// </remarks>
|
||||
/// <param name="version">version to set</param>
|
||||
public SessionConfig(uint version)
|
||||
{
|
||||
SessionVersion = version;
|
||||
ServiceSideDistribution = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Client to Service
|
||||
/// Default package constructor set when <see cref="NetworkManager.Initialize(bool)"/> is invoked.
|
||||
/// </summary>
|
||||
public SessionConfig()
|
||||
{
|
||||
// The current
|
||||
SessionVersion = PackageSessionVersion;
|
||||
ServiceSideDistribution = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Runtime/Configuration/SessionConfig.cs.meta
Normal file
2
Runtime/Configuration/SessionConfig.cs.meta
Normal file
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e0512e5a3e1dc484bbbf98c03a574645
|
||||
@@ -10,15 +10,54 @@ using UnityEngine;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// The connection event type set within <see cref="ConnectionEventData"/> to signify the type of connection event notification received.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <see cref="ConnectionEventData"/> is returned as a parameter of the <see cref="NetworkManager.OnConnectionEvent"/> event notification.
|
||||
/// <see cref="ClientConnected"/> and <see cref="ClientDisconnected"/> event types occur on the client-side of the newly connected client and on the server-side. <br />
|
||||
/// <see cref="PeerConnected"/> and <see cref="PeerDisconnected"/> event types occur on connected clients to notify that a new client (peer) has joined/connected.
|
||||
/// </remarks>
|
||||
public enum ConnectionEvent
|
||||
{
|
||||
/// <summary>
|
||||
/// This event is set on the client-side of the newly connected client and on the server-side.<br />
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// On the newly connected client side, the <see cref="ConnectionEventData.ClientId"/> will be the <see cref="NetworkManager.LocalClientId"/>.<br />
|
||||
/// On the server side, the <see cref="ConnectionEventData.ClientId"/> will be the ID of the client that just connected.
|
||||
/// </remarks>
|
||||
ClientConnected,
|
||||
/// <summary>
|
||||
/// This event is set on clients that are already connected to the session.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The <see cref="ConnectionEventData.ClientId"/> will be the ID of the client that just connected.
|
||||
/// </remarks>
|
||||
PeerConnected,
|
||||
/// <summary>
|
||||
/// This event is set on the client-side of the client that disconnected client and on the server-side.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// On the disconnected client side, the <see cref="ConnectionEventData.ClientId"/> will be the <see cref="NetworkManager.LocalClientId"/>.<br />
|
||||
/// On the server side, this will be the ID of the client that disconnected.
|
||||
/// </remarks>
|
||||
ClientDisconnected,
|
||||
/// <summary>
|
||||
/// This event is set on clients that are already connected to the session.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The <see cref="ConnectionEventData.ClientId"/> will be the ID of the client that just disconnected.
|
||||
/// </remarks>
|
||||
PeerDisconnected
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returned as a parameter of the <see cref="NetworkManager.OnConnectionEvent"/> event notification.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// See <see cref="ConnectionEvent"/> for more details on the types of connection events received.
|
||||
/// </remarks>
|
||||
public struct ConnectionEventData
|
||||
{
|
||||
public ConnectionEvent EventType;
|
||||
@@ -105,8 +144,12 @@ namespace Unity.Netcode
|
||||
continue;
|
||||
}
|
||||
|
||||
peerClientIds[idx] = peerId;
|
||||
++idx;
|
||||
// This assures if the server has not timed out prior to the client synchronizing that it doesn't exceed the allocated peer count.
|
||||
if (peerClientIds.Length > idx)
|
||||
{
|
||||
peerClientIds[idx] = peerId;
|
||||
++idx;
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
@@ -496,24 +539,32 @@ namespace Unity.Netcode
|
||||
// Process the incoming message queue so that we get everything from the server disconnecting us or, if we are the server, so we got everything from that client.
|
||||
MessageManager.ProcessIncomingMessageQueue();
|
||||
|
||||
InvokeOnClientDisconnectCallback(clientId);
|
||||
|
||||
if (LocalClient.IsHost)
|
||||
{
|
||||
InvokeOnPeerDisconnectedCallback(clientId);
|
||||
}
|
||||
|
||||
if (LocalClient.IsServer)
|
||||
{
|
||||
// We need to process the disconnection before notifying
|
||||
OnClientDisconnectFromServer(clientId);
|
||||
|
||||
// Now notify the client has disconnected
|
||||
InvokeOnClientDisconnectCallback(clientId);
|
||||
|
||||
if (LocalClient.IsHost)
|
||||
{
|
||||
InvokeOnPeerDisconnectedCallback(clientId);
|
||||
}
|
||||
}
|
||||
else // As long as we are not in the middle of a shutdown
|
||||
if (!NetworkManager.ShutdownInProgress)
|
||||
else
|
||||
{
|
||||
// We must pass true here and not process any sends messages as we are no longer connected.
|
||||
// Otherwise, attempting to process messages here can cause an exception within UnityTransport
|
||||
// as the client ID is no longer valid.
|
||||
NetworkManager.Shutdown(true);
|
||||
// Notify local client of disconnection
|
||||
InvokeOnClientDisconnectCallback(clientId);
|
||||
|
||||
// As long as we are not in the middle of a shutdown
|
||||
if (!NetworkManager.ShutdownInProgress)
|
||||
{
|
||||
// We must pass true here and not process any sends messages as we are no longer connected.
|
||||
// Otherwise, attempting to process messages here can cause an exception within UnityTransport
|
||||
// as the client ID is no longer valid.
|
||||
NetworkManager.Shutdown(true);
|
||||
}
|
||||
}
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
s_TransportDisconnect.End();
|
||||
@@ -551,10 +602,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
var message = new ConnectionRequestMessage
|
||||
{
|
||||
CMBServiceConnection = NetworkManager.CMBServiceConnection,
|
||||
TickRate = NetworkManager.NetworkConfig.TickRate,
|
||||
EnableSceneManagement = NetworkManager.NetworkConfig.EnableSceneManagement,
|
||||
|
||||
DistributedAuthority = NetworkManager.DistributedAuthorityMode,
|
||||
// Since only a remote client will send a connection request, we should always force the rebuilding of the NetworkConfig hash value
|
||||
ConfigHash = NetworkManager.NetworkConfig.GetConfig(false),
|
||||
ShouldSendConnectionData = NetworkManager.NetworkConfig.ConnectionApproval,
|
||||
@@ -562,6 +610,13 @@ namespace Unity.Netcode
|
||||
MessageVersions = new NativeArray<MessageVersionData>(MessageManager.MessageHandlers.Length, Allocator.Temp)
|
||||
};
|
||||
|
||||
if (NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
message.ClientConfig.SessionConfig = NetworkManager.SessionConfig;
|
||||
message.ClientConfig.TickRate = NetworkManager.NetworkConfig.TickRate;
|
||||
message.ClientConfig.EnableSceneManagement = NetworkManager.NetworkConfig.EnableSceneManagement;
|
||||
}
|
||||
|
||||
for (int index = 0; index < MessageManager.MessageHandlers.Length; index++)
|
||||
{
|
||||
if (MessageManager.MessageTypes[index] != null)
|
||||
@@ -735,42 +790,23 @@ namespace Unity.Netcode
|
||||
RemovePendingClient(ownerClientId);
|
||||
|
||||
var client = AddClient(ownerClientId);
|
||||
if (!NetworkManager.DistributedAuthorityMode && response.CreatePlayerObject && NetworkManager.NetworkConfig.PlayerPrefab != null)
|
||||
|
||||
// Server-side spawning (only if there is a prefab hash or player prefab provided)
|
||||
if (!NetworkManager.DistributedAuthorityMode && response.CreatePlayerObject && (response.PlayerPrefabHash.HasValue || NetworkManager.NetworkConfig.PlayerPrefab != null))
|
||||
{
|
||||
var prefabNetworkObject = NetworkManager.NetworkConfig.PlayerPrefab.GetComponent<NetworkObject>();
|
||||
var playerPrefabHash = response.PlayerPrefabHash ?? prefabNetworkObject.GlobalObjectIdHash;
|
||||
|
||||
// Generate a SceneObject for the player object to spawn
|
||||
// Note: This is only to create the local NetworkObject, many of the serialized properties of the player prefab will be set when instantiated.
|
||||
var sceneObject = new NetworkObject.SceneObject
|
||||
{
|
||||
OwnerClientId = ownerClientId,
|
||||
IsPlayerObject = true,
|
||||
IsSceneObject = false,
|
||||
HasTransform = prefabNetworkObject.SynchronizeTransform,
|
||||
Hash = playerPrefabHash,
|
||||
TargetClientId = ownerClientId,
|
||||
DontDestroyWithOwner = prefabNetworkObject.DontDestroyWithOwner,
|
||||
Transform = new NetworkObject.SceneObject.TransformData
|
||||
{
|
||||
Position = response.Position.GetValueOrDefault(),
|
||||
Rotation = response.Rotation.GetValueOrDefault()
|
||||
}
|
||||
};
|
||||
|
||||
// Create the player NetworkObject locally
|
||||
var networkObject = NetworkManager.SpawnManager.CreateLocalNetworkObject(sceneObject);
|
||||
var playerObject = response.PlayerPrefabHash.HasValue ? NetworkManager.SpawnManager.GetNetworkObjectToSpawn(response.PlayerPrefabHash.Value, ownerClientId, response.Position ?? null, response.Rotation ?? null)
|
||||
: NetworkManager.SpawnManager.GetNetworkObjectToSpawn(NetworkManager.NetworkConfig.PlayerPrefab.GetComponent<NetworkObject>().GlobalObjectIdHash, ownerClientId, response.Position ?? null, response.Rotation ?? null);
|
||||
|
||||
// Spawn the player NetworkObject locally
|
||||
NetworkManager.SpawnManager.SpawnNetworkObjectLocally(
|
||||
networkObject,
|
||||
playerObject,
|
||||
NetworkManager.SpawnManager.GetNetworkObjectId(),
|
||||
sceneObject: false,
|
||||
playerObject: true,
|
||||
ownerClientId,
|
||||
destroyWithScene: false);
|
||||
|
||||
client.AssignPlayerObject(ref networkObject);
|
||||
client.AssignPlayerObject(ref playerObject);
|
||||
}
|
||||
|
||||
// Server doesn't send itself the connection approved message
|
||||
@@ -871,6 +907,7 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
// Exit early if no player object was spawned
|
||||
if (!response.CreatePlayerObject || (response.PlayerPrefabHash == null && NetworkManager.NetworkConfig.PlayerPrefab == null))
|
||||
{
|
||||
return;
|
||||
@@ -902,7 +939,7 @@ namespace Unity.Netcode
|
||||
/// <summary>
|
||||
/// Client-Side Spawning in distributed authority mode uses this to spawn the player.
|
||||
/// </summary>
|
||||
internal void CreateAndSpawnPlayer(ulong ownerId, Vector3 position = default, Quaternion rotation = default)
|
||||
internal void CreateAndSpawnPlayer(ulong ownerId)
|
||||
{
|
||||
if (NetworkManager.DistributedAuthorityMode && NetworkManager.AutoSpawnPlayerPrefabClientSide)
|
||||
{
|
||||
@@ -910,7 +947,7 @@ namespace Unity.Netcode
|
||||
if (playerPrefab != null)
|
||||
{
|
||||
var globalObjectIdHash = playerPrefab.GetComponent<NetworkObject>().GlobalObjectIdHash;
|
||||
var networkObject = NetworkManager.SpawnManager.GetNetworkObjectToSpawn(globalObjectIdHash, ownerId, position, rotation);
|
||||
var networkObject = NetworkManager.SpawnManager.GetNetworkObjectToSpawn(globalObjectIdHash, ownerId, playerPrefab.transform.position, playerPrefab.transform.rotation);
|
||||
networkObject.IsSceneObject = false;
|
||||
networkObject.SpawnAsPlayerObject(ownerId, networkObject.DestroyWithScene);
|
||||
}
|
||||
@@ -1003,10 +1040,26 @@ namespace Unity.Netcode
|
||||
ConnectedClientIds.Add(clientId);
|
||||
}
|
||||
|
||||
var distributedAuthority = NetworkManager.DistributedAuthorityMode;
|
||||
|
||||
// If not using DA return early or if using DA and scene management is disabled then exit early Since we use NetworkShow to spawn
|
||||
// objects on the newly connected client side.
|
||||
if (!distributedAuthority || distributedAuthority && !NetworkManager.NetworkConfig.EnableSceneManagement)
|
||||
{
|
||||
return networkClient;
|
||||
}
|
||||
|
||||
var sessionOwnerId = NetworkManager.CurrentSessionOwner;
|
||||
var isSessionOwner = NetworkManager.LocalClient.IsSessionOwner;
|
||||
foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList)
|
||||
{
|
||||
if (networkObject.SpawnWithObservers)
|
||||
{
|
||||
// Don't add the client to the observers if hidden from the session owner
|
||||
if (networkObject.IsOwner && distributedAuthority && !isSessionOwner && !networkObject.Observers.Contains(sessionOwnerId))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
networkObject.Observers.Add(clientId);
|
||||
}
|
||||
}
|
||||
@@ -1159,7 +1212,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
// Only NetworkObjects that have the OwnershipStatus.Distributable flag set and no parent
|
||||
// (ownership is transferred to all children) will have their ownership redistributed.
|
||||
if (ownedObject.IsOwnershipDistributable && ownedObject.GetCachedParent() == null)
|
||||
if (ownedObject.IsOwnershipDistributable && ownedObject.GetCachedParent() == null && !ownedObject.IsOwnershipSessionOwner)
|
||||
{
|
||||
if (ownedObject.IsOwnershipLocked)
|
||||
{
|
||||
@@ -1196,6 +1249,11 @@ namespace Unity.Netcode
|
||||
childObject.SetOwnershipLock(false);
|
||||
}
|
||||
|
||||
// Ignore session owner marked objects
|
||||
if (childObject.IsOwnershipSessionOwner)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
NetworkManager.SpawnManager.ChangeOwnership(childObject, targetOwner, true);
|
||||
if (EnableDistributeLogging)
|
||||
{
|
||||
@@ -1309,7 +1367,15 @@ namespace Unity.Netcode
|
||||
{
|
||||
if (!LocalClient.IsServer)
|
||||
{
|
||||
throw new NotServerException($"Only server can disconnect remote clients. Please use `{nameof(Shutdown)}()` instead.");
|
||||
if (NetworkManager.NetworkConfig.NetworkTopology == NetworkTopologyTypes.ClientServer)
|
||||
{
|
||||
throw new NotServerException($"Only server can disconnect remote clients. Please use `{nameof(Shutdown)}()` instead.");
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogWarning($"Currently, clients cannot disconnect other clients from a distributed authority session. Please use `{nameof(Shutdown)}()` instead.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (clientId == NetworkManager.ServerClientId)
|
||||
|
||||
@@ -19,6 +19,12 @@ namespace Unity.Netcode
|
||||
/// </summary>
|
||||
public abstract class NetworkBehaviour : MonoBehaviour
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
[HideInInspector]
|
||||
[SerializeField]
|
||||
internal bool ShowTopMostFoldoutHeaderGroup = true;
|
||||
#endif
|
||||
|
||||
#pragma warning disable IDE1006 // disable naming rule violation check
|
||||
|
||||
// RuntimeAccessModifiersILPP will make this `public`
|
||||
@@ -688,6 +694,8 @@ namespace Unity.Netcode
|
||||
/// </remarks>
|
||||
protected virtual void OnNetworkPostSpawn() { }
|
||||
|
||||
protected internal virtual void InternalOnNetworkPostSpawn() { }
|
||||
|
||||
/// <summary>
|
||||
/// This method is only available client-side.
|
||||
/// When a new client joins it's synchronized with all spawned NetworkObjects and scenes loaded for the session joined. At the end of the synchronization process, when all
|
||||
@@ -700,6 +708,8 @@ namespace Unity.Netcode
|
||||
/// </remarks>
|
||||
protected virtual void OnNetworkSessionSynchronized() { }
|
||||
|
||||
protected internal virtual void InternalOnNetworkSessionSynchronized() { }
|
||||
|
||||
/// <summary>
|
||||
/// When a scene is loaded and in-scene placed NetworkObjects are finished spawning, this method is invoked on all of the newly spawned in-scene placed NetworkObjects.
|
||||
/// This method runs both client and server side.
|
||||
@@ -759,6 +769,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
try
|
||||
{
|
||||
InternalOnNetworkPostSpawn();
|
||||
OnNetworkPostSpawn();
|
||||
}
|
||||
catch (Exception e)
|
||||
@@ -771,6 +782,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
try
|
||||
{
|
||||
InternalOnNetworkSessionSynchronized();
|
||||
OnNetworkSessionSynchronized();
|
||||
}
|
||||
catch (Exception e)
|
||||
@@ -806,13 +818,21 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets called when the local client gains ownership of this object.
|
||||
/// In client-server contexts, this method is invoked on both the server and the local client of the owner when <see cref="Netcode.NetworkObject"/> ownership is assigned.
|
||||
/// <para>In distributed authority contexts, this method is only invoked on the local client that has been assigned ownership of the associated <see cref="Netcode.NetworkObject"/>.</para>
|
||||
/// </summary>
|
||||
public virtual void OnGainedOwnership() { }
|
||||
|
||||
internal void InternalOnGainedOwnership()
|
||||
{
|
||||
UpdateNetworkProperties();
|
||||
// New owners need to assure any NetworkVariables they have write permissions
|
||||
// to are updated so the previous and original values are aligned with the
|
||||
// current value (primarily for collections).
|
||||
if (OwnerClientId == NetworkManager.LocalClientId)
|
||||
{
|
||||
UpdateNetworkVariableOnOwnershipChanged();
|
||||
}
|
||||
OnGainedOwnership();
|
||||
}
|
||||
|
||||
@@ -834,7 +854,9 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets called when ownership of this object is lost.
|
||||
/// In client-server contexts, this method is invoked on the local client when it loses ownership of the associated <see cref="Netcode.NetworkObject"/>
|
||||
/// and on the server when any client loses ownership.
|
||||
/// <para>In distributed authority contexts, this method is only invoked on the local client that has lost ownership of the associated <see cref="Netcode.NetworkObject"/>.</para>
|
||||
/// </summary>
|
||||
public virtual void OnLostOwnership() { }
|
||||
|
||||
@@ -850,6 +872,8 @@ namespace Unity.Netcode
|
||||
/// <param name="parentNetworkObject">the new <see cref="NetworkObject"/> parent</param>
|
||||
public virtual void OnNetworkObjectParentChanged(NetworkObject parentNetworkObject) { }
|
||||
|
||||
internal virtual void InternalOnNetworkObjectParentChanged(NetworkObject parentNetworkObject) { }
|
||||
|
||||
private bool m_VarInit = false;
|
||||
|
||||
private readonly List<HashSet<int>> m_DeliveryMappedNetworkVariableIndices = new List<HashSet<int>>();
|
||||
@@ -999,9 +1023,14 @@ namespace Unity.Netcode
|
||||
internal readonly List<int> NetworkVariableIndexesToReset = new List<int>();
|
||||
internal readonly HashSet<int> NetworkVariableIndexesToResetSet = new HashSet<int>();
|
||||
|
||||
internal void NetworkVariableUpdate(ulong targetClientId)
|
||||
/// <summary>
|
||||
/// Determines if a NetworkVariable should have any changes to state sent out
|
||||
/// </summary>
|
||||
/// <param name="targetClientId">target to send the updates to</param>
|
||||
/// <param name="forceSend">specific to change in ownership</param>
|
||||
internal void NetworkVariableUpdate(ulong targetClientId, bool forceSend = false)
|
||||
{
|
||||
if (!CouldHaveDirtyNetworkVariables())
|
||||
if (!forceSend && !CouldHaveDirtyNetworkVariables())
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -1052,7 +1081,11 @@ namespace Unity.Netcode
|
||||
NetworkBehaviourIndex = behaviourIndex,
|
||||
NetworkBehaviour = this,
|
||||
TargetClientId = targetClientId,
|
||||
DeliveryMappedNetworkVariableIndex = m_DeliveryMappedNetworkVariableIndices[j]
|
||||
DeliveryMappedNetworkVariableIndex = m_DeliveryMappedNetworkVariableIndices[j],
|
||||
// By sending the network delivery we can forward messages immediately as opposed to processing them
|
||||
// at the end. While this will send updates to clients that cannot read, the handler will ignore anything
|
||||
// sent to a client that does not have read permissions.
|
||||
NetworkDelivery = m_DeliveryTypesForNetworkVariableGroups[j]
|
||||
};
|
||||
// TODO: Serialization is where the IsDirty flag gets changed.
|
||||
// Messages don't get sent from the server to itself, so if we're host and sending to ourselves,
|
||||
@@ -1097,6 +1130,26 @@ namespace Unity.Netcode
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invoked on a new client to assure the previous and original values
|
||||
/// are synchronized with the current known value.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Primarily for collections to assure the previous value(s) is/are the
|
||||
/// same as the current value(s) in order to not re-send already known entries.
|
||||
/// </remarks>
|
||||
internal void UpdateNetworkVariableOnOwnershipChanged()
|
||||
{
|
||||
for (int j = 0; j < NetworkVariableFields.Count; j++)
|
||||
{
|
||||
// Only invoke OnInitialize on NetworkVariables the owner can write to
|
||||
if (NetworkVariableFields[j].CanClientWrite(OwnerClientId))
|
||||
{
|
||||
NetworkVariableFields[j].OnInitialize();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal void MarkVariablesDirty(bool dirty)
|
||||
{
|
||||
for (int j = 0; j < NetworkVariableFields.Count; j++)
|
||||
@@ -1105,6 +1158,17 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
internal void MarkOwnerReadVariablesDirty()
|
||||
{
|
||||
for (int j = 0; j < NetworkVariableFields.Count; j++)
|
||||
{
|
||||
if (NetworkVariableFields[j].ReadPerm == NetworkVariableReadPermission.Owner)
|
||||
{
|
||||
NetworkVariableFields[j].SetDirty(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Synchronizes by setting only the NetworkVariable field values that the client has permission to read.
|
||||
/// Note: This is only invoked when first synchronizing a NetworkBehaviour (i.e. late join or spawned NetworkObject)
|
||||
@@ -1117,14 +1181,8 @@ namespace Unity.Netcode
|
||||
{
|
||||
// Create any values that require accessing the NetworkManager locally (it is expensive to access it in NetworkBehaviour)
|
||||
var networkManager = NetworkManager;
|
||||
var distributedAuthority = networkManager.DistributedAuthorityMode;
|
||||
var ensureLengthSafety = networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety;
|
||||
|
||||
// Always write the NetworkVariable count even if zero for distributed authority (used by comb server)
|
||||
if (distributedAuthority)
|
||||
{
|
||||
writer.WriteValueSafe((ushort)NetworkVariableFields.Count);
|
||||
}
|
||||
|
||||
// Exit early if there are no NetworkVariables
|
||||
if (NetworkVariableFields.Count == 0)
|
||||
@@ -1139,14 +1197,8 @@ namespace Unity.Netcode
|
||||
if (NetworkVariableFields[j].CanClientRead(targetClientId))
|
||||
{
|
||||
// Write additional NetworkVariable information when length safety is enabled or when in distributed authority mode
|
||||
if (ensureLengthSafety || distributedAuthority)
|
||||
if (ensureLengthSafety)
|
||||
{
|
||||
// Write the type being serialized for distributed authority (only for comb-server)
|
||||
if (distributedAuthority)
|
||||
{
|
||||
writer.WriteValueSafe(NetworkVariableFields[j].Type);
|
||||
}
|
||||
|
||||
var writePos = writer.Position;
|
||||
// Note: This value can't be packed because we don't know how large it will be in advance
|
||||
// we reserve space for it, then write the data, then come back and fill in the space
|
||||
@@ -1155,17 +1207,24 @@ namespace Unity.Netcode
|
||||
// The way we do packing, any value > 63 in a ushort will use the full 2 bytes to represent.
|
||||
writer.WriteValueSafe((ushort)0);
|
||||
var startPos = writer.Position;
|
||||
NetworkVariableFields[j].WriteField(writer);
|
||||
// Write the NetworkVariable field value
|
||||
// WriteFieldSynchronization will write the current value only if there are no pending changes.
|
||||
// Otherwise, it will write the previous value if there are pending changes since the pending
|
||||
// changes will be sent shortly after the client's synchronization.
|
||||
NetworkVariableFields[j].WriteFieldSynchronization(writer);
|
||||
var size = writer.Position - startPos;
|
||||
writer.Seek(writePos);
|
||||
// Write the NetworkVariable value
|
||||
// Write the NetworkVariable field value size
|
||||
writer.WriteValueSafe((ushort)size);
|
||||
writer.Seek(startPos + size);
|
||||
}
|
||||
else // Client-Server Only: Should only ever be invoked when using a client-server NetworkTopology
|
||||
{
|
||||
// Write the NetworkVariable value
|
||||
NetworkVariableFields[j].WriteField(writer);
|
||||
// Write the NetworkVariable field value
|
||||
// WriteFieldSynchronization will write the current value only if there are no pending changes.
|
||||
// Otherwise, it will write the previous value if there are pending changes since the pending
|
||||
// changes will be sent shortly after the client's synchronization.
|
||||
NetworkVariableFields[j].WriteFieldSynchronization(writer);
|
||||
}
|
||||
}
|
||||
else if (ensureLengthSafety)
|
||||
@@ -1190,20 +1249,8 @@ namespace Unity.Netcode
|
||||
{
|
||||
// Stack cache any values that requires accessing the NetworkManager (it is expensive to access it in NetworkBehaviour)
|
||||
var networkManager = NetworkManager;
|
||||
var distributedAuthority = networkManager.DistributedAuthorityMode;
|
||||
var ensureLengthSafety = networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety;
|
||||
|
||||
// Always read the NetworkVariable count when in distributed authority (sanity check if comb-server matches what client has locally)
|
||||
if (distributedAuthority)
|
||||
{
|
||||
reader.ReadValueSafe(out ushort variableCount);
|
||||
if (variableCount != NetworkVariableFields.Count)
|
||||
{
|
||||
Debug.LogError($"[{name}][NetworkObjectId: {NetworkObjectId}][NetworkBehaviourId: {NetworkBehaviourId}] NetworkVariable count mismatch! (Read: {variableCount} vs. Expected: {NetworkVariableFields.Count})");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Exit early if nothing else to read
|
||||
if (NetworkVariableFields.Count == 0)
|
||||
{
|
||||
@@ -1218,14 +1265,8 @@ namespace Unity.Netcode
|
||||
// Distributed Authority: All clients have read permissions, always try to read the value
|
||||
if (NetworkVariableFields[j].CanClientRead(clientId))
|
||||
{
|
||||
if (ensureLengthSafety || distributedAuthority)
|
||||
if (ensureLengthSafety)
|
||||
{
|
||||
// Read the type being serialized and discard it (for now) when in a distributed authority network topology (only used by comb-server)
|
||||
if (distributedAuthority)
|
||||
{
|
||||
reader.ReadValueSafe(out NetworkVariableType _);
|
||||
}
|
||||
|
||||
reader.ReadValueSafe(out varSize);
|
||||
if (varSize == 0)
|
||||
{
|
||||
@@ -1249,11 +1290,11 @@ namespace Unity.Netcode
|
||||
continue;
|
||||
}
|
||||
|
||||
// Read the NetworkVarible value
|
||||
// Read the NetworkVariable value
|
||||
NetworkVariableFields[j].ReadField(reader);
|
||||
|
||||
// When EnsureNetworkVariableLengthSafety or DistributedAuthorityMode always do a bounds check
|
||||
if (ensureLengthSafety || distributedAuthority)
|
||||
// When EnsureNetworkVariableLengthSafety always do a bounds check
|
||||
if (ensureLengthSafety)
|
||||
{
|
||||
if (reader.Position > (readStartPos + varSize))
|
||||
{
|
||||
|
||||
@@ -19,10 +19,15 @@ namespace Unity.Netcode
|
||||
|
||||
internal void AddForUpdate(NetworkObject networkObject)
|
||||
{
|
||||
// Since this is a HashSet, we don't need to worry about duplicate entries
|
||||
m_PendingDirtyNetworkObjects.Add(networkObject);
|
||||
}
|
||||
|
||||
internal void NetworkBehaviourUpdate()
|
||||
/// <summary>
|
||||
/// Sends NetworkVariable deltas
|
||||
/// </summary>
|
||||
/// <param name="forceSend">internal only, when changing ownership we want to send this before the change in ownership message</param>
|
||||
internal void NetworkBehaviourUpdate(bool forceSend = false)
|
||||
{
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
m_NetworkBehaviourUpdate.Begin();
|
||||
@@ -53,7 +58,7 @@ namespace Unity.Netcode
|
||||
// Sync just the variables for just the objects this client sees
|
||||
for (int k = 0; k < dirtyObj.ChildNetworkBehaviours.Count; k++)
|
||||
{
|
||||
dirtyObj.ChildNetworkBehaviours[k].NetworkVariableUpdate(client.ClientId);
|
||||
dirtyObj.ChildNetworkBehaviours[k].NetworkVariableUpdate(client.ClientId, forceSend);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -72,7 +77,7 @@ namespace Unity.Netcode
|
||||
}
|
||||
for (int k = 0; k < sobj.ChildNetworkBehaviours.Count; k++)
|
||||
{
|
||||
sobj.ChildNetworkBehaviours[k].NetworkVariableUpdate(NetworkManager.ServerClientId);
|
||||
sobj.ChildNetworkBehaviours[k].NetworkVariableUpdate(NetworkManager.ServerClientId, forceSend);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -85,19 +90,24 @@ namespace Unity.Netcode
|
||||
var behaviour = dirtyObj.ChildNetworkBehaviours[k];
|
||||
for (int i = 0; i < behaviour.NetworkVariableFields.Count; i++)
|
||||
{
|
||||
// Set to true for NetworkVariable to ignore duplication of the
|
||||
// "internal original value" for collections support.
|
||||
behaviour.NetworkVariableFields[i].NetworkUpdaterCheck = true;
|
||||
if (behaviour.NetworkVariableFields[i].IsDirty() &&
|
||||
!behaviour.NetworkVariableIndexesToResetSet.Contains(i))
|
||||
{
|
||||
behaviour.NetworkVariableIndexesToResetSet.Add(i);
|
||||
behaviour.NetworkVariableIndexesToReset.Add(i);
|
||||
}
|
||||
// Reset back to false when done
|
||||
behaviour.NetworkVariableFields[i].NetworkUpdaterCheck = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Now, reset all the no-longer-dirty variables
|
||||
foreach (var dirtyobj in m_DirtyNetworkObjects)
|
||||
{
|
||||
dirtyobj.PostNetworkVariableWrite();
|
||||
dirtyobj.PostNetworkVariableWrite(forceSend);
|
||||
// Once done processing, we set the previous owner id to the current owner id
|
||||
dirtyobj.PreviousOwnerId = dirtyobj.OwnerClientId;
|
||||
}
|
||||
@@ -131,6 +141,9 @@ namespace Unity.Netcode
|
||||
|
||||
// Then show any NetworkObjects queued to be made visible/shown
|
||||
m_NetworkManager.SpawnManager.HandleNetworkObjectShow();
|
||||
|
||||
// Handle object redistribution (DA + disabled scene management only)
|
||||
m_NetworkManager.HandleRedistributionToClients();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,10 +5,10 @@ using System.Linq;
|
||||
using UnityEngine;
|
||||
#if UNITY_EDITOR
|
||||
using UnityEditor;
|
||||
using PackageInfo = UnityEditor.PackageManager.PackageInfo;
|
||||
#endif
|
||||
using UnityEngine.SceneManagement;
|
||||
using Debug = UnityEngine.Debug;
|
||||
using Unity.Netcode.Components;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
@@ -18,6 +18,23 @@ namespace Unity.Netcode
|
||||
[AddComponentMenu("Netcode/Network Manager", -100)]
|
||||
public class NetworkManager : MonoBehaviour, INetworkUpdateSystem
|
||||
{
|
||||
/// <summary>
|
||||
/// Subscribe to this static event to get notifications when a <see cref="NetworkManager"/> instance has been instantiated.
|
||||
/// </summary>
|
||||
public static event Action<NetworkManager> OnInstantiated;
|
||||
|
||||
/// <summary>
|
||||
/// Subscribe to this static event to get notifications when a <see cref="NetworkManager"/> instance is being destroyed.
|
||||
/// </summary>
|
||||
public static event Action<NetworkManager> OnDestroying;
|
||||
|
||||
|
||||
#if UNITY_EDITOR
|
||||
// Inspector view expand/collapse settings for this derived child class
|
||||
[HideInInspector]
|
||||
public bool NetworkManagerExpanded;
|
||||
#endif
|
||||
|
||||
// TODO: Deprecate...
|
||||
// The following internal values are not used, but because ILPP makes them public in the assembly, they cannot
|
||||
// be removed thanks to our semver validation.
|
||||
@@ -63,6 +80,18 @@ namespace Unity.Netcode
|
||||
}
|
||||
#endif
|
||||
|
||||
internal SessionConfig SessionConfig;
|
||||
|
||||
/// <summary>
|
||||
/// Used for internal testing purposes
|
||||
/// </summary>
|
||||
internal delegate SessionConfig OnGetSessionConfigHandler();
|
||||
internal OnGetSessionConfigHandler OnGetSessionConfig;
|
||||
private SessionConfig GetSessionConfig()
|
||||
{
|
||||
return OnGetSessionConfig != null ? OnGetSessionConfig.Invoke() : new SessionConfig();
|
||||
}
|
||||
|
||||
internal static bool IsDistributedAuthority;
|
||||
|
||||
/// <summary>
|
||||
@@ -145,10 +174,30 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
// DANGO-TODO-MVP: Remove these properties once the service handles object distribution
|
||||
internal ulong ClientToRedistribute;
|
||||
internal bool RedistributeToClient;
|
||||
internal int TickToRedistribute;
|
||||
// DANGO-TODO: Determine if this needs to be removed once the service handles object distribution
|
||||
internal List<ulong> ClientsToRedistribute = new List<ulong>();
|
||||
internal bool RedistributeToClients;
|
||||
|
||||
/// <summary>
|
||||
/// Handles object redistribution when scene management is disabled.
|
||||
/// <see cref="NetworkBehaviourUpdater.NetworkBehaviourUpdater_Tick"/>
|
||||
/// DANGO-TODO: Determine if this needs to be removed once the service handles object distribution
|
||||
/// </summary>
|
||||
internal void HandleRedistributionToClients()
|
||||
{
|
||||
if (!DistributedAuthorityMode || !RedistributeToClients || NetworkConfig.EnableSceneManagement || ShutdownInProgress)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var clientId in ClientsToRedistribute)
|
||||
{
|
||||
SpawnManager.DistributeNetworkObjects(clientId);
|
||||
}
|
||||
RedistributeToClients = false;
|
||||
ClientsToRedistribute.Clear();
|
||||
}
|
||||
|
||||
|
||||
internal List<NetworkObject> DeferredDespawnObjects = new List<NetworkObject>();
|
||||
|
||||
@@ -176,11 +225,7 @@ namespace Unity.Netcode
|
||||
foreach (var networkObjectEntry in SpawnManager.SpawnedObjects)
|
||||
{
|
||||
var networkObject = networkObjectEntry.Value;
|
||||
if (networkObject.IsSceneObject == null || !networkObject.IsSceneObject.Value)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (networkObject.OwnerClientId != LocalClientId)
|
||||
if (networkObject.IsOwnershipSessionOwner && LocalClient.IsSessionOwner)
|
||||
{
|
||||
SpawnManager.ChangeOwnership(networkObject, LocalClientId, true);
|
||||
}
|
||||
@@ -190,7 +235,6 @@ namespace Unity.Netcode
|
||||
OnSessionOwnerPromoted?.Invoke(sessionOwner);
|
||||
}
|
||||
|
||||
// TODO: Make this internal after testing
|
||||
internal void PromoteSessionOwner(ulong clientId)
|
||||
{
|
||||
if (!DistributedAuthorityMode)
|
||||
@@ -215,25 +259,25 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
internal Dictionary<ulong, NetworkTransform> NetworkTransformUpdate = new Dictionary<ulong, NetworkTransform>();
|
||||
internal Dictionary<ulong, NetworkObject> NetworkTransformUpdate = new Dictionary<ulong, NetworkObject>();
|
||||
#if COM_UNITY_MODULES_PHYSICS
|
||||
internal Dictionary<ulong, NetworkTransform> NetworkTransformFixedUpdate = new Dictionary<ulong, NetworkTransform>();
|
||||
internal Dictionary<ulong, NetworkObject> NetworkTransformFixedUpdate = new Dictionary<ulong, NetworkObject>();
|
||||
#endif
|
||||
|
||||
internal void NetworkTransformRegistration(NetworkTransform networkTransform, bool forUpdate = true, bool register = true)
|
||||
internal void NetworkTransformRegistration(NetworkObject networkObject, bool onUpdate = true, bool register = true)
|
||||
{
|
||||
if (forUpdate)
|
||||
if (onUpdate)
|
||||
{
|
||||
if (register)
|
||||
{
|
||||
if (!NetworkTransformUpdate.ContainsKey(networkTransform.NetworkObjectId))
|
||||
if (!NetworkTransformUpdate.ContainsKey(networkObject.NetworkObjectId))
|
||||
{
|
||||
NetworkTransformUpdate.Add(networkTransform.NetworkObjectId, networkTransform);
|
||||
NetworkTransformUpdate.Add(networkObject.NetworkObjectId, networkObject);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
NetworkTransformUpdate.Remove(networkTransform.NetworkObjectId);
|
||||
NetworkTransformUpdate.Remove(networkObject.NetworkObjectId);
|
||||
}
|
||||
}
|
||||
#if COM_UNITY_MODULES_PHYSICS
|
||||
@@ -241,14 +285,14 @@ namespace Unity.Netcode
|
||||
{
|
||||
if (register)
|
||||
{
|
||||
if (!NetworkTransformFixedUpdate.ContainsKey(networkTransform.NetworkObjectId))
|
||||
if (!NetworkTransformFixedUpdate.ContainsKey(networkObject.NetworkObjectId))
|
||||
{
|
||||
NetworkTransformFixedUpdate.Add(networkTransform.NetworkObjectId, networkTransform);
|
||||
NetworkTransformFixedUpdate.Add(networkObject.NetworkObjectId, networkObject);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
NetworkTransformFixedUpdate.Remove(networkTransform.NetworkObjectId);
|
||||
NetworkTransformFixedUpdate.Remove(networkObject.NetworkObjectId);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -275,6 +319,10 @@ namespace Unity.Netcode
|
||||
case NetworkUpdateStage.EarlyUpdate:
|
||||
{
|
||||
UpdateTopology();
|
||||
|
||||
// Handle processing any new connections or transport events
|
||||
NetworkConfig.NetworkTransport.EarlyUpdate();
|
||||
|
||||
ConnectionManager.ProcessPendingApprovals();
|
||||
ConnectionManager.PollAndHandleNetworkEvents();
|
||||
|
||||
@@ -282,6 +330,7 @@ namespace Unity.Netcode
|
||||
|
||||
AnticipationSystem.SetupForUpdate();
|
||||
MessageManager.ProcessIncomingMessageQueue();
|
||||
|
||||
MessageManager.CleanupDisconnectedClients();
|
||||
AnticipationSystem.ProcessReanticipation();
|
||||
}
|
||||
@@ -289,11 +338,21 @@ namespace Unity.Netcode
|
||||
#if COM_UNITY_MODULES_PHYSICS
|
||||
case NetworkUpdateStage.FixedUpdate:
|
||||
{
|
||||
foreach (var networkTransformEntry in NetworkTransformFixedUpdate)
|
||||
foreach (var networkObjectEntry in NetworkTransformFixedUpdate)
|
||||
{
|
||||
if (networkTransformEntry.Value.gameObject.activeInHierarchy && networkTransformEntry.Value.IsSpawned)
|
||||
// if not active or not spawned then skip
|
||||
if (!networkObjectEntry.Value.gameObject.activeInHierarchy || !networkObjectEntry.Value.IsSpawned)
|
||||
{
|
||||
networkTransformEntry.Value.OnFixedUpdate();
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var networkTransformEntry in networkObjectEntry.Value.NetworkTransforms)
|
||||
{
|
||||
// only update if enabled
|
||||
if (networkTransformEntry.enabled)
|
||||
{
|
||||
networkTransformEntry.OnFixedUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -308,11 +367,21 @@ namespace Unity.Netcode
|
||||
case NetworkUpdateStage.PreLateUpdate:
|
||||
{
|
||||
// Non-physics based non-authority NetworkTransforms update their states after all other components
|
||||
foreach (var networkTransformEntry in NetworkTransformUpdate)
|
||||
foreach (var networkObjectEntry in NetworkTransformUpdate)
|
||||
{
|
||||
if (networkTransformEntry.Value.gameObject.activeInHierarchy && networkTransformEntry.Value.IsSpawned)
|
||||
// if not active or not spawned then skip
|
||||
if (!networkObjectEntry.Value.gameObject.activeInHierarchy || !networkObjectEntry.Value.IsSpawned)
|
||||
{
|
||||
networkTransformEntry.Value.OnUpdate();
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var networkTransformEntry in networkObjectEntry.Value.NetworkTransforms)
|
||||
{
|
||||
// only update if enabled
|
||||
if (networkTransformEntry.enabled)
|
||||
{
|
||||
networkTransformEntry.OnUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -343,22 +412,15 @@ namespace Unity.Netcode
|
||||
// Metrics update needs to be driven by NetworkConnectionManager's update to assure metrics are dispatched after the send queue is processed.
|
||||
MetricsManager.UpdateMetrics();
|
||||
|
||||
// Handle sending any pending transport messages
|
||||
NetworkConfig.NetworkTransport.PostLateUpdate();
|
||||
|
||||
// TODO: Determine a better way to handle this
|
||||
NetworkObject.VerifyParentingStatus();
|
||||
|
||||
// This is "ok" to invoke when not processing messages since it is just cleaning up messages that never got handled within their timeout period.
|
||||
DeferredMessageManager.CleanupStaleTriggers();
|
||||
|
||||
// DANGO-TODO-MVP: Remove this once the service handles object distribution
|
||||
// NOTE: This needs to be the last thing done and should happen exactly at this point
|
||||
// in the update
|
||||
if (RedistributeToClient && ServerTime.Tick <= TickToRedistribute)
|
||||
{
|
||||
RedistributeToClient = false;
|
||||
SpawnManager.DistributeNetworkObjects(ClientToRedistribute);
|
||||
ClientToRedistribute = 0;
|
||||
}
|
||||
|
||||
if (m_ShuttingDown)
|
||||
{
|
||||
// Host-server will disconnect any connected clients prior to finalizing its shutdown
|
||||
@@ -850,6 +912,7 @@ namespace Unity.Netcode
|
||||
|
||||
internal Override<ushort> PortOverride;
|
||||
|
||||
|
||||
#if UNITY_EDITOR
|
||||
internal static INetworkManagerHelper NetworkManagerHelper;
|
||||
|
||||
@@ -871,6 +934,16 @@ namespace Unity.Netcode
|
||||
OnNetworkManagerReset?.Invoke(this);
|
||||
}
|
||||
|
||||
protected virtual void OnValidateComponent()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
private PackageInfo GetPackageInfo(string packageName)
|
||||
{
|
||||
return AssetDatabase.FindAssets("package").Select(AssetDatabase.GUIDToAssetPath).Where(x => AssetDatabase.LoadAssetAtPath<TextAsset>(x) != null).Select(PackageInfo.FindForAssetPath).Where(x => x != null).First(x => x.name == packageName);
|
||||
}
|
||||
|
||||
internal void OnValidate()
|
||||
{
|
||||
if (NetworkConfig == null)
|
||||
@@ -878,6 +951,9 @@ namespace Unity.Netcode
|
||||
return; // May occur when the component is added
|
||||
}
|
||||
|
||||
// Do a validation pass on NetworkConfig properties
|
||||
NetworkConfig.OnValidate();
|
||||
|
||||
if (GetComponentInChildren<NetworkObject>() != null)
|
||||
{
|
||||
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
|
||||
@@ -931,14 +1007,22 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
OnValidateComponent();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void ModeChanged(PlayModeStateChange change)
|
||||
{
|
||||
if (IsListening && change == PlayModeStateChange.ExitingPlayMode)
|
||||
{
|
||||
// Make sure we are not holding onto anything in case domain reload is disabled
|
||||
ShutdownInternal();
|
||||
OnApplicationQuit();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -992,6 +1076,8 @@ namespace Unity.Netcode
|
||||
#if UNITY_EDITOR
|
||||
EditorApplication.playModeStateChanged += ModeChanged;
|
||||
#endif
|
||||
// Notify we have instantiated a new instance of NetworkManager.
|
||||
OnInstantiated?.Invoke(this);
|
||||
}
|
||||
|
||||
private void OnEnable()
|
||||
@@ -1103,8 +1189,11 @@ namespace Unity.Netcode
|
||||
|
||||
UpdateTopology();
|
||||
|
||||
//DANGOEXP TODO: Remove this before finalizing the experimental release
|
||||
NetworkConfig.AutoSpawnPlayerPrefabClientSide = DistributedAuthorityMode;
|
||||
// Always create a default session config when starting a NetworkManager instance
|
||||
if (DistributedAuthorityMode)
|
||||
{
|
||||
SessionConfig = GetSessionConfig();
|
||||
}
|
||||
|
||||
// Make sure the ServerShutdownState is reset when initializing
|
||||
if (server)
|
||||
@@ -1594,6 +1683,9 @@ namespace Unity.Netcode
|
||||
|
||||
UnityEngine.SceneManagement.SceneManager.sceneUnloaded -= OnSceneUnloaded;
|
||||
|
||||
// Notify we are destroying NetworkManager
|
||||
OnDestroying?.Invoke(this);
|
||||
|
||||
if (Singleton == this)
|
||||
{
|
||||
Singleton = null;
|
||||
|
||||
@@ -67,6 +67,7 @@ namespace Unity.Netcode
|
||||
/// </remarks>
|
||||
public List<NetworkTransform> NetworkTransforms { get; private set; }
|
||||
|
||||
|
||||
#if COM_UNITY_MODULES_PHYSICS
|
||||
/// <summary>
|
||||
/// All <see cref="NetworkRigidbodyBase"></see> component instances associated with a <see cref="NetworkObject"/> component instance.
|
||||
@@ -101,10 +102,22 @@ namespace Unity.Netcode
|
||||
private const int k_SceneObjectType = 2;
|
||||
private const int k_SourceAssetObjectType = 3;
|
||||
|
||||
// Used to track any InContext or InIsolation prefab being edited.
|
||||
private static PrefabStage s_PrefabStage;
|
||||
// The network prefab asset that the edit mode scene has created an instance of (s_PrefabInstance).
|
||||
private static NetworkObject s_PrefabAsset;
|
||||
// The InContext or InIsolation edit mode network prefab scene instance of the prefab asset (s_PrefabAsset).
|
||||
private static NetworkObject s_PrefabInstance;
|
||||
|
||||
private static bool s_DebugPrefabIdGeneration;
|
||||
|
||||
|
||||
[ContextMenu("Refresh In-Scene Prefab Instances")]
|
||||
internal void RefreshAllPrefabInstances()
|
||||
{
|
||||
var instanceGlobalId = GlobalObjectId.GetGlobalObjectIdSlow(this);
|
||||
// Assign the currently selected instance to be updated
|
||||
NetworkObjectRefreshTool.PrefabNetworkObject = this;
|
||||
if (!PrefabUtility.IsPartOfAnyPrefab(this) || instanceGlobalId.identifierType != k_ImportedAssetObjectType)
|
||||
{
|
||||
EditorUtility.DisplayDialog("Network Prefab Assets Only", "This action can only be performed on a network prefab asset.", "Ok");
|
||||
@@ -112,11 +125,6 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
// Handle updating the currently active scene
|
||||
var networkObjects = FindObjectsByType<NetworkObject>(FindObjectsInactive.Include, FindObjectsSortMode.None);
|
||||
foreach (var networkObject in networkObjects)
|
||||
{
|
||||
networkObject.OnValidate();
|
||||
}
|
||||
NetworkObjectRefreshTool.ProcessActiveScene();
|
||||
|
||||
// Refresh all build settings scenes
|
||||
@@ -129,32 +137,126 @@ namespace Unity.Netcode
|
||||
continue;
|
||||
}
|
||||
// Add the scene to be processed
|
||||
NetworkObjectRefreshTool.ProcessScene(editorScene.path, false);
|
||||
NetworkObjectRefreshTool.ProcessScene(editorScene.path, true);
|
||||
}
|
||||
|
||||
// Process all added scenes
|
||||
NetworkObjectRefreshTool.ProcessScenes();
|
||||
}
|
||||
|
||||
private void OnValidate()
|
||||
/// <summary>
|
||||
/// Register for <see cref="PrefabStage"/> opened and closing event notifications.
|
||||
/// </summary>
|
||||
[InitializeOnLoadMethod]
|
||||
private static void OnApplicationStart()
|
||||
{
|
||||
// do NOT regenerate GlobalObjectIdHash for NetworkPrefabs while Editor is in PlayMode
|
||||
PrefabStage.prefabStageOpened -= PrefabStageOpened;
|
||||
PrefabStage.prefabStageOpened += PrefabStageOpened;
|
||||
PrefabStage.prefabStageClosing -= PrefabStageClosing;
|
||||
PrefabStage.prefabStageClosing += PrefabStageClosing;
|
||||
}
|
||||
|
||||
private static void PrefabStageClosing(PrefabStage prefabStage)
|
||||
{
|
||||
// If domain reloading is enabled, then this will be null when we return from playmode.
|
||||
if (s_PrefabStage == null)
|
||||
{
|
||||
// Determine if we have a network prefab opened in edit mode or not.
|
||||
CheckPrefabStage(prefabStage);
|
||||
}
|
||||
|
||||
s_PrefabStage = null;
|
||||
s_PrefabInstance = null;
|
||||
s_PrefabAsset = null;
|
||||
}
|
||||
|
||||
private static void PrefabStageOpened(PrefabStage prefabStage)
|
||||
{
|
||||
// Determine if we have a network prefab opened in edit mode or not.
|
||||
CheckPrefabStage(prefabStage);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines if we have opened a network prefab in edit mode (InContext or InIsolation)
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// InContext: Typically means a are in prefab edit mode for an in-scene placed network prefab instance.
|
||||
/// (currently no such thing as a network prefab with nested network prefab instances)
|
||||
///
|
||||
/// InIsolation: Typically means we are in prefb edit mode for a prefab asset.
|
||||
/// </remarks>
|
||||
/// <param name="prefabStage"></param>
|
||||
private static void CheckPrefabStage(PrefabStage prefabStage)
|
||||
{
|
||||
s_PrefabStage = prefabStage;
|
||||
s_PrefabInstance = prefabStage.prefabContentsRoot?.GetComponent<NetworkObject>();
|
||||
if (s_PrefabInstance)
|
||||
{
|
||||
// We acquire the source prefab that the prefab edit mode scene instance was instantiated from differently for InContext than InSolation.
|
||||
if (s_PrefabStage.mode == PrefabStage.Mode.InContext && s_PrefabStage.openedFromInstanceRoot != null)
|
||||
{
|
||||
// This is needed to handle the scenario where a user completely loads a new scene while in an InContext prefab edit mode.
|
||||
try
|
||||
{
|
||||
s_PrefabAsset = s_PrefabStage.openedFromInstanceRoot?.GetComponent<NetworkObject>();
|
||||
}
|
||||
catch
|
||||
{
|
||||
s_PrefabAsset = null;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// When editing in InIsolation mode, load the original prefab asset from the provided path.
|
||||
s_PrefabAsset = AssetDatabase.LoadAssetAtPath<NetworkObject>(s_PrefabStage.assetPath);
|
||||
}
|
||||
|
||||
if (s_PrefabInstance.GlobalObjectIdHash != s_PrefabAsset.GlobalObjectIdHash)
|
||||
{
|
||||
s_PrefabInstance.GlobalObjectIdHash = s_PrefabAsset.GlobalObjectIdHash;
|
||||
// For InContext mode, we don't want to record these modifications (the in-scene GlobalObjectIdHash is serialized with the scene).
|
||||
if (s_PrefabStage.mode == PrefabStage.Mode.InIsolation)
|
||||
{
|
||||
PrefabUtility.RecordPrefabInstancePropertyModifications(s_PrefabAsset);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
s_PrefabStage = null;
|
||||
s_PrefabInstance = null;
|
||||
s_PrefabAsset = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// GlobalObjectIdHash values are generated during validation.
|
||||
/// </summary>
|
||||
internal void OnValidate()
|
||||
{
|
||||
// Always exit early if we are in prefab edit mode and this instance is the
|
||||
// prefab instance within the InContext or InIsolation edit scene.
|
||||
if (s_PrefabInstance == this)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Do not regenerate GlobalObjectIdHash for NetworkPrefabs while Editor is in play mode.
|
||||
if (EditorApplication.isPlaying && !string.IsNullOrEmpty(gameObject.scene.name))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// do NOT regenerate GlobalObjectIdHash if Editor is transitioning into or out of PlayMode
|
||||
// Do not regenerate GlobalObjectIdHash if Editor is transitioning into or out of play mode.
|
||||
if (!EditorApplication.isPlaying && EditorApplication.isPlayingOrWillChangePlaymode)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Get a global object identifier for this network prefab
|
||||
var globalId = GetGlobalId();
|
||||
// Get a global object identifier for this network prefab.
|
||||
var globalId = GlobalObjectId.GetGlobalObjectIdSlow(this);
|
||||
|
||||
|
||||
// if the identifier type is 0, then don't update the GlobalObjectIdHash
|
||||
// if the identifier type is 0, then don't update the GlobalObjectIdHash.
|
||||
if (globalId.identifierType == k_NullObjectType)
|
||||
{
|
||||
return;
|
||||
@@ -163,47 +265,34 @@ namespace Unity.Netcode
|
||||
var oldValue = GlobalObjectIdHash;
|
||||
GlobalObjectIdHash = globalId.ToString().Hash32();
|
||||
|
||||
// If the GlobalObjectIdHash value changed, then mark the asset dirty
|
||||
// Always check for in-scene placed to assure any previous version scene assets with in-scene place NetworkObjects gets updated.
|
||||
CheckForInScenePlaced();
|
||||
|
||||
// If the GlobalObjectIdHash value changed, then mark the asset dirty.
|
||||
if (GlobalObjectIdHash != oldValue)
|
||||
{
|
||||
// Check if this is an in-scnee placed NetworkObject (Special Case for In-Scene Placed)
|
||||
if (!IsEditingPrefab() && gameObject.scene.name != null && gameObject.scene.name != gameObject.name)
|
||||
// Check if this is an in-scnee placed NetworkObject (Special Case for In-Scene Placed).
|
||||
if (IsSceneObject.HasValue && IsSceneObject.Value)
|
||||
{
|
||||
// Sanity check to make sure this is a scene placed object
|
||||
// Sanity check to make sure this is a scene placed object.
|
||||
if (globalId.identifierType != k_SceneObjectType)
|
||||
{
|
||||
// This should never happen, but in the event it does throw and error
|
||||
// This should never happen, but in the event it does throw and error.
|
||||
Debug.LogError($"[{gameObject.name}] is detected as an in-scene placed object but its identifier is of type {globalId.identifierType}! **Report this error**");
|
||||
}
|
||||
|
||||
// If this is a prefab instance
|
||||
// If this is a prefab instance, then we want to mark it as having been updated in order for the udpated GlobalObjectIdHash value to be saved.
|
||||
if (PrefabUtility.IsPartOfAnyPrefab(this))
|
||||
{
|
||||
// We must invoke this in order for the modifications to get saved with the scene (does not mark scene as dirty)
|
||||
// We must invoke this in order for the modifications to get saved with the scene (does not mark scene as dirty).
|
||||
PrefabUtility.RecordPrefabInstancePropertyModifications(this);
|
||||
}
|
||||
}
|
||||
else // Otherwise, this is a standard network prefab asset so we just mark it dirty for the AssetDatabase to update it
|
||||
else // Otherwise, this is a standard network prefab asset so we just mark it dirty for the AssetDatabase to update it.
|
||||
{
|
||||
EditorUtility.SetDirty(this);
|
||||
}
|
||||
}
|
||||
|
||||
// Always check for in-scene placed to assure any previous version scene assets with in-scene place NetworkObjects gets updated
|
||||
CheckForInScenePlaced();
|
||||
}
|
||||
|
||||
private bool IsEditingPrefab()
|
||||
{
|
||||
// Check if we are directly editing the prefab
|
||||
var stage = PrefabStageUtility.GetPrefabStage(gameObject);
|
||||
|
||||
// if we are not editing the prefab directly (or a sub-prefab), then return the object identifier
|
||||
if (stage == null || stage.assetPath == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -214,13 +303,12 @@ namespace Unity.Netcode
|
||||
/// <remarks>
|
||||
/// This NetworkObject is considered an in-scene placed prefab asset instance if it is:
|
||||
/// - Part of a prefab
|
||||
/// - Not being directly edited
|
||||
/// - Within a valid scene that is part of the scenes in build list
|
||||
/// (In-scene defined NetworkObjects that are not part of a prefab instance are excluded.)
|
||||
/// </remarks>
|
||||
private void CheckForInScenePlaced()
|
||||
{
|
||||
if (PrefabUtility.IsPartOfAnyPrefab(this) && !IsEditingPrefab() && gameObject.scene.IsValid() && gameObject.scene.isLoaded && gameObject.scene.buildIndex >= 0)
|
||||
if (PrefabUtility.IsPartOfAnyPrefab(this) && gameObject.scene.IsValid() && gameObject.scene.isLoaded && gameObject.scene.buildIndex >= 0)
|
||||
{
|
||||
var prefab = PrefabUtility.GetCorrespondingObjectFromSource(gameObject);
|
||||
var assetPath = AssetDatabase.GetAssetPath(prefab);
|
||||
@@ -228,59 +316,11 @@ namespace Unity.Netcode
|
||||
if (sourceAsset != null && sourceAsset.GlobalObjectIdHash != 0 && InScenePlacedSourceGlobalObjectIdHash != sourceAsset.GlobalObjectIdHash)
|
||||
{
|
||||
InScenePlacedSourceGlobalObjectIdHash = sourceAsset.GlobalObjectIdHash;
|
||||
EditorUtility.SetDirty(this);
|
||||
}
|
||||
IsSceneObject = true;
|
||||
}
|
||||
}
|
||||
|
||||
private GlobalObjectId GetGlobalId()
|
||||
{
|
||||
var instanceGlobalId = GlobalObjectId.GetGlobalObjectIdSlow(this);
|
||||
|
||||
// If not editing a prefab, then just use the generated id
|
||||
if (!IsEditingPrefab())
|
||||
{
|
||||
return instanceGlobalId;
|
||||
}
|
||||
|
||||
// If the asset doesn't exist at the given path, then return the object identifier
|
||||
var prefabStageAssetPath = PrefabStageUtility.GetPrefabStage(gameObject).assetPath;
|
||||
// If (for some reason) the asset path is null return the generated id
|
||||
if (prefabStageAssetPath == null)
|
||||
{
|
||||
return instanceGlobalId;
|
||||
}
|
||||
|
||||
var theAsset = AssetDatabase.LoadAssetAtPath<NetworkObject>(prefabStageAssetPath);
|
||||
// If there is no asset at that path (for some odd/edge case reason), return the generated id
|
||||
if (theAsset == null)
|
||||
{
|
||||
return instanceGlobalId;
|
||||
}
|
||||
|
||||
// If we can't get the asset GUID and/or the file identifier, then return the object identifier
|
||||
if (!AssetDatabase.TryGetGUIDAndLocalFileIdentifier(theAsset, out var guid, out long localFileId))
|
||||
{
|
||||
return instanceGlobalId;
|
||||
}
|
||||
|
||||
// Note: If we reached this point, then we are most likely opening a prefab to edit.
|
||||
// The instanceGlobalId will be constructed as if it is a scene object, however when it
|
||||
// is serialized its value will be treated as a file asset (the "why" to the below code).
|
||||
|
||||
// Construct an imported asset identifier with the type being a source asset object type
|
||||
var prefabGlobalIdText = string.Format(k_GlobalIdTemplate, k_SourceAssetObjectType, guid, (ulong)localFileId, 0);
|
||||
|
||||
// If we can't parse the result log an error and return the instanceGlobalId
|
||||
if (!GlobalObjectId.TryParse(prefabGlobalIdText, out var prefabGlobalId))
|
||||
{
|
||||
Debug.LogError($"[GlobalObjectId Gen] Failed to parse ({prefabGlobalIdText}) returning default ({instanceGlobalId})! ** Please Report This Error **");
|
||||
return instanceGlobalId;
|
||||
}
|
||||
|
||||
// Otherwise, return the constructed identifier for the source prefab asset
|
||||
return prefabGlobalId;
|
||||
}
|
||||
#endif // UNITY_EDITOR
|
||||
|
||||
/// <summary>
|
||||
@@ -339,7 +379,7 @@ namespace Unity.Netcode
|
||||
|
||||
if (!HasAuthority)
|
||||
{
|
||||
NetworkLog.LogError($"Only the authoirty can invoke {nameof(DeferDespawn)} and local Client-{NetworkManager.LocalClientId} is not the authority of {name}!");
|
||||
NetworkLog.LogError($"Only the authority can invoke {nameof(DeferDespawn)} and local Client-{NetworkManager.LocalClientId} is not the authority of {name}!");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -399,6 +439,13 @@ namespace Unity.Netcode
|
||||
/// </remarks>
|
||||
public bool IsOwnershipDistributable => Ownership.HasFlag(OwnershipStatus.Distributable);
|
||||
|
||||
/// <summary>
|
||||
/// When true, the <see cref="NetworkObject"/> can only be owned by the current Session Owner.
|
||||
/// To set <see cref="OwnershipStatus.SessionOwner"/> during runtime, use <see cref="ChangeOwnership(ulong)"/> to ensure the session owner owns the object.
|
||||
/// Once the session owner owns the object, then use <see cref="SetOwnershipStatus(OwnershipStatus, bool, OwnershipLockActions)"/>.
|
||||
/// </summary>
|
||||
public bool IsOwnershipSessionOwner => Ownership.HasFlag(OwnershipStatus.SessionOwner);
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if the <see cref="NetworkObject"/> is has ownership locked.
|
||||
/// When locked, the <see cref="NetworkObject"/> cannot be redistributed nor can it be transferred by another client.
|
||||
@@ -441,7 +488,8 @@ namespace Unity.Netcode
|
||||
/// <see cref="None"/>: If nothing is set, then ownership is considered "static" and cannot be redistributed, requested, or transferred (i.e. a Player would have this).
|
||||
/// <see cref="Distributable"/>: When set, this instance will be automatically redistributed when a client joins (if not locked or no request is pending) or leaves.
|
||||
/// <see cref="Transferable"/>: When set, a non-owner can obtain ownership immediately (without requesting and as long as it is not locked).
|
||||
/// <see cref="RequestRequired"/>: When set, When set, a non-owner must request ownership from the owner (will always get locked once ownership is transferred).
|
||||
/// <see cref="RequestRequired"/>: When set, a non-owner must request ownership from the owner (will always get locked once ownership is transferred).
|
||||
/// <see cref="SessionOwner"/>: When set, only the current session owner may have ownership over this object.
|
||||
/// </summary>
|
||||
// Ranges from 1 to 8 bits
|
||||
[Flags]
|
||||
@@ -451,6 +499,7 @@ namespace Unity.Netcode
|
||||
Distributable = 1 << 0,
|
||||
Transferable = 1 << 1,
|
||||
RequestRequired = 1 << 2,
|
||||
SessionOwner = 1 << 3,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -509,7 +558,7 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
// If we don't have the Transferable flag set and it is not a player object, then it is the same as having a static lock on ownership
|
||||
if (!IsOwnershipTransferable && !IsPlayerObject)
|
||||
if (!(IsOwnershipTransferable || IsPlayerObject) || IsOwnershipSessionOwner)
|
||||
{
|
||||
NetworkLog.LogWarning($"Trying to add or remove ownership lock on [{name}] which does not have the {nameof(OwnershipStatus.Transferable)} flag set!");
|
||||
return false;
|
||||
@@ -542,13 +591,15 @@ namespace Unity.Netcode
|
||||
/// <see cref="RequestRequired"/>: The <see cref="NetworkObject"/> requires an ownership request via <see cref="RequestOwnership"/>.
|
||||
/// <see cref="RequestInProgress"/>: The <see cref="NetworkObject"/> is already processing an ownership request and ownership cannot be acquired at this time.
|
||||
/// <see cref="NotTransferrable"/>: The <see cref="NetworkObject"/> does not have the <see cref="OwnershipStatus.Transferable"/> flag set and ownership cannot be acquired.
|
||||
/// <see cref="SessionOwnerOnly"/>: The <see cref="NetworkObject"/> has the <see cref="OwnershipStatus.SessionOwner"/> flag set and ownership cannot be acquired.
|
||||
/// </summary>
|
||||
public enum OwnershipPermissionsFailureStatus
|
||||
{
|
||||
Locked,
|
||||
RequestRequired,
|
||||
RequestInProgress,
|
||||
NotTransferrable
|
||||
NotTransferrable,
|
||||
SessionOwnerOnly
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -570,6 +621,7 @@ namespace Unity.Netcode
|
||||
/// <see cref="RequestRequiredNotSet"/>: The <see cref="OwnershipStatus.RequestRequired"/> flag is not set on this <see cref="NetworkObject"/>
|
||||
/// <see cref="Locked"/>: The current owner has locked ownership which means requests are not available at this time.
|
||||
/// <see cref="RequestInProgress"/>: There is already a known request in progress. You can scan for ownership changes and try upon
|
||||
/// <see cref="SessionOwnerOnly"/>: This object is marked as SessionOwnerOnly and therefore cannot be requested
|
||||
/// a change in ownership or just try again after a specific period of time or no longer attempt to request ownership.
|
||||
/// </summary>
|
||||
public enum OwnershipRequestStatus
|
||||
@@ -579,6 +631,7 @@ namespace Unity.Netcode
|
||||
RequestRequiredNotSet,
|
||||
Locked,
|
||||
RequestInProgress,
|
||||
SessionOwnerOnly,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -591,6 +644,7 @@ namespace Unity.Netcode
|
||||
/// <see cref="OwnershipRequestStatus.RequestRequiredNotSet"/>: The <see cref="OwnershipStatus.RequestRequired"/> flag is not set on this <see cref="NetworkObject"/>
|
||||
/// <see cref="OwnershipRequestStatus.Locked"/>: The current owner has locked ownership which means requests are not available at this time.
|
||||
/// <see cref="OwnershipRequestStatus.RequestInProgress"/>: There is already a known request in progress. You can scan for ownership changes and try upon
|
||||
/// <see cref="OwnershipRequestStatus.SessionOwnerOnly"/>: This object can only belong the the session owner and so cannot be requested
|
||||
/// a change in ownership or just try again after a specific period of time or no longer attempt to request ownership.
|
||||
/// </remarks>
|
||||
/// <returns><see cref="OwnershipRequestStatus"/></returns>
|
||||
@@ -620,6 +674,12 @@ namespace Unity.Netcode
|
||||
return OwnershipRequestStatus.RequestInProgress;
|
||||
}
|
||||
|
||||
// Exit early if it has the SessionOwner flag
|
||||
if (IsOwnershipSessionOwner)
|
||||
{
|
||||
return OwnershipRequestStatus.SessionOwnerOnly;
|
||||
}
|
||||
|
||||
// Otherwise, send the request ownership message
|
||||
var changeOwnership = new ChangeOwnershipMessage
|
||||
{
|
||||
@@ -676,7 +736,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
response = OwnershipRequestResponseStatus.RequestInProgress;
|
||||
}
|
||||
else if (!IsOwnershipRequestRequired && !IsOwnershipTransferable)
|
||||
else if (!(IsOwnershipRequestRequired || IsOwnershipTransferable) || IsOwnershipSessionOwner)
|
||||
{
|
||||
response = OwnershipRequestResponseStatus.CannotRequest;
|
||||
}
|
||||
@@ -796,6 +856,12 @@ namespace Unity.Netcode
|
||||
/// </remarks>
|
||||
public bool SetOwnershipStatus(OwnershipStatus status, bool clearAndSet = false, OwnershipLockActions lockAction = OwnershipLockActions.None)
|
||||
{
|
||||
if (status.HasFlag(OwnershipStatus.SessionOwner) && !NetworkManager.LocalClient.IsSessionOwner)
|
||||
{
|
||||
NetworkLog.LogWarning("Only the session owner is allowed to set the ownership status to session owner only.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// If it already has the flag do nothing
|
||||
if (!clearAndSet && Ownership.HasFlag(status))
|
||||
{
|
||||
@@ -807,13 +873,25 @@ namespace Unity.Netcode
|
||||
Ownership = OwnershipStatus.None;
|
||||
}
|
||||
|
||||
// Faster to just OR a None status than to check
|
||||
// if it is !None before "OR'ing".
|
||||
Ownership |= status;
|
||||
|
||||
if (lockAction != OwnershipLockActions.None)
|
||||
if (status.HasFlag(OwnershipStatus.SessionOwner))
|
||||
{
|
||||
SetOwnershipLock(lockAction == OwnershipLockActions.SetAndLock);
|
||||
Ownership = OwnershipStatus.SessionOwner;
|
||||
}
|
||||
else if (Ownership.HasFlag(OwnershipStatus.SessionOwner))
|
||||
{
|
||||
NetworkLog.LogWarning("No other ownership statuses may be set while SessionOwner is set.");
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Faster to just OR a None status than to check
|
||||
// if it is !None before "OR'ing".
|
||||
Ownership |= status;
|
||||
|
||||
if (lockAction != OwnershipLockActions.None)
|
||||
{
|
||||
SetOwnershipLock(lockAction == OwnershipLockActions.SetAndLock);
|
||||
}
|
||||
}
|
||||
|
||||
SendOwnershipStatusUpdate();
|
||||
@@ -937,6 +1015,7 @@ namespace Unity.Netcode
|
||||
/// <summary>
|
||||
/// If true, the object will always be replicated as root on clients and the parent will be ignored.
|
||||
/// </summary>
|
||||
[Tooltip("If enabled (default disabled), instances of this NetworkObject will ignore any parent(s) it might have and replicate on clients as the root being its parent.")]
|
||||
public bool AlwaysReplicateAsRoot;
|
||||
|
||||
/// <summary>
|
||||
@@ -954,6 +1033,8 @@ namespace Unity.Netcode
|
||||
/// bandwidth cost. This can also be useful for UI elements that have
|
||||
/// a predetermined fixed position.
|
||||
/// </remarks>
|
||||
[Tooltip("If enabled (default enabled), newly joining clients will be synchronized with the transform of the associated GameObject this component is attached to. Typical use case" +
|
||||
" scenario would be for managment objects or in-scene placed objects that don't move and already have their transform settings applied within the scene information.")]
|
||||
public bool SynchronizeTransform = true;
|
||||
|
||||
/// <summary>
|
||||
@@ -1011,6 +1092,7 @@ namespace Unity.Netcode
|
||||
/// To synchronize clients of a <see cref="NetworkObject"/>'s scene being changed via <see cref="SceneManager.MoveGameObjectToScene(GameObject, Scene)"/>,
|
||||
/// make sure <see cref="SceneMigrationSynchronization"/> is enabled (it is by default).
|
||||
/// </remarks>
|
||||
[Tooltip("When enabled (default disabled), spawned instances of this NetworkObject will automatically migrate to any newly assigned active scene.")]
|
||||
public bool ActiveSceneSynchronization;
|
||||
|
||||
/// <summary>
|
||||
@@ -1029,6 +1111,7 @@ namespace Unity.Netcode
|
||||
/// is <see cref="true"/> and <see cref="ActiveSceneSynchronization"/> is <see cref="false"/> and the scene is not the currently
|
||||
/// active scene, then the <see cref="NetworkObject"/> will be destroyed.
|
||||
/// </remarks>
|
||||
[Tooltip("When enabled (default enabled), dynamically spawned instances of this NetworkObject's migration to a different scene will automatically be synchonize amongst clients.")]
|
||||
public bool SceneMigrationSynchronization = true;
|
||||
|
||||
/// <summary>
|
||||
@@ -1044,7 +1127,7 @@ namespace Unity.Netcode
|
||||
/// <summary>
|
||||
/// When set to false, the NetworkObject will be spawned with no observers initially (other than the server)
|
||||
/// </summary>
|
||||
[Tooltip("When false, the NetworkObject will spawn with no observers initially. (default is true)")]
|
||||
[Tooltip("When disabled (default enabled), the NetworkObject will spawn with no observers. You control object visibility using NetworkShow. This applies to newly joining clients as well.")]
|
||||
public bool SpawnWithObservers = true;
|
||||
|
||||
/// <summary>
|
||||
@@ -1073,13 +1156,35 @@ namespace Unity.Netcode
|
||||
/// Whether or not to destroy this object if it's owner is destroyed.
|
||||
/// If true, the objects ownership will be given to the server.
|
||||
/// </summary>
|
||||
[Tooltip("When enabled (default disabled), instances of this NetworkObject will not be destroyed if the owning client disconnects.")]
|
||||
public bool DontDestroyWithOwner;
|
||||
|
||||
/// <summary>
|
||||
/// Whether or not to enable automatic NetworkObject parent synchronization.
|
||||
/// </summary>
|
||||
[Tooltip("When disabled (default enabled), NetworkObject parenting will not be automatically synchronized. This is typically used when you want to implement your own custom parenting solution.")]
|
||||
public bool AutoObjectParentSync = true;
|
||||
|
||||
/// <summary>
|
||||
/// Determines if the owner will apply transform values sent by the parenting message.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// When enabled, the resultant parenting transform changes sent by the authority will be applied on all instances. <br />
|
||||
/// When disabled, the resultant parenting transform changes sent by the authority will not be applied on the owner's instance. <br />
|
||||
/// When disabled, all non-owner instances will still be synchronized by the authority's transform values when parented.
|
||||
/// When using a <see cref="NetworkTopologyTypes.ClientServer"/> network topology and an owner authoritative motion model, disabling this can help smooth parenting transitions.
|
||||
/// When using a <see cref="NetworkTopologyTypes.DistributedAuthority"/> network topology this will have no impact on the owner's instance since only the authority/owner can parent.
|
||||
/// </remarks>
|
||||
[Tooltip("When disabled (default enabled), the owner will not apply a server or host's transform properties when parenting changes. Primarily useful for client-server network topology configurations.")]
|
||||
public bool SyncOwnerTransformWhenParented = true;
|
||||
|
||||
/// <summary>
|
||||
/// Client-Server specific, when enabled an owner of a NetworkObject can parent locally as opposed to requiring the owner to notify the server it would like to be parented.
|
||||
/// This behavior is always true when using a distributed authority network topology and does not require it to be set.
|
||||
/// </summary>
|
||||
[Tooltip("When enabled (default disabled), owner's can parent a NetworkObject locally without having to send an RPC to the server or host. Only pertinent when using client-server network topology configurations.")]
|
||||
public bool AllowOwnerToParent;
|
||||
|
||||
internal readonly HashSet<ulong> Observers = new HashSet<ulong>();
|
||||
|
||||
#if MULTIPLAYER_TOOLS
|
||||
@@ -1562,7 +1667,7 @@ namespace Unity.Netcode
|
||||
// DANGO-TODO: Review over don't destroy with owner being set but DistributeOwnership not being set
|
||||
if (NetworkManager.LogLevel == LogLevel.Developer)
|
||||
{
|
||||
NetworkLog.LogWarning("DANGO-TODO: Review over don't destroy with owner being set but DistributeOwnership not being set. For now, if the NetworkObject does not destroy with the owner it will automatically set DistributeOwnership.");
|
||||
NetworkLog.LogWarning("DANGO-TODO: Review over don't destroy with owner being set but DistributeOwnership not being set. For now, if the NetworkObject does not destroy with the owner it will set ownership to SessionOwner.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1585,7 +1690,12 @@ namespace Unity.Netcode
|
||||
}
|
||||
else if (NetworkManager.DistributedAuthorityMode && !NetworkManager.DAHost)
|
||||
{
|
||||
NetworkManager.SpawnManager.SendSpawnCallForObject(NetworkManager.ServerClientId, this);
|
||||
// If spawning with observers or if not spawning with observers but the observer count is greater than 1 (i.e. owner/authority creating),
|
||||
// then we want to send a spawn notification.
|
||||
if (SpawnWithObservers || !SpawnWithObservers && Observers.Count > 1)
|
||||
{
|
||||
NetworkManager.SpawnManager.SendSpawnCallForObject(NetworkManager.ServerClientId, this);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -1787,6 +1897,9 @@ namespace Unity.Netcode
|
||||
{
|
||||
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
|
||||
{
|
||||
// Invoke internal notification
|
||||
ChildNetworkBehaviours[i].InternalOnNetworkObjectParentChanged(parentNetworkObject);
|
||||
// Invoke public notification
|
||||
ChildNetworkBehaviours[i].OnNetworkObjectParentChanged(parentNetworkObject);
|
||||
}
|
||||
}
|
||||
@@ -1918,7 +2031,7 @@ namespace Unity.Netcode
|
||||
|
||||
// DANGO-TODO: Do we want to worry about ownership permissions here?
|
||||
// It wouldn't make sense to not allow parenting, but keeping this note here as a reminder.
|
||||
var isAuthority = HasAuthority;
|
||||
var isAuthority = HasAuthority || (AllowOwnerToParent && IsOwner);
|
||||
|
||||
// If we don't have authority and we are not shutting down, then don't allow any parenting.
|
||||
// If we are shutting down and don't have authority then allow it.
|
||||
@@ -1932,12 +2045,14 @@ namespace Unity.Netcode
|
||||
|
||||
internal bool InternalTrySetParent(NetworkObject parent, bool worldPositionStays = true)
|
||||
{
|
||||
if (parent != null && (IsSpawned ^ parent.IsSpawned))
|
||||
if (parent != null && (IsSpawned ^ parent.IsSpawned) && NetworkManager != null && !NetworkManager.ShutdownInProgress)
|
||||
{
|
||||
if (NetworkManager != null && !NetworkManager.ShutdownInProgress)
|
||||
if (NetworkManager.LogLevel <= LogLevel.Developer)
|
||||
{
|
||||
return false;
|
||||
var nameOfNotSpawnedObject = IsSpawned ? $" the parent ({parent.name})" : $"the child ({name})";
|
||||
NetworkLog.LogWarning($"Parenting failed because {nameOfNotSpawnedObject} is not spawned!");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
m_CachedWorldPositionStays = worldPositionStays;
|
||||
@@ -1984,7 +2099,7 @@ namespace Unity.Netcode
|
||||
var isAuthority = false;
|
||||
// With distributed authority, we need to track "valid authoritative" parenting changes.
|
||||
// So, either the authority or AuthorityAppliedParenting is considered a "valid parenting change".
|
||||
isAuthority = HasAuthority || AuthorityAppliedParenting;
|
||||
isAuthority = HasAuthority || AuthorityAppliedParenting || (AllowOwnerToParent && IsOwner);
|
||||
var distributedAuthority = NetworkManager.DistributedAuthorityMode;
|
||||
|
||||
// If we do not have authority and we are spawned
|
||||
@@ -2076,7 +2191,7 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
// If we are connected to a CMB service or we are running a mock CMB service then send to the "server" identifier
|
||||
if (distributedAuthority)
|
||||
if (distributedAuthority || (!distributedAuthority && AllowOwnerToParent && IsOwner && !NetworkManager.IsServer))
|
||||
{
|
||||
if (!NetworkManager.DAHost)
|
||||
{
|
||||
@@ -2359,13 +2474,15 @@ namespace Unity.Netcode
|
||||
{
|
||||
m_ChildNetworkBehaviours.Add(networkBehaviours[i]);
|
||||
var type = networkBehaviours[i].GetType();
|
||||
if (type.IsInstanceOfType(typeof(NetworkTransform)) || type.IsSubclassOf(typeof(NetworkTransform)))
|
||||
if (type == typeof(NetworkTransform) || type.IsInstanceOfType(typeof(NetworkTransform)) || type.IsSubclassOf(typeof(NetworkTransform)))
|
||||
{
|
||||
if (NetworkTransforms == null)
|
||||
{
|
||||
NetworkTransforms = new List<NetworkTransform>();
|
||||
}
|
||||
NetworkTransforms.Add(networkBehaviours[i] as NetworkTransform);
|
||||
var networkTransform = networkBehaviours[i] as NetworkTransform;
|
||||
networkTransform.IsNested = i != 0 && networkTransform.gameObject != gameObject;
|
||||
NetworkTransforms.Add(networkTransform);
|
||||
}
|
||||
#if COM_UNITY_MODULES_PHYSICS
|
||||
else if (type.IsSubclassOf(typeof(NetworkRigidbodyBase)))
|
||||
@@ -2411,6 +2528,14 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
internal void MarkOwnerReadVariablesDirty()
|
||||
{
|
||||
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
|
||||
{
|
||||
ChildNetworkBehaviours[i].MarkOwnerReadVariablesDirty();
|
||||
}
|
||||
}
|
||||
|
||||
// NGO currently guarantees that the client will receive spawn data for all objects in one network tick.
|
||||
// Children may arrive before their parents; when they do they are stored in OrphanedChildren and then
|
||||
// resolved when their parents arrived. Because we don't send a partial list of spawns (yet), something
|
||||
@@ -2737,11 +2862,11 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
internal void PostNetworkVariableWrite()
|
||||
internal void PostNetworkVariableWrite(bool forced = false)
|
||||
{
|
||||
for (int k = 0; k < ChildNetworkBehaviours.Count; k++)
|
||||
{
|
||||
ChildNetworkBehaviours[k].PostNetworkVariableWrite();
|
||||
ChildNetworkBehaviours[k].PostNetworkVariableWrite(forced);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2850,7 +2975,7 @@ namespace Unity.Netcode
|
||||
SyncObservers = syncObservers,
|
||||
Observers = syncObservers ? Observers.ToArray() : null,
|
||||
NetworkSceneHandle = NetworkSceneHandle,
|
||||
Hash = HostCheckForGlobalObjectIdHashOverride(),
|
||||
Hash = CheckForGlobalObjectIdHashOverride(),
|
||||
OwnerObject = this,
|
||||
TargetClientId = targetClientId
|
||||
};
|
||||
@@ -3020,10 +3145,15 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
// Add all known players to the observers list if they don't already exist
|
||||
foreach (var player in networkManager.SpawnManager.PlayerObjects)
|
||||
// Only add all other players as observers if we are spawning with observers,
|
||||
// otherwise user controls via NetworkShow.
|
||||
if (networkObject.SpawnWithObservers)
|
||||
{
|
||||
networkObject.Observers.Add(player.OwnerClientId);
|
||||
// Add all known players to the observers list if they don't already exist
|
||||
foreach (var player in networkManager.SpawnManager.PlayerObjects)
|
||||
{
|
||||
networkObject.Observers.Add(player.OwnerClientId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3197,14 +3327,15 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Only applies to Host mode.
|
||||
/// Client-Server: Only applies to spawn authority (i.e. Server)
|
||||
/// Distributed Authority: Applies to all clients since they all have spawn authority.
|
||||
/// Will return the registered source NetworkPrefab's GlobalObjectIdHash if one exists.
|
||||
/// Server and Clients will always return the NetworkObject's GlobalObjectIdHash.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
internal uint HostCheckForGlobalObjectIdHashOverride()
|
||||
/// <returns>appropriate hash value</returns>
|
||||
internal uint CheckForGlobalObjectIdHashOverride()
|
||||
{
|
||||
if (NetworkManager.IsServer)
|
||||
if (NetworkManager.IsServer || NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
if (NetworkManager.PrefabHandler.ContainsHandler(this))
|
||||
{
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using UnityEditor;
|
||||
using UnityEditor.SceneManagement;
|
||||
using UnityEngine;
|
||||
using UnityEngine.SceneManagement;
|
||||
@@ -21,6 +23,28 @@ namespace Unity.Netcode
|
||||
|
||||
internal static Action AllScenesProcessed;
|
||||
|
||||
internal static NetworkObject PrefabNetworkObject;
|
||||
|
||||
internal static void LogInfo(string msg, bool append = false)
|
||||
{
|
||||
if (!append)
|
||||
{
|
||||
s_Log.AppendLine(msg);
|
||||
}
|
||||
else
|
||||
{
|
||||
s_Log.Append(msg);
|
||||
}
|
||||
}
|
||||
|
||||
internal static void FlushLog()
|
||||
{
|
||||
Debug.Log(s_Log.ToString());
|
||||
s_Log.Clear();
|
||||
}
|
||||
|
||||
private static StringBuilder s_Log = new StringBuilder();
|
||||
|
||||
internal static void ProcessScene(string scenePath, bool processScenes = true)
|
||||
{
|
||||
if (!s_ScenesToUpdate.Contains(scenePath))
|
||||
@@ -29,7 +53,10 @@ namespace Unity.Netcode
|
||||
{
|
||||
EditorSceneManager.sceneOpened += EditorSceneManager_sceneOpened;
|
||||
EditorSceneManager.sceneSaved += EditorSceneManager_sceneSaved;
|
||||
s_Log.Clear();
|
||||
LogInfo("NetworkObject Refresh Scenes to Process:");
|
||||
}
|
||||
LogInfo($"[{scenePath}]", true);
|
||||
s_ScenesToUpdate.Add(scenePath);
|
||||
}
|
||||
s_ProcessScenes = processScenes;
|
||||
@@ -37,6 +64,7 @@ namespace Unity.Netcode
|
||||
|
||||
internal static void ProcessActiveScene()
|
||||
{
|
||||
FlushLog();
|
||||
var activeScene = SceneManager.GetActiveScene();
|
||||
if (s_ScenesToUpdate.Contains(activeScene.path) && s_ProcessScenes)
|
||||
{
|
||||
@@ -54,10 +82,12 @@ namespace Unity.Netcode
|
||||
}
|
||||
else
|
||||
{
|
||||
s_ProcessScenes = false;
|
||||
s_CloseScenes = false;
|
||||
EditorSceneManager.sceneSaved -= EditorSceneManager_sceneSaved;
|
||||
EditorSceneManager.sceneOpened -= EditorSceneManager_sceneOpened;
|
||||
AllScenesProcessed?.Invoke();
|
||||
FlushLog();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,9 +98,8 @@ namespace Unity.Netcode
|
||||
// Provide a log of all scenes that were modified to the user
|
||||
if (refreshed)
|
||||
{
|
||||
Debug.Log($"Refreshed and saved updates to scene: {scene.name}");
|
||||
LogInfo($"Refreshed and saved updates to scene: {scene.name}");
|
||||
}
|
||||
s_ProcessScenes = false;
|
||||
s_ScenesToUpdate.Remove(scene.path);
|
||||
|
||||
if (scene != SceneManager.GetActiveScene())
|
||||
@@ -88,24 +117,41 @@ namespace Unity.Netcode
|
||||
|
||||
private static void SceneOpened(Scene scene)
|
||||
{
|
||||
LogInfo($"Processing scene {scene.name}:");
|
||||
if (s_ScenesToUpdate.Contains(scene.path))
|
||||
{
|
||||
if (s_ProcessScenes)
|
||||
{
|
||||
if (!EditorSceneManager.MarkSceneDirty(scene))
|
||||
var prefabInstances = PrefabUtility.FindAllInstancesOfPrefab(PrefabNetworkObject.gameObject);
|
||||
|
||||
if (prefabInstances.Length > 0)
|
||||
{
|
||||
Debug.Log($"Scene {scene.name} did not get marked as dirty!");
|
||||
FinishedProcessingScene(scene);
|
||||
}
|
||||
else
|
||||
{
|
||||
EditorSceneManager.SaveScene(scene);
|
||||
var instancesSceneLoadedSpecific = prefabInstances.Where((c) => c.scene == scene).ToList();
|
||||
|
||||
if (instancesSceneLoadedSpecific.Count > 0)
|
||||
{
|
||||
foreach (var prefabInstance in instancesSceneLoadedSpecific)
|
||||
{
|
||||
prefabInstance.GetComponent<NetworkObject>().OnValidate();
|
||||
}
|
||||
|
||||
if (!EditorSceneManager.MarkSceneDirty(scene))
|
||||
{
|
||||
LogInfo($"Scene {scene.name} did not get marked as dirty!");
|
||||
FinishedProcessingScene(scene);
|
||||
}
|
||||
else
|
||||
{
|
||||
LogInfo($"Changes detected and applied!");
|
||||
EditorSceneManager.SaveScene(scene);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
FinishedProcessingScene(scene);
|
||||
}
|
||||
|
||||
LogInfo($"No changes required.");
|
||||
FinishedProcessingScene(scene);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -95,6 +95,7 @@ namespace Unity.Netcode
|
||||
return;
|
||||
}
|
||||
|
||||
ValidateMessageSize(messageBuffer, networkDelivery, isNamed: false);
|
||||
|
||||
if (m_NetworkManager.IsHost)
|
||||
{
|
||||
@@ -131,6 +132,8 @@ namespace Unity.Netcode
|
||||
/// <param name="networkDelivery">The delivery type (QoS) to send data with</param>
|
||||
public void SendUnnamedMessage(ulong clientId, FastBufferWriter messageBuffer, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced)
|
||||
{
|
||||
ValidateMessageSize(messageBuffer, networkDelivery, isNamed: false);
|
||||
|
||||
if (m_NetworkManager.IsHost)
|
||||
{
|
||||
if (clientId == m_NetworkManager.LocalClientId)
|
||||
@@ -286,6 +289,8 @@ namespace Unity.Netcode
|
||||
/// <param name="networkDelivery">The delivery type (QoS) to send data with</param>
|
||||
public void SendNamedMessage(string messageName, ulong clientId, FastBufferWriter messageStream, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced)
|
||||
{
|
||||
ValidateMessageSize(messageStream, networkDelivery, isNamed: true);
|
||||
|
||||
ulong hash = 0;
|
||||
switch (m_NetworkManager.NetworkConfig.RpcHashSize)
|
||||
{
|
||||
@@ -367,6 +372,8 @@ namespace Unity.Netcode
|
||||
return;
|
||||
}
|
||||
|
||||
ValidateMessageSize(messageStream, networkDelivery, isNamed: true);
|
||||
|
||||
ulong hash = 0;
|
||||
switch (m_NetworkManager.NetworkConfig.RpcHashSize)
|
||||
{
|
||||
@@ -405,5 +412,32 @@ namespace Unity.Netcode
|
||||
m_NetworkManager.NetworkMetrics.TrackNamedMessageSent(clientIds, messageName, size);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validate the size of the message. If it's a non-fragmented delivery type the message must fit within the
|
||||
/// max allowed size with headers also subtracted. Named messages also include the hash
|
||||
/// of the name string. Only validates in editor and development builds.
|
||||
/// </summary>
|
||||
/// <param name="messageStream">The named message payload</param>
|
||||
/// <param name="networkDelivery">Delivery method</param>
|
||||
/// <param name="isNamed">Is the message named (or unnamed)</param>
|
||||
/// <exception cref="OverflowException">Exception thrown in case validation fails</exception>
|
||||
private unsafe void ValidateMessageSize(FastBufferWriter messageStream, NetworkDelivery networkDelivery, bool isNamed)
|
||||
{
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
var maxNonFragmentedSize = m_NetworkManager.MessageManager.NonFragmentedMessageMaxSize - FastBufferWriter.GetWriteSize<NetworkMessageHeader>() - sizeof(NetworkBatchHeader);
|
||||
if (isNamed)
|
||||
{
|
||||
maxNonFragmentedSize -= sizeof(ulong); // MessageName hash
|
||||
}
|
||||
if (networkDelivery != NetworkDelivery.ReliableFragmentedSequenced
|
||||
&& messageStream.Length > maxNonFragmentedSize)
|
||||
{
|
||||
throw new OverflowException($"Given message size ({messageStream.Length} bytes) is greater than " +
|
||||
$"the maximum allowed for the selected delivery method ({maxNonFragmentedSize} bytes). Try using " +
|
||||
$"ReliableFragmentedSequenced delivery method instead.");
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ namespace Unity.Netcode
|
||||
|
||||
public ulong NetworkObjectId;
|
||||
public ulong OwnerClientId;
|
||||
// DANGOEXP TODO: Remove these notes or change their format
|
||||
// SERVICE NOTES:
|
||||
// When forwarding the message to clients on the CMB Service side,
|
||||
// you can set the ClientIdCount to 0 and skip writing the ClientIds.
|
||||
@@ -258,15 +257,18 @@ namespace Unity.Netcode
|
||||
continue;
|
||||
}
|
||||
|
||||
// If ownership is changing and this is not an ownership request approval then ignore the OnwerClientId
|
||||
// If it is just updating flags then ignore sending to the owner
|
||||
// If it is a request or approving request, then ignore the RequestClientId
|
||||
if ((OwnershipIsChanging && !RequestApproved && OwnerClientId == clientId) || (OwnershipFlagsUpdate && clientId == OwnerClientId)
|
||||
|| ((RequestOwnership || RequestApproved) && clientId == RequestClientId))
|
||||
// If ownership is changing and this is not an ownership request approval then ignore the SenderId
|
||||
if (OwnershipIsChanging && !RequestApproved && context.SenderId == clientId)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// If it is just updating flags then ignore sending to the owner
|
||||
// If it is a request or approving request, then ignore the RequestClientId
|
||||
if ((OwnershipFlagsUpdate && clientId == OwnerClientId) || ((RequestOwnership || RequestApproved) && clientId == RequestClientId))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
networkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.Reliable, clientId);
|
||||
}
|
||||
}
|
||||
@@ -292,7 +294,7 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handle the
|
||||
/// Handle the extended distributed authority ownership updates
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
private void HandleExtendedOwnershipUpdate(ref NetworkContext context)
|
||||
@@ -327,10 +329,12 @@ namespace Unity.Netcode
|
||||
var networkManager = (NetworkManager)context.SystemOwner;
|
||||
var networkObject = networkManager.SpawnManager.SpawnedObjects[NetworkObjectId];
|
||||
|
||||
// DANGO-TODO: This probably shouldn't be allowed to happen.
|
||||
// Sanity check that we are not sending duplicated change ownership messages
|
||||
if (networkObject.OwnerClientId == OwnerClientId)
|
||||
{
|
||||
UnityEngine.Debug.LogWarning($"Unnecessary ownership changed message for {NetworkObjectId}");
|
||||
// Log error and then ignore the message
|
||||
UnityEngine.Debug.LogError($"Client-{context.SenderId} ({RequestClientId}) sent unnecessary ownership changed message for {NetworkObjectId}.");
|
||||
return;
|
||||
}
|
||||
|
||||
var originalOwner = networkObject.OwnerClientId;
|
||||
@@ -347,12 +351,6 @@ namespace Unity.Netcode
|
||||
networkObject.InvokeBehaviourOnLostOwnership();
|
||||
}
|
||||
|
||||
// We are new owner or (client-server) or running in distributed authority mode
|
||||
if (OwnerClientId == networkManager.LocalClientId || networkManager.DistributedAuthorityMode)
|
||||
{
|
||||
networkObject.InvokeBehaviourOnGainedOwnership();
|
||||
}
|
||||
|
||||
// If in distributed authority mode
|
||||
if (networkManager.DistributedAuthorityMode)
|
||||
{
|
||||
@@ -374,6 +372,22 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
// We are new owner or (client-server) or running in distributed authority mode
|
||||
if (OwnerClientId == networkManager.LocalClientId || networkManager.DistributedAuthorityMode)
|
||||
{
|
||||
networkObject.InvokeBehaviourOnGainedOwnership();
|
||||
}
|
||||
|
||||
|
||||
if (originalOwner == networkManager.LocalClientId && !networkManager.DistributedAuthorityMode)
|
||||
{
|
||||
// Mark any owner read variables as dirty
|
||||
networkObject.MarkOwnerReadVariablesDirty();
|
||||
// Immediately queue any pending deltas and order the message before the
|
||||
// change in ownership message.
|
||||
networkManager.BehaviourUpdater.NetworkBehaviourUpdate(true);
|
||||
}
|
||||
|
||||
// Always invoke ownership change notifications
|
||||
networkObject.InvokeOwnershipChanged(originalOwner, OwnerClientId);
|
||||
|
||||
|
||||
@@ -55,10 +55,24 @@ namespace Unity.Netcode
|
||||
// Don't redistribute for the local instance
|
||||
if (ClientId != networkManager.LocalClientId)
|
||||
{
|
||||
// We defer redistribution to the end of the NetworkUpdateStage.PostLateUpdate
|
||||
networkManager.RedistributeToClient = true;
|
||||
networkManager.ClientToRedistribute = ClientId;
|
||||
networkManager.TickToRedistribute = networkManager.ServerTime.Tick + 20;
|
||||
// Synchronize the client with spawned objects (relative to each client)
|
||||
networkManager.SpawnManager.SynchronizeObjectsToNewlyJoinedClient(ClientId);
|
||||
|
||||
// Keeping for reference in case the above doesn't resolve for hidden objects (theoretically it should)
|
||||
// Show any NetworkObjects that are:
|
||||
// - Hidden from the session owner
|
||||
// - Owned by this client
|
||||
// - Has NetworkObject.SpawnWithObservers set to true (the default)
|
||||
//if (!networkManager.LocalClient.IsSessionOwner)
|
||||
//{
|
||||
// networkManager.SpawnManager.ShowHiddenObjectsToNewlyJoinedClient(ClientId);
|
||||
//}
|
||||
|
||||
/// We defer redistribution to happen after NetworkShow has been invoked
|
||||
/// <see cref="NetworkBehaviourUpdater.NetworkBehaviourUpdater_Tick"/>
|
||||
/// DANGO-TODO: Determine if this needs to be removed once the service handles object distribution
|
||||
networkManager.RedistributeToClients = true;
|
||||
networkManager.ClientsToRedistribute.Add(ClientId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,14 +3,54 @@ using Unity.Collections;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
internal struct ServiceConfig : INetworkSerializable
|
||||
{
|
||||
public uint SessionVersion;
|
||||
public bool IsRestoredSession;
|
||||
public ulong CurrentSessionOwner;
|
||||
public bool ServerRedistribution;
|
||||
|
||||
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
|
||||
{
|
||||
if (serializer.IsWriter)
|
||||
{
|
||||
BytePacker.WriteValueBitPacked(serializer.GetFastBufferWriter(), SessionVersion);
|
||||
serializer.SerializeValue(ref IsRestoredSession);
|
||||
BytePacker.WriteValueBitPacked(serializer.GetFastBufferWriter(), CurrentSessionOwner);
|
||||
|
||||
if (SessionVersion >= SessionConfig.ServerDistributionCompatible)
|
||||
{
|
||||
serializer.SerializeValue(ref ServerRedistribution);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ByteUnpacker.ReadValueBitPacked(serializer.GetFastBufferReader(), out SessionVersion);
|
||||
serializer.SerializeValue(ref IsRestoredSession);
|
||||
ByteUnpacker.ReadValueBitPacked(serializer.GetFastBufferReader(), out CurrentSessionOwner);
|
||||
|
||||
if (SessionVersion >= SessionConfig.ServerDistributionCompatible)
|
||||
{
|
||||
serializer.SerializeValue(ref ServerRedistribution);
|
||||
}
|
||||
else
|
||||
{
|
||||
ServerRedistribution = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal struct ConnectionApprovedMessage : INetworkMessage
|
||||
{
|
||||
private const int k_AddCMBServiceConfig = 2;
|
||||
private const int k_VersionAddClientIds = 1;
|
||||
public int Version => k_VersionAddClientIds;
|
||||
public int Version => k_AddCMBServiceConfig;
|
||||
|
||||
public ulong OwnerClientId;
|
||||
public int NetworkTick;
|
||||
// The cloud state service should set this if we are restoring a session
|
||||
public ServiceConfig ServiceConfig;
|
||||
public bool IsRestoredSession;
|
||||
public ulong CurrentSessionOwner;
|
||||
// Not serialized
|
||||
@@ -25,6 +65,32 @@ namespace Unity.Netcode
|
||||
|
||||
public NativeArray<ulong> ConnectedClientIds;
|
||||
|
||||
private int m_ReceiveMessageVersion;
|
||||
|
||||
private ulong GetSessionOwner()
|
||||
{
|
||||
if (m_ReceiveMessageVersion >= k_AddCMBServiceConfig)
|
||||
{
|
||||
return ServiceConfig.CurrentSessionOwner;
|
||||
}
|
||||
else
|
||||
{
|
||||
return CurrentSessionOwner;
|
||||
}
|
||||
}
|
||||
|
||||
private bool GetIsSessionRestor()
|
||||
{
|
||||
if (m_ReceiveMessageVersion >= k_AddCMBServiceConfig)
|
||||
{
|
||||
return ServiceConfig.IsRestoredSession;
|
||||
}
|
||||
else
|
||||
{
|
||||
return IsRestoredSession;
|
||||
}
|
||||
}
|
||||
|
||||
public void Serialize(FastBufferWriter writer, int targetVersion)
|
||||
{
|
||||
// ============================================================
|
||||
@@ -45,8 +111,17 @@ namespace Unity.Netcode
|
||||
BytePacker.WriteValueBitPacked(writer, NetworkTick);
|
||||
if (IsDistributedAuthority)
|
||||
{
|
||||
writer.WriteValueSafe(IsRestoredSession);
|
||||
BytePacker.WriteValueBitPacked(writer, CurrentSessionOwner);
|
||||
if (targetVersion >= k_AddCMBServiceConfig)
|
||||
{
|
||||
ServiceConfig.IsRestoredSession = false;
|
||||
ServiceConfig.CurrentSessionOwner = CurrentSessionOwner;
|
||||
writer.WriteNetworkSerializable(ServiceConfig);
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteValueSafe(IsRestoredSession);
|
||||
BytePacker.WriteValueBitPacked(writer, CurrentSessionOwner);
|
||||
}
|
||||
}
|
||||
|
||||
if (targetVersion >= k_VersionAddClientIds)
|
||||
@@ -122,13 +197,22 @@ namespace Unity.Netcode
|
||||
// ============================================================
|
||||
// END FORBIDDEN SEGMENT
|
||||
// ============================================================
|
||||
|
||||
m_ReceiveMessageVersion = receivedMessageVersion;
|
||||
ByteUnpacker.ReadValueBitPacked(reader, out OwnerClientId);
|
||||
ByteUnpacker.ReadValueBitPacked(reader, out NetworkTick);
|
||||
if (networkManager.DistributedAuthorityMode)
|
||||
{
|
||||
reader.ReadValueSafe(out IsRestoredSession);
|
||||
ByteUnpacker.ReadValueBitPacked(reader, out CurrentSessionOwner);
|
||||
if (receivedMessageVersion >= k_AddCMBServiceConfig)
|
||||
{
|
||||
reader.ReadNetworkSerializable(out ServiceConfig);
|
||||
networkManager.SessionConfig = new SessionConfig(ServiceConfig);
|
||||
}
|
||||
else
|
||||
{
|
||||
reader.ReadValueSafe(out IsRestoredSession);
|
||||
ByteUnpacker.ReadValueBitPacked(reader, out CurrentSessionOwner);
|
||||
networkManager.SessionConfig = new SessionConfig(SessionConfig.NoFeatureCompatibility);
|
||||
}
|
||||
}
|
||||
|
||||
if (receivedMessageVersion >= k_VersionAddClientIds)
|
||||
@@ -157,7 +241,7 @@ namespace Unity.Netcode
|
||||
|
||||
if (networkManager.DistributedAuthorityMode)
|
||||
{
|
||||
networkManager.SetSessionOwner(CurrentSessionOwner);
|
||||
networkManager.SetSessionOwner(GetSessionOwner());
|
||||
if (networkManager.LocalClient.IsSessionOwner && networkManager.NetworkConfig.EnableSceneManagement)
|
||||
{
|
||||
networkManager.SceneManager.InitializeScenesLoaded();
|
||||
@@ -233,9 +317,9 @@ namespace Unity.Netcode
|
||||
// Mark the client being connected
|
||||
networkManager.IsConnectedClient = true;
|
||||
|
||||
networkManager.SceneManager.IsRestoringSession = IsRestoredSession;
|
||||
networkManager.SceneManager.IsRestoringSession = GetIsSessionRestor();
|
||||
|
||||
if (!IsRestoredSession)
|
||||
if (!networkManager.SceneManager.IsRestoringSession)
|
||||
{
|
||||
// Synchronize the service with the initial session owner's loaded scenes and spawned objects
|
||||
networkManager.SceneManager.SynchronizeNetworkObjects(NetworkManager.ServerClientId);
|
||||
|
||||
@@ -2,16 +2,53 @@ using Unity.Collections;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
internal struct ConnectionRequestMessage : INetworkMessage
|
||||
/// <summary>
|
||||
/// Only used when connecting to the distributed authority service
|
||||
/// </summary>
|
||||
internal struct ClientConfig : INetworkSerializable
|
||||
{
|
||||
public int Version => 0;
|
||||
|
||||
public ulong ConfigHash;
|
||||
|
||||
public bool CMBServiceConnection;
|
||||
public SessionConfig SessionConfig;
|
||||
public int SessionVersion => (int)SessionConfig.SessionVersion;
|
||||
public uint TickRate;
|
||||
public bool EnableSceneManagement;
|
||||
|
||||
// Only gets deserialized but should never be used unless testing
|
||||
public int RemoteClientSessionVersion;
|
||||
|
||||
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
|
||||
{
|
||||
// Clients always write
|
||||
if (serializer.IsWriter)
|
||||
{
|
||||
var writer = serializer.GetFastBufferWriter();
|
||||
BytePacker.WriteValueBitPacked(writer, SessionVersion);
|
||||
BytePacker.WriteValueBitPacked(writer, TickRate);
|
||||
writer.WriteValueSafe(EnableSceneManagement);
|
||||
}
|
||||
else
|
||||
{
|
||||
var reader = serializer.GetFastBufferReader();
|
||||
ByteUnpacker.ReadValueBitPacked(reader, out RemoteClientSessionVersion);
|
||||
ByteUnpacker.ReadValueBitPacked(reader, out TickRate);
|
||||
reader.ReadValueSafe(out EnableSceneManagement);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal struct ConnectionRequestMessage : INetworkMessage
|
||||
{
|
||||
internal const string InvalidSessionVersionMessage = "The client version is not compatible with the session version.";
|
||||
|
||||
// This version update is unidirectional (client to service) and version
|
||||
// handling occurs on the service side. This serialized data is never sent
|
||||
// to a host or server.
|
||||
private const int k_SendClientConfigToService = 1;
|
||||
public int Version => k_SendClientConfigToService;
|
||||
|
||||
public ulong ConfigHash;
|
||||
public bool DistributedAuthority;
|
||||
public ClientConfig ClientConfig;
|
||||
|
||||
public byte[] ConnectionData;
|
||||
|
||||
public bool ShouldSendConnectionData;
|
||||
@@ -34,10 +71,9 @@ namespace Unity.Netcode
|
||||
// END FORBIDDEN SEGMENT
|
||||
// ============================================================
|
||||
|
||||
if (CMBServiceConnection)
|
||||
if (DistributedAuthority)
|
||||
{
|
||||
writer.WriteValueSafe(TickRate);
|
||||
writer.WriteValueSafe(EnableSceneManagement);
|
||||
writer.WriteNetworkSerializable(ClientConfig);
|
||||
}
|
||||
|
||||
if (ShouldSendConnectionData)
|
||||
@@ -83,6 +119,11 @@ namespace Unity.Netcode
|
||||
// END FORBIDDEN SEGMENT
|
||||
// ============================================================
|
||||
|
||||
if (networkManager.DAHost)
|
||||
{
|
||||
reader.ReadNetworkSerializable(out ClientConfig);
|
||||
}
|
||||
|
||||
if (networkManager.NetworkConfig.ConnectionApproval)
|
||||
{
|
||||
if (!reader.TryBeginRead(FastBufferWriter.GetWriteSize(ConfigHash) + FastBufferWriter.GetWriteSize<int>()))
|
||||
@@ -145,6 +186,17 @@ namespace Unity.Netcode
|
||||
var networkManager = (NetworkManager)context.SystemOwner;
|
||||
var senderId = context.SenderId;
|
||||
|
||||
// DAHost mocking the service logic to disconnect clients trying to connect with a lower session version
|
||||
if (networkManager.DAHost)
|
||||
{
|
||||
if (ClientConfig.RemoteClientSessionVersion < networkManager.SessionConfig.SessionVersion)
|
||||
{
|
||||
//Disconnect with reason
|
||||
networkManager.ConnectionManager.DisconnectClient(senderId, InvalidSessionVersionMessage);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (networkManager.ConnectionManager.PendingClients.TryGetValue(senderId, out PendingClient client))
|
||||
{
|
||||
// Set to pending approval to prevent future connection requests from being approved
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Unity.Collections;
|
||||
|
||||
namespace Unity.Netcode
|
||||
@@ -10,9 +11,22 @@ namespace Unity.Netcode
|
||||
/// serialization. This is due to the generally amorphous nature of network variable
|
||||
/// deltas, since they're all driven by custom virtual method overloads.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Version 1:
|
||||
/// This version -does not- use the "KeepDirty" approach. Instead, the server will forward any state updates
|
||||
/// to the connected clients that are not the sender or the server itself. Each NetworkVariable state update
|
||||
/// included, on a per client basis, is first validated that the client can read the NetworkVariable before
|
||||
/// being added to the m_ForwardUpdates table.
|
||||
/// Version 0:
|
||||
/// The original version uses the "KeepDirty" approach in a client-server network topology where the server
|
||||
/// proxies state updates by "keeping the NetworkVariable(s) dirty" so it will send state updates
|
||||
/// at the end of the frame (but could delay until the next tick).
|
||||
/// </remarks>
|
||||
internal struct NetworkVariableDeltaMessage : INetworkMessage
|
||||
{
|
||||
public int Version => 0;
|
||||
private const int k_ServerDeltaForwardingAndNetworkDelivery = 1;
|
||||
public int Version => k_ServerDeltaForwardingAndNetworkDelivery;
|
||||
|
||||
|
||||
public ulong NetworkObjectId;
|
||||
public ushort NetworkBehaviourIndex;
|
||||
@@ -21,12 +35,62 @@ namespace Unity.Netcode
|
||||
public ulong TargetClientId;
|
||||
public NetworkBehaviour NetworkBehaviour;
|
||||
|
||||
public NetworkDelivery NetworkDelivery;
|
||||
|
||||
private FastBufferReader m_ReceivedNetworkVariableData;
|
||||
|
||||
private bool m_ForwardingMessage;
|
||||
|
||||
private int m_ReceivedMessageVersion;
|
||||
|
||||
private const string k_Name = "NetworkVariableDeltaMessage";
|
||||
|
||||
// DANGO-TODO: Made some modifications here that overlap/won't play nice with EnsureNetworkVariableLenghtSafety.
|
||||
// Worth either merging or more cleanly separating these codepaths.
|
||||
private Dictionary<ulong, List<int>> m_ForwardUpdates;
|
||||
|
||||
private List<int> m_UpdatedNetworkVariables;
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void WriteNetworkVariable(ref FastBufferWriter writer, ref NetworkVariableBase networkVariable, bool distributedAuthorityMode, bool ensureNetworkVariableLengthSafety, int nonfragmentedSize, int fragmentedSize)
|
||||
{
|
||||
if (ensureNetworkVariableLengthSafety)
|
||||
{
|
||||
var tempWriter = new FastBufferWriter(nonfragmentedSize, Allocator.Temp, fragmentedSize);
|
||||
networkVariable.WriteDelta(tempWriter);
|
||||
BytePacker.WriteValueBitPacked(writer, tempWriter.Length);
|
||||
|
||||
if (!writer.TryBeginWrite(tempWriter.Length))
|
||||
{
|
||||
throw new OverflowException($"Not enough space in the buffer to write {nameof(NetworkVariableDeltaMessage)}");
|
||||
}
|
||||
|
||||
tempWriter.CopyTo(writer);
|
||||
}
|
||||
else
|
||||
{
|
||||
// TODO: Determine if we need to remove this with the 6.1 service updates
|
||||
if (distributedAuthorityMode)
|
||||
{
|
||||
var size_marker = writer.Position;
|
||||
writer.WriteValueSafe<ushort>(0);
|
||||
var start_marker = writer.Position;
|
||||
networkVariable.WriteDelta(writer);
|
||||
var end_marker = writer.Position;
|
||||
writer.Seek(size_marker);
|
||||
var size = end_marker - start_marker;
|
||||
if (size == 0)
|
||||
{
|
||||
UnityEngine.Debug.LogError($"Invalid write size of zero!");
|
||||
}
|
||||
writer.WriteValueSafe((ushort)size);
|
||||
writer.Seek(end_marker);
|
||||
}
|
||||
else
|
||||
{
|
||||
networkVariable.WriteDelta(writer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Serialize(FastBufferWriter writer, int targetVersion)
|
||||
{
|
||||
if (!writer.TryBeginWrite(FastBufferWriter.GetWriteSize(NetworkObjectId) + FastBufferWriter.GetWriteSize(NetworkBehaviourIndex)))
|
||||
@@ -36,10 +100,67 @@ namespace Unity.Netcode
|
||||
|
||||
var obj = NetworkBehaviour.NetworkObject;
|
||||
var networkManager = obj.NetworkManagerOwner;
|
||||
var typeName = NetworkBehaviour.__getTypeName();
|
||||
var nonFragmentedMessageMaxSize = networkManager.MessageManager.NonFragmentedMessageMaxSize;
|
||||
var fragmentedMessageMaxSize = networkManager.MessageManager.FragmentedMessageMaxSize;
|
||||
var ensureNetworkVariableLengthSafety = networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety;
|
||||
var distributedAuthorityMode = networkManager.DistributedAuthorityMode;
|
||||
|
||||
BytePacker.WriteValueBitPacked(writer, NetworkObjectId);
|
||||
BytePacker.WriteValueBitPacked(writer, NetworkBehaviourIndex);
|
||||
if (networkManager.DistributedAuthorityMode)
|
||||
|
||||
// If using k_IncludeNetworkDelivery version, then we want to write the network delivery used and if we
|
||||
// are forwarding state updates then serialize any NetworkVariable states specific to this client.
|
||||
if (targetVersion >= k_ServerDeltaForwardingAndNetworkDelivery)
|
||||
{
|
||||
writer.WriteValueSafe(NetworkDelivery);
|
||||
// If we are forwarding the message, then proceed to forward state updates specific to the targeted client
|
||||
if (m_ForwardingMessage)
|
||||
{
|
||||
// DANGO TODO: Remove distributedAuthorityMode portion when we remove the service specific NetworkVariable stuff
|
||||
if (distributedAuthorityMode)
|
||||
{
|
||||
writer.WriteValueSafe((ushort)NetworkBehaviour.NetworkVariableFields.Count);
|
||||
}
|
||||
|
||||
for (int i = 0; i < NetworkBehaviour.NetworkVariableFields.Count; i++)
|
||||
{
|
||||
var startingSize = writer.Length;
|
||||
var networkVariable = NetworkBehaviour.NetworkVariableFields[i];
|
||||
var shouldWrite = m_ForwardUpdates[TargetClientId].Contains(i);
|
||||
|
||||
// This var does not belong to the currently iterating delivery group.
|
||||
if (distributedAuthorityMode)
|
||||
{
|
||||
if (!shouldWrite)
|
||||
{
|
||||
writer.WriteValueSafe<ushort>(0);
|
||||
}
|
||||
}
|
||||
else if (ensureNetworkVariableLengthSafety)
|
||||
{
|
||||
if (!shouldWrite)
|
||||
{
|
||||
BytePacker.WriteValueBitPacked(writer, (ushort)0);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteValueSafe(shouldWrite);
|
||||
}
|
||||
|
||||
if (shouldWrite)
|
||||
{
|
||||
WriteNetworkVariable(ref writer, ref networkVariable, distributedAuthorityMode, ensureNetworkVariableLengthSafety, nonFragmentedMessageMaxSize, fragmentedMessageMaxSize);
|
||||
networkManager.NetworkMetrics.TrackNetworkVariableDeltaSent(TargetClientId, obj, networkVariable.Name, typeName, writer.Length - startingSize);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// DANGO TODO: Remove this when we remove the service specific NetworkVariable stuff
|
||||
if (distributedAuthorityMode)
|
||||
{
|
||||
writer.WriteValueSafe((ushort)NetworkBehaviour.NetworkVariableFields.Count);
|
||||
}
|
||||
@@ -48,12 +169,12 @@ namespace Unity.Netcode
|
||||
{
|
||||
if (!DeliveryMappedNetworkVariableIndex.Contains(i))
|
||||
{
|
||||
// This var does not belong to the currently iterating delivery group.
|
||||
if (networkManager.DistributedAuthorityMode)
|
||||
// DANGO TODO: Remove distributedAuthorityMode portion when we remove the service specific NetworkVariable stuff
|
||||
if (distributedAuthorityMode)
|
||||
{
|
||||
writer.WriteValueSafe<ushort>(0);
|
||||
}
|
||||
else if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
|
||||
else if (ensureNetworkVariableLengthSafety)
|
||||
{
|
||||
BytePacker.WriteValueBitPacked(writer, (ushort)0);
|
||||
}
|
||||
@@ -90,14 +211,15 @@ namespace Unity.Netcode
|
||||
shouldWrite = false;
|
||||
}
|
||||
|
||||
if (networkManager.DistributedAuthorityMode)
|
||||
// DANGO TODO: Remove distributedAuthorityMode portion when we remove the service specific NetworkVariable stuff
|
||||
if (distributedAuthorityMode)
|
||||
{
|
||||
if (!shouldWrite)
|
||||
{
|
||||
writer.WriteValueSafe<ushort>(0);
|
||||
}
|
||||
}
|
||||
else if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
|
||||
else if (ensureNetworkVariableLengthSafety)
|
||||
{
|
||||
if (!shouldWrite)
|
||||
{
|
||||
@@ -111,71 +233,39 @@ namespace Unity.Netcode
|
||||
|
||||
if (shouldWrite)
|
||||
{
|
||||
if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
|
||||
{
|
||||
var tempWriter = new FastBufferWriter(networkManager.MessageManager.NonFragmentedMessageMaxSize, Allocator.Temp, networkManager.MessageManager.FragmentedMessageMaxSize);
|
||||
NetworkBehaviour.NetworkVariableFields[i].WriteDelta(tempWriter);
|
||||
BytePacker.WriteValueBitPacked(writer, tempWriter.Length);
|
||||
|
||||
if (!writer.TryBeginWrite(tempWriter.Length))
|
||||
{
|
||||
throw new OverflowException($"Not enough space in the buffer to write {nameof(NetworkVariableDeltaMessage)}");
|
||||
}
|
||||
|
||||
tempWriter.CopyTo(writer);
|
||||
}
|
||||
else
|
||||
{
|
||||
// DANGO-TODO:
|
||||
// Complex types with custom type serialization (either registered custom types or INetworkSerializable implementations) will be problematic
|
||||
// Non-complex types always provide a full state update per delta
|
||||
// DANGO-TODO: Add NetworkListEvent<T>.EventType awareness to the cloud-state server
|
||||
if (networkManager.DistributedAuthorityMode)
|
||||
{
|
||||
var size_marker = writer.Position;
|
||||
writer.WriteValueSafe<ushort>(0);
|
||||
var start_marker = writer.Position;
|
||||
networkVariable.WriteDelta(writer);
|
||||
var end_marker = writer.Position;
|
||||
writer.Seek(size_marker);
|
||||
var size = end_marker - start_marker;
|
||||
writer.WriteValueSafe((ushort)size);
|
||||
writer.Seek(end_marker);
|
||||
}
|
||||
else
|
||||
{
|
||||
networkVariable.WriteDelta(writer);
|
||||
}
|
||||
}
|
||||
networkManager.NetworkMetrics.TrackNetworkVariableDeltaSent(
|
||||
TargetClientId,
|
||||
obj,
|
||||
networkVariable.Name,
|
||||
NetworkBehaviour.__getTypeName(),
|
||||
writer.Length - startingSize);
|
||||
WriteNetworkVariable(ref writer, ref networkVariable, distributedAuthorityMode, ensureNetworkVariableLengthSafety, nonFragmentedMessageMaxSize, fragmentedMessageMaxSize);
|
||||
networkManager.NetworkMetrics.TrackNetworkVariableDeltaSent(TargetClientId, obj, networkVariable.Name, typeName, writer.Length - startingSize);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
|
||||
{
|
||||
m_ReceivedMessageVersion = receivedMessageVersion;
|
||||
ByteUnpacker.ReadValueBitPacked(reader, out NetworkObjectId);
|
||||
ByteUnpacker.ReadValueBitPacked(reader, out NetworkBehaviourIndex);
|
||||
|
||||
// If we are using the k_IncludeNetworkDelivery message version, then read the NetworkDelivery used
|
||||
if (receivedMessageVersion >= k_ServerDeltaForwardingAndNetworkDelivery)
|
||||
{
|
||||
reader.ReadValueSafe(out NetworkDelivery);
|
||||
}
|
||||
m_ReceivedNetworkVariableData = reader;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// DANGO-TODO: Made some modifications here that overlap/won't play nice with EnsureNetworkVariableLenghtSafety.
|
||||
// Worth either merging or more cleanly separating these codepaths.
|
||||
public void Handle(ref NetworkContext context)
|
||||
{
|
||||
var networkManager = (NetworkManager)context.SystemOwner;
|
||||
|
||||
if (networkManager.SpawnManager.SpawnedObjects.TryGetValue(NetworkObjectId, out NetworkObject networkObject))
|
||||
{
|
||||
var distributedAuthorityMode = networkManager.DistributedAuthorityMode;
|
||||
var ensureNetworkVariableLengthSafety = networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety;
|
||||
var networkBehaviour = networkObject.GetNetworkBehaviourAtOrderIndex(NetworkBehaviourIndex);
|
||||
var isServerAndDeltaForwarding = m_ReceivedMessageVersion >= k_ServerDeltaForwardingAndNetworkDelivery && networkManager.IsServer;
|
||||
var markNetworkVariableDirty = m_ReceivedMessageVersion >= k_ServerDeltaForwardingAndNetworkDelivery ? false : networkManager.IsServer;
|
||||
m_UpdatedNetworkVariables = new List<int>();
|
||||
|
||||
if (networkBehaviour == null)
|
||||
{
|
||||
@@ -186,7 +276,8 @@ namespace Unity.Netcode
|
||||
}
|
||||
else
|
||||
{
|
||||
if (networkManager.DistributedAuthorityMode)
|
||||
// DANGO TODO: Remove distributedAuthorityMode portion when we remove the service specific NetworkVariable stuff
|
||||
if (distributedAuthorityMode)
|
||||
{
|
||||
m_ReceivedNetworkVariableData.ReadValueSafe(out ushort variableCount);
|
||||
if (variableCount != networkBehaviour.NetworkVariableFields.Count)
|
||||
@@ -195,10 +286,30 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
// (For client-server) As opposed to worrying about adding additional processing on the server to send NetworkVariable
|
||||
// updates at the end of the frame, we now track all NetworkVariable state updates, per client, that need to be forwarded
|
||||
// to the client. This creates a list of all remaining connected clients that could have updates applied.
|
||||
if (isServerAndDeltaForwarding)
|
||||
{
|
||||
m_ForwardUpdates = new Dictionary<ulong, List<int>>();
|
||||
foreach (var clientId in networkManager.ConnectedClientsIds)
|
||||
{
|
||||
if (clientId == context.SenderId || clientId == networkManager.LocalClientId || !networkObject.Observers.Contains(clientId))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
m_ForwardUpdates.Add(clientId, new List<int>());
|
||||
}
|
||||
}
|
||||
|
||||
// Update NetworkVariable Fields
|
||||
for (int i = 0; i < networkBehaviour.NetworkVariableFields.Count; i++)
|
||||
{
|
||||
int varSize = 0;
|
||||
if (networkManager.DistributedAuthorityMode)
|
||||
var networkVariable = networkBehaviour.NetworkVariableFields[i];
|
||||
|
||||
// DANGO TODO: Remove distributedAuthorityMode portion when we remove the service specific NetworkVariable stuff
|
||||
if (distributedAuthorityMode)
|
||||
{
|
||||
m_ReceivedNetworkVariableData.ReadValueSafe(out ushort variableSize);
|
||||
varSize = variableSize;
|
||||
@@ -208,10 +319,9 @@ namespace Unity.Netcode
|
||||
continue;
|
||||
}
|
||||
}
|
||||
else if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
|
||||
else if (ensureNetworkVariableLengthSafety)
|
||||
{
|
||||
ByteUnpacker.ReadValueBitPacked(m_ReceivedNetworkVariableData, out varSize);
|
||||
|
||||
if (varSize == 0)
|
||||
{
|
||||
continue;
|
||||
@@ -226,8 +336,6 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
var networkVariable = networkBehaviour.NetworkVariableFields[i];
|
||||
|
||||
if (networkManager.IsServer && !networkVariable.CanClientWrite(context.SenderId))
|
||||
{
|
||||
// we are choosing not to fire an exception here, because otherwise a malicious client could use this to crash the server
|
||||
@@ -255,13 +363,58 @@ namespace Unity.Netcode
|
||||
NetworkLog.LogError($"Client wrote to {typeof(NetworkVariable<>).Name} without permission. No more variables can be read. This is critical. => {nameof(NetworkObjectId)}: {NetworkObjectId} - {nameof(NetworkObject.GetNetworkBehaviourOrderIndex)}(): {networkObject.GetNetworkBehaviourOrderIndex(networkBehaviour)} - VariableIndex: {i}");
|
||||
NetworkLog.LogError($"[{networkVariable.GetType().Name}]");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
int readStartPos = m_ReceivedNetworkVariableData.Position;
|
||||
|
||||
// Read Delta so we also notify any subscribers to a change in the NetworkVariable
|
||||
networkVariable.ReadDelta(m_ReceivedNetworkVariableData, networkManager.IsServer);
|
||||
// DANGO TODO: Remove distributedAuthorityMode portion when we remove the service specific NetworkVariable stuff
|
||||
if (distributedAuthorityMode || ensureNetworkVariableLengthSafety)
|
||||
{
|
||||
var remainingBufferSize = m_ReceivedNetworkVariableData.Length - m_ReceivedNetworkVariableData.Position;
|
||||
if (varSize > (remainingBufferSize))
|
||||
{
|
||||
UnityEngine.Debug.LogError($"[{networkBehaviour.name}][Delta State Read Error] Expecting to read {varSize} but only {remainingBufferSize} remains!");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Added a try catch here to assure any failure will only fail on this one message and not disrupt the stack
|
||||
try
|
||||
{
|
||||
// Read the delta
|
||||
networkVariable.ReadDelta(m_ReceivedNetworkVariableData, markNetworkVariableDirty);
|
||||
|
||||
// Add the NetworkVariable field index so we can invoke the PostDeltaRead
|
||||
m_UpdatedNetworkVariables.Add(i);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
UnityEngine.Debug.LogException(ex);
|
||||
return;
|
||||
}
|
||||
|
||||
// (For client-server) As opposed to worrying about adding additional processing on the server to send NetworkVariable
|
||||
// updates at the end of the frame, we now track all NetworkVariable state updates, per client, that need to be forwarded
|
||||
// to the client. This happens once the server is finished processing all state updates for this message.
|
||||
if (isServerAndDeltaForwarding)
|
||||
{
|
||||
foreach (var forwardEntry in m_ForwardUpdates)
|
||||
{
|
||||
// Only track things that the client can read
|
||||
if (networkVariable.CanClientRead(forwardEntry.Key))
|
||||
{
|
||||
// If the object is about to be shown to the client then don't send an update as it will
|
||||
// send a full update when shown.
|
||||
if (networkManager.SpawnManager.ObjectsToShowToClient.ContainsKey(forwardEntry.Key) &&
|
||||
networkManager.SpawnManager.ObjectsToShowToClient[forwardEntry.Key]
|
||||
.Contains(networkObject))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
forwardEntry.Value.Add(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
networkManager.NetworkMetrics.TrackNetworkVariableDeltaReceived(
|
||||
context.SenderId,
|
||||
@@ -270,7 +423,8 @@ namespace Unity.Netcode
|
||||
networkBehaviour.__getTypeName(),
|
||||
context.MessageSize);
|
||||
|
||||
if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety || networkManager.DistributedAuthorityMode)
|
||||
// DANGO TODO: Remove distributedAuthorityMode portion when we remove the service specific NetworkVariable stuff
|
||||
if (distributedAuthorityMode || ensureNetworkVariableLengthSafety)
|
||||
{
|
||||
if (m_ReceivedNetworkVariableData.Position > (readStartPos + varSize))
|
||||
{
|
||||
@@ -292,6 +446,40 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we are using the version of this message that includes network delivery, then
|
||||
// forward this update to all connected clients (other than the sender and the server).
|
||||
if (isServerAndDeltaForwarding)
|
||||
{
|
||||
var message = new NetworkVariableDeltaMessage()
|
||||
{
|
||||
NetworkBehaviour = networkBehaviour,
|
||||
NetworkBehaviourIndex = NetworkBehaviourIndex,
|
||||
NetworkObjectId = NetworkObjectId,
|
||||
m_ForwardingMessage = true,
|
||||
m_ForwardUpdates = m_ForwardUpdates,
|
||||
};
|
||||
|
||||
foreach (var forwardEntry in m_ForwardUpdates)
|
||||
{
|
||||
// Only forward updates to any client that has visibility to the state updates included in this message
|
||||
if (forwardEntry.Value.Count > 0)
|
||||
{
|
||||
message.TargetClientId = forwardEntry.Key;
|
||||
networkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery, forwardEntry.Key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// This should be always invoked (client & server) to assure the previous values are set
|
||||
// !! IMPORTANT ORDER OF OPERATIONS !! (Has to happen after forwarding deltas)
|
||||
// When a server forwards delta updates to connected clients, it needs to preserve the previous value
|
||||
// until it is done serializing all valid NetworkVariable field deltas (relative to each client). This
|
||||
// is invoked after it is done forwarding the deltas.
|
||||
foreach (var fieldIndex in m_UpdatedNetworkVariables)
|
||||
{
|
||||
networkBehaviour.NetworkVariableFields[fieldIndex].PostDeltaRead();
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
|
||||
@@ -70,10 +70,6 @@ namespace Unity.Netcode
|
||||
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
|
||||
{
|
||||
var networkManager = (NetworkManager)context.SystemOwner;
|
||||
if (!networkManager.IsClient)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
ByteUnpacker.ReadValueBitPacked(reader, out NetworkObjectId);
|
||||
reader.ReadValueSafe(out m_BitField);
|
||||
@@ -117,22 +113,28 @@ namespace Unity.Netcode
|
||||
networkObject.SetNetworkParenting(LatestParent, WorldPositionStays);
|
||||
networkObject.ApplyNetworkParenting(RemoveParent);
|
||||
|
||||
// We set all of the transform values after parenting as they are
|
||||
// the values of the server-side post-parenting transform values
|
||||
if (!WorldPositionStays)
|
||||
// This check is primarily for client-server network topologies when the motion model is owner authoritative:
|
||||
// When SyncOwnerTransformWhenParented is enabled, then always apply the transform values.
|
||||
// When SyncOwnerTransformWhenParented is disabled, then only synchronize the transform on non-owner instances.
|
||||
if (networkObject.SyncOwnerTransformWhenParented || (!networkObject.SyncOwnerTransformWhenParented && !networkObject.IsOwner))
|
||||
{
|
||||
networkObject.transform.localPosition = Position;
|
||||
networkObject.transform.localRotation = Rotation;
|
||||
// We set all of the transform values after parenting as they are
|
||||
// the values of the server-side post-parenting transform values
|
||||
if (!WorldPositionStays)
|
||||
{
|
||||
networkObject.transform.localPosition = Position;
|
||||
networkObject.transform.localRotation = Rotation;
|
||||
}
|
||||
else
|
||||
{
|
||||
networkObject.transform.position = Position;
|
||||
networkObject.transform.rotation = Rotation;
|
||||
}
|
||||
networkObject.transform.localScale = Scale;
|
||||
}
|
||||
else
|
||||
{
|
||||
networkObject.transform.position = Position;
|
||||
networkObject.transform.rotation = Rotation;
|
||||
}
|
||||
networkObject.transform.localScale = Scale;
|
||||
|
||||
// If in distributed authority mode and we are running a DAHost and this is the DAHost, then forward the parent changed message to any remaining clients
|
||||
if (networkManager.DistributedAuthorityMode && !networkManager.CMBServiceConnection && networkManager.DAHost)
|
||||
if ((networkManager.DistributedAuthorityMode && !networkManager.CMBServiceConnection && networkManager.DAHost) || (networkObject.AllowOwnerToParent && context.SenderId == networkObject.OwnerClientId && networkManager.IsServer))
|
||||
{
|
||||
var size = 0;
|
||||
var message = this;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
using System;
|
||||
using Unity.Collections;
|
||||
|
||||
namespace Unity.Netcode
|
||||
@@ -34,21 +33,13 @@ namespace Unity.Netcode
|
||||
var networkManager = (NetworkManager)context.SystemOwner;
|
||||
if (!networkManager.SpawnManager.SpawnedObjects.TryGetValue(WrappedMessage.Metadata.NetworkObjectId, out var networkObject))
|
||||
{
|
||||
// With distributed authority mode, we can send Rpcs before we have been notified the NetworkObject is despawned.
|
||||
// DANGO-TODO: Should the CMB Service cull out any Rpcs targeting recently despawned NetworkObjects?
|
||||
// DANGO-TODO: This would require the service to keep track of despawned NetworkObjects since we re-use NetworkObject identifiers.
|
||||
if (networkManager.DistributedAuthorityMode)
|
||||
// If the NetworkObject no longer exists then just log a warning when developer mode logging is enabled and exit.
|
||||
// This can happen if NetworkObject is despawned and a client sends an RPC before receiving the despawn message.
|
||||
if (networkManager.LogLevel == LogLevel.Developer)
|
||||
{
|
||||
if (networkManager.LogLevel == LogLevel.Developer)
|
||||
{
|
||||
NetworkLog.LogWarning($"[{WrappedMessage.Metadata.NetworkObjectId}, {WrappedMessage.Metadata.NetworkBehaviourId}, {WrappedMessage.Metadata.NetworkRpcMethodId}]An RPC called on a {nameof(NetworkObject)} that is not in the spawned objects list. Please make sure the {nameof(NetworkObject)} is spawned before calling RPCs.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidOperationException($"[{WrappedMessage.Metadata.NetworkObjectId}, {WrappedMessage.Metadata.NetworkBehaviourId}, {WrappedMessage.Metadata.NetworkRpcMethodId}]An RPC called on a {nameof(NetworkObject)} that is not in the spawned objects list. Please make sure the {nameof(NetworkObject)} is spawned before calling RPCs.");
|
||||
NetworkLog.LogWarning($"[{WrappedMessage.Metadata.NetworkObjectId}, {WrappedMessage.Metadata.NetworkBehaviourId}, {WrappedMessage.Metadata.NetworkRpcMethodId}] An RPC called on a {nameof(NetworkObject)} that is not in the spawned objects list. Please make sure the {nameof(NetworkObject)} is spawned before calling RPCs.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
var observers = networkObject.Observers;
|
||||
|
||||
@@ -60,7 +60,13 @@ namespace Unity.Netcode
|
||||
var networkManager = (NetworkManager)context.SystemOwner;
|
||||
if (!networkManager.SpawnManager.SpawnedObjects.TryGetValue(metadata.NetworkObjectId, out var networkObject))
|
||||
{
|
||||
throw new InvalidOperationException($"An RPC called on a {nameof(NetworkObject)} that is not in the spawned objects list. Please make sure the {nameof(NetworkObject)} is spawned before calling RPCs.");
|
||||
// If the NetworkObject no longer exists then just log a warning when developer mode logging is enabled and exit.
|
||||
// This can happen if NetworkObject is despawned and a client sends an RPC before receiving the despawn message.
|
||||
if (networkManager.LogLevel == LogLevel.Developer)
|
||||
{
|
||||
NetworkLog.LogWarning($"[{metadata.NetworkObjectId}, {metadata.NetworkBehaviourId}, {metadata.NetworkRpcMethodId}] An RPC called on a {nameof(NetworkObject)} that is not in the spawned objects list. Please make sure the {nameof(NetworkObject)} is spawned before calling RPCs.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
var networkBehaviour = networkObject.GetNetworkBehaviourAtOrderIndex(metadata.NetworkBehaviourId);
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ namespace Unity.Netcode
|
||||
|
||||
public void Handle(ref NetworkContext context)
|
||||
{
|
||||
((NetworkManager)context.SystemOwner).CustomMessagingManager.InvokeUnnamedMessage(context.SenderId, m_ReceivedData, context.SerializedHeaderSize);
|
||||
((NetworkManager)context.SystemOwner).CustomMessagingManager?.InvokeUnnamedMessage(context.SenderId, m_ReceivedData, context.SerializedHeaderSize);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,28 +141,6 @@ namespace Unity.Netcode
|
||||
{
|
||||
RegisterMessageType(type);
|
||||
}
|
||||
|
||||
#if UNITY_EDITOR
|
||||
if (EnableMessageOrderConsoleLog)
|
||||
{
|
||||
// DANGO-TODO: Remove this when we have some form of message type indices stability in place
|
||||
// For now, just log the messages and their assigned types for reference purposes.
|
||||
var networkManager = m_Owner as NetworkManager;
|
||||
if (networkManager != null)
|
||||
{
|
||||
if (networkManager.DistributedAuthorityMode)
|
||||
{
|
||||
var messageListing = new StringBuilder();
|
||||
messageListing.AppendLine("NGO Message Index to Type Listing:");
|
||||
foreach (var message in m_MessageTypes)
|
||||
{
|
||||
messageListing.AppendLine($"[{message.Value}][{message.Key.Name}]");
|
||||
}
|
||||
Debug.Log(messageListing);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
@@ -733,7 +711,11 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
ref var writeQueueItem = ref sendQueueItem.ElementAt(sendQueueItem.Length - 1);
|
||||
writeQueueItem.Writer.TryBeginWrite(tmpSerializer.Length + headerSerializer.Length);
|
||||
if (!writeQueueItem.Writer.TryBeginWrite(tmpSerializer.Length + headerSerializer.Length))
|
||||
{
|
||||
Debug.LogError($"Not enough space to write message, size={tmpSerializer.Length + headerSerializer.Length} space used={writeQueueItem.Writer.Position} total size={writeQueueItem.Writer.Capacity}");
|
||||
continue;
|
||||
}
|
||||
|
||||
writeQueueItem.Writer.WriteBytes(headerSerializer.GetUnsafePtr(), headerSerializer.Length);
|
||||
writeQueueItem.Writer.WriteBytes(tmpSerializer.GetUnsafePtr(), tmpSerializer.Length);
|
||||
|
||||
@@ -57,7 +57,7 @@ namespace Unity.Netcode
|
||||
/// <para>Marks a method as ServerRpc.</para>
|
||||
/// <para>A ServerRpc marked method will be fired by a client but executed on the server.</para>
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Method)]
|
||||
[AttributeUsage(AttributeTargets.Method), Obsolete]
|
||||
public class ServerRpcAttribute : RpcAttribute
|
||||
{
|
||||
public new bool RequireOwnership;
|
||||
@@ -72,7 +72,7 @@ namespace Unity.Netcode
|
||||
/// <para>Marks a method as ClientRpc.</para>
|
||||
/// <para>A ClientRpc marked method will be fired by the server but executed on clients.</para>
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Method)]
|
||||
[AttributeUsage(AttributeTargets.Method), Obsolete]
|
||||
public class ClientRpcAttribute : RpcAttribute
|
||||
{
|
||||
public ClientRpcAttribute() : base(SendTo.NotServer)
|
||||
|
||||
@@ -17,7 +17,8 @@ namespace Unity.Netcode
|
||||
// ClientsAndHost sends to everyone who runs any client logic
|
||||
// So if the server is a host, this target includes it (as hosts run client logic)
|
||||
// If the server is not a host, this target leaves it out, ergo the selection of NotServer.
|
||||
if (behaviour.NetworkManager.ServerIsHost)
|
||||
// If we are in distributed authority mode and connected to a service, then send to all clients.
|
||||
if (behaviour.NetworkManager.ServerIsHost || (m_NetworkManager.DistributedAuthorityMode && m_NetworkManager.CMBServiceConnection))
|
||||
{
|
||||
m_UnderlyingTarget = behaviour.RpcTarget.Everyone;
|
||||
}
|
||||
|
||||
@@ -29,6 +29,12 @@ namespace Unity.Netcode
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// The CMB-Service holds ID 0 and should not be added to the targets
|
||||
if (clientId == NetworkManager.ServerClientId && m_NetworkManager.CMBServiceConnection)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
m_GroupSendTarget.Add(clientId);
|
||||
}
|
||||
}
|
||||
@@ -41,6 +47,12 @@ namespace Unity.Netcode
|
||||
continue;
|
||||
}
|
||||
|
||||
// The CMB-Service holds ID 0 and should not be added to the targets
|
||||
if (clientId == NetworkManager.ServerClientId && m_NetworkManager.CMBServiceConnection)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (clientId == m_NetworkManager.LocalClientId)
|
||||
{
|
||||
m_LocalSendRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||
|
||||
@@ -4,12 +4,14 @@ namespace Unity.Netcode
|
||||
{
|
||||
private IGroupRpcTarget m_GroupSendTarget;
|
||||
private ServerRpcTarget m_ServerRpcTarget;
|
||||
private NotAuthorityRpcTarget m_NotAuthorityRpcTarget;
|
||||
private LocalSendRpcTarget m_LocalSendRpcTarget;
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
m_ServerRpcTarget.Dispose();
|
||||
m_LocalSendRpcTarget.Dispose();
|
||||
m_NotAuthorityRpcTarget.Dispose();
|
||||
if (m_GroupSendTarget != null)
|
||||
{
|
||||
m_GroupSendTarget.Target.Dispose();
|
||||
@@ -19,6 +21,13 @@ namespace Unity.Netcode
|
||||
|
||||
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
|
||||
{
|
||||
// Not owner is the same as not authority in distributed authority mode
|
||||
if (m_NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
m_NotAuthorityRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||
return;
|
||||
}
|
||||
|
||||
if (m_GroupSendTarget == null)
|
||||
{
|
||||
if (behaviour.IsServer)
|
||||
@@ -86,6 +95,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
m_ServerRpcTarget = new ServerRpcTarget(manager);
|
||||
m_LocalSendRpcTarget = new LocalSendRpcTarget(manager);
|
||||
m_NotAuthorityRpcTarget = new NotAuthorityRpcTarget(manager);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +51,13 @@ namespace Unity.Netcode
|
||||
continue;
|
||||
}
|
||||
|
||||
if (clientId == behaviour.NetworkManager.LocalClientId)
|
||||
// If we are in distributed authority mode and connected to the service, then we exclude the owner/authority from the list
|
||||
if (m_NetworkManager.DistributedAuthorityMode && m_NetworkManager.CMBServiceConnection && clientId == behaviour.OwnerClientId)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (clientId == m_NetworkManager.LocalClientId)
|
||||
{
|
||||
m_LocalSendRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||
continue;
|
||||
|
||||
@@ -5,9 +5,12 @@ namespace Unity.Netcode
|
||||
private IIndividualRpcTarget m_UnderlyingTarget;
|
||||
private LocalSendRpcTarget m_LocalRpcTarget;
|
||||
private ServerRpcTarget m_ServerRpcTarget;
|
||||
private AuthorityRpcTarget m_AuthorityRpcTarget;
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
m_AuthorityRpcTarget.Dispose();
|
||||
m_ServerRpcTarget.Dispose();
|
||||
m_LocalRpcTarget.Dispose();
|
||||
if (m_UnderlyingTarget != null)
|
||||
{
|
||||
@@ -18,6 +21,13 @@ namespace Unity.Netcode
|
||||
|
||||
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
|
||||
{
|
||||
// Sending to owner is the same as sending to authority in distributed authority mode
|
||||
if (m_NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
m_AuthorityRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||
return;
|
||||
}
|
||||
|
||||
if (behaviour.OwnerClientId == behaviour.NetworkManager.LocalClientId)
|
||||
{
|
||||
m_LocalRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||
@@ -49,6 +59,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
m_LocalRpcTarget = new LocalSendRpcTarget(manager);
|
||||
m_ServerRpcTarget = new ServerRpcTarget(manager);
|
||||
m_AuthorityRpcTarget = new AuthorityRpcTarget(manager);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,11 @@ namespace Unity.Netcode
|
||||
|
||||
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
|
||||
{
|
||||
// If there are no targets then don't attempt to send anything.
|
||||
if (TargetClientIds.Length == 0 && Ids.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var proxyMessage = new ProxyMessage { Delivery = delivery, TargetClientIds = TargetClientIds.AsArray(), WrappedMessage = message };
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||
var size =
|
||||
|
||||
@@ -79,9 +79,28 @@ namespace Unity.Netcode
|
||||
SpecifiedInParams
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This parameter configures a performance optimization. This optimization is not valid in all situations.<br />
|
||||
/// Because BaseRpcTarget is a managed type, allocating a new one is expensive, as it puts pressure on the garbage collector.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// When using a <see cref="Temp"/> allocation type for the RPC target(s):<br />
|
||||
/// You typically don't need to worry about persisting the <see cref="BaseRpcTarget"/> generated.
|
||||
/// When using a <see cref="Persistent"/> allocation type for the RPC target(s): <br />
|
||||
/// You will want to use <see cref="RpcTarget"/>, which returns <see cref="BaseRpcTarget"/>, during <see cref="NetworkBehaviour"/> initialization (i.e. <see cref="NetworkBehaviour.OnNetworkPostSpawn"/>) and it to a property.<br />
|
||||
/// Then, When invoking the RPC, you would use your <see cref="BaseRpcTarget"/> which is a persisted allocation of a given set of client identifiers.
|
||||
/// !! Important !!<br />
|
||||
/// You will want to invoke <see cref="BaseRpcTarget.Dispose"/> of any persisted properties created via <see cref="RpcTarget"/> when despawning or destroying the associated <see cref="NetworkBehaviour"/> component's <see cref="NetworkObject"/>. Not doing so will result in small memory leaks.
|
||||
/// </remarks>
|
||||
public enum RpcTargetUse
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a temporary <see cref="BaseRpcTarget"/> used for the frame an <see cref="RpcAttribute"/> decorated method is invoked.
|
||||
/// </summary>
|
||||
Temp,
|
||||
/// <summary>
|
||||
/// Creates a persisted <see cref="BaseRpcTarget"/> that does not change and will persist until <see cref="BaseRpcTarget.Dispose"/> is called.
|
||||
/// </summary>
|
||||
Persistent
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
using Unity.Collections;
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
internal class ServerRpcTarget : BaseRpcTarget
|
||||
{
|
||||
protected BaseRpcTarget m_UnderlyingTarget;
|
||||
protected ProxyRpcTarget m_ProxyRpcTarget;
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
@@ -11,13 +13,62 @@ namespace Unity.Netcode
|
||||
m_UnderlyingTarget.Dispose();
|
||||
m_UnderlyingTarget = null;
|
||||
}
|
||||
|
||||
if (m_ProxyRpcTarget != null)
|
||||
{
|
||||
m_ProxyRpcTarget.Dispose();
|
||||
m_ProxyRpcTarget = null;
|
||||
}
|
||||
}
|
||||
|
||||
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
|
||||
{
|
||||
// For distributed authority the "server" is considered the authority of the object
|
||||
if (behaviour.NetworkManager.DistributedAuthorityMode && behaviour.NetworkManager.CMBServiceConnection)
|
||||
{
|
||||
UnityEngine.Debug.LogWarning("[Invalid Target] There is no server to send to when in Distributed Authority mode!");
|
||||
// If the local instance is the owner, then invoke the message locally on this behaviour
|
||||
if (behaviour.IsOwner)
|
||||
{
|
||||
var context = new NetworkContext
|
||||
{
|
||||
SenderId = m_NetworkManager.LocalClientId,
|
||||
Timestamp = m_NetworkManager.RealTimeProvider.RealTimeSinceStartup,
|
||||
SystemOwner = m_NetworkManager,
|
||||
// header information isn't valid since it's not a real message.
|
||||
// RpcMessage doesn't access this stuff so it's just left empty.
|
||||
Header = new NetworkMessageHeader(),
|
||||
SerializedHeaderSize = 0,
|
||||
MessageSize = 0
|
||||
};
|
||||
using var tempBuffer = new FastBufferReader(message.WriteBuffer, Allocator.None);
|
||||
message.ReadBuffer = tempBuffer;
|
||||
message.Handle(ref context);
|
||||
// If enabled, then add the RPC metrics for this
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||
int length = tempBuffer.Length;
|
||||
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
|
||||
{
|
||||
m_NetworkManager.NetworkMetrics.TrackRpcSent(
|
||||
m_NetworkManager.LocalClientId,
|
||||
behaviour.NetworkObject,
|
||||
rpcMethodName,
|
||||
behaviour.__getTypeName(),
|
||||
length);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
else // Otherwise, send a proxied message to the owner of the object
|
||||
{
|
||||
if (m_ProxyRpcTarget == null)
|
||||
{
|
||||
m_ProxyRpcTarget = new ProxyRpcTarget(behaviour.OwnerClientId, m_NetworkManager);
|
||||
}
|
||||
else
|
||||
{
|
||||
m_ProxyRpcTarget.SetClientId(behaviour.OwnerClientId);
|
||||
}
|
||||
m_ProxyRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -51,7 +51,6 @@ namespace Unity.Netcode
|
||||
#pragma warning restore IDE0001
|
||||
[Serializable]
|
||||
[GenerateSerializationForGenericParameter(0)]
|
||||
[GenerateSerializationForType(typeof(byte))]
|
||||
public class AnticipatedNetworkVariable<T> : NetworkVariableBase
|
||||
{
|
||||
[SerializeField]
|
||||
|
||||
@@ -24,7 +24,6 @@ namespace Unity.Netcode
|
||||
/// The callback to be invoked when the list gets changed
|
||||
/// </summary>
|
||||
public event OnListChangedDelegate OnListChanged;
|
||||
internal override NetworkVariableType Type => NetworkVariableType.NetworkList;
|
||||
|
||||
/// <summary>
|
||||
/// Constructor method for <see cref="NetworkList"/>
|
||||
@@ -50,6 +49,11 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
~NetworkList()
|
||||
{
|
||||
Dispose();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void ResetDirty()
|
||||
{
|
||||
@@ -131,20 +135,6 @@ namespace Unity.Netcode
|
||||
/// <inheritdoc />
|
||||
public override void WriteField(FastBufferWriter writer)
|
||||
{
|
||||
if (m_NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
writer.WriteValueSafe(NetworkVariableSerialization<T>.Serializer.Type);
|
||||
if (NetworkVariableSerialization<T>.Serializer.Type == NetworkVariableType.Unmanaged)
|
||||
{
|
||||
// Write the size of the unmanaged serialized type as it has a fixed size. This allows the CMB runtime to correctly read the unmanged type.
|
||||
var placeholder = new T();
|
||||
var startPos = writer.Position;
|
||||
NetworkVariableSerialization<T>.Serializer.Write(writer, ref placeholder);
|
||||
var size = writer.Position - startPos;
|
||||
writer.Seek(startPos);
|
||||
BytePacker.WriteValueBitPacked(writer, size);
|
||||
}
|
||||
}
|
||||
writer.WriteValueSafe((ushort)m_List.Length);
|
||||
for (int i = 0; i < m_List.Length; i++)
|
||||
{
|
||||
@@ -156,15 +146,6 @@ namespace Unity.Netcode
|
||||
public override void ReadField(FastBufferReader reader)
|
||||
{
|
||||
m_List.Clear();
|
||||
if (m_NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
SerializationTools.ReadType(reader, NetworkVariableSerialization<T>.Serializer);
|
||||
// Collection item type is used by the DA server, drop value here.
|
||||
if (NetworkVariableSerialization<T>.Serializer.Type == NetworkVariableType.Unmanaged)
|
||||
{
|
||||
ByteUnpacker.ReadValueBitPacked(reader, out int _);
|
||||
}
|
||||
}
|
||||
reader.ReadValueSafe(out ushort count);
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
@@ -177,6 +158,13 @@ namespace Unity.Netcode
|
||||
/// <inheritdoc />
|
||||
public override void ReadDelta(FastBufferReader reader, bool keepDirtyDelta)
|
||||
{
|
||||
/// This is only invoked by <see cref="NetworkVariableDeltaMessage"/> and the only time
|
||||
/// keepDirtyDelta is set is when it is the server processing. To be able to handle previous
|
||||
/// versions, we use IsServer to keep the dirty states received and the keepDirtyDelta to
|
||||
/// actually mark this as dirty and add it to the list of <see cref="NetworkObject"/>s to
|
||||
/// be updated. With the forwarding of deltas being handled by <see cref="NetworkVariableDeltaMessage"/>,
|
||||
/// once all clients have been forwarded the dirty events, we clear them by invoking <see cref="PostDeltaRead"/>.
|
||||
var isServer = m_NetworkManager.IsServer;
|
||||
reader.ReadValueSafe(out ushort deltaCount);
|
||||
for (int i = 0; i < deltaCount; i++)
|
||||
{
|
||||
@@ -199,7 +187,7 @@ namespace Unity.Netcode
|
||||
});
|
||||
}
|
||||
|
||||
if (keepDirtyDelta)
|
||||
if (isServer)
|
||||
{
|
||||
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
||||
{
|
||||
@@ -207,7 +195,11 @@ namespace Unity.Netcode
|
||||
Index = m_List.Length - 1,
|
||||
Value = m_List[m_List.Length - 1]
|
||||
});
|
||||
MarkNetworkObjectDirty();
|
||||
// Preserve the legacy way of handling this
|
||||
if (keepDirtyDelta)
|
||||
{
|
||||
MarkNetworkObjectDirty();
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
@@ -237,7 +229,7 @@ namespace Unity.Netcode
|
||||
});
|
||||
}
|
||||
|
||||
if (keepDirtyDelta)
|
||||
if (isServer)
|
||||
{
|
||||
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
||||
{
|
||||
@@ -245,7 +237,11 @@ namespace Unity.Netcode
|
||||
Index = index,
|
||||
Value = m_List[index]
|
||||
});
|
||||
MarkNetworkObjectDirty();
|
||||
// Preserve the legacy way of handling this
|
||||
if (keepDirtyDelta)
|
||||
{
|
||||
MarkNetworkObjectDirty();
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
@@ -271,7 +267,7 @@ namespace Unity.Netcode
|
||||
});
|
||||
}
|
||||
|
||||
if (keepDirtyDelta)
|
||||
if (isServer)
|
||||
{
|
||||
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
||||
{
|
||||
@@ -279,7 +275,11 @@ namespace Unity.Netcode
|
||||
Index = index,
|
||||
Value = value
|
||||
});
|
||||
MarkNetworkObjectDirty();
|
||||
// Preserve the legacy way of handling this
|
||||
if (keepDirtyDelta)
|
||||
{
|
||||
MarkNetworkObjectDirty();
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
@@ -299,7 +299,7 @@ namespace Unity.Netcode
|
||||
});
|
||||
}
|
||||
|
||||
if (keepDirtyDelta)
|
||||
if (isServer)
|
||||
{
|
||||
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
||||
{
|
||||
@@ -307,7 +307,11 @@ namespace Unity.Netcode
|
||||
Index = index,
|
||||
Value = value
|
||||
});
|
||||
MarkNetworkObjectDirty();
|
||||
// Preserve the legacy way of handling this
|
||||
if (keepDirtyDelta)
|
||||
{
|
||||
MarkNetworkObjectDirty();
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
@@ -335,7 +339,7 @@ namespace Unity.Netcode
|
||||
});
|
||||
}
|
||||
|
||||
if (keepDirtyDelta)
|
||||
if (isServer)
|
||||
{
|
||||
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
||||
{
|
||||
@@ -344,7 +348,11 @@ namespace Unity.Netcode
|
||||
Value = value,
|
||||
PreviousValue = previousValue
|
||||
});
|
||||
MarkNetworkObjectDirty();
|
||||
// Preserve the legacy way of handling this
|
||||
if (keepDirtyDelta)
|
||||
{
|
||||
MarkNetworkObjectDirty();
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
@@ -361,13 +369,18 @@ namespace Unity.Netcode
|
||||
});
|
||||
}
|
||||
|
||||
if (keepDirtyDelta)
|
||||
if (isServer)
|
||||
{
|
||||
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
||||
{
|
||||
Type = eventType
|
||||
});
|
||||
MarkNetworkObjectDirty();
|
||||
|
||||
// Preserve the legacy way of handling this
|
||||
if (keepDirtyDelta)
|
||||
{
|
||||
MarkNetworkObjectDirty();
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
@@ -381,6 +394,18 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <remarks>
|
||||
/// For NetworkList, we just need to reset dirty if a server has read deltas
|
||||
/// </remarks>
|
||||
internal override void PostDeltaRead()
|
||||
{
|
||||
if (m_NetworkManager.IsServer)
|
||||
{
|
||||
ResetDirty();
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IEnumerator<T> GetEnumerator()
|
||||
{
|
||||
@@ -393,7 +418,8 @@ namespace Unity.Netcode
|
||||
// check write permissions
|
||||
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
||||
{
|
||||
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
|
||||
LogWritePermissionError();
|
||||
return;
|
||||
}
|
||||
|
||||
m_List.Add(item);
|
||||
@@ -414,7 +440,8 @@ namespace Unity.Netcode
|
||||
// check write permissions
|
||||
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
||||
{
|
||||
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
|
||||
LogWritePermissionError();
|
||||
return;
|
||||
}
|
||||
|
||||
m_List.Clear();
|
||||
@@ -440,7 +467,8 @@ namespace Unity.Netcode
|
||||
// check write permissions
|
||||
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
||||
{
|
||||
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
|
||||
LogWritePermissionError();
|
||||
return false;
|
||||
}
|
||||
|
||||
int index = m_List.IndexOf(item);
|
||||
@@ -475,7 +503,8 @@ namespace Unity.Netcode
|
||||
// check write permissions
|
||||
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
||||
{
|
||||
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
|
||||
LogWritePermissionError();
|
||||
return;
|
||||
}
|
||||
|
||||
if (index < m_List.Length)
|
||||
@@ -520,6 +549,8 @@ namespace Unity.Netcode
|
||||
HandleAddListEvent(listEvent);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <inheritdoc />
|
||||
public T this[int index]
|
||||
{
|
||||
@@ -529,7 +560,8 @@ namespace Unity.Netcode
|
||||
// check write permissions
|
||||
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
||||
{
|
||||
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
|
||||
LogWritePermissionError();
|
||||
return;
|
||||
}
|
||||
|
||||
var previousValue = m_List[index];
|
||||
@@ -573,8 +605,16 @@ namespace Unity.Netcode
|
||||
/// </summary>
|
||||
public override void Dispose()
|
||||
{
|
||||
m_List.Dispose();
|
||||
m_DirtyEvents.Dispose();
|
||||
if (m_List.IsCreated)
|
||||
{
|
||||
m_List.Dispose();
|
||||
}
|
||||
|
||||
if (m_DirtyEvents.IsCreated)
|
||||
{
|
||||
m_DirtyEvents.Dispose();
|
||||
}
|
||||
|
||||
base.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ namespace Unity.Netcode
|
||||
/// <typeparam name="T">the unmanaged type for <see cref="NetworkVariable{T}"/> </typeparam>
|
||||
[Serializable]
|
||||
[GenerateSerializationForGenericParameter(0)]
|
||||
[GenerateSerializationForType(typeof(byte))]
|
||||
public class NetworkVariable<T> : NetworkVariableBase
|
||||
{
|
||||
/// <summary>
|
||||
@@ -42,11 +41,10 @@ namespace Unity.Netcode
|
||||
base.OnInitialize();
|
||||
|
||||
m_HasPreviousValue = true;
|
||||
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_InternalOriginalValue);
|
||||
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_PreviousValue);
|
||||
}
|
||||
|
||||
internal override NetworkVariableType Type => NetworkVariableType.Value;
|
||||
|
||||
/// <summary>
|
||||
/// Constructor for <see cref="NetworkVariable{T}"/>
|
||||
/// </summary>
|
||||
@@ -59,6 +57,7 @@ namespace Unity.Netcode
|
||||
: base(readPerm, writePerm)
|
||||
{
|
||||
m_InternalValue = value;
|
||||
m_InternalOriginalValue = default;
|
||||
// Since we start with IsDirty = true, this doesn't need to be duplicated
|
||||
// right away. It won't get read until after ResetDirty() is called, and
|
||||
// the duplicate will be made there. Avoiding calling
|
||||
@@ -77,6 +76,7 @@ namespace Unity.Netcode
|
||||
if (m_NetworkBehaviour == null || m_NetworkBehaviour != null && !m_NetworkBehaviour.NetworkObject.IsSpawned)
|
||||
{
|
||||
m_InternalValue = value;
|
||||
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_InternalOriginalValue);
|
||||
m_PreviousValue = default;
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,12 @@ namespace Unity.Netcode
|
||||
[SerializeField]
|
||||
private protected T m_InternalValue;
|
||||
|
||||
// The introduction of standard .NET collections caused an issue with permissions since there is no way to detect changes in the
|
||||
// collection without doing a full comparison. While this approach does consume more memory per collection instance, it is the
|
||||
// lowest risk approach to resolving the issue where a client with no write permissions could make changes to a collection locally
|
||||
// which can cause a myriad of issues.
|
||||
private protected T m_InternalOriginalValue;
|
||||
|
||||
private protected T m_PreviousValue;
|
||||
|
||||
private bool m_HasPreviousValue;
|
||||
@@ -95,27 +101,71 @@ namespace Unity.Netcode
|
||||
/// <summary>
|
||||
/// The value of the NetworkVariable container
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// When assigning collections to <see cref="Value"/>, unless it is a completely new collection this will not
|
||||
/// detect any deltas with most managed collection classes since assignment of one collection value to another
|
||||
/// is actually just a reference to the collection itself. <br />
|
||||
/// To detect deltas in a collection, you should invoke <see cref="CheckDirtyState"/> after making modifications to the collection.
|
||||
/// </remarks>
|
||||
public virtual T Value
|
||||
{
|
||||
get => m_InternalValue;
|
||||
set
|
||||
{
|
||||
// Compare bitwise
|
||||
if (NetworkVariableSerialization<T>.AreEqual(ref m_InternalValue, ref value))
|
||||
if (m_NetworkManager && !CanClientWrite(m_NetworkManager.LocalClientId))
|
||||
{
|
||||
LogWritePermissionError();
|
||||
return;
|
||||
}
|
||||
|
||||
if (m_NetworkManager && !CanClientWrite(m_NetworkManager.LocalClientId))
|
||||
// Compare the Value being applied to the current value
|
||||
if (!NetworkVariableSerialization<T>.AreEqual(ref m_InternalValue, ref value))
|
||||
{
|
||||
throw new InvalidOperationException($"[Client-{m_NetworkManager.LocalClientId}][{m_NetworkBehaviour.name}][{Name}] Write permissions ({WritePerm}) for this client instance is not allowed!");
|
||||
T previousValue = m_InternalValue;
|
||||
m_InternalValue = value;
|
||||
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_InternalOriginalValue);
|
||||
SetDirty(true);
|
||||
m_IsDisposed = false;
|
||||
OnValueChanged?.Invoke(previousValue, m_InternalValue);
|
||||
}
|
||||
|
||||
Set(value);
|
||||
m_IsDisposed = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invoke this method to check if a collection's items are dirty.
|
||||
/// The default behavior is to exit early if the <see cref="NetworkVariable{T}"/> is already dirty.
|
||||
/// </summary>
|
||||
/// <param name="forceCheck"> when true, this check will force a full item collection check even if the NetworkVariable is already dirty</param>
|
||||
/// <remarks>
|
||||
/// This is to be used as a way to check if a <see cref="NetworkVariable{T}"/> containing a managed collection has any changees to the collection items.<br />
|
||||
/// If you invoked this when a collection is dirty, it will not trigger the <see cref="OnValueChanged"/> unless you set <param name="forceCheck"/> to true. <br />
|
||||
/// </remarks>
|
||||
public bool CheckDirtyState(bool forceCheck = false)
|
||||
{
|
||||
var isDirty = base.IsDirty();
|
||||
|
||||
// A client without permissions invoking this method should only check to assure the current value is equal to the last known current value
|
||||
if (m_NetworkManager && !CanClientWrite(m_NetworkManager.LocalClientId))
|
||||
{
|
||||
// If modifications are detected, then revert back to the last known current value
|
||||
if (!NetworkVariableSerialization<T>.AreEqual(ref m_InternalValue, ref m_InternalOriginalValue))
|
||||
{
|
||||
NetworkVariableSerialization<T>.Duplicate(m_InternalOriginalValue, ref m_InternalValue);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Compare the previous with the current if not dirty or forcing a check.
|
||||
if ((!isDirty || forceCheck) && !NetworkVariableSerialization<T>.AreEqual(ref m_PreviousValue, ref m_InternalValue))
|
||||
{
|
||||
SetDirty(true);
|
||||
OnValueChanged?.Invoke(m_PreviousValue, m_InternalValue);
|
||||
m_IsDisposed = false;
|
||||
isDirty = true;
|
||||
}
|
||||
return isDirty;
|
||||
}
|
||||
|
||||
internal ref T RefValue()
|
||||
{
|
||||
return ref m_InternalValue;
|
||||
@@ -129,18 +179,26 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
m_IsDisposed = true;
|
||||
// Dispose the internal value
|
||||
if (m_InternalValue is IDisposable internalValueDisposable)
|
||||
{
|
||||
internalValueDisposable.Dispose();
|
||||
}
|
||||
|
||||
m_InternalValue = default;
|
||||
|
||||
// Dispose the internal original value
|
||||
if (m_InternalOriginalValue is IDisposable internalOriginalValueDisposable)
|
||||
{
|
||||
internalOriginalValueDisposable.Dispose();
|
||||
}
|
||||
m_InternalOriginalValue = default;
|
||||
|
||||
// Dispose the previous value if there is one
|
||||
if (m_HasPreviousValue && m_PreviousValue is IDisposable previousValueDisposable)
|
||||
{
|
||||
m_HasPreviousValue = false;
|
||||
previousValueDisposable.Dispose();
|
||||
}
|
||||
|
||||
m_PreviousValue = default;
|
||||
|
||||
base.Dispose();
|
||||
@@ -157,6 +215,13 @@ namespace Unity.Netcode
|
||||
/// <returns>Whether or not the container is dirty</returns>
|
||||
public override bool IsDirty()
|
||||
{
|
||||
// If the client does not have write permissions but the internal value is determined to be locally modified and we are applying updates, then we should revert
|
||||
// to the original collection value prior to applying updates (primarily for collections).
|
||||
if (!NetworkUpdaterCheck && m_NetworkManager && !CanClientWrite(m_NetworkManager.LocalClientId) && !NetworkVariableSerialization<T>.AreEqual(ref m_InternalValue, ref m_InternalOriginalValue))
|
||||
{
|
||||
NetworkVariableSerialization<T>.Duplicate(m_InternalOriginalValue, ref m_InternalValue);
|
||||
return true;
|
||||
}
|
||||
// For most cases we can use the dirty flag.
|
||||
// This doesn't work for cases where we're wrapping more complex types
|
||||
// like INetworkSerializable, NativeList, NativeArray, etc.
|
||||
@@ -168,11 +233,11 @@ namespace Unity.Netcode
|
||||
return true;
|
||||
}
|
||||
|
||||
var dirty = !NetworkVariableSerialization<T>.AreEqual(ref m_PreviousValue, ref m_InternalValue);
|
||||
// Cache the dirty value so we don't perform this again if we already know we're dirty
|
||||
// Unfortunately we can't cache the NOT dirty state, because that might change
|
||||
// in between to checks... but the DIRTY state won't change until ResetDirty()
|
||||
// is called.
|
||||
var dirty = !NetworkVariableSerialization<T>.AreEqual(ref m_PreviousValue, ref m_InternalValue);
|
||||
SetDirty(dirty);
|
||||
return dirty;
|
||||
}
|
||||
@@ -190,23 +255,12 @@ namespace Unity.Netcode
|
||||
{
|
||||
m_HasPreviousValue = true;
|
||||
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_PreviousValue);
|
||||
// Once updated, assure the original current value is updated for future comparison purposes
|
||||
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_InternalOriginalValue);
|
||||
}
|
||||
base.ResetDirty();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the <see cref="Value"/>, marks the <see cref="NetworkVariable{T}"/> dirty, and invokes the <see cref="OnValueChanged"/> callback
|
||||
/// if there are subscribers to that event.
|
||||
/// </summary>
|
||||
/// <param name="value">the new value of type `T` to be set/></param>
|
||||
private protected void Set(T value)
|
||||
{
|
||||
SetDirty(true);
|
||||
T previousValue = m_InternalValue;
|
||||
m_InternalValue = value;
|
||||
OnValueChanged?.Invoke(previousValue, m_InternalValue);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the variable to the writer
|
||||
/// </summary>
|
||||
@@ -223,26 +277,65 @@ 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:
|
||||
// If the client does not have write permissions but the internal value is determined to be locally modified and we are applying updates, then we should revert
|
||||
// to the original collection value prior to applying updates (primarily for collections).
|
||||
if (m_NetworkManager && !CanClientWrite(m_NetworkManager.LocalClientId) && !NetworkVariableSerialization<T>.AreEqual(ref m_InternalOriginalValue, ref m_InternalValue))
|
||||
{
|
||||
NetworkVariableSerialization<T>.Duplicate(m_InternalOriginalValue, ref m_InternalValue);
|
||||
}
|
||||
|
||||
NetworkVariableSerialization<T>.ReadDelta(reader, ref m_InternalValue);
|
||||
|
||||
// keepDirtyDelta marks a variable received as dirty and causes the server to send the value to clients
|
||||
// In a prefect world, whether a variable was A) modified locally or B) received and needs retransmit
|
||||
// would be stored in different fields
|
||||
|
||||
T previousValue = m_InternalValue;
|
||||
NetworkVariableSerialization<T>.ReadDelta(reader, ref m_InternalValue);
|
||||
|
||||
// LEGACY NOTE: This is only to handle NetworkVariableDeltaMessage Version 0 connections. The updated
|
||||
// NetworkVariableDeltaMessage no longer uses this approach.
|
||||
if (keepDirtyDelta)
|
||||
{
|
||||
SetDirty(true);
|
||||
}
|
||||
|
||||
OnValueChanged?.Invoke(previousValue, m_InternalValue);
|
||||
OnValueChanged?.Invoke(m_PreviousValue, m_InternalValue);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This should be always invoked (client & server) to assure the previous values are set
|
||||
/// !! IMPORTANT !!
|
||||
/// When a server forwards delta updates to connected clients, it needs to preserve the previous dirty value(s)
|
||||
/// until it is done serializing all valid NetworkVariable field deltas (relative to each client). This is invoked
|
||||
/// after it is done forwarding the deltas at the end of the <see cref="NetworkVariableDeltaMessage.Handle(ref NetworkContext)"/> method.
|
||||
/// </summary>
|
||||
internal override void PostDeltaRead()
|
||||
{
|
||||
// In order to get managed collections to properly have a previous and current value, we have to
|
||||
// duplicate the collection at this point before making any modifications to the current.
|
||||
m_HasPreviousValue = true;
|
||||
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_PreviousValue);
|
||||
// Once updated, assure the original current value is updated for future comparison purposes
|
||||
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_InternalOriginalValue);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void ReadField(FastBufferReader reader)
|
||||
{
|
||||
// If the client does not have write permissions but the internal value is determined to be locally modified and we are applying updates, then we should revert
|
||||
// to the original collection value prior to applying updates (primarily for collections).
|
||||
if (m_NetworkManager && !CanClientWrite(m_NetworkManager.LocalClientId) && !NetworkVariableSerialization<T>.AreEqual(ref m_InternalOriginalValue, ref m_InternalValue))
|
||||
{
|
||||
NetworkVariableSerialization<T>.Duplicate(m_InternalOriginalValue, ref m_InternalValue);
|
||||
}
|
||||
|
||||
NetworkVariableSerialization<T>.Read(reader, ref m_InternalValue);
|
||||
// In order to get managed collections to properly have a previous and current value, we have to
|
||||
// duplicate the collection at this point before making any modifications to the current.
|
||||
// We duplicate the final value after the read (for ReadField ONLY) so the previous value is at par
|
||||
// with the current value (since this is only invoked when initially synchronizing).
|
||||
m_HasPreviousValue = true;
|
||||
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_PreviousValue);
|
||||
|
||||
// Once updated, assure the original current value is updated for future comparison purposes
|
||||
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_InternalOriginalValue);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -250,5 +343,20 @@ namespace Unity.Netcode
|
||||
{
|
||||
NetworkVariableSerialization<T>.Write(writer, ref m_InternalValue);
|
||||
}
|
||||
|
||||
internal override void WriteFieldSynchronization(FastBufferWriter writer)
|
||||
{
|
||||
// If we have a pending update, then synchronize the client with the previously known
|
||||
// value since the updated version will be sent on the next tick or next time it is
|
||||
// set to be updated
|
||||
if (base.IsDirty() && m_HasPreviousValue)
|
||||
{
|
||||
NetworkVariableSerialization<T>.Write(writer, ref m_PreviousValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
base.WriteFieldSynchronization(writer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,7 +35,15 @@ namespace Unity.Netcode
|
||||
|
||||
private NetworkManager m_InternalNetworkManager;
|
||||
|
||||
internal virtual NetworkVariableType Type => NetworkVariableType.Unknown;
|
||||
internal string GetWritePermissionError()
|
||||
{
|
||||
return $"|Client-{m_NetworkManager.LocalClientId}|{m_NetworkBehaviour.name}|{Name}| Write permissions ({WritePerm}) for this client instance is not allowed!";
|
||||
}
|
||||
|
||||
internal void LogWritePermissionError()
|
||||
{
|
||||
Debug.LogError(GetWritePermissionError());
|
||||
}
|
||||
|
||||
private protected NetworkManager m_NetworkManager
|
||||
{
|
||||
@@ -177,7 +185,9 @@ namespace Unity.Netcode
|
||||
|
||||
internal bool CanSend()
|
||||
{
|
||||
var timeSinceLastUpdate = m_NetworkBehaviour.NetworkManager.NetworkTimeSystem.LocalTime - LastUpdateSent;
|
||||
// When connected to a service or not the server, always use the synchronized server time as opposed to the local time
|
||||
var time = m_InternalNetworkManager.CMBServiceConnection || !m_InternalNetworkManager.IsServer ? m_NetworkBehaviour.NetworkManager.ServerTime.Time : m_NetworkBehaviour.NetworkManager.NetworkTimeSystem.LocalTime;
|
||||
var timeSinceLastUpdate = time - LastUpdateSent;
|
||||
return
|
||||
(
|
||||
UpdateTraits.MaxSecondsBetweenUpdates > 0 &&
|
||||
@@ -191,7 +201,8 @@ namespace Unity.Netcode
|
||||
|
||||
internal void UpdateLastSentTime()
|
||||
{
|
||||
LastUpdateSent = m_NetworkBehaviour.NetworkManager.NetworkTimeSystem.LocalTime;
|
||||
// When connected to a service or not the server, always use the synchronized server time as opposed to the local time
|
||||
LastUpdateSent = m_InternalNetworkManager.CMBServiceConnection || !m_InternalNetworkManager.IsServer ? m_NetworkBehaviour.NetworkManager.ServerTime.Time : m_NetworkBehaviour.NetworkManager.NetworkTimeSystem.LocalTime;
|
||||
}
|
||||
|
||||
internal static bool IgnoreInitializeWarning;
|
||||
@@ -238,6 +249,12 @@ namespace Unity.Netcode
|
||||
m_IsDirty = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Only used during the NetworkBehaviourUpdater pass and only used for NetworkVariable.
|
||||
/// This is to bypass duplication of the "original internal value" for collections.
|
||||
/// </summary>
|
||||
internal bool NetworkUpdaterCheck;
|
||||
|
||||
/// <summary>
|
||||
/// Gets Whether or not the container is dirty
|
||||
/// </summary>
|
||||
@@ -254,6 +271,11 @@ namespace Unity.Netcode
|
||||
/// <returns>Whether or not the client has permission to read</returns>
|
||||
public bool CanClientRead(ulong clientId)
|
||||
{
|
||||
if (!m_NetworkBehaviour)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// When in distributed authority mode, everyone can read (but only the owner can write)
|
||||
if (m_NetworkManager != null && m_NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
@@ -276,6 +298,11 @@ namespace Unity.Netcode
|
||||
/// <returns>Whether or not the client has permission to write</returns>
|
||||
public bool CanClientWrite(ulong clientId)
|
||||
{
|
||||
if (!m_NetworkBehaviour)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (WritePerm)
|
||||
{
|
||||
default:
|
||||
@@ -318,6 +345,32 @@ namespace Unity.Netcode
|
||||
/// <param name="keepDirtyDelta">Whether or not the delta should be kept as dirty or consumed</param>
|
||||
public abstract void ReadDelta(FastBufferReader reader, bool keepDirtyDelta);
|
||||
|
||||
/// <summary>
|
||||
/// This should be always invoked (client & server) to assure the previous values are set
|
||||
/// !! IMPORTANT !!
|
||||
/// When a server forwards delta updates to connected clients, it needs to preserve the previous dirty value(s)
|
||||
/// until it is done serializing all valid NetworkVariable field deltas (relative to each client). This is invoked
|
||||
/// after it is done forwarding the deltas at the end of the <see cref="NetworkVariableDeltaMessage.Handle(ref NetworkContext)"/> method.
|
||||
/// </summary>
|
||||
internal virtual void PostDeltaRead()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// There are scenarios, specifically with collections, where a client could be synchronizing and
|
||||
/// some NetworkVariables have pending updates. To avoid duplicating entries, this is invoked only
|
||||
/// when sending the full synchronization information.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Derrived classes should send the previous value for synchronization so when the updated value
|
||||
/// is sent (after synchronizing the client) it will apply the updates.
|
||||
/// </remarks>
|
||||
/// <param name="writer"></param>
|
||||
internal virtual void WriteFieldSynchronization(FastBufferWriter writer)
|
||||
{
|
||||
WriteField(writer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Virtual <see cref="IDisposable"/> implementation
|
||||
/// </summary>
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
#if UNITY_EDITOR
|
||||
#endif
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
/// <summary>
|
||||
/// Enum representing the different types of Network Variables that can be sent over the network.
|
||||
/// The values cannot be changed, as they are used to serialize and deserialize variables on the DA server.
|
||||
/// Adding new variables should be done by adding new values to the end of the enum
|
||||
/// using the next free value.
|
||||
/// </summary>
|
||||
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
||||
/// Add any new Variable types to this table at the END with incremented index value
|
||||
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
||||
internal enum NetworkVariableType : byte
|
||||
{
|
||||
/// <summary>
|
||||
/// Value
|
||||
/// Used for all of the basic NetworkVariables that contain a single value
|
||||
/// </summary>
|
||||
Value = 0,
|
||||
/// <summary>
|
||||
/// For any type that is not known at runtime
|
||||
/// </summary>
|
||||
Unknown = 1,
|
||||
/// <summary>
|
||||
/// NetworkList
|
||||
/// </summary>
|
||||
NetworkList = 2,
|
||||
|
||||
// The following types are valid types inside of NetworkVariable collections
|
||||
Short = 11,
|
||||
UShort = 12,
|
||||
Int = 13,
|
||||
UInt = 14,
|
||||
Long = 15,
|
||||
ULong = 16,
|
||||
Unmanaged = 17,
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: df4a4005f1c842669f94a404019400ed
|
||||
timeCreated: 1718292058
|
||||
@@ -14,9 +14,6 @@ namespace Unity.Netcode
|
||||
/// <typeparam name="T"></typeparam>
|
||||
internal class FallbackSerializer<T> : INetworkVariableSerializer<T>
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.Unknown;
|
||||
public bool IsDistributedAuthorityOptimized => true;
|
||||
|
||||
private void ThrowArgumentError()
|
||||
{
|
||||
throw new ArgumentException($"Serialization has not been generated for type {typeof(T).FullName}. This can be addressed by adding a [{nameof(GenerateSerializationForGenericParameterAttribute)}] to your generic class that serializes this value (if you are using one), adding [{nameof(GenerateSerializationForTypeAttribute)}(typeof({typeof(T).FullName})] to the class or method that is attempting to serialize it, or creating a field on a {nameof(NetworkBehaviour)} of type {nameof(NetworkVariable<T>)}. If this error continues to appear after doing one of those things and this is a type you can change, then either implement {nameof(INetworkSerializable)} or mark it as serializable by memcpy by adding {nameof(INetworkSerializeByMemcpy)} to its interface list to enable automatic serialization generation. If not, assign serialization code to {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.WriteValue)}, {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.ReadValue)}, and {nameof(UserNetworkVariableSerialization<T>)}.{nameof(UserNetworkVariableSerialization<T>.DuplicateValue)}, or if it's serializable by memcpy (contains no pointers), wrap it in {typeof(ForceNetworkSerializeByMemcpy<>).Name}.");
|
||||
@@ -82,11 +79,6 @@ namespace Unity.Netcode
|
||||
}
|
||||
UserNetworkVariableSerialization<T>.DuplicateValue(value, ref duplicatedValue);
|
||||
}
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value) => ThrowArgumentError();
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref T value) => ThrowArgumentError();
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => ThrowArgumentError();
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => ThrowArgumentError();
|
||||
}
|
||||
|
||||
// RuntimeAccessModifiersILPP will make this `public`
|
||||
|
||||
@@ -2,28 +2,8 @@ using Unity.Collections;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
/// <summary>
|
||||
/// Interface used by NetworkVariables to serialize them with additional information for the DA runtime
|
||||
/// </summary>
|
||||
///
|
||||
/// <typeparam name="T"></typeparam>
|
||||
internal interface IDistributedAuthoritySerializer<T>
|
||||
{
|
||||
/// <summary>
|
||||
/// The Type tells the DA server how to parse this type.
|
||||
/// The user should never be able to override this value, as it is meaningful for the DA server
|
||||
/// </summary>
|
||||
public NetworkVariableType Type { get; }
|
||||
public bool IsDistributedAuthorityOptimized { get; }
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value);
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref T value);
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value);
|
||||
}
|
||||
|
||||
|
||||
/// <typeparam name="T"></typeparam>
|
||||
internal interface INetworkVariableSerializer<T> : IDistributedAuthoritySerializer<T>
|
||||
internal interface INetworkVariableSerializer<T>
|
||||
{
|
||||
// Write has to be taken by ref here because of INetworkSerializable
|
||||
// Open Instance Delegates (pointers to methods without an instance attached to them)
|
||||
|
||||
@@ -14,8 +14,6 @@ namespace Unity.Netcode
|
||||
{
|
||||
internal static INetworkVariableSerializer<T> Serializer = new FallbackSerializer<T>();
|
||||
|
||||
internal static bool IsDistributedAuthority => NetworkManager.IsDistributedAuthority;
|
||||
|
||||
/// <summary>
|
||||
/// A callback to check if two values are equal.
|
||||
/// </summary>
|
||||
@@ -53,20 +51,7 @@ namespace Unity.Netcode
|
||||
/// <param name="value"></param>
|
||||
public static void Write(FastBufferWriter writer, ref T value)
|
||||
{
|
||||
if (IsDistributedAuthority)
|
||||
{
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
if (!NetworkManager.DisableNotOptimizedSerializedType && !Serializer.IsDistributedAuthorityOptimized)
|
||||
{
|
||||
NetworkManager.LogSerializedTypeNotOptimized<T>();
|
||||
}
|
||||
#endif
|
||||
Serializer.WriteDistributedAuthority(writer, ref value);
|
||||
}
|
||||
else
|
||||
{
|
||||
Serializer.Write(writer, ref value);
|
||||
}
|
||||
Serializer.Write(writer, ref value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -91,14 +76,7 @@ namespace Unity.Netcode
|
||||
/// <param name="value"></param>
|
||||
public static void Read(FastBufferReader reader, ref T value)
|
||||
{
|
||||
if (IsDistributedAuthority)
|
||||
{
|
||||
Serializer.ReadDistributedAuthority(reader, ref value);
|
||||
}
|
||||
else
|
||||
{
|
||||
Serializer.Read(reader, ref value);
|
||||
}
|
||||
Serializer.Read(reader, ref value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -120,20 +98,7 @@ namespace Unity.Netcode
|
||||
/// <param name="value"></param>
|
||||
public static void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue)
|
||||
{
|
||||
if (IsDistributedAuthority)
|
||||
{
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
if (!NetworkManager.DisableNotOptimizedSerializedType && !Serializer.IsDistributedAuthorityOptimized)
|
||||
{
|
||||
NetworkManager.LogSerializedTypeNotOptimized<T>();
|
||||
}
|
||||
#endif
|
||||
Serializer.WriteDeltaDistributedAuthority(writer, ref value, ref previousValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
Serializer.WriteDelta(writer, ref value, ref previousValue);
|
||||
}
|
||||
Serializer.WriteDelta(writer, ref value, ref previousValue);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -158,14 +123,7 @@ namespace Unity.Netcode
|
||||
/// <param name="value"></param>
|
||||
public static void ReadDelta(FastBufferReader reader, ref T value)
|
||||
{
|
||||
if (IsDistributedAuthority)
|
||||
{
|
||||
Serializer.ReadDeltaDistributedAuthority(reader, ref value);
|
||||
}
|
||||
else
|
||||
{
|
||||
Serializer.ReadDelta(reader, ref value);
|
||||
}
|
||||
Serializer.ReadDelta(reader, ref value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -10,21 +10,6 @@ namespace Unity.Netcode
|
||||
/// </summary>
|
||||
internal class ShortSerializer : INetworkVariableSerializer<short>
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.Short;
|
||||
public bool IsDistributedAuthorityOptimized => true;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref short value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref short value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref short value, ref short previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref short value) => Read(reader, ref value);
|
||||
|
||||
public void Write(FastBufferWriter writer, ref short value)
|
||||
{
|
||||
BytePacker.WriteValueBitPacked(writer, value);
|
||||
@@ -61,20 +46,6 @@ namespace Unity.Netcode
|
||||
/// </summary>
|
||||
internal class UshortSerializer : INetworkVariableSerializer<ushort>
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.UShort;
|
||||
public bool IsDistributedAuthorityOptimized => true;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref ushort value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref ushort value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref ushort value, ref ushort previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref ushort value) => Read(reader, ref value);
|
||||
public void Write(FastBufferWriter writer, ref ushort value)
|
||||
{
|
||||
BytePacker.WriteValueBitPacked(writer, value);
|
||||
@@ -111,20 +82,6 @@ namespace Unity.Netcode
|
||||
/// </summary>
|
||||
internal class IntSerializer : INetworkVariableSerializer<int>
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.Int;
|
||||
public bool IsDistributedAuthorityOptimized => true;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref int value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref int value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref int value, ref int previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref int value) => Read(reader, ref value);
|
||||
public void Write(FastBufferWriter writer, ref int value)
|
||||
{
|
||||
BytePacker.WriteValueBitPacked(writer, value);
|
||||
@@ -161,20 +118,6 @@ namespace Unity.Netcode
|
||||
/// </summary>
|
||||
internal class UintSerializer : INetworkVariableSerializer<uint>
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.UInt;
|
||||
public bool IsDistributedAuthorityOptimized => true;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref uint value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref uint value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref uint value, ref uint previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref uint value) => Read(reader, ref value);
|
||||
public void Write(FastBufferWriter writer, ref uint value)
|
||||
{
|
||||
BytePacker.WriteValueBitPacked(writer, value);
|
||||
@@ -211,20 +154,6 @@ namespace Unity.Netcode
|
||||
/// </summary>
|
||||
internal class LongSerializer : INetworkVariableSerializer<long>
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.Long;
|
||||
public bool IsDistributedAuthorityOptimized => true;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref long value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref long value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref long value, ref long previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref long value) => Read(reader, ref value);
|
||||
public void Write(FastBufferWriter writer, ref long value)
|
||||
{
|
||||
BytePacker.WriteValueBitPacked(writer, value);
|
||||
@@ -261,21 +190,6 @@ namespace Unity.Netcode
|
||||
/// </summary>
|
||||
internal class UlongSerializer : INetworkVariableSerializer<ulong>
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.ULong;
|
||||
public bool IsDistributedAuthorityOptimized => true;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref ulong value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref ulong value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref ulong value, ref ulong previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref ulong value) => Read(reader, ref value);
|
||||
|
||||
public void Write(FastBufferWriter writer, ref ulong value)
|
||||
{
|
||||
BytePacker.WriteValueBitPacked(writer, value);
|
||||
@@ -317,21 +231,6 @@ namespace Unity.Netcode
|
||||
/// <typeparam name="T"></typeparam>
|
||||
internal class UnmanagedTypeSerializer<T> : INetworkVariableSerializer<T> where T : unmanaged
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.Unmanaged;
|
||||
public bool IsDistributedAuthorityOptimized => false;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref T value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => Read(reader, ref value);
|
||||
|
||||
public void Write(FastBufferWriter writer, ref T value)
|
||||
{
|
||||
writer.WriteUnmanagedSafe(value);
|
||||
@@ -365,20 +264,6 @@ namespace Unity.Netcode
|
||||
|
||||
internal class ListSerializer<T> : INetworkVariableSerializer<List<T>>
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.Value;
|
||||
public bool IsDistributedAuthorityOptimized => false;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref List<T> value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref List<T> value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref List<T> value, ref List<T> previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref List<T> value) => Read(reader, ref value);
|
||||
public void Write(FastBufferWriter writer, ref List<T> value)
|
||||
{
|
||||
var isNull = value == null;
|
||||
@@ -458,27 +343,16 @@ namespace Unity.Netcode
|
||||
duplicatedValue.Clear();
|
||||
foreach (var item in value)
|
||||
{
|
||||
duplicatedValue.Add(item);
|
||||
// This handles the nested list scenario List<List<T>>
|
||||
T subValue = default;
|
||||
NetworkVariableSerialization<T>.Duplicate(item, ref subValue);
|
||||
duplicatedValue.Add(subValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal class HashSetSerializer<T> : INetworkVariableSerializer<HashSet<T>> where T : IEquatable<T>
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.Value;
|
||||
public bool IsDistributedAuthorityOptimized => false;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref HashSet<T> value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref HashSet<T> value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref HashSet<T> value, ref HashSet<T> previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref HashSet<T> value) => Read(reader, ref value);
|
||||
public void Write(FastBufferWriter writer, ref HashSet<T> value)
|
||||
{
|
||||
var isNull = value == null;
|
||||
@@ -548,6 +422,9 @@ namespace Unity.Netcode
|
||||
duplicatedValue.Clear();
|
||||
foreach (var item in value)
|
||||
{
|
||||
// Handles nested HashSets
|
||||
T subValue = default;
|
||||
NetworkVariableSerialization<T>.Duplicate(item, ref subValue);
|
||||
duplicatedValue.Add(item);
|
||||
}
|
||||
}
|
||||
@@ -557,20 +434,6 @@ namespace Unity.Netcode
|
||||
internal class DictionarySerializer<TKey, TVal> : INetworkVariableSerializer<Dictionary<TKey, TVal>>
|
||||
where TKey : IEquatable<TKey>
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.Value;
|
||||
public bool IsDistributedAuthorityOptimized => false;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref Dictionary<TKey, TVal> value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref Dictionary<TKey, TVal> value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref Dictionary<TKey, TVal> value, ref Dictionary<TKey, TVal> previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref Dictionary<TKey, TVal> value) => Read(reader, ref value);
|
||||
public void Write(FastBufferWriter writer, ref Dictionary<TKey, TVal> value)
|
||||
{
|
||||
var isNull = value == null;
|
||||
@@ -641,27 +504,18 @@ namespace Unity.Netcode
|
||||
duplicatedValue.Clear();
|
||||
foreach (var item in value)
|
||||
{
|
||||
duplicatedValue.Add(item.Key, item.Value);
|
||||
// Handles nested dictionaries
|
||||
TKey subKey = default;
|
||||
TVal subValue = default;
|
||||
NetworkVariableSerialization<TKey>.Duplicate(item.Key, ref subKey);
|
||||
NetworkVariableSerialization<TVal>.Duplicate(item.Value, ref subValue);
|
||||
duplicatedValue.Add(subKey, subValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal class UnmanagedArraySerializer<T> : INetworkVariableSerializer<NativeArray<T>> where T : unmanaged
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.Value;
|
||||
public bool IsDistributedAuthorityOptimized => false;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value, ref NativeArray<T> previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value) => Read(reader, ref value);
|
||||
public void Write(FastBufferWriter writer, ref NativeArray<T> value)
|
||||
{
|
||||
writer.WriteUnmanagedSafe(value);
|
||||
@@ -707,20 +561,6 @@ namespace Unity.Netcode
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
internal class UnmanagedListSerializer<T> : INetworkVariableSerializer<NativeList<T>> where T : unmanaged
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.Value;
|
||||
public bool IsDistributedAuthorityOptimized => false;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeList<T> value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value, ref NativeList<T> previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeList<T> value) => Read(reader, ref value);
|
||||
public void Write(FastBufferWriter writer, ref NativeList<T> value)
|
||||
{
|
||||
writer.WriteUnmanagedSafe(value);
|
||||
@@ -764,21 +604,6 @@ namespace Unity.Netcode
|
||||
|
||||
internal class NativeHashSetSerializer<T> : INetworkVariableSerializer<NativeHashSet<T>> where T : unmanaged, IEquatable<T>
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.Value;
|
||||
public bool IsDistributedAuthorityOptimized => false;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeHashSet<T> value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeHashSet<T> value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeHashSet<T> value, ref NativeHashSet<T> previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeHashSet<T> value) => Read(reader, ref value);
|
||||
|
||||
public void Write(FastBufferWriter writer, ref NativeHashSet<T> value)
|
||||
{
|
||||
writer.WriteValueSafe(value);
|
||||
@@ -824,21 +649,6 @@ namespace Unity.Netcode
|
||||
where TKey : unmanaged, IEquatable<TKey>
|
||||
where TVal : unmanaged
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.Value;
|
||||
public bool IsDistributedAuthorityOptimized => false;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeHashMap<TKey, TVal> value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeHashMap<TKey, TVal> value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeHashMap<TKey, TVal> value, ref NativeHashMap<TKey, TVal> previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeHashMap<TKey, TVal> value) => Read(reader, ref value);
|
||||
|
||||
public void Write(FastBufferWriter writer, ref NativeHashMap<TKey, TVal> value)
|
||||
{
|
||||
writer.WriteValueSafe(value);
|
||||
@@ -886,21 +696,6 @@ namespace Unity.Netcode
|
||||
/// <typeparam name="T"></typeparam>
|
||||
internal class FixedStringSerializer<T> : INetworkVariableSerializer<T> where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.Value;
|
||||
public bool IsDistributedAuthorityOptimized => false;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref T value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => Read(reader, ref value);
|
||||
|
||||
public void Write(FastBufferWriter writer, ref T value)
|
||||
{
|
||||
writer.WriteValueSafe(value);
|
||||
@@ -924,7 +719,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
var val = value[i];
|
||||
var prevVal = previousValue[i];
|
||||
if (!NetworkVariableSerialization<byte>.AreEqual(ref val, ref prevVal))
|
||||
if (val != prevVal)
|
||||
{
|
||||
++numChanges;
|
||||
changes.Set(i);
|
||||
@@ -949,19 +744,11 @@ namespace Unity.Netcode
|
||||
BytePacker.WriteValuePacked(writer, value.Length);
|
||||
writer.WriteValueSafe(changes);
|
||||
var ptr = value.GetUnsafePtr();
|
||||
var prevPtr = previousValue.GetUnsafePtr();
|
||||
for (var i = 0; i < value.Length; ++i)
|
||||
{
|
||||
if (changes.IsSet(i))
|
||||
{
|
||||
if (i < previousValue.Length)
|
||||
{
|
||||
NetworkVariableSerialization<byte>.WriteDelta(writer, ref ptr[i], ref prevPtr[i]);
|
||||
}
|
||||
else
|
||||
{
|
||||
NetworkVariableSerialization<byte>.Write(writer, ref ptr[i]);
|
||||
}
|
||||
writer.WriteByteSafe(ptr[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1016,20 +803,6 @@ namespace Unity.Netcode
|
||||
/// <typeparam name="T"></typeparam>
|
||||
internal class FixedStringArraySerializer<T> : INetworkVariableSerializer<NativeArray<T>> where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.Value;
|
||||
public bool IsDistributedAuthorityOptimized => false;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value, ref NativeArray<T> previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value) => Read(reader, ref value);
|
||||
public void Write(FastBufferWriter writer, ref NativeArray<T> value)
|
||||
{
|
||||
writer.WriteValueSafe(value);
|
||||
@@ -1080,21 +853,6 @@ namespace Unity.Netcode
|
||||
/// <typeparam name="T"></typeparam>
|
||||
internal class FixedStringListSerializer<T> : INetworkVariableSerializer<NativeList<T>> where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.Value;
|
||||
public bool IsDistributedAuthorityOptimized => false;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeList<T> value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value, ref NativeList<T> previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeList<T> value) => Read(reader, ref value);
|
||||
|
||||
public void Write(FastBufferWriter writer, ref NativeList<T> value)
|
||||
{
|
||||
writer.WriteValueSafe(value);
|
||||
@@ -1142,21 +900,6 @@ namespace Unity.Netcode
|
||||
/// <typeparam name="T"></typeparam>
|
||||
internal class UnmanagedNetworkSerializableSerializer<T> : INetworkVariableSerializer<T> where T : unmanaged, INetworkSerializable
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.Value;
|
||||
public bool IsDistributedAuthorityOptimized => false;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref T value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => Read(reader, ref value);
|
||||
|
||||
public void Write(FastBufferWriter writer, ref T value)
|
||||
{
|
||||
var bufferSerializer = new BufferSerializer<BufferSerializerWriter>(new BufferSerializerWriter(writer));
|
||||
@@ -1209,20 +952,6 @@ namespace Unity.Netcode
|
||||
/// <typeparam name="T"></typeparam>
|
||||
internal class UnmanagedNetworkSerializableArraySerializer<T> : INetworkVariableSerializer<NativeArray<T>> where T : unmanaged, INetworkSerializable
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.Value;
|
||||
public bool IsDistributedAuthorityOptimized => false;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeArray<T> value, ref NativeArray<T> previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeArray<T> value) => Read(reader, ref value);
|
||||
public void Write(FastBufferWriter writer, ref NativeArray<T> value)
|
||||
{
|
||||
writer.WriteNetworkSerializable(value);
|
||||
@@ -1273,21 +1002,6 @@ namespace Unity.Netcode
|
||||
/// <typeparam name="T"></typeparam>
|
||||
internal class UnmanagedNetworkSerializableListSerializer<T> : INetworkVariableSerializer<NativeList<T>> where T : unmanaged, INetworkSerializable
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.Value;
|
||||
public bool IsDistributedAuthorityOptimized => false;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref NativeList<T> value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref NativeList<T> value, ref NativeList<T> previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref NativeList<T> value) => Read(reader, ref value);
|
||||
|
||||
public void Write(FastBufferWriter writer, ref NativeList<T> value)
|
||||
{
|
||||
writer.WriteNetworkSerializable(value);
|
||||
@@ -1335,20 +1049,6 @@ namespace Unity.Netcode
|
||||
/// <typeparam name="T"></typeparam>
|
||||
internal class ManagedNetworkSerializableSerializer<T> : INetworkVariableSerializer<T> where T : class, INetworkSerializable, new()
|
||||
{
|
||||
public NetworkVariableType Type => NetworkVariableType.Value;
|
||||
public bool IsDistributedAuthorityOptimized => false;
|
||||
|
||||
public void WriteDistributedAuthority(FastBufferWriter writer, ref T value)
|
||||
{
|
||||
Write(writer, ref value);
|
||||
}
|
||||
|
||||
public void ReadDistributedAuthority(FastBufferReader reader, ref T value)
|
||||
{
|
||||
Read(reader, ref value);
|
||||
}
|
||||
public void WriteDeltaDistributedAuthority(FastBufferWriter writer, ref T value, ref T previousValue) => Write(writer, ref value);
|
||||
public void ReadDeltaDistributedAuthority(FastBufferReader reader, ref T value) => Read(reader, ref value);
|
||||
public void Write(FastBufferWriter writer, ref T value)
|
||||
{
|
||||
var bufferSerializer = new BufferSerializer<BufferSerializerWriter>(new BufferSerializerWriter(writer));
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
|
||||
internal static class SerializationTools
|
||||
{
|
||||
public delegate void WriteDelegate<T>(FastBufferWriter writer, ref T value);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void WriteWithSize<T>(WriteDelegate<T> writeMethod, FastBufferWriter writer, ref T value)
|
||||
{
|
||||
var writePos = writer.Position;
|
||||
// Note: This value can't be packed because we don't know how large it will be in advance
|
||||
// we reserve space for it, then write the data, then come back and fill in the space
|
||||
// to pack here, we'd have to write data to a temporary buffer and copy it in - which
|
||||
// isn't worth possibly saving one byte if and only if the data is less than 63 bytes long...
|
||||
// The way we do packing, any value > 63 in a ushort will use the full 2 bytes to represent.
|
||||
writer.WriteValueSafe((ushort)0);
|
||||
var startPos = writer.Position;
|
||||
writeMethod(writer, ref value);
|
||||
var size = writer.Position - startPos;
|
||||
writer.Seek(writePos);
|
||||
writer.WriteValueSafe((ushort)size);
|
||||
writer.Seek(startPos + size);
|
||||
}
|
||||
|
||||
public delegate void ReadDelegate<T>(FastBufferReader writer, ref T value);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void ReadWithSize<T>(ReadDelegate<T> readMethod, FastBufferReader reader, ref T value)
|
||||
{
|
||||
reader.ReadValueSafe(out ushort _);
|
||||
readMethod(reader, ref value);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void WriteType(FastBufferWriter writer, NetworkVariableType type) => writer.WriteValueSafe(type);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void ReadType<T>(FastBufferReader reader, INetworkVariableSerializer<T> serializer)
|
||||
{
|
||||
reader.ReadValueSafe(out NetworkVariableType type);
|
||||
if (type != serializer.Type)
|
||||
{
|
||||
throw new SerializationException();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 52a4ce368df54b0a8887c08f3402bcd3
|
||||
timeCreated: 1718300602
|
||||
@@ -1081,14 +1081,19 @@ namespace Unity.Netcode
|
||||
}
|
||||
else
|
||||
{
|
||||
var message = new SceneEventMessage
|
||||
// Send to each individual client to assure only the in-scene placed NetworkObjects being observed by the client
|
||||
// is serialized
|
||||
foreach (var clientId in targetClientIds)
|
||||
{
|
||||
EventData = sceneEvent,
|
||||
};
|
||||
var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, targetClientIds);
|
||||
NetworkManager.NetworkMetrics.TrackSceneEventSent(targetClientIds, (uint)SceneEventDataStore[sceneEventId].SceneEventType, SceneNameFromHash(SceneEventDataStore[sceneEventId].SceneHash), size);
|
||||
sceneEvent.TargetClientId = clientId;
|
||||
var message = new SceneEventMessage
|
||||
{
|
||||
EventData = sceneEvent,
|
||||
};
|
||||
var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, clientId);
|
||||
NetworkManager.NetworkMetrics.TrackSceneEventSent(clientId, (uint)sceneEvent.SceneEventType, SceneNameFromHash(sceneEvent.SceneHash), size);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -1898,10 +1903,12 @@ namespace Unity.Netcode
|
||||
SendSceneEventData(sceneEventData.SceneEventId, NetworkManager.ConnectedClientsIds.Where(c => c != sessionOwner).ToArray());
|
||||
|
||||
m_IsSceneEventActive = false;
|
||||
|
||||
sceneEventData.SceneEventType = SceneEventType.LoadComplete;
|
||||
//First, notify local server that the scene was loaded
|
||||
OnSceneEvent?.Invoke(new SceneEvent()
|
||||
{
|
||||
SceneEventType = SceneEventType.LoadComplete,
|
||||
SceneEventType = sceneEventData.SceneEventType,
|
||||
LoadSceneMode = sceneEventData.LoadSceneMode,
|
||||
SceneName = SceneNameFromHash(sceneEventData.SceneHash),
|
||||
ClientId = NetworkManager.LocalClientId,
|
||||
@@ -2550,17 +2557,6 @@ namespace Unity.Netcode
|
||||
// At this point the client is considered fully "connected"
|
||||
if ((NetworkManager.DistributedAuthorityMode && NetworkManager.LocalClient.IsSessionOwner) || !NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
if (NetworkManager.DistributedAuthorityMode && !NetworkManager.DAHost)
|
||||
{
|
||||
// DANGO-EXP TODO: Remove this once service is sending the synchronization message to all clients
|
||||
if (NetworkManager.ConnectedClients.ContainsKey(clientId) && NetworkManager.ConnectionManager.ConnectedClientIds.Contains(clientId) && NetworkManager.ConnectedClientsList.Contains(NetworkManager.ConnectedClients[clientId]))
|
||||
{
|
||||
EndSceneEvent(sceneEventId);
|
||||
return;
|
||||
}
|
||||
NetworkManager.ConnectionManager.AddClient(clientId);
|
||||
}
|
||||
|
||||
// Notify the local server that a client has finished synchronizing
|
||||
OnSceneEvent?.Invoke(new SceneEvent()
|
||||
{
|
||||
@@ -2575,6 +2571,20 @@ namespace Unity.Netcode
|
||||
}
|
||||
else
|
||||
{
|
||||
// Notify the local server that a client has finished synchronizing
|
||||
OnSceneEvent?.Invoke(new SceneEvent()
|
||||
{
|
||||
SceneEventType = sceneEventData.SceneEventType,
|
||||
SceneName = string.Empty,
|
||||
ClientId = clientId
|
||||
});
|
||||
|
||||
// Show any NetworkObjects that are:
|
||||
// - Hidden from the session owner
|
||||
// - Owned by this client
|
||||
// - Has NetworkObject.SpawnWithObservers set to true (the default)
|
||||
NetworkManager.SpawnManager.ShowHiddenObjectsToNewlyJoinedClient(clientId);
|
||||
|
||||
// DANGO-EXP TODO: Remove this once service distributes objects
|
||||
// Non-session owners receive this notification from newly connected clients and upon receiving
|
||||
// the event they will redistribute their NetworkObjects
|
||||
@@ -2589,9 +2599,6 @@ namespace Unity.Netcode
|
||||
// At this time the client is fully synchronized with all loaded scenes and
|
||||
// NetworkObjects and should be considered "fully connected". Send the
|
||||
// notification that the client is connected.
|
||||
// TODO 2023: We should have a better name for this or have multiple states the
|
||||
// client progresses through (the name and associated legacy behavior/expected state
|
||||
// of the client was persisted since MLAPI)
|
||||
NetworkManager.ConnectionManager.InvokeOnClientConnectedCallback(clientId);
|
||||
|
||||
if (NetworkManager.IsHost)
|
||||
@@ -2664,9 +2671,14 @@ namespace Unity.Netcode
|
||||
EventData = sceneEventData,
|
||||
};
|
||||
// Forward synchronization to client then exit early because DAHost is not the current session owner
|
||||
NetworkManager.MessageManager.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, NetworkManager.CurrentSessionOwner);
|
||||
EndSceneEvent(sceneEventData.SceneEventId);
|
||||
return;
|
||||
foreach (var client in NetworkManager.ConnectedClientsIds)
|
||||
{
|
||||
if (client == NetworkManager.LocalClientId)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
NetworkManager.MessageManager.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, client);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
|
||||
@@ -320,9 +320,11 @@ namespace Unity.Netcode
|
||||
internal void AddSpawnedNetworkObjects()
|
||||
{
|
||||
m_NetworkObjectsSync.Clear();
|
||||
// If distributed authority mode and sending to the service, then ignore observers
|
||||
var distributedAuthoritySendingToService = m_NetworkManager.DistributedAuthorityMode && TargetClientId == NetworkManager.ServerClientId;
|
||||
foreach (var sobj in m_NetworkManager.SpawnManager.SpawnedObjectsList)
|
||||
{
|
||||
if (sobj.Observers.Contains(TargetClientId))
|
||||
if (sobj.Observers.Contains(TargetClientId) || distributedAuthoritySendingToService)
|
||||
{
|
||||
m_NetworkObjectsSync.Add(sobj);
|
||||
}
|
||||
@@ -666,12 +668,14 @@ namespace Unity.Netcode
|
||||
// Write our count place holder (must not be packed!)
|
||||
writer.WriteValueSafe((ushort)0);
|
||||
var distributedAuthority = m_NetworkManager.DistributedAuthorityMode;
|
||||
// If distributed authority mode and sending to the service, then ignore observers
|
||||
var distributedAuthoritySendingToService = distributedAuthority && TargetClientId == NetworkManager.ServerClientId;
|
||||
|
||||
foreach (var keyValuePairByGlobalObjectIdHash in m_NetworkManager.SceneManager.ScenePlacedObjects)
|
||||
{
|
||||
foreach (var keyValuePairBySceneHandle in keyValuePairByGlobalObjectIdHash.Value)
|
||||
{
|
||||
if (keyValuePairBySceneHandle.Value.Observers.Contains(TargetClientId))
|
||||
if (keyValuePairBySceneHandle.Value.Observers.Contains(TargetClientId) || distributedAuthoritySendingToService)
|
||||
{
|
||||
// Serialize the NetworkObject
|
||||
var sceneObject = keyValuePairBySceneHandle.Value.GetMessageSceneObject(TargetClientId, distributedAuthority);
|
||||
|
||||
@@ -700,7 +700,7 @@ namespace Unity.Netcode
|
||||
}
|
||||
if (Handle->Position + size > Handle->AllowedWriteMark)
|
||||
{
|
||||
throw new OverflowException($"Attempted to write without first calling {nameof(TryBeginWrite)}()");
|
||||
throw new OverflowException($"Attempted to write without first calling {nameof(TryBeginWrite)}(), Position+Size={Handle->Position + size} > AllowedWriteMark={Handle->AllowedWriteMark}");
|
||||
}
|
||||
#endif
|
||||
UnsafeUtility.MemCpy((Handle->BufferPointer + Handle->Position), value + offset, size);
|
||||
@@ -729,7 +729,7 @@ namespace Unity.Netcode
|
||||
|
||||
if (!TryBeginWriteInternal(size))
|
||||
{
|
||||
throw new OverflowException("Writing past the end of the buffer");
|
||||
throw new OverflowException($"Writing past the end of the buffer, size is {size} bytes but remaining capacity is {Handle->Capacity - Handle->Position} bytes");
|
||||
}
|
||||
UnsafeUtility.MemCpy((Handle->BufferPointer + Handle->Position), value + offset, size);
|
||||
Handle->Position += size;
|
||||
|
||||
@@ -72,11 +72,29 @@ namespace Unity.Netcode
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var player in m_PlayerObjects)
|
||||
{
|
||||
player.Observers.Add(playerObject.OwnerClientId);
|
||||
playerObject.Observers.Add(player.OwnerClientId);
|
||||
// If the player's SpawnWithObservers is not set then do not add the new player object's owner as an observer.
|
||||
if (player.SpawnWithObservers)
|
||||
{
|
||||
player.Observers.Add(playerObject.OwnerClientId);
|
||||
}
|
||||
|
||||
// If the new player object's SpawnWithObservers is not set then do not add this player as an observer to the new player object.
|
||||
if (playerObject.SpawnWithObservers)
|
||||
{
|
||||
playerObject.Observers.Add(player.OwnerClientId);
|
||||
}
|
||||
}
|
||||
|
||||
// Only if spawn with observers is set or we are using a distributed authority network topology and this is the client's player should we add
|
||||
// the owner as an observer.
|
||||
if (playerObject.SpawnWithObservers || (NetworkManager.DistributedAuthorityMode && NetworkManager.LocalClientId == playerObject.OwnerClientId))
|
||||
{
|
||||
playerObject.Observers.Add(playerObject.OwnerClientId);
|
||||
}
|
||||
|
||||
m_PlayerObjects.Add(playerObject);
|
||||
if (!m_PlayerObjectsTable.ContainsKey(playerObject.OwnerClientId))
|
||||
{
|
||||
@@ -99,8 +117,9 @@ namespace Unity.Netcode
|
||||
if (playerNetworkClient.PlayerObject != null && m_PlayerObjects.Contains(playerNetworkClient.PlayerObject))
|
||||
{
|
||||
// Just remove the previous player object but keep the assigned observers of the NetworkObject
|
||||
RemovePlayerObject(playerNetworkClient.PlayerObject, true);
|
||||
RemovePlayerObject(playerNetworkClient.PlayerObject);
|
||||
}
|
||||
|
||||
// Now update the associated NetworkClient's player object
|
||||
NetworkManager.ConnectionManager.ConnectedClients[playerObject.OwnerClientId].AssignPlayerObject(ref playerObject);
|
||||
AddPlayerObject(playerObject);
|
||||
@@ -109,7 +128,7 @@ namespace Unity.Netcode
|
||||
/// <summary>
|
||||
/// Removes a player object and updates all other players' observers list
|
||||
/// </summary>
|
||||
private void RemovePlayerObject(NetworkObject playerObject, bool keepObservers = false)
|
||||
private void RemovePlayerObject(NetworkObject playerObject, bool destroyingObject = false)
|
||||
{
|
||||
if (!playerObject.IsPlayerObject)
|
||||
{
|
||||
@@ -130,16 +149,21 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
// If we want to keep the observers, then exit early
|
||||
if (keepObservers)
|
||||
if (NetworkManager.ConnectionManager.ConnectedClients.ContainsKey(playerObject.OwnerClientId) && destroyingObject)
|
||||
{
|
||||
return;
|
||||
NetworkManager.ConnectionManager.ConnectedClients[playerObject.OwnerClientId].PlayerObject = null;
|
||||
}
|
||||
|
||||
foreach (var player in m_PlayerObjects)
|
||||
{
|
||||
player.Observers.Remove(playerObject.OwnerClientId);
|
||||
}
|
||||
// If we want to keep the observers, then exit early
|
||||
//if (keepObservers)
|
||||
//{
|
||||
// return;
|
||||
//}
|
||||
|
||||
//foreach (var player in m_PlayerObjects)
|
||||
//{
|
||||
// player.Observers.Remove(playerObject.OwnerClientId);
|
||||
//}
|
||||
}
|
||||
|
||||
internal void MarkObjectForShowingTo(NetworkObject networkObject, ulong clientId)
|
||||
@@ -398,35 +422,51 @@ namespace Unity.Netcode
|
||||
{
|
||||
if (NetworkManager.DistributedAuthorityMode && !NetworkManager.ShutdownInProgress)
|
||||
{
|
||||
if (networkObject.IsOwnershipDistributable || networkObject.IsOwnershipTransferable)
|
||||
{
|
||||
if (networkObject.IsOwner || NetworkManager.DAHost)
|
||||
{
|
||||
NetworkLog.LogWarning("DANGO-TODO: Determine if removing ownership should make the CMB Service redistribute ownership or if this just isn't a valid thing in DAMode.");
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
NetworkLog.LogError($"Only the owner is allowed to remove ownership in distributed authority mode!");
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!NetworkManager.DAHost)
|
||||
{
|
||||
Debug.LogError($"Only {nameof(NetworkObject)}s with {nameof(NetworkObject.IsOwnershipDistributable)} or {nameof(NetworkObject.IsOwnershipTransferable)} set can perform ownership changes!");
|
||||
}
|
||||
return;
|
||||
}
|
||||
Debug.LogError($"Removing ownership is invalid in Distributed Authority Mode. Use {nameof(ChangeOwnership)} instead.");
|
||||
return;
|
||||
}
|
||||
ChangeOwnership(networkObject, NetworkManager.ServerClientId, true);
|
||||
}
|
||||
|
||||
private Dictionary<ulong, float> m_LastChangeInOwnership = new Dictionary<ulong, float>();
|
||||
private const int k_MaximumTickOwnershipChangeMultiplier = 6;
|
||||
|
||||
internal void ChangeOwnership(NetworkObject networkObject, ulong clientId, bool isAuthorized, bool isRequestApproval = false)
|
||||
{
|
||||
// For client-server:
|
||||
// If ownership changes faster than the latency between the client-server and there are NetworkVariables being updated during ownership changes,
|
||||
// then notify the user they could potentially lose state updates if developer logging is enabled.
|
||||
if (!NetworkManager.DistributedAuthorityMode && m_LastChangeInOwnership.ContainsKey(networkObject.NetworkObjectId) && m_LastChangeInOwnership[networkObject.NetworkObjectId] > Time.realtimeSinceStartup)
|
||||
{
|
||||
var hasNetworkVariables = false;
|
||||
for (int i = 0; i < networkObject.ChildNetworkBehaviours.Count; i++)
|
||||
{
|
||||
hasNetworkVariables = networkObject.ChildNetworkBehaviours[i].NetworkVariableFields.Count > 0;
|
||||
if (hasNetworkVariables)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (hasNetworkVariables && NetworkManager.LogLevel == LogLevel.Developer)
|
||||
{
|
||||
NetworkLog.LogWarningServer($"[Rapid Ownership Change Detected][Potential Loss in State] Detected a rapid change in ownership that exceeds a frequency less than {k_MaximumTickOwnershipChangeMultiplier}x the current network tick rate! Provide at least {k_MaximumTickOwnershipChangeMultiplier}x the current network tick rate between ownership changes to avoid NetworkVariable state loss.");
|
||||
}
|
||||
}
|
||||
|
||||
if (NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
// Ensure only the session owner can change ownership (i.e. acquire) and that the session owner is not trying to assign a non-session owner client
|
||||
// ownership of a NetworkObject with SessionOwner permissions.
|
||||
if (networkObject.IsOwnershipSessionOwner && (!NetworkManager.LocalClient.IsSessionOwner || clientId != NetworkManager.CurrentSessionOwner))
|
||||
{
|
||||
if (NetworkManager.LogLevel <= LogLevel.Developer)
|
||||
{
|
||||
NetworkLog.LogErrorServer($"[{networkObject.name}][Session Owner Only] You cannot change ownership of a {nameof(NetworkObject)} that has the {NetworkObject.OwnershipStatus.SessionOwner} flag set!");
|
||||
}
|
||||
networkObject.OnOwnershipPermissionsFailure?.Invoke(NetworkObject.OwnershipPermissionsFailureStatus.SessionOwnerOnly);
|
||||
return;
|
||||
}
|
||||
|
||||
// If are not authorized and this is not an approved ownership change, then check to see if we can change ownership
|
||||
if (!isAuthorized && !isRequestApproval)
|
||||
{
|
||||
@@ -497,15 +537,21 @@ namespace Unity.Netcode
|
||||
// Always notify locally on the server when ownership is lost
|
||||
networkObject.InvokeBehaviourOnLostOwnership();
|
||||
|
||||
networkObject.MarkVariablesDirty(true);
|
||||
NetworkManager.BehaviourUpdater.AddForUpdate(networkObject);
|
||||
|
||||
// Authority adds entries for all client ownership
|
||||
UpdateOwnershipTable(networkObject, networkObject.OwnerClientId);
|
||||
|
||||
// Always notify locally on the server when a new owner is assigned
|
||||
networkObject.InvokeBehaviourOnGainedOwnership();
|
||||
|
||||
if (networkObject.PreviousOwnerId == NetworkManager.LocalClientId)
|
||||
{
|
||||
// Mark any owner read variables as dirty
|
||||
networkObject.MarkOwnerReadVariablesDirty();
|
||||
// Immediately queue any pending deltas and order the message before the
|
||||
// change in ownership message.
|
||||
NetworkManager.BehaviourUpdater.NetworkBehaviourUpdate(true);
|
||||
}
|
||||
|
||||
var size = 0;
|
||||
if (NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
@@ -527,7 +573,6 @@ namespace Unity.Netcode
|
||||
{
|
||||
networkObject.ChildNetworkBehaviours[i].UpdateNetworkProperties();
|
||||
}
|
||||
|
||||
size = NetworkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.ReliableSequenced, NetworkManager.ServerClientId);
|
||||
NetworkManager.NetworkMetrics.TrackOwnershipChangeSent(NetworkManager.LocalClientId, networkObject, size);
|
||||
}
|
||||
@@ -569,6 +614,17 @@ namespace Unity.Netcode
|
||||
/// This gets called specifically *after* sending the ownership message so any additional messages that need to proceed an ownership
|
||||
/// change can be sent from NetworkBehaviours that override the <see cref="NetworkBehaviour.OnOwnershipChanged"></see>
|
||||
networkObject.InvokeOwnershipChanged(networkObject.PreviousOwnerId, clientId);
|
||||
|
||||
// Keep track of the ownership change frequency to assure a user is not exceeding changes faster than 2x the current Tick Rate.
|
||||
if (!NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
if (!m_LastChangeInOwnership.ContainsKey(networkObject.NetworkObjectId))
|
||||
{
|
||||
m_LastChangeInOwnership.Add(networkObject.NetworkObjectId, 0.0f);
|
||||
}
|
||||
var tickFrequency = 1.0f / NetworkManager.NetworkConfig.TickRate;
|
||||
m_LastChangeInOwnership[networkObject.NetworkObjectId] = Time.realtimeSinceStartup + (tickFrequency * k_MaximumTickOwnershipChangeMultiplier);
|
||||
}
|
||||
}
|
||||
|
||||
internal bool HasPrefab(NetworkObject.SceneObject sceneObject)
|
||||
@@ -673,12 +729,20 @@ namespace Unity.Netcode
|
||||
internal NetworkObject InstantiateAndSpawnNoParameterChecks(NetworkObject networkPrefab, ulong ownerClientId = NetworkManager.ServerClientId, bool destroyWithScene = false, bool isPlayerObject = false, bool forceOverride = false, Vector3 position = default, Quaternion rotation = default)
|
||||
{
|
||||
var networkObject = networkPrefab;
|
||||
// Host spawns the ovveride and server spawns the original prefab unless forceOverride is set to true where both server or host will spawn the override.
|
||||
// In distributed authority mode, we alaways get the override
|
||||
if (forceOverride || NetworkManager.IsHost || NetworkManager.DistributedAuthorityMode)
|
||||
// - Host and clients always instantiate the override if one exists.
|
||||
// - Server instantiates the original prefab unless:
|
||||
// -- forceOverride is set to true =or=
|
||||
// -- The prefab has a registered prefab handler, then we let user code determine what to spawn.
|
||||
// - Distributed authority mode always spawns the override if one exists.
|
||||
if (forceOverride || NetworkManager.IsClient || NetworkManager.DistributedAuthorityMode || NetworkManager.PrefabHandler.ContainsHandler(networkPrefab.GlobalObjectIdHash))
|
||||
{
|
||||
networkObject = GetNetworkObjectToSpawn(networkPrefab.GlobalObjectIdHash, ownerClientId, position, rotation);
|
||||
}
|
||||
else // Under this case, server instantiate the prefab passed in.
|
||||
{
|
||||
networkObject = InstantiateNetworkPrefab(networkPrefab.gameObject, networkPrefab.GlobalObjectIdHash, position, rotation);
|
||||
}
|
||||
|
||||
if (networkObject == null)
|
||||
{
|
||||
Debug.LogError($"Failed to instantiate and spawn {networkPrefab.name}!");
|
||||
@@ -687,7 +751,15 @@ namespace Unity.Netcode
|
||||
networkObject.IsPlayerObject = isPlayerObject;
|
||||
networkObject.transform.position = position;
|
||||
networkObject.transform.rotation = rotation;
|
||||
networkObject.SpawnWithOwnership(ownerClientId, destroyWithScene);
|
||||
// If spawning as a player, then invoke SpawnAsPlayerObject
|
||||
if (isPlayerObject)
|
||||
{
|
||||
networkObject.SpawnAsPlayerObject(ownerClientId, destroyWithScene);
|
||||
}
|
||||
else // Otherwise just spawn with ownership
|
||||
{
|
||||
networkObject.SpawnWithOwnership(ownerClientId, destroyWithScene);
|
||||
}
|
||||
return networkObject;
|
||||
}
|
||||
|
||||
@@ -695,14 +767,14 @@ namespace Unity.Netcode
|
||||
/// Gets the right NetworkObject prefab instance to spawn. If a handler is registered or there is an override assigned to the
|
||||
/// passed in globalObjectIdHash value, then that is what will be instantiated, spawned, and returned.
|
||||
/// </summary>
|
||||
internal NetworkObject GetNetworkObjectToSpawn(uint globalObjectIdHash, ulong ownerId, Vector3 position = default, Quaternion rotation = default, bool isScenePlaced = false)
|
||||
internal NetworkObject GetNetworkObjectToSpawn(uint globalObjectIdHash, ulong ownerId, Vector3? position, Quaternion? rotation, bool isScenePlaced = false)
|
||||
{
|
||||
NetworkObject networkObject = null;
|
||||
// If the prefab hash has a registered INetworkPrefabInstanceHandler derived class
|
||||
if (NetworkManager.PrefabHandler.ContainsHandler(globalObjectIdHash))
|
||||
{
|
||||
// Let the handler spawn the NetworkObject
|
||||
networkObject = NetworkManager.PrefabHandler.HandleNetworkPrefabSpawn(globalObjectIdHash, ownerId, position, rotation);
|
||||
networkObject = NetworkManager.PrefabHandler.HandleNetworkPrefabSpawn(globalObjectIdHash, ownerId, position ?? default, rotation ?? default);
|
||||
networkObject.NetworkManagerOwner = NetworkManager;
|
||||
}
|
||||
else
|
||||
@@ -752,15 +824,38 @@ namespace Unity.Netcode
|
||||
}
|
||||
else
|
||||
{
|
||||
// Create prefab instance
|
||||
networkObject = UnityEngine.Object.Instantiate(networkPrefabReference).GetComponent<NetworkObject>();
|
||||
networkObject.NetworkManagerOwner = NetworkManager;
|
||||
networkObject.PrefabGlobalObjectIdHash = globalObjectIdHash;
|
||||
// Create prefab instance while applying any pre-assigned position and rotation values
|
||||
networkObject = InstantiateNetworkPrefab(networkPrefabReference, globalObjectIdHash, position, rotation);
|
||||
}
|
||||
}
|
||||
return networkObject;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Instantiates a network prefab instance, assigns the base prefab <see cref="NetworkObject.GlobalObjectIdHash"/>, positions, and orients
|
||||
/// the instance.
|
||||
/// !!! Should only be invoked by <see cref="GetNetworkObjectToSpawn"/> unless used by an integration test !!!
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <param name="prefabGlobalObjectIdHash"> should be the base prefab <see cref="NetworkObject.GlobalObjectIdHash"/> value and not the
|
||||
/// overrided value.
|
||||
/// (Can be used for integration testing)
|
||||
/// </remarks>
|
||||
/// <param name="networkPrefab">prefab to instantiate</param>
|
||||
/// <param name="prefabGlobalObjectIdHash"><see cref="NetworkObject.GlobalObjectIdHash"/> of the base prefab instance</param>
|
||||
/// <param name="position">conditional position in place of the network prefab's default position</param>
|
||||
/// <param name="rotation">conditional rotation in place of the network prefab's default rotation</param>
|
||||
/// <returns>the instance of the <see cref="NetworkObject"/></returns>
|
||||
internal NetworkObject InstantiateNetworkPrefab(GameObject networkPrefab, uint prefabGlobalObjectIdHash, Vector3? position, Quaternion? rotation)
|
||||
{
|
||||
var networkObject = UnityEngine.Object.Instantiate(networkPrefab).GetComponent<NetworkObject>();
|
||||
networkObject.transform.position = position ?? networkObject.transform.position;
|
||||
networkObject.transform.rotation = rotation ?? networkObject.transform.rotation;
|
||||
networkObject.NetworkManagerOwner = NetworkManager;
|
||||
networkObject.PrefabGlobalObjectIdHash = prefabGlobalObjectIdHash;
|
||||
return networkObject;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a local NetowrkObject to be spawned.
|
||||
/// </summary>
|
||||
@@ -1045,6 +1140,12 @@ namespace Unity.Netcode
|
||||
// then add all connected clients as observers
|
||||
if (!NetworkManager.DistributedAuthorityMode && NetworkManager.IsServer && networkObject.SpawnWithObservers)
|
||||
{
|
||||
// If running as a server only, then make sure to always add the server's client identifier
|
||||
if (!NetworkManager.IsHost)
|
||||
{
|
||||
networkObject.Observers.Add(NetworkManager.LocalClientId);
|
||||
}
|
||||
|
||||
// Add client observers
|
||||
for (int i = 0; i < NetworkManager.ConnectedClientsIds.Count; i++)
|
||||
{
|
||||
@@ -1348,6 +1449,15 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
// Since we are spawing in-scene placed NetworkObjects for already loaded scenes,
|
||||
// we need to add any in-scene placed NetworkObject to our tracking table
|
||||
var clearFirst = true;
|
||||
foreach (var sceneLoaded in NetworkManager.SceneManager.ScenesLoaded)
|
||||
{
|
||||
NetworkManager.SceneManager.PopulateScenePlacedObjects(sceneLoaded.Value, clearFirst);
|
||||
clearFirst = false;
|
||||
}
|
||||
|
||||
// Notify all in-scene placed NetworkObjects have been spawned
|
||||
foreach (var networkObject in networkObjectsToSpawn)
|
||||
{
|
||||
@@ -1497,23 +1607,9 @@ namespace Unity.Netcode
|
||||
SpawnedObjectsList.Remove(networkObject);
|
||||
}
|
||||
|
||||
// DANGO-TODO: When we fix the issue with observers not being applied to NetworkObjects,
|
||||
// (client connect/disconnect) we can remove this hacky way of doing this.
|
||||
// Basically, when a player disconnects and/or is destroyed they are removed as an observer from all other client
|
||||
// NetworkOject instances.
|
||||
if (networkObject.IsPlayerObject && !networkObject.IsOwner && networkObject.OwnerClientId != NetworkManager.LocalClientId)
|
||||
{
|
||||
foreach (var netObject in SpawnedObjects)
|
||||
{
|
||||
if (netObject.Value.Observers.Contains(networkObject.OwnerClientId))
|
||||
{
|
||||
netObject.Value.Observers.Remove(networkObject.OwnerClientId);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (networkObject.IsPlayerObject)
|
||||
{
|
||||
RemovePlayerObject(networkObject);
|
||||
RemovePlayerObject(networkObject, destroyGameObject);
|
||||
}
|
||||
|
||||
// Always clear out the observers list when despawned
|
||||
@@ -1581,20 +1677,46 @@ namespace Unity.Netcode
|
||||
{
|
||||
foreach (var entry in ClientsToShowObject)
|
||||
{
|
||||
SendSpawnCallForObserverUpdate(entry.Value.ToArray(), entry.Key);
|
||||
if (entry.Key != null && entry.Key.IsSpawned)
|
||||
{
|
||||
try
|
||||
{
|
||||
SendSpawnCallForObserverUpdate(entry.Value.ToArray(), entry.Key);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (NetworkManager.LogLevel <= LogLevel.Developer)
|
||||
{
|
||||
Debug.LogException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ClientsToShowObject.Clear();
|
||||
ObjectsToShowToClient.Clear();
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle NetworkObjects to show
|
||||
// Server or Host handling of NetworkObjects to show
|
||||
foreach (var client in ObjectsToShowToClient)
|
||||
{
|
||||
ulong clientId = client.Key;
|
||||
foreach (var networkObject in client.Value)
|
||||
{
|
||||
SendSpawnCallForObject(clientId, networkObject);
|
||||
if (networkObject != null && networkObject.IsSpawned)
|
||||
{
|
||||
try
|
||||
{
|
||||
SendSpawnCallForObject(clientId, networkObject);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (NetworkManager.LogLevel <= LogLevel.Developer)
|
||||
{
|
||||
Debug.LogException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ObjectsToShowToClient.Clear();
|
||||
@@ -1626,6 +1748,11 @@ namespace Unity.Netcode
|
||||
|
||||
foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList)
|
||||
{
|
||||
if (networkObject.IsOwnershipSessionOwner)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (networkObject.IsOwnershipDistributable && !networkObject.IsOwnershipLocked)
|
||||
{
|
||||
if (networkObject.transform.parent != null)
|
||||
@@ -1636,17 +1763,15 @@ namespace Unity.Netcode
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// We have to check if it is an in-scene placed NetworkObject and if it is get the source prefab asset GlobalObjectIdHash value of the in-scene placed instance
|
||||
// since all in-scene placed instances use unique GlobalObjectIdHash values.
|
||||
var globalOjectIdHash = networkObject.IsSceneObject.HasValue && networkObject.IsSceneObject.Value ? networkObject.InScenePlacedSourceGlobalObjectIdHash : networkObject.GlobalObjectIdHash;
|
||||
|
||||
if (networkObject.IsSceneObject.Value)
|
||||
if (!objectTypeCount.ContainsKey(globalOjectIdHash))
|
||||
{
|
||||
continue;
|
||||
objectTypeCount.Add(globalOjectIdHash, 0);
|
||||
}
|
||||
|
||||
if (!objectTypeCount.ContainsKey(networkObject.GlobalObjectIdHash))
|
||||
{
|
||||
objectTypeCount.Add(networkObject.GlobalObjectIdHash, 0);
|
||||
}
|
||||
objectTypeCount[networkObject.GlobalObjectIdHash] += 1;
|
||||
objectTypeCount[globalOjectIdHash] += 1;
|
||||
|
||||
// DANGO-TODO-MVP: Remove this once the service handles object distribution
|
||||
if (onlyIncludeOwnedObjects && !networkObject.IsOwner)
|
||||
@@ -1654,133 +1779,141 @@ namespace Unity.Netcode
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
// Divide up by prefab type (GlobalObjectIdHash) to get a better distribution of object types
|
||||
if (!objectByTypeAndOwner.ContainsKey(networkObject.GlobalObjectIdHash))
|
||||
if (!objectByTypeAndOwner.ContainsKey(globalOjectIdHash))
|
||||
{
|
||||
objectByTypeAndOwner.Add(networkObject.GlobalObjectIdHash, new Dictionary<ulong, List<NetworkObject>>());
|
||||
objectByTypeAndOwner.Add(globalOjectIdHash, new Dictionary<ulong, List<NetworkObject>>());
|
||||
}
|
||||
|
||||
// Sub-divide each type by owner
|
||||
if (!objectByTypeAndOwner[networkObject.GlobalObjectIdHash].ContainsKey(networkObject.OwnerClientId))
|
||||
if (!objectByTypeAndOwner[globalOjectIdHash].ContainsKey(networkObject.OwnerClientId))
|
||||
{
|
||||
objectByTypeAndOwner[networkObject.GlobalObjectIdHash].Add(networkObject.OwnerClientId, new List<NetworkObject>());
|
||||
objectByTypeAndOwner[globalOjectIdHash].Add(networkObject.OwnerClientId, new List<NetworkObject>());
|
||||
}
|
||||
|
||||
// Add to the client's spawned object list
|
||||
objectByTypeAndOwner[networkObject.GlobalObjectIdHash][networkObject.OwnerClientId].Add(networkObject);
|
||||
objectByTypeAndOwner[globalOjectIdHash][networkObject.OwnerClientId].Add(networkObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal void DistributeNetworkObjects(ulong clientId)
|
||||
{
|
||||
// Distributed authority mode ownership distribution
|
||||
// DANGO-TODO-MVP: Remove the session owner object distribution check once the service handles object distribution
|
||||
if (NetworkManager.DistributedAuthorityMode && (NetworkManager.DAHost || NetworkManager.CMBServiceConnection))
|
||||
if (!NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
// DA-NGO CMB SERVICE NOTES:
|
||||
// The most basic object distribution should be broken up into a table of spawned object types
|
||||
// where each type contains a list of each client's owned objects of that type that can be
|
||||
// distributed.
|
||||
// The table format:
|
||||
// [GlobalObjectIdHashValue][ClientId][List of Owned Objects]
|
||||
var distributedNetworkObjects = new Dictionary<uint, Dictionary<ulong, List<NetworkObject>>>();
|
||||
return;
|
||||
}
|
||||
|
||||
// DA-NGO CMB SERVICE NOTES:
|
||||
// This is optional, but I found it easier to get the total count of spawned objects for each prefab
|
||||
// type contained in the previous table in order to be able to calculate the targeted object distribution
|
||||
// count of that type per client.
|
||||
var objectTypeCount = new Dictionary<uint, int>();
|
||||
if (NetworkManager.SessionConfig.ServiceSideDistribution)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Get all spawned objects by type and then by client owner that are spawned and can be distributed
|
||||
GetObjectDistribution(ref distributedNetworkObjects, ref objectTypeCount);
|
||||
|
||||
var clientCount = NetworkManager.ConnectedClientsIds.Count;
|
||||
// DA-NGO CMB SERVICE NOTES:
|
||||
// The most basic object distribution should be broken up into a table of spawned object types
|
||||
// where each type contains a list of each client's owned objects of that type that can be
|
||||
// distributed.
|
||||
// The table format:
|
||||
// [GlobalObjectIdHashValue][ClientId][List of Owned Objects]
|
||||
var distributedNetworkObjects = new Dictionary<uint, Dictionary<ulong, List<NetworkObject>>>();
|
||||
|
||||
// Cycle through each prefab type
|
||||
foreach (var objectTypeEntry in distributedNetworkObjects)
|
||||
// DA-NGO CMB SERVICE NOTES:
|
||||
// This is optional, but I found it easier to get the total count of spawned objects for each prefab
|
||||
// type contained in the previous table in order to be able to calculate the targeted object distribution
|
||||
// count of that type per client.
|
||||
var objectTypeCount = new Dictionary<uint, int>();
|
||||
|
||||
// Get all spawned objects by type and then by client owner that are spawned and can be distributed
|
||||
GetObjectDistribution(ref distributedNetworkObjects, ref objectTypeCount);
|
||||
|
||||
var clientCount = NetworkManager.ConnectedClientsIds.Count;
|
||||
|
||||
// Cycle through each prefab type
|
||||
foreach (var objectTypeEntry in distributedNetworkObjects)
|
||||
{
|
||||
// Calculate the number of objects that should be distributed amongst the clients
|
||||
var totalObjectsToDistribute = objectTypeCount[objectTypeEntry.Key];
|
||||
var objPerClientF = totalObjectsToDistribute * (1.0f / clientCount);
|
||||
var floorValue = (int)Math.Floor(objPerClientF);
|
||||
var fractional = objPerClientF - floorValue;
|
||||
var objPerClient = 0;
|
||||
if (fractional >= 0.556f)
|
||||
{
|
||||
// Calculate the number of objects that should be distributed amongst the clients
|
||||
var totalObjectsToDistribute = objectTypeCount[objectTypeEntry.Key];
|
||||
var objPerClientF = totalObjectsToDistribute * (1.0f / clientCount);
|
||||
var floorValue = (int)Math.Floor(objPerClientF);
|
||||
var fractional = objPerClientF - floorValue;
|
||||
var objPerClient = 0;
|
||||
if (fractional >= 0.556f)
|
||||
{
|
||||
objPerClient = (int)Math.Round(totalObjectsToDistribute * (1.0f / clientCount));
|
||||
}
|
||||
else
|
||||
{
|
||||
objPerClient = floorValue;
|
||||
}
|
||||
objPerClient = (int)Math.Round(totalObjectsToDistribute * (1.0f / clientCount));
|
||||
}
|
||||
else
|
||||
{
|
||||
objPerClient = floorValue;
|
||||
}
|
||||
|
||||
// If the object per client count is zero, then move to the next type.
|
||||
if (objPerClient <= 0)
|
||||
// If the object per client count is zero, then move to the next type.
|
||||
if (objPerClient <= 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Evenly distribute this object type amongst the clients
|
||||
foreach (var ownerList in objectTypeEntry.Value)
|
||||
{
|
||||
if (ownerList.Value.Count <= 1)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Evenly distribute this object type amongst the clients
|
||||
foreach (var ownerList in objectTypeEntry.Value)
|
||||
var maxDistributeCount = Mathf.Max(ownerList.Value.Count - objPerClient, 1);
|
||||
var distributed = 0;
|
||||
|
||||
// For now when we have more players then distributed NetworkObjects that
|
||||
// a specific client owns, just assign half of the NetworkObjects to the new client
|
||||
var offsetCount = Mathf.Max((int)Math.Round((float)(ownerList.Value.Count / objPerClient)), 1);
|
||||
if (EnableDistributeLogging)
|
||||
{
|
||||
if (ownerList.Value.Count <= 1)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Debug.Log($"[{objPerClient} of {totalObjectsToDistribute}][Client-{ownerList.Key}] Count: {ownerList.Value.Count} | ObjPerClient: {objPerClient} | maxD: {maxDistributeCount} | Offset: {offsetCount}");
|
||||
}
|
||||
|
||||
var maxDistributeCount = Mathf.Max(ownerList.Value.Count - objPerClient, 1);
|
||||
var distributed = 0;
|
||||
|
||||
// For now when we have more players then distributed NetworkObjects that
|
||||
// a specific client owns, just assign half of the NetworkObjects to the new client
|
||||
var offsetCount = Mathf.Max((int)Math.Round((float)(ownerList.Value.Count / objPerClient)), 1);
|
||||
if (EnableDistributeLogging)
|
||||
for (int i = 0; i < ownerList.Value.Count; i++)
|
||||
{
|
||||
if ((i % offsetCount) == 0)
|
||||
{
|
||||
Debug.Log($"[{objPerClient} of {totalObjectsToDistribute}][Client-{ownerList.Key}] Count: {ownerList.Value.Count} | ObjPerClient: {objPerClient} | maxD: {maxDistributeCount} | Offset: {offsetCount}");
|
||||
}
|
||||
|
||||
for (int i = 0; i < ownerList.Value.Count; i++)
|
||||
{
|
||||
if ((i % offsetCount) == 0)
|
||||
ChangeOwnership(ownerList.Value[i], clientId, true);
|
||||
//if (EnableDistributeLogging)
|
||||
{
|
||||
ChangeOwnership(ownerList.Value[i], clientId, true);
|
||||
if (EnableDistributeLogging)
|
||||
{
|
||||
Debug.Log($"[Client-{ownerList.Key}][NetworkObjectId-{ownerList.Value[i].NetworkObjectId} Distributed to Client-{clientId}");
|
||||
}
|
||||
distributed++;
|
||||
}
|
||||
if (distributed == maxDistributeCount)
|
||||
{
|
||||
break;
|
||||
Debug.Log($"[Client-{ownerList.Key}][NetworkObjectId-{ownerList.Value[i].NetworkObjectId} Distributed to Client-{clientId}");
|
||||
}
|
||||
distributed++;
|
||||
}
|
||||
if (distributed == maxDistributeCount)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If EnableDistributeLogging is enabled, log the object type distribution counts per client
|
||||
if (EnableDistributeLogging)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
distributedNetworkObjects.Clear();
|
||||
objectTypeCount.Clear();
|
||||
GetObjectDistribution(ref distributedNetworkObjects, ref objectTypeCount);
|
||||
builder.AppendLine($"Client Relative Distributed Object Count: (distribution follows)");
|
||||
// Cycle through each prefab type
|
||||
foreach (var objectTypeEntry in distributedNetworkObjects)
|
||||
{
|
||||
builder.AppendLine($"[GID: {objectTypeEntry.Key} | {objectTypeEntry.Value.First().Value.First().name}][Total Count: {objectTypeCount[objectTypeEntry.Key]}]");
|
||||
builder.AppendLine($"[GID: {objectTypeEntry.Key} | {objectTypeEntry.Value.First().Value.First().name}] Distribution:");
|
||||
// Evenly distribute this type amongst clients
|
||||
foreach (var ownerList in objectTypeEntry.Value)
|
||||
{
|
||||
builder.AppendLine($"[Client-{ownerList.Key}] Count: {ownerList.Value.Count}");
|
||||
}
|
||||
}
|
||||
Debug.Log(builder.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
// If EnableDistributeLogging is enabled, log the object type distribution counts per client
|
||||
if (EnableDistributeLogging)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
distributedNetworkObjects.Clear();
|
||||
objectTypeCount.Clear();
|
||||
GetObjectDistribution(ref distributedNetworkObjects, ref objectTypeCount);
|
||||
builder.AppendLine($"Client Relative Distributed Object Count: (distribution follows)");
|
||||
// Cycle through each prefab type
|
||||
foreach (var objectTypeEntry in distributedNetworkObjects)
|
||||
{
|
||||
builder.AppendLine($"[GID: {objectTypeEntry.Key} | {objectTypeEntry.Value.First().Value.First().name}][Total Count: {objectTypeCount[objectTypeEntry.Key]}]");
|
||||
builder.AppendLine($"[GID: {objectTypeEntry.Key} | {objectTypeEntry.Value.First().Value.First().name}] Distribution:");
|
||||
// Evenly distribute this type amongst clients
|
||||
foreach (var ownerList in objectTypeEntry.Value)
|
||||
{
|
||||
builder.AppendLine($"[Client-{ownerList.Key}] Count: {ownerList.Value.Count}");
|
||||
}
|
||||
}
|
||||
Debug.Log(builder.ToString());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
internal struct DeferredDespawnObject
|
||||
@@ -1883,5 +2016,96 @@ namespace Unity.Netcode
|
||||
networkObject.InternalNetworkSessionSynchronized();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Distributed Authority Only
|
||||
/// Should be invoked on non-session owner clients when a newly joined client is finished
|
||||
/// synchronizing in order to "show" (spawn) anything that might be currently hidden from
|
||||
/// the session owner.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Replacement is: SynchronizeObjectsToNewlyJoinedClient
|
||||
/// </remarks>
|
||||
internal void ShowHiddenObjectsToNewlyJoinedClient(ulong newClientId)
|
||||
{
|
||||
if (NetworkManager == null || NetworkManager.ShutdownInProgress && NetworkManager.LogLevel <= LogLevel.Developer)
|
||||
{
|
||||
Debug.LogWarning($"[Internal Error] {nameof(ShowHiddenObjectsToNewlyJoinedClient)} invoked while shutdown is in progress!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
Debug.LogError($"[Internal Error] {nameof(ShowHiddenObjectsToNewlyJoinedClient)} should only be invoked when using a distributed authority network topology!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (NetworkManager.LocalClient.IsSessionOwner)
|
||||
{
|
||||
Debug.LogError($"[Internal Error] {nameof(ShowHiddenObjectsToNewlyJoinedClient)} should only be invoked on a non-session owner client!");
|
||||
return;
|
||||
}
|
||||
var localClientId = NetworkManager.LocalClient.ClientId;
|
||||
var sessionOwnerId = NetworkManager.CurrentSessionOwner;
|
||||
foreach (var networkObject in SpawnedObjectsList)
|
||||
{
|
||||
if (networkObject.SpawnWithObservers && networkObject.OwnerClientId == localClientId && !networkObject.Observers.Contains(sessionOwnerId))
|
||||
{
|
||||
if (networkObject.Observers.Contains(newClientId))
|
||||
{
|
||||
if (NetworkManager.LogLevel <= LogLevel.Developer)
|
||||
{
|
||||
// Track if there is some other location where the client is being added to the observers list when the object is hidden from the session owner
|
||||
Debug.LogWarning($"[{networkObject.name}] Has new client as an observer but it is hidden from the session owner!");
|
||||
}
|
||||
// For now, remove the client (impossible for the new client to have an instance since the session owner doesn't) to make sure newly added
|
||||
// code to handle this edge case works.
|
||||
networkObject.Observers.Remove(newClientId);
|
||||
}
|
||||
networkObject.NetworkShow(newClientId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal void SynchronizeObjectsToNewlyJoinedClient(ulong newClientId)
|
||||
{
|
||||
if (NetworkManager == null || NetworkManager.ShutdownInProgress && NetworkManager.LogLevel <= LogLevel.Developer)
|
||||
{
|
||||
Debug.LogWarning($"[Internal Error] {nameof(SynchronizeObjectsToNewlyJoinedClient)} invoked while shutdown is in progress!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
Debug.LogError($"[Internal Error] {nameof(SynchronizeObjectsToNewlyJoinedClient)} should only be invoked when using a distributed authority network topology!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (NetworkManager.NetworkConfig.EnableSceneManagement)
|
||||
{
|
||||
Debug.LogError($"[Internal Error] {nameof(SynchronizeObjectsToNewlyJoinedClient)} should only be invoked when scene management is disabled!");
|
||||
return;
|
||||
}
|
||||
|
||||
var localClientId = NetworkManager.LocalClient.ClientId;
|
||||
foreach (var networkObject in SpawnedObjectsList)
|
||||
{
|
||||
if (networkObject.SpawnWithObservers && networkObject.OwnerClientId == localClientId)
|
||||
{
|
||||
if (networkObject.Observers.Contains(newClientId))
|
||||
{
|
||||
if (NetworkManager.LogLevel <= LogLevel.Developer)
|
||||
{
|
||||
// Temporary tracking to make sure we are not showing something already visibile (should never be the case for this)
|
||||
Debug.LogWarning($"[{nameof(SynchronizeObjectsToNewlyJoinedClient)}][{networkObject.name}] New client as already an observer!");
|
||||
}
|
||||
// For now, remove the client (impossible for the new client to have an instance since the session owner doesn't) to make sure newly added
|
||||
// code to handle this edge case works.
|
||||
networkObject.Observers.Remove(newClientId);
|
||||
}
|
||||
networkObject.NetworkShow(newClientId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,6 +107,45 @@ namespace Unity.Netcode
|
||||
/// /// <param name="networkManager">optionally pass in NetworkManager</param>
|
||||
public abstract void Initialize(NetworkManager networkManager = null);
|
||||
|
||||
/// <summary>
|
||||
/// Invoked by NetworkManager at the beginning of its EarlyUpdate.
|
||||
/// For order of operations see: <see cref="NetworkManager.NetworkUpdate(NetworkUpdateStage)"/>
|
||||
/// </summary>
|
||||
/// Useful to handle processing any transport-layer events such as processing inbound messages or changes in connection state(s).
|
||||
/// </remarks>
|
||||
protected virtual void OnEarlyUpdate()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invoked by NetworkManager at the beginning of its EarlyUpdate
|
||||
/// </summary>
|
||||
internal void EarlyUpdate()
|
||||
{
|
||||
OnEarlyUpdate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invoked by NetworkManager towards the end of the PostLateUpdate.
|
||||
/// For order of operations see: <see cref="NetworkManager.NetworkUpdate(NetworkUpdateStage)"/>
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Useful to handle any end of frame transport tasks such as sending queued transport messages.
|
||||
/// </remarks>
|
||||
protected virtual void OnPostLateUpdate()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invoked by NetworkManager towards the end of the PostLateUpdate
|
||||
/// </summary>
|
||||
internal void PostLateUpdate()
|
||||
{
|
||||
OnPostLateUpdate();
|
||||
}
|
||||
|
||||
protected virtual NetworkTopologyTypes OnCurrentTopology()
|
||||
{
|
||||
return NetworkTopologyTypes.ClientServer;
|
||||
|
||||
@@ -405,6 +405,7 @@ namespace Unity.Netcode.Transports.UTP
|
||||
|
||||
#if UTP_TRANSPORT_2_0_ABOVE
|
||||
[Obsolete("DebugSimulator is no longer supported and has no effect. Use Network Simulator from the Multiplayer Tools package.", false)]
|
||||
[HideInInspector]
|
||||
#endif
|
||||
public SimulatorParameters DebugSimulator = new SimulatorParameters
|
||||
{
|
||||
@@ -944,17 +945,13 @@ namespace Unity.Netcode.Transports.UTP
|
||||
return false;
|
||||
}
|
||||
|
||||
private void Update()
|
||||
/// <summary>
|
||||
/// Handles accepting new connections and processing transport events.
|
||||
/// </summary>
|
||||
protected override void OnEarlyUpdate()
|
||||
{
|
||||
if (m_Driver.IsCreated)
|
||||
{
|
||||
foreach (var kvp in m_SendQueue)
|
||||
{
|
||||
SendBatchedMessages(kvp.Key, kvp.Value);
|
||||
}
|
||||
|
||||
m_Driver.ScheduleUpdate().Complete();
|
||||
|
||||
if (m_ProtocolType == ProtocolType.RelayUnityTransport && m_Driver.GetRelayConnectionStatus() == RelayConnectionStatus.AllocationInvalid)
|
||||
{
|
||||
Debug.LogError("Transport failure! Relay allocation needs to be recreated, and NetworkManager restarted. " +
|
||||
@@ -964,15 +961,38 @@ namespace Unity.Netcode.Transports.UTP
|
||||
return;
|
||||
}
|
||||
|
||||
m_Driver.ScheduleUpdate().Complete();
|
||||
|
||||
// Process any new connections
|
||||
while (AcceptConnection() && m_Driver.IsCreated)
|
||||
{
|
||||
;
|
||||
}
|
||||
|
||||
// Process any transport events (i.e. connect, disconnect, data, etc)
|
||||
while (ProcessEvent() && m_Driver.IsCreated)
|
||||
{
|
||||
;
|
||||
}
|
||||
}
|
||||
base.OnEarlyUpdate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles sending any queued batched messages.
|
||||
/// </summary>
|
||||
protected override void OnPostLateUpdate()
|
||||
{
|
||||
if (m_Driver.IsCreated)
|
||||
{
|
||||
foreach (var kvp in m_SendQueue)
|
||||
{
|
||||
SendBatchedMessages(kvp.Key, kvp.Value);
|
||||
}
|
||||
|
||||
// Schedule a flush send as the last transport action for the
|
||||
// current frame.
|
||||
m_Driver.ScheduleFlushSend(default).Complete();
|
||||
|
||||
#if MULTIPLAYER_TOOLS_1_0_0_PRE_7
|
||||
if (m_NetworkManager)
|
||||
@@ -981,6 +1001,7 @@ namespace Unity.Netcode.Transports.UTP
|
||||
}
|
||||
#endif
|
||||
}
|
||||
base.OnPostLateUpdate();
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
@@ -1241,6 +1262,30 @@ namespace Unity.Netcode.Transports.UTP
|
||||
return (ulong)ExtractRtt(ParseClientId(clientId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provides the <see cref="NetworkEndpoint"/> for the NGO client identifier specified.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// - This is only really useful for direct connections.
|
||||
/// - Relay connections and clients connected using a distributed authority network topology will not provide the client's actual endpoint information.
|
||||
/// - For LAN topologies this should work as long as it is a direct connection and not a relay connection.
|
||||
/// </remarks>
|
||||
/// <param name="clientId">NGO client identifier to get endpoint information about.</param>
|
||||
/// <returns><see cref="NetworkEndpoint"/></returns>
|
||||
public NetworkEndpoint GetEndpoint(ulong clientId)
|
||||
{
|
||||
if (m_Driver.IsCreated && m_NetworkManager != null && m_NetworkManager.IsListening)
|
||||
{
|
||||
var transportId = m_NetworkManager.ConnectionManager.ClientIdToTransportId(clientId);
|
||||
var networkConnection = ParseClientId(transportId);
|
||||
if (m_Driver.GetConnectionState(networkConnection) == NetworkConnection.State.Connected)
|
||||
{
|
||||
return m_Driver.GetRemoteEndpoint(networkConnection);
|
||||
}
|
||||
}
|
||||
return new NetworkEndpoint();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the transport
|
||||
/// </summary>
|
||||
@@ -1450,8 +1495,18 @@ namespace Unity.Netcode.Transports.UTP
|
||||
/// </summary>
|
||||
public override void Shutdown()
|
||||
{
|
||||
if (m_NetworkManager && !m_NetworkManager.ShutdownInProgress)
|
||||
{
|
||||
Debug.LogWarning("Directly calling `UnityTransport.Shutdown()` results in unexpected shutdown behaviour. All pending events will be lost. Use `NetworkManager.Shutdown()` instead.");
|
||||
}
|
||||
|
||||
if (m_Driver.IsCreated)
|
||||
{
|
||||
while (ProcessEvent() && m_Driver.IsCreated)
|
||||
{
|
||||
;
|
||||
}
|
||||
|
||||
// Flush all send queues to the network. NGO can be configured to flush its message
|
||||
// queue on shutdown. But this only calls the Send() method, which doesn't actually
|
||||
// get anything to the network.
|
||||
@@ -1469,6 +1524,7 @@ namespace Unity.Netcode.Transports.UTP
|
||||
DisposeInternals();
|
||||
|
||||
m_ReliableReceiveQueues.Clear();
|
||||
m_State = State.Disconnected;
|
||||
|
||||
// We must reset this to zero because UTP actually re-uses clientIds if there is a clean disconnect
|
||||
m_ServerClientId = 0;
|
||||
|
||||
@@ -58,16 +58,6 @@
|
||||
"expression": "",
|
||||
"define": "COM_UNITY_MODULES_ANIMATION"
|
||||
},
|
||||
{
|
||||
"name": "com.unity.modules.physics",
|
||||
"expression": "",
|
||||
"define": "COM_UNITY_MODULES_PHYSICS"
|
||||
},
|
||||
{
|
||||
"name": "com.unity.modules.physics2d",
|
||||
"expression": "",
|
||||
"define": "COM_UNITY_MODULES_PHYSICS2D"
|
||||
},
|
||||
{
|
||||
"name": "com.unity.services.multiplayer",
|
||||
"expression": "0.2.0",
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"displayName": "Bootstrap",
|
||||
"description": "A lightweight sample to get started"
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "Bootstrap",
|
||||
"name": "Bootstrap",
|
||||
"rootNamespace": "Unity.Netcode.Samples",
|
||||
"references": [
|
||||
"Unity.Netcode.Runtime"
|
||||
|
||||
@@ -87,6 +87,8 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
return new Vector3(Random.Range(min, max), Random.Range(min, max), Random.Range(min, max));
|
||||
}
|
||||
|
||||
public IntegrationTestWithApproximation(NetworkTopologyTypes networkTopologyType, HostOrServer hostOrServer) : base(networkTopologyType, hostOrServer) { }
|
||||
|
||||
public IntegrationTestWithApproximation(NetworkTopologyTypes networkTopologyType) : base(networkTopologyType) { }
|
||||
|
||||
public IntegrationTestWithApproximation(HostOrServer hostOrServer) : base(hostOrServer) { }
|
||||
|
||||
@@ -24,10 +24,11 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
/// Used to determine if a NetcodeIntegrationTest is currently running to
|
||||
/// determine how clients will load scenes
|
||||
/// </summary>
|
||||
protected const float k_DefaultTimeoutPeriod = 8.0f;
|
||||
protected const float k_TickFrequency = 1.0f / k_DefaultTickRate;
|
||||
internal static bool IsRunning { get; private set; }
|
||||
|
||||
protected static TimeoutHelper s_GlobalTimeoutHelper = new TimeoutHelper(8.0f);
|
||||
protected static WaitForSecondsRealtime s_DefaultWaitForTick = new WaitForSecondsRealtime(1.0f / k_DefaultTickRate);
|
||||
protected static TimeoutHelper s_GlobalTimeoutHelper = new TimeoutHelper(k_DefaultTimeoutPeriod);
|
||||
protected static WaitForSecondsRealtime s_DefaultWaitForTick = new WaitForSecondsRealtime(k_TickFrequency);
|
||||
|
||||
public NetcodeLogAssert NetcodeLogAssert;
|
||||
public enum SceneManagementState
|
||||
@@ -544,9 +545,14 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
private bool AllPlayerObjectClonesSpawned(NetworkManager joinedClient)
|
||||
{
|
||||
m_InternalErrorLog.Clear();
|
||||
// If we are not checking for spawned players then exit early with a success
|
||||
if (!ShouldCheckForSpawnedPlayers())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// Continue to populate the PlayerObjects list until all player object (local and clone) are found
|
||||
ClientNetworkManagerPostStart(joinedClient);
|
||||
|
||||
var playerObjectRelative = m_ServerNetworkManager.SpawnManager.PlayerObjects.Where((c) => c.OwnerClientId == joinedClient.LocalClientId).FirstOrDefault();
|
||||
if (playerObjectRelative == null)
|
||||
{
|
||||
@@ -850,6 +856,12 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
|
||||
protected virtual bool LogAllMessages => false;
|
||||
|
||||
protected virtual bool ShouldCheckForSpawnedPlayers()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// This starts the server and clients as long as <see cref="CanStartServerAndClients"/>
|
||||
/// returns true.
|
||||
@@ -938,7 +950,12 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
AssertOnTimeout($"{nameof(CreateAndStartNewClient)} timed out waiting for all sessions to spawn Client-{m_ServerNetworkManager.LocalClientId}'s player object!\n {m_InternalErrorLog}");
|
||||
}
|
||||
}
|
||||
ClientNetworkManagerPostStartInit();
|
||||
|
||||
if (ShouldCheckForSpawnedPlayers())
|
||||
{
|
||||
ClientNetworkManagerPostStartInit();
|
||||
}
|
||||
|
||||
// Notification that at this time the server and client(s) are instantiated,
|
||||
// started, and connected on both sides.
|
||||
yield return OnServerAndClientsConnected();
|
||||
@@ -1030,7 +1047,10 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
}
|
||||
}
|
||||
|
||||
ClientNetworkManagerPostStartInit();
|
||||
if (ShouldCheckForSpawnedPlayers())
|
||||
{
|
||||
ClientNetworkManagerPostStartInit();
|
||||
}
|
||||
|
||||
// Notification that at this time the server and client(s) are instantiated,
|
||||
// started, and connected on both sides.
|
||||
@@ -1739,6 +1759,13 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
m_DistributedAuthority = m_NetworkTopologyType == NetworkTopologyTypes.DistributedAuthority;
|
||||
}
|
||||
|
||||
public NetcodeIntegrationTest(NetworkTopologyTypes networkTopologyType, HostOrServer hostOrServer)
|
||||
{
|
||||
m_NetworkTopologyType = networkTopologyType;
|
||||
m_DistributedAuthority = m_NetworkTopologyType == NetworkTopologyTypes.DistributedAuthority;
|
||||
m_UseHost = hostOrServer == HostOrServer.Host || hostOrServer == HostOrServer.DAHost;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Optional Host or Server integration tests
|
||||
/// Constructor that allows you To break tests up as a host
|
||||
|
||||
@@ -326,20 +326,30 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
|
||||
s_IsStarted = false;
|
||||
|
||||
// Shutdown the server which forces clients to disconnect
|
||||
foreach (var networkManager in NetworkManagerInstances)
|
||||
try
|
||||
{
|
||||
networkManager.Shutdown();
|
||||
s_Hooks.Remove(networkManager);
|
||||
}
|
||||
|
||||
// Destroy the network manager instances
|
||||
foreach (var networkManager in NetworkManagerInstances)
|
||||
{
|
||||
if (networkManager.gameObject != null)
|
||||
// Shutdown the server which forces clients to disconnect
|
||||
foreach (var networkManager in NetworkManagerInstances)
|
||||
{
|
||||
Object.DestroyImmediate(networkManager.gameObject);
|
||||
if (networkManager != null && networkManager.IsListening)
|
||||
{
|
||||
networkManager?.Shutdown();
|
||||
s_Hooks.Remove(networkManager);
|
||||
}
|
||||
}
|
||||
|
||||
// Destroy the network manager instances
|
||||
foreach (var networkManager in NetworkManagerInstances)
|
||||
{
|
||||
if (networkManager != null && networkManager.gameObject)
|
||||
{
|
||||
Object.DestroyImmediate(networkManager.gameObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.LogException(ex);
|
||||
}
|
||||
|
||||
NetworkManagerInstances.Clear();
|
||||
@@ -549,6 +559,29 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="NetworkObject"/> to be used with integration testing
|
||||
/// </summary>
|
||||
/// <param name="baseName">namr of the object</param>
|
||||
/// <param name="owner">owner of the object</param>
|
||||
/// <param name="moveToDDOL">when true, the instance is automatically migrated into the DDOL</param>
|
||||
/// <returns></returns>
|
||||
internal static GameObject CreateNetworkObject(string baseName, NetworkManager owner, bool moveToDDOL = false)
|
||||
{
|
||||
var gameObject = new GameObject
|
||||
{
|
||||
name = baseName
|
||||
};
|
||||
var networkObject = gameObject.AddComponent<NetworkObject>();
|
||||
networkObject.NetworkManagerOwner = owner;
|
||||
MakeNetworkObjectTestPrefab(networkObject);
|
||||
if (moveToDDOL)
|
||||
{
|
||||
Object.DontDestroyOnLoad(gameObject);
|
||||
}
|
||||
return gameObject;
|
||||
}
|
||||
|
||||
public static GameObject CreateNetworkObjectPrefab(string baseName, NetworkManager server, params NetworkManager[] clients)
|
||||
{
|
||||
void AddNetworkPrefab(NetworkConfig config, NetworkPrefab prefab)
|
||||
@@ -560,13 +593,7 @@ namespace Unity.Netcode.TestHelpers.Runtime
|
||||
Assert.IsNotNull(server, prefabCreateAssertError);
|
||||
Assert.IsFalse(server.IsListening, prefabCreateAssertError);
|
||||
|
||||
var gameObject = new GameObject
|
||||
{
|
||||
name = baseName
|
||||
};
|
||||
var networkObject = gameObject.AddComponent<NetworkObject>();
|
||||
networkObject.NetworkManagerOwner = server;
|
||||
MakeNetworkObjectTestPrefab(networkObject);
|
||||
var gameObject = CreateNetworkObject(baseName, server);
|
||||
var networkPrefab = new NetworkPrefab() { Prefab = gameObject };
|
||||
|
||||
// We could refactor this test framework to share a NetworkPrefabList instance, but at this point it's
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e5a2c06211b0c224c94202c2cda733fd
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,8 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d656bc8bb2502584ab6883d254d64782
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,31 +0,0 @@
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Unity.Netcode.EditorTests
|
||||
{
|
||||
internal class ArithmeticTests
|
||||
{
|
||||
[Test]
|
||||
public void TestCeil()
|
||||
{
|
||||
Assert.That(Arithmetic.CeilingExact(10, 5), Is.EqualTo(2));
|
||||
Assert.That(Arithmetic.CeilingExact(11, 5), Is.EqualTo(3));
|
||||
Assert.That(Arithmetic.CeilingExact(0, 5), Is.EqualTo(0));
|
||||
Assert.That(Arithmetic.CeilingExact(1, 5), Is.EqualTo(1));
|
||||
Assert.That(Arithmetic.CeilingExact(2, 5), Is.EqualTo(1));
|
||||
Assert.That(Arithmetic.CeilingExact(3, 5), Is.EqualTo(1));
|
||||
Assert.That(Arithmetic.CeilingExact(4, 5), Is.EqualTo(1));
|
||||
Assert.That(Arithmetic.CeilingExact(5, 5), Is.EqualTo(1));
|
||||
Assert.That(Arithmetic.CeilingExact(6, 5), Is.EqualTo(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TestZigZag()
|
||||
{
|
||||
Assert.That(Arithmetic.ZigZagDecode(Arithmetic.ZigZagEncode(1234)), Is.EqualTo(1234));
|
||||
Assert.That(Arithmetic.ZigZagDecode(Arithmetic.ZigZagEncode(-1)), Is.EqualTo(-1));
|
||||
Assert.That(Arithmetic.ZigZagDecode(Arithmetic.ZigZagEncode(0)), Is.EqualTo(0));
|
||||
Assert.That(Arithmetic.ZigZagDecode(Arithmetic.ZigZagEncode(long.MaxValue)), Is.EqualTo(long.MaxValue));
|
||||
Assert.That(Arithmetic.ZigZagDecode(Arithmetic.ZigZagEncode(long.MinValue)), Is.EqualTo(long.MinValue));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: cc0dc1cbf78a5486db1ccbc245d90992
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,8 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2a46bbc7e63044f498612ed996afa274
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,371 +0,0 @@
|
||||
%YAML 1.1
|
||||
%TAG !u! tag:unity3d.com,2011:
|
||||
--- !u!29 &1
|
||||
OcclusionCullingSettings:
|
||||
m_ObjectHideFlags: 0
|
||||
serializedVersion: 2
|
||||
m_OcclusionBakeSettings:
|
||||
smallestOccluder: 5
|
||||
smallestHole: 0.25
|
||||
backfaceThreshold: 100
|
||||
m_SceneGUID: 00000000000000000000000000000000
|
||||
m_OcclusionCullingData: {fileID: 0}
|
||||
--- !u!104 &2
|
||||
RenderSettings:
|
||||
m_ObjectHideFlags: 0
|
||||
serializedVersion: 9
|
||||
m_Fog: 0
|
||||
m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1}
|
||||
m_FogMode: 3
|
||||
m_FogDensity: 0.01
|
||||
m_LinearFogStart: 0
|
||||
m_LinearFogEnd: 300
|
||||
m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1}
|
||||
m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1}
|
||||
m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1}
|
||||
m_AmbientIntensity: 1
|
||||
m_AmbientMode: 0
|
||||
m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1}
|
||||
m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0}
|
||||
m_HaloStrength: 0.5
|
||||
m_FlareStrength: 1
|
||||
m_FlareFadeSpeed: 3
|
||||
m_HaloTexture: {fileID: 0}
|
||||
m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0}
|
||||
m_DefaultReflectionMode: 0
|
||||
m_DefaultReflectionResolution: 128
|
||||
m_ReflectionBounces: 1
|
||||
m_ReflectionIntensity: 1
|
||||
m_CustomReflection: {fileID: 0}
|
||||
m_Sun: {fileID: 0}
|
||||
m_IndirectSpecularColor: {r: 0.44657874, g: 0.49641275, b: 0.5748172, a: 1}
|
||||
m_UseRadianceAmbientProbe: 0
|
||||
--- !u!157 &3
|
||||
LightmapSettings:
|
||||
m_ObjectHideFlags: 0
|
||||
serializedVersion: 12
|
||||
m_GIWorkflowMode: 1
|
||||
m_GISettings:
|
||||
serializedVersion: 2
|
||||
m_BounceScale: 1
|
||||
m_IndirectOutputScale: 1
|
||||
m_AlbedoBoost: 1
|
||||
m_EnvironmentLightingMode: 0
|
||||
m_EnableBakedLightmaps: 1
|
||||
m_EnableRealtimeLightmaps: 0
|
||||
m_LightmapEditorSettings:
|
||||
serializedVersion: 12
|
||||
m_Resolution: 2
|
||||
m_BakeResolution: 40
|
||||
m_AtlasSize: 1024
|
||||
m_AO: 0
|
||||
m_AOMaxDistance: 1
|
||||
m_CompAOExponent: 1
|
||||
m_CompAOExponentDirect: 0
|
||||
m_ExtractAmbientOcclusion: 0
|
||||
m_Padding: 2
|
||||
m_LightmapParameters: {fileID: 0}
|
||||
m_LightmapsBakeMode: 1
|
||||
m_TextureCompression: 1
|
||||
m_FinalGather: 0
|
||||
m_FinalGatherFiltering: 1
|
||||
m_FinalGatherRayCount: 256
|
||||
m_ReflectionCompression: 2
|
||||
m_MixedBakeMode: 2
|
||||
m_BakeBackend: 1
|
||||
m_PVRSampling: 1
|
||||
m_PVRDirectSampleCount: 32
|
||||
m_PVRSampleCount: 512
|
||||
m_PVRBounces: 2
|
||||
m_PVREnvironmentSampleCount: 256
|
||||
m_PVREnvironmentReferencePointCount: 2048
|
||||
m_PVRFilteringMode: 1
|
||||
m_PVRDenoiserTypeDirect: 1
|
||||
m_PVRDenoiserTypeIndirect: 1
|
||||
m_PVRDenoiserTypeAO: 1
|
||||
m_PVRFilterTypeDirect: 0
|
||||
m_PVRFilterTypeIndirect: 0
|
||||
m_PVRFilterTypeAO: 0
|
||||
m_PVREnvironmentMIS: 1
|
||||
m_PVRCulling: 1
|
||||
m_PVRFilteringGaussRadiusDirect: 1
|
||||
m_PVRFilteringGaussRadiusIndirect: 5
|
||||
m_PVRFilteringGaussRadiusAO: 2
|
||||
m_PVRFilteringAtrousPositionSigmaDirect: 0.5
|
||||
m_PVRFilteringAtrousPositionSigmaIndirect: 2
|
||||
m_PVRFilteringAtrousPositionSigmaAO: 1
|
||||
m_ExportTrainingData: 0
|
||||
m_TrainingDataDestination: TrainingData
|
||||
m_LightProbeSampleCountMultiplier: 4
|
||||
m_LightingDataAsset: {fileID: 0}
|
||||
m_LightingSettings: {fileID: 0}
|
||||
--- !u!196 &4
|
||||
NavMeshSettings:
|
||||
serializedVersion: 2
|
||||
m_ObjectHideFlags: 0
|
||||
m_BuildSettings:
|
||||
serializedVersion: 2
|
||||
agentTypeID: 0
|
||||
agentRadius: 0.5
|
||||
agentHeight: 2
|
||||
agentSlope: 45
|
||||
agentClimb: 0.4
|
||||
ledgeDropHeight: 0
|
||||
maxJumpAcrossDistance: 0
|
||||
minRegionArea: 2
|
||||
manualCellSize: 0
|
||||
cellSize: 0.16666667
|
||||
manualTileSize: 0
|
||||
tileSize: 256
|
||||
accuratePlacement: 0
|
||||
maxJobWorkers: 0
|
||||
preserveTilesOutsideBounds: 0
|
||||
debug:
|
||||
m_Flags: 0
|
||||
m_NavMeshData: {fileID: 0}
|
||||
--- !u!1 &1290761662
|
||||
GameObject:
|
||||
m_ObjectHideFlags: 0
|
||||
m_CorrespondingSourceObject: {fileID: 0}
|
||||
m_PrefabInstance: {fileID: 0}
|
||||
m_PrefabAsset: {fileID: 0}
|
||||
serializedVersion: 6
|
||||
m_Component:
|
||||
- component: {fileID: 1290761665}
|
||||
- component: {fileID: 1290761664}
|
||||
- component: {fileID: 1290761663}
|
||||
m_Layer: 0
|
||||
m_Name: Main Camera
|
||||
m_TagString: MainCamera
|
||||
m_Icon: {fileID: 0}
|
||||
m_NavMeshLayer: 0
|
||||
m_StaticEditorFlags: 0
|
||||
m_IsActive: 1
|
||||
--- !u!81 &1290761663
|
||||
AudioListener:
|
||||
m_ObjectHideFlags: 0
|
||||
m_CorrespondingSourceObject: {fileID: 0}
|
||||
m_PrefabInstance: {fileID: 0}
|
||||
m_PrefabAsset: {fileID: 0}
|
||||
m_GameObject: {fileID: 1290761662}
|
||||
m_Enabled: 1
|
||||
--- !u!20 &1290761664
|
||||
Camera:
|
||||
m_ObjectHideFlags: 0
|
||||
m_CorrespondingSourceObject: {fileID: 0}
|
||||
m_PrefabInstance: {fileID: 0}
|
||||
m_PrefabAsset: {fileID: 0}
|
||||
m_GameObject: {fileID: 1290761662}
|
||||
m_Enabled: 1
|
||||
serializedVersion: 2
|
||||
m_ClearFlags: 1
|
||||
m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0}
|
||||
m_projectionMatrixMode: 1
|
||||
m_GateFitMode: 2
|
||||
m_FOVAxisMode: 0
|
||||
m_SensorSize: {x: 36, y: 24}
|
||||
m_LensShift: {x: 0, y: 0}
|
||||
m_FocalLength: 50
|
||||
m_NormalizedViewPortRect:
|
||||
serializedVersion: 2
|
||||
x: 0
|
||||
y: 0
|
||||
width: 1
|
||||
height: 1
|
||||
near clip plane: 0.3
|
||||
far clip plane: 1000
|
||||
field of view: 60
|
||||
orthographic: 0
|
||||
orthographic size: 5
|
||||
m_Depth: -1
|
||||
m_CullingMask:
|
||||
serializedVersion: 2
|
||||
m_Bits: 4294967295
|
||||
m_RenderingPath: -1
|
||||
m_TargetTexture: {fileID: 0}
|
||||
m_TargetDisplay: 0
|
||||
m_TargetEye: 3
|
||||
m_HDR: 1
|
||||
m_AllowMSAA: 1
|
||||
m_AllowDynamicResolution: 0
|
||||
m_ForceIntoRT: 0
|
||||
m_OcclusionCulling: 1
|
||||
m_StereoConvergence: 10
|
||||
m_StereoSeparation: 0.022
|
||||
--- !u!4 &1290761665
|
||||
Transform:
|
||||
m_ObjectHideFlags: 0
|
||||
m_CorrespondingSourceObject: {fileID: 0}
|
||||
m_PrefabInstance: {fileID: 0}
|
||||
m_PrefabAsset: {fileID: 0}
|
||||
m_GameObject: {fileID: 1290761662}
|
||||
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
|
||||
m_LocalPosition: {x: 0, y: 1, z: -10}
|
||||
m_LocalScale: {x: 1, y: 1, z: 1}
|
||||
m_Children: []
|
||||
m_Father: {fileID: 0}
|
||||
m_RootOrder: 0
|
||||
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
|
||||
--- !u!1 &1858588911
|
||||
GameObject:
|
||||
m_ObjectHideFlags: 0
|
||||
m_CorrespondingSourceObject: {fileID: 0}
|
||||
m_PrefabInstance: {fileID: 0}
|
||||
m_PrefabAsset: {fileID: 0}
|
||||
serializedVersion: 6
|
||||
m_Component:
|
||||
- component: {fileID: 1858588913}
|
||||
- component: {fileID: 1858588912}
|
||||
m_Layer: 0
|
||||
m_Name: Directional Light
|
||||
m_TagString: Untagged
|
||||
m_Icon: {fileID: 0}
|
||||
m_NavMeshLayer: 0
|
||||
m_StaticEditorFlags: 0
|
||||
m_IsActive: 1
|
||||
--- !u!108 &1858588912
|
||||
Light:
|
||||
m_ObjectHideFlags: 0
|
||||
m_CorrespondingSourceObject: {fileID: 0}
|
||||
m_PrefabInstance: {fileID: 0}
|
||||
m_PrefabAsset: {fileID: 0}
|
||||
m_GameObject: {fileID: 1858588911}
|
||||
m_Enabled: 1
|
||||
serializedVersion: 10
|
||||
m_Type: 1
|
||||
m_Shape: 0
|
||||
m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1}
|
||||
m_Intensity: 1
|
||||
m_Range: 10
|
||||
m_SpotAngle: 30
|
||||
m_InnerSpotAngle: 21.80208
|
||||
m_CookieSize: 10
|
||||
m_Shadows:
|
||||
m_Type: 2
|
||||
m_Resolution: -1
|
||||
m_CustomResolution: -1
|
||||
m_Strength: 1
|
||||
m_Bias: 0.05
|
||||
m_NormalBias: 0.4
|
||||
m_NearPlane: 0.2
|
||||
m_CullingMatrixOverride:
|
||||
e00: 1
|
||||
e01: 0
|
||||
e02: 0
|
||||
e03: 0
|
||||
e10: 0
|
||||
e11: 1
|
||||
e12: 0
|
||||
e13: 0
|
||||
e20: 0
|
||||
e21: 0
|
||||
e22: 1
|
||||
e23: 0
|
||||
e30: 0
|
||||
e31: 0
|
||||
e32: 0
|
||||
e33: 1
|
||||
m_UseCullingMatrixOverride: 0
|
||||
m_Cookie: {fileID: 0}
|
||||
m_DrawHalo: 0
|
||||
m_Flare: {fileID: 0}
|
||||
m_RenderMode: 0
|
||||
m_CullingMask:
|
||||
serializedVersion: 2
|
||||
m_Bits: 4294967295
|
||||
m_RenderingLayerMask: 1
|
||||
m_Lightmapping: 4
|
||||
m_LightShadowCasterMode: 0
|
||||
m_AreaSize: {x: 1, y: 1}
|
||||
m_BounceIntensity: 1
|
||||
m_ColorTemperature: 6570
|
||||
m_UseColorTemperature: 0
|
||||
m_BoundingSphereOverride: {x: 0, y: 0, z: 0, w: 0}
|
||||
m_UseBoundingSphereOverride: 0
|
||||
m_UseViewFrustumForShadowCasterCull: 1
|
||||
m_ShadowRadius: 0
|
||||
m_ShadowAngle: 0
|
||||
--- !u!4 &1858588913
|
||||
Transform:
|
||||
m_ObjectHideFlags: 0
|
||||
m_CorrespondingSourceObject: {fileID: 0}
|
||||
m_PrefabInstance: {fileID: 0}
|
||||
m_PrefabAsset: {fileID: 0}
|
||||
m_GameObject: {fileID: 1858588911}
|
||||
m_LocalRotation: {x: 0.40821788, y: -0.23456968, z: 0.10938163, w: 0.8754261}
|
||||
m_LocalPosition: {x: 0, y: 3, z: 0}
|
||||
m_LocalScale: {x: 1, y: 1, z: 1}
|
||||
m_Children: []
|
||||
m_Father: {fileID: 0}
|
||||
m_RootOrder: 1
|
||||
m_LocalEulerAnglesHint: {x: 50, y: -30, z: 0}
|
||||
--- !u!1 &1896907459
|
||||
GameObject:
|
||||
m_ObjectHideFlags: 0
|
||||
m_CorrespondingSourceObject: {fileID: 0}
|
||||
m_PrefabInstance: {fileID: 0}
|
||||
m_PrefabAsset: {fileID: 0}
|
||||
serializedVersion: 6
|
||||
m_Component:
|
||||
- component: {fileID: 1896907460}
|
||||
- component: {fileID: 1896907461}
|
||||
m_Layer: 0
|
||||
m_Name: '[NetworkManager]'
|
||||
m_TagString: Untagged
|
||||
m_Icon: {fileID: 0}
|
||||
m_NavMeshLayer: 0
|
||||
m_StaticEditorFlags: 0
|
||||
m_IsActive: 1
|
||||
--- !u!4 &1896907460
|
||||
Transform:
|
||||
m_ObjectHideFlags: 0
|
||||
m_CorrespondingSourceObject: {fileID: 0}
|
||||
m_PrefabInstance: {fileID: 0}
|
||||
m_PrefabAsset: {fileID: 0}
|
||||
m_GameObject: {fileID: 1896907459}
|
||||
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
|
||||
m_LocalPosition: {x: 0, y: 0, z: 0}
|
||||
m_LocalScale: {x: 1, y: 1, z: 1}
|
||||
m_Children: []
|
||||
m_Father: {fileID: 0}
|
||||
m_RootOrder: 2
|
||||
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
|
||||
--- !u!114 &1896907461
|
||||
MonoBehaviour:
|
||||
m_ObjectHideFlags: 0
|
||||
m_CorrespondingSourceObject: {fileID: 0}
|
||||
m_PrefabInstance: {fileID: 0}
|
||||
m_PrefabAsset: {fileID: 0}
|
||||
m_GameObject: {fileID: 1896907459}
|
||||
m_Enabled: 1
|
||||
m_EditorHideFlags: 0
|
||||
m_Script: {fileID: 11500000, guid: 593a2fe42fa9d37498c96f9a383b6521, type: 3}
|
||||
m_Name:
|
||||
m_EditorClassIdentifier:
|
||||
DontDestroy: 1
|
||||
RunInBackground: 1
|
||||
LogLevel: 1
|
||||
NetworkConfig:
|
||||
ProtocolVersion: 0
|
||||
NetworkTransport: {fileID: 0}
|
||||
RegisteredScenes:
|
||||
- BuildTestScene
|
||||
AllowRuntimeSceneChanges: 0
|
||||
PlayerPrefab: {fileID: 0}
|
||||
NetworkPrefabs: []
|
||||
TickRate: 30
|
||||
ClientConnectionBufferTimeout: 10
|
||||
ConnectionApproval: 0
|
||||
ConnectionData:
|
||||
EnableTimeResync: 0
|
||||
TimeResyncInterval: 30
|
||||
EnableNetworkVariable: 1
|
||||
EnsureNetworkVariableLengthSafety: 0
|
||||
EnableSceneManagement: 1
|
||||
ForceSamePrefabs: 1
|
||||
RecycleNetworkIds: 1
|
||||
NetworkIdRecycleDelay: 120
|
||||
RpcHashSize: 0
|
||||
LoadSceneTimeOut: 120
|
||||
SpawnTimeout: 20
|
||||
EnableNetworkLogs: 1
|
||||
@@ -1,7 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d45c09a54b1da466ab6c385ee45fd3e4
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,42 +0,0 @@
|
||||
#if !MULTIPLAYER_TOOLS
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using NUnit.Framework;
|
||||
using UnityEditor;
|
||||
using UnityEditor.Build.Reporting;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Unity.Netcode.EditorTests
|
||||
{
|
||||
internal class BuildTests
|
||||
{
|
||||
public const string DefaultBuildScenePath = "Tests/Editor/Build/BuildTestScene.unity";
|
||||
|
||||
[Test]
|
||||
public void BasicBuildTest()
|
||||
{
|
||||
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);
|
||||
|
||||
if (buildTargetSupported)
|
||||
{
|
||||
var buildReport = BuildPipeline.BuildPlayer(
|
||||
new[] { Path.Combine(packagePath, DefaultBuildScenePath) },
|
||||
Path.Combine(Path.GetDirectoryName(Application.dataPath), "Builds", nameof(BuildTests)),
|
||||
buildTarget,
|
||||
BuildOptions.None
|
||||
);
|
||||
|
||||
Assert.AreEqual(BuildResult.Succeeded, buildReport.summary.result);
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Log($"Skipped building player due to Unsupported Build Target");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,11 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: efb549c2173d5478e93a71fbd05c0392
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,62 +0,0 @@
|
||||
using NUnit.Framework;
|
||||
using Unity.Collections;
|
||||
|
||||
namespace Unity.Netcode.EditorTests
|
||||
{
|
||||
internal class DisconnectMessageTests
|
||||
{
|
||||
[Test]
|
||||
public void EmptyDisconnectReason()
|
||||
{
|
||||
var networkContext = new NetworkContext();
|
||||
var writer = new FastBufferWriter(20, Allocator.Temp, 20);
|
||||
var msg = new DisconnectReasonMessage
|
||||
{
|
||||
Reason = string.Empty
|
||||
};
|
||||
msg.Serialize(writer, msg.Version);
|
||||
|
||||
var fbr = new FastBufferReader(writer, Allocator.Temp);
|
||||
var recvMsg = new DisconnectReasonMessage();
|
||||
recvMsg.Deserialize(fbr, ref networkContext, msg.Version);
|
||||
|
||||
Assert.IsEmpty(recvMsg.Reason);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DisconnectReason()
|
||||
{
|
||||
var networkContext = new NetworkContext();
|
||||
var writer = new FastBufferWriter(20, Allocator.Temp, 20);
|
||||
var msg = new DisconnectReasonMessage
|
||||
{
|
||||
Reason = "Foo"
|
||||
};
|
||||
msg.Serialize(writer, msg.Version);
|
||||
|
||||
var fbr = new FastBufferReader(writer, Allocator.Temp);
|
||||
var recvMsg = new DisconnectReasonMessage();
|
||||
recvMsg.Deserialize(fbr, ref networkContext, msg.Version);
|
||||
|
||||
Assert.AreEqual("Foo", recvMsg.Reason);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DisconnectReasonTooLong()
|
||||
{
|
||||
var networkContext = new NetworkContext();
|
||||
var writer = new FastBufferWriter(20, Allocator.Temp, 20);
|
||||
var msg = new DisconnectReasonMessage
|
||||
{
|
||||
Reason = "ThisStringIsWayLongerThanTwentyBytes"
|
||||
};
|
||||
msg.Serialize(writer, msg.Version);
|
||||
|
||||
var fbr = new FastBufferReader(writer, Allocator.Temp);
|
||||
var recvMsg = new DisconnectReasonMessage();
|
||||
recvMsg.Deserialize(fbr, ref networkContext, msg.Version);
|
||||
|
||||
Assert.IsEmpty(recvMsg.Reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 55a1355c62fe14a118253f8bbee7c3cf
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,361 +0,0 @@
|
||||
using System;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Unity.Netcode.EditorTests
|
||||
{
|
||||
internal class InterpolatorTests
|
||||
{
|
||||
private const float k_Precision = 0.00000001f;
|
||||
private const int k_MockTickRate = 1;
|
||||
|
||||
private NetworkTime T(float time, uint tickRate = k_MockTickRate)
|
||||
{
|
||||
return new NetworkTime(tickRate, timeSec: time);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TestReset()
|
||||
{
|
||||
var interpolator = new BufferedLinearInterpolatorFloat();
|
||||
|
||||
var serverTime = new NetworkTime(k_MockTickRate, 100f);
|
||||
interpolator.AddMeasurement(5, 1.0f);
|
||||
var initVal = interpolator.Update(10f, serverTime.Time, serverTime.TimeTicksAgo(1).Time); // big value
|
||||
Assert.That(initVal, Is.EqualTo(5f));
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(5f));
|
||||
|
||||
interpolator.ResetTo(100f, serverTime.Time);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(100f));
|
||||
var val = interpolator.Update(1f, serverTime.Time, serverTime.TimeTicksAgo(1).Time);
|
||||
Assert.That(val, Is.EqualTo(100f));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NormalUsage()
|
||||
{
|
||||
// Testing float instead of Vector3. The only difference with Vector3 is the lerp method used.
|
||||
var interpolator = new BufferedLinearInterpolatorFloat();
|
||||
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(0f));
|
||||
|
||||
interpolator.AddMeasurement(0f, 1.0f);
|
||||
interpolator.AddMeasurement(1f, 2.0f);
|
||||
|
||||
// too small update, nothing happens, doesn't consume from buffer yet
|
||||
var serverTime = new NetworkTime(k_MockTickRate, 0.01d); // t = 0.1d
|
||||
interpolator.Update(.01f, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(0f));
|
||||
|
||||
// consume first measurement, still can't interpolate with just one tick consumed
|
||||
serverTime += 1.0d; // t = 1.01
|
||||
interpolator.Update(1.0f, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(0f));
|
||||
|
||||
// consume second measurement, start to interpolate
|
||||
serverTime += 1.0d; // t = 2.01
|
||||
var valueFromUpdate = interpolator.Update(1.0f, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(0.01f).Within(k_Precision));
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(0.01f).Within(k_Precision)); // test a second time, to make sure the get doesn't update the value
|
||||
Assert.That(valueFromUpdate, Is.EqualTo(interpolator.GetInterpolatedValue()).Within(k_Precision));
|
||||
|
||||
// continue interpolation
|
||||
serverTime = new NetworkTime(k_MockTickRate, 2.5d); // t = 2.5d
|
||||
interpolator.Update(2.5f - 2.01f, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(0.5f).Within(k_Precision));
|
||||
|
||||
// check when reaching end
|
||||
serverTime += 0.5d; // t = 3
|
||||
interpolator.Update(0.5f, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(1f).Within(k_Precision));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Out of order or 'ACB' problem
|
||||
/// Given two measurements have already arrived A and C, if a new measurement B arrives, the interpolation shouldn't go to B, but continue
|
||||
/// to C.
|
||||
/// Adding B should be ignored if interpolation is already interpolating between A and C
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void OutOfOrderShouldStillWork()
|
||||
{
|
||||
var serverTime = new NetworkTime(k_MockTickRate, 0.01d);
|
||||
var interpolator = new BufferedLinearInterpolatorFloat();
|
||||
double timeStep = 0.5d;
|
||||
|
||||
interpolator.AddMeasurement(0f, 0d);
|
||||
interpolator.AddMeasurement(2f, 2d);
|
||||
|
||||
serverTime = new NetworkTime(k_MockTickRate, 1.5d);
|
||||
interpolator.Update(1.5f, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(0f).Within(k_Precision));
|
||||
|
||||
serverTime += timeStep; // t = 2.0
|
||||
interpolator.Update((float)timeStep, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(1f).Within(k_Precision));
|
||||
|
||||
serverTime += timeStep; // t = 2.5
|
||||
interpolator.Update((float)timeStep, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(1.5f).Within(k_Precision));
|
||||
|
||||
// makes sure that interpolation still continues in right direction
|
||||
interpolator.AddMeasurement(1, 1d);
|
||||
|
||||
serverTime += timeStep; // t = 3
|
||||
interpolator.Update((float)timeStep, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(2f).Within(k_Precision));
|
||||
}
|
||||
|
||||
[Ignore("TODO: Fix this test to still handle testing message loss without extrapolation")]
|
||||
[Test]
|
||||
public void MessageLoss()
|
||||
{
|
||||
var serverTime = new NetworkTime(k_MockTickRate, 0.01d);
|
||||
var interpolator = new BufferedLinearInterpolatorFloat();
|
||||
double timeStep = 0.5d;
|
||||
|
||||
interpolator.AddMeasurement(1f, 1d);
|
||||
interpolator.AddMeasurement(2f, 2d);
|
||||
// message time=3 was lost
|
||||
interpolator.AddMeasurement(4f, 4d);
|
||||
interpolator.AddMeasurement(5f, 5d);
|
||||
// message time=6 was lost
|
||||
interpolator.AddMeasurement(100f, 7d); // high value to produce a misprediction
|
||||
|
||||
// first value teleports interpolator
|
||||
serverTime = new NetworkTime(k_MockTickRate, 1d);
|
||||
interpolator.Update(1f, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(1f));
|
||||
|
||||
// nothing happens, not ready to consume second value yet
|
||||
serverTime += timeStep; // t = 1.5
|
||||
interpolator.Update((float)timeStep, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(1f));
|
||||
|
||||
// beginning of interpolation, second value consumed, currently at start
|
||||
serverTime += timeStep; // t = 2
|
||||
interpolator.Update((float)timeStep, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(1f));
|
||||
|
||||
// interpolation starts
|
||||
serverTime += timeStep; // t = 2.5
|
||||
interpolator.Update((float)timeStep, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(1.5f));
|
||||
|
||||
serverTime += timeStep; // t = 3
|
||||
interpolator.Update((float)timeStep, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(2f));
|
||||
|
||||
// extrapolating to 2.5
|
||||
serverTime += timeStep; // t = 3.5d
|
||||
interpolator.Update((float)timeStep, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(2.5f));
|
||||
|
||||
// next value skips to where it was supposed to be once buffer time is showing the next value
|
||||
serverTime += timeStep; // t = 4
|
||||
interpolator.Update((float)timeStep, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(3f));
|
||||
|
||||
// interpolation continues as expected
|
||||
serverTime += timeStep; // t = 4.5
|
||||
interpolator.Update((float)timeStep, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(3.5f));
|
||||
|
||||
serverTime += timeStep; // t = 5
|
||||
interpolator.Update((float)timeStep, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(4f));
|
||||
|
||||
// lost time=6, extrapolating
|
||||
serverTime += timeStep; // t = 5.5
|
||||
interpolator.Update((float)timeStep, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(4.5f));
|
||||
|
||||
serverTime += timeStep; // t = 6.0
|
||||
interpolator.Update((float)timeStep, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(5f));
|
||||
|
||||
// misprediction
|
||||
serverTime += timeStep; // t = 6.5
|
||||
interpolator.Update((float)timeStep, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.EqualTo(5.5f));
|
||||
|
||||
// lerp to right value
|
||||
serverTime += timeStep; // t = 7.0
|
||||
interpolator.Update((float)timeStep, serverTime);
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.GreaterThan(6.0f));
|
||||
Assert.That(interpolator.GetInterpolatedValue(), Is.LessThanOrEqualTo(100f));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AddFirstMeasurement()
|
||||
{
|
||||
var interpolator = new BufferedLinearInterpolatorFloat();
|
||||
|
||||
var serverTime = new NetworkTime(k_MockTickRate, 0d);
|
||||
interpolator.AddMeasurement(2f, 1d);
|
||||
interpolator.AddMeasurement(3f, 2d);
|
||||
|
||||
serverTime += 1d; // t = 1
|
||||
var interpolatedValue = interpolator.Update(1f, serverTime);
|
||||
// when consuming only one measurement and it's the first one consumed, teleport to it
|
||||
Assert.That(interpolatedValue, Is.EqualTo(2f));
|
||||
|
||||
// then interpolation should work as usual
|
||||
serverTime += 1d; // t = 2
|
||||
interpolatedValue = interpolator.Update(1f, serverTime);
|
||||
Assert.That(interpolatedValue, Is.EqualTo(2f));
|
||||
|
||||
serverTime += 0.5d; // t = 2.5
|
||||
interpolatedValue = interpolator.Update(0.5f, serverTime);
|
||||
Assert.That(interpolatedValue, Is.EqualTo(2.5f));
|
||||
|
||||
serverTime += 0.5d; // t = 3
|
||||
interpolatedValue = interpolator.Update(.5f, serverTime);
|
||||
Assert.That(interpolatedValue, Is.EqualTo(3f));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void JumpToEachValueIfDeltaTimeTooBig()
|
||||
{
|
||||
var interpolator = new BufferedLinearInterpolatorFloat();
|
||||
|
||||
var serverTime = new NetworkTime(k_MockTickRate, 0d);
|
||||
interpolator.AddMeasurement(2f, 1d);
|
||||
interpolator.AddMeasurement(3f, 2d);
|
||||
|
||||
serverTime += 1d; // t = 1
|
||||
var interpolatedValue = interpolator.Update(1f, serverTime);
|
||||
Assert.That(interpolatedValue, Is.EqualTo(2f));
|
||||
|
||||
// big deltaTime, jumping to latest value
|
||||
serverTime += 9f; // t = 10
|
||||
interpolatedValue = interpolator.Update(8f, serverTime);
|
||||
Assert.That(interpolatedValue, Is.EqualTo(3));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void JumpToLastValueFromStart()
|
||||
{
|
||||
var interpolator = new BufferedLinearInterpolatorFloat();
|
||||
|
||||
var serverTime = new NetworkTime(k_MockTickRate, 0d);
|
||||
|
||||
serverTime += 1d; // t = 1
|
||||
interpolator.AddMeasurement(1f, serverTime.Time);
|
||||
serverTime += 1d; // t = 2
|
||||
interpolator.AddMeasurement(2f, serverTime.Time);
|
||||
serverTime += 1d; // t = 3
|
||||
interpolator.AddMeasurement(3f, serverTime.Time);
|
||||
|
||||
// big time jump
|
||||
serverTime += 7d; // t = 10
|
||||
var interpolatedValue = interpolator.Update(10f, serverTime);
|
||||
Assert.That(interpolatedValue, Is.EqualTo(3f));
|
||||
|
||||
// interpolation continues as normal
|
||||
serverTime = new NetworkTime(k_MockTickRate, 11d); // t = 11
|
||||
interpolator.AddMeasurement(11f, serverTime.Time); // out of order
|
||||
|
||||
serverTime = new NetworkTime(k_MockTickRate, 10.5d); // t = 10.5
|
||||
interpolatedValue = interpolator.Update(0.5f, serverTime);
|
||||
Assert.That(interpolatedValue, Is.EqualTo(3f));
|
||||
|
||||
serverTime += 0.5d; // t = 11
|
||||
interpolatedValue = interpolator.Update(0.5f, serverTime);
|
||||
Assert.That(interpolatedValue, Is.EqualTo(10f));
|
||||
|
||||
serverTime += 0.5d; // t = 11.5
|
||||
interpolatedValue = interpolator.Update(0.5f, serverTime);
|
||||
Assert.That(interpolatedValue, Is.EqualTo(10.5f));
|
||||
|
||||
serverTime += 0.5d; // t = 12
|
||||
interpolatedValue = interpolator.Update(0.5f, serverTime);
|
||||
Assert.That(interpolatedValue, Is.EqualTo(11f));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TestBufferSizeLimit()
|
||||
{
|
||||
var interpolator = new BufferedLinearInterpolatorFloat();
|
||||
|
||||
// set first value
|
||||
var serverTime = new NetworkTime(k_MockTickRate, 0d);
|
||||
serverTime += 1.0d; // t = 1
|
||||
interpolator.AddMeasurement(-1f, serverTime.Time);
|
||||
interpolator.Update(1f, serverTime);
|
||||
|
||||
// max + 1
|
||||
serverTime += 1.0d; // t = 2
|
||||
interpolator.AddMeasurement(2, serverTime.Time); // +1, this should trigger a burst and teleport to last value
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
interpolator.AddMeasurement(i + 3, i + 3d);
|
||||
}
|
||||
|
||||
// client was paused for a while, some time has past, we just got a burst of values from the server that teleported us to the last value received
|
||||
serverTime = new NetworkTime(k_MockTickRate, 102d);
|
||||
var interpolatedValue = interpolator.Update(101f, serverTime);
|
||||
Assert.That(interpolatedValue, Is.EqualTo(102));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TestUpdatingInterpolatorWithNoData()
|
||||
{
|
||||
var interpolator = new BufferedLinearInterpolatorFloat();
|
||||
var serverTime = new NetworkTime(k_MockTickRate, 0.0d);
|
||||
// invalid case, this is undefined behaviour
|
||||
Assert.Throws<InvalidOperationException>(() => interpolator.Update(1f, serverTime));
|
||||
}
|
||||
|
||||
[Ignore("TODO: Fix this test to still test duplicated values without extrapolation")]
|
||||
[Test]
|
||||
public void TestDuplicatedValues()
|
||||
{
|
||||
var interpolator = new BufferedLinearInterpolatorFloat();
|
||||
|
||||
var serverTime = new NetworkTime(k_MockTickRate, 0.0d);
|
||||
|
||||
serverTime += 1d; // t = 1
|
||||
interpolator.AddMeasurement(1f, serverTime.Time);
|
||||
serverTime += 1d; // t = 2
|
||||
interpolator.AddMeasurement(2f, serverTime.Time);
|
||||
interpolator.AddMeasurement(2f, serverTime.Time);
|
||||
|
||||
// empty interpolator teleports to initial value
|
||||
serverTime = new NetworkTime(k_MockTickRate, 0.0d);
|
||||
serverTime += 1d; // t = 1
|
||||
var interp = interpolator.Update(1f, serverTime);
|
||||
Assert.That(interp, Is.EqualTo(1f));
|
||||
|
||||
// consume value, start interp, currently at start value
|
||||
serverTime += 1d; // t = 2
|
||||
interp = interpolator.Update(1f, serverTime);
|
||||
Assert.That(interp, Is.EqualTo(1f));
|
||||
|
||||
// interp
|
||||
serverTime += 0.5d; // t = 2.5
|
||||
interp = interpolator.Update(0.5f, serverTime);
|
||||
Assert.That(interp, Is.EqualTo(1.5f));
|
||||
|
||||
// reach end
|
||||
serverTime += 0.5d; // t = 3
|
||||
interp = interpolator.Update(0.5f, serverTime);
|
||||
Assert.That(interp, Is.EqualTo(2f));
|
||||
|
||||
// with unclamped interpolation, we continue mispredicting since the two last values are actually treated as the same. Therefore we're not stopping at "2"
|
||||
serverTime += 0.5d; // t = 3.5
|
||||
interp = interpolator.Update(0.5f, serverTime);
|
||||
Assert.That(interp, Is.EqualTo(2.5f));
|
||||
|
||||
serverTime += 0.5d; // t = 4
|
||||
interp = interpolator.Update(0.5f, serverTime);
|
||||
Assert.That(interp, Is.EqualTo(3f));
|
||||
|
||||
// we add a measurement with an updated time
|
||||
var pastServerTime = new NetworkTime(k_MockTickRate, 3.0d);
|
||||
interpolator.AddMeasurement(2f, pastServerTime.Time);
|
||||
|
||||
interp = interpolator.Update(0.5f, serverTime);
|
||||
Assert.That(interp, Is.EqualTo(2f));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a5cfbc170161c4e95ac6124ee43068b6
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -1,3 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 55531000b0344935b665541f089df60e
|
||||
timeCreated: 1630354914
|
||||
@@ -1,92 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace Unity.Netcode.EditorTests
|
||||
{
|
||||
internal class DisconnectOnSendTests
|
||||
{
|
||||
private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy
|
||||
{
|
||||
public void Serialize(FastBufferWriter writer, int targetVersion)
|
||||
{
|
||||
}
|
||||
|
||||
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Handle(ref NetworkContext context)
|
||||
{
|
||||
}
|
||||
|
||||
public int Version => 0;
|
||||
}
|
||||
|
||||
private class DisconnectOnSendMessageSender : INetworkMessageSender
|
||||
{
|
||||
public NetworkMessageManager MessageManager;
|
||||
|
||||
public void Send(ulong clientId, NetworkDelivery delivery, FastBufferWriter batchData)
|
||||
{
|
||||
MessageManager.ClientDisconnected(clientId);
|
||||
}
|
||||
}
|
||||
|
||||
private class TestMessageProvider : INetworkMessageProvider
|
||||
{
|
||||
// Keep track of what we sent
|
||||
private List<NetworkMessageManager.MessageWithHandler> m_MessageList = new List<NetworkMessageManager.MessageWithHandler>
|
||||
{
|
||||
new NetworkMessageManager.MessageWithHandler
|
||||
{
|
||||
MessageType = typeof(TestMessage),
|
||||
Handler = NetworkMessageManager.ReceiveMessage<TestMessage>,
|
||||
GetVersion = NetworkMessageManager.CreateMessageAndGetVersion<TestMessage>
|
||||
}
|
||||
};
|
||||
|
||||
public List<NetworkMessageManager.MessageWithHandler> GetMessages()
|
||||
{
|
||||
return m_MessageList;
|
||||
}
|
||||
}
|
||||
|
||||
private TestMessageProvider m_TestMessageProvider;
|
||||
private DisconnectOnSendMessageSender m_MessageSender;
|
||||
private NetworkMessageManager m_MessageManager;
|
||||
private ulong[] m_Clients = { 0 };
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
m_MessageSender = new DisconnectOnSendMessageSender();
|
||||
m_TestMessageProvider = new TestMessageProvider();
|
||||
m_MessageManager = new NetworkMessageManager(m_MessageSender, this, m_TestMessageProvider);
|
||||
m_MessageSender.MessageManager = m_MessageManager;
|
||||
m_MessageManager.ClientConnected(0);
|
||||
m_MessageManager.SetVersion(0, XXHash.Hash32(typeof(TestMessage).FullName), 0);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
m_MessageManager.Dispose();
|
||||
}
|
||||
|
||||
private TestMessage GetMessage()
|
||||
{
|
||||
return new TestMessage();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WhenDisconnectIsCalledDuringSend_NoErrorsOccur()
|
||||
{
|
||||
var message = GetMessage();
|
||||
m_MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, m_Clients);
|
||||
|
||||
// This is where an exception would be thrown and logged.
|
||||
m_MessageManager.ProcessSendQueues();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7984df99de5c4b85a1b8567582d00c64
|
||||
timeCreated: 1680888331
|
||||
@@ -1,203 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.RegularExpressions;
|
||||
using NUnit.Framework;
|
||||
using NUnit.Framework.Internal;
|
||||
using Unity.Collections;
|
||||
using Unity.Collections.LowLevel.Unsafe;
|
||||
using UnityEngine;
|
||||
using UnityEngine.TestTools;
|
||||
|
||||
namespace Unity.Netcode.EditorTests
|
||||
{
|
||||
internal class MessageCorruptionTests
|
||||
{
|
||||
|
||||
private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy
|
||||
{
|
||||
public ForceNetworkSerializeByMemcpy<Guid> Value;
|
||||
public static bool Handled;
|
||||
public static bool Deserialized;
|
||||
|
||||
public void Serialize(FastBufferWriter writer, int targetVersion)
|
||||
{
|
||||
writer.WriteValueSafe(Value);
|
||||
}
|
||||
|
||||
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
|
||||
{
|
||||
Deserialized = true;
|
||||
reader.ReadValueSafe(out Value);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Handle(ref NetworkContext context)
|
||||
{
|
||||
Handled = true;
|
||||
}
|
||||
|
||||
public int Version => 0;
|
||||
}
|
||||
|
||||
private class TestMessageProvider : INetworkMessageProvider
|
||||
{
|
||||
public List<NetworkMessageManager.MessageWithHandler> GetMessages()
|
||||
{
|
||||
return new List<NetworkMessageManager.MessageWithHandler>
|
||||
{
|
||||
new NetworkMessageManager.MessageWithHandler
|
||||
{
|
||||
MessageType = typeof(TestMessage),
|
||||
Handler = NetworkMessageManager.ReceiveMessage<TestMessage>,
|
||||
GetVersion = NetworkMessageManager.CreateMessageAndGetVersion<TestMessage>
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public enum TypeOfCorruption
|
||||
{
|
||||
OffsetPlus,
|
||||
OffsetMinus,
|
||||
CorruptBytes,
|
||||
Truncated,
|
||||
AdditionalGarbageData,
|
||||
}
|
||||
|
||||
private class TestMessageSender : INetworkMessageSender
|
||||
{
|
||||
|
||||
public TypeOfCorruption Corruption;
|
||||
public List<byte[]> MessageQueue = new List<byte[]>();
|
||||
|
||||
public unsafe void Send(ulong clientId, NetworkDelivery delivery, FastBufferWriter batchData)
|
||||
{
|
||||
switch (Corruption)
|
||||
{
|
||||
case TypeOfCorruption.OffsetPlus:
|
||||
{
|
||||
using var subWriter = new FastBufferWriter(batchData.Length + 1, Allocator.Temp);
|
||||
subWriter.WriteByteSafe(0);
|
||||
subWriter.WriteBytesSafe(batchData.GetUnsafePtr(), batchData.Length);
|
||||
MessageQueue.Add(subWriter.ToArray());
|
||||
break;
|
||||
}
|
||||
case TypeOfCorruption.OffsetMinus:
|
||||
{
|
||||
using var subWriter = new FastBufferWriter(batchData.Length - 1, Allocator.Temp);
|
||||
subWriter.WriteBytesSafe(batchData.GetUnsafePtr() + 1, batchData.Length - 1);
|
||||
MessageQueue.Add(subWriter.ToArray());
|
||||
break;
|
||||
}
|
||||
case TypeOfCorruption.CorruptBytes:
|
||||
batchData.Seek(batchData.Length - 2);
|
||||
var currentByte = batchData.GetUnsafePtr()[0];
|
||||
batchData.WriteByteSafe((byte)(currentByte == 0 ? 1 : 0));
|
||||
MessageQueue.Add(batchData.ToArray());
|
||||
break;
|
||||
case TypeOfCorruption.Truncated:
|
||||
batchData.Truncate(batchData.Length - 1);
|
||||
MessageQueue.Add(batchData.ToArray());
|
||||
break;
|
||||
case TypeOfCorruption.AdditionalGarbageData:
|
||||
batchData.Seek(batchData.Length);
|
||||
batchData.WriteByteSafe(0);
|
||||
MessageQueue.Add(batchData.ToArray());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private NetworkMessageManager m_MessageManager;
|
||||
private TestMessageSender m_MessageSender;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
TestMessage.Handled = false;
|
||||
TestMessage.Deserialized = false;
|
||||
m_MessageSender = new TestMessageSender();
|
||||
|
||||
m_MessageManager = new NetworkMessageManager(m_MessageSender, this, new TestMessageProvider());
|
||||
|
||||
m_MessageManager.ClientConnected(0);
|
||||
m_MessageManager.SetVersion(0, XXHash.Hash32(typeof(TestMessage).FullName), 0);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
m_MessageManager.Dispose();
|
||||
}
|
||||
|
||||
private TestMessage GetMessage()
|
||||
{
|
||||
return new TestMessage
|
||||
{
|
||||
Value = Guid.NewGuid()
|
||||
};
|
||||
}
|
||||
|
||||
[Test]
|
||||
public unsafe void WhenPacketsAreCorrupted_TheyDontGetProcessed([Values] TypeOfCorruption typeOfCorruption)
|
||||
{
|
||||
m_MessageSender.Corruption = typeOfCorruption;
|
||||
|
||||
switch (typeOfCorruption)
|
||||
{
|
||||
case TypeOfCorruption.OffsetMinus:
|
||||
case TypeOfCorruption.OffsetPlus:
|
||||
LogAssert.Expect(LogType.Error, new Regex("Received a packet with an invalid Magic Value\\."));
|
||||
break;
|
||||
case TypeOfCorruption.Truncated:
|
||||
case TypeOfCorruption.AdditionalGarbageData:
|
||||
LogAssert.Expect(LogType.Error, new Regex("Received a packet with an invalid Batch Size Value\\."));
|
||||
break;
|
||||
case TypeOfCorruption.CorruptBytes:
|
||||
LogAssert.Expect(LogType.Error, new Regex("Received a packet with an invalid Hash Value\\."));
|
||||
break;
|
||||
}
|
||||
|
||||
// Dummy batch header
|
||||
var batchHeader = new NetworkBatchHeader
|
||||
{
|
||||
BatchCount = 1
|
||||
};
|
||||
var messageHeader = new NetworkMessageHeader
|
||||
{
|
||||
MessageSize = (ushort)UnsafeUtility.SizeOf<TestMessage>(),
|
||||
MessageType = m_MessageManager.GetMessageType(typeof(TestMessage)),
|
||||
};
|
||||
var message = GetMessage();
|
||||
|
||||
var writer = new FastBufferWriter(1300, Allocator.Temp);
|
||||
using (writer)
|
||||
{
|
||||
writer.TryBeginWrite(FastBufferWriter.GetWriteSize(batchHeader) +
|
||||
FastBufferWriter.GetWriteSize(messageHeader) +
|
||||
FastBufferWriter.GetWriteSize(message));
|
||||
writer.WriteValue(batchHeader);
|
||||
writer.WriteValue(messageHeader);
|
||||
writer.WriteValue(message);
|
||||
|
||||
// Fill out the rest of the batch header
|
||||
writer.Seek(0);
|
||||
batchHeader = new NetworkBatchHeader
|
||||
{
|
||||
Magic = NetworkBatchHeader.MagicValue,
|
||||
BatchSize = writer.Length,
|
||||
BatchHash = XXHash.Hash64(writer.GetUnsafePtr() + sizeof(NetworkBatchHeader), writer.Length - sizeof(NetworkBatchHeader)),
|
||||
BatchCount = 1
|
||||
};
|
||||
writer.WriteValue(batchHeader);
|
||||
m_MessageSender.Send(0, NetworkDelivery.Reliable, writer);
|
||||
|
||||
var receivedMessage = m_MessageSender.MessageQueue[0];
|
||||
m_MessageSender.MessageQueue.Clear();
|
||||
m_MessageManager.HandleIncomingData(0, new ArraySegment<byte>(receivedMessage), 0);
|
||||
Assert.IsFalse(TestMessage.Deserialized);
|
||||
Assert.IsFalse(TestMessage.Handled);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d3c01a0b5a0e478ebc5182fe339bde04
|
||||
timeCreated: 1676997550
|
||||
@@ -1,263 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using NUnit.Framework;
|
||||
using NUnit.Framework.Internal;
|
||||
using Unity.Collections;
|
||||
using Unity.Collections.LowLevel.Unsafe;
|
||||
|
||||
namespace Unity.Netcode.EditorTests
|
||||
{
|
||||
internal class MessageReceivingTests
|
||||
{
|
||||
private struct TestMessage : INetworkMessage, INetworkSerializeByMemcpy
|
||||
{
|
||||
public int A;
|
||||
public int B;
|
||||
public int C;
|
||||
public static bool Deserialized;
|
||||
public static bool Handled;
|
||||
public static List<TestMessage> DeserializedValues = new List<TestMessage>();
|
||||
|
||||
public void Serialize(FastBufferWriter writer, int targetVersion)
|
||||
{
|
||||
writer.WriteValueSafe(this);
|
||||
}
|
||||
|
||||
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
|
||||
{
|
||||
Deserialized = true;
|
||||
reader.ReadValueSafe(out this);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Handle(ref NetworkContext context)
|
||||
{
|
||||
Handled = true;
|
||||
DeserializedValues.Add(this);
|
||||
}
|
||||
|
||||
public int Version => 0;
|
||||
}
|
||||
|
||||
private class TestMessageProvider : INetworkMessageProvider
|
||||
{
|
||||
public List<NetworkMessageManager.MessageWithHandler> GetMessages()
|
||||
{
|
||||
return new List<NetworkMessageManager.MessageWithHandler>
|
||||
{
|
||||
new NetworkMessageManager.MessageWithHandler
|
||||
{
|
||||
MessageType = typeof(TestMessage),
|
||||
Handler = NetworkMessageManager.ReceiveMessage<TestMessage>,
|
||||
GetVersion = NetworkMessageManager.CreateMessageAndGetVersion<TestMessage>
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private NetworkMessageManager m_MessageManager;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
TestMessage.Deserialized = false;
|
||||
TestMessage.Handled = false;
|
||||
TestMessage.DeserializedValues.Clear();
|
||||
|
||||
m_MessageManager = new NetworkMessageManager(new NopMessageSender(), this, new TestMessageProvider());
|
||||
m_MessageManager.SetVersion(0, XXHash.Hash32(typeof(TestMessage).FullName), 0);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
m_MessageManager.Dispose();
|
||||
}
|
||||
|
||||
private TestMessage GetMessage()
|
||||
{
|
||||
var random = new Random();
|
||||
return new TestMessage
|
||||
{
|
||||
A = random.Next(),
|
||||
B = random.Next(),
|
||||
C = random.Next(),
|
||||
};
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WhenHandlingAMessage_ReceiveMethodIsCalled()
|
||||
{
|
||||
var messageHeader = new NetworkMessageHeader
|
||||
{
|
||||
MessageSize = (ushort)UnsafeUtility.SizeOf<TestMessage>(),
|
||||
MessageType = m_MessageManager.GetMessageType(typeof(TestMessage)),
|
||||
};
|
||||
var message = GetMessage();
|
||||
|
||||
var writer = new FastBufferWriter(1300, Allocator.Temp);
|
||||
using (writer)
|
||||
{
|
||||
writer.TryBeginWrite(FastBufferWriter.GetWriteSize(message));
|
||||
writer.WriteValue(message);
|
||||
|
||||
var reader = new FastBufferReader(writer, Allocator.Temp);
|
||||
using (reader)
|
||||
{
|
||||
m_MessageManager.HandleMessage(messageHeader, reader, 0, 0, 0);
|
||||
Assert.IsTrue(TestMessage.Deserialized);
|
||||
Assert.IsTrue(TestMessage.Handled);
|
||||
Assert.AreEqual(1, TestMessage.DeserializedValues.Count);
|
||||
Assert.AreEqual(message, TestMessage.DeserializedValues[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public unsafe void WhenHandlingIncomingData_ReceiveIsNotCalledBeforeProcessingIncomingMessageQueue()
|
||||
{
|
||||
var batchHeader = new NetworkBatchHeader
|
||||
{
|
||||
BatchCount = 1
|
||||
};
|
||||
var messageHeader = new NetworkMessageHeader
|
||||
{
|
||||
MessageSize = (ushort)UnsafeUtility.SizeOf<TestMessage>(),
|
||||
MessageType = m_MessageManager.GetMessageType(typeof(TestMessage)),
|
||||
};
|
||||
var message = GetMessage();
|
||||
|
||||
var writer = new FastBufferWriter(1300, Allocator.Temp);
|
||||
using (writer)
|
||||
{
|
||||
writer.TryBeginWrite(FastBufferWriter.GetWriteSize(batchHeader) +
|
||||
FastBufferWriter.GetWriteSize(messageHeader) +
|
||||
FastBufferWriter.GetWriteSize(message));
|
||||
writer.WriteValue(batchHeader);
|
||||
writer.WriteValue(messageHeader);
|
||||
writer.WriteValue(message);
|
||||
|
||||
// Fill out the rest of the batch header
|
||||
writer.Seek(0);
|
||||
batchHeader = new NetworkBatchHeader
|
||||
{
|
||||
Magic = NetworkBatchHeader.MagicValue,
|
||||
BatchSize = writer.Length,
|
||||
BatchHash = XXHash.Hash64(writer.GetUnsafePtr() + sizeof(NetworkBatchHeader), writer.Length - sizeof(NetworkBatchHeader)),
|
||||
BatchCount = 1
|
||||
};
|
||||
writer.WriteValue(batchHeader);
|
||||
|
||||
var reader = new FastBufferReader(writer, Allocator.Temp);
|
||||
using (reader)
|
||||
{
|
||||
m_MessageManager.HandleIncomingData(0, new ArraySegment<byte>(writer.ToArray()), 0);
|
||||
Assert.IsFalse(TestMessage.Deserialized);
|
||||
Assert.IsFalse(TestMessage.Handled);
|
||||
Assert.IsEmpty(TestMessage.DeserializedValues);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public unsafe void WhenReceivingAMessageAndProcessingMessageQueue_ReceiveMethodIsCalled()
|
||||
{
|
||||
var batchHeader = new NetworkBatchHeader
|
||||
{
|
||||
BatchCount = 1
|
||||
};
|
||||
var messageHeader = new NetworkMessageHeader
|
||||
{
|
||||
MessageSize = (uint)UnsafeUtility.SizeOf<TestMessage>(),
|
||||
MessageType = m_MessageManager.GetMessageType(typeof(TestMessage)),
|
||||
};
|
||||
var message = GetMessage();
|
||||
|
||||
var writer = new FastBufferWriter(1300, Allocator.Temp);
|
||||
using (writer)
|
||||
{
|
||||
writer.WriteValueSafe(batchHeader);
|
||||
BytePacker.WriteValueBitPacked(writer, messageHeader.MessageType);
|
||||
BytePacker.WriteValueBitPacked(writer, messageHeader.MessageSize);
|
||||
writer.WriteValueSafe(message);
|
||||
|
||||
// Fill out the rest of the batch header
|
||||
writer.Seek(0);
|
||||
batchHeader = new NetworkBatchHeader
|
||||
{
|
||||
Magic = NetworkBatchHeader.MagicValue,
|
||||
BatchSize = writer.Length,
|
||||
BatchHash = XXHash.Hash64(writer.GetUnsafePtr() + sizeof(NetworkBatchHeader), writer.Length - sizeof(NetworkBatchHeader)),
|
||||
BatchCount = 1
|
||||
};
|
||||
writer.WriteValue(batchHeader);
|
||||
|
||||
var reader = new FastBufferReader(writer, Allocator.Temp);
|
||||
using (reader)
|
||||
{
|
||||
m_MessageManager.HandleIncomingData(0, new ArraySegment<byte>(writer.ToArray()), 0);
|
||||
m_MessageManager.ProcessIncomingMessageQueue();
|
||||
Assert.IsTrue(TestMessage.Deserialized);
|
||||
Assert.IsTrue(TestMessage.Handled);
|
||||
Assert.AreEqual(1, TestMessage.DeserializedValues.Count);
|
||||
Assert.AreEqual(message, TestMessage.DeserializedValues[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public unsafe void WhenReceivingMultipleMessagesAndProcessingMessageQueue_ReceiveMethodIsCalledMultipleTimes()
|
||||
{
|
||||
var batchHeader = new NetworkBatchHeader
|
||||
{
|
||||
BatchCount = 2
|
||||
};
|
||||
var messageHeader = new NetworkMessageHeader
|
||||
{
|
||||
MessageSize = (ushort)UnsafeUtility.SizeOf<TestMessage>(),
|
||||
MessageType = m_MessageManager.GetMessageType(typeof(TestMessage)),
|
||||
};
|
||||
var message = GetMessage();
|
||||
var message2 = GetMessage();
|
||||
|
||||
var writer = new FastBufferWriter(1300, Allocator.Temp);
|
||||
using (writer)
|
||||
{
|
||||
writer.WriteValueSafe(batchHeader);
|
||||
BytePacker.WriteValueBitPacked(writer, messageHeader.MessageType);
|
||||
BytePacker.WriteValueBitPacked(writer, messageHeader.MessageSize);
|
||||
writer.WriteValueSafe(message);
|
||||
BytePacker.WriteValueBitPacked(writer, messageHeader.MessageType);
|
||||
BytePacker.WriteValueBitPacked(writer, messageHeader.MessageSize);
|
||||
writer.WriteValueSafe(message2);
|
||||
|
||||
// Fill out the rest of the batch header
|
||||
writer.Seek(0);
|
||||
batchHeader = new NetworkBatchHeader
|
||||
{
|
||||
Magic = NetworkBatchHeader.MagicValue,
|
||||
BatchSize = writer.Length,
|
||||
BatchHash = XXHash.Hash64(writer.GetUnsafePtr() + sizeof(NetworkBatchHeader), writer.Length - sizeof(NetworkBatchHeader)),
|
||||
BatchCount = 2
|
||||
};
|
||||
writer.WriteValue(batchHeader);
|
||||
|
||||
var reader = new FastBufferReader(writer, Allocator.Temp);
|
||||
using (reader)
|
||||
{
|
||||
m_MessageManager.HandleIncomingData(0, new ArraySegment<byte>(writer.ToArray()), 0);
|
||||
Assert.IsFalse(TestMessage.Deserialized);
|
||||
Assert.IsFalse(TestMessage.Handled);
|
||||
Assert.IsEmpty(TestMessage.DeserializedValues);
|
||||
|
||||
m_MessageManager.ProcessIncomingMessageQueue();
|
||||
Assert.IsTrue(TestMessage.Deserialized);
|
||||
Assert.IsTrue(TestMessage.Handled);
|
||||
Assert.AreEqual(2, TestMessage.DeserializedValues.Count);
|
||||
Assert.AreEqual(message, TestMessage.DeserializedValues[0]);
|
||||
Assert.AreEqual(message2, TestMessage.DeserializedValues[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user