Decompiled source of ModCore v1.3.1

BepInEx/plugins/DiceModders.ModCore.dll

Decompiled 5 days ago
using System;
using System.Collections.Concurrent;
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.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Hook;
using DiceKingdoms.Game;
using DiceKingdoms.Interface;
using DiceKingdoms.Meta;
using DiceKingdoms.Network;
using DiceModders.ModCore.Tools;
using HarmonyLib;
using Il2CppInterop.Common;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Collections.ObjectModel;
using Il2CppSystem.IO;
using Il2CppSystem.Runtime.CompilerServices;
using MLAPI;
using MLAPI.Serialization;
using MLAPI.Serialization.Pooled;
using Microsoft.CodeAnalysis;
using Steamworks;
using Steamworks.Data;
using TMPro;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Localization;
using UnityEngine.Localization.Settings;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.SceneManagement;
using UnityEngine.TextCore;
using UnityEngine.UI;
using Utility.Pooling;
using Utility.Steamworks;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("DiceModders.ModCore")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.3.1.0")]
[assembly: AssemblyInformationalVersion("1.3.1")]
[assembly: AssemblyProduct("ModCore")]
[assembly: AssemblyTitle("DiceModders.ModCore")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.3.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace DiceModders.ModCore
{
	public static class ModCore
	{
		public static class BuildActions
		{
			public delegate bool Handler(BuildData data, int buildingId);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			private delegate byte DoActionFn(IntPtr self, IntPtr action, IntPtr method);

			private const int Marker = 1073741824;

			private const int CodeShift = 24;

			private const int MaxCode = 63;

			private const int IdMask = 16777215;

			private const int RepairAction = 0;

			private const int ActionType = 0;

			private const int ActionBuildingId = 12;

			private static readonly Dictionary<int, Handler> Handlers = new Dictionary<int, Handler>();

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

			private static DoActionFn _hook;

			private static DoActionFn _original;

			private static object _detour;

			private static bool _hooked;

			public static bool Register(int code, string owner, Handler handler)
			{
				Core.Ensure();
				if (code < 0 || code > 63 || handler == null)
				{
					CoreLog.Error("build actions: code " + code + " (" + owner + ") is not 0.." + 63);
					return false;
				}
				if (Handlers.ContainsKey(code))
				{
					CoreLog.Error("build actions: code " + code + " is already used by " + Owners[code] + "; " + owner + " was refused");
					return false;
				}
				Handlers[code] = handler;
				Owners[code] = owner ?? "?";
				Hook();
				CoreLog.Info("build actions: code " + code + " = " + Owners[code]);
				return true;
			}

			public static bool Plan(BuildData data, int code, int buildingId)
			{
				//IL_003a: Unknown result type (might be due to invalid IL or missing references)
				//IL_003f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				Core.Ensure();
				if ((Object)(object)data == (Object)null || !Handlers.ContainsKey(code) || (buildingId & -16777216) != 0)
				{
					return false;
				}
				int source = buildingId | 0x40000000 | (code << 24);
				Id val = Unsafe.As<int, Id>(ref source);
				return data.RepairBuilding(val);
			}

			private static void Hook()
			{
				if (_hooked)
				{
					return;
				}
				_hooked = true;
				try
				{
					IntPtr intPtr = Marshal.ReadIntPtr((IntPtr)Il2CppInteropUtils.GetIl2CppMethodInfoPointerFieldForGeneratedMethod((MethodBase)typeof(BuildData).GetMethod("DoAction")).GetValue(null));
					_hook = DoAction;
					_detour = INativeDetour.CreateAndApply<DoActionFn>(intPtr, _hook, ref _original);
					CoreLog.Info("build actions: listening to the game's build actions");
				}
				catch (Exception ex)
				{
					CoreLog.Error("build actions: hook failed, mod build actions will not work: " + ex.Message);
				}
			}

			private static byte DoAction(IntPtr self, IntPtr action, IntPtr method)
			{
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				//IL_0056: Expected O, but got Unknown
				try
				{
					if (action != IntPtr.Zero && Mem.ReadInt(action, 0) == 0)
					{
						int num = Mem.ReadInt(action, 12);
						if ((num & 0x40000000) != 0)
						{
							int key = (num >> 24) & 0x3F;
							if (!Handlers.TryGetValue(key, out var value))
							{
								return 0;
							}
							return value(new BuildData(self), num & 0xFFFFFF) ? ((byte)1) : ((byte)0);
						}
					}
				}
				catch (Exception ex)
				{
					CoreLog.Once("buildactions:run", "build actions: a mod action failed: " + ex);
					return 0;
				}
				return _original(self, action, method);
			}
		}

		public static class Buildings
		{
			private static readonly Dictionary<int, int> Suggested = new Dictionary<int, int>();

			private static readonly Dictionary<int, LobbyRule<bool>> SuggestedWhile = new Dictionary<int, LobbyRule<bool>>();

			private static Func<BuildingTypeName, int?> _source;

			public static void SuggestLimit(BuildingTypeName type, int limit)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				SuggestLimit(type, limit, null);
			}

			public unsafe static void SuggestLimit(BuildingTypeName type, int limit, LobbyRule<bool> rule)
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0017: Expected I4, but got Unknown
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Expected I4, but got Unknown
				//IL_001f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Expected I4, but got Unknown
				//IL_0049: Unknown result type (might be due to invalid IL or missing references)
				//IL_004b: Expected I4, but got Unknown
				Core.Ensure();
				Suggested[(int)type] = Math.Max(0, limit);
				if (rule != null)
				{
					SuggestedWhile[(int)type] = rule;
				}
				else
				{
					SuggestedWhile.Remove((int)type);
				}
				BuildingLimitHooks.Install();
				CoreLog.Info("buildings: limit for building " + (int)type + " (" + ((object)(*(BuildingTypeName*)(&type))/*cast due to .constrained prefix*/).ToString() + "): " + ((limit <= 0) ? "none" : limit.ToString()) + ((rule != null) ? (" while the rule '" + rule.Key + "' is on") : ""));
			}

			public static int SuggestedLimit(BuildingTypeName type)
			{
				//IL_0005: Unknown result type (might be due to invalid IL or missing references)
				//IL_000d: Expected I4, but got Unknown
				if (!Suggested.TryGetValue((int)type, out var value))
				{
					return 0;
				}
				return value;
			}

			private static int SuggestedNow(BuildingTypeName type)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Expected I4, but got Unknown
				int num = SuggestedLimit(type);
				if (num <= 0 || !SuggestedWhile.TryGetValue((int)type, out var value))
				{
					return num;
				}
				if (!value.Value || !BuiltInChanges.EveryoneHas(value))
				{
					return 0;
				}
				return num;
			}

			public static void SetLimits(string owner, Func<BuildingTypeName, int?> limits)
			{
				Core.Ensure();
				_source = limits;
				BuildingLimitHooks.Install();
				CoreLog.Info("buildings: limits set by " + (owner ?? "?"));
			}

			public static int LimitOf(BuildingTypeName type)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0055: Unknown result type (might be due to invalid IL or missing references)
				BuildingTypeName val = BaseOf(type);
				int? num = null;
				try
				{
					num = _source?.Invoke(val);
				}
				catch (Exception ex)
				{
					CoreLog.Once("buildings:source", "buildings: the limits source failed: " + ex.Message);
				}
				return Math.Max(0, num ?? SuggestedNow(val));
			}

			public static int CountOn(Island island, BuildingTypeName type)
			{
				//IL_000c: 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)
				return BuildingLimitHooks.Count((island != null) ? island.grid : null, BaseOf(type));
			}

			public static BuildingTypeName BaseOf(BuildingTypeName type)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return BuildingLimitHooks.BaseOf(type);
			}
		}

		public static class Civilizations
		{
			public static IReadOnlyList<ModCivilization> All
			{
				get
				{
					Core.Ensure();
					return CivilizationRegistry.All;
				}
			}

			public static bool IsGameDataLoaded => GameData.Loaded;

			public static event Action<ModCivilization> Added;

			public static event Action<ModCivilization> Removed;

			public static event Action GameDataLoaded;

			[MethodImpl(MethodImplOptions.NoInlining)]
			public static int AddBuildOrders(int civilization, string text)
			{
				LobbyMod owner = LobbyMods.IdentifySimulation(Assembly.GetCallingAssembly());
				Core.Ensure();
				return BuildOrders.Add(civilization, text, owner);
			}

			[MethodImpl(MethodImplOptions.NoInlining)]
			public static void RemoveBuildOrders(int civilization)
			{
				LobbyMod owner = LobbyMods.IdentifySimulation(Assembly.GetCallingAssembly());
				Core.Ensure();
				BuildOrders.Remove(civilization, owner);
			}

			public static CivilizationSkins Reskin(int builtInCivilization)
			{
				Core.Ensure();
				if (builtInCivilization < 0 || builtInCivilization > 4)
				{
					throw new ArgumentOutOfRangeException("builtInCivilization", "0..4 (for a mod civilization use its own Skins)");
				}
				ref CivilizationSkins reference = ref CivilizationRegistry.BuiltInSkins[builtInCivilization];
				return reference ?? (reference = new CivilizationSkins());
			}

			[MethodImpl(MethodImplOptions.NoInlining)]
			public static LobbyRule<bool> ReplaceTree(int builtInCivilization, Func<TechTree> tree, string ruleKey, string title, string description = null)
			{
				//IL_0044: Unknown result type (might be due to invalid IL or missing references)
				Core.Ensure();
				LobbyMod mod = LobbyMods.IdentifySimulation(Assembly.GetCallingAssembly());
				if (builtInCivilization < 0 || builtInCivilization > 4)
				{
					throw new ArgumentOutOfRangeException("builtInCivilization", "0..4 (a mod civilization gives its tree to Add)");
				}
				if (tree == null)
				{
					throw new ArgumentNullException("tree");
				}
				LobbyRule<bool> lobbyRule = Lobby.Rules.ToggleFor(mod, ruleKey, title, defaultValue: true, description ?? ("Uses this mod's tech tree for " + ((object)(Civilization)builtInCivilization/*cast due to .constrained prefix*/).ToString() + ". Only when every player has the mod; otherwise the original tree.")).InGroup(LobbyGroupRegistry.ForCivilization(builtInCivilization));
				BuiltInChanges.Trees[builtInCivilization] = new BuiltInChanges.TreeReplacement
				{
					Provider = tree,
					Rule = lobbyRule
				};
				return lobbyRule;
			}

			public static void RenderIcons(int civilization, IconView view = null, Action<BuildingTypeName, Sprite[]> rendered = null, params BuildingTypeName[] buildings)
			{
				Core.Ensure();
				WhenGameDataLoaded(delegate
				{
					CivilizationIcons.Render(civilization, view, buildings, rendered);
				});
			}

			public static int ToLobbyNumber(int civilization)
			{
				Core.Ensure();
				return CivilizationTable.Number(civilization);
			}

			public static int FromLobbyNumber(int civilization)
			{
				Core.Ensure();
				return CivilizationTable.Lookup(civilization);
			}

			public static void WhenGameDataLoaded(Action action)
			{
				Core.Ensure();
				if (action == null)
				{
					return;
				}
				if (GameData.Loaded)
				{
					try
					{
						action();
						return;
					}
					catch (Exception ex)
					{
						CoreLog.Error("GameDataLoaded handler failed: " + ex);
						return;
					}
				}
				GameDataLoaded += action;
			}

			internal static void RaiseGameDataLoaded()
			{
				TextLanguage.Listen();
				Action gameDataLoaded = Civilizations.GameDataLoaded;
				if (gameDataLoaded != null)
				{
					Delegate[] invocationList = gameDataLoaded.GetInvocationList();
					for (int i = 0; i < invocationList.Length; i++)
					{
						Action action = (Action)invocationList[i];
						try
						{
							using (CoreLog.Slow("handler " + CoreLog.NameOf(action)))
							{
								action();
							}
						}
						catch (Exception ex)
						{
							CoreLog.Error("GameDataLoaded handler failed: " + ex);
						}
					}
				}
				GameBalance.Recompute("game data loaded");
				DiskCache.Prune();
			}

			internal static void RaiseAdded(ModCivilization civ)
			{
				Raise(Civilizations.Added, civ, "Civilizations.Added");
			}

			internal static void RaiseRemoved(ModCivilization civ)
			{
				Raise(Civilizations.Removed, civ, "Civilizations.Removed");
			}

			private static void Raise(Action<ModCivilization> handler, ModCivilization civ, string what)
			{
				if (handler == null)
				{
					return;
				}
				Delegate[] invocationList = handler.GetInvocationList();
				for (int i = 0; i < invocationList.Length; i++)
				{
					Action<ModCivilization> action = (Action<ModCivilization>)invocationList[i];
					try
					{
						using (CoreLog.Slow("handler " + CoreLog.NameOf(action)))
						{
							action(civ);
						}
					}
					catch (Exception ex)
					{
						CoreLog.Error(what + " handler failed: " + ex);
					}
				}
			}

			[MethodImpl(MethodImplOptions.NoInlining)]
			public static ModCivilization Add(string key, string name, Func<TechTree> techTree = null, int skinsLike = 0)
			{
				LobbyMod owner = LobbyMods.IdentifySimulation(Assembly.GetCallingAssembly());
				Core.Ensure();
				if (string.IsNullOrWhiteSpace(key))
				{
					throw new ArgumentException("key is required", "key");
				}
				if (string.IsNullOrWhiteSpace(name))
				{
					throw new ArgumentException("name is required", "name");
				}
				return CivilizationRegistry.Add(key, name, techTree, skinsLike, owner);
			}

			public static void Rename(int civilization, string name, IReadOnlyDictionary<string, string> byLanguage = null)
			{
				Core.Ensure();
				if (name != null)
				{
					CivilizationText.Set(civilization, new CivilizationName(name, byLanguage));
					return;
				}
				ModCivilization modCivilization = CivilizationRegistry.Find(civilization);
				CivilizationText.Set(civilization, (modCivilization != null) ? new CivilizationName(modCivilization.Name) : null);
			}

			public static void SetText(int civilization, string key, string text, IReadOnlyDictionary<string, string> byLanguage = null)
			{
				Core.Ensure();
				CivilizationText.SetText(civilization, key, (text != null) ? new CivilizationName(text, byLanguage) : null);
			}

			public static void SetTexts(int civilization, TextSet texts)
			{
				Core.Ensure();
				CivilizationText.SetTexts(civilization, texts);
				if (texts == null || !texts.Has("civilization.name"))
				{
					ModCivilization modCivilization = CivilizationRegistry.Find(civilization);
					if (modCivilization != null)
					{
						CivilizationText.Set(civilization, new CivilizationName(modCivilization.Name));
					}
				}
			}

			public unsafe static void RenameUnit(int civilization, Type unit, string name, IReadOnlyDictionary<string, string> byLanguage = null)
			{
				SetText(civilization, "unit." + ((object)(*(Type*)(&unit))/*cast due to .constrained prefix*/).ToString() + ".name", name, byLanguage);
			}

			public unsafe static void SetUnitLore(int civilization, Type unit, string lore, IReadOnlyDictionary<string, string> byLanguage = null)
			{
				SetText(civilization, "unit." + ((object)(*(Type*)(&unit))/*cast due to .constrained prefix*/).ToString() + ".lore", lore, byLanguage);
			}

			public static void RenameBuilding(int civilization, string buildingType, string name, IReadOnlyDictionary<string, string> byLanguage = null)
			{
				SetText(civilization, "building." + buildingType + ".name", name, byLanguage);
			}

			public static TechTree CloneTree(int fromCivilization)
			{
				Core.Ensure();
				if (fromCivilization < 0 || fromCivilization > 4)
				{
					throw new ArgumentOutOfRangeException("fromCivilization", "only the built-in civilizations 0..4 have a tree to copy");
				}
				Il2CppArrayBase<Technologies> obj = Resources.FindObjectsOfTypeAll<Technologies>();
				if (obj.Length == 0)
				{
					throw new InvalidOperationException("The game's technologies are not loaded yet.");
				}
				TechTree val = obj[0].TechTree((Civilization)fromCivilization);
				TechTree obj2 = Object.Instantiate<TechTree>(val);
				((Object)obj2).name = ((Object)val).name + " (mod copy)";
				((Object)obj2).hideFlags = (HideFlags)61;
				return obj2;
			}

			public static int RefreshLooks(MatchPlayer player)
			{
				Core.Ensure();
				try
				{
					object grid;
					if (player == null)
					{
						grid = null;
					}
					else
					{
						Island island = player.Island;
						grid = ((island != null) ? island.grid : null);
					}
					return LiveLooks.Refresh((IslandGrid)grid);
				}
				catch (Exception ex)
				{
					CoreLog.Warn("live looks: " + ex.Message);
					return 0;
				}
			}

			public static int RefreshLooks()
			{
				int num = 0;
				foreach (MatchPlayer item in Players.All)
				{
					num += RefreshLooks(item);
				}
				CoreLog.Info("live looks: " + num + " building model(s) rebuilt");
				return num;
			}

			public static ConfigEntry<bool> AddLooksSwitch(ConfigFile config, CivilizationSkins skins, string section = "Looks", string key = "Enabled", string description = null)
			{
				ConfigEntry<bool> entry = config.Bind<bool>(section, key, true, description ?? "Show this mod's models. Visual and on this PC only; switching works at once, also during a match (standing buildings are rebuilt).");
				skins.Enabled = entry.Value;
				entry.SettingChanged += delegate
				{
					skins.Enabled = entry.Value;
					RefreshLooks();
				};
				return entry;
			}
		}

		public static class Hotkeys
		{
			private static readonly List<Hotkey> Items = new List<Hotkey>();

			private static bool _ready;

			public static IReadOnlyList<Hotkey> All => Items;

			public static event Action<Hotkey> Added;

			public static event Action<Hotkey> Changed;

			[MethodImpl(MethodImplOptions.NoInlining)]
			public static Hotkey Add(ConfigFile config, string id, string title, string defaultKeys, Action pressed, Func<bool> when = null)
			{
				LobbyMod mod = LobbyMods.Identify(Assembly.GetCallingAssembly());
				Core.Ensure();
				if (config == null)
				{
					throw new ArgumentNullException("config");
				}
				if (string.IsNullOrWhiteSpace(id))
				{
					throw new ArgumentException("id is required", "id");
				}
				ConfigEntry<string> entry = config.Bind<string>("Hotkeys", id, HotkeyKeys.Normalize(defaultKeys), title + " (keys like F9, Ctrl+E, Shift+Alt+H; empty = none)");
				Hotkey hotkey = new Hotkey(mod, entry, id, title ?? id, HotkeyKeys.Normalize(defaultKeys), when);
				if (pressed != null)
				{
					hotkey.Pressed += pressed;
				}
				Items.Add(hotkey);
				if (_ready)
				{
					hotkey.Bind();
				}
				else
				{
					Civilizations.WhenGameDataLoaded(BindAll);
				}
				Hotkeys.Added?.Invoke(hotkey);
				return hotkey;
			}

			private static void BindAll()
			{
				if (_ready)
				{
					return;
				}
				_ready = true;
				foreach (Hotkey item in Items)
				{
					item.Bind();
				}
			}

			internal static void RaiseChanged(Hotkey h)
			{
				Hotkeys.Changed?.Invoke(h);
			}
		}

		public static class Lobby
		{
			public static class Rules
			{
				public static IReadOnlyList<ILobbyRule> All => LobbyRuleRegistry.All;

				public static bool Fixed => LobbyState.RulesFrozen;

				public static event Action<ILobbyRule> Registered;

				internal static void RaiseRegistered(ILobbyRule rule)
				{
					Action<ILobbyRule> registered = Rules.Registered;
					if (registered == null)
					{
						return;
					}
					Delegate[] invocationList = registered.GetInvocationList();
					for (int i = 0; i < invocationList.Length; i++)
					{
						Action<ILobbyRule> action = (Action<ILobbyRule>)invocationList[i];
						try
						{
							using (CoreLog.Slow("handler " + CoreLog.NameOf(action)))
							{
								action(rule);
							}
						}
						catch (Exception ex)
						{
							CoreLog.Error("Lobby.Rules.Registered handler failed: " + ex);
						}
					}
				}

				[MethodImpl(MethodImplOptions.NoInlining)]
				public static LobbyRule<bool> Toggle(string key, string title, bool defaultValue, string description = null, Func<bool> visible = null, bool affectsSimulation = true)
				{
					return ToggleFor(LobbyMods.Identify(Assembly.GetCallingAssembly()), key, title, defaultValue, description, visible, affectsSimulation);
				}

				internal static LobbyRule<bool> ToggleFor(LobbyMod mod, string key, string title, bool defaultValue, string description = null, Func<bool> visible = null, bool affectsSimulation = true)
				{
					return LobbyRuleRegistry.Register(key, () => new LobbyRule<bool>(mod, key, title, defaultValue, description, visible, affectsSimulation, (bool v) => (!v) ? "0" : "1", (string raw) => (!(raw == "1") && !raw.Equals("true", StringComparison.OrdinalIgnoreCase)) ? ((!(raw == "0") && !raw.Equals("false", StringComparison.OrdinalIgnoreCase)) ? (ok: false, value: false) : (ok: true, value: false)) : (ok: true, value: true)));
				}

				[MethodImpl(MethodImplOptions.NoInlining)]
				public static LobbyRule<int> Number(string key, string title, int defaultValue, int min, int max, int step, string description = null, Func<bool> visible = null, bool affectsSimulation = true)
				{
					LobbyMod mod = LobbyMods.Identify(Assembly.GetCallingAssembly());
					if (max < min)
					{
						int num = max;
						max = min;
						min = num;
					}
					int lo = min;
					int hi = max;
					int result;
					LobbyRule<int> lobbyRule = LobbyRuleRegistry.Register(key, () => new LobbyRule<int>(mod, key, title, Math.Clamp(defaultValue, lo, hi), description, visible, affectsSimulation, (int v) => v.ToString(CultureInfo.InvariantCulture), (string raw) => (!int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out result)) ? (ok: false, value: 0) : (ok: true, value: Math.Clamp(result, lo, hi))));
					lobbyRule.Min = lo;
					lobbyRule.Max = hi;
					lobbyRule.Step = Math.Max(1, step);
					return lobbyRule;
				}

				[MethodImpl(MethodImplOptions.NoInlining)]
				public static LobbyRule<string> Text(string key, string title, string defaultValue = "", string description = null, Func<bool> visible = null, bool affectsSimulation = true)
				{
					LobbyMod mod = LobbyMods.Identify(Assembly.GetCallingAssembly());
					return LobbyRuleRegistry.Register(key, () => new LobbyRule<string>(mod, key, title, defaultValue ?? "", description, visible, affectsSimulation, (string v) => v ?? "", (string raw) => (ok: true, value: raw ?? "")));
				}

				[MethodImpl(MethodImplOptions.NoInlining)]
				public static LobbyRule<int> Choice(string key, string title, int defaultIndex, IReadOnlyList<string> choices, string description = null, Func<bool> visible = null, bool affectsSimulation = true)
				{
					if (choices == null || choices.Count == 0)
					{
						throw new ArgumentException("at least one choice is needed", "choices");
					}
					LobbyMod mod = LobbyMods.Identify(Assembly.GetCallingAssembly());
					int hi = choices.Count - 1;
					int result;
					LobbyRule<int> lobbyRule = LobbyRuleRegistry.Register(key, () => new LobbyRule<int>(mod, key, title, Math.Clamp(defaultIndex, 0, hi), description, visible, affectsSimulation, (int v) => v.ToString(CultureInfo.InvariantCulture), (string raw) => (!int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out result)) ? (ok: false, value: 0) : (ok: true, value: Math.Clamp(result, 0, hi))));
					lobbyRule.Min = 0;
					lobbyRule.Max = hi;
					lobbyRule.Step = 1;
					lobbyRule.Choices = new List<string>(choices);
					return lobbyRule;
				}
			}

			public static class Compatibility
			{
				public static IReadOnlyList<string> Warnings
				{
					get
					{
						Core.Ensure();
						return LobbyRuleRegistry.Warnings();
					}
				}

				public static bool IsCompatible => Warnings.Count == 0;
			}

			public static class Groups
			{
				public static IReadOnlyList<LobbyGroup> All
				{
					get
					{
						Core.Ensure();
						return LobbyGroupRegistry.All;
					}
				}

				public static event Action Changed;

				public static LobbyGroup ForCivilization(int civilization)
				{
					Core.Ensure();
					return LobbyGroupRegistry.ForCivilization(civilization);
				}

				public static LobbyGroup Get(string key, string title, int order = 500)
				{
					Core.Ensure();
					if (string.IsNullOrWhiteSpace(key))
					{
						throw new ArgumentException("key is required", "key");
					}
					return LobbyGroupRegistry.Get("mod." + key, title ?? key, order, null);
				}

				internal static void RaiseChanged()
				{
					Action changed = Groups.Changed;
					if (changed == null)
					{
						return;
					}
					Delegate[] invocationList = changed.GetInvocationList();
					for (int i = 0; i < invocationList.Length; i++)
					{
						Action action = (Action)invocationList[i];
						try
						{
							action();
						}
						catch (Exception ex)
						{
							CoreLog.Error("Lobby.Groups.Changed handler failed: " + ex);
						}
					}
				}
			}

			public static class PlayerValues
			{
				public static event Action<ulong> Changed;

				public static bool Set(string key, string value)
				{
					Core.Ensure();
					return LobbyState.SetOwnValue(key, value);
				}

				public static string Get(ulong steamId, string key)
				{
					Core.Ensure();
					return LobbyState.GetMemberValue(steamId, key);
				}

				internal static void RaiseChanged(ulong steamId)
				{
					Action<ulong> changed = PlayerValues.Changed;
					if (changed == null)
					{
						return;
					}
					Delegate[] invocationList = changed.GetInvocationList();
					for (int i = 0; i < invocationList.Length; i++)
					{
						Action<ulong> action = (Action<ulong>)invocationList[i];
						try
						{
							action(steamId);
						}
						catch (Exception ex)
						{
							CoreLog.Error("Lobby.PlayerValues.Changed handler failed: " + ex);
						}
					}
				}
			}

			private static Action _changed;

			public static bool InLobby
			{
				get
				{
					Core.Ensure();
					return LobbyState.InLobby;
				}
			}

			public static bool IsHost
			{
				get
				{
					Core.Ensure();
					return LobbyState.IsHost;
				}
			}

			public static ulong LocalSteamId
			{
				get
				{
					Core.Ensure();
					return LobbyState.LocalSteamId;
				}
			}

			public static Lobby? Current
			{
				get
				{
					Core.Ensure();
					return LobbyState.Current;
				}
			}

			public static IReadOnlyList<LobbyMember> Members
			{
				get
				{
					Core.Ensure();
					return LobbyState.Members;
				}
			}

			public static event Action Changed
			{
				add
				{
					Core.Ensure();
					_changed = (Action)Delegate.Combine(_changed, value);
				}
				remove
				{
					_changed = (Action)Delegate.Remove(_changed, value);
				}
			}

			internal static void RaiseChanged()
			{
				Raise(_changed, "Lobby.Changed");
			}

			private static void Raise(Action handler, string what)
			{
				if (handler == null)
				{
					return;
				}
				Delegate[] invocationList = handler.GetInvocationList();
				for (int i = 0; i < invocationList.Length; i++)
				{
					Action action = (Action)invocationList[i];
					try
					{
						using (CoreLog.Slow("handler " + CoreLog.NameOf(action)))
						{
							action();
						}
					}
					catch (Exception ex)
					{
						CoreLog.Error(what + " handler failed: " + ex);
					}
				}
			}
		}

		public static class Match
		{
			private static Action _islandsSpawned;

			private static Action _started;

			private static Action<MatchPhase> _phaseEntered;

			private static Action<MatchPhase> _phaseSynced;

			private static Action _gameOver;

			private static Action _rejoined;

			private static Action _reset;

			private static Action _ended;

			public static bool Running
			{
				get
				{
					Core.Ensure();
					return LobbyState.MatchRunning;
				}
			}

			public static MatchPhase Phase
			{
				get
				{
					Core.Ensure();
					return MatchState.Phase;
				}
			}

			public static int Turn
			{
				get
				{
					Core.Ensure();
					return MatchState.Turn;
				}
			}

			public static MatchSettings Settings { get; } = new MatchSettings();

			public static bool IsTraining
			{
				get
				{
					Core.Ensure();
					try
					{
						GameState game = MatchState.Game;
						return (Object)(object)game != (Object)null && game.IsTraining;
					}
					catch
					{
						return false;
					}
				}
			}

			public static bool IsSolo
			{
				get
				{
					Core.Ensure();
					int num = 0;
					foreach (MatchPlayer item in Players.All)
					{
						if (!item.IsAI)
						{
							num++;
						}
					}
					return num < 2;
				}
			}

			public static event Action IslandsSpawned
			{
				add
				{
					Core.Ensure();
					_islandsSpawned = (Action)Delegate.Combine(_islandsSpawned, value);
				}
				remove
				{
					_islandsSpawned = (Action)Delegate.Remove(_islandsSpawned, value);
				}
			}

			public static event Action Started
			{
				add
				{
					Core.Ensure();
					_started = (Action)Delegate.Combine(_started, value);
				}
				remove
				{
					_started = (Action)Delegate.Remove(_started, value);
				}
			}

			public static event Action<MatchPhase> PhaseEntered
			{
				add
				{
					Core.Ensure();
					_phaseEntered = (Action<MatchPhase>)Delegate.Combine(_phaseEntered, value);
				}
				remove
				{
					_phaseEntered = (Action<MatchPhase>)Delegate.Remove(_phaseEntered, value);
				}
			}

			public static event Action<MatchPhase> PhaseSynced
			{
				add
				{
					Core.Ensure();
					_phaseSynced = (Action<MatchPhase>)Delegate.Combine(_phaseSynced, value);
				}
				remove
				{
					_phaseSynced = (Action<MatchPhase>)Delegate.Remove(_phaseSynced, value);
				}
			}

			public static event Action GameOver
			{
				add
				{
					Core.Ensure();
					_gameOver = (Action)Delegate.Combine(_gameOver, value);
				}
				remove
				{
					_gameOver = (Action)Delegate.Remove(_gameOver, value);
				}
			}

			public static event Action Rejoined
			{
				add
				{
					Core.Ensure();
					_rejoined = (Action)Delegate.Combine(_rejoined, value);
				}
				remove
				{
					_rejoined = (Action)Delegate.Remove(_rejoined, value);
				}
			}

			public static event Action Reset
			{
				add
				{
					Core.Ensure();
					_reset = (Action)Delegate.Combine(_reset, value);
				}
				remove
				{
					_reset = (Action)Delegate.Remove(_reset, value);
				}
			}

			public static event Action Ended
			{
				add
				{
					Core.Ensure();
					_ended = (Action)Delegate.Combine(_ended, value);
				}
				remove
				{
					_ended = (Action)Delegate.Remove(_ended, value);
				}
			}

			internal static void RaiseIslandsSpawned()
			{
				Raise(_islandsSpawned, "Match.IslandsSpawned");
			}

			internal static void RaiseStarted()
			{
				Raise(_started, "Match.Started");
			}

			internal static void RaisePhaseEntered(MatchPhase phase)
			{
				Raise(_phaseEntered, phase, "Match.PhaseEntered");
			}

			internal static void RaisePhaseSynced(MatchPhase phase)
			{
				Raise(_phaseSynced, phase, "Match.PhaseSynced");
			}

			internal static void RaiseGameOver()
			{
				Raise(_gameOver, "Match.GameOver");
			}

			internal static void RaiseRejoined()
			{
				Raise(_rejoined, "Match.Rejoined");
			}

			internal static void RaiseReset()
			{
				Raise(_reset, "Match.Reset");
			}

			internal static void RaiseEnded()
			{
				Raise(_ended, "Match.Ended");
			}

			private static void Raise(Action handler, string what)
			{
				if (handler == null)
				{
					return;
				}
				Delegate[] invocationList = handler.GetInvocationList();
				for (int i = 0; i < invocationList.Length; i++)
				{
					Action action = (Action)invocationList[i];
					try
					{
						using (CoreLog.Slow("handler " + CoreLog.NameOf(action)))
						{
							action();
						}
					}
					catch (Exception ex)
					{
						CoreLog.Error(what + " handler failed: " + ex);
					}
				}
			}

			private static void Raise(Action<MatchPhase> handler, MatchPhase phase, string what)
			{
				if (handler == null)
				{
					return;
				}
				Delegate[] invocationList = handler.GetInvocationList();
				for (int i = 0; i < invocationList.Length; i++)
				{
					Action<MatchPhase> action = (Action<MatchPhase>)invocationList[i];
					try
					{
						using (CoreLog.Slow("handler " + CoreLog.NameOf(action)))
						{
							action(phase);
						}
					}
					catch (Exception ex)
					{
						CoreLog.Error(what + " handler failed: " + ex);
					}
				}
			}
		}

		public static class Messages
		{
			public static bool Post(GameText text)
			{
				Core.Ensure();
				if (text == null)
				{
					return false;
				}
				try
				{
					GameState game = MatchState.Game;
					Log val = (((Object)(object)game != (Object)null) ? game.log : null);
					if ((Object)(object)val == (Object)null)
					{
						return false;
					}
					if (!((NetworkedBehaviour)val).IsServer)
					{
						CoreLog.Once("messages:post-client", "Messages.Post: only the host can add log lines (this machine is a client)");
						return false;
					}
					val.AddMessage(text.ToGame());
					return true;
				}
				catch (Exception ex)
				{
					CoreLog.Once("messages:post", "Messages.Post failed: " + ex.Message);
					return false;
				}
			}

			public static bool Post(string text)
			{
				return Post(new GameText().Text(text));
			}

			public static bool Chat(string text)
			{
				Core.Ensure();
				if (string.IsNullOrWhiteSpace(text))
				{
					return false;
				}
				try
				{
					Player localPlayer = Player.LocalPlayer;
					if ((Object)(object)localPlayer == (Object)null)
					{
						return false;
					}
					localPlayer.Chat(text);
					return true;
				}
				catch (Exception ex)
				{
					CoreLog.Once("messages:chat", "Messages.Chat failed: " + ex.Message);
					return false;
				}
			}
		}

		public static class Mods
		{
			[MethodImpl(MethodImplOptions.NoInlining)]
			public static ModSwitch Switch(ConfigFile config, bool affectsSimulation = false, bool restartNeeded = false, string description = null)
			{
				Core.Ensure();
				if (config == null)
				{
					throw new ArgumentNullException("config");
				}
				string id = LobbyMods.Identify(Assembly.GetCallingAssembly()).Id;
				if (ModSwitches.ById.TryGetValue(id, out var value))
				{
					return value;
				}
				string text = (description ?? "Turn this mod on or off.") + (restartNeeded ? " Takes effect after a restart." : (affectsSimulation ? " Changes during a match apply when it ends." : ""));
				ConfigEntry<bool> entry = config.Bind<bool>("General", "Enabled", true, text);
				ModSwitch modSwitch = new ModSwitch(id, entry, affectsSimulation, restartNeeded);
				ModSwitches.ById[id] = modSwitch;
				return modSwitch;
			}

			public static bool IsOn(string pluginGuid)
			{
				return ModSwitches.IsOn(pluginGuid);
			}
		}

		public static class Players
		{
			public static IReadOnlyList<MatchPlayer> All
			{
				get
				{
					Core.Ensure();
					List<MatchPlayer> list = new List<MatchPlayer>();
					try
					{
						GameState game = MatchState.Game;
						List<Player> val = (((Object)(object)game != (Object)null) ? game.Players : null);
						if (val == null)
						{
							return list;
						}
						for (int i = 0; i < val.Count; i++)
						{
							Player val2 = val[i];
							if ((Object)(object)val2 != (Object)null)
							{
								list.Add(new MatchPlayer(val2));
							}
						}
					}
					catch (Exception ex)
					{
						CoreLog.Once("players:all", "players: could not read the game's player list: " + ex.Message);
					}
					return list;
				}
			}

			public static MatchPlayer Local
			{
				get
				{
					Core.Ensure();
					try
					{
						Player localPlayer = Player.LocalPlayer;
						return ((Object)(object)localPlayer != (Object)null) ? new MatchPlayer(localPlayer) : null;
					}
					catch
					{
						return null;
					}
				}
			}

			public static MatchPlayer Host
			{
				get
				{
					foreach (MatchPlayer item in All)
					{
						if (item.IsHost)
						{
							return item;
						}
					}
					return null;
				}
			}

			public static MatchPlayer Find(ulong id)
			{
				foreach (MatchPlayer item in All)
				{
					if (item.Id == id)
					{
						return item;
					}
				}
				return null;
			}

			public static bool TrySetCivilization(MatchPlayer player, int civilization, out string why)
			{
				//IL_00da: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e0: Expected O, but got Unknown
				Core.Ensure();
				why = null;
				try
				{
					Player val = player?.Game;
					if ((Object)(object)val == (Object)null)
					{
						why = "no such player";
						return false;
					}
					if (!((NetworkedBehaviour)val).IsServer)
					{
						why = "only the host can change civilizations";
						return false;
					}
					if (LobbyState.MatchRunning)
					{
						why = "the match has started";
						return false;
					}
					if (val.StartGameReady)
					{
						why = "the player is already ready";
						return false;
					}
					int num = civilization;
					if (civilization < 0 || civilization > 4)
					{
						ModCivilization modCivilization = CivilizationRegistry.Find(civilization);
						if (modCivilization == null)
						{
							why = "civilization " + civilization + " is not known";
							return false;
						}
						if (LobbyState.InLobby && !LobbyState.EveryoneHasCivilization(modCivilization))
						{
							why = "'" + modCivilization.Name + "' is not installed for everybody in the lobby";
							return false;
						}
						num = modCivilization.SkinsLike;
					}
					PlayerSkins val2 = new PlayerSkins((Civilization)num, val.skinRegistry);
					val2.civilization = (Civilization)civilization;
					val.skins.Value = val2;
					return true;
				}
				catch (Exception ex)
				{
					why = ex.Message;
					return false;
				}
			}
		}

		public static class Texts
		{
			internal static readonly Dictionary<string, TextSet> ByAssembly = new Dictionary<string, TextSet>();

			private static bool _languagePending;

			public static string Language
			{
				get
				{
					Core.Ensure();
					return TextLanguage.Current;
				}
			}

			public static event Action LanguageChanged;

			internal static string Lookup(string assemblyName, string key, string fallback)
			{
				if (assemblyName == null || !ByAssembly.TryGetValue(assemblyName, out var value) || !value.Has(key))
				{
					return fallback;
				}
				string text = value.Get(key);
				if (!string.IsNullOrEmpty(text) && !(text == key))
				{
					return text;
				}
				return fallback;
			}

			public static string Game(string key, string fallback = null)
			{
				if (!TextLanguage.Ready)
				{
					_ = TextLanguage.Current;
					return fallback ?? key;
				}
				try
				{
					string render = ITextElement.L(key, new Il2CppReferenceArray<ITextElement>(0L)).Render;
					if (string.IsNullOrEmpty(render) || render == key || render.StartsWith("No translation found", StringComparison.Ordinal))
					{
						return fallback ?? key;
					}
					return render;
				}
				catch (Exception ex)
				{
					CoreLog.Once("texts:game", "texts: game text '" + key + "' could not be read: " + ex.Message);
					return fallback ?? key;
				}
			}

			internal static string LookupAny(string key, string fallback)
			{
				foreach (TextSet value in ByAssembly.Values)
				{
					if (value.Has(key))
					{
						string text = value.Get(key);
						if (!string.IsNullOrEmpty(text) && text != key)
						{
							return text;
						}
					}
				}
				return fallback;
			}

			internal static void RaiseLanguageChanged()
			{
				if (!_languagePending)
				{
					_languagePending = true;
					HotkeyKeys.Later(RunLanguageChanged);
				}
			}

			private static void RunLanguageChanged()
			{
				_languagePending = false;
				CoreLog.Info("texts: redrawing for the language '" + TextLanguage.Current + "'");
				Action languageChanged = Texts.LanguageChanged;
				if (languageChanged == null)
				{
					return;
				}
				Delegate[] invocationList = languageChanged.GetInvocationList();
				for (int i = 0; i < invocationList.Length; i++)
				{
					Action action = (Action)invocationList[i];
					try
					{
						action();
					}
					catch (Exception ex)
					{
						CoreLog.Error("Texts.LanguageChanged handler failed: " + ex);
					}
				}
			}

			[MethodImpl(MethodImplOptions.NoInlining)]
			public static TextSet Load(string resource = "texts.json", string section = null)
			{
				return Load(Assembly.GetCallingAssembly(), resource, section);
			}

			public static TextSet Load(Assembly assembly, string resource = "texts.json", string section = null)
			{
				Core.Ensure();
				if (assembly == null)
				{
					throw new ArgumentNullException("assembly");
				}
				string name = assembly.GetName().Name;
				TextSet textSet = new TextSet
				{
					Source = name
				};
				try
				{
					using Stream stream = FindResource(assembly, resource);
					if (stream != null)
					{
						using StreamReader streamReader = new StreamReader(stream);
						textSet = TextSet.Parse(streamReader.ReadToEnd(), section, name);
					}
					else
					{
						CoreLog.Warn("texts: '" + resource + "' is not built into " + name + " (EmbeddedResource with LogicalName=\"" + resource + "\")");
					}
				}
				catch (Exception ex)
				{
					CoreLog.Error("texts: " + name + " '" + resource + "' could not be read: " + ex.Message);
				}
				string text = LooseFile(assembly);
				if (text != null && File.Exists(text))
				{
					try
					{
						TextSet textSet2 = TextSet.Parse(File.ReadAllText(text), null, text);
						textSet.Merge(textSet2);
						CoreLog.Info("texts: " + name + " uses " + textSet2.Count + " key(s) from " + Path.GetFileName(text));
					}
					catch (Exception ex2)
					{
						CoreLog.Warn("texts: " + Path.GetFileName(text) + " has a mistake and was left out (" + ex2.Message + ")");
					}
				}
				List<string> list = textSet.MissingEnglish();
				if (list.Count > 0)
				{
					CoreLog.Warn("texts: " + name + " has " + list.Count + " key(s) without English (the fallback language), e.g. " + list[0]);
				}
				GameTexts.Add(textSet);
				ByAssembly[name] = textSet;
				return textSet;
			}

			public static string LooseFile(Assembly assembly)
			{
				string text = assembly?.Location;
				if (!string.IsNullOrEmpty(text))
				{
					return Path.Combine(Path.GetDirectoryName(text) ?? "", Path.GetFileNameWithoutExtension(text) + ".texts.json");
				}
				return null;
			}

			private static Stream FindResource(Assembly assembly, string resource)
			{
				Stream manifestResourceStream = assembly.GetManifestResourceStream(resource);
				if (manifestResourceStream != null)
				{
					return manifestResourceStream;
				}
				string[] manifestResourceNames = assembly.GetManifestResourceNames();
				foreach (string text in manifestResourceNames)
				{
					if (text.EndsWith("." + resource, StringComparison.OrdinalIgnoreCase))
					{
						return assembly.GetManifestResourceStream(text);
					}
				}
				return null;
			}
		}

		public static class Balance
		{
			public static IReadOnlyList<BalanceMod> Mods => GameBalance.Mods;

			[MethodImpl(MethodImplOptions.NoInlining)]
			public static BalanceMod Register(string key, string title, int priority = 0, string description = null)
			{
				Core.Ensure();
				if (string.IsNullOrWhiteSpace(key))
				{
					throw new ArgumentException("key is required", "key");
				}
				foreach (BalanceMod mod in GameBalance.Mods)
				{
					if (mod.Key == key)
					{
						return mod;
					}
				}
				LobbyRule<bool> lobbyRule = Lobby.Rules.ToggleFor(LobbyMods.IdentifySimulation(Assembly.GetCallingAssembly()), key, title, defaultValue: true, description ?? "This mod's building and technology values. Used only when every player has the mod; otherwise the game's values.");
				BalanceMod balanceMod = new BalanceMod(key, priority, lobbyRule);
				lobbyRule.Changed += delegate
				{
					GameBalance.Recompute("lobby rule " + key);
				};
				GameBalance.Mods.Add(balanceMod);
				GameBalance.Recompute("registered " + key);
				return balanceMod;
			}

			public static BuildingValues Building(BuildingTypeName building)
			{
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				BuildingType[] array = GameBalance.BuildingTypes() ?? Array.Empty<BuildingType>();
				foreach (BuildingType val in array)
				{
					if (val != null && val.name == building)
					{
						return GameBalance.ReadBuilding(((Il2CppObjectBase)val).Pointer);
					}
				}
				return null;
			}

			public static BuildingValues DefaultBuilding(BuildingTypeName building)
			{
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				BuildingType[] array = GameBalance.BuildingTypes() ?? Array.Empty<BuildingType>();
				foreach (BuildingType val in array)
				{
					if (val != null && val.name == building)
					{
						return GameBalance.Original(((Il2CppObjectBase)val).Pointer, GameBalance.ReadBuilding);
					}
				}
				return null;
			}

			public static ResourceValues TechnologyCost(TechnologyName technology)
			{
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				Technology[] array = GameBalance.Technologies() ?? Array.Empty<Technology>();
				foreach (Technology val in array)
				{
					if (val != null && val.name == technology)
					{
						return GameBalance.ReadRes(((Il2CppObjectBase)val).Pointer, 20);
					}
				}
				return null;
			}

			public static ResourceValues DefaultTechnologyCost(TechnologyName technology)
			{
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				Technology[] array = GameBalance.Technologies() ?? Array.Empty<Technology>();
				foreach (Technology val in array)
				{
					if (val != null && val.name == technology)
					{
						return GameBalance.Original(((Il2CppObjectBase)val).Pointer, (IntPtr p) => GameBalance.ReadRes(p, 20));
					}
				}
				return null;
			}
		}

		public static class Units
		{
			public static IReadOnlyList<UnitStatsMod> Mods => UnitStatsRegistry.Mods;

			[MethodImpl(MethodImplOptions.NoInlining)]
			public static UnitStatsMod Register(string key, string title, int priority = 0, string description = null)
			{
				Core.Ensure();
				LobbyMod mod = LobbyMods.IdentifySimulation(Assembly.GetCallingAssembly());
				if (string.IsNullOrWhiteSpace(key))
				{
					throw new ArgumentException("key is required", "key");
				}
				foreach (UnitStatsMod mod2 in UnitStatsRegistry.Mods)
				{
					if (mod2.Key == key)
					{
						return mod2;
					}
				}
				LobbyRule<bool> lobbyRule = Lobby.Rules.ToggleFor(mod, key, title, defaultValue: true, description ?? "This mod's unit stats. Used only when every player has the mod; otherwise the game's values.");
				UnitStatsMod unitStatsMod = new UnitStatsMod(key, priority, lobbyRule);
				lobbyRule.Changed += delegate
				{
					UnitStatsRegistry.Changed();
				};
				UnitStatsRegistry.Mods.Add(unitStatsMod);
				UnitStatsRegistry.Install();
				return unitStatsMod;
			}

			public static void SetCivilizationDefaults(ModCivilization civilization, Type unit, UnitStatChange values)
			{
				//IL_003a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0040: Expected I4, but got Unknown
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Expected I4, but got Unknown
				Core.Ensure();
				if (civilization == null)
				{
					throw new ArgumentNullException("civilization");
				}
				if (values == null)
				{
					UnitStatsRegistry.CivDefaults.Remove((civilization.Id, (int)unit));
				}
				else
				{
					UnitStatsRegistry.CivDefaults[(civilization.Id, (int)unit)] = values;
				}
				UnitStatsRegistry.Changed();
				UnitStatsRegistry.Install();
			}

			public static UnitStatChange CivilizationDefaults(int civilization, Type unit)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Expected I4, but got Unknown
				if (!UnitStatsRegistry.CivDefaults.TryGetValue((civilization, (int)unit), out var value))
				{
					return null;
				}
				return value;
			}

			public static UnitStatValues Default(Type unit)
			{
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				UnitStats val = Asset();
				if ((Object)(object)val == (Object)null)
				{
					return null;
				}
				UnitStatsRegistry.Bypass = true;
				try
				{
					return UnitStatsRegistry.Read(val[unit]);
				}
				finally
				{
					UnitStatsRegistry.Bypass = false;
				}
			}

			public static UnitStatValues Effective(int civilization, Type unit)
			{
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				UnitStats val = Asset();
				if ((Object)(object)val == (Object)null)
				{
					return null;
				}
				int contextCiv = UnitStatsRegistry.ContextCiv;
				UnitStatsRegistry.SetContext(civilization);
				try
				{
					return UnitStatsRegistry.Read(val[unit]);
				}
				finally
				{
					UnitStatsRegistry.ContextCiv = contextCiv;
				}
			}

			private static UnitStats Asset()
			{
				Il2CppArrayBase<UnitStats> val = Resources.FindObjectsOfTypeAll<UnitStats>();
				if (val.Length <= 0)
				{
					return null;
				}
				return val[0];
			}
		}

		public static void Init()
		{
			Core.Ensure();
		}
	}
	internal static class BuildingLimitHooks
	{
		private static bool _installed;

		private static Dictionary<int, int> _upgrades;

		private static IntPtr _grid;

		private static int _frame = -1;

		private static int _total = -1;

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

		private static bool _inBar;

		private static int _barFrame = -1;

		internal static void Install()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Expected O, but got Unknown
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Expected O, but got Unknown
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			//IL_00d4: Expected O, but got Unknown
			if (_installed)
			{
				return;
			}
			_installed = true;
			try
			{
				Harmony val = new Harmony("DiceModders.ModCore.buildinglimits");
				Patch(val, typeof(BuildData), "CanBuildType", "CanBuildPostfix", prefix: false);
				Patch(val, typeof(BuildData), "PlaceBuildingBulk", "BulkPrefix", prefix: true);
				Patch(val, typeof(BuildData), "CanAfford", "CanAffordPostfix", prefix: false);
				Patch(val, typeof(BuildData), "CanAffordBulk", "CanAffordBulkPostfix", prefix: false);
				Patch(val, typeof(BuildInterface), "RefreshBuildingButtons", "ButtonsPrefix", prefix: true);
				Patch(val, typeof(BuildInterface), "RefreshBuildingButtons", "ButtonsPostfix", prefix: false);
				Patch(val, typeof(BuildInterface), "TooltipText", "TooltipPostfix", prefix: false);
				CoreLog.Info("buildings: limits are checked");
			}
			catch (Exception ex)
			{
				CoreLog.Error("buildings: limit hooks failed, building limits will not work: " + ex);
			}
		}

		private static void Patch(Harmony h, Type type, string method, string patch, bool prefix)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(type, method, (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				CoreLog.Error("buildings: " + type.Name + "." + method + " not found");
			}
			else
			{
				HarmonyMethod val = new HarmonyMethod(typeof(BuildingLimitHooks), patch, (Type[])null);
				if (prefix)
				{
					h.Patch((MethodBase)methodInfo, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				else
				{
					h.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
		}

		private static Dictionary<int, int> Upgrades()
		{
			if (_upgrades != null)
			{
				return _upgrades;
			}
			Dictionary<int, int> map = new Dictionary<int, int>();
			foreach (Technologies item in Resources.FindObjectsOfTypeAll<Technologies>())
			{
				Take((Technology)(object)item.upgradeGuardTower);
				Il2CppReferenceArray<Technology> values = item.Values;
				if (values == null)
				{
					continue;
				}
				foreach (Technology item2 in (Il2CppArrayBase<Technology>)(object)values)
				{
					Take(item2);
				}
			}
			if (map.Count == 0)
			{
				return null;
			}
			return _upgrades = map;
			void Take(Technology t)
			{
				//IL_0011: Unknown result type (might be due to invalid IL or missing references)
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				//IL_0025: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Expected I4, but got Unknown
				//IL_0035: Expected I4, but got Unknown
				ReplaceBuildings val = ((t != null) ? ((Il2CppObjectBase)t).TryCast<ReplaceBuildings>() : null);
				if (val != null && val.upgradedBuildingType != val.baseBuildingType)
				{
					map[(int)val.upgradedBuildingType] = (int)val.baseBuildingType;
				}
			}
		}

		internal static BuildingTypeName BaseOf(BuildingTypeName type)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected I4, but got Unknown
			Dictionary<int, int> dictionary = Upgrades();
			if (dictionary == null || !dictionary.TryGetValue((int)type, out var value))
			{
				return type;
			}
			return (BuildingTypeName)value;
		}

		internal static int Count(IslandGrid grid, BuildingTypeName baseType)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected I4, but got Unknown
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected I4, but got Unknown
			if ((Object)(object)grid == (Object)null)
			{
				return 0;
			}
			Dictionary<int, int> dictionary = Upgrades();
			int num = 0;
			int num2 = (int)baseType;
			Enumerator<Id, Building> enumerator = grid.Buildings.GetEnumerator();
			while (enumerator.MoveNext())
			{
				BuildingType type = enumerator.Current.type;
				if (type != null)
				{
					int num3 = (int)type.name;
					if (dictionary != null && dictionary.TryGetValue(num3, out var value))
					{
						num3 = value;
					}
					if (num3 == num2)
					{
						num++;
					}
				}
			}
			return num;
		}

		private static int CountForScreen(IslandGrid grid, BuildingTypeName baseType)
		{
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Expected I4, but got Unknown
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Expected I4, but got Unknown
			if ((Object)(object)grid == (Object)null)
			{
				return 0;
			}
			int count = grid.Buildings.Count;
			if (((Il2CppObjectBase)grid).Pointer != _grid || Time.frameCount != _frame || count != _total)
			{
				_grid = ((Il2CppObjectBase)grid).Pointer;
				_frame = Time.frameCount;
				_total = count;
				Counted.Clear();
				Dictionary<int, int> dictionary = Upgrades();
				Enumerator<Id, Building> enumerator = grid.Buildings.GetEnumerator();
				while (enumerator.MoveNext())
				{
					BuildingType type = enumerator.Current.type;
					if (type != null)
					{
						int key = (int)type.name;
						if (dictionary != null && dictionary.TryGetValue(key, out var value))
						{
							key = value;
						}
						Counted[key] = ((!Counted.TryGetValue(key, out var value2)) ? 1 : (value2 + 1));
					}
				}
			}
			if (!Counted.TryGetValue((int)baseType, out var value3))
			{
				return 0;
			}
			return value3;
		}

		public static void CanBuildPostfix(BuildData __instance, BuildingType __0, ref bool __result)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!__result || __0 == null)
				{
					return;
				}
				int num = ModCore.Buildings.LimitOf(__0.name);
				if (num > 0)
				{
					Island island = ((PhaseData<BuildData, BuildIslandState>)(object)__instance).Island;
					if (Count((island != null) ? island.grid : null, BaseOf(__0.name)) >= num)
					{
						__result = false;
					}
				}
			}
			catch (Exception ex)
			{
				CoreLog.Once("buildings:check", "buildings: limit check failed: " + ex);
			}
		}

		public static bool BulkPrefix(BuildData __instance, Il2CppReferenceArray<Building> __0, ref bool __result)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (__0 == null || ((Il2CppArrayBase<Building>)(object)__0).Length == 0)
				{
					return true;
				}
				BuildingType type = ((Il2CppArrayBase<Building>)(object)__0)[0].type;
				if (type == null)
				{
					return true;
				}
				int num = ModCore.Buildings.LimitOf(type.name);
				if (num > 0)
				{
					Island island = ((PhaseData<BuildData, BuildIslandState>)(object)__instance).Island;
					if (Count((island != null) ? island.grid : null, BaseOf(type.name)) + ((Il2CppArrayBase<Building>)(object)__0).Length > num)
					{
						__result = false;
						return false;
					}
				}
				return true;
			}
			catch (Exception ex)
			{
				CoreLog.Once("buildings:bulk", "buildings: wall limit check failed: " + ex);
				return true;
			}
		}

		public static void CanAffordPostfix(BuildData __instance, BuildingType __0, ref bool __result)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!__result || __0 == null || (_inBar && _barFrame == Time.frameCount))
				{
					return;
				}
				int num = ModCore.Buildings.LimitOf(__0.name);
				if (num > 0)
				{
					Island island = ((PhaseData<BuildData, BuildIslandState>)(object)__instance).Island;
					if (CountForScreen((island != null) ? island.grid : null, BaseOf(__0.name)) >= num)
					{
						__result = false;
					}
				}
			}
			catch (Exception ex)
			{
				CoreLog.Once("buildings:afford", "buildings: limit check (keep placing) failed: " + ex);
			}
		}

		public static void ButtonsPrefix()
		{
			_inBar = true;
			_barFrame = Time.frameCount;
		}

		public static void CanAffordBulkPostfix(BuildData __instance, BuildingType __0, int __1, ref bool __result)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!__result || __0 == null)
				{
					return;
				}
				int num = ModCore.Buildings.LimitOf(__0.name);
				if (num > 0)
				{
					Island island = ((PhaseData<BuildData, BuildIslandState>)(object)__instance).Island;
					if (CountForScreen((island != null) ? island.grid : null, BaseOf(__0.name)) + Math.Max(1, __1) > num)
					{
						__result = false;
					}
				}
			}
			catch (Exception ex)
			{
				CoreLog.Once("buildings:affordbulk", "buildings: wall limit check failed: " + ex);
			}
		}

		public static void ButtonsPostfix(BuildInterface __instance)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			_inBar = false;
			try
			{
				BuildData data = ((PhaseInterface<BuildData, BuildIslandState>)(object)__instance).Data;
				object obj;
				if (data == null)
				{
					obj = null;
				}
				else
				{
					Island island = ((PhaseData<BuildData, BuildIslandState>)(object)data).Island;
					obj = ((island != null) ? island.grid : null);
				}
				IslandGrid val = (IslandGrid)obj;
				Il2CppReferenceArray<BuildingType> buildableBuildingTypes = __instance.buildableBuildingTypes;
				Il2CppReferenceArray<BuildingButton> buildingButtons = __instance.buildingButtons;
				if ((Object)(object)val == (Object)null || buildableBuildingTypes == null || buildingButtons == null)
				{
					return;
				}
				for (int i = 0; i < ((Il2CppArrayBase<BuildingType>)(object)buildableBuildingTypes).Length && i < ((Il2CppArrayBase<BuildingButton>)(object)buildingButtons).Length; i++)
				{
					BuildingType val2 = ((Il2CppArrayBase<BuildingType>)(object)buildableBuildingTypes)[i];
					if (val2 == null)
					{
						continue;
					}
					int num = ModCore.Buildings.LimitOf(val2.name);
					if (num > 0 && CountForScreen(val, BaseOf(val2.name)) >= num)
					{
						BuildingButton obj2 = ((Il2CppArrayBase<BuildingButton>)(object)buildingButtons)[i];
						ButtonIcon val3 = ((obj2 != null) ? obj2.button : null);
						if ((Object)(object)val3 != (Object)null)
						{
							((BaseButton)val3).Interactable = false;
						}
					}
				}
			}
			catch (Exception ex)
			{
				CoreLog.Once("buildings:bar", "buildings: greying the build bar failed: " + ex);
			}
		}

		public static void TooltipPostfix(BuildInterface __instance, BuildingType __0, ref StructuredText __result)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (__0 == null || __result == null)
				{
					return;
				}
				int num = ModCore.Buildings.LimitOf(__0.name);
				if (num > 0)
				{
					BuildData data = ((PhaseInterface<BuildData, BuildIslandState>)(object)__instance).Data;
					object grid;
					if (data == null)
					{
						grid = null;
					}
					else
					{
						Island island = ((PhaseData<BuildData, BuildIslandState>)(object)data).Island;
						grid = ((island != null) ? island.grid : null);
					}
					int num2 = CountForScreen((IslandGrid)grid, BaseOf(__0.name));
					TextSet value;
					string text = ((ModCore.Texts.ByAssembly.TryGetValue(typeof(Core).Assembly.GetName().Name, out value) && value.Has("buildings.limit")) ? value.Get("buildings.limit", num2, num) : ("On this island: " + num2 + " of " + num));
					StructuredText val = new GameText().Text("\n" + text).ToGame();
					__result += val;
				}
			}
			catch (Exception ex)
			{
				CoreLog.Once("buildings:tooltip", "buildings: limit tooltip failed: " + ex.Message);
			}
		}
	}
	internal static class BuildOrders
	{
		internal sealed class Order
		{
			public int Civilization;

			public int Weight;

			public string Strategy;

			public string Name;

			public List<string> Technologies;

			public List<string> Buildings;

			public string Source;

			public string ToText(int civ, IEnumerable<string> techs)
			{
				return $"civilization={civ} weight={Weight} strategy={Strategy} name={Name} [\n technologies [\n {string.Join(" ", techs)}\n ]\n buildings [\n {string.Join(" ", Buildings)}\n ]\n]\n\n";
			}
		}

		private sealed class Added
		{
			public int Civilization;

			public LobbyMod Owner;

			public List<Order> Orders;
		}

		internal static readonly Regex Block = new Regex("\\s*civilization=(\\w+)\\s+weight=(\\d+)\\s+strategy=(\\w+)\\s+name=(\\w+)\\s*\\[\\s*technologies\\s*\\[([^]]*)\\]\\s*buildings\\s*\\[([^]]*)\\]\\s*\\]", RegexOptions.Compiled);

		private static readonly Regex Space = new Regex("\\s+", RegexOptions.Compiled);

		private static readonly List<Added> FromMods = new List<Added>();

		internal static readonly HashSet<int> Loaded = new HashSet<int>();

		private static string _builtInText;

		[ThreadStatic]
		private static string _realPath;

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

		public static IEnumerable<string> Split(string text)
		{
			return from s in Space.Split(text.Trim())
				where s.Length > 0
				select s;
		}

		internal static List<Order> Parse(string text, string source, Action<string> bad)
		{
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Expected I4, but got Unknown
			List<Order> list = new List<Order>();
			foreach (Match item in Block.Matches(text ?? ""))
			{
				string text2 = source + " '" + item.Groups[4].Value + "'";
				if (!int.TryParse(item.Groups[2].Value, out var result) || result <= 0)
				{
					bad(text2 + ": weight must be a whole number above 0");
					continue;
				}
				if (!Enum.TryParse<AIStrategy>(item.Groups[3].Value, out AIStrategy _) || int.TryParse(item.Groups[3].Value, out var _))
				{
					bad(text2 + ": unknown strategy " + item.Groups[3].Value + " (" + string.Join(", ", Enum.GetNames(typeof(AIStrategy))) + ")");
					continue;
				}
				List<string> list2 = Split(item.Groups[5].Value).ToList();
				TechnologyName result5;
				int result6;
				List<string> list3 = list2.Where((string t) => !Enum.TryParse<TechnologyName>(t, out result5) || int.TryParse(t, out result6)).ToList();
				if (list3.Count > 0)
				{
					bad(text2 + ": unknown technolog" + ((list3.Count == 1) ? "y " : "ies ") + string.Join(", ", list3));
					continue;
				}
				int civilization = -1;
				if (Enum.TryParse<Civilization>(item.Groups[1].Value, out Civilization result4))
				{
					civilization = (int)result4;
				}
				list.Add(new Order
				{
					Civilization = civilization,
					Weight = result,
					Strategy = item.Groups[3].Value,
					Name = item.Groups[4].Value,
					Technologies = list2,
					Buildings = Split(item.Groups[6].Value).ToList(),
					Source = source
				});
			}
			return list;
		}

		public static int Add(int civilization, string text, LobbyMod owner)
		{
			string text2 = (owner?.Name ?? "a mod") + " build order";
			List<Order> list = Parse(text, text2, delegate(string why)
			{
				CoreLog.Warn("build order left out: " + why);
			});
			if (list.Count == 0)
			{
				CoreLog.Warn(text2 + " for civilization " + civilization + ": no usable block (format: civilization=X weight=N strategy=MILITARY name=x [ technologies [ ... ] buildings [ ... ] ])");
			}
			foreach (Order item in list)
			{
				item.Civilization = civilization;
			}
			FromMods.RemoveAll((Added a) => a.Civilization == civilization && a.Owner == owner);
			if (list.Count > 0)
			{
				FromMods.Add(new Added
				{
					Civilization = civilization,
					Owner = owner,
					Orders = list
				});
			}
			ResetLoaded();
			return list.Count;
		}

		public static void Remove(int civilization, LobbyMod owner)
		{
			if (FromMods.RemoveAll((Added a) => a.Civilization == civilization && a.Owner == owner) > 0)
			{
				ResetLoaded();
			}
		}

		internal static void ResetLoaded()
		{
			try
			{
				foreach (AIPlay item in Object.FindObjectsOfType<AIPlay>())
				{
					if ((Object)(object)item != (Object)null)
					{
						item.buildOrders = null;
					}
				}
			}
			catch (Exception ex)
			{
				CoreLog.Once("bo:reset", "build orders reset: " + ex.Message);
			}
		}

		private static bool Needed(out TechTree[] builtInTrees)
		{
			builtInTrees = (TechTree[])(object)new TechTree[5];
			bool result = CivilizationRegistry.All.Count > 0 || FromMods.Count > 0;
			for (int i = 0; i < 5; i++)
			{
				if (BuiltInChanges.TryGetTree(i, out var tree))
				{
					builtInTrees[i] = tree;
					result = true;
				}
			}
			return result;
		}

		private static string BuiltInText()
		{
			if (_builtInText != null)
			{
				return _builtInText;
			}
			PropertyInfo[] properties = typeof(AIPlay).GetProperties(BindingFlags.Static | BindingFlags.Public);
			foreach (PropertyInfo propertyInfo in properties)
			{
				if (propertyInfo.PropertyType == typeof(string) && propertyInfo.GetValue(null) is string text && text.Contains("civilization="))
				{
					return _builtInText = text;
				}
			}
			return null;
		}

		internal static void Prepare(AIPlay ai)
		{
			using (CoreLog.Slow("build orders"))
			{
				Loaded.Clear();
				string customBuildOrdersPath = ai.customBuildOrdersPath;
				string text;
				string source;
				if (!string.IsNullOrEmpty(customBuildOrdersPath) && File.Exists(customBuildOrdersPath))
				{
					text = File.ReadAllText(customBuildOrdersPath);
					source = "custom-build-orders.txt";
				}
				else
				{
					if (SteamworksInit.IsSteamAndDemo)
					{
						return;
					}
					Interface val = Object.FindObjectOfType<Interface>();
					if ((Object)(object)val == (Object)null || val.IsTraining)
					{
						return;
					}
					text = BuiltInText();
					source = "the game's build orders";
					if (text == null)
					{
						return;
					}
				}
				List<string> problems = new List<string>();
				List<Order> list = Parse(text, source, problems.Add);
				if (!Needed(out var builtInTrees) && problems.Count == 0 && list.All((Order o) => o.Civilization >= 0 && Valid(ai, o, problems)))
				{
					return;
				}
				Technologies val2 = ((IEnumerable<Technologies>)Resources.FindObjectsOfTypeAll<Technologies>()).FirstOrDefault();
				StringBuilder stringBuilder = new StringBuilder();
				Dictionary<int, List<Order>> dictionary = new Dictionary<int, List<Order>>();
				foreach (Order item in list)
				{
					if (item.Civilization < 0)
					{
						problems.Add(item.Source + " '" + item.Name + "': unknown civilization");
					}
					else if (Valid(ai, item, problems))
					{
						if (!dictionary.TryGetValue(item.Civilization, out var value))
						{
							value = (dictionary[item.Civilization] = new List<Order>());
						}
						value.Add(item);
						TechTree val3 = ((item.Civilization < 5) ? builtInTrees[item.Civilization] : null);
						stringBuilder.Append(item.ToText(item.Civilization, ((Object)(object)val3 != (Object)null) ? Arrange(item.Technologies, val3) : item.Technologies));
					}
				}
				foreach (Added item2 in FromMods.Where((Added a) => a.Civilization >= 0 && a.Civilization < 5))
				{
					TechTree val4 = builtInTrees[item2.Civilization] ?? ((val2 != null) ? val2.TechTree((Civilization)item2.Civilization) : null);
					foreach (Order order in item2.Orders)
					{
						if (Valid(ai, order, problems))
						{
							stringBuilder.Append(order.ToText(item2.Civilization, ((Object)(object)val4 != (Object)null) ? Arrange(order.Technologies, val4) : order.Technologies));
						}
					}
				}
				foreach (ModCivilization civ in CivilizationRegistry.All)
				{
					CivilizationRegistry.TryGetTree(civ.Id, out var tree);
					if (tree == null)
					{
						tree = ((val2 != null) ? val2.TechTree((Civilization)civ.SkinsLike) : null);
					}
					HashSet<string> hashSet = new HashSet<string>();
					foreach (Added item3 in FromMods.Where((Added a) => a.Civilization == civ.Id))
					{
						foreach (Order order2 in item3.Orders)
						{
							if (Valid(ai, order2, problems))
							{
								stringBuilder.Append(order2.ToText(civ.Id, ((Object)(object)tree != (Object)null) ? Arrange(order2.Technologies, tree) : order2.Technologies));
								hashSet.Add(order2.Strategy);
							}
						}
					}
					if (dictionary.TryGetValue(civ.SkinsLike, out var value2))
					{
						foreach (Order item4 in value2)
						{
							if (!hashSet.Contains(item4.Strategy))
							{
								stringBuilder.Append(item4.ToText(civ.Id, ((Object)(object)tree != (Object)null) ? Arrange(item4.Technologies, tree) : item4.Technologies));
								hashSet.Add("look:" + item4.Strategy);
							}
						}
					}
					if (hashSet.Count > 0)
					{
						Loaded.Add(civ.Id);
					}
				}
				foreach (string item5 in problems.Distinct())
				{
					CoreLog.Once("bo:" + item5, "build order left out: " + item5);
				}
				string text2 = DiskCache.PathFor("ModCore", "build-orders.txt");
				File.WriteAllText(text2, stringBuilder.ToString());
				_realPath = customBuildOrdersPath;
				ai.customBuildOrdersPath = text2;
			}
		}

		internal static void Restore(AIPlay ai)
		{
			if (_realPath != null || !(ai.customBuildOrdersPath != DiskCache.PathFor("ModCore", "build-orders.txt")))
			{
				ai.customBuildOrdersPath = _realPath;
				_realPath = null;
			}
		}

		private static bool Valid(AIPlay ai, Order o, List<string> problems)
		{
			foreach (string building in o.Buildings)
			{
				if (!KnownBuildings.TryGetValue(building, out var value))
				{
					try
					{
						value = ai.ParseBuildingType(building) != null;
					}
					catch
					{
						value = false;
					}
					KnownBuildings[building] = value;
				}
				if (!value)
				{
					problems.Add(o.Source + " '" + o.Name + "': unknown building " + building);
					return false;
				}
			}
			return true;
		}

		internal static List<string> Arrange(IEnumerable<string> wanted, TechTree tree)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<string, string[]> deps = new Dictionary<string, string[]>();
			List<string> list = new List<string>();
			Dictionary<TechnologyName, Technology> dictionary = new Dictionary<TechnologyName, Technology>();
			Technology[] array = GameBalance.Technologies() ?? Array.Empty<Technology>();
			foreach (Technology val in array)
			{
				if (val != null)
				{
					dictionary[val.name] = val;
				}
			}
			foreach (Slot item in (Il2CppArrayBase<Slot>)(object)tree.slots)
			{
				TechnologyName? val2 = ((item != null) ? new TechnologyName?(item.technology) : ((TechnologyName?)null));
				if (!val2.HasValue || !dictionary.TryGetValue(val2.Value, out var value))
				{
					continue;
				}
				string text = ((object)val2.Value/*cast due to .constrained prefix*/).ToString();
				if (!deps.ContainsKey(text))
				{
					list.Add(text);
					deps[text] = (from d in (IEnumerable<Technology>)(tree.GetDependencies(value) ?? new Il2CppReferenceArray<Technology>(0L))
						where d != null
						select ((object)d.name/*cast due to .constrained prefix*/).ToString()).ToArray();
				}
			}
			List<string> queue = wanted.Where(deps.ContainsKey).Distinct().ToList();
			queue.AddRange(list.Where((string n) => !queue.Contains(n)));
			List<string> list2 = new List<string>();
			HashSet<string> learnt = new HashSet<string>();
			while (queue.Count > 0)
			{
				int num = queue.FindIndex((string n) => deps[n].Length == 0 || deps[n].Any(learnt.Contains));
				if (num < 0)
				{
					break;
				}
				learnt.Add(queue[num]);
				list2.Add(queue[num]);
				queue.RemoveAt(num);
			}
			return list2;
		}
	}
	[HarmonyPatch(typeof(AIPlay), "InitBuildOrders")]
	internal static class BuildOrdersHook
	{
		[HarmonyPrefix]
		public static void Prefix(AIPlay __instance)
		{
			try
			{
				BuildOrders.Prepare(__instance);
			}
			catch (Exception ex)
			{
				CoreLog.Error("build orders: could not check them, the game reads its own: " + ex);
			}
		}

		[HarmonyFinalizer]
		public static Exception Finalizer(AIPlay __instance, Exception __exception)
		{
			try
			{
				BuildOrders.Restore(__instance);
			}
			catch (Exception ex)
			{
				CoreLog.Once("bo:restore", "build orders restore: " + ex.Message);
			}
			if (__exception != null)
			{
				CoreLog.Error("the game could not read its AI build orders (the AI cannot choose one): " + __exception.Message);
			}
			return __exception;
		}
	}
	internal static class BuiltInChanges
	{
		internal sealed class TreeReplacement
		{
			public Func<TechTree> Provider;

			public LobbyRule<bool> Rule;

			public TechTree Cached;

			public bool? Frozen;
		}

		internal static readonly TreeReplacement[] Trees = new TreeReplacement[5];

		public static bool TryGetTree(int id, out TechTree tree)
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			tree = null;
			if (id < 0 || id >= Trees.Length)
			{
				return false;
			}
			TreeReplacement treeReplacement = Trees[id];
			if (treeReplacement == null || !Active(treeReplacement))
			{
				return false;
			}
			if ((Object)(object)treeReplacement.Cached == (Object)null)
			{
				try
				{
					treeReplacement.Cached = treeReplacement.Provider();
				}
				catch (Exception ex)
				{
					CoreLog.Once("builtin:tree:" + id, "replacement tech tree of " + ((object)(Civilization)id/*cast due to .constrained prefix*/).ToString() + " failed: " + ex);
				}
			}
			tree = treeReplacement.Cached;
			return (Object)(object)tree != (Object)null;
		}

		private static bool Active(TreeReplacement r)
		{
			if (!ModSwitches.IsOn(r.Rule.ModId))
			{
				r.Frozen = null;
				return false;
			}
			if (!LobbyState.InLobby)
			{
				r.Frozen = null;
				return r.Rule.Value;
			}
			if (LobbyState.MatchRunning)
			{
				bool valueOrDefault = r.Frozen == true;
				if (!r.Frozen.HasValue)
				{
					valueOrDefault = Live(r);
					r.Frozen = valueOrDefault;
					return valueOrDefault;
				}
				return valueOrDefault;
			}
			r.Frozen = null;
			return Live(r);
		}

		private static bool Live(TreeReplacement r)
		{
			if (r.Rule.Value)
			{
				return EveryoneHas(r.Rule);
			}
			return false;
		}

		internal static bool EveryoneHas(ILobbyRule rule)
		{
			string tag = LobbyRuleRegistry.TagOf(rule);
			foreach (LobbyMember member in LobbyState.Members)
			{
				if (!member.IsLocal && !LobbyState.MemberHasKey(member.SteamId, tag))
				{
					return false;
				}
			}
			return true;
		}
	}
	internal static class CivilizationHooks
	{
		private static bool _installed;

		public static void Install()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Expected O, but got Unknown
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Expected O, but got Unknown
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Expected O, but got Unknown
			//IL_00af: Expected O, but got Unknown
			if (_installed)
			{
				return;
			}
			_installed = true;
			try
			{
				Harmony val = new Harmony("DiceModders.ModCore.civilizations");
				val.PatchAll(typeof(TechTreeLookupHook));
				val.PatchAll(typeof(PlayerSkinsCivilizationHook));
				val.PatchAll(typeof(PlayerSkinsCloneHook));
				val.PatchAll(typeof(NextCivilizationHook));
				val.PatchAll(typeof(AiBuildOrderHook));
				val.PatchAll(typeof(BuildOrdersHook));
				val.PatchAll(typeof(StatisticsTechTreeHook));
				val.PatchAll(typeof(StatisticsLearnableHook));
				PlayerSkinsLookHooks.Install(val);
				CivilizationText.Install(val);
				IslandColours.Install(val);
				GameData.Install(val);
			}
			catch (Exception ex)
			{
				CoreLog.Error("civilization hooks failed: " + ex);
			}
		}
	}
	[HarmonyPatch(typeof(Technologies), "TechTree")]
	internal static class TechTreeLookupHook
	{
		[HarmonyPrefix]
		public static bool Prefix(Technologies __instance, Civilization civilization, ref TechTree __result)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Expected I4, but got Unknown
			try
			{
				int num = (int)civilization;
				if (num >= 0 && num <= 4)
				{
					if (BuiltInChanges.TryGetTree(num, out var tree))
					{
						__result = tree;
						return false;
					}
					return true;
				}
				if (CivilizationRegistry.TryGetTree(num, out var tree2))
				{
					__result = tree2;
					return false;
				}
				if (CivilizationRegistry.TryGetSkinsLike(num, out var like))
				{
					__result = __instance.TechTree((Civilization)like);
					return false;
				}
			}
			catch (Exception ex)
			{
				CoreLog.Once("civ:tree", "tech tree hook: " + ex);
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Player), "NextCivilization")]
	internal static class NextCivilizationHook
	{
		private static bool IsReady(Player p)
		{
			try
			{
				return p.startGameReady != null && p.startGameReady.Value;
			}
			catch
			{
				return false;
			}
		}

		[HarmonyPrefix]
		public static bool Prefix(Player __instance)
		{
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Expected I4, but got Unknown
			//IL_039e: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a5: Expected O, but got Unknown
			//IL_02bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c7: Invalid comparison between Unknown and I4
			//IL_0329: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				CoreLog.Info("civilization cycle: castle clicked (server " + ((NetworkedBehaviour)__instance).IsServer + ", ready " + IsReady(__instance) + ", mod civilizations " + CivilizationRegistry.All.Count + ")");
				if (!((NetworkedBehaviour)__instance).IsServer)
				{
					return true;
				}
				List<ModCivilization> list = new List<ModCivilization>(CivilizationRegistry.All);
				if (list.Count == 0)
				{
					return true;
				}
				List<ModCivilization> mods = list.FindAll((ModCivilization c) => LobbyState.EveryoneHasCivilization(c));
				if (mods.Count < list.Count)
				{
					CoreLog.Once("civ:missing:" + mods.Count + "/" + list.Count, $"civilization cycle: {list.Count - mods.Count} mod civilization(s) skipped, a lobby member does not have them " + "in the same version: " + string.Join(", ", list.FindAll((ModCivilization c) => !mods.Contains(c)).ConvertAll((ModCivilization c) => c.Name)));
				}
				GameState gameState = __instance.GameState;
				if ((Object)(object)gameState != (Object)null && gameState.GameStarted)
				{
					return true;
				}
				PlayerSkins skins = __instance.Skins;
				if (skins == null)
				{
					return true;
				}
				int previous = (int)skins.civilization;
				int num = -1;
				for (int num2 = 0; num2 < mods.Count; num2++)
				{
					if (mods[num2].Id == previous)
					{
						num = num2;
					}
				}
				if (mods.Count == 0)
				{
					return true;
				}
				if (num < 0 && list.Exists((ModCivilization c) => c.Id == previous))
				{
					CoreLog.Info("civilization cycle: on a mod civilization somebody lacks, back to the game's cycle");
					return true;
				}
				int num3 = -1;
				if (num >= 0)
				{
					if (num + 1 < mods.Count)
					{
						num3 = mods[num + 1].Id;
					}
				}
				else
				{
					PlayerInventory inventory = __instance.Inventory;
					Il2CppStructArray<Civilization> val = ((inventory != null) ? inventory.UnlockedCivilizations : null);
					if (val != null && ((Il2CppArrayBase<Civilization>)(object)val).Length > 0 && (int)((Il2CppArrayBase<Civilization>)(object)val)[((Il2CppArrayBase<Civilization>)(object)val).Length - 1] == previous)
					{
						num3 = mods[0].Id;
					}
					CoreLog.Info($"civilization cycle: on {previous}, last unlocked = {((val == null || ((Il2CppArrayBase<Civilization>)(object)val).Length <= 0) ? (-1) : ((int)((Il2CppArrayBase<Civilization>)(object)val)[((Il2CppArrayBase<Civilization>)(object)val).Length - 1]))}" + ((num3 >= 0) ? $", next = mod civilization {num3}" : ", the game's own next"));
				}
				if (num3 < 0)
				{
					return true;
				}
				if (!CivilizationRegistry.TryGetSkinsLike(num3, out var like))
				{
					return true;
				}
				PlayerSkins val2 = new PlayerSkins((Civilization)like, __instance.skinRegistry);
				val2.civilization = (Civilization)num3;
				__instance.skins.Value = val2;
				CoreLog.Trace("castle click: mod civilization " + num3 + " (looks like " + like + ")");
				return false;
			}
			catch (Exception ex)
			{
				CoreLog.Once("civ:next", "castle click hook: " + ex.Message);
			}
			return true;
		}
	}
	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	internal static class PlayerSkinsCivilizationHook
	{
		private static bool _busy;

		[HarmonyPrefix]
		public static bool Prefix(PlayerSkins __instance, Civilization value)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected I4, but got Unknown
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			if (_busy)
			{
				return true;
			}
			try
			{
				int num = (int)value;
				if (num >= 0 && num <= 4)
				{
					return true;
				}
				if (!CivilizationRegistry.TryGetSkinsLike(num, out var like))
				{
					return true;
				}
				_busy = true;
				try
				{
					__instance.Civilization = (Civilization)like;
					__instance.civilization = value;
				}
				finally
				{
					_busy = false;
				}
				return false;
			}
			catch (Exception ex)
			{
				CoreLog.Once("civ:skins", "civilization setter hook: " + ex);
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(PlayerSkins), "Clone")]
	internal static class PlayerSkinsCloneHook
	{
		[HarmonyPrefix]
		public static bool Prefix(PlayerSkins __instance, ref PlayerSkins __result)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected I4, but got Unknown
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			try
			{
				int num = (int)__instance.civilization;
				if (num >= 0 && num <= 4)
				{
					return true;
				}
				if (!CivilizationRegistry.TryGetSkinsLike(num, out var like))
				{
					return true;
				}
				PlayerSkins val = new PlayerSkins((Civilization)like, __instance.skinRegistry);
				val.civilization = (Civilization)num;
				__result = val;
				return false;
			}
			catch (Exception ex)
			{
				CoreLog.Once("civ:clone", "cloning skins: " + ex.Message);
			}
			return true;
		}
	}
	internal static class PlayerSkinsLookHooks
	{
		private static readonly string[] VisualGetters = new string[5] { "GetBuildingVisualPrefab", "GetInnerCliffVisualHubPrefab", "GetNatureVisualHubPrefab", "GetShipVisualPrefab", "GetUnitVisualPrefab" };

		public static int RealId = -1;

		public static void Install(Harmony harmony)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Expected O, but got Unknown
			//IL_015f: 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_0181: Expected O, but got Unknown
			//IL_0181: Expected O, but got Unknown
			try
			{
				Type? typeFromHandle = typeof(PlayerSkinsSerialization);
				MethodInfo methodInfo = AccessTools.Method(typeFromHandle, "ReadPlayerSkins", (Type[])null, (Type[])null);
				if (methodInfo != null)
				{
					harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(PlayerSkinsLookHooks), "ReadPlayerSkinsPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				else
				{
					CoreLog.Warn("PlayerSkinsSerialization.ReadPlayerSkins not found");
				}
				MethodInfo methodInfo2 = null;
				foreach (MethodInfo declaredMethod in AccessTools.GetDeclaredMethods(typeFromHandle))
				{
					if (declaredMethod.Name.Contains("OnEnable") && declaredMethod.Name.Contains("b__5_1"))
					{
						methodInfo2 = declaredMethod;
						break;
					}
				}
				if (methodInfo2 != null)
				{
					harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(PlayerSkinsLookHooks), "ReadStreamPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				else
				{
					CoreLog.Warn("PlayerSkinsSerialization stream reader not found; a civilization number from the network may throw");
				}
			}
			catch (Exception ex)
			{
				CoreLog.Error("PlayerSkins reader hooks failed: " + ex);
			}
			string[] visualGetters = VisualGetters;
			foreach (string text in visualGetters)
			{
				try
				{
					MethodInfo methodInfo3 = AccessTools.Method(typeof(PlayerSkins), text, (Type[])null, (Type[])null);
					if (methodInfo3 == null)
					{
						CoreLog.Warn("PlayerSkins." + text + " not found");
					}
					else
					{
						harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(typeof(PlayerSkinsLookHooks), "LookupPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(PlayerSkinsLookHooks), "LookupFinalizer", (Type[])null), (HarmonyMethod)null);
					}
				}
				catch (Exception ex2)
				{
					CoreLog.Error("PlayerSkins." + text + " hook failed: " + ex2);
				}
			}
			CivilizationSkinHooks.Install(harmony);
		}

		public static bool ReadPlayerSkinsPrefix(PlayerSkinsSerialization __instance, BitReader reader, ref PlayerSkins __result)
		{
			try
			{
				__result = Build(__instance, reader.ReadSByte());
				return false;
			}
			catch (Exception ex)
			{
				CoreLog.Once("civ:read", "reading skins: " + ex.Message);
				return true;
			}
		}

		public static bool ReadStreamPrefix(PlayerSkinsSerialization __instance, Stream stream, ref PlayerSkins __result)
		{
			try
			{
				PooledBitReader val = PooledBitReader.Get(stream);
				try
				{
					__result = Build(__instance, ((BitReader)val).ReadSByte());
				}
				finally
				{
					val.Dispose();
				}
				return false;
			}
			catch (Exception ex)
			{
				CoreLog.Once("civ:readstream", "reading skins: " + ex.Message);
				return true;
			}
		}

		private static PlayerSkins Build(PlayerSkinsSerialization serializer, int id)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			int num = id;
			int num2 = -1;
			if (id < 0 || id > 4)
			{
				if (CivilizationRegistry.TryGetSkinsLike(id, out var like))
				{
					num = like;
					num2 = id;
				}
				else
				{
					num = 0;
					CoreLog.Once("civ:unknown" + id, $"civilization {id} is not known here (a mod the host has is missing); using the first civilization");
				}
			}
			PlayerSkins val = new PlayerSkins((Civilization)num, serializer.skinRegistry);
			if (num2 != -1)
			{
				val.civilization = (Civilization)num2;
			}
			return val;
		}

		public static void LookupPrefix(PlayerSkins __instance, out int __state)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Expected I4, but got Unknown
			__state = -1;
			try
			{
				int num = (int)__instance.civilization;
				if ((num < 0 || num > 4) && CivilizationRegistry.TryGetSkinsLike(num, out var like))
				{
					__state = num;
					RealId = num;
					__instance.civilization = (Civilization)like;
				}
			}
			catch (Exception ex)
			{
				CoreLog.Once("civ:look", "skin lookup hook: " + ex.Message);
			}
		}

		public static Exception LookupFinalizer(PlayerSkins __instance, int __state, Exception __exception)
		{
			RealId = -1;
			if (__state >= 0)
			{
				try
				{
					__instance.civilization = (Civilization)__state;
				}
				catch (Exception ex)
				{
					CoreLog.Once("civ:look2", "skin lookup hook: " + ex.Message);
				}
			}
			return __exception;
		}
	}
	internal static class CivilizationGuard
	{
		public static void Run()
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Expected I4, but got Unknown
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Expected O, but got Unknown
			using (CoreLog.Slow("civilization guard"))
			{
				try
				{
					if (!LobbyState.InLobby || !LobbyState.IsHost || LobbyState.RulesFrozen)
					{
						return;
					}
					foreach (Player item in Object.FindObjectsOfType<Player>())
					{
						if ((Object)(object)item == (Object)null || !((NetworkedBehaviour)item).IsServer)
						{
							continue;
						}
						PlayerSkins skins = item.Skins;
						if (skins == null)
						{
							continue;
						}
						int num = (int)skins.civilization;
						if (num >= 5)
						{
							ModCivilization modCivilization = CivilizationRegistry.Find(num);
							if (modCivilization == null || !LobbyState.EveryoneHasCivilization(modCivilization))
							{
								item.skins.Value = new PlayerSkins((Civilization)(modCivilization?.SkinsLike ?? 0), item.skinRegistry);
								CoreLog.Warn((modCivilization != null) ? ("'" + modCivilization.Name + "' is not installed for everybody in the lobby; a player was moved to the civilization it looks like.") : $"civilization {num} was removed; a player was moved to Europe.");
							}
						}
					}
				}
				catch (Exception ex)
				{
					CoreLog.Once("civ:guard", "civilization guard: " + ex.Message);
				}
			}
		}
	}
	[HarmonyPatch(typeof(AIPlay), "SampleBuildOrder")]
	internal static class AiBuildOrderHook
	{
		[HarmonyPrefix]
		public static void Prefix(AIPlay __instance, ref Civilization civilization)
		{
			try
			{
				int num = (int)civilization;
				if (num < 0 || num > 4)
				{
					if (__instance.buildOrders == null)
					{
						__instance.InitBuildOrders();
					}
					if (!BuildOrders.Loaded.Contains(num) && CivilizationRegistry.TryGetSkinsLike(num, out var like))
					{
						civilization = (Civilization)like;
					}
				}
			}
			catch (Exception ex)
			{
				CoreLog.Once("civ:ai", "AI build order hook: " + ex.Message);
			}
		}
	}
	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	internal static class StatisticsTechTreeHook
	{
		[HarmonyPrefix]
		public static bool Prefix(Statistics __instance, ref TechTree __result)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected I4, but got Unknown
			try
			{
				Island island = __instance.island;
				PlayerSkins val = ((island != null) ? island.Skins : null);
				if (val == null)
				{
					return true;
				}
				int num = (int)val.civilization;
				if (num >= 0 && num <= 4)
				{
					if (!BuiltInChanges.TryGetTree(num, out var _))
					{
						return true;
					}
				}
				else if (CivilizationRegistry.Find(num) == null)
				{
					return true;
				}
				Technologies technologies = __instance.technologies;
				if ((Object)(object)technologies == (Object)null)
				{
					return true;
				}
				__result = technologies.TechTree((Civilization)num);
				return false;
			}
			catch (Exception ex)
			{
				CoreLog.Once("civ:stats", "tech tree getter hook: " + ex.Message);
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Statistics), "IsTechnologyLearnable")]
	internal static class StatisticsLearnableHook
	{
		[HarmonyPrefix]
		public static bool Prefix(Statistics __instance, Technology technology, ref bool __result)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected I4, but got Unknown
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Invalid comparison between Unknown and I4
			try
			{
				Island island = __instance.island;
				PlayerSkins val = ((island != null) ? island.Skins : null);
				if (val == null || technology == null)
				{
					return true;
				}
				int num = (int)val.civilization;
				if (num >= 0 && num <= 4)
				{
					if (!BuiltInChanges.TryGetTree(num, out var _))
					{
						return true;
					}
				}
				else if (CivilizationRegistry.Find(num) == null)
				{
					return true;
				}
				ReadOnlyCollection<Technology> learntTechnologies = __instance.LearntTechnologies;
				if (learntTechnologies == null)
				{
					return true;
				}
				if (learntTechnologies.Contains(technology))
				{
					__result = false;
					return false;
				}
				if (SteamworksInit.IsSteamAndDemo && (int)technology.name != 5)
				{
					__result = false;
					return false;
				}
				TechTree techTree = __instance.TechTree;
				if ((Object)(object)techTree == (Object)null)
				{
					return true;
				}
				Il2CppReferenceArray<Technology> dependencies = techTree.GetDependencies(technology);
				bool flag = dependencies == null || ((Il2CppArrayBase<Technology>)(object)dependencies).Length == 0;
				if (!flag)
				{
					foreach (Technology item in (Il2CppArrayBase<Technology>)(object)dependencies)
					{
						if (learntTechnologies.Contains(item))
						{
							flag = true;
							break;
						}
					}
				}
				__result = flag;
				return false;
			}
			catch (Exception ex)
			{
				CoreLog.Once("civ:learnable", "IsTechnologyLearnable hook: " + ex.Message);
			}
			return true;
		}
	}
	internal static class CivilizationIcons
	{
		public cons