Decompiled source of MistOptimizer v1.0.0

plugins/MistOptimizer.dll

Decompiled 5 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using MistOptimizer.Mist;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("MistOptimizer")]
[assembly: AssemblyProduct("MistOptimizer")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyCopyright("Copyright (c) 2026 AugusDogus, sz3ry")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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 MistOptimizer
{
	[BepInPlugin("sz3ry.mods.MistOptimizer", "MistOptimizer", "1.0.0")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginId = "sz3ry.mods.MistOptimizer";

		public const string PluginVersion = "1.0.0";

		internal static ManualLogSource Log { get; private set; } = null;

		internal static MistReport Report { get; } = new MistReport();

		private void Awake()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			MistConfig.Bind(((BaseUnityPlugin)this).Config);
			new Harmony("sz3ry.mods.MistOptimizer").PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"MistOptimizer loaded.");
		}

		private void Update()
		{
			Report.Tick(Time.unscaledDeltaTime);
		}
	}
}
namespace MistOptimizer.Mist
{
	public static class MistClock
	{
		public const float TickSeconds = 0.1f;

		public static float Step(bool fix, float deltaTime, float fixedDeltaTime)
		{
			if (!fix)
			{
				return fixedDeltaTime;
			}
			return deltaTime;
		}

		public static float TicksPerSecond(bool fix, float fps, float fixedDeltaTime)
		{
			return fps * Step(fix, 1f / fps, fixedDeltaTime) / 0.1f;
		}
	}
	[HarmonyPatch(typeof(ParticleMist), "Update")]
	internal static class MistClockPatch
	{
		private static readonly MethodInfo FixedDeltaTime = AccessTools.PropertyGetter(typeof(Time), "fixedDeltaTime");

		private static readonly MethodInfo Step = AccessTools.Method(typeof(MistClockPatch), "CurrentStep", (Type[])null, (Type[])null);

		public static float Accumulated { get; set; }

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
		{
			int replaced = 0;
			foreach (CodeInstruction instruction in instructions)
			{
				if (CodeInstructionExtensions.Calls(instruction, FixedDeltaTime))
				{
					replaced++;
					instruction.operand = Step;
				}
				yield return instruction;
			}
			if (replaced != 1)
			{
				Plugin.Log.LogWarning((object)$"ParticleMist.Update: expected one fixedDeltaTime read, replaced {replaced}.");
			}
		}

		private static float CurrentStep()
		{
			float num = MistClock.Step(MistConfig.FixEmissionRate, Time.deltaTime, Time.fixedDeltaTime);
			Accumulated += num;
			return num;
		}
	}
	[HarmonyPatch(typeof(Terminal), "InitTerminal")]
	internal static class MistCommands
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static ConsoleEvent <>9__0_0;

			public static ConsoleEvent <>9__0_1;

			public static ConsoleEvent <>9__0_2;

			internal void <Postfix>b__0_0(ConsoleEventArgs args)
			{
				if (args.Length > 1)
				{
					float? num = MistScreenRules.Parse(args[1]);
					if (!num.HasValue)
					{
						Say(args, "Usage: mistscreen 1, mistscreen 0.75 or mistscreen off");
						return;
					}
					float valueOrDefault = num.GetValueOrDefault();
					MistConfig.MaxScreenSize = valueOrDefault;
				}
				Say(args, $"Mist max screen size: {MistConfig.MaxScreenSize:0.##}");
			}

			internal void <Postfix>b__0_1(ConsoleEventArgs args)
			{
				if (args.Length > 1)
				{
					bool fixEmissionRate;
					switch (args[1])
					{
					case "on":
					case "1":
					case "true":
						fixEmissionRate = true;
						break;
					default:
						fixEmissionRate = false;
						break;
					}
					MistConfig.FixEmissionRate = fixEmissionRate;
				}
				Say(args, "Mist emission fix: " + (MistConfig.FixEmissionRate ? "on" : "off"));
			}

