Decompiled source of Sulfur NoGore v1.0.3

plugins/SulfurNoGore.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using PerfectRandom.Sulfur.Core;
using Ryuka.Sulfur.NativeUI;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[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 SulfurNoGore
{
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("com.henw.sulfurnogore", "Sulfur No Gore", "1.0.3")]
	public class Plugin : BaseUnityPlugin
	{
		private sealed class Group
		{
			public string Label;

			public string Description;

			public (string type, string method)[] Targets;

			public ConfigEntry<bool> Entry;
		}

		internal static ManualLogSource Log;

		private static readonly Group[] Groups = new Group[5]
		{
			new Group
			{
				Label = "Blood splatters",
				Description = "Blood sprays and splashes when something is hit.",
				Targets = new(string, string)[5]
				{
					("PerfectRandom.Sulfur.Gameplay.BloodProjectileSpawner", "CreateEffect"),
					("PerfectRandom.Sulfur.Gameplay.BloodProjectileSpawner", "TriggerEffect"),
					("PerfectRandom.Sulfur.Core.Effects.BloodSplafsEffect", "StartBloodSplaf"),
					("PerfectRandom.Sulfur.Core.Effects.BloodProjectileSystemNEW", "Spawn"),
					("PerfectRandom.Sulfur.Core.Units.Unit", "CreateBloodProjectiles")
				}
			},
			new Group
			{
				Label = "Blood stains",
				Description = "Blood left on the ground and walls.",
				Targets = new(string, string)[1] { ("PerfectRandom.Sulfur.Core.Effects.BloodProjectileSystemNEW", "SpawnDecal") }
			},
			new Group
			{
				Label = "Gibs and body chunks",
				Description = "Chunks flying off when enemies die or explode.",
				Targets = new(string, string)[4]
				{
					("PerfectRandom.Sulfur.Core.Effects.GibSystemNEW", "Spawn"),
					("PerfectRandom.Sulfur.Core.Effects.GibSystemNEW", "SpawnGibSet"),
					("PerfectRandom.Sulfur.Core.Effects.GibSystemNEW", "SpawnGibSetForUnit"),
					("PerfectRandom.Sulfur.Core.Units.Npc", "SpawnGibExplosion")
				}
			},
			new Group
			{
				Label = "Hit effects and slash marks",
				Description = "The blood and slash marks shown when a unit takes damage. Turn this off if enemies freeze or you can't die.",
				Targets = new(string, string)[2]
				{
					("PerfectRandom.Sulfur.Core.Units.Unit", "CreateDamageEffects"),
					("PerfectRandom.Sulfur.Core.Units.Npc", "CreateDamageEffects")
				}
			},
			new Group
			{
				Label = "Bullet holes",
				Description = "Bullet-hole marks on enemies.",
				Targets = new(string, string)[1] { ("PerfectRandom.Sulfur.Core.Units.Npc", "DrawBulletHole") }
			}
		};

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<bool> BrownBlood;

		internal static ConfigEntry<bool> HideCorpses;

		private static Type _bakedHolesType;

		private static readonly HashSet<GameObject> HiddenCorpses = new HashSet<GameObject>();

		internal static ConfigEntry<bool> HideProjected;

		private static readonly HashSet<GameObject> HiddenProjected = new HashSet<GameObject>();

		private static readonly Color BloodRedLow = new Color(0.5882353f, 9f / 85f, 0.11764706f);

		private static readonly Color BloodRedHigh = new Color(0.64f, 0.11f, 0.13f);

		private static readonly Color Brown = new Color(0.4f, 0.27f, 0.16f);

		private const float ColorTolerance = 0.01f;

		private static readonly List<Action> Restores = new List<Action>();

		private static readonly HashSet<object> Scanned = new HashSet<object>();

		private static readonly Dictionary<Type, FieldInfo[]> FieldCache = new Dictionary<Type, FieldInfo[]>();

		private static readonly Dictionary<MethodBase, ConfigEntry<bool>> Switches = new Dictionary<MethodBase, ConfigEntry<bool>>();

		private void Awake()
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Expected O, but got Unknown
			//IL_02fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Expected O, but got Unknown
			//IL_04e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_04eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0501: Unknown result type (might be due to invalid IL or missing references)
			//IL_050c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0531: Unknown result type (might be due to invalid IL or missing references)
			//IL_0548: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enable mod", true, "Master switch for every effect below.");
			HideProjected = ((BaseUnityPlugin)this).Config.Bind<bool>("Effects", "Level blood decals", true, "Hides the blood decals placed around level decorations such as graveyards (ProjectedBlood).");
			HideCorpses = ((BaseUnityPlugin)this).Config.Bind<bool>("Effects", "Dead bodies", true, "Hides the pre-placed dead bodies (Man Corpse) that decorate levels.");
			BrownBlood = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Brown blood", true, "Any colour or material in the game's blood-red range is changed to dirt brown.");
			Harmony val = new Harmony("com.henw.sulfurnogore");
			HarmonyMethod val2 = new HarmonyMethod(typeof(Plugin).GetMethod("SkipOriginal", BindingFlags.Static | BindingFlags.NonPublic));
			int num = 0;
			Group[] groups = Groups;
			foreach (Group obj in groups)
			{
				obj.Entry = ((BaseUnityPlugin)this).Config.Bind<bool>("Effects", obj.Label, true, obj.Description);
				(string, string)[] targets = obj.Targets;
				for (int j = 0; j < targets.Length; j++)
				{
					(string, string) tuple = targets[j];
					string item = tuple.Item1;
					string item2 = tuple.Item2;
					Type type = AccessTools.TypeByName(item);
					if (type == null)
					{
						Log.LogWarning((object)("Type not found: " + item));
						continue;
					}
					List<MethodBase> list = new List<MethodBase>();
					MethodInfo[] methods = type.GetMethods(AccessTools.all);
					foreach (MethodInfo methodInfo in methods)
					{
						if (methodInfo.Name == item2 && methodInfo.DeclaringType == type && !methodInfo.IsAbstract)
						{
							list.Add(methodInfo);
						}
					}
					if (list.Count == 0)
					{
						Log.LogWarning((object)("Method not found: " + item + "." + item2));
						continue;
					}
					foreach (MethodBase item3 in list)
					{
						try
						{
							val.Patch(item3, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
							Switches[item3] = obj.Entry;
							num++;
							Log.LogInfo((object)("Patched " + item + "." + item2 + " (" + obj.Label + ")"));
						}
						catch (Exception arg)
						{
							Log.LogError((object)$"Failed to patch {item}.{item2}: {arg}");
						}
					}
				}
			}
			Type type2 = AccessTools.TypeByName("PerfectRandom.Sulfur.Core.Units.Unit");
			MethodInfo methodInfo2 = ((type2 != null) ? AccessTools.PropertyGetter(type2, "currentBloodEffectData") : null);
			if (methodInfo2 != null)
			{
				val.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin).GetMethod("TintBlood", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				num++;
			}
			else
			{
				Log.LogWarning((object)"Unit.currentBloodEffectData getter not found, brown blood disabled");
			}
			Log.LogInfo((object)$"Sulfur No Gore loaded, {num} methods patched.");
			ApplyBrownBlood();
			SceneManager.sceneLoaded += OnSceneLoaded;
			foreach (Type item4 in AccessTools.AllTypes())
			{
				if (item4.Name == "BakedBulletHoles")
				{
					_bakedHolesType = item4;
					break;
				}
			}
			if (_bakedHolesType == null)
			{
				Log.LogWarning((object)"BakedBulletHoles type not found, dead bodies will not be hidden");
			}
			((MonoBehaviour)this).InvokeRepeating("HideCorpsesTick", 1f, 1f);
			((MonoBehaviour)this).InvokeRepeating("HideProjectedTick", 1.5f, 2f);
			HideProjected.SettingChanged += delegate
			{
				RefreshProjected();
			};
			Enabled.SettingChanged += delegate
			{
				RefreshProjected();
			};
			HideCorpses.SettingChanged += delegate
			{
				RefreshCorpses();
			};
			Enabled.SettingChanged += delegate
			{
				RefreshCorpses();
			};
			BrownBlood.SettingChanged += delegate
			{
				ApplyBrownBlood();
			};
			Enabled.SettingChanged += delegate
			{
				ApplyBrownBlood();
			};
			SulfurOptionsApi.RegisterPage(new SulfurOptionsPage
			{
				PageId = "com.henw.sulfurnogore",
				DisplayName = "No Gore",
				SortOrder = 1000,
				GetDisplayName = () => "No Gore",
				BuildPage = BuildPage
			});
		}

		private static bool SkipOriginal(MethodBase __originalMethod)
		{
			ConfigEntry<bool> value;
			return !Enabled.Value || (Switches.TryGetValue(__originalMethod, out value) && !value.Value);
		}

		private static void TintBlood(ref BloodEffectData __result)
		{
			if (!((Object)(object)__result == (Object)null) && Enabled.Value && BrownBlood.Value)
			{
				WalkColors(__result, 0);
			}
		}

		private static bool IsBloodRed(Color c)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: 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)
			if (InRange(c.r, BloodRedLow.r, BloodRedHigh.r) && InRange(c.g, BloodRedLow.g, BloodRedHigh.g))
			{
				return InRange(c.b, BloodRedLow.b, BloodRedHigh.b);
			}
			return false;
		}

		private static bool InRange(float v, float a, float b)
		{
			float num = Math.Min(a, b) - 0.01f;
			float num2 = Math.Max(a, b) + 0.01f;
			if (v >= num)
			{
				return v <= num2;
			}
			return false;
		}

		private static Color BrownWithAlpha(float alpha)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			return new Color(Brown.r, Brown.g, Brown.b, alpha);
		}

		private static bool IsGameType(Type t)
		{
			if (t != null && t.IsClass && !typeof(Object).IsAssignableFrom(t) && t.Namespace != null)
			{
				return t.Namespace.StartsWith("PerfectRandom");
			}
			return false;
		}

		private static bool ShouldDescend(Type t)
		{
			if (IsGameType(t))
			{
				return true;
			}
			if (t.IsArray)
			{
				return IsGameType(t.GetElementType());
			}
			if (t.IsGenericType && t.GetGenericArguments().Length == 1)
			{
				return IsGameType(t.GetGenericArguments()[0]);
			}
			return false;
		}

		private static FieldInfo[] FieldsOf(Type type)
		{
			if (FieldCache.TryGetValue(type, out var value))
			{
				return value;
			}
			List<FieldInfo> list = new List<FieldInfo>();
			Type type2 = type;
			while (type2 != null && type2 != typeof(object) && (type2.Namespace == null || !type2.Namespace.StartsWith("UnityEngine")))
			{
				list.AddRange(type2.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic));
				type2 = type2.BaseType;
			}
			FieldInfo[] array = list.ToArray();
			FieldCache[type] = array;
			return array;
		}

		private static void WalkColors(object obj, int depth)
		{
			//IL_0051: 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_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			if (obj == null || depth > 4 || !Scanned.Add(obj))
			{
				return;
			}
			FieldInfo[] array = FieldsOf(obj.GetType());
			foreach (FieldInfo fieldInfo in array)
			{
				try
				{
					if (fieldInfo.FieldType == typeof(Color))
					{
						Color c = (Color)fieldInfo.GetValue(obj);
						if (!IsBloodRed(c))
						{
							continue;
						}
						object target = obj;
						FieldInfo field = fieldInfo;
						field.SetValue(target, BrownWithAlpha(c.a));
						Restores.Add(delegate
						{
							//IL_0026: Unknown result type (might be due to invalid IL or missing references)
							object obj2 = target;
							Object val = (Object)((obj2 is Object) ? obj2 : null);
							if (val == null || !(val == (Object)null))
							{
								field.SetValue(target, c);
							}
						});
						continue;
					}
					if (!ShouldDescend(fieldInfo.FieldType))
					{
						continue;
					}
					object value = fieldInfo.GetValue(obj);
					if (value is IEnumerable enumerable)
					{
						foreach (object item in enumerable)
						{
							WalkColors(item, depth + 1);
						}
					}
					else
					{
						WalkColors(value, depth + 1);
					}
				}
				catch (Exception ex)
				{
					Log.LogDebug((object)("Colour scan skipped " + obj.GetType().Name + "." + fieldInfo.Name + ": " + ex.Message));
				}
			}
		}

		private static void RecolorMaterial(Material m)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: 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_0077: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)m == (Object)null || (Object)(object)m.shader == (Object)null)
			{
				return;
			}
			Shader shader = m.shader;
			int propertyCount = shader.GetPropertyCount();
			for (int i = 0; i < propertyCount; i++)
			{
				if ((int)shader.GetPropertyType(i) != 0)
				{
					continue;
				}
				string name = shader.GetPropertyName(i);
				Color c = m.GetColor(name);
				if (!IsBloodRed(c))
				{
					continue;
				}
				m.SetColor(name, BrownWithAlpha(c.a));
				Material mat = m;
				Restores.Add(delegate
				{
					//IL_001b: Unknown result type (might be due to invalid IL or missing references)
					if ((Object)(object)mat != (Object)null)
					{
						mat.SetColor(name, c);
					}
				});
			}
		}

		private static void ScanAll()
		{
			ScriptableObject[] array = Resources.FindObjectsOfTypeAll<ScriptableObject>();
			foreach (ScriptableObject val in array)
			{
				if ((Object)(object)val != (Object)null && IsGameNamespace(((object)val).GetType()))
				{
					WalkColors(val, 0);
				}
			}
			MonoBehaviour[] array2 = Resources.FindObjectsOfTypeAll<MonoBehaviour>();
			foreach (MonoBehaviour val2 in array2)
			{
				if ((Object)(object)val2 != (Object)null && IsGameNamespace(((object)val2).GetType()))
				{
					WalkColors(val2, 0);
				}
			}
			Material[] array3 = Resources.FindObjectsOfTypeAll<Material>();
			foreach (Material m in array3)
			{
				try
				{
					RecolorMaterial(m);
				}
				catch (Exception ex)
				{
					Log.LogDebug((object)("Material scan skipped: " + ex.Message));
				}
			}
			Log.LogInfo((object)$"Brown blood: {Restores.Count} colours recoloured.");
		}

		private static bool IsGameNamespace(Type t)
		{
			if (t.Namespace != null)
			{
				return t.Namespace.StartsWith("PerfectRandom");
			}
			return false;
		}

		private static void ApplyBrownBlood()
		{
			foreach (Action restore in Restores)
			{
				try
				{
					restore();
				}
				catch
				{
				}
			}
			Restores.Clear();
			Scanned.Clear();
			if (Enabled.Value && BrownBlood.Value)
			{
				ScanAll();
			}
		}

		private void HideCorpsesTick()
		{
			HideCorpsesNow();
		}

		private static void RefreshCorpses()
		{
			if (Enabled.Value && HideCorpses.Value)
			{
				HideCorpsesNow();
			}
			else
			{
				RestoreCorpses();
			}
		}

		private static void HideCorpsesNow()
		{
			HiddenCorpses.RemoveWhere((GameObject g) => (Object)(object)g == (Object)null);
			if (!Enabled.Value || !HideCorpses.Value || _bakedHolesType == null)
			{
				return;
			}
			Object[] array = Object.FindObjectsOfType(_bakedHolesType);
			foreach (Object obj in array)
			{
				Component val = (Component)(object)((obj is Component) ? obj : null);
				if (!((Object)(object)val == (Object)null))
				{
					GameObject gameObject = val.gameObject;
					if (((Object)gameObject).name.StartsWith("Man Corpse") && HiddenCorpses.Add(gameObject))
					{
						gameObject.SetActive(false);
					}
				}
			}
		}

		private void HideProjectedTick()
		{
			HideProjectedNow();
		}

		private static void RefreshProjected()
		{
			if (Enabled.Value && HideProjected.Value)
			{
				HideProjectedNow();
			}
			else
			{
				RestoreProjected();
			}
		}

		private static void HideProjectedNow()
		{
			HiddenProjected.RemoveWhere((GameObject g) => (Object)(object)g == (Object)null);
			if (!Enabled.Value || !HideProjected.Value)
			{
				return;
			}
			Transform[] array = Object.FindObjectsOfType<Transform>();
			foreach (Transform val in array)
			{
				if (!((Object)(object)val == (Object)null))
				{
					GameObject gameObject = ((Component)val).gameObject;
					if (((Object)gameObject).name.StartsWith("ProjectedBlood") && HiddenProjected.Add(gameObject))
					{
						gameObject.SetActive(false);
					}
				}
			}
		}

		private static void RestoreProjected()
		{
			foreach (GameObject item in HiddenProjected)
			{
				if ((Object)(object)item != (Object)null)
				{
					item.SetActive(true);
				}
			}
			HiddenProjected.Clear();
		}

		private static void RestoreCorpses()
		{
			foreach (GameObject hiddenCorpse in HiddenCorpses)
			{
				if ((Object)(object)hiddenCorpse != (Object)null)
				{
					hiddenCorpse.SetActive(true);
				}
			}
			HiddenCorpses.Clear();
		}

		private static void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			if (Enabled.Value && BrownBlood.Value)
			{
				ScanAll();
			}
		}

		private void OnDestroy()
		{
			SceneManager.sceneLoaded -= OnSceneLoaded;
			SulfurOptionsApi.UnregisterPage("com.henw.sulfurnogore");
		}

		private void BuildPage(SulfurOptionsContext ctx)
		{
			ctx.AddSection("No Gore");
			ctx.AddDescription("Choose which kinds of gore to remove. Changes apply immediately.");
			AddToggle(ctx, Enabled, "Enable mod", "Master switch for everything below.");
			AddToggle(ctx, BrownBlood, "Brown blood", "Any colour or material in the game's blood-red range is changed to dirt brown.");
			ctx.AddSection("Effects to remove");
			Group[] groups = Groups;
			foreach (Group obj in groups)
			{
				AddToggle(ctx, obj.Entry, obj.Label, obj.Description);
			}
			AddToggle(ctx, HideProjected, "Level blood decals", "Hides the blood decals placed around level decorations such as graveyards (ProjectedBlood).");
			AddToggle(ctx, HideCorpses, "Dead bodies", "Hides the pre-placed dead bodies (Man Corpse) that decorate levels.");
		}

		private static void AddToggle(SulfurOptionsContext ctx, ConfigEntry<bool> entry, string label, string description)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			SulfurSettingRow val = new SulfurSettingRow
			{
				Label = label,
				Description = description
			};
			SulfurOptionsSettingRows.AddSettingToggle(ctx, val, entry.Value, (Action<bool>)delegate(bool v)
			{
				entry.Value = v;
			});
		}
	}
}