Decompiled source of NightsOfTerror v0.1.4

plugins/NightsOfTerror.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using SuperFantasyKingdom;
using SuperFantasyKingdom.Spawner;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("NightsOfTerror")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.4.0")]
[assembly: AssemblyInformationalVersion("0.1.4+b695cf71aa5f0a9bc4e662dcc5637631115229f2")]
[assembly: AssemblyProduct("NightsOfTerror")]
[assembly: AssemblyTitle("NightsOfTerror")]
[assembly: AssemblyVersion("0.1.4.0")]
namespace NightsOfTerror;

internal sealed class DuskPool
{
	private readonly List<(Monster Prefab, int Difficulty)> enemies = new List<(Monster, int)>();

	internal int Count => enemies.Count;

	internal DuskPool(Wave[] waves, int currentDifficulty)
	{
		if (waves == null)
		{
			return;
		}
		int num = Math.Min(currentDifficulty, waves.Length);
		for (int i = 0; i < num; i++)
		{
			Monster val = waves[i]?.monster;
			if ((Object)(object)val != (Object)null && !((MonsterBase)val).IsBoss() && !((MonsterBase)val).IsMiniBoss())
			{
				enemies.Add((val, i + 1));
			}
		}
	}

	internal (Monster Prefab, int Difficulty) Pick(double roll)
	{
		int num = enemies.Count - 1;
		while (num > 0 && roll < 0.5)
		{
			num--;
			roll *= 2.0;
		}
		return enemies[num];
	}
}
internal static class NightGates
{
	[HarmonyPatch(typeof(DaytimeManager), "SwitchState")]
	private static class PhaseAdvance
	{
		private static void Prefix(DaytimeManager __instance)
		{
			Plugin.Active?.EveningExpired(__instance);
		}

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			return GateClearance(instructions, CountBeforeNight);
		}
	}

	[HarmonyPatch(typeof(DaytimeManager), "Update")]
	private static class TavernPrompt
	{
		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			return GateClearance(instructions, CountBeforeTavern);
		}
	}

	[HarmonyPatch(typeof(GameManager), "ChangeState")]
	private static class Survival
	{
		private static bool Prefix(GameState __0)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			if ((int)__0 == 4)
			{
				Plugin active = Plugin.Active;
				if (active != null && active.Owns(DaytimeManager.Instance))
				{
					if (CombatManager.Instance.IsCombatOver())
					{
						return Plugin.Active.BeginSettlement();
					}
					return false;
				}
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(GameManager), "EndDay")]
	private static class TavernEntry
	{
		private static bool Prefix()
		{
			Plugin active = Plugin.Active;
			if (active != null && active.Owns(DaytimeManager.Instance))
			{
				if (!Plugin.Active.Settled)
				{
					return CombatManager.Instance.IsCombatOver();
				}
				return false;
			}
			return true;
		}
	}

	private static IEnumerable<CodeInstruction> GateClearance(IEnumerable<CodeInstruction> instructions, Func<int, int> gate)
	{
		//IL_0068: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		List<CodeInstruction> list = instructions.ToList();
		MethodInfo count = typeof(CombatManager).GetMethod("CurrentMonstersAmount");
		List<CodeInstruction> list2 = list.FindAll((CodeInstruction i) => CodeInstructionExtensions.Calls(i, count));
		if (list2.Count != 1)
		{
			throw new InvalidOperationException("Expected one native night-clearance check.");
		}
		list.Insert(list.IndexOf(list2[0]) + 1, new CodeInstruction(OpCodes.Call, (object)gate.Method));
		return list;
	}

	private static int CountBeforeTavern(int actual)
	{
		return Plugin.Active?.ForClearance(actual) ?? actual;
	}

	private static int CountBeforeNight(int actual)
	{
		if (actual == 0)
		{
			Plugin active = Plugin.Active;
			if (active != null && active.Owns(DaytimeManager.Instance) && !CombatManager.Instance.IsCombatOver())
			{
				return 1;
			}
		}
		return actual;
	}
}
[BepInPlugin("gkj.nightsofterror", "Nights of Terror", "0.1.4")]
public sealed class Plugin : BaseUnityPlugin
{
	internal static Plugin Active;

	private Harmony patches;

	private ConfigEntry<bool> rushed;

	private DaytimeManager clock;

	private DuskPool pool;

	private FieldRef<MonsterSpawner, int> ordinaryQuota;

	private int night;

	private Reinforcement group;

	private Action<MonsterSpawner, Monster, int, Vector3> spawn;

	internal bool Settled { get; private set; }

