Decompiled source of Blyssheim v0.4.35

plugins/Blyssheim/Blyssheim.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using Blyssheim.Building;
using Blyssheim.Dev;
using Blyssheim.Pets;
using Blyssheim.Warden;
using Blyssheim.Watch;
using Blyssheim.World;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using TMPro;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;

[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("Blyssheim")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.4.35.0")]
[assembly: AssemblyInformationalVersion("0.4.35+4688e3d8d93ef4727083733ddf9bf4f757b20df4")]
[assembly: AssemblyProduct("Blyssheim")]
[assembly: AssemblyTitle("Blyssheim")]
[assembly: AssemblyVersion("0.4.35.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 Blyssheim
{
	[BepInPlugin("overzealyss.blyssheim", "Blyssheim", "0.4.35")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "overzealyss.blyssheim";

		public const string Name = "Blyssheim";

		public const string Version = "0.4.35";

		internal static ManualLogSource Log;

		internal static Plugin Instance;

		private void Awake()
		{
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			Settings.Bind(((BaseUnityPlugin)this).Config);
			Diagnostics.Bind(((BaseUnityPlugin)this).Config);
			BodyExport.Bind(((BaseUnityPlugin)this).Config);
			ComfortDump.Bind(((BaseUnityPlugin)this).Config);
			ZdoCensus.Bind(((BaseUnityPlugin)this).Config);
			ZdoCensus.BindAround(((BaseUnityPlugin)this).Config);
			CommandInbox.Bind(((BaseUnityPlugin)this).Config);
			WardenItems.Init(((BaseUnityPlugin)this).Config);
			WardenNet.Init(((BaseUnityPlugin)this).Config);
			PetFetch.Bind(((BaseUnityPlugin)this).Config);
			SansasBone.Bind(((BaseUnityPlugin)this).Config);
			TameDeer.Bind(((BaseUnityPlugin)this).Config);
			StayHome.Bind(((BaseUnityPlugin)this).Config);
			LandRefresh.Bind(((BaseUnityPlugin)this).Config);
			LessSmoke.Bind(((BaseUnityPlugin)this).Config);
			FenceFix.Bind(((BaseUnityPlugin)this).Config);
			StillLeaves.Bind(((BaseUnityPlugin)this).Config);
			NoShake.Bind(((BaseUnityPlugin)this).Config);
			Records.RegisterCommands();
			VersionGate.Bind(((BaseUnityPlugin)this).Config);
			BastionWard.Bind(((BaseUnityPlugin)this).Config);
			SharedBed.Bind(((BaseUnityPlugin)this).Config);
			BlackDye.Bind(((BaseUnityPlugin)this).Config);
			TravelingTraders.Bind(((BaseUnityPlugin)this).Config);
			Perf.Bind(((BaseUnityPlugin)this).Config);
			ArmorShots.Register();
			Capybara.Bind(((BaseUnityPlugin)this).Config);
			CatNap.Bind(((BaseUnityPlugin)this).Config);
			TombLock.Bind(((BaseUnityPlugin)this).Config);
			new Harmony("overzealyss.blyssheim").PatchAll();
			Log.LogInfo((object)"Blyssheim 0.4.35 loaded.");
		}

		private void Update()
		{
			WardenNet.Tick();
			WardenSearch.Tick();
			InspectionNotice.Pulse();
			OfficeBoard.Pulse();
			SansasBone.Tick();
			LandRefresh.Tick();
			ZdoCensus.Tick();
			CommandInbox.Tick();
			Records.Tick();
			Perf.Tick();
		}
	}
	[HarmonyPatch(typeof(Game), "Start")]
	internal static class Rpc
	{
		public const string Snapshot = "Blyssheim_Snapshot";

		public const string Alert = "Blyssheim_Alert";

		private static void Postfix()
		{
			ZRoutedRpc.instance.Register<ZPackage>("Blyssheim_Snapshot", (Action<long, ZPackage>)ServerWatch.OnSnapshot);
			ZRoutedRpc.instance.Register<string>("Blyssheim_Alert", (Action<long, string>)ClientWatch.OnAlert);
			WardenNet.Register();
			if (Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsDedicated())
			{
				((MonoBehaviour)Plugin.Instance).StartCoroutine(ReportContrabandSoon());
			}
		}

		private static IEnumerator ReportContrabandSoon()
		{
			yield return (object)new WaitForSeconds(15f);
			Contraband.LogSummary();
		}

		public static long ServerPeerId()
		{
			return (long)AccessTools.Method(typeof(ZRoutedRpc), "GetServerPeerID", (Type[])null, (Type[])null).Invoke(ZRoutedRpc.instance, null);
		}
	}
}
namespace Blyssheim.World
{
	internal static class FenceFix
	{
		public static ConfigEntry<bool> Enabled;

		private static readonly Dictionary<Mesh, Mesh> Copies = new Dictionary<Mesh, Mesh>();

		public static void Bind(ConfigFile cfg)
		{
			Enabled = cfg.Bind<bool>("Fixes", "ReadableColliders", true, "Give building pieces with unreadable collision models (Valheim's Stone Fence) a readable copy, so creatures path around them and the navmesh errors stop.");
			PrefabManager.OnPrefabsRegistered += Apply;
		}

		private static void Apply()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Invalid comparison between Unknown and I4
			if (!Enabled.Value || (int)SystemInfo.graphicsDeviceType == 4 || !Object.op_Implicit((Object)(object)ZNetScene.instance))
			{
				return;
			}
			int num = 0;
			int num2 = 0;
			foreach (GameObject item in ZNetScene.instance.m_prefabs.Where((GameObject p) => Object.op_Implicit((Object)(object)p) && Object.op_Implicit((Object)(object)p.GetComponent<Piece>())))
			{
				bool flag = false;
				MeshCollider[] componentsInChildren = item.GetComponentsInChildren<MeshCollider>(true);
				foreach (MeshCollider val in componentsInChildren)
				{
					Mesh sharedMesh = val.sharedMesh;
					if (Object.op_Implicit((Object)(object)sharedMesh) && !sharedMesh.isReadable)
					{
						Mesh val2 = ReadableCopy(sharedMesh);
						if (!Object.op_Implicit((Object)(object)val2))
						{
							Plugin.Log.LogWarning((object)("FenceFix: could not copy " + ((Object)sharedMesh).name + " on " + ((Object)item).name));
							continue;
						}
						val.sharedMesh = val2;
						flag = true;
						num2++;
					}
				}
				if (flag)
				{
					num++;
				}
			}
			if (num2 > 0)
			{
				Plugin.Log.LogInfo((object)$"FenceFix: gave {num} piece(s) readable collision models ({num2} colliders).");
			}
		}

		private static Mesh ReadableCopy(Mesh src)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: 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_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Invalid comparison between Unknown and I4
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Expected O, but got Unknown
			if (Copies.TryGetValue(src, out var value))
			{
				return value;
			}
			try
			{
				int vertexAttributeStream = src.GetVertexAttributeStream((VertexAttribute)0);
				int vertexAttributeOffset = src.GetVertexAttributeOffset((VertexAttribute)0);
				if (vertexAttributeStream < 0 || (int)src.GetVertexAttributeFormat((VertexAttribute)0) != 0)
				{
					return null;
				}
				int vertexCount = src.vertexCount;
				GraphicsBuffer vertexBuffer = src.GetVertexBuffer(vertexAttributeStream);
				Vector3[] array2;
				try
				{
					byte[] array = new byte[vertexBuffer.count * vertexBuffer.stride];
					vertexBuffer.GetData((Array)array);
					array2 = (Vector3[])(object)new Vector3[vertexCount];
					for (int i = 0; i < vertexCount; i++)
					{
						int num = i * vertexBuffer.stride + vertexAttributeOffset;
						array2[i] = new Vector3(BitConverter.ToSingle(array, num), BitConverter.ToSingle(array, num + 4), BitConverter.ToSingle(array, num + 8));
					}
				}
				finally
				{
					((IDisposable)vertexBuffer)?.Dispose();
				}
				List<int> list = new List<int>();
				GraphicsBuffer indexBuffer = src.GetIndexBuffer();
				try
				{
					bool flag = (int)src.indexFormat == 1;
					byte[] array3 = new byte[indexBuffer.count * indexBuffer.stride];
					indexBuffer.GetData((Array)array3);
					for (int j = 0; j < src.subMeshCount; j++)
					{
						SubMeshDescriptor subMesh = src.GetSubMesh(j);
						if ((int)((SubMeshDescriptor)(ref subMesh)).topology == 0)
						{
							for (int k = 0; k < ((SubMeshDescriptor)(ref subMesh)).indexCount; k++)
							{
								int startIndex = (((SubMeshDescriptor)(ref subMesh)).indexStart + k) * (flag ? 4 : 2);
								int num2 = (flag ? BitConverter.ToInt32(array3, startIndex) : BitConverter.ToUInt16(array3, startIndex));
								list.Add(num2 + ((SubMeshDescriptor)(ref subMesh)).baseVertex);
							}
						}
					}
				}
				finally
				{
					((IDisposable)indexBuffer)?.Dispose();
				}
				Mesh val = new Mesh
				{
					name = ((Object)src).name + "_readable",
					indexFormat = (IndexFormat)(vertexCount > 65535)
				};
				val.vertices = array2;
				val.triangles = list.ToArray();
				val.RecalculateBounds();
				Copies[src] = val;
				return val;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("FenceFix: " + ex.Message));
				return null;
			}
		}
	}
	internal static class LandRefresh
	{
		private class RefreshCommand : ConsoleCommand
		{
			public override string Name => "blyssrefresh";

			public override string Help => "Admins: regrow ore and rebuild crypts away from bases and recently visited areas. Shows what it would do; add 'start' to do it.";

			public override void Run(string[] args)
			{
				WardenNet.AskServer("refresh", args.Any((string a) => a.Equals("start", StringComparison.OrdinalIgnoreCase)) ? 1f : 0f);
			}
		}

		public static ConfigEntry<float> SkipVisitedDays;

		public static ConfigEntry<string> Dungeons;

		public static ConfigEntry<string> OreIds;

		public static ConfigEntry<string> Announcement;

		private const float ZoneSize = 64f;

		private const int VisitRadius = 2;

		private static readonly Dictionary<Vector2s, DateTime> Visits = new Dictionary<Vector2s, DateTime>();

		private static float _nextSample;

		private static float _nextSave;

		private static bool _loaded;

		private static bool _dirty;

		private static bool _patched;

		private static readonly Regex OreDrop = new Regex("Ore|Scrap|Obsidian", RegexOptions.IgnoreCase);

		private static string VisitsFile => Path.Combine(ServerWatch.DataDir, "visits.txt");

		public static void Bind(ConfigFile cfg)
		{
			SkipVisitedDays = cfg.Bind<float>("Land refresh", "SkipVisitedDays", 3f, "Server: areas a player has been in during the last this many (real) days are not refreshed.");
			Dungeons = cfg.Bind<string>("Land refresh", "Dungeons", "Crypt2,Crypt3,Crypt4,SunkenCrypt4,TrollCave02,MountainCave02,Mistlands_DvergrTownEntrance1,Mistlands_DvergrTownEntrance2", "Server: the locations rebuilt by the refresh (Upgrade World location ids; unknown ids are ignored).");
			OreIds = cfg.Bind<string>("Land refresh", "OreIds", "auto", "Server: what regrows. 'auto' = every rock in the world's vegetation that drops ore, scrap or obsidian; or a list of ids.");
			Announcement = cfg.Bind<string>("Land refresh", "Announcement", "The land stirs. Ore and crypts are returning to the wilds...", "Server: shown to everyone online when a refresh starts.");
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new RefreshCommand());
		}

		public static void Tick()
		{
			//IL_00a6: 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_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || (Object)(object)ZoneSystem.instance == (Object)null)
			{
				return;
			}
			if (!_loaded)
			{
				Load();
				Plugin.Log.LogInfo((object)("Land refresh: ore that would regrow: " + string.Join(", ", OreList())));
			}
			if (Time.time >= _nextSample)
			{
				_nextSample = Time.time + 20f;
				DateTime utcNow = DateTime.UtcNow;
				foreach (ZNetPeer peer in ZNet.instance.GetPeers())
				{
					for (int i = -2; i <= 2; i++)
					{
						for (int j = -2; j <= 2; j++)
						{
							Visits[ZoneSystem.GetZone(peer.m_refPos + new Vector3((float)i * 64f, 0f, (float)j * 64f))] = utcNow;
							_dirty = true;
						}
					}
				}
			}
			if (_dirty && Time.time >= _nextSave)
			{
				_nextSave = Time.time + 300f;
				Save();
			}
		}

		private static void Load()
		{
			//IL_0077: 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)
			_loaded = true;
			try
			{
				if (!File.Exists(VisitsFile))
				{
					return;
				}
				string[] array = File.ReadAllLines(VisitsFile);
				for (int i = 0; i < array.Length; i++)
				{
					string[] array2 = array[i].Split(',');
					if (array2.Length == 3 && int.TryParse(array2[0], out var result) && int.TryParse(array2[1], out var result2) && long.TryParse(array2[2], out var result3))
					{
						Visits[ZoneSystem.GetZone(new Vector3((float)result * 64f, 0f, (float)result2 * 64f))] = new DateTime(result3, DateTimeKind.Utc);
					}
				}
				Plugin.Log.LogInfo((object)$"Land refresh: {Visits.Count} visited zones remembered.");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Land refresh: could not read visits.txt: " + ex.Message));
			}
		}

		private static void Save()
		{
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			_dirty = false;
			try
			{
				DateTime cutoff = DateTime.UtcNow.AddDays(0f - Math.Max(30f, SkipVisitedDays.Value * 2f));
				foreach (Vector2s item in (from kv in Visits
					where kv.Value < cutoff
					select kv.Key).ToList())
				{
					Visits.Remove(item);
				}
				File.WriteAllLines(VisitsFile, Visits.Select((KeyValuePair<Vector2s, DateTime> kv) => $"{kv.Key.x},{kv.Key.y},{kv.Value.Ticks}"));
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Land refresh: could not write visits.txt: " + ex.Message));
			}
		}

		private static HashSet<Vector2s> RecentZones()
		{
			DateTime cutoff = DateTime.UtcNow.AddDays(0f - SkipVisitedDays.Value);
			return new HashSet<Vector2s>(from kv in Visits
				where kv.Value >= cutoff
				select kv.Key);
		}

		public static string Run(bool start)
		{
			Type type = AccessTools.TypeByName("UpgradeWorld.PlayerBaseFilterer");
			if (type == null || (Object)(object)Console.instance == (Object)null)
			{
				return "The land refresh needs Upgrade World installed on the server.";
			}
			if (!_patched && !Patch(type))
			{
				return "Could not hook into Upgrade World (has it changed?). Nothing was refreshed.";
			}
			Tick();
			Save();
			List<string> list = OreList();
			List<string> list2 = (from s in Dungeons.Value.Split(',')
				select s.Trim() into s
				where s.Length > 0
				select s).ToList();
			int count = RecentZones().Count;
			string text = "Land refresh" + (start ? " started" : " (preview)") + ":\n- Ore regrows: " + ((list.Count > 0) ? string.Join(", ", list) : "nothing found") + "\n- Rebuilt: " + string.Join(", ", list2) + "\n" + $"- Left alone: areas near player bases, and {count} zones visited in the last {SkipVisitedDays.Value:0.#} days.";
			if (!start)
			{
				return text + "\nType blyssrefresh start to do it. Back up the world first.";
			}
			Terminal.m_cheat = true;
			if (list.Count > 0)
			{
				((Terminal)Console.instance).TryRunCommand("vegetation_reset " + string.Join(",", list) + " start", false, false);
			}
			if (list2.Count > 0)
			{
				((Terminal)Console.instance).TryRunCommand("locations_reset " + string.Join(",", list2) + " start", false, false);
			}
			Plugin.Log.LogInfo((object)("Land refresh: " + text.Replace("\n", " ")));
			if (!string.IsNullOrEmpty(Announcement.Value))
			{
				MessageHud instance = MessageHud.instance;
				if (instance != null)
				{
					instance.MessageAll((MessageType)2, Announcement.Value);
				}
			}
			return text + "\nUpgrade World is working through it now; the server log shows when each part is done.";
		}

		private static List<string> OreList()
		{
			if (!OreIds.Value.Trim().Equals("auto", StringComparison.OrdinalIgnoreCase))
			{
				return (from s in OreIds.Value.Split(',')
					select s.Trim() into s
					where s.Length > 0
					select s).ToList();
			}
			List<string> list = new List<string>();
			foreach (GameObject item in (from v in ZoneSystem.instance.m_vegetation
				where Object.op_Implicit((Object)(object)v.m_prefab)
				select v.m_prefab).Distinct())
			{
				string text = OreIn(item, 0);
				if (text != null)
				{
					Plugin.Log.LogInfo((object)("Land refresh: " + ((Object)item).name + " gives " + text));
				}
				if (text != null)
				{
					list.Add(((Object)item).name);
				}
			}
			return (from n in list.Distinct()
				orderby n
				select n).ToList();
		}

		private static string OreIn(GameObject p, int depth)
		{
			if (!Object.op_Implicit((Object)(object)p) || depth > 2)
			{
				return null;
			}
			string text = Drops(p.GetComponentInChildren<MineRock5>(true)?.m_dropItems) ?? Drops(p.GetComponentInChildren<MineRock>(true)?.m_dropItems) ?? Drops(p.GetComponentInChildren<DropOnDestroyed>(true)?.m_dropWhenDestroyed);
			if (text != null)
			{
				return text;
			}
			Destructible componentInChildren = p.GetComponentInChildren<Destructible>(true);
			if (!Object.op_Implicit((Object)(object)componentInChildren))
			{
				return null;
			}
			return OreIn(componentInChildren.m_spawnWhenDestroyed, depth + 1);
			static string Drops(DropTable t)
			{
				return (from d in t?.m_drops?.Where((DropData d) => Object.op_Implicit((Object)(object)d.m_item) && OreDrop.IsMatch(((Object)d.m_item).name))
					select ((Object)d.m_item).name).FirstOrDefault();
			}
		}

		private static bool Patch(Type filterer)
		{
			//IL_0030: 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_0054: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(filterer, "CalculateExcluded", new Type[1] { typeof(int) }, (Type[])null);
			if (methodInfo == null)
			{
				return false;
			}
			new Harmony("overzealyss.blyssheim.landrefresh").Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(LandRefresh), "AddRecent", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			_patched = true;
			return true;
		}

		private static void AddRecent(HashSet<Vector2s> __result)
		{
			__result?.UnionWith(RecentZones());
		}
	}
	internal static class LessSmoke
	{
		[HarmonyPatch(typeof(Smoke), "Awake")]
		private static class ShortLived
		{
			private static void Postfix(Smoke __instance)
			{
				if (!_logged)
				{
					_logged = true;
					Plugin.Log.LogInfo((object)($"Smoke: normal puff lasts {__instance.m_ttl:0.#} s (fade {__instance.m_fadetime:0.#} s); " + string.Format("now x{0}, limit {1}", Lifetime.Value, (MaxPuffs.Value > 0) ? MaxPuffs.Value.ToString() : "unchanged")));
				}
				float num = Mathf.Clamp(Lifetime.Value, 0.05f, 1f);
				__instance.m_ttl *= num;
				__instance.m_fadetime = Mathf.Min(__instance.m_fadetime, Mathf.Max(0.5f, __instance.m_ttl * 0.5f));
			}
		}

		[HarmonyPatch(typeof(SmokeSpawner), "Awake")]
		private static class FewerPuffs
		{
			private static void Postfix(SmokeSpawner __instance)
			{
				__instance.m_interval *= Mathf.Clamp(Interval.Value, 1f, 5f);
			}
		}

		[HarmonyPatch(typeof(SmokeSpawner), "Spawn")]
		private static class AtMost
		{
			private static void Prefix()
			{
				if (MaxPuffs.Value <= 0)
				{
					return;
				}
				for (int i = 0; i < 4; i++)
				{
					if (Smoke.GetTotalSmoke() < MaxPuffs.Value)
					{
						break;
					}
					Smoke.FadeOldest();
				}
			}
		}

		public static ConfigEntry<float> Lifetime;

		public static ConfigEntry<float> Interval;

		public static ConfigEntry<int> MaxPuffs;

		private static bool _logged;

		public static void Bind(ConfigFile cfg)
		{
			Lifetime = cfg.Bind<float>("Smoke", "Lifetime", 0.2f, "How long a smoke puff lasts, as a share of the game's normal time (1 = normal, 0.2 = a fifth).");
			MaxPuffs = cfg.Bind<int>("Smoke", "MaxPuffs", 40, "Most smoke puffs in the world at once (0 = the game's own limit).");
			Interval = cfg.Bind<float>("Smoke", "Interval", 1.5f, "Time between puffs, as a multiple of the normal time (1 = normal, 2 = half as many).");
		}
	}
	internal static class NoShake
	{
		[HarmonyPatch(typeof(GameCamera), "AddShake")]
		private static class Shake
		{
			private static bool Prefix()
			{
				if (Enabled != null)
				{
					return !Enabled.Value;
				}
				return true;
			}
		}

		public static ConfigEntry<bool> Enabled;

		public static void Bind(ConfigFile cfg)
		{
			Enabled = cfg.Bind<bool>("Accessibility", "NoCameraShake", false, "Stop every camera shake in the world (boss summons, slams, explosions, quakes). Valheim's own Camera shake setting only covers being hurt: switch that off too. Your own game only; works at once.");
		}
	}
	internal static class StillLeaves
	{
		public static ConfigEntry<bool> FallingLeaves;

		public static ConfigEntry<string> Trees;

		public static void Bind(ConfigFile cfg)
		{
			FallingLeaves = cfg.Bind<bool>("Trees", "FallingLeaves", false, "Leaves drifting down from beech trees all the time. Off saves a lot of frame rate in Meadows forests; leaves still fly when a tree is hit. Needs a restart.");
			Trees = cfg.Bind<string>("Trees", "LeafTrees", "", "Trees whose drifting leaves are switched off (start of the prefab name, comma separated, e.g. Beech,Oak). Empty = every tree.");
			PrefabManager.OnPrefabsRegistered += Apply;
		}

		private static void Apply()
		{
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			if (FallingLeaves.Value || !Object.op_Implicit((Object)(object)ZNetScene.instance))
			{
				return;
			}
			string[] array = (from s in Trees.Value.Split(',')
				select s.Trim() into s
				where s.Length > 0
				select s).ToArray();
			int num = 0;
			int num2 = 0;
			List<string> list = new List<string>();
			foreach (GameObject prefab in ZNetScene.instance.m_prefabs)
			{
				if (!Object.op_Implicit((Object)(object)prefab) || (array.Length != 0 && !array.Any((string n) => ((Object)prefab).name.StartsWith(n))) || !Object.op_Implicit((Object)(object)prefab.GetComponent<TreeBase>()))
				{
					continue;
				}
				bool flag = false;
				ParticleSystem[] componentsInChildren = prefab.GetComponentsInChildren<ParticleSystem>(true);
				foreach (ParticleSystem val in componentsInChildren)
				{
					GameObject gameObject = ((Component)val).gameObject;
					if ((Object)(object)gameObject != (Object)(object)prefab && gameObject.GetComponents<Component>().All((Component c) => c is Transform || c is ParticleSystem || c is ParticleSystemRenderer))
					{
						gameObject.SetActive(false);
					}
					else
					{
						MainModule main = val.main;
						((MainModule)(ref main)).playOnAwake = false;
						EmissionModule emission = val.emission;
						((EmissionModule)(ref emission)).enabled = false;
					}
					flag = true;
					num2++;
				}
				if (flag)
				{
					num++;
					list.Add(((Object)prefab).name);
				}
			}
			if (num2 > 0)
			{
				Plugin.Log.LogInfo((object)string.Format("Still leaves: switched off {0} leaf effects on {1} kinds of tree ({2}).", num2, num, string.Join(", ", list)));
			}
		}
	}
}
namespace Blyssheim.Watch
{
	internal static class ClientWatch
	{
		[HarmonyPatch(typeof(Player), "OnSpawned")]
		private static class SpawnPatch
		{
			private static void Postfix(Player __instance)
			{
				if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && _loop == null)
				{
					_loop = ((MonoBehaviour)Plugin.Instance).StartCoroutine(Loop());
				}
			}
		}

