Decompiled source of MonitorTakeoverGreenLights v1.0.0

Y4NGZMonitorTakeoverGreenLights.dll

Decompiled an hour ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Y4NGZMonitorTakeoverGreenLights")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Y4NGZMonitorTakeoverGreenLights")]
[assembly: AssemblyTitle("Y4NGZMonitorTakeoverGreenLights")]
[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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Y4NGZCompany.GreenLights
{
	[BepInPlugin("com.y4ngz.company.greenlights", "Monitor Takeover: Green Lights", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class GreenLightsPlugin : BaseUnityPlugin
	{
		private enum LightPhase
		{
			Dimming,
			Flashing,
			Restoring
		}

		private struct LightSnapshot
		{
			internal Light Light;

			internal float Intensity;

			internal Color Color;

			internal LightSnapshot(Light light, float intensity, Color color)
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				Light = light;
				Intensity = intensity;
				Color = color;
			}
		}

		public const string PluginGuid = "com.y4ngz.company.greenlights";

		public const string PluginName = "Monitor Takeover: Green Lights";

		public const string PluginVersion = "1.0.0";

		private const string MonitorTakeoverGuid = "com.y4ngz.company.monitortakeover";

		private const string CoreGuid = "com.y4ngz.core";

		internal static readonly Type ManagerType = Type.GetType("Y4NGZCompany.ShipSystems.Takeover.TakeoverManager, Y4NGZMonitorTakeover", throwOnError: false);

		internal ConfigEntry<bool> Enabled;

		internal ConfigEntry<float> FlashRate;

		internal ConfigEntry<float> BrightIntensity;

		internal ConfigEntry<float> DarkIntensity;

		internal ConfigEntry<float> DimSeconds;

		internal ConfigEntry<float> RestoreSeconds;

		internal ConfigEntry<string> BrightColor;

		internal ConfigEntry<string> DarkColor;

		private readonly List<LightSnapshot> _lights = new List<LightSnapshot>();

		private readonly List<LightSnapshot> _restoreFrom = new List<LightSnapshot>();

		private readonly HashSet<Light> _alarmLamps = new HashSet<Light>();

		private PropertyInfo _isActive;

		private Harmony _harmony;

		private bool _running;

		private LightPhase _phase;

		private float _dimElapsed;

		private float _flashElapsed;

		private float _restoreElapsed;

		private Color _bright;

		private Color _dark;

		internal static GreenLightsPlugin Instance { get; private set; }

		private void Awake()
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			Instance = this;
			BindConfig();
			if (ManagerType == null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Monitor Takeover: Green Lights: Monitor Takeover (Y4NGZMonitorTakeover) was not found, so the green lights addon cannot run. Check that Monitor Takeover 1.1.1 or newer is installed.");
				return;
			}
			_isActive = ManagerType.GetProperty("IsActive", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			if (_isActive == null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Monitor Takeover: Green Lights: Monitor Takeover's takeover state was not found. This addon targets Monitor Takeover 1.1.1; update or remove the addon.");
				return;
			}
			_harmony = new Harmony("com.y4ngz.company.greenlights");
			try
			{
				_harmony.PatchAll(typeof(GreenLightsPlugin).Assembly);
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Monitor Takeover: Green Lights: Monitor Takeover's light sequence could not be hooked (" + ex.GetType().Name + ": " + ex.Message + "). This addon targets Monitor Takeover 1.1.1; update or remove the addon."));
				_harmony.UnpatchSelf();
				_harmony = null;
				return;
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Monitor Takeover: Green Lights v1.0.0 loaded; it now owns the takeover's green lights.");
		}

		private void BindConfig()
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Expected O, but got Unknown
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Expected O, but got Unknown
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Expected O, but got Unknown
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Expected O, but got Unknown
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Green Lights", "Enabled", true, "Run this addon's green lights during a Monitor Takeover. false leaves Monitor Takeover's own lights alone.");
			FlashRate = ((BaseUnityPlugin)this).Config.Bind<float>("Green Lights", "Flash Rate", 3f, new ConfigDescription("Full bright-to-dark flashes per second. Monitor Takeover's own effect flashes 3 times a second.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 10f), Array.Empty<object>()));
			BrightIntensity = ((BaseUnityPlugin)this).Config.Bind<float>("Green Lights", "Bright Intensity", 0.6f, new ConfigDescription("Fraction of each light's normal brightness while it is bright green.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			DarkIntensity = ((BaseUnityPlugin)this).Config.Bind<float>("Green Lights", "Dark Intensity", 0.03f, new ConfigDescription("Fraction of each light's normal brightness while it is dark green.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			DimSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Green Lights", "Dim Seconds", 1.5f, new ConfigDescription("Seconds the lights fade from their normal colour to dark green before flashing starts.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 10f), Array.Empty<object>()));
			RestoreSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Green Lights", "Restore Seconds", 1.5f, new ConfigDescription("Seconds the lights fade back when Monitor Takeover is not doing its own restore (for example with its Dim Lights setting off).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 10f), Array.Empty<object>()));
			BrightColor = ((BaseUnityPlugin)this).Config.Bind<string>("Green Lights", "Bright Color", "#1AFF1A", "Hex colour of the bright flash.");
			DarkColor = ((BaseUnityPlugin)this).Config.Bind<string>("Green Lights", "Dark Color", "#006600", "Hex colour of the dark half of the flash.");
		}

		private void Update()
		{
			if (_running && !IsTakeoverActive() && _phase != LightPhase.Restoring)
			{
				BeginRestore();
			}
		}

		private void LateUpdate()
		{
			if (_running)
			{
				switch (_phase)
				{
				case LightPhase.Dimming:
					ApplyDimming();
					break;
				case LightPhase.Flashing:
					ApplyFlashing();
					break;
				case LightPhase.Restoring:
					ApplyRestoring();
					break;
				}
			}
		}

		private void OnDestroy()
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			if (_running)
			{
				foreach (LightSnapshot light in _lights)
				{
					if ((Object)(object)light.Light != (Object)null)
					{
						light.Light.intensity = light.Intensity;
						light.Light.color = light.Color;
					}
				}
			}
			_running = false;
			_lights.Clear();
			_restoreFrom.Clear();
			if (_harmony != null)
			{
				_harmony.UnpatchSelf();
				_harmony = null;
			}
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}

		internal void OnTakeoverAlarm()
		{
			if (Enabled.Value && !_running && IsTakeoverActive())
			{
				StartEffect();
			}
		}

		internal void OnBaseRestoreStarting()
		{
			if (_running)
			{
				_running = false;
				_lights.Clear();
				_restoreFrom.Clear();
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Monitor Takeover: Green Lights: Monitor Takeover is restoring the ship lights; handed them back.");
			}
		}

		private void StartEffect()
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			if (!TryParseColors())
			{
				return;
			}
			_lights.Clear();
			_alarmLamps.Clear();
			GameObject val = GameObject.Find("Environment/HangarShip") ?? GameObject.Find("HangarShip");
			Light[] obj = (((Object)(object)val != (Object)null) ? val.GetComponentsInChildren<Light>(true) : Object.FindObjectsOfType<Light>());
			CollectAlarmLamps();
			Light[] array = obj;
			foreach (Light val2 in array)
			{
				if (!((Object)(object)val2 == (Object)null) && ((Component)val2).gameObject.activeInHierarchy && !_alarmLamps.Contains(val2))
				{
					_lights.Add(new LightSnapshot(val2, val2.intensity, val2.color));
				}
			}
			if (_lights.Count == 0)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"Monitor Takeover: Green Lights: no ship lights were found, so the green lights effect was skipped.");
				return;
			}
			_dimElapsed = 0f;
			_flashElapsed = 0f;
			_restoreElapsed = 0f;
			_phase = LightPhase.Dimming;
			_running = true;
			((BaseUnityPlugin)this).Logger.LogInfo((object)string.Format("{0}: took over {1} ship lights for the takeover.", "Monitor Takeover: Green Lights", _lights.Count));
		}

		private void CollectAlarmLamps()
		{
			try
			{
				if ((Object)(object)StartOfRound.Instance == (Object)null || (Object)(object)StartOfRound.Instance.shipAnimator == (Object)null)
				{
					return;
				}
				Transform transform = ((Component)StartOfRound.Instance.shipAnimator).transform;
				string[] array = new string[4] { "ShipModels2b/Light/RedLight", "ShipModels2b/Light (1)/RedLight", "ShipModels2b/Light (2)/RedLight", "ShipModels2b/Light (3)/RedLight" };
				foreach (string text in array)
				{
					Transform val = transform.Find(text);
					Light val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<Light>() : null);
					if ((Object)(object)val2 != (Object)null)
					{
						_alarmLamps.Add(val2);
					}
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogDebug((object)("Monitor Takeover: Green Lights: could not collect the alarm lamps: " + ex.Message));
			}
		}

		private void ApplyDimming()
		{
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: 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)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			_dimElapsed += Time.deltaTime;
			float num = Mathf.Max(0.01f, DimSeconds.Value);
			float num2 = Mathf.Clamp01(_dimElapsed / num);
			float num3 = Mathf.SmoothStep(0f, 1f, num2);
			foreach (LightSnapshot light in _lights)
			{
				if (!((Object)(object)light.Light == (Object)null))
				{
					light.Light.intensity = Mathf.Lerp(light.Intensity, light.Intensity * DarkIntensity.Value, num3);
					light.Light.color = WithAlpha(Color.Lerp(light.Color, _dark, num3), light.Color.a);
				}
			}
			if (num2 >= 1f)
			{
				_phase = LightPhase.Flashing;
				_flashElapsed = 0f;
			}
		}

		private void ApplyFlashing()
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: 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_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: 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)
			_flashElapsed += Time.deltaTime;
			float num = 1f / (2f * Mathf.Max(0.1f, FlashRate.Value));
			bool num2 = Mathf.FloorToInt(_flashElapsed / num) % 2 == 0;
			Color color = (num2 ? _bright : _dark);
			float num3 = (num2 ? BrightIntensity.Value : DarkIntensity.Value);
			foreach (LightSnapshot light in _lights)
			{
				if (!((Object)(object)light.Light == (Object)null))
				{
					light.Light.intensity = light.Intensity * num3;
					light.Light.color = WithAlpha(color, light.Color.a);
				}
			}
		}

		private void BeginRestore()
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			_restoreFrom.Clear();
			foreach (LightSnapshot light in _lights)
			{
				if ((Object)(object)light.Light != (Object)null)
				{
					_restoreFrom.Add(new LightSnapshot(light.Light, light.Light.intensity, light.Light.color));
				}
			}
			_restoreElapsed = 0f;
			_phase = LightPhase.Restoring;
		}

		private void ApplyRestoring()
		{
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			if (_restoreFrom.Count == 0)
			{
				StopEffect();
				return;
			}
			_restoreElapsed += Time.deltaTime;
			float num = Mathf.Max(0.01f, RestoreSeconds.Value);
			float num2 = Mathf.Clamp01(_restoreElapsed / num);
			float num3 = Mathf.SmoothStep(0f, 1f, num2);
			for (int i = 0; i < _lights.Count && i < _restoreFrom.Count; i++)
			{
				Light light = _lights[i].Light;
				if (!((Object)(object)light == (Object)null))
				{
					LightSnapshot lightSnapshot = _restoreFrom[i];
					light.intensity = Mathf.Lerp(lightSnapshot.Intensity, _lights[i].Intensity, num3);
					light.color = Color.Lerp(lightSnapshot.Color, _lights[i].Color, num3);
				}
			}
			if (num2 >= 1f)
			{
				StopEffect();
			}
		}

		private void StopEffect()
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < _lights.Count && i < _restoreFrom.Count; i++)
			{
				Light light = _lights[i].Light;
				if ((Object)(object)light != (Object)null)
				{
					light.intensity = _lights[i].Intensity;
					light.color = _lights[i].Color;
				}
			}
			_running = false;
			_lights.Clear();
			_restoreFrom.Clear();
			_phase = LightPhase.Dimming;
		}

		private bool TryParseColors()
		{
			if (!ColorUtility.TryParseHtmlString(BrightColor.Value, ref _bright))
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Monitor Takeover: Green Lights: Bright Color '" + BrightColor.Value + "' is not a hex colour; using #1AFF1A."));
				ColorUtility.TryParseHtmlString("#1AFF1A", ref _bright);
			}
			if (!ColorUtility.TryParseHtmlString(DarkColor.Value, ref _dark))
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Monitor Takeover: Green Lights: Dark Color '" + DarkColor.Value + "' is not a hex colour; using #006600."));
				ColorUtility.TryParseHtmlString("#006600", ref _dark);
			}
			return true;
		}

		private bool IsTakeoverActive()
		{
			try
			{
				return _isActive != null && (bool)_isActive.GetValue(null);
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogDebug((object)("Monitor Takeover: Green Lights: could not read the takeover state: " + ex.Message));
				return false;
			}
		}

		private static Color WithAlpha(Color color, float alpha)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			color.a = alpha;
			return color;
		}
	}
	[HarmonyPatch]
	internal static class TakeoverAlarmPatch
	{
		private static MethodBase TargetMethod()
		{
			return AccessTools.Method(GreenLightsPlugin.ManagerType, "PlayAlarm", (Type[])null, (Type[])null);
		}

		[HarmonyPostfix]
		private static void Postfix()
		{
			GreenLightsPlugin.Instance?.OnTakeoverAlarm();
		}
	}
	[HarmonyPatch]
	internal static class TakeoverRestorePatch
	{
		private static MethodBase TargetMethod()
		{
			return AccessTools.Method(GreenLightsPlugin.ManagerType, "RestoreLights", (Type[])null, (Type[])null);
		}

		[HarmonyPrefix]
		private static void Prefix()
		{
			GreenLightsPlugin.Instance?.OnBaseRestoreStarting();
		}
	}
}