com.unity.netcode.gameobjects@1.8.0

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

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

## [1.8.0] - 2023-12-12

### Added

- Added a new RPC attribute, which is simply `Rpc`. (#2762)
  - This is a generic attribute that can perform the functions of both Server and Client RPCs, as well as enabling client-to-client RPCs. Includes several default targets: `Server`, `NotServer`, `Owner`, `NotOwner`, `Me`, `NotMe`, `ClientsAndHost`, and `Everyone`. Runtime overrides are available for any of these targets, as well as for sending to a specific ID or groups of IDs.
  - This attribute also includes the ability to defer RPCs that are sent to the local process to the start of the next frame instead of executing them immediately, treating them as if they had gone across the network. The default behavior is to execute immediately.
  - This attribute effectively replaces `ServerRpc` and `ClientRpc`. `ServerRpc` and `ClientRpc` remain in their existing forms for backward compatibility, but `Rpc` will be the recommended and most supported option.
- Added `NetworkManager.OnConnectionEvent` as a unified connection event callback to notify clients and servers of all client connections and disconnections within the session (#2762)
- Added `NetworkManager.ServerIsHost` and `NetworkBehaviour.ServerIsHost` to allow a client to tell if it is connected to a host or to a dedicated server (#2762)
- Added `SceneEventProgress.SceneManagementNotEnabled` return status to be returned when a `NetworkSceneManager` method is invoked and scene management is not enabled. (#2735)
- Added `SceneEventProgress.ServerOnlyAction` return status to be returned when a `NetworkSceneManager` method is invoked by a client. (#2735)
- Added `NetworkObject.InstantiateAndSpawn` and `NetworkSpawnManager.InstantiateAndSpawn` methods to simplify prefab spawning by assuring that the prefab is valid and applies any override prior to instantiating the `GameObject` and spawning the `NetworkObject` instance. (#2710)

### Fixed

- Fixed issue where a client disconnected by a server-host would not receive a local notification. (#2789)
- Fixed issue where a server-host could shutdown during a relay connection but periodically the transport disconnect message sent to any connected clients could be dropped. (#2789)
- Fixed issue where a host could disconnect its local client but remain running as a server. (#2789)
- Fixed issue where `OnClientDisconnectedCallback` was not being invoked under certain conditions. (#2789)
- Fixed issue where `OnClientDisconnectedCallback` was always returning 0 as the client identifier. (#2789)
- Fixed issue where if a host or server shutdown while a client owned NetworkObjects (other than the player) it would throw an exception. (#2789)
- Fixed issue where setting values on a `NetworkVariable` or `NetworkList` within `OnNetworkDespawn` during a shutdown sequence would throw an exception. (#2789)
- Fixed issue where a teleport state could potentially be overridden by a previous unreliable delta state. (#2777)
- Fixed issue where `NetworkTransform` was using the `NetworkManager.ServerTime.Tick` as opposed to `NetworkManager.NetworkTickSystem.ServerTime.Tick` during the authoritative side's tick update where it performed a delta state check. (#2777)
- Fixed issue where a parented in-scene placed NetworkObject would be destroyed upon a client or server exiting a network session but not unloading the original scene in which the NetworkObject was placed. (#2737)
- Fixed issue where during client synchronization and scene loading, when client synchronization or the scene loading mode are set to `LoadSceneMode.Single`, a `CreateObjectMessage` could be received, processed, and the resultant spawned `NetworkObject` could be instantiated in the client's currently active scene that could, towards the end of the client synchronization or loading process, be unloaded and cause the newly created `NetworkObject` to be destroyed (and throw and exception). (#2735)
- Fixed issue where a `NetworkTransform` instance with interpolation enabled would result in wide visual motion gaps (stuttering) under above normal latency conditions and a 1-5% or higher packet are drop rate. (#2713)
- Fixed issue where  you could not have multiple source network prefab overrides targeting the same network prefab as their override. (#2710)

### Changed
- Changed the server or host shutdown so it will now perform a "soft shutdown" when `NetworkManager.Shutdown` is invoked. This will send a disconnect notification to all connected clients and the server-host will wait for all connected clients to disconnect or timeout after a 5 second period before completing the shutdown process. (#2789)
- Changed `OnClientDisconnectedCallback` will now return the assigned client identifier on the local client side if the client was approved and assigned one prior to being disconnected. (#2789)
- Changed `NetworkTransform.SetState` (and related methods) now are cumulative during a fractional tick period and sent on the next pending tick. (#2777)
- `NetworkManager.ConnectedClientsIds` is now accessible on the client side and will contain the list of all clients in the session, including the host client if the server is operating in host mode (#2762)
- Changed `NetworkSceneManager` to return a `SceneEventProgress` status and not throw exceptions for methods invoked when scene management is disabled and when a client attempts to access a `NetworkSceneManager` method by a client. (#2735)
- Changed `NetworkTransform` authoritative instance tick registration so a single `NetworkTransform` specific tick event update will update all authoritative instances to improve perofmance. (#2713)
- Changed `NetworkPrefabs.OverrideToNetworkPrefab` dictionary is no longer used/populated due to it ending up being related to a regression bug and not allowing more than one override to be assigned to a network prefab asset. (#2710)
- Changed in-scene placed `NetworkObject`s now store their source network prefab asset's `GlobalObjectIdHash` internally that is used, when scene management is disabled, by clients to spawn the correct prefab even if the `NetworkPrefab` entry has an override. This does not impact dynamically spawning the same prefab which will yield the override on both host and client. (#2710)
- Changed in-scene placed `NetworkObject`s no longer require a `NetworkPrefab` entry with `GlobalObjectIdHash` override in order for clients to properly synchronize. (#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)
This commit is contained in:
Unity Technologies
2023-12-12 00:00:00 +00:00
parent 514166e159
commit 07f206ff9e
99 changed files with 8667 additions and 1710 deletions

View File

@@ -26,8 +26,10 @@ namespace Unity.Netcode.Editor.CodeGen
public static readonly string INetworkMessage_FullName = typeof(INetworkMessage).FullName;
public static readonly string ServerRpcAttribute_FullName = typeof(ServerRpcAttribute).FullName;
public static readonly string ClientRpcAttribute_FullName = typeof(ClientRpcAttribute).FullName;
public static readonly string RpcAttribute_FullName = typeof(RpcAttribute).FullName;
public static readonly string ServerRpcParams_FullName = typeof(ServerRpcParams).FullName;
public static readonly string ClientRpcParams_FullName = typeof(ClientRpcParams).FullName;
public static readonly string RpcParams_FullName = typeof(RpcParams).FullName;
public static readonly string ClientRpcSendParams_FullName = typeof(ClientRpcSendParams).FullName;
public static readonly string ClientRpcReceiveParams_FullName = typeof(ClientRpcReceiveParams).FullName;
public static readonly string ServerRpcSendParams_FullName = typeof(ServerRpcSendParams).FullName;

View File

@@ -363,11 +363,14 @@ namespace Unity.Netcode.Editor.CodeGen
private FieldReference m_NetworkManager_LogLevel_FieldRef;
private MethodReference m_NetworkBehaviour___registerRpc_MethodRef;
private TypeReference m_NetworkBehaviour_TypeRef;
private TypeReference m_AttributeParamsType_TypeRef;
private TypeReference m_NetworkVariableBase_TypeRef;
private MethodReference m_NetworkVariableBase_Initialize_MethodRef;
private MethodReference m_NetworkBehaviour___nameNetworkVariable_MethodRef;
private MethodReference m_NetworkBehaviour_beginSendServerRpc_MethodRef;
private MethodReference m_NetworkBehaviour_endSendServerRpc_MethodRef;
private MethodReference m_NetworkBehaviour_beginSendRpc_MethodRef;
private MethodReference m_NetworkBehaviour_endSendRpc_MethodRef;
private MethodReference m_NetworkBehaviour_beginSendClientRpc_MethodRef;
private MethodReference m_NetworkBehaviour_endSendClientRpc_MethodRef;
private FieldReference m_NetworkBehaviour_rpc_exec_stage_FieldRef;
@@ -378,9 +381,13 @@ namespace Unity.Netcode.Editor.CodeGen
private TypeReference m_RpcParams_TypeRef;
private FieldReference m_RpcParams_Server_FieldRef;
private FieldReference m_RpcParams_Client_FieldRef;
private FieldReference m_RpcParams_Ext_FieldRef;
private TypeReference m_ServerRpcParams_TypeRef;
private FieldReference m_ServerRpcParams_Receive_FieldRef;
private FieldReference m_ServerRpcParams_Receive_SenderClientId_FieldRef;
private FieldReference m_UniversalRpcParams_Receive_FieldRef;
private FieldReference m_UniversalRpcParams_Receive_SenderClientId_FieldRef;
private TypeReference m_UniversalRpcParams_TypeRef;
private TypeReference m_ClientRpcParams_TypeRef;
private MethodReference m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpy_MethodRef;
private MethodReference m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpyArray_MethodRef;
@@ -495,6 +502,8 @@ namespace Unity.Netcode.Editor.CodeGen
private const string k_NetworkBehaviour_NetworkVariableFields = nameof(NetworkBehaviour.NetworkVariableFields);
private const string k_NetworkBehaviour_beginSendServerRpc = nameof(NetworkBehaviour.__beginSendServerRpc);
private const string k_NetworkBehaviour_endSendServerRpc = nameof(NetworkBehaviour.__endSendServerRpc);
private const string k_NetworkBehaviour_beginSendRpc = nameof(NetworkBehaviour.__beginSendRpc);
private const string k_NetworkBehaviour_endSendRpc = nameof(NetworkBehaviour.__endSendRpc);
private const string k_NetworkBehaviour_beginSendClientRpc = nameof(NetworkBehaviour.__beginSendClientRpc);
private const string k_NetworkBehaviour_endSendClientRpc = nameof(NetworkBehaviour.__endSendClientRpc);
private const string k_NetworkBehaviour___initializeVariables = nameof(NetworkBehaviour.__initializeVariables);
@@ -511,8 +520,11 @@ namespace Unity.Netcode.Editor.CodeGen
private const string k_ServerRpcAttribute_RequireOwnership = nameof(ServerRpcAttribute.RequireOwnership);
private const string k_RpcParams_Server = nameof(__RpcParams.Server);
private const string k_RpcParams_Client = nameof(__RpcParams.Client);
private const string k_RpcParams_Ext = nameof(__RpcParams.Ext);
private const string k_ServerRpcParams_Receive = nameof(ServerRpcParams.Receive);
private const string k_RpcParams_Receive = nameof(RpcParams.Receive);
private const string k_ServerRpcReceiveParams_SenderClientId = nameof(ServerRpcReceiveParams.SenderClientId);
private const string k_RpcReceiveParams_SenderClientId = nameof(RpcReceiveParams.SenderClientId);
// CodeGen cannot reference the collections assembly to do a typeof() on it due to a bug that causes that to crash.
private const string k_INativeListBool_FullName = "Unity.Collections.INativeList`1<System.Byte>";
@@ -545,13 +557,20 @@ namespace Unity.Netcode.Editor.CodeGen
TypeDefinition rpcParamsTypeDef = null;
TypeDefinition serverRpcParamsTypeDef = null;
TypeDefinition clientRpcParamsTypeDef = null;
TypeDefinition universalRpcParamsTypeDef = null;
TypeDefinition fastBufferWriterTypeDef = null;
TypeDefinition fastBufferReaderTypeDef = null;
TypeDefinition networkVariableSerializationTypesTypeDef = null;
TypeDefinition bytePackerTypeDef = null;
TypeDefinition byteUnpackerTypeDef = null;
TypeDefinition attributeParamsType = null;
foreach (var netcodeTypeDef in m_NetcodeModule.GetAllTypes())
{
if (attributeParamsType == null && netcodeTypeDef.Name == nameof(RpcAttribute.RpcAttributeParams))
{
attributeParamsType = netcodeTypeDef;
continue;
}
if (networkManagerTypeDef == null && netcodeTypeDef.Name == nameof(NetworkManager))
{
networkManagerTypeDef = netcodeTypeDef;
@@ -588,6 +607,12 @@ namespace Unity.Netcode.Editor.CodeGen
continue;
}
if (universalRpcParamsTypeDef == null && netcodeTypeDef.Name == nameof(RpcParams))
{
universalRpcParamsTypeDef = netcodeTypeDef;
continue;
}
if (clientRpcParamsTypeDef == null && netcodeTypeDef.Name == nameof(ClientRpcParams))
{
clientRpcParamsTypeDef = netcodeTypeDef;
@@ -662,6 +687,8 @@ namespace Unity.Netcode.Editor.CodeGen
}
}
m_AttributeParamsType_TypeRef = moduleDefinition.ImportReference(attributeParamsType);
foreach (var fieldDef in networkManagerTypeDef.Fields)
{
switch (fieldDef.Name)
@@ -696,6 +723,12 @@ namespace Unity.Netcode.Editor.CodeGen
case k_NetworkBehaviour_endSendServerRpc:
m_NetworkBehaviour_endSendServerRpc_MethodRef = moduleDefinition.ImportReference(methodDef);
break;
case k_NetworkBehaviour_beginSendRpc:
m_NetworkBehaviour_beginSendRpc_MethodRef = moduleDefinition.ImportReference(methodDef);
break;
case k_NetworkBehaviour_endSendRpc:
m_NetworkBehaviour_endSendRpc_MethodRef = moduleDefinition.ImportReference(methodDef);
break;
case k_NetworkBehaviour_beginSendClientRpc:
m_NetworkBehaviour_beginSendClientRpc_MethodRef = moduleDefinition.ImportReference(methodDef);
break;
@@ -763,6 +796,9 @@ namespace Unity.Netcode.Editor.CodeGen
case k_RpcParams_Client:
m_RpcParams_Client_FieldRef = moduleDefinition.ImportReference(fieldDef);
break;
case k_RpcParams_Ext:
m_RpcParams_Ext_FieldRef = moduleDefinition.ImportReference(fieldDef);
break;
}
}
@@ -786,6 +822,26 @@ namespace Unity.Netcode.Editor.CodeGen
break;
}
}
m_UniversalRpcParams_TypeRef = moduleDefinition.ImportReference(rpcParamsTypeDef);
foreach (var fieldDef in rpcParamsTypeDef.Fields)
{
switch (fieldDef.Name)
{
case k_RpcParams_Receive:
foreach (var recvFieldDef in fieldDef.FieldType.Resolve().Fields)
{
switch (recvFieldDef.Name)
{
case k_RpcReceiveParams_SenderClientId:
m_UniversalRpcParams_Receive_SenderClientId_FieldRef = moduleDefinition.ImportReference(recvFieldDef);
break;
}
}
m_UniversalRpcParams_Receive_FieldRef = moduleDefinition.ImportReference(fieldDef);
break;
}
}
m_ClientRpcParams_TypeRef = moduleDefinition.ImportReference(clientRpcParamsTypeDef);
m_FastBufferWriter_TypeRef = moduleDefinition.ImportReference(fastBufferWriterTypeDef);
@@ -1354,7 +1410,8 @@ namespace Unity.Netcode.Editor.CodeGen
var customAttributeType_FullName = customAttribute.AttributeType.FullName;
if (customAttributeType_FullName == CodeGenHelpers.ServerRpcAttribute_FullName ||
customAttributeType_FullName == CodeGenHelpers.ClientRpcAttribute_FullName)
customAttributeType_FullName == CodeGenHelpers.ClientRpcAttribute_FullName ||
customAttributeType_FullName == CodeGenHelpers.RpcAttribute_FullName)
{
bool isValid = true;
@@ -1389,6 +1446,13 @@ namespace Unity.Netcode.Editor.CodeGen
isValid = false;
}
if (customAttributeType_FullName == CodeGenHelpers.RpcAttribute_FullName &&
!methodDefinition.Name.EndsWith("Rpc", StringComparison.OrdinalIgnoreCase))
{
m_Diagnostics.AddError(methodDefinition, "Rpc method must end with 'Rpc' suffix!");
isValid = false;
}
if (customAttributeType_FullName == CodeGenHelpers.ClientRpcAttribute_FullName &&
!methodDefinition.Name.EndsWith("ClientRpc", StringComparison.OrdinalIgnoreCase))
{
@@ -1411,11 +1475,15 @@ namespace Unity.Netcode.Editor.CodeGen
{
if (methodDefinition.Name.EndsWith("ServerRpc", StringComparison.OrdinalIgnoreCase))
{
m_Diagnostics.AddError(methodDefinition, "ServerRpc method must be marked with 'ServerRpc' attribute!");
m_Diagnostics.AddError(methodDefinition, $"ServerRpc method {methodDefinition} must be marked with 'ServerRpc' attribute!");
}
else if (methodDefinition.Name.EndsWith("ClientRpc", StringComparison.OrdinalIgnoreCase))
{
m_Diagnostics.AddError(methodDefinition, "ClientRpc method must be marked with 'ClientRpc' attribute!");
m_Diagnostics.AddError(methodDefinition, $"ClientRpc method {methodDefinition} must be marked with 'ClientRpc' attribute!");
}
else if (methodDefinition.Name.EndsWith("ExtRpc", StringComparison.OrdinalIgnoreCase))
{
m_Diagnostics.AddError(methodDefinition, $"Ext Rpc method {methodDefinition} must be marked with 'ExtRpc' attribute!");
}
return null;
@@ -1887,8 +1955,17 @@ namespace Unity.Netcode.Editor.CodeGen
var instructions = new List<Instruction>();
var processor = methodDefinition.Body.GetILProcessor();
var isServerRpc = rpcAttribute.AttributeType.FullName == CodeGenHelpers.ServerRpcAttribute_FullName;
var isClientRpc = rpcAttribute.AttributeType.FullName == CodeGenHelpers.ClientRpcAttribute_FullName;
var isGenericRpc = rpcAttribute.AttributeType.FullName == CodeGenHelpers.RpcAttribute_FullName;
var requireOwnership = true; // default value MUST be == `ServerRpcAttribute.RequireOwnership`
var rpcDelivery = RpcDelivery.Reliable; // default value MUST be == `RpcAttribute.Delivery`
var defaultTarget = SendTo.Everyone;
var allowTargetOverride = false;
if (isGenericRpc)
{
defaultTarget = (SendTo)rpcAttribute.ConstructorArguments[0].Value;
}
foreach (var attrField in rpcAttribute.Fields)
{
switch (attrField.Name)
@@ -1899,6 +1976,9 @@ namespace Unity.Netcode.Editor.CodeGen
case k_ServerRpcAttribute_RequireOwnership:
requireOwnership = attrField.Argument.Type == typeSystem.Boolean && (bool)attrField.Argument.Value;
break;
case nameof(RpcAttribute.AllowTargetOverride):
allowTargetOverride = attrField.Argument.Type == typeSystem.Boolean && (bool)attrField.Argument.Value;
break;
}
}
@@ -1906,7 +1986,33 @@ namespace Unity.Netcode.Editor.CodeGen
var hasRpcParams =
paramCount > 0 &&
((isServerRpc && methodDefinition.Parameters[paramCount - 1].ParameterType.FullName == CodeGenHelpers.ServerRpcParams_FullName) ||
(!isServerRpc && methodDefinition.Parameters[paramCount - 1].ParameterType.FullName == CodeGenHelpers.ClientRpcParams_FullName));
(isClientRpc && methodDefinition.Parameters[paramCount - 1].ParameterType.FullName == CodeGenHelpers.ClientRpcParams_FullName) ||
(isGenericRpc && methodDefinition.Parameters[paramCount - 1].ParameterType.FullName == CodeGenHelpers.RpcParams_FullName));
if (isGenericRpc && defaultTarget == SendTo.SpecifiedInParams)
{
if (!hasRpcParams)
{
m_Diagnostics.AddError($"{methodDefinition}: {nameof(SendTo)}.{nameof(SendTo.SpecifiedInParams)} cannot be used without a final parameter of type {CodeGenHelpers.RpcParams_FullName}.");
}
foreach (var attrField in rpcAttribute.Fields)
{
switch (attrField.Name)
{
case nameof(RpcAttribute.AllowTargetOverride):
m_Diagnostics.AddWarning($"{methodDefinition}: {nameof(RpcAttribute.AllowTargetOverride)} is ignored with {nameof(SendTo)}.{nameof(SendTo.SpecifiedInParams)}");
break;
}
}
}
if (isGenericRpc && allowTargetOverride)
{
if (!hasRpcParams)
{
m_Diagnostics.AddError($"{methodDefinition}: {nameof(RpcAttribute.AllowTargetOverride)} cannot be used without a final parameter of type {CodeGenHelpers.RpcParams_FullName}.");
}
}
methodDefinition.Body.InitLocals = true;
// NetworkManager networkManager;
@@ -1919,10 +2025,17 @@ namespace Unity.Netcode.Editor.CodeGen
// XXXRpcParams
if (!hasRpcParams)
{
methodDefinition.Body.Variables.Add(new VariableDefinition(isServerRpc ? m_ServerRpcParams_TypeRef : m_ClientRpcParams_TypeRef));
methodDefinition.Body.Variables.Add(new VariableDefinition(isServerRpc ? m_ServerRpcParams_TypeRef : (isClientRpc ? m_ClientRpcParams_TypeRef : m_UniversalRpcParams_TypeRef)));
}
int rpcParamsIdx = !hasRpcParams ? methodDefinition.Body.Variables.Count - 1 : -1;
if (isGenericRpc)
{
methodDefinition.Body.Variables.Add(new VariableDefinition(m_AttributeParamsType_TypeRef));
}
int rpcAttributeParamsIdx = isGenericRpc ? methodDefinition.Body.Variables.Count - 1 : -1;
{
var returnInstr = processor.Create(OpCodes.Ret);
var lastInstr = processor.Create(OpCodes.Nop);
@@ -1952,20 +2065,23 @@ namespace Unity.Netcode.Editor.CodeGen
// if (__rpc_exec_stage != __RpcExecStage.Client) -> ClientRpc
instructions.Add(processor.Create(OpCodes.Ldarg_0));
instructions.Add(processor.Create(OpCodes.Ldfld, m_NetworkBehaviour_rpc_exec_stage_FieldRef));
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)(isServerRpc ? NetworkBehaviour.__RpcExecStage.Server : NetworkBehaviour.__RpcExecStage.Client)));
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)NetworkBehaviour.__RpcExecStage.Execute));
instructions.Add(processor.Create(OpCodes.Ceq));
instructions.Add(processor.Create(OpCodes.Ldc_I4, 0));
instructions.Add(processor.Create(OpCodes.Ceq));
instructions.Add(processor.Create(OpCodes.Brfalse, lastInstr));
// if (networkManager.IsClient || networkManager.IsHost) { ... } -> ServerRpc
// if (networkManager.IsServer || networkManager.IsHost) { ... } -> ClientRpc
instructions.Add(processor.Create(OpCodes.Ldloc, netManLocIdx));
instructions.Add(processor.Create(OpCodes.Callvirt, isServerRpc ? m_NetworkManager_getIsClient_MethodRef : m_NetworkManager_getIsServer_MethodRef));
instructions.Add(processor.Create(OpCodes.Brtrue, beginInstr));
instructions.Add(processor.Create(OpCodes.Ldloc, netManLocIdx));
instructions.Add(processor.Create(OpCodes.Callvirt, m_NetworkManager_getIsHost_MethodRef));
instructions.Add(processor.Create(OpCodes.Brfalse, lastInstr));
if (!isGenericRpc)
{
// if (networkManager.IsClient || networkManager.IsHost) { ... } -> ServerRpc
// if (networkManager.IsServer || networkManager.IsHost) { ... } -> ClientRpc
instructions.Add(processor.Create(OpCodes.Ldloc, netManLocIdx));
instructions.Add(processor.Create(OpCodes.Callvirt, isServerRpc ? m_NetworkManager_getIsClient_MethodRef : m_NetworkManager_getIsServer_MethodRef));
instructions.Add(processor.Create(OpCodes.Brtrue, beginInstr));
instructions.Add(processor.Create(OpCodes.Ldloc, netManLocIdx));
instructions.Add(processor.Create(OpCodes.Callvirt, m_NetworkManager_getIsHost_MethodRef));
instructions.Add(processor.Create(OpCodes.Brfalse, lastInstr));
}
instructions.Add(beginInstr);
@@ -2027,7 +2143,7 @@ namespace Unity.Netcode.Editor.CodeGen
instructions.Add(processor.Create(OpCodes.Call, m_NetworkBehaviour_beginSendServerRpc_MethodRef));
instructions.Add(processor.Create(OpCodes.Stloc, bufWriterLocIdx));
}
else
else if (isClientRpc)
{
// ClientRpc
@@ -2047,6 +2163,89 @@ namespace Unity.Netcode.Editor.CodeGen
instructions.Add(processor.Create(OpCodes.Call, m_NetworkBehaviour_beginSendClientRpc_MethodRef));
instructions.Add(processor.Create(OpCodes.Stloc, bufWriterLocIdx));
}
else
{
// Generic RPC
// var bufferWriter = __beginSendRpc(rpcMethodId, rpcParams, rpcAttributeParams, defaultTarget, rpcDelivery);
instructions.Add(processor.Create(OpCodes.Ldarg_0));
// rpcMethodId
instructions.Add(processor.Create(OpCodes.Ldc_I4, unchecked((int)rpcMethodId)));
// rpcParams
instructions.Add(hasRpcParams ? processor.Create(OpCodes.Ldarg, paramCount) : processor.Create(OpCodes.Ldloc, rpcParamsIdx));
// rpcAttributeParams
instructions.Add(processor.Create(OpCodes.Ldloca, rpcAttributeParamsIdx));
instructions.Add(processor.Create(OpCodes.Initobj, m_AttributeParamsType_TypeRef));
RpcAttribute.RpcAttributeParams dflt = default;
foreach (var field in rpcAttribute.Fields)
{
var found = false;
foreach (var attrField in m_AttributeParamsType_TypeRef.Resolve().Fields)
{
if (attrField.Name == field.Name)
{
found = true;
var value = field.Argument.Value;
var paramField = dflt.GetType().GetField(attrField.Name);
if (value != paramField.GetValue(dflt))
{
instructions.Add(processor.Create(OpCodes.Ldloca, rpcAttributeParamsIdx));
var type = value.GetType();
if (type == typeof(bool))
{
instructions.Add(processor.Create(OpCodes.Ldc_I4, (bool)value ? 1 : 0));
}
else if (type == typeof(short) || type == typeof(int) || type == typeof(ushort)
|| type == typeof(byte) || type == typeof(sbyte) || type == typeof(char))
{
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)value));
}
else if (type == typeof(long) || type == typeof(ulong))
{
instructions.Add(processor.Create(OpCodes.Ldc_I8, (long)value));
}
else if (type == typeof(float))
{
instructions.Add(processor.Create(OpCodes.Ldc_R8, (float)value));
}
else if (type == typeof(double))
{
instructions.Add(processor.Create(OpCodes.Ldc_R8, (double)value));
}
else
{
m_Diagnostics.AddError("Unsupported attribute parameter type.");
}
}
instructions.Add(processor.Create(OpCodes.Stfld, m_MainModule.ImportReference(attrField)));
break;
}
}
if (!found)
{
m_Diagnostics.AddError($"{nameof(RpcAttribute)} contains field {field} which is not present in {nameof(RpcAttribute.RpcAttributeParams)}.");
}
}
instructions.Add(processor.Create(OpCodes.Ldloc, rpcAttributeParamsIdx));
// defaultTarget
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)defaultTarget));
// rpcDelivery
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)rpcDelivery));
// __beginSendRpc
instructions.Add(processor.Create(OpCodes.Call, m_NetworkBehaviour_beginSendRpc_MethodRef));
instructions.Add(processor.Create(OpCodes.Stloc, bufWriterLocIdx));
}
// write method parameters into stream
for (int paramIndex = 0; paramIndex < paramCount; ++paramIndex)
@@ -2075,7 +2274,7 @@ namespace Unity.Netcode.Editor.CodeGen
}
if (!isServerRpc)
{
m_Diagnostics.AddError($"ClientRpcs may not accept {nameof(ServerRpcParams)} as a parameter.");
m_Diagnostics.AddError($"Only ServerRpcs may accept {nameof(ServerRpcParams)} as a parameter.");
}
continue;
}
@@ -2086,9 +2285,22 @@ namespace Unity.Netcode.Editor.CodeGen
{
m_Diagnostics.AddError(methodDefinition, $"{nameof(ClientRpcParams)} must be the last parameter in a ClientRpc.");
}
if (isServerRpc)
if (!isClientRpc)
{
m_Diagnostics.AddError($"ServerRpcs may not accept {nameof(ClientRpcParams)} as a parameter.");
m_Diagnostics.AddError($"Only clientRpcs may accept {nameof(ClientRpcParams)} as a parameter.");
}
continue;
}
// RpcParams
if (paramType.FullName == CodeGenHelpers.RpcParams_FullName)
{
if (paramIndex != paramCount - 1)
{
m_Diagnostics.AddError(methodDefinition, $"{nameof(RpcParams)} must be the last parameter in a ClientRpc.");
}
if (!isGenericRpc)
{
m_Diagnostics.AddError($"Only Rpcs may accept {nameof(RpcParams)} as a parameter.");
}
continue;
}
@@ -2251,7 +2463,7 @@ namespace Unity.Netcode.Editor.CodeGen
// __endSendServerRpc
instructions.Add(processor.Create(OpCodes.Call, m_NetworkBehaviour_endSendServerRpc_MethodRef));
}
else
else if (isClientRpc)
{
// ClientRpc
@@ -2279,6 +2491,41 @@ namespace Unity.Netcode.Editor.CodeGen
// __endSendClientRpc
instructions.Add(processor.Create(OpCodes.Call, m_NetworkBehaviour_endSendClientRpc_MethodRef));
}
else
{
// Generic Rpc
// __endSendRpc(ref bufferWriter, rpcMethodId, rpcParams, rpcAttributeParams, defaultTarget, rpcDelivery);
instructions.Add(processor.Create(OpCodes.Ldarg_0));
// bufferWriter
instructions.Add(processor.Create(OpCodes.Ldloca, bufWriterLocIdx));
// rpcMethodId
instructions.Add(processor.Create(OpCodes.Ldc_I4, unchecked((int)rpcMethodId)));
if (hasRpcParams)
{
// rpcParams
instructions.Add(processor.Create(OpCodes.Ldarg, paramCount));
}
else
{
// default
instructions.Add(processor.Create(OpCodes.Ldloc, rpcParamsIdx));
}
// rpcAttributeParams
instructions.Add(processor.Create(OpCodes.Ldloc, rpcAttributeParamsIdx));
// defaultTarget
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)defaultTarget));
// rpcDelivery
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)rpcDelivery));
// __endSendClientRpc
instructions.Add(processor.Create(OpCodes.Call, m_NetworkBehaviour_endSendRpc_MethodRef));
}
instructions.Add(lastInstr);
}
@@ -2287,25 +2534,53 @@ namespace Unity.Netcode.Editor.CodeGen
var returnInstr = processor.Create(OpCodes.Ret);
var lastInstr = processor.Create(OpCodes.Nop);
// if (__rpc_exec_stage == __RpcExecStage.Server) -> ServerRpc
// if (__rpc_exec_stage == __RpcExecStage.Client) -> ClientRpc
instructions.Add(processor.Create(OpCodes.Ldarg_0));
instructions.Add(processor.Create(OpCodes.Ldfld, m_NetworkBehaviour_rpc_exec_stage_FieldRef));
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)(isServerRpc ? NetworkBehaviour.__RpcExecStage.Server : NetworkBehaviour.__RpcExecStage.Client)));
instructions.Add(processor.Create(OpCodes.Ceq));
instructions.Add(processor.Create(OpCodes.Brfalse, returnInstr));
if (!isGenericRpc)
{
// if (__rpc_exec_stage == __RpcExecStage.Execute)
instructions.Add(processor.Create(OpCodes.Ldarg_0));
instructions.Add(processor.Create(OpCodes.Ldfld, m_NetworkBehaviour_rpc_exec_stage_FieldRef));
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)NetworkBehaviour.__RpcExecStage.Execute));
instructions.Add(processor.Create(OpCodes.Ceq));
instructions.Add(processor.Create(OpCodes.Brfalse, returnInstr));
// if (networkManager.IsServer || networkManager.IsHost) -> ServerRpc
// if (networkManager.IsClient || networkManager.IsHost) -> ClientRpc
instructions.Add(processor.Create(OpCodes.Ldloc, netManLocIdx));
instructions.Add(processor.Create(OpCodes.Callvirt, isServerRpc ? m_NetworkManager_getIsServer_MethodRef : m_NetworkManager_getIsClient_MethodRef));
instructions.Add(processor.Create(OpCodes.Brtrue, lastInstr));
instructions.Add(processor.Create(OpCodes.Ldloc, netManLocIdx));
instructions.Add(processor.Create(OpCodes.Callvirt, m_NetworkManager_getIsHost_MethodRef));
instructions.Add(processor.Create(OpCodes.Brtrue, lastInstr));
// if (networkManager.IsServer || networkManager.IsHost) -> ServerRpc
// if (networkManager.IsClient || networkManager.IsHost) -> ClientRpc
instructions.Add(processor.Create(OpCodes.Ldloc, netManLocIdx));
instructions.Add(processor.Create(OpCodes.Callvirt, isServerRpc ? m_NetworkManager_getIsServer_MethodRef : m_NetworkManager_getIsClient_MethodRef));
instructions.Add(processor.Create(OpCodes.Brtrue, lastInstr));
instructions.Add(processor.Create(OpCodes.Ldloc, netManLocIdx));
instructions.Add(processor.Create(OpCodes.Callvirt, m_NetworkManager_getIsHost_MethodRef));
instructions.Add(processor.Create(OpCodes.Brtrue, lastInstr));
instructions.Add(returnInstr);
instructions.Add(lastInstr);
// This needs to be set back before executing the callback or else sending another RPC
// from within an RPC will not work.
// __rpc_exec_stage = __RpcExecStage.Send
instructions.Add(processor.Create(OpCodes.Ldarg_0));
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)NetworkBehaviour.__RpcExecStage.Send));
instructions.Add(processor.Create(OpCodes.Stfld, m_NetworkBehaviour_rpc_exec_stage_FieldRef));
}
else
{
// if (__rpc_exec_stage == __RpcExecStage.Execute)
instructions.Add(processor.Create(OpCodes.Ldarg_0));
instructions.Add(processor.Create(OpCodes.Ldfld, m_NetworkBehaviour_rpc_exec_stage_FieldRef));
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)NetworkBehaviour.__RpcExecStage.Execute));
instructions.Add(processor.Create(OpCodes.Ceq));
instructions.Add(processor.Create(OpCodes.Brtrue, lastInstr));
instructions.Add(returnInstr);
instructions.Add(lastInstr);
// This needs to be set back before executing the callback or else sending another RPC
// from within an RPC will not work.
// __rpc_exec_stage = __RpcExecStage.Send
instructions.Add(processor.Create(OpCodes.Ldarg_0));
instructions.Add(processor.Create(OpCodes.Ldc_I4, (int)NetworkBehaviour.__RpcExecStage.Send));
instructions.Add(processor.Create(OpCodes.Stfld, m_NetworkBehaviour_rpc_exec_stage_FieldRef));
}
instructions.Add(returnInstr);
instructions.Add(lastInstr);
}
instructions.Reverse();
@@ -2458,6 +2733,8 @@ namespace Unity.Netcode.Editor.CodeGen
var processor = rpcHandler.Body.GetILProcessor();
var isServerRpc = rpcAttribute.AttributeType.FullName == CodeGenHelpers.ServerRpcAttribute_FullName;
var isCientRpc = rpcAttribute.AttributeType.FullName == CodeGenHelpers.ClientRpcAttribute_FullName;
var isGenericRpc = rpcAttribute.AttributeType.FullName == CodeGenHelpers.RpcAttribute_FullName;
var requireOwnership = true; // default value MUST be == `ServerRpcAttribute.RequireOwnership`
foreach (var attrField in rpcAttribute.Fields)
{
@@ -2564,6 +2841,15 @@ namespace Unity.Netcode.Editor.CodeGen
processor.Emit(OpCodes.Stloc, localIndex);
continue;
}
// RpcParams
if (paramType.FullName == CodeGenHelpers.RpcParams_FullName)
{
processor.Emit(OpCodes.Ldarg_2);
processor.Emit(OpCodes.Ldfld, m_RpcParams_Ext_FieldRef);
processor.Emit(OpCodes.Stloc, localIndex);
continue;
}
}
Instruction jumpInstruction = null;
@@ -2690,7 +2976,7 @@ namespace Unity.Netcode.Editor.CodeGen
// NetworkBehaviour.__rpc_exec_stage = __RpcExecStage.Server; -> ServerRpc
// NetworkBehaviour.__rpc_exec_stage = __RpcExecStage.Client; -> ClientRpc
processor.Emit(OpCodes.Ldarg_0);
processor.Emit(OpCodes.Ldc_I4, (int)(isServerRpc ? NetworkBehaviour.__RpcExecStage.Server : NetworkBehaviour.__RpcExecStage.Client));
processor.Emit(OpCodes.Ldc_I4, (int)(NetworkBehaviour.__RpcExecStage.Execute));
processor.Emit(OpCodes.Stfld, m_NetworkBehaviour_rpc_exec_stage_FieldRef);
// NetworkBehaviour.XXXRpc(...);
@@ -2713,7 +2999,7 @@ namespace Unity.Netcode.Editor.CodeGen
// NetworkBehaviour.__rpc_exec_stage = __RpcExecStage.None;
processor.Emit(OpCodes.Ldarg_0);
processor.Emit(OpCodes.Ldc_I4, (int)NetworkBehaviour.__RpcExecStage.None);
processor.Emit(OpCodes.Ldc_I4, (int)NetworkBehaviour.__RpcExecStage.Send);
processor.Emit(OpCodes.Stfld, m_NetworkBehaviour_rpc_exec_stage_FieldRef);
processor.Emit(OpCodes.Ret);