		[HarmonyPatch(typeof(Game), "Logout")]
		private static class LogoutPatch
		{
			private static void Prefix()
			{
				Send("leave");
			}
		}

		private static readonly PlayerStatType[] TrackedStats;

		private static Coroutine _loop;

		private static string _lastSent;

		private static bool OnDedicatedServer
		{
			get
			{
				if ((Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsServer())
				{
					return (Object)(object)Player.m_localPlayer != (Object)null;
				}
				return false;
			}
		}

		public unsafe static Snapshot Take(string kind)
		{
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			Game instance = Game.instance;
			PlayerProfile val = ((instance != null) ? instance.GetPlayerProfile() : null);
			if ((Object)(object)localPlayer == (Object)null || val == null)
			{
				return null;
			}
			Snapshot snapshot = new Snapshot
			{
				Kind = kind,
				PlayerId = val.GetPlayerID(),
				Character = val.GetName(),
				UsedCheats = val.m_usedCheats
			};
			PlayerStats[] array = val.m_playerStats ?? Array.Empty<PlayerStats>();
			foreach (PlayerStats val2 in array)
			{
				if (val2 != null)
				{
					if (val2.m_knownWorlds != null)
					{
						snapshot.KnownWorlds.AddRange(val2.m_knownWorlds.Keys);
					}
					if (val2.m_knownCommands != null)
					{
						snapshot.KnownCommands.AddRange(val2.m_knownCommands.Keys);
					}
				}
			}
			snapshot.KnownWorlds = snapshot.KnownWorlds.Distinct().ToList();
			snapshot.KnownCommands = snapshot.KnownCommands.Distinct().Where(IsCheatCommand).ToList();
			try
			{
				PlayerStatType[] trackedStats = TrackedStats;
				for (int i = 0; i < trackedStats.Length; i++)
				{
					PlayerStatType val3 = trackedStats[i];
					snapshot.Stats[((object)(*(PlayerStatType*)(&val3))/*cast due to .constrained prefix*/).ToString()] = val.GetStat(val3, (DifficultyRequirement)0);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Watch: stats unavailable (" + ex.GetType().Name + ")"));
			}
			foreach (ItemData allItem in ((Humanoid)localPlayer).GetInventory().GetAllItems())
			{
				snapshot.Items.Add(new ItemEntry
				{
					Name = (Object.op_Implicit((Object)(object)allItem.m_dropPrefab) ? ((Object)allItem.m_dropPrefab).name : allItem.m_shared.m_name),
					Stack = allItem.m_stack,
					Quality = allItem.m_quality,
					Cheated = allItem.m_cheated,
					Crafter = allItem.m_crafterName
				});
			}
			return snapshot;
		}

		private static bool IsCheatCommand(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				return false;
			}
			string text = name.Split(' ')[0].ToLowerInvariant();
			if (text == "devcommands")
			{
				return true;
			}
			if (!(AccessTools.Field(typeof(Terminal), "commands")?.GetValue(null) is IDictionary dictionary) || !dictionary.Contains(text))
			{
				return false;
			}
			object? obj = dictionary[text];
			return ((ConsoleCommand)(((obj is ConsoleCommand) ? obj : null)?)).IsCheat ?? false;
		}

		public static void Send(string kind, bool onlyIfChanged = false)
		{
			if (!OnDedicatedServer)
			{
				return;
			}
			Snapshot snapshot = Take(kind);
			if (snapshot != null)
			{
				string text = string.Join(";", from kv in snapshot.Totals()
					orderby kv.Key
					select kv.Key + "=" + kv.Value);
				if (!onlyIfChanged || !(text == _lastSent))
				{
					_lastSent = text;
					ZRoutedRpc.instance.InvokeRoutedRPC(Rpc.ServerPeerId(), "Blyssheim_Snapshot", new object[1] { snapshot.ToPackage() });
				}
			}
		}

		private static IEnumerator Loop()
		{
			yield return (object)new WaitForSeconds(3f);
			_lastSent = null;
			SafeSend("arrive");
			while ((Object)(object)Player.m_localPlayer != (Object)null)
			{
				yield return (object)new WaitForSeconds((float)Mathf.Max(5, Settings.CheckpointSeconds.Value));
				SafeSend("checkpoint", onlyIfChanged: true);
			}
			_loop = null;
		}

		private static void SafeSend(string kind, bool onlyIfChanged = false)
		{
			try
			{
				Send(kind, onlyIfChanged);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Watch: " + kind + " not sent: " + ex));
			}
		}

		public static void OnAlert(long sender, string text)
		{
			if (Object.op_Implicit((Object)(object)MessageHud.instance))
			{
				MessageHud.instance.ShowMessage((MessageType)2, "<color=#ff4040>CONTRABAND</color>\n" + text, 0, (Sprite)null, false, true);
			}
			if (Object.op_Implicit((Object)(object)Chat.instance))
			{
				((Terminal)Chat.instance).AddString("<color=#ff4040>Blyssheim</color>", text, (Type)0, true);
			}
			Plugin.Log.LogWarning((object)("Contraband alert: " + text));
			Alerts.Raise(text);
		}

		static ClientWatch()
		{
			PlayerStatType[] array = new PlayerStatType[16];
			RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
			TrackedStats = (PlayerStatType[])(object)array;
		}
	}
	public static class Alerts
	{
		public static event Action<string> OnContraband;

