Decompiled source of FadingFlashlights v1.0.2

BepInEx/plugins/FadingFlashlights.dll

Decompiled 10 months ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using FadingFlashlights.NetcodePatcher;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

[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: AssemblyCompany("FadingFlashlights")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Dimming over time.")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("FadingFlashlights")]
[assembly: AssemblyTitle("FadingFlashlights")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 FadingFlashlights
{
	[BepInPlugin("FadingFlashlights", "FadingFlashlights", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public static ManualLogSource sLogger { get; internal set; }

		public static FFConfig FFConfig { get; internal set; }

		public void Awake()
		{
			sLogger = ((BaseUnityPlugin)this).Logger;
			Patches.logger = ((BaseUnityPlugin)this).Logger;
			FFConfig = new FFConfig(((BaseUnityPlugin)this).Config);
			Harmony.CreateAndPatchAll(typeof(Patches), (string)null);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin FadingFlashlights is loaded!");
		}
	}
	internal class Patches
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static HandleNamedMessageDelegate <0>__OnRequestSync;

			public static HandleNamedMessageDelegate <1>__OnReceiveSync;
		}

		public static ManualLogSource logger;

		[HarmonyPatch(typeof(FlashlightItem), "Start")]
		[HarmonyPrefix]
		public static void AddFlashlightFader(FlashlightItem __instance)
		{
			((Component)__instance).gameObject.AddComponent<FlashlightFaderComponent>();
			((Component)__instance).gameObject.GetComponent<FlashlightFaderComponent>().flashlight = __instance;
		}

		[HarmonyPatch(typeof(FlashlightItem), "PocketItem")]
		[HarmonyPostfix]
		public static void PocketItem(FlashlightItem __instance)
		{
			((Component)__instance).gameObject.GetComponent<FlashlightFaderComponent>().PocketItem();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")]
		public static void PlayerLeave()
		{
			SyncedInstance<FFConfig>.RevertSync();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
		public static void InitializeLocalPlayer()
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_0025: 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_0030: Expected O, but got Unknown
			if (SyncedInstance<FFConfig>.IsHost)
			{
				CustomMessagingManager messageManager = SyncedInstance<FFConfig>.MessageManager;
				object obj = <>O.<0>__OnRequestSync;
				if (obj == null)
				{
					HandleNamedMessageDelegate val = FFConfig.OnRequestSync;
					<>O.<0>__OnRequestSync = val;
					obj = (object)val;
				}
				messageManager.RegisterNamedMessageHandler("FadingFlashlights_OnRequestConfigSync", (HandleNamedMessageDelegate)obj);
				SyncedInstance<FFConfig>.Synced = true;
				return;
			}
			SyncedInstance<FFConfig>.Synced = false;
			CustomMessagingManager messageManager2 = SyncedInstance<FFConfig>.MessageManager;
			object obj2 = <>O.<1>__OnReceiveSync;
			if (obj2 == null)
			{
				HandleNamedMessageDelegate val2 = FFConfig.OnReceiveSync;
				<>O.<1>__OnReceiveSync = val2;
				obj2 = (object)val2;
			}
			messageManager2.RegisterNamedMessageHandler("FadingFlashlights_OnReceiveConfigSync", (HandleNamedMessageDelegate)obj2);
			FFConfig.RequestSync();
		}
	}
	public class FlashlightFaderComponent : MonoBehaviour
	{
		public FlashlightItem flashlight;

		private Color initialBulbColor;

		private Color initialBulbGlowColor;

		private Color initialHelmetLightColor;

		private static readonly FieldInfo previousPlayerHeldBy = typeof(FlashlightItem).GetField("previousPlayerHeldBy", BindingFlags.Instance | BindingFlags.NonPublic);

		private void Start()
		{
			//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_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			initialBulbColor = flashlight.flashlightBulb.color;
			initialBulbGlowColor = flashlight.flashlightBulbGlow.color;
		}

		private void Update()
		{
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Expected O, but got Unknown
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			float num = 1f - Plugin.FFConfig.startFade;
			float finalBrightness = Plugin.FFConfig.finalBrightness;
			float num2 = (1f - finalBrightness) / num * (((GrabbableObject)flashlight).insertedBattery.charge - num) + 1f;
			float num3 = Mathf.Pow(Mathf.Clamp(num2, 0f, 1f), Mathf.Pow(2f, Plugin.FFConfig.functionExponent));
			if (flashlight.usingPlayerHelmetLight)
			{
				PlayerControllerB val = (PlayerControllerB)previousPlayerHeldBy.GetValue(flashlight);
				val.helmetLight.color = initialHelmetLightColor * num3;
			}
			else
			{
				flashlight.flashlightBulb.color = initialBulbColor * num3;
				flashlight.flashlightBulbGlow.color = initialBulbGlowColor * num3;
			}
		}

		public void PocketItem()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			//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)
			PlayerControllerB val = (PlayerControllerB)previousPlayerHeldBy.GetValue(flashlight);
			initialHelmetLightColor = val.helmetLight.color;
		}
	}
	[Serializable]
	public class FFConfig : SyncedInstance<FFConfig>
	{
		public static ConfigEntry<float> configStartFade;

		public static ConfigEntry<float> configFinalBrightness;

		public static ConfigEntry<float> configFunctionExponent;

		public float startFade;

		public float finalBrightness;

		public float functionExponent;

		public FFConfig(ConfigFile cfg)
		{
			InitInstance(this);
			configStartFade = cfg.Bind<float>("Flashlights", "FadeStart", 0.5f, "Number between 0 and 1 that represents the decimal that the flashlight will start fading at. For example, 0.5 means it will start fading at half battery.");
			configFinalBrightness = cfg.Bind<float>("Flashlights", "FadeFinalBrightness", 0f, "Number between 0 and 1 that represents the brightness that the flashlight will run out of battery with. For example, 0.5 means it will be at half brightness when it shuts down.");
			configFunctionExponent = cfg.Bind<float>("Flashlights", "FadeFunctionExponent", -1f, "The logarhithm (base 2) of the power that the result of the fade function will be put to the power of. In simple terms, negative numbers mean that your flashlight will stay brighter for longer. Positive numbers mean that your flashlight will get dark quickly, and stay dark. Zero means that the light brightness will follow a straight line over time. By default, this is set to -1, which corresponds to a square root.");
			startFade = configStartFade.Value;
			finalBrightness = configFinalBrightness.Value;
			functionExponent = configFunctionExponent.Value;
		}

		public void ReloadConfig()
		{
			startFade = configStartFade.Value;
			finalBrightness = configFinalBrightness.Value;
			functionExponent = configFunctionExponent.Value;
			RequestSync();
		}

		public static void RequestSync()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			if (!SyncedInstance<FFConfig>.IsClient)
			{
				return;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(SyncedInstance<FFConfig>.IntSize, (Allocator)2, -1);
			try
			{
				SyncedInstance<FFConfig>.MessageManager.SendNamedMessage("FadingFlashlights_OnRequestConfigSync", 0uL, val, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		public static void OnRequestSync(ulong clientId, FastBufferReader _)
		{
			//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 (!SyncedInstance<FFConfig>.IsHost)
			{
				return;
			}
			Plugin.sLogger.LogInfo((object)$"Config sync request received from client: {clientId}");
			byte[] array = SyncedInstance<FFConfig>.SerializeToBytes(SyncedInstance<FFConfig>.Instance);
			int num = array.Length;
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(num + SyncedInstance<FFConfig>.IntSize, (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteBytesSafe(array, -1, 0);
				SyncedInstance<FFConfig>.MessageManager.SendNamedMessage("FadingFlashlights_OnReceiveConfigSync", clientId, val, (NetworkDelivery)3);
			}
			catch (Exception arg)
			{
				Plugin.sLogger.LogInfo((object)$"Error occurred syncing config with client: {clientId}\n{arg}");
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		public static void OnReceiveSync(ulong _, FastBufferReader reader)
		{
			//IL_002d: 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)
			if (!((FastBufferReader)(ref reader)).TryBeginRead(SyncedInstance<FFConfig>.IntSize))
			{
				Plugin.sLogger.LogError((object)"Config sync error: Could not begin reading buffer.");
				return;
			}
			int num = default(int);
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			if (!((FastBufferReader)(ref reader)).TryBeginRead(num))
			{
				Plugin.sLogger.LogError((object)"Config sync error: Host could not sync.");
				return;
			}
			byte[] data = new byte[num];
			((FastBufferReader)(ref reader)).ReadBytesSafe(ref data, num, 0);
			SyncedInstance<FFConfig>.SyncInstance(data);
			Plugin.sLogger.LogInfo((object)"Successfully synced config with host.");
		}
	}
	[Serializable]
	public class SyncedInstance<T>
	{
		[NonSerialized]
		protected static int IntSize = 4;

		internal static CustomMessagingManager MessageManager => NetworkManager.Singleton.CustomMessagingManager;

		internal static bool IsClient => NetworkManager.Singleton.IsClient;

		internal static bool IsHost => NetworkManager.Singleton.IsHost;

		public static T Default { get; private set; }

		public static T Instance { get; private set; }

		public static bool Synced { get; internal set; }

		protected void InitInstance(T instance)
		{
			Default = instance;
			Instance = instance;
			IntSize = 4;
		}

		internal static void SyncInstance(byte[] data)
		{
			Instance = DeserializeFromBytes(data);
			Synced = true;
		}

		internal static void RevertSync()
		{
			Instance = Default;
			Synced = false;
		}

		public static byte[] SerializeToBytes(T val)
		{
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			using MemoryStream memoryStream = new MemoryStream();
			try
			{
				binaryFormatter.Serialize(memoryStream, val);
				return memoryStream.ToArray();
			}
			catch (Exception arg)
			{
				Plugin.sLogger.LogError((object)$"Error serializing instance: {arg}");
				return null;
			}
		}

		public static T DeserializeFromBytes(byte[] data)
		{
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			using MemoryStream serializationStream = new MemoryStream(data);
			try
			{
				return (T)binaryFormatter.Deserialize(serializationStream);
			}
			catch (Exception arg)
			{
				Plugin.sLogger.LogError((object)$"Error deserializing instance: {arg}");
				return default(T);
			}
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "FadingFlashlights";

		public const string PLUGIN_NAME = "FadingFlashlights";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace FadingFlashlights.NetcodePatcher
{
	[AttributeUsage(AttributeTargets.Module)]
	internal class NetcodePatchedAssemblyAttribute : Attribute
	{
	}
}