	private void Awake()
	{
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Expected O, but got Unknown
		rushed = ((BaseUnityPlugin)this).Config.Bind<bool>("Reinforcements", "RushedArrival", true, "Use the native Rush spacing for this group. When disabled, its members arrive one second apart.");
		patches = new Harmony("gkj.nightsofterror");
		try
		{
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(MonsterSpawner), "SpawnMonster", new Type[3]
			{
				typeof(Monster),
				typeof(int),
				typeof(Vector3)
			}, (Type[])null);
			spawn = AccessTools.MethodDelegate<Action<MonsterSpawner, Monster, int, Vector3>>(methodInfo, (object)null, true);
			ordinaryQuota = AccessTools.FieldRefAccess<MonsterSpawner, int>("m_MinMonstersToSpawn");
			patches.PatchAll(typeof(Plugin).Assembly);
		}
		catch (Exception ex)
		{
			patches.UnpatchSelf();
			((BaseUnityPlugin)this).Logger.LogError((object)("Could not install the native wave hooks. " + ex));
			return;
		}
		Active = this;
		GameManager.OnGameInit += ResetNight;
		GameManager.OnGameOver += ResetNight;
		DaytimeManager.BeforeMorningStart += Dawn;
		DaytimeManager.OnSunsetStart += Dusk;
	}

	private void OnDestroy()
	{
		Active = null;
		GameManager.OnGameInit -= ResetNight;
		GameManager.OnGameOver -= ResetNight;
		DaytimeManager.BeforeMorningStart -= Dawn;
		DaytimeManager.OnSunsetStart -= Dusk;
		Harmony obj = patches;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
	}

	private void Dawn(int day)
	{
		ResetNight();
	}

	private void ResetNight()
	{
		clock = null;
		pool = null;
		night = 0;
		Settled = false;
		group = null;
	}

	internal bool BeginSettlement()
	{
		if (Settled)
		{
			return false;
		}
		Settled = true;
		return true;
	}

	private void Dusk(int day)
	{
		MonsterSpawner instance = MonsterSpawner.Instance;
		if (!((Object)(object)instance == (Object)null))
		{
			int num = ordinaryQuota.Invoke(instance);
			if (Schedule(DaytimeManager.Instance, instance, day, num))
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)$"Night {day}: dusk quota {num}, remaining {instance.GetMonstersToSpawn()}, midnight group {group.Count}, eligible enemy tiers {pool.Count}.");
				AlertManager.Instance.DisplayMessage("Nights of Terror", $"{group.Count} more foes arrive at midnight.");
			}
		}
	}

	private bool Schedule(DaytimeManager today, MonsterSpawner spawner, int day, int quota)
	{
		if ((Object)(object)today == (Object)null || (Object)(object)spawner == (Object)null || Owns(today) || today.IsSpecialDay() || today.IsBossDay() || day >= today.GetDayLimit() || GameManager.Instance.IsGameOver())
		{
			return false;
		}
		int num = Reinforcement.SizeFromQuota(quota);
		if (num == 0)
		{
			return false;
		}
		DuskPool duskPool = new DuskPool(spawner.waves, spawner.GetCurrentDifficulty());
		if (duskPool.Count == 0)
		{
			return false;
		}
		clock = today;
		night = day;
		group = new Reinforcement(num);
		pool = duskPool;
		return true;
	}

	internal bool Owns(DaytimeManager today)
	{
		if (group != null && today == clock)
		{
			return night == today.CurrentDay();
		}
		return false;
	}

	internal int ForClearance(int living)
	{
		if (!Owns(DaytimeManager.Instance))
		{
			return living;
		}
		return group.ForClearance(living);
	}

	internal void EveningExpired(DaytimeManager today)
	{
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		if (Owns(today) && today.IsEvening() && group.IsDue(Time.time))
		{
			MonsterSpawner instance = MonsterSpawner.Instance;
			Vector2 val = CombatManager.Instance.GetCombatZone() + Vector2.one * 0.1f;
			Vector3 arg = default(Vector3);
			((Vector3)(ref arg))..ctor(Random.Range(0f - val.x, val.x), val.y, 0f);
			bool flag = group.Remaining == group.Count;
			try
			{
				(Monster, int) tuple = pool.Pick(Random.value);
				spawn(instance, tuple.Item1, tuple.Item2, arg);
				group.Arrived(Time.time, rushed.Value);
			}
			catch (Exception ex)
			{
				group.Cancel();
				((BaseUnityPlugin)this).Logger.LogError((object)("Reinforcement interrupted. Native combat will settle surviving enemies. " + ex));
				return;
			}
			if (flag)
			{
				AlertManager.Instance.DisplayMessage("Midnight", "Reinforcements have arrived!");
			}
		}
	}
}
internal sealed class Reinforcement
{
	private float nextArrival;

	internal int Count { get; }

	internal int Remaining { get; private set; }

	internal Reinforcement(int count)
	{
		Count = (Remaining = count);
	}

	internal static int SizeFromQuota(int quota)
	{
		if (quota > 0)
		{
			return quota / 2 + quota % 2;
		}
		return 0;
	}

	internal bool IsDue(float scaledTime)
	{
		if (Remaining > 0)
		{
			return scaledTime >= nextArrival;
		}
		return false;
	}

	internal void Arrived(float scaledTime, bool rushed)
	{
		Remaining--;
		nextArrival = scaledTime + (rushed ? 0.075f : 1f);
	}

	internal int ForClearance(int living)
	{
		if (Remaining <= 0 || living != 0)
		{
			return living;
		}
		return 1;
	}

	internal void Cancel()
	{
		Remaining = 0;
	}
}