Decompiled source of ColorfulPortals v1.8.0

ColorfulPortals.dll

Decompiled 10 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ComfyLib;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("ColorfulPortals")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ColorfulPortals")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("77bcdd82-4a30-4874-adba-3b9dd9dd6ccb")]
[assembly: AssemblyFileVersion("1.8.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.8.0.0")]
[module: UnverifiableCode]
namespace ComfyLib
{
	public static class ConfigFileExtensions
	{
		internal sealed class ConfigurationManagerAttributes
		{
			public Action<ConfigEntryBase> CustomDrawer;

			public bool? Browsable;

			public bool? HideDefaultButton;

			public int? Order;
		}

		private static readonly Dictionary<string, int> _sectionToSettingOrder = new Dictionary<string, int>();

		private static int GetSettingOrder(string section)
		{
			if (!_sectionToSettingOrder.TryGetValue(section, out var value))
			{
				value = 0;
			}
			_sectionToSettingOrder[section] = value - 1;
			return value;
		}

		public static ConfigEntry<T> BindInOrder<T>(this ConfigFile config, string section, string key, T defaultValue, string description, AcceptableValueBase acceptableValues)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			return config.Bind<T>(section, key, defaultValue, new ConfigDescription(description, acceptableValues, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = GetSettingOrder(section)
				}
			}));
		}

		public static ConfigEntry<T> BindInOrder<T>(this ConfigFile config, string section, string key, T defaultValue, string description, Action<ConfigEntryBase> customDrawer = null, bool browsable = true, bool hideDefaultButton = false, bool hideSettingName = false)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			return config.Bind<T>(section, key, defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Browsable = browsable,
					CustomDrawer = customDrawer,
					HideDefaultButton = hideDefaultButton,
					Order = GetSettingOrder(section)
				}
			}));
		}

		public static void OnSettingChanged<T>(this ConfigEntry<T> configEntry, Action settingChangedHandler)
		{
			configEntry.SettingChanged += delegate
			{
				settingChangedHandler();
			};
		}

		public static void OnSettingChanged<T>(this ConfigEntry<T> configEntry, Action<T> settingChangedHandler)
		{
			configEntry.SettingChanged += delegate(object _, EventArgs eventArgs)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				settingChangedHandler((T)((SettingChangedEventArgs)eventArgs).ChangedSetting.BoxedValue);
			};
		}

		public static void OnSettingChanged<T>(this ConfigEntry<T> configEntry, Action<ConfigEntry<T>> settingChangedHandler)
		{
			configEntry.SettingChanged += delegate(object _, EventArgs eventArgs)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				settingChangedHandler((ConfigEntry<T>)((SettingChangedEventArgs)eventArgs).ChangedSetting.BoxedValue);
			};
		}
	}
	public sealed class ExtendedColorConfigEntry
	{
		private static readonly Texture2D _colorTexture = GUIBuilder.CreateColorTexture(10, 10, Color.white);

		private readonly HexColorTextField _hexInput = new HexColorTextField();

		private readonly ColorPalette _colorPalette;

		private bool _showSliders;

		public ConfigEntry<Color> ConfigEntry { get; }

		public Color Value { get; private set; }

		public ColorFloatTextField RedInput { get; } = new ColorFloatTextField("R");


		public ColorFloatTextField GreenInput { get; } = new ColorFloatTextField("G");


		public ColorFloatTextField BlueInput { get; } = new ColorFloatTextField("B");


		public ColorFloatTextField AlphaInput { get; } = new ColorFloatTextField("A");


		public ExtendedColorConfigEntry(ConfigFile config, string section, string key, Color defaultValue, string description)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			ConfigEntry = config.BindInOrder<Color>(section, key, defaultValue, description, Drawer, browsable: true, hideDefaultButton: false, hideSettingName: false);
			SetValue(ConfigEntry.Value);
		}

		public ExtendedColorConfigEntry(ConfigFile config, string section, string key, Color defaultValue, string description, string colorPaletteKey)
			: this(config, section, key, defaultValue, description)
		{
			//IL_0004: 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)
			ConfigEntry<string> paletteConfigEntry = config.BindInOrder(section, colorPaletteKey, ColorUtility.ToHtmlStringRGBA(defaultValue) + ",FF0000FF,00FF00FF,0000FFFF", "Color palette for: [" + section + "] " + key, null, browsable: false);
			_colorPalette = new ColorPalette(this, paletteConfigEntry);
		}

		public void SetValue(Color value)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: 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_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: 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_005d: Unknown result type (might be due to invalid IL or missing references)
			ConfigEntry.Value = value;
			Value = value;
			RedInput.SetValue(value.r);
			GreenInput.SetValue(value.g);
			BlueInput.SetValue(value.b);
			AlphaInput.SetValue(value.a);
			_hexInput.SetValue(value);
		}

		public void Drawer(ConfigEntryBase configEntry)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Invalid comparison between Unknown and I4
			//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)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b7: 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_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			Color val = (Color)configEntry.BoxedValue;
			if (GUIFocus.HasChanged() || GUIHelper.IsEnterPressed() || Value != val)
			{
				SetValue(val);
			}
			GUILayout.BeginVertical(GUI.skin.box, Array.Empty<GUILayoutOption>());
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			_hexInput.DrawField();
			GUILayout.Space(3f);
			GUIHelper.BeginColor(val);
			GUILayout.Label(string.Empty, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
			if ((int)Event.current.type == 7)
			{
				GUI.DrawTexture(GUILayoutUtility.GetLastRect(), (Texture)(object)_colorTexture);
			}
			GUIHelper.EndColor();
			GUILayout.Space(3f);
			if (GUILayout.Button(_showSliders ? "∨" : "≡", (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.MinWidth(40f),
				GUILayout.ExpandWidth(false)
			}))
			{
				_showSliders = !_showSliders;
			}
			GUILayout.EndHorizontal();
			if (_showSliders)
			{
				GUILayout.Space(4f);
				GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
				RedInput.DrawField();
				GUILayout.Space(3f);
				GreenInput.DrawField();
				GUILayout.Space(3f);
				BlueInput.DrawField();
				GUILayout.Space(3f);
				AlphaInput.DrawField();
				GUILayout.EndHorizontal();
			}
			if (_colorPalette != null)
			{
				GUILayout.Space(5f);
				_colorPalette.DrawColorPalette();
			}
			GUILayout.EndVertical();
			Color val2 = default(Color);
			((Color)(ref val2))..ctor(RedInput.CurrentValue, GreenInput.CurrentValue, BlueInput.CurrentValue, AlphaInput.CurrentValue);
			if (val2 != val)
			{
				configEntry.BoxedValue = val2;
				SetValue(val2);
			}
			else if (_hexInput.CurrentValue != val)
			{
				configEntry.BoxedValue = _hexInput.CurrentValue;
				SetValue(_hexInput.CurrentValue);
			}
		}
	}
	public sealed class ColorPalette
	{
		private static readonly char[] _partSeparator = new char[1] { ',' };

		private static readonly string _partJoiner = ",";

		private static readonly Texture2D _colorTexture = GUIBuilder.CreateColorTexture(10, 10, Color.white);

		private readonly ExtendedColorConfigEntry _colorConfigEntry;

		private readonly ConfigEntry<string> _paletteConfigEntry;

		private readonly List<Color> _paletteColors;

		public ColorPalette(ExtendedColorConfigEntry colorConfigEntry, ConfigEntry<string> paletteConfigEntry)
		{
			_colorConfigEntry = colorConfigEntry;
			_paletteConfigEntry = paletteConfigEntry;
			_paletteColors = new List<Color>();
			LoadPalette();
		}

		private void LoadPalette()
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			_paletteColors.Clear();
			string[] array = _paletteConfigEntry.Value.Split(_partSeparator, StringSplitOptions.RemoveEmptyEntries);
			Color item = default(Color);
			foreach (string text in array)
			{
				if (ColorUtility.TryParseHtmlString("#" + text, ref item))
				{
					_paletteColors.Add(item);
				}
			}
		}

		private void SavePalette()
		{
			((ConfigEntryBase)_paletteConfigEntry).BoxedValue = string.Join(_partJoiner, _paletteColors.Select((Color color) => ColorUtility.ToHtmlStringRGBA(color)));
		}

		private bool PaletteColorButtons(out int colorIndex)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			Texture2D background = GUI.skin.button.normal.background;
			GUI.skin.button.normal.background = _colorTexture;
			colorIndex = -1;
			for (int i = 0; i < _paletteColors.Count; i++)
			{
				GUIHelper.BeginColor(_paletteColors[i]);
				if (GUILayout.Button(string.Empty, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(20f) }))
				{
					colorIndex = i;
				}
				GUIHelper.EndColor();
			}
			GUI.skin.button.normal.background = background;
			return colorIndex >= 0;
		}

		private bool AddColorButton()
		{
			return GUILayout.Button("+", (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.MinWidth(25f),
				GUILayout.ExpandWidth(false)
			});
		}

		private bool RemoveColorButton()
		{
			return GUILayout.Button("−", (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.MinWidth(25f),
				GUILayout.ExpandWidth(false)
			});
		}

		private bool ResetColorsButton()
		{
			return GUILayout.Button("❇", (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.MinWidth(25f),
				GUILayout.ExpandWidth(false)
			});
		}

		public void DrawColorPalette()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			if (AddColorButton())
			{
				_paletteColors.Add(_colorConfigEntry.Value);
				SavePalette();
			}
			GUILayout.Space(2f);
			if (PaletteColorButtons(out var colorIndex))
			{
				if (Event.current.button == 0)
				{
					_colorConfigEntry.SetValue(_paletteColors[colorIndex]);
				}
				else if (Event.current.button == 1 && colorIndex >= 0 && colorIndex < _paletteColors.Count)
				{
					_paletteColors.RemoveAt(colorIndex);
					SavePalette();
				}
			}
			GUILayout.FlexibleSpace();
			if (_paletteColors.Count > 0)
			{
				if (RemoveColorButton())
				{
					_paletteColors.RemoveAt(_paletteColors.Count - 1);
					SavePalette();
				}
			}
			else if (ResetColorsButton())
			{
				((ConfigEntryBase)_paletteConfigEntry).BoxedValue = ((ConfigEntryBase)_paletteConfigEntry).DefaultValue;
				LoadPalette();
			}
			GUILayout.EndHorizontal();
		}
	}
	public sealed class ColorFloatTextField
	{
		private string _fieldText;

		private Color _fieldColor;

		public string Label { get; set; }

		public float CurrentValue { get; private set; }

		public float MinValue { get; private set; }

		public float MaxValue { get; private set; }

		public void SetValue(float value)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			CurrentValue = Mathf.Clamp(value, MinValue, MaxValue);
			_fieldText = value.ToString("F3", CultureInfo.InvariantCulture);
			_fieldColor = GUI.color;
		}

		public void SetValueRange(float minValue, float maxValue)
		{
			MinValue = Mathf.Min(minValue, minValue);
			MaxValue = Mathf.Max(maxValue, maxValue);
		}

		public ColorFloatTextField(string label)
		{
			Label = label;
			SetValueRange(0f, 1f);
		}

		public void DrawField()
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginVertical(Array.Empty<GUILayoutOption>());
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label(Label, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
			GUIHelper.BeginColor(_fieldColor);
			string text = GUILayout.TextField(_fieldText, (GUILayoutOption[])(object)new GUILayoutOption[3]
			{
				GUILayout.MinWidth(45f),
				GUILayout.MaxWidth(55f),
				GUILayout.ExpandWidth(true)
			});
			GUIHelper.EndColor();
			GUILayout.EndHorizontal();
			GUILayout.Space(2f);
			float num = GUILayout.HorizontalSlider(CurrentValue, MinValue, MaxValue, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
			GUILayout.EndVertical();
			if (num != CurrentValue)
			{
				SetValue(num);
			}
			else if (!(text == _fieldText))
			{
				if (float.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out var result) && result >= MinValue && result <= MaxValue)
				{
					CurrentValue = result;
					_fieldColor = GUI.color;
				}
				else
				{
					_fieldColor = Color.red;
				}
				_fieldText = text;
			}
		}
	}
	public sealed class HexColorTextField
	{
		private Color _textColor = GUI.color;

		public Color CurrentValue { get; private set; }

		public string CurrentText { get; private set; }

		public void SetValue(Color value)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: 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)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: 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)
			CurrentValue = value;
			CurrentText = "#" + ((value.a == 1f) ? ColorUtility.ToHtmlStringRGB(value) : ColorUtility.ToHtmlStringRGBA(value));
			_textColor = GUI.color;
		}

		public void DrawField()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: 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)
			GUIHelper.BeginColor(_textColor);
			string text = GUILayout.TextField(CurrentText, (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.Width(90f),
				GUILayout.ExpandWidth(false)
			});
			GUIHelper.EndColor();
			if (!(text == CurrentText))
			{
				CurrentText = text;
				Color currentValue = default(Color);
				if (ColorUtility.TryParseHtmlString(text, ref currentValue))
				{
					CurrentValue = currentValue;
				}
				else
				{
					_textColor = Color.red;
				}
			}
		}
	}
	public static class GUIBuilder
	{
		public static Texture2D CreateColorTexture(int width, int height, Color color)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			return CreateColorTexture(width, height, color, 0, color);
		}

		public static Texture2D CreateColorTexture(int width, int height, Color color, int radius, Color outsideColor)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			if (width <= 0 || height <= 0)
			{
				throw new ArgumentException("Texture width and height must be > 0.");
			}
			if (radius < 0 || radius > width || radius > height)
			{
				throw new ArgumentException("Texture radius must be >= 0 and < width/height.");
			}
			Texture2D val = new Texture2D(width, height, (TextureFormat)5, false);
			((Object)val).name = $"w-{width}-h-{height}-rad-{radius}-color-{ColorId(color)}-ocolor-{ColorId(outsideColor)}";
			((Texture)val).wrapMode = (TextureWrapMode)1;
			((Texture)val).filterMode = (FilterMode)2;
			Color[] array = (Color[])(object)new Color[width * height];
			for (int i = 0; i < height; i++)
			{
				for (int j = 0; j < width; j++)
				{
					array[i * width + j] = (IsCornerPixel(j, i, width, height, radius) ? outsideColor : color);
				}
			}
			val.SetPixels(array);
			val.Apply();
			return val;
		}

		private static string ColorId(Color color)
		{
			//IL_000d: 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_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			return $"{color.r:F3}r-{color.g:F3}g-{color.b:F3}b-{color.a:F3}a";
		}

		private static bool IsCornerPixel(int x, int y, int w, int h, int rad)
		{
			if (rad == 0)
			{
				return false;
			}
			int num = Math.Min(x, w - x);
			int num2 = Math.Min(y, h - y);
			if (num == 0 && num2 == 0)
			{
				return true;
			}
			if (num > rad || num2 > rad)
			{
				return false;
			}
			num = rad - num;
			num2 = rad - num2;
			return Math.Round(Math.Sqrt(num * num + num2 * num2)) > (double)rad;
		}
	}
	public static class GUIFocus
	{
		private static int _lastFrameCount;

		private static int _lastHotControl;

		private static int _lastKeyboardControl;

		private static bool _hasChanged;

		public static bool HasChanged()
		{
			int frameCount = Time.frameCount;
			if (_lastFrameCount == frameCount)
			{
				return _hasChanged;
			}
			_lastFrameCount = frameCount;
			int hotControl = GUIUtility.hotControl;
			int keyboardControl = GUIUtility.keyboardControl;
			_hasChanged = hotControl != _lastHotControl || keyboardControl != _lastKeyboardControl;
			if (_hasChanged)
			{
				_lastHotControl = hotControl;
				_lastKeyboardControl = keyboardControl;
			}
			return _hasChanged;
		}
	}
	public static class GUIHelper
	{
		private static readonly Stack<Color> _colorStack = new Stack<Color>();

		public static void BeginColor(Color color)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			_colorStack.Push(GUI.color);
			GUI.color = color;
		}

		public static void EndColor()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			GUI.color = _colorStack.Pop();
		}

		public static bool IsEnterPressed()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Invalid comparison between Unknown and I4
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Invalid comparison between Unknown and I4
			if (Event.current.isKey)
			{
				if ((int)Event.current.keyCode != 13)
				{
					return (int)Event.current.keyCode == 271;
				}
				return true;
			}
			return false;
		}
	}
	public static class ColorExtensions
	{
		public static string GetColorHtmlString(this Color color)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			if (color.a != 1f)
			{
				return ColorUtility.ToHtmlStringRGBA(color);
			}
			return ColorUtility.ToHtmlStringRGB(color);
		}

		public static Color SetAlpha(this Color color, float alpha)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			color.a = alpha;
			return color;
		}
	}
	public static class UnityExtensions
	{
		public static T Ref<T>(this T gameObject) where T : Object
		{
			if (!Object.op_Implicit((Object)(object)gameObject))
			{
				return default(T);
			}
			return gameObject;
		}

		public static bool TryGetComponentInParent<T>(this GameObject gameObject, out T component) where T : Component
		{
			component = gameObject.GetComponentInParent<T>();
			return Object.op_Implicit((Object)(object)component);
		}
	}
	public static class ZDOExtensions
	{
		public static bool TryGetFloat(this ZDO zdo, int keyHashCode, out float value)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			if (ZDOExtraData.s_floats.TryGetValue(zdo.m_uid, out var value2) && value2.TryGetValue(keyHashCode, ref value))
			{
				return true;
			}
			value = 0f;
			return false;
		}

		public static bool TryGetVector3(this ZDO zdo, int hash, out Vector3 value)
		{
			//IL_0006: 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)
			if (ZDOExtraData.s_vec3.TryGetValue(zdo.m_uid, out var value2) && value2.TryGetValue(hash, ref value))
			{
				return true;
			}
			value = default(Vector3);
			return false;
		}
	}
}
namespace ColorfulPortals
{
	[BepInPlugin("redseiko.valheim.colorfulportals", "ColorfulPortals", "1.8.0")]
	public sealed class ColorfulPortals : BaseUnityPlugin
	{
		public const string PluginGUID = "redseiko.valheim.colorfulportals";

