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 OptionalFixesAndAddons v1.0.4
OptionalFixesAndAddons.dll
Decompiled 2 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using DunGen; using DunGen.Tags; using GameNetcodeStuff; using GeneralModFixes.Fixes; using GeneralModFixes.Fixes.Jailbird; using HarmonyLib; using Microsoft.CodeAnalysis; using TMPro; using Unity.Collections; using Unity.Netcode; using UnityEngine; using UnityEngine.AI; using UnityEngine.Experimental.Rendering; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Utilities; using UnityEngine.Networking; using UnityEngine.SceneManagement; using UnityEngine.UI; [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("slivkonsin")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.4.0")] [assembly: AssemblyInformationalVersion("1.0.4")] [assembly: AssemblyProduct("OptionalFixesAndAddons")] [assembly: AssemblyTitle("OptionalFixesAndAddons")] [assembly: AssemblyVersion("1.0.4.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 GeneralModFixes { [BepInPlugin("0.slivkonsin.OptionalFixesAndAddons.Early", "Optional Fixes & Addons (early)", "1.0.4")] public sealed class EarlyPlugin : BaseUnityPlugin { public const string Guid = "0.slivkonsin.OptionalFixesAndAddons.Early"; internal static readonly List<string> Reports = new List<string>(); internal static readonly string ModelSettingsDescription = "Some playermodel mods (like the Rain World ones) use settings they never create, which throws an error for every model at startup.\nThis creates those settings with their normal values first.\nOnly active for playermodel mods that actually have this problem, otherwise it does nothing."; private static ConfigEntry<bool> _modelConfigs; private static ConfigEntry<bool> _twoStory; private static ConfigEntry<bool> _vlc; internal static bool TwoStoryPlaceholderSet; internal static bool VlcDebugTurnedOff; private static Harmony _harmony; private static Assembly _vlcAssembly; private static int _modelConfigsFixed; private static readonly HashSet<Assembly> Seen = new HashSet<Assembly>(); private static readonly (string Name, Type Type, object Default, string Description)[] ModelSettings = new(string, Type, object, string)[3] { ("enableModelForAllSuits", typeof(bool), false, "Use this model for every suit."), ("enableModelAsDefault", typeof(bool), false, "Use this model as the default one."), ("suitNamesToEnableModel", typeof(string), "", "Suits to use this model on, separated by commas.") }; private void Awake() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Expected O, but got Unknown ConfigFile val = new ConfigFile(Path.Combine(Paths.ConfigPath, "slivkonsin.OptionalFixesAndAddons.cfg"), true); ConfigEntry<bool> val2 = val.Bind<bool>("1. General", "Enabled", true, "Turns every fix on or off at once. Each fix also has its own switch below."); _modelConfigs = val.Bind<bool>("2. Mod fixes", "MissingModelSettings", true, ModelSettingsDescription); _twoStory = val.Bind<bool>("2. Mod fixes", "ShipWindowsWaitFor2StoryShip", true, new ShipWindowsTwoStory().FullDescription); _vlc = val.Bind<bool>("2. Mod fixes", "VeryLateCompanyFixes", true, new VeryLateCompanyFixes().FullDescription); if (!val2.Value || (!_modelConfigs.Value && !_twoStory.Value && !_vlc.Value)) { Reports.Add("Early fixes: turned off in the config"); return; } _harmony = new Harmony("0.slivkonsin.OptionalFixesAndAddons.Early"); AppDomain.CurrentDomain.AssemblyLoad += delegate(object _, AssemblyLoadEventArgs e) { Check(e.LoadedAssembly); }; Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int num = 0; num < assemblies.Length; num++) { Check(assemblies[num]); } Reports.Add(_modelConfigs.Value ? "Missing playermodel settings: on (watching mods as they load)" : "Missing playermodel settings: turned off in the config"); } private static void Check(Assembly a) { //IL_01b8: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Expected O, but got Unknown try { if (a == null || a.IsDynamic || !Seen.Add(a)) { return; } string name = a.GetName().Name; if (name.StartsWith("System") || name.StartsWith("Unity") || name.StartsWith("Mono") || name == "mscorlib" || name == "Assembly-CSharp") { return; } if (_twoStory.Value) { TwoStoryPlaceholder(a); } if (_vlc.Value && name == "VeryLateCompany") { HookVlcStartup(a); } if (!_modelConfigs.Value) { return; } foreach (Type item in Util.SafeTypes(a)) { if (!typeof(BaseUnityPlugin).IsAssignableFrom(item)) { continue; } object? obj = item.GetCustomAttributes(typeof(BepInPlugin), inherit: false).FirstOrDefault(); BepInPlugin val = (BepInPlugin)((obj is BepInPlugin) ? obj : null); if (val == null) { continue; } ConfigFile val2 = null; (string, Type, object, string)[] modelSettings = ModelSettings; for (int i = 0; i < modelSettings.Length; i++) { (string, Type, object, string) tuple = modelSettings[i]; PropertyInfo property = item.GetProperty(tuple.Item1, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); Type type = typeof(ConfigEntry<>).MakeGenericType(tuple.Item2); if (property == null || property.PropertyType != type || property.GetValue(null) != null) { continue; } MethodInfo setMethod = property.GetSetMethod(nonPublic: true); if (!(setMethod == null)) { if (val2 == null) { val2 = new ConfigFile(Path.Combine(Paths.ConfigPath, val.GUID + ".cfg"), true); } object obj2 = typeof(ConfigFile).GetMethods().First((MethodInfo m) => m.Name == "Bind" && m.IsGenericMethod && m.GetParameters().Length == 4 && m.GetParameters()[0].ParameterType == typeof(string) && m.GetParameters()[3].ParameterType == typeof(string)).MakeGenericMethod(tuple.Item2) .Invoke(val2, new object[4] { "General", tuple.Item1, tuple.Item3, tuple.Item4 }); setMethod.Invoke(null, new object[1] { obj2 }); _modelConfigsFixed++; } } if (val2 != null) { Reports.Add("Missing playermodel settings: created for " + val.Name + " (" + val.GUID + ")"); } } } catch { } } private static void HookVlcStartup(Assembly a) { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Expected O, but got Unknown try { foreach (Type item in Util.SafeTypes(a)) { if (typeof(BaseUnityPlugin).IsAssignableFrom(item)) { MethodInfo method = item.GetMethod("Awake", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (!(method == null)) { _vlcAssembly = a; _harmony.Patch((MethodBase)method, (HarmonyMethod)null, new HarmonyMethod(typeof(EarlyPlugin), "DebugOff", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); break; } } } } catch { } } private static void DebugOff() { if (Harmony.DEBUG) { Harmony.DEBUG = false; VlcDebugTurnedOff = true; } if (VeryLateCompanyFixes.ClearDebugTags(_vlcAssembly) > 0) { VlcDebugTurnedOff = true; } } private static void TwoStoryPlaceholder(Assembly a) { try { if (TwoStoryPlaceholderSet) { return; } foreach (Type item in Util.SafeTypes(a)) { if (item.Name != "HarmonyPatches" || item.Namespace != "MelMel2SS") { continue; } FieldInfo field = item.GetField("matRef", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (!(field == null) && !(field.FieldType != typeof(Material[]))) { if (field.GetValue(null) == null) { field.SetValue(null, new Material[16]); } TwoStoryPlaceholderSet = true; } break; } } catch { } } } [BepInPlugin("slivkonsin.OptionalFixesAndAddons", "Optional Fixes & Addons", "1.0.4")] [BepInDependency(/*Could not decode attribute arguments.*/)] public sealed class Plugin : BaseUnityPlugin { public const string Guid = "slivkonsin.OptionalFixesAndAddons"; public const string Name = "Optional Fixes & Addons"; public const string Version = "1.0.4"; internal static Plugin Instance; internal static ManualLogSource Log; internal static ConfigFile Cfg; internal static Harmony Harmony; internal static ConfigEntry<bool> Enabled; internal static ConfigEntry<bool> DebugLog; internal static readonly List<Fix> Fixes = new List<Fix>(); private static bool _installed; private void Awake() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown //IL_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Expected O, but got Unknown //IL_01b0: Unknown result type (might be due to invalid IL or missing references) Instance = this; Log = ((BaseUnityPlugin)this).Logger; Cfg = ((BaseUnityPlugin)this).Config; Harmony = new Harmony("slivkonsin.OptionalFixesAndAddons"); Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("1. General", "Enabled", true, "Turns every fix on or off at once. Each fix also has its own switch below."); DebugLog = ((BaseUnityPlugin)this).Config.Bind<bool>("1. General", "DebugLog", false, "Writes extra info to the log. Only useful for testing."); ((BaseUnityPlugin)this).Config.Bind<bool>("2. Mod fixes", "MissingModelSettings", true, EarlyPlugin.ModelSettingsDescription); Fixes.Add(new Scp3199Tag()); Fixes.Add(new StarshipStaleSound()); Fixes.Add(new SpongeSpreadOut()); Fixes.Add(new MoreSuitsEarlyLoad()); Fixes.Add(new SpectateEnemiesFixes()); Fixes.Add(new ShipWindowsTwoStory()); Fixes.Add(new ShipWindowsShutterGuard()); Fixes.Add(new ModDataLibNullPlugin()); Fixes.Add(new WesleyInteriorRules()); Fixes.Add(new SoundApiReporting()); Fixes.Add(new DawnLibParentingNoise()); Fixes.Add(new VeryLateCompanyFixes()); Fixes.Add(new LateJoinDropship()); Fixes.Add(new JailbirdRework()); Fixes.Add(new StartupErrorIsolation()); foreach (Fix fix in Fixes) { fix.Bind(((BaseUnityPlugin)this).Config); } GameObject val = new GameObject("OptionalFixesAndAddons"); Object.DontDestroyOnLoad((Object)val); ((Object)val).hideFlags = (HideFlags)61; val.AddComponent<Runner>(); SceneManager.sceneLoaded += OnSceneLoaded; Log.LogInfo((object)"Optional Fixes & Addons 1.0.4 loaded."); } private static void OnSceneLoaded(Scene s, LoadSceneMode m) { foreach (Fix fix in Fixes) { try { fix.OnSceneLoaded(); } catch (Exception e) { fix.Failed(e); } } if (_installed) { return; } _installed = true; foreach (Fix fix2 in Fixes) { if (!Enabled.Value || !fix2.Enabled.Value) { fix2.Status = "turned off in the config"; continue; } try { fix2.Install(Harmony); } catch (Exception e2) { fix2.Failed(e2); } } StringBuilder stringBuilder = new StringBuilder("Fixes:"); foreach (string report in EarlyPlugin.Reports) { stringBuilder.Append("\n ").Append(report); } foreach (Fix fix3 in Fixes) { stringBuilder.Append("\n ").Append(fix3.Title).Append(": ") .Append(fix3.Status); } Log.LogInfo((object)stringBuilder.ToString()); } } internal sealed class Runner : MonoBehaviour { private void Update() { foreach (Fix fix in Plugin.Fixes) { if (fix.Active) { try { fix.Update(); } catch (Exception e) { fix.Failed(e); } } } } } internal abstract class Fix { public ConfigEntry<bool> Enabled; public string Status = "waiting"; public bool Active; public int Errors; public abstract string Key { get; } public abstract string Title { get; } public abstract string Description { get; } public virtual string Section => "2. Mod fixes"; public virtual string Requires => null; public string FullDescription => Compose(Description, Requires); public static string Compose(string description, string requires) { return description + "\n" + ((requires == null) ? "Works with any mods." : ("Only active if " + requires + (requires.Contains(" and ") ? " are" : " is") + " installed, otherwise it does nothing.")); } public virtual void Bind(ConfigFile c) { Enabled = c.Bind<bool>(Section, Key, true, FullDescription); } public abstract void Install(Harmony h); public virtual void Update() { } public virtual void OnSceneLoaded() { } protected void Skip(string why) { Status = "not needed (" + why + ")"; Active = false; } protected void On(string what) { Status = "on" + (string.IsNullOrEmpty(what) ? "" : (" (" + what + ")")); Active = true; } public void Failed(Exception e) { Errors++; DiagnosticsTelemetry.Errors++; if (Errors <= 3) { Plugin.Log.LogWarning((object)(Title + ": " + e.Message + (Plugin.DebugLog.Value ? ("\n" + e) : ""))); } if (Errors == 3) { Active = false; Status = "turned itself off after errors"; Plugin.Log.LogWarning((object)(Title + ": turned off after repeated errors.")); } } } public static class DiagnosticsTelemetry { public static int MissingTagsCaught; public static int StaleListenersRemoved; public static int SpongeItemsQueued; public static int SpongeQueueLength; public static float SpongeMsLastFrame; public static int SuitImagesPreloaded; public static int SuitImagesUsedEarly; public static int SuitImagesFallback; public static int ShipWindowsDelayed; public static bool TwoStoryWindowPartRemoved; public static bool ShipFloorRestored; public static int ShutterCallsSkipped; public static int StartupErrorsContained; public static int FailedPluginsSkipped; public static bool WesleyRulesActive; public static int LogLinesQuieted; public static int JailbirdProtections; public static int JailbirdAlerts; public static int LateJoinersResynced; public static int LateJoinsDuringTakeoff; public static int DroppedOffByDropship; public static int LateJoinsRefused; public static int Errors; } internal static class Util { public static IEnumerable<Type> SafeTypes(Assembly a) { try { return a.GetTypes(); } catch (ReflectionTypeLoadException ex) { return ex.Types.Where((Type t) => t != null); } catch { return Enumerable.Empty<Type>(); } } public static Assembly PluginAssembly(string guid) { if (!Chainloader.PluginInfos.TryGetValue(guid, out var value) || !((Object)(object)value.Instance != (Object)null)) { return null; } return ((object)value.Instance).GetType().Assembly; } public static List<Type> TypesNamed(string name, Assembly only = null) { List<Type> list = new List<Type>(); Assembly[] array = ((!(only != null)) ? AppDomain.CurrentDomain.GetAssemblies() : new Assembly[1] { only }); foreach (Assembly assembly in array) { if (assembly.IsDynamic) { continue; } string name2 = assembly.GetName().Name; if (only == null && (name2.StartsWith("System") || name2.StartsWith("Unity") || name2 == "mscorlib" || name2 == "Assembly-CSharp")) { continue; } foreach (Type item in SafeTypes(assembly)) { if (item.Name == name) { list.Add(item); } } } return list; } public static bool Calls(MethodBase method, Func<MethodInfo, bool> target) { try { foreach (KeyValuePair<OpCode, object> item in PatchProcessor.ReadMethodBody(method)) { if (item.Value is MethodInfo arg && target(arg)) { return true; } } } catch { } return false; } public static IEnumerable<MethodInfo> DeclaredMethods(Type t) { return from m in t.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) where !m.IsAbstract && !m.ContainsGenericParameters select m; } } } namespace GeneralModFixes.Fixes { internal sealed class DawnLibParentingNoise : Fix { private const string Guid = "com.github.teamxiaolan.dawnlib"; private const string Prefix = "Parenting of object: "; public override string Key => "DawnLibParentingErrors"; public override string Title => "DawnLib furniture parenting errors"; public override string Section => "4. Log spam"; public override string Requires => "DawnLib"; public override string Description => "DawnLib writes \"Parenting of object ... failed\" as an error for lots of furniture on every load. The furniture works fine.\nThis writes those as debug lines instead of errors."; public override void Install(Harmony h) { //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Expected O, but got Unknown if (!Chainloader.PluginInfos.ContainsKey("com.github.teamxiaolan.dawnlib")) { Skip("DawnLib not installed"); return; } MethodInfo methodInfo = AccessTools.Method(typeof(ManualLogSource), "Log", new Type[2] { typeof(LogLevel), typeof(object) }, (Type[])null); if (methodInfo == null) { Skip("BepInEx logging changed"); return; } h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(DawnLibParentingNoise), "Quieter", (Type[])null) { priority = 800 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); On(null); } private static void Quieter(ManualLogSource __instance, ref LogLevel level, object data) { if (((uint)level & 2u) != 0 && data is string text && text.StartsWith("Parenting of object: ", StringComparison.Ordinal) && !(__instance.SourceName != "DawnLib") && text.EndsWith(" failed.", StringComparison.Ordinal)) { level = (LogLevel)32; DiagnosticsTelemetry.LogLinesQuieted++; } } } internal sealed class JailbirdRework : Fix { private const string Guid = "com.github.elmish.LCJailbird"; internal static bool LocalSlowed; internal static bool LocalSlowLook; internal static bool Bypass; private static float _immuneUntil; private static float _resistUntil; private static float _weakResistUntil; private static bool _inDamage; private const float StaminaFactor = 4f; private const float StaminaFadeTime = 5f; private static float _staminaBefore; private static float _lastHeldAt = -999f; public override string Key => "JailbirdRework"; public override string Title => "Jailbird rework (LCJailbird)"; public override string Section => "5. Mod reworks"; public override string Requires => "LCJailbird"; public override string Description => "Recodes the Jailbird and strengthens its balancing for a better experience.\nEveryone in the lobby needs the same setting. Needs a game restart to turn on or off."; public override void Bind(ConfigFile c) { Enabled = c.Bind<bool>(Section, Key, true, base.FullDescription); } public override void Install(Harmony h) { //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_01fd: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Expected O, but got Unknown //IL_020a: Expected O, but got Unknown //IL_022a: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Expected O, but got Unknown //IL_0258: Unknown result type (might be due to invalid IL or missing references) //IL_025d: Unknown result type (might be due to invalid IL or missing references) //IL_0274: Unknown result type (might be due to invalid IL or missing references) //IL_0281: Expected O, but got Unknown //IL_0281: Expected O, but got Unknown //IL_02aa: Unknown result type (might be due to invalid IL or missing references) //IL_02b7: Expected O, but got Unknown //IL_02d7: Unknown result type (might be due to invalid IL or missing references) //IL_02dc: Unknown result type (might be due to invalid IL or missing references) //IL_02f7: Unknown result type (might be due to invalid IL or missing references) //IL_02fc: Unknown result type (might be due to invalid IL or missing references) //IL_030b: Expected O, but got Unknown //IL_030b: Expected O, but got Unknown //IL_032b: Unknown result type (might be due to invalid IL or missing references) //IL_0339: Expected O, but got Unknown //IL_03cc: Unknown result type (might be due to invalid IL or missing references) //IL_03da: Expected O, but got Unknown //IL_0403: Unknown result type (might be due to invalid IL or missing references) //IL_0410: Expected O, but got Unknown //IL_0388: Unknown result type (might be due to invalid IL or missing references) //IL_0396: Expected O, but got Unknown if (!Chainloader.PluginInfos.TryGetValue("com.github.elmish.LCJailbird", out var value) || (Object)(object)value.Instance == (Object)null) { Skip("LCJailbird not installed"); return; } Item val = null; FieldInfo[] fields = ((object)value.Instance).GetType().GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { if (fieldInfo.FieldType == typeof(Item)) { object? value2 = fieldInfo.GetValue(fieldInfo.IsStatic ? null : value.Instance); val = (Item)((value2 is Item) ? value2 : null); if ((Object)(object)val != (Object)null) { break; } } } if ((Object)(object)val == (Object)null || (Object)(object)val.spawnPrefab == (Object)null) { Skip("couldn't find LCJailbird's item"); return; } GameObject spawnPrefab = val.spawnPrefab; GrabbableObject old = ((IEnumerable<GrabbableObject>)spawnPrefab.GetComponents<GrabbableObject>()).FirstOrDefault((Func<GrabbableObject, bool>)((GrabbableObject g) => !(g is JailbirdItem))); if ((Object)(object)old == (Object)null) { Skip("LCJailbird's item script wasn't there"); return; } JailbirdItem jailbirdItem = spawnPrefab.AddComponent<JailbirdItem>(); ((GrabbableObject)jailbirdItem).itemProperties = val; ((GrabbableObject)jailbirdItem).grabbable = true; jailbirdItem.windupSFX = Get<AudioClip>("reelUpSFX"); jailbirdItem.chargeSwingSFX = Get<AudioClip>("swingSFX"); jailbirdItem.dashSFX = Get<AudioClip>("chargeSFX"); jailbirdItem.hitSFX = Get<AudioClip[]>("hitSFX")?.FirstOrDefault(); jailbirdItem.jbAudio = Get<AudioSource>("jailbirdAudio") ?? spawnPrefab.GetComponent<AudioSource>(); Object.DestroyImmediate((Object)(object)old, true); val.toolTips = new string[2] { "Attack : [LMB]", "Charge : [RMB] (hold)" }; Type typeFromHandle = typeof(PlayerControllerB); h.Patch((MethodBase)AccessTools.Method(typeFromHandle, "DamagePlayer", (Type[])null, (Type[])null), new HarmonyMethod(typeof(JailbirdRework), "DamagePrefix", (Type[])null), new HarmonyMethod(typeof(JailbirdRework), "DamagePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)AccessTools.Method(typeFromHandle, "KillPlayer", (Type[])null, (Type[])null), new HarmonyMethod(typeof(JailbirdRework), "KillPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)AccessTools.Method(typeFromHandle, "KillPlayer", (Type[])null, (Type[])null), new HarmonyMethod(typeof(JailbirdRework), "RememberRedJailbirds", (Type[])null) { priority = 0 }, new HarmonyMethod(typeof(JailbirdRework), "ExplodeRedJailbirdsOnDeath", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)AccessTools.Method(typeof(EnemyAI), "MeetsStandardPlayerCollisionConditions", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(JailbirdRework), "CollisionPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)AccessTools.Method(typeFromHandle, "Update", (Type[])null, (Type[])null), new HarmonyMethod(typeof(JailbirdRework), "StaminaBefore", (Type[])null) { priority = 800 }, new HarmonyMethod(typeof(JailbirdRework), "StaminaAfter", (Type[])null) { priority = 0 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)AccessTools.Method(typeFromHandle, "Jump_performed", (Type[])null, (Type[])null), new HarmonyMethod(typeof(JailbirdRework), "NoJump", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); string[] array = new string[2] { "CalculateNormalLookingInput", "CalculateSmoothLookingInput" }; foreach (string text in array) { MethodInfo methodInfo = AccessTools.Method(typeFromHandle, text, (Type[])null, (Type[])null); if (methodInfo != null) { h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(JailbirdRework), "SlowLook", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } h.Patch((MethodBase)AccessTools.Method(typeof(HUDManager), "PingScan_performed", (Type[])null, (Type[])null), new HarmonyMethod(typeof(JailbirdRework), "NoScan", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)AccessTools.Method(typeof(StartOfRound), "OnShipLandedMiscEvents", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(JailbirdRework), "Landed", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); On(null); T Get<T>(string name) where T : class { return ((object)old).GetType().GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(old) as T; } } public override void Update() { JailbirdNet.Update(); } internal static void GrantProtection() { _immuneUntil = Time.time + 1f; _resistUntil = Time.time + 3f; DiagnosticsTelemetry.JailbirdProtections++; } internal static void GrantResist(float seconds, float takenFactor) { if (takenFactor <= 0.5f) { _resistUntil = Mathf.Max(_resistUntil, Time.time + seconds); } else { _weakResistUntil = Mathf.Max(_weakResistUntil, Time.time + seconds); } } private static bool IsLocal(PlayerControllerB p) { if ((Object)(object)p != (Object)null) { return (Object)(object)p == (Object)(object)GameNetworkManager.Instance?.localPlayerController; } return false; } private static bool DamagePrefix(PlayerControllerB __instance, ref int damageNumber, bool fallDamage) { if (Bypass || fallDamage || !IsLocal(__instance)) { return true; } EnemyDanger.Hurt(damageNumber); _inDamage = true; if (Time.time < _immuneUntil) { return false; } if (Time.time < _resistUntil) { damageNumber = Mathf.CeilToInt((float)damageNumber * 0.5f); } else if (Time.time < _weakResistUntil) { damageNumber = Mathf.CeilToInt((float)damageNumber * 0.75f); } return true; } private static void DamagePostfix() { _inDamage = false; } private static bool KillPrefix(PlayerControllerB __instance, CauseOfDeath causeOfDeath) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Invalid comparison between Unknown and I4 //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Invalid comparison between Unknown and I4 if (!Bypass && !_inDamage && IsLocal(__instance)) { EnemyDanger.Hurt(100f); } if (Bypass || !IsLocal(__instance) || Time.time >= _immuneUntil) { return true; } if ((int)causeOfDeath != 2) { return (int)causeOfDeath == 10; } return true; } private static void CollisionPostfix(EnemyAI __instance, ref PlayerControllerB __result) { if (!((Object)(object)__result == (Object)null) && IsLocal(__result)) { if (Time.time < _immuneUntil) { __result = null; } else { EnemyDanger.Touched(__instance); } } } private static void RememberRedJailbirds(PlayerControllerB __instance, out List<JailbirdItem> __state) { __state = null; if (!IsLocal(__instance) || __instance.isPlayerDead || __instance.ItemSlots == null) { return; } foreach (GrabbableObject item in __instance.ItemSlots.Append(__instance.ItemOnlySlot)) { if (item is JailbirdItem { charges: <=1 } jailbirdItem) { (__state ?? (__state = new List<JailbirdItem>())).Add(jailbirdItem); } } } private static void ExplodeRedJailbirdsOnDeath(PlayerControllerB __instance, List<JailbirdItem> __state) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) if (__state == null || !__instance.isPlayerDead) { return; } foreach (JailbirdItem item in __state) { if (!((Object)(object)item == (Object)null)) { try { Vector3 position = ((Component)item).transform.position; JailbirdNet.Remove((GrabbableObject)(object)item); JailbirdNet.Explode(position, ring: false); Plugin.Log.LogInfo((object)"Jailbird: last charge went off as its holder died."); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Jailbird death explosion: " + ex.Message)); } } } } private static void StaminaBefore(PlayerControllerB __instance) { if (IsLocal(__instance)) { _staminaBefore = __instance.sprintMeter; } } private static void StaminaAfter(PlayerControllerB __instance) { if (!IsLocal(__instance) || __instance.isPlayerDead) { return; } if (__instance.currentlyHeldObjectServer is JailbirdItem && !__instance.currentlyHeldObjectServer.isPocketed) { _lastHeldAt = Time.time; } float num = Time.time - _lastHeldAt; if (!(num >= 5f)) { float num2 = Mathf.Pow(4f, 1f - Mathf.Clamp01(num / 5f)); float num3 = __instance.sprintMeter - _staminaBefore; if (!(Mathf.Abs(num3) < 1E-06f)) { __instance.sprintMeter = Mathf.Clamp01(_staminaBefore + num3 * num2); } } } private static bool NoJump(PlayerControllerB __instance) { if (LocalSlowed) { return !IsLocal(__instance); } return true; } private static void SlowLook(PlayerControllerB __instance, ref Vector2 inputVector) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) if (LocalSlowLook && IsLocal(__instance)) { inputVector *= 0.25f; } } private static bool NoScan() { PlayerControllerB val = GameNetworkManager.Instance?.localPlayerController; if ((Object)(object)val != (Object)null && val.currentlyHeldObjectServer is JailbirdItem) { return val.isPlayerDead; } return true; } private static void Landed() { JailbirdTip.NewRound(); JailbirdItem.NewRound(); } } internal sealed class LateJoinDropship : Fix { private enum Ev : byte { WaitForDropship = 1, Revive, Announce } [CompilerGenerated] private static class <>O { public static HandleNamedMessageDelegate <0>__OnMessage; } private const string Msg = "slivkonsin.OptionalFixesAndAddons.Dropoff"; private const float CallAfter = 20f; private const float GiveUpAfter = 120f; private const float AfterLeaveCooldown = 12f; private const float ConfirmTimeout = 10f; private const string AnnounceText = "The Company has sent new employees to assist you in your scavenging. They will arrive on the dropship soon."; private static bool _announcedThisTrip; internal static LateJoinDropship Instance; private static CustomMessagingManager _registered; private static MethodInfo _landShip; private static MethodInfo _deliverVehicle; private static readonly Dictionary<ulong, float> Pending = new Dictionary<ulong, float>(); private static readonly List<int> Queue = new List<int>(); private static float _waitingSince; private static float _callTimer; private static float _cooldownUntil; private static bool _wasDelivering; private static readonly HashSet<ulong> InRoundFromStart = new HashSet<ulong>(); private static ItemDropship _dropship; private static FieldInfo _readingDialogue; public override string Key => "LateJoinDropship"; public override string Title => "Mid-round joiners arrive by dropship"; public override string Section => "5. Mod reworks"; public override string Requires => "VeryLateCompany"; public override string Description => "Players who join mid-round watch as spectators until the dropship drops them off next to it (it gets called if it isn't coming already).\nWhile someone is waiting for it, the round doesn't end even if everyone else is dead. Only the host needs this on."; internal static bool IsOn { get { if (Instance != null) { return Instance.Active; } return false; } } public override void Install(Harmony h) { //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Expected O, but got Unknown //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Expected O, but got Unknown //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Expected O, but got Unknown //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Expected O, but got Unknown //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Expected O, but got Unknown //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Expected O, but got Unknown Instance = this; if (!Chainloader.PluginInfos.ContainsKey("VeryLateCompany")) { Skip("VeryLateCompany not installed"); return; } _landShip = AccessTools.Method(typeof(ItemDropship), "LandShipOnServer", (Type[])null, (Type[])null); _deliverVehicle = AccessTools.Method(typeof(ItemDropship), "DeliverVehicleOnServer", (Type[])null, (Type[])null); if (_landShip == null) { Skip("the dropship's code changed"); return; } h.Patch((MethodBase)AccessTools.Method(typeof(ItemDropship), "Update", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(LateJoinDropship), "DropshipTick", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)AccessTools.Method(typeof(StartOfRound), "ShipLeaveAutomatically", (Type[])null, (Type[])null), new HarmonyMethod(typeof(LateJoinDropship), "HoldRound", (Type[])null) { priority = 800 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)AccessTools.Method(typeof(StartOfRound), "ShipLeave", (Type[])null, (Type[])null), new HarmonyMethod(typeof(LateJoinDropship), "ShipLeaving", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)AccessTools.Method(typeof(StartOfRound), "OnPlayerDC", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(LateJoinDropship), "PlayerLeft", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)AccessTools.Method(typeof(StartOfRound), "StartGame", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(LateJoinDropship), "NewRound", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)AccessTools.Method(typeof(RoundManager), "FinishedGeneratingLevelServerRpc", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(LateJoinDropship), "SomeoneBuiltLevel", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); On(null); } public override void Update() { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null || !singleton.IsListening || singleton.CustomMessagingManager == null) { _registered = null; } else if (_registered != singleton.CustomMessagingManager) { _registered = singleton.CustomMessagingManager; CustomMessagingManager registered = _registered; object obj = <>O.<0>__OnMessage; if (obj == null) { HandleNamedMessageDelegate val = OnMessage; <>O.<0>__OnMessage = val; obj = (object)val; } registered.RegisterNamedMessageHandler("slivkonsin.OptionalFixesAndAddons.Dropoff", (HandleNamedMessageDelegate)obj); Pending.Clear(); Queue.Clear(); } } private static void NewRound() { Pending.Clear(); Queue.Clear(); _callTimer = 0f; _announcedThisTrip = false; InRoundFromStart.Clear(); NetworkManager singleton = NetworkManager.Singleton; if (!((Object)(object)singleton != (Object)null) || !singleton.IsServer) { return; } foreach (ulong connectedClientsId in singleton.ConnectedClientsIds) { InRoundFromStart.Add(connectedClientsId); } } private static void SomeoneBuiltLevel(ulong clientId) { NetworkManager singleton = NetworkManager.Singleton; if (!((Object)(object)singleton == (Object)null) && singleton.IsServer && clientId != singleton.LocalClientId && InRoundFromStart.Add(clientId)) { ((MonoBehaviour)Plugin.Instance).StartCoroutine(Later(2f, delegate { OnLateJoinerReady(clientId); })); } } private static IEnumerator Later(float seconds, Action a) { yield return (object)new WaitForSeconds(seconds); try { a(); } catch (Exception e) { Instance?.Failed(e); } } internal static bool OnLateJoinerReady(ulong clientId) { //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) if (!IsOn) { return false; } StartOfRound instance = StartOfRound.Instance; NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)instance == (Object)null || (Object)(object)singleton == (Object)null || !singleton.IsServer) { return false; } if (!instance.shipHasLanded || instance.shipIsLeaving || instance.inShipPhase) { return false; } if ((Object)(object)Dropship() == (Object)null) { Plugin.Log.LogInfo((object)"Late joiner: this moon has no dropship, they join in the ship."); return false; } Pending[clientId] = Time.realtimeSinceStartup; Send(new ulong[1] { clientId }, Ev.WaitForDropship, 0, default(Vector3)); Plugin.Log.LogInfo((object)$"Late joiner {clientId}: spectating until the dropship drops them off."); return true; } public static string TestDropOff() { if (!IsOn) { return "The late-join dropship isn't on (needs VeryLateCompany and the setting)."; } StartOfRound instance = StartOfRound.Instance; NetworkManager singleton = NetworkManager.Singleton; PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null); if ((Object)(object)instance == (Object)null || (Object)(object)singleton == (Object)null || !singleton.IsServer || (Object)(object)val == (Object)null) { return "Host only, in a game."; } if (!instance.shipHasLanded || instance.shipIsLeaving) { return "Only while landed on a moon."; } if ((Object)(object)Dropship() == (Object)null) { return "This moon has no dropship."; } if (!val.isPlayerDead) { return "Die first (and turn on 'keep round alive')."; } int item = (int)val.playerClientId; if (!Queue.Contains(item)) { Queue.Add(item); } if (Queue.Count == 1) { _waitingSince = Time.time; } AnnounceOnce(); return "Queued: the dropship will come and drop you off."; } private static ItemDropship Dropship() { if ((Object)(object)_dropship == (Object)null) { _dropship = Object.FindObjectOfType<ItemDropship>(); } return _dropship; } private static void DropshipTick(ItemDropship __instance) { try { if (!((NetworkBehaviour)__instance).IsServer) { return; } _dropship = __instance; StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null) { return; } if (_wasDelivering && !__instance.deliveringOrder) { _cooldownUntil = Time.time + 12f; } _wasDelivering = __instance.deliveringOrder; ConfirmPending(instance); if (Queue.Count == 0) { _callTimer = 0f; } else if (Time.time - _waitingSince > 120f) { Plugin.Log.LogWarning((object)"Late joiners: the dropship didn't make it in time, putting them in the ship."); DropAll(inShip: true, __instance); } else if (__instance.shipLanded || (__instance.deliveringVehicle && __instance.untetheredVehicle)) { if (__instance.shipLanded && !__instance.shipDoorsOpened) { __instance.TryOpeningShip(); } DropAll(inShip: false, __instance); } else { if (__instance.deliveringOrder || !instance.shipHasLanded || instance.shipIsLeaving || Time.time < _cooldownUntil) { return; } _callTimer += Time.deltaTime; if (!(_callTimer < 20f)) { _callTimer = 0f; Terminal val = Object.FindObjectOfType<Terminal>(); if ((Object)(object)val != (Object)null && val.orderedVehicleFromTerminal != -1 && _deliverVehicle != null) { _deliverVehicle.Invoke(__instance, null); } else { _landShip.Invoke(__instance, null); } Plugin.Log.LogInfo((object)$"Late joiners: called the dropship for {Queue.Count} player(s)."); } } } catch (Exception e) { Instance?.Failed(e); } } private static void ConfirmPending(StartOfRound sor) { if (Pending.Count == 0) { return; } foreach (KeyValuePair<ulong, float> item in Pending.ToList()) { if (!sor.ClientPlayerList.TryGetValue(item.Key, out var value)) { Pending.Remove(item.Key); } else if (sor.allPlayerScripts[value].isPlayerDead) { Pending.Remove(item.Key); if (!Queue.Contains(value)) { Queue.Add(value); } if (Queue.Count == 1) { _waitingSince = Time.time; } AnnounceOnce(); } else if (Time.realtimeSinceStartup - item.Value > 10f) { Pending.Remove(item.Key); Plugin.Log.LogInfo((object)$"Late joiner {item.Key} didn't start spectating (no Optional Fixes & Addons?), they just play from the ship."); } } } private static void AnnounceOnce() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) if (!_announcedThisTrip) { _announcedThisTrip = true; Send(StartOfRound.Instance.ConnectedClientsList(), Ev.Announce, 0, default(Vector3)); } } private static void DropAll(bool inShip, ItemDropship ship) { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) _announcedThisTrip = false; StartOfRound instance = StartOfRound.Instance; Vector3[] array = (inShip ? null : SpotsNextTo(ship, Queue.Count)); for (int i = 0; i < Queue.Count; i++) { int num = Queue[i]; if (num >= 0 && num < instance.allPlayerScripts.Length && instance.allPlayerScripts[num].isPlayerDead) { Vector3 at = (inShip ? instance.playerSpawnPositions[num].position : array[i]); Send(instance.ConnectedClientsList(), Ev.Revive, num, at); DiagnosticsTelemetry.DroppedOffByDropship++; } } Queue.Clear(); } private static Vector3[] SpotsNextTo(ItemDropship ship, int count) { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01b8: Unknown result type (might be due to invalid IL or missing references) //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_01cc: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: Unknown result type (might be due to invalid IL or missing references) //IL_01b1: Unknown result type (might be due to invalid IL or missing references) Vector3[] array = (Vector3[])(object)new Vector3[count]; Transform val = (((Object)(object)((Component)ship).transform.parent != (Object)null) ? ((Component)ship).transform.parent.Find("ItemShipLandingPosition") : null); Vector3 val2 = (((Object)(object)val != (Object)null) ? val.position : ((Component)ship).transform.position); float num = 3f; NavMeshObstacle component = ((Component)ship).GetComponent<NavMeshObstacle>(); if ((Object)(object)component != (Object)null) { Vector3 val3 = Vector3.Scale(component.size, ((Component)ship).transform.lossyScale); num = Mathf.Max(new float[3] { Mathf.Abs(val3.x), Mathf.Abs(val3.y), Mathf.Abs(val3.z) }) * 0.5f; } num = Mathf.Clamp(num, 2f, 15f) + 2f; Vector3 val4 = StartOfRound.Instance.elevatorTransform.position - val2; val4.y = 0f; if (((Vector3)(ref val4)).sqrMagnitude < 0.01f) { val4 = Vector3.forward; } ((Vector3)(ref val4)).Normalize(); NavMeshHit val6 = default(NavMeshHit); RaycastHit val7 = default(RaycastHit); for (int i = 0; i < count; i++) { float num2 = ((float)i - (float)(count - 1) * 0.5f) * 35f; Vector3 val5 = val2 + Quaternion.Euler(0f, num2, 0f) * val4 * num; if (NavMesh.SamplePosition(val5, ref val6, 5f, -1)) { val5 = ((NavMeshHit)(ref val6)).position; } else if (Physics.Raycast(val5 + Vector3.up * 10f, Vector3.down, ref val7, 30f, StartOfRound.Instance.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1)) { val5 = ((RaycastHit)(ref val7)).point; } array[i] = val5 + Vector3.up * 0.1f; } return array; } private static bool HoldRound(StartOfRound __instance, bool leavingOnMidnight) { if (!IsOn || leavingOnMidnight || !((NetworkBehaviour)__instance).IsServer || (Queue.Count == 0 && Pending.Count == 0)) { return true; } __instance.allPlayersDead = false; return false; } private static void ShipLeaving(StartOfRound __instance) { if (IsOn && ((NetworkBehaviour)__instance).IsServer && Queue.Count != 0) { Plugin.Log.LogInfo((object)"Late joiners: ship is leaving before the dropship came, putting them in the ship."); DropAll(inShip: true, Dropship()); } } private static void PlayerLeft(StartOfRound __instance, int playerObjectNumber, ulong clientId) { Queue.Remove(playerObjectNumber); Pending.Remove(clientId); } private unsafe static void Send(IEnumerable<ulong> to, Ev ev, int idx, Vector3 at) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) NetworkManager singleton = NetworkManager.Singleton; List<ulong> list = to.ToList(); if (list.Remove(singleton.LocalClientId)) { Handle(ev, idx, at); } if (list.Count == 0 || _registered == null) { return; } FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(32, (Allocator)2, -1); try { byte b = (byte)ev; ((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref idx, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe(ref at); _registered.SendNamedMessage("slivkonsin.OptionalFixesAndAddons.Dropoff", (IReadOnlyList<ulong>)list, val, (NetworkDelivery)2); } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } } private static void OnMessage(ulong sender, FastBufferReader r) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: 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) try { if (sender == 0L) { byte ev = default(byte); ((FastBufferReader)(ref r)).ReadValueSafe<byte>(ref ev, default(ForPrimitives)); int idx = default(int); ((FastBufferReader)(ref r)).ReadValueSafe<int>(ref idx, default(ForPrimitives)); Vector3 at = default(Vector3); ((FastBufferReader)(ref r)).ReadValueSafe(ref at); Handle((Ev)ev, idx, at); } } catch (Exception e) { Instance?.Failed(e); } } private static void Handle(Ev ev, int idx, Vector3 at) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) switch (ev) { case Ev.WaitForDropship: BecomeSpectator(); break; case Ev.Revive: ReviveAt(idx, at); break; case Ev.Announce: ((MonoBehaviour)Plugin.Instance).StartCoroutine(ShowAnnouncement()); break; } } private static void BecomeSpectator() { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0038: 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) PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null); if ((Object)(object)val == (Object)null || val.isPlayerDead) { return; } val.KillPlayer(Vector3.zero, false, (CauseOfDeath)0, 0, default(Vector3), false); try { HUDManager.Instance.DisplayTip("On your way", "The dropship will drop you off soon.", false, false, "LC_Tip1"); } catch { } } private static IEnumerator ShowAnnouncement() { HUDManager hud = HUDManager.Instance; if ((Object)(object)hud == (Object)null) { yield break; } if (_readingDialogue == null) { _readingDialogue = AccessTools.Field(typeof(HUDManager), "readDialogueCoroutine"); } float waited = 0f; while (waited < 20f && IsDialogueBusy(hud)) { waited += 0.5f; yield return (object)new WaitForSeconds(0.5f); } if (IsDialogueBusy(hud)) { yield break; } try { hud.ReadDialogue((DialogueSegment[])(object)new DialogueSegment[1] { new DialogueSegment { bodyText = "The Company has sent new employees to assist you in your scavenging. They will arrive on the dropship soon.", waitTime = 6f } }); } catch (Exception e) { Instance?.Failed(e); } } private static bool IsDialogueBusy(HUDManager hud) { try { if (_readingDialogue != null && _readingDialogue.GetValue(hud) != null) { return true; } return (Object)(object)hud.dialogueBoxAnimator != (Object)null && hud.dialogueBoxAnimator.GetBool("Open"); } catch { return false; } } private static void ResetSpectateEnemies() { try { foreach (Type item in Util.TypesNamed("SpectateEnemies")) { object obj = AccessTools.Field(item, "Instance")?.GetValue(null) ?? AccessTools.Property(item, "Instance")?.GetValue(null); if (obj != null) { AccessTools.Field(item, "SpectatedEnemyIndex")?.SetValue(obj, -1); AccessTools.Field(item, "SpectatingEnemies")?.SetValue(obj, false); AccessTools.Method(item, "Hide", (Type[])null, (Type[])null)?.Invoke(obj, null); } } } catch (Exception ex) { Plugin.Log.LogWarning((object)("Couldn't reset SpectateEnemies after the drop-off: " + ex.Message)); } } private static void ReviveAt(int i, Vector3 at) { //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Unknown result type (might be due to invalid IL or missing references) StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null || i < 0 || i >= instance.allPlayerScripts.Length) { return; } PlayerControllerB val = instance.allPlayerScripts[i]; if (!val.isPlayerDead) { return; } try { val.ResetPlayerBloodObjects(true); val.isClimbingLadder = false; val.clampLooking = false; val.inVehicleAnimation = false; val.disableMoveInput = false; val.ResetZAndXRotation(); ((Collider)val.thisController).enabled = true; val.health = 100; val.hasBeenCriticallyInjured = false; val.disableLookInput = false; val.disableInteract = false; val.isPlayerDead = false; val.isPlayerControlled = true; Bounds bounds; int num; if ((Object)(object)instance.shipBounds != (Object)null) { bounds = instance.shipBounds.bounds; num = (((Bounds)(ref bounds)).Contains(at) ? 1 : 0); } else { num = 0; } bool flag = (byte)num != 0; val.isInElevator = flag; int isInHangarShipRoom; if (flag && (Object)(object)instance.shipInnerRoomBounds != (Object)null) { bounds = instance.shipInnerRoomBounds.bounds; isInHangarShipRoom = (((Bounds)(ref bounds)).Contains(at) ? 1 : 0); } else { isInHangarShipRoom = 0; } val.isInHangarShipRoom = (byte)isInHangarShipRoom != 0; val.isInsideFactory = false; val.parentedToElevatorLastFrame = false; val.overrideGameOverSpectatePivot = null; instance.SetPlayerObjectExtrapolate(false); val.TeleportPlayer(at, false, 0f, false, true); val.setPositionOfDeadPlayer = false; val.DisablePlayerModel(instance.allPlayerObjects[i], true, true); ((Behaviour)val.helmetLight).enabled = false; val.Crouch(false); val.criticallyInjured = false; if ((Object)(object)val.playerBodyAnimator != (Object)null) { val.playerBodyAnimator.SetBool("Limp", false); } val.bleedingHeavily = false; val.activatingItem = false; val.twoHanded = false; val.inShockingMinigame = false; val.inSpecialInteractAnimation = false; val.freeRotationInInteractAnimation = false; val.disableSyncInAnimation = false; val.inAnimationWithEnemy = null; val.holdingWalkieTalkie = false; val.speakingToWalkieTalkie = false; val.isSinking = false; val.isUnderwater = false; val.sinkingValue = 0f; val.statusEffectAudio.Stop(); val.DisableJetpackControlsLocally(); val.mapRadarDotAnimator.SetBool("dead", false); val.externalForceAutoFade = Vector3.zero; val.carryWeight = 1f; val.voiceMuffledByEnemy = false; if ((Object)(object)SoundManager.Instance != (Object)null) { SoundManager.Instance.playerVoicePitchTargets[i] = 1f; SoundManager.Instance.SetPlayerPitch(1f, i); } HUDManager instance2 = HUDManager.Instance; if (((NetworkBehaviour)val).IsOwner && (Object)(object)instance2 != (Object)null) { instance2.SetCracksOnVisor(100f); instance2.gasHelmetAnimator.SetBool("gasEmitting", false); val.hasBegunSpectating = false; instance2.RemoveSpectateUI(); instance2.gameOverAnimator.SetTrigger("revive"); val.hinderedMultiplier = 1f; val.isMovementHindered = 0; val.sourcesCausingSinking = 0; val.spectatedPlayerScript = null; ((Behaviour)instance2.audioListenerLowPass).enabled = false; instance.SetSpectateCameraToGameOverMode(false, val); instance2.HideHUD(false); instance2.SetNearDepthOfFieldEnabled(false); instance2.UpdateHealthUI(100, false); ResetSpectateEnemies(); } instance.livingPlayers++; instance.allPlayersDead = false; PlayerControllerB val2 = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null); if ((Object)(object)val2 != (Object)null && val2.isPlayerDead && (Object)(object)instance2 != (Object)null) { instance2.UpdateBoxesSpectateUI(); } Plugin.Log.LogInfo((object)(val.playerUsername + " " + (flag ? "is in the ship" : "got dropped off by the dropship") + ".")); } catch (Exception e) { Instance?.Failed(e); } } } internal static class LateJoinExtensions { public static IEnumerable<ulong> ConnectedClientsList(this StartOfRound _) { if (!((Object)(object)NetworkManager.Singleton != (Object)null)) { return new List<ulong>(); } return NetworkManager.Singleton.ConnectedClientsIds.ToList(); } } internal sealed class ModDataLibNullPlugin : Fix { private const string Guid = "MaxWasUnavailable.LethalModDataLib"; private static MethodInfo _registerOne; private static MethodInfo _deregisterOne; public override string Key => "ModDataLibBrokenPlugin"; public override string Title => "LethalModDataLib + a plugin that failed to start"; public override string Requires => "LethalModDataLib"; public override string Description => "If any mod failed to start, LethalModDataLib crashes at startup, and mods that save through it may not save.\nThis makes it skip mods that failed to start."; public override void Install(Harmony h) { //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Expected O, but got Unknown //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Expected O, but got Unknown Assembly assembly = Util.PluginAssembly("MaxWasUnavailable.LethalModDataLib"); if (assembly == null) { Skip("LethalModDataLib not installed"); return; } MethodInfo methodInfo = null; MethodInfo methodInfo2 = null; foreach (Type item in Util.SafeTypes(assembly)) { foreach (MethodInfo item2 in Util.DeclaredMethods(item)) { if (!item2.IsStatic) { continue; } ParameterInfo[] parameters = item2.GetParameters(); if (item2.Name == "RegisterModDataAttributes") { if (parameters.Length == 0) { methodInfo = item2; } else if (parameters.Length == 4 && parameters[0].ParameterType == typeof(string) && parameters[1].ParameterType == typeof(Type)) { _registerOne = item2; } } else if (item2.Name == "DeRegisterModDataAttributes") { if (parameters.Length == 0) { methodInfo2 = item2; } else if (parameters.Length == 1 && parameters[0].ParameterType == typeof(Type)) { _deregisterOne = item2; } } } } int num = 0; if (methodInfo != null && _registerOne != null) { h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(ModDataLibNullPlugin), "RegisterAll", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); num++; } if (methodInfo2 != null && _deregisterOne != null) { h.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(ModDataLibNullPlugin), "DeregisterAll", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); num++; } if (num == 0) { Skip("LethalModDataLib changed this code"); } else { On(null); } } private static bool AnyFailedPlugin() { return Chainloader.PluginInfos.Values.Any((PluginInfo p) => p == null || (Object)(object)p.Instance == (Object)null); } private static bool RegisterAll() { if (!AnyFailedPlugin()) { return true; } foreach (PluginInfo item in Chainloader.PluginInfos.Values.ToList()) { if ((Object)(object)((item != null) ? item.Instance : null) == (Object)null) { DiagnosticsTelemetry.FailedPluginsSkipped++; continue; } foreach (Type item2 in Util.SafeTypes(((object)item.Instance).GetType().Assembly)) { _registerOne.Invoke(null, new object[4] { item.Metadata.GUID, item2, null, null }); } } return false; } private static bool DeregisterAll() { if (!AnyFailedPlugin()) { return true; } foreach (PluginInfo item in Chainloader.PluginInfos.Values.ToList()) { if ((Object)(object)((item != null) ? item.Instance : null) == (Object)null) { continue; } foreach (Type item2 in Util.SafeTypes(((object)item.Instance).GetType().Assembly)) { _deregisterOne.Invoke(null, new object[1] { item2 }); } } return false; } } internal sealed class MoreSuitsEarlyLoad : Fix { private sealed class Ready { public Texture2D Tex; } private const string Guid = "x753.More_Suits"; private const int Parallel = 3; private static readonly MethodInfo LoadImage = AccessTools.Method(typeof(ImageConversion), "LoadImage", new Type[2] { typeof(Texture2D), typeof(byte[]) }, (Type[])null); private static readonly MethodInfo Apply2 = AccessTools.Method(typeof(Texture2D), "Apply", new Type[2] { typeof(bool), typeof(bool) }, (Type[])null); private static readonly Dictionary<(long, ulong), Ready> Cache = new Dictionary<(long, ulong), Ready>(); private static readonly Dictionary<Texture2D, (Texture2D src, byte[] bytes)> Pending = new Dictionary<Texture2D, (Texture2D, byte[])>(); private static FieldInfo _suitsAdded; private static bool _started; private static bool _done; private static float _checkTimer; public override string Key => "MoreSuitsEarlyLoad"; public override string Title => "More Suits lobby freeze"; public override string Section => "3. Performance"; public override string Requires => "More Suits"; public override string Description => "More Suits loads every suit picture at once when you join a lobby, which freezes the game for a few seconds with lots of suits.\nThis loads them in the background while you're in the main menu instead. Suits look exactly the same."; public override void Install(Harmony h) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Expected O, but got Unknown Assembly assembly = Util.PluginAssembly("x753.More_Suits"); if (assembly == null) { Skip("More Suits not installed"); return; } if ((SystemInfo.copyTextureSupport & 0x10) == 0) { Skip("this graphics card can't copy textures that way"); return; } foreach (Type item in Util.SafeTypes(assembly)) { FieldInfo field = item.GetField("SuitsAdded", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field != null && field.FieldType == typeof(bool)) { _suitsAdded = field; } } int num = 0; foreach (Type item2 in Util.SafeTypes(assembly)) { foreach (MethodInfo item3 in Util.DeclaredMethods(item2)) { if (Util.Calls(item3, (MethodInfo x) => x == LoadImage)) { h.Patch((MethodBase)item3, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(MoreSuitsEarlyLoad), "Transpiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null); num++; } } } if (num == 0) { Skip("More Suits changed how it loads pictures"); return; } if (SuitsAlreadyAdded()) { Skip("suits were already loaded"); return; } On(null); _started = true; ((MonoBehaviour)Plugin.Instance).StartCoroutine(Preload()); } private static bool SuitsAlreadyAdded() { try { return _suitsAdded != null && (bool)_suitsAdded.GetValue(null); } catch { return false; } } private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> code) { MethodInfo load = AccessTools.Method(typeof(MoreSuitsEarlyLoad), "LoadImageEarly", (Type[])null, (Type[])null); MethodInfo apply = AccessTools.Method(typeof(MoreSuitsEarlyLoad), "ApplyEarly", (Type[])null, (Type[])null); foreach (CodeInstruction item in code) { if (item.operand is MethodInfo methodInfo && methodInfo == LoadImage) { yield return CodeInstructionExtensions.MoveBlocksFrom(CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Call, (object)load), item), item); } else if (item.operand is MethodInfo methodInfo2 && methodInfo2 == Apply2) { yield return CodeInstructionExtensions.MoveBlocksFrom(CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Call, (object)apply), item), item); } else { yield return item; } } } private static List<string> SuitImages() { List<string> list = new List<string>(); try { string[] directories = Directory.GetDirectories(Paths.PluginPath, "moresuits", SearchOption.AllDirectories); foreach (string text in directories) { list.AddRange(Directory.GetFiles(text, "*.png")); string path = Path.Combine(text, "advanced"); if (Directory.Exists(path)) { list.AddRange(Directory.GetFiles(path, "*.png")); } } } catch (Exception ex) { Plugin.Log.LogWarning((object)("More Suits early loading: couldn't list suit pictures: " + ex.Message)); } return list; } private static IEnumerator Preload() { List<string> files = SuitImages(); int i = 0; List<IEnumerator> running = new List<IEnumerator>(); while ((i < files.Count || running.Count > 0) && !SuitsAlreadyAdded()) { while (running.Count < 3 && i < files.Count) { running.Add(LoadOne(files[i++])); } for (int num = running.Count - 1; num >= 0; num--) { if (!running[num].MoveNext()) { running.RemoveAt(num); } } yield return null; } if (Plugin.DebugLog.Value) { Plugin.Log.LogInfo((object)$"More Suits early loading: {DiagnosticsTelemetry.SuitImagesPreloaded} of {files.Count} pictures ready."); } } private static IEnumerator LoadOne(string path) { Task<(long, ulong)> hash = Task.Run(delegate { byte[] array = File.ReadAllBytes(path); return ((long, ulong))(array.Length, Fnv(array)); }); UnityWebRequest req; try { req = UnityWebRequestTexture.GetTexture(new Uri(path).AbsoluteUri, true); } catch { yield break; } UnityWebRequestAsyncOperation op = req.SendWebRequest(); while (!((AsyncOperation)op).isDone || !hash.IsCompleted) { yield return null; } try { if ((int)req.result != 1 || hash.IsFaulted) { yield break; } Texture2D content = DownloadHandlerTexture.GetContent(req); if (!((Object)(object)content == (Object)null)) { ((Object)content).name = "GMF_preload_" + Path.GetFileNameWithoutExtension(path); if (Cache.ContainsKey(hash.Result)) { Object.Destroy((Object)(object)content); yield break; } Cache[hash.Result] = new Ready { Tex = content }; DiagnosticsTelemetry.SuitImagesPreloaded++; } } finally { req.Dispose(); } } private static ulong Fnv(byte[] data) { ulong num = 14695981039346656037uL; for (int i = 0; i < data.Length; i++) { num ^= data[i]; num *= 1099511628211L; } return num; } public static bool LoadImageEarly(Texture2D tex, byte[] data) { try { if (_started && (Object)(object)tex != (Object)null && data != null && Cache.TryGetValue((data.Length, Fnv(data)), out var value) && (Object)(object)value.Tex != (Object)null) { tex.Reinitialize(((Texture)value.Tex).width, ((Texture)value.Tex).height, (TextureFormat)5, true); Pending[tex] = (value.Tex, data); value.Tex = null; return true; } } catch { } return ImageConversion.LoadImage(tex, data); } public static void ApplyEarly(Texture2D tex, bool updateMipmaps, bool makeNoLongerReadable) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: 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) if ((Object)(object)tex == (Object)null || !Pending.TryGetValue(tex, out (Texture2D, byte[]) value)) { tex.Apply(updateMipmaps, makeNoLongerReadable); return; } Pending.Remove(tex); RenderTexture val = null; try { if (!SystemInfo.IsFormatSupported(((Texture)tex).graphicsFormat, (FormatUsage)4)) { throw new Exception("texture format " + ((object)((Texture)tex).graphicsFormat/*cast due to .constrained prefix*/).ToString() + " can't be rendered to here"); } tex.Apply(false, makeNoLongerReadable); RenderTextureDescriptor val2 = new RenderTextureDescriptor(((Texture)tex).width, ((Texture)tex).height, ((Texture)tex).graphicsFormat, 0, ((Texture)tex).mipmapCount); ((RenderTextureDescriptor)(ref val2)).useMipMap = ((Texture)tex).mipmapCount > 1; ((RenderTextureDescriptor)(ref val2)).autoGenerateMips = false; val = RenderTexture.GetTemporary(val2); Graphics.Blit((Texture)(object)value.Item1, val); if (((Texture)tex).mipmapCount > 1) { val.GenerateMips(); } for (int i = 0; i < ((Texture)tex).mipmapCount; i++) { Graphics.CopyTexture((Texture)(object)val, 0, i, (Texture)(object)tex, 0, i); } DiagnosticsTelemetry.SuitImagesUsedEarly++; } catch (Exception ex) { DiagnosticsTelemetry.SuitImagesFallback++; if (Plugin.DebugLog.Value) { Plugin.Log.LogWarning((object)("More Suits early loading, using normal loading for one picture: " + ex.Message)); } try { ImageConversion.LoadImage(tex, value.Item2); tex.Apply(updateMipmaps, makeNoLongerReadable); } catch { } } finally { if ((Object)(object)val != (Object)null) { RenderTexture.ReleaseTemporary(val); } Object.Destroy((Object)(object)value.Item1); } } public override void Update() { if (_done) { return; } _checkTimer -= Time.unscaledDeltaTime; if (_checkTimer > 0f) { return; } _checkTimer = 2f; if (!SuitsAlreadyAdded()) { return; } _done = true; int num = 0; foreach (Ready value in Cache.Values) { if ((Object)(object)value.Tex != (Object)null) { Object.Destroy((Object)(object)value.Tex); value.Tex = null; num++; } } Cache.Clear(); Plugin.Log.LogInfo((object)($"More Suits early loading: {DiagnosticsTelemetry.SuitImagesUsedEarly} pictures were ready in time, " + $"{DiagnosticsTelemetry.SuitImagesFallback} loaded normally, {num} weren't needed.")); } } internal sealed class Scp3199Tag : Fix { public override string Key => "SCP3199MissingTag"; public override string Title => "SCP-3199 missing tag"; public override string Requires => "SCP-3199"; public override string Description => "SCP-3199 uses a tag the game doesn't have, which stops it from finishing its setup when it spawns.\nThis skips that tag so the enemy sets up normally."; public override void Install(Harmony h) { //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Expected O, but got Unknown List<Type> list = Util.TypesNamed("SCP3199AI"); if (list.Count == 0) { Skip("SCP-3199 not installed"); return; } int num = 0; foreach (Type item in list) { foreach (MethodInfo item2 in Util.DeclaredMethods(item)) { if (Util.Calls(item2, SafeTags.IsTagCall)) { h.Patch((MethodBase)item2, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(SafeTags), "Transpiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null); num++; } } } if (num == 0) { Skip("its code no longer uses tags"); } else { On(num + ((num == 1) ? " method" : " methods")); } } } internal static class SafeTags { private static readonly HashSet<string> Reported = new HashSet<string>(); private static readonly HashSet<string> Missing = new HashSet<string>(); private static readonly MethodInfo GoSetTag = AccessTools.PropertySetter(typeof(GameObject), "tag"); private static readonly MethodInfo CSetTag = AccessTools.PropertySetter(typeof(Component), "tag"); private static readonly MethodInfo GoCompare = AccessTools.Method(typeof(GameObject), "CompareTag", new Type[1] { typeof(string) }, (Type[])null); private static readonly MethodInfo CCompare = AccessTools.Method(typeof(Component), "CompareTag", new Type[1] { typeof(string) }, (Type[])null); private static readonly MethodInfo FindAll = AccessTools.Method(typeof(GameObject), "FindGameObjectsWithTag", new Type[1] { typeof(string) }, (Type[])null); private static readonly MethodInfo FindOne = AccessTools.Method(typeof(GameObject), "FindGameObjectWithTag", new Type[1] { typeof(string) }, (Type[])null); private static readonly MethodInfo FindOne2 = AccessTools.Method(typeof(GameObject), "FindWithTag", new Type[1] { typeof(string) }, (Type[])null); private static Dictionary<MethodInfo, MethodInfo> _map; private static Dictionary<MethodInfo, MethodInfo> Map { get { object obj = _map; if (obj == null) { obj = new Dictionary<MethodInfo, MethodInfo> { [GoSetTag] = AccessTools.Method(typeof(SafeTags), "SetTag", (Type[])null, (Type[])null), [CSetTag] = AccessTools.Method(typeof(SafeTags), "SetTagC", (Type[])null, (Type[])null), [GoCompare] = AccessTools.Method(typeof(SafeTags), "Compare", (Type[])null, (Type[])null), [CCompare] = AccessTools.Method(typeof(SafeTags), "CompareC", (Type[])null, (Type[])null), [FindAll] = AccessTools.Method(typeof(SafeTags), "FindAllWith", (Type[])null, (Type[])null), [FindOne] = AccessTools.Method(typeof(SafeTags), "FindOneWith", (Type[])null, (Type[])null), [FindOne2] = AccessTools.Method(typeof(SafeTags), "FindOneWith", (Type[])null, (Type[])null) }; _map = (Dictionary<MethodInfo, MethodInfo>)obj; } return (Dictionary<MethodInfo, MethodInfo>)obj; } } private static bool Known(string tag) { if (tag == null || !Missing.Contains(tag)) { return false; } DiagnosticsTelemetry.MissingTagsCaught++; return true; } public static bool IsTagCall(MethodInfo m) { if (m != null) { return Map.ContainsKey(m); } return false; } public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> code) { foreach (CodeInstruction item in code) { if (item.operand is MethodInfo key && Map.TryGetValue(key, out var value)) { yield return CodeInstructionExtensions.MoveBlocksFrom(CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Call, (object)value), item), item); } else { yield return item; } } } private static void Report(string tag, Exception e) { DiagnosticsTelemetry.MissingTagsCaught++; if (tag != null) { Missing.Add(tag); } if (Reported.Add(tag ?? "")) { Plugin.Log.LogInfo((object)("A mod used the tag \"" + tag + "\", which doesn't exist in the game. Skipped it instead of erroring. (" + e.Message + ")")); } } public static void SetTag(GameObject go, string tag) { //IL_0014: Expected O, but got Unknown if (Known(tag)) { return; } try { go.tag = tag; } catch (UnityException ex) { UnityException e = ex; Report(tag, (Exception)(object)e); } } public static void SetTagC(Component c, string tag) { //IL_0014: Expected O, but got Unknown if (Known(tag)) { return; } try { c.tag = tag; } catch (UnityException ex) { UnityException e = ex; Report(tag, (Exception)(object)e); } } public static bool Compare(GameObject go, string tag) { //IL_0016: Expected O, but got Unknown if (Known(tag)) { return false; } try { return go.CompareTag(tag); } catch (UnityException ex) { UnityException e = ex; Report(tag, (Exception)(object)e); return false; } } public static bool CompareC(Component c, string tag) { //IL_0016: Expected O, but got Unknown if (Known(tag)) { return false; } try { return c.CompareTag(tag); } catch (UnityException ex) { UnityException e = ex; Report(tag, (Exception)(object)e); return false; } } public static GameObject[] FindAllWith(string tag) { //IL_0019: Expected O, but got Unknown if (Known(tag)) { return Array.Empty<GameObject>(); } try { return GameObject.FindGameObjectsWithTag(tag); } catch (UnityException ex) { UnityException e = ex; Report(tag, (Exception)(object)e); return Array.Empty<GameObject>(); } } public static GameObject FindOneWith(string tag) { //IL_0015: Expected O, but got Unknown if (Known(tag)) { return null; } try { return GameObject.FindGameObjectWithTag(tag); } catch (UnityException ex) { UnityException e = ex; Report(tag, (Exception)(object)e); return null; } } } internal sealed class ShipWindowsShutterGuard : Fix { private const string Guid = "TestAccount666.ShipWindows"; private static FieldInfo _windowManager; private static bool _told; public override string Key => "ShipWindowsShutterErrors"; public override string Title => "ShipWindows shutter errors"; public override string Requires => "ShipWindows"; public override string Description => "If ShipWindows' windows didn't load, it throws an error every time the shutters open or close.\nThis skips the shutters when there are no windows."; public override void Install(Harmony h) { //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Expected O, but got Unknown Assembly assembly = Util.PluginAssembly("TestAccount666.ShipWindows"); if (assembly == null) { Skip("ShipWindows not installed"); return; } List<MethodInfo> list = new List<MethodInfo>(); foreach (Type item in Util.SafeTypes(assembly)) { if (_windowManager == null) { FieldInfo field = item.GetField("windowManager", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field != null && field.FieldType.Name == "WindowManager") { _windowManager = field; } } MethodInfo method = item.GetMethod("ToggleShutterOnLocalClient", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (method != null && method.ReturnType == typeof(void)) { list.Add(method); } } if (_windowManager == null || list.Count == 0) { Skip("ShipWindows changed its shutter code"); return; } foreach (MethodInfo item2 in list) { h.Patch((MethodBase)item2, new HarmonyMethod(typeof(ShipWindowsShutterGuard), "Guard", (Type[])null) { priority = 800 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } On(null); } private static bool Guard() { object value; try { value = _windowManager.GetValue(null); } catch { return true; } if (value != null) { return true; } DiagnosticsTelemetry.ShutterCallsSkipped++; if (!_told) { _told = true; Plugin.Log.LogWarning((object)"ShipWindows has no windows loaded (it failed to start), skipping its shutters."); } return false; } } internal sealed class ShipWindowsTwoStory : Fix { private const string WindowsGuid = "TestAccount666.ShipWindows"; private const string TwoStoryGuid = "MelanieMelicious.2StoryShip"; private static ShipWindowsTwoStory _self; private static MethodInfo _create; private static StartOfRound _readyFor; private static bool _pending; private static int _waitedFrames; private static bool _repairedOrGaveUp; public override string Key => "ShipWindowsWaitFor2StoryShip"; public override string Title => "ShipWindows + 2 Story Ship startup order"; public override string Requires => "ShipWindows and 2 Story Ship"; public override string Description => "Sometimes the game sets up the HUD before 2 Story Ship is ready, which crashes ShipWindows: no windows, and some other mods' HUD parts go missing too.\nThis makes ShipWindows wait until 2 Story Ship is ready."; public override void Install(Harmony h) { //IL_0245: Unknown result type (might be due to invalid IL or missing references) //IL_024a: Unknown result type (might be due to invalid IL or missing references) //IL_0259: Expected O, but got Unknown //IL_0289: Unknown result type (might be due to invalid IL or missing references) //IL_028e: Unknown result type (might be due to invalid IL or missing references) //IL_02ab: Unknown result type (might be due to invalid IL or missing references) //IL_02b0: Unknown result type (might be due to invalid IL or missing references) //IL_02c1: Expected O, but got Unknown //IL_02c1: Expected O, but got Unknown _self = this; if (!Chainloader.PluginInfos.ContainsKey("TestAccount666.ShipWindows")) { Skip("ShipWindows not installed"); return; } if (!Chainloader.PluginInfos.ContainsKey("MelanieMelicious.2StoryShip")) { Skip("2 Story Ship not installed"); return; } Patches patchInfo = Harmony.GetPatchInfo((MethodBase)AccessTools.Method(typeof(HUDManager), "Awake", (Type[])null, (Type[])null)); _create = (from p in patchInfo?.Postfixes.Concat(patchInfo.Prefixes) where p.owner == "TestAccount666.ShipWindows" select p.PatchMethod).FirstOrDefault((MethodInfo m) => m.Name.Contains("WindowManager") || Util.Calls(m, (MethodInfo x) => x.DeclaringType != null && x.DeclaringType.Name == "WindowManager")); if (_create == null) { _create = (from p in patchInfo?.Postfixes where p.owner == "TestAccount666.ShipWindows" select p.PatchMethod).FirstOrDefault((MethodInfo m) => CreatesWindowManager(m)); } if (_create == null) { Skip("ShipWindows changed how it builds windows"); return; } Patches patchInfo2 = Harmony.GetPatchInfo((MethodBase)AccessTools.Method(typeof(StartOfRound), "Awake", (Type[])null, (Type[])null)); List<MethodInfo> list = (from p in patchInfo2?.Postfixes.Concat(patchInfo2.Prefixes) where p.owner == "MelanieMelicious.2StoryShip" select p.PatchMethod).ToList(); if (list == null || list.Count == 0) { Skip("2 Story Ship changed how it starts up"); return; } foreach (MethodInfo item in list) { h.Patch((MethodBase)item, (HarmonyMethod)null, new HarmonyMethod(typeof(ShipWindowsTwoStory), "TwoStoryReady", (Type[])null) { priority = 0 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } h.Patch((MethodBase)_create, new HarmonyMethod(typeof(ShipWindowsTwoStory), "WaitIfNotReady", (Type[])null) { priority = 800 }, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(ShipWindowsTwoStory), "AfterBuild", (Type[])null) { priority = 800 }, (HarmonyMethod)null); On(null); } private static bool CreatesWindowManager(MethodInfo m) { try { foreach (KeyValuePair<OpCode, object> item in PatchProcessor.ReadMethodBody((MethodBase)m)) { if (item.Value is ConstructorInfo constructorInfo && constructorInfo.DeclaringType != null && constructorInfo.DeclaringType.Name == "WindowManager") { return true; } } } catch { } return false; } private static bool WaitIfNotReady() { StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance != (Object)null && (Object)(object)_readyFor == (Object)(object)instance) { RepairWindowPart(); return true; } _pending = true; _waitedFrames = 0; DiagnosticsTelemetry.ShipWindowsDelayed++; if (Plugin.DebugLog.Value) { Plugin.Log.LogInfo((object)"ShipWindows: waiting for 2 Story Ship before building windows."); } return false; } private static void TwoStoryReady() { _readyFor = StartOfRound.Instance; RepairWindowPart(); if (_pending) { BuildNow(); } } private static void RepairWindowPart() { if (_repairedOrGaveUp) { return; } _repairedOrGaveUp = true; Type type = null; Type type2 = null; Assembly assembly = Util.PluginAssembly("MelanieMelicious.2StoryShip"); if (assembly == null) { return; } foreach (Type item in Util.SafeTypes(assembly)) { if (item.Name == "ShipWindowPatch") { type = item; } else if (item.Name == "HarmonyPatches") { type2 = item; } } if (type == null) { return; } try { RuntimeHelpers.RunClassConstructor(type.TypeHandle); } catch (TypeInitializationException) { Plugin.Log.LogWarning((object)"2 Story Ship's ShipWindows part already failed to start and can't recover. Turning its window changes off so ShipWindows still works on its own."); DiagnosticsTelemetry.TwoStoryWindowPartRemoved = true; RemoveHooks(assembly); return; } try { Material[] array = type2?.GetField("matRef", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null) as Material[]; FieldInfo field = type.GetField("invis", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field != null && field.GetValue(null) == null && array != null && array.Length > 9 && (Object)(object)array[9] != (Object)null) { field.SetValue(null, array[9]); } FieldInfo field2 = type.GetField("glass", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field2 != null && field2.GetValue(null) == null) { object? obj = (from t in Util.TypesNamed("ShipWindows", Util.PluginAssembly("TestAccount666.ShipWindows")) select t.GetField("mainAssetBundle", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)).FirstOrDefault((FieldInfo f) => f != null)?.GetValue(null); AssetBundle val = (AssetBundle)((obj is AssetBundle) ? obj : null); if ((Object)(object)val != (Object)null) { field2.SetValue(null, val.LoadAsset<Material>("Assets/LethalCompany/Mods/plugins/ShipWindows/Windows/Shared/WindowMaterials/GlassNoRefraction.mat")); } } if (Plugin.DebugLog.Value) { Plugin.Log.LogInfo((object)"2 Story Ship's ShipWindows part is ready."); } } catch (Exception e) { _self?.Failed(e); } } private static void RemoveHooks(Assembly twoStory) { Assembly assembly = Util.PluginAssembly("TestAccount666.ShipWindows"); if (assembly == null) { return; } foreach (MethodBase item in Harmony.GetAllPatchedMethods().ToList()) { if (item.DeclaringType == null || item.DeclaringType.Assembly != assembly) { continue; } Patches patchInfo = Harmony.GetPatchInfo(item); if (patchInfo == null) { continue; } foreach (Patch item2 in patchInfo.Prefixes.Concat(patchInfo.Postfixes).Concat(patchInfo.Transpilers).Concat(patchInfo.Finalizers) .ToList()) { if (item2.owner == "MelanieMelicious.2StoryShip") { try { Plugin.Harmony.Unpatch(item, item2.PatchMethod); } catch (Exception e) { _self?.Failed(e); } } } } } private static Exception AfterBuild(Exception __exception) { if (_pending) { return __exception; } try { FieldInfo fieldInfo = (from t in Util.TypesNamed("ShipWindows", Util.PluginAssembly("TestAccount666.ShipWindows")) select t.GetField("windowManager", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)).FirstOrDefault((FieldInfo f) => f != null); if (__exception == null && (fieldInfo == null || fieldInfo.GetValue(null) != null)) { return null; } StartOfRound instance = StartOfRound.Instance; Transform val = (((Object)(object)instance != (Object)null && (Object)(object)instance.elevatorTransform != (Object)null) ? instance.elevatorTransform.Find("ShipInside") : null); if ((Object)(object)val == (Object)null) { return __exception; } Transform val2 = val.Find("DecapitatedShip"); if ((Object)(object)val2 != (Object)null) { Object.Destroy((Object)(object)((Component)val2).gameObject); } MeshRenderer component = ((Component)val).GetComponent<MeshRenderer>(); if ((Object)(object)component != (Object)null) { ((Renderer)component).enabled = true; } MeshCollider component2 = ((Component)val).GetComponent<MeshCollider>(); if ((Object)(object)component2 != (Object)null) { ((Collider)component2).enabled = true; } DiagnosticsTelemetry.ShipFloorRestored = true; Plugin.Log.LogWarning((object)"ShipWindows failed to build its windows, put the ship's normal walls and floor back so nobody falls out."); } catch (Exception e) { _self?.Failed(e); } return __exception; } private static void BuildNow() { _pending = false; try { _create.Invoke(null, null); } catch (TargetInvocationException ex) { _self?.Failed(ex.InnerException ?? ex); } catch (Exception e) { _self?.Failed(e); } } public override void Update() { if (_pending && !((Object)(object)StartOfRound.Instance == (Object)null) && !((Object)(object)HUDManager.Instance == (Object)null) && ++_waitedFrames >= 60) { Plugin.Log.LogWarning((object)"ShipWindows: 2 Story Ship never finished starting up, building the windows anyway."); _readyFor = StartOfRound.Instance; BuildNow(); } } } internal sealed class SoundApiReporting : Fix { private const string Guid = "me.loaforc.soundapi.lethalcompany"; public override string Key => "SoundApiReportError"; public override string Title => "loaforcsSoundAPI report error every round"; public override string Requires => "loaforc's SoundAPI"; public override string Description => "loaforcsSoundAPI throws an error every round from its sound report, even when the report is off.\nThis removes that part while the report is off."; public override void Install(Harmony h) { Assembly assembly = Util.PluginAssembly("me.loaforc.soundapi.lethalcompany"); if (assembly == null) { Skip("loaforcsSoundAPI not installed"); return; } if (ReportIsOn()) { Skip("the sound report is turned on"); return; } MethodInfo methodInfo = AccessTools.Method(typeof(RoundManager), "GenerateNewFloor", (Type[])null, (Type[])null); Patches val = ((methodInfo != null) ? Harmony.GetPatchInfo((MethodBase)methodInfo) : null); int num = 0; if (val != null) { foreach (Patch postfix in val.Postfixes) { MethodInfo patchMethod = postfix.PatchMethod; if (!(patchMethod?.DeclaringType == null) && !(patchMethod.DeclaringType.Assembly != assembly) && !(patchMethod.Name != "Reporting")) { h.Unpatch((MethodBase)methodInfo, patchMethod); num++; } } } if (num == 0) { Skip("that hook isn't there anymore"); } else { On(null); } } private static bool ReportIsOn() { foreach (Type item in Util.TypesNamed("SoundReportHandler")) { try { PropertyInfo property = item.GetProperty("CurrentReport", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (property != null) { return property.GetValue(null) != null; } FieldInfo field = item.GetField("CurrentReport", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field != null) { return field.GetValue(null) != null; } } catch (Exception) { return true; } } return true; } } internal sealed class SpectateEnemiesFixes : Fix { private static FieldInfo _instance; private static FieldInfo _spectating; private static MethodInfo _tip; public override string Key => "SpectateEnemiesSwitchBack"; public override string Title => "SpectateEnemies switching back to players"; public override string Requires => "SpectateEnemies"; public override string Description => "SpectateEnemies crashes when switching back to players while nobody is alive, and otherwise picks the first player instead of the nearest one\n(with the wrong lighting). This fixes both. Not needed with Refined Spectating, which already does this."; public override void Install(Harmony h) { //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Expected O, but got Unknown //IL_0122: Expected O, but got Unknown Assembly assembly = Util.PluginAssembly("SpectateEnemy"); if (assembly == null) { Skip("SpectateEnemies not installed"); return; } if (Util.PluginAssembly("slivkonsin.RefinedSpectating") != null) { Skip("Refined Spectating already fixes this"); return; } Type type = Util.TypesNamed("SpectateEnemies", assembly).Find((Type x) => x.GetField("SpectatingEnemies", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) != null); MethodInfo methodInfo = ((type != null) ? AccessTools.Method(type, "ToggleSpectatingMode", new Type[1] { typeof(PlayerControllerB) }, (Type[])null) : null); if (methodInfo == null) { Skip("SpectateEnemies changed, nothing to fix"); return; } _instance = type.GetField("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); _spectating = type.GetField("SpectatingEnemies", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); _tip = AccessTools.Method(typeof(HUDManager), "DisplaySpectatorTip", (Type[])null, (Type[])null); h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(SpectateEnemiesFixes), "Before", (Type[])null), new HarmonyMethod(typeof(SpectateEnemiesFixes), "After", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); On(null); } private static bool Spectating(object se) { if (se != null && _spectating != null) { return (bool)_spectating.GetValue(se); } return false; } private static bool AnyoneAlive(PlayerControllerB local) { StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null) { return false; } PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts; foreach (PlayerControllerB val in allPlayerScripts) { if ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)local && !val.isPlayerDead && val.isPlayerControlled) { return true; } } return false; } private static bool Before(object __instance, PlayerControllerB __0) { try { if (!Spectating(__instance) || AnyoneAlive(__0)) { return true; } if (_tip != null && (Object)(object)HUDManager.Instance != (Object)null) { _tip.Invoke(HUDManager.Instance, new object[1] { "Nobody alive to spectate" }); } return false; } catch {