Decompiled source of RepoRelics v0.1.0

RepoRelics.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using UnityEngine.SceneManagement;

[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("RepoRelics")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("RepoRelics")]
[assembly: AssemblyTitle("RepoRelics")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace RepoRelics
{
	[BepInPlugin("den.repo.relics", "REPO Relics", "0.2.1")]
	public sealed class Plugin : BaseUnityPlugin
	{
		private sealed class Profile
		{
			public int[] Levels = new int[6];

			public List<string> Receipts = new List<string>();
		}

		private sealed class Overlay
		{
			public IDictionary<string, int> Dict;

			public string Id;

			public int Count;
		}

		private sealed class StripState
		{
			public bool Own;

			public bool Reset;

			public readonly List<Tuple<Overlay, int>> Values = new List<Tuple<Overlay, int>>();
		}

		private const string ProfileKey = "den.relics.skills.v2";

		private const string RelicKey = "den.relics.object.v2";

		private const string ResultKey = "den.relics.result.v2";

		private const string Wire = "den.relics.award.v2";

		private const byte AwardCode = 185;

		private static Plugin self;

		private readonly string[] names = new string[6] { "Long Arm", "Power Throw", "Air Step", "Rolling Force", "Quick Rest", "Wall Tumble" };

		private readonly string[] desc = new string[6] { "Grab range +1", "Throw strength +1", "Extra jump +1", "Tumble launch +1", "Crouch rest +1", "Tumble climb +1" };

		private readonly string[] fields = new string[6] { "playerUpgradeRange", "playerUpgradeThrow", "playerUpgradeExtraJump", "playerUpgradeLaunch", "playerUpgradeCrouchRest", "playerUpgradeTumbleClimb" };

		private readonly string[] upgrades = new string[6] { "UpgradePlayerGrabRange", "UpgradePlayerThrowStrength", "UpgradePlayerExtraJump", "UpgradePlayerTumbleLaunch", "UpgradePlayerCrouchRest", "UpgradePlayerTumbleClimb" };

		private readonly string[] refresh = new string[6] { "UpdateGrabRangeRightAway", "UpdateThrowStrengthRightAway", "UpdateExtraJumpRightAway", "UpdateTumbleLaunchRightAway", "UpdateCrouchRestRightAway", "UpdateTumbleClimbRightAway" };

		private readonly FieldInfo[] dictFields = new FieldInfo[6];

		private readonly MethodInfo[] upMethods = new MethodInfo[6];

		private readonly MethodInfo[] liveMethods = new MethodInfo[6];

		private readonly int[] live = new int[6];

		private const int MaxSkill = 1000;

		private readonly Dictionary<string, Profile> personal = new Dictionary<string, Profile>();

		private GameObject glow;

		private ValuableObject glowTarget;

		private readonly Dictionary<string, Overlay> applied = new Dictionary<string, Overlay>();

		private ConfigEntry<int> chance;

		private ConfigEntry<bool> active;

		private Harmony harmony;

		private FieldInfo truckField;

		private ValuableObject relic;

		private int viewId;

		private int rolledScene = int.MinValue;

		private int rewardedScene = int.MinValue;

		private int master;

		private bool ready;

		private bool saving;

		private bool blocked;

		private bool show;

		private bool hadRoom;

		private float tick;

		private float genAt = -1f;

		private string file;

		private string room = "";

		private string localId = "";

		private string published = "";

		private string notice = "";

		private string lastResult = "";

		private float noticeUntil;

		private bool Host
		{
			get
			{
				if (SemiFunc.IsMultiplayer())
				{
					return PhotonNetwork.IsMasterClient;
				}
				return true;
			}
		}

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

		private bool CanHost
		{
			get
			{
				if (ready && active.Value && Host && !saving)
				{
					return !blocked;
				}
				return false;
			}
		}

		private int Supported
		{
			get
			{
				int num = 0;
				for (int i = 0; i < 6; i++)
				{
					if (dictFields[i] != null && upMethods[i] != null && liveMethods[i] != null)
					{
						num |= 1 << i;
					}
				}
				return num;
			}
		}

		private void Awake()
		{
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_027f: Expected O, but got Unknown
			//IL_0298: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: Expected O, but got Unknown
			//IL_02be: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e0: Expected O, but got Unknown
			//IL_02e0: Expected O, but got Unknown
			//IL_0325: Unknown result type (might be due to invalid IL or missing references)
			//IL_033c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0347: Expected O, but got Unknown
			//IL_0347: Expected O, but got Unknown
			//IL_037c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0393: Unknown result type (might be due to invalid IL or missing references)
			//IL_039e: Expected O, but got Unknown
			//IL_039e: Expected O, but got Unknown
			self = this;
			Array.Fill(live, -1);
			active = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable relics");
			chance = ((BaseUnityPlugin)this).Config.Bind<int>("Loot", "SpawnChancePercent", 20, "Chance per exploration stage (100 for testing)");
			file = Path.Combine(Paths.ConfigPath, "den.repo.relics.personal.tsv");
			Load();
			truckField = AccessTools.Field(typeof(RoomVolumeCheck), "inTruck");
			for (int i = 0; i < 6; i++)
			{
				dictFields[i] = AccessTools.Field(typeof(StatsManager), fields[i]);
				upMethods[i] = AccessTools.Method(typeof(PunManager), upgrades[i], new Type[2]
				{
					typeof(string),
					typeof(int)
				}, (Type[])null) ?? AccessTools.Method(typeof(PunManager), upgrades[i], new Type[1] { typeof(string) }, (Type[])null);
				liveMethods[i] = AccessTools.Method(typeof(PunManager), refresh[i], new Type[2]
				{
					typeof(string),
					typeof(int)
				}, (Type[])null);
			}
			MethodInfo[] array = (from m in typeof(RunManager).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
				where m.Name == "ChangeLevel" && m.GetParameters().Any((ParameterInfo p) => p.Name == "_completedLevel" && p.ParameterType == typeof(bool)) && m.GetParameters().Any((ParameterInfo p) => p.Name == "_levelFailed" && p.ParameterType == typeof(bool))
				select m).ToArray();
			MethodInfo methodInfo = AccessTools.Method(typeof(StatsManager), "SaveGame", new Type[1] { typeof(string) }, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(typeof(StatsManager), "LoadGame", (Type[])null, (Type[])null);
			MethodInfo methodInfo3 = AccessTools.Method(typeof(StatsManager), "ResetAllStats", Type.EmptyTypes, (Type[])null);
			if (truckField == null || truckField.FieldType != typeof(bool) || array.Length != 1 || methodInfo == null || methodInfo2 == null || methodInfo3 == null || Supported == 0)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"REPO Relics: incompatible API; disabled safely.");
				return;
			}
			harmony = new Harmony("den.repo.relics");
			try
			{
				harmony.Patch((MethodBase)array[0], new HarmonyMethod(typeof(Plugin), "BeforeChange", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(Plugin), "BeforeSave", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "AfterStrip", (Type[])null), (HarmonyMethod)null);
				MethodInfo methodInfo4 = AccessTools.Method(typeof(StatsManager), "SaveFileSave", (Type[])null, (Type[])null);
				if (methodInfo4 != null && methodInfo4 != methodInfo)
				{
					harmony.Patch((MethodBase)methodInfo4, new HarmonyMethod(typeof(Plugin), "BeforeSave", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "AfterStrip", (Type[])null), (HarmonyMethod)null);
				}
				MethodInfo[] array2 = new MethodInfo[2] { methodInfo2, methodInfo3 };
				foreach (MethodInfo methodInfo5 in array2)
				{
					harmony.Patch((MethodBase)methodInfo5, new HarmonyMethod(typeof(Plugin), "BeforeReset", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "AfterStrip", (Type[])null), (HarmonyMethod)null);
				}
				SceneManager.sceneLoaded += OnScene;
				PhotonNetwork.NetworkingClient.EventReceived += OnEvent;
				ready = true;
				((BaseUnityPlugin)this).Logger.LogInfo((object)("REPO Relics initialized; supported mask=" + Supported));
			}
			catch (Exception ex)
			{
				harmony.UnpatchSelf();
				((BaseUnityPlugin)this).Logger.LogError((object)ex);
			}
		}

		private void OnDestroy()
		{
			if (ready)
			{
				SceneManager.sceneLoaded -= OnScene;
				PhotonNetwork.NetworkingClient.EventReceived -= OnEvent;
			}
			ClearGlow();
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			if ((Object)(object)self == (Object)(object)this)
			{
				self = null;
			}
		}

		private void OnScene(Scene scene, LoadSceneMode mode)
		{
			//IL_005c: 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_0072: Expected O, but got Unknown
			//IL_0079: Expected O, but got Unknown
			ClearGlow();
			relic = null;
			viewId = 0;
			genAt = -1f;
			rolledScene = int.MinValue;
			rewardedScene = int.MinValue;
			Array.Fill(live, -1);
			if (PhotonNetwork.InRoom && PhotonNetwork.IsMasterClient && !blocked)
			{
				Room currentRoom = PhotonNetwork.CurrentRoom;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add((object)"den.relics.object.v2", (object)0);
				currentRoom.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
			}
		}

		private static bool ValidId(string id)
		{
			if (!string.IsNullOrEmpty(id) && id.Length <= 64)
			{
				return id.All(char.IsDigit);
			}
			return false;
		}

		private string Id(PlayerAvatar a)
		{
			if (!((Object)(object)a == (Object)null))
			{
				return SemiFunc.PlayerGetSteamID(a);
			}
			return "";
		}

		private string LocalId()
		{
			string id = Id(PlayerAvatar.instance);
			if (ValidId(id))
			{
				localId = id;
			}
			return localId;
		}

		private Profile GetProfile(string id)
		{
			if (!ValidId(id))
			{
				return new Profile();
			}
			if (!personal.TryGetValue(id, out var value))
			{
				value = (personal[id] = new Profile());
			}
			return value;
		}

		private int[] Owned(string id)
		{
			return GetProfile(id).Levels;
		}

		private void Load()
		{
			try
			{
				if (!File.Exists(file))
				{
					return;
				}
				string[] array = File.ReadAllLines(file);
				for (int i = 0; i < array.Length; i++)
				{
					string[] array2 = array[i].Split('\t');
					if (array2.Length < 2 || !ValidId(array2[0]))
					{
						continue;
					}
					Profile profile = new Profile();
					if (array2.Length == 2 && int.TryParse(array2[1], out var result) && result >= 0 && result < 64)
					{
						for (int j = 0; j < 6; j++)
						{
							profile.Levels[j] = (result >> j) & 1;
						}
					}
					else
					{
						if (array2.Length != 9 || !(array2[1] == "v2"))
						{
							continue;
						}
						bool flag = true;
						for (int k = 0; k < 6; k++)
						{
							if (!int.TryParse(array2[k + 2], out profile.Levels[k]) || profile.Levels[k] < 0 || profile.Levels[k] > 1000)
							{
								flag = false;
							}
						}
						if (!flag)
						{
							continue;
						}
						profile.Receipts = (from x in array2[8].Split(',')
							where Guid.TryParseExact(x, "N", out var _)
							select x).Distinct().Take(256).ToList();
					}
					personal[array2[0]] = profile;
				}
			}
			catch (Exception ex)
			{
				blocked = true;
				((BaseUnityPlugin)this).Logger.LogError((object)ex);
			}
		}

		private bool Save(string id, Profile profile)
		{
			try
			{
				string text = file + ".tmp";
				File.WriteAllText(text, id + "\tv2\t" + string.Join("\t", profile.Levels) + "\t" + string.Join(",", profile.Receipts) + "\n");
				if (File.Exists(file))
				{
					File.Replace(text, file, file + ".bak");
				}
				else
				{
					File.Move(text, file);
				}
				personal[id] = profile;
				return true;
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)ex);
				return false;
			}
		}

		private void Publish()
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Expected O, but got Unknown
			//IL_0090: Expected O, but got Unknown
			if (!PhotonNetwork.InRoom || PhotonNetwork.LocalPlayer == null)
			{
				return;
			}
			string text = LocalId();
			if (!ValidId(text))
			{
				return;
			}
			string text2 = text + "," + string.Join(",", Owned(text)) + "," + Supported;
			if (!(text2 == published))
			{
				Player localPlayer = PhotonNetwork.LocalPlayer;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add((object)"den.relics.skills.v2", (object)text2);
				if (localPlayer.SetCustomProperties(val, (Hashtable)null, (WebFlags)null))
				{
					published = text2;
				}
			}
		}

		private PhotonView View(Component c)
		{
			if ((Object)(object)c == (Object)null)
			{
				return null;
			}
			return c.GetComponent<PhotonView>() ?? c.GetComponentInParent<PhotonView>() ?? c.GetComponentInChildren<PhotonView>();
		}

		private bool PlayerProfile(PlayerAvatar a, out int[] owned, out int supported, out int actor)
		{
			owned = new int[6];
			supported = 0;
			actor = 0;
			string text = Id(a);
			if (!ValidId(text))
			{
				return false;
			}
			if (text == LocalId())
			{
				owned = Owned(text);
				supported = Supported;
				return true;
			}
			if (!PhotonNetwork.InRoom)
			{
				return false;
			}
			PhotonView val = View((Component)(object)a);
			if ((Object)(object)val == (Object)null || val.Owner == null)
			{
				return false;
			}
			actor = val.OwnerActorNr;
			if (!((Dictionary<object, object>)(object)val.Owner.CustomProperties).TryGetValue((object)"den.relics.skills.v2", out object value) || !(value is string text2))
			{
				return false;
			}
			string[] array = text2.Split(',');
			if (array.Length != 8 || array[0] != text || !int.TryParse(array[7], out supported) || supported < 0 || supported >= 64)
			{
				return false;
			}
			for (int i = 0; i < 6; i++)
			{
				if (!int.TryParse(array[i + 1], out owned[i]) || owned[i] < 0 || owned[i] > 1000)
				{
					return false;
				}
			}
			return true;
		}

		private int Available(int[] levels, int supported)
		{
			int num = supported & Supported;
			for (int i = 0; i < 6; i++)
			{
				if (levels[i] >= 1000)
				{
					num &= ~(1 << i);
				}
			}
			return num;
		}

		private bool InTruck(ValuableObject v)
		{
			if ((Object)(object)v == (Object)null)
			{
				return false;
			}
			RoomVolumeCheck val = ((Component)v).GetComponent<RoomVolumeCheck>() ?? ((Component)v).GetComponentInChildren<RoomVolumeCheck>(true) ?? ((Component)v).GetComponentInParent<RoomVolumeCheck>();
			bool flag = default(bool);
			int num;
			if ((Object)(object)val != (Object)null)
			{
				object value = truckField.GetValue(val);
				if (value is bool)
				{
					flag = (bool)value;
					num = 1;
				}
				else
				{
					num = 0;
				}
			}
			else
			{
				num = 0;
			}
			return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
		}

		private void ChooseRelic()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Expected O, but got Unknown
			//IL_00d4: Expected O, but got Unknown
			Scene activeScene = SceneManager.GetActiveScene();
			int num = SceneHandle.op_Implicit(((Scene)(ref activeScene)).handle);
			if (rolledScene == num)
			{
				return;
			}
			rolledScene = num;
			if (Random.Range(0, 100) >= Mathf.Clamp(chance.Value, 0, 100))
			{
				return;
			}
			ValuableObject[] array = (from v in Object.FindObjectsByType<ValuableObject>((FindObjectsSortMode)0)
				where (Object)(object)v != (Object)null && ((Component)v).gameObject.activeInHierarchy && ((Object)(object)((Component)v).GetComponent<RoomVolumeCheck>() != (Object)null || (Object)(object)((Component)v).GetComponentInChildren<RoomVolumeCheck>(true) != (Object)null || (Object)(object)((Component)v).GetComponentInParent<RoomVolumeCheck>() != (Object)null) && !InTruck(v) && (!PhotonNetwork.InRoom || ((Object)(object)View((Component)(object)v) != (Object)null && View((Component)(object)v).ViewID > 0))
				select v).ToArray();
			if (array.Length == 0)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"No suitable relic candidates");
				return;
			}
			relic = array[Random.Range(0, array.Length)];
			viewId = (PhotonNetwork.InRoom ? View((Component)(object)relic).ViewID : 0);
			if (PhotonNetwork.InRoom)
			{
				Room currentRoom = PhotonNetwork.CurrentRoom;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add((object)"den.relics.object.v2", (object)viewId);
				currentRoom.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
			}
			Notice("A relic is hidden in this stage!", 12f);
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Relic selected: " + ((Object)relic).name + " view=" + viewId));
		}

		private static void BeforeChange(bool _completedLevel, bool _levelFailed)
		{
			try
			{
				if ((Object)(object)self != (Object)null && _completedLevel && !_levelFailed)
				{
					self.ResolveRelic();
				}
			}
			catch (Exception ex)
			{
				Plugin plugin = self;
				if (plugin != null)
				{
					((BaseUnityPlugin)plugin).Logger.LogError((object)ex);
				}
			}
		}

		private void ResolveRelic()
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: 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_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0214: Expected O, but got Unknown
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			if (!CanHost || !Stage || (Object)(object)relic == (Object)null || !InTruck(relic))
			{
				return;
			}
			Scene activeScene = SceneManager.GetActiveScene();
			int num = SceneHandle.op_Implicit(((Scene)(ref activeScene)).handle);
			if (rewardedScene == num)
			{
				return;
			}
			rewardedScene = num;
			List<Tuple<PlayerAvatar, int, int>> list = new List<Tuple<PlayerAvatar, int, int>>();
			HashSet<string> hashSet = new HashSet<string>();
			foreach (PlayerAvatar item in SemiFunc.PlayerGetAll())
			{
				string text = Id(item);
				if (ValidId(text) && hashSet.Add(text) && PlayerProfile(item, out var owned, out var supported, out var actor))
				{
					int num2 = Available(owned, supported);
					if (num2 != 0)
					{
						list.Add(Tuple.Create<PlayerAvatar, int, int>(item, num2, actor));
					}
				}
			}
			PlayerAvatar instance = PlayerAvatar.instance;
			if ((Object)(object)instance != (Object)null && hashSet.Add(LocalId()) && PlayerProfile(instance, out var owned2, out var supported2, out var actor2))
			{
				int num3 = Available(owned2, supported2);
				if (num3 != 0)
				{
					list.Add(Tuple.Create<PlayerAvatar, int, int>(instance, num3, actor2));
				}
			}
			if (list.Count == 0)
			{
				Result("Relic recovered - no eligible player");
				return;
			}
			Tuple<PlayerAvatar, int, int> winner = list[Random.Range(0, list.Count)];
			int[] array = (from i in Enumerable.Range(0, 6)
				where (winner.Item2 & (1 << i)) != 0
				select i).ToArray();
			int num4 = array[Random.Range(0, array.Length)];
			string text2 = Id(winner.Item1);
			string text3 = Guid.NewGuid().ToString("N");
			if (text2 == LocalId())
			{
				if (!Unlock(num4, text3))
				{
					return;
				}
			}
			else
			{
				if (!PhotonNetwork.InRoom || winner.Item3 <= 0)
				{
					return;
				}
				object[] obj = new object[4] { "den.relics.award.v2", text2, num4, text3 };
				RaiseEventOptions val = new RaiseEventOptions();
				val.TargetActors = new int[1] { winner.Item3 };
				if (!PhotonNetwork.RaiseEvent((byte)185, (object)obj, val, SendOptions.SendReliable))
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)"Relic award could not be sent");
					return;
				}
			}
			string text4 = SemiFunc.PlayerGetName(winner.Item1);
			Result("RELIC RECOVERED: " + text4 + " gained " + names[num4] + " +1");
		}

		private bool Unlock(int skill, string receipt)
		{
			string id = LocalId();
			if (!ValidId(id) || skill < 0 || skill >= 6 || (Supported & (1 << skill)) == 0 || !Guid.TryParseExact(receipt, "N", out var _))
			{
				return false;
			}
			Profile profile = GetProfile(id);
			if (profile.Receipts.Contains(receipt) || profile.Levels[skill] >= 1000)
			{
				return false;
			}
			Profile profile2 = new Profile
			{
				Levels = (int[])profile.Levels.Clone(),
				Receipts = new List<string>(profile.Receipts)
			};
			profile2.Levels[skill]++;
			profile2.Receipts.Insert(0, receipt);
			if (profile2.Receipts.Count > 256)
			{
				profile2.Receipts.RemoveAt(profile2.Receipts.Count - 1);
			}
			if (!Save(id, profile2))
			{
				return false;
			}
			Publish();
			Notice("PERMANENT SKILL: " + names[skill] + " Lv." + profile2.Levels[skill], 15f);
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Relic upgraded: " + names[skill] + " Lv." + profile2.Levels[skill]));
			return true;
		}

		private void OnEvent(EventData e)
		{
			if (e.Code != 185 || !ready || blocked || !active.Value || !PhotonNetwork.InRoom || PhotonNetwork.MasterClient == null || e.Sender != PhotonNetwork.MasterClient.ActorNumber || !(e.CustomData is object[] array) || array.Length != 4 || !object.Equals(array[0], "den.relics.award.v2") || !(array[1] is string text) || !(text == LocalId()) || !(array[2] is int skill) || !(array[3] is string receipt))
			{
				return;
			}
			try
			{
				Unlock(skill, receipt);
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)ex);
			}
		}

		private void Result(string text)
		{
			//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_0051: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			//IL_0069: Expected O, but got Unknown
			Notice(text, 15f);
			((BaseUnityPlugin)this).Logger.LogInfo((object)text);
			if (PhotonNetwork.InRoom)
			{
				Room currentRoom = PhotonNetwork.CurrentRoom;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add((object)"den.relics.result.v2", (object)(Guid.NewGuid().ToString("N") + "|" + text));
				((Dictionary<object, object>)val).Add((object)"den.relics.object.v2", (object)0);
				currentRoom.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
			}
		}

		private void Notice(string text, float seconds)
		{
			notice = text;
			noticeUntil = Time.unscaledTime + seconds;
		}

		private IDictionary<string, int> Dict(int i)
		{
			if ((Object)(object)StatsManager.instance == (Object)null || dictFields[i] == null)
			{
				return null;
			}
			if (AccessTools.Field(typeof(StatsManager), "dictionaryOfDictionaries")?.GetValue(StatsManager.instance) is IDictionary dictionary && dictionary.Contains(fields[i]) && dictionary[fields[i]] is IDictionary<string, int> result)
			{
				return result;
			}
			return dictFields[i].GetValue(StatsManager.instance) as IDictionary<string, int>;
		}

		private void Apply(string id, int[] levels)
		{
			if (!CanHost || (Object)(object)PunManager.instance == (Object)null || !ValidId(id))
			{
				return;
			}
			for (int i = 0; i < 6; i++)
			{
				if (levels[i] <= 0 || (Supported & (1 << i)) == 0)
				{
					continue;
				}
				IDictionary<string, int> dictionary = Dict(i);
				if (dictionary == null)
				{
					continue;
				}
				if (!dictionary.TryGetValue(id, out var value))
				{
					if (!SemiFunc.LevelGenDone())
					{
						continue;
					}
					value = (dictionary[id] = 0);
				}
				string key = id + ":" + i;
				if (!applied.TryGetValue(key, out var value2) || value2.Dict != dictionary)
				{
					Dictionary<string, Overlay> dictionary2 = applied;
					Overlay obj = new Overlay
					{
						Dict = dictionary,
						Id = id
					};
					value2 = obj;
					dictionary2[key] = obj;
				}
				if (value < value2.Count)
				{
					blocked = true;
					((BaseUnityPlugin)this).Logger.LogWarning((object)"Relic overlay mismatch; suspended");
					break;
				}
				int num2 = Math.Min(20, levels[i] - value2.Count);
				for (int j = 0; j < num2; j++)
				{
					int num3 = dictionary[id];
					MethodInfo methodInfo = upMethods[i];
					value2.Count++;
					try
					{
						methodInfo.Invoke(PunManager.instance, (methodInfo.GetParameters().Length != 2) ? new object[1] { id } : new object[2] { id, 1 });
					}
					catch (Exception ex)
					{
						if (dictionary[id] == num3)
						{
							value2.Count--;
						}
						blocked = true;
						((BaseUnityPlugin)this).Logger.LogError((object)ex);
						return;
					}
					if (dictionary[id] != num3 + 1)
					{
						value2.Count--;
						blocked = true;
						((BaseUnityPlugin)this).Logger.LogWarning((object)"Unexpected relic upgrade delta");
						return;
					}
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Applied relic " + names[i] + " permanent=" + value2.Count + " total=" + dictionary[id]));
				}
			}
		}

		private void RefreshLocal()
		{
			string text = LocalId();
			if (!ValidId(text) || (Object)(object)PunManager.instance == (Object)null || (Object)(object)PlayerAvatar.instance == (Object)null)
			{
				return;
			}
			int[] array = Owned(text);
			for (int i = 0; i < 6; i++)
			{
				if (array[i] > 0 && (Supported & (1 << i)) != 0)
				{
					IDictionary<string, int> dictionary = Dict(i);
					if (dictionary != null && dictionary.TryGetValue(text, out var value) && value >= array[i] && live[i] != value)
					{
						liveMethods[i].Invoke(PunManager.instance, new object[2] { text, value });
						live[i] = value;
					}
				}
			}
		}

		private static void BeforeSave(ref StripState __state)
		{
			__state = self?.Strip(reset: false);
		}

		private static void BeforeReset(ref StripState __state)
		{
			__state = self?.Strip(reset: true);
		}

		private StripState Strip(bool reset)
		{
			StripState stripState = new StripState
			{
				Reset = reset
			};
			if (!ready || !Host || saving)
			{
				return stripState;
			}
			saving = true;
			stripState.Own = true;
			foreach (Overlay value2 in applied.Values)
			{
				if (value2.Count > 0 && value2.Dict.TryGetValue(value2.Id, out var value) && value >= value2.Count)
				{
					value2.Dict[value2.Id] = value - value2.Count;
					stripState.Values.Add(Tuple.Create(value2, value));
				}
			}
			return stripState;
		}

		private static Exception AfterStrip(Exception __exception, StripState __state)
		{
			if ((Object)(object)self == (Object)null || __state == null || !__state.Own)
			{
				return __exception;
			}
			try
			{
				if (__state.Reset && __exception == null)
				{
					self.applied.Clear();
					Array.Fill(self.live, -1);
				}
				else
				{
					foreach (Tuple<Overlay, int> value2 in __state.Values)
					{
						if (value2.Item1.Dict.TryGetValue(value2.Item1.Id, out var value) && value == value2.Item2 - value2.Item1.Count)
						{
							value2.Item1.Dict[value2.Item1.Id] = value2.Item2;
						}
						else
						{
							self.blocked = true;
						}
					}
				}
			}
			finally
			{
				self.saving = false;
			}
			return __exception;
		}

		private void Update()
		{
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Expected O, but got Unknown
			//IL_00ec: Expected O, but got Unknown
			if (!ready)
			{
				return;
			}
			if (Input.GetKeyDown((KeyCode)286))
			{
				show = !show;
			}
			string text = (PhotonNetwork.InRoom ? PhotonNetwork.CurrentRoom.Name : "");
			if (text != room || hadRoom != PhotonNetwork.InRoom)
			{
				room = text;
				hadRoom = PhotonNetwork.InRoom;
				published = "";
				lastResult = "";
				master = ((PhotonNetwork.InRoom && PhotonNetwork.MasterClient != null) ? PhotonNetwork.MasterClient.ActorNumber : 0);
				if (PhotonNetwork.InRoom && PhotonNetwork.IsMasterClient && !blocked)
				{
					Room currentRoom = PhotonNetwork.CurrentRoom;
					Hashtable val = new Hashtable();
					((Dictionary<object, object>)val).Add((object)"den.relics.object.v2", (object)0);
					((Dictionary<object, object>)val).Add((object)"den.relics.result.v2", (object)"");
					currentRoom.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
				}
			}
			if (PhotonNetwork.InRoom && PhotonNetwork.MasterClient != null && PhotonNetwork.MasterClient.ActorNumber != master)
			{
				blocked = true;
			}
			if (Time.unscaledTime < tick)
			{
				return;
			}
			tick = Time.unscaledTime + 1f;
			if (blocked || !active.Value)
			{
				ClearGlow();
				return;
			}
			try
			{
				Publish();
				if (PhotonNetwork.InRoom && ((Dictionary<object, object>)(object)((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties).TryGetValue((object)"den.relics.result.v2", out object value) && value is string text2 && text2 != lastResult)
				{
					lastResult = text2;
					int num = text2.IndexOf('|');
					if (num >= 0)
					{
						Notice(text2.Substring(num + 1), 15f);
					}
				}
				if (!Stage && (!((Object)(object)RunManager.instance != (Object)null) || (!SemiFunc.RunIsShop() && !SemiFunc.RunIsLobby())))
				{
					ClearGlow();
					return;
				}
				if (CanHost)
				{
					if (Stage && SemiFunc.LevelGenDone())
					{
						if (genAt < 0f)
						{
							genAt = Time.unscaledTime;
						}
						if (Time.unscaledTime - genAt >= 3f)
						{
							ChooseRelic();
						}
					}
					string text3 = LocalId();
					if (ValidId(text3) && (Object)(object)PlayerAvatar.instance != (Object)null)
					{
						Apply(text3, Owned(text3));
					}
					foreach (PlayerAvatar item in SemiFunc.PlayerGetAll())
					{
						string text4 = Id(item);
						if (ValidId(text4) && text4 != text3 && PlayerProfile(item, out var owned, out var _, out var _))
						{
							Apply(text4, owned);
						}
					}
				}
				RefreshLocal();
				UpdateGlow();
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)ex);
			}
		}

		private void OnGUI()
		{
			//IL_004d: 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_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_037c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0395: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0408: Unknown result type (might be due to invalid IL or missing references)
			//IL_045d: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_021b: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_022a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_0289: Unknown result type (might be due to invalid IL or missing references)
			//IL_029f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
			if (!ready || !active.Value || (Object)(object)RunManager.instance == (Object)null)
			{
				return;
			}
			if (Time.unscaledTime < noticeUntil)
			{
				GUI.Box(new Rect((float)((Screen.width - 500) / 2), 45f, 500f, 40f), notice);
			}
			if (Stage || SemiFunc.RunIsShop() || SemiFunc.RunIsLobby() || SemiFunc.RunIsLobbyMenu())
			{
				GUI.Box(new Rect(18f, 208f, 300f, 30f), "F5: Relic Skill List");
			}
			if (show)
			{
				GUI.Box(new Rect(18f, 240f, 300f, 210f), "REPO RELICS / F5");
				int[] array = Owned(LocalId());
				for (int i = 0; i < 6; i++)
				{
					GUI.Label(new Rect(28f, (float)(266 + i * 29), 280f, 26f), "Lv." + array[i] + " " + names[i]);
				}
			}
			if (!Stage || blocked)
			{
				return;
			}
			ValuableObject val = MarkedRelic();
			Camera main = Camera.main;
			if ((Object)(object)val == (Object)null || (Object)(object)main == (Object)null || InTruck(val) || !TryBounds(val, out var b))
			{
				return;
			}
			float num = Vector3.Distance(((Component)main).transform.position, ((Bounds)(ref b)).center);
			if (num > 12f)
			{
				return;
			}
			Vector3 min = ((Bounds)(ref b)).min;
			Vector3 max = ((Bounds)(ref b)).max;
			float num2 = float.PositiveInfinity;
			float num3 = float.NegativeInfinity;
			float num4 = float.PositiveInfinity;
			float num5 = float.NegativeInfinity;
			Vector3 val2 = default(Vector3);
			Vector3 val5 = default(Vector3);
			for (int j = 0; j < 8; j++)
			{
				((Vector3)(ref val2))..ctor(((j & 1) == 0) ? min.x : max.x, ((j & 2) == 0) ? min.y : max.y, ((j & 4) == 0) ? min.z : max.z);
				Vector3 val3 = main.WorldToViewportPoint(val2);
				Rect val4 = DisplayViewport(main);
				((Vector3)(ref val5))..ctor(((Rect)(ref val4)).x + val3.x * ((Rect)(ref val4)).width, ((Rect)(ref val4)).y + val3.y * ((Rect)(ref val4)).height, val3.z);
				if (val5.z <= 0f)
				{
					return;
				}
				num2 = Mathf.Min(num2, val5.x);
				num3 = Mathf.Max(num3, val5.x);
				num4 = Mathf.Min(num4, (float)Screen.height - val5.y);
				num5 = Mathf.Max(num5, (float)Screen.height - val5.y);
			}
			if (!(num3 < 0f) && !(num2 > (float)Screen.width) && !(num5 < 0f) && !(num4 > (float)Screen.height))
			{
				float num6 = Mathf.Clamp(num2 - 5f, 0f, (float)Screen.width);
				float num7 = Mathf.Clamp(num4 - 5f, 0f, (float)Screen.height);
				float num8 = Mathf.Max(8f, Mathf.Clamp(num3 + 5f, 0f, (float)Screen.width) - num6);
				float num9 = Mathf.Max(8f, Mathf.Clamp(num5 + 5f, 0f, (float)Screen.height) - num7);
				Color color = GUI.color;
				GUI.color = new Color(1f, 0.78f, 0.12f, 1f);
				Texture2D whiteTexture = Texture2D.whiteTexture;
				GUI.DrawTexture(new Rect(num6, num7, num8, 3f), (Texture)(object)whiteTexture);
				GUI.DrawTexture(new Rect(num6, num7 + num9 - 3f, num8, 3f), (Texture)(object)whiteTexture);
				GUI.DrawTexture(new Rect(num6, num7, 3f, num9), (Texture)(object)whiteTexture);
				GUI.DrawTexture(new Rect(num6 + num8 - 3f, num7, 3f, num9), (Texture)(object)whiteTexture);
				GUI.Box(new Rect(Mathf.Clamp(num6 + num8 / 2f - 82f, 0f, (float)Mathf.Max(0, Screen.width - 164)), Mathf.Max(0f, num7 - 34f), 164f, 30f), "RELIC  " + num.ToString("0.0") + "m");
				GUI.color = color;
			}
		}

		private static Rect DisplayViewport(Camera cam)
		{
			//IL_0023: 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)
			RenderTexture targetTexture = cam.targetTexture;
			if ((Object)(object)targetTexture == (Object)null || ((Texture)targetTexture).width <= 0 || ((Texture)targetTexture).height <= 0)
			{
				return cam.pixelRect;
			}
			float num = (float)((Texture)targetTexture).width / (float)((Texture)targetTexture).height;
			float num2 = Screen.width;
			float num3 = Screen.height;
			if (num2 / num3 > num)
			{
				num2 = num3 * num;
			}
			else
			{
				num3 = num2 / num;
			}
			return new Rect(((float)Screen.width - num2) * 0.5f, ((float)Screen.height - num3) * 0.5f, num2, num3);
		}

		private ValuableObject MarkedRelic()
		{
			if (!Stage || blocked)
			{
				return null;
			}
			if (!PhotonNetwork.InRoom)
			{
				return relic;
			}
			if (!((Dictionary<object, object>)(object)((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties).TryGetValue((object)"den.relics.object.v2", out object value) || !(value is int num) || num <= 0)
			{
				return null;
			}
			PhotonView val = PhotonView.Find(num);
			object obj;
			if (!((Object)(object)val == (Object)null))
			{
				obj = ((Component)val).GetComponent<ValuableObject>();
				if (obj == null)
				{
					obj = ((Component)val).GetComponentInChildren<ValuableObject>();
					if (obj == null)
					{
						return ((Component)val).GetComponentInParent<ValuableObject>();
					}
				}
			}
			else
			{
				obj = null;
			}
			return (ValuableObject)obj;
		}

		private bool TryBounds(ValuableObject target, out Bounds b)
		{
			//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_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: 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_006d: 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_0062: Unknown result type (might be due to invalid IL or missing references)
			b = new Bounds(((Component)target).transform.position, Vector3.one * 0.5f);
			Renderer[] componentsInChildren = ((Component)target).GetComponentsInChildren<Renderer>(false);
			bool flag = false;
			Renderer[] array = componentsInChildren;
			foreach (Renderer val in array)
			{
				if (!((Object)(object)val == (Object)null) && val.enabled && (val is MeshRenderer || val is SkinnedMeshRenderer))
				{
					if (!flag)
					{
						b = val.bounds;
						flag = true;
					}
					else
					{
						((Bounds)(ref b)).Encapsulate(val.bounds);
					}
				}
			}
			return true;
		}

		private void ClearGlow()
		{
			if ((Object)(object)glow != (Object)null)
			{
				Object.Destroy((Object)(object)glow);
			}
			glow = null;
			glowTarget = null;
		}

		private void UpdateGlow()
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_00b5: 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)
			ValuableObject val = MarkedRelic();
			if ((Object)(object)val == (Object)null || InTruck(val))
			{
				ClearGlow();
			}
			else if (!((Object)(object)glowTarget == (Object)(object)val) || !((Object)(object)glow != (Object)null))
			{
				ClearGlow();
				glowTarget = val;
				glow = new GameObject("RepoRelics_LocalGoldGlow");
				glow.transform.SetParent(((Component)val).transform, false);
				if (TryBounds(val, out var b))
				{
					glow.transform.position = ((Bounds)(ref b)).center;
				}
				Light obj = glow.AddComponent<Light>();
				obj.type = (LightType)2;
				obj.color = new Color(1f, 0.72f, 0.12f);
				obj.range = 3.5f;
				obj.intensity = 2f;
			}
		}
	}
}