		internal static void Raise(string text)
		{
			Alerts.OnContraband?.Invoke(text);
		}
	}
	internal static class Contraband
	{
		public static readonly (string Key, string Boss)[] Bosses = new(string, string)[7]
		{
			("defeated_eikthyr", "Eikthyr"),
			("defeated_gdking", "The Elder"),
			("defeated_bonemass", "Bonemass"),
			("defeated_dragon", "Moder"),
			("defeated_goblinking", "Yagluth"),
			("defeated_queen", "The Queen"),
			("defeated_fader", "Fader")
		};

		private static readonly Dictionary<string, string[]> Defaults = new Dictionary<string, string[]>
		{
			["defeated_eikthyr"] = new string[1] { "HardAntler" },
			["defeated_gdking"] = new string[4] { "Iron", "IronScrap", "IronOre", "CryptKey" },
			["defeated_bonemass"] = new string[3] { "Silver", "SilverOre", "Wishbone" },
			["defeated_dragon"] = new string[3] { "DragonTear", "BlackMetal", "LinenThread" },
			["defeated_goblinking"] = new string[4] { "YagluthDrop", "Wisp", "Eitr", "BlackCore" },
			["defeated_queen"] = new string[5] { "QueenDrop", "FlametalNew", "FlametalOreNew", "Flametal", "FlametalOre" },
			["defeated_fader"] = new string[1] { "FaderDrop" }
		};

		private static Dictionary<string, int> _tier;

		private static string FilePath => Path.Combine(ServerWatch.DataDir, "contraband.json");

		private static Dictionary<string, string[]> LoadTable()
		{
			if (!File.Exists(FilePath))
			{
				File.WriteAllText(FilePath, JsonConvert.SerializeObject((object)Defaults, (Formatting)1));
			}
			try
			{
				return JsonConvert.DeserializeObject<Dictionary<string, string[]>>(File.ReadAllText(FilePath)) ?? Defaults;
			}
			catch
			{
				return Defaults;
			}
		}

		private static void Build()
		{
			_tier = new Dictionary<string, int>();
			Dictionary<string, string[]> dictionary = LoadTable();
			for (int i = 0; i < Bosses.Length; i++)
			{
				if (dictionary.TryGetValue(Bosses[i].Key, out var value))
				{
					string[] array = value;
					foreach (string key in array)
					{
						_tier[key] = i;
					}
				}
			}
			List<Recipe> list = (Object.op_Implicit((Object)(object)ObjectDB.instance) ? ObjectDB.instance.m_recipes.Where((Recipe r) => Object.op_Implicit((Object)(object)r) && Object.op_Implicit((Object)(object)r.m_item)).ToList() : new List<Recipe>());
			bool flag = true;
			int num = 0;
			while (flag && num < 20)
			{
				flag = false;
				foreach (Recipe item in list)
				{
					int num2 = -1;
					Requirement[] array2 = (Requirement[])(((object)item.m_resources) ?? ((object)new Requirement[0]));
					foreach (Requirement val in array2)
					{
						if (Object.op_Implicit((Object)(object)val?.m_resItem) && _tier.TryGetValue(((Object)((Component)val.m_resItem).gameObject).name, out var value2) && value2 > num2)
						{
							num2 = value2;
						}
					}
					if (num2 >= 0)
					{
						string name = ((Object)((Component)item.m_item).gameObject).name;
						if (!_tier.TryGetValue(name, out var value3) || num2 > value3)
						{
							_tier[name] = num2;
							flag = true;
						}
					}
				}
				num++;
			}
			Plugin.Log.LogInfo((object)$"Contraband table: {_tier.Count} gated items.");
		}

		public static string BossNeeded(string item)
		{
			if (_tier == null)
			{
				Build();
			}
			if (!_tier.TryGetValue(item, out var value))
			{
				return null;
			}
			ZoneSystem instance = ZoneSystem.instance;
			if ((Object)(object)instance != (Object)null && instance.GetGlobalKey(Bosses[value].Key))
			{
				return null;
			}
			return Bosses[value].Boss;
		}

		public static void Reset()
		{
			_tier = null;
		}

		public static void LogSummary()
		{
			if (_tier == null)
			{
				Build();
			}
			List<IGrouping<string, (string, string)>> list = (from i in _tier.Keys
				select (Item: i, Boss: BossNeeded(i)) into x
				where x.Boss != null
				group x by x.Boss).ToList();
			IEnumerable<string> values = from b in Bosses
				where Object.op_Implicit((Object)(object)ZoneSystem.instance) && ZoneSystem.instance.GetGlobalKey(b.Key)
				select b.Boss;
			Plugin.Log.LogInfo((object)("Contraband: bosses beaten: " + string.Join(", ", values) + ". " + $"{list.Sum((IGrouping<string, (string Item, string Boss)> g) => g.Count())} items are contraband right now."));
			foreach (IGrouping<string, (string, string)> item in list)
			{
				Plugin.Log.LogInfo((object)string.Format("  waits on {0} ({1}): {2}{3}", item.Key, item.Count(), string.Join(", ", (from x in item
					select x.Item into x
					orderby x
					select x).Take(25)), (item.Count() > 25) ? ", ..." : ""));
			}
		}
	}
	public class Offence
	{
		public DateTime When;

		public string Character;

		public string Kind;

		public string Text;

		public string By;
	}
	internal static class Records
	{
		private class RecordCommand : ConsoleCommand
		{
			public override string Name => "record";

			public override string Help => "Admins: someone's criminal record (record <name>), or everyone with one (record).";

			public override void Run(string[] args)
			{
				WardenNet.AskServer("record:" + string.Join(" ", args), 0f);
			}
		}

		private class BookCommand : ConsoleCommand
		{
			public override string Name => "book";

			public override string Help => "Admins: add to someone's criminal record. book <name> <offence>";

			public override void Run(string[] args)
			{
				WardenNet.AskServer("book:" + string.Join(" ", args), 0f);
			}
		}

		private class ExpungeCommand : ConsoleCommand
		{
			public override string Name => "expunge";

			public override string Help => "Admins: strike a line off someone's criminal record. expunge <name> [number] (no number = the latest)";

			public override void Run(string[] args)
			{
				WardenNet.AskServer("expunge:" + string.Join(" ", args), 0f);
			}
		}

		private class UnbookCommand : ConsoleCommand
		{
			public override string Name => "unbook";

			public override string Help => "Admins: remove the last hand-booked line from someone's record. unbook <name>";

			public override void Run(string[] args)
			{
				WardenNet.AskServer("unbook:" + string.Join(" ", args), 0f);
			}
		}

		private static readonly JsonSerializerSettings Json = new JsonSerializerSettings
		{
			Formatting = (Formatting)1
		};

		private static List<Offence> _all;

		private static readonly Regex Searched = new Regex("^(.+) was searched by the Realm Warden$");

		private static readonly Regex Seized = new Regex("^The Realm Warden seized (\\d+) (\\S+) from (.+)$");

		private static string PathFile => Path.Combine(ServerWatch.DataDir, "records.json");

