-
Notifications
You must be signed in to change notification settings - Fork 450
perf: Remove reflection from NetworkBehaviour code to improve performance. [MTT-1968] #2522
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
d1ad810
perf: Remove reflection from NetworkBehaviour code to improve perform…
ShadauxCat 3e7d949
changelog
ShadauxCat e1ff678
- Added some comments to clarify some ILPP code
ShadauxCat 3dd8568
Apply suggestions from code review
ShadauxCat 2fbbeec
Merge develop into perf/remove_reflection_in_networkbehaviour
netcode-ci-service File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -166,6 +166,11 @@ private void CreateNetworkVariableTypeInitializers(AssemblyDefinition assembly) | |
|
||
foreach (var type in m_WrappedNetworkVariableTypes) | ||
{ | ||
if (type.Resolve() == null) | ||
{ | ||
continue; | ||
} | ||
|
||
if (IsSpecialCaseType(type)) | ||
{ | ||
continue; | ||
|
@@ -251,11 +256,15 @@ private void CreateNetworkVariableTypeInitializers(AssemblyDefinition assembly) | |
private FieldReference m_NetworkManager_rpc_name_table_FieldRef; | ||
private MethodReference m_NetworkManager_rpc_name_table_Add_MethodRef; | ||
private TypeReference m_NetworkBehaviour_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_beginSendClientRpc_MethodRef; | ||
private MethodReference m_NetworkBehaviour_endSendClientRpc_MethodRef; | ||
private FieldReference m_NetworkBehaviour_rpc_exec_stage_FieldRef; | ||
private FieldReference m_NetworkBehaviour_NetworkVariableFields_FieldRef; | ||
private MethodReference m_NetworkBehaviour_getNetworkManager_MethodRef; | ||
private MethodReference m_NetworkBehaviour_getOwnerClientId_MethodRef; | ||
private MethodReference m_NetworkHandlerDelegateCtor_MethodRef; | ||
|
@@ -275,6 +284,9 @@ private void CreateNetworkVariableTypeInitializers(AssemblyDefinition assembly) | |
private MethodReference m_NetworkVariableSerializationTypes_InitializeEqualityChecker_UnmanagedValueEquals_MethodRef; | ||
private MethodReference m_NetworkVariableSerializationTypes_InitializeEqualityChecker_ManagedClassEquals_MethodRef; | ||
|
||
private MethodReference m_ExceptionCtorMethodReference; | ||
private MethodReference m_List_NetworkVariableBase_Add; | ||
|
||
private MethodReference m_BytePacker_WriteValueBitPacked_Short_MethodRef; | ||
private MethodReference m_BytePacker_WriteValueBitPacked_UShort_MethodRef; | ||
private MethodReference m_BytePacker_WriteValueBitPacked_Int_MethodRef; | ||
|
@@ -348,12 +360,17 @@ private void CreateNetworkVariableTypeInitializers(AssemblyDefinition assembly) | |
private const string k_NetworkManager_rpc_name_table = nameof(NetworkManager.__rpc_name_table); | ||
|
||
private const string k_NetworkBehaviour_rpc_exec_stage = nameof(NetworkBehaviour.__rpc_exec_stage); | ||
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_beginSendClientRpc = nameof(NetworkBehaviour.__beginSendClientRpc); | ||
private const string k_NetworkBehaviour_endSendClientRpc = nameof(NetworkBehaviour.__endSendClientRpc); | ||
private const string k_NetworkBehaviour___initializeVariables = nameof(NetworkBehaviour.__initializeVariables); | ||
private const string k_NetworkBehaviour_NetworkManager = nameof(NetworkBehaviour.NetworkManager); | ||
private const string k_NetworkBehaviour_OwnerClientId = nameof(NetworkBehaviour.OwnerClientId); | ||
private const string k_NetworkBehaviour___nameNetworkVariable = nameof(NetworkBehaviour.__nameNetworkVariable); | ||
|
||
private const string k_NetworkVariableBase_Initialize = nameof(NetworkVariableBase.Initialize); | ||
|
||
private const string k_RpcAttribute_Delivery = nameof(RpcAttribute.Delivery); | ||
private const string k_ServerRpcAttribute_RequireOwnership = nameof(ServerRpcAttribute.RequireOwnership); | ||
|
@@ -379,6 +396,7 @@ private bool ImportReferences(ModuleDefinition moduleDefinition) | |
|
||
TypeDefinition networkManagerTypeDef = null; | ||
TypeDefinition networkBehaviourTypeDef = null; | ||
TypeDefinition networkVariableBaseTypeDef = null; | ||
TypeDefinition networkHandlerDelegateTypeDef = null; | ||
TypeDefinition rpcParamsTypeDef = null; | ||
TypeDefinition serverRpcParamsTypeDef = null; | ||
|
@@ -402,6 +420,12 @@ private bool ImportReferences(ModuleDefinition moduleDefinition) | |
continue; | ||
} | ||
|
||
if (networkVariableBaseTypeDef == null && netcodeTypeDef.Name == nameof(NetworkVariableBase)) | ||
{ | ||
networkVariableBaseTypeDef = netcodeTypeDef; | ||
continue; | ||
} | ||
|
||
if (networkHandlerDelegateTypeDef == null && netcodeTypeDef.Name == nameof(NetworkManager.RpcReceiveHandler)) | ||
{ | ||
networkHandlerDelegateTypeDef = netcodeTypeDef; | ||
|
@@ -548,6 +572,9 @@ private bool ImportReferences(ModuleDefinition moduleDefinition) | |
case k_NetworkBehaviour_endSendClientRpc: | ||
m_NetworkBehaviour_endSendClientRpc_MethodRef = moduleDefinition.ImportReference(methodDef); | ||
break; | ||
case k_NetworkBehaviour___nameNetworkVariable: | ||
m_NetworkBehaviour___nameNetworkVariable_MethodRef = moduleDefinition.ImportReference(methodDef); | ||
break; | ||
} | ||
} | ||
|
||
|
@@ -558,6 +585,21 @@ private bool ImportReferences(ModuleDefinition moduleDefinition) | |
case k_NetworkBehaviour_rpc_exec_stage: | ||
m_NetworkBehaviour_rpc_exec_stage_FieldRef = moduleDefinition.ImportReference(fieldDef); | ||
break; | ||
case k_NetworkBehaviour_NetworkVariableFields: | ||
m_NetworkBehaviour_NetworkVariableFields_FieldRef = moduleDefinition.ImportReference(fieldDef); | ||
break; | ||
} | ||
} | ||
|
||
|
||
m_NetworkVariableBase_TypeRef = moduleDefinition.ImportReference(networkVariableBaseTypeDef); | ||
foreach (var methodDef in networkVariableBaseTypeDef.Methods) | ||
{ | ||
switch (methodDef.Name) | ||
{ | ||
case k_NetworkVariableBase_Initialize: | ||
m_NetworkVariableBase_Initialize_MethodRef = moduleDefinition.ImportReference(methodDef); | ||
break; | ||
} | ||
} | ||
|
||
|
@@ -785,6 +827,16 @@ private bool ImportReferences(ModuleDefinition moduleDefinition) | |
} | ||
} | ||
|
||
// Standard types are really hard to reliably find using the Mono Cecil way, they resolve differently in Mono vs .NET Core | ||
// Importing with typeof() is less dangerous for standard framework types though, so we can just do it | ||
var exceptionType = typeof(Exception); | ||
var exceptionCtor = exceptionType.GetConstructor(new[] { typeof(string) }); | ||
m_ExceptionCtorMethodReference = m_MainModule.ImportReference(exceptionCtor); | ||
|
||
var listType = typeof(List<NetworkVariableBase>); | ||
var addMethod = listType.GetMethod(nameof(List<NetworkVariableBase>.Add), new[] { typeof(NetworkVariableBase) }); | ||
m_List_NetworkVariableBase_Add = moduleDefinition.ImportReference(addMethod); | ||
|
||
return true; | ||
} | ||
|
||
|
@@ -931,6 +983,8 @@ private void ProcessNetworkBehaviour(TypeDefinition typeDefinition, string[] ass | |
} | ||
} | ||
|
||
GenerateVariableInitialization(typeDefinition); | ||
|
||
if (!typeDefinition.HasGenericParameters && !typeDefinition.IsGenericInstance) | ||
{ | ||
var fieldTypes = new List<TypeReference>(); | ||
|
@@ -1889,6 +1943,132 @@ private void InjectWriteAndCallBlocks(MethodDefinition methodDefinition, CustomA | |
instructions.ForEach(instruction => processor.Body.Instructions.Insert(0, instruction)); | ||
} | ||
|
||
private void GenerateVariableInitialization(TypeDefinition type) | ||
{ | ||
foreach (var methodDefinition in type.Methods) | ||
{ | ||
if (methodDefinition.Name == k_NetworkBehaviour___initializeVariables) | ||
{ | ||
// If this hits, we've already generated the method for this class because a child class got processed first. | ||
return; | ||
} | ||
} | ||
|
||
var method = new MethodDefinition( | ||
k_NetworkBehaviour___initializeVariables, | ||
MethodAttributes.Family | MethodAttributes.Virtual | MethodAttributes.HideBySig, | ||
m_MainModule.TypeSystem.Void); | ||
|
||
var processor = method.Body.GetILProcessor(); | ||
|
||
method.Body.Variables.Add(new VariableDefinition(m_MainModule.TypeSystem.Boolean)); | ||
|
||
processor.Emit(OpCodes.Nop); | ||
|
||
foreach (var fieldDefinition in type.Fields) | ||
{ | ||
FieldReference field = fieldDefinition; | ||
if (type.HasGenericParameters) | ||
{ | ||
var genericType = new GenericInstanceType(fieldDefinition.DeclaringType); | ||
foreach (var parameter in fieldDefinition.DeclaringType.GenericParameters) | ||
{ | ||
genericType.GenericArguments.Add(parameter); | ||
} | ||
field = new FieldReference(fieldDefinition.Name, fieldDefinition.FieldType, genericType); | ||
} | ||
if (field.FieldType.IsSubclassOf(m_NetworkVariableBase_TypeRef)) | ||
{ | ||
// if({variable} != null) { | ||
processor.Emit(OpCodes.Ldarg_0); | ||
processor.Emit(OpCodes.Ldfld, field); | ||
processor.Emit(OpCodes.Ldnull); | ||
processor.Emit(OpCodes.Ceq); | ||
processor.Emit(OpCodes.Stloc_0); | ||
processor.Emit(OpCodes.Ldloc_0); | ||
|
||
var afterThrowInstruction = processor.Create(OpCodes.Nop); | ||
|
||
processor.Emit(OpCodes.Brfalse, afterThrowInstruction); | ||
|
||
// throw new Exception("..."); | ||
processor.Emit(OpCodes.Nop); | ||
processor.Emit(OpCodes.Ldstr, $"{type.Name}.{field.Name} cannot be null. All {nameof(NetworkVariableBase)} instances must be initialized."); | ||
processor.Emit(OpCodes.Newobj, m_ExceptionCtorMethodReference); | ||
processor.Emit(OpCodes.Throw); | ||
|
||
// } | ||
processor.Append(afterThrowInstruction); | ||
|
||
// {variable}.Initialize(this); | ||
processor.Emit(OpCodes.Ldarg_0); | ||
processor.Emit(OpCodes.Ldfld, field); | ||
processor.Emit(OpCodes.Ldarg_0); | ||
processor.Emit(OpCodes.Callvirt, m_NetworkVariableBase_Initialize_MethodRef); | ||
|
||
// __nameNetworkVariable({variable}, "{variable}"); | ||
processor.Emit(OpCodes.Nop); | ||
processor.Emit(OpCodes.Ldarg_0); | ||
processor.Emit(OpCodes.Ldarg_0); | ||
processor.Emit(OpCodes.Ldfld, field); | ||
processor.Emit(OpCodes.Ldstr, field.Name.Replace("<", string.Empty).Replace(">k__BackingField", string.Empty)); | ||
processor.Emit(OpCodes.Call, m_NetworkBehaviour___nameNetworkVariable_MethodRef); | ||
|
||
// NetworkVariableFields.Add({variable}); | ||
processor.Emit(OpCodes.Nop); | ||
processor.Emit(OpCodes.Ldarg_0); | ||
processor.Emit(OpCodes.Ldfld, m_NetworkBehaviour_NetworkVariableFields_FieldRef); | ||
processor.Emit(OpCodes.Ldarg_0); | ||
processor.Emit(OpCodes.Ldfld, field); | ||
processor.Emit(OpCodes.Callvirt, m_List_NetworkVariableBase_Add); | ||
} | ||
} | ||
|
||
// Find the base method... | ||
MethodReference initializeVariablesBaseReference = null; | ||
foreach (var methodDefinition in type.BaseType.Resolve().Methods) | ||
{ | ||
if (methodDefinition.Name == k_NetworkBehaviour___initializeVariables) | ||
{ | ||
initializeVariablesBaseReference = m_MainModule.ImportReference(methodDefinition); | ||
break; | ||
} | ||
} | ||
|
||
if (initializeVariablesBaseReference == null) | ||
{ | ||
// If we couldn't find it, we have to go ahead and add it. | ||
// The base class could be in another assembly... that's ok, this won't | ||
// actually save but it'll generate the same method the same way later, | ||
// so this at least allows us to reference it. | ||
GenerateVariableInitialization(type.BaseType.Resolve()); | ||
foreach (var methodDefinition in type.BaseType.Resolve().Methods) | ||
{ | ||
if (methodDefinition.Name == k_NetworkBehaviour___initializeVariables) | ||
{ | ||
initializeVariablesBaseReference = m_MainModule.ImportReference(methodDefinition); | ||
break; | ||
} | ||
} | ||
} | ||
|
||
if (type.BaseType.Resolve().HasGenericParameters) | ||
{ | ||
var baseTypeInstance = (GenericInstanceType)type.BaseType; | ||
initializeVariablesBaseReference = initializeVariablesBaseReference.MakeGeneric(baseTypeInstance.GenericArguments.ToArray()); | ||
} | ||
|
||
// base.__initializeVariables(); | ||
processor.Emit(OpCodes.Nop); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ^ same here There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Also done. |
||
processor.Emit(OpCodes.Ldarg_0); | ||
processor.Emit(OpCodes.Call, initializeVariablesBaseReference); | ||
processor.Emit(OpCodes.Nop); | ||
|
||
processor.Emit(OpCodes.Ret); | ||
|
||
type.Methods.Add(method); | ||
} | ||
|
||
private MethodDefinition GenerateStaticHandler(MethodDefinition methodDefinition, CustomAttribute rpcAttribute, uint rpcMethodId) | ||
{ | ||
var typeSystem = methodDefinition.Module.TypeSystem; | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I usually find inline pseudo-C# code helpful understanding what was tried to be achieved with IL emits.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice... now I can understand what the OpCodes actually mean! 😸
(TILT)