			internal void <Postfix>b__0_2(ConsoleEventArgs args)
			{
				args.Context.AddString(Plugin.Report.Build(1f / Time.smoothDeltaTime, 0f) ?? "No active mist here.");
			}
		}

		private static void Postfix()
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: 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_0029: Expected O, but got Unknown
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			object obj = <>c.<>9__0_0;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					if (args.Length > 1)
					{
						float? num = MistScreenRules.Parse(args[1]);
						if (!num.HasValue)
						{
							Say(args, "Usage: mistscreen 1, mistscreen 0.75 or mistscreen off");
							return;
						}
						float valueOrDefault = num.GetValueOrDefault();
						MistConfig.MaxScreenSize = valueOrDefault;
					}
					Say(args, $"Mist max screen size: {MistConfig.MaxScreenSize:0.##}");
				};
				<>c.<>9__0_0 = val;
				obj = (object)val;
			}
			new ConsoleCommand("mistscreen", "[size|off] largest mist particle as a fraction of the screen (1 looks like vanilla)", (ConsoleEvent)obj, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
			object obj2 = <>c.<>9__0_1;
			if (obj2 == null)
			{
				ConsoleEvent val2 = delegate(ConsoleEventArgs args)
				{
					if (args.Length > 1)
					{
						bool fixEmissionRate;
						switch (args[1])
						{
						case "on":
						case "1":
						case "true":
							fixEmissionRate = true;
							break;
						default:
							fixEmissionRate = false;
							break;
						}
						MistConfig.FixEmissionRate = fixEmissionRate;
					}
					Say(args, "Mist emission fix: " + (MistConfig.FixEmissionRate ? "on" : "off"));
				};
				<>c.<>9__0_1 = val2;
				obj2 = (object)val2;
			}
			new ConsoleCommand("mistfix", "[on|off] emit Mistlands mist 10 times per second whatever the framerate", (ConsoleEvent)obj2, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
			object obj3 = <>c.<>9__0_2;
			if (obj3 == null)
			{
				ConsoleEvent val3 = delegate(ConsoleEventArgs args)
				{
					args.Context.AddString(Plugin.Report.Build(1f / Time.smoothDeltaTime, 0f) ?? "No active mist here.");
				};
				<>c.<>9__0_2 = val3;
				obj3 = (object)val3;
			}
			new ConsoleCommand("mistreport", "print Mistlands mist statistics", (ConsoleEvent)obj3, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
		}

		private static void Say(ConsoleEventArgs args, string text)
		{
			args.Context.AddString(text);
			Plugin.Log.LogInfo((object)("> " + text));
		}
	}
	public static class MistConfig
	{
		private static ConfigEntry<float>? maxScreenSize;

		private static ConfigEntry<bool>? fixEmissionRate;

		private static ConfigEntry<float>? reportSeconds;

		public static float MaxScreenSize
		{
			get
			{
				return MistScreenRules.Clamp(maxScreenSize?.Value ?? 1f);
			}
			set
			{
				if (maxScreenSize != null)
				{
					maxScreenSize.Value = MistScreenRules.Clamp(value);
				}
			}
		}

		public static bool FixEmissionRate
		{
			get
			{
				return fixEmissionRate?.Value ?? false;
			}
			set
			{
				if (fixEmissionRate != null)
				{
					fixEmissionRate.Value = value;
				}
			}
		}

		public static float ReportSeconds => reportSeconds?.Value ?? 0f;

		public static void Bind(ConfigFile config)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			maxScreenSize = config.Bind<float>("Mist", "MaxScreenSize", 1f, new ConfigDescription("Largest size of one Mistlands mist particle, as a fraction of the screen. 1 looks like vanilla and draws far less; 0.75 is faster with a slightly lighter mist close by; 55 is vanilla.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 55f), Array.Empty<object>()));
			maxScreenSize.SettingChanged += delegate
			{
				MistScreen.Apply();
			};
			fixEmissionRate = config.Bind<bool>("Mist", "FixEmissionRate", false, "Emit Mistlands mist 10 times per second whatever the framerate. Vanilla emits more often above 50 FPS, so this thins the mist a little at high framerates.");
			reportSeconds = config.Bind<float>("Diagnostics", "ReportSeconds", 0f, new ConfigDescription("How often to log mist statistics while the mist is active; 0 turns the log off.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 60f), Array.Empty<object>()));
		}
	}
	internal sealed class MistReport
	{
		private float elapsed;

		private int frames;

		private bool staticLogged;

		public void Tick(float deltaTime)
		{
			elapsed += deltaTime;
			frames++;
			float reportSeconds = MistConfig.ReportSeconds;
			if (!(reportSeconds <= 0f) && !(elapsed < reportSeconds))
			{
				float num = MistClockPatch.Accumulated / 0.1f;
				string text = ((num > 0f) ? Build((float)frames / elapsed, num / elapsed) : null);
				if (text != null)
				{
					Plugin.Log.LogInfo((object)text);
				}
				elapsed = 0f;
				frames = 0;
				MistClockPatch.Accumulated = 0f;
			}
		}

		public string? Build(float fps, float ticksPerSecond)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			ParticleMist instance = ParticleMist.instance;
			ParticleSystem val = default(ParticleSystem);
			if (!((Object)(object)instance == (Object)null) && ((Component)instance).TryGetComponent<ParticleSystem>(ref val))
			{
				EmissionModule emission = val.emission;
				if (((EmissionModule)(ref emission)).enabled)
				{
					if (!staticLogged)
					{
						staticLogged = true;
						Plugin.Log.LogInfo((object)Describe(val, "ParticleMist"));
						foreach (MistEmitter item in Object.FindObjectsByType<MistEmitter>((FindObjectsSortMode)0).Take(3))
						{
							if ((Object)(object)item.m_psystem != (Object)null)
							{
								Plugin.Log.LogInfo((object)Describe(item.m_psystem, "MistEmitter"));
							}
						}
					}
					MistEmitter[] array = Object.FindObjectsByType<MistEmitter>((FindObjectsSortMode)0);
					int num = array.Sum((MistEmitter e) => ((Object)(object)e.m_psystem != (Object)null) ? e.m_psystem.particleCount : 0);
					CultureInfo invariantCulture = CultureInfo.InvariantCulture;
					object[] obj = new object[10]
					{
						fps,
						ticksPerSecond,
						MistConfig.FixEmissionRate ? "on" : "off",
						val.particleCount,
						null,
						null,
						null,
						null,
						null,
						null
					};
					MainModule main = val.main;
					obj[4] = ((MainModule)(ref main)).maxParticles;
					obj[5] = array.Length;
					obj[6] = num;
					obj[7] = (QualitySettings.softParticles ? "on" : "off");
					obj[8] = (Application.isFocused ? string.Empty : " (BACKGROUND, capped)");
					obj[9] = MistScreen.Current;
					return string.Format(invariantCulture, "Mist: fps {0:0.0}{8}, emission ticks/s {1:0.0} (0 = not measured), fix {2}, mist particles {3}/{4}, ground emitters {5} with {6} particles, soft particles {7}, max screen size {9:0.##}", obj);
				}
			}
			return null;
		}

		private static string Describe(ParticleSystem ps, string label)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			MainModule main = ps.main;
			ParticleSystemRenderer component = ((Component)ps).GetComponent<ParticleSystemRenderer>();
			Material val = (((Object)(object)component != (Object)null) ? ((Renderer)component).sharedMaterial : null);
			CultureInfo invariantCulture = CultureInfo.InvariantCulture;
			object[] obj = new object[13]
			{
				label,
				((Object)ps).name,
				((MainModule)(ref main)).maxParticles,
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				null,
				null
			};
			MinMaxCurve val2 = ((MainModule)(ref main)).startLifetime;
			obj[3] = ((MinMaxCurve)(ref val2)).constantMin;
			val2 = ((MainModule)(ref main)).startLifetime;
			obj[4] = ((MinMaxCurve)(ref val2)).constantMax;
			val2 = ((MainModule)(ref main)).startSize;
			obj[5] = ((MinMaxCurve)(ref val2)).constantMin;
			val2 = ((MainModule)(ref main)).startSize;
			obj[6] = ((MinMaxCurve)(ref val2)).constantMax;
			obj[7] = (((Object)(object)component != (Object)null) ? ((object)component.renderMode/*cast due to .constrained prefix*/).ToString() : "-");
			obj[8] = (((Object)(object)component != (Object)null) ? ((object)component.sortMode/*cast due to .constrained prefix*/).ToString() : "-");
			obj[9] = (((Object)(object)component != (Object)null) ? component.maxParticleSize : 0f);
			obj[10] = (((Object)(object)val != (Object)null) ? ((Object)val.shader).name : "-");
			obj[11] = (((Object)(object)val != (Object)null) ? val.renderQueue : 0);
			obj[12] = (((Object)(object)val != (Object)null) ? string.Join(" ", val.shaderKeywords) : "");
			return string.Format(invariantCulture, "{0} '{1}': max {2}, lifetime {3:0.##}-{4:0.##} s, start size {5:0.##}-{6:0.##}, render {7}, sort {8}, max screen size {9:0.##}, shader '{10}', queue {11}, keywords [{12}]", obj);
		}
	}
	[HarmonyPatch(typeof(ParticleMist), "Awake")]
	internal static class MistScreen
	{
		public static float Current
		{
			get
			{
				if (!TryGetRenderer(out ParticleSystemRenderer renderer))
				{
					return 0f;
				}
				return renderer.maxParticleSize;
			}
		}

		public static void Apply()
		{
			if (TryGetRenderer(out ParticleSystemRenderer renderer))
			{
				renderer.maxParticleSize = MistConfig.MaxScreenSize;
			}
		}

		private static void Postfix()
		{
			Apply();
		}

		private static bool TryGetRenderer(out ParticleSystemRenderer renderer)
		{
			renderer = null;
			ParticleMist instance = ParticleMist.instance;
			if ((Object)(object)instance != (Object)null)
			{
				return ((Component)instance).TryGetComponent<ParticleSystemRenderer>(ref renderer);
			}
			return false;
		}
	}
	public static class MistScreenRules
	{
		public const float Default = 1f;

		public const float Min = 0.1f;

		public const float Vanilla = 55f;

		public static float? Parse(string text)
		{
			if (text == "off")
			{
				return 55f;
			}
			if (!float.TryParse(text.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
			{
				return null;
			}
			return Clamp(result);
		}

		public static float Clamp(float value)
		{
			if (!(value < 0.1f))
			{
				if (!(value > 55f))
				{
					return value;
				}
				return 55f;
			}
			return 0.1f;
		}
	}
}