		public static void RegisterCommands()
		{
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new RecordCommand());
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new BookCommand());
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new UnbookCommand());
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new ExpungeCommand());
		}

		public static void Load()
		{
			All();
		}

		public static void Tick()
		{
			if (_all == null && Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer())
			{
				Load();
			}
		}

		private static List<Offence> All()
		{
			if (_all != null)
			{
				return _all;
			}
			try
			{
				_all = (File.Exists(PathFile) ? JsonConvert.DeserializeObject<List<Offence>>(File.ReadAllText(PathFile)) : null);
			}
			catch
			{
				_all = null;
			}
			if (_all == null)
			{
				_all = new List<Offence>();
				Backfill();
				Save();
			}
			return _all;
		}

		private static void Save()
		{
			try
			{
				File.WriteAllText(PathFile, JsonConvert.SerializeObject((object)_all, Json));
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Records: could not save: " + ex.Message));
			}
		}

		private static void Backfill()
		{
			try
			{
				string path = Path.Combine(ServerWatch.DataDir, "events.json");
				if (!File.Exists(path))
				{
					return;
				}
				foreach (WatchEvent item in JsonConvert.DeserializeObject<List<WatchEvent>>(File.ReadAllText(path)) ?? new List<WatchEvent>())
				{
					FromEvent(item.When, item.Character, item.Kind, item.Text, save: false);
				}
				Plugin.Log.LogInfo((object)$"Records: started with {_all.Count} past offences from the Watch log.");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Records: backfill failed: " + ex.Message));
			}
		}

		public static void FromEvent(DateTime when, string character, string kind, string text, bool save = true)
		{
			if (kind == "catch")
			{
				List<string> list = (from s in (text ?? "").Split(';')
					select s.Trim() into s
					where s.Length > 0 && !s.StartsWith("also gained while away")
					select s).ToList();
				if (list.Count > 0)
				{
					Add(when, character, "caught", string.Join("; ", list), null, save);
				}
			}
			else
			{
				if (!(kind == "warden"))
				{
					return;
				}
				Match match;
				if ((match = Searched.Match(text ?? "")).Success)
				{
					Add(when, match.Groups[1].Value, "searched", "searched by the Realm Warden", null, save);
				}
				else
				{
					if (!(match = Seized.Match(text ?? "")).Success)
					{
						return;
					}
					string who = match.Groups[3].Value;
					string text2 = match.Groups[1].Value + " " + match.Groups[2].Value;
					Offence offence = _all.LastOrDefault((Offence o) => o.Kind == "seized" && o.Character == who && (when - o.When).TotalMinutes < 2.0);
					if (offence != null)
					{
						offence.Text = offence.Text + ", " + text2;
						if (save)
						{
							Save();
						}
					}
					else
					{
						Add(when, who, "seized", "seized: " + text2, null, save);
					}
				}
			}
		}

		public static void Add(DateTime when, string character, string kind, string text, string by, bool save = true)
		{
			if (!string.IsNullOrEmpty(character))
			{
				All().Add(new Offence
				{
					When = when,
					Character = character,
					Kind = kind,
					Text = text,
					By = by
				});
				if (save)
				{
					Save();
				}
			}
		}

		public static void Marked(string character, string word)
		{
			if (!string.IsNullOrEmpty(character) && !All().Any((Offence o) => o.Kind == "marked" && o.Character == character && (DateTime.Now - o.When).TotalMinutes < 1.0))
			{
				Add(DateTime.Now, character, "marked", "marked " + word + " with the billy club", null);
			}
		}

		private static List<string> Names()
		{
			return (from o in All()
				select o.Character).Distinct().ToList();
		}

		private static string Find(string query)
		{
			string q = (query ?? "").Trim();
			if (q.Length == 0)
			{
				return null;
			}
			List<string> source = Names();
			return source.FirstOrDefault((string n) => n.Equals(q, StringComparison.OrdinalIgnoreCase)) ?? source.FirstOrDefault((string n) => n.StartsWith(q, StringComparison.OrdinalIgnoreCase)) ?? source.FirstOrDefault((string n) => n.IndexOf(q, StringComparison.OrdinalIgnoreCase) >= 0);
		}

		public static string Report(string query)
		{
			if (string.IsNullOrWhiteSpace(query))
			{
				List<string> list = (from o in All()
					group o by o.Character into g
					orderby g.Count() descending, g.Key
					select $"  {g.Key}: {g.Count()} on record, last {g.Max((Offence o) => o.When):MMM d}").ToList();
				if (list.Count != 0)
				{
					return "Criminal records (record <name> for the full sheet):\n" + string.Join("\n", list);
				}
				return "Criminal records: nobody has a record. A law-abiding realm.";
			}
			string who = Find(query);
			if (who == null)
			{
				return "No criminal record for '" + query.Trim() + "'. Clean as a whistle (or never caught).";
			}
			List<Offence> list2 = (from o in All()
				where o.Character == who
				orderby o.When
				select o).ToList();
			List<string> list3 = new List<string> { $"<color=#ff4040>CRIMINAL RECORD</color>: {who} ({list2.Count} on record)" };
			for (int num = 0; num < list2.Count; num++)
			{
				Offence offence = list2[num];
				list3.Add(string.Format("  {0}. {1:MMM d HH:mm}  {2}  {3}{4}", num + 1, offence.When, offence.Kind.ToUpperInvariant(), offence.Text, (offence.By != null) ? (" (booked by " + offence.By + ")") : ""));
			}
			list3.Add("  (expunge " + who + " <number> strikes a line)");
			return string.Join("\n", list3);
		}

		public static string Book(string args, string by)
		{
			string[] array = (args ?? "").Trim().Split(new char[1] { ' ' }, 2);
			if (array.Length < 2 || array[1].Trim().Length == 0)
			{
				return "Usage: book <name> <offence>   e.g. book pikk stole the community carrots";
			}
			string text = Find(array[0]) ?? Online(array[0]) ?? array[0];
			Add(DateTime.Now, text, "booked", array[1].Trim(), by);
			return "Booked " + text + ": " + array[1].Trim();
		}

		public static string Unbook(string query)
		{
			string who = Find(query);
			Offence offence = ((who == null) ? null : All().LastOrDefault((Offence o) => o.Character == who && o.Kind == "booked"));
			if (offence == null)
			{
				return "Nothing hand-booked for '" + query + "' to remove.";
			}
			_all.Remove(offence);
			Save();
			return "Removed from " + who + "'s record: " + offence.Text;
		}

		public static string Expunge(string args, string by)
		{
			string[] array = (args ?? "").Trim().Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
			if (array.Length == 0)
			{
				return "Usage: expunge <name> [number]   (numbers are on the record sheet; no number = the latest line)";
			}
			int result = 0;
			IEnumerable<string> enumerable2;
			if (array.Length <= 1 || !int.TryParse(array[^1], out result))
			{
				IEnumerable<string> enumerable = array;
				enumerable2 = enumerable;
			}
			else
			{
				enumerable2 = array.Take(array.Length - 1);
			}
			IEnumerable<string> values = enumerable2;
			string who = Find(string.Join(" ", values));
			if (who == null)
			{
				return "No criminal record for '" + string.Join(" ", values) + "'.";
			}
			List<Offence> list = (from o in All()
				where o.Character == who
				orderby o.When
				select o).ToList();
			if (result == 0)
			{
				result = list.Count;
			}
			if (result < 1 || result > list.Count)
			{
				return $"{who} has {list.Count} line(s) on record; pick 1 to {list.Count}.";
			}
			Offence offence = list[result - 1];
			_all.Remove(offence);
			Save();
			try
			{
				File.AppendAllText(Path.Combine(ServerWatch.DataDir, "watch.log"), $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}  {by} expunged from {who}'s record: {offence.Kind} {offence.When:MMM d HH:mm} {offence.Text}{Environment.NewLine}");
			}
			catch
			{
			}
			return $"Expunged from {who}'s record: {offence.When:MMM d HH:mm} {offence.Kind} {offence.Text}";
		}

		private static string Online(string query)
		{
			ZNet instance = ZNet.instance;
			if (instance == null)
			{
				return null;
			}
			return (from p in instance.GetPeers()
				select p.m_playerName).FirstOrDefault((string n) => n?.StartsWith(query, StringComparison.OrdinalIgnoreCase) ?? false);
		}
	}
	public class PlayerRecord
	{
		public string Host;

		public string Character;

		public long PlayerId;

		public DateTime LastSeen;

		public bool UsedCheats;

		public List<string> KnownWorlds = new List<string>();

		public List<string> KnownCommands = new List<string>();

		public Dictionary<string, float> Stats = new Dictionary<string, float>();

		public Snapshot Last;

		public DateTime? OnlineSince;

		public double SecondsOnServer;

		public int Sessions;

		public DateTime? FirstSeen;
	}
	public class WatchEvent
	{
		public DateTime When;

		public string Character;

		public string Kind;

		public string Text;
	}
	public class Incident
	{
		public DateTime When;

		public string Character;

		public string Host;

		public List<string> Charges = new List<string>();
	}
	internal static class ServerWatch
	{
		private static readonly Dictionary<long, string> OpenByPeer = new Dictionary<long, string>();

		private static readonly JsonSerializerSettings Json = new JsonSerializerSettings
		{
			Formatting = (Formatting)1
		};

		public static string DataDir
		{
			get
			{
				string text = Path.Combine(Paths.ConfigPath, "Blyssheim");
				Directory.CreateDirectory(text);
				return text;
			}
		}

		private static string PlayersDir
		{
			get
			{
				string text = Path.Combine(DataDir, "players");
				Directory.CreateDirectory(text);
				return text;
			}
		}

		private static string IncidentsPath => Path.Combine(DataDir, "incidents.json");

		private static string LogPath => Path.Combine(DataDir, "watch.log");

		private static string SessionsPath => Path.Combine(DataDir, "sessions.csv");

		private static string EventsPath => Path.Combine(DataDir, "events.json");

		public static void OnSnapshot(long sender, ZPackage pkg)
		{
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				return;
			}
			try
			{
				Snapshot snapshot = Snapshot.FromPackage(pkg);
				ZNetPeer peer = ZNet.instance.GetPeer(sender);
				if (snapshot != null && peer != null)
				{
					Handle(peer, snapshot);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Watch: " + ex));
			}
		}

		private static string FileFor(string host, long id)
		{
			return Path.Combine(PlayersDir, string.Concat(string.Concat((host + "_" + id).Select((char c) => (!Path.GetInvalidFileNameChars().Contains(c)) ? c : '_')), ".json"));
		}

		public static IEnumerable<PlayerRecord> AllRecords()
		{
			return from r in Directory.GetFiles(PlayersDir, "*.json").Select(delegate(string f)
				{
					try
					{
						return JsonConvert.DeserializeObject<PlayerRecord>(File.ReadAllText(f));
					}
					catch
					{
						return (PlayerRecord)null;
					}
				})
				where r != null
				select r;
		}

		public static List<Incident> Incidents()
		{
			try
			{
				return File.Exists(IncidentsPath) ? (JsonConvert.DeserializeObject<List<Incident>>(File.ReadAllText(IncidentsPath)) ?? new List<Incident>()) : new List<Incident>();
			}
			catch
			{
				return new List<Incident>();
			}
		}

		private static void Handle(ZNetPeer peer, Snapshot snap)
		{
			string hostName = peer.m_socket.GetHostName();
			string text = FileFor(hostName, snap.PlayerId);
			PlayerRecord playerRecord = null;
			if (File.Exists(text))
			{
				try
				{
					playerRecord = JsonConvert.DeserializeObject<PlayerRecord>(File.ReadAllText(text));
				}
				catch
				{
				}
			}
			DateTime? dateTime = playerRecord?.LastSeen;
			if (snap.Kind == "arrive")
			{
				string text2 = Changes(playerRecord, snap);
				if (text2 != null)
				{
					AddEvent(snap.Character, "changes", text2);
				}
				List<string> list = Judge(playerRecord, snap);
				if (list.Count > 0 && Settings.IsExempt(snap.Character, hostName))
				{
					Note(snap.Character + " (" + hostName + ") is exempt; not charged with: " + string.Join("; ", list));
					list.Clear();
				}
				if (list.Count > 0)
				{
					AddEvent(snap.Character, "catch", string.Join("; ", list));
				}
				bool caught = list.Any((string x) => !x.StartsWith("also gained") && !x.StartsWith("visited other worlds"));
				Sansa.OnArrival(peer, caught);
				Note($"{snap.Character} ({hostName}) arrived carrying {snap.Items.Sum((ItemEntry i) => i.Stack)} items" + ((list.Count > 0) ? (" - CHARGES: " + string.Join("; ", list)) : " - clean"));
				if (list.Count > 0)
				{
					Report(new Incident
					{
						When = DateTime.Now,
						Character = snap.Character,
						Host = hostName,
						Charges = list
					});
				}
			}
			playerRecord = playerRecord ?? new PlayerRecord();
			if (snap.Kind == "arrive")
			{
				if (playerRecord.OnlineSince.HasValue)
				{
					CloseSession(playerRecord, playerRecord.LastSeen, "no leave recorded");
				}
				playerRecord.OnlineSince = DateTime.Now;
				playerRecord.Sessions++;
				playerRecord.FirstSeen = playerRecord.FirstSeen ?? DateTime.Now;
				OpenByPeer[peer.m_uid] = text;
			}
			else if (snap.Kind == "leave" && playerRecord.OnlineSince.HasValue)
			{
				CloseSession(playerRecord, DateTime.Now, "left");
				OpenByPeer.Remove(peer.m_uid);
			}
			playerRecord.Host = hostName;
			playerRecord.Character = snap.Character;
			playerRecord.PlayerId = snap.PlayerId;
			playerRecord.LastSeen = DateTime.Now;
			playerRecord.UsedCheats = snap.UsedCheats;
			playerRecord.KnownWorlds = snap.KnownWorlds;
			playerRecord.KnownCommands = snap.KnownCommands;
			playerRecord.Stats = snap.Stats;
			playerRecord.Last = snap;
			File.WriteAllText(text, JsonConvert.SerializeObject((object)playerRecord, Json));
			if (snap.Kind == "arrive" && ZNet.instance.IsAdmin(hostName))
			{
				SendDigest(peer.m_uid, dateTime ?? DateTime.Now.AddDays(-1.0), "since you were last here");
			}
		}

		private static string Changes(PlayerRecord rec, Snapshot now)
		{
			if (rec?.Last == null)
			{
				return null;
			}
			Dictionary<string, int> before = rec.Last.Totals();
			Dictionary<string, int> after = now.Totals();
			int value;
			List<(string, int)> list = (from kv in after
				select (Key: kv.Key, d: kv.Value - (before.TryGetValue(kv.Key, out value) ? value : 0)) into x
				where x.d > 0
				orderby x.d descending
				select x).ToList();
			List<(string, int)> list2 = (from kv in before
				select (Key: kv.Key, d: kv.Value - (after.TryGetValue(kv.Key, out value) ? value : 0)) into x
				where x.d > 0
				orderby x.d descending
				select x).ToList();
			if (list.Count == 0 && list2.Count == 0)
			{
				return null;
			}
			TimeSpan timeSpan = DateTime.Now - rec.LastSeen;
			string text = ((timeSpan.TotalHours >= 1.0) ? $"{(int)timeSpan.TotalHours}h {timeSpan.Minutes:00}m" : $"{timeSpan.Minutes}m");
			return "away " + text + "; " + ((list.Count > 0) ? ("came back with " + List(list, "+")) : "") + ((list.Count > 0 && list2.Count > 0) ? "; " : "") + ((list2.Count > 0) ? ("came back without " + List(list2, "-")) : "");
			static string List(List<(string Key, int d)> l, string sign)
			{
				return string.Join(", ", from x in l.Take(12)
					select $"{sign}{x.d} {x.Key}") + ((l.Count > 12) ? $" (+{l.Count - 12} more)" : "");
			}
		}

		private static List<WatchEvent> Events()
		{
			if (!File.Exists(EventsPath) && File.Exists(IncidentsPath))
			{
				try
				{
					File.WriteAllText(EventsPath, JsonConvert.SerializeObject((object)(from i in Incidents()
						select new WatchEvent
						{
							When = i.When,
							Character = i.Character,
							Kind = "catch",
							Text = string.Join("; ", i.Charges)
						}).ToList(), Json));
				}
				catch
				{
				}
			}
			try
			{
				return File.Exists(EventsPath) ? (JsonConvert.DeserializeObject<List<WatchEvent>>(File.ReadAllText(EventsPath)) ?? new List<WatchEvent>()) : new List<WatchEvent>();
			}
			catch
			{
				return new List<WatchEvent>();
			}
		}

		public static void AddEvent(string character, string kind, string text)
		{
			Records.Load();
			List<WatchEvent> list = Events();
			list.Add(new WatchEvent
			{
				When = DateTime.Now,
				Character = character,
				Kind = kind,
				Text = text
			});
			if (list.Count > 1000)
			{
				list = list.Skip(list.Count - 1000).ToList();
			}
			Records.FromEvent(DateTime.Now, character, kind, text);
			try
			{
				File.WriteAllText(EventsPath, JsonConvert.SerializeObject((object)list, Json));
			}
			catch
			{
			}
		}

		public static void SendDigest(long peerId, DateTime since, string label)
		{
			List<WatchEvent> list = (from e in Events()
				where e.When > since
				orderby (!(e.Kind == "catch")) ? ((e.Kind == "warden") ? 1 : 2) : 0, e.When
				select e).ToList();
			List<string> list2 = new List<string> { (list.Count == 0) ? ("Watch: nothing to report " + label + ".") : string.Format("Watch: {0} report{1} {2}:", list.Count, (list.Count == 1) ? "" : "s", label) };
			foreach (WatchEvent item in list.Take(40))
			{
				string text = ((item.Kind == "catch") ? "<color=#ff4040>CAUGHT</color>" : ((item.Kind == "warden") ? "<color=#ffcc66>WARDEN</color>" : "<color=#9fd0ff>CHANGED</color>"));
				list2.Add($"{item.When:MMM d HH:mm}  {text}  {item.Character}: {item.Text}");
			}
			if (list.Count > 40)
			{
				list2.Add($"... and {list.Count - 40} more (watchlog <hours> on the server log: BepInEx/config/Blyssheim/events.json)");
			}
			ZRoutedRpc.instance.InvokeRoutedRPC(peerId, "Blyssheim_Digest", new object[2]
			{
				list.Count,
				string.Join("\n", list2)
			});
		}

		private static void CloseSession(PlayerRecord rec, DateTime end, string how)
		{
			DateTime value = rec.OnlineSince.Value;
			double num = Math.Max(0.0, (end - value).TotalSeconds);
			rec.SecondsOnServer += num;
			rec.OnlineSince = null;
			try
			{
				if (!File.Exists(SessionsPath))
				{
					File.WriteAllText(SessionsPath, "character,account,start,end,minutes,how" + Environment.NewLine);
				}
				File.AppendAllText(SessionsPath, $"{rec.Character},{rec.Host},{value:yyyy-MM-dd HH:mm:ss},{end:yyyy-MM-dd HH:mm:ss},{num / 60.0:0.0},{how}{Environment.NewLine}");
			}
			catch
			{
			}
		}

		public static void OnDisconnect(ZNetPeer peer)
		{
			if (peer == null || !OpenByPeer.TryGetValue(peer.m_uid, out var value))
			{
				return;
			}
			OpenByPeer.Remove(peer.m_uid);
			try
			{
				PlayerRecord playerRecord = JsonConvert.DeserializeObject<PlayerRecord>(File.ReadAllText(value));
				if (playerRecord != null && playerRecord.OnlineSince.HasValue)
				{
					CloseSession(playerRecord, DateTime.Now, "disconnected");
					File.WriteAllText(value, JsonConvert.SerializeObject((object)playerRecord, Json));
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Watch session: " + ex));
			}
		}

		public static string PlaytimeReport()
		{
			List<(string, double, int, bool, float, DateTime?)> list = (from x in AllRecords().Select(delegate(PlayerRecord r)
				{
					double item = r.SecondsOnServer + (r.OnlineSince.HasValue ? (DateTime.Now - r.OnlineSince.Value).TotalSeconds : 0.0);
					float item2 = 0f;
					if (r.Stats != null)
					{
						r.Stats.TryGetValue("TimeInBase", out var value);
						r.Stats.TryGetValue("TimeOutOfBase", out var value2);
						item2 = value + value2;
					}
					return (Character: r.Character, s: item, Sessions: r.Sessions, Online: r.OnlineSince.HasValue, Life: item2, FirstSeen: r.FirstSeen);
				})
				orderby x.s descending
				select x).ToList();
			if (list.Count == 0)
			{
				return "No time recorded yet.";
			}
			return "Time on Blyss (since Blyssheim 0.4.3):\n" + string.Join("\n", list.Select<(string, double, int, bool, float, DateTime?), string>(((string Character, double s, int Sessions, bool Online, float Life, DateTime? FirstSeen) x) => string.Format("{0}: {1} in {2} session{3}{4}", x.Character, Span(x.s), x.Sessions, (x.Sessions == 1) ? "" : "s", x.Online ? " (online now)" : "") + ((x.Life > 0f) ? ("; character total, all worlds: " + Span(x.Life)) : "")));
			static string Span(double s)
			{
				TimeSpan timeSpan = TimeSpan.FromSeconds(s);
				if (!(timeSpan.TotalHours >= 1.0))
				{
					return $"{timeSpan.Minutes}m";
				}
				return $"{(int)timeSpan.TotalHours}h {timeSpan.Minutes:00}m";
			}
		}

		private static List<string> Judge(PlayerRecord rec, Snapshot now)
		{
			List<string> list = new List<string>();
			bool flag = rec?.Last == null;
			Dictionary<string, int> before = (flag ? new Dictionary<string, int>() : rec.Last.Totals());
			Dictionary<string, int> source = now.Totals();
			int num = ((!flag) ? rec.Last.Items.Where((ItemEntry i) => i.Cheated).Sum((ItemEntry i) => i.Stack) : 0);
			List<string> list2 = (from i in now.Items
				where i.Cheated
				group i by i.Name into g
				select $"{g.Sum((ItemEntry i) => i.Stack)} {g.Key}").ToList();
			if (list2.Count > 0 && now.Items.Where((ItemEntry i) => i.Cheated).Sum((ItemEntry i) => i.Stack) > num)
			{
				list.Add("carrying items made with cheats: " + string.Join(", ", list2));
			}
			if (now.UsedCheats && (flag || !rec.UsedCheats))
			{
				list.Add("this character has used cheats");
			}
			List<string> list3 = now.KnownCommands.Except(flag ? new List<string>() : rec.KnownCommands).ToList();
			if (list3.Count > 0)
			{
				list.Add("console commands used: " + string.Join(", ", list3));
			}
			int value;
			List<string> list4 = (from kv in source
				select (Item: kv.Key, Gain: kv.Value - (before.TryGetValue(kv.Key, out value) ? value : 0), Boss: Contraband.BossNeeded(kv.Key)) into x
				where x.Gain > 0 && x.Boss != null
				select $"{x.Gain} {x.Item} (needs {x.Boss})").ToList();
			if (list4.Count > 0)
			{
				list.Add("contraband: " + string.Join(", ", list4));
			}
			if (!flag)
			{
				List<(string Item, int Gain)> list5 = (from kv in source
					select (Item: kv.Key, Gain: kv.Value - (before.TryGetValue(kv.Key, out value) ? value : 0)) into x
					where x.Gain > 0 && Contraband.BossNeeded(x.Item) == null
					select x).ToList();
				int big = Math.Max(1, Settings.BigGainStacks.Value);
				List<(string, int)> list6 = list5.Where(((string Item, int Gain) x) => x.Gain >= big * MaxStack(x.Item)).ToList();
				if (list6.Count > 0)
				{
					list.Add("came back with a big haul: " + string.Join(", ", list6.Select<(string, int), string>(((string Item, int Gain) x) => $"+{x.Gain} {x.Item}")));
				}
				List<(string, int)> list7 = list5.Except<(string, int)>(list6).ToList();
				if (list7.Count > 0 && (Settings.AlertOnAnyGain.Value || list.Count > 0))
				{
					list.Add("also gained while away: " + string.Join(", ", list7.Select<(string, int), string>(((string Item, int Gain) x) => $"+{x.Gain} {x.Item}")));
				}
				List<string> list8 = now.KnownWorlds.Except(rec.KnownWorlds).ToList();
				if (list8.Count > 0 && list.Count > 0)
				{
					list.Add("visited other worlds since last time: " + string.Join(", ", list8));
				}
			}
			return list;
		}

		private static int MaxStack(string item)
		{
			GameObject val = (Object.op_Implicit((Object)(object)ObjectDB.instance) ? ObjectDB.instance.GetItemPrefab(item) : null);
			ItemDrop val2 = (Object.op_Implicit((Object)(object)val) ? val.GetComponent<ItemDrop>() : null);
			if (!Object.op_Implicit((Object)(object)val2))
			{
				return 50;
			}
			return Math.Max(1, val2.m_itemData.m_shared.m_maxStackSize);
		}

		private static void Report(Incident inc)
		{
			List<Incident> list = Incidents();
			list.Add(inc);
			File.WriteAllText(IncidentsPath, JsonConvert.SerializeObject((object)list, Json));
			string text = inc.Character + ": " + string.Join("\n", inc.Charges);
			foreach (ZNetPeer connectedPeer in ZNet.instance.GetConnectedPeers())
			{
				if (ZNet.instance.IsAdmin(connectedPeer.m_socket.GetHostName()))
				{
					ZRoutedRpc.instance.InvokeRoutedRPC(connectedPeer.m_uid, "Blyssheim_Alert", new object[1] { text });
				}
			}
		}

		public static void Log(string line)
		{
			Note(line);
			AddEvent("Realm Warden", "warden", line);
		}

		private static void Note(string line)
		{
			Plugin.Log.LogInfo((object)("Watch: " + line));
			try
			{
				File.AppendAllText(LogPath, $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}  {line}{Environment.NewLine}");
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(ZNet), "Disconnect", new Type[] { typeof(ZNetPeer) })]
	internal static class SessionPatches
	{
		private static void Prefix(ZNetPeer peer)
		{
			if (Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer())
			{
				ServerWatch.OnDisconnect(peer);
			}
		}
	}
	internal static class Settings
	{
		public static ConfigEntry<int> CheckpointSeconds;

		public static ConfigEntry<int> BigGainStacks;

		public static ConfigEntry<bool> AlertOnAnyGain;

		public static ConfigEntry<string> Exempt;

		public static ConfigEntry<bool> ExemptAdmins;

		public static void Bind(ConfigFile cfg)
		{
			CheckpointSeconds = cfg.Bind<int>("Watch", "CheckpointSeconds", 20, "How often a player's game reports what they carry while playing, so a crash still leaves a recent record.");
			BigGainStacks = cfg.Bind<int>("Watch", "BigGainStacks", 2, "Server: coming back with this many more full stacks of one item than you left with counts as a charge.");
			AlertOnAnyGain = cfg.Bind<bool>("Watch", "AlertOnAnyGain", true, "Server: if true, any item gained while away is listed with the charges; if false, only gated, cheated or big gains are.");
			Exempt = cfg.Bind<string>("Watch", "Exempt", "Underzealyss", "Server: characters the Watch never charges (comma separated, any case): what it finds is only noted in watch.log, with no report, record line or Sansa chase. For testing.");
			ExemptAdmins = cfg.Bind<bool>("Watch", "ExemptAdmins", true, "Server: players on the server's admin list are never charged either (whatever character they play): only noted in watch.log, no report, record line or Sansa chase.");
		}

		public static bool IsExempt(string character)
		{
			if (!string.IsNullOrEmpty(character))
			{
				return Exempt.Value.Split(',').Any((string n) => n.Trim().Equals(character, StringComparison.OrdinalIgnoreCase));
			}
			return false;
		}

		public static bool IsExempt(string character, string host)
		{
			if (!IsExempt(character))
			{
				if (ExemptAdmins.Value && !string.IsNullOrEmpty(host) && Object.op_Implicit((Object)(object)ZNet.instance))
				{
					return ZNet.instance.IsAdmin(host);
				}
				return false;
			}
			return true;
		}
	}
	public class ItemEntry
	{
		public string Name;

		public int Stack;

		public int Quality;

		public bool Cheated;

		public string Crafter;
	}
	public class Snapshot
	{
		public const int Format = 1;

		public string Kind;

		public long PlayerId;

		public string Character;

		public bool UsedCheats;

		public List<string> KnownWorlds = new List<string>();

		public List<string> KnownCommands = new List<string>();

		public Dictionary<string, float> Stats = new Dictionary<string, float>();

		public List<ItemEntry> Items = new List<ItemEntry>();

		public Dictionary<string, int> Totals()
		{
			return (from i in Items
				group i by i.Name).ToDictionary((IGrouping<string, ItemEntry> g) => g.Key, (IGrouping<string, ItemEntry> g) => g.Sum((ItemEntry i) => i.Stack));
		}

		public ZPackage ToPackage()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			val.Write(1);
			val.Write(Kind ?? "");
			val.Write(PlayerId);
			val.Write(Character ?? "");
			val.Write(UsedCheats);
			WriteList(val, KnownWorlds);
			WriteList(val, KnownCommands);
			val.Write(Stats.Count);
			foreach (KeyValuePair<string, float> stat in Stats)
			{
				val.Write(stat.Key);
				val.Write(stat.Value);
			}
			val.Write(Items.Count);
			foreach (ItemEntry item in Items)
			{
				val.Write(item.Name ?? "");
				val.Write(item.Stack);
				val.Write(item.Quality);
				val.Write(item.Cheated);
				val.Write(item.Crafter ?? "");
			}
			return val;
		}

		public static Snapshot FromPackage(ZPackage p)
		{
			if (p.ReadInt() != 1)
			{
				return null;
			}
			Snapshot snapshot = new Snapshot
			{
				Kind = p.ReadString(),
				PlayerId = p.ReadLong(),
				Character = p.ReadString(),
				UsedCheats = p.ReadBool(),
				KnownWorlds = ReadList(p),
				KnownCommands = ReadList(p)
			};
			int num = p.ReadInt();
			for (int i = 0; i < num; i++)
			{
				snapshot.Stats[p.ReadString()] = p.ReadSingle();
			}
			num = p.ReadInt();
			for (int j = 0; j < num; j++)
			{
				snapshot.Items.Add(new ItemEntry
				{
					Name = p.ReadString(),
					Stack = p.ReadInt(),
					Quality = p.ReadInt(),
					Cheated = p.ReadBool(),
					Crafter = p.ReadString()
				});
			}
			return snapshot;
		}

		private static void WriteList(ZPackage p, List<string> list)
		{
			p.Write(list.Count);
			foreach (string item in list)
			{
				p.Write(item ?? "");
			}
		}

		private static List<string> ReadList(ZPackage p)
		{
			List<string> list = new List<string>();
			int num = p.ReadInt();
			for (int i = 0; i < num; i++)
			{
				list.Add(p.ReadString());
			}
			return list;
		}
	}
	internal static class VersionGate
	{
		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private static class Gate
		{
			[HarmonyPriority(200)]
			private static bool Prefix(ZNet __instance, ZRpc rpc)
			{
				if (!__instance.IsServer() || rpc == null)
				{
					return true;
				}
				string hostName = rpc.GetSocket().GetHostName();
				Version version = ClientVersion(rpc);
				ByEndpoint[rpc.GetSocket().GetEndPointString()] = version?.ToString() ?? "unknown";
				Plugin.Log.LogInfo((object)("Versions: " + hostName + " runs Blyssheim " + (version?.ToString() ?? "(unknown)")));
				if (version == null || string.IsNullOrWhiteSpace(Minimum.Value) || !TryVersion(Minimum.Value.Trim(), out var v) || version >= v)
				{
					return true;
				}
				Plugin.Log.LogWarning((object)$"Versions: turned away {hostName}: Blyssheim {version} is older than {v}.");
				Note($"{hostName} was turned away: Blyssheim {version}, needs {v} or newer");
				rpc.Invoke("Error", new object[1] { 3 });
				return false;
			}
		}

		private class VersionsCommand : ConsoleCommand
		{
			public override string Name => "versions";

			public override string Help => "Admins: which Blyssheim version each online player runs.";

			public override void Run(string[] args)
			{
				WardenNet.AskServer("versions", 0f);
			}
		}

		public static ConfigEntry<string> Minimum;

		private static readonly Dictionary<string, string> ByEndpoint = new Dictionary<string, string>();

		public static void Bind(ConfigFile cfg)
		{
			Minimum = cfg.Bind<string>("Versions", "Minimum", "0.4.18", "Server: games with an older Blyssheim are turned away (the Bastion Ward needs 0.4.18 on everyone's game). Empty = let any 0.4 in.");
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new VersionsCommand());
		}

		private static Version ClientVersion(ZRpc rpc)
		{
			try
			{
				IDictionary dictionary = AccessTools.Field(AccessTools.TypeByName("Jotunn.Utils.ModCompatibility"), "ClientVersions")?.GetValue(null) as IDictionary;
				string endPointString = rpc.GetSocket().GetEndPointString();
				if (dictionary == null || !dictionary.Contains(endPointString))
				{
					goto IL_004f;
				}
				object? obj = dictionary[endPointString];
				ZPackage val = (ZPackage)((obj is ZPackage) ? obj : null);
				if (val == null)
				{
					goto IL_004f;
				}
				Type type = AccessTools.TypeByName("Jotunn.Utils.ModuleVersionData");
				val.SetPos(0);
				object obj2 = AccessTools.Constructor(type, new Type[1] { typeof(ZPackage) }, false).Invoke(new object[1] { val });
				val.SetPos(0);
				foreach (object item in (IEnumerable)AccessTools.Property(type, "Modules").GetValue(obj2))
				{
					Type type2 = item.GetType();
					string text = AccessTools.Property(type2, "ModID").GetValue(item) as string;
					if (text == "overzealyss.blyssheim" || text == "Blyssheim")
					{
						return AccessTools.Property(type2, "Version").GetValue(item) as Version;
					}
				}
				goto end_IL_0000;
				IL_004f:
				return null;
				end_IL_0000:;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Versions: could not read a client's mod list: " + ex.Message));
			}
			return null;
		}

		private static bool TryVersion(string s, out Version v)
		{
			try
			{
				v = new Version(s);
				return true;
			}
			catch
			{
				v = null;
				return false;
			}
		}

		private static void Note(string line)
		{
			try
			{
				File.AppendAllText(Path.Combine(ServerWatch.DataDir, "watch.log"), $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}  {line}{Environment.NewLine}");
			}
			catch
			{
			}
		}

		public static string Report()
		{
			ZNet instance = ZNet.instance;
			List<ZNetPeer> list = ((instance != null) ? instance.GetPeers() : null) ?? new List<ZNetPeer>();
			if (list.Count == 0)
			{
				return "Nobody is online.";
			}
			string value = Minimum.Value;
			string value2;
			return "Blyssheim versions online" + (string.IsNullOrWhiteSpace(value) ? "" : (" (minimum " + value + ")")) + ":\n" + string.Join("\n", list.Select((ZNetPeer p) => "  " + (p.m_playerName ?? p.m_socket.GetHostName()) + ": " + (ByEndpoint.TryGetValue(p.m_socket.GetEndPointString(), out value2) ? value2 : "unknown")));
		}
	}
}
namespace Blyssheim.Warden
{
	internal static class InspectionNotice
	{
		[HarmonyPatch(typeof(Player), "HaveRequirements", new Type[]
		{
			typeof(Piece),
			typeof(RequirementMode)
		})]
		private static class AdminsOnly
		{
			private static void Postfix(Piece piece, ref bool __result)
			{
				if (__result && Object.op_Implicit((Object)(object)piece) && ((Object)((Component)piece).gameObject).name.StartsWith("BH_InspectionNoticePiece") && !WardenAccess.AdminConfirmed)
				{
					__result = false;
				}
			}
		}

