Decompiled source of CharmCore v1.0.0

CharmCore.dll

Decompiled 7 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using CharmCore.Api;
using CharmCore.Domain;
using CharmCore.Net;
using CharmCore.Ui;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using Pockets.Api;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: AssemblyCompany("Osmar Briones")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+db74fa25a514c7d6815cb9c8d2baf5494e5b5098")]
[assembly: AssemblyProduct("CharmCore")]
[assembly: AssemblyTitle("CharmCore")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[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 CharmCore
{
	[BepInPlugin("com.osmar.CharmCore", "CharmCore", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class CharmCorePlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.osmar.CharmCore";

		public const string PluginName = "CharmCore";

		public const string PluginVersion = "1.0.0";

		internal Harmony? Harmony { get; set; }

		internal static ManualLogSource Logger { get; private set; }

		private void Awake()
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			Logger = ((BaseUnityPlugin)this).Logger;
			((Component)this).gameObject.transform.parent = null;
			((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
			ConfigurationController.Initialize(((BaseUnityPlugin)this).Config);
			PocketsApi.RequireSlotValue("com.osmar.CharmCore");
			((Component)this).gameObject.AddComponent<CharmTracker>();
			((Component)this).gameObject.AddComponent<CharmRoomEvents>();
			((Component)this).gameObject.AddComponent<CharmInfoView>();
			Harmony = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID);
			Harmony.PatchAll();
			Logger.LogInfo((object)"CharmCore 1.0.0 loaded!");
		}

		internal void Unpatch()
		{
			Harmony? harmony = Harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	internal class ConfigurationController
	{
		internal const string EnabledKey = "core.enabled";

		internal const string WearMultiplierKey = "core.wear";

		private static ConfigFile? ConfigFile { get; set; }

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

		private static ConfigEntry<float>? WearMultiplierEntry { get; set; }

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

		internal static bool ShowDescriptions => ShowDescriptionsEntry?.Value ?? true;

		internal static bool LocalCoreEnabled => Enabled?.Value ?? true;

		internal static float LocalWearMultiplier => WearMultiplierEntry?.Value ?? 1f;

		internal static bool CoreEnabled => HostSettings.GetBool("core.enabled", LocalCoreEnabled);

		internal static float WearMultiplier => HostSettings.GetFloat("core.wear", LocalWearMultiplier);

		internal static void Initialize(ConfigFile config)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			ConfigFile = config;
			Enabled = ConfigFile.Bind<bool>("General", "Enabled", true, "Turn all charms on or off. The host's choice applies to everyone.");
			WearMultiplierEntry = ConfigFile.Bind<float>("General", "WearMultiplier", 1f, new ConfigDescription("Scales how fast every charm wears its valuable down: 0.5 halves it, 2 doubles it. The host's choice applies to everyone.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 10f), Array.Empty<object>()));
			ShowDescriptionsEntry = ConfigFile.Bind<bool>("General", "ShowDescriptions", true, "Show the name of a charm and what it does while you hold its valuable. Local setting: it only changes your own screen.");
			ConfigFile.SettingChanged += delegate
			{
				HostSettings.Publish();
			};
			ConfigFile.Save();
		}

		internal static void Reload()
		{
			ConfigFile? configFile = ConfigFile;
			if (configFile != null)
			{
				configFile.Reload();
			}
			ConfigFile? configFile2 = ConfigFile;
			if (configFile2 != null)
			{
				configFile2.Save();
			}
		}
	}
}
namespace CharmCore.Ui
{
	internal sealed class CharmInfoView : MonoBehaviour
	{
		private const float RefreshSeconds = 0.5f;

		private PhysGrabObject? held;

		private Charm? charm;

		private string text = string.Empty;

		private float refreshAt;

		private void Update()
		{
			PhysGrabber instance = PhysGrabber.instance;
			if ((Object)(object)instance == (Object)null || !instance.grabbed || (Object)(object)instance.grabbedPhysGrabObject == (Object)null || (Object)(object)ItemInfoUI.instance == (Object)null || !ConfigurationController.ShowDescriptions)
			{
				Forget();
				return;
			}
			PhysGrabObject grabbedPhysGrabObject = instance.grabbedPhysGrabObject;
			if ((Object)(object)grabbedPhysGrabObject != (Object)(object)held)
			{
				held = grabbedPhysGrabObject;
				ValuableObject component = ((Component)grabbedPhysGrabObject).GetComponent<ValuableObject>();
				charm = (((Object)(object)component != (Object)null) ? CharmsApi.CharmOf(component) : null);
				text = string.Empty;
				refreshAt = 0f;
			}
			if (charm != null)
			{
				if (Time.unscaledTime >= refreshAt)
				{
					refreshAt = Time.unscaledTime + 0.5f;
					text = ((ConfigurationController.CoreEnabled && charm.IsEnabled) ? InfoText.Compose(charm.DisplayName, SemiFunc.InputDisplayReplaceTags(charm.SafeDescription() ?? string.Empty, "<u><b>", "</b></u>")) : string.Empty);
				}
				if (text.Length > 0)
				{
					ItemInfoUI.instance.ItemInfoText((ItemAttributes)null, text, false);
				}
			}
		}

		private void Forget()
		{
			held = null;
			charm = null;
			text = string.Empty;
		}
	}
	internal sealed class CharmSlotView : MonoBehaviour
	{
		private struct LabelState
		{
			internal Vector2 AnchorMin;

			internal Vector2 AnchorMax;

			internal Vector2 Pivot;

			internal Vector2 SizeDelta;

			internal Vector2 AnchoredPosition;

			internal float FontSize;

			internal bool AutoSizing;

			internal float FontSizeMin;

			internal float FontSizeMax;
		}

		private static Sprite? whiteSprite;

		private InventorySpot spot;

		private Image? veil;

		private TextMeshProUGUI? label;

		private readonly Vector3[] corners = (Vector3[])(object)new Vector3[4];

		private bool layoutDone;

		private float lastLeft;

		private float lastRight;

		private float lastTop;

		private float lastBottom;

		private string lastSeconds = string.Empty;

		private bool shown;

		private TextMeshProUGUI? valueLabel;

		private LabelState valueOriginal;

		private bool valueLaidOut;

		internal static CharmSlotView GetOrAdd(InventorySpot spot)
		{
			CharmSlotView charmSlotView = ((Component)spot).GetComponent<CharmSlotView>();
			if ((Object)(object)charmSlotView == (Object)null)
			{
				charmSlotView = ((Component)spot).gameObject.AddComponent<CharmSlotView>();
			}
			return charmSlotView;
		}

		private void Awake()
		{
			spot = ((Component)this).GetComponent<InventorySpot>();
		}

		private void Update()
		{
			float remaining = 0f;
			float total = 0f;
			float fraction = 1f;
			if ((Object)(object)spot == (Object)null || (!CharmTracker.TryGetCooldown(spot.inventorySpotIndex, out remaining, out total) && !CharmTracker.TryGetCharge(spot.inventorySpotIndex, out fraction)))
			{
				SetVisible(visible: false);
				RestoreValueLabel();
			}
			else if (EnsureWidgets())
			{
				bool flag = remaining <= 0f && fraction < 1f;
				veil.fillAmount = (flag ? (1f - fraction) : WearMath.CooldownFraction(remaining, total));
				string text = (flag ? (Mathf.FloorToInt(fraction * 100f).ToString(CultureInfo.InvariantCulture) + "%") : ((remaining >= 10f) ? Mathf.CeilToInt(remaining).ToString(CultureInfo.InvariantCulture) : remaining.ToString("0.0", CultureInfo.InvariantCulture)));
				if (text != lastSeconds)
				{
					lastSeconds = text;
					((TMP_Text)label).text = text;
				}
				SetVisible(visible: true);
				LayoutTexts();
			}
		}

		private TextMeshProUGUI? FindValueLabel()
		{
			Transform val = (((Object)(object)spot.noItem != (Object)null) ? ((TMP_Text)spot.noItem).transform.parent : null);
			Transform val2 = (((Object)(object)val != (Object)null) ? val.Find("PocketValue") : null);
			if (!((Object)(object)val2 != (Object)null))
			{
				return null;
			}
			return ((Component)val2).GetComponent<TextMeshProUGUI>();
		}

		private void LayoutTexts()
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			RectTransform component = ((Component)spot).GetComponent<RectTransform>();
			Canvas componentInParent = ((Component)spot).GetComponentInParent<Canvas>();
			if ((Object)(object)component == (Object)null || (Object)(object)label == (Object)null)
			{
				return;
			}
			Camera val = (((Object)(object)componentInParent != (Object)null && (int)componentInParent.renderMode != 0) ? componentInParent.worldCamera : null);
			component.GetWorldCorners(corners);
			Vector2 val2 = RectTransformUtility.WorldToScreenPoint(val, corners[0]);
			Vector2 val3 = RectTransformUtility.WorldToScreenPoint(val, corners[2]);
			float num = (((Object)(object)val != (Object)null) ? val.pixelWidth : Screen.width);
			float num2 = (((Object)(object)val != (Object)null) ? val.pixelHeight : Screen.height);
			float num3 = Mathf.Max(val2.x, 0f);
			float num4 = Mathf.Min(val3.x, num);
			float num5 = Mathf.Min(val3.y, num2);
			float num6 = Mathf.Max(val2.y, 0f);
			if (layoutDone && valueLaidOut && Mathf.Approximately(num3, lastLeft) && Mathf.Approximately(num4, lastRight) && Mathf.Approximately(num5, lastTop) && Mathf.Approximately(num6, lastBottom))
			{
				return;
			}
			SlotLayout.Split(num3, num4, num5, num6, out var seconds, out var value);
			if (seconds.Width <= 0f)
			{
				return;
			}
			Place(label, seconds, val);
			TextMeshProUGUI val4 = FindValueLabel();
			if (!((Object)(object)val4 == (Object)null))
			{
				if (!valueLaidOut)
				{
					valueLabel = val4;
					valueOriginal = Capture(val4);
					valueLaidOut = true;
				}
				Place(val4, value, val);
				lastLeft = num3;
				lastRight = num4;
				lastTop = num5;
				lastBottom = num6;
				layoutDone = true;
			}
		}

		private static void Place(TextMeshProUGUI text, LabelBox box, Camera? camera)
		{
			//IL_0012: 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_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: 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_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: 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_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			RectTransform rectTransform = ((TMP_Text)text).rectTransform;
			rectTransform.anchorMin = new Vector2(0.5f, 0.5f);
			rectTransform.anchorMax = new Vector2(0.5f, 0.5f);
			rectTransform.pivot = new Vector2(0.5f, 0.5f);
			Vector3 lossyScale = ((Transform)rectTransform).lossyScale;
			float num = ((lossyScale.x > 0.0001f) ? lossyScale.x : 1f);
			float num2 = ((lossyScale.y > 0.0001f) ? lossyScale.y : 1f);
			rectTransform.sizeDelta = new Vector2(box.Width / num, box.Height / num2);
			Transform parent = ((Transform)rectTransform).parent;
			RectTransform val = (RectTransform)(object)((parent is RectTransform) ? parent : null);
			Vector3 position = default(Vector3);
			if (val != null && RectTransformUtility.ScreenPointToWorldPointInRectangle(val, new Vector2(box.CenterX, box.CenterY), camera, ref position))
			{
				((Transform)rectTransform).position = position;
			}
			((TMP_Text)text).alignment = (TextAlignmentOptions)514;
			((TMP_Text)text).textWrappingMode = (TextWrappingModes)0;
			((TMP_Text)text).enableAutoSizing = true;
			((TMP_Text)text).fontSizeMin = 1f;
			((TMP_Text)text).fontSizeMax = Mathf.Max(box.Height / num2, 2f);
		}

		private static LabelState Capture(TextMeshProUGUI text)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: 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_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			RectTransform rectTransform = ((TMP_Text)text).rectTransform;
			return new LabelState
			{
				AnchorMin = rectTransform.anchorMin,
				AnchorMax = rectTransform.anchorMax,
				Pivot = rectTransform.pivot,
				SizeDelta = rectTransform.sizeDelta,
				AnchoredPosition = rectTransform.anchoredPosition,
				FontSize = ((TMP_Text)text).fontSize,
				AutoSizing = ((TMP_Text)text).enableAutoSizing,
				FontSizeMin = ((TMP_Text)text).fontSizeMin,
				FontSizeMax = ((TMP_Text)text).fontSizeMax
			};
		}

		private void RestoreValueLabel()
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: 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_008a: Unknown result type (might be due to invalid IL or missing references)
			if (valueLaidOut)
			{
				valueLaidOut = false;
				layoutDone = false;
				lastSeconds = string.Empty;
				TextMeshProUGUI val = valueLabel;
				valueLabel = null;
				if (!((Object)(object)val == (Object)null))
				{
					RectTransform rectTransform = ((TMP_Text)val).rectTransform;
					rectTransform.anchorMin = valueOriginal.AnchorMin;
					rectTransform.anchorMax = valueOriginal.AnchorMax;
					rectTransform.pivot = valueOriginal.Pivot;
					rectTransform.sizeDelta = valueOriginal.SizeDelta;
					rectTransform.anchoredPosition = valueOriginal.AnchoredPosition;
					((TMP_Text)val).enableAutoSizing = valueOriginal.AutoSizing;
					((TMP_Text)val).fontSizeMin = valueOriginal.FontSizeMin;
					((TMP_Text)val).fontSizeMax = valueOriginal.FontSizeMax;
					((TMP_Text)val).fontSize = valueOriginal.FontSize;
				}
			}
		}

		private void SetVisible(bool visible)
		{
			if (visible != shown)
			{
				shown = visible;
				if ((Object)(object)veil != (Object)null)
				{
					((Behaviour)veil).enabled = visible;
				}
				if ((Object)(object)label != (Object)null)
				{
					((Behaviour)label).enabled = visible;
				}
			}
		}

		private bool EnsureWidgets()
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Expected O, but got Unknown
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)veil != (Object)null && (Object)(object)label != (Object)null)
			{
				return true;
			}
			Image inventoryIcon = spot.inventoryIcon;
			TextMeshProUGUI noItem = spot.noItem;
			if ((Object)(object)inventoryIcon == (Object)null || (Object)(object)noItem == (Object)null)
			{
				return false;
			}
			RectTransform rectTransform = ((Graphic)inventoryIcon).rectTransform;
			GameObject val = new GameObject("CharmCooldown", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			RectTransform component = val.GetComponent<RectTransform>();
			((Transform)component).SetParent(((Transform)rectTransform).parent, false);
			component.anchorMin = rectTransform.anchorMin;
			component.anchorMax = rectTransform.anchorMax;
			component.pivot = rectTransform.pivot;
			component.anchoredPosition = rectTransform.anchoredPosition;
			component.sizeDelta = rectTransform.sizeDelta;
			((Transform)component).localScale = ((Transform)rectTransform).localScale;
			((Transform)component).SetSiblingIndex(((Transform)rectTransform).GetSiblingIndex() + 1);
			veil = val.GetComponent<Image>();
			veil.sprite = WhiteSprite();
			veil.type = (Type)3;
			veil.fillMethod = (FillMethod)1;
			veil.fillOrigin = 1;
			((Graphic)veil).color = new Color(0f, 0f, 0f, 0.65f);
			((Graphic)veil).raycastTarget = false;
			label = Object.Instantiate<TextMeshProUGUI>(noItem, ((Transform)rectTransform).parent);
			((Object)label).name = "CharmCooldownSeconds";
			((TMP_Text)label).alignment = (TextAlignmentOptions)514;
			((TMP_Text)label).enableAutoSizing = true;
			((TMP_Text)label).textWrappingMode = (TextWrappingModes)0;
			((TMP_Text)label).overflowMode = (TextOverflowModes)0;
			((Graphic)label).color = Color.white;
			((Graphic)label).raycastTarget = false;
			((TMP_Text)label).outlineWidth = 0.3f;
			((TMP_Text)label).outlineColor = new Color32((byte)0, (byte)0, (byte)0, byte.MaxValue);
			return true;
		}

		private static Sprite WhiteSprite()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: 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_0054: Expected O, but got Unknown
			if ((Object)(object)whiteSprite == (Object)null)
			{
				Texture2D val = new Texture2D(1, 1);
				val.SetPixel(0, 0, Color.white);
				val.Apply();
				whiteSprite = Sprite.Create(val, new Rect(0f, 0f, 1f, 1f), new Vector2(0.5f, 0.5f));
			}
			return whiteSprite;
		}
	}
}
namespace CharmCore.Patches
{
	[HarmonyPatch(typeof(EnemyDirector), "Start")]
	internal static class EnemyDirector_Start_Patch
	{
		[HarmonyPostfix]
		private static void Postfix()
		{
			if (SemiFunc.RunIsLevel())
			{
				ConfigurationController.Reload();
				CharmTracker.Clear();
				HostSettings.Publish();
				CharmTracker.StartDebugSpawn();
			}
		}
	}
	[HarmonyPatch(typeof(InventorySpot), "UpdateUI")]
	internal static class InventorySpot_UI_Patch
	{
		[HarmonyPostfix]
		private static void Postfix(InventorySpot __instance)
		{
			CharmSlotView.GetOrAdd(__instance);
		}
	}
	[HarmonyPatch(typeof(PhysGrabObjectImpactDetector), "BreakRPC")]
	internal static class PhysGrabObjectImpactDetector_BreakRPC_Patch
	{
		[HarmonyPrefix]
		private static bool Prefix(PhysGrabObjectImpactDetector __instance, float valueLost, int breakLevel, bool _loseValue, PhotonMessageInfo _info)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			if (breakLevel != -77)
			{
				return true;
			}
			if (!SemiFunc.MasterOnlyRPC(_info))
			{
				return false;
			}
			ValuableObject valuableObject = __instance.valuableObject;
			if (_loseValue && (Object)(object)valuableObject != (Object)null)
			{
				valuableObject.dollarValueCurrent -= valueLost;
				if (valuableObject.dollarValueCurrent < valuableObject.dollarValueOriginal * 0.15f && !SemiFunc.RunIsTutorial())
				{
					__instance.DestroyObject(true, false);
				}
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(PlayerHealth), "Hurt")]
	internal static class PlayerHealth_Hurt_Patch
	{
		[HarmonyPrefix]
		private static bool Prefix(PlayerHealth __instance, ref int damage, bool savingGrace, int enemyIndex, bool hurtByHeal, out PlayerHurtContext? __state)
		{
			__state = null;
			if (!CharmsApi.HasHurtHandlers || !ConfigurationController.CoreEnabled || !WouldApplyDamage(__instance, damage, enemyIndex))
			{
				return true;
			}
			PlayerHurtContext playerHurtContext = new PlayerHurtContext(damage, __instance.health, __instance.maxHealth, savingGrace, enemyIndex, hurtByHeal);
			CharmsApi.RunHurtHandlers(playerHurtContext);
			__state = playerHurtContext;
			damage = ((playerHurtContext.Damage >= 0) ? playerHurtContext.Damage : 0);
			return !playerHurtContext.Cancel;
		}