		public const string PluginName = "ColorfulPortals";

		public const string PluginVersion = "1.8.0";

		private static ManualLogSource _logger;

		private Harmony _harmony;

		public static readonly Color NoColor = new Color(-1f, -1f, -1f);

		public static readonly Vector3 NoColorVector3 = new Vector3(-1f, -1f, -1f);

		public static readonly Vector3 BlackColorVector3 = new Vector3(0.00012345f, 0.00012345f, 0.00012345f);

		public static readonly int ColorShaderId = Shader.PropertyToID("_Color");

		public static readonly int TeleportWorldColorHashCode = StringExtensionMethods.GetStableHashCode("TeleportWorldColor");

		public static readonly int TeleportWorldColorAlphaHashCode = StringExtensionMethods.GetStableHashCode("TeleportWorldColorAlpha");

		public static readonly int PortalLastColoredByHashCode = StringExtensionMethods.GetStableHashCode("PortalLastColoredBy");

		public static readonly int PortalLastColoredByHostHashCode = StringExtensionMethods.GetStableHashCode("PortalLastColoredByHost");

		private void Awake()
		{
			_logger = ((BaseUnityPlugin)this).Logger;
			PluginConfig.BindConfig(((BaseUnityPlugin)this).Config);
			_harmony = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "redseiko.valheim.colorfulportals");
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		public static void ChangePortalColor(TeleportWorld targetPortal)
		{
			//IL_0039: 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)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)targetPortal))
			{
				return;
			}
			if (!Object.op_Implicit((Object)(object)targetPortal.m_nview) || !targetPortal.m_nview.IsValid())
			{
				_logger.LogWarning((object)"TeleportWorld does not have a valid ZNetView.");
				return;
			}
			if (!PrivateArea.CheckAccess(((Component)targetPortal).transform.position, 0f, true, false))
			{
				_logger.LogWarning((object)"TeleportWorld is within a PrivateArea.");
				return;
			}
			targetPortal.m_nview.ClaimOwnership();
			SetPortalColorZdoValues(targetPortal.m_nview.m_zdo, ColorToVector3(PluginConfig.TargetPortalColor.Value), PluginConfig.TargetPortalColor.Value.a);
			TeleportWorldColor teleportWorldColor = default(TeleportWorldColor);
			if (((Component)targetPortal).TryGetComponent<TeleportWorldColor>(ref teleportWorldColor))
			{
				teleportWorldColor.UpdateColors(forceUpdate: true);
			}
		}

