Compare commits
14 Commits
2.0.0-exp.
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| fe746bf2a3 | |||
|
|
8fe07bbad2 | ||
| 2e3ccb45b7 | |||
| 76d8157fc7 | |||
| 11e10acc00 | |||
| 887ec37b67 | |||
|
|
016788c21e | ||
|
|
48c6a6121c | ||
|
|
eab996f3ac | ||
|
|
a813ba0dd6 | ||
|
|
c813386c5c | ||
|
|
ed38a4dcc2 | ||
|
|
36d539e265 | ||
|
|
63c7e4c78a |
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"}
|
||||||
251
CHANGELOG.md
251
CHANGELOG.md
@@ -6,11 +6,220 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
|
|||||||
|
|
||||||
Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).
|
Additional documentation and release notes are available at [Multiplayer Documentation](https://docs-multiplayer.unity3d.com).
|
||||||
|
|
||||||
|
|
||||||
|
## [2.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
|
||||||
|
|
||||||
|
- Added `NetworkRigidbodyBase.AttachToFixedJoint` and `NetworkRigidbodyBase.DetachFromFixedJoint` to replace parenting for rigid bodies that have `NetworkRigidbodyBase.UseRigidBodyForMotion` enabled. (#2933)
|
||||||
|
- Added `NetworkBehaviour.OnNetworkPreSpawn` and `NetworkBehaviour.OnNetworkPostSpawn` methods that provide the ability to handle pre and post spawning actions during the `NetworkObject` spawn sequence. (#2912)
|
||||||
|
- Added a client-side only `NetworkBehaviour.OnNetworkSessionSynchronized` convenience method that is invoked on all `NetworkBehaviour`s after a newly joined client has finished synchronizing with the network session in progress. (#2912)
|
||||||
|
- Added `NetworkBehaviour.OnInSceneObjectsSpawned` convenience method that is invoked when all in-scene `NetworkObject`s have been spawned after a scene has been loaded or upon a host or server starting. (#2912)
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fixed issue where non-authoritative rigid bodies with `NetworkRigidbodyBase.UseRigidBodyForMotion` enabled would constantly log errors about the renderTime being before `StartTimeConsumed`. (#2933)
|
||||||
|
- Fixed issue where in-scene placed NetworkObjects could be destroyed if a client disconnects early and/or before approval. (#2924)
|
||||||
|
- Fixed issue where a `NetworkObject` component's associated `NetworkBehaviour` components would not be detected if scene loading is disabled in the editor and the currently loaded scene has in-scene placed `NetworkObject`s. (#2912)
|
||||||
|
- Fixed issue where an in-scene placed `NetworkObject` with `NetworkTransform` that is also parented under a `GameObject` would not properly synchronize when the parent `GameObject` had a world space position other than 0,0,0. (#2898)
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Change all the access modifiers of test class from Public to Internal (#2930)
|
||||||
|
- Changed messages are now sorted by enum values as opposed to ordinally sorting the messages by their type name. (#2929)
|
||||||
|
- Changed `NetworkClient.SessionModeTypes` to `NetworkClient.NetworkTopologyTypes`. (#2875)
|
||||||
|
- Changed `NetworkClient.SessionModeType` to `NetworkClient.NetworkTopologyType`. (#2875)
|
||||||
|
- Changed `NetworkConfig.SessionMode` to `NeworkConfig.NetworkTopology`. (#2875)
|
||||||
|
|
||||||
## [2.0.0-exp.2] - 2024-04-02
|
## [2.0.0-exp.2] - 2024-04-02
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
- Added updates to all internal messages to account for a distributed authority network session connection. (#2863)
|
- Added updates to all internal messages to account for a distributed authority network session connection. (#2863)
|
||||||
- Added `NetworkRigidbodyBase` that provides users with a more customizable network rigidbody, handles both `Rigidbody` and `Rigidbody2D`, and provides an option to make `NetworkTransform` use the rigid body for motion. (#2863)
|
- Added `NetworkRigidbodyBase` that provides users with a more customizable network rigidbody, handles both `Rigidbody` and `Rigidbody2D`, and provides an option to make `NetworkTransform` use the rigid body for motion. (#2863)
|
||||||
- For a customized `NetworkRigidbodyBase` class:
|
- For a customized `NetworkRigidbodyBase` class:
|
||||||
- `NetworkRigidbodyBase.AutoUpdateKinematicState` provides control on whether the kinematic setting will be automatically set or not when ownership changes.
|
- `NetworkRigidbodyBase.AutoUpdateKinematicState` provides control on whether the kinematic setting will be automatically set or not when ownership changes.
|
||||||
- `NetworkRigidbodyBase.AutoSetKinematicOnDespawn` provides control on whether isKinematic will automatically be set to true when the associated `NetworkObject` is despawned.
|
- `NetworkRigidbodyBase.AutoSetKinematicOnDespawn` provides control on whether isKinematic will automatically be set to true when the associated `NetworkObject` is despawned.
|
||||||
@@ -52,7 +261,7 @@ Additional documentation and release notes are available at [Multiplayer Documen
|
|||||||
- Added distributed authority mode specific `NetworkObject.OnDeferredDespawnComplete` callback handler that can be used to further control when deferring the despawning of a `NetworkObject` on non-authoritative instances. (#2863)
|
- Added distributed authority mode specific `NetworkObject.OnDeferredDespawnComplete` callback handler that can be used to further control when deferring the despawning of a `NetworkObject` on non-authoritative instances. (#2863)
|
||||||
- Added `NetworkClient.SessionModeType` as one way to determine the current session mode of the network session a client is connected to. (#2863)
|
- Added `NetworkClient.SessionModeType` as one way to determine the current session mode of the network session a client is connected to. (#2863)
|
||||||
- Added distributed authority mode specific `NetworkClient.IsSessionOwner` property to determine if the current local client is the current session owner of a distributed authority session. (#2863)
|
- Added distributed authority mode specific `NetworkClient.IsSessionOwner` property to determine if the current local client is the current session owner of a distributed authority session. (#2863)
|
||||||
- Added distributed authority mode specific client side spawning capabilities. When running in distributed authority mode, clients can instantiate and spawn `NetworkObject` instances (the local client is authomatically the owner of the spawned object). (#2863)
|
- Added distributed authority mode specific client side spawning capabilities. When running in distributed authority mode, clients can instantiate and spawn `NetworkObject` instances (the local client is automatically the owner of the spawned object). (#2863)
|
||||||
- This is useful to better visually synchronize owner authoritative motion models and newly spawned `NetworkObject` instances (i.e. projectiles for example).
|
- This is useful to better visually synchronize owner authoritative motion models and newly spawned `NetworkObject` instances (i.e. projectiles for example).
|
||||||
- Added distributed authority mode specific client side player spawning capabilities. Clients will automatically spawn their associated player object locally. (#2863)
|
- Added distributed authority mode specific client side player spawning capabilities. Clients will automatically spawn their associated player object locally. (#2863)
|
||||||
- Added distributed authority mode specific `NetworkConfig.AutoSpawnPlayerPrefabClientSide` property (default is true) to provide control over the automatic spawning of player prefabs on the local client side. (#2863)
|
- Added distributed authority mode specific `NetworkConfig.AutoSpawnPlayerPrefabClientSide` property (default is true) to provide control over the automatic spawning of player prefabs on the local client side. (#2863)
|
||||||
@@ -79,6 +288,36 @@ Additional documentation and release notes are available at [Multiplayer Documen
|
|||||||
- Changed `NetworkTransform` to now use `NetworkTransformMessage` as opposed to named messages for NetworkTransformState updates. (#2810)
|
- Changed `NetworkTransform` to now use `NetworkTransformMessage` as opposed to named messages for NetworkTransformState updates. (#2810)
|
||||||
- Changed `CustomMessageManager` so it no longer attempts to register or "unregister" a null or empty string and will log an error if this condition occurs. (#2807)
|
- Changed `CustomMessageManager` so it no longer attempts to register or "unregister" a null or empty string and will log an error if this condition occurs. (#2807)
|
||||||
|
|
||||||
|
## [1.9.1] - 2024-04-18
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Added `AnticipatedNetworkVariable<T>`, which adds support for client anticipation of NetworkVariable values, allowing for more responsive game play (#2820)
|
||||||
|
- Added `AnticipatedNetworkTransform`, which adds support for client anticipation of `NetworkTransform`s (#2820)
|
||||||
|
- Added `NetworkVariableBase.ExceedsDirtinessThreshold` to allow network variables to throttle updates by only sending updates when the difference between the current and previous values exceeds a threshold. (This is exposed in NetworkVariable<T> with the callback NetworkVariable<T>.CheckExceedsDirtinessThreshold) (#2820)
|
||||||
|
- Added `NetworkVariableUpdateTraits`, which add additional throttling support: `MinSecondsBetweenUpdates` will prevent the `NetworkVariable` from sending updates more often than the specified time period (even if it exceeds the dirtiness threshold), while `MaxSecondsBetweenUpdates` will force a dirty `NetworkVariable` to send an update after the specified time period even if it has not yet exceeded the dirtiness threshold. (#2820)
|
||||||
|
- Added virtual method `NetworkVariableBase.OnInitialize()` which can be used by `NetworkVariable` subclasses to add initialization code (#2820)
|
||||||
|
- Added virtual method `NetworkVariableBase.Update()`, which is called once per frame to support behaviors such as interpolation between an anticipated value and an authoritative one. (#2820)
|
||||||
|
- Added `NetworkTime.TickWithPartial`, which represents the current tick as a double that includes the fractional/partial tick value. (#2820)
|
||||||
|
- `NetworkVariable` now includes built-in support for `NativeHashSet`, `NativeHashMap`, `List`, `HashSet`, and `Dictionary` (#2813)
|
||||||
|
- `NetworkVariable` now includes delta compression for collection values (`NativeList`, `NativeArray`, `NativeHashSet`, `NativeHashMap`, `List`, `HashSet`, `Dictionary`, and `FixedString` types) to save bandwidth by only sending the values that changed. (Note: For `NativeList`, `NativeArray`, and `List`, this algorithm works differently than that used in `NetworkList`. This algorithm will use less bandwidth for "set" and "add" operations, but `NetworkList` is more bandwidth-efficient if you are performing frequent "insert" operations.) (#2813)
|
||||||
|
- `UserNetworkVariableSerialization` now has optional callbacks for `WriteDelta` and `ReadDelta`. If both are provided, they will be used for all serialization operations on NetworkVariables of that type except for the first one for each client. If either is missing, the existing `Write` and `Read` will always be used. (#2813)
|
||||||
|
- Network variables wrapping `INetworkSerializable` types can perform delta serialization by setting `UserNetworkVariableSerialization<T>.WriteDelta` and `UserNetworkVariableSerialization<T>.ReadDelta` for those types. The built-in `INetworkSerializable` serializer will continue to be used for all other serialization operations, but if those callbacks are set, it will call into them on all but the initial serialization to perform delta serialization. (This could be useful if you have a large struct where most values do not change regularly and you want to send only the fields that did change.) (#2813)
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fixed issue where `NetworkTransformEditor` would throw and exception if you excluded the physics package. (#2871)
|
||||||
|
- Fixed issue where `NetworkTransform` could not properly synchronize its base position when using half float precision. (#2845)
|
||||||
|
- Fixed issue where the host was not invoking `OnClientDisconnectCallback` for its own local client when internally shutting down. (#2822)
|
||||||
|
- Fixed issue where NetworkTransform could potentially attempt to "unregister" a named message prior to it being registered. (#2807)
|
||||||
|
- Fixed issue where in-scene placed `NetworkObject`s with complex nested children `NetworkObject`s (more than one child in depth) would not synchronize properly if WorldPositionStays was set to true. (#2796)
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Changed `NetworkObjectReference` and `NetworkBehaviourReference` to allow null references when constructing and serializing. (#2874)
|
||||||
|
- Changed `NetworkAnimator` no longer requires the `Animator` component to exist on the same `GameObject`. (#2872)
|
||||||
|
- Changed `NetworkTransform` to now use `NetworkTransformMessage` as opposed to named messages for NetworkTransformState updates. (#2810)
|
||||||
|
- Changed `CustomMessageManager` so it no longer attempts to register or "unregister" a null or empty string and will log an error if this condition occurs. (#2807)
|
||||||
|
|
||||||
## [1.8.1] - 2024-02-05
|
## [1.8.1] - 2024-02-05
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
@@ -116,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)
|
- Fixed issue where you could not have multiple source network prefab overrides targeting the same network prefab as their override. (#2710)
|
||||||
|
|
||||||
### Changed
|
### 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 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 `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)
|
- Changed `NetworkTransform.SetState` (and related methods) now are cumulative during a fractional tick period and sent on the next pending tick. (#2777)
|
||||||
@@ -128,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 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)
|
- Changed the default `NetworkConfig.SpawnTimeout` value from 1.0s to 10.0s. (#2710)
|
||||||
|
|
||||||
|
|
||||||
## [1.7.1] - 2023-11-15
|
## [1.7.1] - 2023-11-15
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
@@ -177,7 +418,7 @@ Additional documentation and release notes are available at [Multiplayer Documen
|
|||||||
### Added
|
### Added
|
||||||
|
|
||||||
- Added a protected virtual method `NetworkTransform.OnInitialize(ref NetworkTransformState replicatedState)` that just returns the replicated state reference.
|
- Added a protected virtual method `NetworkTransform.OnInitialize(ref NetworkTransformState replicatedState)` that just returns the replicated state reference.
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
- Fixed issue where invoking `NetworkManager.Shutdown` within `NetworkManager.OnClientStopped` or `NetworkManager.OnServerStopped` would force `NetworkManager.ShutdownInProgress` to remain true after completing the shutdown process. (#2661)
|
- Fixed issue where invoking `NetworkManager.Shutdown` within `NetworkManager.OnClientStopped` or `NetworkManager.OnServerStopped` would force `NetworkManager.ShutdownInProgress` to remain true after completing the shutdown process. (#2661)
|
||||||
@@ -235,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 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)
|
- 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)
|
- 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)
|
- Connecting clients being synchronized now switch to the server's active scene before spawning and synchronizing NetworkObjects. (#2532)
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
using System.Runtime.CompilerServices;
|
|
||||||
|
|
||||||
#if UNITY_EDITOR
|
|
||||||
[assembly: InternalsVisibleTo("Unity.Netcode.Editor")]
|
|
||||||
[assembly: InternalsVisibleTo("Unity.Netcode.Editor.CodeGen")]
|
|
||||||
#endif // UNITY_EDITOR
|
|
||||||
|
|
||||||
#if UNITY_INCLUDE_TESTS
|
|
||||||
[assembly: InternalsVisibleTo("Unity.Netcode.RuntimeTests")]
|
|
||||||
[assembly: InternalsVisibleTo("TestProject.RuntimeTests")]
|
|
||||||
#if UNITY_EDITOR
|
|
||||||
[assembly: InternalsVisibleTo("Unity.Netcode.EditorTests")]
|
|
||||||
[assembly: InternalsVisibleTo("TestProject.EditorTests")]
|
|
||||||
#endif // UNITY_EDITOR
|
|
||||||
#endif // UNITY_INCLUDE_TESTS
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
fileFormatVersion: 2
|
|
||||||
guid: 5b8086dc75d86473f9e3c928dd773733
|
|
||||||
MonoImporter:
|
|
||||||
externalObjects: {}
|
|
||||||
serializedVersion: 2
|
|
||||||
defaultReferences: []
|
|
||||||
executionOrder: 0
|
|
||||||
icon: {instanceID: 0}
|
|
||||||
userData:
|
|
||||||
assetBundleName:
|
|
||||||
assetBundleVariant:
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
fileFormatVersion: 2
|
|
||||||
guid: a9db1d18fa0117f4da5e8e65386b894a
|
|
||||||
folderAsset: yes
|
|
||||||
DefaultImporter:
|
|
||||||
externalObjects: {}
|
|
||||||
userData:
|
|
||||||
assetBundleName:
|
|
||||||
assetBundleVariant:
|
|
||||||
@@ -1,205 +0,0 @@
|
|||||||
using Unity.Netcode.Components;
|
|
||||||
using UnityEngine;
|
|
||||||
|
|
||||||
namespace Unity.Netcode
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// NetworkTransform State Update Message
|
|
||||||
/// </summary>
|
|
||||||
internal struct NetworkTransformMessage : INetworkMessage
|
|
||||||
{
|
|
||||||
public int Version => 0;
|
|
||||||
public ulong NetworkObjectId;
|
|
||||||
public int NetworkBehaviourId;
|
|
||||||
// This is only used when serializing but not serialized
|
|
||||||
public bool DistributedAuthorityMode;
|
|
||||||
// Might get removed
|
|
||||||
public ulong[] TargetIds;
|
|
||||||
|
|
||||||
private int GetTargetIdLength()
|
|
||||||
{
|
|
||||||
if (TargetIds != null)
|
|
||||||
{
|
|
||||||
return TargetIds.Length;
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
public NetworkTransform.NetworkTransformState State;
|
|
||||||
|
|
||||||
private NetworkTransform m_ReceiverNetworkTransform;
|
|
||||||
private FastBufferReader m_CurrentReader;
|
|
||||||
|
|
||||||
private unsafe void CopyPayload(ref FastBufferWriter writer)
|
|
||||||
{
|
|
||||||
writer.WriteBytesSafe(m_CurrentReader.GetUnsafePtrAtCurrentPosition(), m_CurrentReader.Length - m_CurrentReader.Position);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Serialize(FastBufferWriter writer, int targetVersion)
|
|
||||||
{
|
|
||||||
if (m_CurrentReader.IsInitialized)
|
|
||||||
{
|
|
||||||
CopyPayload(ref writer);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
BytePacker.WriteValueBitPacked(writer, NetworkObjectId);
|
|
||||||
BytePacker.WriteValueBitPacked(writer, NetworkBehaviourId);
|
|
||||||
writer.WriteNetworkSerializable(State);
|
|
||||||
if (DistributedAuthorityMode)
|
|
||||||
{
|
|
||||||
var length = GetTargetIdLength();
|
|
||||||
BytePacker.WriteValuePacked(writer, length);
|
|
||||||
// If no target ids, then just exit early (DAHost specific)
|
|
||||||
if (length == 0)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
foreach (var target in TargetIds)
|
|
||||||
{
|
|
||||||
BytePacker.WriteValuePacked(writer, target);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
|
|
||||||
{
|
|
||||||
var networkManager = context.SystemOwner as NetworkManager;
|
|
||||||
if (networkManager == null)
|
|
||||||
{
|
|
||||||
Debug.LogError($"[{nameof(NetworkTransformMessage)}] System owner context was not of type {nameof(NetworkManager)}!");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
var currentPosition = reader.Position;
|
|
||||||
ByteUnpacker.ReadValueBitPacked(reader, out NetworkObjectId);
|
|
||||||
var isSpawnedLocally = networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId);
|
|
||||||
|
|
||||||
// Only defer if the NetworkObject is not spawned yet and the local NetworkManager is not running as a DAHost.
|
|
||||||
if (!isSpawnedLocally && !networkManager.DAHost)
|
|
||||||
{
|
|
||||||
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// While the below check and assignment might seem out of place, this is specific to running in DAHost mode when a NetworkObject is
|
|
||||||
// hidden from the DAHost but is visible to other clients. Since the DAHost needs to forward updates to the clients, we ignore processing
|
|
||||||
// this message locally
|
|
||||||
var networkObject = (NetworkObject)null;
|
|
||||||
var isServerAuthoritative = false;
|
|
||||||
var ownerAuthoritativeServerSide = false;
|
|
||||||
|
|
||||||
// Get the behaviour index
|
|
||||||
ByteUnpacker.ReadValueBitPacked(reader, out NetworkBehaviourId);
|
|
||||||
|
|
||||||
// Deserialize the state
|
|
||||||
reader.ReadNetworkSerializableInPlace(ref State);
|
|
||||||
|
|
||||||
if (networkManager.DistributedAuthorityMode)
|
|
||||||
{
|
|
||||||
var targetCount = 0;
|
|
||||||
ByteUnpacker.ReadValueBitPacked(reader, out targetCount);
|
|
||||||
if (targetCount > 0)
|
|
||||||
{
|
|
||||||
TargetIds = new ulong[targetCount];
|
|
||||||
}
|
|
||||||
var targetId = (ulong)0;
|
|
||||||
for (int i = 0; i < targetCount; i++)
|
|
||||||
{
|
|
||||||
ByteUnpacker.ReadValueBitPacked(reader, out targetId);
|
|
||||||
TargetIds[i] = targetId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isSpawnedLocally)
|
|
||||||
{
|
|
||||||
networkObject = networkManager.SpawnManager.SpawnedObjects[NetworkObjectId];
|
|
||||||
// Get the target NetworkTransform
|
|
||||||
m_ReceiverNetworkTransform = networkObject.ChildNetworkBehaviours[NetworkBehaviourId] as NetworkTransform;
|
|
||||||
isServerAuthoritative = m_ReceiverNetworkTransform.IsServerAuthoritative();
|
|
||||||
ownerAuthoritativeServerSide = !isServerAuthoritative && networkManager.IsServer;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
// If we are the DAHost and the NetworkObject is hidden from the host we still need to forward this message
|
|
||||||
ownerAuthoritativeServerSide = networkManager.DAHost && !isSpawnedLocally;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ownerAuthoritativeServerSide)
|
|
||||||
{
|
|
||||||
var ownerClientId = (ulong)0;
|
|
||||||
|
|
||||||
if (networkObject != null)
|
|
||||||
{
|
|
||||||
ownerClientId = networkObject.OwnerClientId;
|
|
||||||
if (ownerClientId == NetworkManager.ServerClientId)
|
|
||||||
{
|
|
||||||
// Ownership must have changed, ignore any additional pending messages that might have
|
|
||||||
// come from a previous owner client.
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (networkManager.DAHost)
|
|
||||||
{
|
|
||||||
// Specific to distributed authority mode, the only sender of state updates will be the owner
|
|
||||||
ownerClientId = context.SenderId;
|
|
||||||
}
|
|
||||||
|
|
||||||
var networkDelivery = State.IsReliableStateUpdate() ? NetworkDelivery.ReliableSequenced : NetworkDelivery.UnreliableSequenced;
|
|
||||||
|
|
||||||
// Forward the state update if there are any remote clients to foward it to
|
|
||||||
if (networkManager.ConnectionManager.ConnectedClientsList.Count > (networkManager.IsHost ? 2 : 1))
|
|
||||||
{
|
|
||||||
var clientCount = networkManager.DistributedAuthorityMode ? GetTargetIdLength() : networkManager.ConnectionManager.ConnectedClientsList.Count;
|
|
||||||
if (clientCount == 0)
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// This is only to copy the existing and already serialized struct for forwarding purposes only.
|
|
||||||
// This will not include any changes made to this struct at this particular stage of processing the message.
|
|
||||||
var currentMessage = this;
|
|
||||||
// Create a new reader that replicates this message
|
|
||||||
currentMessage.m_CurrentReader = new FastBufferReader(reader, Collections.Allocator.None);
|
|
||||||
// Rewind the new reader to the beginning of the message's payload
|
|
||||||
currentMessage.m_CurrentReader.Seek(currentPosition);
|
|
||||||
// Forward the message to all connected clients that are observers of the associated NetworkObject
|
|
||||||
|
|
||||||
for (int i = 0; i < clientCount; i++)
|
|
||||||
{
|
|
||||||
var clientId = networkManager.DistributedAuthorityMode ? TargetIds[i] : networkManager.ConnectionManager.ConnectedClientsList[i].ClientId;
|
|
||||||
if (NetworkManager.ServerClientId == clientId || (!isServerAuthoritative && clientId == ownerClientId) ||
|
|
||||||
(!networkManager.DistributedAuthorityMode && !networkObject.Observers.Contains(clientId)))
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
networkManager.MessageManager.SendMessage(ref currentMessage, networkDelivery, clientId);
|
|
||||||
}
|
|
||||||
// Dispose of the reader used for forwarding
|
|
||||||
currentMessage.m_CurrentReader.Dispose();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Handle(ref NetworkContext context)
|
|
||||||
{
|
|
||||||
var networkManager = context.SystemOwner as NetworkManager;
|
|
||||||
// Only if the local NetworkManager instance is running as the DAHost we just exit if there is no local
|
|
||||||
// NetworkTransform component to apply the state update to (i.e. it is hidden from the DAHost and it
|
|
||||||
// just forwarded the state update to any other connected client)
|
|
||||||
if (networkManager.DAHost && m_ReceiverNetworkTransform == null)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (m_ReceiverNetworkTransform == null)
|
|
||||||
{
|
|
||||||
Debug.LogError($"[{nameof(NetworkTransformMessage)}][Dropped] Reciever {nameof(NetworkTransform)} was not set!");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
m_ReceiverNetworkTransform.TransformStateUpdate(ref State, context.SenderId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,535 +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>
|
|
||||||
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;
|
|
||||||
private NetworkTransform m_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;
|
|
||||||
m_NetworkTransform = networkTransform;
|
|
||||||
|
|
||||||
if (m_IsRigidbody2D && m_Rigidbody2D == null)
|
|
||||||
{
|
|
||||||
m_Rigidbody2D = GetComponent<Rigidbody2D>();
|
|
||||||
|
|
||||||
}
|
|
||||||
else if (m_Rigidbody == null)
|
|
||||||
{
|
|
||||||
m_Rigidbody = GetComponent<Rigidbody>();
|
|
||||||
}
|
|
||||||
|
|
||||||
SetOriginalInterpolation();
|
|
||||||
|
|
||||||
if (m_NetworkTransform == null)
|
|
||||||
{
|
|
||||||
m_NetworkTransform = GetComponent<NetworkTransform>();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (m_NetworkTransform != null)
|
|
||||||
{
|
|
||||||
m_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)
|
|
||||||
{
|
|
||||||
m_Rigidbody2D.MoveRotation(rotation);
|
|
||||||
}
|
|
||||||
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 (m_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 : (m_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 (m_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 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);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// When <see cref="UseRigidBodyForMotion"/> is enabled, the <see cref="NetworkTransform"/> will update Kinematic instances using
|
|
||||||
/// the Rigidbody's move methods allowing Rigidbody interpolation settings to be taken into consideration by the physics simulation.
|
|
||||||
/// </summary>
|
|
||||||
/// <remarks>
|
|
||||||
/// This will update the associated <see cref="NetworkTransform"/> during FixedUpdate which also avoids the added expense of adding
|
|
||||||
/// a FixedUpdate to all <see cref="NetworkTransform"/> instances where some might not be using a Rigidbody.
|
|
||||||
/// </remarks>
|
|
||||||
private void FixedUpdate()
|
|
||||||
{
|
|
||||||
if (!IsSpawned || m_NetworkTransform == null || !UseRigidBodyForMotion)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
m_NetworkTransform.OnFixedUpdate();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#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:
|
|
||||||
@@ -1,230 +0,0 @@
|
|||||||
#if COM_UNITY_MODULES_PHYSICS
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using Unity.Collections;
|
|
||||||
using Unity.Jobs;
|
|
||||||
using UnityEngine;
|
|
||||||
|
|
||||||
namespace Unity.Netcode.Components
|
|
||||||
{
|
|
||||||
public interface IContactEventHandler
|
|
||||||
{
|
|
||||||
Rigidbody GetRigidbody();
|
|
||||||
|
|
||||||
void ContactEvent(ulong eventId, Vector3 averagedCollisionNormal, Rigidbody collidingBody, Vector3 contactPoint, bool hasCollisionStay = false, Vector3 averagedCollisionStayNormal = default);
|
|
||||||
}
|
|
||||||
|
|
||||||
[AddComponentMenu("Netcode/Rigidbody Contact Event Manager")]
|
|
||||||
public class RigidbodyContactEventManager : MonoBehaviour
|
|
||||||
{
|
|
||||||
public static RigidbodyContactEventManager Instance { get; private set; }
|
|
||||||
|
|
||||||
private struct JobResultStruct
|
|
||||||
{
|
|
||||||
public bool HasCollisionStay;
|
|
||||||
public int ThisInstanceID;
|
|
||||||
public int OtherInstanceID;
|
|
||||||
public Vector3 AverageNormal;
|
|
||||||
public Vector3 AverageCollisionStayNormal;
|
|
||||||
public Vector3 ContactPoint;
|
|
||||||
}
|
|
||||||
|
|
||||||
private NativeArray<JobResultStruct> m_ResultsArray;
|
|
||||||
private int m_Count = 0;
|
|
||||||
private JobHandle m_JobHandle;
|
|
||||||
|
|
||||||
private readonly Dictionary<int, Rigidbody> m_RigidbodyMapping = new Dictionary<int, Rigidbody>();
|
|
||||||
private readonly Dictionary<int, IContactEventHandler> m_HandlerMapping = new Dictionary<int, IContactEventHandler>();
|
|
||||||
|
|
||||||
private void OnEnable()
|
|
||||||
{
|
|
||||||
m_ResultsArray = new NativeArray<JobResultStruct>(16, Allocator.Persistent);
|
|
||||||
Physics.ContactEvent += Physics_ContactEvent;
|
|
||||||
if (Instance != null)
|
|
||||||
{
|
|
||||||
NetworkLog.LogError($"[Invalid][Multiple Instances] Found more than one instance of {nameof(RigidbodyContactEventManager)}: {name} and {Instance.name}");
|
|
||||||
NetworkLog.LogError($"[Disable][Additional Instance] Disabling {name} instance!");
|
|
||||||
gameObject.SetActive(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Instance = this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void RegisterHandler(IContactEventHandler contactEventHandler, bool register = true)
|
|
||||||
{
|
|
||||||
var rigidbody = contactEventHandler.GetRigidbody();
|
|
||||||
var instanceId = rigidbody.GetInstanceID();
|
|
||||||
if (register)
|
|
||||||
{
|
|
||||||
if (!m_RigidbodyMapping.ContainsKey(instanceId))
|
|
||||||
{
|
|
||||||
m_RigidbodyMapping.Add(instanceId, rigidbody);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!m_HandlerMapping.ContainsKey(instanceId))
|
|
||||||
{
|
|
||||||
m_HandlerMapping.Add(instanceId, contactEventHandler);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
m_RigidbodyMapping.Remove(instanceId);
|
|
||||||
m_HandlerMapping.Remove(instanceId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void OnDisable()
|
|
||||||
{
|
|
||||||
m_JobHandle.Complete();
|
|
||||||
m_ResultsArray.Dispose();
|
|
||||||
|
|
||||||
Physics.ContactEvent -= Physics_ContactEvent;
|
|
||||||
|
|
||||||
m_RigidbodyMapping.Clear();
|
|
||||||
Instance = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private bool m_HasCollisions;
|
|
||||||
private int m_CurrentCount = 0;
|
|
||||||
|
|
||||||
private void ProcessCollisions()
|
|
||||||
{
|
|
||||||
// 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))
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (m_ResultsArray[i].HasCollisionStay)
|
|
||||||
{
|
|
||||||
m_HandlerMapping[thisInstanceID].ContactEvent(m_EventId, m_ResultsArray[i].AverageNormal, m_RigidbodyMapping[otherInstanceID], m_ResultsArray[i].ContactPoint, m_ResultsArray[i].HasCollisionStay, m_ResultsArray[i].AverageCollisionStayNormal);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
m_HandlerMapping[thisInstanceID].ContactEvent(m_EventId, m_ResultsArray[i].AverageNormal, m_RigidbodyMapping[otherInstanceID], m_ResultsArray[i].ContactPoint);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void FixedUpdate()
|
|
||||||
{
|
|
||||||
// Only process new collisions
|
|
||||||
if (!m_HasCollisions && m_CurrentCount == 0)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// This assures we won't process the same collision
|
|
||||||
// set after it has been processed.
|
|
||||||
if (m_HasCollisions)
|
|
||||||
{
|
|
||||||
m_CurrentCount = m_Count;
|
|
||||||
m_HasCollisions = false;
|
|
||||||
m_JobHandle.Complete();
|
|
||||||
}
|
|
||||||
ProcessCollisions();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void LateUpdate()
|
|
||||||
{
|
|
||||||
m_CurrentCount = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
private ulong m_EventId;
|
|
||||||
private void Physics_ContactEvent(PhysicsScene scene, NativeArray<ContactPairHeader>.ReadOnly pairHeaders)
|
|
||||||
{
|
|
||||||
m_EventId++;
|
|
||||||
m_HasCollisions = true;
|
|
||||||
int n = pairHeaders.Length;
|
|
||||||
if (m_ResultsArray.Length < n)
|
|
||||||
{
|
|
||||||
m_ResultsArray.Dispose();
|
|
||||||
m_ResultsArray = new NativeArray<JobResultStruct>(Mathf.NextPowerOfTwo(n), Allocator.Persistent);
|
|
||||||
}
|
|
||||||
m_Count = n;
|
|
||||||
var job = new GetCollisionsJob()
|
|
||||||
{
|
|
||||||
PairedHeaders = pairHeaders,
|
|
||||||
ResultsArray = m_ResultsArray
|
|
||||||
};
|
|
||||||
m_JobHandle = job.Schedule(n, 256);
|
|
||||||
}
|
|
||||||
|
|
||||||
private struct GetCollisionsJob : IJobParallelFor
|
|
||||||
{
|
|
||||||
[ReadOnly]
|
|
||||||
public NativeArray<ContactPairHeader>.ReadOnly PairedHeaders;
|
|
||||||
|
|
||||||
public NativeArray<JobResultStruct> ResultsArray;
|
|
||||||
|
|
||||||
public void Execute(int index)
|
|
||||||
{
|
|
||||||
Vector3 averageNormal = Vector3.zero;
|
|
||||||
Vector3 averagePoint = Vector3.zero;
|
|
||||||
Vector3 averageCollisionStay = Vector3.zero;
|
|
||||||
int count = 0;
|
|
||||||
int collisionStaycount = 0;
|
|
||||||
int positionCount = 0;
|
|
||||||
for (int j = 0; j < PairedHeaders[index].pairCount; j++)
|
|
||||||
{
|
|
||||||
ref readonly var pair = ref PairedHeaders[index].GetContactPair(j);
|
|
||||||
|
|
||||||
if (pair.isCollisionExit)
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int k = 0; k < pair.contactCount; k++)
|
|
||||||
{
|
|
||||||
ref readonly var contact = ref pair.GetContactPoint(k);
|
|
||||||
averagePoint += contact.position;
|
|
||||||
positionCount++;
|
|
||||||
if (!pair.isCollisionStay)
|
|
||||||
{
|
|
||||||
averageNormal += contact.normal;
|
|
||||||
count++;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
averageCollisionStay += contact.normal;
|
|
||||||
collisionStaycount++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (count != 0)
|
|
||||||
{
|
|
||||||
averageNormal /= count;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (collisionStaycount != 0)
|
|
||||||
{
|
|
||||||
averageCollisionStay /= collisionStaycount;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (positionCount != 0)
|
|
||||||
{
|
|
||||||
averagePoint /= positionCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
var result = new JobResultStruct()
|
|
||||||
{
|
|
||||||
ThisInstanceID = PairedHeaders[index].bodyInstanceID,
|
|
||||||
OtherInstanceID = PairedHeaders[index].otherBodyInstanceID,
|
|
||||||
AverageNormal = averageNormal,
|
|
||||||
HasCollisionStay = collisionStaycount != 0,
|
|
||||||
AverageCollisionStayNormal = averageCollisionStay,
|
|
||||||
ContactPoint = averagePoint
|
|
||||||
};
|
|
||||||
|
|
||||||
ResultsArray[index] = result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "Unity.Netcode.Components",
|
|
||||||
"rootNamespace": "Unity.Netcode.Components",
|
|
||||||
"references": [
|
|
||||||
"Unity.Netcode.Runtime",
|
|
||||||
"Unity.Collections",
|
|
||||||
"Unity.Mathematics"
|
|
||||||
],
|
|
||||||
"allowUnsafeCode": true,
|
|
||||||
"versionDefines": [
|
|
||||||
{
|
|
||||||
"name": "com.unity.modules.animation",
|
|
||||||
"expression": "",
|
|
||||||
"define": "COM_UNITY_MODULES_ANIMATION"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "com.unity.modules.physics",
|
|
||||||
"expression": "",
|
|
||||||
"define": "COM_UNITY_MODULES_PHYSICS"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "com.unity.modules.physics2d",
|
|
||||||
"expression": "",
|
|
||||||
"define": "COM_UNITY_MODULES_PHYSICS2D"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
fileFormatVersion: 2
|
|
||||||
guid: 3b8ed52f1b5c64994af4c4e0aa4b6c4b
|
|
||||||
AssemblyDefinitionImporter:
|
|
||||||
externalObjects: {}
|
|
||||||
userData:
|
|
||||||
assetBundleName:
|
|
||||||
assetBundleVariant:
|
|
||||||
@@ -27,7 +27,8 @@ namespace Unity.Netcode.Editor.CodeGen
|
|||||||
|
|
||||||
public override ILPPInterface GetInstance() => this;
|
public override ILPPInterface GetInstance() => this;
|
||||||
|
|
||||||
public override bool WillProcess(ICompiledAssembly compiledAssembly) => compiledAssembly.References.Any(filePath => Path.GetFileNameWithoutExtension(filePath) == CodeGenHelpers.RuntimeAssemblyName);
|
public override bool WillProcess(ICompiledAssembly compiledAssembly) => compiledAssembly.Name == CodeGenHelpers.RuntimeAssemblyName ||
|
||||||
|
compiledAssembly.References.Any(filePath => Path.GetFileNameWithoutExtension(filePath) == CodeGenHelpers.RuntimeAssemblyName);
|
||||||
|
|
||||||
private readonly List<DiagnosticMessage> m_Diagnostics = new List<DiagnosticMessage>();
|
private readonly List<DiagnosticMessage> m_Diagnostics = new List<DiagnosticMessage>();
|
||||||
|
|
||||||
@@ -408,6 +409,7 @@ namespace Unity.Netcode.Editor.CodeGen
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
m_Diagnostics.AddError($"{type}: Managed type in NetworkVariable must implement IEquatable<{type}>");
|
||||||
equalityMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef);
|
equalityMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -720,7 +722,7 @@ namespace Unity.Netcode.Editor.CodeGen
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (networkVariableSerializationTypesTypeDef == null && netcodeTypeDef.Name == nameof(NetworkVariableSerializationTypes))
|
if (networkVariableSerializationTypesTypeDef == null && netcodeTypeDef.Name == nameof(NetworkVariableSerializationTypedInitializers))
|
||||||
{
|
{
|
||||||
networkVariableSerializationTypesTypeDef = netcodeTypeDef;
|
networkVariableSerializationTypesTypeDef = netcodeTypeDef;
|
||||||
continue;
|
continue;
|
||||||
@@ -1006,103 +1008,103 @@ namespace Unity.Netcode.Editor.CodeGen
|
|||||||
|
|
||||||
switch (method.Name)
|
switch (method.Name)
|
||||||
{
|
{
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedByMemcpy):
|
||||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpy_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpy_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpyArray):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedByMemcpyArray):
|
||||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpyArray_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpyArray_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpyList):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedByMemcpyList):
|
||||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpyList_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpyList_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
#endif
|
#endif
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedINetworkSerializable):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedINetworkSerializable):
|
||||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializable_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializable_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedINetworkSerializableArray):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedINetworkSerializableArray):
|
||||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializableArray_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializableArray_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedINetworkSerializableList):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_UnmanagedINetworkSerializableList):
|
||||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializableList_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializableList_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_NativeHashSet):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_NativeHashSet):
|
||||||
m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashSet_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashSet_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_NativeHashMap):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_NativeHashMap):
|
||||||
m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashMap_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeSerializer_NativeHashMap_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
#endif
|
#endif
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_List):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_List):
|
||||||
m_NetworkVariableSerializationTypes_InitializeSerializer_List_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeSerializer_List_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_HashSet):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_HashSet):
|
||||||
m_NetworkVariableSerializationTypes_InitializeSerializer_HashSet_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeSerializer_HashSet_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_Dictionary):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_Dictionary):
|
||||||
m_NetworkVariableSerializationTypes_InitializeSerializer_Dictionary_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeSerializer_Dictionary_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_ManagedINetworkSerializable):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_ManagedINetworkSerializable):
|
||||||
m_NetworkVariableSerializationTypes_InitializeSerializer_ManagedINetworkSerializable_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeSerializer_ManagedINetworkSerializable_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_FixedString):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_FixedString):
|
||||||
m_NetworkVariableSerializationTypes_InitializeSerializer_FixedString_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeSerializer_FixedString_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_FixedStringArray):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_FixedStringArray):
|
||||||
m_NetworkVariableSerializationTypes_InitializeSerializer_FixedStringArray_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeSerializer_FixedStringArray_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_FixedStringList):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeSerializer_FixedStringList):
|
||||||
m_NetworkVariableSerializationTypes_InitializeSerializer_FixedStringList_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeSerializer_FixedStringList_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_ManagedIEquatable):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_ManagedIEquatable):
|
||||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedIEquatable_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedIEquatable_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedIEquatable):
|
||||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatable_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatable_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatableArray):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedIEquatableArray):
|
||||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatableArray_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatableArray_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatableList):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedIEquatableList):
|
||||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatableList_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatableList_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_NativeHashSet):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_NativeHashSet):
|
||||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashSet_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashSet_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_NativeHashMap):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_NativeHashMap):
|
||||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashMap_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_NativeHashMap_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
#endif
|
#endif
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_List):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_List):
|
||||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_List_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_List_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_HashSet):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_HashSet):
|
||||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_HashSet_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_HashSet_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_Dictionary):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_Dictionary):
|
||||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_Dictionary_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_Dictionary_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEquals):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedValueEquals):
|
||||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEquals_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEquals_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEqualsArray):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedValueEqualsArray):
|
||||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEqualsArray_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEqualsArray_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEqualsList):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_UnmanagedValueEqualsList):
|
||||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEqualsList_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEqualsList_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
#endif
|
#endif
|
||||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_ManagedClassEquals):
|
case nameof(NetworkVariableSerializationTypedInitializers.InitializeEqualityChecker_ManagedClassEquals):
|
||||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef = method;
|
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef = method;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ namespace Unity.Netcode.Editor.Configuration
|
|||||||
internal class NetcodeForGameObjectsEditorSettings
|
internal class NetcodeForGameObjectsEditorSettings
|
||||||
{
|
{
|
||||||
internal const string AutoAddNetworkObjectIfNoneExists = "AutoAdd-NetworkObject-When-None-Exist";
|
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 const string InstallMultiplayerToolsTipDismissedPlayerPrefKey = "Netcode_Tip_InstallMPTools_Dismissed";
|
||||||
|
|
||||||
internal static int GetNetcodeInstallMultiplayerToolTips()
|
internal static int GetNetcodeInstallMultiplayerToolTips()
|
||||||
@@ -28,7 +29,7 @@ namespace Unity.Netcode.Editor.Configuration
|
|||||||
{
|
{
|
||||||
return EditorPrefs.GetBool(AutoAddNetworkObjectIfNoneExists);
|
return EditorPrefs.GetBool(AutoAddNetworkObjectIfNoneExists);
|
||||||
}
|
}
|
||||||
|
// Default for this is false
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,5 +37,20 @@ namespace Unity.Netcode.Editor.Configuration
|
|||||||
{
|
{
|
||||||
EditorPrefs.SetBool(AutoAddNetworkObjectIfNoneExists, autoAddSetting);
|
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 NetcodeSettingsLabel NetworkObjectsSectionLabel;
|
||||||
internal static NetcodeSettingsToggle AutoAddNetworkObjectToggle;
|
internal static NetcodeSettingsToggle AutoAddNetworkObjectToggle;
|
||||||
|
internal static NetcodeSettingsToggle CheckForNetworkObjectToggle;
|
||||||
internal static NetcodeSettingsLabel MultiplayerToolsLabel;
|
internal static NetcodeSettingsLabel MultiplayerToolsLabel;
|
||||||
internal static NetcodeSettingsToggle MultiplayerToolTipStatusToggle;
|
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);
|
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)
|
if (MultiplayerToolsLabel == null)
|
||||||
{
|
{
|
||||||
MultiplayerToolsLabel = new NetcodeSettingsLabel("Multiplayer Tools", 20);
|
MultiplayerToolsLabel = new NetcodeSettingsLabel("Multiplayer Tools", 20);
|
||||||
@@ -120,7 +126,9 @@ namespace Unity.Netcode.Editor.Configuration
|
|||||||
CheckForInitialize();
|
CheckForInitialize();
|
||||||
|
|
||||||
var autoAddNetworkObjectSetting = NetcodeForGameObjectsEditorSettings.GetAutoAddNetworkObjectSetting();
|
var autoAddNetworkObjectSetting = NetcodeForGameObjectsEditorSettings.GetAutoAddNetworkObjectSetting();
|
||||||
|
var checkForNetworkObjectSetting = NetcodeForGameObjectsEditorSettings.GetCheckForNetworkObjectSetting();
|
||||||
var multiplayerToolsTipStatus = NetcodeForGameObjectsEditorSettings.GetNetcodeInstallMultiplayerToolTips() == 0;
|
var multiplayerToolsTipStatus = NetcodeForGameObjectsEditorSettings.GetNetcodeInstallMultiplayerToolTips() == 0;
|
||||||
|
|
||||||
var settings = NetcodeForGameObjectsProjectSettings.instance;
|
var settings = NetcodeForGameObjectsProjectSettings.instance;
|
||||||
var generateDefaultPrefabs = settings.GenerateDefaultNetworkPrefabs;
|
var generateDefaultPrefabs = settings.GenerateDefaultNetworkPrefabs;
|
||||||
var networkPrefabsPath = settings.TempNetworkPrefabsPath;
|
var networkPrefabsPath = settings.TempNetworkPrefabsPath;
|
||||||
@@ -134,7 +142,13 @@ namespace Unity.Netcode.Editor.Configuration
|
|||||||
{
|
{
|
||||||
GUILayout.BeginVertical("Box");
|
GUILayout.BeginVertical("Box");
|
||||||
NetworkObjectsSectionLabel.DrawLabel();
|
NetworkObjectsSectionLabel.DrawLabel();
|
||||||
autoAddNetworkObjectSetting = AutoAddNetworkObjectToggle.DrawToggle(autoAddNetworkObjectSetting);
|
|
||||||
|
autoAddNetworkObjectSetting = AutoAddNetworkObjectToggle.DrawToggle(autoAddNetworkObjectSetting, checkForNetworkObjectSetting);
|
||||||
|
checkForNetworkObjectSetting = CheckForNetworkObjectToggle.DrawToggle(checkForNetworkObjectSetting);
|
||||||
|
if (autoAddNetworkObjectSetting && !checkForNetworkObjectSetting)
|
||||||
|
{
|
||||||
|
autoAddNetworkObjectSetting = false;
|
||||||
|
}
|
||||||
GUILayout.EndVertical();
|
GUILayout.EndVertical();
|
||||||
|
|
||||||
GUILayout.BeginVertical("Box");
|
GUILayout.BeginVertical("Box");
|
||||||
@@ -184,6 +198,7 @@ namespace Unity.Netcode.Editor.Configuration
|
|||||||
if (EditorGUI.EndChangeCheck())
|
if (EditorGUI.EndChangeCheck())
|
||||||
{
|
{
|
||||||
NetcodeForGameObjectsEditorSettings.SetAutoAddNetworkObjectSetting(autoAddNetworkObjectSetting);
|
NetcodeForGameObjectsEditorSettings.SetAutoAddNetworkObjectSetting(autoAddNetworkObjectSetting);
|
||||||
|
NetcodeForGameObjectsEditorSettings.SetCheckForNetworkObjectSetting(checkForNetworkObjectSetting);
|
||||||
NetcodeForGameObjectsEditorSettings.SetNetcodeInstallMultiplayerToolTips(multiplayerToolsTipStatus ? 0 : 1);
|
NetcodeForGameObjectsEditorSettings.SetNetcodeInstallMultiplayerToolTips(multiplayerToolsTipStatus ? 0 : 1);
|
||||||
settings.GenerateDefaultNetworkPrefabs = generateDefaultPrefabs;
|
settings.GenerateDefaultNetworkPrefabs = generateDefaultPrefabs;
|
||||||
settings.TempNetworkPrefabsPath = networkPrefabsPath;
|
settings.TempNetworkPrefabsPath = networkPrefabsPath;
|
||||||
@@ -213,10 +228,13 @@ namespace Unity.Netcode.Editor.Configuration
|
|||||||
{
|
{
|
||||||
private GUIContent m_ToggleContent;
|
private GUIContent m_ToggleContent;
|
||||||
|
|
||||||
public bool DrawToggle(bool currentSetting)
|
public bool DrawToggle(bool currentSetting, bool enabled = true)
|
||||||
{
|
{
|
||||||
EditorGUIUtility.labelWidth = m_LabelSize;
|
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)
|
public NetcodeSettingsToggle(string labelText, string toolTip, float layoutOffset)
|
||||||
|
|||||||
@@ -132,7 +132,7 @@ namespace Unity.Netcode.Editor.Configuration
|
|||||||
|
|
||||||
// Process the imported and deleted assets
|
// Process the imported and deleted assets
|
||||||
var markDirty = ProcessImportedAssets(importedAssets);
|
var markDirty = ProcessImportedAssets(importedAssets);
|
||||||
markDirty &= ProcessDeletedAssets(deletedAssets);
|
markDirty |= ProcessDeletedAssets(deletedAssets);
|
||||||
|
|
||||||
if (markDirty)
|
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;
|
expanded = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
serializedObject.ApplyModifiedProperties();
|
|
||||||
EditorGUI.EndChangeCheck();
|
EditorGUI.EndChangeCheck();
|
||||||
|
serializedObject.ApplyModifiedProperties();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -352,6 +351,12 @@ namespace Unity.Netcode.Editor
|
|||||||
return;
|
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)
|
// Now get the root parent transform to the current GameObject (or itself)
|
||||||
var rootTransform = GetRootParentTransform(gameObject.transform);
|
var rootTransform = GetRootParentTransform(gameObject.transform);
|
||||||
if (!rootTransform.TryGetComponent<NetworkManager>(out var networkManager))
|
if (!rootTransform.TryGetComponent<NetworkManager>(out var networkManager))
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ namespace Unity.Netcode.Editor
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
[CustomEditor(typeof(NetworkManager), true)]
|
[CustomEditor(typeof(NetworkManager), true)]
|
||||||
[CanEditMultipleObjects]
|
[CanEditMultipleObjects]
|
||||||
public class NetworkManagerEditor : UnityEditor.Editor
|
public class NetworkManagerEditor : NetcodeEditorBase<NetworkManager>
|
||||||
{
|
{
|
||||||
private static GUIStyle s_CenteredWordWrappedLabelStyle;
|
private static GUIStyle s_CenteredWordWrappedLabelStyle;
|
||||||
private static GUIStyle s_HelpBoxStyle;
|
private static GUIStyle s_HelpBoxStyle;
|
||||||
@@ -30,7 +30,10 @@ namespace Unity.Netcode.Editor
|
|||||||
private SerializedProperty m_ProtocolVersionProperty;
|
private SerializedProperty m_ProtocolVersionProperty;
|
||||||
private SerializedProperty m_NetworkTransportProperty;
|
private SerializedProperty m_NetworkTransportProperty;
|
||||||
private SerializedProperty m_TickRateProperty;
|
private SerializedProperty m_TickRateProperty;
|
||||||
private SerializedProperty m_SessionModeProperty;
|
#if MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||||
|
private SerializedProperty m_AutoSpawnPlayerPrefabClientSide;
|
||||||
|
private SerializedProperty m_NetworkTopologyProperty;
|
||||||
|
#endif
|
||||||
private SerializedProperty m_ClientConnectionBufferTimeoutProperty;
|
private SerializedProperty m_ClientConnectionBufferTimeoutProperty;
|
||||||
private SerializedProperty m_ConnectionApprovalProperty;
|
private SerializedProperty m_ConnectionApprovalProperty;
|
||||||
private SerializedProperty m_EnsureNetworkVariableLengthSafetyProperty;
|
private SerializedProperty m_EnsureNetworkVariableLengthSafetyProperty;
|
||||||
@@ -43,6 +46,9 @@ namespace Unity.Netcode.Editor
|
|||||||
private SerializedProperty m_LoadSceneTimeOutProperty;
|
private SerializedProperty m_LoadSceneTimeOutProperty;
|
||||||
private SerializedProperty m_PrefabsList;
|
private SerializedProperty m_PrefabsList;
|
||||||
|
|
||||||
|
private SerializedProperty m_NetworkProfileMetrics;
|
||||||
|
private SerializedProperty m_NetworkMessageMetrics;
|
||||||
|
|
||||||
private NetworkManager m_NetworkManager;
|
private NetworkManager m_NetworkManager;
|
||||||
private bool m_Initialized;
|
private bool m_Initialized;
|
||||||
|
|
||||||
@@ -97,7 +103,14 @@ namespace Unity.Netcode.Editor
|
|||||||
m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion");
|
m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion");
|
||||||
m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport");
|
m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport");
|
||||||
m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate");
|
m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate");
|
||||||
m_SessionModeProperty = m_NetworkConfigProperty.FindPropertyRelative("SessionMode");
|
#if MULTIPLAYER_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_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout");
|
||||||
m_ConnectionApprovalProperty = m_NetworkConfigProperty.FindPropertyRelative("ConnectionApproval");
|
m_ConnectionApprovalProperty = m_NetworkConfigProperty.FindPropertyRelative("ConnectionApproval");
|
||||||
m_EnsureNetworkVariableLengthSafetyProperty = m_NetworkConfigProperty.FindPropertyRelative("EnsureNetworkVariableLengthSafety");
|
m_EnsureNetworkVariableLengthSafetyProperty = m_NetworkConfigProperty.FindPropertyRelative("EnsureNetworkVariableLengthSafety");
|
||||||
@@ -109,7 +122,10 @@ namespace Unity.Netcode.Editor
|
|||||||
m_SpawnTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("SpawnTimeout");
|
m_SpawnTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("SpawnTimeout");
|
||||||
m_LoadSceneTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("LoadSceneTimeOut");
|
m_LoadSceneTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("LoadSceneTimeOut");
|
||||||
|
|
||||||
|
m_NetworkProfileMetrics = m_NetworkConfigProperty.FindPropertyRelative("NetworkProfileMetrics");
|
||||||
|
#if MULTIPLAYER_TOOLS
|
||||||
|
m_NetworkMessageMetrics = m_NetworkConfigProperty.FindPropertyRelative("NetworkMessageMetrics");
|
||||||
|
#endif
|
||||||
m_RpcHashSizeProperty = m_NetworkConfigProperty.FindPropertyRelative("RpcHashSize");
|
m_RpcHashSizeProperty = m_NetworkConfigProperty.FindPropertyRelative("RpcHashSize");
|
||||||
m_PrefabsList = m_NetworkConfigProperty
|
m_PrefabsList = m_NetworkConfigProperty
|
||||||
.FindPropertyRelative(nameof(NetworkConfig.Prefabs))
|
.FindPropertyRelative(nameof(NetworkConfig.Prefabs))
|
||||||
@@ -130,7 +146,14 @@ namespace Unity.Netcode.Editor
|
|||||||
m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion");
|
m_ProtocolVersionProperty = m_NetworkConfigProperty.FindPropertyRelative("ProtocolVersion");
|
||||||
m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport");
|
m_NetworkTransportProperty = m_NetworkConfigProperty.FindPropertyRelative("NetworkTransport");
|
||||||
m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate");
|
m_TickRateProperty = m_NetworkConfigProperty.FindPropertyRelative("TickRate");
|
||||||
m_SessionModeProperty = m_NetworkConfigProperty.FindPropertyRelative("SessionMode");
|
#if MULTIPLAYER_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_ClientConnectionBufferTimeoutProperty = m_NetworkConfigProperty.FindPropertyRelative("ClientConnectionBufferTimeout");
|
||||||
m_ConnectionApprovalProperty = m_NetworkConfigProperty.FindPropertyRelative("ConnectionApproval");
|
m_ConnectionApprovalProperty = m_NetworkConfigProperty.FindPropertyRelative("ConnectionApproval");
|
||||||
m_EnsureNetworkVariableLengthSafetyProperty = m_NetworkConfigProperty.FindPropertyRelative("EnsureNetworkVariableLengthSafety");
|
m_EnsureNetworkVariableLengthSafetyProperty = m_NetworkConfigProperty.FindPropertyRelative("EnsureNetworkVariableLengthSafety");
|
||||||
@@ -143,30 +166,31 @@ namespace Unity.Netcode.Editor
|
|||||||
m_SpawnTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("SpawnTimeout");
|
m_SpawnTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("SpawnTimeout");
|
||||||
m_LoadSceneTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("LoadSceneTimeOut");
|
m_LoadSceneTimeOutProperty = m_NetworkConfigProperty.FindPropertyRelative("LoadSceneTimeOut");
|
||||||
|
|
||||||
|
m_NetworkProfileMetrics = m_NetworkConfigProperty.FindPropertyRelative("NetworkProfilingMetrics");
|
||||||
|
#if MULTIPLAYER_TOOLS
|
||||||
|
m_NetworkMessageMetrics = m_NetworkConfigProperty.FindPropertyRelative("NetworkMessageMetrics");
|
||||||
|
#endif
|
||||||
|
|
||||||
m_RpcHashSizeProperty = m_NetworkConfigProperty.FindPropertyRelative("RpcHashSize");
|
m_RpcHashSizeProperty = m_NetworkConfigProperty.FindPropertyRelative("RpcHashSize");
|
||||||
m_PrefabsList = m_NetworkConfigProperty
|
m_PrefabsList = m_NetworkConfigProperty
|
||||||
.FindPropertyRelative(nameof(NetworkConfig.Prefabs))
|
.FindPropertyRelative(nameof(NetworkConfig.Prefabs))
|
||||||
.FindPropertyRelative(nameof(NetworkPrefabs.NetworkPrefabsLists));
|
.FindPropertyRelative(nameof(NetworkPrefabs.NetworkPrefabsLists));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc/>
|
private void DisplayNetworkManagerProperties()
|
||||||
public override void OnInspectorGUI()
|
|
||||||
{
|
{
|
||||||
Initialize();
|
|
||||||
CheckNullProperties();
|
|
||||||
|
|
||||||
#if !MULTIPLAYER_TOOLS
|
|
||||||
DrawInstallMultiplayerToolsTip();
|
|
||||||
#endif
|
|
||||||
|
|
||||||
if (!m_NetworkManager.IsServer && !m_NetworkManager.IsClient)
|
if (!m_NetworkManager.IsServer && !m_NetworkManager.IsClient)
|
||||||
{
|
{
|
||||||
serializedObject.Update();
|
serializedObject.Update();
|
||||||
|
|
||||||
EditorGUILayout.PropertyField(m_RunInBackgroundProperty);
|
EditorGUILayout.PropertyField(m_RunInBackgroundProperty);
|
||||||
EditorGUILayout.PropertyField(m_LogLevelProperty);
|
EditorGUILayout.PropertyField(m_LogLevelProperty);
|
||||||
EditorGUILayout.PropertyField(m_SessionModeProperty);
|
|
||||||
EditorGUILayout.Space();
|
EditorGUILayout.Space();
|
||||||
|
|
||||||
EditorGUILayout.LabelField("Network Settings", EditorStyles.boldLabel);
|
EditorGUILayout.LabelField("Network Settings", EditorStyles.boldLabel);
|
||||||
|
#if MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||||
|
EditorGUILayout.PropertyField(m_NetworkTopologyProperty);
|
||||||
|
#endif
|
||||||
EditorGUILayout.PropertyField(m_ProtocolVersionProperty);
|
EditorGUILayout.PropertyField(m_ProtocolVersionProperty);
|
||||||
EditorGUILayout.PropertyField(m_NetworkTransportProperty);
|
EditorGUILayout.PropertyField(m_NetworkTransportProperty);
|
||||||
if (m_NetworkTransportProperty.objectReferenceValue == null)
|
if (m_NetworkTransportProperty.objectReferenceValue == null)
|
||||||
@@ -200,11 +224,25 @@ namespace Unity.Netcode.Editor
|
|||||||
}
|
}
|
||||||
EditorGUILayout.PropertyField(m_RpcHashSizeProperty);
|
EditorGUILayout.PropertyField(m_RpcHashSizeProperty);
|
||||||
|
|
||||||
|
EditorGUILayout.PropertyField(m_NetworkProfileMetrics);
|
||||||
|
#if MULTIPLAYER_TOOLS
|
||||||
|
EditorGUILayout.PropertyField(m_NetworkMessageMetrics);
|
||||||
|
#endif
|
||||||
|
|
||||||
EditorGUILayout.Space();
|
EditorGUILayout.Space();
|
||||||
EditorGUILayout.LabelField("Prefab Settings", EditorStyles.boldLabel);
|
EditorGUILayout.LabelField("Prefab Settings", EditorStyles.boldLabel);
|
||||||
EditorGUILayout.PropertyField(m_ForceSamePrefabsProperty);
|
EditorGUILayout.PropertyField(m_ForceSamePrefabsProperty);
|
||||||
|
#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"));
|
EditorGUILayout.PropertyField(m_PlayerPrefabProperty, new GUIContent("Default Player Prefab"));
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if (m_NetworkManager.NetworkConfig.HasOldPrefabList())
|
if (m_NetworkManager.NetworkConfig.HasOldPrefabList())
|
||||||
{
|
{
|
||||||
EditorGUILayout.HelpBox("Network Prefabs serialized in old format. Migrate to new format to edit the list.", MessageType.Info);
|
EditorGUILayout.HelpBox("Network Prefabs serialized in old format. Migrate to new format to edit the list.", MessageType.Info);
|
||||||
@@ -271,18 +309,23 @@ namespace Unity.Netcode.Editor
|
|||||||
}
|
}
|
||||||
|
|
||||||
serializedObject.ApplyModifiedProperties();
|
serializedObject.ApplyModifiedProperties();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void DisplayCallToActionButtons()
|
||||||
|
{
|
||||||
|
if (!m_NetworkManager.IsServer && !m_NetworkManager.IsClient)
|
||||||
|
{
|
||||||
|
string buttonDisabledReasonSuffix = "";
|
||||||
|
|
||||||
// Start buttons below
|
if (!EditorApplication.isPlaying)
|
||||||
{
|
{
|
||||||
string buttonDisabledReasonSuffix = "";
|
buttonDisabledReasonSuffix = ". This can only be done in play mode";
|
||||||
|
GUI.enabled = false;
|
||||||
if (!EditorApplication.isPlaying)
|
}
|
||||||
{
|
|
||||||
buttonDisabledReasonSuffix = ". This can only be done in play mode";
|
|
||||||
GUI.enabled = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
if (m_NetworkManager.NetworkConfig.NetworkTopology == NetworkTopologyTypes.ClientServer)
|
||||||
|
{
|
||||||
if (GUILayout.Button(new GUIContent("Start Host", "Starts a host instance" + buttonDisabledReasonSuffix)))
|
if (GUILayout.Button(new GUIContent("Start Host", "Starts a host instance" + buttonDisabledReasonSuffix)))
|
||||||
{
|
{
|
||||||
m_NetworkManager.StartHost();
|
m_NetworkManager.StartHost();
|
||||||
@@ -297,12 +340,20 @@ namespace Unity.Netcode.Editor
|
|||||||
{
|
{
|
||||||
m_NetworkManager.StartClient();
|
m_NetworkManager.StartClient();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
if (!EditorApplication.isPlaying)
|
else
|
||||||
|
{
|
||||||
|
if (GUILayout.Button(new GUIContent("Start Client", "Starts a distributed authority client instance" + buttonDisabledReasonSuffix)))
|
||||||
{
|
{
|
||||||
GUI.enabled = true;
|
m_NetworkManager.StartClient();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if (!EditorApplication.isPlaying)
|
||||||
|
{
|
||||||
|
GUI.enabled = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -330,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()
|
private static void DrawInstallMultiplayerToolsTip()
|
||||||
{
|
{
|
||||||
const string getToolsText = "Access additional tools for multiplayer development by installing the Multiplayer Tools package in the Package Manager.";
|
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();
|
s_LastKnownNetworkManagerParents.Clear();
|
||||||
ScenesInBuildActiveSceneCheck();
|
ScenesInBuildActiveSceneCheck();
|
||||||
|
EditorApplication.hierarchyChanged -= EditorApplication_hierarchyChanged;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case PlayModeStateChange.EnteredEditMode:
|
||||||
|
{
|
||||||
|
EditorApplication.hierarchyChanged += EditorApplication_hierarchyChanged;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -110,6 +116,12 @@ namespace Unity.Netcode.Editor
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
private static void EditorApplication_hierarchyChanged()
|
private static void EditorApplication_hierarchyChanged()
|
||||||
{
|
{
|
||||||
|
if (Application.isPlaying)
|
||||||
|
{
|
||||||
|
EditorApplication.hierarchyChanged -= EditorApplication_hierarchyChanged;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
var allNetworkManagers = Resources.FindObjectsOfTypeAll<NetworkManager>();
|
var allNetworkManagers = Resources.FindObjectsOfTypeAll<NetworkManager>();
|
||||||
foreach (var networkManager in allNetworkManagers)
|
foreach (var networkManager in allNetworkManagers)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
#if BYPASS_DEFAULT_ENUM_DRAWER && MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
#endif
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
|
|
||||||
@@ -86,6 +88,14 @@ namespace Unity.Netcode.Editor
|
|||||||
|
|
||||||
while (observerClientIds.MoveNext())
|
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)
|
if (m_NetworkObject.NetworkManager.ConnectedClients[observerClientIds.Current].PlayerObject != null)
|
||||||
{
|
{
|
||||||
EditorGUILayout.ObjectField($"ClientId: {observerClientIds.Current}", m_NetworkObject.NetworkManager.ConnectedClients[observerClientIds.Current].PlayerObject, typeof(GameObject), false);
|
EditorGUILayout.ObjectField($"ClientId: {observerClientIds.Current}", m_NetworkObject.NetworkManager.ConnectedClients[observerClientIds.Current].PlayerObject, typeof(GameObject), false);
|
||||||
@@ -105,6 +115,10 @@ namespace Unity.Netcode.Editor
|
|||||||
EditorGUI.BeginChangeCheck();
|
EditorGUI.BeginChangeCheck();
|
||||||
serializedObject.UpdateIfRequiredOrScript();
|
serializedObject.UpdateIfRequiredOrScript();
|
||||||
DrawPropertiesExcluding(serializedObject, k_HiddenFields);
|
DrawPropertiesExcluding(serializedObject, k_HiddenFields);
|
||||||
|
if (m_NetworkObject.IsOwnershipSessionOwner)
|
||||||
|
{
|
||||||
|
m_NetworkObject.Ownership = NetworkObject.OwnershipStatus.SessionOwner;
|
||||||
|
}
|
||||||
serializedObject.ApplyModifiedProperties();
|
serializedObject.ApplyModifiedProperties();
|
||||||
EditorGUI.EndChangeCheck();
|
EditorGUI.EndChangeCheck();
|
||||||
|
|
||||||
@@ -144,7 +158,9 @@ namespace Unity.Netcode.Editor
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Keeping this here just in case, but it appears that in Unity 6 the visual bugs with
|
||||||
|
// enum flags is resolved
|
||||||
|
#if BYPASS_DEFAULT_ENUM_DRAWER && MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||||
[CustomPropertyDrawer(typeof(NetworkObject.OwnershipStatus))]
|
[CustomPropertyDrawer(typeof(NetworkObject.OwnershipStatus))]
|
||||||
public class NetworkObjectOwnership : PropertyDrawer
|
public class NetworkObjectOwnership : PropertyDrawer
|
||||||
{
|
{
|
||||||
@@ -181,11 +197,12 @@ 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 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
|
// 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.
|
// 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);
|
// var ownership = (NetworkObject.OwnershipStatus)EditorGUI.EnumFlagsField(position, label, (NetworkObject.OwnershipStatus)property.enumValueFlag);
|
||||||
//property.enumValueFlag = (int)ownership;
|
// property.enumValueFlag = (int)ownership;
|
||||||
EditorGUI.EndDisabledGroup();
|
EditorGUI.EndDisabledGroup();
|
||||||
EditorGUI.EndProperty();
|
EditorGUI.EndProperty();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|||||||
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"/>
|
/// The <see cref="CustomEditor"/> for <see cref="NetworkTransform"/>
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[CustomEditor(typeof(NetworkTransform), true)]
|
[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_UseUnreliableDeltas;
|
||||||
private SerializedProperty m_SyncPositionXProperty;
|
private SerializedProperty m_SyncPositionXProperty;
|
||||||
private SerializedProperty m_SyncPositionYProperty;
|
private SerializedProperty m_SyncPositionYProperty;
|
||||||
@@ -30,6 +33,7 @@ namespace Unity.Netcode.Editor
|
|||||||
private SerializedProperty m_UseQuaternionCompression;
|
private SerializedProperty m_UseQuaternionCompression;
|
||||||
private SerializedProperty m_UseHalfFloatPrecision;
|
private SerializedProperty m_UseHalfFloatPrecision;
|
||||||
private SerializedProperty m_SlerpPosition;
|
private SerializedProperty m_SlerpPosition;
|
||||||
|
private SerializedProperty m_AuthorityMode;
|
||||||
|
|
||||||
private static int s_ToggleOffset = 45;
|
private static int s_ToggleOffset = 45;
|
||||||
private static float s_MaxRowWidth = EditorGUIUtility.labelWidth + EditorGUIUtility.fieldWidth + 5;
|
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");
|
private static GUIContent s_ScaleLabel = EditorGUIUtility.TrTextContent("Scale");
|
||||||
|
|
||||||
/// <inheritdoc/>
|
/// <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_UseUnreliableDeltas = serializedObject.FindProperty(nameof(NetworkTransform.UseUnreliableDeltas));
|
||||||
m_SyncPositionXProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionX));
|
m_SyncPositionXProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionX));
|
||||||
m_SyncPositionYProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionY));
|
m_SyncPositionYProperty = serializedObject.FindProperty(nameof(NetworkTransform.SyncPositionY));
|
||||||
@@ -59,12 +65,14 @@ namespace Unity.Netcode.Editor
|
|||||||
m_UseQuaternionCompression = serializedObject.FindProperty(nameof(NetworkTransform.UseQuaternionCompression));
|
m_UseQuaternionCompression = serializedObject.FindProperty(nameof(NetworkTransform.UseQuaternionCompression));
|
||||||
m_UseHalfFloatPrecision = serializedObject.FindProperty(nameof(NetworkTransform.UseHalfFloatPrecision));
|
m_UseHalfFloatPrecision = serializedObject.FindProperty(nameof(NetworkTransform.UseHalfFloatPrecision));
|
||||||
m_SlerpPosition = serializedObject.FindProperty(nameof(NetworkTransform.SlerpPosition));
|
m_SlerpPosition = serializedObject.FindProperty(nameof(NetworkTransform.SlerpPosition));
|
||||||
|
m_AuthorityMode = serializedObject.FindProperty(nameof(NetworkTransform.AuthorityMode));
|
||||||
|
base.OnEnable();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc/>
|
private void DisplayNetworkTransformProperties()
|
||||||
public override void OnInspectorGUI()
|
|
||||||
{
|
{
|
||||||
EditorGUILayout.LabelField("Syncing", EditorStyles.boldLabel);
|
var networkTransform = target as NetworkTransform;
|
||||||
|
EditorGUILayout.LabelField("Axis to Synchronize", EditorStyles.boldLabel);
|
||||||
{
|
{
|
||||||
GUILayout.BeginHorizontal();
|
GUILayout.BeginHorizontal();
|
||||||
|
|
||||||
@@ -126,6 +134,11 @@ namespace Unity.Netcode.Editor
|
|||||||
GUILayout.EndHorizontal();
|
GUILayout.EndHorizontal();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
EditorGUILayout.Space();
|
||||||
|
EditorGUILayout.LabelField("Authority", EditorStyles.boldLabel);
|
||||||
|
{
|
||||||
|
EditorGUILayout.PropertyField(m_AuthorityMode);
|
||||||
|
}
|
||||||
EditorGUILayout.Space();
|
EditorGUILayout.Space();
|
||||||
EditorGUILayout.LabelField("Thresholds", EditorStyles.boldLabel);
|
EditorGUILayout.LabelField("Thresholds", EditorStyles.boldLabel);
|
||||||
EditorGUILayout.PropertyField(m_PositionThresholdProperty);
|
EditorGUILayout.PropertyField(m_PositionThresholdProperty);
|
||||||
@@ -133,11 +146,20 @@ namespace Unity.Netcode.Editor
|
|||||||
EditorGUILayout.PropertyField(m_ScaleThresholdProperty);
|
EditorGUILayout.PropertyField(m_ScaleThresholdProperty);
|
||||||
EditorGUILayout.Space();
|
EditorGUILayout.Space();
|
||||||
EditorGUILayout.LabelField("Delivery", EditorStyles.boldLabel);
|
EditorGUILayout.LabelField("Delivery", EditorStyles.boldLabel);
|
||||||
|
EditorGUILayout.PropertyField(m_TickSyncChildren);
|
||||||
EditorGUILayout.PropertyField(m_UseUnreliableDeltas);
|
EditorGUILayout.PropertyField(m_UseUnreliableDeltas);
|
||||||
EditorGUILayout.Space();
|
EditorGUILayout.Space();
|
||||||
EditorGUILayout.LabelField("Configurations", EditorStyles.boldLabel);
|
EditorGUILayout.LabelField("Configurations", EditorStyles.boldLabel);
|
||||||
|
EditorGUILayout.PropertyField(m_SwitchTransformSpaceWhenParented);
|
||||||
|
if (m_SwitchTransformSpaceWhenParented.boolValue)
|
||||||
|
{
|
||||||
|
m_TickSyncChildren.boolValue = true;
|
||||||
|
}
|
||||||
EditorGUILayout.PropertyField(m_InLocalSpaceProperty);
|
EditorGUILayout.PropertyField(m_InLocalSpaceProperty);
|
||||||
EditorGUILayout.PropertyField(m_InterpolateProperty);
|
if (!networkTransform.HideInterpolateValue)
|
||||||
|
{
|
||||||
|
EditorGUILayout.PropertyField(m_InterpolateProperty);
|
||||||
|
}
|
||||||
EditorGUILayout.PropertyField(m_SlerpPosition);
|
EditorGUILayout.PropertyField(m_SlerpPosition);
|
||||||
EditorGUILayout.PropertyField(m_UseQuaternionSynchronization);
|
EditorGUILayout.PropertyField(m_UseQuaternionSynchronization);
|
||||||
if (m_UseQuaternionSynchronization.boolValue)
|
if (m_UseQuaternionSynchronization.boolValue)
|
||||||
@@ -152,8 +174,7 @@ namespace Unity.Netcode.Editor
|
|||||||
|
|
||||||
#if COM_UNITY_MODULES_PHYSICS
|
#if COM_UNITY_MODULES_PHYSICS
|
||||||
// if rigidbody is present but network rigidbody is not present
|
// if rigidbody is present but network rigidbody is not present
|
||||||
var go = ((NetworkTransform)target).gameObject;
|
if (networkTransform.TryGetComponent<Rigidbody>(out _) && networkTransform.TryGetComponent<NetworkRigidbody>(out _) == false)
|
||||||
if (go.TryGetComponent<Rigidbody>(out _) && go.TryGetComponent<NetworkRigidbody>(out _) == false)
|
|
||||||
{
|
{
|
||||||
EditorGUILayout.HelpBox("This GameObject contains a Rigidbody but no NetworkRigidbody.\n" +
|
EditorGUILayout.HelpBox("This GameObject contains a Rigidbody but no NetworkRigidbody.\n" +
|
||||||
"Add a NetworkRigidbody component to improve Rigidbody synchronization.", MessageType.Warning);
|
"Add a NetworkRigidbody component to improve Rigidbody synchronization.", MessageType.Warning);
|
||||||
@@ -161,14 +182,23 @@ namespace Unity.Netcode.Editor
|
|||||||
#endif // COM_UNITY_MODULES_PHYSICS
|
#endif // COM_UNITY_MODULES_PHYSICS
|
||||||
|
|
||||||
#if COM_UNITY_MODULES_PHYSICS2D
|
#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" +
|
EditorGUILayout.HelpBox("This GameObject contains a Rigidbody2D but no NetworkRigidbody2D.\n" +
|
||||||
"Add a NetworkRigidbody2D component to improve Rigidbody2D synchronization.", MessageType.Warning);
|
"Add a NetworkRigidbody2D component to improve Rigidbody2D synchronization.", MessageType.Warning);
|
||||||
}
|
}
|
||||||
#endif // COM_UNITY_MODULES_PHYSICS2D
|
#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": "",
|
"expression": "",
|
||||||
"define": "COM_UNITY_MODULES_ANIMATION"
|
"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",
|
"name": "com.unity.services.relay",
|
||||||
"expression": "1.0",
|
"expression": "1.0",
|
||||||
@@ -53,6 +43,11 @@
|
|||||||
"name": "com.unity.transport",
|
"name": "com.unity.transport",
|
||||||
"expression": "2.0",
|
"expression": "2.0",
|
||||||
"define": "UTP_TRANSPORT_2_0_ABOVE"
|
"define": "UTP_TRANSPORT_2_0_ABOVE"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "com.unity.services.multiplayer",
|
||||||
|
"expression": "0.2.0",
|
||||||
|
"define": "MULTIPLAYER_SERVICES_SDK_INSTALLED"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"noEngineReferences": false
|
"noEngineReferences": false
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
Unity Companion License (UCL License)
|
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).
|
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.
|
Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. Please review the license for details on these and other terms and conditions.
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
fileFormatVersion: 2
|
fileFormatVersion: 2
|
||||||
guid: 8b267eb841a574dc083ac248a95d4443
|
guid: 2e42215d00468b549bbc69ebf8a74a1e
|
||||||
folderAsset: yes
|
folderAsset: yes
|
||||||
DefaultImporter:
|
DefaultImporter:
|
||||||
externalObjects: {}
|
externalObjects: {}
|
||||||
@@ -8,7 +8,7 @@ namespace Unity.Netcode.Components
|
|||||||
/// Half float precision <see cref="Vector3"/>.
|
/// Half float precision <see cref="Vector3"/>.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <remarks>
|
/// <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
|
/// 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.
|
/// a half float type.
|
||||||
/// </remarks>
|
/// </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.
|
/// Half Precision <see cref="Vector4"/> that can also be used to convert a <see cref="Quaternion"/> to half precision.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <remarks>
|
/// <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
|
/// 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.
|
/// a half float type.
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
@@ -5,14 +5,14 @@ using UnityEngine;
|
|||||||
namespace Unity.Netcode
|
namespace Unity.Netcode
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <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
|
/// Partially solves for message loss. Unclamped lerping helps hide this, but not completely
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="T">The type of interpolated value</typeparam>
|
/// <typeparam name="T">The type of interpolated value</typeparam>
|
||||||
public abstract class BufferedLinearInterpolator<T> where T : struct
|
public abstract class BufferedLinearInterpolator<T> where T : struct
|
||||||
{
|
{
|
||||||
internal float MaxInterpolationBound = 3.0f;
|
internal float MaxInterpolationBound = 3.0f;
|
||||||
private struct BufferedItem
|
protected internal struct BufferedItem
|
||||||
{
|
{
|
||||||
public T Item;
|
public T Item;
|
||||||
public double TimeSent;
|
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 const double k_SmallValue = 9.999999439624929E-11; // copied from Vector3's equal operator
|
||||||
|
|
||||||
private T m_InterpStartValue;
|
protected internal T m_InterpStartValue;
|
||||||
private T m_CurrentInterpValue;
|
protected internal T m_CurrentInterpValue;
|
||||||
private T m_InterpEndValue;
|
protected internal T m_InterpEndValue;
|
||||||
|
|
||||||
private double m_EndTimeConsumed;
|
private double m_EndTimeConsumed;
|
||||||
private double m_StartTimeConsumed;
|
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
|
// Buffer consumption scenarios
|
||||||
// Perfect case consumption
|
// Perfect case consumption
|
||||||
@@ -73,6 +75,21 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
private bool InvalidState => m_Buffer.Count == 0 && m_LifetimeConsumedCount == 0;
|
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>
|
/// <summary>
|
||||||
/// Resets interpolator to initial state
|
/// Resets interpolator to initial state
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -195,7 +212,9 @@ namespace Unity.Netcode
|
|||||||
double range = m_EndTimeConsumed - m_StartTimeConsumed;
|
double range = m_EndTimeConsumed - m_StartTimeConsumed;
|
||||||
if (range > k_SmallValue)
|
if (range > k_SmallValue)
|
||||||
{
|
{
|
||||||
t = (float)((renderTime - m_StartTimeConsumed) / range);
|
var rangeFactor = 1.0f / (float)range;
|
||||||
|
|
||||||
|
t = ((float)renderTime - (float)m_StartTimeConsumed) * rangeFactor;
|
||||||
|
|
||||||
if (t < 0.0f)
|
if (t < 0.0f)
|
||||||
{
|
{
|
||||||
@@ -349,6 +368,35 @@ namespace Unity.Netcode
|
|||||||
return Quaternion.Lerp(start, end, time);
|
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>
|
/// <summary>
|
||||||
@@ -386,5 +434,34 @@ namespace Unity.Netcode
|
|||||||
return Vector3.Lerp(start, end, time);
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -186,7 +186,6 @@ namespace Unity.Netcode.Components
|
|||||||
/// NetworkAnimator enables remote synchronization of <see cref="UnityEngine.Animator"/> state for on network objects.
|
/// NetworkAnimator enables remote synchronization of <see cref="UnityEngine.Animator"/> state for on network objects.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[AddComponentMenu("Netcode/Network Animator")]
|
[AddComponentMenu("Netcode/Network Animator")]
|
||||||
[RequireComponent(typeof(Animator))]
|
|
||||||
public class NetworkAnimator : NetworkBehaviour, ISerializationCallbackReceiver
|
public class NetworkAnimator : NetworkBehaviour, ISerializationCallbackReceiver
|
||||||
{
|
{
|
||||||
[Serializable]
|
[Serializable]
|
||||||
@@ -231,6 +230,7 @@ namespace Unity.Netcode.Components
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#if UNITY_EDITOR
|
#if UNITY_EDITOR
|
||||||
private void ParseStateMachineStates(int layerIndex, ref AnimatorController animatorController, ref AnimatorStateMachine stateMachine)
|
private void ParseStateMachineStates(int layerIndex, ref AnimatorController animatorController, ref AnimatorStateMachine stateMachine)
|
||||||
{
|
{
|
||||||
@@ -264,7 +264,6 @@ namespace Unity.Netcode.Components
|
|||||||
{
|
{
|
||||||
case AnimatorControllerParameterType.Trigger:
|
case AnimatorControllerParameterType.Trigger:
|
||||||
{
|
{
|
||||||
|
|
||||||
if (transition.destinationStateMachine != null)
|
if (transition.destinationStateMachine != null)
|
||||||
{
|
{
|
||||||
var destinationStateMachine = transition.destinationStateMachine;
|
var destinationStateMachine = transition.destinationStateMachine;
|
||||||
@@ -298,18 +297,12 @@ namespace Unity.Netcode.Components
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Creates the TransitionStateInfoList table
|
/// Creates the TransitionStateInfoList table
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private void BuildTransitionStateInfoList()
|
private void BuildTransitionStateInfoList()
|
||||||
{
|
{
|
||||||
#if UNITY_EDITOR
|
|
||||||
if (UnityEditor.EditorApplication.isUpdating || UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (m_Animator == null)
|
if (m_Animator == null)
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
@@ -327,9 +320,18 @@ namespace Unity.Netcode.Components
|
|||||||
var stateMachine = animatorController.layers[x].stateMachine;
|
var stateMachine = animatorController.layers[x].stateMachine;
|
||||||
ParseStateMachineStates(x, ref animatorController, ref 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()
|
public void OnAfterDeserialize()
|
||||||
{
|
{
|
||||||
BuildDestinationToTransitionInfoTable();
|
BuildDestinationToTransitionInfoTable();
|
||||||
@@ -337,7 +339,7 @@ namespace Unity.Netcode.Components
|
|||||||
|
|
||||||
public void OnBeforeSerialize()
|
public void OnBeforeSerialize()
|
||||||
{
|
{
|
||||||
BuildTransitionStateInfoList();
|
// Do nothing when serializing (handled during OnValidate)
|
||||||
}
|
}
|
||||||
|
|
||||||
internal struct AnimationState : INetworkSerializable
|
internal struct AnimationState : INetworkSerializable
|
||||||
@@ -420,8 +422,8 @@ namespace Unity.Netcode.Components
|
|||||||
internal bool HasBeenProcessed;
|
internal bool HasBeenProcessed;
|
||||||
|
|
||||||
// This is preallocated/populated in OnNetworkSpawn for all instances in the event ownership or
|
// This is preallocated/populated in OnNetworkSpawn for all instances in the event ownership or
|
||||||
// authority changes. When serializing, IsDirtyCount determines how many AnimationState entries
|
// authority changes. When serializing, IsDirtyCount determines how many AnimationState entries
|
||||||
// should be serialized from the list. When deserializing the list is created and populated with
|
// should be serialized from the list. When deserializing the list is created and populated with
|
||||||
// only the number of AnimationStates received which is dictated by the deserialized IsDirtyCount.
|
// only the number of AnimationStates received which is dictated by the deserialized IsDirtyCount.
|
||||||
internal List<AnimationState> AnimationStates;
|
internal List<AnimationState> AnimationStates;
|
||||||
|
|
||||||
@@ -497,17 +499,17 @@ namespace Unity.Netcode.Components
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// When using a distributed authority network topology, this will default to
|
||||||
|
/// owner authoritative.
|
||||||
|
/// </remarks>
|
||||||
protected virtual bool OnIsServerAuthoritative()
|
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_TransitionHash;
|
||||||
private int[] m_AnimationHash;
|
private int[] m_AnimationHash;
|
||||||
private float[] m_LayerWeights;
|
private float[] m_LayerWeights;
|
||||||
@@ -531,7 +533,7 @@ namespace Unity.Netcode.Components
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 128 bytes per Animator
|
// 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;
|
private NativeArray<AnimatorParamCache> m_CachedAnimatorParameters;
|
||||||
|
|
||||||
@@ -581,8 +583,16 @@ namespace Unity.Netcode.Components
|
|||||||
base.OnDestroy();
|
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;
|
int layers = m_Animator.layerCount;
|
||||||
// Initializing the below arrays for everyone handles an issue
|
// Initializing the below arrays for everyone handles an issue
|
||||||
// when running in owner authoritative mode and the owner changes.
|
// 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
|
// Build our reference parameter values to detect when they change
|
||||||
var parameters = m_Animator.parameters;
|
var parameters = m_Animator.parameters;
|
||||||
m_CachedAnimatorParameters = new NativeArray<AnimatorParamCache>(parameters.Length, Allocator.Persistent);
|
m_CachedAnimatorParameters = new NativeArray<AnimatorParamCache>(parameters.Length, Allocator.Persistent);
|
||||||
@@ -652,7 +665,37 @@ namespace Unity.Netcode.Components
|
|||||||
}
|
}
|
||||||
|
|
||||||
m_CachedAnimatorParameters[i] = cacheParam;
|
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>
|
/// <summary>
|
||||||
@@ -694,7 +737,7 @@ namespace Unity.Netcode.Components
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
private void WriteSynchronizationData<T>(ref BufferSerializer<T> serializer) where T : IReaderWriter
|
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
|
// The only time this could be set to true
|
||||||
animationState.StateHash = stateHash; // When a transition, this is the originating/starting state
|
animationState.Transition = isInTransition;
|
||||||
|
// When a transition, this is the originating/starting state
|
||||||
|
animationState.StateHash = stateHash;
|
||||||
animationState.NormalizedTime = normalizedTime;
|
animationState.NormalizedTime = normalizedTime;
|
||||||
animationState.Layer = layer;
|
animationState.Layer = layer;
|
||||||
animationState.Weight = m_LayerWeights[layer];
|
animationState.Weight = m_LayerWeights[layer];
|
||||||
@@ -844,7 +889,8 @@ namespace Unity.Netcode.Components
|
|||||||
{
|
{
|
||||||
m_TransitionHash[layer] = nt.fullPathHash;
|
m_TransitionHash[layer] = nt.fullPathHash;
|
||||||
m_AnimationHash[layer] = 0;
|
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.CrossFade = true;
|
||||||
animState.Transition = true;
|
animState.Transition = true;
|
||||||
animState.Duration = tt.duration;
|
animState.Duration = tt.duration;
|
||||||
@@ -852,15 +898,25 @@ namespace Unity.Netcode.Components
|
|||||||
stateChangeDetected = true;
|
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})");
|
//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
|
// first time in this transition for this layer
|
||||||
m_TransitionHash[layer] = tt.fullPathHash;
|
m_TransitionHash[layer] = tt.fullPathHash;
|
||||||
m_AnimationHash[layer] = 0;
|
m_AnimationHash[layer] = 0;
|
||||||
animState.StateHash = tt.fullPathHash; // Transitioning from state
|
// Transitioning from state
|
||||||
|
animState.StateHash = tt.fullPathHash;
|
||||||
animState.CrossFade = false;
|
animState.CrossFade = false;
|
||||||
animState.Transition = true;
|
animState.Transition = true;
|
||||||
animState.NormalizedTime = tt.normalizedTime;
|
animState.NormalizedTime = tt.normalizedTime;
|
||||||
|
if (m_DestinationStateToTransitioninfo.ContainsKey(layer) && m_DestinationStateToTransitioninfo[layer].ContainsKey(nt.fullPathHash))
|
||||||
|
{
|
||||||
|
animState.DestinationStateHash = nt.fullPathHash;
|
||||||
|
}
|
||||||
stateChangeDetected = true;
|
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})");
|
//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
|
// Just notify all remote clients and not the local server
|
||||||
m_ClientSendList.Clear();
|
m_ClientSendList.Clear();
|
||||||
m_ClientSendList.AddRange(NetworkManager.ConnectedClientsIds);
|
foreach (var clientId in NetworkManager.ConnectedClientsIds)
|
||||||
m_ClientSendList.Remove(NetworkManager.LocalClientId);
|
{
|
||||||
|
if (clientId == NetworkManager.LocalClientId || !NetworkObject.Observers.Contains(clientId))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
m_ClientSendList.Add(clientId);
|
||||||
|
}
|
||||||
m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList;
|
m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList;
|
||||||
SendAnimStateClientRpc(m_AnimationMessage, m_ClientRpcParams);
|
SendAnimStateClientRpc(m_AnimationMessage, m_ClientRpcParams);
|
||||||
}
|
}
|
||||||
@@ -1063,7 +1125,7 @@ namespace Unity.Netcode.Components
|
|||||||
{
|
{
|
||||||
writer.Seek(0);
|
writer.Seek(0);
|
||||||
writer.Truncate();
|
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);
|
BytePacker.WriteValuePacked(writer, (uint)m_ParametersToUpdate.Count);
|
||||||
foreach (var parameterIndex in m_ParametersToUpdate)
|
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})!");
|
NetworkLog.LogError($"[DestinationState To Transition Info] Layer ({animationState.Layer}) sub-table does not contain destination state ({animationState.DestinationStateHash})!");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (NetworkManager.LogLevel == LogLevel.Developer)
|
// 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!");
|
//{
|
||||||
}
|
// NetworkLog.LogError($"[DestinationState To Transition Info] Layer ({animationState.Layer}) does not exist!");
|
||||||
|
//}
|
||||||
}
|
}
|
||||||
else if (animationState.Transition && animationState.CrossFade)
|
else if (animationState.Transition && animationState.CrossFade)
|
||||||
{
|
{
|
||||||
@@ -1252,9 +1315,15 @@ namespace Unity.Netcode.Components
|
|||||||
if (NetworkManager.ConnectedClientsIds.Count > (IsHost ? 2 : 1))
|
if (NetworkManager.ConnectedClientsIds.Count > (IsHost ? 2 : 1))
|
||||||
{
|
{
|
||||||
m_ClientSendList.Clear();
|
m_ClientSendList.Clear();
|
||||||
m_ClientSendList.AddRange(NetworkManager.ConnectedClientsIds);
|
foreach (var clientId in NetworkManager.ConnectedClientsIds)
|
||||||
m_ClientSendList.Remove(serverRpcParams.Receive.SenderClientId);
|
{
|
||||||
m_ClientSendList.Remove(NetworkManager.ServerClientId);
|
if (clientId == serverRpcParams.Receive.SenderClientId || clientId == NetworkManager.ServerClientId || !NetworkObject.Observers.Contains(clientId))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
m_ClientSendList.Add(clientId);
|
||||||
|
}
|
||||||
|
|
||||||
m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList;
|
m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList;
|
||||||
m_NetworkAnimatorStateChangeHandler.SendParameterUpdate(parametersUpdate, m_ClientRpcParams);
|
m_NetworkAnimatorStateChangeHandler.SendParameterUpdate(parametersUpdate, m_ClientRpcParams);
|
||||||
}
|
}
|
||||||
@@ -1309,9 +1378,14 @@ namespace Unity.Netcode.Components
|
|||||||
if (NetworkManager.ConnectedClientsIds.Count > (IsHost ? 2 : 1))
|
if (NetworkManager.ConnectedClientsIds.Count > (IsHost ? 2 : 1))
|
||||||
{
|
{
|
||||||
m_ClientSendList.Clear();
|
m_ClientSendList.Clear();
|
||||||
m_ClientSendList.AddRange(NetworkManager.ConnectedClientsIds);
|
foreach (var clientId in NetworkManager.ConnectedClientsIds)
|
||||||
m_ClientSendList.Remove(serverRpcParams.Receive.SenderClientId);
|
{
|
||||||
m_ClientSendList.Remove(NetworkManager.ServerClientId);
|
if (clientId == serverRpcParams.Receive.SenderClientId || clientId == NetworkManager.ServerClientId || !NetworkObject.Observers.Contains(clientId))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
m_ClientSendList.Add(clientId);
|
||||||
|
}
|
||||||
m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList;
|
m_ClientRpcParams.Send.TargetClientIds = m_ClientSendList;
|
||||||
m_NetworkAnimatorStateChangeHandler.SendAnimationUpdate(animationMessage, m_ClientRpcParams);
|
m_NetworkAnimatorStateChangeHandler.SendAnimationUpdate(animationMessage, m_ClientRpcParams);
|
||||||
}
|
}
|
||||||
@@ -1378,9 +1452,14 @@ namespace Unity.Netcode.Components
|
|||||||
InternalSetTrigger(animationTriggerMessage.Hash, animationTriggerMessage.IsTriggerSet);
|
InternalSetTrigger(animationTriggerMessage.Hash, animationTriggerMessage.IsTriggerSet);
|
||||||
|
|
||||||
m_ClientSendList.Clear();
|
m_ClientSendList.Clear();
|
||||||
m_ClientSendList.AddRange(NetworkManager.ConnectedClientsIds);
|
foreach (var clientId in NetworkManager.ConnectedClientsIds)
|
||||||
m_ClientSendList.Remove(NetworkManager.ServerClientId);
|
{
|
||||||
|
if (clientId == NetworkManager.ServerClientId || !NetworkObject.Observers.Contains(clientId))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
m_ClientSendList.Add(clientId);
|
||||||
|
}
|
||||||
if (IsServerAuthoritative())
|
if (IsServerAuthoritative())
|
||||||
{
|
{
|
||||||
m_NetworkAnimatorStateChangeHandler.QueueTriggerUpdateToClient(animationTriggerMessage, m_ClientRpcParams);
|
m_NetworkAnimatorStateChangeHandler.QueueTriggerUpdateToClient(animationTriggerMessage, m_ClientRpcParams);
|
||||||
@@ -1402,7 +1481,7 @@ namespace Unity.Netcode.Components
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Distributed Authority: Internally-called RPC client receiving function to update a trigger when the server wants to forward
|
/// 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>
|
/// </summary>
|
||||||
/// <param name="animationTriggerMessage">the payload containing the trigger data to apply</param>
|
/// <param name="animationTriggerMessage">the payload containing the trigger data to apply</param>
|
||||||
[Rpc(SendTo.NotAuthority)]
|
[Rpc(SendTo.NotAuthority)]
|
||||||
@@ -1413,7 +1492,7 @@ namespace Unity.Netcode.Components
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Client Server: Internally-called RPC client receiving function to update a trigger when the server wants to forward
|
/// 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>
|
/// </summary>
|
||||||
/// <param name="animationTriggerMessage">the payload containing the trigger data to apply</param>
|
/// <param name="animationTriggerMessage">the payload containing the trigger data to apply</param>
|
||||||
/// <param name="clientRpcParams">unused</param>
|
/// <param name="clientRpcParams">unused</param>
|
||||||
@@ -1479,7 +1558,7 @@ namespace Unity.Netcode.Components
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Resets the trigger for the associated animation. See <see cref="SetTrigger(string)">SetTrigger</see> for more on how triggers are special
|
/// Resets the trigger for the associated animation. See <see cref="SetTrigger(string)">SetTrigger</see> for more on how triggers are special
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="triggerName">The string name of the trigger to reset</param>
|
/// <param name="triggerName">The string name of the trigger to reset</param>
|
||||||
public void ResetTrigger(string triggerName)
|
public void ResetTrigger(string triggerName)
|
||||||
@@ -1495,4 +1574,5 @@ namespace Unity.Netcode.Components
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif // COM_UNITY_MODULES_ANIMATION
|
// COM_UNITY_MODULES_ANIMATION
|
||||||
|
#endif
|
||||||
@@ -32,9 +32,13 @@ namespace Unity.Netcode.Components
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
|
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
|
||||||
{
|
{
|
||||||
HalfVector3.NetworkSerialize(serializer);
|
if (!SynchronizeBase)
|
||||||
if (SynchronizeBase)
|
|
||||||
{
|
{
|
||||||
|
HalfVector3.NetworkSerialize(serializer);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
serializer.SerializeValue(ref DeltaPosition);
|
||||||
serializer.SerializeValue(ref CurrentBasePosition);
|
serializer.SerializeValue(ref CurrentBasePosition);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -14,7 +14,7 @@ namespace Unity.Netcode
|
|||||||
/// M = 1.0f (which M * M would still yield 1.0f)
|
/// M = 1.0f (which M * M would still yield 1.0f)
|
||||||
/// w*w = M*M - (x*x + y*y + z*z) or Mathf.Sqrt(1.0f - (x*x + y*y + z*z))
|
/// w*w = M*M - (x*x + y*y + z*z) or Mathf.Sqrt(1.0f - (x*x + y*y + z*z))
|
||||||
/// w = Math.Sqrt(1.0f - (x*x + y*y + z*z))
|
/// w = Math.Sqrt(1.0f - (x*x + y*y + z*z))
|
||||||
/// Using the largest the number avoids potential loss of precision in the smallest three values.
|
/// Using the largest number avoids potential loss of precision in the smallest three values.
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
public static class QuaternionCompressor
|
public static class QuaternionCompressor
|
||||||
{
|
{
|
||||||
386
Runtime/Components/RigidbodyContactEventManager.cs
Normal file
386
Runtime/Components/RigidbodyContactEventManager.cs
Normal file
@@ -0,0 +1,386 @@
|
|||||||
|
#if COM_UNITY_MODULES_PHYSICS
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Unity.Collections;
|
||||||
|
using Unity.Jobs;
|
||||||
|
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
|
||||||
|
{
|
||||||
|
public static RigidbodyContactEventManager Instance { get; private set; }
|
||||||
|
|
||||||
|
private struct JobResultStruct
|
||||||
|
{
|
||||||
|
public bool HasCollisionStay;
|
||||||
|
public int ThisInstanceID;
|
||||||
|
public int OtherInstanceID;
|
||||||
|
public Vector3 AverageNormal;
|
||||||
|
public Vector3 AverageCollisionStayNormal;
|
||||||
|
public Vector3 ContactPoint;
|
||||||
|
}
|
||||||
|
|
||||||
|
private NativeArray<JobResultStruct> m_ResultsArray;
|
||||||
|
private int m_Count = 0;
|
||||||
|
private JobHandle m_JobHandle;
|
||||||
|
|
||||||
|
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()
|
||||||
|
{
|
||||||
|
m_ResultsArray = new NativeArray<JobResultStruct>(16, Allocator.Persistent);
|
||||||
|
Physics.ContactEvent += Physics_ContactEvent;
|
||||||
|
if (Instance != null)
|
||||||
|
{
|
||||||
|
NetworkLog.LogError($"[Invalid][Multiple Instances] Found more than one instance of {nameof(RigidbodyContactEventManager)}: {name} and {Instance.name}");
|
||||||
|
NetworkLog.LogError($"[Disable][Additional Instance] Disabling {name} instance!");
|
||||||
|
gameObject.SetActive(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
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();
|
||||||
|
var instanceId = rigidbody.GetInstanceID();
|
||||||
|
if (register)
|
||||||
|
{
|
||||||
|
if (!m_RigidbodyMapping.ContainsKey(instanceId))
|
||||||
|
{
|
||||||
|
m_RigidbodyMapping.Add(instanceId, rigidbody);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!m_HandlerMapping.ContainsKey(instanceId))
|
||||||
|
{
|
||||||
|
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
|
||||||
|
{
|
||||||
|
m_RigidbodyMapping.Remove(instanceId);
|
||||||
|
m_HandlerMapping.Remove(instanceId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnDisable()
|
||||||
|
{
|
||||||
|
m_JobHandle.Complete();
|
||||||
|
m_ResultsArray.Dispose();
|
||||||
|
|
||||||
|
Physics.ContactEvent -= Physics_ContactEvent;
|
||||||
|
|
||||||
|
m_RigidbodyMapping.Clear();
|
||||||
|
Instance = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool m_HasCollisions;
|
||||||
|
private int m_CurrentCount = 0;
|
||||||
|
|
||||||
|
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 contactHandler0 = (IContactEventHandler)null;
|
||||||
|
var contactHandler1 = (IContactEventHandler)null;
|
||||||
|
var preferredContactHandler = (IContactEventHandler)null;
|
||||||
|
var preferredContactHandlerNonRigidbody = false;
|
||||||
|
var preferredRigidbody = (Rigidbody)null;
|
||||||
|
var otherContactHandler = (IContactEventHandler)null;
|
||||||
|
var otherRigidbody = (Rigidbody)null;
|
||||||
|
|
||||||
|
var otherContactHandlerNonRigidbody = false;
|
||||||
|
|
||||||
|
if (m_RigidbodyMapping.ContainsKey(thisInstanceID))
|
||||||
|
{
|
||||||
|
contactHandler0 = m_HandlerMapping[thisInstanceID];
|
||||||
|
contactEventHandlerInfo0 = m_HandlerInfo[thisInstanceID];
|
||||||
|
if (contactEventHandlerInfo0.HasContactEventPriority)
|
||||||
|
{
|
||||||
|
preferredContactHandler = contactHandler0;
|
||||||
|
preferredContactHandlerNonRigidbody = contactEventHandlerInfo0.ProvideNonRigidBodyContactEvents;
|
||||||
|
preferredRigidbody = m_RigidbodyMapping[thisInstanceID];
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
otherContactHandler = contactHandler0;
|
||||||
|
otherContactHandlerNonRigidbody = contactEventHandlerInfo0.ProvideNonRigidBodyContactEvents;
|
||||||
|
otherRigidbody = m_RigidbodyMapping[thisInstanceID];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (m_RigidbodyMapping.ContainsKey(otherInstanceID))
|
||||||
|
{
|
||||||
|
contactHandler1 = m_HandlerMapping[otherInstanceID];
|
||||||
|
contactEventHandlerInfo1 = m_HandlerInfo[otherInstanceID];
|
||||||
|
if (contactEventHandlerInfo1.HasContactEventPriority && preferredContactHandler == null)
|
||||||
|
{
|
||||||
|
preferredContactHandler = contactHandler1;
|
||||||
|
preferredContactHandlerNonRigidbody = contactEventHandlerInfo1.ProvideNonRigidBodyContactEvents;
|
||||||
|
preferredRigidbody = m_RigidbodyMapping[otherInstanceID];
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
otherContactHandler = contactHandler1;
|
||||||
|
otherContactHandlerNonRigidbody = contactEventHandlerInfo1.ProvideNonRigidBodyContactEvents;
|
||||||
|
otherRigidbody = m_RigidbodyMapping[otherInstanceID];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (preferredContactHandler == null && otherContactHandler != null)
|
||||||
|
{
|
||||||
|
preferredContactHandler = otherContactHandler;
|
||||||
|
preferredContactHandlerNonRigidbody = otherContactHandlerNonRigidbody;
|
||||||
|
preferredRigidbody = otherRigidbody;
|
||||||
|
otherContactHandler = null;
|
||||||
|
otherContactHandlerNonRigidbody = false;
|
||||||
|
otherRigidbody = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (preferredContactHandler == null || (preferredContactHandler != null && otherContactHandler == null && !preferredContactHandlerNonRigidbody))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (m_ResultsArray[i].HasCollisionStay)
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void FixedUpdate()
|
||||||
|
{
|
||||||
|
// Only process new collisions
|
||||||
|
if (!m_HasCollisions && m_CurrentCount == 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// This assures we won't process the same collision
|
||||||
|
// set after it has been processed.
|
||||||
|
if (m_HasCollisions)
|
||||||
|
{
|
||||||
|
m_CurrentCount = m_Count;
|
||||||
|
m_HasCollisions = false;
|
||||||
|
m_JobHandle.Complete();
|
||||||
|
}
|
||||||
|
ProcessCollisions();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LateUpdate()
|
||||||
|
{
|
||||||
|
m_CurrentCount = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ulong m_EventId;
|
||||||
|
private void Physics_ContactEvent(PhysicsScene scene, NativeArray<ContactPairHeader>.ReadOnly pairHeaders)
|
||||||
|
{
|
||||||
|
m_EventId++;
|
||||||
|
m_HasCollisions = true;
|
||||||
|
int n = pairHeaders.Length;
|
||||||
|
if (m_ResultsArray.Length < n)
|
||||||
|
{
|
||||||
|
m_ResultsArray.Dispose();
|
||||||
|
m_ResultsArray = new NativeArray<JobResultStruct>(Mathf.NextPowerOfTwo(n), Allocator.Persistent);
|
||||||
|
}
|
||||||
|
m_Count = n;
|
||||||
|
var job = new GetCollisionsJob()
|
||||||
|
{
|
||||||
|
PairedHeaders = pairHeaders,
|
||||||
|
ResultsArray = m_ResultsArray
|
||||||
|
};
|
||||||
|
m_JobHandle = job.Schedule(n, 256);
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct GetCollisionsJob : IJobParallelFor
|
||||||
|
{
|
||||||
|
[ReadOnly]
|
||||||
|
public NativeArray<ContactPairHeader>.ReadOnly PairedHeaders;
|
||||||
|
|
||||||
|
public NativeArray<JobResultStruct> ResultsArray;
|
||||||
|
|
||||||
|
public void Execute(int index)
|
||||||
|
{
|
||||||
|
Vector3 averageNormal = Vector3.zero;
|
||||||
|
Vector3 averagePoint = Vector3.zero;
|
||||||
|
Vector3 averageCollisionStay = Vector3.zero;
|
||||||
|
int count = 0;
|
||||||
|
int collisionStaycount = 0;
|
||||||
|
int positionCount = 0;
|
||||||
|
for (int j = 0; j < PairedHeaders[index].pairCount; j++)
|
||||||
|
{
|
||||||
|
ref readonly var pair = ref PairedHeaders[index].GetContactPair(j);
|
||||||
|
|
||||||
|
if (pair.isCollisionExit)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int k = 0; k < pair.contactCount; k++)
|
||||||
|
{
|
||||||
|
ref readonly var contact = ref pair.GetContactPoint(k);
|
||||||
|
averagePoint += contact.position;
|
||||||
|
positionCount++;
|
||||||
|
if (!pair.isCollisionStay)
|
||||||
|
{
|
||||||
|
averageNormal += contact.normal;
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
averageCollisionStay += contact.normal;
|
||||||
|
collisionStaycount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (count != 0)
|
||||||
|
{
|
||||||
|
averageNormal /= count;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (collisionStaycount != 0)
|
||||||
|
{
|
||||||
|
averageCollisionStay /= collisionStaycount;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (positionCount != 0)
|
||||||
|
{
|
||||||
|
averagePoint /= positionCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = new JobResultStruct()
|
||||||
|
{
|
||||||
|
ThisInstanceID = PairedHeaders[index].bodyInstanceID,
|
||||||
|
OtherInstanceID = PairedHeaders[index].otherBodyInstanceID,
|
||||||
|
AverageNormal = averageNormal,
|
||||||
|
HasCollisionStay = collisionStaycount != 0,
|
||||||
|
AverageCollisionStayNormal = averageCollisionStay,
|
||||||
|
ContactPoint = averagePoint
|
||||||
|
};
|
||||||
|
|
||||||
|
ResultsArray[index] = result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -13,6 +13,14 @@ namespace Unity.Netcode
|
|||||||
[Serializable]
|
[Serializable]
|
||||||
public class NetworkConfig
|
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>
|
/// <summary>
|
||||||
/// The protocol version. Different versions doesn't talk to each other.
|
/// The protocol version. Different versions doesn't talk to each other.
|
||||||
/// </summary>
|
/// </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.
|
/// 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>
|
/// </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.")]
|
[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;
|
public float SpawnTimeout = 10f;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -149,8 +159,8 @@ namespace Unity.Netcode
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public const int RttWindowSize = 64; // number of slots to use for RTT computations (max number of in-flight packets)
|
public const int RttWindowSize = 64; // number of slots to use for RTT computations (max number of in-flight packets)
|
||||||
|
|
||||||
[Tooltip("Determines if the network session will run in client-server or distributed authority mode.")]
|
[Tooltip("Determines whether to use the client-server or distributed authority network topology.")]
|
||||||
public SessionModeTypes SessionMode;
|
public NetworkTopologyTypes NetworkTopology;
|
||||||
|
|
||||||
[HideInInspector]
|
[HideInInspector]
|
||||||
public bool UseCMBService;
|
public bool UseCMBService;
|
||||||
@@ -158,6 +168,39 @@ namespace Unity.Netcode
|
|||||||
[Tooltip("When enabled (default), the player prefab will automatically be spawned (client-side) upon the client being approved and synchronized.")]
|
[Tooltip("When enabled (default), the player prefab will automatically be spawned (client-side) upon the client being approved and synchronized.")]
|
||||||
public bool AutoSpawnPlayerPrefabClientSide = true;
|
public bool AutoSpawnPlayerPrefabClientSide = true;
|
||||||
|
|
||||||
|
#if MULTIPLAYER_TOOLS
|
||||||
|
/// <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>
|
/// <summary>
|
||||||
/// Returns a base64 encoded version of the configuration
|
/// Returns a base64 encoded version of the configuration
|
||||||
/// </summary>
|
/// </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;
|
using UnityEngine;
|
||||||
|
|
||||||
namespace Unity.Netcode
|
namespace Unity.Netcode
|
||||||
{
|
{
|
||||||
|
|
||||||
public enum SessionModeTypes
|
|
||||||
{
|
|
||||||
ClientServer,
|
|
||||||
DistributedAuthority
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// A NetworkClient
|
/// A NetworkClient
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -41,7 +34,7 @@ namespace Unity.Netcode
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal bool IsApproved { get; set; }
|
internal bool IsApproved { get; set; }
|
||||||
|
|
||||||
public SessionModeTypes SessionModeType { get; internal set; }
|
public NetworkTopologyTypes NetworkTopologyType { get; internal set; }
|
||||||
|
|
||||||
public bool DAHost { get; internal set; }
|
public bool DAHost { get; internal set; }
|
||||||
|
|
||||||
@@ -61,9 +54,9 @@ namespace Unity.Netcode
|
|||||||
public NetworkObject PlayerObject;
|
public NetworkObject PlayerObject;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The list of NetworkObject's owned by this client instance
|
/// The NetworkObject's owned by this client instance
|
||||||
/// </summary>
|
/// </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; }
|
internal NetworkSpawnManager SpawnManager { get; private set; }
|
||||||
|
|
||||||
@@ -77,9 +70,9 @@ namespace Unity.Netcode
|
|||||||
if (networkManager != null)
|
if (networkManager != null)
|
||||||
{
|
{
|
||||||
SpawnManager = networkManager.SpawnManager;
|
SpawnManager = networkManager.SpawnManager;
|
||||||
SessionModeType = networkManager.NetworkConfig.SessionMode;
|
NetworkTopologyType = networkManager.NetworkConfig.NetworkTopology;
|
||||||
|
|
||||||
if (SessionModeType == SessionModeTypes.DistributedAuthority)
|
if (NetworkTopologyType == NetworkTopologyTypes.DistributedAuthority)
|
||||||
{
|
{
|
||||||
DAHost = IsClient && IsServer;
|
DAHost = IsClient && IsServer;
|
||||||
|
|
||||||
|
|||||||
@@ -10,15 +10,54 @@ using UnityEngine;
|
|||||||
|
|
||||||
namespace Unity.Netcode
|
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
|
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,
|
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,
|
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,
|
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
|
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 struct ConnectionEventData
|
||||||
{
|
{
|
||||||
public ConnectionEvent EventType;
|
public ConnectionEvent EventType;
|
||||||
@@ -105,8 +144,12 @@ namespace Unity.Netcode
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
peerClientIds[idx] = peerId;
|
// This assures if the server has not timed out prior to the client synchronizing that it doesn't exceed the allocated peer count.
|
||||||
++idx;
|
if (peerClientIds.Length > idx)
|
||||||
|
{
|
||||||
|
peerClientIds[idx] = peerId;
|
||||||
|
++idx;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
@@ -496,24 +539,32 @@ namespace Unity.Netcode
|
|||||||
// Process the incoming message queue so that we get everything from the server disconnecting us or, if we are the server, so we got everything from that client.
|
// 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();
|
MessageManager.ProcessIncomingMessageQueue();
|
||||||
|
|
||||||
InvokeOnClientDisconnectCallback(clientId);
|
|
||||||
|
|
||||||
if (LocalClient.IsHost)
|
|
||||||
{
|
|
||||||
InvokeOnPeerDisconnectedCallback(clientId);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (LocalClient.IsServer)
|
if (LocalClient.IsServer)
|
||||||
{
|
{
|
||||||
|
// We need to process the disconnection before notifying
|
||||||
OnClientDisconnectFromServer(clientId);
|
OnClientDisconnectFromServer(clientId);
|
||||||
|
|
||||||
|
// Now notify the client has disconnected
|
||||||
|
InvokeOnClientDisconnectCallback(clientId);
|
||||||
|
|
||||||
|
if (LocalClient.IsHost)
|
||||||
|
{
|
||||||
|
InvokeOnPeerDisconnectedCallback(clientId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else // As long as we are not in the middle of a shutdown
|
else
|
||||||
if (!NetworkManager.ShutdownInProgress)
|
|
||||||
{
|
{
|
||||||
// We must pass true here and not process any sends messages as we are no longer connected.
|
// Notify local client of disconnection
|
||||||
// Otherwise, attempting to process messages here can cause an exception within UnityTransport
|
InvokeOnClientDisconnectCallback(clientId);
|
||||||
// as the client ID is no longer valid.
|
|
||||||
NetworkManager.Shutdown(true);
|
// As long as we are not in the middle of a shutdown
|
||||||
|
if (!NetworkManager.ShutdownInProgress)
|
||||||
|
{
|
||||||
|
// We must pass true here and not process any sends messages as we are no longer connected.
|
||||||
|
// Otherwise, attempting to process messages here can cause an exception within UnityTransport
|
||||||
|
// as the client ID is no longer valid.
|
||||||
|
NetworkManager.Shutdown(true);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||||
s_TransportDisconnect.End();
|
s_TransportDisconnect.End();
|
||||||
@@ -551,10 +602,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
var message = new ConnectionRequestMessage
|
var message = new ConnectionRequestMessage
|
||||||
{
|
{
|
||||||
CMBServiceConnection = NetworkManager.CMBServiceConnection,
|
DistributedAuthority = NetworkManager.DistributedAuthorityMode,
|
||||||
TickRate = NetworkManager.NetworkConfig.TickRate,
|
|
||||||
EnableSceneManagement = NetworkManager.NetworkConfig.EnableSceneManagement,
|
|
||||||
|
|
||||||
// Since only a remote client will send a connection request, we should always force the rebuilding of the NetworkConfig hash value
|
// 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),
|
ConfigHash = NetworkManager.NetworkConfig.GetConfig(false),
|
||||||
ShouldSendConnectionData = NetworkManager.NetworkConfig.ConnectionApproval,
|
ShouldSendConnectionData = NetworkManager.NetworkConfig.ConnectionApproval,
|
||||||
@@ -562,6 +610,13 @@ namespace Unity.Netcode
|
|||||||
MessageVersions = new NativeArray<MessageVersionData>(MessageManager.MessageHandlers.Length, Allocator.Temp)
|
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++)
|
for (int index = 0; index < MessageManager.MessageHandlers.Length; index++)
|
||||||
{
|
{
|
||||||
if (MessageManager.MessageTypes[index] != null)
|
if (MessageManager.MessageTypes[index] != null)
|
||||||
@@ -735,42 +790,23 @@ namespace Unity.Netcode
|
|||||||
RemovePendingClient(ownerClientId);
|
RemovePendingClient(ownerClientId);
|
||||||
|
|
||||||
var client = AddClient(ownerClientId);
|
var client = AddClient(ownerClientId);
|
||||||
if (!NetworkManager.DistributedAuthorityMode && response.CreatePlayerObject && NetworkManager.NetworkConfig.PlayerPrefab != null)
|
|
||||||
|
// Server-side spawning (only if there is a prefab hash or player prefab provided)
|
||||||
|
if (!NetworkManager.DistributedAuthorityMode && response.CreatePlayerObject && (response.PlayerPrefabHash.HasValue || NetworkManager.NetworkConfig.PlayerPrefab != null))
|
||||||
{
|
{
|
||||||
var prefabNetworkObject = NetworkManager.NetworkConfig.PlayerPrefab.GetComponent<NetworkObject>();
|
var playerObject = response.PlayerPrefabHash.HasValue ? NetworkManager.SpawnManager.GetNetworkObjectToSpawn(response.PlayerPrefabHash.Value, ownerClientId, response.Position ?? null, response.Rotation ?? null)
|
||||||
var playerPrefabHash = response.PlayerPrefabHash ?? prefabNetworkObject.GlobalObjectIdHash;
|
: NetworkManager.SpawnManager.GetNetworkObjectToSpawn(NetworkManager.NetworkConfig.PlayerPrefab.GetComponent<NetworkObject>().GlobalObjectIdHash, ownerClientId, response.Position ?? null, response.Rotation ?? null);
|
||||||
|
|
||||||
// Generate a SceneObject for the player object to spawn
|
|
||||||
// Note: This is only to create the local NetworkObject, many of the serialized properties of the player prefab will be set when instantiated.
|
|
||||||
var sceneObject = new NetworkObject.SceneObject
|
|
||||||
{
|
|
||||||
OwnerClientId = ownerClientId,
|
|
||||||
IsPlayerObject = true,
|
|
||||||
IsSceneObject = false,
|
|
||||||
HasTransform = prefabNetworkObject.SynchronizeTransform,
|
|
||||||
Hash = playerPrefabHash,
|
|
||||||
TargetClientId = ownerClientId,
|
|
||||||
DontDestroyWithOwner = prefabNetworkObject.DontDestroyWithOwner,
|
|
||||||
Transform = new NetworkObject.SceneObject.TransformData
|
|
||||||
{
|
|
||||||
Position = response.Position.GetValueOrDefault(),
|
|
||||||
Rotation = response.Rotation.GetValueOrDefault()
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Create the player NetworkObject locally
|
|
||||||
var networkObject = NetworkManager.SpawnManager.CreateLocalNetworkObject(sceneObject);
|
|
||||||
|
|
||||||
// Spawn the player NetworkObject locally
|
// Spawn the player NetworkObject locally
|
||||||
NetworkManager.SpawnManager.SpawnNetworkObjectLocally(
|
NetworkManager.SpawnManager.SpawnNetworkObjectLocally(
|
||||||
networkObject,
|
playerObject,
|
||||||
NetworkManager.SpawnManager.GetNetworkObjectId(),
|
NetworkManager.SpawnManager.GetNetworkObjectId(),
|
||||||
sceneObject: false,
|
sceneObject: false,
|
||||||
playerObject: true,
|
playerObject: true,
|
||||||
ownerClientId,
|
ownerClientId,
|
||||||
destroyWithScene: false);
|
destroyWithScene: false);
|
||||||
|
|
||||||
client.AssignPlayerObject(ref networkObject);
|
client.AssignPlayerObject(ref playerObject);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Server doesn't send itself the connection approved message
|
// 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))
|
if (!response.CreatePlayerObject || (response.PlayerPrefabHash == null && NetworkManager.NetworkConfig.PlayerPrefab == null))
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
@@ -902,7 +939,7 @@ namespace Unity.Netcode
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Client-Side Spawning in distributed authority mode uses this to spawn the player.
|
/// Client-Side Spawning in distributed authority mode uses this to spawn the player.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal void CreateAndSpawnPlayer(ulong ownerId, Vector3 position = default, Quaternion rotation = default)
|
internal void CreateAndSpawnPlayer(ulong ownerId)
|
||||||
{
|
{
|
||||||
if (NetworkManager.DistributedAuthorityMode && NetworkManager.AutoSpawnPlayerPrefabClientSide)
|
if (NetworkManager.DistributedAuthorityMode && NetworkManager.AutoSpawnPlayerPrefabClientSide)
|
||||||
{
|
{
|
||||||
@@ -910,7 +947,7 @@ namespace Unity.Netcode
|
|||||||
if (playerPrefab != null)
|
if (playerPrefab != null)
|
||||||
{
|
{
|
||||||
var globalObjectIdHash = playerPrefab.GetComponent<NetworkObject>().GlobalObjectIdHash;
|
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.IsSceneObject = false;
|
||||||
networkObject.SpawnAsPlayerObject(ownerId, networkObject.DestroyWithScene);
|
networkObject.SpawnAsPlayerObject(ownerId, networkObject.DestroyWithScene);
|
||||||
}
|
}
|
||||||
@@ -1003,10 +1040,26 @@ namespace Unity.Netcode
|
|||||||
ConnectedClientIds.Add(clientId);
|
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)
|
foreach (var networkObject in NetworkManager.SpawnManager.SpawnedObjectsList)
|
||||||
{
|
{
|
||||||
if (networkObject.SpawnWithObservers)
|
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);
|
networkObject.Observers.Add(clientId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1159,7 +1212,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
// Only NetworkObjects that have the OwnershipStatus.Distributable flag set and no parent
|
// Only NetworkObjects that have the OwnershipStatus.Distributable flag set and no parent
|
||||||
// (ownership is transferred to all children) will have their ownership redistributed.
|
// (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)
|
if (ownedObject.IsOwnershipLocked)
|
||||||
{
|
{
|
||||||
@@ -1196,6 +1249,11 @@ namespace Unity.Netcode
|
|||||||
childObject.SetOwnershipLock(false);
|
childObject.SetOwnershipLock(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Ignore session owner marked objects
|
||||||
|
if (childObject.IsOwnershipSessionOwner)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
NetworkManager.SpawnManager.ChangeOwnership(childObject, targetOwner, true);
|
NetworkManager.SpawnManager.ChangeOwnership(childObject, targetOwner, true);
|
||||||
if (EnableDistributeLogging)
|
if (EnableDistributeLogging)
|
||||||
{
|
{
|
||||||
@@ -1229,6 +1287,8 @@ namespace Unity.Netcode
|
|||||||
var message = new ClientDisconnectedMessage { ClientId = clientId };
|
var message = new ClientDisconnectedMessage { ClientId = clientId };
|
||||||
MessageManager?.SendMessage(ref message, NetworkDelivery.ReliableFragmentedSequenced, ConnectedClientIds);
|
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)
|
if (NetworkManager.DistributedAuthorityMode && !NetworkManager.ShutdownInProgress && NetworkManager.IsListening)
|
||||||
{
|
{
|
||||||
var newSessionOwner = NetworkManager.LocalClientId;
|
var newSessionOwner = NetworkManager.LocalClientId;
|
||||||
@@ -1259,6 +1319,7 @@ namespace Unity.Netcode
|
|||||||
MessageManager?.SendMessage(ref sessionOwnerMessage, NetworkDelivery.ReliableFragmentedSequenced, ConnectedClientIds);
|
MessageManager?.SendMessage(ref sessionOwnerMessage, NetworkDelivery.ReliableFragmentedSequenced, ConnectedClientIds);
|
||||||
NetworkManager.SetSessionOwner(newSessionOwner);
|
NetworkManager.SetSessionOwner(newSessionOwner);
|
||||||
}
|
}
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
// If the client ID transport map exists
|
// If the client ID transport map exists
|
||||||
@@ -1306,7 +1367,15 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
if (!LocalClient.IsServer)
|
if (!LocalClient.IsServer)
|
||||||
{
|
{
|
||||||
throw new NotServerException($"Only server can disconnect remote clients. Please use `{nameof(Shutdown)}()` instead.");
|
if (NetworkManager.NetworkConfig.NetworkTopology == NetworkTopologyTypes.ClientServer)
|
||||||
|
{
|
||||||
|
throw new NotServerException($"Only server can disconnect remote clients. Please use `{nameof(Shutdown)}()` instead.");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Debug.LogWarning($"Currently, clients cannot disconnect other clients from a distributed authority session. Please use `{nameof(Shutdown)}()` instead.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (clientId == NetworkManager.ServerClientId)
|
if (clientId == NetworkManager.ServerClientId)
|
||||||
|
|||||||
@@ -15,10 +15,16 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The base class to override to write network code. Inherits MonoBehaviour
|
/// The base class to override to write network code. Inherits MonoBehaviour.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public abstract class NetworkBehaviour : MonoBehaviour
|
public abstract class NetworkBehaviour : MonoBehaviour
|
||||||
{
|
{
|
||||||
|
#if UNITY_EDITOR
|
||||||
|
[HideInInspector]
|
||||||
|
[SerializeField]
|
||||||
|
internal bool ShowTopMostFoldoutHeaderGroup = true;
|
||||||
|
#endif
|
||||||
|
|
||||||
#pragma warning disable IDE1006 // disable naming rule violation check
|
#pragma warning disable IDE1006 // disable naming rule violation check
|
||||||
|
|
||||||
// RuntimeAccessModifiersILPP will make this `public`
|
// RuntimeAccessModifiersILPP will make this `public`
|
||||||
@@ -27,7 +33,7 @@ namespace Unity.Netcode
|
|||||||
// RuntimeAccessModifiersILPP will make this `public`
|
// RuntimeAccessModifiersILPP will make this `public`
|
||||||
internal static readonly Dictionary<Type, Dictionary<uint, RpcReceiveHandler>> __rpc_func_table = new Dictionary<Type, Dictionary<uint, RpcReceiveHandler>>();
|
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`
|
// RuntimeAccessModifiersILPP will make this `public`
|
||||||
internal static readonly Dictionary<Type, Dictionary<uint, string>> __rpc_name_table = new Dictionary<Type, Dictionary<uint, string>>();
|
internal static readonly Dictionary<Type, Dictionary<uint, string>> __rpc_name_table = new Dictionary<Type, Dictionary<uint, string>>();
|
||||||
#endif
|
#endif
|
||||||
@@ -124,7 +130,7 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
bufferWriter.Dispose();
|
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 (__rpc_name_table[GetType()].TryGetValue(rpcMethodId, out var rpcMethodName))
|
||||||
{
|
{
|
||||||
NetworkManager.NetworkMetrics.TrackRpcSent(
|
NetworkManager.NetworkMetrics.TrackRpcSent(
|
||||||
@@ -252,7 +258,7 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
bufferWriter.Dispose();
|
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 (__rpc_name_table[GetType()].TryGetValue(rpcMethodId, out var rpcMethodName))
|
||||||
{
|
{
|
||||||
if (clientRpcParams.Send.TargetClientIds != null)
|
if (clientRpcParams.Send.TargetClientIds != null)
|
||||||
@@ -410,8 +416,8 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the NetworkManager that owns this NetworkBehaviour instance
|
/// 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
|
/// See `NetworkObject` note for how there is a chicken/egg problem when not initialized.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public NetworkManager NetworkManager
|
public NetworkManager NetworkManager
|
||||||
{
|
{
|
||||||
@@ -439,38 +445,40 @@ namespace Unity.Netcode
|
|||||||
/// <see cref="Unity.Netcode.RpcTarget.Not(NativeArray{ulong})"/>,
|
/// <see cref="Unity.Netcode.RpcTarget.Not(NativeArray{ulong})"/>,
|
||||||
/// <see cref="Unity.Netcode.RpcTarget.Not(NativeList{ulong})"/>,
|
/// <see cref="Unity.Netcode.RpcTarget.Not(NativeList{ulong})"/>,
|
||||||
/// <see cref="Unity.Netcode.RpcTarget.Not(ulong[])"/>, and
|
/// <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>
|
/// </summary>
|
||||||
#pragma warning restore IDE0001
|
#pragma warning restore IDE0001
|
||||||
public RpcTarget RpcTarget => NetworkManager.RpcTarget;
|
public RpcTarget RpcTarget => NetworkManager.RpcTarget;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// If a NetworkObject is assigned, it will return whether or not this NetworkObject
|
/// If a NetworkObject is assigned, returns whether the NetworkObject
|
||||||
/// is the local player object. If no NetworkObject is assigned it will always return false.
|
/// is the local player object. If no NetworkObject is assigned, returns false.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool IsLocalPlayer { get; private set; }
|
public bool IsLocalPlayer { get; private set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
public bool IsOwner { get; internal set; }
|
public bool IsOwner { get; internal set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets if we are executing as server
|
/// Gets whether executing as a server.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool IsServer { get; private set; }
|
public bool IsServer { get; private set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Determines if the local client has authority over the associated NetworkObject
|
/// Determines if the local client has authority over the associated NetworkObject.
|
||||||
/// Client-Server: This will return true if IsServer or IsHost
|
/// <list type="bullet">
|
||||||
/// Distributed Authority: This will return true if IsOwner
|
/// <item>In client-server contexts: returns true if `IsServer` or `IsHost`.</item>
|
||||||
|
/// <item>In distributed authority contexts: returns true if `IsOwner`.</item>
|
||||||
|
/// </list>
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool HasAuthority { get; internal set; }
|
public bool HasAuthority { get; internal set; }
|
||||||
|
|
||||||
internal NetworkClient LocalClient { get; private set; }
|
internal NetworkClient LocalClient { get; private set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets if the client is the distributed authority mode session owner
|
/// Gets whether the client is the distributed authority mode session owner.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool IsSessionOwner
|
public bool IsSessionOwner
|
||||||
{
|
{
|
||||||
@@ -486,29 +494,29 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
public bool ServerIsHost { get; private set; }
|
public bool ServerIsHost { get; private set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets if we are executing as client
|
/// Gets whether executing as a client.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool IsClient { get; private set; }
|
public bool IsClient { get; private set; }
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets if we are executing as Host, I.E Server and Client
|
/// Gets whether executing as a host (both server and client).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool IsHost { get; private set; }
|
public bool IsHost { get; private set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets Whether or not the object has a owner
|
/// Gets whether the object has an owner.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool IsOwnedByServer { get; internal set; }
|
public bool IsOwnedByServer { get; internal set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Used to determine if it is safe to access NetworkObject and NetworkManager from within a NetworkBehaviour component
|
/// Determines whether it's safe to access a NetworkObject and NetworkManager from within a NetworkBehaviour component.
|
||||||
/// Primarily useful when checking NetworkObject/NetworkManager properties within FixedUpate
|
/// Primarily useful when checking NetworkObject or NetworkManager properties within FixedUpate.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool IsSpawned { get; internal set; }
|
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
|
/// 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
|
/// how NetworkObject works but it was close to the release and too risky to change
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the NetworkObject that owns this NetworkBehaviour instance
|
/// Gets the NetworkObject that owns this NetworkBehaviour instance.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public NetworkObject NetworkObject
|
public NetworkObject NetworkObject
|
||||||
{
|
{
|
||||||
@@ -567,19 +575,19 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets whether or not this NetworkBehaviour instance has a NetworkObject owner.
|
/// Gets whether this NetworkBehaviour instance has a NetworkObject owner.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool HasNetworkObject => NetworkObject != null;
|
public bool HasNetworkObject => NetworkObject != null;
|
||||||
|
|
||||||
private NetworkObject m_NetworkObject = null;
|
private NetworkObject m_NetworkObject = null;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the NetworkId of the NetworkObject that owns this NetworkBehaviour
|
/// Gets the NetworkId of the NetworkObject that owns this NetworkBehaviour instance.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public ulong NetworkObjectId { get; internal set; }
|
public ulong NetworkObjectId { get; internal set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets NetworkId for this NetworkBehaviour from the owner NetworkObject
|
/// Gets NetworkId for this NetworkBehaviour from the owner NetworkObject.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public ushort NetworkBehaviourId { get; internal set; }
|
public ushort NetworkBehaviourId { get; internal set; }
|
||||||
|
|
||||||
@@ -589,7 +597,7 @@ namespace Unity.Netcode
|
|||||||
internal ushort NetworkBehaviourIdCache = 0;
|
internal ushort NetworkBehaviourIdCache = 0;
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
/// <param name="behaviourId">The behaviourId to return</param>
|
/// <param name="behaviourId">The behaviourId to return</param>
|
||||||
/// <returns>Returns NetworkBehaviour with given behaviourId</returns>
|
/// <returns>Returns NetworkBehaviour with given behaviourId</returns>
|
||||||
@@ -599,7 +607,7 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the ClientId that owns the NetworkObject
|
/// Gets the ClientId that owns this NetworkObject.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public ulong OwnerClientId { get; internal set; }
|
public ulong OwnerClientId { get; internal set; }
|
||||||
|
|
||||||
@@ -651,25 +659,83 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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.
|
/// Invoked only on the authority instance when a <see cref="NetworkObject"/> is deferring its despawn on non-authoritative instances.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <remarks>
|
/// <remarks>
|
||||||
/// See also: <see cref="NetworkObject.DeferDespawn(int, bool)"/>
|
/// See also: <see cref="NetworkObject.DeferDespawn(int, bool)"/>
|
||||||
/// </remarks>
|
/// </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) { }
|
public virtual void OnDeferringDespawn(int despawnTick) { }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets called when the <see cref="NetworkObject"/> gets spawned, message handlers are ready to be registered and the network is setup.
|
/// Gets called 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` or `IsClient`).
|
||||||
|
/// </summary>
|
||||||
|
/// <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 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 set up.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public virtual void OnNetworkSpawn() { }
|
public virtual void OnNetworkSpawn() { }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets called when the <see cref="NetworkObject"/> gets despawned. Is called both on the server and clients.
|
/// Gets called after the <see cref="NetworkObject"/> is spawned. All NetworkBehaviours associated with the NetworkObject will have had <see cref="OnNetworkSpawn"/> invoked.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Will be invoked on each <see cref="NetworkBehaviour"/> associated with the <see cref="NetworkObject"/> being spawned.
|
||||||
|
/// All associated <see cref="NetworkBehaviour"/> components will have had <see cref="OnNetworkSpawn"/> invoked on the spawned <see cref="NetworkObject"/>.
|
||||||
|
/// </remarks>
|
||||||
|
protected virtual void OnNetworkPostSpawn() { }
|
||||||
|
|
||||||
|
protected internal virtual void InternalOnNetworkPostSpawn() { }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// This method is only available client-side.
|
||||||
|
/// When a new client joins it's synchronized with all spawned NetworkObjects and scenes loaded for the session joined. At the end of the synchronization process, when all
|
||||||
|
/// <see cref="NetworkObject"/>s and scenes (if scene management is enabled) have finished synchronizing, all NetworkBehaviour components associated with spawned <see cref="NetworkObject"/>s
|
||||||
|
/// will have this method invoked.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// This can be used to handle post-synchronization actions where you might need to access a different NetworkObject and/or NetworkBehaviour not local to the current NetworkObject context.
|
||||||
|
/// This is only invoked on clients during a client-server network topology session.
|
||||||
|
/// </remarks>
|
||||||
|
protected virtual void OnNetworkSessionSynchronized() { }
|
||||||
|
|
||||||
|
protected internal virtual void InternalOnNetworkSessionSynchronized() { }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// When a scene is loaded and in-scene placed NetworkObjects are finished spawning, this method is invoked on all of the newly spawned in-scene placed NetworkObjects.
|
||||||
|
/// This method runs both client and server side.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// 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. This method runs both client and server side.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public virtual void OnNetworkDespawn() { }
|
public virtual void OnNetworkDespawn() { }
|
||||||
|
|
||||||
|
internal void NetworkPreSpawn(ref NetworkManager networkManager)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
OnNetworkPreSpawn(ref networkManager);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Debug.LogException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
internal void InternalOnNetworkSpawn()
|
internal void InternalOnNetworkSpawn()
|
||||||
{
|
{
|
||||||
IsSpawned = true;
|
IsSpawned = true;
|
||||||
@@ -699,6 +765,44 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal void NetworkPostSpawn()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
InternalOnNetworkPostSpawn();
|
||||||
|
OnNetworkPostSpawn();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Debug.LogException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal void NetworkSessionSynchronized()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
InternalOnNetworkSessionSynchronized();
|
||||||
|
OnNetworkSessionSynchronized();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Debug.LogException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal void InSceneNetworkObjectsSpawned()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
OnInSceneObjectsSpawned();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Debug.LogException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
internal void InternalOnNetworkDespawn()
|
internal void InternalOnNetworkDespawn()
|
||||||
{
|
{
|
||||||
IsSpawned = false;
|
IsSpawned = false;
|
||||||
@@ -714,19 +818,27 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
public virtual void OnGainedOwnership() { }
|
public virtual void OnGainedOwnership() { }
|
||||||
|
|
||||||
internal void InternalOnGainedOwnership()
|
internal void InternalOnGainedOwnership()
|
||||||
{
|
{
|
||||||
UpdateNetworkProperties();
|
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();
|
OnGainedOwnership();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Invoked on all clients, override this method to be notified of any
|
/// Invoked on all clients. Override this method to be notified of any
|
||||||
/// ownership changes (even if the instance was niether the previous or
|
/// ownership changes (even if the instance was neither the previous or
|
||||||
/// newly assigned current owner).
|
/// newly assigned current owner).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="previous">the previous owner</param>
|
/// <param name="previous">the previous owner</param>
|
||||||
@@ -742,7 +854,9 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
public virtual void OnLostOwnership() { }
|
public virtual void OnLostOwnership() { }
|
||||||
|
|
||||||
@@ -753,11 +867,13 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
/// <param name="parentNetworkObject">the new <see cref="NetworkObject"/> parent</param>
|
/// <param name="parentNetworkObject">the new <see cref="NetworkObject"/> parent</param>
|
||||||
public virtual void OnNetworkObjectParentChanged(NetworkObject parentNetworkObject) { }
|
public virtual void OnNetworkObjectParentChanged(NetworkObject parentNetworkObject) { }
|
||||||
|
|
||||||
|
internal virtual void InternalOnNetworkObjectParentChanged(NetworkObject parentNetworkObject) { }
|
||||||
|
|
||||||
private bool m_VarInit = false;
|
private bool m_VarInit = false;
|
||||||
|
|
||||||
private readonly List<HashSet<int>> m_DeliveryMappedNetworkVariableIndices = new List<HashSet<int>>();
|
private readonly List<HashSet<int>> m_DeliveryMappedNetworkVariableIndices = new List<HashSet<int>>();
|
||||||
@@ -788,7 +904,7 @@ namespace Unity.Netcode
|
|||||||
#pragma warning restore IDE1006 // restore naming rule violation check
|
#pragma warning restore IDE1006 // restore naming rule violation check
|
||||||
{
|
{
|
||||||
__rpc_func_table[GetType()][hash] = handler;
|
__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;
|
__rpc_name_table[GetType()][hash] = rpcMethodName;
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
@@ -814,7 +930,7 @@ namespace Unity.Netcode
|
|||||||
if (!__rpc_func_table.ContainsKey(GetType()))
|
if (!__rpc_func_table.ContainsKey(GetType()))
|
||||||
{
|
{
|
||||||
__rpc_func_table[GetType()] = new Dictionary<uint, RpcReceiveHandler>();
|
__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>();
|
__rpc_name_table[GetType()] = new Dictionary<uint, string>();
|
||||||
#endif
|
#endif
|
||||||
__initializeRpcs();
|
__initializeRpcs();
|
||||||
@@ -861,7 +977,16 @@ namespace Unity.Netcode
|
|||||||
// during OnNetworkSpawn has been sent and needs to be cleared
|
// during OnNetworkSpawn has been sent and needs to be cleared
|
||||||
for (int i = 0; i < NetworkVariableFields.Count; i++)
|
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
|
else
|
||||||
@@ -869,7 +994,16 @@ namespace Unity.Netcode
|
|||||||
// mark any variables we wrote as no longer dirty
|
// mark any variables we wrote as no longer dirty
|
||||||
for (int i = 0; i < NetworkVariableIndexesToReset.Count; i++)
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -889,9 +1023,14 @@ namespace Unity.Netcode
|
|||||||
internal readonly List<int> NetworkVariableIndexesToReset = new List<int>();
|
internal readonly List<int> NetworkVariableIndexesToReset = new List<int>();
|
||||||
internal readonly HashSet<int> NetworkVariableIndexesToResetSet = new HashSet<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;
|
return;
|
||||||
}
|
}
|
||||||
@@ -912,7 +1051,10 @@ namespace Unity.Netcode
|
|||||||
networkVariable = NetworkVariableFields[k];
|
networkVariable = NetworkVariableFields[k];
|
||||||
if (networkVariable.IsDirty() && networkVariable.CanClientRead(targetClientId))
|
if (networkVariable.IsDirty() && networkVariable.CanClientRead(targetClientId))
|
||||||
{
|
{
|
||||||
shouldSend = true;
|
if (networkVariable.CanSend())
|
||||||
|
{
|
||||||
|
shouldSend = true;
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -939,7 +1081,11 @@ namespace Unity.Netcode
|
|||||||
NetworkBehaviourIndex = behaviourIndex,
|
NetworkBehaviourIndex = behaviourIndex,
|
||||||
NetworkBehaviour = this,
|
NetworkBehaviour = this,
|
||||||
TargetClientId = targetClientId,
|
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.
|
// 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,
|
// Messages don't get sent from the server to itself, so if we're host and sending to ourselves,
|
||||||
@@ -968,15 +1114,42 @@ namespace Unity.Netcode
|
|||||||
// TODO: There should be a better way by reading one dirty variable vs. 'n'
|
// TODO: There should be a better way by reading one dirty variable vs. 'n'
|
||||||
for (int i = 0; i < NetworkVariableFields.Count; i++)
|
for (int i = 0; i < NetworkVariableFields.Count; i++)
|
||||||
{
|
{
|
||||||
if (NetworkVariableFields[i].IsDirty())
|
var networkVariable = NetworkVariableFields[i];
|
||||||
|
if (networkVariable.IsDirty())
|
||||||
{
|
{
|
||||||
return true;
|
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;
|
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)
|
internal void MarkVariablesDirty(bool dirty)
|
||||||
{
|
{
|
||||||
for (int j = 0; j < NetworkVariableFields.Count; j++)
|
for (int j = 0; j < NetworkVariableFields.Count; j++)
|
||||||
@@ -985,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>
|
/// <summary>
|
||||||
/// Synchronizes by setting only the NetworkVariable field values that the client has permission to read.
|
/// 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)
|
/// Note: This is only invoked when first synchronizing a NetworkBehaviour (i.e. late join or spawned NetworkObject)
|
||||||
@@ -995,30 +1179,25 @@ namespace Unity.Netcode
|
|||||||
/// </remarks>
|
/// </remarks>
|
||||||
internal void WriteNetworkVariableData(FastBufferWriter writer, ulong targetClientId)
|
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;
|
var networkManager = NetworkManager;
|
||||||
if (networkManager.DistributedAuthorityMode)
|
var ensureLengthSafety = networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety;
|
||||||
{
|
|
||||||
writer.WriteValueSafe((ushort)NetworkVariableFields.Count);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
// Exit early if there are no NetworkVariables
|
||||||
if (NetworkVariableFields.Count == 0)
|
if (NetworkVariableFields.Count == 0)
|
||||||
{
|
{
|
||||||
return;
|
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++)
|
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 (NetworkVariableFields[j].CanClientRead(targetClientId))
|
||||||
{
|
{
|
||||||
if (networkManager.DistributedAuthorityMode)
|
// Write additional NetworkVariable information when length safety is enabled or when in distributed authority mode
|
||||||
{
|
if (ensureLengthSafety)
|
||||||
writer.WriteValueSafe(NetworkVariableFields[j].Type);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (networkManager.DistributedAuthorityMode || networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
|
|
||||||
{
|
{
|
||||||
var writePos = writer.Position;
|
var writePos = writer.Position;
|
||||||
// Note: This value can't be packed because we don't know how large it will be in advance
|
// Note: This value can't be packed because we don't know how large it will be in advance
|
||||||
@@ -1028,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.
|
// The way we do packing, any value > 63 in a ushort will use the full 2 bytes to represent.
|
||||||
writer.WriteValueSafe((ushort)0);
|
writer.WriteValueSafe((ushort)0);
|
||||||
var startPos = writer.Position;
|
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;
|
var size = writer.Position - startPos;
|
||||||
writer.Seek(writePos);
|
writer.Seek(writePos);
|
||||||
|
// Write the NetworkVariable field value size
|
||||||
writer.WriteValueSafe((ushort)size);
|
writer.WriteValueSafe((ushort)size);
|
||||||
writer.Seek(startPos + 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
|
// Client-Server Only: If the client cannot read this field, then skip it but write a 0 for this NetworkVariable's position
|
||||||
if (networkManager.DistributedAuthorityMode || networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
|
|
||||||
{
|
{
|
||||||
writer.WriteValueSafe((ushort)0);
|
writer.WriteValueSafe((ushort)0);
|
||||||
}
|
}
|
||||||
@@ -1060,75 +1247,60 @@ namespace Unity.Netcode
|
|||||||
/// </remarks>
|
/// </remarks>
|
||||||
internal void SetNetworkVariableData(FastBufferReader reader, ulong clientId)
|
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;
|
var networkManager = NetworkManager;
|
||||||
if (networkManager.DistributedAuthorityMode)
|
var ensureLengthSafety = networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety;
|
||||||
{
|
|
||||||
reader.ReadValueSafe(out ushort variableCount);
|
|
||||||
if (variableCount != NetworkVariableFields.Count)
|
|
||||||
{
|
|
||||||
Debug.LogError("NetworkVariable count mismatch.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// Exit early if nothing else to read
|
||||||
if (NetworkVariableFields.Count == 0)
|
if (NetworkVariableFields.Count == 0)
|
||||||
{
|
{
|
||||||
return;
|
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++)
|
for (int j = 0; j < NetworkVariableFields.Count; j++)
|
||||||
{
|
{
|
||||||
var varSize = (ushort)0;
|
var varSize = (ushort)0;
|
||||||
var readStartPos = 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))
|
||||||
{
|
{
|
||||||
reader.ReadValueSafe(out varSize);
|
if (ensureLengthSafety)
|
||||||
if (varSize == 0)
|
|
||||||
{
|
{
|
||||||
continue;
|
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;
|
||||||
}
|
}
|
||||||
readStartPos = reader.Position;
|
|
||||||
}
|
}
|
||||||
else // If the client cannot read this field, then skip it
|
else // Client-Server Only: If the client cannot read this field, then skip it
|
||||||
if (!NetworkVariableFields[j].CanClientRead(clientId))
|
|
||||||
{
|
{
|
||||||
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);
|
reader.ReadValueSafe(out ushort size);
|
||||||
if (size != 0)
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (networkManager.DistributedAuthorityMode)
|
// Read the NetworkVariable value
|
||||||
{
|
NetworkVariableFields[j].ReadField(reader);
|
||||||
// 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;
|
|
||||||
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 (reader.Position > (readStartPos + varSize))
|
||||||
{
|
{
|
||||||
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
|
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);
|
reader.Seek(readStartPos + varSize);
|
||||||
@@ -1137,7 +1309,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
|
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);
|
reader.Seek(readStartPos + varSize);
|
||||||
@@ -1147,7 +1319,7 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the local instance of a object with a given NetworkId
|
/// Gets the local instance of a NetworkObject with a given NetworkId.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="networkId"></param>
|
/// <param name="networkId"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
@@ -1158,14 +1330,14 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Override this method if your derived NetworkBehaviour requires custom synchronization data.
|
/// 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
|
/// and will increase the payload size for client synchronization and dynamically spawned
|
||||||
/// <see cref="NetworkObject"/>s.
|
/// <see cref="NetworkObject"/>s.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <remarks>
|
/// <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 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.
|
/// NetworkObject being spawned.
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
/// <param name="serializer">The serializer to use to read and write the data.</param>
|
/// <param name="serializer">The serializer to use to read and write the data.</param>
|
||||||
@@ -1179,14 +1351,19 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public virtual void OnReanticipate(double lastRoundTripTime)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The relative client identifier targeted for the serialization of this <see cref="NetworkBehaviour"/> instance.
|
/// The relative client identifier targeted for the serialization of this <see cref="NetworkBehaviour"/> instance.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <remarks>
|
/// <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 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"/>.
|
/// 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>
|
/// </remarks>
|
||||||
protected ulong m_TargetIdBeingSynchronized { get; private set; }
|
protected ulong m_TargetIdBeingSynchronized { get; private set; }
|
||||||
|
|
||||||
@@ -1309,9 +1486,8 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Invoked when the <see cref="GameObject"/> the <see cref="NetworkBehaviour"/> is attached to.
|
/// Invoked when the <see cref="GameObject"/> the <see cref="NetworkBehaviour"/> is attached to is destroyed.
|
||||||
/// NOTE: If you override this, you will want to always invoke this base class version of this
|
/// If you override this, you must always invoke the base class version of this <see cref="OnDestroy"/> method.
|
||||||
/// <see cref="OnDestroy"/> method!!
|
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public virtual void OnDestroy()
|
public virtual void OnDestroy()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ namespace Unity.Netcode
|
|||||||
private NetworkManager m_NetworkManager;
|
private NetworkManager m_NetworkManager;
|
||||||
private NetworkConnectionManager m_ConnectionManager;
|
private NetworkConnectionManager m_ConnectionManager;
|
||||||
private HashSet<NetworkObject> m_DirtyNetworkObjects = new HashSet<NetworkObject>();
|
private HashSet<NetworkObject> m_DirtyNetworkObjects = new HashSet<NetworkObject>();
|
||||||
|
private HashSet<NetworkObject> m_PendingDirtyNetworkObjects = new HashSet<NetworkObject>();
|
||||||
|
|
||||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||||
private ProfilerMarker m_NetworkBehaviourUpdate = new ProfilerMarker($"{nameof(NetworkBehaviour)}.{nameof(NetworkBehaviourUpdate)}");
|
private ProfilerMarker m_NetworkBehaviourUpdate = new ProfilerMarker($"{nameof(NetworkBehaviour)}.{nameof(NetworkBehaviourUpdate)}");
|
||||||
@@ -18,16 +19,24 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
internal void AddForUpdate(NetworkObject networkObject)
|
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
|
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||||
m_NetworkBehaviourUpdate.Begin();
|
m_NetworkBehaviourUpdate.Begin();
|
||||||
#endif
|
#endif
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
m_DirtyNetworkObjects.UnionWith(m_PendingDirtyNetworkObjects);
|
||||||
|
m_PendingDirtyNetworkObjects.Clear();
|
||||||
|
|
||||||
// NetworkObject references can become null, when hidden or despawned. Once NUll, there is no point
|
// 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.
|
// trying to process them, even if they were previously marked as dirty.
|
||||||
m_DirtyNetworkObjects.RemoveWhere((sobj) => sobj == null);
|
m_DirtyNetworkObjects.RemoveWhere((sobj) => sobj == null);
|
||||||
@@ -49,7 +58,7 @@ namespace Unity.Netcode
|
|||||||
// Sync just the variables for just the objects this client sees
|
// Sync just the variables for just the objects this client sees
|
||||||
for (int k = 0; k < dirtyObj.ChildNetworkBehaviours.Count; k++)
|
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++)
|
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];
|
var behaviour = dirtyObj.ChildNetworkBehaviours[k];
|
||||||
for (int i = 0; i < behaviour.NetworkVariableFields.Count; i++)
|
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() &&
|
if (behaviour.NetworkVariableFields[i].IsDirty() &&
|
||||||
!behaviour.NetworkVariableIndexesToResetSet.Contains(i))
|
!behaviour.NetworkVariableIndexesToResetSet.Contains(i))
|
||||||
{
|
{
|
||||||
behaviour.NetworkVariableIndexesToResetSet.Add(i);
|
behaviour.NetworkVariableIndexesToResetSet.Add(i);
|
||||||
behaviour.NetworkVariableIndexesToReset.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
|
// Now, reset all the no-longer-dirty variables
|
||||||
foreach (var dirtyobj in m_DirtyNetworkObjects)
|
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
|
// Once done processing, we set the previous owner id to the current owner id
|
||||||
dirtyobj.PreviousOwnerId = dirtyobj.OwnerClientId;
|
dirtyobj.PreviousOwnerId = dirtyobj.OwnerClientId;
|
||||||
}
|
}
|
||||||
@@ -127,6 +141,9 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
// Then show any NetworkObjects queued to be made visible/shown
|
// Then show any NetworkObjects queued to be made visible/shown
|
||||||
m_NetworkManager.SpawnManager.HandleNetworkObjectShow();
|
m_NetworkManager.SpawnManager.HandleNetworkObjectShow();
|
||||||
|
|
||||||
|
// Handle object redistribution (DA + disabled scene management only)
|
||||||
|
m_NetworkManager.HandleRedistributionToClients();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ using System.Linq;
|
|||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
#if UNITY_EDITOR
|
#if UNITY_EDITOR
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
|
using PackageInfo = UnityEditor.PackageManager.PackageInfo;
|
||||||
#endif
|
#endif
|
||||||
using UnityEngine.SceneManagement;
|
using UnityEngine.SceneManagement;
|
||||||
using Debug = UnityEngine.Debug;
|
using Debug = UnityEngine.Debug;
|
||||||
@@ -17,6 +18,23 @@ namespace Unity.Netcode
|
|||||||
[AddComponentMenu("Netcode/Network Manager", -100)]
|
[AddComponentMenu("Netcode/Network Manager", -100)]
|
||||||
public class NetworkManager : MonoBehaviour, INetworkUpdateSystem
|
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...
|
// TODO: Deprecate...
|
||||||
// The following internal values are not used, but because ILPP makes them public in the assembly, they cannot
|
// 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.
|
// be removed thanks to our semver validation.
|
||||||
@@ -28,24 +46,59 @@ namespace Unity.Netcode
|
|||||||
// RuntimeAccessModifiersILPP will make this `public`
|
// RuntimeAccessModifiersILPP will make this `public`
|
||||||
internal static readonly Dictionary<uint, RpcReceiveHandler> __rpc_func_table = new Dictionary<uint, RpcReceiveHandler>();
|
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`
|
// RuntimeAccessModifiersILPP will make this `public`
|
||||||
internal static readonly Dictionary<uint, string> __rpc_name_table = new Dictionary<uint, string>();
|
internal static readonly Dictionary<uint, string> __rpc_name_table = new Dictionary<uint, string>();
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#pragma warning restore IDE1006 // restore naming rule violation check
|
#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>
|
/// <summary>
|
||||||
/// Distributed Authority Mode
|
/// Distributed Authority Mode
|
||||||
/// Returns true if the current session is running in distributed authority mode.
|
/// Returns true if the current session is running in distributed authority mode.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool DistributedAuthorityMode
|
public bool DistributedAuthorityMode { get; private set; }
|
||||||
{
|
|
||||||
get
|
|
||||||
{
|
|
||||||
return NetworkConfig.SessionMode == SessionModeTypes.DistributedAuthority;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Distributed Authority Mode
|
/// Distributed Authority Mode
|
||||||
@@ -121,15 +174,47 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// DANGO-TODO-MVP: Remove these properties once the service handles object distribution
|
// DANGO-TODO: Determine if this needs to be removed once the service handles object distribution
|
||||||
internal ulong ClientToRedistribute;
|
internal List<ulong> ClientsToRedistribute = new List<ulong>();
|
||||||
internal bool RedistributeToClient;
|
internal bool RedistributeToClients;
|
||||||
internal int TickToRedistribute;
|
|
||||||
|
/// <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>();
|
internal List<NetworkObject> DeferredDespawnObjects = new List<NetworkObject>();
|
||||||
|
|
||||||
public ulong CurrentSessionOwner { get; internal set; }
|
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)
|
internal void SetSessionOwner(ulong sessionOwner)
|
||||||
{
|
{
|
||||||
var previousSessionOwner = CurrentSessionOwner;
|
var previousSessionOwner = CurrentSessionOwner;
|
||||||
@@ -140,20 +225,17 @@ namespace Unity.Netcode
|
|||||||
foreach (var networkObjectEntry in SpawnManager.SpawnedObjects)
|
foreach (var networkObjectEntry in SpawnManager.SpawnedObjects)
|
||||||
{
|
{
|
||||||
var networkObject = networkObjectEntry.Value;
|
var networkObject = networkObjectEntry.Value;
|
||||||
if (networkObject.IsSceneObject == null || !networkObject.IsSceneObject.Value)
|
if (networkObject.IsOwnershipSessionOwner && LocalClient.IsSessionOwner)
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (networkObject.OwnerClientId != LocalClientId)
|
|
||||||
{
|
{
|
||||||
SpawnManager.ChangeOwnership(networkObject, LocalClientId, true);
|
SpawnManager.ChangeOwnership(networkObject, LocalClientId, true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
OnSessionOwnerPromoted?.Invoke(sessionOwner);
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Make this internal after testing
|
internal void PromoteSessionOwner(ulong clientId)
|
||||||
public void PromoteSessionOwner(ulong clientId)
|
|
||||||
{
|
{
|
||||||
if (!DistributedAuthorityMode)
|
if (!DistributedAuthorityMode)
|
||||||
{
|
{
|
||||||
@@ -177,24 +259,137 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal Dictionary<ulong, NetworkObject> NetworkTransformUpdate = new Dictionary<ulong, NetworkObject>();
|
||||||
|
#if COM_UNITY_MODULES_PHYSICS
|
||||||
|
internal Dictionary<ulong, NetworkObject> NetworkTransformFixedUpdate = new Dictionary<ulong, NetworkObject>();
|
||||||
|
#endif
|
||||||
|
|
||||||
|
internal void NetworkTransformRegistration(NetworkObject networkObject, bool onUpdate = true, bool register = true)
|
||||||
|
{
|
||||||
|
if (onUpdate)
|
||||||
|
{
|
||||||
|
if (register)
|
||||||
|
{
|
||||||
|
if (!NetworkTransformUpdate.ContainsKey(networkObject.NetworkObjectId))
|
||||||
|
{
|
||||||
|
NetworkTransformUpdate.Add(networkObject.NetworkObjectId, networkObject);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
NetworkTransformUpdate.Remove(networkObject.NetworkObjectId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#if COM_UNITY_MODULES_PHYSICS
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (register)
|
||||||
|
{
|
||||||
|
if (!NetworkTransformFixedUpdate.ContainsKey(networkObject.NetworkObjectId))
|
||||||
|
{
|
||||||
|
NetworkTransformFixedUpdate.Add(networkObject.NetworkObjectId, networkObject);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
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)
|
public void NetworkUpdate(NetworkUpdateStage updateStage)
|
||||||
{
|
{
|
||||||
switch (updateStage)
|
switch (updateStage)
|
||||||
{
|
{
|
||||||
case NetworkUpdateStage.EarlyUpdate:
|
case NetworkUpdateStage.EarlyUpdate:
|
||||||
{
|
{
|
||||||
|
UpdateTopology();
|
||||||
|
|
||||||
|
// Handle processing any new connections or transport events
|
||||||
|
NetworkConfig.NetworkTransport.EarlyUpdate();
|
||||||
|
|
||||||
ConnectionManager.ProcessPendingApprovals();
|
ConnectionManager.ProcessPendingApprovals();
|
||||||
ConnectionManager.PollAndHandleNetworkEvents();
|
ConnectionManager.PollAndHandleNetworkEvents();
|
||||||
|
|
||||||
DeferredMessageManager.ProcessTriggers(IDeferredNetworkMessageManager.TriggerType.OnNextFrame, 0);
|
DeferredMessageManager.ProcessTriggers(IDeferredNetworkMessageManager.TriggerType.OnNextFrame, 0);
|
||||||
|
|
||||||
|
AnticipationSystem.SetupForUpdate();
|
||||||
MessageManager.ProcessIncomingMessageQueue();
|
MessageManager.ProcessIncomingMessageQueue();
|
||||||
|
|
||||||
MessageManager.CleanupDisconnectedClients();
|
MessageManager.CleanupDisconnectedClients();
|
||||||
|
AnticipationSystem.ProcessReanticipation();
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
#if COM_UNITY_MODULES_PHYSICS
|
||||||
|
case NetworkUpdateStage.FixedUpdate:
|
||||||
|
{
|
||||||
|
foreach (var networkObjectEntry in NetworkTransformFixedUpdate)
|
||||||
|
{
|
||||||
|
// if not active or not spawned then skip
|
||||||
|
if (!networkObjectEntry.Value.gameObject.activeInHierarchy || !networkObjectEntry.Value.IsSpawned)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var networkTransformEntry in networkObjectEntry.Value.NetworkTransforms)
|
||||||
|
{
|
||||||
|
// only update if enabled
|
||||||
|
if (networkTransformEntry.enabled)
|
||||||
|
{
|
||||||
|
networkTransformEntry.OnFixedUpdate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
#endif
|
||||||
case NetworkUpdateStage.PreUpdate:
|
case NetworkUpdateStage.PreUpdate:
|
||||||
{
|
{
|
||||||
NetworkTimeSystem.UpdateTime();
|
NetworkTimeSystem.UpdateTime();
|
||||||
|
AnticipationSystem.Update();
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case NetworkUpdateStage.PreLateUpdate:
|
||||||
|
{
|
||||||
|
// Non-physics based non-authority NetworkTransforms update their states after all other components
|
||||||
|
foreach (var networkObjectEntry in NetworkTransformUpdate)
|
||||||
|
{
|
||||||
|
// if not active or not spawned then skip
|
||||||
|
if (!networkObjectEntry.Value.gameObject.activeInHierarchy || !networkObjectEntry.Value.IsSpawned)
|
||||||
|
{
|
||||||
|
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;
|
break;
|
||||||
case NetworkUpdateStage.PostLateUpdate:
|
case NetworkUpdateStage.PostLateUpdate:
|
||||||
@@ -217,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.
|
// Metrics update needs to be driven by NetworkConnectionManager's update to assure metrics are dispatched after the send queue is processed.
|
||||||
MetricsManager.UpdateMetrics();
|
MetricsManager.UpdateMetrics();
|
||||||
|
|
||||||
|
// Handle sending any pending transport messages
|
||||||
|
NetworkConfig.NetworkTransport.PostLateUpdate();
|
||||||
|
|
||||||
// TODO: Determine a better way to handle this
|
// TODO: Determine a better way to handle this
|
||||||
NetworkObject.VerifyParentingStatus();
|
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.
|
// 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();
|
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)
|
if (m_ShuttingDown)
|
||||||
{
|
{
|
||||||
// Host-server will disconnect any connected clients prior to finalizing its shutdown
|
// Host-server will disconnect any connected clients prior to finalizing its shutdown
|
||||||
@@ -436,6 +624,25 @@ namespace Unity.Netcode
|
|||||||
remove => ConnectionManager.OnTransportFailure -= value;
|
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>
|
/// <summary>
|
||||||
/// The callback to invoke during connection approval. Allows client code to decide whether or not to allow incoming client connection
|
/// The callback to invoke during connection approval. Allows client code to decide whether or not to allow incoming client connection
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -680,6 +887,8 @@ namespace Unity.Netcode
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public NetworkTickSystem NetworkTickSystem { get; private set; }
|
public NetworkTickSystem NetworkTickSystem { get; private set; }
|
||||||
|
|
||||||
|
internal AnticipationSystem AnticipationSystem { get; private set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Used for time mocking in tests
|
/// Used for time mocking in tests
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -703,6 +912,7 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
internal Override<ushort> PortOverride;
|
internal Override<ushort> PortOverride;
|
||||||
|
|
||||||
|
|
||||||
#if UNITY_EDITOR
|
#if UNITY_EDITOR
|
||||||
internal static INetworkManagerHelper NetworkManagerHelper;
|
internal static INetworkManagerHelper NetworkManagerHelper;
|
||||||
|
|
||||||
@@ -724,6 +934,16 @@ namespace Unity.Netcode
|
|||||||
OnNetworkManagerReset?.Invoke(this);
|
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()
|
internal void OnValidate()
|
||||||
{
|
{
|
||||||
if (NetworkConfig == null)
|
if (NetworkConfig == null)
|
||||||
@@ -731,6 +951,9 @@ namespace Unity.Netcode
|
|||||||
return; // May occur when the component is added
|
return; // May occur when the component is added
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Do a validation pass on NetworkConfig properties
|
||||||
|
NetworkConfig.OnValidate();
|
||||||
|
|
||||||
if (GetComponentInChildren<NetworkObject>() != null)
|
if (GetComponentInChildren<NetworkObject>() != null)
|
||||||
{
|
{
|
||||||
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
|
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
|
||||||
@@ -784,14 +1007,22 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
OnValidateComponent();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Debug.LogException(ex);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ModeChanged(PlayModeStateChange change)
|
private void ModeChanged(PlayModeStateChange change)
|
||||||
{
|
{
|
||||||
if (IsListening && change == PlayModeStateChange.ExitingPlayMode)
|
if (IsListening && change == PlayModeStateChange.ExitingPlayMode)
|
||||||
{
|
{
|
||||||
// Make sure we are not holding onto anything in case domain reload is disabled
|
OnApplicationQuit();
|
||||||
ShutdownInternal();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
@@ -845,6 +1076,8 @@ namespace Unity.Netcode
|
|||||||
#if UNITY_EDITOR
|
#if UNITY_EDITOR
|
||||||
EditorApplication.playModeStateChanged += ModeChanged;
|
EditorApplication.playModeStateChanged += ModeChanged;
|
||||||
#endif
|
#endif
|
||||||
|
// Notify we have instantiated a new instance of NetworkManager.
|
||||||
|
OnInstantiated?.Invoke(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnEnable()
|
private void OnEnable()
|
||||||
@@ -942,9 +1175,25 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
internal void Initialize(bool server)
|
internal void Initialize(bool server)
|
||||||
{
|
{
|
||||||
|
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||||
|
if (!DisableNotOptimizedSerializedType)
|
||||||
|
{
|
||||||
|
s_SerializedType.Clear();
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
//DANGOEXP TODO: Remove this before finalizing the experimental release
|
#if COM_UNITY_MODULES_PHYSICS
|
||||||
NetworkConfig.AutoSpawnPlayerPrefabClientSide = DistributedAuthorityMode;
|
NetworkTransformFixedUpdate.Clear();
|
||||||
|
#endif
|
||||||
|
NetworkTransformUpdate.Clear();
|
||||||
|
|
||||||
|
UpdateTopology();
|
||||||
|
|
||||||
|
// Always create a default session config when starting a NetworkManager instance
|
||||||
|
if (DistributedAuthorityMode)
|
||||||
|
{
|
||||||
|
SessionConfig = GetSessionConfig();
|
||||||
|
}
|
||||||
|
|
||||||
// Make sure the ServerShutdownState is reset when initializing
|
// Make sure the ServerShutdownState is reset when initializing
|
||||||
if (server)
|
if (server)
|
||||||
@@ -978,7 +1227,12 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.RegisterNetworkUpdate(NetworkUpdateStage.EarlyUpdate);
|
this.RegisterNetworkUpdate(NetworkUpdateStage.EarlyUpdate);
|
||||||
|
#if COM_UNITY_MODULES_PHYSICS
|
||||||
|
this.RegisterNetworkUpdate(NetworkUpdateStage.FixedUpdate);
|
||||||
|
#endif
|
||||||
this.RegisterNetworkUpdate(NetworkUpdateStage.PreUpdate);
|
this.RegisterNetworkUpdate(NetworkUpdateStage.PreUpdate);
|
||||||
|
this.RegisterNetworkUpdate(NetworkUpdateStage.PostScriptLateUpdate);
|
||||||
|
this.RegisterNetworkUpdate(NetworkUpdateStage.PreLateUpdate);
|
||||||
this.RegisterNetworkUpdate(NetworkUpdateStage.PostLateUpdate);
|
this.RegisterNetworkUpdate(NetworkUpdateStage.PostLateUpdate);
|
||||||
|
|
||||||
// ComponentFactory needs to set its defaults next
|
// ComponentFactory needs to set its defaults next
|
||||||
@@ -994,11 +1248,17 @@ namespace Unity.Netcode
|
|||||||
MessageManager.Hook(new NetworkManagerHooks(this));
|
MessageManager.Hook(new NetworkManagerHooks(this));
|
||||||
|
|
||||||
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
#if DEVELOPMENT_BUILD || UNITY_EDITOR
|
||||||
MessageManager.Hook(new ProfilingHooks());
|
if (NetworkConfig.NetworkProfilingMetrics)
|
||||||
|
{
|
||||||
|
MessageManager.Hook(new ProfilingHooks());
|
||||||
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if MULTIPLAYER_TOOLS
|
#if MULTIPLAYER_TOOLS
|
||||||
MessageManager.Hook(new MetricHooks(this));
|
if (NetworkConfig.NetworkMessageMetrics)
|
||||||
|
{
|
||||||
|
MessageManager.Hook(new MetricHooks(this));
|
||||||
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Assures there is a server message queue available
|
// Assures there is a server message queue available
|
||||||
@@ -1011,6 +1271,7 @@ namespace Unity.Netcode
|
|||||||
// The remaining systems can then be initialized
|
// The remaining systems can then be initialized
|
||||||
NetworkTimeSystem = server ? NetworkTimeSystem.ServerTimeSystem() : new NetworkTimeSystem(1.0 / NetworkConfig.TickRate);
|
NetworkTimeSystem = server ? NetworkTimeSystem.ServerTimeSystem() : new NetworkTimeSystem(1.0 / NetworkConfig.TickRate);
|
||||||
NetworkTickSystem = NetworkTimeSystem.Initialize(this);
|
NetworkTickSystem = NetworkTimeSystem.Initialize(this);
|
||||||
|
AnticipationSystem = new AnticipationSystem(this);
|
||||||
|
|
||||||
// Create spawn manager instance
|
// Create spawn manager instance
|
||||||
SpawnManager = new NetworkSpawnManager(this);
|
SpawnManager = new NetworkSpawnManager(this);
|
||||||
@@ -1112,6 +1373,8 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
|
SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
|
||||||
|
|
||||||
|
// Notify the server that everything should be synchronized/spawned at this time.
|
||||||
|
SpawnManager.NotifyNetworkObjectsSynchronized();
|
||||||
OnServerStarted?.Invoke();
|
OnServerStarted?.Invoke();
|
||||||
ConnectionManager.LocalClient.IsApproved = true;
|
ConnectionManager.LocalClient.IsApproved = true;
|
||||||
return true;
|
return true;
|
||||||
@@ -1259,6 +1522,9 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
|
SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
|
||||||
|
|
||||||
|
// Notify the host that everything should be synchronized/spawned at this time.
|
||||||
|
SpawnManager.NotifyNetworkObjectsSynchronized();
|
||||||
|
|
||||||
OnServerStarted?.Invoke();
|
OnServerStarted?.Invoke();
|
||||||
OnClientStarted?.Invoke();
|
OnClientStarted?.Invoke();
|
||||||
|
|
||||||
@@ -1417,6 +1683,9 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
UnityEngine.SceneManagement.SceneManager.sceneUnloaded -= OnSceneUnloaded;
|
UnityEngine.SceneManagement.SceneManager.sceneUnloaded -= OnSceneUnloaded;
|
||||||
|
|
||||||
|
// Notify we are destroying NetworkManager
|
||||||
|
OnDestroying?.Invoke(this);
|
||||||
|
|
||||||
if (Singleton == this)
|
if (Singleton == this)
|
||||||
{
|
{
|
||||||
Singleton = null;
|
Singleton = null;
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ using System;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Runtime.CompilerServices;
|
using System.Runtime.CompilerServices;
|
||||||
|
using Unity.Netcode.Components;
|
||||||
#if UNITY_EDITOR
|
#if UNITY_EDITOR
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
#if UNITY_2021_2_OR_NEWER
|
#if UNITY_2021_2_OR_NEWER
|
||||||
@@ -14,6 +15,7 @@ using UnityEngine;
|
|||||||
using UnityEngine.SceneManagement;
|
using UnityEngine.SceneManagement;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
namespace Unity.Netcode
|
namespace Unity.Netcode
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -35,7 +37,7 @@ namespace Unity.Netcode
|
|||||||
internal uint PrefabGlobalObjectIdHash;
|
internal uint PrefabGlobalObjectIdHash;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// This is the source prefab of an in-scene placed NetworkObject. This is not set for in-scene
|
/// This is the source prefab of an in-scene placed NetworkObject. This is not set for in-scene
|
||||||
/// placd NetworkObjects that are not prefab instances, dynamically spawned prefab instances,
|
/// placd NetworkObjects that are not prefab instances, dynamically spawned prefab instances,
|
||||||
/// or for network prefab assets.
|
/// or for network prefab assets.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -55,6 +57,35 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// All <see cref="NetworkTransform"></see> component instances associated with a <see cref="NetworkObject"/> component instance.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// When parented, all child <see cref="NetworkTransform"/> component instances under a <see cref="NetworkObject"/> component instance that do not have
|
||||||
|
/// another <see cref="NetworkObject"/> component instance will be associated with the initial component instance. This list does not contain any parented
|
||||||
|
/// children <see cref="NetworkObject"/> instances with one or more <see cref="NetworkTransform"/> component instance(s).
|
||||||
|
/// </remarks>
|
||||||
|
public List<NetworkTransform> NetworkTransforms { get; private set; }
|
||||||
|
|
||||||
|
|
||||||
|
#if COM_UNITY_MODULES_PHYSICS
|
||||||
|
/// <summary>
|
||||||
|
/// All <see cref="NetworkRigidbodyBase"></see> component instances associated with a <see cref="NetworkObject"/> component instance.
|
||||||
|
/// NOTE: This is only available if a physics package is included. If not, then this will not be available!
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// When parented, all child <see cref="NetworkRigidbodyBase"/> component instances under a <see cref="NetworkObject"/> component instance that do not have
|
||||||
|
/// another <see cref="NetworkObject"/> component instance will be associated with the initial component instance. This list does not contain any parented
|
||||||
|
/// child <see cref="NetworkObject"/> instances with one or more <see cref="NetworkTransform"/> component instance(s).
|
||||||
|
/// </remarks>
|
||||||
|
public List<NetworkRigidbodyBase> NetworkRigidbodies { get; private set; }
|
||||||
|
#endif
|
||||||
|
/// <summary>
|
||||||
|
/// The current parent <see cref="NetworkObject"/> component instance to this <see cref="NetworkObject"/> component instance. When there is no parent then
|
||||||
|
/// this will be <see cref="null"/>.
|
||||||
|
/// </summary>
|
||||||
|
public NetworkObject CurrentParent { get; private set; }
|
||||||
|
|
||||||
#if UNITY_EDITOR
|
#if UNITY_EDITOR
|
||||||
private const string k_GlobalIdTemplate = "GlobalObjectId_V1-{0}-{1}-{2}-{3}";
|
private const string k_GlobalIdTemplate = "GlobalObjectId_V1-{0}-{1}-{2}-{3}";
|
||||||
|
|
||||||
@@ -71,10 +102,22 @@ namespace Unity.Netcode
|
|||||||
private const int k_SceneObjectType = 2;
|
private const int k_SceneObjectType = 2;
|
||||||
private const int k_SourceAssetObjectType = 3;
|
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")]
|
[ContextMenu("Refresh In-Scene Prefab Instances")]
|
||||||
internal void RefreshAllPrefabInstances()
|
internal void RefreshAllPrefabInstances()
|
||||||
{
|
{
|
||||||
var instanceGlobalId = GlobalObjectId.GetGlobalObjectIdSlow(this);
|
var instanceGlobalId = GlobalObjectId.GetGlobalObjectIdSlow(this);
|
||||||
|
// Assign the currently selected instance to be updated
|
||||||
|
NetworkObjectRefreshTool.PrefabNetworkObject = this;
|
||||||
if (!PrefabUtility.IsPartOfAnyPrefab(this) || instanceGlobalId.identifierType != k_ImportedAssetObjectType)
|
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");
|
EditorUtility.DisplayDialog("Network Prefab Assets Only", "This action can only be performed on a network prefab asset.", "Ok");
|
||||||
@@ -82,11 +125,6 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Handle updating the currently active scene
|
// Handle updating the currently active scene
|
||||||
var networkObjects = FindObjectsByType<NetworkObject>(FindObjectsInactive.Include, FindObjectsSortMode.None);
|
|
||||||
foreach (var networkObject in networkObjects)
|
|
||||||
{
|
|
||||||
networkObject.OnValidate();
|
|
||||||
}
|
|
||||||
NetworkObjectRefreshTool.ProcessActiveScene();
|
NetworkObjectRefreshTool.ProcessActiveScene();
|
||||||
|
|
||||||
// Refresh all build settings scenes
|
// Refresh all build settings scenes
|
||||||
@@ -99,32 +137,126 @@ namespace Unity.Netcode
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
// Add the scene to be processed
|
// Add the scene to be processed
|
||||||
NetworkObjectRefreshTool.ProcessScene(editorScene.path, false);
|
NetworkObjectRefreshTool.ProcessScene(editorScene.path, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Process all added scenes
|
// Process all added scenes
|
||||||
NetworkObjectRefreshTool.ProcessScenes();
|
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))
|
if (EditorApplication.isPlaying && !string.IsNullOrEmpty(gameObject.scene.name))
|
||||||
{
|
{
|
||||||
return;
|
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)
|
if (!EditorApplication.isPlaying && EditorApplication.isPlayingOrWillChangePlaymode)
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get a global object identifier for this network prefab
|
// Get a global object identifier for this network prefab.
|
||||||
var globalId = GetGlobalId();
|
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)
|
if (globalId.identifierType == k_NullObjectType)
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
@@ -133,64 +265,50 @@ namespace Unity.Netcode
|
|||||||
var oldValue = GlobalObjectIdHash;
|
var oldValue = GlobalObjectIdHash;
|
||||||
GlobalObjectIdHash = globalId.ToString().Hash32();
|
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)
|
if (GlobalObjectIdHash != oldValue)
|
||||||
{
|
{
|
||||||
// Check if this is an in-scnee placed NetworkObject (Special Case for In-Scene Placed)
|
// 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)
|
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)
|
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**");
|
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))
|
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);
|
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);
|
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>
|
/// <summary>
|
||||||
/// This checks to see if this NetworkObject is an in-scene placed prefab instance. If so it will
|
/// This checks to see if this NetworkObject is an in-scene placed prefab instance. If so it will
|
||||||
/// automatically find the source prefab asset's GlobalObjectIdHash value, assign it to
|
/// automatically find the source prefab asset's GlobalObjectIdHash value, assign it to
|
||||||
/// InScenePlacedSourceGlobalObjectIdHash and mark this as being in-scene placed.
|
/// InScenePlacedSourceGlobalObjectIdHash and mark this as being in-scene placed.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <remarks>
|
/// <remarks>
|
||||||
/// This NetworkObject is considered an in-scene placed prefab asset instance if it is:
|
/// This NetworkObject is considered an in-scene placed prefab asset instance if it is:
|
||||||
/// - Part of a prefab
|
/// - Part of a prefab
|
||||||
/// - Not being directly edited
|
|
||||||
/// - Within a valid scene that is part of the scenes in build list
|
/// - 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.)
|
/// (In-scene defined NetworkObjects that are not part of a prefab instance are excluded.)
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
private void CheckForInScenePlaced()
|
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 prefab = PrefabUtility.GetCorrespondingObjectFromSource(gameObject);
|
||||||
var assetPath = AssetDatabase.GetAssetPath(prefab);
|
var assetPath = AssetDatabase.GetAssetPath(prefab);
|
||||||
@@ -198,59 +316,11 @@ namespace Unity.Netcode
|
|||||||
if (sourceAsset != null && sourceAsset.GlobalObjectIdHash != 0 && InScenePlacedSourceGlobalObjectIdHash != sourceAsset.GlobalObjectIdHash)
|
if (sourceAsset != null && sourceAsset.GlobalObjectIdHash != 0 && InScenePlacedSourceGlobalObjectIdHash != sourceAsset.GlobalObjectIdHash)
|
||||||
{
|
{
|
||||||
InScenePlacedSourceGlobalObjectIdHash = sourceAsset.GlobalObjectIdHash;
|
InScenePlacedSourceGlobalObjectIdHash = sourceAsset.GlobalObjectIdHash;
|
||||||
|
EditorUtility.SetDirty(this);
|
||||||
}
|
}
|
||||||
IsSceneObject = true;
|
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
|
#endif // UNITY_EDITOR
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -309,7 +379,7 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
if (!HasAuthority)
|
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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -369,6 +439,13 @@ namespace Unity.Netcode
|
|||||||
/// </remarks>
|
/// </remarks>
|
||||||
public bool IsOwnershipDistributable => Ownership.HasFlag(OwnershipStatus.Distributable);
|
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>
|
/// <summary>
|
||||||
/// Returns true if the <see cref="NetworkObject"/> is has ownership locked.
|
/// 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.
|
/// When locked, the <see cref="NetworkObject"/> cannot be redistributed nor can it be transferred by another client.
|
||||||
@@ -398,8 +475,11 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Determines whether a NetworkObject can be distributed to other clients during
|
/// Determines whether a NetworkObject can be distributed to other clients during
|
||||||
/// a <see cref="SessionModeTypes.DistributedAuthority"/> session.
|
/// a <see cref="NetworkTopologyTypes.DistributedAuthority"/> session.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
#if !MULTIPLAYER_SERVICES_SDK_INSTALLED
|
||||||
|
[HideInInspector]
|
||||||
|
#endif
|
||||||
[SerializeField]
|
[SerializeField]
|
||||||
internal OwnershipStatus Ownership = OwnershipStatus.Distributable;
|
internal OwnershipStatus Ownership = OwnershipStatus.Distributable;
|
||||||
|
|
||||||
@@ -408,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="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="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="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>
|
/// </summary>
|
||||||
// Ranges from 1 to 8 bits
|
// Ranges from 1 to 8 bits
|
||||||
[Flags]
|
[Flags]
|
||||||
@@ -418,6 +499,7 @@ namespace Unity.Netcode
|
|||||||
Distributable = 1 << 0,
|
Distributable = 1 << 0,
|
||||||
Transferable = 1 << 1,
|
Transferable = 1 << 1,
|
||||||
RequestRequired = 1 << 2,
|
RequestRequired = 1 << 2,
|
||||||
|
SessionOwner = 1 << 3,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -476,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 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!");
|
NetworkLog.LogWarning($"Trying to add or remove ownership lock on [{name}] which does not have the {nameof(OwnershipStatus.Transferable)} flag set!");
|
||||||
return false;
|
return false;
|
||||||
@@ -507,15 +589,17 @@ namespace Unity.Netcode
|
|||||||
/// permission failure status codes will be returned via <see cref="OnOwnershipPermissionsFailure"/>.
|
/// 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="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="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="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="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>
|
/// </summary>
|
||||||
public enum OwnershipPermissionsFailureStatus
|
public enum OwnershipPermissionsFailureStatus
|
||||||
{
|
{
|
||||||
Locked,
|
Locked,
|
||||||
RequestRequired,
|
RequestRequired,
|
||||||
RequestInProgress,
|
RequestInProgress,
|
||||||
NotTransferrable
|
NotTransferrable,
|
||||||
|
SessionOwnerOnly
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -537,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="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="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="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.
|
/// a change in ownership or just try again after a specific period of time or no longer attempt to request ownership.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public enum OwnershipRequestStatus
|
public enum OwnershipRequestStatus
|
||||||
@@ -546,6 +631,7 @@ namespace Unity.Netcode
|
|||||||
RequestRequiredNotSet,
|
RequestRequiredNotSet,
|
||||||
Locked,
|
Locked,
|
||||||
RequestInProgress,
|
RequestInProgress,
|
||||||
|
SessionOwnerOnly,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -558,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.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.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.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.
|
/// a change in ownership or just try again after a specific period of time or no longer attempt to request ownership.
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
/// <returns><see cref="OwnershipRequestStatus"/></returns>
|
/// <returns><see cref="OwnershipRequestStatus"/></returns>
|
||||||
@@ -587,6 +674,12 @@ namespace Unity.Netcode
|
|||||||
return OwnershipRequestStatus.RequestInProgress;
|
return OwnershipRequestStatus.RequestInProgress;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Exit early if it has the SessionOwner flag
|
||||||
|
if (IsOwnershipSessionOwner)
|
||||||
|
{
|
||||||
|
return OwnershipRequestStatus.SessionOwnerOnly;
|
||||||
|
}
|
||||||
|
|
||||||
// Otherwise, send the request ownership message
|
// Otherwise, send the request ownership message
|
||||||
var changeOwnership = new ChangeOwnershipMessage
|
var changeOwnership = new ChangeOwnershipMessage
|
||||||
{
|
{
|
||||||
@@ -643,7 +736,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
response = OwnershipRequestResponseStatus.RequestInProgress;
|
response = OwnershipRequestResponseStatus.RequestInProgress;
|
||||||
}
|
}
|
||||||
else if (!IsOwnershipRequestRequired && !IsOwnershipTransferable)
|
else if (!(IsOwnershipRequestRequired || IsOwnershipTransferable) || IsOwnershipSessionOwner)
|
||||||
{
|
{
|
||||||
response = OwnershipRequestResponseStatus.CannotRequest;
|
response = OwnershipRequestResponseStatus.CannotRequest;
|
||||||
}
|
}
|
||||||
@@ -763,6 +856,12 @@ namespace Unity.Netcode
|
|||||||
/// </remarks>
|
/// </remarks>
|
||||||
public bool SetOwnershipStatus(OwnershipStatus status, bool clearAndSet = false, OwnershipLockActions lockAction = OwnershipLockActions.None)
|
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 it already has the flag do nothing
|
||||||
if (!clearAndSet && Ownership.HasFlag(status))
|
if (!clearAndSet && Ownership.HasFlag(status))
|
||||||
{
|
{
|
||||||
@@ -774,13 +873,25 @@ namespace Unity.Netcode
|
|||||||
Ownership = OwnershipStatus.None;
|
Ownership = OwnershipStatus.None;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Faster to just OR a None status than to check
|
if (status.HasFlag(OwnershipStatus.SessionOwner))
|
||||||
// if it is !None before "OR'ing".
|
|
||||||
Ownership |= status;
|
|
||||||
|
|
||||||
if (lockAction != OwnershipLockActions.None)
|
|
||||||
{
|
{
|
||||||
SetOwnershipLock(lockAction == OwnershipLockActions.SetAndLock);
|
Ownership = OwnershipStatus.SessionOwner;
|
||||||
|
}
|
||||||
|
else if (Ownership.HasFlag(OwnershipStatus.SessionOwner))
|
||||||
|
{
|
||||||
|
NetworkLog.LogWarning("No other ownership statuses may be set while SessionOwner is set.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Faster to just OR a None status than to check
|
||||||
|
// if it is !None before "OR'ing".
|
||||||
|
Ownership |= status;
|
||||||
|
|
||||||
|
if (lockAction != OwnershipLockActions.None)
|
||||||
|
{
|
||||||
|
SetOwnershipLock(lockAction == OwnershipLockActions.SetAndLock);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
SendOwnershipStatusUpdate();
|
SendOwnershipStatusUpdate();
|
||||||
@@ -904,6 +1015,7 @@ namespace Unity.Netcode
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// If true, the object will always be replicated as root on clients and the parent will be ignored.
|
/// If true, the object will always be replicated as root on clients and the parent will be ignored.
|
||||||
/// </summary>
|
/// </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;
|
public bool AlwaysReplicateAsRoot;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -921,6 +1033,8 @@ namespace Unity.Netcode
|
|||||||
/// bandwidth cost. This can also be useful for UI elements that have
|
/// bandwidth cost. This can also be useful for UI elements that have
|
||||||
/// a predetermined fixed position.
|
/// a predetermined fixed position.
|
||||||
/// </remarks>
|
/// </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;
|
public bool SynchronizeTransform = true;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -978,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)"/>,
|
/// 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).
|
/// make sure <see cref="SceneMigrationSynchronization"/> is enabled (it is by default).
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
|
[Tooltip("When enabled (default disabled), spawned instances of this NetworkObject will automatically migrate to any newly assigned active scene.")]
|
||||||
public bool ActiveSceneSynchronization;
|
public bool ActiveSceneSynchronization;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -996,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
|
/// 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.
|
/// active scene, then the <see cref="NetworkObject"/> will be destroyed.
|
||||||
/// </remarks>
|
/// </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;
|
public bool SceneMigrationSynchronization = true;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -1011,7 +1127,7 @@ namespace Unity.Netcode
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// When set to false, the NetworkObject will be spawned with no observers initially (other than the server)
|
/// When set to false, the NetworkObject will be spawned with no observers initially (other than the server)
|
||||||
/// </summary>
|
/// </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;
|
public bool SpawnWithObservers = true;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -1040,13 +1156,35 @@ namespace Unity.Netcode
|
|||||||
/// Whether or not to destroy this object if it's owner is destroyed.
|
/// Whether or not to destroy this object if it's owner is destroyed.
|
||||||
/// If true, the objects ownership will be given to the server.
|
/// If true, the objects ownership will be given to the server.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
[Tooltip("When enabled (default disabled), instances of this NetworkObject will not be destroyed if the owning client disconnects.")]
|
||||||
public bool DontDestroyWithOwner;
|
public bool DontDestroyWithOwner;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Whether or not to enable automatic NetworkObject parent synchronization.
|
/// Whether or not to enable automatic NetworkObject parent synchronization.
|
||||||
/// </summary>
|
/// </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;
|
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>();
|
internal readonly HashSet<ulong> Observers = new HashSet<ulong>();
|
||||||
|
|
||||||
#if MULTIPLAYER_TOOLS
|
#if MULTIPLAYER_TOOLS
|
||||||
@@ -1514,6 +1652,11 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
if (NetworkManager.DistributedAuthorityMode)
|
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)
|
if (NetworkManager.NetworkConfig.EnableSceneManagement)
|
||||||
{
|
{
|
||||||
NetworkSceneHandle = NetworkManager.SceneManager.ClientSceneHandleToServerSceneHandle[gameObject.scene.handle];
|
NetworkSceneHandle = NetworkManager.SceneManager.ClientSceneHandleToServerSceneHandle[gameObject.scene.handle];
|
||||||
@@ -1524,7 +1667,7 @@ namespace Unity.Netcode
|
|||||||
// DANGO-TODO: Review over don't destroy with owner being set but DistributeOwnership not being set
|
// DANGO-TODO: Review over don't destroy with owner being set but DistributeOwnership not being set
|
||||||
if (NetworkManager.LogLevel == LogLevel.Developer)
|
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.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1547,7 +1690,12 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
else if (NetworkManager.DistributedAuthorityMode && !NetworkManager.DAHost)
|
else if (NetworkManager.DistributedAuthorityMode && !NetworkManager.DAHost)
|
||||||
{
|
{
|
||||||
NetworkManager.SpawnManager.SendSpawnCallForObject(NetworkManager.ServerClientId, this);
|
// If spawning with observers or if not spawning with observers but the observer count is greater than 1 (i.e. owner/authority creating),
|
||||||
|
// then we want to send a spawn notification.
|
||||||
|
if (SpawnWithObservers || !SpawnWithObservers && Observers.Count > 1)
|
||||||
|
{
|
||||||
|
NetworkManager.SpawnManager.SendSpawnCallForObject(NetworkManager.ServerClientId, this);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -1605,7 +1753,7 @@ namespace Unity.Netcode
|
|||||||
return null;
|
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
|
// We only need to check for authority when running in client-server mode
|
||||||
if (!networkManager.IsServer && !networkManager.DistributedAuthorityMode)
|
if (!networkManager.IsServer && !networkManager.DistributedAuthorityMode)
|
||||||
{
|
{
|
||||||
@@ -1749,6 +1897,9 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
|
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
|
||||||
{
|
{
|
||||||
|
// Invoke internal notification
|
||||||
|
ChildNetworkBehaviours[i].InternalOnNetworkObjectParentChanged(parentNetworkObject);
|
||||||
|
// Invoke public notification
|
||||||
ChildNetworkBehaviours[i].OnNetworkObjectParentChanged(parentNetworkObject);
|
ChildNetworkBehaviours[i].OnNetworkObjectParentChanged(parentNetworkObject);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1880,7 +2031,7 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
// DANGO-TODO: Do we want to worry about ownership permissions here?
|
// 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.
|
// 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 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.
|
// If we are shutting down and don't have authority then allow it.
|
||||||
@@ -1894,23 +2045,26 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
internal bool InternalTrySetParent(NetworkObject parent, bool worldPositionStays = true)
|
internal bool InternalTrySetParent(NetworkObject parent, bool worldPositionStays = true)
|
||||||
{
|
{
|
||||||
|
if (parent != null && (IsSpawned ^ parent.IsSpawned) && NetworkManager != null && !NetworkManager.ShutdownInProgress)
|
||||||
if (parent != null && (IsSpawned ^ parent.IsSpawned))
|
|
||||||
{
|
{
|
||||||
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;
|
m_CachedWorldPositionStays = worldPositionStays;
|
||||||
|
|
||||||
if (parent == null)
|
if (parent == null)
|
||||||
{
|
{
|
||||||
|
CurrentParent = null;
|
||||||
transform.SetParent(null, worldPositionStays);
|
transform.SetParent(null, worldPositionStays);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
CurrentParent = parent;
|
||||||
transform.SetParent(parent.transform, worldPositionStays);
|
transform.SetParent(parent.transform, worldPositionStays);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1945,7 +2099,7 @@ namespace Unity.Netcode
|
|||||||
var isAuthority = false;
|
var isAuthority = false;
|
||||||
// With distributed authority, we need to track "valid authoritative" parenting changes.
|
// With distributed authority, we need to track "valid authoritative" parenting changes.
|
||||||
// So, either the authority or AuthorityAppliedParenting is considered a "valid parenting change".
|
// So, either the authority or AuthorityAppliedParenting is considered a "valid parenting change".
|
||||||
isAuthority = HasAuthority || AuthorityAppliedParenting;
|
isAuthority = HasAuthority || AuthorityAppliedParenting || (AllowOwnerToParent && IsOwner);
|
||||||
var distributedAuthority = NetworkManager.DistributedAuthorityMode;
|
var distributedAuthority = NetworkManager.DistributedAuthorityMode;
|
||||||
|
|
||||||
// If we do not have authority and we are spawned
|
// If we do not have authority and we are spawned
|
||||||
@@ -2037,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 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)
|
if (!NetworkManager.DAHost)
|
||||||
{
|
{
|
||||||
@@ -2209,6 +2363,18 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal void InvokeBehaviourNetworkPreSpawn()
|
||||||
|
{
|
||||||
|
var networkManager = NetworkManager;
|
||||||
|
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
|
||||||
|
{
|
||||||
|
if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy)
|
||||||
|
{
|
||||||
|
ChildNetworkBehaviours[i].NetworkPreSpawn(ref networkManager);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
internal void InvokeBehaviourNetworkSpawn()
|
internal void InvokeBehaviourNetworkSpawn()
|
||||||
{
|
{
|
||||||
NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId);
|
NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId);
|
||||||
@@ -2238,6 +2404,42 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal void InvokeBehaviourNetworkPostSpawn()
|
||||||
|
{
|
||||||
|
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
|
||||||
|
{
|
||||||
|
if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy)
|
||||||
|
{
|
||||||
|
ChildNetworkBehaviours[i].NetworkPostSpawn();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
internal void InternalNetworkSessionSynchronized()
|
||||||
|
{
|
||||||
|
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
|
||||||
|
{
|
||||||
|
if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy)
|
||||||
|
{
|
||||||
|
ChildNetworkBehaviours[i].NetworkSessionSynchronized();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal void InternalInSceneNetworkObjectsSpawned()
|
||||||
|
{
|
||||||
|
for (int i = 0; i < ChildNetworkBehaviours.Count; i++)
|
||||||
|
{
|
||||||
|
if (ChildNetworkBehaviours[i].gameObject.activeInHierarchy)
|
||||||
|
{
|
||||||
|
ChildNetworkBehaviours[i].InSceneNetworkObjectsSpawned();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
internal void InvokeBehaviourNetworkDespawn()
|
internal void InvokeBehaviourNetworkDespawn()
|
||||||
{
|
{
|
||||||
NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId, true);
|
NetworkManager.SpawnManager.UpdateOwnershipTable(this, OwnerClientId, true);
|
||||||
@@ -2271,6 +2473,27 @@ namespace Unity.Netcode
|
|||||||
if (networkBehaviours[i].NetworkObject == this)
|
if (networkBehaviours[i].NetworkObject == this)
|
||||||
{
|
{
|
||||||
m_ChildNetworkBehaviours.Add(networkBehaviours[i]);
|
m_ChildNetworkBehaviours.Add(networkBehaviours[i]);
|
||||||
|
var type = networkBehaviours[i].GetType();
|
||||||
|
if (type == typeof(NetworkTransform) || type.IsInstanceOfType(typeof(NetworkTransform)) || type.IsSubclassOf(typeof(NetworkTransform)))
|
||||||
|
{
|
||||||
|
if (NetworkTransforms == null)
|
||||||
|
{
|
||||||
|
NetworkTransforms = new List<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)))
|
||||||
|
{
|
||||||
|
if (NetworkRigidbodies == null)
|
||||||
|
{
|
||||||
|
NetworkRigidbodies = new List<NetworkRigidbodyBase>();
|
||||||
|
}
|
||||||
|
NetworkRigidbodies.Add(networkBehaviours[i] as NetworkRigidbodyBase);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2305,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.
|
// 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
|
// 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
|
// resolved when their parents arrived. Because we don't send a partial list of spawns (yet), something
|
||||||
@@ -2335,10 +2566,10 @@ namespace Unity.Netcode
|
|||||||
if (NetworkManager.DistributedAuthorityMode)
|
if (NetworkManager.DistributedAuthorityMode)
|
||||||
{
|
{
|
||||||
var readerPosition = reader.Position;
|
var readerPosition = reader.Position;
|
||||||
reader.ReadValueSafe(out ushort behaviorCount);
|
reader.ReadValueSafe(out ushort behaviourCount);
|
||||||
if (behaviorCount != ChildNetworkBehaviours.Count)
|
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;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2631,11 +2862,11 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal void PostNetworkVariableWrite()
|
internal void PostNetworkVariableWrite(bool forced = false)
|
||||||
{
|
{
|
||||||
for (int k = 0; k < ChildNetworkBehaviours.Count; k++)
|
for (int k = 0; k < ChildNetworkBehaviours.Count; k++)
|
||||||
{
|
{
|
||||||
ChildNetworkBehaviours[k].PostNetworkVariableWrite();
|
ChildNetworkBehaviours[k].PostNetworkVariableWrite(forced);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2744,7 +2975,7 @@ namespace Unity.Netcode
|
|||||||
SyncObservers = syncObservers,
|
SyncObservers = syncObservers,
|
||||||
Observers = syncObservers ? Observers.ToArray() : null,
|
Observers = syncObservers ? Observers.ToArray() : null,
|
||||||
NetworkSceneHandle = NetworkSceneHandle,
|
NetworkSceneHandle = NetworkSceneHandle,
|
||||||
Hash = HostCheckForGlobalObjectIdHashOverride(),
|
Hash = CheckForGlobalObjectIdHashOverride(),
|
||||||
OwnerObject = this,
|
OwnerObject = this,
|
||||||
TargetClientId = targetClientId
|
TargetClientId = targetClientId
|
||||||
};
|
};
|
||||||
@@ -2862,6 +3093,9 @@ namespace Unity.Netcode
|
|||||||
// in order to be able to determine which NetworkVariables the client will be allowed to read.
|
// in order to be able to determine which NetworkVariables the client will be allowed to read.
|
||||||
networkObject.OwnerClientId = sceneObject.OwnerClientId;
|
networkObject.OwnerClientId = sceneObject.OwnerClientId;
|
||||||
|
|
||||||
|
// Special Case: Invoke NetworkBehaviour.OnPreSpawn methods here before SynchronizeNetworkBehaviours
|
||||||
|
networkObject.InvokeBehaviourNetworkPreSpawn();
|
||||||
|
|
||||||
// Synchronize NetworkBehaviours
|
// Synchronize NetworkBehaviours
|
||||||
var bufferSerializer = new BufferSerializer<BufferSerializerReader>(new BufferSerializerReader(reader));
|
var bufferSerializer = new BufferSerializer<BufferSerializerReader>(new BufferSerializerReader(reader));
|
||||||
networkObject.SynchronizeNetworkBehaviours(ref bufferSerializer, networkManager.LocalClientId);
|
networkObject.SynchronizeNetworkBehaviours(ref bufferSerializer, networkManager.LocalClientId);
|
||||||
@@ -2911,10 +3145,15 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add all known players to the observers list if they don't already exist
|
// Only add all other players as observers if we are spawning with observers,
|
||||||
foreach (var player in networkManager.SpawnManager.PlayerObjects)
|
// otherwise user controls via NetworkShow.
|
||||||
|
if (networkObject.SpawnWithObservers)
|
||||||
{
|
{
|
||||||
networkObject.Observers.Add(player.OwnerClientId);
|
// Add all known players to the observers list if they don't already exist
|
||||||
|
foreach (var player in networkManager.SpawnManager.PlayerObjects)
|
||||||
|
{
|
||||||
|
networkObject.Observers.Add(player.OwnerClientId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3051,6 +3290,11 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
private void Awake()
|
private void Awake()
|
||||||
{
|
{
|
||||||
|
m_ChildNetworkBehaviours = null;
|
||||||
|
NetworkTransforms?.Clear();
|
||||||
|
#if COM_UNITY_MODULES_PHYSICS
|
||||||
|
NetworkRigidbodies?.Clear();
|
||||||
|
#endif
|
||||||
SetCachedParent(transform.parent);
|
SetCachedParent(transform.parent);
|
||||||
SceneOrigin = gameObject.scene;
|
SceneOrigin = gameObject.scene;
|
||||||
}
|
}
|
||||||
@@ -3083,14 +3327,15 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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.
|
/// Will return the registered source NetworkPrefab's GlobalObjectIdHash if one exists.
|
||||||
/// Server and Clients will always return the NetworkObject's GlobalObjectIdHash.
|
/// Server and Clients will always return the NetworkObject's GlobalObjectIdHash.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns>appropriate hash value</returns>
|
||||||
internal uint HostCheckForGlobalObjectIdHashOverride()
|
internal uint CheckForGlobalObjectIdHashOverride()
|
||||||
{
|
{
|
||||||
if (NetworkManager.IsServer)
|
if (NetworkManager.IsServer || NetworkManager.DistributedAuthorityMode)
|
||||||
{
|
{
|
||||||
if (NetworkManager.PrefabHandler.ContainsHandler(this))
|
if (NetworkManager.PrefabHandler.ContainsHandler(this))
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using UnityEditor;
|
||||||
using UnityEditor.SceneManagement;
|
using UnityEditor.SceneManagement;
|
||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
using UnityEngine.SceneManagement;
|
using UnityEngine.SceneManagement;
|
||||||
@@ -9,7 +11,7 @@ using UnityEngine.SceneManagement;
|
|||||||
namespace Unity.Netcode
|
namespace Unity.Netcode
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// This is a helper tool to update all in-scene placed instances of a prefab that
|
/// This is a helper tool to update all in-scene placed instances of a prefab that
|
||||||
/// originally did not have a NetworkObject component but one was added to the prefab
|
/// originally did not have a NetworkObject component but one was added to the prefab
|
||||||
/// later.
|
/// later.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -21,6 +23,28 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
internal static Action AllScenesProcessed;
|
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)
|
internal static void ProcessScene(string scenePath, bool processScenes = true)
|
||||||
{
|
{
|
||||||
if (!s_ScenesToUpdate.Contains(scenePath))
|
if (!s_ScenesToUpdate.Contains(scenePath))
|
||||||
@@ -29,7 +53,10 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
EditorSceneManager.sceneOpened += EditorSceneManager_sceneOpened;
|
EditorSceneManager.sceneOpened += EditorSceneManager_sceneOpened;
|
||||||
EditorSceneManager.sceneSaved += EditorSceneManager_sceneSaved;
|
EditorSceneManager.sceneSaved += EditorSceneManager_sceneSaved;
|
||||||
|
s_Log.Clear();
|
||||||
|
LogInfo("NetworkObject Refresh Scenes to Process:");
|
||||||
}
|
}
|
||||||
|
LogInfo($"[{scenePath}]", true);
|
||||||
s_ScenesToUpdate.Add(scenePath);
|
s_ScenesToUpdate.Add(scenePath);
|
||||||
}
|
}
|
||||||
s_ProcessScenes = processScenes;
|
s_ProcessScenes = processScenes;
|
||||||
@@ -37,6 +64,7 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
internal static void ProcessActiveScene()
|
internal static void ProcessActiveScene()
|
||||||
{
|
{
|
||||||
|
FlushLog();
|
||||||
var activeScene = SceneManager.GetActiveScene();
|
var activeScene = SceneManager.GetActiveScene();
|
||||||
if (s_ScenesToUpdate.Contains(activeScene.path) && s_ProcessScenes)
|
if (s_ScenesToUpdate.Contains(activeScene.path) && s_ProcessScenes)
|
||||||
{
|
{
|
||||||
@@ -54,10 +82,12 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
s_ProcessScenes = false;
|
||||||
s_CloseScenes = false;
|
s_CloseScenes = false;
|
||||||
EditorSceneManager.sceneSaved -= EditorSceneManager_sceneSaved;
|
EditorSceneManager.sceneSaved -= EditorSceneManager_sceneSaved;
|
||||||
EditorSceneManager.sceneOpened -= EditorSceneManager_sceneOpened;
|
EditorSceneManager.sceneOpened -= EditorSceneManager_sceneOpened;
|
||||||
AllScenesProcessed?.Invoke();
|
AllScenesProcessed?.Invoke();
|
||||||
|
FlushLog();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,9 +98,8 @@ namespace Unity.Netcode
|
|||||||
// Provide a log of all scenes that were modified to the user
|
// Provide a log of all scenes that were modified to the user
|
||||||
if (refreshed)
|
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);
|
s_ScenesToUpdate.Remove(scene.path);
|
||||||
|
|
||||||
if (scene != SceneManager.GetActiveScene())
|
if (scene != SceneManager.GetActiveScene())
|
||||||
@@ -88,24 +117,41 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
private static void SceneOpened(Scene scene)
|
private static void SceneOpened(Scene scene)
|
||||||
{
|
{
|
||||||
|
LogInfo($"Processing scene {scene.name}:");
|
||||||
if (s_ScenesToUpdate.Contains(scene.path))
|
if (s_ScenesToUpdate.Contains(scene.path))
|
||||||
{
|
{
|
||||||
if (s_ProcessScenes)
|
if (s_ProcessScenes)
|
||||||
{
|
{
|
||||||
if (!EditorSceneManager.MarkSceneDirty(scene))
|
var prefabInstances = PrefabUtility.FindAllInstancesOfPrefab(PrefabNetworkObject.gameObject);
|
||||||
|
|
||||||
|
if (prefabInstances.Length > 0)
|
||||||
{
|
{
|
||||||
Debug.Log($"Scene {scene.name} did not get marked as dirty!");
|
var instancesSceneLoadedSpecific = prefabInstances.Where((c) => c.scene == scene).ToList();
|
||||||
FinishedProcessingScene(scene);
|
|
||||||
}
|
if (instancesSceneLoadedSpecific.Count > 0)
|
||||||
else
|
{
|
||||||
{
|
foreach (var prefabInstance in instancesSceneLoadedSpecific)
|
||||||
EditorSceneManager.SaveScene(scene);
|
{
|
||||||
|
prefabInstance.GetComponent<NetworkObject>().OnValidate();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!EditorSceneManager.MarkSceneDirty(scene))
|
||||||
|
{
|
||||||
|
LogInfo($"Scene {scene.name} did not get marked as dirty!");
|
||||||
|
FinishedProcessingScene(scene);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
LogInfo($"Changes detected and applied!");
|
||||||
|
EditorSceneManager.SaveScene(scene);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
|
||||||
{
|
LogInfo($"No changes required.");
|
||||||
FinishedProcessingScene(scene);
|
FinishedProcessingScene(scene);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -54,6 +54,12 @@ namespace Unity.Netcode
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
PreLateUpdate = 6,
|
PreLateUpdate = 6,
|
||||||
/// <summary>
|
/// <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
|
/// Updated after the Monobehaviour.LateUpdate for all components is invoked
|
||||||
/// </summary>
|
/// </summary>
|
||||||
PostLateUpdate = 7
|
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
|
internal struct NetworkPostLateUpdate
|
||||||
{
|
{
|
||||||
public static PlayerLoopSystem CreateLoopSystem()
|
public static PlayerLoopSystem CreateLoopSystem()
|
||||||
@@ -399,6 +417,7 @@ namespace Unity.Netcode
|
|||||||
else if (currentSystem.type == typeof(PreLateUpdate))
|
else if (currentSystem.type == typeof(PreLateUpdate))
|
||||||
{
|
{
|
||||||
TryAddLoopSystem(ref currentSystem, NetworkPreLateUpdate.CreateLoopSystem(), typeof(PreLateUpdate.ScriptRunBehaviourLateUpdate), LoopSystemPosition.Before);
|
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))
|
else if (currentSystem.type == typeof(PostLateUpdate))
|
||||||
{
|
{
|
||||||
@@ -440,6 +459,7 @@ namespace Unity.Netcode
|
|||||||
else if (currentSystem.type == typeof(PreLateUpdate))
|
else if (currentSystem.type == typeof(PreLateUpdate))
|
||||||
{
|
{
|
||||||
TryRemoveLoopSystem(ref currentSystem, typeof(NetworkPreLateUpdate));
|
TryRemoveLoopSystem(ref currentSystem, typeof(NetworkPreLateUpdate));
|
||||||
|
TryRemoveLoopSystem(ref currentSystem, typeof(NetworkPostScriptLateUpdate));
|
||||||
}
|
}
|
||||||
else if (currentSystem.type == typeof(PostLateUpdate))
|
else if (currentSystem.type == typeof(PostLateUpdate))
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -63,16 +63,40 @@ namespace Unity.Netcode
|
|||||||
/// <param name="networkDelivery">The delivery type (QoS) to send data with</param>
|
/// <param name="networkDelivery">The delivery type (QoS) to send data with</param>
|
||||||
public void SendUnnamedMessage(IReadOnlyList<ulong> clientIds, FastBufferWriter messageBuffer, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced)
|
public void SendUnnamedMessage(IReadOnlyList<ulong> clientIds, FastBufferWriter messageBuffer, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced)
|
||||||
{
|
{
|
||||||
if (!m_NetworkManager.IsServer)
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException("Can not send unnamed messages to multiple users as a client");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (clientIds == null)
|
if (clientIds == null)
|
||||||
{
|
{
|
||||||
throw new ArgumentNullException(nameof(clientIds), "You must pass in a valid clientId List");
|
throw new ArgumentNullException(nameof(clientIds), "You must pass in a valid clientId List!");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!m_NetworkManager.DistributedAuthorityMode && !m_NetworkManager.IsServer)
|
||||||
|
{
|
||||||
|
if (clientIds.Count > 1 || (clientIds.Count == 1 && clientIds[0] != NetworkManager.ServerClientId))
|
||||||
|
{
|
||||||
|
Debug.LogError("Clients cannot send unnamed messages to other clients!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
else if (clientIds.Count == 1)
|
||||||
|
{
|
||||||
|
SendUnnamedMessage(clientIds[0], messageBuffer, networkDelivery);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (m_NetworkManager.DistributedAuthorityMode && !m_NetworkManager.DAHost)
|
||||||
|
{
|
||||||
|
if (clientIds.Count > 1)
|
||||||
|
{
|
||||||
|
Debug.LogError("Sending an unnamed message to multiple clients is not yet supported in distributed authority.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (clientIds.Count == 0)
|
||||||
|
{
|
||||||
|
Debug.LogError($"{nameof(clientIds)} is empty! No clients to send to.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ValidateMessageSize(messageBuffer, networkDelivery, isNamed: false);
|
||||||
|
|
||||||
if (m_NetworkManager.IsHost)
|
if (m_NetworkManager.IsHost)
|
||||||
{
|
{
|
||||||
for (var i = 0; i < clientIds.Count; ++i)
|
for (var i = 0; i < clientIds.Count; ++i)
|
||||||
@@ -108,6 +132,8 @@ namespace Unity.Netcode
|
|||||||
/// <param name="networkDelivery">The delivery type (QoS) to send data with</param>
|
/// <param name="networkDelivery">The delivery type (QoS) to send data with</param>
|
||||||
public void SendUnnamedMessage(ulong clientId, FastBufferWriter messageBuffer, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced)
|
public void SendUnnamedMessage(ulong clientId, FastBufferWriter messageBuffer, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced)
|
||||||
{
|
{
|
||||||
|
ValidateMessageSize(messageBuffer, networkDelivery, isNamed: false);
|
||||||
|
|
||||||
if (m_NetworkManager.IsHost)
|
if (m_NetworkManager.IsHost)
|
||||||
{
|
{
|
||||||
if (clientId == m_NetworkManager.LocalClientId)
|
if (clientId == m_NetworkManager.LocalClientId)
|
||||||
@@ -203,6 +229,14 @@ namespace Unity.Netcode
|
|||||||
var hash32 = XXHash.Hash32(name);
|
var hash32 = XXHash.Hash32(name);
|
||||||
var hash64 = XXHash.Hash64(name);
|
var hash64 = XXHash.Hash64(name);
|
||||||
|
|
||||||
|
if (m_NetworkManager.LogLevel <= LogLevel.Developer)
|
||||||
|
{
|
||||||
|
if (m_MessageHandlerNameLookup32.ContainsKey(hash32) || m_MessageHandlerNameLookup64.ContainsKey(hash64))
|
||||||
|
{
|
||||||
|
Debug.LogWarning($"Registering {name} named message over existing registration! Your previous registration's callback is being overwritten!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
m_NamedMessageHandlers32[hash32] = callback;
|
m_NamedMessageHandlers32[hash32] = callback;
|
||||||
m_NamedMessageHandlers64[hash64] = callback;
|
m_NamedMessageHandlers64[hash64] = callback;
|
||||||
|
|
||||||
@@ -255,6 +289,8 @@ namespace Unity.Netcode
|
|||||||
/// <param name="networkDelivery">The delivery type (QoS) to send data with</param>
|
/// <param name="networkDelivery">The delivery type (QoS) to send data with</param>
|
||||||
public void SendNamedMessage(string messageName, ulong clientId, FastBufferWriter messageStream, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced)
|
public void SendNamedMessage(string messageName, ulong clientId, FastBufferWriter messageStream, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced)
|
||||||
{
|
{
|
||||||
|
ValidateMessageSize(messageStream, networkDelivery, isNamed: true);
|
||||||
|
|
||||||
ulong hash = 0;
|
ulong hash = 0;
|
||||||
switch (m_NetworkManager.NetworkConfig.RpcHashSize)
|
switch (m_NetworkManager.NetworkConfig.RpcHashSize)
|
||||||
{
|
{
|
||||||
@@ -303,16 +339,41 @@ namespace Unity.Netcode
|
|||||||
/// <param name="networkDelivery">The delivery type (QoS) to send data with</param>
|
/// <param name="networkDelivery">The delivery type (QoS) to send data with</param>
|
||||||
public void SendNamedMessage(string messageName, IReadOnlyList<ulong> clientIds, FastBufferWriter messageStream, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced)
|
public void SendNamedMessage(string messageName, IReadOnlyList<ulong> clientIds, FastBufferWriter messageStream, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced)
|
||||||
{
|
{
|
||||||
if (!m_NetworkManager.IsServer)
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException("Can not send unnamed messages to multiple users as a client");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (clientIds == null)
|
if (clientIds == null)
|
||||||
{
|
{
|
||||||
throw new ArgumentNullException(nameof(clientIds), "You must pass in a valid clientId List");
|
throw new ArgumentNullException(nameof(clientIds), "Client list is null! You must pass in a valid clientId list to send a named message.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!m_NetworkManager.DistributedAuthorityMode && !m_NetworkManager.IsServer)
|
||||||
|
{
|
||||||
|
if (clientIds.Count > 1 || (clientIds.Count == 1 && clientIds[0] != NetworkManager.ServerClientId))
|
||||||
|
{
|
||||||
|
Debug.LogError("Clients cannot send named messages to other clients!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
else if (clientIds.Count == 1)
|
||||||
|
{
|
||||||
|
SendNamedMessage(messageName, clientIds[0], messageStream, networkDelivery);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (m_NetworkManager.DistributedAuthorityMode && !m_NetworkManager.DAHost)
|
||||||
|
{
|
||||||
|
if (clientIds.Count > 1)
|
||||||
|
{
|
||||||
|
Debug.LogError("Sending a named message to multiple clients is not yet supported in distributed authority.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (clientIds.Count == 0)
|
||||||
|
{
|
||||||
|
Debug.LogError($"{nameof(clientIds)} is empty! No clients to send the named message {messageName} to!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ValidateMessageSize(messageStream, networkDelivery, isNamed: true);
|
||||||
|
|
||||||
ulong hash = 0;
|
ulong hash = 0;
|
||||||
switch (m_NetworkManager.NetworkConfig.RpcHashSize)
|
switch (m_NetworkManager.NetworkConfig.RpcHashSize)
|
||||||
{
|
{
|
||||||
@@ -351,5 +412,32 @@ namespace Unity.Netcode
|
|||||||
m_NetworkManager.NetworkMetrics.TrackNamedMessageSent(clientIds, messageName, size);
|
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
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
#if UNITY_EDITOR
|
#if UNITY_EDITOR
|
||||||
using UnityEditor;
|
using UnityEditor;
|
||||||
@@ -12,9 +13,121 @@ namespace Unity.Netcode
|
|||||||
internal static readonly List<NetworkMessageManager.MessageWithHandler> __network_message_types = new List<NetworkMessageManager.MessageWithHandler>();
|
internal static readonly List<NetworkMessageManager.MessageWithHandler> __network_message_types = new List<NetworkMessageManager.MessageWithHandler>();
|
||||||
#pragma warning restore IDE1006 // restore naming rule violation check
|
#pragma warning restore IDE1006 // restore naming rule violation check
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Enum representing the different types of messages that can be sent over the network.
|
||||||
|
/// The values cannot be changed, as they are used to serialize and deserialize messages.
|
||||||
|
/// Adding new messages should be done by adding new values to the end of the enum
|
||||||
|
/// using the next free value.
|
||||||
|
/// </summary>
|
||||||
|
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
||||||
|
/// Add any new Message types to this table at the END with incremented index value
|
||||||
|
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
||||||
|
internal enum NetworkMessageTypes : uint
|
||||||
|
{
|
||||||
|
ConnectionApproved = 0,
|
||||||
|
ConnectionRequest = 1,
|
||||||
|
ChangeOwnership = 2,
|
||||||
|
ClientConnected = 3,
|
||||||
|
ClientDisconnected = 4,
|
||||||
|
ClientRpc = 5,
|
||||||
|
CreateObject = 6,
|
||||||
|
DestroyObject = 7,
|
||||||
|
DisconnectReason = 8,
|
||||||
|
ForwardClientRpc = 9,
|
||||||
|
ForwardServerRpc = 10,
|
||||||
|
NamedMessage = 11,
|
||||||
|
NetworkTransformMessage = 12,
|
||||||
|
NetworkVariableDelta = 13,
|
||||||
|
ParentSync = 14,
|
||||||
|
Proxy = 15,
|
||||||
|
Rpc = 16,
|
||||||
|
SceneEvent = 17,
|
||||||
|
ServerLog = 18,
|
||||||
|
ServerRpc = 19,
|
||||||
|
SessionOwner = 20,
|
||||||
|
TimeSync = 21,
|
||||||
|
Unnamed = 22,
|
||||||
|
AnticipationCounterSyncPingMessage = 23,
|
||||||
|
AnticipationCounterSyncPongMessage = 24,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Enable this for integration tests that need no message types defined
|
||||||
|
internal static bool IntegrationTestNoMessages;
|
||||||
|
|
||||||
public List<NetworkMessageManager.MessageWithHandler> GetMessages()
|
public List<NetworkMessageManager.MessageWithHandler> GetMessages()
|
||||||
{
|
{
|
||||||
return __network_message_types;
|
// return no message types when defined for integration tests
|
||||||
|
if (IntegrationTestNoMessages)
|
||||||
|
{
|
||||||
|
return new List<NetworkMessageManager.MessageWithHandler>();
|
||||||
|
}
|
||||||
|
var messageTypeCount = Enum.GetValues(typeof(NetworkMessageTypes)).Length;
|
||||||
|
// Assure the allowed types count is the same as our NetworkMessageType enum count
|
||||||
|
if (__network_message_types.Count != messageTypeCount)
|
||||||
|
{
|
||||||
|
throw new Exception($"Allowed types is not equal to the number of message type indices! Allowed Count: {__network_message_types.Count} | Index Count: {messageTypeCount}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Populate with blanks to be replaced later
|
||||||
|
var adjustedMessageTypes = new List<NetworkMessageManager.MessageWithHandler>();
|
||||||
|
var blank = new NetworkMessageManager.MessageWithHandler();
|
||||||
|
for (int i = 0; i < messageTypeCount; i++)
|
||||||
|
{
|
||||||
|
adjustedMessageTypes.Add(blank);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a type to enum index lookup table
|
||||||
|
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
||||||
|
// Add new Message types to this table paired with its new NetworkMessageTypes enum
|
||||||
|
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
||||||
|
var messageTypes = new Dictionary<Type, NetworkMessageTypes>
|
||||||
|
{
|
||||||
|
{ typeof(ConnectionApprovedMessage), NetworkMessageTypes.ConnectionApproved }, // This MUST be first
|
||||||
|
{ typeof(ConnectionRequestMessage), NetworkMessageTypes.ConnectionRequest }, // This MUST be second
|
||||||
|
{ typeof(ChangeOwnershipMessage), NetworkMessageTypes.ChangeOwnership },
|
||||||
|
{ typeof(ClientConnectedMessage), NetworkMessageTypes.ClientConnected },
|
||||||
|
{ typeof(ClientDisconnectedMessage), NetworkMessageTypes.ClientDisconnected },
|
||||||
|
{ typeof(ClientRpcMessage), NetworkMessageTypes.ClientRpc },
|
||||||
|
{ typeof(CreateObjectMessage), NetworkMessageTypes.CreateObject },
|
||||||
|
{ typeof(DestroyObjectMessage), NetworkMessageTypes.DestroyObject },
|
||||||
|
{ typeof(DisconnectReasonMessage), NetworkMessageTypes.DisconnectReason },
|
||||||
|
{ typeof(ForwardClientRpcMessage), NetworkMessageTypes.ForwardClientRpc },
|
||||||
|
{ typeof(ForwardServerRpcMessage), NetworkMessageTypes.ForwardServerRpc },
|
||||||
|
{ typeof(NamedMessage), NetworkMessageTypes.NamedMessage },
|
||||||
|
{ typeof(NetworkTransformMessage), NetworkMessageTypes.NetworkTransformMessage },
|
||||||
|
{ typeof(NetworkVariableDeltaMessage), NetworkMessageTypes.NetworkVariableDelta },
|
||||||
|
{ typeof(ParentSyncMessage), NetworkMessageTypes.ParentSync },
|
||||||
|
{ typeof(ProxyMessage), NetworkMessageTypes.Proxy },
|
||||||
|
{ typeof(RpcMessage), NetworkMessageTypes.Rpc },
|
||||||
|
{ typeof(SceneEventMessage), NetworkMessageTypes.SceneEvent },
|
||||||
|
{ typeof(ServerLogMessage), NetworkMessageTypes.ServerLog },
|
||||||
|
{ typeof(ServerRpcMessage), NetworkMessageTypes.ServerRpc },
|
||||||
|
{ typeof(TimeSyncMessage), NetworkMessageTypes.TimeSync },
|
||||||
|
{ typeof(UnnamedMessage), NetworkMessageTypes.Unnamed },
|
||||||
|
{ typeof(SessionOwnerMessage), NetworkMessageTypes.SessionOwner },
|
||||||
|
{ 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)
|
||||||
|
if (messageTypes.Count != messageTypeCount)
|
||||||
|
{
|
||||||
|
throw new Exception($"Message type to Message type index count mistmatch! Table Count: {messageTypes.Count} | Index Count: {messageTypeCount}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now order the allowed types list based on the order of the NetworkMessageType enum
|
||||||
|
foreach (var messageHandler in __network_message_types)
|
||||||
|
{
|
||||||
|
if (!messageTypes.ContainsKey(messageHandler.MessageType))
|
||||||
|
{
|
||||||
|
throw new Exception($"Missing message type from lookup table: {messageHandler.MessageType}");
|
||||||
|
}
|
||||||
|
adjustedMessageTypes[(int)messageTypes[messageHandler.MessageType]] = messageHandler;
|
||||||
|
}
|
||||||
|
|
||||||
|
// return the NetworkMessageType enum ordered list
|
||||||
|
return adjustedMessageTypes;
|
||||||
}
|
}
|
||||||
|
|
||||||
#if UNITY_EDITOR
|
#if UNITY_EDITOR
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -5,9 +5,10 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
public int Version => 0;
|
public int Version => 0;
|
||||||
|
|
||||||
|
private const string k_Name = "ChangeOwnershipMessage";
|
||||||
|
|
||||||
public ulong NetworkObjectId;
|
public ulong NetworkObjectId;
|
||||||
public ulong OwnerClientId;
|
public ulong OwnerClientId;
|
||||||
// DANGOEXP TODO: Remove these notes or change their format
|
|
||||||
// SERVICE NOTES:
|
// SERVICE NOTES:
|
||||||
// When forwarding the message to clients on the CMB Service side,
|
// When forwarding the message to clients on the CMB Service side,
|
||||||
// you can set the ClientIdCount to 0 and skip writing the ClientIds.
|
// you can set the ClientIdCount to 0 and skip writing the ClientIds.
|
||||||
@@ -16,7 +17,7 @@ namespace Unity.Netcode
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// When requesting, RequestClientId is the requestor.
|
/// When requesting, RequestClientId is the requestor.
|
||||||
/// When approving, RequestClientId is the owner that approved.
|
/// When approving, RequestClientId is the owner that approved.
|
||||||
/// When responding (only for denied), RequestClientId is the requestor
|
/// When responding (only for denied), RequestClientId is the requestor
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal ulong RequestClientId;
|
internal ulong RequestClientId;
|
||||||
internal int ClientIdCount;
|
internal int ClientIdCount;
|
||||||
@@ -199,7 +200,7 @@ namespace Unity.Netcode
|
|||||||
// authority of the NetworkObject in question.
|
// authority of the NetworkObject in question.
|
||||||
if (!networkManager.DAHost && !networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId))
|
if (!networkManager.DAHost && !networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId))
|
||||||
{
|
{
|
||||||
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, GetType().Name);
|
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, k_Name);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
@@ -256,19 +257,22 @@ namespace Unity.Netcode
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// If ownership is changing and this is not an ownership request approval then ignore the OnwerClientId
|
// If ownership is changing and this is not an ownership request approval then ignore the SenderId
|
||||||
// If it is just updating flags then ignore sending to the owner
|
if (OwnershipIsChanging && !RequestApproved && context.SenderId == clientId)
|
||||||
// If it is a request or approving request, then ignore the RequestClientId
|
|
||||||
if ((OwnershipIsChanging && !RequestApproved && OwnerClientId == clientId) || (OwnershipFlagsUpdate && clientId == OwnerClientId)
|
|
||||||
|| ((RequestOwnership || RequestApproved) && clientId == RequestClientId))
|
|
||||||
{
|
{
|
||||||
continue;
|
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);
|
networkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.Reliable, clientId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// If the NetworkObject is not visible to the DAHost client, then exit early
|
// If the NetworkObject is not visible to the DAHost client, then exit early
|
||||||
if (!networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId))
|
if (!networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId))
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
@@ -290,7 +294,7 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Handle the
|
/// Handle the extended distributed authority ownership updates
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="context"></param>
|
/// <param name="context"></param>
|
||||||
private void HandleExtendedOwnershipUpdate(ref NetworkContext context)
|
private void HandleExtendedOwnershipUpdate(ref NetworkContext context)
|
||||||
@@ -325,10 +329,12 @@ namespace Unity.Netcode
|
|||||||
var networkManager = (NetworkManager)context.SystemOwner;
|
var networkManager = (NetworkManager)context.SystemOwner;
|
||||||
var networkObject = networkManager.SpawnManager.SpawnedObjects[NetworkObjectId];
|
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)
|
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;
|
var originalOwner = networkObject.OwnerClientId;
|
||||||
@@ -345,16 +351,10 @@ namespace Unity.Netcode
|
|||||||
networkObject.InvokeBehaviourOnLostOwnership();
|
networkObject.InvokeBehaviourOnLostOwnership();
|
||||||
}
|
}
|
||||||
|
|
||||||
// We are new owner or (client-server) or running in distributed authority mode
|
// If in distributed authority mode
|
||||||
if (OwnerClientId == networkManager.LocalClientId || networkManager.DistributedAuthorityMode)
|
|
||||||
{
|
|
||||||
networkObject.InvokeBehaviourOnGainedOwnership();
|
|
||||||
}
|
|
||||||
|
|
||||||
// If in distributed authority mode
|
|
||||||
if (networkManager.DistributedAuthorityMode)
|
if (networkManager.DistributedAuthorityMode)
|
||||||
{
|
{
|
||||||
// Always update the network properties in distributed authority mode
|
// Always update the network properties in distributed authority mode
|
||||||
for (int i = 0; i < networkObject.ChildNetworkBehaviours.Count; i++)
|
for (int i = 0; i < networkObject.ChildNetworkBehaviours.Count; i++)
|
||||||
{
|
{
|
||||||
networkObject.ChildNetworkBehaviours[i].UpdateNetworkProperties();
|
networkObject.ChildNetworkBehaviours[i].UpdateNetworkProperties();
|
||||||
@@ -372,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
|
// Always invoke ownership change notifications
|
||||||
networkObject.InvokeOwnershipChanged(originalOwner, OwnerClientId);
|
networkObject.InvokeOwnershipChanged(originalOwner, OwnerClientId);
|
||||||
|
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ namespace Unity.Netcode
|
|||||||
public void Handle(ref NetworkContext context)
|
public void Handle(ref NetworkContext context)
|
||||||
{
|
{
|
||||||
var networkManager = (NetworkManager)context.SystemOwner;
|
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);
|
networkManager.SceneManager.SynchronizeNetworkObjects(ClientId);
|
||||||
}
|
}
|
||||||
@@ -55,10 +55,24 @@ namespace Unity.Netcode
|
|||||||
// Don't redistribute for the local instance
|
// Don't redistribute for the local instance
|
||||||
if (ClientId != networkManager.LocalClientId)
|
if (ClientId != networkManager.LocalClientId)
|
||||||
{
|
{
|
||||||
// We defer redistribution to the end of the NetworkUpdateStage.PostLateUpdate
|
// Synchronize the client with spawned objects (relative to each client)
|
||||||
networkManager.RedistributeToClient = true;
|
networkManager.SpawnManager.SynchronizeObjectsToNewlyJoinedClient(ClientId);
|
||||||
networkManager.ClientToRedistribute = ClientId;
|
|
||||||
networkManager.TickToRedistribute = networkManager.ServerTime.Tick + 20;
|
// 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
|
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
|
internal struct ConnectionApprovedMessage : INetworkMessage
|
||||||
{
|
{
|
||||||
|
private const int k_AddCMBServiceConfig = 2;
|
||||||
private const int k_VersionAddClientIds = 1;
|
private const int k_VersionAddClientIds = 1;
|
||||||
public int Version => k_VersionAddClientIds;
|
public int Version => k_AddCMBServiceConfig;
|
||||||
|
|
||||||
public ulong OwnerClientId;
|
public ulong OwnerClientId;
|
||||||
public int NetworkTick;
|
public int NetworkTick;
|
||||||
// The cloud state service should set this if we are restoring a session
|
// The cloud state service should set this if we are restoring a session
|
||||||
|
public ServiceConfig ServiceConfig;
|
||||||
public bool IsRestoredSession;
|
public bool IsRestoredSession;
|
||||||
public ulong CurrentSessionOwner;
|
public ulong CurrentSessionOwner;
|
||||||
// Not serialized
|
// Not serialized
|
||||||
@@ -25,6 +65,32 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
public NativeArray<ulong> ConnectedClientIds;
|
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)
|
public void Serialize(FastBufferWriter writer, int targetVersion)
|
||||||
{
|
{
|
||||||
// ============================================================
|
// ============================================================
|
||||||
@@ -45,8 +111,17 @@ namespace Unity.Netcode
|
|||||||
BytePacker.WriteValueBitPacked(writer, NetworkTick);
|
BytePacker.WriteValueBitPacked(writer, NetworkTick);
|
||||||
if (IsDistributedAuthority)
|
if (IsDistributedAuthority)
|
||||||
{
|
{
|
||||||
writer.WriteValueSafe(IsRestoredSession);
|
if (targetVersion >= k_AddCMBServiceConfig)
|
||||||
BytePacker.WriteValueBitPacked(writer, CurrentSessionOwner);
|
{
|
||||||
|
ServiceConfig.IsRestoredSession = false;
|
||||||
|
ServiceConfig.CurrentSessionOwner = CurrentSessionOwner;
|
||||||
|
writer.WriteNetworkSerializable(ServiceConfig);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
writer.WriteValueSafe(IsRestoredSession);
|
||||||
|
BytePacker.WriteValueBitPacked(writer, CurrentSessionOwner);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (targetVersion >= k_VersionAddClientIds)
|
if (targetVersion >= k_VersionAddClientIds)
|
||||||
@@ -122,13 +197,22 @@ namespace Unity.Netcode
|
|||||||
// ============================================================
|
// ============================================================
|
||||||
// END FORBIDDEN SEGMENT
|
// END FORBIDDEN SEGMENT
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
m_ReceiveMessageVersion = receivedMessageVersion;
|
||||||
ByteUnpacker.ReadValueBitPacked(reader, out OwnerClientId);
|
ByteUnpacker.ReadValueBitPacked(reader, out OwnerClientId);
|
||||||
ByteUnpacker.ReadValueBitPacked(reader, out NetworkTick);
|
ByteUnpacker.ReadValueBitPacked(reader, out NetworkTick);
|
||||||
if (networkManager.DistributedAuthorityMode)
|
if (networkManager.DistributedAuthorityMode)
|
||||||
{
|
{
|
||||||
reader.ReadValueSafe(out IsRestoredSession);
|
if (receivedMessageVersion >= k_AddCMBServiceConfig)
|
||||||
ByteUnpacker.ReadValueBitPacked(reader, out CurrentSessionOwner);
|
{
|
||||||
|
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)
|
if (receivedMessageVersion >= k_VersionAddClientIds)
|
||||||
@@ -157,7 +241,7 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
if (networkManager.DistributedAuthorityMode)
|
if (networkManager.DistributedAuthorityMode)
|
||||||
{
|
{
|
||||||
networkManager.SetSessionOwner(CurrentSessionOwner);
|
networkManager.SetSessionOwner(GetSessionOwner());
|
||||||
if (networkManager.LocalClient.IsSessionOwner && networkManager.NetworkConfig.EnableSceneManagement)
|
if (networkManager.LocalClient.IsSessionOwner && networkManager.NetworkConfig.EnableSceneManagement)
|
||||||
{
|
{
|
||||||
networkManager.SceneManager.InitializeScenesLoaded();
|
networkManager.SceneManager.InitializeScenesLoaded();
|
||||||
@@ -222,6 +306,9 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
// When scene management is disabled we notify after everything is synchronized
|
// When scene management is disabled we notify after everything is synchronized
|
||||||
networkManager.ConnectionManager.InvokeOnClientConnectedCallback(context.SenderId);
|
networkManager.ConnectionManager.InvokeOnClientConnectedCallback(context.SenderId);
|
||||||
|
|
||||||
|
// For convenience, notify all NetworkBehaviours that synchronization is complete.
|
||||||
|
networkManager.SpawnManager.NotifyNetworkObjectsSynchronized();
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -230,16 +317,33 @@ namespace Unity.Netcode
|
|||||||
// Mark the client being connected
|
// Mark the client being connected
|
||||||
networkManager.IsConnectedClient = true;
|
networkManager.IsConnectedClient = true;
|
||||||
|
|
||||||
// Spawn any in-scene placed NetworkObjects
|
networkManager.SceneManager.IsRestoringSession = GetIsSessionRestor();
|
||||||
networkManager.SpawnManager.ServerSpawnSceneObjectsOnStartSweep();
|
|
||||||
|
|
||||||
// Spawn the local player of the session owner
|
if (!networkManager.SceneManager.IsRestoringSession)
|
||||||
if (networkManager.AutoSpawnPlayerPrefabClientSide)
|
|
||||||
{
|
{
|
||||||
networkManager.ConnectionManager.CreateAndSpawnPlayer(OwnerClientId);
|
// 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();
|
||||||
|
|
||||||
|
// Spawn the local player of the session owner
|
||||||
|
if (networkManager.AutoSpawnPlayerPrefabClientSide)
|
||||||
|
{
|
||||||
|
networkManager.ConnectionManager.CreateAndSpawnPlayer(OwnerClientId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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);
|
||||||
}
|
}
|
||||||
// Synchronize the service with the initial session owner's loaded scenes and spawned objects
|
|
||||||
networkManager.SceneManager.SynchronizeNetworkObjects(NetworkManager.ServerClientId);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ConnectedClientIds.Dispose();
|
ConnectedClientIds.Dispose();
|
||||||
|
|||||||
@@ -2,16 +2,53 @@ using Unity.Collections;
|
|||||||
|
|
||||||
namespace Unity.Netcode
|
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 SessionConfig SessionConfig;
|
||||||
|
public int SessionVersion => (int)SessionConfig.SessionVersion;
|
||||||
public ulong ConfigHash;
|
|
||||||
|
|
||||||
public bool CMBServiceConnection;
|
|
||||||
public uint TickRate;
|
public uint TickRate;
|
||||||
public bool EnableSceneManagement;
|
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 byte[] ConnectionData;
|
||||||
|
|
||||||
public bool ShouldSendConnectionData;
|
public bool ShouldSendConnectionData;
|
||||||
@@ -34,10 +71,9 @@ namespace Unity.Netcode
|
|||||||
// END FORBIDDEN SEGMENT
|
// END FORBIDDEN SEGMENT
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
if (CMBServiceConnection)
|
if (DistributedAuthority)
|
||||||
{
|
{
|
||||||
writer.WriteValueSafe(TickRate);
|
writer.WriteNetworkSerializable(ClientConfig);
|
||||||
writer.WriteValueSafe(EnableSceneManagement);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ShouldSendConnectionData)
|
if (ShouldSendConnectionData)
|
||||||
@@ -83,6 +119,11 @@ namespace Unity.Netcode
|
|||||||
// END FORBIDDEN SEGMENT
|
// END FORBIDDEN SEGMENT
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
|
if (networkManager.DAHost)
|
||||||
|
{
|
||||||
|
reader.ReadNetworkSerializable(out ClientConfig);
|
||||||
|
}
|
||||||
|
|
||||||
if (networkManager.NetworkConfig.ConnectionApproval)
|
if (networkManager.NetworkConfig.ConnectionApproval)
|
||||||
{
|
{
|
||||||
if (!reader.TryBeginRead(FastBufferWriter.GetWriteSize(ConfigHash) + FastBufferWriter.GetWriteSize<int>()))
|
if (!reader.TryBeginRead(FastBufferWriter.GetWriteSize(ConfigHash) + FastBufferWriter.GetWriteSize<int>()))
|
||||||
@@ -145,6 +186,17 @@ namespace Unity.Netcode
|
|||||||
var networkManager = (NetworkManager)context.SystemOwner;
|
var networkManager = (NetworkManager)context.SystemOwner;
|
||||||
var senderId = context.SenderId;
|
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))
|
if (networkManager.ConnectionManager.PendingClients.TryGetValue(senderId, out PendingClient client))
|
||||||
{
|
{
|
||||||
// Set to pending approval to prevent future connection requests from being approved
|
// Set to pending approval to prevent future connection requests from being approved
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
public int Version => 0;
|
public int Version => 0;
|
||||||
|
|
||||||
|
private const string k_Name = "CreateObjectMessage";
|
||||||
|
|
||||||
public NetworkObject.SceneObject ObjectInfo;
|
public NetworkObject.SceneObject ObjectInfo;
|
||||||
private FastBufferReader m_ReceivedNetworkVariableData;
|
private FastBufferReader m_ReceivedNetworkVariableData;
|
||||||
|
|
||||||
@@ -161,7 +163,7 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
if (!networkManager.NetworkConfig.ForceSamePrefabs && !networkManager.SpawnManager.HasPrefab(ObjectInfo))
|
if (!networkManager.NetworkConfig.ForceSamePrefabs && !networkManager.SpawnManager.HasPrefab(ObjectInfo))
|
||||||
{
|
{
|
||||||
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnAddPrefab, ObjectInfo.Hash, reader, ref context, GetType().Name);
|
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnAddPrefab, ObjectInfo.Hash, reader, ref context, k_Name);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
m_ReceivedNetworkVariableData = reader;
|
m_ReceivedNetworkVariableData = reader;
|
||||||
@@ -255,7 +257,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
// DA - NGO CMB SERVICE NOTES:
|
// DA - NGO CMB SERVICE NOTES:
|
||||||
// (*** See above notes fist ***)
|
// (*** See above notes fist ***)
|
||||||
// If it is a player object freshly spawning and one or more clients all connect at the exact same time (i.e. received on effectively
|
// If it is a player object freshly spawning and one or more clients all connect at the exact same time (i.e. received on effectively
|
||||||
// the same frame), then we need to check the observers list to make sure all players are visible upon first spawning. At a later date,
|
// the same frame), then we need to check the observers list to make sure all players are visible upon first spawning. At a later date,
|
||||||
// for area of interest we will need to have some form of follow up "observer update" message to cull out players not within each
|
// for area of interest we will need to have some form of follow up "observer update" message to cull out players not within each
|
||||||
// player's AOI.
|
// player's AOI.
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
public int Version => 0;
|
public int Version => 0;
|
||||||
|
|
||||||
|
private const string k_Name = "DestroyObjectMessage";
|
||||||
|
|
||||||
public ulong NetworkObjectId;
|
public ulong NetworkObjectId;
|
||||||
public bool DestroyGameObject;
|
public bool DestroyGameObject;
|
||||||
private byte m_DestroyFlags;
|
private byte m_DestroyFlags;
|
||||||
@@ -84,7 +86,7 @@ namespace Unity.Netcode
|
|||||||
// Client-Server mode we always defer where in distributed authority mode we only defer if it is not a targeted destroy
|
// Client-Server mode we always defer where in distributed authority mode we only defer if it is not a targeted destroy
|
||||||
if (!networkManager.DistributedAuthorityMode || (networkManager.DistributedAuthorityMode && !IsTargetedDestroy))
|
if (!networkManager.DistributedAuthorityMode || (networkManager.DistributedAuthorityMode && !IsTargetedDestroy))
|
||||||
{
|
{
|
||||||
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, GetType().Name);
|
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, k_Name);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
193
Runtime/Messaging/Messages/NetworkTransformMessage.cs
Normal file
193
Runtime/Messaging/Messages/NetworkTransformMessage.cs
Normal file
@@ -0,0 +1,193 @@
|
|||||||
|
using Unity.Netcode.Components;
|
||||||
|
using UnityEngine;
|
||||||
|
|
||||||
|
namespace Unity.Netcode
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// NetworkTransform State Update Message
|
||||||
|
/// </summary>
|
||||||
|
internal struct NetworkTransformMessage : INetworkMessage
|
||||||
|
{
|
||||||
|
public int Version => 0;
|
||||||
|
private const string k_Name = "NetworkTransformMessage";
|
||||||
|
|
||||||
|
internal NetworkTransform NetworkTransform;
|
||||||
|
|
||||||
|
// Only used for DAHost
|
||||||
|
internal NetworkTransform.NetworkTransformState State;
|
||||||
|
private FastBufferReader m_CurrentReader;
|
||||||
|
|
||||||
|
internal int BytesWritten;
|
||||||
|
|
||||||
|
private unsafe void CopyPayload(ref FastBufferWriter writer)
|
||||||
|
{
|
||||||
|
writer.WriteBytesSafe(m_CurrentReader.GetUnsafePtrAtCurrentPosition(), m_CurrentReader.Length - m_CurrentReader.Position);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Serialize(FastBufferWriter writer, int targetVersion)
|
||||||
|
{
|
||||||
|
if (m_CurrentReader.IsInitialized)
|
||||||
|
{
|
||||||
|
CopyPayload(ref writer);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
BytesWritten = NetworkTransform.SerializeMessage(writer, targetVersion);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
|
||||||
|
{
|
||||||
|
var networkManager = context.SystemOwner as NetworkManager;
|
||||||
|
if (networkManager == null)
|
||||||
|
{
|
||||||
|
Debug.LogError($"[{nameof(NetworkTransformMessage)}] System owner context was not of type {nameof(NetworkManager)}!");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
var currentPosition = reader.Position;
|
||||||
|
var networkObjectId = (ulong)0;
|
||||||
|
var networkBehaviourId = 0;
|
||||||
|
|
||||||
|
ByteUnpacker.ReadValueBitPacked(reader, out networkObjectId);
|
||||||
|
var isSpawnedLocally = networkManager.SpawnManager.SpawnedObjects.ContainsKey(networkObjectId);
|
||||||
|
|
||||||
|
// Only defer if the NetworkObject is not spawned yet and the local NetworkManager is not running as a DAHost.
|
||||||
|
if (!isSpawnedLocally && !networkManager.DAHost)
|
||||||
|
{
|
||||||
|
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, networkObjectId, reader, ref context, k_Name);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// While the below check and assignment might seem out of place, this is specific to running in DAHost mode when a NetworkObject is
|
||||||
|
// hidden from the DAHost but is visible to other clients. Since the DAHost needs to forward updates to the clients, we ignore processing
|
||||||
|
// this message locally
|
||||||
|
var networkObject = (NetworkObject)null;
|
||||||
|
var isServerAuthoritative = false;
|
||||||
|
var ownerAuthoritativeServerSide = false;
|
||||||
|
|
||||||
|
// Get the behaviour index
|
||||||
|
ByteUnpacker.ReadValueBitPacked(reader, out networkBehaviourId);
|
||||||
|
|
||||||
|
if (isSpawnedLocally)
|
||||||
|
{
|
||||||
|
networkObject = networkManager.SpawnManager.SpawnedObjects[networkObjectId];
|
||||||
|
// Get the target NetworkTransform
|
||||||
|
NetworkTransform = networkObject.ChildNetworkBehaviours[networkBehaviourId] as NetworkTransform;
|
||||||
|
isServerAuthoritative = NetworkTransform.IsServerAuthoritative();
|
||||||
|
ownerAuthoritativeServerSide = !isServerAuthoritative && networkManager.IsServer;
|
||||||
|
|
||||||
|
reader.ReadNetworkSerializableInPlace(ref NetworkTransform.InboundState);
|
||||||
|
NetworkTransform.InboundState.LastSerializedSize = reader.Position - currentPosition;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Deserialize the state
|
||||||
|
reader.ReadNetworkSerializableInPlace(ref State);
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe
|
||||||
|
{
|
||||||
|
if (ownerAuthoritativeServerSide)
|
||||||
|
{
|
||||||
|
var targetCount = 1;
|
||||||
|
|
||||||
|
if (networkManager.DistributedAuthorityMode && networkManager.DAHost)
|
||||||
|
{
|
||||||
|
ByteUnpacker.ReadValueBitPacked(reader, out targetCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
var targetIds = stackalloc ulong[targetCount];
|
||||||
|
|
||||||
|
if (networkManager.DistributedAuthorityMode && networkManager.DAHost)
|
||||||
|
{
|
||||||
|
var targetId = (ulong)0;
|
||||||
|
for (int i = 0; i < targetCount; i++)
|
||||||
|
{
|
||||||
|
ByteUnpacker.ReadValueBitPacked(reader, out targetId);
|
||||||
|
targetIds[i] = targetId;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isSpawnedLocally)
|
||||||
|
{
|
||||||
|
// If we are the DAHost and the NetworkObject is hidden from the host we still need to forward this message
|
||||||
|
ownerAuthoritativeServerSide = networkManager.DAHost && !isSpawnedLocally;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var ownerClientId = (ulong)0;
|
||||||
|
|
||||||
|
if (networkObject != null)
|
||||||
|
{
|
||||||
|
ownerClientId = networkObject.OwnerClientId;
|
||||||
|
if (ownerClientId == NetworkManager.ServerClientId)
|
||||||
|
{
|
||||||
|
// Ownership must have changed, ignore any additional pending messages that might have
|
||||||
|
// come from a previous owner client.
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (networkManager.DAHost)
|
||||||
|
{
|
||||||
|
// Specific to distributed authority mode, the only sender of state updates will be the owner
|
||||||
|
ownerClientId = context.SenderId;
|
||||||
|
}
|
||||||
|
|
||||||
|
var networkDelivery = State.IsReliableStateUpdate() ? NetworkDelivery.ReliableSequenced : NetworkDelivery.UnreliableSequenced;
|
||||||
|
|
||||||
|
// Forward the state update if there are any remote clients to foward it to
|
||||||
|
if (networkManager.ConnectionManager.ConnectedClientsList.Count > (networkManager.IsHost ? 2 : 1))
|
||||||
|
{
|
||||||
|
var clientCount = networkManager.DistributedAuthorityMode ? targetCount : networkManager.ConnectionManager.ConnectedClientsList.Count;
|
||||||
|
if (clientCount == 0)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// This is only to copy the existing and already serialized struct for forwarding purposes only.
|
||||||
|
// This will not include any changes made to this struct at this particular stage of processing the message.
|
||||||
|
var currentMessage = this;
|
||||||
|
// Create a new reader that replicates this message
|
||||||
|
currentMessage.m_CurrentReader = new FastBufferReader(reader, Collections.Allocator.None);
|
||||||
|
// Rewind the new reader to the beginning of the message's payload
|
||||||
|
currentMessage.m_CurrentReader.Seek(currentPosition);
|
||||||
|
// Forward the message to all connected clients that are observers of the associated NetworkObject
|
||||||
|
|
||||||
|
for (int i = 0; i < clientCount; i++)
|
||||||
|
{
|
||||||
|
var clientId = networkManager.DistributedAuthorityMode ? targetIds[i] : networkManager.ConnectionManager.ConnectedClientsList[i].ClientId;
|
||||||
|
if (NetworkManager.ServerClientId == clientId || (!isServerAuthoritative && clientId == ownerClientId) ||
|
||||||
|
(!networkManager.DistributedAuthorityMode && !networkObject.Observers.Contains(clientId)))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
networkManager.MessageManager.SendMessage(ref currentMessage, networkDelivery, clientId);
|
||||||
|
}
|
||||||
|
// Dispose of the reader used for forwarding
|
||||||
|
currentMessage.m_CurrentReader.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Handle(ref NetworkContext context)
|
||||||
|
{
|
||||||
|
var networkManager = context.SystemOwner as NetworkManager;
|
||||||
|
// Only if the local NetworkManager instance is running as the DAHost we just exit if there is no local
|
||||||
|
// NetworkTransform component to apply the state update to (i.e. it is hidden from the DAHost and it
|
||||||
|
// just forwarded the state update to any other connected client)
|
||||||
|
if (networkManager.DAHost && NetworkTransform == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (NetworkTransform == null)
|
||||||
|
{
|
||||||
|
Debug.LogError($"[{nameof(NetworkTransformMessage)}][Dropped] Reciever {nameof(NetworkTransform)} was not set!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
NetworkTransform.TransformStateUpdate(context.SenderId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
using Unity.Collections;
|
using Unity.Collections;
|
||||||
|
|
||||||
namespace Unity.Netcode
|
namespace Unity.Netcode
|
||||||
@@ -10,9 +11,22 @@ namespace Unity.Netcode
|
|||||||
/// serialization. This is due to the generally amorphous nature of network variable
|
/// serialization. This is due to the generally amorphous nature of network variable
|
||||||
/// deltas, since they're all driven by custom virtual method overloads.
|
/// deltas, since they're all driven by custom virtual method overloads.
|
||||||
/// </summary>
|
/// </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
|
internal struct NetworkVariableDeltaMessage : INetworkMessage
|
||||||
{
|
{
|
||||||
public int Version => 0;
|
private const int k_ServerDeltaForwardingAndNetworkDelivery = 1;
|
||||||
|
public int Version => k_ServerDeltaForwardingAndNetworkDelivery;
|
||||||
|
|
||||||
|
|
||||||
public ulong NetworkObjectId;
|
public ulong NetworkObjectId;
|
||||||
public ushort NetworkBehaviourIndex;
|
public ushort NetworkBehaviourIndex;
|
||||||
@@ -21,10 +35,62 @@ namespace Unity.Netcode
|
|||||||
public ulong TargetClientId;
|
public ulong TargetClientId;
|
||||||
public NetworkBehaviour NetworkBehaviour;
|
public NetworkBehaviour NetworkBehaviour;
|
||||||
|
|
||||||
|
public NetworkDelivery NetworkDelivery;
|
||||||
|
|
||||||
private FastBufferReader m_ReceivedNetworkVariableData;
|
private FastBufferReader m_ReceivedNetworkVariableData;
|
||||||
|
|
||||||
// DANGO-TODO: Made some modifications here that overlap/won't play nice with EnsureNetworkVariableLenghtSafety.
|
private bool m_ForwardingMessage;
|
||||||
// Worth either merging or more cleanly separating these codepaths.
|
|
||||||
|
private int m_ReceivedMessageVersion;
|
||||||
|
|
||||||
|
private const string k_Name = "NetworkVariableDeltaMessage";
|
||||||
|
|
||||||
|
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)
|
public void Serialize(FastBufferWriter writer, int targetVersion)
|
||||||
{
|
{
|
||||||
if (!writer.TryBeginWrite(FastBufferWriter.GetWriteSize(NetworkObjectId) + FastBufferWriter.GetWriteSize(NetworkBehaviourIndex)))
|
if (!writer.TryBeginWrite(FastBufferWriter.GetWriteSize(NetworkObjectId) + FastBufferWriter.GetWriteSize(NetworkBehaviourIndex)))
|
||||||
@@ -34,10 +100,67 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
var obj = NetworkBehaviour.NetworkObject;
|
var obj = NetworkBehaviour.NetworkObject;
|
||||||
var networkManager = obj.NetworkManagerOwner;
|
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, NetworkObjectId);
|
||||||
BytePacker.WriteValueBitPacked(writer, NetworkBehaviourIndex);
|
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);
|
writer.WriteValueSafe((ushort)NetworkBehaviour.NetworkVariableFields.Count);
|
||||||
}
|
}
|
||||||
@@ -46,12 +169,12 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
if (!DeliveryMappedNetworkVariableIndex.Contains(i))
|
if (!DeliveryMappedNetworkVariableIndex.Contains(i))
|
||||||
{
|
{
|
||||||
// This var does not belong to the currently iterating delivery group.
|
// DANGO TODO: Remove distributedAuthorityMode portion when we remove the service specific NetworkVariable stuff
|
||||||
if (networkManager.DistributedAuthorityMode)
|
if (distributedAuthorityMode)
|
||||||
{
|
{
|
||||||
writer.WriteValueSafe<ushort>(0);
|
writer.WriteValueSafe<ushort>(0);
|
||||||
}
|
}
|
||||||
else if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
|
else if (ensureNetworkVariableLengthSafety)
|
||||||
{
|
{
|
||||||
BytePacker.WriteValueBitPacked(writer, (ushort)0);
|
BytePacker.WriteValueBitPacked(writer, (ushort)0);
|
||||||
}
|
}
|
||||||
@@ -67,7 +190,8 @@ namespace Unity.Netcode
|
|||||||
var networkVariable = NetworkBehaviour.NetworkVariableFields[i];
|
var networkVariable = NetworkBehaviour.NetworkVariableFields[i];
|
||||||
var shouldWrite = networkVariable.IsDirty() &&
|
var shouldWrite = networkVariable.IsDirty() &&
|
||||||
networkVariable.CanClientRead(TargetClientId) &&
|
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
|
// 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
|
// Allowing the write would send an old value to the client and cause jitter
|
||||||
@@ -87,14 +211,15 @@ namespace Unity.Netcode
|
|||||||
shouldWrite = false;
|
shouldWrite = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (networkManager.DistributedAuthorityMode)
|
// DANGO TODO: Remove distributedAuthorityMode portion when we remove the service specific NetworkVariable stuff
|
||||||
|
if (distributedAuthorityMode)
|
||||||
{
|
{
|
||||||
if (!shouldWrite)
|
if (!shouldWrite)
|
||||||
{
|
{
|
||||||
writer.WriteValueSafe<ushort>(0);
|
writer.WriteValueSafe<ushort>(0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
|
else if (ensureNetworkVariableLengthSafety)
|
||||||
{
|
{
|
||||||
if (!shouldWrite)
|
if (!shouldWrite)
|
||||||
{
|
{
|
||||||
@@ -108,71 +233,39 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
if (shouldWrite)
|
if (shouldWrite)
|
||||||
{
|
{
|
||||||
if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
|
WriteNetworkVariable(ref writer, ref networkVariable, distributedAuthorityMode, ensureNetworkVariableLengthSafety, nonFragmentedMessageMaxSize, fragmentedMessageMaxSize);
|
||||||
{
|
networkManager.NetworkMetrics.TrackNetworkVariableDeltaSent(TargetClientId, obj, networkVariable.Name, typeName, writer.Length - startingSize);
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
|
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
|
||||||
{
|
{
|
||||||
|
m_ReceivedMessageVersion = receivedMessageVersion;
|
||||||
ByteUnpacker.ReadValueBitPacked(reader, out NetworkObjectId);
|
ByteUnpacker.ReadValueBitPacked(reader, out NetworkObjectId);
|
||||||
ByteUnpacker.ReadValueBitPacked(reader, out NetworkBehaviourIndex);
|
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;
|
m_ReceivedNetworkVariableData = reader;
|
||||||
|
|
||||||
return true;
|
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)
|
public void Handle(ref NetworkContext context)
|
||||||
{
|
{
|
||||||
var networkManager = (NetworkManager)context.SystemOwner;
|
var networkManager = (NetworkManager)context.SystemOwner;
|
||||||
|
|
||||||
if (networkManager.SpawnManager.SpawnedObjects.TryGetValue(NetworkObjectId, out NetworkObject networkObject))
|
if (networkManager.SpawnManager.SpawnedObjects.TryGetValue(NetworkObjectId, out NetworkObject networkObject))
|
||||||
{
|
{
|
||||||
|
var distributedAuthorityMode = networkManager.DistributedAuthorityMode;
|
||||||
|
var ensureNetworkVariableLengthSafety = networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety;
|
||||||
var networkBehaviour = networkObject.GetNetworkBehaviourAtOrderIndex(NetworkBehaviourIndex);
|
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)
|
if (networkBehaviour == null)
|
||||||
{
|
{
|
||||||
@@ -183,7 +276,8 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
else
|
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);
|
m_ReceivedNetworkVariableData.ReadValueSafe(out ushort variableCount);
|
||||||
if (variableCount != networkBehaviour.NetworkVariableFields.Count)
|
if (variableCount != networkBehaviour.NetworkVariableFields.Count)
|
||||||
@@ -192,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++)
|
for (int i = 0; i < networkBehaviour.NetworkVariableFields.Count; i++)
|
||||||
{
|
{
|
||||||
int varSize = 0;
|
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);
|
m_ReceivedNetworkVariableData.ReadValueSafe(out ushort variableSize);
|
||||||
varSize = variableSize;
|
varSize = variableSize;
|
||||||
@@ -205,10 +319,9 @@ namespace Unity.Netcode
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (networkManager.NetworkConfig.EnsureNetworkVariableLengthSafety)
|
else if (ensureNetworkVariableLengthSafety)
|
||||||
{
|
{
|
||||||
ByteUnpacker.ReadValueBitPacked(m_ReceivedNetworkVariableData, out varSize);
|
ByteUnpacker.ReadValueBitPacked(m_ReceivedNetworkVariableData, out varSize);
|
||||||
|
|
||||||
if (varSize == 0)
|
if (varSize == 0)
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
@@ -223,8 +336,6 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var networkVariable = networkBehaviour.NetworkVariableFields[i];
|
|
||||||
|
|
||||||
if (networkManager.IsServer && !networkVariable.CanClientWrite(context.SenderId))
|
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
|
// we are choosing not to fire an exception here, because otherwise a malicious client could use this to crash the server
|
||||||
@@ -252,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($"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}]");
|
NetworkLog.LogError($"[{networkVariable.GetType().Name}]");
|
||||||
}
|
}
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
int readStartPos = m_ReceivedNetworkVariableData.Position;
|
int readStartPos = m_ReceivedNetworkVariableData.Position;
|
||||||
|
|
||||||
// Read Delta so we also notify any subscribers to a change in the NetworkVariable
|
// DANGO TODO: Remove distributedAuthorityMode portion when we remove the service specific NetworkVariable stuff
|
||||||
networkVariable.ReadDelta(m_ReceivedNetworkVariableData, networkManager.IsServer);
|
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(
|
networkManager.NetworkMetrics.TrackNetworkVariableDeltaReceived(
|
||||||
context.SenderId,
|
context.SenderId,
|
||||||
@@ -267,7 +423,8 @@ namespace Unity.Netcode
|
|||||||
networkBehaviour.__getTypeName(),
|
networkBehaviour.__getTypeName(),
|
||||||
context.MessageSize);
|
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))
|
if (m_ReceivedNetworkVariableData.Position > (readStartPos + varSize))
|
||||||
{
|
{
|
||||||
@@ -289,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
|
else
|
||||||
@@ -296,7 +487,7 @@ namespace Unity.Netcode
|
|||||||
// DANGO-TODO: Fix me!
|
// DANGO-TODO: Fix me!
|
||||||
// When a client-spawned NetworkObject is despawned by the owner client, the owner client will still get messages for deltas and cause this to
|
// When a client-spawned NetworkObject is despawned by the owner client, the owner client will still get messages for deltas and cause this to
|
||||||
// log a warning. The issue is primarily how NetworkVariables handle updating and will require some additional re-factoring.
|
// log a warning. The issue is primarily how NetworkVariables handle updating and will require some additional re-factoring.
|
||||||
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, m_ReceivedNetworkVariableData, ref context, GetType().Name);
|
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, m_ReceivedNetworkVariableData, ref context, k_Name);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
public int Version => 0;
|
public int Version => 0;
|
||||||
|
|
||||||
|
private const string k_Name = "DestroyObjectMessage";
|
||||||
|
|
||||||
public ulong NetworkObjectId;
|
public ulong NetworkObjectId;
|
||||||
|
|
||||||
private byte m_BitField;
|
private byte m_BitField;
|
||||||
@@ -68,10 +70,6 @@ namespace Unity.Netcode
|
|||||||
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
|
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
|
||||||
{
|
{
|
||||||
var networkManager = (NetworkManager)context.SystemOwner;
|
var networkManager = (NetworkManager)context.SystemOwner;
|
||||||
if (!networkManager.IsClient)
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
ByteUnpacker.ReadValueBitPacked(reader, out NetworkObjectId);
|
ByteUnpacker.ReadValueBitPacked(reader, out NetworkObjectId);
|
||||||
reader.ReadValueSafe(out m_BitField);
|
reader.ReadValueSafe(out m_BitField);
|
||||||
@@ -92,7 +90,7 @@ namespace Unity.Netcode
|
|||||||
// If the target NetworkObject does not exist =or= the target latest parent does not exist then defer the message
|
// If the target NetworkObject does not exist =or= the target latest parent does not exist then defer the message
|
||||||
if (!networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId) || (LatestParent.HasValue && !networkManager.SpawnManager.SpawnedObjects.ContainsKey(LatestParent.Value)))
|
if (!networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId) || (LatestParent.HasValue && !networkManager.SpawnManager.SpawnedObjects.ContainsKey(LatestParent.Value)))
|
||||||
{
|
{
|
||||||
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, GetType().Name);
|
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, k_Name);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
@@ -115,22 +113,28 @@ namespace Unity.Netcode
|
|||||||
networkObject.SetNetworkParenting(LatestParent, WorldPositionStays);
|
networkObject.SetNetworkParenting(LatestParent, WorldPositionStays);
|
||||||
networkObject.ApplyNetworkParenting(RemoveParent);
|
networkObject.ApplyNetworkParenting(RemoveParent);
|
||||||
|
|
||||||
// We set all of the transform values after parenting as they are
|
// This check is primarily for client-server network topologies when the motion model is owner authoritative:
|
||||||
// the values of the server-side post-parenting transform values
|
// When SyncOwnerTransformWhenParented is enabled, then always apply the transform values.
|
||||||
if (!WorldPositionStays)
|
// When SyncOwnerTransformWhenParented is disabled, then only synchronize the transform on non-owner instances.
|
||||||
|
if (networkObject.SyncOwnerTransformWhenParented || (!networkObject.SyncOwnerTransformWhenParented && !networkObject.IsOwner))
|
||||||
{
|
{
|
||||||
networkObject.transform.localPosition = Position;
|
// We set all of the transform values after parenting as they are
|
||||||
networkObject.transform.localRotation = Rotation;
|
// the values of the server-side post-parenting transform values
|
||||||
|
if (!WorldPositionStays)
|
||||||
|
{
|
||||||
|
networkObject.transform.localPosition = Position;
|
||||||
|
networkObject.transform.localRotation = Rotation;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
networkObject.transform.position = Position;
|
||||||
|
networkObject.transform.rotation = Rotation;
|
||||||
|
}
|
||||||
|
networkObject.transform.localScale = Scale;
|
||||||
}
|
}
|
||||||
else
|
|
||||||
{
|
|
||||||
networkObject.transform.position = Position;
|
|
||||||
networkObject.transform.rotation = Rotation;
|
|
||||||
}
|
|
||||||
networkObject.transform.localScale = Scale;
|
|
||||||
|
|
||||||
// If in distributed authority mode and we are running a DAHost and this is the DAHost, then forward the parent changed message to any remaining clients
|
// If 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 size = 0;
|
||||||
var message = this;
|
var message = this;
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
using System;
|
|
||||||
using Unity.Collections;
|
using Unity.Collections;
|
||||||
|
|
||||||
namespace Unity.Netcode
|
namespace Unity.Netcode
|
||||||
@@ -34,21 +33,13 @@ namespace Unity.Netcode
|
|||||||
var networkManager = (NetworkManager)context.SystemOwner;
|
var networkManager = (NetworkManager)context.SystemOwner;
|
||||||
if (!networkManager.SpawnManager.SpawnedObjects.TryGetValue(WrappedMessage.Metadata.NetworkObjectId, out var networkObject))
|
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.
|
// If the NetworkObject no longer exists then just log a warning when developer mode logging is enabled and exit.
|
||||||
// DANGO-TODO: Should the CMB Service cull out any Rpcs targeting recently despawned NetworkObjects?
|
// This can happen if NetworkObject is despawned and a client sends an RPC before receiving the despawn message.
|
||||||
// DANGO-TODO: This would require the service to keep track of despawned NetworkObjects since we re-use NetworkObject identifiers.
|
if (networkManager.LogLevel == LogLevel.Developer)
|
||||||
if (networkManager.DistributedAuthorityMode)
|
|
||||||
{
|
{
|
||||||
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.");
|
|
||||||
}
|
}
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var observers = networkObject.Observers;
|
var observers = networkObject.Observers;
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
payload = new FastBufferReader(reader.GetUnsafePtrAtCurrentPosition(), Allocator.None, reader.Length - reader.Position);
|
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))
|
if (NetworkBehaviour.__rpc_name_table[networkBehaviour.GetType()].TryGetValue(metadata.NetworkRpcMethodId, out var rpcMethodName))
|
||||||
{
|
{
|
||||||
networkManager.NetworkMetrics.TrackRpcReceived(
|
networkManager.NetworkMetrics.TrackRpcReceived(
|
||||||
@@ -60,7 +60,13 @@ namespace Unity.Netcode
|
|||||||
var networkManager = (NetworkManager)context.SystemOwner;
|
var networkManager = (NetworkManager)context.SystemOwner;
|
||||||
if (!networkManager.SpawnManager.SpawnedObjects.TryGetValue(metadata.NetworkObjectId, out var networkObject))
|
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);
|
var networkBehaviour = networkObject.GetNetworkBehaviourAtOrderIndex(metadata.NetworkBehaviourId);
|
||||||
|
|
||||||
@@ -99,6 +105,8 @@ namespace Unity.Netcode
|
|||||||
public FastBufferWriter WriteBuffer;
|
public FastBufferWriter WriteBuffer;
|
||||||
public FastBufferReader ReadBuffer;
|
public FastBufferReader ReadBuffer;
|
||||||
|
|
||||||
|
private const string k_Name = "ServerRpcMessage";
|
||||||
|
|
||||||
public unsafe void Serialize(FastBufferWriter writer, int targetVersion)
|
public unsafe void Serialize(FastBufferWriter writer, int targetVersion)
|
||||||
{
|
{
|
||||||
RpcMessageHelpers.Serialize(ref writer, ref Metadata, ref WriteBuffer);
|
RpcMessageHelpers.Serialize(ref writer, ref Metadata, ref WriteBuffer);
|
||||||
@@ -106,7 +114,7 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
public unsafe bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
|
public unsafe bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
|
||||||
{
|
{
|
||||||
return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, GetType().Name);
|
return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, k_Name);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Handle(ref NetworkContext context)
|
public void Handle(ref NetworkContext context)
|
||||||
@@ -134,6 +142,8 @@ namespace Unity.Netcode
|
|||||||
public FastBufferWriter WriteBuffer;
|
public FastBufferWriter WriteBuffer;
|
||||||
public FastBufferReader ReadBuffer;
|
public FastBufferReader ReadBuffer;
|
||||||
|
|
||||||
|
private const string k_Name = "ClientRpcMessage";
|
||||||
|
|
||||||
public void Serialize(FastBufferWriter writer, int targetVersion)
|
public void Serialize(FastBufferWriter writer, int targetVersion)
|
||||||
{
|
{
|
||||||
RpcMessageHelpers.Serialize(ref writer, ref Metadata, ref WriteBuffer);
|
RpcMessageHelpers.Serialize(ref writer, ref Metadata, ref WriteBuffer);
|
||||||
@@ -141,7 +151,7 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
|
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
|
||||||
{
|
{
|
||||||
return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, GetType().Name);
|
return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, k_Name);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Handle(ref NetworkContext context)
|
public void Handle(ref NetworkContext context)
|
||||||
@@ -169,6 +179,8 @@ namespace Unity.Netcode
|
|||||||
public FastBufferWriter WriteBuffer;
|
public FastBufferWriter WriteBuffer;
|
||||||
public FastBufferReader ReadBuffer;
|
public FastBufferReader ReadBuffer;
|
||||||
|
|
||||||
|
private const string k_Name = "RpcMessage";
|
||||||
|
|
||||||
public unsafe void Serialize(FastBufferWriter writer, int targetVersion)
|
public unsafe void Serialize(FastBufferWriter writer, int targetVersion)
|
||||||
{
|
{
|
||||||
BytePacker.WriteValuePacked(writer, SenderClientId);
|
BytePacker.WriteValuePacked(writer, SenderClientId);
|
||||||
@@ -179,7 +191,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
ByteUnpacker.ReadValuePacked(reader, out SenderClientId);
|
ByteUnpacker.ReadValuePacked(reader, out SenderClientId);
|
||||||
|
|
||||||
return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, GetType().Name);
|
return RpcMessageHelpers.Deserialize(ref reader, ref context, ref Metadata, ref ReadBuffer, k_Name);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Handle(ref NetworkContext context)
|
public void Handle(ref NetworkContext context)
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
public void Handle(ref NetworkContext context)
|
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
|
internal class NetworkMessageManager : IDisposable
|
||||||
{
|
{
|
||||||
public bool StopProcessing = false;
|
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
|
private struct ReceiveQueueItem
|
||||||
{
|
{
|
||||||
@@ -120,75 +123,24 @@ namespace Unity.Netcode
|
|||||||
public VersionGetter GetVersion;
|
public VersionGetter GetVersion;
|
||||||
}
|
}
|
||||||
|
|
||||||
internal List<MessageWithHandler> PrioritizeMessageOrder(List<MessageWithHandler> allowedTypes)
|
|
||||||
{
|
|
||||||
var prioritizedTypes = new List<MessageWithHandler>();
|
|
||||||
|
|
||||||
// First pass puts the priority message in the first indices
|
|
||||||
// Those are the messages that must be delivered in order to allow re-ordering the others later
|
|
||||||
foreach (var t in allowedTypes)
|
|
||||||
{
|
|
||||||
if (t.MessageType.FullName == typeof(ConnectionRequestMessage).FullName ||
|
|
||||||
t.MessageType.FullName == typeof(ConnectionApprovedMessage).FullName)
|
|
||||||
{
|
|
||||||
prioritizedTypes.Add(t);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach (var t in allowedTypes)
|
|
||||||
{
|
|
||||||
if (t.MessageType.FullName != typeof(ConnectionRequestMessage).FullName &&
|
|
||||||
t.MessageType.FullName != typeof(ConnectionApprovedMessage).FullName)
|
|
||||||
{
|
|
||||||
prioritizedTypes.Add(t);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return prioritizedTypes;
|
|
||||||
}
|
|
||||||
|
|
||||||
public NetworkMessageManager(INetworkMessageSender sender, object owner, INetworkMessageProvider provider = null)
|
public NetworkMessageManager(INetworkMessageSender sender, object owner, INetworkMessageProvider provider = null)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
m_Sender = sender;
|
m_Sender = sender;
|
||||||
m_Owner = owner;
|
m_Owner = owner;
|
||||||
|
|
||||||
if (provider == null)
|
if (provider == null)
|
||||||
{
|
{
|
||||||
provider = new ILPPMessageProvider();
|
provider = new ILPPMessageProvider();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get the presorted message types returned by the provider
|
||||||
var allowedTypes = provider.GetMessages();
|
var allowedTypes = provider.GetMessages();
|
||||||
|
|
||||||
allowedTypes.Sort((a, b) => string.CompareOrdinal(a.MessageType.FullName, b.MessageType.FullName));
|
|
||||||
allowedTypes = PrioritizeMessageOrder(allowedTypes);
|
|
||||||
foreach (var type in allowedTypes)
|
foreach (var type in allowedTypes)
|
||||||
{
|
{
|
||||||
RegisterMessageType(type);
|
RegisterMessageType(type);
|
||||||
}
|
}
|
||||||
|
|
||||||
#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)
|
catch (Exception)
|
||||||
{
|
{
|
||||||
@@ -553,6 +505,7 @@ namespace Unity.Netcode
|
|||||||
return new T().Version;
|
return new T().Version;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
internal int GetMessageVersion(Type type, ulong clientId, bool forReceive = false)
|
internal int GetMessageVersion(Type type, ulong clientId, bool forReceive = false)
|
||||||
{
|
{
|
||||||
if (!m_PerClientMessageVersions.TryGetValue(clientId, out var versionMap))
|
if (!m_PerClientMessageVersions.TryGetValue(clientId, out var versionMap))
|
||||||
@@ -580,16 +533,20 @@ namespace Unity.Netcode
|
|||||||
return messageVersion;
|
return messageVersion;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
public static void ReceiveMessage<T>(FastBufferReader reader, ref NetworkContext context, NetworkMessageManager manager) where T : INetworkMessage, new()
|
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 message = new T();
|
||||||
var messageVersion = 0;
|
var messageVersion = 0;
|
||||||
|
|
||||||
// Special cases because these are the messages that carry the version info - thus the version info isn't
|
// 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
|
// populated yet when we get these. The first part of these messages always has to be the version data
|
||||||
// and can't change.
|
// 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)
|
if (messageVersion < 0)
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
@@ -641,7 +598,7 @@ namespace Unity.Netcode
|
|||||||
var messageVersion = 0;
|
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.
|
// 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.
|
// 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]);
|
messageVersion = GetMessageVersion(typeof(TMessageType), clientIds[i]);
|
||||||
if (messageVersion < 0)
|
if (messageVersion < 0)
|
||||||
@@ -695,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.
|
// 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.
|
// 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]);
|
var messageVersion = GetMessageVersion(typeof(TMessageType), clientIds[i]);
|
||||||
if (messageVersion < 0)
|
if (messageVersion < 0)
|
||||||
@@ -754,7 +711,11 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
ref var writeQueueItem = ref sendQueueItem.ElementAt(sendQueueItem.Length - 1);
|
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(headerSerializer.GetUnsafePtr(), headerSerializer.Length);
|
||||||
writeQueueItem.Writer.WriteBytes(tmpSerializer.GetUnsafePtr(), tmpSerializer.Length);
|
writeQueueItem.Writer.WriteBytes(tmpSerializer.GetUnsafePtr(), tmpSerializer.Length);
|
||||||
@@ -775,7 +736,7 @@ namespace Unity.Netcode
|
|||||||
// Special case because this is the message that carries the version info - thus the version info isn't
|
// 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
|
// populated yet when we get this. The first part of this message always has to be the version data
|
||||||
// and can't change.
|
// and can't change.
|
||||||
if (typeof(TMessageType) != typeof(ConnectionRequestMessage))
|
if (typeof(TMessageType) != s_ConnectionRequestType)
|
||||||
{
|
{
|
||||||
messageVersion = GetMessageVersion(typeof(TMessageType), clientId);
|
messageVersion = GetMessageVersion(typeof(TMessageType), clientId);
|
||||||
if (messageVersion < 0)
|
if (messageVersion < 0)
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ namespace Unity.Netcode
|
|||||||
/// <para>Marks a method as ServerRpc.</para>
|
/// <para>Marks a method as ServerRpc.</para>
|
||||||
/// <para>A ServerRpc marked method will be fired by a client but executed on the server.</para>
|
/// <para>A ServerRpc marked method will be fired by a client but executed on the server.</para>
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[AttributeUsage(AttributeTargets.Method)]
|
[AttributeUsage(AttributeTargets.Method), Obsolete]
|
||||||
public class ServerRpcAttribute : RpcAttribute
|
public class ServerRpcAttribute : RpcAttribute
|
||||||
{
|
{
|
||||||
public new bool RequireOwnership;
|
public new bool RequireOwnership;
|
||||||
@@ -72,7 +72,7 @@ namespace Unity.Netcode
|
|||||||
/// <para>Marks a method as ClientRpc.</para>
|
/// <para>Marks a method as ClientRpc.</para>
|
||||||
/// <para>A ClientRpc marked method will be fired by the server but executed on clients.</para>
|
/// <para>A ClientRpc marked method will be fired by the server but executed on clients.</para>
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[AttributeUsage(AttributeTargets.Method)]
|
[AttributeUsage(AttributeTargets.Method), Obsolete]
|
||||||
public class ClientRpcAttribute : RpcAttribute
|
public class ClientRpcAttribute : RpcAttribute
|
||||||
{
|
{
|
||||||
public ClientRpcAttribute() : base(SendTo.NotServer)
|
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)
|
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 =
|
var size =
|
||||||
#endif
|
#endif
|
||||||
behaviour.NetworkManager.MessageManager.SendMessage(ref message, delivery, clientId);
|
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))
|
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
|
||||||
{
|
{
|
||||||
behaviour.NetworkManager.NetworkMetrics.TrackRpcSent(
|
behaviour.NetworkManager.NetworkMetrics.TrackRpcSent(
|
||||||
|
|||||||
@@ -17,7 +17,8 @@ namespace Unity.Netcode
|
|||||||
// ClientsAndHost sends to everyone who runs any client logic
|
// 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)
|
// 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 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;
|
m_UnderlyingTarget = behaviour.RpcTarget.Everyone;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,23 +4,37 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
private NotServerRpcTarget m_NotServerRpcTarget;
|
private NotServerRpcTarget m_NotServerRpcTarget;
|
||||||
private ServerRpcTarget m_ServerRpcTarget;
|
private ServerRpcTarget m_ServerRpcTarget;
|
||||||
|
private NotAuthorityRpcTarget m_NotAuthorityRpcTarget;
|
||||||
|
private AuthorityRpcTarget m_AuthorityRpcTarget;
|
||||||
|
|
||||||
public override void Dispose()
|
public override void Dispose()
|
||||||
{
|
{
|
||||||
m_NotServerRpcTarget.Dispose();
|
m_NotServerRpcTarget.Dispose();
|
||||||
m_ServerRpcTarget.Dispose();
|
m_ServerRpcTarget.Dispose();
|
||||||
|
m_NotAuthorityRpcTarget.Dispose();
|
||||||
|
m_AuthorityRpcTarget.Dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
|
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
|
||||||
{
|
{
|
||||||
m_NotServerRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
if (NetworkManager.IsDistributedAuthority)
|
||||||
m_ServerRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
{
|
||||||
|
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)
|
internal EveryoneRpcTarget(NetworkManager manager) : base(manager)
|
||||||
{
|
{
|
||||||
m_NotServerRpcTarget = new NotServerRpcTarget(manager);
|
m_NotServerRpcTarget = new NotServerRpcTarget(manager);
|
||||||
m_ServerRpcTarget = new ServerRpcTarget(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);
|
message.Handle(ref context);
|
||||||
length = tempBuffer.Length;
|
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))
|
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
|
||||||
{
|
{
|
||||||
networkManager.NetworkMetrics.TrackRpcSent(
|
networkManager.NetworkMetrics.TrackRpcSent(
|
||||||
|
|||||||
@@ -29,6 +29,12 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
continue;
|
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);
|
m_GroupSendTarget.Add(clientId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -41,6 +47,12 @@ namespace Unity.Netcode
|
|||||||
continue;
|
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)
|
if (clientId == m_NetworkManager.LocalClientId)
|
||||||
{
|
{
|
||||||
m_LocalSendRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
m_LocalSendRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||||
|
|||||||
@@ -4,12 +4,14 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
private IGroupRpcTarget m_GroupSendTarget;
|
private IGroupRpcTarget m_GroupSendTarget;
|
||||||
private ServerRpcTarget m_ServerRpcTarget;
|
private ServerRpcTarget m_ServerRpcTarget;
|
||||||
|
private NotAuthorityRpcTarget m_NotAuthorityRpcTarget;
|
||||||
private LocalSendRpcTarget m_LocalSendRpcTarget;
|
private LocalSendRpcTarget m_LocalSendRpcTarget;
|
||||||
|
|
||||||
public override void Dispose()
|
public override void Dispose()
|
||||||
{
|
{
|
||||||
m_ServerRpcTarget.Dispose();
|
m_ServerRpcTarget.Dispose();
|
||||||
m_LocalSendRpcTarget.Dispose();
|
m_LocalSendRpcTarget.Dispose();
|
||||||
|
m_NotAuthorityRpcTarget.Dispose();
|
||||||
if (m_GroupSendTarget != null)
|
if (m_GroupSendTarget != null)
|
||||||
{
|
{
|
||||||
m_GroupSendTarget.Target.Dispose();
|
m_GroupSendTarget.Target.Dispose();
|
||||||
@@ -19,6 +21,13 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
|
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 (m_GroupSendTarget == null)
|
||||||
{
|
{
|
||||||
if (behaviour.IsServer)
|
if (behaviour.IsServer)
|
||||||
@@ -86,6 +95,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
m_ServerRpcTarget = new ServerRpcTarget(manager);
|
m_ServerRpcTarget = new ServerRpcTarget(manager);
|
||||||
m_LocalSendRpcTarget = new LocalSendRpcTarget(manager);
|
m_LocalSendRpcTarget = new LocalSendRpcTarget(manager);
|
||||||
|
m_NotAuthorityRpcTarget = new NotAuthorityRpcTarget(manager);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,7 +51,13 @@ namespace Unity.Netcode
|
|||||||
continue;
|
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);
|
m_LocalSendRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||||
continue;
|
continue;
|
||||||
|
|||||||
@@ -5,9 +5,12 @@ namespace Unity.Netcode
|
|||||||
private IIndividualRpcTarget m_UnderlyingTarget;
|
private IIndividualRpcTarget m_UnderlyingTarget;
|
||||||
private LocalSendRpcTarget m_LocalRpcTarget;
|
private LocalSendRpcTarget m_LocalRpcTarget;
|
||||||
private ServerRpcTarget m_ServerRpcTarget;
|
private ServerRpcTarget m_ServerRpcTarget;
|
||||||
|
private AuthorityRpcTarget m_AuthorityRpcTarget;
|
||||||
|
|
||||||
public override void Dispose()
|
public override void Dispose()
|
||||||
{
|
{
|
||||||
|
m_AuthorityRpcTarget.Dispose();
|
||||||
|
m_ServerRpcTarget.Dispose();
|
||||||
m_LocalRpcTarget.Dispose();
|
m_LocalRpcTarget.Dispose();
|
||||||
if (m_UnderlyingTarget != null)
|
if (m_UnderlyingTarget != null)
|
||||||
{
|
{
|
||||||
@@ -18,6 +21,13 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
internal override void Send(NetworkBehaviour behaviour, ref RpcMessage message, NetworkDelivery delivery, RpcParams rpcParams)
|
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)
|
if (behaviour.OwnerClientId == behaviour.NetworkManager.LocalClientId)
|
||||||
{
|
{
|
||||||
m_LocalRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
m_LocalRpcTarget.Send(behaviour, ref message, delivery, rpcParams);
|
||||||
@@ -49,6 +59,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
m_LocalRpcTarget = new LocalSendRpcTarget(manager);
|
m_LocalRpcTarget = new LocalSendRpcTarget(manager);
|
||||||
m_ServerRpcTarget = new ServerRpcTarget(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)
|
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 };
|
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 =
|
var size =
|
||||||
#endif
|
#endif
|
||||||
behaviour.NetworkManager.MessageManager.SendMessage(ref proxyMessage, delivery, NetworkManager.ServerClientId);
|
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))
|
if (NetworkBehaviour.__rpc_name_table[behaviour.GetType()].TryGetValue(message.Metadata.NetworkRpcMethodId, out var rpcMethodName))
|
||||||
{
|
{
|
||||||
foreach (var clientId in TargetClientIds)
|
foreach (var clientId in TargetClientIds)
|
||||||
|
|||||||
@@ -79,9 +79,28 @@ namespace Unity.Netcode
|
|||||||
SpecifiedInParams
|
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
|
public enum RpcTargetUse
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Creates a temporary <see cref="BaseRpcTarget"/> used for the frame an <see cref="RpcAttribute"/> decorated method is invoked.
|
||||||
|
/// </summary>
|
||||||
Temp,
|
Temp,
|
||||||
|
/// <summary>
|
||||||
|
/// Creates a persisted <see cref="BaseRpcTarget"/> that does not change and will persist until <see cref="BaseRpcTarget.Dispose"/> is called.
|
||||||
|
/// </summary>
|
||||||
Persistent
|
Persistent
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
|
using Unity.Collections;
|
||||||
namespace Unity.Netcode
|
namespace Unity.Netcode
|
||||||
{
|
{
|
||||||
internal class ServerRpcTarget : BaseRpcTarget
|
internal class ServerRpcTarget : BaseRpcTarget
|
||||||
{
|
{
|
||||||
protected BaseRpcTarget m_UnderlyingTarget;
|
protected BaseRpcTarget m_UnderlyingTarget;
|
||||||
|
protected ProxyRpcTarget m_ProxyRpcTarget;
|
||||||
|
|
||||||
public override void Dispose()
|
public override void Dispose()
|
||||||
{
|
{
|
||||||
@@ -11,13 +13,62 @@ namespace Unity.Netcode
|
|||||||
m_UnderlyingTarget.Dispose();
|
m_UnderlyingTarget.Dispose();
|
||||||
m_UnderlyingTarget = null;
|
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)
|
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)
|
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;
|
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
|
/// The callback to be invoked when the list gets changed
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public event OnListChangedDelegate OnListChanged;
|
public event OnListChangedDelegate OnListChanged;
|
||||||
internal override NetworkVariableType Type => NetworkVariableType.NetworkList;
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Constructor method for <see cref="NetworkList"/>
|
/// Constructor method for <see cref="NetworkList"/>
|
||||||
@@ -50,6 +49,11 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
~NetworkList()
|
||||||
|
{
|
||||||
|
Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public override void ResetDirty()
|
public override void ResetDirty()
|
||||||
{
|
{
|
||||||
@@ -94,18 +98,18 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
case NetworkListEvent<T>.EventType.Add:
|
case NetworkListEvent<T>.EventType.Add:
|
||||||
{
|
{
|
||||||
NetworkVariableSerialization<T>.Write(writer, ref element.Value);
|
NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case NetworkListEvent<T>.EventType.Insert:
|
case NetworkListEvent<T>.EventType.Insert:
|
||||||
{
|
{
|
||||||
BytePacker.WriteValueBitPacked(writer, element.Index);
|
BytePacker.WriteValueBitPacked(writer, element.Index);
|
||||||
NetworkVariableSerialization<T>.Write(writer, ref element.Value);
|
NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case NetworkListEvent<T>.EventType.Remove:
|
case NetworkListEvent<T>.EventType.Remove:
|
||||||
{
|
{
|
||||||
NetworkVariableSerialization<T>.Write(writer, ref element.Value);
|
NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case NetworkListEvent<T>.EventType.RemoveAt:
|
case NetworkListEvent<T>.EventType.RemoveAt:
|
||||||
@@ -116,7 +120,7 @@ namespace Unity.Netcode
|
|||||||
case NetworkListEvent<T>.EventType.Value:
|
case NetworkListEvent<T>.EventType.Value:
|
||||||
{
|
{
|
||||||
BytePacker.WriteValueBitPacked(writer, element.Index);
|
BytePacker.WriteValueBitPacked(writer, element.Index);
|
||||||
NetworkVariableSerialization<T>.Write(writer, ref element.Value);
|
NetworkVariableSerialization<T>.Serializer.Write(writer, ref element.Value);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case NetworkListEvent<T>.EventType.Clear:
|
case NetworkListEvent<T>.EventType.Clear:
|
||||||
@@ -131,24 +135,10 @@ namespace Unity.Netcode
|
|||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public override void WriteField(FastBufferWriter writer)
|
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);
|
writer.WriteValueSafe((ushort)m_List.Length);
|
||||||
for (int i = 0; i < m_List.Length; i++)
|
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)
|
public override void ReadField(FastBufferReader reader)
|
||||||
{
|
{
|
||||||
m_List.Clear();
|
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);
|
reader.ReadValueSafe(out ushort count);
|
||||||
for (int i = 0; i < count; i++)
|
for (int i = 0; i < count; i++)
|
||||||
{
|
{
|
||||||
var value = new T();
|
var value = new T();
|
||||||
NetworkVariableSerialization<T>.Read(reader, ref value);
|
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
|
||||||
m_List.Add(value);
|
m_List.Add(value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -177,6 +158,13 @@ namespace Unity.Netcode
|
|||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public override void ReadDelta(FastBufferReader reader, bool keepDirtyDelta)
|
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);
|
reader.ReadValueSafe(out ushort deltaCount);
|
||||||
for (int i = 0; i < deltaCount; i++)
|
for (int i = 0; i < deltaCount; i++)
|
||||||
{
|
{
|
||||||
@@ -186,7 +174,7 @@ namespace Unity.Netcode
|
|||||||
case NetworkListEvent<T>.EventType.Add:
|
case NetworkListEvent<T>.EventType.Add:
|
||||||
{
|
{
|
||||||
var value = new T();
|
var value = new T();
|
||||||
NetworkVariableSerialization<T>.Read(reader, ref value);
|
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
|
||||||
m_List.Add(value);
|
m_List.Add(value);
|
||||||
|
|
||||||
if (OnListChanged != null)
|
if (OnListChanged != null)
|
||||||
@@ -199,7 +187,7 @@ namespace Unity.Netcode
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (keepDirtyDelta)
|
if (isServer)
|
||||||
{
|
{
|
||||||
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
||||||
{
|
{
|
||||||
@@ -207,7 +195,11 @@ namespace Unity.Netcode
|
|||||||
Index = m_List.Length - 1,
|
Index = m_List.Length - 1,
|
||||||
Value = m_List[m_List.Length - 1]
|
Value = m_List[m_List.Length - 1]
|
||||||
});
|
});
|
||||||
MarkNetworkObjectDirty();
|
// Preserve the legacy way of handling this
|
||||||
|
if (keepDirtyDelta)
|
||||||
|
{
|
||||||
|
MarkNetworkObjectDirty();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@@ -215,7 +207,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
ByteUnpacker.ReadValueBitPacked(reader, out int index);
|
ByteUnpacker.ReadValueBitPacked(reader, out int index);
|
||||||
var value = new T();
|
var value = new T();
|
||||||
NetworkVariableSerialization<T>.Read(reader, ref value);
|
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
|
||||||
|
|
||||||
if (index < m_List.Length)
|
if (index < m_List.Length)
|
||||||
{
|
{
|
||||||
@@ -237,7 +229,7 @@ namespace Unity.Netcode
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (keepDirtyDelta)
|
if (isServer)
|
||||||
{
|
{
|
||||||
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
||||||
{
|
{
|
||||||
@@ -245,14 +237,18 @@ namespace Unity.Netcode
|
|||||||
Index = index,
|
Index = index,
|
||||||
Value = m_List[index]
|
Value = m_List[index]
|
||||||
});
|
});
|
||||||
MarkNetworkObjectDirty();
|
// Preserve the legacy way of handling this
|
||||||
|
if (keepDirtyDelta)
|
||||||
|
{
|
||||||
|
MarkNetworkObjectDirty();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case NetworkListEvent<T>.EventType.Remove:
|
case NetworkListEvent<T>.EventType.Remove:
|
||||||
{
|
{
|
||||||
var value = new T();
|
var value = new T();
|
||||||
NetworkVariableSerialization<T>.Read(reader, ref value);
|
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
|
||||||
int index = m_List.IndexOf(value);
|
int index = m_List.IndexOf(value);
|
||||||
if (index == -1)
|
if (index == -1)
|
||||||
{
|
{
|
||||||
@@ -271,7 +267,7 @@ namespace Unity.Netcode
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (keepDirtyDelta)
|
if (isServer)
|
||||||
{
|
{
|
||||||
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
||||||
{
|
{
|
||||||
@@ -279,7 +275,11 @@ namespace Unity.Netcode
|
|||||||
Index = index,
|
Index = index,
|
||||||
Value = value
|
Value = value
|
||||||
});
|
});
|
||||||
MarkNetworkObjectDirty();
|
// Preserve the legacy way of handling this
|
||||||
|
if (keepDirtyDelta)
|
||||||
|
{
|
||||||
|
MarkNetworkObjectDirty();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@@ -299,7 +299,7 @@ namespace Unity.Netcode
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (keepDirtyDelta)
|
if (isServer)
|
||||||
{
|
{
|
||||||
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
||||||
{
|
{
|
||||||
@@ -307,7 +307,11 @@ namespace Unity.Netcode
|
|||||||
Index = index,
|
Index = index,
|
||||||
Value = value
|
Value = value
|
||||||
});
|
});
|
||||||
MarkNetworkObjectDirty();
|
// Preserve the legacy way of handling this
|
||||||
|
if (keepDirtyDelta)
|
||||||
|
{
|
||||||
|
MarkNetworkObjectDirty();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@@ -315,7 +319,7 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
ByteUnpacker.ReadValueBitPacked(reader, out int index);
|
ByteUnpacker.ReadValueBitPacked(reader, out int index);
|
||||||
var value = new T();
|
var value = new T();
|
||||||
NetworkVariableSerialization<T>.Read(reader, ref value);
|
NetworkVariableSerialization<T>.Serializer.Read(reader, ref value);
|
||||||
if (index >= m_List.Length)
|
if (index >= m_List.Length)
|
||||||
{
|
{
|
||||||
throw new Exception("Shouldn't be here, index is higher than 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>()
|
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
||||||
{
|
{
|
||||||
@@ -344,7 +348,11 @@ namespace Unity.Netcode
|
|||||||
Value = value,
|
Value = value,
|
||||||
PreviousValue = previousValue
|
PreviousValue = previousValue
|
||||||
});
|
});
|
||||||
MarkNetworkObjectDirty();
|
// Preserve the legacy way of handling this
|
||||||
|
if (keepDirtyDelta)
|
||||||
|
{
|
||||||
|
MarkNetworkObjectDirty();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@@ -361,13 +369,18 @@ namespace Unity.Netcode
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (keepDirtyDelta)
|
if (isServer)
|
||||||
{
|
{
|
||||||
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
m_DirtyEvents.Add(new NetworkListEvent<T>()
|
||||||
{
|
{
|
||||||
Type = eventType
|
Type = eventType
|
||||||
});
|
});
|
||||||
MarkNetworkObjectDirty();
|
|
||||||
|
// Preserve the legacy way of handling this
|
||||||
|
if (keepDirtyDelta)
|
||||||
|
{
|
||||||
|
MarkNetworkObjectDirty();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@@ -381,6 +394,18 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
/// <remarks>
|
||||||
|
/// For NetworkList, we just need to reset dirty if a server has read deltas
|
||||||
|
/// </remarks>
|
||||||
|
internal override void PostDeltaRead()
|
||||||
|
{
|
||||||
|
if (m_NetworkManager.IsServer)
|
||||||
|
{
|
||||||
|
ResetDirty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public IEnumerator<T> GetEnumerator()
|
public IEnumerator<T> GetEnumerator()
|
||||||
{
|
{
|
||||||
@@ -393,7 +418,8 @@ namespace Unity.Netcode
|
|||||||
// check write permissions
|
// check write permissions
|
||||||
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
|
LogWritePermissionError();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
m_List.Add(item);
|
m_List.Add(item);
|
||||||
@@ -414,7 +440,8 @@ namespace Unity.Netcode
|
|||||||
// check write permissions
|
// check write permissions
|
||||||
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
|
LogWritePermissionError();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
m_List.Clear();
|
m_List.Clear();
|
||||||
@@ -440,7 +467,8 @@ namespace Unity.Netcode
|
|||||||
// check write permissions
|
// check write permissions
|
||||||
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
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);
|
int index = m_List.IndexOf(item);
|
||||||
@@ -475,7 +503,8 @@ namespace Unity.Netcode
|
|||||||
// check write permissions
|
// check write permissions
|
||||||
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
|
LogWritePermissionError();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (index < m_List.Length)
|
if (index < m_List.Length)
|
||||||
@@ -520,6 +549,8 @@ namespace Unity.Netcode
|
|||||||
HandleAddListEvent(listEvent);
|
HandleAddListEvent(listEvent);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public T this[int index]
|
public T this[int index]
|
||||||
{
|
{
|
||||||
@@ -529,7 +560,8 @@ namespace Unity.Netcode
|
|||||||
// check write permissions
|
// check write permissions
|
||||||
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
if (!CanClientWrite(m_NetworkManager.LocalClientId))
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException("Client is not allowed to write to this NetworkList");
|
LogWritePermissionError();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var previousValue = m_List[index];
|
var previousValue = m_List[index];
|
||||||
@@ -573,8 +605,16 @@ namespace Unity.Netcode
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public override void Dispose()
|
public override void Dispose()
|
||||||
{
|
{
|
||||||
m_List.Dispose();
|
if (m_List.IsCreated)
|
||||||
m_DirtyEvents.Dispose();
|
{
|
||||||
|
m_List.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (m_DirtyEvents.IsCreated)
|
||||||
|
{
|
||||||
|
m_DirtyEvents.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
base.Dispose();
|
base.Dispose();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,29 @@ namespace Unity.Netcode
|
|||||||
/// The callback to be invoked when the value gets changed
|
/// The callback to be invoked when the value gets changed
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public OnValueChangedDelegate OnValueChanged;
|
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>
|
/// <summary>
|
||||||
/// Constructor for <see cref="NetworkVariable{T}"/>
|
/// Constructor for <see cref="NetworkVariable{T}"/>
|
||||||
@@ -35,6 +57,7 @@ namespace Unity.Netcode
|
|||||||
: base(readPerm, writePerm)
|
: base(readPerm, writePerm)
|
||||||
{
|
{
|
||||||
m_InternalValue = value;
|
m_InternalValue = value;
|
||||||
|
m_InternalOriginalValue = default;
|
||||||
// Since we start with IsDirty = true, this doesn't need to be duplicated
|
// 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
|
// right away. It won't get read until after ResetDirty() is called, and
|
||||||
// the duplicate will be made there. Avoiding calling
|
// 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)
|
if (m_NetworkBehaviour == null || m_NetworkBehaviour != null && !m_NetworkBehaviour.NetworkObject.IsSpawned)
|
||||||
{
|
{
|
||||||
m_InternalValue = value;
|
m_InternalValue = value;
|
||||||
|
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_InternalOriginalValue);
|
||||||
m_PreviousValue = default;
|
m_PreviousValue = default;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -63,6 +87,12 @@ namespace Unity.Netcode
|
|||||||
[SerializeField]
|
[SerializeField]
|
||||||
private protected T m_InternalValue;
|
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 protected T m_PreviousValue;
|
||||||
|
|
||||||
private bool m_HasPreviousValue;
|
private bool m_HasPreviousValue;
|
||||||
@@ -71,27 +101,71 @@ namespace Unity.Netcode
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// The value of the NetworkVariable container
|
/// The value of the NetworkVariable container
|
||||||
/// </summary>
|
/// </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
|
public virtual T Value
|
||||||
{
|
{
|
||||||
get => m_InternalValue;
|
get => m_InternalValue;
|
||||||
set
|
set
|
||||||
{
|
{
|
||||||
// Compare bitwise
|
if (m_NetworkManager && !CanClientWrite(m_NetworkManager.LocalClientId))
|
||||||
if (NetworkVariableSerialization<T>.AreEqual(ref m_InternalValue, ref value))
|
|
||||||
{
|
{
|
||||||
|
LogWritePermissionError();
|
||||||
return;
|
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()
|
internal ref T RefValue()
|
||||||
{
|
{
|
||||||
return ref m_InternalValue;
|
return ref m_InternalValue;
|
||||||
@@ -105,18 +179,26 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
|
|
||||||
m_IsDisposed = true;
|
m_IsDisposed = true;
|
||||||
|
// Dispose the internal value
|
||||||
if (m_InternalValue is IDisposable internalValueDisposable)
|
if (m_InternalValue is IDisposable internalValueDisposable)
|
||||||
{
|
{
|
||||||
internalValueDisposable.Dispose();
|
internalValueDisposable.Dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
m_InternalValue = default;
|
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)
|
if (m_HasPreviousValue && m_PreviousValue is IDisposable previousValueDisposable)
|
||||||
{
|
{
|
||||||
m_HasPreviousValue = false;
|
m_HasPreviousValue = false;
|
||||||
previousValueDisposable.Dispose();
|
previousValueDisposable.Dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
m_PreviousValue = default;
|
m_PreviousValue = default;
|
||||||
|
|
||||||
base.Dispose();
|
base.Dispose();
|
||||||
@@ -133,6 +215,13 @@ namespace Unity.Netcode
|
|||||||
/// <returns>Whether or not the container is dirty</returns>
|
/// <returns>Whether or not the container is dirty</returns>
|
||||||
public override bool IsDirty()
|
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.
|
// For most cases we can use the dirty flag.
|
||||||
// This doesn't work for cases where we're wrapping more complex types
|
// This doesn't work for cases where we're wrapping more complex types
|
||||||
// like INetworkSerializable, NativeList, NativeArray, etc.
|
// like INetworkSerializable, NativeList, NativeArray, etc.
|
||||||
@@ -144,11 +233,11 @@ namespace Unity.Netcode
|
|||||||
return true;
|
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
|
// 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
|
// 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()
|
// in between to checks... but the DIRTY state won't change until ResetDirty()
|
||||||
// is called.
|
// is called.
|
||||||
var dirty = !NetworkVariableSerialization<T>.AreEqual(ref m_PreviousValue, ref m_InternalValue);
|
|
||||||
SetDirty(dirty);
|
SetDirty(dirty);
|
||||||
return dirty;
|
return dirty;
|
||||||
}
|
}
|
||||||
@@ -166,23 +255,12 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
m_HasPreviousValue = true;
|
m_HasPreviousValue = true;
|
||||||
NetworkVariableSerialization<T>.Duplicate(m_InternalValue, ref m_PreviousValue);
|
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();
|
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>
|
/// <summary>
|
||||||
/// Writes the variable to the writer
|
/// Writes the variable to the writer
|
||||||
/// </summary>
|
/// </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>
|
/// <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)
|
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
|
// 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
|
// In a prefect world, whether a variable was A) modified locally or B) received and needs retransmit
|
||||||
// would be stored in different fields
|
// would be stored in different fields
|
||||||
|
// LEGACY NOTE: This is only to handle NetworkVariableDeltaMessage Version 0 connections. The updated
|
||||||
T previousValue = m_InternalValue;
|
// NetworkVariableDeltaMessage no longer uses this approach.
|
||||||
NetworkVariableSerialization<T>.ReadDelta(reader, ref m_InternalValue);
|
|
||||||
|
|
||||||
if (keepDirtyDelta)
|
if (keepDirtyDelta)
|
||||||
{
|
{
|
||||||
SetDirty(true);
|
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 />
|
/// <inheritdoc />
|
||||||
public override void ReadField(FastBufferReader reader)
|
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);
|
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 />
|
/// <inheritdoc />
|
||||||
@@ -226,5 +343,20 @@ namespace Unity.Netcode
|
|||||||
{
|
{
|
||||||
NetworkVariableSerialization<T>.Write(writer, ref m_InternalValue);
|
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
|
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>
|
/// <summary>
|
||||||
/// Interface for network value containers
|
/// Interface for network value containers
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public abstract class NetworkVariableBase : IDisposable
|
public abstract class NetworkVariableBase : IDisposable
|
||||||
{
|
{
|
||||||
|
[SerializeField]
|
||||||
|
internal NetworkVariableUpdateTraits UpdateTraits = default;
|
||||||
|
|
||||||
|
[NonSerialized]
|
||||||
|
internal double LastUpdateSent;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The delivery type (QoS) to send data with
|
/// The delivery type (QoS) to send data with
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -20,7 +35,15 @@ namespace Unity.Netcode
|
|||||||
|
|
||||||
private NetworkManager m_InternalNetworkManager;
|
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
|
private protected NetworkManager m_NetworkManager
|
||||||
{
|
{
|
||||||
@@ -52,7 +75,42 @@ namespace Unity.Netcode
|
|||||||
m_InternalNetworkManager = m_NetworkBehaviour.NetworkObject?.NetworkManager;
|
m_InternalNetworkManager = m_NetworkBehaviour.NetworkObject?.NetworkManager;
|
||||||
// When in distributed authority mode, there is no such thing as server write permissions
|
// When in distributed authority mode, there is no such thing as server write permissions
|
||||||
InternalWritePerm = m_InternalNetworkManager.DistributedAuthorityMode ? NetworkVariableWritePermission.Owner : InternalWritePerm;
|
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>
|
/// <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;
|
internal static bool IgnoreInitializeWarning;
|
||||||
|
|
||||||
protected void MarkNetworkBehaviourDirty()
|
protected void MarkNetworkBehaviourDirty()
|
||||||
@@ -147,6 +227,17 @@ namespace Unity.Netcode
|
|||||||
}
|
}
|
||||||
return;
|
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);
|
m_NetworkBehaviour.NetworkManager.BehaviourUpdater?.AddForUpdate(m_NetworkBehaviour.NetworkObject);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -158,6 +249,12 @@ namespace Unity.Netcode
|
|||||||
m_IsDirty = false;
|
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>
|
/// <summary>
|
||||||
/// Gets Whether or not the container is dirty
|
/// Gets Whether or not the container is dirty
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -174,6 +271,11 @@ namespace Unity.Netcode
|
|||||||
/// <returns>Whether or not the client has permission to read</returns>
|
/// <returns>Whether or not the client has permission to read</returns>
|
||||||
public bool CanClientRead(ulong clientId)
|
public bool CanClientRead(ulong clientId)
|
||||||
{
|
{
|
||||||
|
if (!m_NetworkBehaviour)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
// When in distributed authority mode, everyone can read (but only the owner can write)
|
// When in distributed authority mode, everyone can read (but only the owner can write)
|
||||||
if (m_NetworkManager != null && m_NetworkManager.DistributedAuthorityMode)
|
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>
|
/// <returns>Whether or not the client has permission to write</returns>
|
||||||
public bool CanClientWrite(ulong clientId)
|
public bool CanClientWrite(ulong clientId)
|
||||||
{
|
{
|
||||||
|
if (!m_NetworkBehaviour)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
switch (WritePerm)
|
switch (WritePerm)
|
||||||
{
|
{
|
||||||
default:
|
default:
|
||||||
@@ -231,7 +338,6 @@ namespace Unity.Netcode
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="reader">The stream to read the state from</param>
|
/// <param name="reader">The stream to read the state from</param>
|
||||||
public abstract void ReadField(FastBufferReader reader);
|
public abstract void ReadField(FastBufferReader reader);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Reads delta from the reader and applies them to the internal value
|
/// Reads delta from the reader and applies them to the internal value
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -239,6 +345,32 @@ namespace Unity.Netcode
|
|||||||
/// <param name="keepDirtyDelta">Whether or not the delta should be kept as dirty or consumed</param>
|
/// <param name="keepDirtyDelta">Whether or not the delta should be kept as dirty or consumed</param>
|
||||||
public abstract void ReadDelta(FastBufferReader reader, bool keepDirtyDelta);
|
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>
|
/// <summary>
|
||||||
/// Virtual <see cref="IDisposable"/> implementation
|
/// Virtual <see cref="IDisposable"/> implementation
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -247,47 +379,4 @@ namespace Unity.Netcode
|
|||||||
m_InternalNetworkManager = null;
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user