		[HarmonyPatch(typeof(Sign), "Interact")]
		private static class Read
		{
			private static bool Prefix(Sign __instance, ref bool __result)
			{
				if (!IsNotice((Component)(object)__instance))
				{
					return true;
				}
				if (Object.op_Implicit((Object)(object)TextViewer.instance))
				{
					TextViewer.instance.ShowText((Style)0, "NOTICE OF INSPECTION", "These premises have been deemed <b>SUSPECT</b> and searched by the Realm Warden.\n\nThe resident is hereby found <b>GUILTY</b> of <b>ITEM DUPING / SMUGGLING CONTRABAND</b>. Suspect items have been removed. You may pray to Odin or appeal to the Realm Warden for further information.\n\n<b>Verdict: GUILTY.</b> Probation, effective immediately.\n\n<i>Odin saw that. Odin sees everything.</i>", false);
				}
				__result = true;
				return false;
			}
		}

		[HarmonyPatch(typeof(Sign), "UseItem")]
		private static class NoWriting
		{
			private static bool Prefix(Sign __instance, ref bool __result)
			{
				if (!IsNotice((Component)(object)__instance))
				{
					return true;
				}
				__result = false;
				return false;
			}
		}

		[HarmonyPatch(typeof(Sign), "GetHoverText")]
		private static class Hover
		{
			private static void Postfix(Sign __instance, ref string __result)
			{
				if (IsNotice((Component)(object)__instance))
				{
					__result = "Notice of Inspection\n[<color=yellow><b>$KEY_Use</b></color>] Read";
				}
			}
		}

