Decompiled source of Nutcracker Fire Warning v1.1.0

BepInEx/plugins/NutcrackerFireWarning/NutcrackerFireWarning.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using LethalConfig;
using LethalConfig.ConfigItems;
using LethalConfig.ConfigItems.Options;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("NutcrackerFireWarning.Tests")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("NutcrackerFireWarning")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0+beaa7f595c7bf1e2a7ec5c2deda200a734b677a0")]
[assembly: AssemblyProduct("NutcrackerFireWarning")]
[assembly: AssemblyTitle("NutcrackerFireWarning")]
[assembly: AssemblyVersion("1.1.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 NutcrackerShotUI
{
	internal readonly struct NutcrackerCombatState
	{
		public readonly bool AimingGun;

		public readonly bool ReloadingGun;

		public readonly bool Stunned;

		public NutcrackerCombatState(bool aimingGun, bool reloadingGun, bool stunned)
		{
			AimingGun = aimingGun;
			ReloadingGun = reloadingGun;
			Stunned = stunned;
		}
	}
	internal static class NutcrackerCombatStateReader
	{
		private static readonly FieldRef<NutcrackerEnemyAI, bool> AimingGunRef = CreateFieldRef<bool>("aimingGun");

		private static readonly FieldRef<NutcrackerEnemyAI, bool> ReloadingGunRef = CreateFieldRef<bool>("reloadingGun");

		public static bool TryRead(NutcrackerEnemyAI nutcracker, out NutcrackerCombatState combatState)
		{
			combatState = default(NutcrackerCombatState);
			if ((Object)(object)nutcracker == (Object)null || AimingGunRef == null || ReloadingGunRef == null)
			{
				return false;
			}
			combatState = new NutcrackerCombatState(AimingGunRef.Invoke(nutcracker), ReloadingGunRef.Invoke(nutcracker), ((EnemyAI)nutcracker).stunNormalizedTimer > 0f);
			return true;
		}

		public static float GetAimDuration(NutcrackerEnemyAI nutcracker)
		{
			if (((EnemyAI)nutcracker).enemyHP <= 1)
			{
				return 0.5f;
			}
			ShotgunItem gun = nutcracker.gun;
			if ((Object)(object)gun != (Object)null && gun.shellsLoaded == 1)
			{
				return 1.3f;
			}
			return 1.75f;
		}

		private static FieldRef<NutcrackerEnemyAI, T> CreateFieldRef<T>(string fieldName)
		{
			try
			{
				return AccessTools.FieldRefAccess<NutcrackerEnemyAI, T>(fieldName);
			}
			catch
			{
				return null;
			}
		}
	}
	internal static class NutcrackerConfigLanguageDetector
	{
		internal const string ChineseProjectGuid = "Aueser.LCChineseProject";

		internal const string LegacyChineseProjectGuid = "cn.codex.v81testchn";

		private const string ChineseProjectFolderName = "V81TestChn";

		private const string ChineseProjectDllName = "V81TestChn.dll";

		public static bool ShouldUseChineseConfig()
		{
			try
			{
				if (Chainloader.PluginInfos != null && ContainsChineseProjectGuid(Chainloader.PluginInfos.Keys))
				{
					return true;
				}
			}
			catch
			{
			}
			return ShouldUseChineseConfig(null, Paths.PluginPath);
		}

		internal static bool ShouldUseChineseConfig(IEnumerable<string> pluginGuids, string pluginRoot)
		{
			if (ContainsChineseProjectGuid(pluginGuids))
			{
				return true;
			}
			return ContainsChineseProjectDll(pluginRoot);
		}

		private static bool ContainsChineseProjectGuid(IEnumerable<string> pluginGuids)
		{
			if (pluginGuids == null)
			{
				return false;
			}
			foreach (string pluginGuid in pluginGuids)
			{
				if (string.Equals(pluginGuid, "Aueser.LCChineseProject", StringComparison.OrdinalIgnoreCase) || string.Equals(pluginGuid, "cn.codex.v81testchn", StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
			return false;
		}

		private static bool ContainsChineseProjectDll(string pluginRoot)
		{
			if (string.IsNullOrWhiteSpace(pluginRoot) || !Directory.Exists(pluginRoot))
			{
				return false;
			}
			if (File.Exists(Path.Combine(pluginRoot, "V81TestChn", "V81TestChn.dll")) || File.Exists(Path.Combine(pluginRoot, "V81TestChn.dll")))
			{
				return true;
			}
			try
			{
				foreach (string item in Directory.EnumerateFiles(pluginRoot, "V81TestChn.dll", SearchOption.AllDirectories))
				{
					if (string.Equals(Path.GetFileName(item), "V81TestChn.dll", StringComparison.OrdinalIgnoreCase))
					{
						return true;
					}
				}
			}
			catch
			{
				return false;
			}
			return false;
		}
	}
	internal sealed class NutcrackerConfigText
	{
		internal const string SectionGeneral = "General";

		internal const string SectionWarnings = "Warnings";

		internal const string SectionDebug = "Debug";

		internal const string KeyEnableMod = "EnableMod";

		internal const string KeyFireWindowSeconds = "FireWindowSeconds";

		internal const string KeyAimIntensity = "ModelChaseTintIntensity";

		internal const string KeyFireIntensity = "ModelFireWindowTintIntensity";

		internal const string KeyMaxDistance = "ModelWarningMaxDistance";

		internal const string KeyDebugLogs = "EnableDebugLogs";

		internal static readonly string[] Keys = new string[6] { "EnableMod", "FireWindowSeconds", "ModelChaseTintIntensity", "ModelFireWindowTintIntensity", "ModelWarningMaxDistance", "EnableDebugLogs" };

		internal static readonly string[] Sections = new string[3] { "General", "Warnings", "Debug" };

		private readonly bool chinese;

		public string ModDescription
		{
			get
			{
				if (!chinese)
				{
					return "Changes the Nutcracker's color before it fires: white while aiming, red just before the shot.";
				}
				return "胡桃夹子开枪前改变模型颜色:瞄准时变白,即将开枪时变红。";
			}
		}

		public NutcrackerConfigText(bool chinese)
		{
			this.chinese = chinese;
		}

		public string Section(string section)
		{
			if (!chinese)
			{
				return section;
			}
			return section switch
			{
				"General" => "常规", 
				"Warnings" => "预警", 
				"Debug" => "调试", 
				_ => section, 
			};
		}

		public string Name(string key)
		{
			switch (key)
			{
			case "EnableMod":
				if (!chinese)
				{
					return "Enable mod";
				}
				return "启用模组";
			case "FireWindowSeconds":
				if (!chinese)
				{
					return "Red warning seconds";
				}
				return "红色预警时长(秒)";
			case "ModelChaseTintIntensity":
				if (!chinese)
				{
					return "White aim brightness";
				}
				return "瞄准白色亮度";
			case "ModelFireWindowTintIntensity":
				if (!chinese)
				{
					return "Red fire brightness";
				}
				return "开火红色亮度";
			case "ModelWarningMaxDistance":
				if (!chinese)
				{
					return "Max warning distance";
				}
				return "最大提示距离(米)";
			case "EnableDebugLogs":
				if (!chinese)
				{
					return "Debug logs";
				}
				return "调试日志";
			default:
				return key;
			}
		}

		public string Description(string key)
		{
			switch (key)
			{
			case "EnableMod":
				if (!chinese)
				{
					return "Enable the Nutcracker color warning.";
				}
				return "启用胡桃夹子开枪前的模型变色提示。";
			case "FireWindowSeconds":
				if (!chinese)
				{
					return "Seconds before the predicted shot to turn red, up to half of the aim.";
				}
				return "预计开枪前多少秒变红,最长为本次瞄准时长的一半。";
			case "ModelChaseTintIntensity":
				if (!chinese)
				{
					return "Glow strength of the white aiming color.";
				}
				return "瞄准时白色染色的发光强度。";
			case "ModelFireWindowTintIntensity":
				if (!chinese)
				{
					return "Glow strength of the red firing color.";
				}
				return "即将开枪时红色染色的发光强度。";
			case "ModelWarningMaxDistance":
				if (!chinese)
				{
					return "No color change beyond this distance. Set to 0 for no limit.";
				}
				return "超过此距离时不变色。设为 0 表示不限制。";
			case "EnableDebugLogs":
				if (!chinese)
				{
					return "Log the full aim and shot timing. Usually left off.";
				}
				return "记录完整的瞄准和开枪时序,通常保持关闭。";
			default:
				return key;
			}
		}
	}
	internal static class NutcrackerCoroutineObserver
	{
		public static IEnumerator Observe(IEnumerator routine, Action onStarted, Action onCompleted = null, Action<Exception> onError = null)
		{
			bool started = false;
			try
			{
				while (routine.MoveNext())
				{
					if (!started)
					{
						started = true;
						Notify(onStarted, onError);
					}
					yield return routine.Current;
				}
				if (started)
				{
					Notify(onCompleted, onError);
				}
			}
			finally
			{
				(routine as IDisposable)?.Dispose();
			}
		}

		private static void Notify(Action callback, Action<Exception> onError)
		{
			try
			{
				callback?.Invoke();
			}
			catch (Exception obj)
			{
				try
				{
					onError?.Invoke(obj);
				}
				catch
				{
				}
			}
		}
	}
	internal static class NutcrackerLethalConfig
	{
		internal const string PluginGuid = "ainavt.lc.lethalconfig";

		internal static void Register(NutcrackerConfigText text)
		{
			try
			{
				LethalConfigManager.SetModDescription(text.ModDescription);
				AddBool(NutcrackerShotConfig.EnableMod, "EnableMod", "General", text);
				AddFloat(NutcrackerShotConfig.FireWindowSeconds, "FireWindowSeconds", text);
				AddFloat(NutcrackerShotConfig.ModelChaseTintIntensity, "ModelChaseTintIntensity", text);
				AddFloat(NutcrackerShotConfig.ModelFireWindowTintIntensity, "ModelFireWindowTintIntensity", text);
				AddFloat(NutcrackerShotConfig.ModelWarningMaxDistance, "ModelWarningMaxDistance", text);
				AddBool(NutcrackerShotConfig.EnableDebugLogs, "EnableDebugLogs", "Debug", text);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not register LethalConfig entries: " + ex.Message));
			}
		}

		private static void AddBool(ConfigEntry<bool> entry, string key, string section, NutcrackerConfigText text)
		{
			//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_0019: 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_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			LethalConfigManager.SkipAutoGenFor((ConfigEntryBase)(object)entry);
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(entry, new BoolCheckBoxOptions
			{
				Name = text.Name(key),
				Section = text.Section(section),
				Description = text.Description(key),
				RequiresRestart = false
			}));
		}

		private static void AddFloat(ConfigEntry<float> entry, string key, NutcrackerConfigText text)
		{
			//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_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_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			LethalConfigManager.SkipAutoGenFor((ConfigEntryBase)(object)entry);
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatSliderConfigItem(entry, new FloatSliderOptions
			{
				Name = text.Name(key),
				Section = text.Section("Warnings"),
				Description = text.Description(key),
				RequiresRestart = false
			}));
		}
	}
	internal static class NutcrackerModelRendererFilter
	{
		public static bool IsExcludedPath(string path)
		{
			return ContainsAny(path, "MapDot", "ScanNode", "BloodSpurtParticle", "Collider");
		}

		public static bool IsBody(string path, string meshName)
		{
			if (!ContainsAny(path, "LOD0", "LOD1"))
			{
				return ContainsAny(meshName, "LOD0", "LOD1");
			}
			return true;
		}

		public static bool IsShotgun(string path, string meshName)
		{
			if (!ContainsAny(path, "Gun", "Shotgun"))
			{
				return ContainsAny(meshName, "Gun", "Shotgun");
			}
			return true;
		}

		private static bool ContainsAny(string value, params string[] fragments)
		{
			if (string.IsNullOrEmpty(value))
			{
				return false;
			}
			for (int i = 0; i < fragments.Length; i++)
			{
				if (value.IndexOf(fragments[i], StringComparison.OrdinalIgnoreCase) >= 0)
				{
					return true;
				}
			}
			return false;
		}
	}
	internal sealed class NutcrackerModelTint
	{
		private sealed class RendererTint
		{
			private static readonly int BaseColorId = Shader.PropertyToID("_BaseColor");

			private static readonly int ColorId = Shader.PropertyToID("_Color");

			private static readonly int UnlitColorId = Shader.PropertyToID("_UnlitColor");

			private static readonly int EmissionColorId = Shader.PropertyToID("_EmissionColor");

			private static readonly int EmissiveColorId = Shader.PropertyToID("_EmissiveColor");

			private static readonly int EmissiveColorLdrId = Shader.PropertyToID("_EmissiveColorLDR");

			private readonly Renderer renderer;

			private readonly MaterialPropertyBlock originalBlock = new MaterialPropertyBlock();

			private readonly MaterialPropertyBlock tintBlock = new MaterialPropertyBlock();

			private bool capturedOriginalBlock;

			private bool hadOriginalBlock;

			private bool active;

			private Color appliedColor;

			private float appliedIntensity;

			public bool IsVisible
			{
				get
				{
					if ((Object)(object)renderer != (Object)null)
					{
						return renderer.isVisible;
					}
					return false;
				}
			}

			public RendererTint(Renderer renderer)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_000b: Expected O, but got Unknown
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Expected O, but got Unknown
				this.renderer = renderer;
			}

			public bool Apply(Color color, float intensity)
			{
				//IL_002c: 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_008b: 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)
				//IL_009b: 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_00c9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00da: Unknown result type (might be due to invalid IL or missing references)
				//IL_00eb: 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_010d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0125: Unknown result type (might be due to invalid IL or missing references)
				//IL_0126: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)renderer == (Object)null || !renderer.enabled)
				{
					Restore();
					return false;
				}
				if (active && appliedColor == color && appliedIntensity == intensity)
				{
					return true;
				}
				if (!capturedOriginalBlock)
				{
					renderer.GetPropertyBlock(originalBlock);
					hadOriginalBlock = !originalBlock.isEmpty;
					capturedOriginalBlock = true;
				}
				renderer.GetPropertyBlock(tintBlock);
				Color val = default(Color);
				((Color)(ref val))..ctor(color.r * intensity, color.g * intensity, color.b * intensity, 1f);
				tintBlock.SetColor(BaseColorId, color);
				tintBlock.SetColor(ColorId, color);
				tintBlock.SetColor(UnlitColorId, color);
				tintBlock.SetColor(EmissionColorId, val);
				tintBlock.SetColor(EmissiveColorId, val);
				tintBlock.SetColor(EmissiveColorLdrId, val);
				renderer.SetPropertyBlock(tintBlock);
				appliedColor = color;
				appliedIntensity = intensity;
				active = true;
				return true;
			}

			public void Restore()
			{
				if (!((Object)(object)renderer == (Object)null) && active)
				{
					renderer.SetPropertyBlock(hadOriginalBlock ? originalBlock : null);
					active = false;
				}
			}
		}

		private readonly NutcrackerEnemyAI nutcracker;

		private readonly List<RendererTint> tints = new List<RendererTint>();

		private bool built;

		private ModelWarningPhase lastTracedPhase;

		public NutcrackerModelTint(NutcrackerEnemyAI nutcracker)
		{
			this.nutcracker = nutcracker;
		}

		public void Dispose()
		{
			Restore();
		}

		public void Update(ModelWarningPhase phase)
		{
			//IL_0047: 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)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			if (phase == ModelWarningPhase.None || (Object)(object)nutcracker == (Object)null)
			{
				lastTracedPhase = ModelWarningPhase.None;
				Restore();
				return;
			}
			EnsureRenderers();
			bool num = phase == ModelWarningPhase.FireWindow;
			Color val = (Color)(num ? new Color(1f, 0.12f, 0.06f, 1f) : Color.white);
			float num2 = (num ? NutcrackerShotConfig.ModelFireWindowTintIntensity.Value : NutcrackerShotConfig.ModelChaseTintIntensity.Value);
			int num3 = 0;
			for (int i = 0; i < tints.Count; i++)
			{
				if (tints[i].Apply(val, num2))
				{
					num3++;
				}
			}
			if (lastTracedPhase != phase)
			{
				NutcrackerTimingTrace.Write($"enemy={((EnemyAI)nutcracker).thisEnemyIndex} tint={phase} appliedRenderers={num3} visibleRenderers={CountVisible()} rgb={val.r:0.00},{val.g:0.00},{val.b:0.00} intensity={num2:0.00}");
				lastTracedPhase = phase;
			}
		}

		private void EnsureRenderers()
		{
			if (built)
			{
				return;
			}
			built = true;
			Renderer[] componentsInChildren = ((Component)nutcracker).GetComponentsInChildren<Renderer>(false);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				if (IsTintRenderer(componentsInChildren[i]))
				{
					tints.Add(new RendererTint(componentsInChildren[i]));
				}
			}
		}

		private void Restore()
		{
			for (int i = 0; i < tints.Count; i++)
			{
				tints[i].Restore();
			}
		}

		private int CountVisible()
		{
			int num = 0;
			for (int i = 0; i < tints.Count; i++)
			{
				if (tints[i].IsVisible)
				{
					num++;
				}
			}
			return num;
		}

		private static bool IsTintRenderer(Renderer renderer)
		{
			if ((Object)(object)renderer == (Object)null)
			{
				return false;
			}
			string path = GetPath(((Component)renderer).transform);
			if (NutcrackerModelRendererFilter.IsExcludedPath(path))
			{
				return false;
			}
			SkinnedMeshRenderer val = (SkinnedMeshRenderer)(object)((renderer is SkinnedMeshRenderer) ? renderer : null);
			if ((Object)(object)val != (Object)null)
			{
				return NutcrackerModelRendererFilter.IsBody(path, ((Object)(object)val.sharedMesh == (Object)null) ? string.Empty : ((Object)val.sharedMesh).name);
			}
			MeshFilter component = ((Component)renderer).GetComponent<MeshFilter>();
			if ((Object)(object)component != (Object)null && (Object)(object)component.sharedMesh != (Object)null)
			{
				return NutcrackerModelRendererFilter.IsShotgun(path, ((Object)component.sharedMesh).name);
			}
			return false;
		}

		private static string GetPath(Transform transform)
		{
			string text = ((Object)transform).name;
			Transform parent = transform.parent;
			while ((Object)(object)parent != (Object)null)
			{
				text = ((Object)parent).name + "/" + text;
				parent = parent.parent;
			}
			return text;
		}
	}
	internal enum ModelWarningPhase
	{
		None,
		Aiming,
		FireWindow
	}
	internal static class NutcrackerModelWarningPhaseSelector
	{
		public static bool IsAiming(bool alive, int behaviourState, bool hasLoadedGun, bool reloading, bool aiming)
		{
			return alive && behaviourState == 2 && hasLoadedGun && !reloading && aiming;
		}

		public static ModelWarningPhase Select(bool fireWindowActive, bool aimingActive)
		{
			if (fireWindowActive)
			{
				return ModelWarningPhase.FireWindow;
			}
			if (!aimingActive)
			{
				return ModelWarningPhase.None;
			}
			return ModelWarningPhase.Aiming;
		}
	}
	[HarmonyPatch(typeof(NutcrackerEnemyAI))]
	internal static class NutcrackerPatches
	{
		private static readonly NutcrackerRpcExecutionReader RpcStage = new NutcrackerRpcExecutionReader(typeof(NutcrackerEnemyAI));

		private static readonly MethodBase UpdateMethod = AccessTools.Method(typeof(NutcrackerEnemyAI), "Update", (Type[])null, (Type[])null);

		internal static bool IsUpdateHookActive()
		{
			return Harmony.GetPatchInfo(UpdateMethod)?.Postfixes.Any((Patch patch) => patch.owner == "aueser.lethalcompany.nutcrackerfirewarning") ?? false;
		}

		internal static void LogRpcHooks()
		{
			NutcrackerTimingTrace.Write("Receive-stage reader: " + RpcStage.Description);
			string[] array = new string[3] { "AimGunClientRpc", "FireGunClientRpc", "ReloadGunClientRpc" };
			foreach (string text in array)
			{
				Patches patchInfo = Harmony.GetPatchInfo((MethodBase)AccessTools.Method(typeof(NutcrackerEnemyAI), text, (Type[])null, (Type[])null));
				if (RpcStage.IsAvailable && patchInfo != null && patchInfo.Prefixes.Any((Patch patch) => patch.owner == "aueser.lethalcompany.nutcrackerfirewarning") && patchInfo.Postfixes.Any((Patch patch) => patch.owner == "aueser.lethalcompany.nutcrackerfirewarning"))
				{
					NutcrackerTimingTrace.Write("Receive hook ready: " + text);
				}
				else
				{
					Plugin.Log.LogError((object)("[NutcrackerTiming] Receive hook unavailable: " + text));
				}
			}
		}

		private static bool IsClientReceive(NutcrackerEnemyAI owner)
		{
			if (NutcrackerShotConfig.IsModEnabled() && (Object)(object)owner != (Object)null && !((EnemyAI)owner).isEnemyDead && ((NetworkBehaviour)owner).IsClient)
			{
				return RpcStage.IsExecuting(owner);
			}
			return false;
		}

		[HarmonyPostfix]
		[HarmonyPatch("Update")]
		private static void UpdatePostfix(NutcrackerEnemyAI __instance)
		{
			if (NutcrackerShotConfig.IsModEnabled() && !((Object)(object)__instance == (Object)null) && !((EnemyAI)__instance).isEnemyDead && NutcrackerCombatStateReader.TryRead(__instance, out var combatState))
			{
				NutcrackerShotIndicator nutcrackerShotIndicator = NutcrackerShotIndicator.GetExisting(__instance);
				if ((Object)(object)nutcrackerShotIndicator == (Object)null && NutcrackerShotIndicator.ShouldCreateForCombatState(__instance, combatState))
				{
					nutcrackerShotIndicator = NutcrackerShotIndicator.For(__instance);
				}
				nutcrackerShotIndicator?.ObserveCombatState(combatState);
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch("AimGunClientRpc")]
		private static void AimGunClientRpcPrefix(NutcrackerEnemyAI __instance, out bool __state)
		{
			__state = IsClientReceive(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("AimGunClientRpc")]
		private static void AimGunClientRpcPostfix(NutcrackerEnemyAI __instance, bool __state)
		{
			if (__state)
			{
				ObserveSafely(__instance, "AimGunClientRpc", delegate
				{
					NutcrackerShotIndicator.For(__instance)?.BeginAim(NutcrackerCombatStateReader.GetAimDuration(__instance));
				});
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch("FireGunClientRpc")]
		private static void FireGunClientRpcPrefix(NutcrackerEnemyAI __instance, out bool __state)
		{
			__state = IsClientReceive(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("FireGunClientRpc")]
		private static void FireGunClientRpcPostfix(NutcrackerEnemyAI __instance, bool __state)
		{
			if (__state)
			{
				ObserveSafely(__instance, "FireGunClientRpc", delegate
				{
					NutcrackerShotIndicator.For(__instance)?.MarkFired();
				});
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch("ReloadGunClientRpc")]
		private static void ReloadGunClientRpcPrefix(NutcrackerEnemyAI __instance, out bool __state)
		{
			__state = IsClientReceive(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch("ReloadGunClientRpc")]
		private static void ReloadGunClientRpcPostfix(NutcrackerEnemyAI __instance, bool __state)
		{
			if (__state)
			{
				ObserveSafely(__instance, "ReloadGunClientRpc", delegate
				{
					NutcrackerShotIndicator.For(__instance)?.BeginReload();
				});
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch("StopAimingGun")]
		private static void StopAimingGunPostfix(NutcrackerEnemyAI __instance)
		{
			NutcrackerShotIndicator.GetExisting(__instance)?.CancelAim();
		}

		[HarmonyPostfix]
		[HarmonyPatch("StopReloading")]
		private static void StopReloadingPostfix(NutcrackerEnemyAI __instance)
		{
			NutcrackerShotIndicator existing = NutcrackerShotIndicator.GetExisting(__instance);
			if ((Object)(object)existing != (Object)null)
			{
				existing.CancelAim();
				existing.FinishReload();
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch("KillEnemy")]
		private static void KillEnemyPostfix(NutcrackerEnemyAI __instance)
		{
			NutcrackerShotIndicator.Remove(__instance);
		}

		private static void ObserveSafely(NutcrackerEnemyAI owner, string eventName, Action notification)
		{
			try
			{
				NutcrackerTimingTrace.Write($"enemy={((EnemyAI)owner).thisEnemyIndex} received={eventName}");
				notification();
			}
			catch (Exception arg)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)$"[NutcrackerTiming] Receive observation failed; native RPC already completed. {arg}");
				}
			}
		}
	}
	internal sealed class NutcrackerRpcExecutionReader
	{
		private readonly FieldInfo stageField;

		private readonly object executeStage;

		public bool IsAvailable => executeStage != null;

		public string Description { get; }

		public NutcrackerRpcExecutionReader(Type behaviourType)
		{
			Type type = behaviourType;
			while (type != null)
			{
				stageField = type.GetField("__rpc_exec_stage", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (stageField != null)
				{
					break;
				}
				type = type.BaseType;
			}
			if (stageField != null && stageField.FieldType.IsEnum && Enum.IsDefined(stageField.FieldType, "Execute"))
			{
				executeStage = Enum.Parse(stageField.FieldType, "Execute");
				Description = $"{stageField.DeclaringType.FullName}.{stageField.Name} Execute={Convert.ToInt32(executeStage)}";
			}
			else
			{
				Description = "RPC execution-stage field or Execute enum value unavailable";
			}
		}

		public bool IsExecuting(object behaviour)
		{
			if (!IsAvailable || behaviour == null)
			{
				return false;
			}
			try
			{
				return executeStage.Equals(stageField.GetValue(behaviour));
			}
			catch (ArgumentException)
			{
				return false;
			}
			catch (TargetException)
			{
				return false;
			}
		}
	}
	internal sealed class NutcrackerSessionLifetime
	{
		private readonly Action removeHooks;

		public bool IsQuitting { get; private set; }

		public bool PluginComponentDestroyed { get; private set; }

		public NutcrackerSessionLifetime(Action removeHooks)
		{
			this.removeHooks = removeHooks ?? throw new ArgumentNullException("removeHooks");
		}

		public void OnPluginComponentDestroyed()
		{
			PluginComponentDestroyed = true;
		}

		public void Quit()
		{
			if (!IsQuitting)
			{
				IsQuitting = true;
				removeHooks();
			}
		}
	}
	internal static class NutcrackerShotConfig
	{
		public static ConfigEntry<bool> EnableMod { get; private set; }

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

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

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

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

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

		public static void Bind(ConfigFile config, NutcrackerConfigText text)
		{
			EnableMod = config.Bind<bool>("General", "EnableMod", true, text.Description("EnableMod"));
			FireWindowSeconds = BindFloat(config, text, "FireWindowSeconds", 0.35f, 0.05f, 2f);
			ModelChaseTintIntensity = BindFloat(config, text, "ModelChaseTintIntensity", 1f, 0f, 12f);
			ModelFireWindowTintIntensity = BindFloat(config, text, "ModelFireWindowTintIntensity", 1f, 0f, 12f);
			ModelWarningMaxDistance = BindFloat(config, text, "ModelWarningMaxDistance", 45f, 0f, 100f);
			EnableDebugLogs = config.Bind<bool>("Debug", "EnableDebugLogs", false, text.Description("EnableDebugLogs"));
		}

		public static bool IsModEnabled()
		{
			if (EnableMod != null)
			{
				return EnableMod.Value;
			}
			return true;
		}

		private static ConfigEntry<float> BindFloat(ConfigFile config, NutcrackerConfigText text, string key, float value, float min, float max)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			return config.Bind<float>("Warnings", key, value, new ConfigDescription(text.Description(key), (AcceptableValueBase)(object)new AcceptableValueRange<float>(min, max), Array.Empty<object>()));
		}
	}
	internal sealed class NutcrackerShotIndicator : MonoBehaviour
	{
		private static readonly Dictionary<NutcrackerEnemyAI, NutcrackerShotIndicator> Indicators = new Dictionary<NutcrackerEnemyAI, NutcrackerShotIndicator>();

		private NutcrackerEnemyAI nutcracker;

		private NutcrackerModelTint modelTint;

		private readonly NutcrackerWarningTimeline timeline = new NutcrackerWarningTimeline();

		private NutcrackerCombatState lastCombatState;

		private ModelWarningPhase lastTracedPhase;

		public static NutcrackerShotIndicator For(NutcrackerEnemyAI nutcracker)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			if (!NutcrackerShotConfig.IsModEnabled() || (Object)(object)nutcracker == (Object)null)
			{
				return null;
			}
			NutcrackerShotIndicator existing = GetExisting(nutcracker);
			if ((Object)(object)existing != (Object)null)
			{
				return existing;
			}
			GameObject val = new GameObject("NutcrackerShotUI");
			val.transform.SetParent(((Component)nutcracker).transform, false);
			existing = val.AddComponent<NutcrackerShotIndicator>();
			try
			{
				existing.Initialize(nutcracker);
			}
			catch
			{
				Object.Destroy((Object)(object)val);
				throw;
			}
			Indicators[nutcracker] = existing;
			return existing;
		}

		public static NutcrackerShotIndicator GetExisting(NutcrackerEnemyAI nutcracker)
		{
			if ((Object)(object)nutcracker == (Object)null)
			{
				return null;
			}
			if (Indicators.TryGetValue(nutcracker, out var value))
			{
				if ((Object)(object)value != (Object)null)
				{
					return value;
				}
				Indicators.Remove(nutcracker);
			}
			return null;
		}

		public static bool ShouldCreateForCombatState(NutcrackerEnemyAI nutcracker, NutcrackerCombatState combatState)
		{
			if (NutcrackerShotConfig.IsModEnabled() && (Object)(object)nutcracker != (Object)null && !((EnemyAI)nutcracker).isEnemyDead)
			{
				if (!combatState.AimingGun)
				{
					return combatState.ReloadingGun;
				}
				return true;
			}
			return false;
		}

		public static void Remove(NutcrackerEnemyAI nutcracker)
		{
			if (!((Object)(object)nutcracker == (Object)null))
			{
				NutcrackerShotIndicator existing = GetExisting(nutcracker);
				if ((Object)(object)existing != (Object)null)
				{
					Indicators.Remove(nutcracker);
					Object.Destroy((Object)(object)((Component)existing).gameObject);
				}
			}
		}

		public void BeginAim(float duration)
		{
			if (NutcrackerShotConfig.IsModEnabled())
			{
				timeline.BeginAim(Time.time, duration, ((EnemyAI)nutcracker).stunNormalizedTimer > 0f);
				NutcrackerTimingTrace.Write($"enemy={((EnemyAI)nutcracker).thisEnemyIndex} aim-start duration={duration:0.000} shells={nutcracker.gun?.shellsLoaded ?? (-1)} hp={((EnemyAI)nutcracker).enemyHP}");
				UpdateModelWarningPhase(fireWindowActive: false);
			}
		}

		public void MarkFired()
		{
			if (NutcrackerShotConfig.IsModEnabled())
			{
				timeline.MarkFired(Time.time);
				NutcrackerTimingTrace.Write($"enemy={((EnemyAI)nutcracker).thisEnemyIndex} shot-confirmed shells={nutcracker.gun?.shellsLoaded ?? (-1)}");
				UpdateModelWarningPhase(fireWindowActive: true);
			}
		}

		public void BeginReload()
		{
			if (NutcrackerShotConfig.IsModEnabled())
			{
				timeline.BeginReload(Time.time);
			}
		}

		public void CancelAim()
		{
			timeline.CancelAim();
			SetModelWarningPhase(ModelWarningPhase.None);
		}

		public void FinishReload()
		{
			timeline.FinishReload();
		}

		public void ObserveCombatState(NutcrackerCombatState combatState)
		{
			lastCombatState = combatState;
			if (NutcrackerShotConfig.IsModEnabled())
			{
				WarningState state = timeline.State;
				timeline.Observe(Time.time, combatState.AimingGun, combatState.ReloadingGun, combatState.Stunned);
				if (state != WarningState.AwaitingShot && timeline.State == WarningState.AwaitingShot && !timeline.HasKnownAimStart)
				{
					NutcrackerTimingTrace.Write($"enemy={((EnemyAI)nutcracker).thisEnemyIndex} missing-start-event; observed aiming uses white fallback");
				}
			}
		}

		private void Initialize(NutcrackerEnemyAI owner)
		{
			nutcracker = owner;
			modelTint = new NutcrackerModelTint(owner);
		}

		private void OnDestroy()
		{
			modelTint?.Dispose();
			if (nutcracker != null && Indicators.TryGetValue(nutcracker, out var value) && (Object)(object)value == (Object)(object)this)
			{
				Indicators.Remove(nutcracker);
			}
		}

		private void OnDisable()
		{
			SetModelWarningPhase(ModelWarningPhase.None);
		}

		private void LateUpdate()
		{
			if (!NutcrackerShotConfig.IsModEnabled() || (Object)(object)nutcracker == (Object)null || ((EnemyAI)nutcracker).isEnemyDead)
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
			else
			{
				UpdateState();
			}
		}

		private void UpdateState()
		{
			if ((Object)(object)nutcracker.gun == (Object)null || !((GrabbableObject)nutcracker.gun).isHeldByEnemy)
			{
				timeline.Reset();
				SetModelWarningPhase(ModelWarningPhase.None);
			}
			else
			{
				timeline.Advance(Time.time);
				UpdateModelWarningPhase(timeline.IsFireWindow(Time.time, NutcrackerShotConfig.FireWindowSeconds.Value));
			}
		}

		private void SetModelWarningPhase(ModelWarningPhase phase)
		{
			if (phase != ModelWarningPhase.None || lastTracedPhase != ModelWarningPhase.None)
			{
				if (phase != lastTracedPhase)
				{
					NutcrackerTimingTrace.Write($"enemy={((EnemyAI)nutcracker).thisEnemyIndex} phase={phase} state={timeline.State} knownStart={timeline.HasKnownAimStart} remaining={timeline.Remaining(Time.time):0.000} stunned={timeline.IsStunned}");
					lastTracedPhase = phase;
				}
				modelTint?.Update(phase);
			}
		}

		private void UpdateModelWarningPhase(bool fireWindowActive)
		{
			bool flag = IsAimTintCandidate();
			if (!fireWindowActive && !flag)
			{
				SetModelWarningPhase(ModelWarningPhase.None);
				return;
			}
			bool flag2 = IsWithinWarningDistance();
			bool flag3 = (Object)(object)nutcracker != (Object)null && !((EnemyAI)nutcracker).isEnemyDead && (Object)(object)nutcracker.gun != (Object)null && ((GrabbableObject)nutcracker.gun).isHeldByEnemy;
			SetModelWarningPhase(NutcrackerModelWarningPhaseSelector.Select(fireWindowActive && flag3 && flag2, flag && flag2));
		}

		private bool IsWithinWarningDistance()
		{
			//IL_0089: 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_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: 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_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: 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)
			PlayerControllerB val = GameNetworkManager.Instance?.localPlayerController;
			Camera val2 = (((Object)(object)val != (Object)null && (Object)(object)val.gameplayCamera != (Object)null) ? val.gameplayCamera : Camera.main);
			if ((Object)(object)val != (Object)null && val.isPlayerDead)
			{
				return false;
			}
			float value = NutcrackerShotConfig.ModelWarningMaxDistance.Value;
			if (value > 0f)
			{
				Vector3 val3 = (((Object)(object)val2 != (Object)null) ? ((Component)val2).transform.position : (((Object)(object)val != (Object)null) ? ((Component)val).transform.position : Vector3.zero));
				if (val3 != Vector3.zero && Vector3.Distance(val3, ((Component)nutcracker).transform.position) > value)
				{
					return false;
				}
			}
			return true;
		}

		private bool IsAimTintCandidate()
		{
			if ((Object)(object)nutcracker == (Object)null)
			{
				return false;
			}
			return NutcrackerModelWarningPhaseSelector.IsAiming(!((EnemyAI)nutcracker).isEnemyDead, ((EnemyAI)nutcracker).currentBehaviourStateIndex, (Object)(object)nutcracker.gun != (Object)null && ((GrabbableObject)nutcracker.gun).isHeldByEnemy && nutcracker.gun.shellsLoaded > 0, lastCombatState.ReloadingGun, timeline.IsAiming);
		}
	}
	internal sealed class NutcrackerShotMonitor : MonoBehaviour
	{
		private const float HookAuditInterval = 5f;

		private const float ActiveScanInterval = 0.5f;

		private const float IdleScanInterval = 2f;

		private float nextScanTime;

		private float nextHookAuditTime;

		private bool updateHookActive;

		private int lastObservedCount = -1;

		private void Awake()
		{
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
		}

		private void OnApplicationQuit()
		{
			Plugin.ShutdownSession();
		}

		private void Update()
		{
			if (!NutcrackerShotConfig.IsModEnabled())
			{
				nextScanTime = Time.time + 2f;
				return;
			}
			if (Time.time >= nextHookAuditTime)
			{
				AuditUpdateHook();
			}
			if (updateHookActive || Time.time < nextScanTime)
			{
				return;
			}
			NutcrackerEnemyAI[] array = Object.FindObjectsOfType<NutcrackerEnemyAI>();
			nextScanTime = Time.time + ((array.Length != 0) ? 0.5f : 2f);
			if (IsDebugLoggingEnabled() && array.Length != lastObservedCount)
			{
				lastObservedCount = array.Length;
				Plugin.Log.LogInfo((object)$"Nutcracker monitor found {array.Length} NutcrackerEnemyAI instance(s).");
			}
			foreach (NutcrackerEnemyAI val in array)
			{
				if (!((Object)(object)val == (Object)null) && !((EnemyAI)val).isEnemyDead && NutcrackerCombatStateReader.TryRead(val, out var combatState))
				{
					NutcrackerShotIndicator nutcrackerShotIndicator = NutcrackerShotIndicator.GetExisting(val);
					if ((Object)(object)nutcrackerShotIndicator == (Object)null && NutcrackerShotIndicator.ShouldCreateForCombatState(val, combatState))
					{
						nutcrackerShotIndicator = NutcrackerShotIndicator.For(val);
					}
					nutcrackerShotIndicator?.ObserveCombatState(combatState);
				}
			}
		}

		private void AuditUpdateHook()
		{
			bool flag = NutcrackerPatches.IsUpdateHookActive();
			if (updateHookActive && !flag)
			{
				Plugin.Log.LogWarning((object)"[NutcrackerLifecycle] Nutcracker Update hook is missing; using the fallback monitor scan.");
			}
			updateHookActive = flag;
			nextHookAuditTime = Time.time + 5f;
		}

		private static bool IsDebugLoggingEnabled()
		{
			if (NutcrackerShotConfig.EnableDebugLogs != null)
			{
				return NutcrackerShotConfig.EnableDebugLogs.Value;
			}
			return false;
		}
	}
	internal static class NutcrackerTimingTrace
	{
		public static void Write(string message)
		{
			if (NutcrackerShotConfig.EnableDebugLogs != null && NutcrackerShotConfig.EnableDebugLogs.Value)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogInfo((object)("[NutcrackerTiming] " + message));
				}
			}
		}
	}
	internal static class NutcrackerTintPalette
	{
		internal const float DefaultAimIntensity = 1f;

		internal const float DefaultFireWindowIntensity = 1f;

		internal const float FireRed = 1f;

		internal const float FireGreen = 0.12f;

		internal const float FireBlue = 0.06f;
	}
	internal enum WarningState
	{
		Idle,
		Aiming,
		AwaitingShot,
		Fired,
		Reloading
	}
	internal sealed class NutcrackerWarningTimeline
	{
		internal const float FiredHoldTime = 0.35f;

		internal const float ShotTintHoldTime = 0.12f;

		internal const float ShotArrivalGraceTime = 0.25f;

		internal const float ReloadDuration = 1.74f;

		private bool observedAiming;

		private bool observedReloading;

		private bool suppressObservedAim;

		private bool hasKnownAimStart;

		private bool shotTimingInvalidated;

		public WarningState State { get; private set; }

		public float StartedAt { get; private set; }

		public float Duration { get; private set; }

		public bool IsStunned { get; private set; }

		public bool HasKnownAimStart => hasKnownAimStart;

		public bool IsAiming
		{
			get
			{
				if (observedAiming)
				{
					if (State != WarningState.Aiming)
					{
						if (State == WarningState.AwaitingShot)
						{
							return !hasKnownAimStart;
						}
						return false;
					}
					return true;
				}
				return false;
			}
		}

		public void BeginAim(float now, float duration, bool stunned = false)
		{
			State = WarningState.Aiming;
			StartedAt = now;
			Duration = (IsPositiveFinite(duration) ? duration : 0.5f);
			IsStunned = stunned;
			hasKnownAimStart = true;
			shotTimingInvalidated = false;
			observedAiming = true;
			observedReloading = false;
			suppressObservedAim = false;
		}

		public void MarkFired(float now)
		{
			State = WarningState.Fired;
			StartedAt = now;
			Duration = 0.35f;
			suppressObservedAim = true;
		}

		public void BeginReload(float now)
		{
			State = WarningState.Reloading;
			StartedAt = now;
			Duration = 1.74f;
			observedReloading = true;
			suppressObservedAim = true;
		}

		public void CancelAim()
		{
			if (State == WarningState.Aiming || State == WarningState.AwaitingShot)
			{
				State = WarningState.Idle;
			}
			suppressObservedAim = true;
		}

		public void FinishReload()
		{
			if (State == WarningState.Reloading)
			{
				State = WarningState.Idle;
			}
		}

		public void Reset()
		{
			State = WarningState.Idle;
			observedAiming = false;
			observedReloading = false;
			suppressObservedAim = false;
			IsStunned = false;
			hasKnownAimStart = false;
			shotTimingInvalidated = false;
		}

		public void Observe(float now, bool aimingGun, bool reloadingGun, bool stunned = false)
		{
			IsStunned = stunned;
			if (stunned && hasKnownAimStart && now >= StartedAt + Duration && (State == WarningState.Aiming || State == WarningState.AwaitingShot))
			{
				shotTimingInvalidated = true;
			}
			if (!aimingGun)
			{
				suppressObservedAim = false;
			}
			if (reloadingGun)
			{
				if (!observedReloading)
				{
					BeginReload(now);
				}
			}
			else
			{
				FinishReload();
				if (aimingGun && !observedAiming && !suppressObservedAim)
				{
					State = WarningState.AwaitingShot;
					hasKnownAimStart = false;
					StartedAt = now;
					Duration = 0f;
				}
			}
			observedAiming = aimingGun;
			observedReloading = reloadingGun;
			Advance(now);
		}

		public void Advance(float now)
		{
			if (State == WarningState.Aiming && Remaining(now) <= 0f)
			{
				shotTimingInvalidated |= IsStunned;
				State = WarningState.AwaitingShot;
			}
			else if (State == WarningState.Fired && Remaining(now) <= 0f)
			{
				State = WarningState.Idle;
			}
		}

		public float Remaining(float now)
		{
			return Math.Max(0f, Duration - Math.Max(0f, now - StartedAt));
		}

		public float Progress(float now)
		{
			if (!(Duration > 0f))
			{
				return 1f;
			}
			return Math.Min(1f, Math.Max(0f, now - StartedAt) / Duration);
		}

		public float GetFireWindowSeconds(float configuredSeconds)
		{
			float val = (IsPositiveFinite(configuredSeconds) ? configuredSeconds : 0.35f);
			return Math.Min(Duration * 0.5f, Math.Max(0.05f, val));
		}

		public bool IsFireWindow(float now, float windowSeconds)
		{
			if (State == WarningState.Fired)
			{
				return now - StartedAt < 0.12f;
			}
			if (!hasKnownAimStart || IsStunned || shotTimingInvalidated || (State != WarningState.Aiming && State != WarningState.AwaitingShot))
			{
				return false;
			}
			float num = now - StartedAt - Duration;
			if (num >= 0f - GetFireWindowSeconds(windowSeconds))
			{
				return num < 0.25f;
			}
			return false;
		}

		private static bool IsPositiveFinite(float value)
		{
			if (value > 0f)
			{
				return !float.IsInfinity(value);
			}
			return false;
		}
	}
	[BepInPlugin("aueser.lethalcompany.nutcrackerfirewarning", "Nutcracker Fire Warning", "1.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "aueser.lethalcompany.nutcrackerfirewarning";

		public const string PluginName = "Nutcracker Fire Warning";

		public const string PluginVersion = "1.1.0";

		private static NutcrackerSessionLifetime session;

		internal static ManualLogSource Log { get; private set; }

		private void Awake()
		{
			//IL_0040: 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)
			//IL_0051: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			bool flag = NutcrackerConfigLanguageDetector.ShouldUseChineseConfig();
			NutcrackerConfigText text = new NutcrackerConfigText(flag);
			NutcrackerShotConfig.Bind(((BaseUnityPlugin)this).Config, text);
			if (Chainloader.PluginInfos.ContainsKey("ainavt.lc.lethalconfig"))
			{
				NutcrackerLethalConfig.Register(text);
			}
			Harmony val = new Harmony("aueser.lethalcompany.nutcrackerfirewarning");
			session = new NutcrackerSessionLifetime((Action)val.UnpatchSelf);
			Application.quitting += ShutdownSession;
			CreateMonitor();
			val.PatchAll(typeof(Plugin).Assembly);
			NutcrackerPatches.LogRpcHooks();
			((BaseUnityPlugin)this).Logger.LogInfo((object)string.Format("{0} {1} loaded. enabled={2}, chinese={3}, debug={4}.", "Nutcracker Fire Warning", "1.1.0", NutcrackerShotConfig.EnableMod.Value, flag, NutcrackerShotConfig.EnableDebugLogs.Value));
		}

		private void OnDestroy()
		{
			session?.OnPluginComponentDestroyed();
			if (session != null && !session.IsQuitting)
			{
				NutcrackerTimingTrace.Write("Plugin component destroyed before application quit; session hooks preserved.");
				NutcrackerPatches.LogRpcHooks();
			}
		}

		internal static void ShutdownSession()
		{
			if (session != null && !session.IsQuitting)
			{
				Application.quitting -= ShutdownSession;
				NutcrackerTimingTrace.Write("Application quitting; removing session hooks.");
				session.Quit();
			}
		}

		private static void CreateMonitor()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			new GameObject("NutcrackerShotUIMonitor")
			{
				hideFlags = (HideFlags)61
			}.AddComponent<NutcrackerShotMonitor>();
		}
	}
}