		[HarmonyPostfix]
		private static void Postfix(PlayerHealth __instance, PlayerHurtContext? __state)
		{
			if (__state != null && __state.InvincibleSecondsAfter > 0f)
			{
				__instance.InvincibleSet(__state.InvincibleSecondsAfter);
			}
		}

		private static bool WouldApplyDamage(PlayerHealth health, int damage, int enemyIndex)
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Invalid comparison between Unknown and I4
			try
			{
				if (health.isMenuAvatar || damage <= 0 || health.godMode || health.invincibleTimer > 0f)
				{
					return false;
				}
				if (SemiFunc.IsMultiplayer() && !health.photonView.IsMine)
				{
					return false;
				}
				PlayerAvatar playerAvatar = health.playerAvatar;
				if ((Object)(object)playerAvatar == (Object)null || playerAvatar.deadSet || (Object)(object)GameDirector.instance == (Object)null || (int)GameDirector.instance.currentState != 2)
				{
					return false;
				}
				return true;
			}
			catch (Exception ex)
			{
				CharmCorePlugin.Logger.LogWarning((object)("Could not check whether a hit would land: " + ex.Message));
				return false;
			}
		}
	}
	[HarmonyPatch(typeof(ValuableObject), "Start")]
	internal static class ValuableObject_Start_Patch
	{
		[HarmonyPostfix]
		private static void Postfix(ValuableObject __instance)
		{
			if (!((Object)(object)((Component)__instance).GetComponent<CharmWear>() != (Object)null))
			{
				((Component)__instance).gameObject.AddComponent<CharmWear>();
				PhotonView component = ((Component)__instance).GetComponent<PhotonView>();
				if ((Object)(object)component != (Object)null)
				{
					component.RefreshRpcMonoBehaviourCache();
				}
			}
		}
	}
}
namespace CharmCore.Net
{
	internal static class ChargeEvents
	{
		internal const byte EventCode = 184;