		private static void SetPortalColorZdoValues(ZDO zdo, Vector3 colorVector3, float colorAlpha)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			zdo.Set(TeleportWorldColorHashCode, colorVector3);
			zdo.Set(TeleportWorldColorAlphaHashCode, colorAlpha);
			int portalLastColoredByHashCode = PortalLastColoredByHashCode;
			Player obj = Player.m_localPlayer.Ref<Player>();
			zdo.Set(portalLastColoredByHashCode, (obj != null) ? obj.GetPlayerID() : 0);
			zdo.Set(PortalLastColoredByHostHashCode, PrivilegeManager.GetNetworkUserId());
		}

		public static Vector3 ColorToVector3(Color color)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: 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_001f: Unknown result type (might be due to invalid IL or missing references)
			if (!(color == Color.black))
			{
				return new Vector3(color.r, color.g, color.b);
			}
			return BlackColorVector3;
		}

		public static Color Vector3ToColor(Vector3 vector3)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: 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_001f: Unknown result type (might be due to invalid IL or missing references)
			if (!(vector3 == BlackColorVector3))
			{
				return new Color(vector3.x, vector3.y, vector3.z);
			}
			return Color.black;
		}
	}
	public sealed class TeleportWorldColor : MonoBehaviour
	{
		public static readonly List<TeleportWorldColor> TeleportWorldColorCache = new List<TeleportWorldColor>();

		private TeleportWorld _teleportWorld;

		private ZNetView _netView;

		private Color _currentColor;

		private long _lastDataRevision;

		private Light _pointLight;

		private ParticleSystem _suckParticles;

		private ParticleSystem _particleSystem;

		private ParticleSystem _blueFlames;

		private void Awake()
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			_teleportWorld = ((Component)this).GetComponent<TeleportWorld>();
			if (Object.op_Implicit((Object)(object)_teleportWorld) && Object.op_Implicit((Object)(object)_teleportWorld.m_nview) && _teleportWorld.m_nview.IsValid())
			{
				_netView = _teleportWorld.m_nview;
				_currentColor = ColorfulPortals.NoColor;
				_lastDataRevision = -1L;
				_pointLight = ((Component)((Component)this).transform.Find("_target_found_red/Point light")).GetComponent<Light>();
				_suckParticles = ((Component)((Component)this).transform.Find("_target_found_red/Particle System/suck particles")).GetComponent<ParticleSystem>();
				_particleSystem = ((Component)((Component)this).transform.Find("_target_found_red/Particle System")).GetComponent<ParticleSystem>();
				_blueFlames = ((Component)((Component)this).transform.Find("_target_found_red/Particle System/blue flames")).GetComponent<ParticleSystem>();
				TeleportWorldColorCache.Add(this);
			}
		}

		private void OnDestroy()
		{
			TeleportWorldColorCache.Remove(this);
		}

		public void UpdateColors(bool forceUpdate = false)
		{
			//IL_005b: 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_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: 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_0093: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)_netView) || !_netView.IsValid())
			{
				return;
			}
			long num = _netView.m_zdo.DataRevision;
			if (!forceUpdate && _lastDataRevision >= num)
			{
				return;
			}
			_lastDataRevision = num;
			if (_netView.m_zdo.TryGetVector3(ColorfulPortals.TeleportWorldColorHashCode, out var value))
			{
				Color val = ColorfulPortals.Vector3ToColor(value);
				if (_netView.m_zdo.TryGetFloat(ColorfulPortals.TeleportWorldColorAlphaHashCode, out var value2))
				{
					val.a = value2;
				}
				if (!(val == _currentColor))
				{
					SetPortalColors(val);
				}
			}
		}

		public void SetPortalColors(Color portalColor)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: 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_0034: Unknown result type (might be due to invalid IL or missing references)
			_currentColor = portalColor;
			_pointLight.color = portalColor;
			SetParticleSystemColor(_suckParticles, portalColor);
			SetParticleSystemColor(_particleSystem, portalColor);
			SetParticleSystemColor(_blueFlames, portalColor);
		}

		private void SetParticleSystemColor(ParticleSystem ps, Color portalColor)
		{
			//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_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_0026: 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_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: 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_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			ColorOverLifetimeModule colorOverLifetime = ps.colorOverLifetime;
			if (((ColorOverLifetimeModule)(ref colorOverLifetime)).enabled)
			{
				((ColorOverLifetimeModule)(ref colorOverLifetime)).color = new MinMaxGradient(portalColor);
			}
			MainModule main = ps.main;
			((MainModule)(ref main)).startColor = new MinMaxGradient(portalColor);
			CustomDataModule customData = ps.customData;
			if (((CustomDataModule)(ref customData)).enabled)
			{
				((CustomDataModule)(ref customData)).SetColor((ParticleSystemCustomData)0, new MinMaxGradient(portalColor));
			}
			ps.Clear();
			ps.Simulate(0f);
			ps.Play();
		}
	}
	public sealed class TeleportWorldColorUpdater : MonoBehaviour
	{
		private void Awake()
		{
			((MonoBehaviour)this).StartCoroutine(UpdateTeleportWorldColors());
		}

		private IEnumerator UpdateTeleportWorldColors()
		{
			WaitForSeconds waitInterval = new WaitForSeconds(PluginConfig.UpdateColorsWaitInterval.Value);
			while (true)
			{
				int frameLimit = PluginConfig.UpdateColorsFrameLimit.Value;
				int index = 0;
				while (index < TeleportWorldColor.TeleportWorldColorCache.Count)
				{
					for (int i = 0; i < frameLimit; i++)
					{
						if (TeleportWorldColor.TeleportWorldColorCache.Count <= 0)
						{
							break;
						}
						if (index >= TeleportWorldColor.TeleportWorldColorCache.Count)
						{
							break;
						}
						TeleportWorldColor.TeleportWorldColorCache[index].UpdateColors();
						index++;
					}
					yield return null;
				}
				yield return waitInterval;
			}
		}
	}
	[HarmonyPatch(typeof(Game))]
	internal static class GamePatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("Start")]
		private static void StartPostfix(ref Game __instance)
		{
			if (PluginConfig.IsModEnabled.Value)
			{
				((Component)__instance).gameObject.AddComponent<TeleportWorldColorUpdater>();
			}
		}
	}
	[HarmonyPatch(typeof(Player))]
	internal static class PlayerPatch
	{
		[HarmonyTranspiler]
		[HarmonyPatch("Update")]
		private static IEnumerable<CodeInstruction> UpdateTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((OpCode?)OpCodes.Call, (object)AccessTools.Method(typeof(Player), "UpdateHover", (Type[])null, (Type[])null), (string)null)
			}).Advance(1).InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[3]
			{
				new CodeInstruction(OpCodes.Ldloc_1, (object)null),
				Transpilers.EmitDelegate<Func<bool, bool>>((Func<bool, bool>)UpdateHoverPostDelegate),
				new CodeInstruction(OpCodes.Stloc_1, (object)null)
			})
				.InstructionEnumeration();
		}

		private static bool UpdateHoverPostDelegate(bool takeInput)
		{
			//IL_0014: 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)
			if (takeInput && PluginConfig.IsModEnabled.Value)
			{
				KeyboardShortcut value = PluginConfig.ChangePortalColorShortcut.Value;
				if (((KeyboardShortcut)(ref value)).IsDown() && Object.op_Implicit((Object)(object)Player.m_localPlayer) && Object.op_Implicit((Object)(object)Player.m_localPlayer.m_hovering) && Player.m_localPlayer.m_hovering.TryGetComponentInParent<TeleportWorld>(out TeleportWorld component))
				{
					ColorfulPortals.ChangePortalColor(component);
					return false;
				}
			}
			return takeInput;
		}
	}
	[HarmonyPatch(typeof(TeleportWorld))]
	internal static class TeleportWorldPatch
	{
		private static readonly int _portalWoodHashCode = StringExtensionMethods.GetStableHashCode("portal_wood");

		[HarmonyPostfix]
		[HarmonyPatch("Awake")]
		private static void AwakePostfix(ref TeleportWorld __instance)
		{
			if (PluginConfig.IsModEnabled.Value && Object.op_Implicit((Object)(object)__instance) && Object.op_Implicit((Object)(object)__instance.m_nview) && __instance.m_nview.IsValid() && __instance.m_nview.m_zdo.m_prefab == _portalWoodHashCode)
			{
				((Component)__instance).gameObject.AddComponent<TeleportWorldColor>();
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch("GetHoverText")]
		private static void GetHoverTextPostfix(ref TeleportWorld __instance, ref string __result)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			if (PluginConfig.IsModEnabled.Value && PluginConfig.ShowChangeColorHoverText.Value && Object.op_Implicit((Object)(object)__instance))
			{
				__result = string.Format("{0}\n[<color={1}>{2}</color>] Change color to: <color=#{3}>#{3}</color>", __result, "#FFA726", PluginConfig.ChangePortalColorShortcut.Value, PluginConfig.TargetPortalColor.Value.GetColorHtmlString());
			}
		}
	}
	public static class PluginConfig
	{
		public static ConfigEntry<bool> IsModEnabled { get; private set; }

		public static ConfigEntry<KeyboardShortcut> ChangePortalColorShortcut { get; private set; }

		public static ExtendedColorConfigEntry TargetPortalColor { get; private set; }

		public static ConfigEntry<bool> ShowChangeColorHoverText { get; private set; }

		public static ConfigEntry<int> UpdateColorsFrameLimit { get; private set; }

		public static ConfigEntry<float> UpdateColorsWaitInterval { get; private set; }

		public static void BindConfig(ConfigFile config)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			IsModEnabled = config.BindInOrder("_Global", "isModEnabled", defaultValue: true, "Globally enable or disable this mod.");
			ChangePortalColorShortcut = config.BindInOrder<KeyboardShortcut>("Hotkeys", "changePortalColorShortcut", new KeyboardShortcut((KeyCode)101, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Keyboard shortcut to change (or clear) the color of the hovered/targeted portal.");
			TargetPortalColor = new ExtendedColorConfigEntry(config, "Color", "targetPortalColor", Color.cyan, "Target color to set any torch/fire to.", "targetPortalColorPalette");
			ShowChangeColorHoverText = config.BindInOrder("Hud", "showChangeColorHoverText", defaultValue: false, "Show the 'change color' text when hovering over a portal.");
			BindUpdateColorsConfig(config);
		}

		private static void BindUpdateColorsConfig(ConfigFile config)
		{
			UpdateColorsFrameLimit = config.BindInOrder("UpdateColors", "updateColorsFrameLimit", 100, "Limit for how many TelepwortWorldColor.UpdateColors to process per update frame.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(50, 250));
			UpdateColorsWaitInterval = config.BindInOrder("UpdateColors", "updateColorsWaitInterval", 5f, "Interval to wait after each TelepwortWorldColor.UpdateColors loop. *Restart required!*", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 10f));
		}
	}
}