Decompiled source of Internal Error v1.0.0

InternalError.dll

Decompiled 2 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
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 UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("")]
[assembly: AssemblyCompany("Omniscye")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("InternalError")]
[assembly: AssemblyTitle("InternalError")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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 Empress.RepoMods.ShaderShenanigans
{
	[BepInPlugin("empress.repo.shader-shenanigans", "ShaderShenanigans", "1.0.0")]
	public class ShaderShenanigansPlugin : BaseUnityPlugin
	{
		public enum ModeOption
		{
			NonePink,
			CursedUnlit
		}

		[CompilerGenerated]
		private sealed class <GetAllRenderable>d__22 : IEnumerable<Renderer>, IEnumerable, IEnumerator<Renderer>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private Renderer <>2__current;

			private int <>l__initialThreadId;

			public ShaderShenanigansPlugin <>4__this;

			private Renderer[] <renderers>5__1;

			private Renderer[] <>s__2;

			private int <>s__3;

			private Renderer <r>5__4;

			Renderer IEnumerator<Renderer>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <GetAllRenderable>d__22(int <>1__state)
			{
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<renderers>5__1 = null;
				<>s__2 = null;
				<r>5__4 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				int num = <>1__state;
				if (num != 0)
				{
					if (num != 1)
					{
						return false;
					}
					<>1__state = -1;
					<r>5__4 = null;
					goto IL_00be;
				}
				<>1__state = -1;
				<renderers>5__1 = Resources.FindObjectsOfTypeAll<Renderer>();
				<>s__2 = <renderers>5__1;
				<>s__3 = 0;
				goto IL_00cc;
				IL_00be:
				<>s__3++;
				goto IL_00cc;
				IL_00cc:
				if (<>s__3 < <>s__2.Length)
				{
					<r>5__4 = <>s__2[<>s__3];
					if ((Object)(object)<r>5__4 == (Object)null || <>4__this._ignoredRenderers.Contains(<r>5__4) || IsUIOrShouldIgnore(<r>5__4))
					{
						goto IL_00be;
					}
					<>2__current = <r>5__4;
					<>1__state = 1;
					return true;
				}
				<>s__2 = null;
				return false;
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			IEnumerator<Renderer> IEnumerable<Renderer>.GetEnumerator()
			{
				<GetAllRenderable>d__22 result;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					result = this;
				}
				else
				{
					result = new <GetAllRenderable>d__22(0)
					{
						<>4__this = <>4__this
					};
				}
				return result;
			}

			[DebuggerHidden]
			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable<Renderer>)this).GetEnumerator();
			}
		}

		public const string PluginGuid = "empress.repo.shader-shenanigans";

		public const string PluginName = "ShaderShenanigans";

		public const string PluginVersion = "1.0.0";

		private static ManualLogSource _log;

		private ConfigEntry<ModeOption> _mode;

		private ConfigEntry<bool> _applyOnSceneLoad;

		private ConfigEntry<bool> _autoReapplyEachLoadCycle;

		private ConfigEntry<bool> _touchSkybox;

		private ConfigEntry<bool> _duplicateMaterialsPerRenderer;

		private ConfigEntry<KeyboardShortcut> _applyHotkey;

		private ConfigEntry<KeyboardShortcut> _restoreHotkey;

		private readonly Dictionary<Material, Shader> _originalShaders = new Dictionary<Material, Shader>(256);

		private readonly HashSet<Renderer> _ignoredRenderers = new HashSet<Renderer>();

		private Material _savedSkybox;

		private Shader _errorShader;

		private Shader _unlitColorShader;

		private void Awake()
		{
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			_log = ((BaseUnityPlugin)this).Logger;
			_mode = ((BaseUnityPlugin)this).Config.Bind<ModeOption>("General", "Mode", ModeOption.NonePink, "NonePink: everything turns hot-pink (Hidden/InternalErrorShader). CursedUnlit: everything becomes Unlit/Color with randomized tints.");
			_applyOnSceneLoad = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ApplyOnSceneLoad", true, "Apply automatically each time a scene finishes loading.");
			_autoReapplyEachLoadCycle = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ReapplyAfterRestore", false, "If true, re-apply on each scene load even if you restored previously.");
			_touchSkybox = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "AffectSkybox", false, "If true, also replace RenderSettings.skybox.");
			_duplicateMaterialsPerRenderer = ((BaseUnityPlugin)this).Config.Bind<bool>("Advanced", "DuplicatePerRenderer", false, "If true, swaps operate on per-renderer material instances (renderer.materials) instead of shared materials. Costs memory, but isolates effects.");
			_applyHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "ApplyHotkey", new KeyboardShortcut((KeyCode)288, Array.Empty<KeyCode>()), "Press to apply shader swap to the current scene.");
			_restoreHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "RestoreHotkey", new KeyboardShortcut((KeyCode)289, Array.Empty<KeyCode>()), "Press to restore all original shaders.");
			SceneManager.sceneLoaded += OnSceneLoaded;
			_errorShader = Shader.Find("Hidden/InternalErrorShader");
			_unlitColorShader = Shader.Find("Unlit/Color");
			if ((Object)(object)_errorShader == (Object)null)
			{
				_log.LogWarning((object)"Hidden/InternalErrorShader not found (unexpected). Pink mode may not work on this Unity build.");
			}
			if ((Object)(object)_unlitColorShader == (Object)null)
			{
				_log.LogWarning((object)"Unlit/Color not found. CursedUnlit will try Unlit/Texture as fallback.");
			}
		}

		private void OnDestroy()
		{
			SceneManager.sceneLoaded -= OnSceneLoaded;
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			if (_applyOnSceneLoad.Value)
			{
				try
				{
					Apply();
				}
				catch (Exception arg)
				{
					_log.LogError((object)$"Apply on scene load failed: {arg}");
				}
			}
		}

		private void Update()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: 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_002c: Unknown result type (might be due to invalid IL or missing references)
			KeyboardShortcut value = _applyHotkey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				Apply();
			}
			value = _restoreHotkey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				Restore();
			}
		}

		private static bool IsUIOrShouldIgnore(Renderer r)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Invalid comparison between Unknown and I4
			if ((Object)(object)r == (Object)null)
			{
				return true;
			}
			if ((((Object)r).hideFlags & 1) > 0)
			{
				return true;
			}
			if (!((Component)r).gameObject.activeInHierarchy)
			{
				return true;
			}
			if ((Object)(object)((Component)r).GetComponentInParent<Canvas>(true) != (Object)null)
			{
				return true;
			}
			return false;
		}

		[IteratorStateMachine(typeof(<GetAllRenderable>d__22))]
		private IEnumerable<Renderer> GetAllRenderable()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <GetAllRenderable>d__22(-2)
			{
				<>4__this = this
			};
		}

		private void Apply()
		{
			//IL_025e: Unknown result type (might be due to invalid IL or missing references)
			int num = 0;
			int num2 = 0;
			foreach (Renderer item in GetAllRenderable())
			{
				try
				{
					Material[] array = (_duplicateMaterialsPerRenderer.Value ? item.materials : item.sharedMaterials);
					if (array == null || array.Length == 0)
					{
						continue;
					}
					foreach (Material val in array)
					{
						if ((Object)(object)val == (Object)null)
						{
							continue;
						}
						if (!_originalShaders.ContainsKey(val))
						{
							_originalShaders[val] = val.shader;
						}
						switch (_mode.Value)
						{
						case ModeOption.NonePink:
							if ((Object)(object)_errorShader != (Object)null)
							{
								val.shader = _errorShader;
							}
							break;
						case ModeOption.CursedUnlit:
							ApplyUnlitCursed(val);
							break;
						}
						num++;
					}
					if (_duplicateMaterialsPerRenderer.Value)
					{
						item.materials = array;
					}
					num2++;
				}
				catch (Exception ex)
				{
					_ignoredRenderers.Add(item);
					_log.LogWarning((object)("Renderer " + ((Object)item).name + " caused an exception and will be ignored this session: " + ex.Message));
				}
			}
			if (_touchSkybox.Value)
			{
				try
				{
					if ((Object)(object)_savedSkybox == (Object)null)
					{
						_savedSkybox = RenderSettings.skybox;
					}
					if ((Object)(object)_savedSkybox != (Object)null)
					{
						switch (_mode.Value)
						{
						case ModeOption.NonePink:
							if ((Object)(object)_errorShader != (Object)null)
							{
								_savedSkybox.shader = _errorShader;
							}
							break;
						case ModeOption.CursedUnlit:
							if ((Object)(object)_unlitColorShader != (Object)null)
							{
								_savedSkybox.shader = _unlitColorShader;
								if (_savedSkybox.HasProperty("_Color"))
								{
									_savedSkybox.SetColor("_Color", Random.ColorHSV());
								}
							}
							else
							{
								Shader val2 = Shader.Find("Unlit/Texture");
								if ((Object)(object)val2 != (Object)null)
								{
									_savedSkybox.shader = val2;
								}
							}
							break;
						}
						RenderSettings.skybox = _savedSkybox;
					}
				}
				catch (Exception ex2)
				{
					_log.LogWarning((object)("Skybox swap failed: " + ex2.Message));
				}
			}
			_log.LogInfo((object)$"ShaderShenanigans applied. Renderers: {num2}, Materials touched: {num}. Mode={_mode.Value}");
		}

		private void ApplyUnlitCursed(Material m)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)m == (Object)null)
			{
				return;
			}
			if ((Object)(object)_unlitColorShader != (Object)null)
			{
				m.shader = _unlitColorShader;
				if (m.HasProperty("_Color"))
				{
					m.SetColor("_Color", Random.ColorHSV(0f, 1f, 0.6f, 1f, 0.6f, 1f));
				}
			}
			else
			{
				Shader val = Shader.Find("Unlit/Texture");
				if ((Object)(object)val != (Object)null)
				{
					m.shader = val;
				}
			}
		}

		private void Restore()
		{
			int num = 0;
			KeyValuePair<Material, Shader>[] array = _originalShaders.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				KeyValuePair<Material, Shader> keyValuePair = array[i];
				Material key = keyValuePair.Key;
				Shader value = keyValuePair.Value;
				if (!((Object)(object)key == (Object)null))
				{
					try
					{
						key.shader = value;
						num++;
					}
					catch (Exception ex)
					{
						_log.LogWarning((object)("Failed to restore material " + ((Object)key).name + ": " + ex.Message));
					}
				}
			}
			_originalShaders.Clear();
			if (_touchSkybox.Value && (Object)(object)_savedSkybox != (Object)null)
			{
				try
				{
					RenderSettings.skybox = _savedSkybox;
				}
				catch (Exception ex2)
				{
					_log.LogWarning((object)("Failed to restore skybox: " + ex2.Message));
				}
			}
			_log.LogInfo((object)$"ShaderShenanigans restored {num} materials.");
		}
	}
}
namespace InternalError
{
	[BepInPlugin("Omniscye.InternalError", "InternalError", "1.0")]
	public class InternalError : BaseUnityPlugin
	{
		internal static InternalError Instance { get; private set; }

		internal static ManualLogSource Logger => Instance._logger;

		private ManualLogSource _logger => ((BaseUnityPlugin)this).Logger;

		internal Harmony? Harmony { get; set; }

		private void Awake()
		{
			Instance = this;
			((Component)this).gameObject.transform.parent = null;
			((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
			Patch();
			Logger.LogInfo((object)$"{((BaseUnityPlugin)this).Info.Metadata.GUID} v{((BaseUnityPlugin)this).Info.Metadata.Version} has loaded!");
		}

		internal void Patch()
		{
			//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_0021: Expected O, but got Unknown
			//IL_0026: Expected O, but got Unknown
			if (Harmony == null)
			{
				Harmony val = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID);
				Harmony val2 = val;
				Harmony = val;
			}
			Harmony.PatchAll();
		}

		internal void Unpatch()
		{
			Harmony? harmony = Harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		private void Update()
		{
		}
	}
}