com.unity.netcode.gameobjects@1.1.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.1.0] - 2022-10-21 ### Added - Added `NetworkManager.IsApproved` flag that is set to `true` a client has been approved.(#2261) - `UnityTransport` now provides a way to set the Relay server data directly from the `RelayServerData` structure (provided by the Unity Transport package) throuh its `SetRelayServerData` method. This allows making use of the new APIs in UTP 1.3 that simplify integration of the Relay SDK. (#2235) - IPv6 is now supported for direct connections when using `UnityTransport`. (#2232) - Added WebSocket support when using UTP 2.0 with `UseWebSockets` property in the `UnityTransport` component of the `NetworkManager` allowing to pick WebSockets for communication. When building for WebGL, this selection happens automatically. (#2201) - Added position, rotation, and scale to the `ParentSyncMessage` which provides users the ability to specify the final values on the server-side when `OnNetworkObjectParentChanged` is invoked just before the message is created (when the `Transform` values are applied to the message). (#2146) - Added `NetworkObject.TryRemoveParent` method for convenience purposes opposed to having to cast null to either `GameObject` or `NetworkObject`. (#2146) ### Changed - Updated `UnityTransport` dependency on `com.unity.transport` to 1.3.0. (#2231) - The send queues of `UnityTransport` are now dynamically-sized. This means that there shouldn't be any need anymore to tweak the 'Max Send Queue Size' value. In fact, this field is now removed from the inspector and will not be serialized anymore. It is still possible to set it manually using the `MaxSendQueueSize` property, but it is not recommended to do so aside from some specific needs (e.g. limiting the amount of memory used by the send queues in very constrained environments). (#2212) - As a consequence of the above change, the `UnityTransport.InitialMaxSendQueueSize` field is now deprecated. There is no default value anymore since send queues are dynamically-sized. (#2212) - The debug simulator in `UnityTransport` is now non-deterministic. Its random number generator used to be seeded with a constant value, leading to the same pattern of packet drops, delays, and jitter in every run. (#2196) - `NetworkVariable<>` now supports managed `INetworkSerializable` types, as well as other managed types with serialization/deserialization delegates registered to `UserNetworkVariableSerialization<T>.WriteValue` and `UserNetworkVariableSerialization<T>.ReadValue` (#2219) - `NetworkVariable<>` and `BufferSerializer<BufferSerializerReader>` now deserialize `INetworkSerializable` types in-place, rather than constructing new ones. (#2219) ### Fixed - Fixed `NetworkManager.ApprovalTimeout` will not timeout due to slower client synchronization times as it now uses the added `NetworkManager.IsApproved` flag to determined if the client has been approved or not.(#2261) - Fixed issue caused when changing ownership of objects hidden to some clients (#2242) - Fixed issue where an in-scene placed NetworkObject would not invoke NetworkBehaviour.OnNetworkSpawn if the GameObject was disabled when it was despawned. (#2239) - Fixed issue where clients were not rebuilding the `NetworkConfig` hash value for each unique connection request. (#2226) - Fixed the issue where player objects were not taking the `DontDestroyWithOwner` property into consideration when a client disconnected. (#2225) - Fixed issue where `SceneEventProgress` would not complete if a client late joins while it is still in progress. (#2222) - Fixed issue where `SceneEventProgress` would not complete if a client disconnects. (#2222) - Fixed issues with detecting if a `SceneEventProgress` has timed out. (#2222) - Fixed issue #1924 where `UnityTransport` would fail to restart after a first failure (even if what caused the initial failure was addressed). (#2220) - Fixed issue where `NetworkTransform.SetStateServerRpc` and `NetworkTransform.SetStateClientRpc` were not honoring local vs world space settings when applying the position and rotation. (#2203) - Fixed ILPP `TypeLoadException` on WebGL on MacOS Editor and potentially other platforms. (#2199) - Implicit conversion of NetworkObjectReference to GameObject will now return null instead of throwing an exception if the referenced object could not be found (i.e., was already despawned) (#2158) - Fixed warning resulting from a stray NetworkAnimator.meta file (#2153) - Fixed Connection Approval Timeout not working client side. (#2164) - Fixed issue where the `WorldPositionStays` parenting parameter was not being synchronized with clients. (#2146) - Fixed issue where parented in-scene placed `NetworkObject`s would fail for late joining clients. (#2146) - Fixed issue where scale was not being synchronized which caused issues with nested parenting and scale when `WorldPositionStays` was true. (#2146) - Fixed issue with `NetworkTransform.ApplyTransformToNetworkStateWithInfo` where it was not honoring axis sync settings when `NetworkTransformState.IsTeleportingNextFrame` was true. (#2146) - Fixed issue with `NetworkTransform.TryCommitTransformToServer` where it was not honoring the `InLocalSpace` setting. (#2146) - Fixed ClientRpcs always reporting in the profiler view as going to all clients, even when limited to a subset of clients by `ClientRpcParams`. (#2144) - Fixed RPC codegen failing to choose the correct extension methods for `FastBufferReader` and `FastBufferWriter` when the parameters were a generic type (i.e., List<int>) and extensions for multiple instantiations of that type have been defined (i.e., List<int> and List<string>) (#2142) - Fixed the issue where running a server (i.e. not host) the second player would not receive updates (unless a third player joined). (#2127) - Fixed issue where late-joining client transition synchronization could fail when more than one transition was occurring.(#2127) - Fixed throwing an exception in `OnNetworkUpdate` causing other `OnNetworkUpdate` calls to not be executed. (#1739) - Fixed synchronization when Time.timeScale is set to 0. This changes timing update to use unscaled deltatime. Now network updates rate are independent from the local time scale. (#2171) - Fixed not sending all NetworkVariables to all clients when a client connects to a server. (#1987) - Fixed IsOwner/IsOwnedByServer being wrong on the server after calling RemoveOwnership (#2211)
This commit is contained in:
@@ -15,6 +15,10 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
{
|
||||
internal static class CodeGenHelpers
|
||||
{
|
||||
public const string DotnetModuleName = "netstandard.dll";
|
||||
public const string UnityModuleName = "UnityEngine.CoreModule.dll";
|
||||
public const string NetcodeModuleName = "Unity.Netcode.Runtime.dll";
|
||||
|
||||
public const string RuntimeAssemblyName = "Unity.Netcode.Runtime";
|
||||
|
||||
public static readonly string NetworkBehaviour_FullName = typeof(NetworkBehaviour).FullName;
|
||||
@@ -119,6 +123,19 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
try
|
||||
{
|
||||
var typeDef = typeReference.Resolve();
|
||||
// Note: this won't catch generics correctly.
|
||||
//
|
||||
// class Foo<T>: IInterface<T> {}
|
||||
// class Bar: Foo<int> {}
|
||||
//
|
||||
// Bar.HasInterface(IInterface<int>) -> returns false even though it should be true.
|
||||
//
|
||||
// This can be fixed (see GetAllFieldsAndResolveGenerics() in NetworkBehaviourILPP to understand how)
|
||||
// but right now we don't need that to work so it's left alone to reduce complexity
|
||||
if (typeDef.BaseType.HasInterface(interfaceTypeFullName))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
var typeFaces = typeDef.Interfaces;
|
||||
return typeFaces.Any(iface => iface.InterfaceType.FullName == interfaceTypeFullName);
|
||||
}
|
||||
@@ -380,5 +397,74 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
|
||||
return assemblyDefinition;
|
||||
}
|
||||
|
||||
private static void SearchForBaseModulesRecursive(AssemblyDefinition assemblyDefinition, PostProcessorAssemblyResolver assemblyResolver, ref ModuleDefinition unityModule, ref ModuleDefinition netcodeModule, HashSet<string> visited)
|
||||
{
|
||||
|
||||
foreach (var module in assemblyDefinition.Modules)
|
||||
{
|
||||
if (module == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (unityModule != null && netcodeModule != null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (unityModule == null && module.Name == UnityModuleName)
|
||||
{
|
||||
unityModule = module;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (netcodeModule == null && module.Name == NetcodeModuleName)
|
||||
{
|
||||
netcodeModule = module;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (unityModule != null && netcodeModule != null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var assemblyNameReference in assemblyDefinition.MainModule.AssemblyReferences)
|
||||
{
|
||||
if (assemblyNameReference == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (visited.Contains(assemblyNameReference.Name))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
visited.Add(assemblyNameReference.Name);
|
||||
|
||||
var assembly = assemblyResolver.Resolve(assemblyNameReference);
|
||||
if (assembly == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
SearchForBaseModulesRecursive(assembly, assemblyResolver, ref unityModule, ref netcodeModule, visited);
|
||||
|
||||
if (unityModule != null && netcodeModule != null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static (ModuleDefinition UnityModule, ModuleDefinition NetcodeModule) FindBaseModules(AssemblyDefinition assemblyDefinition, PostProcessorAssemblyResolver assemblyResolver)
|
||||
{
|
||||
ModuleDefinition unityModule = null;
|
||||
ModuleDefinition netcodeModule = null;
|
||||
var visited = new HashSet<string>();
|
||||
SearchForBaseModulesRecursive(assemblyDefinition, assemblyResolver, ref unityModule, ref netcodeModule, visited);
|
||||
|
||||
return (unityModule, netcodeModule);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using Mono.Cecil;
|
||||
using Mono.Cecil.Cil;
|
||||
using Mono.Cecil.Rocks;
|
||||
@@ -17,8 +16,7 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
{
|
||||
public override ILPPInterface GetInstance() => this;
|
||||
|
||||
public override bool WillProcess(ICompiledAssembly compiledAssembly) =>
|
||||
compiledAssembly.Name == CodeGenHelpers.RuntimeAssemblyName;
|
||||
public override bool WillProcess(ICompiledAssembly compiledAssembly) => compiledAssembly.Name == CodeGenHelpers.RuntimeAssemblyName;
|
||||
|
||||
private readonly List<DiagnosticMessage> m_Diagnostics = new List<DiagnosticMessage>();
|
||||
|
||||
@@ -32,13 +30,22 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
m_Diagnostics.Clear();
|
||||
|
||||
// read
|
||||
var assemblyDefinition = CodeGenHelpers.AssemblyDefinitionFor(compiledAssembly, out var resolver);
|
||||
var assemblyDefinition = CodeGenHelpers.AssemblyDefinitionFor(compiledAssembly, out m_AssemblyResolver);
|
||||
if (assemblyDefinition == null)
|
||||
{
|
||||
m_Diagnostics.AddError($"Cannot read assembly definition: {compiledAssembly.Name}");
|
||||
return null;
|
||||
}
|
||||
|
||||
// modules
|
||||
(_, m_NetcodeModule) = CodeGenHelpers.FindBaseModules(assemblyDefinition, m_AssemblyResolver);
|
||||
|
||||
if (m_NetcodeModule == null)
|
||||
{
|
||||
m_Diagnostics.AddError($"Cannot find Netcode module: {CodeGenHelpers.NetcodeModuleName}");
|
||||
return null;
|
||||
}
|
||||
|
||||
// process
|
||||
var mainModule = assemblyDefinition.MainModule;
|
||||
if (mainModule != null)
|
||||
@@ -60,7 +67,7 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
m_Diagnostics.AddError((e.ToString() + e.StackTrace.ToString()).Replace("\n", "|").Replace("\r", "|"));
|
||||
m_Diagnostics.AddError((e.ToString() + e.StackTrace).Replace("\n", "|").Replace("\r", "|"));
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -91,6 +98,8 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
return new ILPostProcessResult(new InMemoryAssembly(pe.ToArray(), pdb.ToArray()), m_Diagnostics);
|
||||
}
|
||||
|
||||
private ModuleDefinition m_NetcodeModule;
|
||||
private PostProcessorAssemblyResolver m_AssemblyResolver;
|
||||
|
||||
private MethodReference m_MessagingSystem_ReceiveMessage_MethodRef;
|
||||
private TypeReference m_MessagingSystem_MessageWithHandler_TypeRef;
|
||||
@@ -105,63 +114,102 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
|
||||
private bool ImportReferences(ModuleDefinition moduleDefinition)
|
||||
{
|
||||
m_MessagingSystem_MessageHandler_Constructor_TypeRef = moduleDefinition.ImportReference(typeof(MessagingSystem.MessageHandler).GetConstructors()[0]);
|
||||
// Different environments seem to have different situations...
|
||||
// Some have these definitions in netstandard.dll...
|
||||
// some seem to have them elsewhere...
|
||||
// Since they're standard .net classes they're not going to cause
|
||||
// the same issues as referencing other assemblies, in theory, since
|
||||
// the definitions should be standard and consistent across platforms
|
||||
// (i.e., there's no #if UNITY_EDITOR in them that could create
|
||||
// invalid IL code)
|
||||
TypeDefinition typeTypeDef = moduleDefinition.ImportReference(typeof(Type)).Resolve();
|
||||
TypeDefinition listTypeDef = moduleDefinition.ImportReference(typeof(List<>)).Resolve();
|
||||
|
||||
var messageWithHandlerType = typeof(MessagingSystem.MessageWithHandler);
|
||||
m_MessagingSystem_MessageWithHandler_TypeRef = moduleDefinition.ImportReference(messageWithHandlerType);
|
||||
foreach (var fieldInfo in messageWithHandlerType.GetFields())
|
||||
TypeDefinition messageHandlerTypeDef = null;
|
||||
TypeDefinition messageWithHandlerTypeDef = null;
|
||||
TypeDefinition ilppMessageProviderTypeDef = null;
|
||||
TypeDefinition messagingSystemTypeDef = null;
|
||||
foreach (var netcodeTypeDef in m_NetcodeModule.GetAllTypes())
|
||||
{
|
||||
switch (fieldInfo.Name)
|
||||
if (messageHandlerTypeDef == null && netcodeTypeDef.Name == nameof(MessagingSystem.MessageHandler))
|
||||
{
|
||||
messageHandlerTypeDef = netcodeTypeDef;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (messageWithHandlerTypeDef == null && netcodeTypeDef.Name == nameof(MessagingSystem.MessageWithHandler))
|
||||
{
|
||||
messageWithHandlerTypeDef = netcodeTypeDef;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ilppMessageProviderTypeDef == null && netcodeTypeDef.Name == nameof(ILPPMessageProvider))
|
||||
{
|
||||
ilppMessageProviderTypeDef = netcodeTypeDef;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (messagingSystemTypeDef == null && netcodeTypeDef.Name == nameof(MessagingSystem))
|
||||
{
|
||||
messagingSystemTypeDef = netcodeTypeDef;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
m_MessagingSystem_MessageHandler_Constructor_TypeRef = moduleDefinition.ImportReference(messageHandlerTypeDef.GetConstructors().First());
|
||||
|
||||
m_MessagingSystem_MessageWithHandler_TypeRef = moduleDefinition.ImportReference(messageWithHandlerTypeDef);
|
||||
foreach (var fieldDef in messageWithHandlerTypeDef.Fields)
|
||||
{
|
||||
switch (fieldDef.Name)
|
||||
{
|
||||
case nameof(MessagingSystem.MessageWithHandler.MessageType):
|
||||
m_MessagingSystem_MessageWithHandler_MessageType_FieldRef = moduleDefinition.ImportReference(fieldInfo);
|
||||
m_MessagingSystem_MessageWithHandler_MessageType_FieldRef = moduleDefinition.ImportReference(fieldDef);
|
||||
break;
|
||||
case nameof(MessagingSystem.MessageWithHandler.Handler):
|
||||
m_MessagingSystem_MessageWithHandler_Handler_FieldRef = moduleDefinition.ImportReference(fieldInfo);
|
||||
m_MessagingSystem_MessageWithHandler_Handler_FieldRef = moduleDefinition.ImportReference(fieldDef);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var typeType = typeof(Type);
|
||||
foreach (var methodInfo in typeType.GetMethods())
|
||||
foreach (var methodDef in typeTypeDef.Methods)
|
||||
{
|
||||
switch (methodInfo.Name)
|
||||
switch (methodDef.Name)
|
||||
{
|
||||
case nameof(Type.GetTypeFromHandle):
|
||||
m_Type_GetTypeFromHandle_MethodRef = moduleDefinition.ImportReference(methodInfo);
|
||||
m_Type_GetTypeFromHandle_MethodRef = moduleDefinition.ImportReference(methodDef);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var ilppMessageProviderType = typeof(ILPPMessageProvider);
|
||||
foreach (var fieldInfo in ilppMessageProviderType.GetFields(BindingFlags.Static | BindingFlags.NonPublic))
|
||||
foreach (var fieldDef in ilppMessageProviderTypeDef.Fields)
|
||||
{
|
||||
switch (fieldInfo.Name)
|
||||
switch (fieldDef.Name)
|
||||
{
|
||||
case nameof(ILPPMessageProvider.__network_message_types):
|
||||
m_ILPPMessageProvider___network_message_types_FieldRef = moduleDefinition.ImportReference(fieldInfo);
|
||||
m_ILPPMessageProvider___network_message_types_FieldRef = moduleDefinition.ImportReference(fieldDef);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var listType = typeof(List<MessagingSystem.MessageWithHandler>);
|
||||
foreach (var methodInfo in listType.GetMethods())
|
||||
foreach (var methodDef in listTypeDef.Methods)
|
||||
{
|
||||
switch (methodInfo.Name)
|
||||
switch (methodDef.Name)
|
||||
{
|
||||
case nameof(List<MessagingSystem.MessageWithHandler>.Add):
|
||||
m_List_Add_MethodRef = moduleDefinition.ImportReference(methodInfo);
|
||||
case "Add":
|
||||
m_List_Add_MethodRef = methodDef;
|
||||
m_List_Add_MethodRef.DeclaringType = listTypeDef.MakeGenericInstanceType(messageWithHandlerTypeDef);
|
||||
m_List_Add_MethodRef = moduleDefinition.ImportReference(m_List_Add_MethodRef);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var messagingSystemType = typeof(MessagingSystem);
|
||||
foreach (var methodInfo in messagingSystemType.GetMethods(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public))
|
||||
foreach (var methodDef in messagingSystemTypeDef.Methods)
|
||||
{
|
||||
switch (methodInfo.Name)
|
||||
switch (methodDef.Name)
|
||||
{
|
||||
case k_ReceiveMessageName:
|
||||
m_MessagingSystem_ReceiveMessage_MethodRef = moduleDefinition.ImportReference(methodInfo);
|
||||
m_MessagingSystem_ReceiveMessage_MethodRef = moduleDefinition.ImportReference(methodDef);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -217,10 +265,8 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
instructions.Add(processor.Create(OpCodes.Callvirt, m_List_Add_MethodRef));
|
||||
}
|
||||
|
||||
// Creates a static module constructor (which is executed when the module is loaded) that registers all the
|
||||
// message types in the assembly with MessagingSystem.
|
||||
// This is the same behavior as annotating a static method with [ModuleInitializer] in standardized
|
||||
// C# (that attribute doesn't exist in Unity, but the static module constructor still works)
|
||||
// Creates a static module constructor (which is executed when the module is loaded) that registers all the message types in the assembly with MessagingSystem.
|
||||
// This is the same behavior as annotating a static method with [ModuleInitializer] in standardized C# (that attribute doesn't exist in Unity, but the static module constructor still works).
|
||||
// https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.moduleinitializerattribute?view=net-5.0
|
||||
// https://web.archive.org/web/20100212140402/http://blogs.msdn.com/junfeng/archive/2005/11/19/494914.aspx
|
||||
private void CreateModuleInitializer(AssemblyDefinition assembly, List<TypeDefinition> networkMessageTypes)
|
||||
|
||||
@@ -10,7 +10,6 @@ using ILPPInterface = Unity.CompilationPipeline.Common.ILPostProcessing.ILPostPr
|
||||
|
||||
namespace Unity.Netcode.Editor.CodeGen
|
||||
{
|
||||
|
||||
internal sealed class INetworkSerializableILPP : ILPPInterface
|
||||
{
|
||||
public override ILPPInterface GetInstance() => this;
|
||||
@@ -92,7 +91,7 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
m_Diagnostics.AddError((e.ToString() + e.StackTrace.ToString()).Replace("\n", "|").Replace("\r", "|"));
|
||||
m_Diagnostics.AddError((e.ToString() + e.StackTrace).Replace("\n", "|").Replace("\r", "|"));
|
||||
}
|
||||
}
|
||||
else
|
||||
|
||||
@@ -2,7 +2,6 @@ using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Mono.Cecil;
|
||||
using Mono.Cecil.Cil;
|
||||
@@ -23,8 +22,7 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
|
||||
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.References.Any(filePath => Path.GetFileNameWithoutExtension(filePath) == CodeGenHelpers.RuntimeAssemblyName);
|
||||
|
||||
private readonly List<DiagnosticMessage> m_Diagnostics = new List<DiagnosticMessage>();
|
||||
|
||||
@@ -35,7 +33,6 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
m_Diagnostics.Clear();
|
||||
|
||||
// read
|
||||
@@ -46,11 +43,27 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
return null;
|
||||
}
|
||||
|
||||
// modules
|
||||
(m_UnityModule, m_NetcodeModule) = CodeGenHelpers.FindBaseModules(assemblyDefinition, m_AssemblyResolver);
|
||||
|
||||
if (m_UnityModule == null)
|
||||
{
|
||||
m_Diagnostics.AddError($"Cannot find Unity module: {CodeGenHelpers.UnityModuleName}");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (m_NetcodeModule == null)
|
||||
{
|
||||
m_Diagnostics.AddError($"Cannot find Netcode module: {CodeGenHelpers.NetcodeModuleName}");
|
||||
return null;
|
||||
}
|
||||
|
||||
// process
|
||||
var mainModule = assemblyDefinition.MainModule;
|
||||
if (mainModule != null)
|
||||
{
|
||||
m_MainModule = mainModule;
|
||||
|
||||
if (ImportReferences(mainModule))
|
||||
{
|
||||
// process `NetworkBehaviour` types
|
||||
@@ -60,10 +73,12 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
.Where(t => t.IsSubclassOf(CodeGenHelpers.NetworkBehaviour_FullName))
|
||||
.ToList()
|
||||
.ForEach(b => ProcessNetworkBehaviour(b, compiledAssembly.Defines));
|
||||
|
||||
CreateNetworkVariableTypeInitializers(assemblyDefinition);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
m_Diagnostics.AddError((e.ToString() + e.StackTrace.ToString()).Replace("\n", "|").Replace("\r", "|"));
|
||||
m_Diagnostics.AddError((e.ToString() + e.StackTrace).Replace("\n", "|").Replace("\r", "|"));
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -92,7 +107,117 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
return new ILPostProcessResult(new InMemoryAssembly(pe.ToArray(), pdb.ToArray()), m_Diagnostics);
|
||||
}
|
||||
|
||||
private MethodDefinition GetOrCreateStaticConstructor(TypeDefinition typeDefinition)
|
||||
{
|
||||
var staticCtorMethodDef = typeDefinition.GetStaticConstructor();
|
||||
if (staticCtorMethodDef == null)
|
||||
{
|
||||
staticCtorMethodDef = new MethodDefinition(
|
||||
".cctor", // Static Constructor (constant-constructor)
|
||||
MethodAttributes.HideBySig |
|
||||
MethodAttributes.SpecialName |
|
||||
MethodAttributes.RTSpecialName |
|
||||
MethodAttributes.Static,
|
||||
typeDefinition.Module.TypeSystem.Void);
|
||||
staticCtorMethodDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
|
||||
typeDefinition.Methods.Add(staticCtorMethodDef);
|
||||
}
|
||||
|
||||
return staticCtorMethodDef;
|
||||
}
|
||||
|
||||
private bool IsMemcpyableType(TypeReference type)
|
||||
{
|
||||
foreach (var supportedType in BaseSupportedTypes)
|
||||
{
|
||||
if (type.FullName == supportedType.FullName)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void CreateNetworkVariableTypeInitializers(AssemblyDefinition assembly)
|
||||
{
|
||||
foreach (var typeDefinition in assembly.MainModule.Types)
|
||||
{
|
||||
if (typeDefinition.FullName == "<Module>")
|
||||
{
|
||||
var staticCtorMethodDef = GetOrCreateStaticConstructor(typeDefinition);
|
||||
|
||||
var processor = staticCtorMethodDef.Body.GetILProcessor();
|
||||
|
||||
var instructions = new List<Instruction>();
|
||||
|
||||
foreach (var type in m_WrappedNetworkVariableTypes)
|
||||
{
|
||||
// If a serializable type isn't found, FallbackSerializer will be used automatically, which will
|
||||
// call into UserNetworkVariableSerialization, giving the user a chance to define their own serializaiton
|
||||
// for types that aren't in our official supported types list.
|
||||
GenericInstanceMethod serializeMethod = null;
|
||||
GenericInstanceMethod equalityMethod;
|
||||
|
||||
if (type.IsValueType)
|
||||
{
|
||||
if (type.HasInterface(typeof(INetworkSerializeByMemcpy).FullName) || type.Resolve().IsEnum || IsMemcpyableType(type))
|
||||
{
|
||||
serializeMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpy_MethodRef);
|
||||
}
|
||||
else if (type.HasInterface(typeof(INetworkSerializable).FullName))
|
||||
{
|
||||
serializeMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializable_MethodRef);
|
||||
}
|
||||
else if (type.HasInterface(CodeGenHelpers.IUTF8Bytes_FullName) && type.HasInterface(k_INativeListBool_FullName))
|
||||
{
|
||||
serializeMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeSerializer_FixedString_MethodRef);
|
||||
}
|
||||
|
||||
if (type.HasInterface(typeof(IEquatable<>).FullName + "<" + type.FullName + ">"))
|
||||
{
|
||||
equalityMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatable_MethodRef);
|
||||
}
|
||||
else
|
||||
{
|
||||
equalityMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEquals_MethodRef);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (type.HasInterface(typeof(INetworkSerializable).FullName))
|
||||
{
|
||||
serializeMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeSerializer_ManagedINetworkSerializable_MethodRef);
|
||||
}
|
||||
|
||||
if (type.HasInterface(typeof(IEquatable<>).FullName + "<" + type.FullName + ">"))
|
||||
{
|
||||
equalityMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedIEquatable_MethodRef);
|
||||
}
|
||||
else
|
||||
{
|
||||
equalityMethod = new GenericInstanceMethod(m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef);
|
||||
}
|
||||
}
|
||||
|
||||
if (serializeMethod != null)
|
||||
{
|
||||
serializeMethod.GenericArguments.Add(type);
|
||||
instructions.Add(processor.Create(OpCodes.Call, m_MainModule.ImportReference(serializeMethod)));
|
||||
}
|
||||
equalityMethod.GenericArguments.Add(type);
|
||||
instructions.Add(processor.Create(OpCodes.Call, m_MainModule.ImportReference(equalityMethod)));
|
||||
}
|
||||
|
||||
instructions.ForEach(instruction => processor.Body.Instructions.Insert(processor.Body.Instructions.Count - 1, instruction));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ModuleDefinition m_MainModule;
|
||||
private ModuleDefinition m_UnityModule;
|
||||
private ModuleDefinition m_NetcodeModule;
|
||||
private PostProcessorAssemblyResolver m_AssemblyResolver;
|
||||
|
||||
private MethodReference m_Debug_LogError_MethodRef;
|
||||
@@ -123,14 +248,51 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
private FieldReference m_ServerRpcParams_Receive_FieldRef;
|
||||
private FieldReference m_ServerRpcParams_Receive_SenderClientId_FieldRef;
|
||||
private TypeReference m_ClientRpcParams_TypeRef;
|
||||
private MethodReference m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpy_MethodRef;
|
||||
private MethodReference m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializable_MethodRef;
|
||||
private MethodReference m_NetworkVariableSerializationTypes_InitializeSerializer_ManagedINetworkSerializable_MethodRef;
|
||||
private MethodReference m_NetworkVariableSerializationTypes_InitializeSerializer_FixedString_MethodRef;
|
||||
private MethodReference m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedIEquatable_MethodRef;
|
||||
private MethodReference m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatable_MethodRef;
|
||||
private MethodReference m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEquals_MethodRef;
|
||||
private MethodReference m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef;
|
||||
|
||||
private TypeReference m_FastBufferWriter_TypeRef;
|
||||
private Dictionary<string, MethodReference> m_FastBufferWriter_WriteValue_MethodRefs = new Dictionary<string, MethodReference>();
|
||||
private List<MethodReference> m_FastBufferWriter_ExtensionMethodRefs = new List<MethodReference>();
|
||||
private readonly Dictionary<string, MethodReference> m_FastBufferWriter_WriteValue_MethodRefs = new Dictionary<string, MethodReference>();
|
||||
private readonly List<MethodReference> m_FastBufferWriter_ExtensionMethodRefs = new List<MethodReference>();
|
||||
|
||||
private TypeReference m_FastBufferReader_TypeRef;
|
||||
private Dictionary<string, MethodReference> m_FastBufferReader_ReadValue_MethodRefs = new Dictionary<string, MethodReference>();
|
||||
private List<MethodReference> m_FastBufferReader_ExtensionMethodRefs = new List<MethodReference>();
|
||||
private readonly Dictionary<string, MethodReference> m_FastBufferReader_ReadValue_MethodRefs = new Dictionary<string, MethodReference>();
|
||||
private readonly List<MethodReference> m_FastBufferReader_ExtensionMethodRefs = new List<MethodReference>();
|
||||
|
||||
private HashSet<TypeReference> m_WrappedNetworkVariableTypes = new HashSet<TypeReference>();
|
||||
|
||||
internal static readonly Type[] BaseSupportedTypes = new[]
|
||||
{
|
||||
typeof(bool),
|
||||
typeof(byte),
|
||||
typeof(sbyte),
|
||||
typeof(char),
|
||||
typeof(decimal),
|
||||
typeof(double),
|
||||
typeof(float),
|
||||
typeof(int),
|
||||
typeof(uint),
|
||||
typeof(long),
|
||||
typeof(ulong),
|
||||
typeof(short),
|
||||
typeof(ushort),
|
||||
typeof(Vector2),
|
||||
typeof(Vector3),
|
||||
typeof(Vector2Int),
|
||||
typeof(Vector3Int),
|
||||
typeof(Vector4),
|
||||
typeof(Quaternion),
|
||||
typeof(Color),
|
||||
typeof(Color32),
|
||||
typeof(Ray),
|
||||
typeof(Ray2D)
|
||||
};
|
||||
|
||||
private const string k_Debug_LogError = nameof(Debug.LogError);
|
||||
private const string k_NetworkManager_LocalClientId = nameof(NetworkManager.LocalClientId);
|
||||
@@ -157,160 +319,243 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
private const string k_ServerRpcParams_Receive = nameof(ServerRpcParams.Receive);
|
||||
private const string k_ServerRpcReceiveParams_SenderClientId = nameof(ServerRpcReceiveParams.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>";
|
||||
|
||||
private bool ImportReferences(ModuleDefinition moduleDefinition)
|
||||
{
|
||||
var debugType = typeof(Debug);
|
||||
foreach (var methodInfo in debugType.GetMethods())
|
||||
TypeDefinition debugTypeDef = null;
|
||||
foreach (var unityTypeDef in m_UnityModule.GetAllTypes())
|
||||
{
|
||||
switch (methodInfo.Name)
|
||||
if (debugTypeDef == null && unityTypeDef.FullName == typeof(Debug).FullName)
|
||||
{
|
||||
debugTypeDef = unityTypeDef;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
TypeDefinition networkManagerTypeDef = null;
|
||||
TypeDefinition networkBehaviourTypeDef = null;
|
||||
TypeDefinition networkHandlerDelegateTypeDef = null;
|
||||
TypeDefinition rpcParamsTypeDef = null;
|
||||
TypeDefinition serverRpcParamsTypeDef = null;
|
||||
TypeDefinition clientRpcParamsTypeDef = null;
|
||||
TypeDefinition fastBufferWriterTypeDef = null;
|
||||
TypeDefinition fastBufferReaderTypeDef = null;
|
||||
TypeDefinition networkVariableSerializationTypesTypeDef = null;
|
||||
foreach (var netcodeTypeDef in m_NetcodeModule.GetAllTypes())
|
||||
{
|
||||
if (networkManagerTypeDef == null && netcodeTypeDef.Name == nameof(NetworkManager))
|
||||
{
|
||||
networkManagerTypeDef = netcodeTypeDef;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (networkBehaviourTypeDef == null && netcodeTypeDef.Name == nameof(NetworkBehaviour))
|
||||
{
|
||||
networkBehaviourTypeDef = netcodeTypeDef;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (networkHandlerDelegateTypeDef == null && netcodeTypeDef.Name == nameof(NetworkManager.RpcReceiveHandler))
|
||||
{
|
||||
networkHandlerDelegateTypeDef = netcodeTypeDef;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (rpcParamsTypeDef == null && netcodeTypeDef.Name == nameof(__RpcParams))
|
||||
{
|
||||
rpcParamsTypeDef = netcodeTypeDef;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (serverRpcParamsTypeDef == null && netcodeTypeDef.Name == nameof(ServerRpcParams))
|
||||
{
|
||||
serverRpcParamsTypeDef = netcodeTypeDef;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (clientRpcParamsTypeDef == null && netcodeTypeDef.Name == nameof(ClientRpcParams))
|
||||
{
|
||||
clientRpcParamsTypeDef = netcodeTypeDef;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (fastBufferWriterTypeDef == null && netcodeTypeDef.Name == nameof(FastBufferWriter))
|
||||
{
|
||||
fastBufferWriterTypeDef = netcodeTypeDef;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (fastBufferReaderTypeDef == null && netcodeTypeDef.Name == nameof(FastBufferReader))
|
||||
{
|
||||
fastBufferReaderTypeDef = netcodeTypeDef;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (networkVariableSerializationTypesTypeDef == null && netcodeTypeDef.Name == nameof(NetworkVariableSerializationTypes))
|
||||
{
|
||||
networkVariableSerializationTypesTypeDef = netcodeTypeDef;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var methodDef in debugTypeDef.Methods)
|
||||
{
|
||||
switch (methodDef.Name)
|
||||
{
|
||||
case k_Debug_LogError:
|
||||
if (methodInfo.GetParameters().Length == 1)
|
||||
if (methodDef.Parameters.Count == 1)
|
||||
{
|
||||
m_Debug_LogError_MethodRef = moduleDefinition.ImportReference(methodInfo);
|
||||
m_Debug_LogError_MethodRef = moduleDefinition.ImportReference(methodDef);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var networkManagerType = typeof(NetworkManager);
|
||||
m_NetworkManager_TypeRef = moduleDefinition.ImportReference(networkManagerType);
|
||||
foreach (var propertyInfo in networkManagerType.GetProperties())
|
||||
m_NetworkManager_TypeRef = moduleDefinition.ImportReference(networkManagerTypeDef);
|
||||
foreach (var propertyDef in networkManagerTypeDef.Properties)
|
||||
{
|
||||
switch (propertyInfo.Name)
|
||||
switch (propertyDef.Name)
|
||||
{
|
||||
case k_NetworkManager_LocalClientId:
|
||||
m_NetworkManager_getLocalClientId_MethodRef = moduleDefinition.ImportReference(propertyInfo.GetMethod);
|
||||
m_NetworkManager_getLocalClientId_MethodRef = moduleDefinition.ImportReference(propertyDef.GetMethod);
|
||||
break;
|
||||
case k_NetworkManager_IsListening:
|
||||
m_NetworkManager_getIsListening_MethodRef = moduleDefinition.ImportReference(propertyInfo.GetMethod);
|
||||
m_NetworkManager_getIsListening_MethodRef = moduleDefinition.ImportReference(propertyDef.GetMethod);
|
||||
break;
|
||||
case k_NetworkManager_IsHost:
|
||||
m_NetworkManager_getIsHost_MethodRef = moduleDefinition.ImportReference(propertyInfo.GetMethod);
|
||||
m_NetworkManager_getIsHost_MethodRef = moduleDefinition.ImportReference(propertyDef.GetMethod);
|
||||
break;
|
||||
case k_NetworkManager_IsServer:
|
||||
m_NetworkManager_getIsServer_MethodRef = moduleDefinition.ImportReference(propertyInfo.GetMethod);
|
||||
m_NetworkManager_getIsServer_MethodRef = moduleDefinition.ImportReference(propertyDef.GetMethod);
|
||||
break;
|
||||
case k_NetworkManager_IsClient:
|
||||
m_NetworkManager_getIsClient_MethodRef = moduleDefinition.ImportReference(propertyInfo.GetMethod);
|
||||
m_NetworkManager_getIsClient_MethodRef = moduleDefinition.ImportReference(propertyDef.GetMethod);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var fieldInfo in networkManagerType.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
|
||||
foreach (var fieldDef in networkManagerTypeDef.Fields)
|
||||
{
|
||||
switch (fieldInfo.Name)
|
||||
switch (fieldDef.Name)
|
||||
{
|
||||
case k_NetworkManager_LogLevel:
|
||||
m_NetworkManager_LogLevel_FieldRef = moduleDefinition.ImportReference(fieldInfo);
|
||||
m_NetworkManager_LogLevel_FieldRef = moduleDefinition.ImportReference(fieldDef);
|
||||
break;
|
||||
case k_NetworkManager_rpc_func_table:
|
||||
m_NetworkManager_rpc_func_table_FieldRef = moduleDefinition.ImportReference(fieldInfo);
|
||||
m_NetworkManager_rpc_func_table_Add_MethodRef = moduleDefinition.ImportReference(fieldInfo.FieldType.GetMethod("Add"));
|
||||
m_NetworkManager_rpc_func_table_FieldRef = moduleDefinition.ImportReference(fieldDef);
|
||||
|
||||
m_NetworkManager_rpc_func_table_Add_MethodRef = fieldDef.FieldType.Resolve().Methods.First(m => m.Name == "Add");
|
||||
m_NetworkManager_rpc_func_table_Add_MethodRef.DeclaringType = fieldDef.FieldType;
|
||||
m_NetworkManager_rpc_func_table_Add_MethodRef = moduleDefinition.ImportReference(m_NetworkManager_rpc_func_table_Add_MethodRef);
|
||||
break;
|
||||
case k_NetworkManager_rpc_name_table:
|
||||
m_NetworkManager_rpc_name_table_FieldRef = moduleDefinition.ImportReference(fieldInfo);
|
||||
m_NetworkManager_rpc_name_table_Add_MethodRef = moduleDefinition.ImportReference(fieldInfo.FieldType.GetMethod("Add"));
|
||||
m_NetworkManager_rpc_name_table_FieldRef = moduleDefinition.ImportReference(fieldDef);
|
||||
|
||||
m_NetworkManager_rpc_name_table_Add_MethodRef = fieldDef.FieldType.Resolve().Methods.First(m => m.Name == "Add");
|
||||
m_NetworkManager_rpc_name_table_Add_MethodRef.DeclaringType = fieldDef.FieldType;
|
||||
m_NetworkManager_rpc_name_table_Add_MethodRef = moduleDefinition.ImportReference(m_NetworkManager_rpc_name_table_Add_MethodRef);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var networkBehaviourType = typeof(NetworkBehaviour);
|
||||
m_NetworkBehaviour_TypeRef = moduleDefinition.ImportReference(networkBehaviourType);
|
||||
foreach (var propertyInfo in networkBehaviourType.GetProperties())
|
||||
m_NetworkBehaviour_TypeRef = moduleDefinition.ImportReference(networkBehaviourTypeDef);
|
||||
foreach (var propertyDef in networkBehaviourTypeDef.Properties)
|
||||
{
|
||||
switch (propertyInfo.Name)
|
||||
switch (propertyDef.Name)
|
||||
{
|
||||
case k_NetworkBehaviour_NetworkManager:
|
||||
m_NetworkBehaviour_getNetworkManager_MethodRef = moduleDefinition.ImportReference(propertyInfo.GetMethod);
|
||||
m_NetworkBehaviour_getNetworkManager_MethodRef = moduleDefinition.ImportReference(propertyDef.GetMethod);
|
||||
break;
|
||||
case k_NetworkBehaviour_OwnerClientId:
|
||||
m_NetworkBehaviour_getOwnerClientId_MethodRef = moduleDefinition.ImportReference(propertyInfo.GetMethod);
|
||||
m_NetworkBehaviour_getOwnerClientId_MethodRef = moduleDefinition.ImportReference(propertyDef.GetMethod);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var methodInfo in networkBehaviourType.GetMethods(BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
|
||||
foreach (var methodDef in networkBehaviourTypeDef.Methods)
|
||||
{
|
||||
switch (methodInfo.Name)
|
||||
switch (methodDef.Name)
|
||||
{
|
||||
case k_NetworkBehaviour_beginSendServerRpc:
|
||||
m_NetworkBehaviour_beginSendServerRpc_MethodRef = moduleDefinition.ImportReference(methodInfo);
|
||||
m_NetworkBehaviour_beginSendServerRpc_MethodRef = moduleDefinition.ImportReference(methodDef);
|
||||
break;
|
||||
case k_NetworkBehaviour_endSendServerRpc:
|
||||
m_NetworkBehaviour_endSendServerRpc_MethodRef = moduleDefinition.ImportReference(methodInfo);
|
||||
m_NetworkBehaviour_endSendServerRpc_MethodRef = moduleDefinition.ImportReference(methodDef);
|
||||
break;
|
||||
case k_NetworkBehaviour_beginSendClientRpc:
|
||||
m_NetworkBehaviour_beginSendClientRpc_MethodRef = moduleDefinition.ImportReference(methodInfo);
|
||||
m_NetworkBehaviour_beginSendClientRpc_MethodRef = moduleDefinition.ImportReference(methodDef);
|
||||
break;
|
||||
case k_NetworkBehaviour_endSendClientRpc:
|
||||
m_NetworkBehaviour_endSendClientRpc_MethodRef = moduleDefinition.ImportReference(methodInfo);
|
||||
m_NetworkBehaviour_endSendClientRpc_MethodRef = moduleDefinition.ImportReference(methodDef);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var fieldInfo in networkBehaviourType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
|
||||
foreach (var fieldDef in networkBehaviourTypeDef.Fields)
|
||||
{
|
||||
switch (fieldInfo.Name)
|
||||
switch (fieldDef.Name)
|
||||
{
|
||||
case k_NetworkBehaviour_rpc_exec_stage:
|
||||
m_NetworkBehaviour_rpc_exec_stage_FieldRef = moduleDefinition.ImportReference(fieldInfo);
|
||||
m_NetworkBehaviour_rpc_exec_stage_FieldRef = moduleDefinition.ImportReference(fieldDef);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var networkHandlerDelegateType = typeof(NetworkManager.RpcReceiveHandler);
|
||||
m_NetworkHandlerDelegateCtor_MethodRef = moduleDefinition.ImportReference(networkHandlerDelegateType.GetConstructor(new[] { typeof(object), typeof(IntPtr) }));
|
||||
|
||||
var rpcParamsType = typeof(__RpcParams);
|
||||
m_RpcParams_TypeRef = moduleDefinition.ImportReference(rpcParamsType);
|
||||
foreach (var fieldInfo in rpcParamsType.GetFields())
|
||||
foreach (var ctor in networkHandlerDelegateTypeDef.Resolve().GetConstructors())
|
||||
{
|
||||
switch (fieldInfo.Name)
|
||||
if (ctor.HasParameters &&
|
||||
ctor.Parameters.Count == 2 &&
|
||||
ctor.Parameters[0].ParameterType.Name == nameof(System.Object) &&
|
||||
ctor.Parameters[1].ParameterType.Name == nameof(IntPtr))
|
||||
{
|
||||
m_NetworkHandlerDelegateCtor_MethodRef = moduleDefinition.ImportReference(ctor);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
m_RpcParams_TypeRef = moduleDefinition.ImportReference(rpcParamsTypeDef);
|
||||
foreach (var fieldDef in rpcParamsTypeDef.Fields)
|
||||
{
|
||||
switch (fieldDef.Name)
|
||||
{
|
||||
case k_RpcParams_Server:
|
||||
m_RpcParams_Server_FieldRef = moduleDefinition.ImportReference(fieldInfo);
|
||||
m_RpcParams_Server_FieldRef = moduleDefinition.ImportReference(fieldDef);
|
||||
break;
|
||||
case k_RpcParams_Client:
|
||||
m_RpcParams_Client_FieldRef = moduleDefinition.ImportReference(fieldInfo);
|
||||
m_RpcParams_Client_FieldRef = moduleDefinition.ImportReference(fieldDef);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var serverRpcParamsType = typeof(ServerRpcParams);
|
||||
m_ServerRpcParams_TypeRef = moduleDefinition.ImportReference(serverRpcParamsType);
|
||||
foreach (var fieldInfo in serverRpcParamsType.GetFields())
|
||||
m_ServerRpcParams_TypeRef = moduleDefinition.ImportReference(serverRpcParamsTypeDef);
|
||||
foreach (var fieldDef in serverRpcParamsTypeDef.Fields)
|
||||
{
|
||||
switch (fieldInfo.Name)
|
||||
switch (fieldDef.Name)
|
||||
{
|
||||
case k_ServerRpcParams_Receive:
|
||||
foreach (var recvFieldInfo in fieldInfo.FieldType.GetFields())
|
||||
foreach (var recvFieldDef in fieldDef.FieldType.Resolve().Fields)
|
||||
{
|
||||
switch (recvFieldInfo.Name)
|
||||
switch (recvFieldDef.Name)
|
||||
{
|
||||
case k_ServerRpcReceiveParams_SenderClientId:
|
||||
m_ServerRpcParams_Receive_SenderClientId_FieldRef = moduleDefinition.ImportReference(recvFieldInfo);
|
||||
m_ServerRpcParams_Receive_SenderClientId_FieldRef = moduleDefinition.ImportReference(recvFieldDef);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
m_ServerRpcParams_Receive_FieldRef = moduleDefinition.ImportReference(fieldInfo);
|
||||
m_ServerRpcParams_Receive_FieldRef = moduleDefinition.ImportReference(fieldDef);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var clientRpcParamsType = typeof(ClientRpcParams);
|
||||
m_ClientRpcParams_TypeRef = moduleDefinition.ImportReference(clientRpcParamsType);
|
||||
m_ClientRpcParams_TypeRef = moduleDefinition.ImportReference(clientRpcParamsTypeDef);
|
||||
m_FastBufferWriter_TypeRef = moduleDefinition.ImportReference(fastBufferWriterTypeDef);
|
||||
m_FastBufferReader_TypeRef = moduleDefinition.ImportReference(fastBufferReaderTypeDef);
|
||||
|
||||
var fastBufferWriterType = typeof(FastBufferWriter);
|
||||
m_FastBufferWriter_TypeRef = moduleDefinition.ImportReference(fastBufferWriterType);
|
||||
|
||||
var fastBufferReaderType = typeof(FastBufferReader);
|
||||
m_FastBufferReader_TypeRef = moduleDefinition.ImportReference(fastBufferReaderType);
|
||||
|
||||
// Find all extension methods for FastBufferReader and FastBufferWriter to enable user-implemented
|
||||
// methods to be called.
|
||||
// Find all extension methods for FastBufferReader and FastBufferWriter to enable user-implemented methods to be called
|
||||
var assemblies = new List<AssemblyDefinition> { m_MainModule.Assembly };
|
||||
foreach (var reference in m_MainModule.AssemblyReferences)
|
||||
{
|
||||
@@ -371,9 +616,94 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var method in networkVariableSerializationTypesTypeDef.Methods)
|
||||
{
|
||||
if (!method.IsStatic)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (method.Name)
|
||||
{
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedByMemcpy_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedINetworkSerializable):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_UnmanagedINetworkSerializable_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_ManagedINetworkSerializable):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_ManagedINetworkSerializable_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeSerializer_FixedString):
|
||||
m_NetworkVariableSerializationTypes_InitializeSerializer_FixedString_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_ManagedIEquatable):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedIEquatable_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedIEquatable_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEquals):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEquals_MethodRef = method;
|
||||
break;
|
||||
case nameof(NetworkVariableSerializationTypes.InitializeEqualityChecker_ManagedClassEquals):
|
||||
m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef = method;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// This gets all fields from this type as well as any parent types, up to (but not including) the base NetworkBehaviour class
|
||||
// Importantly... this also resolves any generics, so if the base class is Foo<T> and contains a field of NetworkVariable<T>,
|
||||
// and this class is Bar : Foo<int>, it will properly resolve NetworkVariable<T> to NetworkVariable<int>.
|
||||
private void GetAllFieldsAndResolveGenerics(TypeDefinition type, ref List<TypeReference> fieldTypes, Dictionary<string, TypeReference> genericParameters = null)
|
||||
{
|
||||
foreach (var field in type.Fields)
|
||||
{
|
||||
if (field.FieldType.IsGenericInstance)
|
||||
{
|
||||
var genericType = (GenericInstanceType)field.FieldType;
|
||||
var newGenericType = new GenericInstanceType(field.FieldType.Resolve());
|
||||
for (var i = 0; i < genericType.GenericArguments.Count; ++i)
|
||||
{
|
||||
var argument = genericType.GenericArguments[i];
|
||||
|
||||
if (genericParameters != null && genericParameters.ContainsKey(argument.Name))
|
||||
{
|
||||
newGenericType.GenericArguments.Add(genericParameters[argument.Name]);
|
||||
}
|
||||
else
|
||||
{
|
||||
newGenericType.GenericArguments.Add(argument);
|
||||
}
|
||||
}
|
||||
fieldTypes.Add(newGenericType);
|
||||
}
|
||||
else
|
||||
{
|
||||
fieldTypes.Add(field.FieldType);
|
||||
}
|
||||
}
|
||||
|
||||
if (type.BaseType == null || type.BaseType.Name == nameof(NetworkBehaviour))
|
||||
{
|
||||
return;
|
||||
}
|
||||
var genericParams = new Dictionary<string, TypeReference>();
|
||||
var resolved = type.BaseType.Resolve();
|
||||
if (type.BaseType.IsGenericInstance)
|
||||
{
|
||||
var genericType = (GenericInstanceType)type.BaseType;
|
||||
for (var i = 0; i < genericType.GenericArguments.Count; ++i)
|
||||
{
|
||||
genericParams[resolved.GenericParameters[i].Name] = genericType.GenericArguments[i];
|
||||
}
|
||||
}
|
||||
GetAllFieldsAndResolveGenerics(resolved, ref fieldTypes, genericParams);
|
||||
}
|
||||
|
||||
private void ProcessNetworkBehaviour(TypeDefinition typeDefinition, string[] assemblyDefines)
|
||||
{
|
||||
var rpcHandlers = new List<(uint RpcMethodId, MethodDefinition RpcHandler)>();
|
||||
@@ -416,6 +746,28 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
}
|
||||
}
|
||||
|
||||
if (!typeDefinition.HasGenericParameters && !typeDefinition.IsGenericInstance)
|
||||
{
|
||||
var fieldTypes = new List<TypeReference>();
|
||||
GetAllFieldsAndResolveGenerics(typeDefinition, ref fieldTypes);
|
||||
foreach (var type in fieldTypes)
|
||||
{
|
||||
//var type = field.FieldType;
|
||||
if (type.IsGenericInstance)
|
||||
{
|
||||
if (type.Resolve().Name == typeof(NetworkVariable<>).Name || type.Resolve().Name == typeof(NetworkList<>).Name)
|
||||
{
|
||||
var genericInstanceType = (GenericInstanceType)type;
|
||||
var wrappedType = genericInstanceType.GenericArguments[0];
|
||||
if (!m_WrappedNetworkVariableTypes.Contains(wrappedType))
|
||||
{
|
||||
m_WrappedNetworkVariableTypes.Add(wrappedType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (rpcHandlers.Count > 0 || rpcNames.Count > 0)
|
||||
{
|
||||
var staticCtorMethodDef = typeDefinition.GetStaticConstructor();
|
||||
@@ -669,7 +1021,7 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
{
|
||||
if (parameters[1].IsIn)
|
||||
{
|
||||
if (parameters[1].ParameterType.Resolve() == paramType.MakeByReferenceType().Resolve() &&
|
||||
if (((ByReferenceType)parameters[1].ParameterType).ElementType.FullName == paramType.FullName &&
|
||||
((ByReferenceType)parameters[1].ParameterType).ElementType.IsArray == paramType.IsArray)
|
||||
{
|
||||
methodRef = method;
|
||||
@@ -679,8 +1031,7 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
if (parameters[1].ParameterType.Resolve() == paramType.Resolve() &&
|
||||
if (parameters[1].ParameterType.FullName == paramType.FullName &&
|
||||
parameters[1].ParameterType.IsArray == paramType.IsArray)
|
||||
{
|
||||
methodRef = method;
|
||||
@@ -813,7 +1164,7 @@ namespace Unity.Netcode.Editor.CodeGen
|
||||
var parameters = method.Resolve().Parameters;
|
||||
if (method.Name == k_ReadValueMethodName &&
|
||||
parameters[1].IsOut &&
|
||||
parameters[1].ParameterType.Resolve() == paramType.MakeByReferenceType().Resolve() &&
|
||||
((ByReferenceType)parameters[1].ParameterType).ElementType.FullName == paramType.FullName &&
|
||||
((ByReferenceType)parameters[1].ParameterType).ElementType.IsArray == paramType.IsArray)
|
||||
{
|
||||
methodRef = method;
|
||||
|
||||
81
Editor/HiddenScriptEditor.cs
Normal file
81
Editor/HiddenScriptEditor.cs
Normal file
@@ -0,0 +1,81 @@
|
||||
using Unity.Netcode.Components;
|
||||
#if UNITY_UNET_PRESENT
|
||||
using Unity.Netcode.Transports.UNET;
|
||||
#endif
|
||||
using Unity.Netcode.Transports.UTP;
|
||||
using UnityEditor;
|
||||
|
||||
namespace Unity.Netcode.Editor
|
||||
{
|
||||
/// <summary>
|
||||
/// Internal use. Hides the script field for the given component.
|
||||
/// </summary>
|
||||
public class HiddenScriptEditor : UnityEditor.Editor
|
||||
{
|
||||
private static readonly string[] k_HiddenFields = { "m_Script" };
|
||||
|
||||
/// <summary>
|
||||
/// Draws inspector properties without the script field.
|
||||
/// </summary>
|
||||
public override void OnInspectorGUI()
|
||||
{
|
||||
EditorGUI.BeginChangeCheck();
|
||||
serializedObject.UpdateIfRequiredOrScript();
|
||||
DrawPropertiesExcluding(serializedObject, k_HiddenFields);
|
||||
serializedObject.ApplyModifiedProperties();
|
||||
EditorGUI.EndChangeCheck();
|
||||
}
|
||||
}
|
||||
#if UNITY_UNET_PRESENT
|
||||
/// <summary>
|
||||
/// Internal use. Hides the script field for UNetTransport.
|
||||
/// </summary>
|
||||
[CustomEditor(typeof(UNetTransport), true)]
|
||||
public class UNetTransportEditor : HiddenScriptEditor
|
||||
{
|
||||
|
||||
}
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Internal use. Hides the script field for UnityTransport.
|
||||
/// </summary>
|
||||
[CustomEditor(typeof(UnityTransport), true)]
|
||||
public class UnityTransportEditor : HiddenScriptEditor
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
#if COM_UNITY_MODULES_ANIMATION
|
||||
/// <summary>
|
||||
/// Internal use. Hides the script field for NetworkAnimator.
|
||||
/// </summary>
|
||||
[CustomEditor(typeof(NetworkAnimator), true)]
|
||||
public class NetworkAnimatorEditor : HiddenScriptEditor
|
||||
{
|
||||
|
||||
}
|
||||
#endif
|
||||
|
||||
#if COM_UNITY_MODULES_PHYSICS
|
||||
/// <summary>
|
||||
/// Internal use. Hides the script field for NetworkRigidbody.
|
||||
/// </summary>
|
||||
[CustomEditor(typeof(NetworkRigidbody), true)]
|
||||
public class NetworkRigidbodyEditor : HiddenScriptEditor
|
||||
{
|
||||
|
||||
}
|
||||
#endif
|
||||
|
||||
#if COM_UNITY_MODULES_PHYSICS2D
|
||||
/// <summary>
|
||||
/// Internal use. Hides the script field for NetworkRigidbody2D.
|
||||
/// </summary>
|
||||
[CustomEditor(typeof(NetworkRigidbody2D), true)]
|
||||
public class NetworkRigidbody2DEditor : HiddenScriptEditor
|
||||
{
|
||||
|
||||
}
|
||||
#endif
|
||||
}
|
||||
3
Editor/HiddenScriptEditor.cs.meta
Normal file
3
Editor/HiddenScriptEditor.cs.meta
Normal file
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ebf622cc80e94f488e59caf8b7419f50
|
||||
timeCreated: 1661959406
|
||||
@@ -263,8 +263,7 @@ namespace Unity.Netcode.Editor
|
||||
|
||||
// Now get the root parent transform to the current GameObject (or itself)
|
||||
var rootTransform = GetRootParentTransform(gameObject.transform);
|
||||
var networkManager = rootTransform.GetComponent<NetworkManager>();
|
||||
if (networkManager == null)
|
||||
if (!rootTransform.TryGetComponent<NetworkManager>(out var networkManager))
|
||||
{
|
||||
networkManager = rootTransform.GetComponentInChildren<NetworkManager>();
|
||||
}
|
||||
@@ -299,8 +298,7 @@ namespace Unity.Netcode.Editor
|
||||
|
||||
// Otherwise, check to see if there is any NetworkObject from the root GameObject down to all children.
|
||||
// If not, notify the user that NetworkBehaviours require that the relative GameObject has a NetworkObject component.
|
||||
var networkObject = rootTransform.GetComponent<NetworkObject>();
|
||||
if (networkObject == null)
|
||||
if (!rootTransform.TryGetComponent<NetworkObject>(out var networkObject))
|
||||
{
|
||||
networkObject = rootTransform.GetComponentInChildren<NetworkObject>();
|
||||
|
||||
|
||||
@@ -214,18 +214,6 @@ namespace Unity.Netcode.Editor
|
||||
DrawInstallMultiplayerToolsTip();
|
||||
#endif
|
||||
|
||||
{
|
||||
var iterator = serializedObject.GetIterator();
|
||||
|
||||
for (bool enterChildren = true; iterator.NextVisible(enterChildren); enterChildren = false)
|
||||
{
|
||||
using (new EditorGUI.DisabledScope("m_Script" == iterator.propertyPath))
|
||||
{
|
||||
EditorGUILayout.PropertyField(iterator, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!m_NetworkManager.IsServer && !m_NetworkManager.IsClient)
|
||||
{
|
||||
serializedObject.Update();
|
||||
|
||||
@@ -64,7 +64,7 @@ namespace Unity.Netcode.Editor
|
||||
{
|
||||
var scenesList = EditorBuildSettings.scenes.ToList();
|
||||
var activeScene = SceneManager.GetActiveScene();
|
||||
var isSceneInBuildSettings = scenesList.Where((c) => c.path == activeScene.path).Count() == 1;
|
||||
var isSceneInBuildSettings = scenesList.Count((c) => c.path == activeScene.path) == 1;
|
||||
var networkManager = Object.FindObjectOfType<NetworkManager>();
|
||||
if (!isSceneInBuildSettings && networkManager != null)
|
||||
{
|
||||
@@ -109,9 +109,8 @@ namespace Unity.Netcode.Editor
|
||||
public void CheckAndNotifyUserNetworkObjectRemoved(NetworkManager networkManager, bool editorTest = false)
|
||||
{
|
||||
// Check for any NetworkObject at the same gameObject relative layer
|
||||
var networkObject = networkManager.gameObject.GetComponent<NetworkObject>();
|
||||
|
||||
if (networkObject == null)
|
||||
if (!networkManager.gameObject.TryGetComponent<NetworkObject>(out var networkObject))
|
||||
{
|
||||
// if none is found, check to see if any children have a NetworkObject
|
||||
networkObject = networkManager.gameObject.GetComponentInChildren<NetworkObject>();
|
||||
|
||||
@@ -15,6 +15,8 @@ namespace Unity.Netcode.Editor
|
||||
private NetworkObject m_NetworkObject;
|
||||
private bool m_ShowObservers;
|
||||
|
||||
private static readonly string[] k_HiddenFields = { "m_Script" };
|
||||
|
||||
private void Initialize()
|
||||
{
|
||||
if (m_Initialized)
|
||||
@@ -95,7 +97,11 @@ namespace Unity.Netcode.Editor
|
||||
}
|
||||
else
|
||||
{
|
||||
base.OnInspectorGUI();
|
||||
EditorGUI.BeginChangeCheck();
|
||||
serializedObject.UpdateIfRequiredOrScript();
|
||||
DrawPropertiesExcluding(serializedObject, k_HiddenFields);
|
||||
serializedObject.ApplyModifiedProperties();
|
||||
EditorGUI.EndChangeCheck();
|
||||
|
||||
var guiEnabled = GUI.enabled;
|
||||
GUI.enabled = false;
|
||||
|
||||
@@ -13,6 +13,26 @@
|
||||
"name": "com.unity.multiplayer.tools",
|
||||
"expression": "",
|
||||
"define": "MULTIPLAYER_TOOLS"
|
||||
},
|
||||
{
|
||||
"name": "Unity",
|
||||
"expression": "(0,2022.2.0a5)",
|
||||
"define": "UNITY_UNET_PRESENT"
|
||||
},
|
||||
{
|
||||
"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"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user