View File

@@ -2,6 +2,7 @@ using System.Collections.Generic;
using System.IO;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using Unity.CompilationPipeline.Common.Diagnostics;
using Unity.CompilationPipeline.Common.ILPostProcessing;
using ILPPInterface = Unity.CompilationPipeline.Common.ILPostProcessing.ILPostProcessor;
@@ -52,6 +53,15 @@ namespace Unity.Netcode.Editor.CodeGen
case nameof(NetworkBehaviour):
ProcessNetworkBehaviour(typeDefinition);
break;
case nameof(RpcAttribute):
foreach (var methodDefinition in typeDefinition.GetConstructors())
{
if (methodDefinition.Parameters.Count == 0)
{
methodDefinition.IsPublic = true;
}
}
break;
case nameof(__RpcParams):
case nameof(RpcFallbackSerialization):
typeDefinition.IsPublic = true;
@@ -154,6 +164,8 @@ namespace Unity.Netcode.Editor.CodeGen
methodDefinition.Name == nameof(NetworkBehaviour.__endSendServerRpc) ||
methodDefinition.Name == nameof(NetworkBehaviour.__beginSendClientRpc) ||
methodDefinition.Name == nameof(NetworkBehaviour.__endSendClientRpc) ||
methodDefinition.Name == nameof(NetworkBehaviour.__beginSendRpc) ||
methodDefinition.Name == nameof(NetworkBehaviour.__endSendRpc) ||
methodDefinition.Name == nameof(NetworkBehaviour.__initializeVariables) ||
methodDefinition.Name == nameof(NetworkBehaviour.__initializeRpcs) ||
methodDefinition.Name == nameof(NetworkBehaviour.__registerRpc) ||