Decompiled source of Upkeep v1.0.3

BepInEx/plugins/DiceModders.Upkeep.dll

Decompiled 4 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using DiceKingdoms.Game;
using DiceKingdoms.Interface;
using DiceModders.ModCore;
using DiceModders.ModCore.Tools;
using DiceModders.UiKit;
using DiceModders.UiKit.Custom;
using DiceModders.UiKit.Native;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using Unity.Mathematics;
using UnityEngine;

[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")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Upkeep for Dice Kingdoms: guard towers eat food, lighthouses use wood or stone, and an offering at the Cathedral doubles its culture.")]
[assembly: AssemblyFileVersion("1.0.3.0")]
[assembly: AssemblyInformationalVersion("1.0.3")]
[assembly: AssemblyProduct("DiceModders.Upkeep")]
[assembly: AssemblyTitle("DiceModders.Upkeep")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.3.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.Upkeep
{
	internal static class Choices
	{
		private const string ChoiceKey = "upkeep.c";

		internal const string Default = "110";

		internal static ConfigEntry<bool> PayTowers;

		internal static ConfigEntry<bool> PayLighthouses;

		internal static ConfigEntry<bool> TowersFirst;

		internal static string OwnFlags => (PayTowers.Value ? "1" : "0") + (PayLighthouses.Value ? "1" : "0") + (TowersFirst.Value ? "1" : "0");

		private static ulong LocalId
		{
			get
			{
				MatchPlayer local = Players.Local;
				if (local == null)
				{
					return 0uL;
				}
				return local.Id;
			}
		}

		internal static void Bind(ConfigFile config)
		{
			PayTowers = config.Bind<bool>("Choices", "PayGuardTowers", true, "Feed the guard towers (unfed towers do not shoot in this turn's combat).");
			PayLighthouses = config.Bind<bool>("Choices", "PayLighthouses", true, "Pay the lighthouses (unpaid ones do not shoot and give no fish bonus).");
			TowersFirst = config.Bind<bool>("Choices", "GuardTowersEatFirst", false, "When food is short, the guard towers eat before the houses.");
			Match.Started += delegate
			{
				Publish(matchStart: true);
			};
			ConfigEntry<bool>[] array = new ConfigEntry<bool>[3] { PayTowers, PayLighthouses, TowersFirst };
			for (int num = 0; num < array.Length; num++)
			{
				array[num].SettingChanged += delegate
				{
					if (Match.Running)
					{
						Publish();
					}
				};
			}
		}

		internal static void Publish(bool matchStart = false)
		{
			int turn = Match.Turn;
			string text = (matchStart ? OwnFlags : Effective(PlayerValues.Get(LocalId, "upkeep.c"), turn));
			int num = ((!matchStart) ? (turn + 1) : 0);
			PlayerValues.Set("upkeep.c", num + "|" + OwnFlags + "|" + text);
		}

		internal static string Of(MatchPlayer player, int turn)
		{
			if (player == null || player.IsAI)
			{
				return "110";
			}
			return Effective(PlayerValues.Get(player.Id, "upkeep.c"), turn);
		}

		private static string Effective(string value, int turn)
		{
			if (string.IsNullOrEmpty(value))
			{
				return "110";
			}
			string[] array = value.Split('|');
			if (array.Length != 3 || !int.TryParse(array[0], out var result) || array[1].Length != 3 || array[2].Length != 3)
			{
				return "110";
			}
			if (turn < result)
			{
				return array[2];
			}
			return array[1];
		}
	}
	internal static class Panel
	{
		private static UiScope _ui;

		private static TopBarButtonHandle _button;

		private static UiWindow _window;

		private static UiButton _offer;

		private static UiText _offerText;

		private static UiText _status;

		private static BuildInterface _build;

		internal static void Install(UiScope ui, Patcher patcher)
		{
			_ui = ui;
			UiScope ui2 = _ui;
			if (ui2 != null)
			{
				ui2.WhenReady((Action<UiScope>)delegate(UiScope s)
				{
					_button = s.Native.TopBar.AddIconButton("food", Tx.T("panel.tooltip"), (Action)Toggle, 21);
					Refresh();
				});
			}
			Texts.LanguageChanged += delegate
			{
				TopBarButtonHandle button = _button;
				if (button != null)
				{
					button.SetTooltip(Tx.T("panel.tooltip"));
				}
				if (_window != null)
				{
					_window.Close();
					Toggle();
				}
			};
			Match.Started += Refresh;
			Match.Ended += Refresh;
			Match.PhaseEntered += delegate
			{
				Refresh();
				Redraw();
			};
			patcher.Patch(typeof(BuildInterface), "OnEnable", typeof(Panel), (string)null, "BuildShown");
			patcher.Patch(typeof(BuildInterface), "OnDisable", typeof(Panel), (string)null, "BuildHidden");
		}

		public static void BuildShown(BuildInterface __instance)
		{
			_build = __instance;
			Redraw();
		}

		public static void BuildHidden(BuildInterface __instance)
		{
			if ((Object)(object)_build != (Object)null && (Object)(object)__instance != (Object)null && ((Il2CppObjectBase)_build).Pointer == ((Il2CppObjectBase)__instance).Pointer)
			{
				_build = null;
			}
			Redraw();
		}

		internal static void Refresh()
		{
			bool flag = Upkeep.On;
			TopBarButtonHandle button = _button;
			if (button != null)
			{
				button.SetVisible(flag);
			}
			if (!flag)
			{
				UiWindow window = _window;
				if (window != null)
				{
					window.Close();
				}
			}
		}

		private static void Toggle()
		{
			if (_window != null)
			{
				_window.Close();
			}
			else
			{
				if (!Upkeep.On)
				{
					return;
				}
				UiScope ui = _ui;
				_window = ((ui != null) ? ui.Custom.Window((Action<UiWindow>)delegate(UiWindow w)
				{
					w.Title(Tx.T("panel.title")).Size(520f, 470f).Position(60f, 80f)
						.Draggable(true)
						.Closable(true);
					w.OnClose((Action)delegate
					{
						_window = null;
						_offer = null;
						_offerText = (_status = null);
					});
					w.Body.Paragraph(Tx.T("panel.help"));
					w.Body.Toggle(Tx.T("panel.payTowers", Upkeep.TowerFood), Choices.PayTowers.Value, (Action<bool>)delegate(bool v)
					{
						Choose(delegate
						{
							Choices.PayTowers.Value = v;
						});
					});
					w.Body.Toggle(Tx.T("panel.payLighthouses", Upkeep.LighthouseCost), Choices.PayLighthouses.Value, (Action<bool>)delegate(bool v)
					{
						Choose(delegate
						{
							Choices.PayLighthouses.Value = v;
						});
					});
					w.Body.Toggle(Tx.T("panel.towersFirst"), Choices.TowersFirst.Value, (Action<bool>)delegate(bool v)
					{
						Choose(delegate
						{
							Choices.TowersFirst.Value = v;
						});
					});
					w.Body.Separator(1f);
					_offerText = w.Body.Paragraph("");
					_offer = w.Body.Button(Tx.T("panel.offer"), (Action)Offer);
					w.Body.Separator(1f);
					_status = w.Body.Paragraph("");
				}) : null);
				Redraw();
			}
		}

		private static void Choose(Action set)
		{
			set();
			Redraw();
		}

		private static void Offer()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Invalid comparison between Unknown and I4
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Expected O, but got Unknown
			try
			{
				BuildData val = ((PhaseInterface<BuildData, BuildIslandState>)(object)_build)?.Data;
				if ((Object)(object)val == (Object)null || (int)Match.Phase != 4)
				{
					return;
				}
				int num = 0;
				foreach (int item in Upkeep.Cathedrals(((PhaseData<BuildData, BuildIslandState>)(object)val).Island))
				{
					if (BuildActions.Plan(val, 0, item))
					{
						num++;
					}
				}
				BuildInterface build = _build;
				if (build != null)
				{
					build.RefreshButtons();
				}
				ManualLogSource l = Plugin.L;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(23, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("offering: ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" Cathedral(s)");
				}
				l.LogInfo(val2);
			}
			catch (Exception ex)
			{
				Plugin.L.LogWarning((object)("offering: " + ex.Message));
			}
			Redraw();
		}

		private static void Redraw()
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Invalid comparison between Unknown and I4
			if (_window != null)
			{
				MatchPlayer local = Players.Local;
				Island island = ((local != null) ? local.Island : null);
				int count = Upkeep.Cathedrals(island).Count;
				int num = Upkeep.OfferedForNextHarvest(island);
				bool flag = (Object)(object)_build != (Object)null && (int)Match.Phase == 4 && count > num;
				if (_offerText != null)
				{
					_offerText.Value = ((count == 0) ? Tx.T("panel.noCathedral") : ((num > 0) ? Tx.T("panel.offered", num, count) : Tx.T("panel.offerHelp", Upkeep.OfferGold, count)));
				}
				UiButton offer = _offer;
				if (offer != null)
				{
					offer.Interactable(flag);
				}
				if (_status != null)
				{
					var (num2, num3, flag2) = Upkeep.Unpaid(island);
					_status.Value = ((!flag2) ? Tx.T("panel.fromNextTurn") : ((num2 + num3 == 0) ? Tx.T("panel.allPaid") : Tx.T("panel.unpaid", num2, num3)));
				}
			}
		}
	}
	[BepInPlugin("org.dicemodders.dicekingdoms.upkeep", "DiceKingdoms Upkeep", "1.0.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInProcess("Dice-Kingdoms.exe")]
	public sealed class Plugin : BasePlugin
	{
		public const string Guid = "org.dicemodders.dicekingdoms.upkeep";

		public const string Name = "DiceKingdoms Upkeep";

		public const string Version = "1.0.3";

		internal static ManualLogSource L;

		internal static bool On;

		private static readonly HashSet<string> Logged = new HashSet<string>();

		public override void Load()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			Tx.Load();
			L = ((BasePlugin)this).Log;
			Choices.Bind(((BasePlugin)this).Config);
			Patcher val = new Patcher("org.dicemodders.dicekingdoms.upkeep", ((BasePlugin)this).Log);
			Upkeep.Install(val);
			Panel.Install(UiKit.CreateScope("org.dicemodders.dicekingdoms.upkeep"), val);
			val.Summary();
			Mods.Switch(((BasePlugin)this).Config, true, false, "Turns the upkeep rule of this mod on or off.").WhenOn((Action)delegate
			{
				On = true;
				Panel.Refresh();
			}, (Action)delegate
			{
				On = false;
				Panel.Refresh();
			});
		}

		internal static void Once(string key, string message)
		{
			if (Logged.Add(key))
			{
				ManualLogSource l = L;
				if (l != null)
				{
					l.LogError((object)message);
				}
			}
		}
	}
	internal static class Tx
	{
		internal static TextSet Set;

		internal static void Load()
		{
			Set = Texts.Load("texts.json", (string)null);
		}

		internal static string T(string key)
		{
			TextSet set = Set;
			return ((set != null) ? set.Get(key) : null) ?? key;
		}

		internal static string T(string key, params object[] values)
		{
			TextSet set = Set;
			return ((set != null) ? set.Get(key, values) : null) ?? key;
		}
	}
	internal static class Upkeep
	{
		private sealed class IslandState
		{
			public int Turn = -1;

			public readonly HashSet<int> Towers = new HashSet<int>();

			public readonly HashSet<int> Lights = new HashSet<int>();

			public int OfferTurn = -1;

			public readonly HashSet<int> Offered = new HashSet<int>();
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static Handler <0>__Offer;

			public static Action <1>__Clear;
		}

		private static LobbyRule<bool> _on;

		private static LobbyRule<int> _towerFood;

		private static LobbyRule<int> _lighthouseCost;

		private static LobbyRule<int> _offerGold;

		private static readonly Dictionary<IntPtr, IslandState> States = new Dictionary<IntPtr, IslandState>();

		private static Island _pendingIsland;

		private static string _pendingFlags;

		private static int _pendingTurn;

		private static bool _harvest;

		private static int _harvestTurn;

		private const int TowersField = 200;

		private const int ListItems = 16;

		private const int ListSize = 24;

		private const int ArrayData = 32;

		private const int TowerPosition = 20;

		private const int TypeTowerHas = 200;

		private const int TypeTowerOffset = 212;

		private static int _towerSize;

		internal const int OfferAction = 0;

		internal static bool On
		{
			get
			{
				if (Plugin.On && _on != null && _on.Value)
				{
					return Match.Running;
				}
				return false;
			}
		}

		internal static int TowerFood => _towerFood?.Value ?? 1;

		internal static int LighthouseCost => _lighthouseCost?.Value ?? 1;

		internal static int OfferGold => _offerGold?.Value ?? 4;

		internal static void Install(Patcher patcher)
		{
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Expected O, but got Unknown
			_on = Rules.Toggle("upkeep.on", "Upkeep", false, "Guard towers eat food and lighthouses use wood or stone every turn; unpaid ones do not shoot, and unpaid lighthouses give no fish bonus. Each player chooses what to pay in the Upkeep window; a choice counts from the next turn.", (Func<bool>)null, true);
			_towerFood = Rules.Number("upkeep.towerFood", "Food per guard tower", 1, 1, 5, 1, "Food each guard tower eats per turn.", (Func<bool>)(() => _on.Value), true);
			_lighthouseCost = Rules.Number("upkeep.lighthouseCost", "Wood or stone per lighthouse", 1, 1, 5, 1, "Wood or stone (whichever there is more of) each lighthouse uses per turn.", (Func<bool>)(() => _on.Value), true);
			_offerGold = Rules.Number("upkeep.offerGold", "Cathedral offering (gold)", 4, 1, 20, 1, "Gold per Cathedral for an offering, which doubles its culture at the next harvest.", (Func<bool>)(() => _on.Value), true);
			LobbyGroup val = Groups.Get("upkeep", "Upkeep", 500);
			_on.InGroup(val);
			_towerFood.InGroup(val);
			_lighthouseCost.InGroup(val);
			_offerGold.InGroup(val);
			patcher.Patch(typeof(_Execute_d__1), "MoveNext", typeof(Upkeep), "StarvationPrefix", "StarvationPostfix");
			patcher.Patch(typeof(CombatGrid), "Init", typeof(Upkeep), (string)null, "CombatPostfix");
			patcher.Patch(typeof(BuildingTypeApplyModifierInRange), "HasModifier", typeof(Upkeep), (string)null, "ModifierPostfix");
			patcher.Patch(typeof(HarvestPhase), "Reset", typeof(Upkeep), "HarvestResetPrefix", (string)null);
			patcher.Patch(typeof(BuildingTypeProducerAmplifier), "Yield", typeof(Upkeep), (string)null, "YieldPostfix");
			patcher.Patch(typeof(BuildingTypeProducerAmplifier), "AverageFactor", typeof(Upkeep), (string)null, "AverageFactorPostfix");
			object obj = <>O.<0>__Offer;
			if (obj == null)
			{
				Handler val2 = Offer;
				<>O.<0>__Offer = val2;
				obj = (object)val2;
			}
			BuildActions.Register(0, "Upkeep (Cathedral offering)", (Handler)obj);
			Match.PhaseEntered += delegate(MatchPhase phase)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Invalid comparison between Unknown and I4
				if ((int)phase == 3)
				{
					_harvest = false;
				}
			};
			Match.Started += Clear;
			Match.Ended += Clear;
		}

		private static void Clear()
		{
			States.Clear();
			_harvest = false;
			_pendingIsland = null;
		}

		private static IslandState StateOf(IslandGrid grid)
		{
			if (!States.TryGetValue(((Il2CppObjectBase)grid).Pointer, out var value))
			{
				value = (States[((Il2CppObjectBase)grid).Pointer] = new IslandState());
			}
			return value;
		}

		private static bool TryState(IslandGrid grid, out IslandState state)
		{
			state = null;
			if ((Object)(object)grid != (Object)null)
			{
				return States.TryGetValue(((Il2CppObjectBase)grid).Pointer, out state);
			}
			return false;
		}

		private static List<(Id id, Building b)> Buildings(IslandGrid grid)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			List<(Id, Building)> list = new List<(Id, Building)>();
			Enumerator<Id, Building> enumerator = grid.Buildings.GetEnumerator();
			while (enumerator.MoveNext())
			{
				Building current = enumerator.Current;
				list.Add((Id.OfPosition(current.transform.position), current));
			}
			return list;
		}

		public static void StarvationPrefix(_Execute_d__1 __instance)
		{
			_pendingIsland = null;
			try
			{
				if (!On || __instance.__1__state != 0)
				{
					return;
				}
				GameState gameState = __instance.gameState;
				DisasterOccurrence occurrence = __instance.occurrence;
				Player val = ((occurrence != null) ? occurrence.Target : null);
				if ((Object)(object)gameState == (Object)null || (Object)(object)val == (Object)null)
				{
					return;
				}
				Island val2 = gameState.Island(val);
				if (!((Object)(object)val2 == (Object)null))
				{
					int turnCounter = gameState.TurnCounter;
					string text = Choices.Of(FindPlayer(val), turnCounter);
					if (text[2] == '1')
					{
						Charge(val2, text, (Disaster)(object)__instance.__4__this, turnCounter);
						return;
					}
					_pendingIsland = val2;
					_pendingFlags = text;
					_pendingTurn = turnCounter;
				}
			}
			catch (Exception ex)
			{
				Plugin.Once("starve:pre", "upkeep (before food upkeep): " + ex);
			}
		}

		public static void StarvationPostfix(_Execute_d__1 __instance)
		{
			Island pendingIsland = _pendingIsland;
			_pendingIsland = null;
			if ((Object)(object)pendingIsland == (Object)null)
			{
				return;
			}
			try
			{
				Charge(pendingIsland, _pendingFlags, (Disaster)(object)__instance.__4__this, _pendingTurn);
			}
			catch (Exception ex)
			{
				Plugin.Once("starve:post", "upkeep (after food upkeep): " + ex);
			}
		}

		private static MatchPlayer FindPlayer(Player p)
		{
			foreach (MatchPlayer item in Players.All)
			{
				if ((Object)(object)item.Game != (Object)null && ((Il2CppObjectBase)item.Game).Pointer == ((Il2CppObjectBase)p).Pointer)
				{
					return item;
				}
			}
			return null;
		}

		private static void Charge(Island island, string flags, Disaster hungry, int turn)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Invalid comparison between Unknown and I4
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Invalid comparison between Unknown and I4
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Invalid comparison between Unknown and I4
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Expected O, but got Unknown
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			IslandGrid grid = island.grid;
			Statistics statistics = island.statistics;
			if ((Object)(object)grid == (Object)null || (Object)(object)statistics == (Object)null)
			{
				return;
			}
			IslandState islandState = StateOf(grid);
			if (islandState.Turn == turn)
			{
				return;
			}
			islandState.Turn = turn;
			islandState.Towers.Clear();
			islandState.Lights.Clear();
			ResourceAmount stored = statistics.Storage.stored;
			int food = stored.food;
			int wood = stored.wood;
			int stone = stored.stone;
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			bool flag = flags[0] == '1';
			bool flag2 = flags[1] == '1';
			List<Id> list = new List<Id>();
			foreach (var item2 in Buildings(grid))
			{
				Id item = item2.id;
				BuildingTypeName name = item2.b.type.name;
				if ((int)name == 8 || (int)name == 9)
				{
					int towerFood = TowerFood;
					if (flag && food - num >= towerFood)
					{
						num += towerFood;
						continue;
					}
					islandState.Towers.Add(item.value);
					list.Add(item);
				}
				else
				{
					if ((int)name != 22)
					{
						continue;
					}
					int lighthouseCost = LighthouseCost;
					int num4 = wood - num2;
					int num5 = stone - num3;
					if (flag2 && Math.Max(num4, num5) >= lighthouseCost)
					{
						if (num4 >= num5)
						{
							num2 += lighthouseCost;
						}
						else
						{
							num3 += lighthouseCost;
						}
					}
					else
					{
						islandState.Lights.Add(item.value);
						list.Add(item);
					}
				}
			}
			if (num + num2 + num3 > 0)
			{
				statistics.RemoveResource(new ResourceAmount
				{
					food = num,
					wood = num2,
					stone = num3
				});
			}
			if (hungry != null)
			{
				foreach (Id item3 in list)
				{
					grid.DisasterAffectBuilding(hungry, item3);
				}
			}
			if (list.Count > 0 || num + num2 + num3 > 0)
			{
				ManualLogSource l = Plugin.L;
				bool flag3 = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(74, 7, ref flag3);
				if (flag3)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("turn ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(turn);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
					Player owner = island.Owner;
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>((owner != null) ? owner.UserName : null);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" paid ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" food, ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num2);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" wood, ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num3);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" stone; unpaid: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(islandState.Towers.Count);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" guard tower(s), ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(islandState.Lights.Count);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" lighthouse(s)");
				}
				l.LogInfo(val);
			}
		}

		public static void CombatPostfix(CombatGrid __instance)
		{
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Expected O, but got Unknown
			try
			{
				if (!On || (Object)(object)__instance == (Object)null)
				{
					return;
				}
				IslandGrid islandGrid = __instance.islandGrid;
				if (!TryState(islandGrid, out var state) || state.Turn != Match.Turn || state.Towers.Count + state.Lights.Count == 0)
				{
					return;
				}
				HashSet<long> hashSet = new HashSet<long>();
				foreach (var (val, val2) in Buildings(islandGrid))
				{
					if (state.Towers.Contains(val.value) || state.Lights.Contains(val.value))
					{
						IntPtr pointer = ((Il2CppObjectBase)val2.type).Pointer;
						if ((Mem.ReadInt(pointer, 200) & 0xFF) != 0)
						{
							GridTransform transform = val2.transform;
							int2 val3 = ((GridTransform)(ref transform)).TransformCombat(new int2(Mem.ReadInt(pointer, 212), Mem.ReadInt(pointer, 216)));
							hashSet.Add(Key(val3.x, val3.y));
						}
					}
				}
				if (hashSet.Count == 0)
				{
					return;
				}
				if (_towerSize == 0)
				{
					uint num = 0u;
					_towerSize = IL2CPP.il2cpp_class_value_size(Il2CppClassPointerStore<Tower>.NativeClassPtr, ref num);
				}
				IntPtr intPtr = Mem.ReadPtr(((Il2CppObjectBase)__instance).Pointer, 200);
				IntPtr intPtr2 = Mem.ReadPtr(intPtr, 16);
				int num2 = Mem.ReadInt(intPtr, 24);
				int num3 = 0;
				for (int i = 0; i < num2; i++)
				{
					IntPtr intPtr3 = intPtr2 + 32 + i * _towerSize;
					if (hashSet.Contains(Key(Mem.ReadInt(intPtr3, 20), Mem.ReadInt(intPtr3, 24))))
					{
						Mem.WriteInt(intPtr3, 0, 0);
						num3++;
					}
				}
				ManualLogSource l = Plugin.L;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val4 = new BepInExInfoLogInterpolatedStringHandler(49, 3, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val4).AppendLiteral("turn ");
					((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<int>(state.Turn);
					((BepInExLogInterpolatedStringHandler)val4).AppendLiteral(": ");
					((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<int>(num3);
					((BepInExLogInterpolatedStringHandler)val4).AppendLiteral(" of ");
					((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<int>(hashSet.Count);
					((BepInExLogInterpolatedStringHandler)val4).AppendLiteral(" unpaid tower(s) silent in this combat");
				}
				l.LogInfo(val4);
			}
			catch (Exception ex)
			{
				Plugin.Once("combat", "upkeep (combat towers): " + ex);
			}
		}

		private static long Key(int x, int y)
		{
			return ((long)x << 32) | (uint)y;
		}

		public static void ModifierPostfix(Island __0, Building __2, ref bool __result)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!__result || !On || (Object)(object)__0 == (Object)null || !TryState(__0.grid, out var state) || state.Lights.Count == 0)
				{
					return;
				}
				int num = (_harvest ? (_harvestTurn - 1) : Match.Turn);
				if (state.Turn != num)
				{
					return;
				}
				foreach (var (val, val2) in Buildings(__0.grid))
				{
					if (!state.Lights.Contains(val.value))
					{
						BuildingTypeApplyModifierInRange val3 = ((Il2CppObjectBase)val2.type).TryCast<BuildingTypeApplyModifierInRange>();
						if (val3 != null && val3.Affects(val2, __2))
						{
							return;
						}
					}
				}
				__result = false;
			}
			catch (Exception ex)
			{
				Plugin.Once("modifier", "upkeep (fish bonus): " + ex);
			}
		}

		private static bool Offer(BuildData data, int cathedral)
		{
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Invalid comparison between Unknown and I4
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Expected O, but got Unknown
			if (!On)
			{
				return false;
			}
			Island island = ((PhaseData<BuildData, BuildIslandState>)(object)data).Island;
			Statistics val = ((island != null) ? island.statistics : null);
			IslandGrid val2 = ((island != null) ? island.grid : null);
			GameState gameState = ((PhaseData<BuildData, BuildIslandState>)(object)data).GameState;
			if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null || (Object)(object)gameState == (Object)null)
			{
				return false;
			}
			int num = gameState.TurnCounter + 1;
			IslandState islandState = StateOf(val2);
			if (islandState.OfferTurn != num)
			{
				islandState.OfferTurn = num;
				islandState.Offered.Clear();
			}
			if (islandState.Offered.Contains(cathedral))
			{
				return false;
			}
			bool flag = false;
			foreach (var (val3, val4) in Buildings(val2))
			{
				if (val3.value == cathedral && (int)val4.type.name == 3)
				{
					flag = true;
					break;
				}
			}
			if (!flag || val.Storage.stored.gold < OfferGold)
			{
				return false;
			}
			val.RemoveResource(new ResourceAmount
			{
				gold = OfferGold
			});
			islandState.Offered.Add(cathedral);
			ManualLogSource l = Plugin.L;
			bool flag2 = default(bool);
			BepInExInfoLogInterpolatedStringHandler val5 = new BepInExInfoLogInterpolatedStringHandler(74, 3, ref flag2);
			if (flag2)
			{
				((BepInExLogInterpolatedStringHandler)val5).AppendLiteral("turn ");
				((BepInExLogInterpolatedStringHandler)val5).AppendFormatted<int>(num - 1);
				((BepInExLogInterpolatedStringHandler)val5).AppendLiteral(": ");
				Player owner = island.Owner;
				((BepInExLogInterpolatedStringHandler)val5).AppendFormatted<string>((owner != null) ? owner.UserName : null);
				((BepInExLogInterpolatedStringHandler)val5).AppendLiteral(" offered ");
				((BepInExLogInterpolatedStringHandler)val5).AppendFormatted<int>(OfferGold);
				((BepInExLogInterpolatedStringHandler)val5).AppendLiteral(" gold at a Cathedral (culture doubled at the next harvest)");
			}
			l.LogInfo(val5);
			return true;
		}

		public static void HarvestResetPrefix(HarvestPhase __instance)
		{
			try
			{
				if (On)
				{
					GameState gameState = ((TurnPhase<HarvestData, HarvestIslandState>)(object)__instance).GameState;
					if (!((Object)(object)gameState == (Object)null) && gameState.TurnCounter > 0)
					{
						_harvest = true;
						_harvestTurn = gameState.TurnCounter;
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Once("harvest", "upkeep (harvest start): " + ex);
			}
		}

		private static bool Doubled(Island island, Building building)
		{
			//IL_0044: 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)
			if (!TryState(island.grid, out var state) || state.Offered.Count == 0)
			{
				return false;
			}
			int num = (_harvest ? _harvestTurn : (Match.Turn + 1));
			if (state.OfferTurn == num)
			{
				return state.Offered.Contains(Id.OfPosition(building.transform.position).value);
			}
			return false;
		}

		public static void YieldPostfix(Island __0, Building __1, ref ResourceAmount __result)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: 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_002d: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (On && __0 != null && __1 != null && Doubled(__0, __1))
				{
					ResourceAmount val = __result;
					val.culture *= 2;
					__result = val;
				}
			}
			catch (Exception ex)
			{
				Plugin.Once("yield", "upkeep (Cathedral culture): " + ex);
			}
		}

		public static void AverageFactorPostfix(BuildingTypeProducerAmplifier __instance, Island __0, Il2CppReferenceArray<Building> __1, ref float __result)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Invalid comparison between Unknown and I4
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!On || __0 == null || __1 == null || ((Il2CppArrayBase<Building>)(object)__1).Length == 0 || (int)((BuildingType)__instance).name != 3)
				{
					return;
				}
				bool flag = false;
				foreach (Building item in (Il2CppArrayBase<Building>)(object)__1)
				{
					if (item != null && Doubled(__0, item))
					{
						flag = true;
						break;
					}
				}
				if (!flag)
				{
					return;
				}
				int num = __instance.AmplifiedCount(__0);
				if (num <= 0)
				{
					return;
				}
				float num2 = 0f;
				foreach (Building item2 in (Il2CppArrayBase<Building>)(object)__1)
				{
					if (item2 != null)
					{
						num2 += (float)((BuildingTypeProducer)__instance).Yield(__0, item2).culture;
					}
				}
				__result = num2 / (float)((Il2CppArrayBase<Building>)(object)__1).Length / (float)num;
			}
			catch (Exception ex)
			{
				Plugin.Once("average", "upkeep (harvest screen): " + ex);
			}
		}

		internal static (int towers, int lights, bool now) Unpaid(Island island)
		{
			if (!((Object)(object)((island != null) ? island.grid : null) != (Object)null) || !TryState(island.grid, out var state))
			{
				return (towers: 0, lights: 0, now: false);
			}
			return (towers: state.Towers.Count, lights: state.Lights.Count, now: state.Turn == Match.Turn);
		}

		internal static List<int> Cathedrals(Island island)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Invalid comparison between Unknown and I4
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			List<int> list = new List<int>();
			if ((Object)(object)((island != null) ? island.grid : null) == (Object)null)
			{
				return list;
			}
			foreach (var item in Buildings(island.grid))
			{
				var (val, _) = item;
				if ((int)item.b.type.name == 3)
				{
					list.Add(val.value);
				}
			}
			return list;
		}

		internal static int OfferedForNextHarvest(Island island)
		{
			if (!((Object)(object)((island != null) ? island.grid : null) != (Object)null) || !TryState(island.grid, out var state) || state.OfferTurn != Match.Turn + 1)
			{
				return 0;
			}
			return state.Offered.Count;
		}
	}
}