Decompiled source of ModpackFixes v1.0.0

plugins/ModpackFixes.dll

Decompiled 5 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using TMPro;
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("ModpackFixes")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ModpackFixes")]
[assembly: AssemblyTitle("ModpackFixes")]
[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.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[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 ModpackFixes
{
	internal static class AnimatronicHurtModule
	{
		internal sealed class AnimatronicHurtEffect : MonoBehaviour
		{
			public bool IsFreddy;

			public Component? FreddyController;

			private Transform? _visualTarget;

			private readonly List<Renderer> _renderers = new List<Renderer>();

			private AudioSource? _hurtSource;

			private ParticleSystem? _fallbackSparks;

			private Coroutine? _flashRoutine;

			private Coroutine? _flinchRoutine;

			private float _lastHurtTime = -99f;

			private Vector3 _baseLocalPos;

			private Quaternion _baseLocalRot;

			private bool _capturedBaseTransform;

			private void Awake()
			{
				CollectRenderers();
				EnsureAudioSource();
				FindVisualTarget();
			}

			private void CollectRenderers()
			{
				_renderers.Clear();
				Renderer[] componentsInChildren = ((Component)this).GetComponentsInChildren<Renderer>(true);
				foreach (Renderer val in componentsInChildren)
				{
					if (val is SkinnedMeshRenderer || val is MeshRenderer)
					{
						_renderers.Add(val);
					}
				}
			}

			private void FindVisualTarget()
			{
				//IL_0075: Unknown result type (might be due to invalid IL or missing references)
				//IL_007a: 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_008b: Unknown result type (might be due to invalid IL or missing references)
				Animator componentInChildren = ((Component)this).GetComponentInChildren<Animator>(true);
				if ((Object)(object)componentInChildren != (Object)null && (Object)(object)((Component)componentInChildren).transform != (Object)(object)((Component)this).transform)
				{
					_visualTarget = ((Component)componentInChildren).transform;
				}
				else if (((Component)this).transform.childCount > 0)
				{
					_visualTarget = ((Component)this).transform.GetChild(0);
				}
				else
				{
					_visualTarget = ((Component)this).transform;
				}
				if ((Object)(object)_visualTarget != (Object)null)
				{
					_baseLocalPos = _visualTarget.localPosition;
					_baseLocalRot = _visualTarget.localRotation;
					_capturedBaseTransform = true;
				}
			}

			private void EnsureAudioSource()
			{
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Expected O, but got Unknown
				if (!((Object)(object)_hurtSource != (Object)null))
				{
					GameObject val = new GameObject("Factor_AnimatronicHurtAudio");
					val.transform.SetParent(((Component)this).transform, false);
					_hurtSource = val.AddComponent<AudioSource>();
					_hurtSource.playOnAwake = false;
					_hurtSource.spatialBlend = 1f;
					_hurtSource.rolloffMode = (AudioRolloffMode)1;
					_hurtSource.minDistance = 2f;
					_hurtSource.maxDistance = 30f;
					if ((Object)(object)AudioManager.instance != (Object)null && (Object)(object)AudioManager.instance.SoundMasterGroup != (Object)null)
					{
						_hurtSource.outputAudioMixerGroup = AudioManager.instance.SoundMasterGroup;
					}
				}
			}

			private void EnsureFallbackSparks()
			{
				//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)
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0040: 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_0052: 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_0080: Unknown result type (might be due to invalid IL or missing references)
				//IL_0096: 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_00cc: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
				//IL_010e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0113: Unknown result type (might be due to invalid IL or missing references)
				//IL_011d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0122: Unknown result type (might be due to invalid IL or missing references)
				//IL_0178: Unknown result type (might be due to invalid IL or missing references)
				//IL_0182: Expected O, but got Unknown
				if ((Object)(object)_fallbackSparks != (Object)null)
				{
					return;
				}
				GameObject val = new GameObject("Factor_AnimatronicHurtSparks");
				val.transform.SetParent(((Component)this).transform, false);
				val.transform.localPosition = new Vector3(0f, 1.15f, 0f);
				ParticleSystem val2 = val.AddComponent<ParticleSystem>();
				MainModule main = val2.main;
				((MainModule)(ref main)).playOnAwake = false;
				((MainModule)(ref main)).loop = false;
				((MainModule)(ref main)).duration = 0.25f;
				((MainModule)(ref main)).startLifetime = new MinMaxCurve(0.18f, 0.35f);
				((MainModule)(ref main)).startSpeed = new MinMaxCurve(2.2f, 5.5f);
				((MainModule)(ref main)).startSize = new MinMaxCurve(0.03f, 0.08f);
				((MainModule)(ref main)).startColor = new MinMaxGradient(new Color(1f, 0.85f, 0.25f, 1f), new Color(1f, 0.45f, 0.1f, 1f));
				((MainModule)(ref main)).gravityModifier = MinMaxCurve.op_Implicit(1.2f);
				((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1;
				EmissionModule emission = val2.emission;
				((EmissionModule)(ref emission)).enabled = false;
				ShapeModule shape = val2.shape;
				((ShapeModule)(ref shape)).enabled = true;
				((ShapeModule)(ref shape)).shapeType = (ParticleSystemShapeType)0;
				((ShapeModule)(ref shape)).radius = 0.22f;
				ParticleSystemRenderer component = val.GetComponent<ParticleSystemRenderer>();
				if ((Object)(object)component != (Object)null)
				{
					Shader val3 = Shader.Find("Sprites/Default") ?? Shader.Find("Universal Render Pipeline/Unlit");
					if ((Object)(object)val3 != (Object)null)
					{
						((Renderer)component).material = new Material(val3);
					}
				}
				_fallbackSparks = val2;
			}

			public void TriggerHurt(Vector3 hurtDirection)
			{
				//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
				float unscaledTime = Time.unscaledTime;
				if (unscaledTime - _lastHurtTime < 0.06f)
				{
					return;
				}
				_lastHurtTime = unscaledTime;
				PlayHurtSound();
				EmitSparks();
				float num = _flashDuration?.Value ?? 0.16f;
				if (num > 0.01f && _renderers.Count > 0)
				{
					if (_flashRoutine != null)
					{
						((MonoBehaviour)this).StopCoroutine(_flashRoutine);
					}
					_flashRoutine = ((MonoBehaviour)this).StartCoroutine(FlashRoutine(num));
				}
				float num2 = _flinchIntensity?.Value ?? 1f;
				if (num2 > 0.01f && (Object)(object)_visualTarget != (Object)null)
				{
					if (_flinchRoutine != null)
					{
						((MonoBehaviour)this).StopCoroutine(_flinchRoutine);
						RestoreVisualTransform();
					}
					_flinchRoutine = ((MonoBehaviour)this).StartCoroutine(FlinchRoutine(hurtDirection, num2));
				}
			}

			private void PlayHurtSound()
			{
				EnsureAudioSource();
				if ((Object)(object)_hurtSource == (Object)null)
				{
					return;
				}
				AudioClip val = null;
				if (IsFreddy && (Object)(object)FreddyController != (Object)null && _freddyAnimatorField != null && _freddySfxHurtField != null)
				{
					object value = _freddyAnimatorField.GetValue(FreddyController);
					if (value != null)
					{
						object? value2 = _freddySfxHurtField.GetValue(value);
						Sound val2 = (Sound)((value2 is Sound) ? value2 : null);
						if (val2 != null)
						{
							if (val2.Sounds != null && val2.Sounds.Length != 0)
							{
								AudioClip[] sounds = val2.Sounds;
								foreach (AudioClip val3 in sounds)
								{
									if ((Object)(object)val3 != (Object)null)
									{
										val = val3;
										break;
									}
								}
							}
							if ((Object)(object)val == (Object)null)
							{
								val = FindFreddyBundledHurtClip();
								if ((Object)(object)val != (Object)null)
								{
									val2.Sounds = (AudioClip[])(object)new AudioClip[1] { val };
								}
							}
							if (val2.Sounds != null && val2.Sounds.Length != 0 && val2.Volume < 0.5f)
							{
								val2.Volume = 0.85f;
							}
						}
					}
				}
				if ((Object)(object)val == (Object)null)
				{
					val = GetProceduralMetallicHurtClip();
				}
				_hurtSource.pitch = Random.Range(0.9f, 1.12f);
				float num = Mathf.Clamp(_hurtSoundVolume?.Value ?? 0.85f, 0f, 2f);
				_hurtSource.PlayOneShot(val, num);
			}

			private void EmitSparks()
			{
				if (IsFreddy && (Object)(object)FreddyController != (Object)null && _freddyAnimatorField != null && _freddySparkParticlesField != null)
				{
					object value = _freddyAnimatorField.GetValue(FreddyController);
					if (value != null)
					{
						object? value2 = _freddySparkParticlesField.GetValue(value);
						ParticleSystem val = (ParticleSystem)((value2 is ParticleSystem) ? value2 : null);
						if (val != null && (Object)(object)val != (Object)null)
						{
							val.Emit(14);
							return;
						}
					}
				}
				EnsureFallbackSparks();
				ParticleSystem? fallbackSparks = _fallbackSparks;
				if (fallbackSparks != null)
				{
					fallbackSparks.Emit(12);
				}
			}

			private IEnumerator FlashRoutine(float duration)
			{
				List<(Material Mat, bool HasOverlayColor, Color PrevOverlayColor, bool HasOverlayAmt, float PrevOverlayAmt, bool HasEmission, Color PrevEmission, bool WasEmissionEnabled)> snapshots = new List<(Material, bool, Color, bool, float, bool, Color, bool)>();
				HashSet<Material> hashSet = new HashSet<Material>();
				foreach (Renderer renderer in _renderers)
				{
					if ((Object)(object)renderer == (Object)null)
					{
						continue;
					}
					Material[] materials = renderer.materials;
					foreach (Material val in materials)
					{
						if ((Object)(object)val == (Object)null || !hashSet.Add(val))
						{
							continue;
						}
						bool flag = val.HasProperty(ColorOverlayId);
						bool flag2 = val.HasProperty(ColorOverlayAmountId);
						bool flag3 = val.HasProperty(EmissionColorId);
						if (flag || flag2 || flag3)
						{
							Color item = (flag ? val.GetColor(ColorOverlayId) : Color.clear);
							float item2 = (flag2 ? val.GetFloat(ColorOverlayAmountId) : 0f);
							Color item3 = (flag3 ? val.GetColor(EmissionColorId) : Color.black);
							bool item4 = val.IsKeywordEnabled("_EMISSION");
							if (flag)
							{
								val.SetColor(ColorOverlayId, new Color(1f, 0.12f, 0.08f, 1f));
							}
							if (flag3)
							{
								val.EnableKeyword("_EMISSION");
							}
							snapshots.Add((val, flag, item, flag2, item2, flag3, item3, item4));
						}
					}
				}
				float elapsed = 0f;
				while (elapsed < duration)
				{
					float num = 1f - Mathf.Clamp01(elapsed / duration);
					foreach (var item5 in snapshots)
					{
						if (!((Object)(object)item5.Mat == (Object)null))
						{
							if (item5.HasOverlayAmt)
							{
								item5.Mat.SetFloat(ColorOverlayAmountId, Mathf.Lerp(item5.PrevOverlayAmt, 0.85f, num));
							}
							if (item5.HasEmission)
							{
								item5.Mat.SetColor(EmissionColorId, Color.Lerp(item5.PrevEmission, new Color(1.4f, 0.18f, 0.08f, 1f), num));
							}
						}
					}
					elapsed += Time.deltaTime;
					yield return null;
				}
				foreach (var item6 in snapshots)
				{
					if ((Object)(object)item6.Mat == (Object)null)
					{
						continue;
					}
					if (item6.HasOverlayColor)
					{
						item6.Mat.SetColor(ColorOverlayId, item6.PrevOverlayColor);
					}
					if (item6.HasOverlayAmt)
					{
						item6.Mat.SetFloat(ColorOverlayAmountId, item6.PrevOverlayAmt);
					}
					if (item6.HasEmission)
					{
						item6.Mat.SetColor(EmissionColorId, item6.PrevEmission);
						if (!item6.Rest.Item1)
						{
							item6.Mat.DisableKeyword("_EMISSION");
						}
					}
				}
				_flashRoutine = null;
			}

			private IEnumerator FlinchRoutine(Vector3 hurtDirection, float intensity)
			{
				//IL_000e: 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)
				if (!((Object)(object)_visualTarget == (Object)null))
				{
					if (!_capturedBaseTransform)
					{
						_baseLocalPos = _visualTarget.localPosition;
						_baseLocalRot = _visualTarget.localRotation;
						_capturedBaseTransform = true;
					}
					Vector3 val = ((Component)this).transform.InverseTransformDirection((((Vector3)(ref hurtDirection)).sqrMagnitude > 0.001f) ? ((Vector3)(ref hurtDirection)).normalized : (-((Component)this).transform.forward));
					Vector3 kickOffset = new Vector3(val.x, 0f, val.z) * (0.14f * intensity);
					Vector3 eulerKick = new Vector3(-14f * intensity, Random.Range(-10f, 10f) * intensity, Random.Range(-12f, 12f) * intensity);
					float elapsed = 0f;
					while (elapsed < 0.22f && (Object)(object)_visualTarget != (Object)null)
					{
						float num = Mathf.Clamp01(elapsed / 0.22f);
						float num2 = Mathf.Sin(num * MathF.PI) * (1f - num * 0.35f);
						float num3 = Mathf.Sin(num * MathF.PI * 5f) * (1f - num);
						_visualTarget.localPosition = _baseLocalPos + kickOffset * num2;
						_visualTarget.localRotation = _baseLocalRot * Quaternion.Euler(eulerKick * num2 + new Vector3(0f, 0f, num3 * 4f * intensity));
						elapsed += Time.deltaTime;
						yield return null;
					}
					RestoreVisualTransform();
					_flinchRoutine = null;
				}
			}

			private void RestoreVisualTransform()
			{
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)_visualTarget != (Object)null && _capturedBaseTransform)
				{
					_visualTarget.localPosition = _baseLocalPos;
					_visualTarget.localRotation = _baseLocalRot;
				}
			}

			private void OnDisable()
			{
				RestoreVisualTransform();
				_flashRoutine = null;
				_flinchRoutine = null;
			}
		}

		private static ConfigEntry<bool>? _enableFreddy;

		private static ConfigEntry<bool>? _enableMimic;

		private static ConfigEntry<float>? _hurtSoundVolume;

		private static ConfigEntry<float>? _flashDuration;

		private static ConfigEntry<float>? _flinchIntensity;

		private static Type? _freddyType;

		private static Type? _mimicType;

		private static FieldInfo? _freddyAnimatorField;

		private static FieldInfo? _freddySfxHurtField;

		private static FieldInfo? _freddySparkParticlesField;

		private static AudioClip? _freddyClipCached;

		private static bool _searchedFreddyClip;

		private static AudioClip? _proceduralMetallicHurtClip;

		private static readonly int ColorOverlayId = Shader.PropertyToID("_ColorOverlay");

		private static readonly int ColorOverlayAmountId = Shader.PropertyToID("_ColorOverlayAmount");

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

		internal static void Init(ConfigFile config, Harmony harmony)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Expected O, but got Unknown
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Expected O, but got Unknown
			_enableFreddy = config.Bind<bool>("AnimatronicHurtFeedback", "EnableFreddyHurtFeedback", true, "Ensure Freddy animatronic plays a hurt sound, red hit-flash, recoil twitch, and sparks when damaged.");
			_enableMimic = config.Bind<bool>("AnimatronicHurtFeedback", "EnableMimicHurtFeedback", true, "Add a metallic endoskeleton hurt sound, red hit-flash, recoil twitch, and sparks to EnemyMimic when damaged.");
			_hurtSoundVolume = config.Bind<float>("AnimatronicHurtFeedback", "HurtSoundVolume", 0.85f, new ConfigDescription("Playback volume for animatronic hurt SFX.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), Array.Empty<object>()));
			_flashDuration = config.Bind<float>("AnimatronicHurtFeedback", "FlashDuration", 0.16f, new ConfigDescription("Duration (seconds) of the red hit-flash on Freddy and Mimic.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 0.5f), Array.Empty<object>()));
			_flinchIntensity = config.Bind<float>("AnimatronicHurtFeedback", "FlinchIntensity", 1f, new ConfigDescription("Physical recoil/twitch flinch strength on hit (0 = disabled).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), Array.Empty<object>()));
			_freddyType = AccessTools.TypeByName("FreddyEnemy.AI.EnemyFreddy");
			if (_freddyType != null)
			{
				_freddyAnimatorField = AccessTools.Field(_freddyType, "animator");
				Type type = AccessTools.TypeByName("FreddyEnemy.AI.EnemyFreddyAnim");
				if (type != null)
				{
					_freddySfxHurtField = AccessTools.Field(type, "sfxHurt");
					_freddySparkParticlesField = AccessTools.Field(type, "sparkParticles");
				}
			}
			_mimicType = AccessTools.TypeByName("EnemyMimic");
			MethodInfo methodInfo = AccessTools.Method(typeof(EnemyHealth), "HurtRPC", new Type[3]
			{
				typeof(int),
				typeof(Vector3),
				typeof(PhotonMessageInfo)
			}, (Type[])null);
			if (methodInfo != null)
			{
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(AnimatronicHurtModule), "EnemyHurtRpcPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				ManualLogSource? log = Plugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"AnimatronicHurtModule: patched EnemyHealth.HurtRPC (Freddy={_freddyType != null}, Mimic={_mimicType != null}).");
				}
			}
			else
			{
				ManualLogSource? log2 = Plugin.Log;
				if (log2 != null)
				{
					log2.LogWarning((object)"AnimatronicHurtModule: could not resolve EnemyHealth.HurtRPC.");
				}
			}
		}

		private static void EnemyHurtRpcPostfix(EnemyHealth __instance, Vector3 _hurtDirection)
		{
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			ConfigEntry<bool> enableFreddy = _enableFreddy;
			Component val = ((enableFreddy != null && enableFreddy.Value && _freddyType != null) ? (((Component)__instance).GetComponent(_freddyType) ?? ((Component)__instance).GetComponentInParent(_freddyType) ?? ((Component)__instance).GetComponentInChildren(_freddyType)) : null);
			object obj;
			if ((Object)(object)val == (Object)null)
			{
				enableFreddy = _enableMimic;
				if (enableFreddy != null && enableFreddy.Value && _mimicType != null)
				{
					obj = ((Component)__instance).GetComponent(_mimicType) ?? ((Component)__instance).GetComponentInParent(_mimicType) ?? ((Component)__instance).GetComponentInChildren(_mimicType);
					goto IL_00a8;
				}
			}
			obj = null;
			goto IL_00a8;
			IL_00a8:
			Component val2 = (Component)obj;
			if (!((Object)(object)val == (Object)null) || !((Object)(object)val2 == (Object)null))
			{
				AnimatronicHurtEffect animatronicHurtEffect = ((Component)__instance).GetComponent<AnimatronicHurtEffect>();
				if ((Object)(object)animatronicHurtEffect == (Object)null)
				{
					animatronicHurtEffect = ((Component)__instance).gameObject.AddComponent<AnimatronicHurtEffect>();
					animatronicHurtEffect.IsFreddy = (Object)(object)val != (Object)null;
					animatronicHurtEffect.FreddyController = val;
				}
				animatronicHurtEffect.TriggerHurt(_hurtDirection);
			}
		}

		private static AudioClip? FindFreddyBundledHurtClip()
		{
			if (_searchedFreddyClip)
			{
				return _freddyClipCached;
			}
			_searchedFreddyClip = true;
			AudioClip[] array = Resources.FindObjectsOfTypeAll<AudioClip>();
			foreach (AudioClip val in array)
			{
				if (!((Object)(object)val == (Object)null))
				{
					string text = ((Object)val).name ?? string.Empty;
					if (text.IndexOf("freddy_hurt", StringComparison.OrdinalIgnoreCase) >= 0 || string.Equals(text, "r_hurt_1", StringComparison.OrdinalIgnoreCase))
					{
						_freddyClipCached = val;
						break;
					}
				}
			}
			return _freddyClipCached;
		}

		private static AudioClip GetProceduralMetallicHurtClip()
		{
			if ((Object)(object)_proceduralMetallicHurtClip != (Object)null)
			{
				return _proceduralMetallicHurtClip;
			}
			int num = 7497;
			float[] array = new float[num];
			uint num2 = 2654435769u;
			for (int i = 0; i < num; i++)
			{
				float num3 = (float)i / 22050f;
				num2 = num2 * 1664525 + 1013904223;
				float num4 = (float)(num2 >> 16) / 32768f - 1f;
				float num5 = Mathf.Exp((0f - num3) * 58f);
				float num6 = num4 * num5 * 0.55f;
				float num7 = Mathf.Exp((0f - num3) * 14f);
				float num8 = Mathf.Sin(MathF.PI * 620f * num3) * 0.35f + Mathf.Sin(MathF.PI * 1174f * num3) * 0.28f + Mathf.Sin(MathF.PI * 2180f * num3) * 0.18f;
				float num9 = Mathf.Lerp(195f, 92f, Mathf.Clamp01(num3 / 0.34f));
				float num10 = Mathf.Exp((0f - num3) * 7.5f) * Mathf.Clamp01(num3 * 40f);
				float num11 = (float)Math.Tanh(Mathf.Sin(MathF.PI * 2f * num9 * num3) * 2.2f) * 0.25f * num10;
				array[i] = Mathf.Clamp(num6 + num8 * num7 + num11, -0.95f, 0.95f);
			}
			AudioClip obj = AudioClip.Create("Factor_MetallicAnimatronicHurt", num, 1, 22050, false);
			obj.SetData(array, 0);
			((Object)obj).hideFlags = (HideFlags)52;
			_proceduralMetallicHurtClip = obj;
			return obj;
		}
	}
	internal static class DefibroModule
	{
		internal sealed class DefibroBatteryState : MonoBehaviour
		{
			public bool IsDepleted;

			public bool ReviveFired;

			public float LastReviveRealtime = -999f;
		}

		private static ConfigEntry<bool>? _enabled;

		private static ConfigEntry<int>? _batteryBars;

		private static ConfigEntry<int>? _chargeOnSpawn;

		private static ConfigEntry<int>? _chargeAfterUse;

		private static readonly FieldInfo? ChargerListField = AccessTools.Field(typeof(ItemBattery), "chargerList");

		private static readonly Type? BatteryChargerType = AccessTools.Inner(typeof(ItemBattery), "BatteryCharger");

		private static readonly FieldInfo? UsesFullBarsField = AccessTools.Field(typeof(ItemBattery), "usesFullBars");

		private static readonly FieldInfo? ItemInstanceNameField = AccessTools.Field(typeof(ItemAttributes), "instanceName");

		private static readonly FieldInfo? BatteryLifeIntField = AccessTools.Field(typeof(ItemBattery), "batteryLifeInt");

		private static readonly FieldInfo? CurrentBarsField = AccessTools.Field(typeof(ItemBattery), "currentBars");

		private static readonly FieldInfo? BatteryColorMediumField = AccessTools.Field(typeof(ItemBattery), "batteryColorMedium");

		private static readonly FieldInfo? BatteryAttributesField = AccessTools.Field(typeof(ItemBattery), "itemAttributes");

		private static readonly FieldInfo? BatteryEquippableField = AccessTools.Field(typeof(ItemBattery), "itemEquippable");

		private static readonly FieldInfo? BatteryPhysGrabField = AccessTools.Field(typeof(ItemBattery), "physGrabObject");

		private static readonly FieldInfo? BatteryPhotonViewField = AccessTools.Field(typeof(ItemBattery), "photonView");

		private static readonly FieldInfo? BatteryVisualLogicField = AccessTools.Field(typeof(ItemBattery), "batteryVisualLogic");

		private static readonly MethodInfo? BatteryStateInitMethod = AccessTools.Method(typeof(ItemBattery), "BatteryStateInitialize", (Type[])null, (Type[])null);

		private static readonly MethodInfo? SaveBatteryChargeMethod = AccessTools.Method(typeof(ItemBattery), "SaveBatteryCharge", (Type[])null, (Type[])null);

		private static readonly FieldInfo? ReviveInReleaseSeqField = AccessTools.Field(typeof(ItemReviveItem), "isInReleaseSequence");

		private static readonly FieldInfo? ReviveHasTargetField = AccessTools.Field(typeof(ItemReviveItem), "hasTarget");

		private static readonly FieldInfo? RevivePlayerTargetField = AccessTools.Field(typeof(ItemReviveItem), "playerTarget");

		private static readonly MethodInfo? ReviveHardResetVisualsMethod = AccessTools.Method(typeof(ItemReviveItem), "HardResetVisuals", (Type[])null, (Type[])null);

		[ThreadStatic]
		private static bool _suppressItemRemove;

		internal static void Init(ConfigFile config, Harmony harmony)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Expected O, but got Unknown
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Expected O, but got Unknown
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Expected O, but got Unknown
			//IL_01bf: Expected O, but got Unknown
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Expected O, but got Unknown
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_027f: Expected O, but got Unknown
			//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f8: Expected O, but got Unknown
			//IL_036c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0379: Expected O, but got Unknown
			_enabled = config.Bind<bool>("RechargeableDefibro", "Enabled", true, "Make the Defibro rechargeable instead of single-use, keep it across revives/shops/levels, and block activation at 0 charges.");
			_batteryBars = config.Bind<int>("RechargeableDefibro", "BatteryBars", 1, new ConfigDescription("Number of battery bars shown for the Defibro.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 6), Array.Empty<object>()));
			_chargeOnSpawn = config.Bind<int>("RechargeableDefibro", "ChargeOnSpawn", 100, new ConfigDescription("Starting battery percentage when a Defibro has no saved charge.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			_chargeAfterUse = config.Bind<int>("RechargeableDefibro", "ChargeAfterUse", 0, new ConfigDescription("Battery percentage remaining after reviving a player.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>()));
			harmony.Patch((MethodBase)AccessTools.Method(typeof(ItemReviveItem), "Start", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(DefibroModule), "ReviveStartPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			string[] array = new string[4] { "Update", "FixedUpdate", "HeldChanged", "EquipChanged" };
			foreach (string text in array)
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(ItemReviveItem), text, (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(AccessTools.Method(typeof(DefibroModule), "ReviveGuardedActionPrefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			MethodInfo methodInfo2 = AccessTools.Method(typeof(ItemReviveItem), "ReviveAndDestroy", (Type[])null, (Type[])null);
			if (methodInfo2 != null)
			{
				harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(AccessTools.Method(typeof(DefibroModule), "ReviveAndDestroyPrefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(DefibroModule), "ReviveAndDestroyFinalizer", (Type[])null, (Type[])null)), (HarmonyMethod)null);
			}
			MethodInfo methodInfo3 = AccessTools.Method(typeof(StatsManager), "ItemRemove", new Type[1] { typeof(string) }, (Type[])null);
			if (methodInfo3 != null)
			{
				harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(AccessTools.Method(typeof(DefibroModule), "StatsItemRemovePrefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			array = new string[2] { "DestroyPhysGrabObject", "DestroyPhysGrabObjectRPC" };
			foreach (string text2 in array)
			{
				MethodInfo methodInfo4 = AccessTools.Method(typeof(PhysGrabObject), text2, (Type[])null, (Type[])null);
				if (methodInfo4 != null)
				{
					harmony.Patch((MethodBase)methodInfo4, new HarmonyMethod(AccessTools.Method(typeof(DefibroModule), "DestroyPhysGrabPrefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			array = new string[3] { "BatteryLookAt", "BatteryUpdateBars", "BatteryChargingVisuals" };
			foreach (string text3 in array)
			{
				MethodInfo methodInfo5 = AccessTools.Method(typeof(ItemBattery), text3, (Type[])null, (Type[])null);
				if (methodInfo5 != null)
				{
					harmony.Patch((MethodBase)methodInfo5, new HarmonyMethod(AccessTools.Method(typeof(DefibroModule), "NullVisualGuardPrefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			array = new string[4] { "Update", "ChargeBattery", "ReceiveCharge", "SetBatteryLife" };
			foreach (string text4 in array)
			{
				MethodInfo methodInfo6 = AccessTools.Method(typeof(ItemBattery), text4, (Type[])null, (Type[])null);
				if (methodInfo6 != null)
				{
					harmony.Patch((MethodBase)methodInfo6, (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(DefibroModule), "BatteryPostUpdatePostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			ManualLogSource? log = Plugin.Log;
			if (log != null)
			{
				log.LogInfo((object)"DefibroModule: initialized v0.5.4-native Rechargeable Defibro.");
			}
		}

		private static void ReviveStartPostfix(ItemReviveItem __instance)
		{
			//IL_00bd: 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_00e7: Unknown result type (might be due to invalid IL or missing references)
			ConfigEntry<bool> enabled = _enabled;
			if (enabled == null || !enabled.Value || (Object)(object)__instance == (Object)null)
			{
				return;
			}
			DefibroBatteryState defibroBatteryState = ((Component)__instance).GetComponent<DefibroBatteryState>();
			if ((Object)(object)defibroBatteryState == (Object)null)
			{
				defibroBatteryState = ((Component)__instance).gameObject.AddComponent<DefibroBatteryState>();
			}
			ItemBattery val = ((Component)__instance).GetComponent<ItemBattery>();
			bool num = (Object)(object)val == (Object)null;
			if ((Object)(object)val == (Object)null)
			{
				val = ((Component)__instance).gameObject.AddComponent<ItemBattery>();
			}
			int batteryBars = Mathf.Clamp(_batteryBars?.Value ?? 1, 1, 6);
			val.batteryBars = batteryBars;
			val.autoDrain = false;
			val.batteryDrainRate = 0f;
			val.isUnchargable = false;
			val.hasBatteryVisuals = false;
			val.batteryActive = false;
			val.onlyShowWhenItemToggleIsOn = false;
			val.batteryColor = new Color(0.25f, 1f, 0.45f, 1f);
			BatteryColorMediumField?.SetValue(val, (object)new Color(1f, 0.85f, 0.15f, 1f));
			EnsureBatteryReferences(val);
			if (num)
			{
				int num2 = Mathf.Clamp(_chargeOnSpawn?.Value ?? 100, 0, 100);
				ItemAttributes component = ((Component)__instance).GetComponent<ItemAttributes>();
				string text = (((Object)(object)component != (Object)null) ? ((ItemInstanceNameField?.GetValue(component) as string) ?? string.Empty) : string.Empty);
				if (!string.IsNullOrEmpty(text) && (Object)(object)StatsManager.instance != (Object)null && StatsManager.instance.itemStatBattery != null && StatsManager.instance.itemStatBattery.TryGetValue(text, out var value))
				{
					num2 = Mathf.Clamp(value, 0, 100);
				}
				val.batteryLife = num2;
				BatteryStateInitMethod?.Invoke(val, null);
			}
			SyncBatteryInts(val);
			defibroBatteryState.IsDepleted = IsBatteryDepleted(val);
			if (defibroBatteryState.IsDepleted)
			{
				ClearTargetAndVisuals(__instance);
			}
			Plugin.LogVerbose($"Defibro Start: life={val.batteryLife:0.#}%, depleted={defibroBatteryState.IsDepleted}, bars={val.batteryBars}.");
		}

		private static bool ReviveGuardedActionPrefix(ItemReviveItem __instance)
		{
			ConfigEntry<bool> enabled = _enabled;
			if (enabled == null || !enabled.Value || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			DefibroBatteryState component = ((Component)__instance).GetComponent<DefibroBatteryState>();
			ItemBattery component2 = ((Component)__instance).GetComponent<ItemBattery>();
			if ((Object)(object)component == (Object)null || (Object)(object)component2 == (Object)null)
			{
				return true;
			}
			SyncStateFromBattery(__instance, component2, component);
			if (!component.IsDepleted)
			{
				return true;
			}
			ClearTargetAndVisuals(__instance);
			return false;
		}

		private static bool ReviveAndDestroyPrefix(ItemReviveItem __instance)
		{
			ConfigEntry<bool> enabled = _enabled;
			if (enabled == null || !enabled.Value || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			DefibroBatteryState defibroBatteryState = ((Component)__instance).GetComponent<DefibroBatteryState>() ?? ((Component)__instance).gameObject.AddComponent<DefibroBatteryState>();
			ItemBattery component = ((Component)__instance).GetComponent<ItemBattery>();
			if ((Object)(object)component != (Object)null)
			{
				SyncStateFromBattery(__instance, component, defibroBatteryState);
			}
			if (defibroBatteryState.IsDepleted)
			{
				ClearTargetAndVisuals(__instance);
				Plugin.LogVerbose("Blocked Defibro ReviveAndDestroy while depleted (0 charges).");
				return false;
			}
			defibroBatteryState.ReviveFired = true;
			defibroBatteryState.LastReviveRealtime = Time.realtimeSinceStartup;
			_suppressItemRemove = true;
			return true;
		}

		private static void ReviveAndDestroyFinalizer(ItemReviveItem __instance)
		{
			_suppressItemRemove = false;
			ConfigEntry<bool> enabled = _enabled;
			if (enabled == null || !enabled.Value || (Object)(object)__instance == (Object)null)
			{
				return;
			}
			DefibroBatteryState component = ((Component)__instance).GetComponent<DefibroBatteryState>();
			if (!((Object)(object)component == (Object)null) && component.ReviveFired)
			{
				component.ReviveFired = false;
				component.IsDepleted = true;
				ClearTargetAndVisuals(__instance);
				PhysGrabObject component2 = ((Component)__instance).GetComponent<PhysGrabObject>();
				if ((Object)(object)component2 != (Object)null)
				{
					component2.dead = false;
				}
				ItemBattery component3 = ((Component)__instance).GetComponent<ItemBattery>();
				if ((Object)(object)component3 != (Object)null)
				{
					int lifePercent = Mathf.Clamp(_chargeAfterUse?.Value ?? 0, 0, 100);
					ApplyBatteryLifeNow(component3, lifePercent);
					component.IsDepleted = IsBatteryDepleted(component3);
				}
				ManualLogSource? log = Plugin.Log;
				if (log != null)
				{
					log.LogInfo((object)"DefibroModule: revive completed — battery set to 0%, preserved in StatsManager.");
				}
			}
		}

		private static bool StatsItemRemovePrefix()
		{
			return !_suppressItemRemove;
		}

		private static bool DestroyPhysGrabPrefix(PhysGrabObject __instance)
		{
			ConfigEntry<bool> enabled = _enabled;
			if (enabled == null || !enabled.Value || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			if ((Object)(object)((Component)__instance).GetComponent<ItemReviveItem>() == (Object)null)
			{
				return true;
			}
			DefibroBatteryState component = ((Component)__instance).GetComponent<DefibroBatteryState>();
			if ((Object)(object)component == (Object)null)
			{
				return true;
			}
			if (!component.ReviveFired && !(Time.realtimeSinceStartup - component.LastReviveRealtime < 4f))
			{
				return true;
			}
			__instance.dead = false;
			Plugin.LogVerbose("DefibroModule: prevented post-revive PhysGrabObject destruction.");
			return false;
		}

		private static bool NullVisualGuardPrefix(ItemBattery __instance)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return false;
			}
			object? obj = BatteryVisualLogicField?.GetValue(__instance);
			BatteryVisualLogic val = (BatteryVisualLogic)((obj is BatteryVisualLogic) ? obj : null);
			if (val == null || (Object)(object)val == (Object)null)
			{
				if (IsDefibroBattery(__instance))
				{
					SyncBatteryInts(__instance);
				}
				return false;
			}
			return true;
		}

		private static void BatteryPostUpdatePostfix(ItemBattery __instance)
		{
			ConfigEntry<bool> enabled = _enabled;
			if (enabled != null && enabled.Value && !((Object)(object)__instance == (Object)null) && IsDefibroBattery(__instance))
			{
				ItemReviveItem component = ((Component)__instance).GetComponent<ItemReviveItem>();
				DefibroBatteryState component2 = ((Component)__instance).GetComponent<DefibroBatteryState>();
				if (!((Object)(object)component == (Object)null) && !((Object)(object)component2 == (Object)null))
				{
					SyncBatteryInts(__instance);
					SyncStateFromBattery(component, __instance, component2);
				}
			}
		}

		private static void EnsureBatteryReferences(ItemBattery battery)
		{
			if (ChargerListField != null && ChargerListField.GetValue(battery) == null && BatteryChargerType != null)
			{
				Type type = typeof(List<>).MakeGenericType(BatteryChargerType);
				ChargerListField.SetValue(battery, Activator.CreateInstance(type));
			}
			if (BatteryAttributesField?.GetValue(battery) == null)
			{
				BatteryAttributesField?.SetValue(battery, ((Component)battery).GetComponent<ItemAttributes>());
			}
			if (BatteryEquippableField?.GetValue(battery) == null)
			{
				BatteryEquippableField?.SetValue(battery, ((Component)battery).GetComponent<ItemEquippable>());
			}
			if (BatteryPhysGrabField?.GetValue(battery) == null)
			{
				BatteryPhysGrabField?.SetValue(battery, ((Component)battery).GetComponent<PhysGrabObject>());
			}
			if (BatteryPhotonViewField?.GetValue(battery) == null)
			{
				BatteryPhotonViewField?.SetValue(battery, ((Component)battery).GetComponent<PhotonView>());
			}
		}

		private static bool IsDefibroBattery(ItemBattery battery)
		{
			return (Object)(object)((Component)battery).GetComponent<ItemReviveItem>() != (Object)null;
		}

		private static bool IsBatteryDepleted(ItemBattery battery)
		{
			if (battery.batteryBars <= 1)
			{
				return battery.batteryLife < 99f;
			}
			return ComputeBarsInt(battery) <= 0;
		}

		private static int ComputeBarsInt(ItemBattery battery)
		{
			int num = Mathf.Max(1, battery.batteryBars);
			float num2 = Mathf.Clamp(battery.batteryLife, 0f, 100f);
			if (num2 <= 0.01f)
			{
				return 0;
			}
			int num3 = Mathf.RoundToInt(num2 / 100f * (float)num);
			object obj = UsesFullBarsField?.GetValue(battery);
			bool flag = default(bool);
			int num4;
			if (obj is bool)
			{
				flag = (bool)obj;
				num4 = 1;
			}
			else
			{
				num4 = 0;
			}
			if (((uint)num4 & (flag ? 1u : 0u)) == 0 && num3 == 0 && num2 > 0.01f)
			{
				num3 = 1;
			}
			return Mathf.Clamp(num3, 0, num);
		}

		private static void SyncBatteryInts(ItemBattery battery)
		{
			int num = ComputeBarsInt(battery);
			BatteryLifeIntField?.SetValue(battery, num);
			CurrentBarsField?.SetValue(battery, num);
		}

		private static void SyncStateFromBattery(ItemReviveItem revive, ItemBattery battery, DefibroBatteryState state)
		{
			if (state.IsDepleted && battery.batteryLife >= 99.5f)
			{
				battery.batteryLife = 100f;
				SyncBatteryInts(battery);
				state.IsDepleted = false;
				state.ReviveFired = false;
				PhysGrabObject component = ((Component)revive).GetComponent<PhysGrabObject>();
				if ((Object)(object)component != (Object)null)
				{
					component.dead = false;
				}
				ReviveHardResetVisualsMethod?.Invoke(revive, null);
				SaveBatteryChargeMethod?.Invoke(battery, null);
				ManualLogSource? log = Plugin.Log;
				if (log != null)
				{
					log.LogInfo((object)"DefibroModule: Defibro recharged to 100% — ready to revive again.");
				}
			}
			else if (!state.IsDepleted && IsBatteryDepleted(battery))
			{
				state.IsDepleted = true;
				ClearTargetAndVisuals(revive);
			}
		}

		private static void ApplyBatteryLifeNow(ItemBattery battery, int lifePercent)
		{
			float num = (battery.batteryLife = Mathf.Clamp(lifePercent, 0, 100));
			SyncBatteryInts(battery);
			if (SemiFunc.IsMasterClientOrSingleplayer())
			{
				battery.SetBatteryLife((int)num);
				SaveBatteryChargeMethod?.Invoke(battery, null);
				ItemAttributes component = ((Component)battery).GetComponent<ItemAttributes>();
				string text = (((Object)(object)component != (Object)null) ? ((ItemInstanceNameField?.GetValue(component) as string) ?? string.Empty) : string.Empty);
				if (!string.IsNullOrEmpty(text) && (Object)(object)StatsManager.instance != (Object)null && !SemiFunc.RunIsShop())
				{
					StatsManager.instance.ItemUpdateStatBattery(text, (int)num, false);
				}
			}
		}

		private static void ClearTargetAndVisuals(ItemReviveItem revive)
		{
			ReviveInReleaseSeqField?.SetValue(revive, false);
			ReviveHasTargetField?.SetValue(revive, false);
			RevivePlayerTargetField?.SetValue(revive, null);
			ReviveHardResetVisualsMethod?.Invoke(revive, null);
		}
	}
	internal static class PingItFixModule
	{
		private sealed class PingLabelUpdateState
		{
			public bool Modified;

			public float OriginalLookAngle;

			public float PrevTypeProgress;
		}

		private static ConfigEntry<bool>? _fixShrunkBounds;

		private static ConfigEntry<bool>? _fixCarriedFlicker;

		private static ConfigEntry<float>? _lookConeGraceSeconds;

		private static ConfigEntry<float>? _carriedLookAngle;

		private static Type? _scaleControllerType;

		private static PropertyInfo? _scaleIsScaledProp;

		private static FieldInfo? _labelTargetField;

		private static FieldInfo? _labelLookAngleField;

		private static FieldInfo? _labelTypeProgressField;

		private static FieldInfo? _labelTextField;

		private static FieldInfo? _labelFullTextField;

		private static readonly Dictionary<int, float> LastLookedAtUnscaledTime = new Dictionary<int, float>();

		internal static void Init(ConfigFile config, Harmony harmony)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Expected O, but got Unknown
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Expected O, but got Unknown
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Expected O, but got Unknown
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Expected O, but got Unknown
			//IL_0370: Unknown result type (might be due to invalid IL or missing references)
			//IL_037e: Expected O, but got Unknown
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f6: Expected O, but got Unknown
			//IL_02f6: Expected O, but got Unknown
			//IL_032a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0337: Expected O, but got Unknown
			_fixShrunkBounds = config.Bind<bool>("PingItFix", "FixShrunkBounds", true, "Prevent PingIt from attaching oversized bounds proxies to shrunk/scaled items and clamp oversized discover brackets.");
			_fixCarriedFlicker = config.Bind<bool>("PingItFix", "FixCarriedFlicker", true, "Stop carried/held pinged items from flickering and re-typing their ping info label while moving.");
			_lookConeGraceSeconds = config.Bind<float>("PingItFix", "LookConeGraceSeconds", 0.45f, new ConfigDescription("Hysteresis grace window (seconds) before a brief look-away clears a typed PingLabel.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), Array.Empty<object>()));
			_carriedLookAngle = config.Bind<float>("PingItFix", "CarriedLookAngle", 45f, new ConfigDescription("Effective look cone half-angle (degrees) for an item currently grabbed by the local player.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 180f), Array.Empty<object>()));
			_scaleControllerType = AccessTools.TypeByName("ScalerCore.ScaleController");
			if (_scaleControllerType != null)
			{
				_scaleIsScaledProp = AccessTools.Property(_scaleControllerType, "IsScaled");
				MethodInfo methodInfo = AccessTools.Method(_scaleControllerType, "ApplyScale", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(PingItFixModule), "ScaleApplyPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			Type type = AccessTools.TypeByName("PingIt.PingIt");
			Type type2 = AccessTools.TypeByName("PingIt.PingLabel");
			if (type != null)
			{
				string[] array = new string[2] { "AttachValuableBoundsProxy", "AttachBoundsProxy" };
				foreach (string text in array)
				{
					MethodInfo methodInfo2 = AccessTools.Method(type, text, new Type[1] { typeof(PhysGrabObject) }, (Type[])null);
					if (methodInfo2 != null)
					{
						harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(AccessTools.Method(typeof(PingItFixModule), "AttachBoundsProxyPrefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					}
				}
				MethodInfo methodInfo3 = AccessTools.Method(type, "BuildBoundsProxy", new Type[3]
				{
					typeof(PhysGrabObject),
					typeof(Vector3),
					typeof(Vector3)
				}, (Type[])null);
				if (methodInfo3 != null)
				{
					harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(AccessTools.Method(typeof(PingItFixModule), "BuildBoundsProxyPrefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				if (type2 != null)
				{
					_labelTargetField = AccessTools.Field(type2, "_target");
					_labelLookAngleField = AccessTools.Field(type2, "_lookAngle");
					_labelTypeProgressField = AccessTools.Field(type2, "_typeProgress");
					_labelTextField = AccessTools.Field(type2, "_text");
					_labelFullTextField = AccessTools.Field(type2, "_fullText");
					MethodInfo methodInfo4 = AccessTools.Method(type2, "Update", (Type[])null, (Type[])null);
					if (methodInfo4 != null)
					{
						harmony.Patch((MethodBase)methodInfo4, new HarmonyMethod(AccessTools.Method(typeof(PingItFixModule), "PingLabelUpdatePrefix", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.Method(typeof(PingItFixModule), "PingLabelUpdatePostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					}
					MethodInfo methodInfo5 = AccessTools.Method(type2, "OnDestroy", (Type[])null, (Type[])null);
					if (methodInfo5 != null)
					{
						harmony.Patch((MethodBase)methodInfo5, (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(PingItFixModule), "PingLabelDestroyPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					}
				}
				MethodInfo methodInfo6 = AccessTools.Method(typeof(ValuableDiscoverGraphic), "Update", (Type[])null, (Type[])null);
				if (methodInfo6 != null)
				{
					harmony.Patch((MethodBase)methodInfo6, new HarmonyMethod(AccessTools.Method(typeof(PingItFixModule), "DiscoverUpdatePrefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				ManualLogSource? log = Plugin.Log;
				if (log != null)
				{
					log.LogInfo((object)"PingItFixModule: initialized shrunk-bounds and carried-label anti-flicker fixes.");
				}
			}
			else
			{
				ManualLogSource? log2 = Plugin.Log;
				if (log2 != null)
				{
					log2.LogInfo((object)"PingIt not found; PingItFixModule inactive.");
				}
			}
		}

		private static bool AttachBoundsProxyPrefix(PhysGrabObject? physGrab)
		{
			ConfigEntry<bool> fixShrunkBounds = _fixShrunkBounds;
			if (fixShrunkBounds == null || !fixShrunkBounds.Value || (Object)(object)physGrab == (Object)null)
			{
				return true;
			}
			if (IsObjectScaled(physGrab))
			{
				DestroyPingProxyChildren(((Component)physGrab).transform);
				Plugin.LogVerbose("PingItFix: skipped oversized bounds proxy on scaled object '" + ((Object)physGrab).name + "'.");
				return false;
			}
			return true;
		}

		private static bool BuildBoundsProxyPrefix(PhysGrabObject? physGrab, Vector3 worldCenter, ref Vector3 worldSize)
		{
			//IL_0022: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//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)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			ConfigEntry<bool> fixShrunkBounds = _fixShrunkBounds;
			if (fixShrunkBounds == null || !fixShrunkBounds.Value || (Object)(object)physGrab == (Object)null)
			{
				return true;
			}
			Vector3 lossyScale = ((Component)physGrab).transform.lossyScale;
			if (IsObjectScaled(physGrab) || Mathf.Abs(lossyScale.x) < 0.05f || Mathf.Abs(lossyScale.y) < 0.05f || Mathf.Abs(lossyScale.z) < 0.05f)
			{
				DestroyPingProxyChildren(((Component)physGrab).transform);
				return false;
			}
			if (float.IsNaN(worldCenter.x) || float.IsInfinity(worldCenter.x) || float.IsNaN(worldSize.x) || float.IsInfinity(worldSize.x))
			{
				return false;
			}
			worldSize = new Vector3(Mathf.Clamp(worldSize.x, 0.05f, 3.5f), Mathf.Clamp(worldSize.y, 0.05f, 3.5f), Mathf.Clamp(worldSize.z, 0.05f, 3.5f));
			return true;
		}

		private static void ScaleApplyPostfix(MonoBehaviour __instance)
		{
			ConfigEntry<bool> fixShrunkBounds = _fixShrunkBounds;
			if (fixShrunkBounds != null && fixShrunkBounds.Value && !((Object)(object)__instance == (Object)null))
			{
				DestroyPingProxyChildren(((Component)__instance).transform);
			}
		}

		private static void DiscoverUpdatePrefix(ValuableDiscoverGraphic __instance)
		{
			ConfigEntry<bool> fixShrunkBounds = _fixShrunkBounds;
			if (fixShrunkBounds != null && fixShrunkBounds.Value && !((Object)(object)__instance == (Object)null) && !((Object)(object)__instance.target == (Object)null) && IsObjectScaled(__instance.target))
			{
				DestroyPingProxyChildren(((Component)__instance.target).transform);
			}
		}

		private static void PingLabelUpdatePrefix(MonoBehaviour __instance, out PingLabelUpdateState? __state)
		{
			__state = null;
			ConfigEntry<bool> fixCarriedFlicker = _fixCarriedFlicker;
			if (fixCarriedFlicker == null || !fixCarriedFlicker.Value || (Object)(object)__instance == (Object)null || _labelTargetField == null || _labelLookAngleField == null || _labelTypeProgressField == null)
			{
				return;
			}
			object? value = _labelTargetField.GetValue(__instance);
			PhysGrabObject val = (PhysGrabObject)((value is PhysGrabObject) ? value : null);
			if (val != null && !((Object)(object)val == (Object)null))
			{
				float num = ((_labelLookAngleField.GetValue(__instance) is float num2) ? num2 : 0f);
				float prevTypeProgress = ((_labelTypeProgressField.GetValue(__instance) is float num3) ? num3 : 0f);
				PingLabelUpdateState pingLabelUpdateState = new PingLabelUpdateState
				{
					Modified = true,
					OriginalLookAngle = num,
					PrevTypeProgress = prevTypeProgress
				};
				if (IsHeldByLocalPlayer(val))
				{
					float num4 = Mathf.Max(num, _carriedLookAngle?.Value ?? 45f);
					_labelLookAngleField.SetValue(__instance, num4);
				}
				__state = pingLabelUpdateState;
			}
		}

		private static void PingLabelUpdatePostfix(MonoBehaviour __instance, PingLabelUpdateState? __state)
		{
			if (__state == null || !__state.Modified || (Object)(object)__instance == (Object)null || _labelLookAngleField == null || _labelTypeProgressField == null)
			{
				return;
			}
			_labelLookAngleField.SetValue(__instance, __state.OriginalLookAngle);
			float num = ((_labelTypeProgressField.GetValue(__instance) is float num2) ? num2 : 0f);
			int instanceID = ((Object)__instance).GetInstanceID();
			float unscaledTime = Time.unscaledTime;
			if (num > 0.01f)
			{
				LastLookedAtUnscaledTime[instanceID] = unscaledTime;
				return;
			}
			float num3 = _lookConeGraceSeconds?.Value ?? 0.45f;
			if (!(num3 > 0.001f) || !(__state.PrevTypeProgress > 0.01f) || !LastLookedAtUnscaledTime.TryGetValue(instanceID, out var value) || !(unscaledTime - value <= num3))
			{
				return;
			}
			_labelTypeProgressField.SetValue(__instance, __state.PrevTypeProgress);
			object? obj = _labelTextField?.GetValue(__instance);
			TextMeshProUGUI val = (TextMeshProUGUI)((obj is TextMeshProUGUI) ? obj : null);
			if (val != null && (Object)(object)val != (Object)null)
			{
				string text = (_labelFullTextField?.GetValue(__instance) as string) ?? string.Empty;
				if (!string.IsNullOrEmpty(text))
				{
					((TMP_Text)val).text = text;
					((TMP_Text)val).maxVisibleCharacters = Mathf.Max(1, (int)__state.PrevTypeProgress);
				}
			}
		}

		private static void PingLabelDestroyPostfix(MonoBehaviour __instance)
		{
			if ((Object)(object)__instance != (Object)null)
			{
				LastLookedAtUnscaledTime.Remove(((Object)__instance).GetInstanceID());
			}
		}

		private static bool IsHeldByLocalPlayer(PhysGrabObject target)
		{
			if (target.playerGrabbing == null || target.playerGrabbing.Count == 0)
			{
				return false;
			}
			foreach (PhysGrabber item in target.playerGrabbing)
			{
				if ((Object)(object)item != (Object)null && item.isLocal)
				{
					return true;
				}
			}
			return false;
		}

		private static bool IsObjectScaled(PhysGrabObject obj)
		{
			//IL_0057: 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_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			if (_scaleControllerType != null)
			{
				Component component = ((Component)obj).GetComponent(_scaleControllerType);
				bool flag = default(bool);
				int num;
				if ((Object)(object)component != (Object)null)
				{
					object obj2 = _scaleIsScaledProp?.GetValue(component);
					if (obj2 is bool)
					{
						flag = (bool)obj2;
						num = 1;
					}
					else
					{
						num = 0;
					}
				}
				else
				{
					num = 0;
				}
				if (((uint)num & (flag ? 1u : 0u)) != 0)
				{
					return true;
				}
			}
			Vector3 localScale = ((Component)obj).transform.localScale;
			if (!(Mathf.Abs(localScale.x - 1f) > 0.08f) && !(Mathf.Abs(localScale.y - 1f) > 0.08f))
			{
				return Mathf.Abs(localScale.z - 1f) > 0.08f;
			}
			return true;
		}

		private static void DestroyPingProxyChildren(Transform root)
		{
			for (int num = root.childCount - 1; num >= 0; num--)
			{
				Transform child = root.GetChild(num);
				if ((Object)(object)child != (Object)null && ((Object)child).name == "PingIt_BoundsProxy")
				{
					Object.Destroy((Object)(object)((Component)child).gameObject);
				}
			}
		}
	}
	[BepInPlugin("Factor.ModpackFixes", "ModpackFixes", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[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 = "Factor.ModpackFixes";

		public const string PluginName = "ModpackFixes";

		public const string PluginVersion = "1.0.0";

		private Harmony? _harmony;

		internal static ManualLogSource? Log { get; private set; }

		internal static ConfigEntry<bool>? VerboseLogging { get; private set; }

		private void Awake()
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			VerboseLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "VerboseLogging", false, "Enable detailed diagnostic logging for Defibro, PingIt, and Animatronic Hurt fixes.");
			_harmony = new Harmony("Factor.ModpackFixes");
			DefibroModule.Init(((BaseUnityPlugin)this).Config, _harmony);
			PingItFixModule.Init(((BaseUnityPlugin)this).Config, _harmony);
			AnimatronicHurtModule.Init(((BaseUnityPlugin)this).Config, _harmony);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"ModpackFixes v1.0.0 loaded.");
		}

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

		internal static void LogVerbose(string message)
		{
			ConfigEntry<bool> verboseLogging = VerboseLogging;
			if (verboseLogging != null && verboseLogging.Value)
			{
				ManualLogSource? log = Log;
				if (log != null)
				{
					log.LogInfo((object)message);
				}
			}
		}
	}
}