		[HarmonyPatch(typeof(Piece), "CanBeRemoved")]
		private static class OnlyTheWardenTakesItDown
		{
			private static void Postfix(Piece __instance, ref bool __result)
			{
				if (__result && IsNotice((Component)(object)__instance) && !WardenAccess.AdminConfirmed)
				{
					__result = false;
				}
			}
		}

		[HarmonyPatch(typeof(WearNTear), "RPC_Damage")]
		private static class CannotBeDamaged
		{
			private static bool Prefix(WearNTear __instance)
			{
				return !IsNotice((Component)(object)__instance);
			}
		}

		public const string PieceName = "BH_InspectionNoticePiece";

		public const string Title = "Notice of Inspection";

		public const string Body = "These premises have been deemed <b>SUSPECT</b> and searched by the Realm Warden.\n\nThe resident is hereby found <b>GUILTY</b> of <b>ITEM DUPING / SMUGGLING CONTRABAND</b>. Suspect items have been removed. You may pray to Odin or appeal to the Realm Warden for further information.\n\n<b>Verdict: GUILTY.</b> Probation, effective immediately.\n\n<i>Odin saw that. Odin sees everything.</i>";

		private const string Face = "<b>NOTICE</b>";

		public static void Add()
		{
			//IL_0015: 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_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			Sprite val = WardenModels.LoadIcon("icon_notice");
			CustomPiece val2 = new CustomPiece("BH_InspectionNoticePiece", "sign", new PieceConfig
			{
				Name = "Notice of Inspection",
				Description = "Nail a Notice of Inspection to the premises.",
				PieceTable = "Hammer",
				Category = "Misc"
			});
			GameObject piecePrefab = val2.PiecePrefab;
			if (Object.op_Implicit((Object)(object)val))
			{
				val2.Piece.m_icon = val;
			}
			Sign component = piecePrefab.GetComponent<Sign>();
			if (Object.op_Implicit((Object)(object)component))
			{
				component.m_name = "Notice of Inspection";
				component.m_defaultText = "<b>NOTICE</b>";
				component.m_characterLimit = 0;
			}
			if (Object.op_Implicit((Object)(object)component) && Object.op_Implicit((Object)(object)component.m_textWidget))
			{
				((Graphic)component.m_textWidget).color = new Color(0.08f, 0.06f, 0.05f);
				((TMP_Text)component.m_textWidget).text = "<b>NOTICE</b>";
			}
			WearNTear component2 = piecePrefab.GetComponent<WearNTear>();
			if (Object.op_Implicit((Object)(object)component2))
			{
				component2.m_health = 10000000f;
				component2.m_noRoofWear = true;
				component2.m_noSupportWear = true;
			}
			Transform val3 = WardenModels.ApplyCentered(piecePrefab, "notice");
			if (Object.op_Implicit((Object)(object)val3))
			{
				Collider[] componentsInChildren = piecePrefab.GetComponentsInChildren<Collider>(true);
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					Object.DestroyImmediate((Object)(object)componentsInChildren[i]);
				}
				BoxCollider obj = piecePrefab.AddComponent<BoxCollider>();
				Bounds bounds = ((Component)val3).GetComponent<MeshFilter>().sharedMesh.bounds;
				obj.center = piecePrefab.transform.InverseTransformPoint(val3.TransformPoint(((Bounds)(ref bounds)).center));
				obj.size = Vector3.Scale(((Bounds)(ref bounds)).size, val3.localScale);
			}
			if (Object.op_Implicit((Object)(object)component) && Object.op_Implicit((Object)(object)component.m_textWidget) && Object.op_Implicit((Object)(object)WardenModels.Parts["notice"].Material))
			{
				((Component)component.m_textWidget).gameObject.SetActive(false);
			}
			Canvas[] componentsInChildren2 = piecePrefab.GetComponentsInChildren<Canvas>(true);
			foreach (Canvas val4 in componentsInChildren2)
			{
				if (Object.op_Implicit((Object)(object)WardenModels.Parts["notice"].Material))
				{
					((Component)val4).gameObject.SetActive(false);
				}
			}
			PieceManager.Instance.AddPiece(val2);
		}