		internal static void Broadcast(Charm charm, ValuableObject valuable)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			if (SemiFunc.IsMultiplayer() && PhotonNetwork.IsMasterClient)
			{
				PhotonView component = ((Component)valuable).GetComponent<PhotonView>();
				if (!((Object)(object)component == (Object)null) && component.ViewID != 0)
				{
					object[] array = new object[2] { charm.Id, component.ViewID };
					PhotonNetwork.RaiseEvent((byte)184, (object)array, new RaiseEventOptions
					{
						Receivers = (ReceiverGroup)0
					}, SendOptions.SendReliable);
				}
			}
		}

		internal static void Receive(EventData photonEvent)
		{
			if (photonEvent.Code == 184 && photonEvent.CustomData is object[] array && array.Length >= 2 && array[1] is int num)
			{
				PhotonView val = PhotonView.Find(num);
				ValuableObject val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<ValuableObject>() : null);
				if ((Object)(object)val2 != (Object)null)
				{
					CharmTracker.SpendCharge(val2);
				}
			}
		}
	}
	internal sealed class CharmRoomEvents : MonoBehaviourPunCallbacks, IOnEventCallback
	{
		public override void OnMasterClientSwitched(Player newMasterClient)
		{
			HostSettings.Publish();
		}

		public void OnEvent(EventData photonEvent)
		{
			HostRequests.Receive(photonEvent);
			ChargeEvents.Receive(photonEvent);
		}
	}
	internal sealed class CharmTracker : MonoBehaviour
	{
		private const int SlotCount = 3;

		private static readonly ValuableObject?[] SlotValuables = (ValuableObject?[])(object)new ValuableObject[3];

		private static readonly Charm?[] SlotCharms = new Charm[3];

		private static CharmTracker? instance;

		private static readonly Dictionary<int, ChargeTimer> Charges = new Dictionary<int, ChargeTimer>();

		private float nextSpawnSwitchCheck;

		private float nextLevelCheck;

		private bool wasInLevel;

		private static void ChargeStored(ValuableObject valuable)
		{
			int instanceID = ((Object)valuable).GetInstanceID();
			Charges.TryGetValue(instanceID, out var value);
			value.Store(Time.time);
			Charges[instanceID] = value;
		}

		private static void ChargeRemoved(ValuableObject valuable)
		{
			int instanceID = ((Object)valuable).GetInstanceID();
			if (Charges.TryGetValue(instanceID, out var value))
			{
				value.Remove(Time.time);
				Charges[instanceID] = value;
			}
		}

		internal static void SpendCharge(ValuableObject valuable)
		{
			int instanceID = ((Object)valuable).GetInstanceID();
			Charges.TryGetValue(instanceID, out var value);
			value.Spend(Time.time);
			Charges[instanceID] = value;
		}

		internal static float ChargeFractionOf(ValuableObject valuable, float seconds)
		{
			if (seconds <= 0f)
			{
				return 1f;
			}
			int instanceID = ((Object)valuable).GetInstanceID();
			if (!Charges.TryGetValue(instanceID, out var value))
			{
				value.Store(Time.time);
				Charges[instanceID] = value;
			}
			return value.Fraction(Time.time, seconds);
		}

		internal static bool TryGetCharge(int slot, out float fraction)
		{
			fraction = 1f;
			if (slot < 0 || slot >= 3 || SlotCharms[slot] == null || (Object)(object)SlotValuables[slot] == (Object)null || !SlotCharms[slot].UsesCharge)
			{
				return false;
			}
			fraction = ChargeFractionOf(SlotValuables[slot], SlotCharms[slot].ChargeSeconds);
			return fraction < 0.9999f;
		}

		internal static void StartDebugSpawn()
		{
			if ((Object)(object)instance != (Object)null)
			{
				((MonoBehaviour)instance).StartCoroutine(DebugSpawner.Run());
			}
		}

		private void OnEnable()
		{
			instance = this;
			PocketsApi.Stored += OnStored;
			PocketsApi.Removed += OnRemoved;
		}

		private void OnDisable()
		{
			PocketsApi.Stored -= OnStored;
			PocketsApi.Removed -= OnRemoved;
		}

		private void Update()
		{
			if (Time.unscaledTime >= nextSpawnSwitchCheck)
			{
				nextSpawnSwitchCheck = Time.unscaledTime + 1f;
				DebugSpawner.ServeSpawnSwitches();
			}
			if (Time.unscaledTime >= nextLevelCheck)
			{
				nextLevelCheck = Time.unscaledTime + 0.5f;
				bool flag = IsInLevel();
				if (wasInLevel && !flag)
				{
					Clear();
				}
				wasInLevel = flag;
			}
			for (int i = 0; i < 3; i++)
			{
				if (SlotCharms[i] != null && (Object)(object)SlotValuables[i] == (Object)null)
				{
					Release(i);
				}
			}
		}

		internal static void Clear()
		{
			for (int i = 0; i < 3; i++)
			{
				Release(i);
			}
			foreach (Charm item in CharmsApi.All)
			{
				item.DropAll();
				item.NotifyLevelEnded();
			}
			CharmsApi.ClearCache();
			Charges.Clear();
		}

		internal static bool TryGetCooldown(int slot, out float remaining, out float total)
		{
			remaining = 0f;
			total = 0f;
			if (slot < 0 || slot >= 3 || SlotCharms[slot] == null)
			{
				return false;
			}
			Charm charm = SlotCharms[slot];
			remaining = charm.CooldownRemaining;
			total = charm.CooldownTotal;
			if (remaining > 0f)
			{
				return total > 0f;
			}
			return false;
		}

		private static bool IsInLevel()
		{
			if ((Object)(object)RunManager.instance != (Object)null)
			{
				return SemiFunc.RunIsLevel();
			}
			return false;
		}

		private static void OnStored(PocketEvent pocketEvent)
		{
			if ((Object)(object)((PocketEvent)(ref pocketEvent)).Valuable != (Object)null)
			{
				Charm charm = CharmsApi.CharmOf(((PocketEvent)(ref pocketEvent)).Valuable);
				if (charm != null && charm.UsesCharge)
				{
					ChargeStored(((PocketEvent)(ref pocketEvent)).Valuable);
				}
			}
			if (((PocketEvent)(ref pocketEvent)).PlayerKey == LocalKey() && !((Object)(object)((PocketEvent)(ref pocketEvent)).Valuable == (Object)null) && ((PocketEvent)(ref pocketEvent)).Slot >= 0 && ((PocketEvent)(ref pocketEvent)).Slot < 3)
			{
				Charm charm2 = CharmsApi.CharmOf(((PocketEvent)(ref pocketEvent)).Valuable);
				if (charm2 != null)
				{
					Release(((PocketEvent)(ref pocketEvent)).Slot);
					SlotValuables[((PocketEvent)(ref pocketEvent)).Slot] = ((PocketEvent)(ref pocketEvent)).Valuable;
					SlotCharms[((PocketEvent)(ref pocketEvent)).Slot] = charm2;
					charm2.Carry(((PocketEvent)(ref pocketEvent)).Valuable);
				}
			}
		}

		private static void OnRemoved(PocketEvent pocketEvent)
		{
			if ((Object)(object)((PocketEvent)(ref pocketEvent)).Valuable != (Object)null)
			{
				ChargeRemoved(((PocketEvent)(ref pocketEvent)).Valuable);
			}
			if (((PocketEvent)(ref pocketEvent)).PlayerKey == LocalKey() && ((PocketEvent)(ref pocketEvent)).Slot >= 0 && ((PocketEvent)(ref pocketEvent)).Slot < 3)
			{
				Release(((PocketEvent)(ref pocketEvent)).Slot);
			}
		}

		private static void Release(int slot)
		{
			Charm charm = SlotCharms[slot];
			ValuableObject val = SlotValuables[slot];
			SlotCharms[slot] = null;
			SlotValuables[slot] = null;
			if (charm != null)
			{
				if ((Object)(object)val != (Object)null)
				{
					charm.Drop(val);
				}
				else
				{
					charm.DropAll();
				}
			}
		}

		private static int LocalKey()
		{
			PlayerAvatar val = PlayerAvatar.instance;
			if ((Object)(object)val == (Object)null)
			{
				return int.MinValue;
			}
			if (!SemiFunc.IsMultiplayer())
			{
				return -1;
			}
			return val.photonView.ViewID;
		}
	}
	internal sealed class CharmWear : MonoBehaviourPun
	{
		private ValuableObject valuable;

		internal const int QuietBreakLevel = -77;

		private float deadSince = -1f;

		private void Awake()
		{
			valuable = ((Component)this).GetComponent<ValuableObject>();
		}

		private void Update()
		{
			if (!((Object)(object)valuable == (Object)null) && SemiFunc.IsMasterClientOrSingleplayer())
			{
				PhysGrabObject physGrabObject = valuable.physGrabObject;
				if ((Object)(object)physGrabObject == (Object)null || !physGrabObject.dead || !PocketsApi.IsPocketed(valuable))
				{
					deadSince = -1f;
				}
				else if (deadSince < 0f)
				{
					deadSince = Time.time;
				}
				else if (Time.time - deadSince > 0.5f)
				{
					deadSince = -1f;
					OwnerCharm()?.LogDebug(((Object)valuable).name + " is worn out in a pocket: destroying it");
					physGrabObject.DestroyPhysGrabObject();
				}
			}
		}

		internal void RequestWear(float percent, bool quiet = false)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = (((Object)(object)PlayerAvatar.instance != (Object)null) ? (((Component)PlayerAvatar.instance).transform.position + Vector3.up) : ((Component)this).transform.position);
			if (!SemiFunc.IsMultiplayer() || PhotonNetwork.IsMasterClient)
			{
				ApplyWear(percent, val, quiet);
				return;
			}
			((MonoBehaviourPun)this).photonView.RPC("RequestWearRpc", (RpcTarget)2, new object[3] { percent, val, quiet });
		}

		[PunRPC]
		private void RequestWearRpc(float percent, Vector3 at, bool quiet)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			if (PhotonNetwork.IsMasterClient)
			{
				ApplyWear(Mathf.Clamp(percent, 0f, 100f), at, quiet);
			}
		}

		private void ApplyWear(float percent, Vector3 at, bool quiet)
		{
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)valuable == (Object)null || !PocketsApi.IsPocketed(valuable))
			{
				return;
			}
			PhysGrabObjectImpactDetector val = (((Object)(object)valuable.physGrabObject != (Object)null) ? valuable.physGrabObject.impactDetector : null);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			float num = WearMath.ValueLost(valuable.dollarValueOriginal, valuable.dollarValueCurrent, percent, 1f);
			if (!(num <= 0f))
			{
				WearContext wearContext = new WearContext(valuable, CharmsApi.CarrierOf(valuable), num);
				CharmsApi.RunWearHandlers(wearContext);
				num = ((wearContext.Loss < 0f) ? 0f : Math.Min(wearContext.Loss, valuable.dollarValueCurrent));
				if (!(num <= 0f))
				{
					OwnerCharm()?.LogDebug($"Wear {((Object)valuable).name}: -{num:0} (original {valuable.dollarValueOriginal:0}, current {valuable.dollarValueCurrent:0}, {percent:0.#}%)");
					val.Break(num, at, quiet ? (-77) : val.breakLevelLight, true);
					OwnerCharm()?.LogDebug($"After wear {((Object)valuable).name}: current {valuable.dollarValueCurrent:0}, dead {(Object)(object)valuable.physGrabObject != (Object)null && valuable.physGrabObject.dead}");
				}
			}
		}

		private Charm? OwnerCharm()
		{
			if (!((Object)(object)valuable != (Object)null))
			{
				return null;
			}
			return CharmsApi.CharmOf(valuable);
		}
	}
	internal static class DebugSpawner
	{
		private static readonly string[] SizeFolders = new string[7] { "01 Tiny", "02 Small", "03 Medium", "04 Big", "05 Wide", "06 Tall", "07 Very Tall" };

		private const float WaitForLevelSeconds = 60f;

		private const float SettleSeconds = 2f;

		private const float SpawnDistance = 2.5f;

		private const float SideStep = 0.5f;

		internal static IEnumerator Run()
		{
			if (!AnyDebugCharm())
			{
				yield break;
			}
			float deadline = Time.time + 60f;
			while (Time.time < deadline && !LevelReady())
			{
				yield return null;
			}
			yield return (object)new WaitForSeconds(2f);
			if (!LevelReady() || !SemiFunc.RunIsLevel() || !SemiFunc.IsMasterClientOrSingleplayer())
			{
				yield break;
			}
			PlayerAvatar instance = PlayerAvatar.instance;
			int num = 0;
			foreach (Charm item in CharmsApi.All)
			{
				if (item.DebugMode && TryPlace(item, instance, num))
				{
					num++;
				}
			}
		}

		internal static bool TryPlace(Charm charm, PlayerAvatar avatar, int index)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			if (!SemiFunc.IsMasterClientOrSingleplayer())
			{
				charm.LogDebug("Only the host (or a singleplayer game) can place a valuable.");
				return false;
			}
			foreach (string valuablePrefabName in charm.ValuablePrefabNames)
			{
				string text = FindResourcePath(valuablePrefabName);
				if (text != null)
				{
					Vector3 val = FloorPosition(avatar, index);
					if (Spawn(text, val, Quaternion.identity))
					{
						charm.LogDebug($"Debug mode: placed {valuablePrefabName} at {val}");
						return true;
					}
					break;
				}
			}
			CharmCorePlugin.Logger.LogWarning((object)("Debug mode: could not find a valuable to place for charm '" + charm.Id + "' (" + string.Join(", ", charm.ValuablePrefabNames) + ")."));
			return false;
		}

		internal static void ServeSpawnSwitches()
		{
			int num = 0;
			foreach (Charm item in CharmsApi.All)
			{
				if (item.DebugMode)
				{
					item.ReloadConfigFile();
				}
				if (item.ConsumeSpawnRequest(out var debugModeOn))
				{
					PlayerAvatar instance = PlayerAvatar.instance;
					if (!debugModeOn)
					{
						CharmCorePlugin.Logger.LogWarning((object)("Charm '" + item.Id + "': Debug.SpawnNow needs Debug.DebugMode to be on; the switch was turned off."));
					}
					else if ((Object)(object)instance == (Object)null || !SemiFunc.RunIsLevel())
					{
						CharmCorePlugin.Logger.LogWarning((object)("Charm '" + item.Id + "': Debug.SpawnNow only works inside a level; the switch was turned off."));
					}
					else if (TryPlace(item, instance, num))
					{
						num++;
					}
				}
			}
		}

		private static bool AnyDebugCharm()
		{
			foreach (Charm item in CharmsApi.All)
			{
				if (item.DebugMode)
				{
					return true;
				}
			}
			return false;
		}

		private static bool LevelReady()
		{
			if ((Object)(object)LevelGenerator.Instance != (Object)null && LevelGenerator.Instance.Generated)
			{
				return (Object)(object)PlayerAvatar.instance != (Object)null;
			}
			return false;
		}

		private static Vector3 FloorPosition(PlayerAvatar avatar, int index)
		{
			//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_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: 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_002b: 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_0031: 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_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: 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_004f: 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_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//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_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			Transform transform = ((Component)avatar).transform;
			Vector3 val = Vector3.ProjectOnPlane(transform.forward, Vector3.up);
			Vector3 normalized = ((Vector3)(ref val)).normalized;
			Vector3 val2 = Vector3.Cross(Vector3.up, normalized);
			Vector3 val3 = transform.position + normalized * 2.5f + val2 * (0.5f * (float)index);
			RaycastHit val4 = default(RaycastHit);
			if (Physics.Raycast(val3 + Vector3.up * 2f, Vector3.down, ref val4, 6f, LayerMask.op_Implicit(SemiFunc.LayerMaskGetVisionObstruct())))
			{
				return ((RaycastHit)(ref val4)).point + Vector3.up * 0.2f;
			}
			return val3;
		}

		private static string? FindResourcePath(string prefabName)
		{
			string[] sizeFolders = SizeFolders;
			foreach (string text in sizeFolders)
			{
				string text2 = "Valuables/" + text + "/" + prefabName;
				if ((Object)(object)Resources.Load<GameObject>(text2) != (Object)null)
				{
					return text2;
				}
			}
			return null;
		}

		private static bool Spawn(string resourcePath, Vector3 position, Quaternion rotation)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: 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_002c: Unknown result type (might be due to invalid IL or missing references)
			if (SemiFunc.IsMultiplayer())
			{
				return (Object)(object)PhotonNetwork.InstantiateRoomObject(resourcePath, position, rotation, (byte)0, (object[])null) != (Object)null;
			}
			GameObject val = Resources.Load<GameObject>(resourcePath);
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			Object.Instantiate<GameObject>(val, position, rotation);
			return true;
		}
	}
	internal static class HostRequests
	{
		internal const byte EventCode = 183;

		internal static void Send(Charm charm, string action, object[] args)
		{
			//IL_0045: 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_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			if (!SemiFunc.IsMultiplayer() || PhotonNetwork.IsMasterClient)
			{
				PlayerAvatar instance = PlayerAvatar.instance;
				if ((Object)(object)instance != (Object)null)
				{
					charm.HandleHostRequest(instance, action, args);
				}
			}
			else
			{
				object[] array = new object[3] { charm.Id, action, args };
				PhotonNetwork.RaiseEvent((byte)183, (object)array, new RaiseEventOptions
				{
					Receivers = (ReceiverGroup)2
				}, SendOptions.SendReliable);
			}
		}

		internal static void Receive(EventData photonEvent)
		{
			if (photonEvent.Code != 183 || !PhotonNetwork.IsMasterClient || !(photonEvent.CustomData is object[] array) || array.Length < 3 || !(array[0] is string text) || !(array[1] is string action))
			{
				return;
			}
			object[] args = (array[2] as object[]) ?? new object[0];
			Charm charm = null;
			foreach (Charm item in CharmsApi.All)
			{
				if (item.Id == text)
				{
					charm = item;
					break;
				}
			}
			PlayerAvatar val = AvatarOf(photonEvent.Sender);
			if (charm != null && !((Object)(object)val == (Object)null) && charm.IsEnabled && ConfigurationController.CoreEnabled && !((Object)(object)CharmsApi.FirstCarried(val, charm) == (Object)null))
			{
				charm.HandleHostRequest(val, action, args);
			}
		}

		private static PlayerAvatar? AvatarOf(int actorNumber)
		{
			foreach (PlayerAvatar player in GameDirector.instance.PlayerList)
			{
				if ((Object)(object)player != (Object)null && (Object)(object)player.photonView != (Object)null && player.photonView.OwnerActorNr == actorNumber)
				{
					return player;
				}
			}
			return null;
		}
	}
	internal static class HostSettings
	{
		private static bool UseHostValues
		{
			get
			{
				if (PhotonNetwork.InRoom)
				{
					return !PhotonNetwork.IsMasterClient;
				}
				return false;
			}
		}

		internal static void Publish()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_003f: Expected O, but got Unknown
			if (!PhotonNetwork.InRoom || !PhotonNetwork.IsMasterClient)
			{
				return;
			}
			Hashtable val = new Hashtable();
			((Dictionary<object, object>)val).Add((object)"core.enabled", (object)ConfigurationController.LocalCoreEnabled);
			((Dictionary<object, object>)val).Add((object)"core.wear", (object)ConfigurationController.LocalWearMultiplier);
			Hashtable val2 = val;
			foreach (Charm item in CharmsApi.All)
			{
				val2[(object)item.EnabledKey] = item.LocalEnabled;
				val2[(object)item.WearKey] = item.LocalWearPercent;
				if (item.LocalCooldownSeconds.HasValue)
				{
					val2[(object)item.CooldownKey] = item.LocalCooldownSeconds.Value;
				}
				foreach (CharmSetting setting in item.Settings)
				{
					val2[(object)setting.Key] = setting.LocalValue;
				}
			}
			PhotonNetwork.CurrentRoom.SetCustomProperties(val2, (Hashtable)null, (WebFlags)null);
		}

		internal static bool GetBool(string key, bool local)
		{
			if (UseHostValues && ((Dictionary<object, object>)(object)((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties).TryGetValue((object)key, out object value) && value is bool)
			{
				return (bool)value;
			}
			return local;
		}

		internal static float GetFloat(string key, float local)
		{
			if (UseHostValues && ((Dictionary<object, object>)(object)((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties).TryGetValue((object)key, out object value) && value is float)
			{
				return (float)value;
			}
			return local;
		}
	}
}
namespace CharmCore.Domain
{
	internal struct ChargeTimer
	{
		private float accumulated;

		private float storedSince;

		private bool isStored;

		internal void Store(float now)
		{
			if (!isStored)
			{
				storedSince = now;
				isStored = true;
			}
		}

		internal void Remove(float now)
		{
			if (isStored)
			{
				accumulated += Elapsed(now);
				isStored = false;
			}
		}

		internal void Spend(float now)
		{
			accumulated = 0f;
			if (isStored)
			{
				storedSince = now;
			}
		}

		internal float Seconds(float now)
		{
			return accumulated + (isStored ? Elapsed(now) : 0f);
		}

		internal float Fraction(float now, float fullSeconds)
		{
			if (fullSeconds <= 0f)
			{
				return 1f;
			}
			float num = Seconds(now) / fullSeconds;
			if (!(num >= 1f))
			{
				return num;
			}
			return 1f;
		}

		private float Elapsed(float now)
		{
			float num = now - storedSince;
			if (!(num > 0f))
			{
				return 0f;
			}
			return num;
		}
	}
	internal struct CooldownTimer
	{
		private float endsAt;

		private float total;

		internal float Total => total;

		internal float Remaining(float now)
		{
			float num = endsAt - now;
			if (!(num > 0f))
			{
				return 0f;
			}
			return num;
		}

		internal bool IsReady(float now)
		{
			return Remaining(now) <= 0f;
		}

		internal void Start(float now, float seconds)
		{
			if (seconds <= 0f)
			{
				endsAt = 0f;
				total = 0f;
			}
			else
			{
				endsAt = now + seconds;
				total = seconds;
			}
		}

		internal void Reset()
		{
			endsAt = 0f;
			total = 0f;
		}
	}
	internal static class InfoText
	{
		internal static string Compose(string name, string? description)
		{
			string text = description?.Trim() ?? string.Empty;
			if (text.Length != 0)
			{
				return name + "\n<size=80%><color=#FFFFFF>" + text + "</color></size>";
			}
			return string.Empty;
		}
	}
	internal readonly struct LabelBox
	{
		internal float CenterX { get; }

		internal float CenterY { get; }

		internal float Width { get; }

		internal float Height { get; }

		internal float Top => CenterY + Height / 2f;

		internal float Bottom => CenterY - Height / 2f;

		internal LabelBox(float centerX, float centerY, float width, float height)
		{
			CenterX = centerX;
			CenterY = centerY;
			Width = width;
			Height = height;
		}
	}
	internal static class SlotLayout
	{
		private const float WidthShare = 0.96f;

		private const float BoxHeightShare = 0.56f;

		private const float TopMargin = 0.03f;

		private const float BottomMargin = 0.05f;

		internal const float GlyphHeightShare = 0.55f;

		internal static void Split(float left, float right, float top, float bottom, out LabelBox seconds, out LabelBox value)
		{
			float num = top - bottom;
			float num2 = right - left;
			if (num <= 0f || num2 <= 0f)
			{
				seconds = new LabelBox(left, bottom, 0f, 0f);
				value = new LabelBox(left, bottom, 0f, 0f);
				return;
			}
			float centerX = (left + right) / 2f;
			float width = num2 * 0.96f;
			float num3 = num * 0.56f;
			seconds = new LabelBox(centerX, top - num * 0.03f - num3 / 2f, width, num3);
			value = new LabelBox(centerX, bottom + num * 0.05f + num3 / 2f, width, num3);
		}
	}
	internal static class WearMath
	{
		internal static float ValueLost(float original, float current, float percent, float multiplier)
		{
			if (original <= 0f || current <= 0f || percent <= 0f || multiplier <= 0f)
			{
				return 0f;
			}
			return Math.Min(Math.Max((float)Math.Round(original * (percent / 100f) * multiplier), 1f), current);
		}

		internal static float CooldownFraction(float remaining, float total)
		{
			if (total <= 0f || remaining <= 0f)
			{
				return 0f;
			}
			return Math.Min(remaining / total, 1f);
		}
	}
}
namespace CharmCore.Api
{
	public abstract class Charm
	{
		internal const float MaxWearPercent = 100f;

		internal const float MaxCooldownSeconds = 600f;

		private readonly List<ValuableObject> carried = new List<ValuableObject>();

		private readonly List<CharmSetting> settings = new List<CharmSetting>();

		private CooldownTimer cooldown;

		private float pendingWear;

		private ConfigEntry<bool>? enabledEntry;

		private ConfigEntry<float>? wearEntry;

		private ConfigEntry<float>? cooldownEntry;

		private ConfigEntry<bool>? debugEntry;

		private ConfigEntry<bool>? spawnNowEntry;

		private ConfigFile? configFile;

		private bool spawnRequested;

		private CharmSetting? chargeSeconds;

		public string Id { get; }

		public bool UsesCharge => chargeSeconds != null;

		public float ChargeSeconds => chargeSeconds?.Value ?? 0f;

		public float ChargeFraction
		{
			get
			{
				if (!UsesCharge)
				{
					return 1f;
				}
				ValuableObject val = FirstCarried();
				if (!((Object)(object)val == (Object)null))
				{
					return CharmTracker.ChargeFractionOf(val, ChargeSeconds);
				}
				return 0f;
			}
		}

		protected bool WearsPerSecond { get; set; }

		protected string? WearDescription { get; set; }

		public string DisplayName { get; }

		public virtual string? Description => null;

		public IReadOnlyList<string> ValuablePrefabNames { get; }

		public float DefaultWearPercent { get; }

		public float? DefaultCooldownSeconds { get; }

		public bool DebugMode => debugEntry?.Value ?? false;

		public bool IsEnabled => HostSettings.GetBool(EnabledKey, enabledEntry?.Value ?? true);

		public float WearPercent => Mathf.Clamp(HostSettings.GetFloat(WearKey, wearEntry?.Value ?? DefaultWearPercent), 0f, 100f) * ConfigurationController.WearMultiplier;

		public float CooldownSeconds
		{
			get
			{
				if (!DefaultCooldownSeconds.HasValue)
				{
					return 0f;
				}
				return Mathf.Clamp(HostSettings.GetFloat(CooldownKey, cooldownEntry?.Value ?? DefaultCooldownSeconds.Value), 0f, 600f);
			}
		}

		public bool IsActive
		{
			get
			{
				if (carried.Count > 0 && ConfigurationController.CoreEnabled)
				{
					return IsEnabled;
				}
				return false;
			}
		}

		public float CooldownRemaining => cooldown.Remaining(Time.time);

		public bool IsReady
		{
			get
			{
				if (IsActive)
				{
					return cooldown.IsReady(Time.time);
				}
				return false;
			}
		}

		internal float CooldownTotal => cooldown.Total;

		internal IReadOnlyList<CharmSetting> Settings => settings;

		internal float LocalWearPercent => wearEntry?.Value ?? DefaultWearPercent;

		internal float? LocalCooldownSeconds => cooldownEntry?.Value;

		internal bool LocalEnabled => enabledEntry?.Value ?? true;

		internal string EnabledKey { get; }

		internal string WearKey { get; }

		internal string CooldownKey { get; }

		protected Charm(string id, string displayName, float defaultWearPercent, float? defaultCooldownSeconds, params string[] valuablePrefabNames)
		{
			Id = id;
			EnabledKey = "charm." + id + ".enabled";
			WearKey = "charm." + id + ".wear";
			CooldownKey = "charm." + id + ".cooldown";
			DisplayName = displayName;
			DefaultWearPercent = defaultWearPercent;
			DefaultCooldownSeconds = defaultCooldownSeconds;
			ValuablePrefabNames = valuablePrefabNames;
		}

		protected void EnableCharge(float defaultSeconds)
		{
			chargeSeconds = AddSetting("ChargeSeconds", defaultSeconds, 5f, 1800f, "Seconds the valuable must stay in a pocket to be fully charged (5 to 1800). A partly charged charm works in proportion to its charge.");
		}

		internal string? SafeDescription()
		{
			try
			{
				return Description;
			}
			catch (Exception arg)
			{
				CharmCorePlugin.Logger.LogError((object)$"Charm '{Id}' threw building its description: {arg}");
				return null;
			}
		}

		public void LogDebug(string message)
		{
			if (DebugMode)
			{
				CharmCorePlugin.Logger.LogInfo((object)("[" + Id + "] " + message));
			}
		}

		public bool TryUse()
		{
			return TryUse(WearPercent);
		}

		public bool TryUse(float wearPercent)
		{
			if (!IsReady)
			{
				return false;
			}
			cooldown.Start(Time.time, CooldownSeconds);
			LogDebug($"Used: wear {wearPercent:0.#}%, cooldown {CooldownSeconds:0.#} s");
			Wear(wearPercent);
			return true;
		}

		public void WearForSeconds(float deltaSeconds)
		{
			if (IsActive && !(deltaSeconds <= 0f))
			{
				pendingWear += WearPercent * deltaSeconds;
				if (pendingWear >= 1f)
				{
					float wearPercent = pendingWear;
					pendingWear = 0f;
					Wear(wearPercent, quiet: true);
				}
			}
		}

		public void SendToHost(string action, params object[] args)
		{
			if (IsActive)
			{
				HostRequests.Send(this, action, args);
			}
		}

		protected virtual void OnHostRequest(PlayerAvatar sender, string action, object[] args)
		{
		}

		internal void HandleHostRequest(PlayerAvatar sender, string action, object[] args)
		{
			try
			{
				OnHostRequest(sender, action, args);
			}
			catch (Exception arg)
			{
				CharmCorePlugin.Logger.LogError((object)$"Charm '{Id}' threw handling the host request '{action}': {arg}");
			}
		}

		public void WearValuable(ValuableObject valuable, float wearPercent)
		{
			WearValuable(valuable, wearPercent, quiet: false);
		}

		public void WearValuable(ValuableObject valuable, float wearPercent, bool quiet)
		{
			if (!((Object)(object)valuable == (Object)null) && !(wearPercent <= 0f))
			{
				CharmWear component = ((Component)valuable).GetComponent<CharmWear>();
				if ((Object)(object)component != (Object)null)
				{
					component.RequestWear(wearPercent, quiet);
				}
			}
		}

		public void Wear(float wearPercent)
		{
			Wear(wearPercent, quiet: false);
		}

		public void Wear(float wearPercent, bool quiet)
		{
			if (carried.Count == 0 || wearPercent <= 0f)
			{
				return;
			}
			ValuableObject val = FirstCarried();
			if (!((Object)(object)val == (Object)null))
			{
				CharmWear component = ((Component)val).GetComponent<CharmWear>();
				if ((Object)(object)component != (Object)null)
				{
					component.RequestWear(wearPercent, quiet);
				}
			}
		}

		protected CharmSetting AddSetting(string name, float defaultValue, float min, float max, string description)
		{
			CharmSetting charmSetting = new CharmSetting(this, name, defaultValue, min, max, description);
			settings.Add(charmSetting);
			return charmSetting;
		}

		protected virtual void OnActivated()
		{
		}

		protected virtual void OnDeactivated()
		{
		}

		protected virtual void OnLevelEnded()
		{
		}

		internal void NotifyLevelEnded()
		{
			Guard(OnLevelEnded, "OnLevelEnded");
		}

		internal void Bind(ConfigFile config)
		{
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Expected O, but got Unknown
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Expected O, but got Unknown
			string text = "Charm." + Id;
			enabledEntry = config.Bind<bool>(text, "Enabled", true, "Turn this charm on or off. The host's choice applies to everyone.");
			string text2 = WearDescription ?? (WearsPerSecond ? "How much of the valuable's original value is worn away each second the power is working, in percent (0 to 100)." : "How much of the valuable's original value each use wears away, in percent (0 to 100).");
			wearEntry = config.Bind<float>(text, "WearPercent", Mathf.Clamp(DefaultWearPercent, 0f, 100f), new ConfigDescription(text2 + " The host's choice applies to everyone.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			if (DefaultCooldownSeconds.HasValue)
			{
				cooldownEntry = config.Bind<float>(text, "CooldownSeconds", Mathf.Clamp(DefaultCooldownSeconds.Value, 0f, 600f), new ConfigDescription("Pause between uses, in seconds (0 to 600). 0 means no pause. The host's choice applies to everyone.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 600f), Array.Empty<object>()));
			}
			foreach (CharmSetting setting in settings)
			{
				setting.Bind(config, text);
			}
			debugEntry = config.Bind<bool>("Debug", "DebugMode", false, "For testing: when a level starts, this charm's valuable appears on the floor in front of you (host or singleplayer only), and detailed log lines are written. Local setting.");
			configFile = config;
			spawnNowEntry = config.Bind<bool>("Debug", "SpawnNow", false, "For testing, with DebugMode on: set to true while a level is running and this charm's valuable is placed near you right away (host or singleplayer only). The switch turns itself back off. Local setting.");
			spawnNowEntry.SettingChanged += delegate
			{
				if (spawnNowEntry.Value)
				{
					spawnRequested = true;
				}
			};
			config.SettingChanged += delegate
			{
				HostSettings.Publish();
			};
		}

		internal void ReloadConfigFile()
		{
			ConfigFile? obj = configFile;
			if (obj != null)
			{
				obj.Reload();
			}
		}

		internal bool ConsumeSpawnRequest(out bool debugModeOn)
		{
			debugModeOn = DebugMode;
			if (!spawnRequested)
			{
				ConfigEntry<bool>? obj = spawnNowEntry;
				if (obj == null || !obj.Value)
				{
					return false;
				}
			}
			spawnRequested = false;
			if (spawnNowEntry != null && spawnNowEntry.Value)
			{
				spawnNowEntry.Value = false;
			}
			return true;
		}

		internal string Key(string name)
		{
			return "charm." + Id + "." + name;
		}

		internal void Carry(ValuableObject valuable)
		{
			if (!carried.Contains(valuable))
			{
				carried.Add(valuable);
				LogDebug($"Carrying {((Object)valuable).name} (value {valuable.dollarValueCurrent:0}); active: {IsActive}");
				if (carried.Count == 1)
				{
					Guard(OnActivated, "OnActivated");
				}
			}
		}

		internal void Drop(ValuableObject valuable)
		{
			if (carried.Remove(valuable))
			{
				LogDebug("No longer carrying " + ((Object)valuable).name);
				if (carried.Count == 0)
				{
					cooldown.Reset();
					pendingWear = 0f;
					Guard(OnDeactivated, "OnDeactivated");
				}
			}
		}

		internal void DropAll()
		{
			if (carried.Count != 0)
			{
				carried.Clear();
				cooldown.Reset();
				pendingWear = 0f;
				Guard(OnDeactivated, "OnDeactivated");
			}
		}

		private ValuableObject? FirstCarried()
		{
			for (int i = 0; i < carried.Count; i++)
			{
				if ((Object)(object)carried[i] != (Object)null)
				{
					return carried[i];
				}
			}
			return null;
		}

		private void Guard(Action action, string name)
		{
			try
			{
				action();
			}
			catch (Exception arg)
			{
				CharmCorePlugin.Logger.LogError((object)$"Charm '{Id}' threw in {name}: {arg}");
			}
		}
	}
	public static class CharmsApi
	{
		private static readonly List<Charm> Charms = new List<Charm>();

		private static readonly List<KeyValuePair<int, Action<PlayerHurtContext>>> HurtHandlers = new List<KeyValuePair<int, Action<PlayerHurtContext>>>();

		private static readonly List<Action<WearContext>> WearHandlers = new List<Action<WearContext>>();

		private static readonly Dictionary<int, Charm?> CharmOfCache = new Dictionary<int, Charm>();

		internal static bool HasHurtHandlers => HurtHandlers.Count > 0;

		internal static IReadOnlyList<Charm> All => Charms;

		public static void Register(Charm charm, ConfigFile config)
		{
			if (charm == null)
			{
				throw new ArgumentNullException("charm");
			}
			if (config == null)
			{
				throw new ArgumentNullException("config");
			}
			foreach (Charm charm2 in Charms)
			{
				if (charm2.Id == charm.Id)
				{
					CharmCorePlugin.Logger.LogWarning((object)("A charm with id '" + charm.Id + "' is already registered; ignoring the duplicate."));
					return;
				}
			}
			charm.Bind(config);
			Charms.Add(charm);
			CharmOfCache.Clear();
			CharmCorePlugin.Logger.LogInfo((object)("Charm registered: " + charm.DisplayName + " (" + string.Join(", ", charm.ValuablePrefabNames) + ")"));
		}

		public static void OnPlayerHurting(Action<PlayerHurtContext> handler, int priority = 10)
		{
			if (handler == null)
			{
				throw new ArgumentNullException("handler");
			}
			int num = HurtHandlers.Count;
			while (num > 0 && HurtHandlers[num - 1].Key > priority)
			{
				num--;
			}
			HurtHandlers.Insert(num, new KeyValuePair<int, Action<PlayerHurtContext>>(priority, handler));
		}

		internal static void RunHurtHandlers(PlayerHurtContext context)
		{
			KeyValuePair<int, Action<PlayerHurtContext>>[] array = HurtHandlers.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				KeyValuePair<int, Action<PlayerHurtContext>> keyValuePair = array[i];
				if (context.Cancel)
				{
					break;
				}
				try
				{
					keyValuePair.Value(context);
				}
				catch (Exception arg)
				{
					CharmCorePlugin.Logger.LogError((object)$"A player-hurting handler threw: {arg}");
				}
			}
		}

		public static void OnWearing(Action<WearContext> handler)
		{
			if (handler == null)
			{
				throw new ArgumentNullException("handler");
			}
			WearHandlers.Add(handler);
		}

		internal static void RunWearHandlers(WearContext context)
		{
			Action<WearContext>[] array = WearHandlers.ToArray();
			foreach (Action<WearContext> action in array)
			{
				try
				{
					action(context);
				}
				catch (Exception arg)
				{
					CharmCorePlugin.Logger.LogError((object)$"A wear handler threw: {arg}");
				}
			}
		}

		public static Charm? CharmOf(ValuableObject valuable)
		{
			if ((Object)(object)valuable == (Object)null)
			{
				return null;
			}
			int instanceID = ((Object)valuable).GetInstanceID();
			if (!CharmOfCache.TryGetValue(instanceID, out Charm value))
			{
				value = FindFor(((Object)((Component)valuable).gameObject).name.Replace("(Clone)", string.Empty).Trim());
				CharmOfCache[instanceID] = value;
			}
			return value;
		}

		internal static void ClearCache()
		{
			CharmOfCache.Clear();
		}

		public static PlayerAvatar? CarrierOf(ValuableObject valuable)
		{
			if ((Object)(object)valuable == (Object)null || (Object)(object)GameDirector.instance == (Object)null)
			{
				return null;
			}
			PlayerAvatar[] array = GameDirector.instance.PlayerList.ToArray();
			foreach (PlayerAvatar val in array)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				foreach (ValuableObject item in PocketsApi.GetStored(KeyOf(val)))
				{
					if ((Object)(object)item == (Object)(object)valuable)
					{
						return val;
					}
				}
			}
			return null;
		}

		public static IReadOnlyList<ValuableObject> CarriedBy(PlayerAvatar avatar, Charm charm)
		{
			List<ValuableObject> list = new List<ValuableObject>();
			if ((Object)(object)avatar == (Object)null)
			{
				return list;
			}
			foreach (ValuableObject item in PocketsApi.GetStored(KeyOf(avatar)))
			{
				if ((Object)(object)item != (Object)null && CharmOf(item) == charm)
				{
					list.Add(item);
				}
			}
			return list;
		}

		public static void ForEachCarrier(Charm charm, Action<PlayerAvatar, ValuableObject> action)
		{
			if (charm == null || action == null || (Object)(object)GameDirector.instance == (Object)null || !ConfigurationController.CoreEnabled || !charm.IsEnabled)
			{
				return;
			}
			List<PlayerAvatar> playerList = GameDirector.instance.PlayerList;
			for (int i = 0; i < playerList.Count; i++)
			{
				PlayerAvatar val = playerList[i];
				if (!((Object)(object)val == (Object)null) && !val.deadSet)
				{
					ValuableObject val2 = FirstCarried(val, charm);
					if ((Object)(object)val2 != (Object)null)
					{
						action(val, val2);
					}
				}
			}
		}

		public static float ChargeOf(PlayerAvatar avatar, Charm charm)
		{
			if (charm == null || !charm.UsesCharge)
			{
				return 1f;
			}
			ValuableObject val = FirstCarried(avatar, charm);
			if (!((Object)(object)val == (Object)null))
			{
				return CharmTracker.ChargeFractionOf(val, charm.ChargeSeconds);
			}
			return 0f;
		}

		public static void ConsumeCharge(Charm charm, ValuableObject valuable)
		{
			if (charm != null && !((Object)(object)valuable == (Object)null) && charm.UsesCharge)
			{
				CharmTracker.SpendCharge(valuable);
				ChargeEvents.Broadcast(charm, valuable);
			}
		}

		internal static ValuableObject? FirstCarried(PlayerAvatar avatar, Charm charm)
		{
			if ((Object)(object)avatar == (Object)null)
			{
				return null;
			}
			IReadOnlyList<ValuableObject> stored = PocketsApi.GetStored(KeyOf(avatar));
			for (int i = 0; i < stored.Count; i++)
			{
				ValuableObject val = stored[i];
				if ((Object)(object)val != (Object)null && CharmOf(val) == charm)
				{
					return val;
				}
			}
			return null;
		}

		internal static int KeyOf(PlayerAvatar avatar)
		{
			if (!SemiFunc.IsMultiplayer())
			{
				return -1;
			}
			return avatar.photonView.ViewID;
		}

		internal static Charm? FindFor(string prefabName)
		{
			foreach (Charm charm in Charms)
			{
				foreach (string valuablePrefabName in charm.ValuablePrefabNames)
				{
					if (string.Equals(valuablePrefabName, prefabName, StringComparison.OrdinalIgnoreCase))
					{
						return charm;
					}
				}
			}
			return null;
		}
	}
	public sealed class CharmSetting
	{
		private readonly Charm owner;

		private readonly string name;

		private readonly float defaultValue;

		private readonly float min;

		private readonly float max;

		private readonly string description;

		private ConfigEntry<float>? entry;

		private string? key;

		public float Value => Clamp(HostSettings.GetFloat(Key, LocalValue));

		internal string Key => key ?? (key = owner.Key(name));

		internal float LocalValue => entry?.Value ?? defaultValue;

		internal CharmSetting(Charm owner, string name, float defaultValue, float min, float max, string description)
		{
			this.owner = owner;
			this.name = name;
			this.min = min;
			this.max = max;
			this.defaultValue = ((defaultValue < min) ? min : ((defaultValue > max) ? max : defaultValue));
			this.description = description;
		}

		private float Clamp(float value)
		{
			if (!(value < min))
			{
				if (!(value > max))
				{
					return value;
				}
				return max;
			}
			return min;
		}

		internal void Bind(ConfigFile config, string section)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			entry = config.Bind<float>(section, name, defaultValue, new ConfigDescription(description + " The host's choice applies to everyone.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(min, max), Array.Empty<object>()));
		}
	}
	public sealed class PlayerHurtContext
	{
		public int Damage { get; set; }

		public bool Cancel { get; set; }

		public float InvincibleSecondsAfter { get; set; }

		public int Health { get; }

		public int MaxHealth { get; }

		public bool SavingGrace { get; }

		public int EnemyIndex { get; }

		public bool HurtByHeal { get; }

		public bool IsLethal
		{
			get
			{
				if (!Cancel)
				{
					return Damage >= Health;
				}
				return false;
			}
		}

		internal PlayerHurtContext(int damage, int health, int maxHealth, bool savingGrace, int enemyIndex, bool hurtByHeal)
		{
			Damage = damage;
			Health = health;
			MaxHealth = maxHealth;
			SavingGrace = savingGrace;
			EnemyIndex = enemyIndex;
			HurtByHeal = hurtByHeal;
		}
	}
	public sealed class WearContext
	{
		public ValuableObject Valuable { get; }

		public PlayerAvatar? Carrier { get; }

		public float Loss { get; set; }

		internal WearContext(ValuableObject valuable, PlayerAvatar? carrier, float loss)
		{
			Valuable = valuable;
			Carrier = carrier;
			Loss = loss;
		}
	}
}