Skip to content

Commit

Permalink
Code cleanup.
Browse files Browse the repository at this point in the history
Cache many places where reflection is used.
  • Loading branch information
roncli committed Feb 13, 2021
1 parent ddd6372 commit 1fd7e8b
Show file tree
Hide file tree
Showing 26 changed files with 440 additions and 521 deletions.
14 changes: 7 additions & 7 deletions GameMod/AddOnLevelSort.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,25 +14,25 @@ namespace GameMod
/// Email: tobiasksu@gmail.com
/// Sort addon levels by DisplayName instead of arbitrary load
/// </summary>
[HarmonyPatch(typeof(Overload.GameManager), "InitializeMissionList")]
[HarmonyPatch(typeof(GameManager), "InitializeMissionList")]
class AddOnLevelSort
{
private static FieldInfo _Mission_Levels_Field = typeof(Mission).GetField("Levels", BindingFlags.NonPublic | BindingFlags.Instance);
private static PropertyInfo _LevelInfo_LevelNum_Property = typeof(LevelInfo).GetProperty("LevelNum");
static void Postfix()
{
try
{
FieldInfo fi = typeof(Mission).GetField("Levels", BindingFlags.NonPublic | BindingFlags.Instance);
object __obj = fi.GetValue(GameManager.MultiplayerMission);
object __obj = _Mission_Levels_Field.GetValue(GameManager.MultiplayerMission);
List<LevelInfo> __m_mission_list = (List<LevelInfo>)__obj;

__m_mission_list.Sort((a, b) => a.IsAddOn && b.IsAddOn ? a.DisplayName.CompareTo(b.DisplayName) : a.LevelNum-b.LevelNum);
for (var i = 0; i < __m_mission_list.Count; i++)
{
PropertyInfo ln = typeof(LevelInfo).GetProperty("LevelNum");
ln.DeclaringType.GetProperty("LevelNum");
ln.SetValue(__m_mission_list[i], i, BindingFlags.NonPublic | BindingFlags.Instance, null, null, null);
_LevelInfo_LevelNum_Property.DeclaringType.GetProperty("LevelNum");
_LevelInfo_LevelNum_Property.SetValue(__m_mission_list[i], i, BindingFlags.NonPublic | BindingFlags.Instance, null, null, null);
}
fi.SetValue(GameManager.MultiplayerMission, __m_mission_list);
_Mission_Levels_Field.SetValue(GameManager.MultiplayerMission, __m_mission_list);
} catch (Exception ex)
{
Debug.Log("InitializeMissionList() patch failed - " + ex.Message);
Expand Down
17 changes: 7 additions & 10 deletions GameMod/CTF.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@
using UnityEngine.Networking;
using UnityEngine.Networking.NetworkSystem;

namespace GameMod
{
namespace GameMod {
public enum FlagState
{
HOME, PICKEDUP, LOST
Expand Down Expand Up @@ -444,6 +443,7 @@ private static bool Prefix(ref string __result)
class CTFRegisterSpawnHandlers
{
private static Dictionary<NetworkHash128, GameObject> m_registered_prefabs = new Dictionary<NetworkHash128, GameObject>();
private static FieldInfo _NetworkIdentity_m_AssetId_Field = typeof(NetworkIdentity).GetField("m_AssetId", BindingFlags.NonPublic | BindingFlags.Instance);

private static GameObject NetworkSpawnItemHandler(Vector3 pos, NetworkHash128 asset_id)
{
Expand All @@ -464,7 +464,7 @@ private static GameObject NetworkSpawnItemHandler(Vector3 pos, NetworkHash128 as
//Debug.Log("Spawning flag " + asset_id + " active " + gameObject.activeSelf + " seg " + gameObject.GetComponent<Item>().m_current_segment);

var netId = gameObject.GetComponent<NetworkIdentity>();
netId.GetType().GetField("m_AssetId", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(netId, asset_id);
_NetworkIdentity_m_AssetId_Field.SetValue(netId, asset_id);
//Debug.Log("post spawn assetid " + gameObject.GetComponent<NetworkIdentity>().assetId);

return gameObject;
Expand Down Expand Up @@ -520,7 +520,7 @@ private static void Postfix()
}
var assetId = CTF.FlagAssetId(i);
var netId = flag.GetComponent<NetworkIdentity>();
netId.GetType().GetField("m_AssetId", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(netId, assetId);
_NetworkIdentity_m_AssetId_Field.SetValue(netId, assetId);
UnityEngine.Object.DontDestroyOnLoad(flag);
flag.SetActive(false);
var item = flag.GetComponent<Item>();
Expand Down Expand Up @@ -574,11 +574,8 @@ private static void Postfix()
[HarmonyPatch(typeof(Item), "OnTriggerEnter")]
class CTFOnTriggerEnter
{
static MethodInfo ItemIsReachable;
static void Prepare()
{
ItemIsReachable = typeof(Item).GetMethod("ItemIsReachable", BindingFlags.NonPublic | BindingFlags.Instance);
}
private static MethodInfo _Item_ItemIsReachable_Method = typeof(Item).GetMethod("ItemIsReachable", BindingFlags.NonPublic | BindingFlags.Instance);

static bool Prefix(Item __instance, Collider other)
{
//Debug.Log("OnTriggerEnter " + __instance.m_type + " server =" + Overload.NetworkManager.IsServer() + " index=" + __instance.m_index);
Expand All @@ -594,7 +591,7 @@ static bool Prefix(Item __instance, Collider other)
return false;
}
Player c_player = component.c_player;
if (!(bool)ItemIsReachable.Invoke(__instance, new object[] { other }) || (bool)component.m_dying)
if (!(bool)_Item_ItemIsReachable_Method.Invoke(__instance, new object[] { other }) || (bool)component.m_dying)
{
return false;
}
Expand Down
9 changes: 3 additions & 6 deletions GameMod/Config.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using UnityEngine;

namespace GameMod
{
namespace GameMod {
static class Config
{
public static string OLModDir;
Expand Down
22 changes: 13 additions & 9 deletions GameMod/Console.cs
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
using GameMod.Core;
using Harmony;
using Overload;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using GameMod.Core;
using Harmony;
using Overload;
using UnityEngine;

namespace GameMod
{
namespace GameMod {
static class Console
{
public static bool KeyEnabled;
public static int CustomUIColor;

private static MethodInfo _GameManager_InitializeMissionList_Method = typeof(GameManager).GetMethod("InitializeMissionList", AccessTools.all);
public static void CmdReloadMissions()
{
MBLevelPatch.SLInit = false;
typeof(GameManager).GetMethod("InitializeMissionList", AccessTools.all).Invoke(GameManager.m_gm, null);
_GameManager_InitializeMissionList_Method.Invoke(GameManager.m_gm, null);
uConsole.Log("Missions reloaded (" + GameManager.GetAvailableMissions().Length + " sp, " +
GameManager.ChallengeMission.NumLevels + " cm, " + GameManager.MultiplayerMission.NumLevels + " mp)");
}
Expand Down Expand Up @@ -146,6 +146,8 @@ public static void DrawConsoleOption(UIElement uie, ref Vector2 position)

private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> codes)
{
var consoleOptionPatch_DrawConsoleOption_Method = AccessTools.Method(typeof(ConsoleOptionPatch), "DrawConsoleOption");

int state = 0; // 0 = before adv.ctrl, 1 = before 248f, 2 = before stloc (last opt), 3 = before last SelectAndDrawStringOptionItem, 4 = rest
foreach (var code in codes) {
if (state == 0 && code.opcode == OpCodes.Ldstr && (string)code.operand == "CONTROL OPTIONS - ADVANCED") {
Expand All @@ -159,7 +161,7 @@ private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstructi
yield return code;
yield return new CodeInstruction(OpCodes.Ldarg_0);
yield return new CodeInstruction(OpCodes.Ldloca, 0);
yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(ConsoleOptionPatch), "DrawConsoleOption"));
yield return new CodeInstruction(OpCodes.Call, consoleOptionPatch_DrawConsoleOption_Method);
state = 4;
continue;
}
Expand All @@ -174,12 +176,14 @@ class ConsoleOptionTogglePatch
{
private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> codes)
{
var consoleOptionTogglePatch_HandleConsoleToggle_Method = AccessTools.Method(typeof(ConsoleOptionTogglePatch), "HandleConsoleToggle");

foreach (var code in codes)
{
if (code.opcode == OpCodes.Call && ((MethodInfo)code.operand).Name == "MaybeReverseOption")
{
yield return code;
yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(ConsoleOptionTogglePatch), "HandleConsoleToggle"));
yield return new CodeInstruction(OpCodes.Call, consoleOptionTogglePatch_HandleConsoleToggle_Method);
continue;
}

Expand Down
3 changes: 2 additions & 1 deletion GameMod/Controllers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,8 @@ static void Postfix(string filename)
}
catch (Exception ex)
{
GameManager.DebugOut(ex.GetType() + " in ControlsMod.SaveControlData: " + ex.Message, 15f);
Debug.LogException(ex);
GameManager.DebugOut("Error in ControlsMod.SaveControlData: " + ex.Message, 15f);
}
}

Expand Down
8 changes: 6 additions & 2 deletions GameMod/CustomLevelResources.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@ class CustomLevelMaterials
{ "alien_decals_02a_dark", "alien_decals_02a/alien_decals_02a_dark" },
{ "alien_decals_02b_dark", "alien_decals_02b/alien_decals_02b_dark" },
{ "alien_decals_03g_dark", "alien_decals_03g/alien_decals_03g_dark" },
{ "om_signs_ambient_02b", "om_signs_ambient_02b/om_signs_ambient_02b" } };
{ "om_signs_ambient_02b", "om_signs_ambient_02b/om_signs_ambient_02b" }
};

static MethodInfo TargetMethod()
{
return typeof(UserLevelLoader).Assembly.GetType("ResourceDatabase").GetMethod("LookupMaterial", BindingFlags.Static | BindingFlags.Public);
}

static void Postfix(string name, ref string __result)
{
if (__result != null)
Expand All @@ -44,12 +46,14 @@ class CustomLevelPrefabs
{ "entity_prop_fan_tn_corner", "entity_prop_fan_tn_corner" },
{ "entity_prop_reactor_om16", "entity_prop_reactor_om16" },
{ "entity_trigger_box_lava_alien", "entity_trigger_box_lava_alien" },
{ "entity_trigger_box_lava_normal", "entity_trigger_box_lava_normal" } };
{ "entity_trigger_box_lava_normal", "entity_trigger_box_lava_normal" }
};

static MethodInfo TargetMethod()
{
return typeof(UserLevelLoader).Assembly.GetType("ResourceDatabase").GetMethod("LookupPrefab", BindingFlags.Static | BindingFlags.Public);
}

static void Postfix(string name, ref string __result)
{
if (__result != null)
Expand Down
14 changes: 7 additions & 7 deletions GameMod/FastLoad.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
using Harmony;
using Overload;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Reflection;
using Harmony;
using Overload;
using UnityEngine;

namespace GameMod
{
namespace GameMod {
// load faster by doing multiple steps in the same frame
[HarmonyPatch(typeof(GameManager), "MaybeEnableDeveloperMode")]
class FastLoadInit
Expand Down Expand Up @@ -38,6 +37,8 @@ private static bool Prepare()
Debug.Log("nosound enabled");
return enabled;
}

private static MethodInfo _UnityAudio_CreateAudioSourceAndObject_Method = typeof(UnityAudio).GetMethod("CreateAudioSourceAndObject", BindingFlags.NonPublic | BindingFlags.Instance);
private static bool Prefix(ref IEnumerable<float> __result, AudioClip[] ___m_sound_effects, float[] ___m_sound_effects_volume,
float[] ___m_sound_effects_pitch_amt, float[] ___m_sound_effects_cooldown, UnityAudio __instance)
{
Expand All @@ -47,12 +48,11 @@ private static bool Prefix(ref IEnumerable<float> __result, AudioClip[] ___m_sou
___m_sound_effects_volume[i] = 1f;
}
__instance.InitSoundFX();
var CreateAudioSourceAndObject = typeof(UnityAudio).GetMethod("CreateAudioSourceAndObject", BindingFlags.NonPublic | BindingFlags.Instance);
var args = new object[] { 0, "" };
for (int j = 0; j < 512; j++)
{
args[0] = j;
CreateAudioSourceAndObject.Invoke(__instance, args);
_UnityAudio_CreateAudioSourceAndObject_Method.Invoke(__instance, args);
}
__instance.SFXVolume = MenuManager.opt_volume_sfx;
__result = new float[0];
Expand Down
64 changes: 14 additions & 50 deletions GameMod/GameMod.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
using Overload;
using UnityEngine;

namespace GameMod.Core
{
namespace GameMod.Core {
public class GameMod
{
public static string Version = "olmod 0.3.5";
Expand All @@ -27,7 +26,7 @@ public static void Initialize()

Modded = FindArg("-modded");

GameVersion = typeof(Overload.GameManager).Assembly.GetName().Version;
GameVersion = typeof(GameManager).Assembly.GetName().Version;
Debug.Log("Initializing " + Version + ", game " + GameVersion);
Debug.Log("Command line " + String.Join(" ", Environment.GetCommandLineArgs()));
Config.Init();
Expand Down Expand Up @@ -95,54 +94,13 @@ public static bool FindArgVal(string arg, out string val)
return true;
}

// enable monsterball mode, allow max players up to 16
[HarmonyPatch(typeof(Overload.MenuManager), "MpMatchSetup")]
class MBModeSelPatch
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
int n = 0;
var codes = new List<CodeInstruction>(instructions);
for (var i = 0; i < codes.Count; i++)
{
// increase max mode to allow monsterball mode
if (codes[i].opcode == OpCodes.Ldsfld && (codes[i].operand as FieldInfo).Name == "mms_mode")
{
i++;
if (codes[i].opcode == OpCodes.Ldc_I4_2)
codes[i].opcode = OpCodes.Ldc_I4_4;
i++;
while (codes[i].opcode == OpCodes.Add || codes[i].opcode == OpCodes.Ldsfld)
i++;
if (codes[i].opcode == OpCodes.Ldc_I4_2)
codes[i].opcode = OpCodes.Ldc_I4_4;
n++;
}
if (codes[i].opcode == OpCodes.Ldsfld && (codes[i].operand as FieldInfo).Name == "mms_max_players" &&
i > 0 && codes[i - 1].opcode == OpCodes.Br) // take !online branch
{
while (codes[i].opcode == OpCodes.Add || codes[i].opcode == OpCodes.Ldsfld)
i++;
if (codes[i].opcode == OpCodes.Ldc_I4_1 && codes[i + 1].opcode == OpCodes.Ldc_I4_8)
{
codes[i + 1].opcode = OpCodes.Ldc_I4;
codes[i + 1].operand = 16;
}
n++;
}
}
Debug.Log("Patched MpMatchSetup n=" + n);
return codes;
}
}

public static bool HasInternetMatch()
{
return GameVersion.CompareTo(new Version(1, 0, 1885)) >= 0;
}

// add modified indicator to main menu
[HarmonyPatch(typeof(Overload.UIElement), "DrawMainMenu")]
[HarmonyPatch(typeof(UIElement), "DrawMainMenu")]
class VersionPatch
{
static string GetVersion(string stockVersion)
Expand All @@ -152,16 +110,19 @@ static string GetVersion(string stockVersion)

static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> codes)
{
var _string_Format_Method = AccessTools.Method(typeof(String), "Format", new Type[] { typeof(string), typeof(object), typeof(object), typeof(object) });
var _versionPatch_GetVersion_Method = AccessTools.Method(typeof(VersionPatch), "GetVersion");

int state = 0;

foreach (var code in codes)
{
// this.DrawStringSmall(string.Format(Loc.LS("VERSION {0}.{1} BUILD {2}"), GameManager.Version.Major, GameManager.Version.Minor, GameManager.Version.Build), position, 0.5f, StringOffset.RIGHT, UIManager.m_col_ui1, 0.5f, -1f);
if (state == 0 && code.opcode == OpCodes.Call && code.operand == AccessTools.Method(typeof(System.String), "Format", new Type[] { typeof(string), typeof(object), typeof(object), typeof(object) }))
if (state == 0 && code.opcode == OpCodes.Call && code.operand == _string_Format_Method)
{
state = 1;
yield return code;
yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(VersionPatch), "GetVersion"));
yield return new CodeInstruction(OpCodes.Call, _versionPatch_GetVersion_Method);
continue;
}

Expand All @@ -180,7 +141,7 @@ static void Postfix(UIElement __instance)
}

// add monsterball mb_arena1 level to multiplayer levels
[HarmonyPatch(typeof(Overload.GameManager), "ScanForLevels")]
[HarmonyPatch(typeof(GameManager), "ScanForLevels")]
class MBLevelPatch
{
public static bool SLInit = false;
Expand Down Expand Up @@ -237,14 +198,16 @@ static float MaybeMin(float a, float b)

static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
var mpRemove10FPSFloor_MaybeMin_Method = AccessTools.Method(typeof(MPRemove10FPSFloor), "MaybeMin");

var found = false;
foreach (var code in instructions)
{
if (!found)
{
if (code.opcode == OpCodes.Call && ((MethodInfo)code.operand).Name == "Min")
{
code.operand = AccessTools.Method(typeof(MPRemove10FPSFloor), "MaybeMin");
code.operand = mpRemove10FPSFloor_MaybeMin_Method;
found = true;
}
}
Expand Down Expand Up @@ -275,9 +238,10 @@ static bool Prefix()
[HarmonyPatch(typeof(Player), "RestorePlayerShipDataAfterRespawn")]
class CycloneFlakTBAfterDeathFix
{
private static FieldInfo _PlayerShip_flak_fire_count_Field = typeof(PlayerShip).GetField("flak_fire_count", BindingFlags.NonPublic | BindingFlags.Instance);
static void Prefix(Player __instance)
{
__instance.c_player_ship.GetType().GetField("flak_fire_count", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(__instance.c_player_ship, 0);
_PlayerShip_flak_fire_count_Field.SetValue(__instance.c_player_ship, 0);
__instance.c_player_ship.m_thunder_power = 0;
}
}
Expand Down
Loading

0 comments on commit 1fd7e8b

Please sign in to comment.