		public static void Pulse()
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			WardenModels.Part value;
			Material val = (WardenModels.Parts.TryGetValue("notice", out value) ? value.Material : null);
			if (Object.op_Implicit((Object)(object)val))
			{
				float num = 0.5f + 0.5f * Mathf.Sin(Time.time * 1.6f);
				val.SetColor("_EmissionColor", Color.white * (0.25f + 0.65f * num));
			}
		}

		private static bool IsNotice(Component c)
		{
			if (Object.op_Implicit((Object)(object)c))
			{
				return ((Object)c.gameObject).name.StartsWith("BH_InspectionNoticePiece");
			}
			return false;
		}
	}
	internal class OfficeBoard : MonoBehaviour, Hoverable, Interactable, TextReceiver
	{
		[HarmonyPatch(typeof(Player), "HaveRequirements", new Type[]
		{
			typeof(Piece),
			typeof(RequirementMode)
		})]
		private static class AdminsOnly
		{
			private static void Postfix(Piece piece, ref bool __result)
			{
				if (__result && Object.op_Implicit((Object)(object)piece) && ((Object)((Component)piece).gameObject).name.StartsWith("BH_WardensOfficeBoard") && !WardenAccess.AdminConfirmed)
				{
					__result = false;
				}
			}
		}

		[HarmonyPatch(typeof(Piece), "CanBeRemoved")]
		private static class OnlyTheWardenTakesItDown
		{
			private static void Postfix(Piece __instance, ref bool __result)
			{
				if (__result && IsBoard((Component)(object)__instance) && !WardenAccess.AdminConfirmed)
				{
					__result = false;
				}
			}
		}

		[HarmonyPatch(typeof(WearNTear), "RPC_Damage")]
		private static class CannotBeDamaged
		{
			private static bool Prefix(WearNTear __instance)
			{
				return !IsBoard((Component)(object)__instance);
			}
		}

		public const string PieceName = "BH_WardensOfficeBoard";

		private const string Title = "Warden's Office";

		private const string StartKey = "bh_start_day";

		private static readonly float[] TileX = new float[3] { 0.195f, 0f, -0.195f };

		private const float TileY = 0.264f;

		private const float TileZ = 0.056f;

		private const float DigitW = 0.15f;

		private const float DigitH = 0.18f;

		private static Mesh[] _digitMeshes;

		private static Material _digitMaterial;

		private ZNetView _nview;

		private MeshFilter[] _digits;

		private int _shown = -1;

		private float _next;

		public static void Add()
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			CustomPiece val = new CustomPiece("BH_WardensOfficeBoard", "sign", new PieceConfig
			{
				Name = "Warden's Office",
				Description = "Days since the last incident, kept by the Realm Warden.",
				PieceTable = "Hammer",
				Category = "Misc"
			});
			GameObject piecePrefab = val.PiecePrefab;
			Sprite val2 = WardenModels.LoadIcon("icon_office");
			if (Object.op_Implicit((Object)(object)val2))
			{
				val.Piece.m_icon = val2;
			}
			Sign component = piecePrefab.GetComponent<Sign>();
			if (Object.op_Implicit((Object)(object)component) && Object.op_Implicit((Object)(object)component.m_textWidget))
			{
				((Component)component.m_textWidget).gameObject.SetActive(false);
			}
			Canvas[] componentsInChildren = piecePrefab.GetComponentsInChildren<Canvas>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				((Component)componentsInChildren[i]).gameObject.SetActive(false);
			}
			if (Object.op_Implicit((Object)(object)component))
			{
				Object.DestroyImmediate((Object)(object)component);
			}
			WearNTear component2 = piecePrefab.GetComponent<WearNTear>();
			if (Object.op_Implicit((Object)(object)component2))
			{
				component2.m_health = 10000000f;
				component2.m_noRoofWear = true;
				component2.m_noSupportWear = true;
			}
			Transform val3 = WardenModels.ApplyCentered(piecePrefab, "office");
			Collider[] componentsInChildren2 = piecePrefab.GetComponentsInChildren<Collider>(true);
			for (int i = 0; i < componentsInChildren2.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren2[i]);
			}
			BoxCollider val4 = piecePrefab.AddComponent<BoxCollider>();
			if (Object.op_Implicit((Object)(object)val3))
			{
				Bounds bounds = ((Component)val3).GetComponent<MeshFilter>().sharedMesh.bounds;
				val4.center = piecePrefab.transform.InverseTransformPoint(val3.TransformPoint(((Bounds)(ref bounds)).center));
				val4.size = Vector3.Scale(((Bounds)(ref bounds)).size, val3.localScale);
			}
			else
			{
				val4.size = new Vector3(2f, 2.3f, 0.3f);
			}
			piecePrefab.AddComponent<OfficeBoard>();
			PieceManager.Instance.AddPiece(val);
		}

		private void Awake()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Invalid comparison between Unknown and I4
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			_nview = ((Component)this).GetComponent<ZNetView>();
			if ((int)SystemInfo.graphicsDeviceType == 4)
			{
				return;
			}
			Transform val = ((Component)this).transform.Find(WardenModels.Parts["office"].ChildName);
			if (Object.op_Implicit((Object)(object)val))
			{
				BuildDigitAssets();
				_digits = (MeshFilter[])(object)new MeshFilter[3];
				for (int i = 0; i < 3; i++)
				{
					GameObject val2 = new GameObject("digit" + i);
					val2.transform.SetParent(val, false);
					val2.transform.localPosition = new Vector3(TileX[i], 0.264f, 0.056f);
					_digits[i] = val2.AddComponent<MeshFilter>();
					((Renderer)val2.AddComponent<MeshRenderer>()).sharedMaterial = _digitMaterial;
				}
			}
		}

		private void Update()
		{
			if ((Object)(object)_nview == (Object)null || !_nview.IsValid())
			{
				return;
			}
			ZDO zDO = _nview.GetZDO();
			if (_nview.IsOwner() && zDO.GetInt("bh_start_day", int.MinValue) == int.MinValue && Object.op_Implicit((Object)(object)EnvMan.instance))
			{
				zDO.Set("bh_start_day", EnvMan.instance.GetDay());
			}
			if (_digits == null || Time.time < _next)
			{
				return;
			}
			_next = Time.time + 1f;
			int num = Days();
			if (num != _shown)
			{
				_shown = num;
				string text = num.ToString("000");
				for (int i = 0; i < 3; i++)
				{
					_digits[i].sharedMesh = _digitMeshes[text[i] - 48];
				}
			}
		}

		private int Days()
		{
			if ((Object)(object)_nview == (Object)null || !_nview.IsValid() || !Object.op_Implicit((Object)(object)EnvMan.instance))
			{
				return 0;
			}
			int num = _nview.GetZDO().GetInt("bh_start_day", EnvMan.instance.GetDay());
			return Mathf.Clamp(EnvMan.instance.GetDay() - num, 0, 999);
		}

		private void SetDays(int n)
		{
			if (Object.op_Implicit((Object)(object)EnvMan.instance))
			{
				_nview.ClaimOwnership();
				_nview.GetZDO().Set("bh_start_day", EnvMan.instance.GetDay() - Mathf.Clamp(n, 0, 999));
				_next = 0f;
			}
		}

		public string GetHoverName()
		{
			return "Warden's Office";
		}

		public float GetHoverOffset()
		{
			return 0f;
		}

		public string GetHoverText()
		{
			string text = string.Format("{0}\nDays since last incident: <b>{1:000}</b>", "Warden's Office", Days());
			if (WardenAccess.AdminConfirmed)
			{
				text += "\n[<color=yellow><b>$KEY_Use</b></color>] Reset to 000\n[<color=yellow><b>$KEY_AltPlace + $KEY_Use</b></color>] Set number";
			}
			if (Localization.instance == null)
			{
				return text;
			}
			return Localization.instance.Localize(text);
		}

		public bool Interact(Humanoid user, bool hold, bool alt)
		{
			if (hold || !WardenAccess.AdminConfirmed || (Object)(object)_nview == (Object)null || !_nview.IsValid())
			{
				return false;
			}
			if (alt)
			{
				if (Object.op_Implicit((Object)(object)TextInput.instance))
				{
					TextInput.instance.RequestText((TextReceiver)(object)this, "Days since last incident (0-999)", 3);
				}
				return true;
			}
			SetDays(0);
			if (user != null)
			{
				((Character)user).Message((MessageType)2, "Days since last incident: 000", 0, (Sprite)null, false);
			}
			return true;
		}

		public bool UseItem(Humanoid user, ItemData item)
		{
			return false;
		}

		public string GetText()
		{
			return Days().ToString();
		}

		public void SetText(string text)
		{
			if (WardenAccess.AdminConfirmed && int.TryParse(text.Trim(), out var result))
			{
				SetDays(result);
			}
		}

		private static void BuildDigitAssets()
		{
			if (_digitMeshes == null)
			{
				_digitMaterial = WardenModels.BuildMaterialFor("office_digits");
				Texture mainTexture = _digitMaterial.mainTexture;
				Texture2D tex = (Texture2D)(object)((mainTexture is Texture2D) ? mainTexture : null);
				_digitMeshes = (Mesh[])(object)new Mesh[10];
				for (int i = 0; i < 10; i++)
				{
					_digitMeshes[i] = DigitMesh(tex, i);
				}
			}
		}

		private static Mesh DigitMesh(Texture2D tex, int d)
		{
			//IL_0385: Unknown result type (might be due to invalid IL or missing references)
			//IL_038a: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a8: 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_03ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c7: Expected O, but got Unknown
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_025e: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0302: Unknown result type (might be due to invalid IL or missing references)
			int num = 50;
			int num2 = 60;
			bool[,] array = new bool[num, num2];
			if (Object.op_Implicit((Object)(object)tex) && ((Texture)tex).isReadable)
			{
				Color32[] pixels = tex.GetPixels32();
				int width = ((Texture)tex).width;
				int height = ((Texture)tex).height;
				for (int i = 0; i < num2; i++)
				{
					for (int j = 0; j < num; j++)
					{
						int num3 = 0;
						int num4 = 0;
						for (int k = 0; k < 4; k++)
						{
							for (int l = 0; l < 4; l++)
							{
								int num5 = d * 200 + 24 + j * 4 + l;
								int num6 = height - 1 - (8 + (num2 - 1 - i) * 4 + k);
								if (num5 >= 0 && num5 < width && num6 >= 0 && num6 < height)
								{
									num4++;
									if (pixels[num6 * width + num5].a > 110)
									{
										num3++;
									}
								}
							}
						}
						array[j, i] = num4 > 0 && num3 * 2 >= num4;
					}
				}
			}
			else
			{
				for (int m = 0; m < num2; m++)
				{
					for (int n = 0; n < num; n++)
					{
						array[n, m] = true;
					}
				}
			}
			List<Vector3> list = new List<Vector3>();
			List<Vector2> list2 = new List<Vector2>();
			List<int> list3 = new List<int>();
			float num7 = 0.15f;
			float num8 = 0.18f;
			for (int num9 = 0; num9 < num2; num9++)
			{
				int num10 = 0;
				while (num10 < num)
				{
					if (!array[num10, num9])
					{
						num10++;
						continue;
					}
					int num11;
					for (num11 = num10; num11 + 1 < num && array[num11 + 1, num9]; num11++)
					{
					}
					float num12 = (float)num10 / (float)num;
					float num13 = (float)(num11 + 1) / (float)num;
					float num14 = (float)num9 / (float)num2;
					float num15 = (float)(num9 + 1) / (float)num2;
					int count = list.Count;
					list.Add(new Vector3(num7 * (0.5f - num12), num8 * (num14 - 0.5f), 0f));
					list.Add(new Vector3(num7 * (0.5f - num13), num8 * (num14 - 0.5f), 0f));
					list.Add(new Vector3(num7 * (0.5f - num13), num8 * (num15 - 0.5f), 0f));
					list.Add(new Vector3(num7 * (0.5f - num12), num8 * (num15 - 0.5f), 0f));
					float num16 = ((float)(d * 200 + 24) + num12 * 200f) / 2048f;
					float num17 = ((float)(d * 200 + 24) + num13 * 200f) / 2048f;
					float num18 = (8f + num14 * 240f) / 256f;
					float num19 = (8f + num15 * 240f) / 256f;
					list2.Add(new Vector2(num16, num18));
					list2.Add(new Vector2(num17, num18));
					list2.Add(new Vector2(num17, num19));
					list2.Add(new Vector2(num16, num19));
					list3.AddRange(new int[12]
					{
						count,
						count + 1,
						count + 2,
						count,
						count + 2,
						count + 3,
						count,
						count + 2,
						count + 1,
						count,
						count + 3,
						count + 2
					});
					num10 = num11 + 1;
				}
			}
			Mesh val = new Mesh
			{
				name = "digit" + d
			};
			val.SetVertices(list);
			val.SetUVs(0, list2);
			val.SetTriangles(list3, 0);
			val.RecalculateNormals();
			val.RecalculateBounds();
			return val;
		}

		public static void Pulse()
		{
			//IL_0034: 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)
			if (Object.op_Implicit((Object)(object)_digitMaterial))
			{
				float num = 0.5f + 0.5f * Mathf.Sin(Time.time * 1.6f);
				_digitMaterial.SetColor("_EmissionColor", Color.white * (0.35f + 0.75f * num));
			}
		}

		private static bool IsBoard(Component c)
		{
			if (Object.op_Implicit((Object)(object)c))
			{
				return ((Object)c.gameObject).name.StartsWith("BH_WardensOfficeBoard");
			}
			return false;
		}
	}
	internal static class TombLock
	{
		[HarmonyPatch(typeof(TombStone), "Setup")]
		private static class LockOnDeath
		{
			private static void Postfix(TombStone __instance, long ownerUID)
			{
				Player localPlayer = Player.m_localPlayer;
				if (Object.op_Implicit((Object)(object)localPlayer) && ownerUID == localPlayer.GetPlayerID() && (WardenAccess.AdminConfirmed || LockEveryone.Value))
				{
					ZNetView obj = View.Invoke(__instance);
					ZDO val = ((obj != null) ? obj.GetZDO() : null);
					if (val != null)
					{
						val.Set("bh_locked", true);
					}
				}
			}
		}

		[HarmonyPatch(typeof(TombStone), "Interact")]
		private static class OnlyOwnerOrAdmin
		{
			private static bool Prefix(TombStone __instance, ref bool __result)
			{
				ZNetView obj = View.Invoke(__instance);
				ZDO val = ((obj != null) ? obj.GetZDO() : null);
				if (val == null || !val.GetBool("bh_locked", false))
				{
					return true;
				}
				long num = (long)GetOwner.Invoke(__instance, null);
				Player localPlayer = Player.m_localPlayer;
				if (Object.op_Implicit((Object)(object)localPlayer) && (num == localPlayer.GetPlayerID() || WardenAccess.AdminConfirmed))
				{
					return true;
				}
				if (Object.op_Implicit((Object)(object)localPlayer))
				{
					((Character)localPlayer).Message((MessageType)2, "<color=#ff4040>Sealed by the Realm Warden.</color>", 0, (Sprite)null, false);
				}
				__result = false;
				return false;
			}
		}

		private const string Key = "bh_locked";

		public static ConfigEntry<bool> LockEveryone;

		private static readonly MethodInfo GetOwner = AccessTools.Method(typeof(TombStone), "GetOwner", (Type[])null, (Type[])null);

		private static readonly FieldRef<TombStone, ZNetView> View = AccessTools.FieldRefAccess<TombStone, ZNetView>("m_nview");

		public static void Bind(ConfigFile cfg)
		{
			LockEveryone = cfg.Bind<bool>("Tombstones", "LockEveryone", false, "Lock every player's tombstone to its owner and admins (admins' tombstones are always locked).");
		}
	}
	internal static class WardenAccess
	{
		[HarmonyPatch(typeof(PrivateArea), "CheckAccess")]
		private static class Wards
		{
			private static void Postfix(ref bool __result)
			{
				if (!__result && Active())
				{
					__result = true;
				}
			}
		}

		[HarmonyPatch(typeof(Container), "CheckAccess")]
		private static class PrivateChests
		{
			private static void Postfix(ref bool __result)
			{
				if (!__result && Active())
				{
					__result = true;
				}
			}
		}

		[HarmonyPatch(typeof(Player), "OnSpawned")]
		private static class AskOnSpawn
		{
			private static void Postfix(Player __instance)
			{
				if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && Object.op_Implicit((Object)(object)ZNet.instance) && !ZNet.instance.IsServer())
				{
					AdminConfirmed = false;
					WardenNet.AskServer("whoami", 0f);
				}
			}
		}

		public static bool AdminConfirmed;

		public static bool Active()
		{
			Player localPlayer = Player.m_localPlayer;
			if (AdminConfirmed && Object.op_Implicit((Object)(object)localPlayer))
			{
				return WardenVisuals.IsWarden(((Component)localPlayer).GetComponent<VisEquipment>());
			}
			return false;
		}
	}
	internal class WardenFX : MonoBehaviour
	{
		[HarmonyPatch(typeof(Player), "Awake")]
		private static class AttachToPlayers
		{
			private static void Postfix(Player __instance)
			{
				if (!Object.op_Implicit((Object)(object)((Component)__instance).GetComponent<WardenFX>()))
				{
					((Component)__instance).gameObject.AddComponent<WardenFX>();
				}
			}
		}

		public static readonly Dictionary<ZDOID, float> SirenUntil = new Dictionary<ZDOID, float>();

		public static readonly Dictionary<ZDOID, (string Word, float Until)> Shamed = new Dictionary<ZDOID, (string, float)>();

		private static readonly Color RuneDim = new Color(0.45f, 0.02f, 0.02f);

		private static readonly Color RuneBright = new Color(1f, 0.12f, 0.08f);

		private Player _player;

		private VisEquipment _vis;

		private GameObject _rig;

		private Transform _hips;

		private Transform _spine2;

		private Transform _head;

		private Transform _lFore;

		private Transform _lHand;

		private Transform _rFore;

		private Transform _rHand;

		private Transform _lUp;

		private Transform _lLeg;

		private Transform _lFoot;

		private Transform _rUp;

		private Transform _rLeg;

		private Transform _rFoot;

		private readonly List<(Transform T, Func<Vector3> Pos, Func<Quaternion> Rot)> _pieces = new List<(Transform, Func<Vector3>, Func<Quaternion>)>();

		private readonly List<Material> _runeMats = new List<Material>();

		private Light _chestLight;

		private Light _beaconLight;

		private Light _beaconSpot;

		private Transform _beacon;

		private Transform _spinner;

		private Material _beaconMat;

		private float _nextBubble;

		private Transform _helmModel;

		private List<GameObject> _clothes;

		private float _nextHelmLook;

		private static Material _unlit;

		private ZDOID Id
		{
			get
			{
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				if (!Object.op_Implicit((Object)(object)_player))
				{
					return ZDOID.None;
				}
				return ((Character)_player).GetZDOID();
			}
		}

		private void Awake()
		{
			_player = ((Component)this).GetComponent<Player>();
			_vis = ((Component)this).GetComponent<VisEquipment>();
		}

		private void LateUpdate()
		{
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Invalid comparison between Unknown and I4
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)_player))
			{
				return;
			}
			bool flag = WardenVisuals.IsWarden(_vis);
			if (flag && !Object.op_Implicit((Object)(object)_rig))
			{
				Build();
			}
			if (!flag && Object.op_Implicit((Object)(object)_rig))
			{
				Object.Destroy((Object)(object)_rig);
				_rig = null;
				_pieces.Clear();
				_runeMats.Clear();
			}
			if (!flag && Object.op_Implicit((Object)(object)_helmModel))
			{
				Object.Destroy((Object)(object)((Component)_helmModel).gameObject);
				_helmModel = null;
			}
			if (!flag && _clothes != null)
			{
				foreach (GameObject clothe in _clothes)
				{
					if (Object.op_Implicit((Object)(object)clothe))
					{
						Object.Destroy((Object)(object)clothe);
					}
				}
				_clothes = null;
			}
			if (flag && _clothes == null && (int)SystemInfo.graphicsDeviceType != 4)
			{
				_clothes = new List<GameObject>();
				string[] array = new string[2] { "warden_coat", "warden_pants" };
				foreach (string asset in array)
				{
					GameObject val = WardenSkinned.Attach(_vis, asset);
					if (Object.op_Implicit((Object)(object)val))
					{
						_clothes.Add(val);
					}
				}
				if (Object.op_Implicit((Object)(object)_rig) && WardenSkinned.Has("warden_coat"))
				{
					Renderer[] componentsInChildren = _rig.GetComponentsInChildren<Renderer>(true);
					foreach (Renderer val2 in componentsInChildren)
					{
						if ((Object)(object)((Component)val2).transform != (Object)(object)_beacon)
						{
							val2.enabled = false;
						}
					}
				}
			}
			ZDOID id = Id;
			float value;
			bool siren = SirenUntil.TryGetValue(id, out value) && Time.time < value;
			if (Object.op_Implicit((Object)(object)_rig))
			{
				Animate(siren);
			}
			Bubbles(id, siren);
		}

		private Transform Bone(string name)
		{
			Transform[] componentsInChildren = ((Component)this).GetComponentsInChildren<Transform>(true);
			foreach (Transform val in componentsInChildren)
			{
				if (((Object)val).name == name)
				{
					return val;
				}
			}
			return null;
		}

		private void Build()
		{
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Expected O, but got Unknown
			//IL_02e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_036d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0372: Unknown result type (might be due to invalid IL or missing references)
			//IL_03cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_03df: Unknown result type (might be due to invalid IL or missing references)
			//IL_0438: Unknown result type (might be due to invalid IL or missing references)
			//IL_047b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0481: Expected O, but got Unknown
			//IL_04a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d0: Unknown result type (might be due to invalid IL or missing references)
			_hips = Bone("Hips");
			_spine2 = Bone("Spine2");
			_head = Bone("Helmet_attach") ?? Bone("Head");
			_lFore = Bone("LeftForeArm");
			_lHand = Bone("LeftHand");
			_rFore = Bone("RightForeArm");
			_rHand = Bone("RightHand");
			_lUp = Bone("LeftUpLeg");
			_lLeg = Bone("LeftLeg");
			_lFoot = Bone("LeftFoot");
			_rUp = Bone("RightUpLeg");
			_rLeg = Bone("RightLeg");
			_rF