This repository has been archived on 2025-04-22. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
com.unity.netcode.gameobjects/Runtime/Messaging/Messages/ChangeOwnershipMessage.cs
Unity Technologies 143a6cbd34 com.unity.netcode.gameobjects@2.0.0-exp.2
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

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

## [2.0.0-exp.2] - 2024-04-02

### Added
- Added updates to all internal messages to account for a distributed authority network session connection.  (#2863)
- Added `NetworkRigidbodyBase` that provides users with a more customizable network rigidbody, handles both `Rigidbody` and `Rigidbody2D`, and provides an option to make `NetworkTransform` use the rigid body for motion.  (#2863)
  - For a customized `NetworkRigidbodyBase` class:
    - `NetworkRigidbodyBase.AutoUpdateKinematicState` provides control on whether the kinematic setting will be automatically set or not when ownership changes.
    - `NetworkRigidbodyBase.AutoSetKinematicOnDespawn` provides control on whether isKinematic will automatically be set to true when the associated `NetworkObject` is despawned.
    - `NetworkRigidbodyBase.Initialize` is a protected method that, when invoked, will initialize the instance. This includes options to:
      - Set whether using a `RigidbodyTypes.Rigidbody` or `RigidbodyTypes.Rigidbody2D`.
      - Includes additional optional parameters to set the `NetworkTransform`, `Rigidbody`, and `Rigidbody2d` to use.
  - Provides additional public methods:
    - `NetworkRigidbodyBase.GetPosition` to return the position of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).
    - `NetworkRigidbodyBase.GetRotation` to return the rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).
    - `NetworkRigidbodyBase.MovePosition` to move to the position of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).
    - `NetworkRigidbodyBase.MoveRotation` to move to the rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).
    - `NetworkRigidbodyBase.Move` to move to the position and rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).
    - `NetworkRigidbodyBase.Move` to move to the position and rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).
    - `NetworkRigidbodyBase.SetPosition` to set the position of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).
    - `NetworkRigidbodyBase.SetRotation` to set the rotation of the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting).
    - `NetworkRigidbodyBase.ApplyCurrentTransform` to set the position and rotation of the `Rigidbody` or `Rigidbody2d` based on the associated `GameObject` transform (depending upon its initialized setting).
    - `NetworkRigidbodyBase.WakeIfSleeping` to wake up the rigid body if sleeping.
    - `NetworkRigidbodyBase.SleepRigidbody` to put the rigid body to sleep.
    - `NetworkRigidbodyBase.IsKinematic` to determine if the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting) is currently kinematic.
    - `NetworkRigidbodyBase.SetIsKinematic` to set the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting) current kinematic state.
    - `NetworkRigidbodyBase.ResetInterpolation` to reset the `Rigidbody` or `Rigidbody2d` (depending upon its initialized setting) back to its original interpolation value when initialized.
  - Now includes a `MonoBehaviour.FixedUpdate` implementation that will update the assigned `NetworkTransform` when `NetworkRigidbodyBase.UseRigidBodyForMotion` is true. (#2863)
- Added `RigidbodyContactEventManager` that provides a more optimized way to process collision enter and collision stay events as opposed to the `Monobehaviour` approach. (#2863)
  - Can be used in client-server and distributed authority modes, but is particularly useful in distributed authority.
- Added rigid body motion updates to `NetworkTransform` which allows users to set interolation on rigid bodies. (#2863)
  - Extrapolation is only allowed on authoritative instances, but custom class derived from `NetworkRigidbodyBase` or `NetworkRigidbody` or `NetworkRigidbody2D` automatically switches non-authoritative instances to interpolation if set to extrapolation.
- Added distributed authority mode support to `NetworkAnimator`. (#2863)
- Added session mode selection to `NetworkManager` inspector view. (#2863)
- Added distributed authority permissions feature. (#2863)
- Added distributed authority mode specific `NetworkObject` permissions flags (Distributable, Transferable, and RequestRequired). (#2863)
- Added distributed authority mode specific `NetworkObject.SetOwnershipStatus` method that applies one or more `NetworkObject` instance's ownership flags. If updated when spawned, the ownership permission changes are synchronized with the other connected clients. (#2863)
- Added distributed authority mode specific `NetworkObject.RemoveOwnershipStatus` method that removes one or more `NetworkObject` instance's ownership flags. If updated when spawned, the ownership permission changes are synchronized with the other connected clients. (#2863)
- Added distributed authority mode specific `NetworkObject.HasOwnershipStatus` method that will return (true or false) whether one or more ownership flags is set. (#2863)
- Added distributed authority mode specific `NetworkObject.SetOwnershipLock` method that locks ownership of a `NetworkObject` to prevent ownership from changing until the current owner releases the lock. (#2863)
- Added distributed authority mode specific `NetworkObject.RequestOwnership` method that sends an ownership request to the current owner of a spawned `NetworkObject` instance. (#2863)
- Added distributed authority mode specific `NetworkObject.OnOwnershipRequested` callback handler that is invoked on the owner/authoritative side when a non-owner requests ownership. Depending upon the boolean returned value depends upon whether the request is approved or denied. (#2863)
- Added distributed authority mode specific `NetworkObject.OnOwnershipRequestResponse` callback handler that is invoked when a non-owner's request has been processed. This callback includes a `NetworkObjet.OwnershipRequestResponseStatus` response parameter that describes whether the request was approved or the reason why it was not approved. (#2863)
- Added distributed authority mode specific `NetworkObject.DeferDespawn` method that defers the despawning of `NetworkObject` instances on non-authoritative clients based on the tick offset parameter. (#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 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)
  - 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 `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 `NetworkManager.OnFetchLocalPlayerPrefabToSpawn` callback that, when assigned, will allow the local client to provide the player prefab to be spawned for the local client. (#2863)
  - This is only invoked if the `NetworkConfig.AutoSpawnPlayerPrefabClientSide` property is set to true.
- Added distributed authority mode specific `NetworkBehaviour.HasAuthority` property that determines if the local client has authority over the associated `NetworkObject` instance (typical use case is within a `NetworkBehaviour` script much like that of `IsServer` or `IsClient`). (#2863)
- Added distributed authority mode specific `NetworkBehaviour.IsSessionOwner` property that determines if the local client is the session owner (typical use case would be to determine if the local client can has scene management authority within a `NetworkBehaviour` script). (#2863)
- Added support for distributed authority mode scene management where the currently assigned session owner can start scene events (i.e. scene loading and scene unloading). (#2863)

### Fixed

- 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 client side awareness of other clients is now the same as a server or host. (#2863)
- Changed `NetworkManager.ConnectedClients` can now be accessed by both server and clients. (#2863)
- Changed `NetworkManager.ConnectedClientsList` can now be accessed by both server and clients. (#2863)
- Changed `NetworkTransform` defaults to owner authoritative when connected to a distributed authority session. (#2863)
- Changed `NetworkVariable` defaults to owner write and everyone read permissions when connected to a distributed authority session (even if declared with server read or write permissions).  (#2863)
- Changed `NetworkObject` no longer implements the `MonoBehaviour.Update` method in order to determine whether a `NetworkObject` instance has been migrated to a different scene. Instead, only `NetworkObjects` with the `SceneMigrationSynchronization` property set will be updated internally during the `NetworkUpdateStage.PostLateUpdate` by `NetworkManager`. (#2863)
- Changed `NetworkManager` inspector view layout where properties are now organized by category. (#2863)
- 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)
2024-04-02 00:00:00 +00:00

400 lines
16 KiB
C#

namespace Unity.Netcode
{
internal struct ChangeOwnershipMessage : INetworkMessage, INetworkSerializeByMemcpy
{
public int Version => 0;
public ulong NetworkObjectId;
public ulong OwnerClientId;
// DANGOEXP TODO: Remove these notes or change their format
// SERVICE NOTES:
// When forwarding the message to clients on the CMB Service side,
// you can set the ClientIdCount to 0 and skip writing the ClientIds.
// See the NetworkObjet.OwnershipRequest for more potential service side additions
/// <summary>
/// When requesting, RequestClientId is the requestor.
/// When approving, RequestClientId is the owner that approved.
/// When responding (only for denied), RequestClientId is the requestor
/// </summary>
internal ulong RequestClientId;
internal int ClientIdCount;
internal ulong[] ClientIds;
internal bool DistributedAuthorityMode;
internal ushort OwnershipFlags;
internal byte OwnershipRequestResponseStatus;
private byte m_OwnershipMessageTypeFlags;
private const byte k_OwnershipChanging = 0x01;
private const byte k_OwnershipFlagsUpdate = 0x02;
private const byte k_RequestOwnership = 0x04;
private const byte k_RequestApproved = 0x08;
private const byte k_RequestDenied = 0x10;
// If no flags are set, then ownership is changing
internal bool OwnershipIsChanging
{
get
{
return GetFlag(k_OwnershipChanging);
}
set
{
SetFlag(value, k_OwnershipChanging);
}
}
internal bool OwnershipFlagsUpdate
{
get
{
return GetFlag(k_OwnershipFlagsUpdate);
}
set
{
SetFlag(value, k_OwnershipFlagsUpdate);
}
}
internal bool RequestOwnership
{
get
{
return GetFlag(k_RequestOwnership);
}
set
{
SetFlag(value, k_RequestOwnership);
}
}
internal bool RequestApproved
{
get
{
return GetFlag(k_RequestApproved);
}
set
{
SetFlag(value, k_RequestApproved);
}
}
internal bool RequestDenied
{
get
{
return GetFlag(k_RequestDenied);
}
set
{
SetFlag(value, k_RequestDenied);
}
}
private bool GetFlag(int flag)
{
return (m_OwnershipMessageTypeFlags & flag) != 0;
}
private void SetFlag(bool set, byte flag)
{
if (set) { m_OwnershipMessageTypeFlags = (byte)(m_OwnershipMessageTypeFlags | flag); }
else { m_OwnershipMessageTypeFlags = (byte)(m_OwnershipMessageTypeFlags & ~flag); }
}
public void Serialize(FastBufferWriter writer, int targetVersion)
{
BytePacker.WriteValueBitPacked(writer, NetworkObjectId);
BytePacker.WriteValueBitPacked(writer, OwnerClientId);
if (DistributedAuthorityMode)
{
BytePacker.WriteValueBitPacked(writer, ClientIdCount);
if (ClientIdCount > 0)
{
if (ClientIdCount != ClientIds.Length)
{
throw new System.Exception($"[{nameof(ChangeOwnershipMessage)}] ClientIdCount is {ClientIdCount} but the ClientIds length is {ClientIds.Length}!");
}
foreach (var clientId in ClientIds)
{
BytePacker.WriteValueBitPacked(writer, clientId);
}
}
writer.WriteValueSafe(m_OwnershipMessageTypeFlags);
if (OwnershipFlagsUpdate || OwnershipIsChanging)
{
writer.WriteValueSafe(OwnershipFlags);
}
// When requesting, it is the requestor
// When approving, it is the owner that approved
// When denied, it is the requestor
if (RequestOwnership || RequestApproved || RequestDenied)
{
writer.WriteValueSafe(RequestClientId);
if (RequestDenied)
{
writer.WriteValueSafe(OwnershipRequestResponseStatus);
}
}
}
}
public bool Deserialize(FastBufferReader reader, ref NetworkContext context, int receivedMessageVersion)
{
var networkManager = (NetworkManager)context.SystemOwner;
if (!networkManager.IsClient)
{
return false;
}
ByteUnpacker.ReadValueBitPacked(reader, out NetworkObjectId);
ByteUnpacker.ReadValueBitPacked(reader, out OwnerClientId);
if (networkManager.DistributedAuthorityMode)
{
ByteUnpacker.ReadValueBitPacked(reader, out ClientIdCount);
if (ClientIdCount > 0)
{
ClientIds = new ulong[ClientIdCount];
var clientId = (ulong)0;
for (int i = 0; i < ClientIdCount; i++)
{
ByteUnpacker.ReadValueBitPacked(reader, out clientId);
ClientIds[i] = clientId;
}
}
reader.ReadValueSafe(out m_OwnershipMessageTypeFlags);
if (OwnershipFlagsUpdate || OwnershipIsChanging)
{
reader.ReadValueSafe(out OwnershipFlags);
}
// When requesting, it is the requestor
// When approving, it is the owner that approved
// When denied, it is the requestor
if (RequestOwnership || RequestApproved || RequestDenied)
{
reader.ReadValueSafe(out RequestClientId);
if (RequestDenied)
{
reader.ReadValueSafe(out OwnershipRequestResponseStatus);
}
}
}
// If we are not a DAHost instance and the NetworkObject does not exist then defer it as it very likely is not spawned yet.
// Otherwise if we are the DAHost and it does not exist then we want to forward this message because when the NetworkObject
// is made visible again, the ownership flags and owner information will be synchronized with the DAHost by the current
// authority of the NetworkObject in question.
if (!networkManager.DAHost && !networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId))
{
networkManager.DeferredMessageManager.DeferMessage(IDeferredNetworkMessageManager.TriggerType.OnSpawn, NetworkObjectId, reader, ref context, GetType().Name);
return false;
}
return true;
}
public void Handle(ref NetworkContext context)
{
var networkManager = (NetworkManager)context.SystemOwner;
// If we are the DAHost then forward this message
if (networkManager.DAHost)
{
var clientList = ClientIdCount > 0 ? ClientIds : networkManager.ConnectedClientsIds;
var message = new ChangeOwnershipMessage()
{
NetworkObjectId = NetworkObjectId,
OwnerClientId = OwnerClientId,
DistributedAuthorityMode = true,
OwnershipFlags = OwnershipFlags,
RequestClientId = RequestClientId,
ClientIdCount = 0,
m_OwnershipMessageTypeFlags = m_OwnershipMessageTypeFlags,
};
if (RequestDenied)
{
// If the local DAHost's client is not the target, then forward to the target
if (RequestClientId != networkManager.LocalClientId)
{
message.OwnershipRequestResponseStatus = OwnershipRequestResponseStatus;
networkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.Reliable, RequestClientId);
// We don't want the local DAHost's client to process this message, so exit early
return;
}
}
else if (RequestOwnership)
{
// If the DAHost client is not authority, just forward the message to the authority
if (OwnerClientId != networkManager.LocalClientId)
{
networkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.Reliable, OwnerClientId);
// We don't want the local DAHost's client to process this message, so exit early
return;
}
// Otherwise, fall through and process the request.
}
else
{
foreach (var clientId in clientList)
{
if (clientId == networkManager.LocalClientId)
{
continue;
}
// If ownership is changing and this is not an ownership request approval then ignore the OnwerClientId
// If it is just updating flags then ignore sending to the owner
// If it is a request or approving request, then ignore the RequestClientId
if ((OwnershipIsChanging && !RequestApproved && OwnerClientId == clientId) || (OwnershipFlagsUpdate && clientId == OwnerClientId)
|| ((RequestOwnership || RequestApproved) && clientId == RequestClientId))
{
continue;
}
networkManager.ConnectionManager.SendMessage(ref message, NetworkDelivery.Reliable, clientId);
}
}
// If the NetworkObject is not visible to the DAHost client, then exit early
if (!networkManager.SpawnManager.SpawnedObjects.ContainsKey(NetworkObjectId))
{
return;
}
}
// If ownership is changing, then run through the ownershipd changed sequence
// Note: There is some extended ownership script at the bottom of HandleOwnershipChange
// If not in distributed authority mode, then always go straight to HandleOwnershipChange
if (OwnershipIsChanging || !networkManager.DistributedAuthorityMode)
{
HandleOwnershipChange(ref context);
}
else if (networkManager.DistributedAuthorityMode)
{
// Otherwise, we handle and extended ownership update
HandleExtendedOwnershipUpdate(ref context);
}
}
/// <summary>
/// Handle the
/// </summary>
/// <param name="context"></param>
private void HandleExtendedOwnershipUpdate(ref NetworkContext context)
{
var networkManager = (NetworkManager)context.SystemOwner;
// Handle the extended ownership message types
var networkObject = networkManager.SpawnManager.SpawnedObjects[NetworkObjectId];
if (OwnershipFlagsUpdate)
{
// Just update the ownership flags
networkObject.Ownership = (NetworkObject.OwnershipStatus)OwnershipFlags;
}
else if (RequestOwnership)
{
// Requesting ownership, if allowed it will automatically send the ownership change message
networkObject.OwnershipRequest(RequestClientId);
}
else if (RequestDenied)
{
networkObject.OwnershipRequestResponse((NetworkObject.OwnershipRequestResponseStatus)OwnershipRequestResponseStatus);
}
}
/// <summary>
/// Handle the traditional change in ownership message type logic
/// </summary>
/// <param name="context"></param>
private void HandleOwnershipChange(ref NetworkContext context)
{
var networkManager = (NetworkManager)context.SystemOwner;
var networkObject = networkManager.SpawnManager.SpawnedObjects[NetworkObjectId];
// DANGO-TODO: This probably shouldn't be allowed to happen.
if (networkObject.OwnerClientId == OwnerClientId)
{
UnityEngine.Debug.LogWarning($"Unnecessary ownership changed message for {NetworkObjectId}");
}
var originalOwner = networkObject.OwnerClientId;
networkObject.OwnerClientId = OwnerClientId;
if (networkManager.DistributedAuthorityMode)
{
networkObject.Ownership = (NetworkObject.OwnershipStatus)OwnershipFlags;
}
// We are current owner (client-server) or running in distributed authority mode
if (originalOwner == networkManager.LocalClientId || networkManager.DistributedAuthorityMode)
{
networkObject.InvokeBehaviourOnLostOwnership();
}
// We are new owner or (client-server) or running in distributed authority mode
if (OwnerClientId == networkManager.LocalClientId || networkManager.DistributedAuthorityMode)
{
networkObject.InvokeBehaviourOnGainedOwnership();
}
// If in distributed authority mode
if (networkManager.DistributedAuthorityMode)
{
// Always update the network properties in distributed authority mode
for (int i = 0; i < networkObject.ChildNetworkBehaviours.Count; i++)
{
networkObject.ChildNetworkBehaviours[i].UpdateNetworkProperties();
}
}
else // Otherwise update properties like we would in client-server
{
// For all other clients that are neither the former or current owner, update the behaviours' properties
if (OwnerClientId != networkManager.LocalClientId && originalOwner != networkManager.LocalClientId)
{
for (int i = 0; i < networkObject.ChildNetworkBehaviours.Count; i++)
{
networkObject.ChildNetworkBehaviours[i].UpdateNetworkProperties();
}
}
}
// Always invoke ownership change notifications
networkObject.InvokeOwnershipChanged(originalOwner, OwnerClientId);
// If this change was requested, then notify that the request was approved (doing this last so all ownership
// changes have already been applied if the callback is invoked)
if (networkManager.DistributedAuthorityMode && networkManager.LocalClientId == OwnerClientId)
{
if (RequestApproved)
{
networkObject.OwnershipRequestResponse(NetworkObject.OwnershipRequestResponseStatus.Approved);
}
// If the NetworkObject changed ownership and the Requested flag was set (i.e. it was an ownership request),
// then the new owner granted ownership removes the Requested flag and sends out an ownership status update.
if (networkObject.HasExtendedOwnershipStatus(NetworkObject.OwnershipStatusExtended.Requested))
{
networkObject.RemoveOwnershipExtended(NetworkObject.OwnershipStatusExtended.Requested);
networkObject.SendOwnershipStatusUpdate();
}
}
networkManager.NetworkMetrics.TrackOwnershipChangeReceived(context.SenderId, networkObject, context.MessageSize);
}
}
}