Compare commits
12 Commits
2.0.0-exp.
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| fe746bf2a3 | |||
|
|
8fe07bbad2 | ||
| 2e3ccb45b7 | |||
| 76d8157fc7 | |||
| 11e10acc00 | |||
| 887ec37b67 | |||
|
|
016788c21e | ||
|
|
48c6a6121c | ||
|
|
eab996f3ac | ||
|
|
a813ba0dd6 | ||
|
|
c813386c5c | ||
|
|
ed38a4dcc2 |
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"}
|
||||
183
CHANGELOG.md
183
CHANGELOG.md
@@ -6,12 +6,191 @@ 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
|
||||
- Added: `UnityTransport.GetNetworkDriver` and `UnityTransport.GetLocalEndpoint` methods to expose the driver and local endpoint being used. (#2978)
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed issue where deferred despawn was causing GC allocations when converting an `IEnumerable` to a list. (#2983)
|
||||
- Fixed issue where the realtime network stats monitor was not able to display RPC traffic in release builds due to those stats being only available in development builds or the editor. (#2979)
|
||||
- Fixed issue where `NetworkManager.ScenesLoaded` was not being updated if `PostSynchronizationSceneUnloading` was set and any loaded scenes not used during synchronization were unloaded. (#2971)
|
||||
- Fixed issue where `Rigidbody2d` under Unity 6000.0.11f1 has breaking changes where `velocity` is now `linearVelocity` and `isKinematic` is replaced by `bodyType`. (#2971)
|
||||
- Fixed issue where `NetworkSpawnManager.InstantiateAndSpawn` and `NetworkObject.InstantiateAndSpawn` were not honoring the ownerClientId parameter when using a client-server network topology. (#2968)
|
||||
- Fixed issue where internal delta serialization could not have a byte serializer defined when serializing deltas for other types. Added `[GenerateSerializationForType(typeof(byte))]` to both the `NetworkVariable` and `AnticipatedNetworkVariable` classes to assure a byte serializer is defined.(#2962)
|
||||
- Fixed issue when scene management was disabled and the session owner would still try to synchronize a late joining client. (#2962)
|
||||
- Fixed issue when using a distributed authority network topology where it would allow a session owner to spawn a `NetworkObject` prior to being approved. Now, an error message is logged and the `NetworkObject` will not be spawned prior to the client being approved. (#2962)
|
||||
- Fixed issue where attempting to spawn during `NetworkBehaviour.OnInSceneObjectsSpawned` and `NetworkBehaviour.OnNetworkSessionSynchronized` notifications would throw a collection modified exception. (#2962)
|
||||
|
||||
### Changed
|
||||
|
||||
- Changed logic where clients can now set the `NetworkSceneManager` client synchronization mode when using a distributed authority network topology. (#2985)
|
||||
|
||||
|
||||
## [2.0.0-pre.2] - 2024-06-17
|
||||
|
||||
### Added
|
||||
|
||||
- Added `AnticipatedNetworkVariable<T>`, which adds support for client anticipation of `NetworkVariable` values, allowing for more responsive gameplay. (#2957)
|
||||
- Added `AnticipatedNetworkTransform`, which adds support for client anticipation of NetworkTransforms. (#2957)
|
||||
- Added `NetworkVariableBase.ExceedsDirtinessThreshold` to allow network variables to throttle updates by only sending updates when the difference between the current and previous values exceeds a threshold. (This is exposed in `NetworkVariable<T>` with the callback `NetworkVariable<T>.CheckExceedsDirtinessThreshold`). (#2957)
|
||||
- Added `NetworkVariableUpdateTraits`, which add additional throttling support: `MinSecondsBetweenUpdates` will prevent the `NetworkVariable` from sending updates more often than the specified time period (even if it exceeds the dirtiness threshold), while `MaxSecondsBetweenUpdates` will force a dirty `NetworkVariable` to send an update after the specified time period even if it has not yet exceeded the dirtiness threshold. (#2957)
|
||||
- Added virtual method `NetworkVariableBase.OnInitialize` which can be used by `NetworkVariable` subclasses to add initialization code. (#2957)
|
||||
- Added `NetworkTime.TickWithPartial`, which represents the current tick as a double that includes the fractional/partial tick value. (#2957)
|
||||
- Added `NetworkTickSystem.AnticipationTick`, which can be helpful with implementation of client anticipation. This value represents the tick the current local client was at at the beginning of the most recent network round trip, which enables it to correlate server update ticks with the client tick that may have triggered them. (#2957)
|
||||
- Added event `NetworkManager.OnSessionOwnerPromoted` that is invoked when a new session owner promotion occurs. (#2948)
|
||||
- Added `NetworkRigidBodyBase.GetLinearVelocity` and `NetworkRigidBodyBase.SetLinearVelocity` convenience/helper methods. (#2948)
|
||||
- Added `NetworkRigidBodyBase.GetAngularVelocity` and `NetworkRigidBodyBase.SetAngularVelocity` convenience/helper methods. (#2948)
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed issue when `NetworkTransform` half float precision is enabled and ownership changes the current base position was not being synchronized. (#2948)
|
||||
- Fixed issue where `OnClientConnected` not being invoked on the session owner when connecting to a new distributed authority session. (#2948)
|
||||
- Fixed issue where Rigidbody micro-motion (i.e. relatively small velocities) would result in non-authority instances slightly stuttering as the body would come to a rest (i.e. no motion). Now, the threshold value can increase at higher velocities and can decrease slightly below the provided threshold to account for this. (#2948)
|
||||
|
||||
### Changed
|
||||
|
||||
- Changed `NetworkAnimator` no longer requires the `Animator` component to exist on the same `GameObject`. (#2957)
|
||||
- Changed `NetworkObjectReference` and `NetworkBehaviourReference` to allow null references when constructing and serializing. (#2957)
|
||||
- Changed the client's owned objects is now returned (`NetworkClient` and `NetworkSpawnManager`) as an array as opposed to a list for performance purposes. (#2948)
|
||||
- Changed `NetworkTransfrom.TryCommitTransformToServer` to be internal as it will be removed by the final 2.0.0 release. (#2948)
|
||||
- Changed `NetworkTransformEditor.OnEnable` to a virtual method to be able to customize a `NetworkTransform` derived class by creating a derived editor control from `NetworkTransformEditor`. (#2948)
|
||||
|
||||
|
||||
## [2.0.0-exp.5] - 2024-06-03
|
||||
|
||||
### Added
|
||||
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed issue where SessionOwner message was being treated as a new entry for the new message indexing when it should have been ordinally sorted with the legacy message indices. (#2942)
|
||||
|
||||
### Changed
|
||||
- Changed `FastBufferReader` and `FastBufferWriter` so that they always ensure the length of items serialized is always serialized as an `uint` and added a check before casting for safe reading and writing.(#2946)
|
||||
|
||||
|
||||
## [2.0.0-exp.4] - 2024-05-31
|
||||
|
||||
### Added
|
||||
@@ -176,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)
|
||||
@@ -188,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
|
||||
@@ -295,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)
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8b267eb841a574dc083ac248a95d4443
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -409,6 +409,7 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
}
|
||||
else
|
||||
{
|
||||
m_Diagnostics.AddError($"{type}: Managed type in NetworkVariable must implement IEquatable<{type}>");
|
||||
equalityMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef);
|
||||
}
|
||||
|
||||
@@ -721,7 +722,7 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
continue;
|
||||
}
|
||||
|
||||
if (networkVariableSerializationTypesTypeDef == null && netcodeTypeDef.Name == nameof(NetworkVariableSerializationTypes))
|
||||
if (networkVariableSerializationTypesTypeDef == null && netcodeTypeDef.Name == nameof(NetworkVariableSerializationTypedInitializers))
|
||||
{
|
||||
networkVariableSerializationTypesTypeDef = netcodeTypeDef;
|
||||
continue;
|
||||
@@ -1007,103 +1008,103 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
|
||||
switch (method.Name)
|
||||
{
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedByMemcpy):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpy_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpyArray):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedByMemcpyArray):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpyArray_MethodRef = method;
|
||||
break;
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpyList):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedByMemcpyList):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpyList_MethodRef = method;
|
||||
break;
|
||||
#endif
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedINetworkSerializable):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedINetworkSerializable):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializable_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedINetworkSerializableArray):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedINetworkSerializableArray):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializableArray_MethodRef = method;
|
||||
break;
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedINetworkSerializableList):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedINetworkSerializableList):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializableList_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_NativeHashSet):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_NativeHashSet):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashSet_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_NativeHashMap):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_NativeHashMap):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashMap_MethodRef = method;
|
||||
break;
|
||||
#endif
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_List):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_List):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_List_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_HashSet):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_HashSet):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_HashSet_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_Dictionary):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_Dictionary):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_Dictionary_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_ManagedINetworkSerializable):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_ManagedINetworkSerializable):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_ManagedINetworkSerializable_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_FixedString):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_FixedString):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_FixedString_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_FixedStringArray):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_FixedStringArray):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_FixedStringArray_MethodRef = method;
|
||||
break;
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_FixedStringList):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_FixedStringList):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_FixedStringList_MethodRef = method;
|
||||
break;
|
||||
#endif
|
||||
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_ManagedIEquatable):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_ManagedIEquatable):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedIEquatable_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedIEquatable):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatable_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatableArray):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedIEquatableArray):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatableArray_MethodRef = method;
|
||||
break;
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatableList):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedIEquatableList):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatableList_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_NativeHashSet):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_NativeHashSet):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashSet_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_NativeHashMap):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_NativeHashMap):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashMap_MethodRef = method;
|
||||
break;
|
||||
#endif
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_List):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_List):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_List_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_HashSet):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_HashSet):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_HashSet_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_Dictionary):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_Dictionary):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_Dictionary_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEquals):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedValueEquals):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEquals_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEqualsArray):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedValueEqualsArray):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEqualsArray_MethodRef = method;
|
||||
break;
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEqualsList):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedValueEqualsList):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEqualsList_MethodRef = method;
|
||||
break;
|
||||
#endif
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_ManagedClassEquals):
|
||||
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_ManagedClassEquals):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef = method;
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -30,7 +30,8 @@ namespace Unity.Netcode.Editor
|
||||
private SerializedProperty m_ProtocolVersionProperty;
|
||||
private SerializedProperty m_NetworkTransportProperty;
|
||||
private SerializedProperty m_TickRateProperty;
|
||||
#if MULTIPLAYER_SDK_INSTALLED
|
||||
#if MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
private SerializedProperty m_AutoSpawnPlayerPrefabClientSide;
|
||||
private SerializedProperty m_NetworkTopologyProperty;
|
||||
#endif
|
||||
private SerializedProperty m_ClientConnectionBufferTimeoutProperty;
|
||||
@@ -102,8 +103,13 @@ namespace Unity.Netcode.Editor
|
||||
m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion");
|
||||
m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport");
|
||||
m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate");
|
||||
#if MULTIPLAYER_SDK_INSTALLED
|
||||
#if MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
m_NetworkTopologyProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTopology");
|
||||
// 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))
|
||||
@@ -142,8 +146,13 @@ namespace Unity.Netcode.Editor
|
||||
m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion");
|
||||
m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport");
|
||||
m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate");
|
||||
#if MULTIPLAYER_SDK_INSTALLED
|
||||
#if MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
m_NetworkTopologyProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTopology");
|
||||
// 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,25 +177,18 @@ 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_SDK_INSTALLED
|
||||
#if MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
EditorGUILayout.PropertyField(m_NetworkTopologyProperty);
|
||||
#endif
|
||||
EditorGUILayout.PropertyField(m_ProtocolVersionProperty);
|
||||
@@ -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,9 +309,12 @@ namespace Unity.Netcode.Editor
|
||||
}
|
||||
|
||||
serializedObject.ApplyModifiedProperties();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Start buttons below
|
||||
private void DisplayCallToActionButtons()
|
||||
{
|
||||
if (!m_NetworkManager.IsServer && !m_NetworkManager.IsClient)
|
||||
{
|
||||
string buttonDisabledReasonSuffix = "";
|
||||
|
||||
@@ -310,6 +324,8 @@ namespace Unity.Netcode.Editor
|
||||
GUI.enabled = false;
|
||||
}
|
||||
|
||||
if (m_NetworkManager.NetworkConfig.NetworkTopology == NetworkTopologyTypes.ClientServer)
|
||||
{
|
||||
if (GUILayout.Button(new GUIContent("Start Host", "Starts a host instance" + buttonDisabledReasonSuffix)))
|
||||
{
|
||||
m_NetworkManager.StartHost();
|
||||
@@ -324,13 +340,21 @@ namespace Unity.Netcode.Editor
|
||||
{
|
||||
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
|
||||
{
|
||||
string instanceType = string.Empty;
|
||||
@@ -357,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)
|
||||
{
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
using System.Collections.Generic;
|
||||
#if MULTIPLAYER_SDK_INSTALLED
|
||||
#if BYPASS_DEFAULT_ENUM_DRAWER && MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
using System.Linq;
|
||||
#endif
|
||||
using UnityEditor;
|
||||
@@ -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();
|
||||
|
||||
@@ -148,7 +160,7 @@ namespace Unity.Netcode.Editor
|
||||
|
||||
// Keeping this here just in case, but it appears that in Unity 6 the visual bugs with
|
||||
// enum flags is resolved
|
||||
#if BYPASS_DEFAULT_ENUM_DRAWER && MULTIPLAYER_SDK_INSTALLED
|
||||
#if BYPASS_DEFAULT_ENUM_DRAWER && MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
[CustomPropertyDrawer(typeof(NetworkObject.OwnershipStatus))]
|
||||
public class NetworkObjectOwnership : PropertyDrawer
|
||||
{
|
||||
@@ -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;
|
||||
@@ -30,6 +33,7 @@ namespace Unity.Netcode.Editor
|
||||
private SerializedProperty m_UseQuaternionCompression;
|
||||
private SerializedProperty m_UseHalfFloatPrecision;
|
||||
private SerializedProperty m_SlerpPosition;
|
||||
private SerializedProperty m_AuthorityMode;
|
||||
|
||||
private static int s_ToggleOffset = 45;
|
||||
private static float s_MaxRowWidth = EditorGUIUtility.labelWidth + EditorGUIUtility.fieldWidth + 5;
|
||||
@@ -38,8 +42,10 @@ namespace Unity.Netcode.Editor
|
||||
private static GUIContent s_ScaleLabel = EditorGUIUtility.TrTextContent("Scale");
|
||||
|
||||
/// <inheritdoc/>
|
||||
public 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));
|
||||
@@ -59,12 +65,14 @@ namespace Unity.Netcode.Editor
|
||||
m_UseQuaternionCompression = serializedObject.FindProperty(nameof(NetworkTransform.UseQuaternionCompression));
|
||||
m_UseHalfFloatPrecision = serializedObject.FindProperty(nameof(NetworkTransform.UseHalfFloatPrecision));
|
||||
m_SlerpPosition = serializedObject.FindProperty(nameof(NetworkTransform.SlerpPosition));
|
||||
m_AuthorityMode = serializedObject.FindProperty(nameof(NetworkTransform.AuthorityMode));
|
||||
base.OnEnable();
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override void OnInspectorGUI()
|
||||
private void DisplayNetworkTransformProperties()
|
||||
{
|
||||
EditorGUILayout.LabelField("Syncing", EditorStyles.boldLabel);
|
||||
var networkTransform = target as NetworkTransform;
|
||||
EditorGUILayout.LabelField("Axis to Synchronize", EditorStyles.boldLabel);
|
||||
{
|
||||
GUILayout.BeginHorizontal();
|
||||
|
||||
@@ -126,6 +134,11 @@ namespace Unity.Netcode.Editor
|
||||
GUILayout.EndHorizontal();
|
||||
}
|
||||
|
||||
EditorGUILayout.Space();
|
||||
EditorGUILayout.LabelField("Authority", EditorStyles.boldLabel);
|
||||
{
|
||||
EditorGUILayout.PropertyField(m_AuthorityMode);
|
||||
}
|
||||
EditorGUILayout.Space();
|
||||
EditorGUILayout.LabelField("Thresholds", EditorStyles.boldLabel);
|
||||
EditorGUILayout.PropertyField(m_PositionThresholdProperty);
|
||||
@@ -133,11 +146,20 @@ 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)
|
||||
{
|
||||
EditorGUILayout.PropertyField(m_InterpolateProperty);
|
||||
}
|
||||
EditorGUILayout.PropertyField(m_SlerpPosition);
|
||||
EditorGUILayout.PropertyField(m_UseQuaternionSynchronization);
|
||||
if (m_UseQuaternionSynchronization.boolValue)
|
||||
@@ -152,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);
|
||||
@@ -161,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",
|
||||
@@ -57,7 +47,7 @@
|
||||
{
|
||||
"name": "com.unity.services.multiplayer",
|
||||
"expression": "0.2.0",
|
||||
"define": "MULTIPLAYER_SDK_INSTALLED"
|
||||
"define": "MULTIPLAYER_SERVICES_SDK_INSTALLED"
|
||||
}
|
||||
],
|
||||
"noEngineReferences": false
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ namespace Unity.Netcode.Components
|
||||
/// Half float precision <see cref="Vector3"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The Vector3T<ushort> values are half float values returned by <see cref="Mathf.FloatToHalf(float)"/> for each
|
||||
/// The Vector3T<ushort> values are half float values returned by <see cref="Mathf.FloatToHalf(float)"/> for each
|
||||
/// individual axis and the 16 bits of the half float are stored as <see cref="ushort"/> values since C# does not have
|
||||
/// a half float type.
|
||||
/// </remarks>
|
||||
|
||||
@@ -8,7 +8,7 @@ namespace Unity.Netcode.Components
|
||||
/// Half Precision <see cref="Vector4"/> that can also be used to convert a <see cref="Quaternion"/> to half precision.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The Vector4T<ushort> values are half float values returned by <see cref="Mathf.FloatToHalf(float)"/> for each
|
||||
/// The Vector4T<ushort> values are half float values returned by <see cref="Mathf.FloatToHalf(float)"/> for each
|
||||
/// individual axis and the 16 bits of the half float are stored as <see cref="ushort"/> values since C# does not have
|
||||
/// a half float type.
|
||||
/// </remarks>
|
||||
|
||||
@@ -5,14 +5,14 @@ using UnityEngine;
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
/// <summary>
|
||||
/// Solves for incoming values that are jittered
|
||||
/// Solves for incoming values that are jittered.
|
||||
/// Partially solves for message loss. Unclamped lerping helps hide this, but not completely
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of interpolated value</typeparam>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a9db1d18fa0117f4da5e8e65386b894a
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -186,7 +186,6 @@ namespace Unity.Netcode.Components
|
||||
/// NetworkAnimator enables remote synchronization of <see cref="UnityEngine.Animator"/> state for on network objects.
|
||||
/// </summary>
|
||||
[AddComponentMenu("Netcode/Network Animator")]
|
||||
[RequireComponent(typeof(Animator))]
|
||||
public class NetworkAnimator : NetworkBehaviour, ISerializationCallbackReceiver
|
||||
{
|
||||
[Serializable]
|
||||
@@ -231,6 +230,7 @@ namespace Unity.Netcode.Components
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#if UNITY_EDITOR
|
||||
private void ParseStateMachineStates(int layerIndex, ref AnimatorController animatorController, ref AnimatorStateMachine stateMachine)
|
||||
{
|
||||
@@ -264,7 +264,6 @@ namespace Unity.Netcode.Components
|
||||
{
|
||||
case AnimatorControllerParameterType.Trigger:
|
||||
{
|
||||
|
||||
if (transition.destinationStateMachine != null)
|
||||
{
|
||||
var destinationStateMachine = transition.destinationStateMachine;
|
||||
@@ -298,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;
|
||||
@@ -327,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();
|
||||
@@ -337,7 +339,7 @@ namespace Unity.Netcode.Components
|
||||
|
||||
public void OnBeforeSerialize()
|
||||
{
|
||||
BuildTransitionStateInfoList();
|
||||
// Do nothing when serializing (handled during OnValidate)
|
||||
}
|
||||
|
||||
internal struct AnimationState : INetworkSerializable
|
||||
@@ -497,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;
|
||||
@@ -531,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;
|
||||
|
||||
@@ -581,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.
|
||||
@@ -612,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);
|
||||
@@ -652,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>
|
||||
@@ -694,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
|
||||
{
|
||||
@@ -769,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];
|
||||
@@ -844,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;
|
||||
@@ -852,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})");
|
||||
}
|
||||
@@ -940,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);
|
||||
}
|
||||
@@ -1063,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)
|
||||
{
|
||||
@@ -1212,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)
|
||||
{
|
||||
@@ -1252,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);
|
||||
}
|
||||
@@ -1309,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);
|
||||
}
|
||||
@@ -1378,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);
|
||||
@@ -1402,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)]
|
||||
@@ -1413,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>
|
||||
@@ -1495,4 +1574,5 @@ namespace Unity.Netcode.Components
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // COM_UNITY_MODULES_ANIMATION
|
||||
// COM_UNITY_MODULES_ANIMATION
|
||||
#endif
|
||||
|
||||
@@ -1,722 +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 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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
|
||||
{
|
||||
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.isKinematic;
|
||||
}
|
||||
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.isKinematic = isKinematic;
|
||||
}
|
||||
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()
|
||||
{
|
||||
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)
|
||||
{
|
||||
m_Rigidbody2D.velocity = Vector2.zero;
|
||||
m_Rigidbody2D.angularVelocity = 0.0f;
|
||||
}
|
||||
|
||||
FixedJoint2D = gameObject.AddComponent<FixedJoint2D>();
|
||||
FixedJoint2D.connectedBody = bodyToConnect.m_Rigidbody2D;
|
||||
OnFixedJoint2DCreated();
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void ApplyFixedJoint(NetworkRigidbodyBase bodyToConnectTo, Vector3 position, float connectedMassScale = 0.0f, float massScale = 1.0f, bool useGravity = false, bool zeroVelocity = true)
|
||||
{
|
||||
transform.position = position;
|
||||
m_Rigidbody.position = position;
|
||||
if (zeroVelocity)
|
||||
{
|
||||
m_Rigidbody.linearVelocity = Vector3.zero;
|
||||
m_Rigidbody.angularVelocity = Vector3.zero;
|
||||
}
|
||||
m_OriginalGravitySetting = m_Rigidbody.useGravity;
|
||||
m_Rigidbody.useGravity = useGravity;
|
||||
FixedJoint = gameObject.AddComponent<FixedJoint>();
|
||||
FixedJoint.connectedBody = bodyToConnectTo.m_Rigidbody;
|
||||
FixedJoint.connectedMassScale = connectedMassScale;
|
||||
FixedJoint.massScale = massScale;
|
||||
OnFixedJointCreated();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Authority Only:
|
||||
/// When invoked and not already attached to a fixed joint, this will connect two rigid bodies with <see cref="UseRigidBodyForMotion"/> enabled.
|
||||
/// Invoke this method on the rigid body you wish to attach to another (i.e. weapon to player, sticky bomb to player/object, etc).
|
||||
/// <seealso cref="FixedJoint"/>
|
||||
/// <seealso cref="FixedJoint2D"/>
|
||||
/// </summary>
|
||||
/// <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))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (m_ResultsArray[i].HasCollisionStay)
|
||||
contactHandler0 = m_HandlerMapping[thisInstanceID];
|
||||
contactEventHandlerInfo0 = m_HandlerInfo[thisInstanceID];
|
||||
if (contactEventHandlerInfo0.HasContactEventPriority)
|
||||
{
|
||||
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 = contactHandler0;
|
||||
preferredContactHandlerNonRigidbody = contactEventHandlerInfo0.ProvideNonRigidBodyContactEvents;
|
||||
preferredRigidbody = m_RigidbodyMapping[thisInstanceID];
|
||||
}
|
||||
else
|
||||
{
|
||||
m_HandlerMapping[thisInstanceID].ContactEvent(m_EventId, m_ResultsArray[i].AverageNormal, m_RigidbodyMapping[otherInstanceID], m_ResultsArray[i].ContactPoint);
|
||||
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)
|
||||
{
|
||||
preferredContactHandler.ContactEvent(m_EventId, m_ResultsArray[i].AverageNormal, otherRigidbody, m_ResultsArray[i].ContactPoint, m_ResultsArray[i].HasCollisionStay, m_ResultsArray[i].AverageCollisionStayNormal);
|
||||
}
|
||||
else
|
||||
{
|
||||
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>
|
||||
@@ -159,11 +169,38 @@ namespace Unity.Netcode
|
||||
public bool AutoSpawnPlayerPrefabClientSide = true;
|
||||
|
||||
#if MULTIPLAYER_TOOLS
|
||||
/// <summary>
|
||||
/// Controls whether network messaging metrics will be gathered. (defaults to true)
|
||||
/// There is a slight performance cost to having this enabled, and can increase in processing time based on network message traffic.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The Realtime Network Stats Monitoring tool requires this to be enabled.
|
||||
/// </remarks>
|
||||
[Tooltip("Enable (default) if you want to gather messaging metrics. Realtime Network Stats Monitor requires this to be enabled. Disabling this can improve performance in release builds.")]
|
||||
public bool NetworkMessageMetrics = true;
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// When enabled (default, this enables network profiling information. This does come with a per message processing cost.
|
||||
/// Network profiling information is automatically disabled in release builds.
|
||||
/// </summary>
|
||||
[Tooltip("Enable (default) if you want to profile network messages with development builds and defaults to being disabled in release builds. When disabled, network messaging profiling will be disabled in development builds.")]
|
||||
public bool NetworkProfilingMetrics = true;
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
@@ -1,15 +1,8 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
|
||||
public enum NetworkTopologyTypes
|
||||
{
|
||||
ClientServer,
|
||||
DistributedAuthority
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A NetworkClient
|
||||
/// </summary>
|
||||
@@ -61,9 +54,9 @@ namespace Unity.Netcode
|
||||
public NetworkObject PlayerObject;
|
||||
|
||||
/// <summary>
|
||||
/// The list of NetworkObject's owned by this client instance
|
||||
/// The NetworkObject's owned by this client instance
|
||||
/// </summary>
|
||||
public List<NetworkObject> OwnedObjects => IsConnected ? SpawnManager.GetClientOwnedObjects(ClientId) : new List<NetworkObject>();
|
||||
public NetworkObject[] OwnedObjects => IsConnected ? SpawnManager.GetClientOwnedObjects(ClientId) : new NetworkObject[] { };
|
||||
|
||||
internal NetworkSpawnManager SpawnManager { get; private set; }
|
||||
|
||||
|
||||
@@ -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,9 +144,13 @@ namespace Unity.Netcode
|
||||
continue;
|
||||
}
|
||||
|
||||
// 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,18 +539,25 @@ 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();
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
if (LocalClient.IsServer)
|
||||
{
|
||||
OnClientDisconnectFromServer(clientId);
|
||||
}
|
||||
else // As long as we are not in the middle of a shutdown
|
||||
else
|
||||
{
|
||||
// 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.
|
||||
@@ -515,6 +565,7 @@ namespace Unity.Netcode
|
||||
// as the client ID is no longer valid.
|
||||
NetworkManager.Shutdown(true);
|
||||
}
|
||||
}
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
s_TransportDisconnect.End();
|
||||
#endif
|
||||
@@ -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)
|
||||
{
|
||||
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
|
||||
// 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))
|
||||
{
|
||||
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)
|
||||
{
|
||||
@@ -1229,6 +1287,8 @@ namespace Unity.Netcode
|
||||
var message = new ClientDisconnectedMessage { ClientId = clientId };
|
||||
MessageManager?.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, ConnectedClientIds);
|
||||
|
||||
// Used for testing/validation purposes only
|
||||
#if ENABLE_DAHOST_AUTOPROMOTE_SESSION_OWNER
|
||||
if (NetworkManager.DistributedAuthorityMode && !NetworkManager.ShutdownInProgress && NetworkManager.IsListening)
|
||||
{
|
||||
var newSessionOwner = NetworkManager.LocalClientId;
|
||||
@@ -1259,6 +1319,7 @@ namespace Unity.Netcode
|
||||
MessageManager?.SendMessage(ref sessionOwnerMessage, NetworkDelivery.ReliableFragmentedSequenced, ConnectedClientIds);
|
||||
NetworkManager.SetSessionOwner(newSessionOwner);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// If the client ID transport map exists
|
||||
@@ -1305,9 +1366,17 @@ namespace Unity.Netcode
|
||||
internal void DisconnectClient(ulong clientId, string reason = null)
|
||||
{
|
||||
if (!LocalClient.IsServer)
|
||||
{
|
||||
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)
|
||||
{
|
||||
|
||||
@@ -15,10 +15,16 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The base class to override to write network code. Inherits MonoBehaviour
|
||||
/// The base class to override to write network code. Inherits MonoBehaviour.
|
||||
/// </summary>
|
||||
public abstract class NetworkBehaviour : MonoBehaviour
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
[HideInInspector]
|
||||
[SerializeField]
|
||||
internal bool ShowTopMostFoldoutHeaderGroup = true;
|
||||
#endif
|
||||
|
||||
#pragma warning disable IDE1006 // disable naming rule violation check
|
||||
|
||||
// RuntimeAccessModifiersILPP will make this `public`
|
||||
@@ -27,7 +33,7 @@ namespace Unity.Netcode
|
||||
// RuntimeAccessModifiersILPP will make this `public`
|
||||
internal static readonly Dictionary<Type, Dictionary<uint, RpcReceiveHandler>> __rpc_func_table = new Dictionary<Type, Dictionary<uint, RpcReceiveHandler>>();
|
||||
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||
// RuntimeAccessModifiersILPP will make this `public`
|
||||
internal static readonly Dictionary<Type, Dictionary<uint, string>> __rpc_name_table = new Dictionary<Type, Dictionary<uint, string>>();
|
||||
#endif
|
||||
@@ -124,7 +130,7 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
bufferWriter.Dispose();
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||
if (__rpc_name_table[GetType()].TryGetValue(rpcMethodId, out var rpcMethodName))
|
||||
{
|
||||
NetworkManager.NetworkMetrics.TrackRpcSent(
|
||||
@@ -252,7 +258,7 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
bufferWriter.Dispose();
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||
if (__rpc_name_table[GetType()].TryGetValue(rpcMethodId, out var rpcMethodName))
|
||||
{
|
||||
if (clientRpcParams.Send.TargetClientIds != null)
|
||||
@@ -410,8 +416,8 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the NetworkManager that owns this NetworkBehaviour instance
|
||||
/// See note around `NetworkObject` for how there is a chicken / egg problem when we are not initialized
|
||||
/// Gets the NetworkManager that owns this NetworkBehaviour instance.
|
||||
/// See `NetworkObject` note for how there is a chicken/egg problem when not initialized.
|
||||
/// </summary>
|
||||
public NetworkManager NetworkManager
|
||||
{
|
||||
@@ -439,38 +445,40 @@ namespace Unity.Netcode
|
||||
/// <see cref="Unity.Netcode.RpcTarget.Not(NativeArray{ulong})"/>,
|
||||
/// <see cref="Unity.Netcode.RpcTarget.Not(NativeList{ulong})"/>,
|
||||
/// <see cref="Unity.Netcode.RpcTarget.Not(ulong[])"/>, and
|
||||
/// <see cref="Unity.Netcode.RpcTarget.Not{T}(T)"/>
|
||||
/// <see cref="Unity.Netcode.RpcTarget.Not{T}(T)"/>.
|
||||
/// </summary>
|
||||
#pragma warning restore IDE0001
|
||||
public RpcTarget RpcTarget => NetworkManager.RpcTarget;
|
||||
|
||||
/// <summary>
|
||||
/// If a NetworkObject is assigned, it will return whether or not this NetworkObject
|
||||
/// is the local player object. If no NetworkObject is assigned it will always return false.
|
||||
/// If a NetworkObject is assigned, returns whether the NetworkObject
|
||||
/// is the local player object. If no NetworkObject is assigned, returns false.
|
||||
/// </summary>
|
||||
public bool IsLocalPlayer { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets if the object is owned by the local player or if the object is the local player object
|
||||
/// Gets whether the object is owned by the local player or if the object is the local player object.
|
||||
/// </summary>
|
||||
public bool IsOwner { get; internal set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets if we are executing as server
|
||||
/// Gets whether executing as a server.
|
||||
/// </summary>
|
||||
public bool IsServer { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Determines if the local client has authority over the associated NetworkObject
|
||||
/// Client-Server: This will return true if IsServer or IsHost
|
||||
/// Distributed Authority: This will return true if IsOwner
|
||||
/// Determines if the local client has authority over the associated NetworkObject.
|
||||
/// <list type="bullet">
|
||||
/// <item>In client-server contexts: returns true if `IsServer` or `IsHost`.</item>
|
||||
/// <item>In distributed authority contexts: returns true if `IsOwner`.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public bool HasAuthority { get; internal set; }
|
||||
|
||||
internal NetworkClient LocalClient { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets if the client is the distributed authority mode session owner
|
||||
/// Gets whether the client is the distributed authority mode session owner.
|
||||
/// </summary>
|
||||
public bool IsSessionOwner
|
||||
{
|
||||
@@ -486,29 +494,29 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets if the server (local or remote) is a host - i.e., also a client
|
||||
/// Gets whether the server (local or remote) is a host.
|
||||
/// </summary>
|
||||
public bool ServerIsHost { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets if we are executing as client
|
||||
/// Gets whether executing as a client.
|
||||
/// </summary>
|
||||
public bool IsClient { get; private set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets if we are executing as Host, I.E Server and Client
|
||||
/// Gets whether executing as a host (both server and client).
|
||||
/// </summary>
|
||||
public bool IsHost { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets Whether or not the object has a owner
|
||||
/// Gets whether the object has an owner.
|
||||
/// </summary>
|
||||
public bool IsOwnedByServer { get; internal set; }
|
||||
|
||||
/// <summary>
|
||||
/// Used to determine if it is safe to access NetworkObject and NetworkManager from within a NetworkBehaviour component
|
||||
/// Primarily useful when checking NetworkObject/NetworkManager properties within FixedUpate
|
||||
/// Determines whether it's safe to access a NetworkObject and NetworkManager from within a NetworkBehaviour component.
|
||||
/// Primarily useful when checking NetworkObject or NetworkManager properties within FixedUpate.
|
||||
/// </summary>
|
||||
public bool IsSpawned { get; internal set; }
|
||||
|
||||
@@ -528,7 +536,7 @@ namespace Unity.Netcode
|
||||
/// the warning below. This is why IsBehaviourEditable had to be created. Matt was going to re-do
|
||||
/// how NetworkObject works but it was close to the release and too risky to change
|
||||
/// <summary>
|
||||
/// Gets the NetworkObject that owns this NetworkBehaviour instance
|
||||
/// Gets the NetworkObject that owns this NetworkBehaviour instance.
|
||||
/// </summary>
|
||||
public NetworkObject NetworkObject
|
||||
{
|
||||
@@ -567,19 +575,19 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether or not this NetworkBehaviour instance has a NetworkObject owner.
|
||||
/// Gets whether this NetworkBehaviour instance has a NetworkObject owner.
|
||||
/// </summary>
|
||||
public bool HasNetworkObject => NetworkObject != null;
|
||||
|
||||
private NetworkObject m_NetworkObject = null;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the NetworkId of the NetworkObject that owns this NetworkBehaviour
|
||||
/// Gets the NetworkId of the NetworkObject that owns this NetworkBehaviour instance.
|
||||
/// </summary>
|
||||
public ulong NetworkObjectId { get; internal set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets NetworkId for this NetworkBehaviour from the owner NetworkObject
|
||||
/// Gets NetworkId for this NetworkBehaviour from the owner NetworkObject.
|
||||
/// </summary>
|
||||
public ushort NetworkBehaviourId { get; internal set; }
|
||||
|
||||
@@ -589,7 +597,7 @@ namespace Unity.Netcode
|
||||
internal ushort NetworkBehaviourIdCache = 0;
|
||||
|
||||
/// <summary>
|
||||
/// Returns a the NetworkBehaviour with a given BehaviourId for the current NetworkObject
|
||||
/// Returns the NetworkBehaviour with a given BehaviourId for the current NetworkObject.
|
||||
/// </summary>
|
||||
/// <param name="behaviourId">The behaviourId to return</param>
|
||||
/// <returns>Returns NetworkBehaviour with given behaviourId</returns>
|
||||
@@ -599,7 +607,7 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the ClientId that owns the NetworkObject
|
||||
/// Gets the ClientId that owns this NetworkObject.
|
||||
/// </summary>
|
||||
public ulong OwnerClientId { get; internal set; }
|
||||
|
||||
@@ -651,28 +659,29 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Distributed Authority Mode Only
|
||||
/// Only for use in distributed authority mode.
|
||||
/// Invoked only on the authority instance when a <see cref="NetworkObject"/> is deferring its despawn on non-authoritative instances.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// See also: <see cref="NetworkObject.DeferDespawn(int, bool)"/>
|
||||
/// </remarks>
|
||||
/// <param name="despawnTick">the future network tick that the <see cref="NetworkObject"/> will be despawned on non-authoritative instances</param>
|
||||
/// <param name="despawnTick">The future network tick that the <see cref="NetworkObject"/> will be despawned on non-authoritative instances</param>
|
||||
public virtual void OnDeferringDespawn(int despawnTick) { }
|
||||
|
||||
/// <summary>
|
||||
/// Gets called after the <see cref="NetworkObject"/> is spawned. No NetworkBehaviours associated with the NetworkObject will have had <see cref="OnNetworkSpawn"/> invoked yet.
|
||||
/// A reference to <see cref="NetworkManager"/> is passed in as a parameter to determine the context of execution (IsServer/IsClient)
|
||||
/// A reference to <see cref="NetworkManager"/> is passed in as a parameter to determine the context of execution (`IsServer` or `IsClient`).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <param name="networkManager">a ref to the <see cref="NetworkManager"/> since this is not yet set on the <see cref="NetworkBehaviour"/></param>
|
||||
/// <remarks>
|
||||
/// The <see cref="NetworkBehaviour"/> will not have anything assigned to it at this point in time.
|
||||
/// Settings like ownership, NetworkBehaviourId, NetworkManager, and most other spawn related properties will not be set.
|
||||
/// This can be used to handle things like initializing/instantiating a NetworkVariable or the like.
|
||||
/// Settings like ownership, NetworkBehaviourId, NetworkManager, and most other spawn-related properties will not be set.
|
||||
/// This can be used to handle things like initializing a NetworkVariable.
|
||||
/// </remarks>
|
||||
protected virtual void OnNetworkPreSpawn(ref NetworkManager networkManager) { }
|
||||
|
||||
/// <summary>
|
||||
/// Gets called when the <see cref="NetworkObject"/> gets spawned, message handlers are ready to be registered and the network is setup.
|
||||
/// Gets called when the <see cref="NetworkObject"/> gets spawned, message handlers are ready to be registered, and the network is set up.
|
||||
/// </summary>
|
||||
public virtual void OnNetworkSpawn() { }
|
||||
|
||||
@@ -685,29 +694,33 @@ namespace Unity.Netcode
|
||||
/// </remarks>
|
||||
protected virtual void OnNetworkPostSpawn() { }
|
||||
|
||||
protected internal virtual void InternalOnNetworkPostSpawn() { }
|
||||
|
||||
/// <summary>
|
||||
/// [Client-Side Only]
|
||||
/// When a new client joins it is synchronized with all spawned NetworkObjects and scenes loaded for the session joined. At the end of the synchronization process, when all
|
||||
/// This method is only available client-side.
|
||||
/// When a new client joins it's synchronized with all spawned NetworkObjects and scenes loaded for the session joined. At the end of the synchronization process, when all
|
||||
/// <see cref="NetworkObject"/>s and scenes (if scene management is enabled) have finished synchronizing, all NetworkBehaviour components associated with spawned <see cref="NetworkObject"/>s
|
||||
/// will have this method invoked.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This can be used to handle post synchronization actions where you might need to access a different NetworkObject and/or NetworkBehaviour not local to the current NetworkObject context.
|
||||
/// This can be used to handle post-synchronization actions where you might need to access a different NetworkObject and/or NetworkBehaviour not local to the current NetworkObject context.
|
||||
/// This is only invoked on clients during a client-server network topology session.
|
||||
/// </remarks>
|
||||
protected virtual void OnNetworkSessionSynchronized() { }
|
||||
|
||||
protected internal virtual void InternalOnNetworkSessionSynchronized() { }
|
||||
|
||||
/// <summary>
|
||||
/// [Client & Server Side]
|
||||
/// When a scene is loaded an in-scene placed NetworkObjects are all spawned, this method is invoked on all of the newly spawned in-scene placed NetworkObjects.
|
||||
/// When a scene is loaded and in-scene placed NetworkObjects are finished spawning, this method is invoked on all of the newly spawned in-scene placed NetworkObjects.
|
||||
/// This method runs both client and server side.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This can be used to handle post scene loaded actions for in-scene placed NetworkObjcts where you might need to access a different NetworkObject and/or NetworkBehaviour not local to the current NetworkObject context.
|
||||
/// This method can be used to handle post-scene loaded actions for in-scene placed NetworkObjcts where you might need to access a different NetworkObject and/or NetworkBehaviour not local to the current NetworkObject context.
|
||||
/// </remarks>
|
||||
protected virtual void OnInSceneObjectsSpawned() { }
|
||||
|
||||
/// <summary>
|
||||
/// Gets called when the <see cref="NetworkObject"/> gets despawned. Is called both on the server and clients.
|
||||
/// Gets called when the <see cref="NetworkObject"/> gets despawned. This method runs both client and server side.
|
||||
/// </summary>
|
||||
public virtual void OnNetworkDespawn() { }
|
||||
|
||||
@@ -756,6 +769,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
try
|
||||
{
|
||||
InternalOnNetworkPostSpawn();
|
||||
OnNetworkPostSpawn();
|
||||
}
|
||||
catch (Exception e)
|
||||
@@ -768,6 +782,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
try
|
||||
{
|
||||
InternalOnNetworkSessionSynchronized();
|
||||
OnNetworkSessionSynchronized();
|
||||
}
|
||||
catch (Exception e)
|
||||
@@ -803,19 +818,27 @@ 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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Invoked on all clients, override this method to be notified of any
|
||||
/// ownership changes (even if the instance was niether the previous or
|
||||
/// Invoked on all clients. Override this method to be notified of any
|
||||
/// ownership changes (even if the instance was neither the previous or
|
||||
/// newly assigned current owner).
|
||||
/// </summary>
|
||||
/// <param name="previous">the previous owner</param>
|
||||
@@ -831,7 +854,9 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets called when we loose ownership of this object
|
||||
/// In client-server contexts, this method is invoked on the local client when it loses ownership of the associated <see cref="Netcode.NetworkObject"/>
|
||||
/// and on the server when any client loses ownership.
|
||||
/// <para>In distributed authority contexts, this method is only invoked on the local client that has lost ownership of the associated <see cref="Netcode.NetworkObject"/>.</para>
|
||||
/// </summary>
|
||||
public virtual void OnLostOwnership() { }
|
||||
|
||||
@@ -842,11 +867,13 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets called when the parent NetworkObject of this NetworkBehaviour's NetworkObject has changed
|
||||
/// Gets called when the parent NetworkObject of this NetworkBehaviour's NetworkObject has changed.
|
||||
/// </summary>
|
||||
/// <param name="parentNetworkObject">the new <see cref="NetworkObject"/> parent</param>
|
||||
public virtual void OnNetworkObjectParentChanged(NetworkObject parentNetworkObject) { }
|
||||
|
||||
internal virtual void InternalOnNetworkObjectParentChanged(NetworkObject parentNetworkObject) { }
|
||||
|
||||
private bool m_VarInit = false;
|
||||
|
||||
private readonly List<HashSet<int>> m_DeliveryMappedNetworkVariableIndices = new List<HashSet<int>>();
|
||||
@@ -877,7 +904,7 @@ namespace Unity.Netcode
|
||||
#pragma warning restore IDE1006 // restore naming rule violation check
|
||||
{
|
||||
__rpc_func_table[GetType()][hash] = handler;
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||
__rpc_name_table[GetType()][hash] = rpcMethodName;
|
||||
#endif
|
||||
}
|
||||
@@ -903,7 +930,7 @@ namespace Unity.Netcode
|
||||
if (!__rpc_func_table.ContainsKey(GetType()))
|
||||
{
|
||||
__rpc_func_table[GetType()] = new Dictionary<uint, RpcReceiveHandler>();
|
||||
#if UNITY_EDITOR || DEVELOPMENT_BUILD
|
||||
#if UNITY_EDITOR || DEVELOPMENT_BUILD || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||
__rpc_name_table[GetType()] = new Dictionary<uint, string>();
|
||||
#endif
|
||||
__initializeRpcs();
|
||||
@@ -950,7 +977,16 @@ namespace Unity.Netcode
|
||||
// during OnNetworkSpawn has been sent and needs to be cleared
|
||||
for (int i = 0; i < NetworkVariableFields.Count; i++)
|
||||
{
|
||||
NetworkVariableFields[i].ResetDirty();
|
||||
var networkVariable = NetworkVariableFields[i];
|
||||
if (networkVariable.IsDirty())
|
||||
{
|
||||
if (networkVariable.CanSend())
|
||||
{
|
||||
networkVariable.UpdateLastSentTime();
|
||||
networkVariable.ResetDirty();
|
||||
networkVariable.SetDirty(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -958,7 +994,16 @@ namespace Unity.Netcode
|
||||
// mark any variables we wrote as no longer dirty
|
||||
for (int i = 0; i < NetworkVariableIndexesToReset.Count; i++)
|
||||
{
|
||||
NetworkVariableFields[NetworkVariableIndexesToReset[i]].ResetDirty();
|
||||
var networkVariable = NetworkVariableFields[NetworkVariableIndexesToReset[i]];
|
||||
if (networkVariable.IsDirty())
|
||||
{
|
||||
if (networkVariable.CanSend())
|
||||
{
|
||||
networkVariable.UpdateLastSentTime();
|
||||
networkVariable.ResetDirty();
|
||||
networkVariable.SetDirty(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -978,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;
|
||||
}
|
||||
@@ -1000,8 +1050,11 @@ namespace Unity.Netcode
|
||||
{
|
||||
networkVariable = NetworkVariableFields[k];
|
||||
if (networkVariable.IsDirty() && networkVariable.CanClientRead(targetClientId))
|
||||
{
|
||||
if (networkVariable.CanSend())
|
||||
{
|
||||
shouldSend = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -1028,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,
|
||||
@@ -1057,15 +1114,42 @@ namespace Unity.Netcode
|
||||
// TODO: There should be a better way by reading one dirty variable vs. 'n'
|
||||
for (int i = 0; i < NetworkVariableFields.Count; i++)
|
||||
{
|
||||
if (NetworkVariableFields[i].IsDirty())
|
||||
var networkVariable = NetworkVariableFields[i];
|
||||
if (networkVariable.IsDirty())
|
||||
{
|
||||
if (networkVariable.CanSend())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
// If it's dirty but can't be sent yet, we have to keep monitoring it until one of the
|
||||
// conditions blocking its send changes.
|
||||
NetworkManager.BehaviourUpdater.AddForUpdate(NetworkObject);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <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++)
|
||||
@@ -1074,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)
|
||||
@@ -1084,30 +1179,25 @@ namespace Unity.Netcode
|
||||
/// </remarks>
|
||||
internal void WriteNetworkVariableData(FastBufferWriter writer, ulong targetClientId)
|
||||
{
|
||||
// Create any values that require accessing the NetworkManager locally (it is expensive to access it in NetworkBehaviour)
|
||||
var networkManager = NetworkManager;
|
||||
if (networkManager.DistributedAuthorityMode)
|
||||
{
|
||||
writer.WriteValueSafe((ushort)NetworkVariableFields.Count);
|
||||
}
|
||||
var ensureLengthSafety = networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety;
|
||||
|
||||
|
||||
// Exit early if there are no NetworkVariables
|
||||
if (NetworkVariableFields.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// DANGO-TODO: Made some modifications here that overlap/won't play nice with EnsureNetworkVariableLenghtSafety.
|
||||
// Worth either merging or more cleanly separating these codepaths.
|
||||
for (int j = 0; j < NetworkVariableFields.Count; j++)
|
||||
{
|
||||
// Note: In distributed authority mode, all clients can read
|
||||
// Client-Server: Try to write values only for clients that have read permissions.
|
||||
// Distributed Authority: All clients have read permissions, always try to write the value.
|
||||
if (NetworkVariableFields[j].CanClientRead(targetClientId))
|
||||
{
|
||||
if (networkManager.DistributedAuthorityMode)
|
||||
{
|
||||
writer.WriteValueSafe(NetworkVariableFields[j].Type);
|
||||
}
|
||||
|
||||
if (networkManager.DistributedAuthorityMode || networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
|
||||
// Write additional NetworkVariable information when length safety is enabled or when in distributed authority mode
|
||||
if (ensureLengthSafety)
|
||||
{
|
||||
var writePos = writer.Position;
|
||||
// Note: This value can't be packed because we don't know how large it will be in advance
|
||||
@@ -1117,21 +1207,29 @@ 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 field value size
|
||||
writer.WriteValueSafe((ushort)size);
|
||||
writer.Seek(startPos + size);
|
||||
}
|
||||
else
|
||||
else // Client-Server Only: Should only ever be invoked when using a client-server NetworkTopology
|
||||
{
|
||||
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
|
||||
else if (ensureLengthSafety)
|
||||
{
|
||||
// Only if EnsureNetworkVariableLengthSafety, otherwise just skip
|
||||
if (networkManager.DistributedAuthorityMode || networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
|
||||
// Client-Server Only: If the client cannot read this field, then skip it but write a 0 for this NetworkVariable's position
|
||||
{
|
||||
writer.WriteValueSafe((ushort)0);
|
||||
}
|
||||
@@ -1149,75 +1247,60 @@ namespace Unity.Netcode
|
||||
/// </remarks>
|
||||
internal void SetNetworkVariableData(FastBufferReader reader, ulong clientId)
|
||||
{
|
||||
// Stack cache any values that requires accessing the NetworkManager (it is expensive to access it in NetworkBehaviour)
|
||||
var networkManager = NetworkManager;
|
||||
if (networkManager.DistributedAuthorityMode)
|
||||
{
|
||||
reader.ReadValueSafe(out ushort variableCount);
|
||||
if (variableCount != NetworkVariableFields.Count)
|
||||
{
|
||||
Debug.LogError("NetworkVariable count mismatch.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
var ensureLengthSafety = networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety;
|
||||
|
||||
// Exit early if nothing else to read
|
||||
if (NetworkVariableFields.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// DANGO-TODO: Made some modifications here that overlap/won't play nice with EnsureNetworkVariableLenghtSafety.
|
||||
// Worth either merging or more cleanly separating these codepaths.
|
||||
for (int j = 0; j < NetworkVariableFields.Count; j++)
|
||||
{
|
||||
var varSize = (ushort)0;
|
||||
var readStartPos = 0;
|
||||
if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
|
||||
// Client-Server: Clients that only have read permissions will try to read the value
|
||||
// Distributed Authority: All clients have read permissions, always try to read the value
|
||||
if (NetworkVariableFields[j].CanClientRead(clientId))
|
||||
{
|
||||
if (ensureLengthSafety)
|
||||
{
|
||||
reader.ReadValueSafe(out varSize);
|
||||
if (varSize == 0)
|
||||
{
|
||||
Debug.LogError($"[{name}][NetworkObjectId: {NetworkObjectId}][NetworkBehaviourId: {NetworkBehaviourId}][{NetworkVariableFields[j].Name}] Expected non-zero size readable NetworkVariable! (Skipping)");
|
||||
continue;
|
||||
}
|
||||
readStartPos = reader.Position;
|
||||
}
|
||||
else // If the client cannot read this field, then skip it
|
||||
if (!NetworkVariableFields[j].CanClientRead(clientId))
|
||||
}
|
||||
else // Client-Server Only: If the client cannot read this field, then skip it
|
||||
{
|
||||
if (networkManager.DistributedAuthorityMode)
|
||||
// If skipping and length safety, then fill in a 0 size for this one spot
|
||||
if (ensureLengthSafety)
|
||||
{
|
||||
reader.ReadValueSafe(out ushort size);
|
||||
if (size != 0)
|
||||
{
|
||||
Debug.LogError("Expected zero size");
|
||||
Debug.LogError($"[{name}][NetworkObjectId: {NetworkObjectId}][NetworkBehaviourId: {NetworkBehaviourId}][{NetworkVariableFields[j].Name}] Expected zero size for non-readable NetworkVariable when EnsureNetworkVariableLengthSafety is enabled! (Skipping)");
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (networkManager.DistributedAuthorityMode)
|
||||
{
|
||||
// Explicit setting of the NetworkVariableType is only needed for CMB Runtime
|
||||
reader.ReadValueSafe(out NetworkVariableType _);
|
||||
reader.ReadValueSafe(out ushort size);
|
||||
var start_marker = reader.Position;
|
||||
// Read the NetworkVariable value
|
||||
NetworkVariableFields[j].ReadField(reader);
|
||||
if (reader.Position - start_marker != size)
|
||||
{
|
||||
Debug.LogError("Mismatched network variable size");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
NetworkVariableFields[j].ReadField(reader);
|
||||
}
|
||||
|
||||
if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
|
||||
// When EnsureNetworkVariableLengthSafety always do a bounds check
|
||||
if (ensureLengthSafety)
|
||||
{
|
||||
if (reader.Position > (readStartPos + varSize))
|
||||
{
|
||||
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
|
||||
{
|
||||
NetworkLog.LogWarning($"Var data read too far. {reader.Position - (readStartPos + varSize)} bytes.");
|
||||
NetworkLog.LogWarning($"[{name}][NetworkObjectId: {NetworkObjectId}][NetworkBehaviourId: {NetworkBehaviourId}][{NetworkVariableFields[j].Name}] NetworkVariable data read too big. {reader.Position - (readStartPos + varSize)} bytes.");
|
||||
}
|
||||
|
||||
reader.Seek(readStartPos + varSize);
|
||||
@@ -1226,7 +1309,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
|
||||
{
|
||||
NetworkLog.LogWarning($"Var data read too little. {(readStartPos + varSize) - reader.Position} bytes.");
|
||||
NetworkLog.LogWarning($"[{name}][NetworkObjectId: {NetworkObjectId}][NetworkBehaviourId: {NetworkBehaviourId}][{NetworkVariableFields[j].Name}] NetworkVariable data read too small. {(readStartPos + varSize) - reader.Position} bytes.");
|
||||
}
|
||||
|
||||
reader.Seek(readStartPos + varSize);
|
||||
@@ -1236,7 +1319,7 @@ namespace Unity.Netcode
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the local instance of a object with a given NetworkId
|
||||
/// Gets the local instance of a NetworkObject with a given NetworkId.
|
||||
/// </summary>
|
||||
/// <param name="networkId"></param>
|
||||
/// <returns></returns>
|
||||
@@ -1247,14 +1330,14 @@ namespace Unity.Netcode
|
||||
|
||||
/// <summary>
|
||||
/// Override this method if your derived NetworkBehaviour requires custom synchronization data.
|
||||
/// Note: Use of this method is only for the initial client synchronization of NetworkBehaviours
|
||||
/// Use of this method is only for the initial client synchronization of NetworkBehaviours
|
||||
/// and will increase the payload size for client synchronization and dynamically spawned
|
||||
/// <see cref="NetworkObject"/>s.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// When serializing (writing) this will be invoked during the client synchronization period and
|
||||
/// When serializing (writing), this method is invoked during the client synchronization period and
|
||||
/// when spawning new NetworkObjects.
|
||||
/// When deserializing (reading), this will be invoked prior to the NetworkBehaviour's associated
|
||||
/// When deserializing (reading), this method is invoked prior to the NetworkBehaviour's associated
|
||||
/// NetworkObject being spawned.
|
||||
/// </remarks>
|
||||
/// <param name="serializer">The serializer to use to read and write the data.</param>
|
||||
@@ -1268,14 +1351,19 @@ namespace Unity.Netcode
|
||||
|
||||
}
|
||||
|
||||
public virtual void OnReanticipate(double lastRoundTripTime)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The relative client identifier targeted for the serialization of this <see cref="NetworkBehaviour"/> instance.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This value will be set prior to <see cref="OnSynchronize{T}(ref BufferSerializer{T})"/> being invoked.
|
||||
/// This value is set prior to <see cref="OnSynchronize{T}(ref BufferSerializer{T})"/> being invoked.
|
||||
/// For writing (server-side), this is useful to know which client will receive the serialized data.
|
||||
/// For reading (client-side), this will be the <see cref="NetworkManager.LocalClientId"/>.
|
||||
/// When synchronization of this instance is complete, this value will be reset to 0
|
||||
/// When synchronization of this instance is complete, this value is reset to 0.
|
||||
/// </remarks>
|
||||
protected ulong m_TargetIdBeingSynchronized { get; private set; }
|
||||
|
||||
@@ -1398,9 +1486,8 @@ namespace Unity.Netcode
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Invoked when the <see cref="GameObject"/> the <see cref="NetworkBehaviour"/> is attached to.
|
||||
/// NOTE: If you override this, you will want to always invoke this base class version of this
|
||||
/// <see cref="OnDestroy"/> method!!
|
||||
/// Invoked when the <see cref="GameObject"/> the <see cref="NetworkBehaviour"/> is attached to is destroyed.
|
||||
/// If you override this, you must always invoke the base class version of this <see cref="OnDestroy"/> method.
|
||||
/// </summary>
|
||||
public virtual void OnDestroy()
|
||||
{
|
||||
|
||||
@@ -11,6 +11,7 @@ namespace Unity.Netcode
|
||||
private NetworkManager m_NetworkManager;
|
||||
private NetworkConnectionManager m_ConnectionManager;
|
||||
private HashSet<NetworkObject> m_DirtyNetworkObjects = new HashSet<NetworkObject>();
|
||||
private HashSet<NetworkObject> m_PendingDirtyNetworkObjects = new HashSet<NetworkObject>();
|
||||
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
private ProfilerMarker m_NetworkBehaviourUpdate = new ProfilerMarker($"{nameof(NetworkBehaviour)}.{nameof(NetworkBehaviourUpdate)}");
|
||||
@@ -18,16 +19,24 @@ namespace Unity.Netcode
|
||||
|
||||
internal void AddForUpdate(NetworkObject networkObject)
|
||||
{
|
||||
m_DirtyNetworkObjects.Add(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();
|
||||
#endif
|
||||
try
|
||||
{
|
||||
m_DirtyNetworkObjects.UnionWith(m_PendingDirtyNetworkObjects);
|
||||
m_PendingDirtyNetworkObjects.Clear();
|
||||
|
||||
// NetworkObject references can become null, when hidden or despawned. Once NUll, there is no point
|
||||
// trying to process them, even if they were previously marked as dirty.
|
||||
m_DirtyNetworkObjects.RemoveWhere((sobj) => sobj == null);
|
||||
@@ -49,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -68,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,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;
|
||||
}
|
||||
@@ -127,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.
|
||||
@@ -29,24 +46,59 @@ namespace Unity.Netcode
|
||||
// RuntimeAccessModifiersILPP will make this `public`
|
||||
internal static readonly Dictionary<uint, RpcReceiveHandler> __rpc_func_table = new Dictionary<uint, RpcReceiveHandler>();
|
||||
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||
// RuntimeAccessModifiersILPP will make this `public`
|
||||
internal static readonly Dictionary<uint, string> __rpc_name_table = new Dictionary<uint, string>();
|
||||
#endif
|
||||
|
||||
#pragma warning restore IDE1006 // restore naming rule violation check
|
||||
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
private static List<Type> s_SerializedType = new List<Type>();
|
||||
// This is used to control the serialized type not optimized messaging for integration test purposes
|
||||
internal static bool DisableNotOptimizedSerializedType;
|
||||
/// <summary>
|
||||
/// Until all serialized types are optimized for the distributed authority network topology,
|
||||
/// this will handle the notification to the user that the type being serialized is not yet
|
||||
/// optimized but will only log the message once to prevent log spamming.
|
||||
/// </summary>
|
||||
internal static void LogSerializedTypeNotOptimized<T>()
|
||||
{
|
||||
if (DisableNotOptimizedSerializedType)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var type = typeof(T);
|
||||
if (!s_SerializedType.Contains(type))
|
||||
{
|
||||
s_SerializedType.Add(type);
|
||||
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer)
|
||||
{
|
||||
Debug.LogWarning($"[{type.Name}] Serialized type has not been optimized for use with Distributed Authority!");
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
internal 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>
|
||||
/// Distributed Authority Mode
|
||||
/// Returns true if the current session is running in distributed authority mode.
|
||||
/// </summary>
|
||||
public bool DistributedAuthorityMode
|
||||
{
|
||||
get
|
||||
{
|
||||
return NetworkConfig.NetworkTopology == NetworkTopologyTypes.DistributedAuthority;
|
||||
}
|
||||
}
|
||||
public bool DistributedAuthorityMode { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Distributed Authority Mode
|
||||
@@ -122,15 +174,47 @@ 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>();
|
||||
|
||||
public ulong CurrentSessionOwner { get; internal set; }
|
||||
|
||||
/// <summary>
|
||||
/// Delegate declaration for <see cref="OnSessionOwnerPromoted"/>
|
||||
/// </summary>
|
||||
/// <param name="sessionOwnerPromoted">the new session owner client identifier</param>
|
||||
public delegate void OnSessionOwnerPromotedDelegateHandler(ulong sessionOwnerPromoted);
|
||||
|
||||
/// <summary>
|
||||
/// Network Topology: Distributed Authority
|
||||
/// When a new session owner is promoted, this event is triggered on all connected clients
|
||||
/// </summary>
|
||||
public event OnSessionOwnerPromotedDelegateHandler OnSessionOwnerPromoted;
|
||||
|
||||
internal void SetSessionOwner(ulong sessionOwner)
|
||||
{
|
||||
var previousSessionOwner = CurrentSessionOwner;
|
||||
@@ -141,20 +225,17 @@ 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
OnSessionOwnerPromoted?.Invoke(sessionOwner);
|
||||
}
|
||||
|
||||
// TODO: Make this internal after testing
|
||||
public void PromoteSessionOwner(ulong clientId)
|
||||
internal void PromoteSessionOwner(ulong clientId)
|
||||
{
|
||||
if (!DistributedAuthorityMode)
|
||||
{
|
||||
@@ -178,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
|
||||
@@ -204,42 +285,74 @@ 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
|
||||
}
|
||||
|
||||
private void UpdateTopology()
|
||||
{
|
||||
var transportTopology = IsListening ? NetworkConfig.NetworkTransport.CurrentTopology() : NetworkConfig.NetworkTopology;
|
||||
if (transportTopology != NetworkConfig.NetworkTopology)
|
||||
{
|
||||
NetworkLog.LogErrorServer($"[Topology Mismatch] Transport detected an issue with the topology ({transportTopology} | {NetworkConfig.NetworkTopology}) usage or setting! Disconnecting from session.");
|
||||
Shutdown();
|
||||
}
|
||||
else
|
||||
{
|
||||
IsDistributedAuthority = DistributedAuthorityMode = transportTopology == NetworkTopologyTypes.DistributedAuthority;
|
||||
}
|
||||
}
|
||||
|
||||
public void NetworkUpdate(NetworkUpdateStage updateStage)
|
||||
{
|
||||
switch (updateStage)
|
||||
{
|
||||
case NetworkUpdateStage.EarlyUpdate:
|
||||
{
|
||||
UpdateTopology();
|
||||
|
||||
// Handle processing any new connections or transport events
|
||||
NetworkConfig.NetworkTransport.EarlyUpdate();
|
||||
|
||||
ConnectionManager.ProcessPendingApprovals();
|
||||
ConnectionManager.PollAndHandleNetworkEvents();
|
||||
|
||||
DeferredMessageManager.ProcessTriggers(IDeferredNetworkMessageManager.TriggerType.OnNextFrame, 0);
|
||||
|
||||
AnticipationSystem.SetupForUpdate();
|
||||
MessageManager.ProcessIncomingMessageQueue();
|
||||
|
||||
MessageManager.CleanupDisconnectedClients();
|
||||
AnticipationSystem.ProcessReanticipation();
|
||||
}
|
||||
break;
|
||||
#if COM_UNITY_MODULES_PHYSICS
|
||||
case NetworkUpdateStage.FixedUpdate:
|
||||
{
|
||||
foreach (var networkTransformEntry in NetworkTransformFixedUpdate)
|
||||
foreach (var networkObjectEntry in NetworkTransformFixedUpdate)
|
||||
{
|
||||
if (networkTransformEntry.Value.gameObject.activeInHierarchy && networkTransformEntry.Value.IsSpawned)
|
||||
// if not active or not spawned then skip
|
||||
if (!networkObjectEntry.Value.gameObject.activeInHierarchy || !networkObjectEntry.Value.IsSpawned)
|
||||
{
|
||||
networkTransformEntry.Value.OnFixedUpdate();
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var networkTransformEntry in networkObjectEntry.Value.NetworkTransforms)
|
||||
{
|
||||
// only update if enabled
|
||||
if (networkTransformEntry.enabled)
|
||||
{
|
||||
networkTransformEntry.OnFixedUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -248,19 +361,36 @@ namespace Unity.Netcode
|
||||
case NetworkUpdateStage.PreUpdate:
|
||||
{
|
||||
NetworkTimeSystem.UpdateTime();
|
||||
AnticipationSystem.Update();
|
||||
}
|
||||
break;
|
||||
case NetworkUpdateStage.PreLateUpdate:
|
||||
{
|
||||
// Non-physics based non-authority NetworkTransforms update their states after all other components
|
||||
foreach (var networkTransformEntry in NetworkTransformUpdate)
|
||||
foreach (var networkObjectEntry in NetworkTransformUpdate)
|
||||
{
|
||||
if (networkTransformEntry.Value.gameObject.activeInHierarchy && networkTransformEntry.Value.IsSpawned)
|
||||
// if not active or not spawned then skip
|
||||
if (!networkObjectEntry.Value.gameObject.activeInHierarchy || !networkObjectEntry.Value.IsSpawned)
|
||||
{
|
||||
networkTransformEntry.Value.OnUpdate();
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var networkTransformEntry in networkObjectEntry.Value.NetworkTransforms)
|
||||
{
|
||||
// only update if enabled
|
||||
if (networkTransformEntry.enabled)
|
||||
{
|
||||
networkTransformEntry.OnUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
case NetworkUpdateStage.PostScriptLateUpdate:
|
||||
{
|
||||
AnticipationSystem.Sync();
|
||||
AnticipationSystem.SetupForRender();
|
||||
}
|
||||
break;
|
||||
case NetworkUpdateStage.PostLateUpdate:
|
||||
{
|
||||
@@ -282,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
|
||||
@@ -501,6 +624,25 @@ namespace Unity.Netcode
|
||||
remove => ConnectionManager.OnTransportFailure -= value;
|
||||
}
|
||||
|
||||
public delegate void ReanticipateDelegate(double lastRoundTripTime);
|
||||
|
||||
/// <summary>
|
||||
/// This callback is called after all individual OnReanticipate calls on AnticipatedNetworkVariable
|
||||
/// and AnticipatedNetworkTransform values have been invoked. The first parameter is a hash set of
|
||||
/// all the variables that have been changed on this frame (you can detect a particular variable by
|
||||
/// checking if the set contains it), while the second parameter is a set of all anticipated network
|
||||
/// transforms that have been changed. Both are passed as their base class type.
|
||||
///
|
||||
/// The third parameter is the local time corresponding to the current authoritative server state
|
||||
/// (i.e., to determine the amount of time that needs to be re-simulated, you will use
|
||||
/// NetworkManager.LocalTime.Time - authorityTime).
|
||||
/// </summary>
|
||||
public event ReanticipateDelegate OnReanticipate
|
||||
{
|
||||
add => AnticipationSystem.OnReanticipate += value;
|
||||
remove => AnticipationSystem.OnReanticipate -= value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The callback to invoke during connection approval. Allows client code to decide whether or not to allow incoming client connection
|
||||
/// </summary>
|
||||
@@ -745,6 +887,8 @@ namespace Unity.Netcode
|
||||
/// </summary>
|
||||
public NetworkTickSystem NetworkTickSystem { get; private set; }
|
||||
|
||||
internal AnticipationSystem AnticipationSystem { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Used for time mocking in tests
|
||||
/// </summary>
|
||||
@@ -768,6 +912,7 @@ namespace Unity.Netcode
|
||||
|
||||
internal Override<ushort> PortOverride;
|
||||
|
||||
|
||||
#if UNITY_EDITOR
|
||||
internal static INetworkManagerHelper NetworkManagerHelper;
|
||||
|
||||
@@ -789,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)
|
||||
@@ -796,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)
|
||||
@@ -849,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
|
||||
@@ -910,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()
|
||||
@@ -1007,13 +1175,25 @@ namespace Unity.Netcode
|
||||
|
||||
internal void Initialize(bool server)
|
||||
{
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
if (!DisableNotOptimizedSerializedType)
|
||||
{
|
||||
s_SerializedType.Clear();
|
||||
}
|
||||
#endif
|
||||
|
||||
#if COM_UNITY_MODULES_PHYSICS
|
||||
NetworkTransformFixedUpdate.Clear();
|
||||
#endif
|
||||
NetworkTransformUpdate.Clear();
|
||||
|
||||
//DANGOEXP TODO: Remove this before finalizing the experimental release
|
||||
NetworkConfig.AutoSpawnPlayerPrefabClientSide = DistributedAuthorityMode;
|
||||
UpdateTopology();
|
||||
|
||||
// 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)
|
||||
@@ -1051,6 +1231,7 @@ namespace Unity.Netcode
|
||||
this.RegisterNetworkUpdate(NetworkUpdateStage.FixedUpdate);
|
||||
#endif
|
||||
this.RegisterNetworkUpdate(NetworkUpdateStage.PreUpdate);
|
||||
this.RegisterNetworkUpdate(NetworkUpdateStage.PostScriptLateUpdate);
|
||||
this.RegisterNetworkUpdate(NetworkUpdateStage.PreLateUpdate);
|
||||
this.RegisterNetworkUpdate(NetworkUpdateStage.PostLateUpdate);
|
||||
|
||||
@@ -1090,6 +1271,7 @@ namespace Unity.Netcode
|
||||
// The remaining systems can then be initialized
|
||||
NetworkTimeSystem = server ? NetworkTimeSystem.ServerTimeSystem() : new NetworkTimeSystem(1.0 / NetworkConfig.TickRate);
|
||||
NetworkTickSystem = NetworkTimeSystem.Initialize(this);
|
||||
AnticipationSystem = new AnticipationSystem(this);
|
||||
|
||||
// Create spawn manager instance
|
||||
SpawnManager = new NetworkSpawnManager(this);
|
||||
@@ -1191,6 +1373,8 @@ namespace Unity.Netcode
|
||||
{
|
||||
SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
|
||||
|
||||
// Notify the server that everything should be synchronized/spawned at this time.
|
||||
SpawnManager.NotifyNetworkObjectsSynchronized();
|
||||
OnServerStarted?.Invoke();
|
||||
ConnectionManager.LocalClient.IsApproved = true;
|
||||
return true;
|
||||
@@ -1338,6 +1522,9 @@ namespace Unity.Netcode
|
||||
|
||||
SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
|
||||
|
||||
// Notify the host that everything should be synchronized/spawned at this time.
|
||||
SpawnManager.NotifyNetworkObjectsSynchronized();
|
||||
|
||||
OnServerStarted?.Invoke();
|
||||
OnClientStarted?.Invoke();
|
||||
|
||||
@@ -1496,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.
|
||||
@@ -430,7 +477,7 @@ namespace Unity.Netcode
|
||||
/// Determines whether a NetworkObject can be distributed to other clients during
|
||||
/// a <see cref="NetworkTopologyTypes.DistributedAuthority"/> session.
|
||||
/// </summary>
|
||||
#if !MULTIPLAYER_SDK_INSTALLED
|
||||
#if !MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||
[HideInInspector]
|
||||
#endif
|
||||
[SerializeField]
|
||||
@@ -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;
|
||||
@@ -540,15 +589,17 @@ namespace Unity.Netcode
|
||||
/// permission failure status codes will be returned via <see cref="OnOwnershipPermissionsFailure"/>.
|
||||
/// <see cref="Locked"/>: The <see cref="NetworkObject"/> is locked and ownership cannot be acquired.
|
||||
/// <see cref="RequestRequired"/>: The <see cref="NetworkObject"/> requires an ownership request via <see cref="RequestOwnership"/>.
|
||||
/// <see cref="RequestInProgress"/>: The <see cref="NetworkObject"/> already is processing an ownership request and ownership cannot be acquired at this time.
|
||||
/// <see cref="NotTransferrable": The <see cref="NetworkObject"/> does not have the <see cref="OwnershipStatus.Transferable"/> flag set and ownership cannot be acquired.
|
||||
/// <see cref="RequestInProgress"/>: The <see cref="NetworkObject"/> is already processing an ownership request and ownership cannot be acquired at this time.
|
||||
/// <see cref="NotTransferrable"/>: The <see cref="NetworkObject"/> does not have the <see cref="OwnershipStatus.Transferable"/> flag set and ownership cannot be acquired.
|
||||
/// <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,6 +873,17 @@ namespace Unity.Netcode
|
||||
Ownership = OwnershipStatus.None;
|
||||
}
|
||||
|
||||
if (status.HasFlag(OwnershipStatus.SessionOwner))
|
||||
{
|
||||
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;
|
||||
@@ -815,6 +892,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
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
|
||||
@@ -1547,6 +1652,11 @@ namespace Unity.Netcode
|
||||
|
||||
if (NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
if (NetworkManager.LocalClient == null || !NetworkManager.IsConnectedClient || !NetworkManager.ConnectionManager.LocalClient.IsApproved)
|
||||
{
|
||||
Debug.LogError($"Cannot spawn {name} until the client is fully connected to the session!");
|
||||
return;
|
||||
}
|
||||
if (NetworkManager.NetworkConfig.EnableSceneManagement)
|
||||
{
|
||||
NetworkSceneHandle = NetworkManager.SceneManager.ClientSceneHandleToServerSceneHandle[gameObject.scene.handle];
|
||||
@@ -1557,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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1579,9 +1689,14 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
else if (NetworkManager.DistributedAuthorityMode && !NetworkManager.DAHost)
|
||||
{
|
||||
// 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
|
||||
{
|
||||
NetworkLog.LogWarningServer($"Ran into unknown conditional check during spawn when determining distributed authority mode or not");
|
||||
@@ -1638,7 +1753,7 @@ namespace Unity.Netcode
|
||||
return null;
|
||||
}
|
||||
|
||||
ownerClientId = networkManager.DistributedAuthorityMode ? networkManager.LocalClientId : NetworkManager.ServerClientId;
|
||||
ownerClientId = networkManager.DistributedAuthorityMode ? networkManager.LocalClientId : ownerClientId;
|
||||
// We only need to check for authority when running in client-server mode
|
||||
if (!networkManager.IsServer && !networkManager.DistributedAuthorityMode)
|
||||
{
|
||||
@@ -1782,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);
|
||||
}
|
||||
}
|
||||
@@ -1913,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.
|
||||
@@ -1927,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;
|
||||
@@ -1979,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
|
||||
@@ -2071,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)
|
||||
{
|
||||
@@ -2354,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)))
|
||||
@@ -2406,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
|
||||
@@ -2436,10 +2566,10 @@ namespace Unity.Netcode
|
||||
if (NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
var readerPosition = reader.Position;
|
||||
reader.ReadValueSafe(out ushort behaviorCount);
|
||||
if (behaviorCount != ChildNetworkBehaviours.Count)
|
||||
reader.ReadValueSafe(out ushort behaviourCount);
|
||||
if (behaviourCount != ChildNetworkBehaviours.Count)
|
||||
{
|
||||
Debug.LogError($"Network Behavior Count Mismatch! [{readerPosition}][{reader.Position}]");
|
||||
Debug.LogError($"[{name}] Network Behavior Count Mismatch! [In: {behaviourCount} vs Local: {ChildNetworkBehaviours.Count}][StartReaderPos: {readerPosition}] CurrentReaderPos: {reader.Position}]");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -2732,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2845,7 +2975,7 @@ namespace Unity.Netcode
|
||||
SyncObservers = syncObservers,
|
||||
Observers = syncObservers ? Observers.ToArray() : null,
|
||||
NetworkSceneHandle = NetworkSceneHandle,
|
||||
Hash = HostCheckForGlobalObjectIdHashOverride(),
|
||||
Hash = CheckForGlobalObjectIdHashOverride(),
|
||||
OwnerObject = this,
|
||||
TargetClientId = targetClientId
|
||||
};
|
||||
@@ -3015,6 +3145,10 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
// Only add all other players as observers if we are spawning with observers,
|
||||
// otherwise user controls via NetworkShow.
|
||||
if (networkObject.SpawnWithObservers)
|
||||
{
|
||||
// Add all known players to the observers list if they don't already exist
|
||||
foreach (var player in networkManager.SpawnManager.PlayerObjects)
|
||||
{
|
||||
@@ -3022,6 +3156,7 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return networkObject;
|
||||
}
|
||||
|
||||
@@ -3192,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,26 +117,43 @@ namespace Unity.Netcode
|
||||
|
||||
private static void SceneOpened(Scene scene)
|
||||
{
|
||||
LogInfo($"Processing scene {scene.name}:");
|
||||
if (s_ScenesToUpdate.Contains(scene.path))
|
||||
{
|
||||
if (s_ProcessScenes)
|
||||
{
|
||||
var prefabInstances = PrefabUtility.FindAllInstancesOfPrefab(PrefabNetworkObject.gameObject);
|
||||
|
||||
if (prefabInstances.Length > 0)
|
||||
{
|
||||
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))
|
||||
{
|
||||
Debug.Log($"Scene {scene.name} did not get marked as dirty!");
|
||||
LogInfo($"Scene {scene.name} did not get marked as dirty!");
|
||||
FinishedProcessingScene(scene);
|
||||
}
|
||||
else
|
||||
{
|
||||
LogInfo($"Changes detected and applied!");
|
||||
EditorSceneManager.SaveScene(scene);
|
||||
}
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
LogInfo($"No changes required.");
|
||||
FinishedProcessingScene(scene);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void EditorSceneManager_sceneOpened(Scene scene, OpenSceneMode mode)
|
||||
{
|
||||
|
||||
@@ -54,6 +54,12 @@ namespace Unity.Netcode
|
||||
/// </summary>
|
||||
PreLateUpdate = 6,
|
||||
/// <summary>
|
||||
/// Updated after Monobehaviour.LateUpdate, but BEFORE rendering
|
||||
/// </summary>
|
||||
// Yes, these numbers are out of order due to backward compatibility requirements.
|
||||
// The enum values are listed in the order they will be called.
|
||||
PostScriptLateUpdate = 8,
|
||||
/// <summary>
|
||||
/// Updated after the Monobehaviour.LateUpdate for all components is invoked
|
||||
/// </summary>
|
||||
PostLateUpdate = 7
|
||||
@@ -258,6 +264,18 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
internal struct NetworkPostScriptLateUpdate
|
||||
{
|
||||
public static PlayerLoopSystem CreateLoopSystem()
|
||||
{
|
||||
return new PlayerLoopSystem
|
||||
{
|
||||
type = typeof(NetworkPostScriptLateUpdate),
|
||||
updateDelegate = () => RunNetworkUpdateStage(NetworkUpdateStage.PostScriptLateUpdate)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
internal struct NetworkPostLateUpdate
|
||||
{
|
||||
public static PlayerLoopSystem CreateLoopSystem()
|
||||
@@ -399,6 +417,7 @@ namespace Unity.Netcode
|
||||
else if (currentSystem.type == typeof(PreLateUpdate))
|
||||
{
|
||||
TryAddLoopSystem(ref currentSystem, NetworkPreLateUpdate.CreateLoopSystem(), typeof(PreLateUpdate.ScriptRunBehaviourLateUpdate), LoopSystemPosition.Before);
|
||||
TryAddLoopSystem(ref currentSystem, NetworkPostScriptLateUpdate.CreateLoopSystem(), typeof(PreLateUpdate.ScriptRunBehaviourLateUpdate), LoopSystemPosition.After);
|
||||
}
|
||||
else if (currentSystem.type == typeof(PostLateUpdate))
|
||||
{
|
||||
@@ -440,6 +459,7 @@ namespace Unity.Netcode
|
||||
else if (currentSystem.type == typeof(PreLateUpdate))
|
||||
{
|
||||
TryRemoveLoopSystem(ref currentSystem, typeof(NetworkPreLateUpdate));
|
||||
TryRemoveLoopSystem(ref currentSystem, typeof(NetworkPostScriptLateUpdate));
|
||||
}
|
||||
else if (currentSystem.type == typeof(PostLateUpdate))
|
||||
{
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +47,8 @@ namespace Unity.Netcode
|
||||
SessionOwner = 20,
|
||||
TimeSync = 21,
|
||||
Unnamed = 22,
|
||||
AnticipationCounterSyncPingMessage = 23,
|
||||
AnticipationCounterSyncPongMessage = 24,
|
||||
}
|
||||
|
||||
|
||||
@@ -103,7 +105,9 @@ namespace Unity.Netcode
|
||||
{ typeof(ServerRpcMessage), NetworkMessageTypes.ServerRpc },
|
||||
{ typeof(TimeSyncMessage), NetworkMessageTypes.TimeSync },
|
||||
{ typeof(UnnamedMessage), NetworkMessageTypes.Unnamed },
|
||||
{ typeof(SessionOwnerMessage), NetworkMessageTypes.SessionOwner }
|
||||
{ typeof(SessionOwnerMessage), NetworkMessageTypes.SessionOwner },
|
||||
{ typeof(AnticipationCounterSyncPingMessage), NetworkMessageTypes.AnticipationCounterSyncPingMessage},
|
||||
{ typeof(AnticipationCounterSyncPongMessage), NetworkMessageTypes.AnticipationCounterSyncPongMessage},
|
||||
};
|
||||
|
||||
// Assure the type to lookup table count and NetworkMessageType enum count matches (i.e. to catch human error when adding new messages)
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
internal struct AnticipationCounterSyncPingMessage : INetworkMessage
|
||||
{
|
||||
public int Version => 0;
|
||||
|
||||
public ulong Counter;
|
||||
public double Time;
|
||||
|
||||
public void Serialize(FastBufferWriter writer, int targetVersion)
|
||||
{
|
||||
BytePacker.WriteValuePacked(writer, Counter);
|
||||
writer.WriteValueSafe(Time);
|
||||
}
|
||||
|
||||
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
|
||||
{
|
||||
var networkManager = (NetworkManager)context.SystemOwner;
|
||||
if (!networkManager.IsServer)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
ByteUnpacker.ReadValuePacked(reader, out Counter);
|
||||
reader.ReadValueSafe(out Time);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Handle(ref NetworkContext context)
|
||||
{
|
||||
var networkManager = (NetworkManager)context.SystemOwner;
|
||||
if (networkManager.IsListening && !networkManager.ShutdownInProgress && networkManager.ConnectedClients.ContainsKey(context.SenderId))
|
||||
{
|
||||
var message = new AnticipationCounterSyncPongMessage { Counter = Counter, Time = Time };
|
||||
networkManager.MessageManager.SendMessage(ref message, NetworkDelivery.Reliable, context.SenderId);
|
||||
}
|
||||
}
|
||||
}
|
||||
internal struct AnticipationCounterSyncPongMessage : INetworkMessage
|
||||
{
|
||||
public int Version => 0;
|
||||
|
||||
public ulong Counter;
|
||||
public double Time;
|
||||
|
||||
public void Serialize(FastBufferWriter writer, int targetVersion)
|
||||
{
|
||||
BytePacker.WriteValuePacked(writer, Counter);
|
||||
writer.WriteValueSafe(Time);
|
||||
}
|
||||
|
||||
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
|
||||
{
|
||||
var networkManager = (NetworkManager)context.SystemOwner;
|
||||
if (!networkManager.IsClient)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
ByteUnpacker.ReadValuePacked(reader, out Counter);
|
||||
reader.ReadValueSafe(out Time);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Handle(ref NetworkContext context)
|
||||
{
|
||||
var networkManager = (NetworkManager)context.SystemOwner;
|
||||
networkManager.AnticipationSystem.LastAnticipationAck = Counter;
|
||||
networkManager.AnticipationSystem.LastAnticipationAckTime = Time;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b7d5c92979ad7e646a078aaf058b53a9
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ namespace Unity.Netcode
|
||||
public void Handle(ref NetworkContext context)
|
||||
{
|
||||
var networkManager = (NetworkManager)context.SystemOwner;
|
||||
if ((ShouldSynchronize || networkManager.CMBServiceConnection) && networkManager.DistributedAuthorityMode && networkManager.LocalClient.IsSessionOwner)
|
||||
if (ShouldSynchronize && networkManager.NetworkConfig.EnableSceneManagement && networkManager.DistributedAuthorityMode && networkManager.LocalClient.IsSessionOwner)
|
||||
{
|
||||
networkManager.SceneManager.SynchronizeNetworkObjects(ClientId);
|
||||
}
|
||||
@@ -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)
|
||||
{
|
||||
// ============================================================
|
||||
@@ -44,10 +110,19 @@ namespace Unity.Netcode
|
||||
BytePacker.WriteValueBitPacked(writer, OwnerClientId);
|
||||
BytePacker.WriteValueBitPacked(writer, NetworkTick);
|
||||
if (IsDistributedAuthority)
|
||||
{
|
||||
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)
|
||||
{
|
||||
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();
|
||||
@@ -224,10 +308,7 @@ namespace Unity.Netcode
|
||||
networkManager.ConnectionManager.InvokeOnClientConnectedCallback(context.SenderId);
|
||||
|
||||
// For convenience, notify all NetworkBehaviours that synchronization is complete.
|
||||
foreach (var networkObject in networkManager.SpawnManager.SpawnedObjectsList)
|
||||
{
|
||||
networkObject.InternalNetworkSessionSynchronized();
|
||||
}
|
||||
networkManager.SpawnManager.NotifyNetworkObjectsSynchronized();
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -236,10 +317,13 @@ 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);
|
||||
|
||||
// Spawn any in-scene placed NetworkObjects
|
||||
networkManager.SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
|
||||
|
||||
@@ -251,6 +335,14 @@ namespace Unity.Netcode
|
||||
|
||||
// Synchronize the service with the initial session owner's loaded scenes and spawned objects
|
||||
networkManager.SceneManager.SynchronizeNetworkObjects(NetworkManager.ServerClientId);
|
||||
|
||||
// With scene management enabled and since the session owner doesn't send a Synchronize scene event synchronize itself,
|
||||
// we need to notify the session owner that everything should be synchronized/spawned at this time.
|
||||
networkManager.SpawnManager.NotifyNetworkObjectsSynchronized();
|
||||
|
||||
// When scene management is enabled and since the session owner is synchronizing the service (i.e. acting like host),
|
||||
// we need to locallyh invoke the OnClientConnected callback at this point in time.
|
||||
networkManager.ConnectionManager.InvokeOnClientConnectedCallback(OwnerClientId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -17,6 +17,8 @@ namespace Unity.Netcode
|
||||
internal NetworkTransform.NetworkTransformState State;
|
||||
private FastBufferReader m_CurrentReader;
|
||||
|
||||
internal int BytesWritten;
|
||||
|
||||
private unsafe void CopyPayload(ref FastBufferWriter writer)
|
||||
{
|
||||
writer.WriteBytesSafe(m_CurrentReader.GetUnsafePtrAtCurrentPosition(), m_CurrentReader.Length - m_CurrentReader.Position);
|
||||
@@ -30,7 +32,7 @@ namespace Unity.Netcode
|
||||
}
|
||||
else
|
||||
{
|
||||
NetworkTransform.SerializeMessage(writer, targetVersion);
|
||||
BytesWritten = NetworkTransform.SerializeMessage(writer, targetVersion);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,6 +77,7 @@ namespace Unity.Netcode
|
||||
ownerAuthoritativeServerSide = !isServerAuthoritative && networkManager.IsServer;
|
||||
|
||||
reader.ReadNetworkSerializableInPlace(ref NetworkTransform.InboundState);
|
||||
NetworkTransform.InboundState.LastSerializedSize = reader.Position - currentPosition;
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -69,7 +190,8 @@ namespace Unity.Netcode
|
||||
var networkVariable = NetworkBehaviour.NetworkVariableFields[i];
|
||||
var shouldWrite = networkVariable.IsDirty() &&
|
||||
networkVariable.CanClientRead(TargetClientId) &&
|
||||
(networkManager.IsServer || networkVariable.CanClientWrite(networkManager.LocalClientId));
|
||||
(networkManager.IsServer || networkVariable.CanClientWrite(networkManager.LocalClientId)) &&
|
||||
networkVariable.CanSend();
|
||||
|
||||
// Prevent the server from writing to the client that owns a given NetworkVariable
|
||||
// Allowing the write would send an old value to the client and cause jitter
|
||||
@@ -89,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)
|
||||
{
|
||||
@@ -110,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)
|
||||
{
|
||||
@@ -185,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)
|
||||
@@ -194,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;
|
||||
@@ -207,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;
|
||||
@@ -225,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
|
||||
@@ -254,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,
|
||||
@@ -269,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))
|
||||
{
|
||||
@@ -291,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,6 +113,11 @@ namespace Unity.Netcode
|
||||
networkObject.SetNetworkParenting(LatestParent, WorldPositionStays);
|
||||
networkObject.ApplyNetworkParenting(RemoveParent);
|
||||
|
||||
// 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))
|
||||
{
|
||||
// We set all of the transform values after parenting as they are
|
||||
// the values of the server-side post-parenting transform values
|
||||
if (!WorldPositionStays)
|
||||
@@ -130,9 +131,10 @@ namespace Unity.Netcode
|
||||
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,22 +33,14 @@ 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)
|
||||
{
|
||||
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.");
|
||||
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.");
|
||||
}
|
||||
}
|
||||
|
||||
var observers = networkObject.Observers;
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ namespace Unity.Netcode
|
||||
|
||||
payload = new FastBufferReader(reader.GetUnsafePtrAtCurrentPosition(), Allocator.None, reader.Length - reader.Position);
|
||||
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||
if (NetworkBehaviour.__rpc_name_table[networkBehaviour.GetType()].TryGetValue(metadata.NetworkRpcMethodId, out var rpcMethodName))
|
||||
{
|
||||
networkManager.NetworkMetrics.TrackRpcReceived(
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,9 @@ namespace Unity.Netcode
|
||||
internal class NetworkMessageManager : IDisposable
|
||||
{
|
||||
public bool StopProcessing = false;
|
||||
private static Type s_ConnectionApprovedType = typeof(ConnectionApprovedMessage);
|
||||
private static Type s_ConnectionRequestType = typeof(ConnectionRequestMessage);
|
||||
private static Type s_DisconnectReasonType = typeof(DisconnectReasonMessage);
|
||||
|
||||
private struct ReceiveQueueItem
|
||||
{
|
||||
@@ -138,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)
|
||||
{
|
||||
@@ -524,6 +505,7 @@ namespace Unity.Netcode
|
||||
return new T().Version;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal int GetMessageVersion(Type type, ulong clientId, bool forReceive = false)
|
||||
{
|
||||
if (!m_PerClientMessageVersions.TryGetValue(clientId, out var versionMap))
|
||||
@@ -551,16 +533,20 @@ namespace Unity.Netcode
|
||||
return messageVersion;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static void ReceiveMessage<T>(FastBufferReader reader, ref NetworkContext context, NetworkMessageManager manager) where T : INetworkMessage, new()
|
||||
{
|
||||
var messageType = typeof(T);
|
||||
var message = new T();
|
||||
var messageVersion = 0;
|
||||
|
||||
// Special cases because these are the messages that carry the version info - thus the version info isn't
|
||||
// populated yet when we get these. The first part of these messages always has to be the version data
|
||||
// and can't change.
|
||||
if (typeof(T) != typeof(ConnectionRequestMessage) && typeof(T) != typeof(ConnectionApprovedMessage) && typeof(T) != typeof(DisconnectReasonMessage) && context.SenderId != manager.m_LocalClientId)
|
||||
if (messageType != s_ConnectionRequestType && messageType != s_ConnectionApprovedType && messageType != s_DisconnectReasonType && context.SenderId != manager.m_LocalClientId)
|
||||
{
|
||||
messageVersion = manager.GetMessageVersion(typeof(T), context.SenderId, true);
|
||||
messageVersion = manager.GetMessageVersion(messageType, context.SenderId, true);
|
||||
if (messageVersion < 0)
|
||||
{
|
||||
return;
|
||||
@@ -612,7 +598,7 @@ namespace Unity.Netcode
|
||||
var messageVersion = 0;
|
||||
// Special case because this is the message that carries the version info - thus the version info isn't populated yet when we get this.
|
||||
// The first part of this message always has to be the version data and can't change.
|
||||
if (typeof(TMessageType) != typeof(ConnectionRequestMessage))
|
||||
if (typeof(TMessageType) != s_ConnectionRequestType)
|
||||
{
|
||||
messageVersion = GetMessageVersion(typeof(TMessageType), clientIds[i]);
|
||||
if (messageVersion < 0)
|
||||
@@ -666,7 +652,7 @@ namespace Unity.Netcode
|
||||
|
||||
// Special case because this is the message that carries the version info - thus the version info isn't populated yet when we get this.
|
||||
// The first part of this message always has to be the version data and can't change.
|
||||
if (typeof(TMessageType) != typeof(ConnectionRequestMessage))
|
||||
if (typeof(TMessageType) != s_ConnectionRequestType)
|
||||
{
|
||||
var messageVersion = GetMessageVersion(typeof(TMessageType), clientIds[i]);
|
||||
if (messageVersion < 0)
|
||||
@@ -725,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);
|
||||
@@ -746,7 +736,7 @@ namespace Unity.Netcode
|
||||
// Special case because this is the message that carries the version info - thus the version info isn't
|
||||
// populated yet when we get this. The first part of this message always has to be the version data
|
||||
// and can't change.
|
||||
if (typeof(TMessageType) != typeof(ConnectionRequestMessage))
|
||||
if (typeof(TMessageType) != s_ConnectionRequestType)
|
||||
{
|
||||
messageVersion = GetMessageVersion(typeof(TMessageType), clientId);
|
||||
if (messageVersion < 0)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -36,12 +36,12 @@ namespace Unity.Netcode
|
||||
|
||||
private protected void SendMessageToClient(NetworkBehaviour behaviour, ulong clientId, ref RpcMessage message, NetworkDelivery delivery)
|
||||
{
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||
var size =
|
||||
#endif
|
||||
behaviour.NetworkManager.MessageManager.SendMessage(ref message, delivery, clientId);
|
||||
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
|
||||
{
|
||||
behaviour.NetworkManager.NetworkMetrics.TrackRpcSent(
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -4,23 +4,37 @@ namespace Unity.Netcode
|
||||
{
|
||||
private NotServerRpcTarget m_NotServerRpcTarget;
|
||||
private ServerRpcTarget m_ServerRpcTarget;
|
||||
private NotAuthorityRpcTarget m_NotAuthorityRpcTarget;
|
||||
private AuthorityRpcTarget m_AuthorityRpcTarget;
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
m_NotServerRpcTarget.Dispose();
|
||||
m_ServerRpcTarget.Dispose();
|
||||
m_NotAuthorityRpcTarget.Dispose();
|
||||
m_AuthorityRpcTarget.Dispose();
|
||||
}
|
||||
|
||||
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
|
||||
{
|
||||
if (NetworkManager.IsDistributedAuthority)
|
||||
{
|
||||
m_NotAuthorityRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||
m_AuthorityRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||
}
|
||||
else
|
||||
{
|
||||
m_NotServerRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||
m_ServerRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||
}
|
||||
}
|
||||
|
||||
internal EveryoneRpcTarget(NetworkManager manager) : base(manager)
|
||||
{
|
||||
m_NotServerRpcTarget = new NotServerRpcTarget(manager);
|
||||
m_ServerRpcTarget = new ServerRpcTarget(manager);
|
||||
m_NotAuthorityRpcTarget = new NotAuthorityRpcTarget(manager);
|
||||
m_AuthorityRpcTarget = new AuthorityRpcTarget(manager);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ namespace Unity.Netcode
|
||||
message.Handle(ref context);
|
||||
length = tempBuffer.Length;
|
||||
}
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
|
||||
{
|
||||
networkManager.NetworkMetrics.TrackRpcSent(
|
||||
|
||||
@@ -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,13 +17,18 @@ namespace Unity.Netcode
|
||||
|
||||
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
|
||||
{
|
||||
// If there are no targets then don't attempt to send anything.
|
||||
if (TargetClientIds.Length == 0 && Ids.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var proxyMessage = new ProxyMessage { Delivery = delivery, TargetClientIds = TargetClientIds.AsArray(), WrappedMessage = message };
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||
var size =
|
||||
#endif
|
||||
behaviour.NetworkManager.MessageManager.SendMessage(ref proxyMessage, delivery, NetworkManager.ServerClientId);
|
||||
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR || UNITY_MP_TOOLS_NET_STATS_MONITOR_ENABLED_IN_RELEASE
|
||||
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
|
||||
{
|
||||
foreach (var clientId in TargetClientIds)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
392
Runtime/NetworkVariable/AnticipatedNetworkVariable.cs
Normal file
392
Runtime/NetworkVariable/AnticipatedNetworkVariable.cs
Normal file
@@ -0,0 +1,392 @@
|
||||
using System;
|
||||
using Unity.Mathematics;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
|
||||
public enum StaleDataHandling
|
||||
{
|
||||
Ignore,
|
||||
Reanticipate
|
||||
}
|
||||
|
||||
#pragma warning disable IDE0001
|
||||
/// <summary>
|
||||
/// A variable that can be synchronized over the network.
|
||||
/// This version supports basic client anticipation - the client can set a value on the belief that the server
|
||||
/// will update it to reflect the same value in a future update (i.e., as the result of an RPC call).
|
||||
/// This value can then be adjusted as new updates from the server come in, in three basic modes:
|
||||
///
|
||||
/// <list type="bullet">
|
||||
///
|
||||
/// <item><b>Snap:</b> In this mode (with <see cref="StaleDataHandling"/> set to
|
||||
/// <see cref="Netcode.StaleDataHandling.Ignore"/> and no <see cref="NetworkBehaviour.OnReanticipate"/> callback),
|
||||
/// the moment a more up-to-date value is received from the authority, it will simply replace the anticipated value,
|
||||
/// resulting in a "snap" to the new value if it is different from the anticipated value.</item>
|
||||
///
|
||||
/// <item><b>Smooth:</b> In this mode (with <see cref="StaleDataHandling"/> set to
|
||||
/// <see cref="Netcode.StaleDataHandling.Ignore"/> and an <see cref="NetworkBehaviour.OnReanticipate"/> callback that calls
|
||||
/// <see cref="Smooth"/> from the anticipated value to the authority value with an appropriate
|
||||
/// <see cref="Mathf.Lerp"/>-style smooth function), when a more up-to-date value is received from the authority,
|
||||
/// it will interpolate over time from an incorrect anticipated value to the correct authoritative value.</item>
|
||||
///
|
||||
/// <item><b>Constant Reanticipation:</b> In this mode (with <see cref="StaleDataHandling"/> set to
|
||||
/// <see cref="Netcode.StaleDataHandling.Reanticipate"/> and an <see cref="NetworkBehaviour.OnReanticipate"/> that calculates a
|
||||
/// new anticipated value based on the current authoritative value), when a more up-to-date value is received from
|
||||
/// the authority, user code calculates a new anticipated value, possibly calling <see cref="Smooth"/> to interpolate
|
||||
/// between the previous anticipation and the new anticipation. This is useful for values that change frequently and
|
||||
/// need to constantly be re-evaluated, as opposed to values that change only in response to user action and simply
|
||||
/// need a one-time anticipation when the user performs that action.</item>
|
||||
///
|
||||
/// </list>
|
||||
///
|
||||
/// Note that these three modes may be combined. For example, if an <see cref="NetworkBehaviour.OnReanticipate"/> callback
|
||||
/// does not call either <see cref="Smooth"/> or <see cref="Anticipate"/>, the result will be a snap to the
|
||||
/// authoritative value, enabling for a callback that may conditionally call <see cref="Smooth"/> when the
|
||||
/// difference between the anticipated and authoritative values is within some threshold, but fall back to
|
||||
/// snap behavior if the difference is too large.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">the unmanaged type for <see cref="NetworkVariable{T}"/> </typeparam>
|
||||
#pragma warning restore IDE0001
|
||||
[Serializable]
|
||||
[GenerateSerializationForGenericParameter(0)]
|
||||
public class AnticipatedNetworkVariable<T> : NetworkVariableBase
|
||||
{
|
||||
[SerializeField]
|
||||
private NetworkVariable<T> m_AuthoritativeValue;
|
||||
private T m_AnticipatedValue;
|
||||
private T m_PreviousAnticipatedValue;
|
||||
private ulong m_LastAuthorityUpdateCounter = 0;
|
||||
private ulong m_LastAnticipationCounter = 0;
|
||||
private bool m_IsDisposed = false;
|
||||
private bool m_SettingAuthoritativeValue = false;
|
||||
|
||||
private T m_SmoothFrom;
|
||||
private T m_SmoothTo;
|
||||
private float m_SmoothDuration;
|
||||
private float m_CurrentSmoothTime;
|
||||
private bool m_HasSmoothValues;
|
||||
|
||||
#pragma warning disable IDE0001
|
||||
/// <summary>
|
||||
/// Defines what the behavior should be if we receive a value from the server with an earlier associated
|
||||
/// time value than the anticipation time value.
|
||||
/// <br/><br/>
|
||||
/// If this is <see cref="Netcode.StaleDataHandling.Ignore"/>, the stale data will be ignored and the authoritative
|
||||
/// value will not replace the anticipated value until the anticipation time is reached. <see cref="OnAuthoritativeValueChanged"/>
|
||||
/// and <see cref="NetworkBehaviour.OnReanticipate"/> will also not be invoked for this stale data.
|
||||
/// <br/><br/>
|
||||
/// If this is <see cref="Netcode.StaleDataHandling.Reanticipate"/>, the stale data will replace the anticipated data and
|
||||
/// <see cref="OnAuthoritativeValueChanged"/> and <see cref="NetworkBehaviour.OnReanticipate"/> will be invoked.
|
||||
/// In this case, the authoritativeTime value passed to <see cref="NetworkBehaviour.OnReanticipate"/> will be lower than
|
||||
/// the anticipationTime value, and that callback can be used to calculate a new anticipated value.
|
||||
/// </summary>
|
||||
#pragma warning restore IDE0001
|
||||
public StaleDataHandling StaleDataHandling;
|
||||
|
||||
public delegate void OnAuthoritativeValueChangedDelegate(AnticipatedNetworkVariable<T> variable, in T previousValue, in T newValue);
|
||||
|
||||
/// <summary>
|
||||
/// Invoked any time the authoritative value changes, even when the data is stale or has been changed locally.
|
||||
/// </summary>
|
||||
public OnAuthoritativeValueChangedDelegate OnAuthoritativeValueChanged = null;
|
||||
|
||||
/// <summary>
|
||||
/// Determines if the difference between the last serialized value and the current value is large enough
|
||||
/// to serialize it again.
|
||||
/// </summary>
|
||||
public event NetworkVariable<T>.CheckExceedsDirtinessThresholdDelegate CheckExceedsDirtinessThreshold
|
||||
{
|
||||
add => m_AuthoritativeValue.CheckExceedsDirtinessThreshold += value;
|
||||
remove => m_AuthoritativeValue.CheckExceedsDirtinessThreshold -= value;
|
||||
}
|
||||
|
||||
private class AnticipatedObject : IAnticipatedObject
|
||||
{
|
||||
public AnticipatedNetworkVariable<T> Variable;
|
||||
|
||||
public void Update()
|
||||
{
|
||||
Variable.Update();
|
||||
}
|
||||
|
||||
public void ResetAnticipation()
|
||||
{
|
||||
Variable.ShouldReanticipate = false;
|
||||
}
|
||||
|
||||
public NetworkObject OwnerObject => Variable.m_NetworkBehaviour.NetworkObject;
|
||||
}
|
||||
|
||||
private AnticipatedObject m_AnticipatedObject;
|
||||
|
||||
public override void OnInitialize()
|
||||
{
|
||||
m_AuthoritativeValue.Initialize(m_NetworkBehaviour);
|
||||
NetworkVariableSerialization<T>.Duplicate(m_AuthoritativeValue.Value, ref m_AnticipatedValue);
|
||||
NetworkVariableSerialization<T>.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue);
|
||||
if (m_NetworkBehaviour != null && m_NetworkBehaviour.NetworkManager != null && m_NetworkBehaviour.NetworkManager.AnticipationSystem != null)
|
||||
{
|
||||
m_AnticipatedObject = new AnticipatedObject { Variable = this };
|
||||
m_NetworkBehaviour.NetworkManager.AnticipationSystem.AllAnticipatedObjects.Add(m_AnticipatedObject);
|
||||
}
|
||||
}
|
||||
|
||||
public override bool ExceedsDirtinessThreshold()
|
||||
{
|
||||
return m_AuthoritativeValue.ExceedsDirtinessThreshold();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the current value for the variable.
|
||||
/// This is the "display value" for this variable, and is affected by <see cref="Anticipate"/> and
|
||||
/// <see cref="Smooth"/>, as well as by updates from the authority, depending on <see cref="StaleDataHandling"/>
|
||||
/// and the behavior of any <see cref="NetworkBehaviour.OnReanticipate"/> callbacks.
|
||||
/// <br /><br />
|
||||
/// When a server update arrives, this value will be overwritten
|
||||
/// by the new server value (unless stale data handling is set
|
||||
/// to "Ignore" and the update is determined to be stale).
|
||||
/// This value will be duplicated in
|
||||
/// <see cref="PreviousAnticipatedValue"/>, which
|
||||
/// will NOT be overwritten in server updates.
|
||||
/// </summary>
|
||||
public T Value => m_AnticipatedValue;
|
||||
|
||||
/// <summary>
|
||||
/// Indicates whether this variable currently needs
|
||||
/// reanticipation. If this is true, the anticipated value
|
||||
/// has been overwritten by the authoritative value from the
|
||||
/// server; the previous anticipated value is stored in <see cref="PreviousAnticipatedState"/>
|
||||
/// </summary>
|
||||
public bool ShouldReanticipate
|
||||
{
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Holds the most recent anticipated value, whatever was
|
||||
/// most recently set using <see cref="Anticipate"/>. Unlike
|
||||
/// <see cref="Value"/>, this does not get overwritten
|
||||
/// when a server update arrives.
|
||||
/// </summary>
|
||||
public T PreviousAnticipatedValue => m_PreviousAnticipatedValue;
|
||||
|
||||
/// <summary>
|
||||
/// Sets the current value of the variable on the expectation that the authority will set the variable
|
||||
/// to the same value within one network round trip (i.e., in response to an RPC).
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
public void Anticipate(T value)
|
||||
{
|
||||
if (m_NetworkBehaviour.NetworkManager.ShutdownInProgress || !m_NetworkBehaviour.NetworkManager.IsListening)
|
||||
{
|
||||
return;
|
||||
}
|
||||
m_SmoothDuration = 0;
|
||||
m_CurrentSmoothTime = 0;
|
||||
m_LastAnticipationCounter = m_NetworkBehaviour.NetworkManager.AnticipationSystem.AnticipationCounter;
|
||||
m_AnticipatedValue = value;
|
||||
NetworkVariableSerialization<T>.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue);
|
||||
if (CanClientWrite(m_NetworkBehaviour.NetworkManager.LocalClientId))
|
||||
{
|
||||
AuthoritativeValue = value;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma warning disable IDE0001
|
||||
/// <summary>
|
||||
/// Retrieves or sets the underlying authoritative value.
|
||||
/// Note that only a client or server with write permissions to this variable may set this value.
|
||||
/// When this variable has been anticipated, this value will alawys return the most recent authoritative
|
||||
/// state, which is updated even if <see cref="StaleDataHandling"/> is <see cref="Netcode.StaleDataHandling.Ignore"/>.
|
||||
/// </summary>
|
||||
#pragma warning restore IDE0001
|
||||
public T AuthoritativeValue
|
||||
{
|
||||
get => m_AuthoritativeValue.Value;
|
||||
set
|
||||
{
|
||||
m_SettingAuthoritativeValue = true;
|
||||
try
|
||||
{
|
||||
m_AuthoritativeValue.Value = value;
|
||||
m_AnticipatedValue = value;
|
||||
NetworkVariableSerialization<T>.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue);
|
||||
}
|
||||
finally
|
||||
{
|
||||
m_SettingAuthoritativeValue = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A function to interpolate between two values based on a percentage.
|
||||
/// See <see cref="Mathf.Lerp"/>, <see cref="Vector3.Lerp"/>, <see cref="Vector3.Slerp"/>, and so on
|
||||
/// for examples.
|
||||
/// </summary>
|
||||
public delegate T SmoothDelegate(T authoritativeValue, T anticipatedValue, float amount);
|
||||
|
||||
private SmoothDelegate m_SmoothDelegate = null;
|
||||
|
||||
public AnticipatedNetworkVariable(T value = default,
|
||||
StaleDataHandling staleDataHandling = StaleDataHandling.Ignore)
|
||||
: base()
|
||||
{
|
||||
StaleDataHandling = staleDataHandling;
|
||||
m_AuthoritativeValue = new NetworkVariable<T>(value)
|
||||
{
|
||||
OnValueChanged = OnValueChangedInternal
|
||||
};
|
||||
}
|
||||
|
||||
public void Update()
|
||||
{
|
||||
if (m_CurrentSmoothTime < m_SmoothDuration)
|
||||
{
|
||||
m_CurrentSmoothTime += m_NetworkBehaviour.NetworkManager.RealTimeProvider.DeltaTime;
|
||||
var pct = math.min(m_CurrentSmoothTime / m_SmoothDuration, 1f);
|
||||
m_AnticipatedValue = m_SmoothDelegate(m_SmoothFrom, m_SmoothTo, pct);
|
||||
NetworkVariableSerialization<T>.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue);
|
||||
}
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
if (m_IsDisposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (m_NetworkBehaviour != null && m_NetworkBehaviour.NetworkManager != null && m_NetworkBehaviour.NetworkManager.AnticipationSystem != null)
|
||||
{
|
||||
if (m_AnticipatedObject != null)
|
||||
{
|
||||
m_NetworkBehaviour.NetworkManager.AnticipationSystem.AllAnticipatedObjects.Remove(m_AnticipatedObject);
|
||||
m_NetworkBehaviour.NetworkManager.AnticipationSystem.ObjectsToReanticipate.Remove(m_AnticipatedObject);
|
||||
m_AnticipatedObject = null;
|
||||
}
|
||||
}
|
||||
|
||||
m_IsDisposed = true;
|
||||
|
||||
m_AuthoritativeValue.Dispose();
|
||||
if (m_AnticipatedValue is IDisposable anticipatedValueDisposable)
|
||||
{
|
||||
anticipatedValueDisposable.Dispose();
|
||||
}
|
||||
|
||||
m_AnticipatedValue = default;
|
||||
if (m_PreviousAnticipatedValue is IDisposable previousValueDisposable)
|
||||
{
|
||||
previousValueDisposable.Dispose();
|
||||
m_PreviousAnticipatedValue = default;
|
||||
}
|
||||
|
||||
if (m_HasSmoothValues)
|
||||
{
|
||||
if (m_SmoothFrom is IDisposable smoothFromDisposable)
|
||||
{
|
||||
smoothFromDisposable.Dispose();
|
||||
m_SmoothFrom = default;
|
||||
}
|
||||
if (m_SmoothTo is IDisposable smoothToDisposable)
|
||||
{
|
||||
smoothToDisposable.Dispose();
|
||||
m_SmoothTo = default;
|
||||
}
|
||||
|
||||
m_HasSmoothValues = false;
|
||||
}
|
||||
}
|
||||
|
||||
~AnticipatedNetworkVariable()
|
||||
{
|
||||
Dispose();
|
||||
}
|
||||
|
||||
private void OnValueChangedInternal(T previousValue, T newValue)
|
||||
{
|
||||
if (!m_SettingAuthoritativeValue)
|
||||
{
|
||||
m_LastAuthorityUpdateCounter = m_NetworkBehaviour.NetworkManager.AnticipationSystem.LastAnticipationAck;
|
||||
if (StaleDataHandling == StaleDataHandling.Ignore && m_LastAnticipationCounter > m_LastAuthorityUpdateCounter)
|
||||
{
|
||||
// Keep the anticipated value unchanged because it is more recent than the authoritative one.
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
ShouldReanticipate = true;
|
||||
m_NetworkBehaviour.NetworkManager.AnticipationSystem.ObjectsToReanticipate.Add(m_AnticipatedObject);
|
||||
}
|
||||
|
||||
NetworkVariableSerialization<T>.Duplicate(AuthoritativeValue, ref m_AnticipatedValue);
|
||||
|
||||
m_SmoothDuration = 0;
|
||||
m_CurrentSmoothTime = 0;
|
||||
OnAuthoritativeValueChanged?.Invoke(this, previousValue, newValue);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Interpolate this variable from <see cref="from"/> to <see cref="to"/> over <see cref="durationSeconds"/> of
|
||||
/// real time. The duration uses <see cref="Time.deltaTime"/>, so it is affected by <see cref="Time.timeScale"/>.
|
||||
/// </summary>
|
||||
/// <param name="from"></param>
|
||||
/// <param name="to"></param>
|
||||
/// <param name="durationSeconds"></param>
|
||||
/// <param name="how"></param>
|
||||
public void Smooth(in T from, in T to, float durationSeconds, SmoothDelegate how)
|
||||
{
|
||||
if (durationSeconds <= 0)
|
||||
{
|
||||
NetworkVariableSerialization<T>.Duplicate(to, ref m_AnticipatedValue);
|
||||
m_SmoothDuration = 0;
|
||||
m_CurrentSmoothTime = 0;
|
||||
m_SmoothDelegate = null;
|
||||
return;
|
||||
}
|
||||
NetworkVariableSerialization<T>.Duplicate(from, ref m_AnticipatedValue);
|
||||
NetworkVariableSerialization<T>.Duplicate(from, ref m_SmoothFrom);
|
||||
NetworkVariableSerialization<T>.Duplicate(to, ref m_SmoothTo);
|
||||
m_SmoothDuration = durationSeconds;
|
||||
m_CurrentSmoothTime = 0;
|
||||
m_SmoothDelegate = how;
|
||||
m_HasSmoothValues = true;
|
||||
}
|
||||
|
||||
public override bool IsDirty()
|
||||
{
|
||||
return m_AuthoritativeValue.IsDirty();
|
||||
}
|
||||
|
||||
public override void ResetDirty()
|
||||
{
|
||||
m_AuthoritativeValue.ResetDirty();
|
||||
}
|
||||
|
||||
public override void WriteDelta(FastBufferWriter writer)
|
||||
{
|
||||
m_AuthoritativeValue.WriteDelta(writer);
|
||||
}
|
||||
|
||||
public override void WriteField(FastBufferWriter writer)
|
||||
{
|
||||
m_AuthoritativeValue.WriteField(writer);
|
||||
}
|
||||
|
||||
public override void ReadField(FastBufferReader reader)
|
||||
{
|
||||
m_AuthoritativeValue.ReadField(reader);
|
||||
NetworkVariableSerialization<T>.Duplicate(m_AuthoritativeValue.Value, ref m_AnticipatedValue);
|
||||
NetworkVariableSerialization<T>.Duplicate(m_AnticipatedValue, ref m_PreviousAnticipatedValue);
|
||||
}
|
||||
|
||||
public override void ReadDelta(FastBufferReader reader, bool keepDirtyDelta)
|
||||
{
|
||||
m_AuthoritativeValue.ReadDelta(reader, keepDirtyDelta);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: fc9fd5701bee8534a971eb9f49178e21
|
||||
@@ -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()
|
||||
{
|
||||
@@ -94,18 +98,18 @@ namespace Unity.Netcode
|
||||
{
|
||||
case NetworkListEvent<T>.EventType.Add:
|
||||
{
|
||||
NetworkVariableSerialization<T>.Write(writer, ref element.Value);
|
||||
NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
|
||||
}
|
||||
break;
|
||||
case NetworkListEvent<T>.EventType.Insert:
|
||||
{
|
||||
BytePacker.WriteValueBitPacked(writer, element.Index);
|
||||
NetworkVariableSerialization<T>.Write(writer, ref element.Value);
|
||||
NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
|
||||
}
|
||||
break;
|
||||
case NetworkListEvent<T>.EventType.Remove:
|
||||
{
|
||||
NetworkVariableSerialization<T>.Write(writer, ref element.Value);
|
||||
NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
|
||||
}
|
||||
break;
|
||||
case NetworkListEvent<T>.EventType.RemoveAt:
|
||||
@@ -116,7 +120,7 @@ namespace Unity.Netcode
|
||||
case NetworkListEvent<T>.EventType.Value:
|
||||
{
|
||||
BytePacker.WriteValueBitPacked(writer, element.Index);
|
||||
NetworkVariableSerialization<T>.Write(writer, ref element.Value);
|
||||
NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
|
||||
}
|
||||
break;
|
||||
case NetworkListEvent<T>.EventType.Clear:
|
||||
@@ -131,24 +135,10 @@ namespace Unity.Netcode
|
||||
/// <inheritdoc />
|
||||
public override void WriteField(FastBufferWriter writer)
|
||||
{
|
||||
if (m_NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
writer.WriteValueSafe(NetworkVariableSerialization<T>.Type);
|
||||
if (NetworkVariableSerialization<T>.Type == CollectionItemType.Unmanaged)
|
||||
{
|
||||
// Write the size of the unmanaged serialized type as it has a fixed size. This allows the CMB runtime to correctly read the unmanged type.
|
||||
var placeholder = new T();
|
||||
var startPos = writer.Position;
|
||||
NetworkVariableSerialization<T>.Write(writer, ref placeholder);
|
||||
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++)
|
||||
{
|
||||
NetworkVariableSerialization<T>.Write(writer, ref m_List.ElementAt(i));
|
||||
NetworkVariableSerialization<T>.Serializer.Write(writer, ref m_List.ElementAt(i));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,20 +146,11 @@ namespace Unity.Netcode
|
||||
public override void ReadField(FastBufferReader reader)
|
||||
{
|
||||
m_List.Clear();
|
||||
if (m_NetworkManager.DistributedAuthorityMode)
|
||||
{
|
||||
// Collection item type is used by the CMB rust service, drop value here.
|
||||
reader.ReadValueSafe(out CollectionItemType type);
|
||||
if (type == CollectionItemType.Unmanaged)
|
||||
{
|
||||
ByteUnpacker.ReadValueBitPacked(reader, out int _);
|
||||
}
|
||||
}
|
||||
reader.ReadValueSafe(out ushort count);
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
var value = new T();
|
||||
NetworkVariableSerialization<T>.Read(reader, ref value);
|
||||
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
|
||||
m_List.Add(value);
|
||||
}
|
||||
}
|
||||
@@ -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++)
|
||||
{
|
||||
@@ -186,7 +174,7 @@ namespace Unity.Netcode
|
||||
case NetworkListEvent<T>.EventType.Add:
|
||||
{
|
||||
var value = new T();
|
||||
NetworkVariableSerialization<T>.Read(reader, ref value);
|
||||
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
|
||||
m_List.Add(value);
|
||||
|
||||
if (OnListChanged != null)
|
||||
@@ -199,7 +187,7 @@ namespace Unity.Netcode
|
||||
});
|
||||
}
|
||||
|
||||
if (keepDirtyDelta)
|
||||
if (isServer)
|
||||
{
|
||||
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
||||
{
|
||||
@@ -207,15 +195,19 @@ namespace Unity.Netcode
|
||||
Index = m_List.Length - 1,
|
||||
Value = m_List[m_List.Length - 1]
|
||||
});
|
||||
// Preserve the legacy way of handling this
|
||||
if (keepDirtyDelta)
|
||||
{
|
||||
MarkNetworkObjectDirty();
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
case NetworkListEvent<T>.EventType.Insert:
|
||||
{
|
||||
ByteUnpacker.ReadValueBitPacked(reader, out int index);
|
||||
var value = new T();
|
||||
NetworkVariableSerialization<T>.Read(reader, ref value);
|
||||
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
|
||||
|
||||
if (index < m_List.Length)
|
||||
{
|
||||
@@ -237,7 +229,7 @@ namespace Unity.Netcode
|
||||
});
|
||||
}
|
||||
|
||||
if (keepDirtyDelta)
|
||||
if (isServer)
|
||||
{
|
||||
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
||||
{
|
||||
@@ -245,14 +237,18 @@ namespace Unity.Netcode
|
||||
Index = index,
|
||||
Value = m_List[index]
|
||||
});
|
||||
// Preserve the legacy way of handling this
|
||||
if (keepDirtyDelta)
|
||||
{
|
||||
MarkNetworkObjectDirty();
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
case NetworkListEvent<T>.EventType.Remove:
|
||||
{
|
||||
var value = new T();
|
||||
NetworkVariableSerialization<T>.Read(reader, ref value);
|
||||
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
|
||||
int index = m_List.IndexOf(value);
|
||||
if (index == -1)
|
||||
{
|
||||
@@ -271,7 +267,7 @@ namespace Unity.Netcode
|
||||
});
|
||||
}
|
||||
|
||||
if (keepDirtyDelta)
|
||||
if (isServer)
|
||||
{
|
||||
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
||||
{
|
||||
@@ -279,9 +275,13 @@ namespace Unity.Netcode
|
||||
Index = index,
|
||||
Value = value
|
||||
});
|
||||
// Preserve the legacy way of handling this
|
||||
if (keepDirtyDelta)
|
||||
{
|
||||
MarkNetworkObjectDirty();
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
case NetworkListEvent<T>.EventType.RemoveAt:
|
||||
{
|
||||
@@ -299,7 +299,7 @@ namespace Unity.Netcode
|
||||
});
|
||||
}
|
||||
|
||||
if (keepDirtyDelta)
|
||||
if (isServer)
|
||||
{
|
||||
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
||||
{
|
||||
@@ -307,15 +307,19 @@ namespace Unity.Netcode
|
||||
Index = index,
|
||||
Value = value
|
||||
});
|
||||
// Preserve the legacy way of handling this
|
||||
if (keepDirtyDelta)
|
||||
{
|
||||
MarkNetworkObjectDirty();
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
case NetworkListEvent<T>.EventType.Value:
|
||||
{
|
||||
ByteUnpacker.ReadValueBitPacked(reader, out int index);
|
||||
var value = new T();
|
||||
NetworkVariableSerialization<T>.Read(reader, ref value);
|
||||
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
|
||||
if (index >= m_List.Length)
|
||||
{
|
||||
throw new Exception("Shouldn't be here, index is higher than list length");
|
||||
@@ -335,7 +339,7 @@ namespace Unity.Netcode
|
||||
});
|
||||
}
|
||||
|
||||
if (keepDirtyDelta)
|
||||
if (isServer)
|
||||
{
|
||||
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
||||
{
|
||||
@@ -344,9 +348,13 @@ namespace Unity.Netcode
|
||||
Value = value,
|
||||
PreviousValue = previousValue
|
||||
});
|
||||
// Preserve the legacy way of handling this
|
||||
if (keepDirtyDelta)
|
||||
{
|
||||
MarkNetworkObjectDirty();
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
case NetworkListEvent<T>.EventType.Clear:
|
||||
{
|
||||
@@ -361,15 +369,20 @@ namespace Unity.Netcode
|
||||
});
|
||||
}
|
||||
|
||||
if (keepDirtyDelta)
|
||||
if (isServer)
|
||||
{
|
||||
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
||||
{
|
||||
Type = eventType
|
||||
});
|
||||
|
||||
// Preserve the legacy way of handling this
|
||||
if (keepDirtyDelta)
|
||||
{
|
||||
MarkNetworkObjectDirty();
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
case NetworkListEvent<T>.EventType.Full:
|
||||
{
|
||||
@@ -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];
|
||||
@@ -572,9 +604,17 @@ namespace Unity.Netcode
|
||||
/// you **must** always invoke the base.Dispose() method!
|
||||
/// </summary>
|
||||
public override void Dispose()
|
||||
{
|
||||
if (m_List.IsCreated)
|
||||
{
|
||||
m_List.Dispose();
|
||||
}
|
||||
|
||||
if (m_DirtyEvents.IsCreated)
|
||||
{
|
||||
m_DirtyEvents.Dispose();
|
||||
}
|
||||
|
||||
base.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,29 @@ namespace Unity.Netcode
|
||||
/// The callback to be invoked when the value gets changed
|
||||
/// </summary>
|
||||
public OnValueChangedDelegate OnValueChanged;
|
||||
internal override NetworkVariableType Type => NetworkVariableType.Value;
|
||||
|
||||
public delegate bool CheckExceedsDirtinessThresholdDelegate(in T previousValue, in T newValue);
|
||||
|
||||
public CheckExceedsDirtinessThresholdDelegate CheckExceedsDirtinessThreshold;
|
||||
|
||||
public override bool ExceedsDirtinessThreshold()
|
||||
{
|
||||
if (CheckExceedsDirtinessThreshold != null && m_HasPreviousValue)
|
||||
{
|
||||
return CheckExceedsDirtinessThreshold(m_PreviousValue, m_InternalValue);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public override void OnInitialize()
|
||||
{
|
||||
base.OnInitialize();
|
||||
|
||||
m_HasPreviousValue = true;
|
||||
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_InternalOriginalValue);
|
||||
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_PreviousValue);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructor for <see cref="NetworkVariable{T}"/>
|
||||
@@ -35,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
|
||||
@@ -53,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;
|
||||
}
|
||||
}
|
||||
@@ -63,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;
|
||||
@@ -71,25 +101,69 @@ 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()
|
||||
@@ -105,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();
|
||||
@@ -133,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.
|
||||
@@ -144,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;
|
||||
}
|
||||
@@ -166,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>
|
||||
@@ -199,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 />
|
||||
@@ -226,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,11 +3,26 @@ using UnityEngine;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
public struct NetworkVariableUpdateTraits
|
||||
{
|
||||
[Tooltip("The minimum amount of time that must pass between sending updates. If this amount of time has not passed since the last update, dirtiness will be ignored.")]
|
||||
public float MinSecondsBetweenUpdates;
|
||||
|
||||
[Tooltip("The maximum amount of time that a variable can be dirty without sending an update. If this amount of time has passed since the last update, an update will be sent even if the dirtiness threshold has not been met.")]
|
||||
public float MaxSecondsBetweenUpdates;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Interface for network value containers
|
||||
/// </summary>
|
||||
public abstract class NetworkVariableBase : IDisposable
|
||||
{
|
||||
[SerializeField]
|
||||
internal NetworkVariableUpdateTraits UpdateTraits = default;
|
||||
|
||||
[NonSerialized]
|
||||
internal double LastUpdateSent;
|
||||
|
||||
/// <summary>
|
||||
/// The delivery type (QoS) to send data with
|
||||
/// </summary>
|
||||
@@ -20,7 +35,15 @@ namespace Unity.Netcode
|
||||
|
||||
private NetworkManager m_InternalNetworkManager;
|
||||
|
||||
internal virtual NetworkVariableType Type => NetworkVariableType.Custom;
|
||||
internal string GetWritePermissionError()
|
||||
{
|
||||
return $"|Client-{m_NetworkManager.LocalClientId}|{m_NetworkBehaviour.name}|{Name}| Write permissions ({WritePerm}) for this client instance is not allowed!";
|
||||
}
|
||||
|
||||
internal void LogWritePermissionError()
|
||||
{
|
||||
Debug.LogError(GetWritePermissionError());
|
||||
}
|
||||
|
||||
private protected NetworkManager m_NetworkManager
|
||||
{
|
||||
@@ -52,9 +75,44 @@ namespace Unity.Netcode
|
||||
m_InternalNetworkManager = m_NetworkBehaviour.NetworkObject?.NetworkManager;
|
||||
// When in distributed authority mode, there is no such thing as server write permissions
|
||||
InternalWritePerm = m_InternalNetworkManager.DistributedAuthorityMode ? NetworkVariableWritePermission.Owner : InternalWritePerm;
|
||||
|
||||
if (m_NetworkBehaviour.NetworkManager.NetworkTimeSystem != null)
|
||||
{
|
||||
UpdateLastSentTime();
|
||||
}
|
||||
}
|
||||
|
||||
OnInitialize();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called on initialization
|
||||
/// </summary>
|
||||
public virtual void OnInitialize()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the update traits for this network variable to determine how frequently it will send updates.
|
||||
/// </summary>
|
||||
/// <param name="traits"></param>
|
||||
public void SetUpdateTraits(NetworkVariableUpdateTraits traits)
|
||||
{
|
||||
UpdateTraits = traits;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check whether or not this variable has changed significantly enough to send an update.
|
||||
/// If not, no update will be sent even if the variable is dirty, unless the time since last update exceeds
|
||||
/// the <see cref="UpdateTraits"/>' <see cref="NetworkVariableUpdateTraits.MaxSecondsBetweenUpdates"/>.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public virtual bool ExceedsDirtinessThreshold()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The default read permissions
|
||||
/// </summary>
|
||||
@@ -125,6 +183,28 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
internal bool CanSend()
|
||||
{
|
||||
// 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 &&
|
||||
timeSinceLastUpdate >= UpdateTraits.MaxSecondsBetweenUpdates
|
||||
) ||
|
||||
(
|
||||
timeSinceLastUpdate >= UpdateTraits.MinSecondsBetweenUpdates &&
|
||||
ExceedsDirtinessThreshold()
|
||||
);
|
||||
}
|
||||
|
||||
internal void UpdateLastSentTime()
|
||||
{
|
||||
// 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;
|
||||
|
||||
protected void MarkNetworkBehaviourDirty()
|
||||
@@ -147,6 +227,17 @@ namespace Unity.Netcode
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!m_NetworkBehaviour.NetworkManager.IsListening)
|
||||
{
|
||||
if (m_NetworkBehaviour.NetworkManager.LogLevel <= LogLevel.Developer)
|
||||
{
|
||||
Debug.LogWarning($"NetworkVariable is written to after the NetworkManager has already shutdown! " +
|
||||
"Are you modifying a NetworkVariable within a NetworkBehaviour.OnDestroy or NetworkBehaviour.OnDespawn method?");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
m_NetworkBehaviour.NetworkManager.BehaviourUpdater?.AddForUpdate(m_NetworkBehaviour.NetworkObject);
|
||||
}
|
||||
|
||||
@@ -158,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>
|
||||
@@ -174,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)
|
||||
{
|
||||
@@ -196,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:
|
||||
@@ -231,7 +338,6 @@ namespace Unity.Netcode
|
||||
/// </summary>
|
||||
/// <param name="reader">The stream to read the state from</param>
|
||||
public abstract void ReadField(FastBufferReader reader);
|
||||
|
||||
/// <summary>
|
||||
/// Reads delta from the reader and applies them to the internal value
|
||||
/// </summary>
|
||||
@@ -239,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>
|
||||
@@ -247,47 +379,4 @@ namespace Unity.Netcode
|
||||
m_InternalNetworkManager = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enum representing the different types of Network Variables.
|
||||
/// </summary>
|
||||
public enum NetworkVariableType : byte
|
||||
{
|
||||
/// <summary>
|
||||
/// Value
|
||||
/// Used for all of the basic NetworkVariables that contain a single value
|
||||
/// </summary>
|
||||
Value = 0,
|
||||
|
||||
/// <summary>
|
||||
/// Custom
|
||||
/// For any custom implemented extension of the NetworkVariableBase
|
||||
/// </summary>
|
||||
Custom = 1,
|
||||
|
||||
/// <summary>
|
||||
/// NetworkList
|
||||
/// </summary>
|
||||
NetworkList = 2
|
||||
}
|
||||
|
||||
public enum CollectionItemType : byte
|
||||
{
|
||||
/// <summary>
|
||||
/// For any type that is not valid inside a NetworkVariable collection
|
||||
/// </summary>
|
||||
Unknown = 0,
|
||||
|
||||
/// <summary>
|
||||
/// The following types are valid types inside of NetworkVariable collections
|
||||
/// </summary>
|
||||
Short = 1,
|
||||
UShort = 2,
|
||||
Int = 3,
|
||||
UInt = 4,
|
||||
Long = 5,
|
||||
ULong = 6,
|
||||
Unmanaged = 7,
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,3 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2c6ef5fdf2e94ec3b4ce8086d52700b3
|
||||
timeCreated: 1650985453
|
||||
3
Runtime/NetworkVariable/Serialization.meta
Normal file
3
Runtime/NetworkVariable/Serialization.meta
Normal file
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d960ae6c5b8241aa9e2906b709095ea1
|
||||
timeCreated: 1718215841
|
||||
99
Runtime/NetworkVariable/Serialization/FallbackSerializer.cs
Normal file
99
Runtime/NetworkVariable/Serialization/FallbackSerializer.cs
Normal file
@@ -0,0 +1,99 @@
|
||||
using System;
|
||||
using Unity.Collections;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
/// <summary>
|
||||
/// This class is instantiated for types that we can't determine ahead of time are serializable - types
|
||||
/// that don't meet any of the constraints for methods that are available on FastBufferReader and
|
||||
/// FastBufferWriter. These types may or may not be serializable through extension methods. To ensure
|
||||
/// the user has time to pass in the delegates to UserNetworkVariableSerialization, the existence
|
||||
/// of user serialization isn't checked until it's used, so if no serialization is provided, this
|
||||
/// will throw an exception when an object containing the relevant NetworkVariable is spawned.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
internal class FallbackSerializer<T> : INetworkVariableSerializer<T>
|
||||
{
|
||||
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}.");
|
||||
}
|
||||
|
||||
public void Write(FastBufferWriter writer, ref T value)
|
||||
{
|
||||
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
|
||||
{
|
||||
ThrowArgumentError();
|
||||
}
|
||||
UserNetworkVariableSerialization<T>.WriteValue(writer, value);
|
||||
}
|
||||
public void Read(FastBufferReader reader, ref T value)
|
||||
{
|
||||
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
|
||||
{
|
||||
ThrowArgumentError();
|
||||
}
|
||||
UserNetworkVariableSerialization<T>.ReadValue(reader, out value);
|
||||
}
|
||||
|
||||
public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue)
|
||||
{
|
||||
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
|
||||
{
|
||||
ThrowArgumentError();
|
||||
}
|
||||
|
||||
if (UserNetworkVariableSerialization<T>.WriteDelta == null || UserNetworkVariableSerialization<T>.ReadDelta == null)
|
||||
{
|
||||
UserNetworkVariableSerialization<T>.WriteValue(writer, value);
|
||||
return;
|
||||
}
|
||||
UserNetworkVariableSerialization<T>.WriteDelta(writer, value, previousValue);
|
||||
}
|
||||
|
||||
public void ReadDelta(FastBufferReader reader, ref T value)
|
||||
{
|
||||
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
|
||||
{
|
||||
ThrowArgumentError();
|
||||
}
|
||||
|
||||
if (UserNetworkVariableSerialization<T>.WriteDelta == null || UserNetworkVariableSerialization<T>.ReadDelta == null)
|
||||
{
|
||||
UserNetworkVariableSerialization<T>.ReadValue(reader, out value);
|
||||
return;
|
||||
}
|
||||
UserNetworkVariableSerialization<T>.ReadDelta(reader, ref value);
|
||||
}
|
||||
|
||||
void INetworkVariableSerializer<T>.ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void Duplicate(in T value, ref T duplicatedValue)
|
||||
{
|
||||
if (UserNetworkVariableSerialization<T>.ReadValue == null || UserNetworkVariableSerialization<T>.WriteValue == null || UserNetworkVariableSerialization<T>.DuplicateValue == null)
|
||||
{
|
||||
ThrowArgumentError();
|
||||
}
|
||||
UserNetworkVariableSerialization<T>.DuplicateValue(value, ref duplicatedValue);
|
||||
}
|
||||
}
|
||||
|
||||
// RuntimeAccessModifiersILPP will make this `public`
|
||||
// This is just pass-through to NetworkVariableSerialization<T> but is here because I could not get ILPP
|
||||
// to generate code that would successfully call Type<T>.Method(T), but it has no problem calling Type.Method<T>(T)
|
||||
internal class RpcFallbackSerialization
|
||||
{
|
||||
public static void Write<T>(FastBufferWriter writer, ref T value)
|
||||
{
|
||||
NetworkVariableSerialization<T>.Write(writer, ref value);
|
||||
}
|
||||
|
||||
public static void Read<T>(FastBufferReader reader, ref T value)
|
||||
{
|
||||
NetworkVariableSerialization<T>.Read(reader, ref value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 288dbe7d1ff74860ae3552c034485538
|
||||
timeCreated: 1718219109
|
||||
@@ -0,0 +1,22 @@
|
||||
using Unity.Collections;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
/// <typeparam name="T"></typeparam>
|
||||
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)
|
||||
// require the first parameter passed to them (the instance) to be passed by ref.
|
||||
// So foo.Bar() becomes BarDelegate(ref foo);
|
||||
// Taking T as an in parameter like we do in other places would require making a copy
|
||||
// of it to pass it as a ref parameter.,
|
||||
|
||||
public void Write(FastBufferWriter writer, ref T value);
|
||||
public void Read(FastBufferReader reader, ref T value);
|
||||
public void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue);
|
||||
public void ReadDelta(FastBufferReader reader, ref T value);
|
||||
internal void ReadWithAllocator(FastBufferReader reader, out T value, Allocator allocator);
|
||||
public void Duplicate(in T value, ref T duplicatedValue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f78e258ef55f4ee89bc3f24d67b8d242
|
||||
timeCreated: 1718218205
|
||||
357
Runtime/NetworkVariable/Serialization/NetworkVariableEquality.cs
Normal file
357
Runtime/NetworkVariable/Serialization/NetworkVariableEquality.cs
Normal file
@@ -0,0 +1,357 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Unity.Collections;
|
||||
using Unity.Collections.LowLevel.Unsafe;
|
||||
using Unity.Netcode;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
internal static class NetworkVariableEquality<T>
|
||||
{
|
||||
// Compares two values of the same unmanaged type by underlying memory
|
||||
// Ignoring any overridden value checks
|
||||
// Size is fixed
|
||||
internal static unsafe bool ValueEquals<TValueType>(ref TValueType a, ref TValueType b) where TValueType : unmanaged
|
||||
{
|
||||
// get unmanaged pointers
|
||||
var aptr = UnsafeUtility.AddressOf(ref a);
|
||||
var bptr = UnsafeUtility.AddressOf(ref b);
|
||||
|
||||
// compare addresses
|
||||
return UnsafeUtility.MemCmp(aptr, bptr, sizeof(TValueType)) == 0;
|
||||
}
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
// Compares two values of the same unmanaged type by underlying memory
|
||||
// Ignoring any overridden value checks
|
||||
// Size is fixed
|
||||
internal static unsafe bool ValueEqualsList<TValueType>(ref NativeList<TValueType> a, ref NativeList<TValueType> b) where TValueType : unmanaged
|
||||
{
|
||||
if (a.IsCreated != b.IsCreated)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!a.IsCreated)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (a.Length != b.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
#if UTP_TRANSPORT_2_0_ABOVE
|
||||
var aptr = a.GetUnsafePtr();
|
||||
var bptr = b.GetUnsafePtr();
|
||||
#else
|
||||
var aptr = (TValueType*)a.GetUnsafePtr();
|
||||
var bptr = (TValueType*)b.GetUnsafePtr();
|
||||
#endif
|
||||
|
||||
return UnsafeUtility.MemCmp(aptr, bptr, sizeof(TValueType) * a.Length) == 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
// Compares two values of the same unmanaged type by underlying memory
|
||||
// Ignoring any overridden value checks
|
||||
// Size is fixed
|
||||
internal static unsafe bool ValueEqualsArray<TValueType>(ref NativeArray<TValueType> a, ref NativeArray<TValueType> b) where TValueType : unmanaged
|
||||
{
|
||||
if (a.IsCreated != b.IsCreated)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!a.IsCreated)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (a.Length != b.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var aptr = (TValueType*)a.GetUnsafePtr();
|
||||
var bptr = (TValueType*)b.GetUnsafePtr();
|
||||
return UnsafeUtility.MemCmp(aptr, bptr, sizeof(TValueType) * a.Length) == 0;
|
||||
}
|
||||
|
||||
internal static bool EqualityEqualsObject<TValueType>(ref TValueType a, ref TValueType b) where TValueType : class, IEquatable<TValueType>
|
||||
{
|
||||
if (a == null)
|
||||
{
|
||||
return b == null;
|
||||
}
|
||||
|
||||
if (b == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return a.Equals(b);
|
||||
}
|
||||
|
||||
internal static bool EqualityEquals<TValueType>(ref TValueType a, ref TValueType b) where TValueType : unmanaged, IEquatable<TValueType>
|
||||
{
|
||||
return a.Equals(b);
|
||||
}
|
||||
|
||||
internal static bool EqualityEqualsList<TValueType>(ref List<TValueType> a, ref List<TValueType> b)
|
||||
{
|
||||
if (a == null != (b == null))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (a == null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (a.Count != b.Count)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
for (var i = 0; i < a.Count; ++i)
|
||||
{
|
||||
var aItem = a[i];
|
||||
var bItem = b[i];
|
||||
if (!NetworkVariableSerialization<TValueType>.AreEqual(ref aItem, ref bItem))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
internal static bool EqualityEqualsHashSet<TValueType>(ref HashSet<TValueType> a, ref HashSet<TValueType> b) where TValueType : IEquatable<TValueType>
|
||||
{
|
||||
if (a == null != (b == null))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (a == null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (a.Count != b.Count)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var item in a)
|
||||
{
|
||||
if (!b.Contains(item))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Compares two values of the same unmanaged type by underlying memory
|
||||
// Ignoring any overridden value checks
|
||||
// Size is fixed
|
||||
internal static unsafe bool EqualityEqualsArray<TValueType>(ref NativeArray<TValueType> a, ref NativeArray<TValueType> b) where TValueType : unmanaged, IEquatable<TValueType>
|
||||
{
|
||||
if (a.IsCreated != b.IsCreated)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!a.IsCreated)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (a.Length != b.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var aptr = (TValueType*)a.GetUnsafePtr();
|
||||
var bptr = (TValueType*)b.GetUnsafePtr();
|
||||
for (var i = 0; i < a.Length; ++i)
|
||||
{
|
||||
if (!EqualityEquals(ref aptr[i], ref bptr[i]))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
internal static bool ClassEquals<TValueType>(ref TValueType a, ref TValueType b) where TValueType : class
|
||||
{
|
||||
return a == b;
|
||||
}
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
// Compares two values of the same unmanaged type by underlying memory
|
||||
// Ignoring any overridden value checks
|
||||
// Size is fixed
|
||||
internal static unsafe bool EqualityEqualsNativeList<TValueType>(ref NativeList<TValueType> a, ref NativeList<TValueType> b) where TValueType : unmanaged, IEquatable<TValueType>
|
||||
{
|
||||
if (a.IsCreated != b.IsCreated)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!a.IsCreated)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (a.Length != b.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
#if UTP_TRANSPORT_2_0_ABOVE
|
||||
var aptr = a.GetUnsafePtr();
|
||||
var bptr = b.GetUnsafePtr();
|
||||
#else
|
||||
var aptr = (TValueType*)a.GetUnsafePtr();
|
||||
var bptr = (TValueType*)b.GetUnsafePtr();
|
||||
#endif
|
||||
for (var i = 0; i < a.Length; ++i)
|
||||
{
|
||||
if (!EqualityEquals(ref aptr[i], ref bptr[i]))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
internal static bool EqualityEqualsNativeHashSet<TValueType>(ref NativeHashSet<TValueType> a, ref NativeHashSet<TValueType> b) where TValueType : unmanaged, IEquatable<TValueType>
|
||||
{
|
||||
if (a.IsCreated != b.IsCreated)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!a.IsCreated)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
#if UTP_TRANSPORT_2_0_ABOVE
|
||||
if (a.Count != b.Count)
|
||||
#else
|
||||
if (a.Count() != b.Count())
|
||||
#endif
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var item in a)
|
||||
{
|
||||
if (!b.Contains(item))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Support methods for equality of NetworkVariable collection types.
|
||||
/// Because there are multiple overloads of WriteValue/ReadValue based on different generic constraints,
|
||||
/// but there's no way to achieve the same thing with a class, this sets up various read/write schemes
|
||||
/// based on which constraints are met by `T` using reflection, which is done at module load time.
|
||||
/// </summary>
|
||||
/// <typeparam name="TKey">The type the associated NetworkVariable dictionary collection key templated on</typeparam>
|
||||
/// <typeparam name="TVal">The type the associated NetworkVariable dictionary collection value templated on</typeparam>
|
||||
internal class NetworkVariableDictionarySerialization<TKey, TVal>
|
||||
where TKey : IEquatable<TKey>
|
||||
{
|
||||
internal static bool GenericEqualsDictionary(ref Dictionary<TKey, TVal> a, ref Dictionary<TKey, TVal> b)
|
||||
{
|
||||
if (a == null != (b == null))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (a == null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (a.Count != b.Count)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var item in a)
|
||||
{
|
||||
var hasKey = b.TryGetValue(item.Key, out var val);
|
||||
if (!hasKey)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var bVal = item.Value;
|
||||
if (!NetworkVariableSerialization<TVal>.AreEqual(ref bVal, ref val))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
internal class NetworkVariableMapSerialization<TKey, TVal>
|
||||
where TKey : unmanaged, IEquatable<TKey>
|
||||
where TVal : unmanaged
|
||||
{
|
||||
internal static bool GenericEqualsNativeHashMap(ref NativeHashMap<TKey, TVal> a, ref NativeHashMap<TKey, TVal> b)
|
||||
{
|
||||
if (a.IsCreated != b.IsCreated)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!a.IsCreated)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
#if UTP_TRANSPORT_2_0_ABOVE
|
||||
if (a.Count != b.Count)
|
||||
#else
|
||||
if (a.Count() != b.Count())
|
||||
#endif
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var item in a)
|
||||
{
|
||||
var hasKey = b.TryGetValue(item.Key, out var val);
|
||||
if (!hasKey || !NetworkVariableSerialization<TVal>.AreEqual(ref item.Value, ref val))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 24b8352a975044509931bf684ccfdb82
|
||||
timeCreated: 1718219366
|
||||
@@ -0,0 +1,153 @@
|
||||
using System;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
/// <summary>
|
||||
/// Support methods for reading/writing NetworkVariables
|
||||
/// Because there are multiple overloads of WriteValue/ReadValue based on different generic constraints,
|
||||
/// but there's no way to achieve the same thing with a class, this sets up various read/write schemes
|
||||
/// based on which constraints are met by `T` using reflection, which is done at module load time.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type the associated NetworkVariable is templated on</typeparam>
|
||||
[Serializable]
|
||||
public static class NetworkVariableSerialization<T>
|
||||
{
|
||||
internal static INetworkVariableSerializer<T> Serializer = new FallbackSerializer<T>();
|
||||
|
||||
/// <summary>
|
||||
/// A callback to check if two values are equal.
|
||||
/// </summary>
|
||||
public delegate bool EqualsDelegate(ref T a, ref T b);
|
||||
|
||||
/// <summary>
|
||||
/// Uses the most efficient mechanism for a given type to determine if two values are equal.
|
||||
/// For types that implement <see cref="IEquatable{T}"/>, it will call the Equals() method.
|
||||
/// For unmanaged types, it will do a bytewise memory comparison.
|
||||
/// For other types, it will call the == operator.
|
||||
/// <br/>
|
||||
/// <br/>
|
||||
/// Note: If you are using this in a custom generic class, please make sure your class is
|
||||
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute"/> so that codegen can
|
||||
/// initialize the serialization mechanisms correctly. If your class is NOT
|
||||
/// generic, it is better to check their equality yourself.
|
||||
/// </summary>
|
||||
public static EqualsDelegate AreEqual { get; internal set; }
|
||||
/// <summary>
|
||||
/// Serialize a value using the best-known serialization method for a generic value.
|
||||
/// Will reliably serialize any value that is passed to it correctly with no boxing.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// Note: If you are using this in a custom generic class, please make sure your class is
|
||||
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
|
||||
/// initialize the serialization mechanisms correctly. If your class is NOT
|
||||
/// generic, it is better to use FastBufferWriter directly.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// If the codegen is unable to determine a serializer for a type,
|
||||
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.WriteValue" /> is called, which, by default,
|
||||
/// will throw an exception, unless you have assigned a user serialization callback to it at runtime.
|
||||
/// </summary>
|
||||
/// <param name="writer"></param>
|
||||
/// <param name="value"></param>
|
||||
public static void Write(FastBufferWriter writer, ref T value)
|
||||
{
|
||||
Serializer.Write(writer, ref value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserialize a value using the best-known serialization method for a generic value.
|
||||
/// Will reliably deserialize any value that is passed to it correctly with no boxing.
|
||||
/// For types whose deserialization can be determined by codegen (which is most types),
|
||||
/// GC will only be incurred if the type is a managed type and the ref value passed in is `null`,
|
||||
/// in which case a new value is created; otherwise, it will be deserialized in-place.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// Note: If you are using this in a custom generic class, please make sure your class is
|
||||
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
|
||||
/// initialize the serialization mechanisms correctly. If your class is NOT
|
||||
/// generic, it is better to use FastBufferReader directly.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// If the codegen is unable to determine a serializer for a type,
|
||||
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.ReadValue" /> is called, which, by default,
|
||||
/// will throw an exception, unless you have assigned a user deserialization callback to it at runtime.
|
||||
/// </summary>
|
||||
/// <param name="reader"></param>
|
||||
/// <param name="value"></param>
|
||||
public static void Read(FastBufferReader reader, ref T value)
|
||||
{
|
||||
Serializer.Read(reader, ref value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serialize a value using the best-known serialization method for a generic value.
|
||||
/// Will reliably serialize any value that is passed to it correctly with no boxing.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// Note: If you are using this in a custom generic class, please make sure your class is
|
||||
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
|
||||
/// initialize the serialization mechanisms correctly. If your class is NOT
|
||||
/// generic, it is better to use FastBufferWriter directly.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// If the codegen is unable to determine a serializer for a type,
|
||||
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.WriteValue" /> is called, which, by default,
|
||||
/// will throw an exception, unless you have assigned a user serialization callback to it at runtime.
|
||||
/// </summary>
|
||||
/// <param name="writer"></param>
|
||||
/// <param name="value"></param>
|
||||
public static void WriteDelta(FastBufferWriter writer, ref T value, ref T previousValue)
|
||||
{
|
||||
Serializer.WriteDelta(writer, ref value, ref previousValue);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserialize a value using the best-known serialization method for a generic value.
|
||||
/// Will reliably deserialize any value that is passed to it correctly with no boxing.
|
||||
/// For types whose deserialization can be determined by codegen (which is most types),
|
||||
/// GC will only be incurred if the type is a managed type and the ref value passed in is `null`,
|
||||
/// in which case a new value is created; otherwise, it will be deserialized in-place.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// Note: If you are using this in a custom generic class, please make sure your class is
|
||||
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
|
||||
/// initialize the serialization mechanisms correctly. If your class is NOT
|
||||
/// generic, it is better to use FastBufferReader directly.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// If the codegen is unable to determine a serializer for a type,
|
||||
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.ReadValue" /> is called, which, by default,
|
||||
/// will throw an exception, unless you have assigned a user deserialization callback to it at runtime.
|
||||
/// </summary>
|
||||
/// <param name="reader"></param>
|
||||
/// <param name="value"></param>
|
||||
public static void ReadDelta(FastBufferReader reader, ref T value)
|
||||
{
|
||||
Serializer.ReadDelta(reader, ref value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Duplicates a value using the most efficient means of creating a complete copy.
|
||||
/// For most types this is a simple assignment or memcpy.
|
||||
/// For managed types, this is will serialize and then deserialize the value to ensure
|
||||
/// a correct copy.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// Note: If you are using this in a custom generic class, please make sure your class is
|
||||
/// decorated with <see cref="GenerateSerializationForGenericParameterAttribute" /> so that codegen can
|
||||
/// initialize the serialization mechanisms correctly. If your class is NOT
|
||||
/// generic, it is better to duplicate it directly.
|
||||
/// <br />
|
||||
/// <br />
|
||||
/// If the codegen is unable to determine a serializer for a type,
|
||||
/// <see cref="UserNetworkVariableSerialization{T}" />.<see cref="UserNetworkVariableSerialization{T}.DuplicateValue" /> is called, which, by default,
|
||||
/// will throw an exception, unless you have assigned a user duplication callback to it at runtime.
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="duplicatedValue"></param>
|
||||
public static void Duplicate(in T value, ref T duplicatedValue)
|
||||
{
|
||||
Serializer.Duplicate(value, ref duplicatedValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7a943170e35746e8913dd494d79bb63d
|
||||
timeCreated: 1718215899
|
||||
315
Runtime/NetworkVariable/Serialization/TypedILPPInitializers.cs
Normal file
315
Runtime/NetworkVariable/Serialization/TypedILPPInitializers.cs
Normal file
@@ -0,0 +1,315 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Unity.Collections;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
/// <summary>
|
||||
/// This class contains initialization functions for various different types used in NetworkVariables.
|
||||
/// Generally speaking, these methods are called by a module initializer created by codegen (NetworkBehaviourILPP)
|
||||
/// and do not need to be called manually.
|
||||
///
|
||||
/// There are two types of initializers: Serializers and EqualityCheckers. Every type must have an EqualityChecker
|
||||
/// registered to it in order to be used in NetworkVariable; however, not all types need a Serializer. Types without
|
||||
/// a serializer registered will fall back to using the delegates in <see cref="UserNetworkVariableSerialization{T}"/>.
|
||||
/// If no such delegate has been registered, a type without a serializer will throw an exception on the first attempt
|
||||
/// to serialize or deserialize it. (Again, however, codegen handles this automatically and this registration doesn't
|
||||
/// typically need to be performed manually.)
|
||||
/// </summary>
|
||||
public static class NetworkVariableSerializationTypedInitializers
|
||||
{
|
||||
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
|
||||
#if UNITY_EDITOR
|
||||
[InitializeOnLoadMethod]
|
||||
#endif
|
||||
internal static void InitializeIntegerSerialization()
|
||||
{
|
||||
NetworkVariableSerialization<short>.Serializer = new ShortSerializer();
|
||||
NetworkVariableSerialization<short>.AreEqual = NetworkVariableEquality<short>.ValueEquals;
|
||||
NetworkVariableSerialization<ushort>.Serializer = new UshortSerializer();
|
||||
NetworkVariableSerialization<ushort>.AreEqual = NetworkVariableEquality<ushort>.ValueEquals;
|
||||
NetworkVariableSerialization<int>.Serializer = new IntSerializer();
|
||||
NetworkVariableSerialization<int>.AreEqual = NetworkVariableEquality<int>.ValueEquals;
|
||||
NetworkVariableSerialization<uint>.Serializer = new UintSerializer();
|
||||
NetworkVariableSerialization<uint>.AreEqual = NetworkVariableEquality<uint>.ValueEquals;
|
||||
NetworkVariableSerialization<long>.Serializer = new LongSerializer();
|
||||
NetworkVariableSerialization<long>.AreEqual = NetworkVariableEquality<long>.ValueEquals;
|
||||
NetworkVariableSerialization<ulong>.Serializer = new UlongSerializer();
|
||||
NetworkVariableSerialization<ulong>.AreEqual = NetworkVariableEquality<ulong>.ValueEquals;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registeres an unmanaged type that will be serialized by a direct memcpy into a buffer
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_UnmanagedByMemcpy<T>() where T : unmanaged
|
||||
{
|
||||
NetworkVariableSerialization<T>.Serializer = new UnmanagedTypeSerializer<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registeres an unmanaged type that will be serialized by a direct memcpy into a buffer
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_UnmanagedByMemcpyArray<T>() where T : unmanaged
|
||||
{
|
||||
NetworkVariableSerialization<NativeArray<T>>.Serializer = new UnmanagedArraySerializer<T>();
|
||||
}
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
/// <summary>
|
||||
/// Registeres an unmanaged type that will be serialized by a direct memcpy into a buffer
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_UnmanagedByMemcpyList<T>() where T : unmanaged
|
||||
{
|
||||
NetworkVariableSerialization<NativeList<T>>.Serializer = new UnmanagedListSerializer<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registeres a native hash set (this generic implementation works with all types)
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_NativeHashSet<T>() where T : unmanaged, IEquatable<T>
|
||||
{
|
||||
NetworkVariableSerialization<NativeHashSet<T>>.Serializer = new NativeHashSetSerializer<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registeres a native hash set (this generic implementation works with all types)
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_NativeHashMap<TKey, TVal>()
|
||||
where TKey : unmanaged, IEquatable<TKey>
|
||||
where TVal : unmanaged
|
||||
{
|
||||
NetworkVariableSerialization<NativeHashMap<TKey, TVal>>.Serializer = new NativeHashMapSerializer<TKey, TVal>();
|
||||
}
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Registeres a native hash set (this generic implementation works with all types)
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_List<T>()
|
||||
{
|
||||
NetworkVariableSerialization<List<T>>.Serializer = new ListSerializer<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registeres a native hash set (this generic implementation works with all types)
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_HashSet<T>() where T : IEquatable<T>
|
||||
{
|
||||
NetworkVariableSerialization<HashSet<T>>.Serializer = new HashSetSerializer<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registeres a native hash set (this generic implementation works with all types)
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_Dictionary<TKey, TVal>() where TKey : IEquatable<TKey>
|
||||
{
|
||||
NetworkVariableSerialization<Dictionary<TKey, TVal>>.Serializer = new DictionarySerializer<TKey, TVal>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that implements INetworkSerializable and will be serialized through a call to
|
||||
/// NetworkSerialize
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_UnmanagedINetworkSerializable<T>() where T : unmanaged, INetworkSerializable
|
||||
{
|
||||
NetworkVariableSerialization<T>.Serializer = new UnmanagedNetworkSerializableSerializer<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that implements INetworkSerializable and will be serialized through a call to
|
||||
/// NetworkSerialize
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_UnmanagedINetworkSerializableArray<T>() where T : unmanaged, INetworkSerializable
|
||||
{
|
||||
NetworkVariableSerialization<NativeArray<T>>.Serializer = new UnmanagedNetworkSerializableArraySerializer<T>();
|
||||
}
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that implements INetworkSerializable and will be serialized through a call to
|
||||
/// NetworkSerialize
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_UnmanagedINetworkSerializableList<T>() where T : unmanaged, INetworkSerializable
|
||||
{
|
||||
NetworkVariableSerialization<NativeList<T>>.Serializer = new UnmanagedNetworkSerializableListSerializer<T>();
|
||||
}
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Registers a managed type that implements INetworkSerializable and will be serialized through a call to
|
||||
/// NetworkSerialize
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_ManagedINetworkSerializable<T>() where T : class, INetworkSerializable, new()
|
||||
{
|
||||
NetworkVariableSerialization<T>.Serializer = new ManagedNetworkSerializableSerializer<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a FixedString type that will be serialized through FastBufferReader/FastBufferWriter's FixedString
|
||||
/// serializers
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_FixedString<T>() where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
NetworkVariableSerialization<T>.Serializer = new FixedStringSerializer<T>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a FixedString type that will be serialized through FastBufferReader/FastBufferWriter's FixedString
|
||||
/// serializers
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_FixedStringArray<T>() where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
NetworkVariableSerialization<NativeArray<T>>.Serializer = new FixedStringArraySerializer<T>();
|
||||
}
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
/// <summary>
|
||||
/// Registers a FixedString type that will be serialized through FastBufferReader/FastBufferWriter's FixedString
|
||||
/// serializers
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeSerializer_FixedStringList<T>() where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
NetworkVariableSerialization<NativeList<T>>.Serializer = new FixedStringListSerializer<T>();
|
||||
}
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Registers a managed type that will be checked for equality using T.Equals()
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_ManagedIEquatable<T>() where T : class, IEquatable<T>
|
||||
{
|
||||
NetworkVariableSerialization<T>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsObject;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using T.Equals()
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_UnmanagedIEquatable<T>() where T : unmanaged, IEquatable<T>
|
||||
{
|
||||
NetworkVariableSerialization<T>.AreEqual = NetworkVariableEquality<T>.EqualityEquals;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using T.Equals()
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_UnmanagedIEquatableArray<T>() where T : unmanaged, IEquatable<T>
|
||||
{
|
||||
NetworkVariableSerialization<NativeArray<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsArray;
|
||||
}
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using T.Equals()
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_List<T>()
|
||||
{
|
||||
NetworkVariableSerialization<List<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsList;
|
||||
}
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using T.Equals()
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_HashSet<T>() where T : IEquatable<T>
|
||||
{
|
||||
NetworkVariableSerialization<HashSet<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsHashSet;
|
||||
}
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using T.Equals()
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_Dictionary<TKey, TVal>()
|
||||
where TKey : IEquatable<TKey>
|
||||
{
|
||||
NetworkVariableSerialization<Dictionary<TKey, TVal>>.AreEqual = NetworkVariableDictionarySerialization<TKey, TVal>.GenericEqualsDictionary;
|
||||
}
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using T.Equals()
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_UnmanagedIEquatableList<T>() where T : unmanaged, IEquatable<T>
|
||||
{
|
||||
NetworkVariableSerialization<NativeList<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsNativeList;
|
||||
}
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using T.Equals()
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_NativeHashSet<T>() where T : unmanaged, IEquatable<T>
|
||||
{
|
||||
NetworkVariableSerialization<NativeHashSet<T>>.AreEqual = NetworkVariableEquality<T>.EqualityEqualsNativeHashSet;
|
||||
}
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using T.Equals()
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_NativeHashMap<TKey, TVal>()
|
||||
where TKey : unmanaged, IEquatable<TKey>
|
||||
where TVal : unmanaged
|
||||
{
|
||||
NetworkVariableSerialization<NativeHashMap<TKey, TVal>>.AreEqual = NetworkVariableMapSerialization<TKey, TVal>.GenericEqualsNativeHashMap;
|
||||
}
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using memcmp and only considered
|
||||
/// equal if they are bitwise equivalent in memory
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_UnmanagedValueEquals<T>() where T : unmanaged
|
||||
{
|
||||
NetworkVariableSerialization<T>.AreEqual = NetworkVariableEquality<T>.ValueEquals;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using memcmp and only considered
|
||||
/// equal if they are bitwise equivalent in memory
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_UnmanagedValueEqualsArray<T>() where T : unmanaged
|
||||
{
|
||||
NetworkVariableSerialization<NativeArray<T>>.AreEqual = NetworkVariableEquality<T>.ValueEqualsArray;
|
||||
}
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
/// <summary>
|
||||
/// Registers an unmanaged type that will be checked for equality using memcmp and only considered
|
||||
/// equal if they are bitwise equivalent in memory
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_UnmanagedValueEqualsList<T>() where T : unmanaged
|
||||
{
|
||||
NetworkVariableSerialization<NativeList<T>>.AreEqual = NetworkVariableEquality<T>.ValueEqualsList;
|
||||
}
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Registers a managed type that will be checked for equality using the == operator
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public static void InitializeEqualityChecker_ManagedClassEquals<T>() where T : class
|
||||
{
|
||||
NetworkVariableSerialization<T>.AreEqual = NetworkVariableEquality<T>.ClassEquals;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 65bdb3e11a9a412ab5e936a9c96a3da0
|
||||
timeCreated: 1718216842
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bbfa170e9dd448bbbe381ce38d5c139d
|
||||
timeCreated: 1718216671
|
||||
@@ -0,0 +1,73 @@
|
||||
namespace Unity.Netcode
|
||||
{
|
||||
/// <summary>
|
||||
/// This class is used to register user serialization with NetworkVariables for types
|
||||
/// that are serialized via user serialization, such as with FastBufferReader and FastBufferWriter
|
||||
/// extension methods. Finding those methods isn't achievable efficiently at runtime, so this allows
|
||||
/// users to tell NetworkVariable about those extension methods (or simply pass in a lambda)
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class UserNetworkVariableSerialization<T>
|
||||
{
|
||||
/// <summary>
|
||||
/// The write value delegate handler definition
|
||||
/// </summary>
|
||||
/// <param name="writer">The <see cref="FastBufferWriter"/> to write the value of type `T`</param>
|
||||
/// <param name="value">The value of type `T` to be written</param>
|
||||
public delegate void WriteValueDelegate(FastBufferWriter writer, in T value);
|
||||
|
||||
/// <summary>
|
||||
/// The write value delegate handler definition
|
||||
/// </summary>
|
||||
/// <param name="writer">The <see cref="FastBufferWriter"/> to write the value of type `T`</param>
|
||||
/// <param name="value">The value of type `T` to be written</param>
|
||||
public delegate void WriteDeltaDelegate(FastBufferWriter writer, in T value, in T previousValue);
|
||||
|
||||
/// <summary>
|
||||
/// The read value delegate handler definition
|
||||
/// </summary>
|
||||
/// <param name="reader">The <see cref="FastBufferReader"/> to read the value of type `T`</param>
|
||||
/// <param name="value">The value of type `T` to be read</param>
|
||||
public delegate void ReadValueDelegate(FastBufferReader reader, out T value);
|
||||
|
||||
/// <summary>
|
||||
/// The read value delegate handler definition
|
||||
/// </summary>
|
||||
/// <param name="reader">The <see cref="FastBufferReader"/> to read the value of type `T`</param>
|
||||
/// <param name="value">The value of type `T` to be read</param>
|
||||
public delegate void ReadDeltaDelegate(FastBufferReader reader, ref T value);
|
||||
|
||||
/// <summary>
|
||||
/// The read value delegate handler definition
|
||||
/// </summary>
|
||||
/// <param name="reader">The <see cref="FastBufferReader"/> to read the value of type `T`</param>
|
||||
/// <param name="value">The value of type `T` to be read</param>
|
||||
public delegate void DuplicateValueDelegate(in T value, ref T duplicatedValue);
|
||||
|
||||
/// <summary>
|
||||
/// Callback to write a value
|
||||
/// </summary>
|
||||
public static WriteValueDelegate WriteValue;
|
||||
|
||||
/// <summary>
|
||||
/// Callback to read a value
|
||||
/// </summary>
|
||||
public static ReadValueDelegate ReadValue;
|
||||
|
||||
/// <summary>
|
||||
/// Callback to write a delta between two values, based on computing the difference between the previous and
|
||||
/// current values.
|
||||
/// </summary>
|
||||
public static WriteDeltaDelegate WriteDelta;
|
||||
|
||||
/// <summary>
|
||||
/// Callback to read a delta, applying only select changes to the current value.
|
||||
/// </summary>
|
||||
public static ReadDeltaDelegate ReadDelta;
|
||||
|
||||
/// <summary>
|
||||
/// Callback to create a duplicate of a value, used to check for dirty status.
|
||||
/// </summary>
|
||||
public static DuplicateValueDelegate DuplicateValue;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b295a6756640488b9824d2ec6e26ddae
|
||||
timeCreated: 1718218272
|
||||
@@ -227,6 +227,11 @@ namespace Unity.Netcode
|
||||
foreach (var sceneToUnload in m_ScenesToUnload)
|
||||
{
|
||||
SceneManager.UnloadSceneAsync(sceneToUnload);
|
||||
// Update the ScenesLoaded when we unload scenes
|
||||
if (sceneManager.ScenesLoaded.ContainsKey(sceneToUnload.handle))
|
||||
{
|
||||
sceneManager.ScenesLoaded.Remove(sceneToUnload.handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -328,8 +333,9 @@ namespace Unity.Netcode
|
||||
public void SetClientSynchronizationMode(ref NetworkManager networkManager, LoadSceneMode mode)
|
||||
{
|
||||
var sceneManager = networkManager.SceneManager;
|
||||
// Don't let non-authority set this value
|
||||
if ((!networkManager.DistributedAuthorityMode && !networkManager.IsServer) || (networkManager.DistributedAuthorityMode && !networkManager.LocalClient.IsSessionOwner))
|
||||
// In client-server, we don't let client's set this value.
|
||||
// In distributed authority, since session owner can be promoted clients can set this value
|
||||
if (!networkManager.DistributedAuthorityMode && !networkManager.IsServer)
|
||||
{
|
||||
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
|
||||
{
|
||||
@@ -338,7 +344,7 @@ namespace Unity.Netcode
|
||||
return;
|
||||
}
|
||||
else // Warn users if they are changing this after there are clients already connected and synchronized
|
||||
if (networkManager.ConnectedClientsIds.Count > (networkManager.IsHost ? 1 : 0) && sceneManager.ClientSynchronizationMode != mode)
|
||||
if (!networkManager.DistributedAuthorityMode && networkManager.ConnectedClientsIds.Count > (networkManager.IsHost ? 1 : 0) && sceneManager.ClientSynchronizationMode != mode)
|
||||
{
|
||||
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
|
||||
{
|
||||
|
||||
@@ -774,6 +774,7 @@ namespace Unity.Netcode
|
||||
/// <summary>
|
||||
/// This setting changes how clients handle scene loading when initially synchronizing with the server.<br />
|
||||
/// The server or host should set this value as clients will automatically be synchronized with the server (or host) side.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <b>LoadSceneMode.Single:</b> All currently loaded scenes on the client will be unloaded and the
|
||||
/// server's currently active scene will be loaded in single mode on the client unless it was already
|
||||
@@ -1080,14 +1081,19 @@ namespace Unity.Netcode
|
||||
}
|
||||
else
|
||||
{
|
||||
// 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)
|
||||
{
|
||||
sceneEvent.TargetClientId = clientId;
|
||||
var message = new SceneEventMessage
|
||||
{
|
||||
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);
|
||||
var size = NetworkManager.ConnectionManager.SendMessage(ref message, k_DeliveryType, clientId);
|
||||
NetworkManager.NetworkMetrics.TrackSceneEventSent(clientId, (uint)sceneEvent.SceneEventType, SceneNameFromHash(sceneEvent.SceneHash), size);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -1897,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,
|
||||
@@ -2406,16 +2414,6 @@ namespace Unity.Netcode
|
||||
NetworkManager.ConnectionManager.CreateAndSpawnPlayer(NetworkManager.LocalClientId);
|
||||
}
|
||||
|
||||
// Client is now synchronized and fully "connected". This also means the client can send "RPCs" at this time
|
||||
NetworkManager.ConnectionManager.InvokeOnClientConnectedCallback(NetworkManager.LocalClientId);
|
||||
|
||||
// Notify the client that they have finished synchronizing
|
||||
OnSceneEvent?.Invoke(new SceneEvent()
|
||||
{
|
||||
SceneEventType = sceneEventData.SceneEventType,
|
||||
ClientId = NetworkManager.LocalClientId, // Client sent this to the server
|
||||
});
|
||||
|
||||
// Process any SceneEventType.ObjectSceneChanged messages that
|
||||
// were deferred while synchronizing and migrate the associated
|
||||
// NetworkObjects to their newly assigned scenes.
|
||||
@@ -2429,6 +2427,16 @@ namespace Unity.Netcode
|
||||
SceneManagerHandler.UnloadUnassignedScenes(NetworkManager);
|
||||
}
|
||||
|
||||
// Client is now synchronized and fully "connected". This also means the client can send "RPCs" at this time
|
||||
NetworkManager.ConnectionManager.InvokeOnClientConnectedCallback(NetworkManager.LocalClientId);
|
||||
|
||||
// Notify the client that they have finished synchronizing
|
||||
OnSceneEvent?.Invoke(new SceneEvent()
|
||||
{
|
||||
SceneEventType = sceneEventData.SceneEventType,
|
||||
ClientId = NetworkManager.LocalClientId, // Client sent this to the server
|
||||
});
|
||||
|
||||
OnSynchronizeComplete?.Invoke(NetworkManager.LocalClientId);
|
||||
|
||||
if (NetworkLog.CurrentLogLevel <= LogLevel.Developer)
|
||||
@@ -2436,10 +2444,7 @@ namespace Unity.Netcode
|
||||
NetworkLog.LogInfo($"[Client-{NetworkManager.LocalClientId}][Scene Management Enabled] Synchronization complete!");
|
||||
}
|
||||
// For convenience, notify all NetworkBehaviours that synchronization is complete.
|
||||
foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList)
|
||||
{
|
||||
networkObject.InternalNetworkSessionSynchronized();
|
||||
}
|
||||
NetworkManager.SpawnManager.NotifyNetworkObjectsSynchronized();
|
||||
|
||||
if (NetworkManager.DistributedAuthorityMode && HasSceneAuthority() && IsRestoringSession)
|
||||
{
|
||||
@@ -2552,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()
|
||||
{
|
||||
@@ -2577,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
|
||||
@@ -2591,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)
|
||||
@@ -2666,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);
|
||||
|
||||
@@ -523,8 +523,8 @@ namespace Unity.Netcode
|
||||
/// <param name="oneByteChars">Whether or not to use one byte per character. This will only allow ASCII</param>
|
||||
public unsafe void ReadValue(out string s, bool oneByteChars = false)
|
||||
{
|
||||
ReadValue(out uint length);
|
||||
s = "".PadRight((int)length);
|
||||
ReadLength(out int length);
|
||||
s = "".PadRight(length);
|
||||
int target = s.Length;
|
||||
fixed (char* native = s)
|
||||
{
|
||||
@@ -562,18 +562,18 @@ namespace Unity.Netcode
|
||||
}
|
||||
#endif
|
||||
|
||||
if (!TryBeginReadInternal(sizeof(uint)))
|
||||
if (!TryBeginReadInternal(SizeOfLengthField()))
|
||||
{
|
||||
throw new OverflowException("Reading past the end of the buffer");
|
||||
}
|
||||
|
||||
ReadValue(out uint length);
|
||||
ReadLength(out int length);
|
||||
|
||||
if (!TryBeginReadInternal((int)length * (oneByteChars ? 1 : sizeof(char))))
|
||||
if (!TryBeginReadInternal(length * (oneByteChars ? 1 : sizeof(char))))
|
||||
{
|
||||
throw new OverflowException("Reading past the end of the buffer");
|
||||
}
|
||||
s = "".PadRight((int)length);
|
||||
s = "".PadRight(length);
|
||||
int target = s.Length;
|
||||
fixed (char* native = s)
|
||||
{
|
||||
@@ -592,6 +592,33 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static int SizeOfLengthField() => sizeof(uint);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void ReadLengthSafe(out uint length) => ReadUnmanagedSafe(out length);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void ReadLength(out uint length) => ReadUnmanaged(out length);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void ReadLengthSafe(out int length)
|
||||
{
|
||||
ReadLengthSafe(out uint temp);
|
||||
if (temp > int.MaxValue)
|
||||
{
|
||||
throw new InvalidCastException("length value outside of int32 range");
|
||||
}
|
||||
length = (int)temp;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void ReadLength(out int length)
|
||||
{
|
||||
ReadLength(out uint temp);
|
||||
length = (int)temp;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read a partial value. The value is zero-initialized and then the specified number of bytes is read into it.
|
||||
/// </summary>
|
||||
@@ -777,7 +804,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void ReadUnmanaged<T>(out T[] value) where T : unmanaged
|
||||
{
|
||||
ReadUnmanaged(out int sizeInTs);
|
||||
ReadLength(out int sizeInTs);
|
||||
int sizeInBytes = sizeInTs * sizeof(T);
|
||||
value = new T[sizeInTs];
|
||||
fixed (T* ptr = value)
|
||||
@@ -789,7 +816,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void ReadUnmanagedSafe<T>(out T[] value) where T : unmanaged
|
||||
{
|
||||
ReadUnmanagedSafe(out int sizeInTs);
|
||||
ReadLengthSafe(out int sizeInTs);
|
||||
int sizeInBytes = sizeInTs * sizeof(T);
|
||||
value = new T[sizeInTs];
|
||||
fixed (T* ptr = value)
|
||||
@@ -801,7 +828,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void ReadUnmanaged<T>(out NativeArray<T> value, Allocator allocator) where T : unmanaged
|
||||
{
|
||||
ReadUnmanaged(out int sizeInTs);
|
||||
ReadLength(out int sizeInTs);
|
||||
int sizeInBytes = sizeInTs * sizeof(T);
|
||||
value = new NativeArray<T>(sizeInTs, allocator);
|
||||
byte* bytes = (byte*)value.GetUnsafePtr();
|
||||
@@ -810,7 +837,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void ReadUnmanagedSafe<T>(out NativeArray<T> value, Allocator allocator) where T : unmanaged
|
||||
{
|
||||
ReadUnmanagedSafe(out int sizeInTs);
|
||||
ReadLengthSafe(out int sizeInTs);
|
||||
int sizeInBytes = sizeInTs * sizeof(T);
|
||||
value = new NativeArray<T>(sizeInTs, allocator);
|
||||
byte* bytes = (byte*)value.GetUnsafePtr();
|
||||
@@ -820,7 +847,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void ReadUnmanagedInPlace<T>(ref NativeList<T> value) where T : unmanaged
|
||||
{
|
||||
ReadUnmanaged(out int sizeInTs);
|
||||
ReadLength(out int sizeInTs);
|
||||
int sizeInBytes = sizeInTs * sizeof(T);
|
||||
value.Resize(sizeInTs, NativeArrayOptions.UninitializedMemory);
|
||||
byte* bytes = (byte*)value.GetUnsafePtr();
|
||||
@@ -829,7 +856,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void ReadUnmanagedSafeInPlace<T>(ref NativeList<T> value) where T : unmanaged
|
||||
{
|
||||
ReadUnmanagedSafe(out int sizeInTs);
|
||||
ReadLengthSafe(out int sizeInTs);
|
||||
int sizeInBytes = sizeInTs * sizeof(T);
|
||||
value.Resize(sizeInTs, NativeArrayOptions.UninitializedMemory);
|
||||
byte* bytes = (byte*)value.GetUnsafePtr();
|
||||
@@ -1078,7 +1105,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal void ReadValueSafeInPlace<T>(ref NativeHashSet<T> value) where T : unmanaged, IEquatable<T>
|
||||
{
|
||||
ReadUnmanagedSafe(out int length);
|
||||
ReadLengthSafe(out int length);
|
||||
value.Clear();
|
||||
for (var i = 0; i < length; ++i)
|
||||
{
|
||||
@@ -1093,7 +1120,7 @@ namespace Unity.Netcode
|
||||
where TKey : unmanaged, IEquatable<TKey>
|
||||
where TVal : unmanaged
|
||||
{
|
||||
ReadUnmanagedSafe(out int length);
|
||||
ReadLengthSafe(out int length);
|
||||
value.Clear();
|
||||
for (var i = 0; i < length; ++i)
|
||||
{
|
||||
@@ -1553,7 +1580,7 @@ namespace Unity.Netcode
|
||||
/// This method is a little difficult to use, since you have to know the size of the string before
|
||||
/// reading it, but is useful when the string is a known, fixed size. Note that the size of the
|
||||
/// string is also encoded, so the size to call TryBeginRead on is actually the fixed size (in bytes)
|
||||
/// plus sizeof(int)
|
||||
/// plus sizeof(uint)
|
||||
/// </summary>
|
||||
/// <param name="value">the value to read</param>
|
||||
/// <param name="unused">An unused parameter used for enabling overload resolution based on generic constraints</param>
|
||||
@@ -1562,7 +1589,7 @@ namespace Unity.Netcode
|
||||
public unsafe void ReadValue<T>(out T value, FastBufferWriter.ForFixedStrings unused = default)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
ReadUnmanaged(out int length);
|
||||
ReadLength(out int length);
|
||||
value = new T
|
||||
{
|
||||
Length = length
|
||||
@@ -1584,7 +1611,7 @@ namespace Unity.Netcode
|
||||
public unsafe void ReadValueSafe<T>(out T value, FastBufferWriter.ForFixedStrings unused = default)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
ReadUnmanagedSafe(out int length);
|
||||
ReadLengthSafe(out int length);
|
||||
value = new T
|
||||
{
|
||||
Length = length
|
||||
@@ -1606,7 +1633,7 @@ namespace Unity.Netcode
|
||||
public unsafe void ReadValueSafeInPlace<T>(ref T value, FastBufferWriter.ForFixedStrings unused = default)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
ReadUnmanagedSafe(out int length);
|
||||
ReadLengthSafe(out int length);
|
||||
value.Length = length;
|
||||
ReadBytesSafe(value.GetUnsafePtr(), length);
|
||||
}
|
||||
@@ -1625,7 +1652,7 @@ namespace Unity.Netcode
|
||||
public unsafe void ReadValueSafe<T>(out NativeArray<T> value, Allocator allocator)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
ReadUnmanagedSafe(out int length);
|
||||
ReadLengthSafe(out int length);
|
||||
value = new NativeArray<T>(length, allocator);
|
||||
var ptr = (T*)value.GetUnsafePtr();
|
||||
for (var i = 0; i < length; ++i)
|
||||
@@ -1647,7 +1674,7 @@ namespace Unity.Netcode
|
||||
public unsafe void ReadValueSafeTemp<T>(out NativeArray<T> value)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
ReadUnmanagedSafe(out int length);
|
||||
ReadLengthSafe(out int length);
|
||||
value = new NativeArray<T>(length, Allocator.Temp);
|
||||
var ptr = (T*)value.GetUnsafePtr();
|
||||
for (var i = 0; i < length; ++i)
|
||||
@@ -1669,7 +1696,7 @@ namespace Unity.Netcode
|
||||
public void ReadValueSafe<T>(out T[] value, FastBufferWriter.ForFixedStrings unused = default)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
ReadUnmanagedSafe(out int length);
|
||||
ReadLengthSafe(out int length);
|
||||
value = new T[length];
|
||||
for (var i = 0; i < length; ++i)
|
||||
{
|
||||
@@ -1691,7 +1718,7 @@ namespace Unity.Netcode
|
||||
public void ReadValueSafeInPlace<T>(ref NativeList<T> value)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
ReadUnmanagedSafe(out int length);
|
||||
ReadLengthSafe(out int length);
|
||||
value.Resize(length, NativeArrayOptions.UninitializedMemory);
|
||||
for (var i = 0; i < length; ++i)
|
||||
{
|
||||
|
||||
@@ -421,7 +421,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int GetWriteSize(string s, bool oneByteChars = false)
|
||||
{
|
||||
return sizeof(int) + s.Length * (oneByteChars ? sizeof(byte) : sizeof(char));
|
||||
return SizeOfLengthField() + s.Length * (oneByteChars ? sizeof(byte) : sizeof(char));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -445,7 +445,7 @@ namespace Unity.Netcode
|
||||
public void WriteNetworkSerializable<T>(T[] array, int count = -1, int offset = 0) where T : INetworkSerializable
|
||||
{
|
||||
int sizeInTs = count != -1 ? count : array.Length - offset;
|
||||
WriteValueSafe(sizeInTs);
|
||||
WriteLengthSafe(sizeInTs);
|
||||
foreach (var item in array)
|
||||
{
|
||||
WriteNetworkSerializable(item);
|
||||
@@ -462,7 +462,7 @@ namespace Unity.Netcode
|
||||
public void WriteNetworkSerializable<T>(NativeArray<T> array, int count = -1, int offset = 0) where T : unmanaged, INetworkSerializable
|
||||
{
|
||||
int sizeInTs = count != -1 ? count : array.Length - offset;
|
||||
WriteValueSafe(sizeInTs);
|
||||
WriteLengthSafe(sizeInTs);
|
||||
foreach (var item in array)
|
||||
{
|
||||
WriteNetworkSerializable(item);
|
||||
@@ -480,7 +480,7 @@ namespace Unity.Netcode
|
||||
public void WriteNetworkSerializable<T>(NativeList<T> array, int count = -1, int offset = 0) where T : unmanaged, INetworkSerializable
|
||||
{
|
||||
int sizeInTs = count != -1 ? count : array.Length - offset;
|
||||
WriteValueSafe(sizeInTs);
|
||||
WriteLengthSafe(sizeInTs);
|
||||
foreach (var item in array)
|
||||
{
|
||||
WriteNetworkSerializable(item);
|
||||
@@ -495,7 +495,7 @@ namespace Unity.Netcode
|
||||
/// <param name="oneByteChars">Whether or not to use one byte per character. This will only allow ASCII</param>
|
||||
public unsafe void WriteValue(string s, bool oneByteChars = false)
|
||||
{
|
||||
WriteValue((uint)s.Length);
|
||||
WriteLength((uint)s.Length);
|
||||
int target = s.Length;
|
||||
if (oneByteChars)
|
||||
{
|
||||
@@ -538,7 +538,7 @@ namespace Unity.Netcode
|
||||
throw new OverflowException("Writing past the end of the buffer");
|
||||
}
|
||||
|
||||
WriteValue((uint)s.Length);
|
||||
WriteLength((uint)s.Length);
|
||||
int target = s.Length;
|
||||
if (oneByteChars)
|
||||
{
|
||||
@@ -569,7 +569,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
int sizeInTs = count != -1 ? count : array.Length - offset;
|
||||
int sizeInBytes = sizeInTs * sizeof(T);
|
||||
return sizeof(int) + sizeInBytes;
|
||||
return SizeOfLengthField() + sizeInBytes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -585,7 +585,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
int sizeInTs = count != -1 ? count : array.Length - offset;
|
||||
int sizeInBytes = sizeInTs * sizeof(T);
|
||||
return sizeof(int) + sizeInBytes;
|
||||
return SizeOfLengthField() + sizeInBytes;
|
||||
}
|
||||
|
||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||
@@ -602,7 +602,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
int sizeInTs = count != -1 ? count : array.Length - offset;
|
||||
int sizeInBytes = sizeInTs * sizeof(T);
|
||||
return sizeof(int) + sizeInBytes;
|
||||
return SizeOfLengthField() + sizeInBytes;
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -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;
|
||||
@@ -876,7 +876,7 @@ namespace Unity.Netcode
|
||||
public static int GetWriteSize<T>(in T value)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
return value.Length + sizeof(int);
|
||||
return SizeOfLengthField() + value.Length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -888,10 +888,10 @@ namespace Unity.Netcode
|
||||
public static int GetWriteSize<T>(in NativeArray<T> value)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
var size = sizeof(int);
|
||||
var size = SizeOfLengthField();
|
||||
foreach (var item in value)
|
||||
{
|
||||
size += sizeof(int) + item.Length;
|
||||
size += SizeOfLengthField() + item.Length;
|
||||
}
|
||||
|
||||
return size;
|
||||
@@ -907,10 +907,10 @@ namespace Unity.Netcode
|
||||
public static int GetWriteSize<T>(in NativeList<T> value)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
var size = sizeof(int);
|
||||
var size = SizeOfLengthField();
|
||||
foreach (var item in value)
|
||||
{
|
||||
size += sizeof(int) + item.Length;
|
||||
size += SizeOfLengthField() + item.Length;
|
||||
}
|
||||
|
||||
return size;
|
||||
@@ -946,10 +946,32 @@ namespace Unity.Netcode
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static int SizeOfLengthField() => sizeof(uint);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void WriteLengthSafe(uint length) => WriteUnmanagedSafe(length);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void WriteLength(uint length) => WriteUnmanaged(length);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void WriteLengthSafe(int length)
|
||||
{
|
||||
if (length < 0)
|
||||
{
|
||||
throw new InvalidCastException("Cannot write negative length");
|
||||
}
|
||||
WriteLengthSafe((uint)length);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void WriteLength(int length) => WriteLength((uint)length);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void WriteUnmanaged<T>(T[] value) where T : unmanaged
|
||||
{
|
||||
WriteUnmanaged(value.Length);
|
||||
WriteLength(value.Length);
|
||||
fixed (T* ptr = value)
|
||||
{
|
||||
byte* bytes = (byte*)ptr;
|
||||
@@ -959,7 +981,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void WriteUnmanagedSafe<T>(T[] value) where T : unmanaged
|
||||
{
|
||||
WriteUnmanagedSafe(value.Length);
|
||||
WriteLengthSafe(value.Length);
|
||||
fixed (T* ptr = value)
|
||||
{
|
||||
byte* bytes = (byte*)ptr;
|
||||
@@ -970,7 +992,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void WriteUnmanaged<T>(NativeArray<T> value) where T : unmanaged
|
||||
{
|
||||
WriteUnmanaged(value.Length);
|
||||
WriteLength(value.Length);
|
||||
var ptr = (T*)value.GetUnsafePtr();
|
||||
{
|
||||
byte* bytes = (byte*)ptr;
|
||||
@@ -980,7 +1002,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void WriteUnmanagedSafe<T>(NativeArray<T> value) where T : unmanaged
|
||||
{
|
||||
WriteUnmanagedSafe(value.Length);
|
||||
WriteLengthSafe(value.Length);
|
||||
var ptr = (T*)value.GetUnsafePtr();
|
||||
{
|
||||
byte* bytes = (byte*)ptr;
|
||||
@@ -992,7 +1014,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void WriteUnmanaged<T>(NativeList<T> value) where T : unmanaged
|
||||
{
|
||||
WriteUnmanaged(value.Length);
|
||||
WriteLength(value.Length);
|
||||
#if UTP_TRANSPORT_2_0_ABOVE
|
||||
var ptr = value.GetUnsafePtr();
|
||||
#else
|
||||
@@ -1006,7 +1028,7 @@ namespace Unity.Netcode
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal unsafe void WriteUnmanagedSafe<T>(NativeList<T> value) where T : unmanaged
|
||||
{
|
||||
WriteUnmanagedSafe(value.Length);
|
||||
WriteLengthSafe(value.Length);
|
||||
#if UTP_TRANSPORT_2_0_ABOVE
|
||||
var ptr = value.GetUnsafePtr();
|
||||
#else
|
||||
@@ -1210,9 +1232,9 @@ namespace Unity.Netcode
|
||||
internal void WriteValueSafe<T>(NativeHashSet<T> value) where T : unmanaged, IEquatable<T>
|
||||
{
|
||||
#if UTP_TRANSPORT_2_0_ABOVE
|
||||
WriteUnmanagedSafe(value.Count);
|
||||
WriteLengthSafe(value.Count);
|
||||
#else
|
||||
WriteUnmanagedSafe(value.Count());
|
||||
WriteLengthSafe(value.Count());
|
||||
#endif
|
||||
foreach (var item in value)
|
||||
{
|
||||
@@ -1227,9 +1249,9 @@ namespace Unity.Netcode
|
||||
where TVal : unmanaged
|
||||
{
|
||||
#if UTP_TRANSPORT_2_0_ABOVE
|
||||
WriteUnmanagedSafe(value.Count);
|
||||
WriteLengthSafe(value.Count);
|
||||
#else
|
||||
WriteUnmanagedSafe(value.Count());
|
||||
WriteLengthSafe(value.Count());
|
||||
#endif
|
||||
foreach (var item in value)
|
||||
{
|
||||
@@ -1765,7 +1787,8 @@ namespace Unity.Netcode
|
||||
public unsafe void WriteValue<T>(in T value, ForFixedStrings unused = default)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
WriteUnmanaged(value.Length);
|
||||
// BytePacker.WriteValuePacked(this, value.Length);
|
||||
WriteLength(value.Length);
|
||||
// This avoids a copy on the string, which could be costly for FixedString4096Bytes
|
||||
// Otherwise, GetUnsafePtr() is an impure function call and will result in a copy
|
||||
// for `in` parameters.
|
||||
@@ -1787,7 +1810,7 @@ namespace Unity.Netcode
|
||||
public void WriteValue<T>(T[] value, ForFixedStrings unused = default)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
WriteUnmanaged(value.Length);
|
||||
WriteLength(value.Length);
|
||||
foreach (var str in value)
|
||||
{
|
||||
WriteValue(str);
|
||||
@@ -1806,7 +1829,7 @@ namespace Unity.Netcode
|
||||
public void WriteValue<T>(in NativeArray<T> value, ForFixedStrings unused = default)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
WriteUnmanaged(value.Length);
|
||||
WriteLength(value.Length);
|
||||
foreach (var str in value)
|
||||
{
|
||||
WriteValue(str);
|
||||
@@ -1826,7 +1849,7 @@ namespace Unity.Netcode
|
||||
public void WriteValue<T>(in NativeList<T> value, ForFixedStrings unused = default)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
WriteUnmanaged(value.Length);
|
||||
WriteLength(value.Length);
|
||||
foreach (var str in value)
|
||||
{
|
||||
WriteValue(str);
|
||||
@@ -1848,7 +1871,7 @@ namespace Unity.Netcode
|
||||
public void WriteValueSafe<T>(in T value, ForFixedStrings unused = default)
|
||||
where T : unmanaged, INativeList<byte>, IUTF8Bytes
|
||||
{
|
||||
if (!TryBeginWriteInternal(sizeof(int) + value.Length))
|
||||
if (!TryBeginWriteInternal(SizeOfLengthField() + value.Length))
|
||||
{
|
||||
throw new OverflowException("Writing past the end of the buffer");
|
||||
}
|
||||
@@ -1871,7 +1894,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
throw new OverflowException("Writing past the end of the buffer");
|
||||
}
|
||||
WriteUnmanaged(value.Length);
|
||||
WriteLength(value.Length);
|
||||
foreach (var str in value)
|
||||
{
|
||||
WriteValue(str);
|
||||
@@ -1894,7 +1917,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
throw new OverflowException("Writing past the end of the buffer");
|
||||
}
|
||||
WriteUnmanaged(value.Length);
|
||||
WriteLength(value.Length);
|
||||
foreach (var str in value)
|
||||
{
|
||||
WriteValue(str);
|
||||
@@ -1918,7 +1941,7 @@ namespace Unity.Netcode
|
||||
{
|
||||
throw new OverflowException("Writing past the end of the buffer");
|
||||
}
|
||||
WriteUnmanaged(value.Length);
|
||||
WriteLength(value.Length);
|
||||
foreach (var str in value)
|
||||
{
|
||||
WriteValue(str);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user