Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of NoInstantRespawn v1.4.0
NoInstantRespawn.dll
Decompiled 5 days agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("NoInstantRespawn")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.4.0.0")] [assembly: AssemblyInformationalVersion("1.4.0+4088dbb4e4a1a091c5c6fd30cdcd6fa567275d45")] [assembly: AssemblyProduct("NoInstantRespawn")] [assembly: AssemblyTitle("NoInstantRespawn")] [assembly: AssemblyVersion("1.4.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace NoInstantRespawn { public static class SceneSweeper { private static string _lastSceneName; public static void Sweep() { //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Unknown result type (might be due to invalid IL or missing references) NoInstantRespawnPlugin instance = NoInstantRespawnPlugin.Instance; if ((Object)(object)instance == (Object)null) { return; } float value = NoInstantRespawnPlugin.RespawnTimeout.Value; if (value <= 0f) { return; } GameManager instance2 = GameManager.instance; if ((Object)(object)instance2 == (Object)null || !instance2.IsGameplayScene()) { return; } string sceneName = instance2.sceneName; if (string.IsNullOrEmpty(sceneName)) { return; } if (sceneName != _lastSceneName) { _lastSceneName = sceneName; SpawnKeyBook.Reset(); } double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble; int num = 0; HealthManager[] array = Object.FindObjectsByType<HealthManager>((FindObjectsInactive)1, (FindObjectsSortMode)0); NoInstantRespawnPlugin.Log.LogDebug((object)$"[diag] sweep '{sceneName}': {array.Length} HealthManager(s) found, ledger={DeathLedger.DebugCount}"); bool flag = DeathLedger.DebugCount > 0; if (flag) { NoInstantRespawnPlugin.Log.LogDebug((object)("[diag] ledger: " + DeathLedger.DebugDump(realtimeSinceStartupAsDouble))); } HealthManager[] array2 = array; foreach (HealthManager val in array2) { if ((Object)(object)val == (Object)null) { continue; } SpawnKeyBook.Capture(val); GameObject gameObject = ((Component)val).gameObject; if (!gameObject.activeSelf) { continue; } Scene scene = gameObject.scene; if (((Scene)(ref scene)).IsValid()) { scene = gameObject.scene; if (((Scene)(ref scene)).name != sceneName) { continue; } } string text = RespawnKey.For(val); if (text != null) { if (flag) { NoInstantRespawnPlugin.Log.LogDebug((object)("[diag] live key '" + text + "' (" + ((Object)gameObject).name + ")")); } if (DeathLedger.TryGetMatch(text, realtimeSinceStartupAsDouble, value, out var killedAt, out var matchedKey)) { gameObject.SetActive(false); num++; NoInstantRespawnPlugin.Log.LogDebug((object)($"[suppressed, {realtimeSinceStartupAsDouble - killedAt:F1}s old] {text}" + ((matchedKey != text) ? (" [fuzzy ≈ " + matchedKey + "]") : ""))); } } } DeathLedger.Cleanup(realtimeSinceStartupAsDouble, Mathf.Max(value * 4f, 300f)); if (num > 0) { NoInstantRespawnPlugin.Log.LogInfo((object)$"NoInstantRespawn: kept {num} killed enemy(ies) out of room '{sceneName}'"); } } } public static class RespawnKey { public static string For(HealthManager hm) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) try { GameObject gameObject = ((Component)hm).gameObject; Scene scene = gameObject.scene; string value = (((Scene)(ref scene)).IsValid() ? ((Scene)(ref scene)).name : string.Empty); if (string.IsNullOrEmpty(value)) { return null; } Stack<string> stack = new Stack<string>(); Transform val = gameObject.transform; int num = 0; while ((Object)(object)val != (Object)null && num < 10) { stack.Push(NormName(((Object)val).name)); val = val.parent; num++; } Vector3 position = gameObject.transform.position; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(value); while (stack.Count > 0) { stringBuilder.Append('/'); stringBuilder.Append(stack.Pop()); } stringBuilder.Append('@').Append(position.x.ToString("F1", CultureInfo.InvariantCulture)).Append(',') .Append(position.y.ToString("F1", CultureInfo.InvariantCulture)) .Append(',') .Append(position.z.ToString("F1", CultureInfo.InvariantCulture)); return stringBuilder.ToString(); } catch (Exception ex) { NoInstantRespawnPlugin.Log.LogWarning((object)("RespawnKey failed: " + ex.Message)); return null; } } private static string NormName(string name) { if (name != null && name.Length > 3 && name[name.Length - 1] == ')') { int num = name.LastIndexOf(" (", StringComparison.Ordinal); if (num > 0) { bool flag = true; for (int i = num + 2; i < name.Length - 1; i++) { if (!char.IsDigit(name[i])) { flag = false; break; } } if (flag) { return name.Substring(0, num); } } } return name; } } public static class SpawnKeyBook { private static readonly Dictionary<int, string> LoadKeys = new Dictionary<int, string>(); public static void Capture(HealthManager hm) { try { string text = RespawnKey.For(hm); if (text != null) { LoadKeys[((Object)hm).GetInstanceID()] = text; } } catch (Exception ex) { NoInstantRespawnPlugin.Log.LogWarning((object)("SpawnKeyBook.Capture failed: " + ex.Message)); } } public static bool TryConsume(int instanceId, out string key) { if (LoadKeys.TryGetValue(instanceId, out key)) { LoadKeys.Remove(instanceId); return true; } return false; } public static void Reset() { LoadKeys.Clear(); } } public static class DeathLedger { private static readonly Dictionary<string, double> Kills = new Dictionary<string, double>(); private const float PosTolerance = 2f; public static int DebugCount => Kills.Count; public static void Record(string key, double time) { Kills[key] = time; } public static bool TryGet(string key, out double time) { return Kills.TryGetValue(key, out time); } public static string DebugDump(double now) { if (Kills.Count == 0) { return "(empty)"; } List<string> list = new List<string>(Kills.Count); foreach (KeyValuePair<string, double> kill in Kills) { list.Add($"{kill.Key} ({now - kill.Value:F0}s ago)"); } return string.Join(" | ", list); } public static bool TryGetMatch(string key, double now, float timeout, out double killedAt, out string matchedKey) { matchedKey = key; if (Kills.TryGetValue(key, out killedAt)) { return now - killedAt < (double)timeout; } if (!SplitKey(key, out var prefix, out var x, out var y, out var z)) { return false; } float num = float.MaxValue; string text = null; double num2 = 0.0; foreach (KeyValuePair<string, double> kill in Kills) { if (kill.Key.StartsWith(prefix, StringComparison.Ordinal) && SplitKey(kill.Key, out var _, out var x2, out var y2, out var z2)) { float num3 = (x - x2) * (x - x2) + (y - y2) * (y - y2) + (z - z2) * (z - z2); if (num3 < num) { num = num3; text = kill.Key; num2 = kill.Value; } } } if (text == null || num > 4f) { return false; } matchedKey = text; killedAt = num2; return now - num2 < (double)timeout; } private static bool SplitKey(string key, out string prefix, out float x, out float y, out float z) { prefix = null; x = (y = (z = 0f)); if (string.IsNullOrEmpty(key)) { return false; } int num = key.LastIndexOf('@'); if (num <= 0) { return false; } string[] array = key.Substring(num + 1).Split(','); if (array.Length < 3) { return false; } if (!TryParseFloat(array[0], out x)) { return false; } if (!TryParseFloat(array[1], out y)) { return false; } if (!TryParseFloat(array[2], out z)) { return false; } prefix = key.Substring(0, num + 1); return true; } private static bool TryParseFloat(string s, out float v) { if (float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out v)) { return true; } return float.TryParse(s, out v); } public static void Cleanup(double now, double timeout) { if (Kills.Count == 0) { return; } List<string> list = null; foreach (KeyValuePair<string, double> kill in Kills) { if (now - kill.Value > timeout) { (list ?? (list = new List<string>())).Add(kill.Key); } } if (list == null) { return; } foreach (string item in list) { Kills.Remove(item); } } public static void Clear() { Kills.Clear(); } } [BepInPlugin("local.silksong.NoInstantRespawn", "No Instant Respawn", "1.4.0")] [HarmonyPatch] public class NoInstantRespawnPlugin : BaseUnityPlugin { public const string PLUGIN_GUID = "local.silksong.NoInstantRespawn"; public const string PLUGIN_NAME = "No Instant Respawn"; public const string PLUGIN_VERSION = "1.4.0"; public static NoInstantRespawnPlugin Instance; public static ManualLogSource Log; public static ConfigEntry<bool> ModEnabled; public static ConfigEntry<float> RespawnTimeout; private bool _pendingSweep; private bool _sweeping; public void Awake() { //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Expected O, but got Unknown //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Expected O, but got Unknown Instance = this; Log = ((BaseUnityPlugin)this).Logger; ModEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Master toggle for the mod."); RespawnTimeout = ((BaseUnityPlugin)this).Config.Bind<float>("General", "RespawnTimeoutSeconds", 60f, new ConfigDescription("Enemies killed less than this many seconds ago will not come back in a room, even if you leave and re-enter. 60 = stock respawns return after one minute of real time. Use a huge value (e.g. 604800) to disable respawning entirely.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 604800f), Array.Empty<object>())); Harmony val = new Harmony("local.silksong.NoInstantRespawn"); try { val.PatchAll(typeof(NoInstantRespawnPlugin).Assembly); } catch (Exception ex) { Log.LogError((object)"NoInstantRespawn: patching FAILED — the game has likely been updated and this mod needs a fix. The game itself is unaffected; enemies will respawn normally."); Log.LogError((object)ex.ToString()); return; } LogPatchState(val); Log.LogInfo((object)"NoInstantRespawn loaded."); } private static void LogPatchState(Harmony harmony) { (string, Type, string, Type[])[] array = new(string, Type, string, Type[])[3] { ("HealthManager.Die", typeof(HealthManager), "Die", new Type[8] { typeof(float?), typeof(AttackTypes), typeof(NailElements), typeof(GameObject), typeof(bool), typeof(float), typeof(bool), typeof(bool) }), ("GameManager.BeginScene", typeof(GameManager), "BeginScene", Type.EmptyTypes), ("HeroController.Awake", typeof(HeroController), "Awake", Type.EmptyTypes) }; for (int i = 0; i < array.Length; i++) { var (text, type, text2, array2) = array[i]; try { MethodInfo methodInfo = AccessTools.Method(type, text2, array2, (Type[])null); if (methodInfo == null) { Log.LogWarning((object)("[diag] " + text + ": method NOT FOUND")); continue; } Patches info = Harmony.GetPatchInfo((MethodBase)methodInfo); Log.LogInfo((object)("[diag] " + text + ": prefixes=[" + owners("pre") + "] postfixes=[" + owners("post") + "] transpilers=[" + owners("tr") + "]")); string owners(string tag) { object result; if (info != null) { IEnumerable<Patch> source; if (!(tag == "pre")) { if (!(tag == "post")) { IEnumerable<Patch> transpilers = info.Transpilers; source = transpilers; } else { IEnumerable<Patch> transpilers = info.Postfixes; source = transpilers; } } else { IEnumerable<Patch> transpilers = info.Prefixes; source = transpilers; } result = string.Join(",", source.Select((Patch p) => p.owner + "(" + p.PatchMethod.Name + ")").ToArray()); } else { result = "-"; } return (string)result; } } catch (Exception ex) { Log.LogWarning((object)("[diag] " + text + ": " + ex.Message)); } } } [HarmonyPatch(typeof(HealthManager), "Die", new Type[] { typeof(float?), typeof(AttackTypes), typeof(NailElements), typeof(GameObject), typeof(bool), typeof(float), typeof(bool), typeof(bool) })] [HarmonyPostfix] public static void HealthManager_Die_Postfix(HealthManager __instance, bool __runOriginal) { Log.LogDebug((object)string.Format("[diag] Die postfix entered: '{0}' runOriginal={1} isDead={2}", ((Object)(object)__instance != (Object)null) ? ((Object)((Component)__instance).gameObject).name : "<null>", __runOriginal, (Object)(object)__instance != (Object)null && __instance.isDead)); if (__runOriginal && ModEnabled != null && ModEnabled.Value && !((Object)(object)__instance == (Object)null) && __instance.isDead) { if (!SpawnKeyBook.TryConsume(((Object)__instance).GetInstanceID(), out var key)) { Log.LogDebug((object)("[die skipped, dynamic spawn] " + ((Object)((Component)__instance).gameObject).name)); return; } double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble; DeathLedger.Record(key, realtimeSinceStartupAsDouble); Log.LogDebug((object)("[die recorded] " + key)); } } [HarmonyPatch(typeof(HeroController), "Awake")] [HarmonyPostfix] public static void HeroController_Awake_Postfix(HeroController __instance) { __instance.OnDeath += HeroDied; } private static void HeroDied() { if (ModEnabled != null && ModEnabled.Value) { DeathLedger.Clear(); SpawnKeyBook.Reset(); Log.LogInfo((object)"NoInstantRespawn: hero died — cleared recent-death ledger (clean runback)."); } } [HarmonyPatch(typeof(GameManager), "BeginScene")] [HarmonyPostfix] public static void GameManager_BeginScene_Postfix() { GameManager instance = GameManager.instance; Log.LogDebug((object)("[diag] BeginScene fired, scene='" + instance?.sceneName + "'")); Instance?.BeginScene(); } public void BeginScene() { _pendingSweep = true; } public void Update() { if (_pendingSweep) { _pendingSweep = false; SceneSweeper.Sweep(); _sweeping = true; } else if (_sweeping) { _sweeping = false; SceneSweeper.Sweep(); } } } }