Decompiled source of IslandTools v1.0.0

BepInEx/plugins/DiceModders.IslandTools.dll

Decompiled 9 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using DiceKingdoms.Game;
using DiceModders.ModCore;
using DiceModders.ModCore.Tools;
using DiceModders.UiKit;
using DiceModders.UiKit.Custom;
using DiceModders.UiKit.Native;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Microsoft.CodeAnalysis;
using TMPro;
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("In-game island editor and players window for Dice Kingdoms.")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("DiceModders.IslandTools")]
[assembly: AssemblyTitle("DiceModders.IslandTools")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace DiceModders.IslandTools
{
	internal enum EditLayer
	{
		Ground,
		Nature,
		Buildings,
		Hills
	}
	internal enum EditTool
	{
		Point,
		Fill,
		Line,
		Rect,
		Square,
		Circle,
		Oval,
		Spray
	}
	internal sealed class EditorModel
	{
		private sealed class Snapshot
		{
			public int[] Ground;

			public int[] Nature;

			public List<IslandBuilding> Buildings;

			public List<IslandCliff> Cliffs;
		}

		public int HillShape;

		public string HillMessage;

		public IslandData Data;

		public BuildingTable Table = BuildingTable.Parse("0: Archery Range | tier=2 hp=60 | [[0,0],[-1,0],[0,-1],[-1,-1],[-1,-2]]\n1: Barracks | tier=1 hp=60 | [[-1,1],[0,1],[0,0],[0,-1],[1,0],[1,-1]]\n2: Castle | tier=1 hp=200 | [[-1,-1],[-1,0],[-1,1],[-1,2],[0,-1],[0,0],[0,1],[0,2],[1,-1],[1,0],[1,1],[1,2],[2,-1],[2,0],[2,1],[2,2]]\n3: Cathedral | tier=2 hp=40 | [[1,0],[0,0],[-1,0],[-2,0],[0,1],[0,-1]]\n4: Church | tier=1 hp=15 | [[0,0],[-1,0],[-2,0]]\n5: Cottage | tier=1 hp=10 | [[0,0],[0,1]]\n6: Dock | tier=1 hp=50 | [[0,0],[1,0],[2,0],[2,1],[3,0],[3,1],[4,-1],[4,0],[4,1],[5,-1],[5,0],[5,1]]\n7: Farm | tier=1 hp=15 | [[0,1],[0,0],[0,-1],[0,-2],[1,1],[1,0],[1,-1],[1,-2]]\n8: Guard Tower | tier=2 hp=40 | [[0,0],[-1,0],[0,-1],[-1,-1]]\n9: Guard Tower Up | tier=2 hp=40 | [[0,0],[-1,0],[0,-1],[-1,-1]]\n10: Hospital | tier=2 hp=40 | [[0,0],[-1,0],[1,0],[0,-1],[0,1]]\n11: House | tier=1 hp=15 | [[0,0],[-1,0],[0,-1]]\n12: Lumber Camp | tier=3 hp=20 | [[0,0],[-1,0],[-1,1],[-2,1]]\n13: Market | tier=3 hp=10 | [[0,0],[1,0],[1,1],[0,1]]\n14: Sorcerer Tower | tier=2 hp=20 | [[0,0],[1,0],[0,1]]\n15: Stone Quarry | tier=3 hp=20 | [[0,0],[0,1],[1,0]]\n16: Storage | tier=2 hp=20 | [[0,0],[1,0],[0,-1],[1,-1],[0,1],[1,1]]\n17: University | tier=1 hp=50 | [[0,1],[0,0],[0,-1],[1,1],[1,-1],[2,1],[2,-1]]\n18: Wall | tier=1 hp=50 | [[0,0]]\n19: Windmill | tier=2 hp=20 | [[0,0],[-1,0],[-1,1],[0,1]]\n20: Wonder | tier=3 hp=150 | [[3,-1],[3,0],[3,1],[2,-1],[2,0],[2,1],[1,-1],[1,0],[1,1],[0,-1],[0,0],[0,1],[-1,-1],[-1,0],[-1,1]]\n21: Fishing Ship | tier=2 hp=30 | [[0,0],[0,1]]\n22: Lighthouse | tier=3 hp=50 | [[0,0],[-1,0],[0,-1],[-1,-1]]\n23: Land Camp | tier=3 hp=20 | [[0,0],[1,1],[0,1],[-1,1]]");

		public EditLayer Layer;

		public EditTool Tool;

		public int GroundBrush = 2;

		public int NatureBrush;

		public int BrushSize = 1;

		public bool SymX;

		public bool SymY;

		public bool FillShapes = true;

		public int SprayRadius = 3;

		public int SprayDensity = 35;

		public int BType;

		public int BOrient;

		public bool BMirror;

		public int BHealth;

		public bool Dirty;

		public List<(int X, int Y)> Problems = new List<(int, int)>();

		private readonly Random _rng = new Random();

		private readonly List<Snapshot> _undo = new List<Snapshot>();

		private readonly List<Snapshot> _redo = new List<Snapshot>();

		private (int X, int Y)? _dragStart;

		private int[] _baseLayer;

		private bool _strokeOpen;

		public static string[] GroundNames => new string[7]
		{
			Tx.T("ground.0"),
			Tx.T("ground.1"),
			Tx.T("ground.2"),
			Tx.T("ground.3"),
			Tx.T("ground.4"),
			Tx.T("ground.5"),
			Tx.T("ground.6")
		};

		public static string[] NatureNames => new string[6]
		{
			Tx.T("nature.0"),
			Tx.T("nature.1"),
			Tx.T("nature.2"),
			Tx.T("nature.3"),
			Tx.T("nature.4"),
			Tx.T("nature.5")
		};

		public static (int W, int H, int Kind, string Name)[] HillShapes => new(int, int, int, string)[5]
		{
			(3, 3, 0, Tx.T("hill.h33")),
			(2, 2, 0, Tx.T("hill.h22")),
			(2, 2, 1, Tx.T("hill.s22")),
			(1, 2, 1, Tx.T("hill.s12")),
			(1, 1, 1, Tx.T("hill.s11"))
		};

		public bool HasData
		{
			get
			{
				if (Data != null && Data.SideIsExact)
				{
					return Data.Side > 0;
				}
				return false;
			}
		}

		public int Side => Data?.Side ?? 0;

		public bool CanUndo => _undo.Count > 0;

		public bool CanRedo => _redo.Count > 0;

		public int Brush
		{
			get
			{
				if (Layer != EditLayer.Nature)
				{
					return GroundBrush;
				}
				return NatureBrush;
			}
			set
			{
				if (Layer == EditLayer.Nature)
				{
					NatureBrush = value;
				}
				else
				{
					GroundBrush = value;
				}
			}
		}

		private int[] LayerArray
		{
			get
			{
				if (Layer != EditLayer.Nature)
				{
					return Data.Ground;
				}
				return Data.Nature;
			}
		}

		public bool StrokeActive
		{
			get
			{
				if (!_dragStart.HasValue)
				{
					return _strokeOpen;
				}
				return true;
			}
		}

		public int Cell(int x, int y)
		{
			return y * Side + x;
		}

		public bool InBounds(int x, int y)
		{
			if (x >= 0 && y >= 0 && x < Side)
			{
				return y < Side;
			}
			return false;
		}

		public void Load(IslandData d)
		{
			Data = d;
			_undo.Clear();
			_redo.Clear();
			_dragStart = null;
			_baseLayer = null;
			Problems.Clear();
			Dirty = false;
		}

		public void NewBlank(int side)
		{
			Load(IslandData.Blank(side));
		}

		private Snapshot Snap()
		{
			return new Snapshot
			{
				Ground = (int[])Data.Ground.Clone(),
				Nature = (int[])Data.Nature.Clone(),
				Buildings = Data.Buildings.ConvertAll((IslandBuilding b) => b.Clone()),
				Cliffs = Data.Cliffs.ConvertAll((IslandCliff c) => c.Clone())
			};
		}

		public void PushUndo()
		{
			_undo.Add(Snap());
			if (_undo.Count > 60)
			{
				_undo.RemoveAt(0);
			}
			_redo.Clear();
		}

		private void Apply(Snapshot s)
		{
			Data.Ground = s.Ground;
			Data.Nature = s.Nature;
			Data.Buildings = s.Buildings;
			Data.Cliffs = s.Cliffs;
			Dirty = true;
			Problems.Clear();
		}

		public void Undo()
		{
			if (HasData && _undo.Count != 0)
			{
				_redo.Add(Snap());
				Snapshot s = _undo[_undo.Count - 1];
				_undo.RemoveAt(_undo.Count - 1);
				Apply(s);
			}
		}

		public void Redo()
		{
			if (HasData && _redo.Count != 0)
			{
				_undo.Add(Snap());
				Snapshot s = _redo[_redo.Count - 1];
				_redo.RemoveAt(_redo.Count - 1);
				Apply(s);
			}
		}

		private void Put(int x, int y)
		{
			int s = Side;
			int[] arr = LayerArray;
			int b = Brush;
			Set(x, y);
			if (SymX)
			{
				Set(s - 1 - x, y);
			}
			if (SymY)
			{
				Set(x, s - 1 - y);
			}
			if (SymX && SymY)
			{
				Set(s - 1 - x, s - 1 - y);
			}
			void Set(int px, int py)
			{
				if (px >= 0 && py >= 0 && px < s && py < s)
				{
					arr[py * s + px] = b;
				}
			}
		}

		private void SetPixel(int x, int y)
		{
			int num = BrushSize - 1;
			if (num <= 0)
			{
				Put(x, y);
				return;
			}
			for (int i = -num; i <= num; i++)
			{
				for (int j = -num; j <= num; j++)
				{
					if ((double)(j * j + i * i) <= (double)(num * num) + (double)num * 0.5)
					{
						Put(x + j, y + i);
					}
				}
			}
		}

		private void FloodFill(int x0, int y0)
		{
			int[] layerArray = LayerArray;
			int num = layerArray[Cell(x0, y0)];
			if (num == Brush)
			{
				return;
			}
			Stack<(int, int)> stack = new Stack<(int, int)>();
			bool[] array = new bool[layerArray.Length];
			stack.Push((x0, y0));
			while (stack.Count > 0)
			{
				var (num2, num3) = stack.Pop();
				if (InBounds(num2, num3))
				{
					int num4 = Cell(num2, num3);
					if (!array[num4] && layerArray[num4] == num)
					{
						array[num4] = true;
						layerArray[num4] = Brush;
						stack.Push((num2 + 1, num3));
						stack.Push((num2 - 1, num3));
						stack.Push((num2, num3 + 1));
						stack.Push((num2, num3 - 1));
					}
				}
			}
		}

		private void DrawLine(int x0, int y0, int x1, int y1)
		{
			int num = Math.Abs(x1 - x0);
			int num2 = ((x0 < x1) ? 1 : (-1));
			int num3 = -Math.Abs(y1 - y0);
			int num4 = ((y0 < y1) ? 1 : (-1));
			int num5 = num + num3;
			while (true)
			{
				SetPixel(x0, y0);
				if (x0 != x1 || y0 != y1)
				{
					int num6 = 2 * num5;
					if (num6 >= num3)
					{
						num5 += num3;
						x0 += num2;
					}
					if (num6 <= num)
					{
						num5 += num;
						y0 += num4;
					}
					continue;
				}
				break;
			}
		}

		private void DrawRect(int x0, int y0, int x1, int y1)
		{
			int num = Math.Min(x0, x1);
			int num2 = Math.Max(x0, x1);
			int num3 = Math.Min(y0, y1);
			int num4 = Math.Max(y0, y1);
			if (FillShapes)
			{
				for (int i = num3; i <= num4; i++)
				{
					for (int j = num; j <= num2; j++)
					{
						Put(j, i);
					}
				}
			}
			else
			{
				DrawLine(num, num3, num2, num3);
				DrawLine(num2, num3, num2, num4);
				DrawLine(num2, num4, num, num4);
				DrawLine(num, num4, num, num3);
			}
		}

		private void DrawSquare(int x0, int y0, int x1, int y1)
		{
			int num = Math.Max(Math.Abs(x1 - x0), Math.Abs(y1 - y0));
			DrawRect(x0, y0, x0 + ((x1 >= x0) ? num : (-num)), y0 + ((y1 >= y0) ? num : (-num)));
		}

		private void DrawBoxEllipse(int xa, int ya, int xb, int yb)
		{
			if (xa > xb)
			{
				int num = xb;
				xb = xa;
				xa = num;
			}
			if (ya > yb)
			{
				int num2 = yb;
				yb = ya;
				ya = num2;
			}
			double cx = (double)(xa + xb) / 2.0;
			double cy = (double)(ya + yb) / 2.0;
			double rx = (double)(xb - xa + 1) / 2.0;
			double ry = (double)(yb - ya + 1) / 2.0;
			for (int i = Math.Max(ya, 0); i <= Math.Min(yb, Side - 1); i++)
			{
				for (int j = Math.Max(xa, 0); j <= Math.Min(xb, Side - 1); j++)
				{
					if (!Inside(j, i))
					{
						continue;
					}
					if (FillShapes)
					{
						Put(j, i);
						continue;
					}
					bool flag = false;
					for (int k = 1; k <= BrushSize; k++)
					{
						if (flag)
						{
							break;
						}
						flag = !Inside(j + k, i) || !Inside(j - k, i) || !Inside(j, i + k) || !Inside(j, i - k);
					}
					if (flag)
					{
						Put(j, i);
					}
				}
			}
			bool Inside(int x, int y)
			{
				return Math.Pow(((double)x - cx) / rx, 2.0) + Math.Pow(((double)y - cy) / ry, 2.0) <= 1.0;
			}
		}

		private void DrawCircle(int cx, int cy, int x1, int y1)
		{
			int num = (int)Math.Round(Math.Sqrt((double)(x1 - cx) * (double)(x1 - cx) + (double)(y1 - cy) * (double)(y1 - cy)));
			DrawBoxEllipse(cx - num, cy - num, cx + num, cy + num);
		}

		private void Spray(int cx, int cy)
		{
			int sprayRadius = SprayRadius;
			double num = (double)SprayDensity / 100.0;
			for (int i = -sprayRadius; i <= sprayRadius; i++)
			{
				for (int j = -sprayRadius; j <= sprayRadius; j++)
				{
					if (j * j + i * i <= sprayRadius * sprayRadius && _rng.NextDouble() < num)
					{
						SetPixel(cx + j, cy + i);
					}
				}
			}
		}

		private static bool IsLand(int g)
		{
			if (g != 0)
			{
				return g != 1;
			}
			return false;
		}

		private bool Neigh4(int x, int y, Func<int, bool> f)
		{
			(int, int)[] array = new(int, int)[4]
			{
				(1, 0),
				(-1, 0),
				(0, 1),
				(0, -1)
			};
			for (int i = 0; i < array.Length; i++)
			{
				(int, int) tuple = array[i];
				int item = tuple.Item1;
				int item2 = tuple.Item2;
				int x2 = x + item;
				int y2 = y + item2;
				if (InBounds(x2, y2) && f(Data.Ground[Cell(x2, y2)]))
				{
					return true;
				}
			}
			return false;
		}

		public void Morph(string mode)
		{
			if (!HasData)
			{
				return;
			}
			PushUndo();
			int[] ground = Data.Ground;
			int[] array = (int[])ground.Clone();
			bool flag = Layer == EditLayer.Ground;
			for (int i = 0; i < Side; i++)
			{
				for (int j = 0; j < Side; j++)
				{
					bool flag2 = IsLand(ground[Cell(j, i)]);
					if (mode == "outline" && flag2 && Neigh4(j, i, (int v) => !IsLand(v)))
					{
						array[Cell(j, i)] = (flag ? GroundBrush : 3);
					}
					if (mode == "grow" && !flag2 && Neigh4(j, i, IsLand))
					{
						array[Cell(j, i)] = (flag ? GroundBrush : 2);
					}
					if (mode == "shrink" && flag2 && Neigh4(j, i, (int v) => !IsLand(v)))
					{
						array[Cell(j, i)] = 0;
					}
				}
			}
			Data.Ground = array;
			Dirty = true;
		}

		public void PointerDown(int x, int y)
		{
			if (!HasData || !InBounds(x, y))
			{
				return;
			}
			if (Layer == EditLayer.Hills)
			{
				ClickHill(x, y);
				return;
			}
			PushUndo();
			Dirty = true;
			_strokeOpen = true;
			if (Layer == EditLayer.Buildings)
			{
				int num = HitBuilding(x, y);
				if (num >= 0)
				{
					Data.Buildings.RemoveAt(num);
				}
				else
				{
					(int, int, int, int) tuple = CurrentBuilding(x, y);
					Data.Buildings.Add(new IslandBuilding
					{
						Type = tuple.Item1,
						X = x,
						Y = y,
						Orient = tuple.Item2,
						Mirror = tuple.Item3,
						Health = tuple.Item4,
						Turn = 0
					});
				}
				_strokeOpen = false;
				return;
			}
			switch (Tool)
			{
			case EditTool.Point:
				SetPixel(x, y);
				break;
			case EditTool.Fill:
				FloodFill(x, y);
				_strokeOpen = false;
				break;
			case EditTool.Spray:
				Spray(x, y);
				break;
			default:
				_dragStart = (x, y);
				_baseLayer = (int[])LayerArray.Clone();
				break;
			}
		}

		public void PointerDrag(int x, int y)
		{
			if (!HasData || !InBounds(x, y) || Layer == EditLayer.Buildings || Layer == EditLayer.Hills)
			{
				return;
			}
			if (Tool == EditTool.Point && _strokeOpen)
			{
				SetPixel(x, y);
			}
			else if (Tool == EditTool.Spray && _strokeOpen)
			{
				Spray(x, y);
			}
			else if (_dragStart.HasValue)
			{
				Array.Copy(_baseLayer, LayerArray, _baseLayer.Length);
				var (num, num2) = _dragStart.Value;
				switch (Tool)
				{
				case EditTool.Line:
					DrawLine(num, num2, x, y);
					break;
				case EditTool.Rect:
					DrawRect(num, num2, x, y);
					break;
				case EditTool.Square:
					DrawSquare(num, num2, x, y);
					break;
				case EditTool.Circle:
					DrawCircle(num, num2, x, y);
					break;
				case EditTool.Oval:
					DrawBoxEllipse(num, num2, x, y);
					break;
				}
			}
		}

		public void PointerUp()
		{
			_dragStart = null;
			_baseLayer = null;
			_strokeOpen = false;
		}

		public void RightClick(int x, int y)
		{
			if (!HasData || !InBounds(x, y))
			{
				return;
			}
			if (Layer == EditLayer.Buildings)
			{
				int num = HitBuilding(x, y);
				if (num >= 0)
				{
					PushUndo();
					Data.Buildings.RemoveAt(num);
					Dirty = true;
				}
			}
			else if (Layer == EditLayer.Hills)
			{
				int num2 = HitCliff(x, y);
				if (num2 >= 0)
				{
					PushUndo();
					RemoveCliff(num2);
				}
			}
			else
			{
				Brush = LayerArray[Cell(x, y)];
			}
		}

		public IEnumerable<(int X, int Y)> CliffFootprint(int w, int h, int x, int y, int orient, int mirror)
		{
			(int, int) tuple = CosSin(orient);
			int c = tuple.Item1;
			int s = tuple.Item2;
			(int X, int Y) a = T(0, 0);
			(int X, int Y) b = T(w - 1, h - 1);
			for (int yy = Math.Min(a.Y, b.Y); yy <= Math.Max(a.Y, b.Y); yy++)
			{
				for (int xx = Math.Min(a.X, b.X); xx <= Math.Max(a.X, b.X); xx++)
				{
					yield return (X: xx, Y: yy);
				}
			}
			(int X, int Y) T(int dx, int dy)
			{
				int num = dx * c - dy * s;
				int num2 = dx * s + dy * c;
				if (mirror != 0)
				{
					num = -num;
				}
				return (X: x + num, Y: y + num2);
			}
		}

		public IEnumerable<(int X, int Y)> CliffFootprint(IslandCliff c)
		{
			return CliffFootprint(c.W, c.H, c.X, c.Y, c.Orient, c.Mirror);
		}

		public IslandCliff CurrentHill(int x, int y)
		{
			(int, int, int, string) tuple = HillShapes[Math.Clamp(HillShape, 0, HillShapes.Length - 1)];
			return new IslandCliff
			{
				Kind = tuple.Item3,
				W = tuple.Item1,
				H = tuple.Item2,
				X = x,
				Y = y,
				Orient = (BOrient % 4 + 4) % 4,
				Mirror = (BMirror ? 1 : 0)
			};
		}

		public int HitCliff(int x, int y)
		{
			for (int i = 0; i < Data.Cliffs.Count; i++)
			{
				foreach (var (num, num2) in CliffFootprint(Data.Cliffs[i]))
				{
					if (num == x && num2 == y)
					{
						return i;
					}
				}
			}
			return -1;
		}

		private void ClickHill(int x, int y)
		{
			HillMessage = null;
			int num = HitCliff(x, y);
			if (num >= 0)
			{
				PushUndo();
				RemoveCliff(num);
				return;
			}
			IslandCliff islandCliff = CurrentHill(x, y);
			foreach (var (num2, num3) in CliffFootprint(islandCliff))
			{
				if (!InBounds(num2, num3))
				{
					HillMessage = Tx.T("hill.noFit");
					return;
				}
				int num4 = Data.Ground[Cell(num2, num3)];
				if (num4 == 0 || num4 == 1 || num4 == 6)
				{
					HillMessage = Tx.T("hill.needLand", num2, num3, GroundNames[num4].ToLowerInvariant());
					return;
				}
				if (HitBuilding(num2, num3) >= 0)
				{
					HillMessage = Tx.T("hill.building", num2, num3);
					return;
				}
				if (HitCliff(num2, num3) >= 0)
				{
					HillMessage = Tx.T("hill.covered", num2, num3);
					return;
				}
			}
			PushUndo();
			Data.Cliffs.Add(islandCliff);
			foreach (var (x2, y2) in CliffFootprint(islandCliff))
			{
				Data.Ground[Cell(x2, y2)] = 4;
				Data.Nature[Cell(x2, y2)] = -1;
			}
			Dirty = true;
		}

		public int MakeHillsVisible()
		{
			if (!HasData)
			{
				return 0;
			}
			int side = Side;
			int count;
			bool[] array = UncoveredHillTiles(out count);
			if (count == 0)
			{
				return 0;
			}
			List<(int, int, int, int)> list = new List<(int, int, int, int)>();
			(int, int)[] array2 = new(int, int)[5]
			{
				(0, 0),
				(1, 0),
				(3, 0),
				(3, 1),
				(4, 0)
			};
			for (int i = 0; i < array2.Length; i++)
			{
				(int, int) tuple = array2[i];
				int item = tuple.Item1;
				int item2 = tuple.Item2;
				(int, int, int, string) tuple2 = HillShapes[item];
				int num = int.MaxValue;
				int num2 = int.MaxValue;
				foreach (var item9 in CliffFootprint(tuple2.Item1, tuple2.Item2, 0, 0, item2, 0))
				{
					int item3 = item9.X;
					int item4 = item9.Y;
					num = Math.Min(num, item3);
					num2 = Math.Min(num2, item4);
				}
				list.Add((item, item2, -num, -num2));
			}
			PushUndo();
			int num3 = 0;
			for (int j = 0; j < side; j++)
			{
				for (int k = 0; k < side; k++)
				{
					if (!array[Cell(k, j)])
					{
						continue;
					}
					foreach (var item10 in list)
					{
						int item5 = item10.Item1;
						int item6 = item10.Item2;
						int item7 = item10.Item3;
						int item8 = item10.Item4;
						(int, int, int, string) tuple3 = HillShapes[item5];
						IslandCliff islandCliff = new IslandCliff
						{
							Kind = tuple3.Item3,
							W = tuple3.Item1,
							H = tuple3.Item2,
							X = k + item7,
							Y = j + item8,
							Orient = item6,
							Mirror = 0
						};
						bool flag = true;
						foreach (var (x, y) in CliffFootprint(islandCliff))
						{
							if (!InBounds(x, y) || !array[Cell(x, y)])
							{
								flag = false;
								break;
							}
						}
						if (!flag)
						{
							continue;
						}
						foreach (var (x2, y2) in CliffFootprint(islandCliff))
						{
							array[Cell(x2, y2)] = false;
							Data.Nature[Cell(x2, y2)] = -1;
						}
						Data.Cliffs.Add(islandCliff);
						num3++;
						break;
					}
				}
			}
			Dirty = true;
			return num3;
		}

		public int InvisibleHillTiles()
		{
			if (!HasData)
			{
				return 0;
			}
			UncoveredHillTiles(out var count);
			return count;
		}

		private bool[] UncoveredHillTiles(out int count)
		{
			bool[] array = new bool[Side * Side];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = Data.Ground[i] == 4;
			}
			foreach (IslandCliff cliff in Data.Cliffs)
			{
				foreach (var (x, y) in CliffFootprint(cliff))
				{
					if (InBounds(x, y))
					{
						array[Cell(x, y)] = false;
					}
				}
			}
			count = 0;
			for (int j = 0; j < array.Length; j++)
			{
				if (array[j])
				{
					count++;
				}
			}
			return array;
		}

		private void RemoveCliff(int index)
		{
			IslandCliff c = Data.Cliffs[index];
			Data.Cliffs.RemoveAt(index);
			foreach (var (x, y) in CliffFootprint(c))
			{
				if (InBounds(x, y) && Data.Ground[Cell(x, y)] == 4 && HitCliff(x, y) < 0)
				{
					Data.Ground[Cell(x, y)] = 2;
				}
			}
			Dirty = true;
		}

		public (int Type, int Orient, int Mirror, int Health) CurrentBuilding(int x, int y)
		{
			int num2;
			if (BHealth <= 0)
			{
				int? num = Table.Get(BType)?.Hp;
				if (num.HasValue)
				{
					int valueOrDefault = num.GetValueOrDefault();
					if (valueOrDefault > 0)
					{
						num2 = valueOrDefault;
						goto IL_0056;
					}
				}
				num2 = 100;
			}
			else
			{
				num2 = BHealth;
			}
			goto IL_0056;
			IL_0056:
			int item = num2;
			return (Type: BType, Orient: (BOrient % 4 + 4) % 4, Mirror: BMirror ? 1 : 0, Health: item);
		}

		private static (int C, int S) CosSin(int orient)
		{
			return ((orient % 4 + 4) % 4) switch
			{
				0 => (C: 1, S: 0), 
				1 => (C: 0, S: 1), 
				2 => (C: -1, S: 0), 
				_ => (C: 0, S: -1), 
			};
		}

		public IEnumerable<(int X, int Y)> Footprint(int type, int x, int y, int orient, int mirror)
		{
			int[][] array = Table.Get(type)?.Shape;
			if (array == null || array.Length == 0)
			{
				yield return (X: x, Y: y);
				yield break;
			}
			(int, int) tuple = CosSin(orient);
			int c = tuple.Item1;
			int s = tuple.Item2;
			int[][] array2 = array;
			foreach (int[] array3 in array2)
			{
				int num = array3[0] * c - array3[1] * s;
				int num2 = array3[0] * s + array3[1] * c;
				if (mirror != 0)
				{
					num = -num;
				}
				yield return (X: x + num, Y: y + num2);
			}
		}

		public IEnumerable<(int X, int Y)> Footprint(IslandBuilding b)
		{
			return Footprint(b.Type, b.X, b.Y, b.Orient, b.Mirror);
		}

		public int HitBuilding(int x, int y)
		{
			for (int i = 0; i < Data.Buildings.Count; i++)
			{
				foreach (var (num, num2) in Footprint(Data.Buildings[i]))
				{
					if (num == x && num2 == y)
					{
						return i;
					}
				}
			}
			return -1;
		}

		public List<string> Check()
		{
			Problems.Clear();
			List<string> list = new List<string>();
			if (!HasData)
			{
				return list;
			}
			Dictionary<(int, int), int> dictionary = new Dictionary<(int, int), int>();
			for (int i = 0; i < Data.Buildings.Count; i++)
			{
				IslandBuilding islandBuilding = Data.Buildings[i];
				string text = Table.NameOf(islandBuilding.Type);
				foreach (var (num, num2) in Footprint(islandBuilding))
				{
					if (!InBounds(num, num2))
					{
						Problems.Add((num, num2));
						list.Add(Tx.T("check.outside", text, islandBuilding.X, islandBuilding.Y));
						continue;
					}
					if (Data.Nature[Cell(num, num2)] != -1)
					{
						Problems.Add((num, num2));
						list.Add(Tx.T("check.nature", text, islandBuilding.X, islandBuilding.Y, num, num2));
					}
					int num3 = Data.Ground[Cell(num, num2)];
					if ((num3 == 0 || num3 == 1) && islandBuilding.Type != 6 && islandBuilding.Type != 21 && islandBuilding.Type != 22)
					{
						Problems.Add((num, num2));
						list.Add(Tx.T("check.water", text, islandBuilding.X, islandBuilding.Y, num, num2));
					}
					if (num3 == 4)
					{
						Problems.Add((num, num2));
						list.Add(Tx.T("check.onHill", text, islandBuilding.X, islandBuilding.Y, num, num2));
					}
					if (dictionary.TryGetValue((num, num2), out var value) && value != i)
					{
						Problems.Add((num, num2));
						list.Add(Tx.T("check.overlapsBuilding", text, islandBuilding.X, islandBuilding.Y, Table.NameOf(Data.Buildings[value].Type), num, num2));
					}
					dictionary[(num, num2)] = i;
				}
			}
			Dictionary<(int, int), int> dictionary2 = new Dictionary<(int, int), int>();
			for (int j = 0; j < Data.Cliffs.Count; j++)
			{
				IslandCliff islandCliff = Data.Cliffs[j];
				string text2 = Tx.T("check.hill", islandCliff.W, islandCliff.H);
				foreach (var (num4, num5) in CliffFootprint(islandCliff))
				{
					if (!InBounds(num4, num5))
					{
						Problems.Add((num4, num5));
						list.Add(Tx.T("check.outside", text2, islandCliff.X, islandCliff.Y));
						continue;
					}
					int num6 = Data.Ground[Cell(num4, num5)];
					if (num6 != 4)
					{
						Problems.Add((num4, num5));
						list.Add(Tx.T("check.notHillGround", text2, islandCliff.X, islandCliff.Y, num4, num5, (num6 >= 0 && num6 < GroundNames.Length) ? GroundNames[num6].ToLowerInvariant() : ("#" + num6)));
					}
					if (dictionary2.TryGetValue((num4, num5), out var value2) && value2 != j)
					{
						Problems.Add((num4, num5));
						list.Add(Tx.T("check.overlapHill", text2, islandCliff.X, islandCliff.Y, num4, num5));
					}
					dictionary2[(num4, num5)] = j;
				}
			}
			int num7 = InvisibleHillTiles();
			if (num7 > 0)
			{
				list.Add(Tx.T("check.invisible", num7));
			}
			return list;
		}

		public void ClearNatureUnderBuildings()
		{
			if (!HasData)
			{
				return;
			}
			PushUndo();
			foreach (IslandBuilding building in Data.Buildings)
			{
				foreach (var (x, y) in Footprint(building))
				{
					if (InBounds(x, y))
					{
						Data.Nature[Cell(x, y)] = -1;
					}
				}
			}
			Problems.Clear();
			Dirty = true;
		}

		public void SetAllHpToDefault()
		{
			if (!HasData)
			{
				return;
			}
			PushUndo();
			foreach (IslandBuilding building in Data.Buildings)
			{
				BuildingInfo buildingInfo = Table.Get(building.Type);
				if (buildingInfo != null && buildingInfo.Hp > 0)
				{
					building.Health = buildingInfo.Hp;
				}
			}
			Dirty = true;
		}

		public string Summary()
		{
			if (!HasData)
			{
				return Tx.T("summary.none");
			}
			int num = 0;
			int[] ground = Data.Ground;
			foreach (int num2 in ground)
			{
				if (num2 != 0 && num2 != 1)
				{
					num++;
				}
			}
			return Tx.T("summary", Side, num, Data.Buildings.Count, Data.Cliffs.Count);
		}
	}
	internal static class EditorWindow
	{
		private static readonly EditorModel M = new EditorModel();

		private static bool _yUp = true;

		private static UiWindow _win;

		private static string _titleShown;

		private static bool _painting;

		private static bool _texDirty;

		private static bool _uiDirty;

		private static bool _viewDirty;

		private static bool _refreshing;

		private static string _hoverKey = "";

		private static (int X, int Y)? _hoverTile;

		private static readonly List<string> _checkLines = new List<string>();

		private static UiImage _map;

		private static UiText _noData;

		private static UiText _status;

		private static UiText _hover;

		private static UiText _checks;

		private static UiText _playerLbl;

		private static UiText _bName;

		private static UiText _bInfo;

		private static UiContainer _paintGroup;

		private static UiContainer _groundGroup;

		private static UiContainer _natureGroup;

		private static UiContainer _sprayGroup;

		private static UiContainer _buildGroup;

		private static UiContainer _hillGroup;

		private static readonly List<UiButton> _layerBtn = new List<UiButton>();

		private static readonly List<UiButton> _toolBtn = new List<UiButton>();

		private static readonly List<UiButton> _groundBtn = new List<UiButton>();

		private static readonly List<UiButton> _natureBtn = new List<UiButton>();

		private static readonly List<UiButton> _hillBtn = new List<UiButton>();

		private static UiButton _rotateBtn;

		private static UiButton _hillRotateBtn;

		private static UiToggle _symX;

		private static UiToggle _symY;

		private static UiToggle _fill;

		private static UiToggle _yUpTog;

		private static UiToggle _mirrorTog;

		private static UiToggle _hillMirrorTog;

		private static UiScroll _left;

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

		private static Vector2 _pointerAt;

		private static int _dragButton = -1;

		private static float _dragMoved;

		internal static readonly Color32[] GroundColors = (Color32[])(object)new Color32[7]
		{
			C(2060171),
			C(5991283),
			C(4886332),
			C(15259048),
			C(9075299),
			C(10132122),
			C(12159565)
		};

		internal static readonly Color32[] NatureColors = (Color32[])(object)new Color32[6]
		{
			C(1859114),
			C(7039851),
			C(5913887),
			C(12670763),
			C(13909882),
			C(3056583)
		};

		private static string[] ToolNames => new string[8]
		{
			Tx.T("tool.0"),
			Tx.T("tool.1"),
			Tx.T("tool.2"),
			Tx.T("tool.3"),
			Tx.T("tool.4"),
			Tx.T("tool.5"),
			Tx.T("tool.6"),
			Tx.T("tool.7")
		};

		private static string[] LayerNames => new string[4]
		{
			Tx.T("layer.0"),
			Tx.T("layer.1"),
			Tx.T("layer.2"),
			Tx.T("layer.3")
		};

		internal static bool IsOpen => _win != null;

		internal static byte[] CurrentCode()
		{
			if (!M.HasData)
			{
				return null;
			}
			return IslandCodec.ToCodeBytes(M.Data);
		}

		internal static void Install()
		{
			Islands.SelectionChanged += delegate
			{
				_uiDirty = true;
				Flush();
			};
		}

		internal static void Toggle()
		{
			if (IsOpen)
			{
				Close();
			}
			else
			{
				Open();
			}
		}

		internal static void KeyRotate()
		{
			Run(delegate
			{
				M.BOrient = (M.BOrient + 1) % 4;
				_hoverKey = "";
				_uiDirty = true;
			});
		}

		internal static void KeyMirror()
		{
			Run(delegate
			{
				M.BMirror = !M.BMirror;
				_hoverKey = "";
				_uiDirty = true;
			});
		}

		internal static void KeyUndo()
		{
			Run(delegate
			{
				if (M.CanUndo)
				{
					M.Undo();
					AfterEdit(redraw: true);
				}
			});
		}

		internal static void KeyRedo()
		{
			Run(delegate
			{
				if (M.CanRedo)
				{
					M.Redo();
					AfterEdit(redraw: true);
				}
			});
		}

		internal static void Close()
		{
			UiWindow win = _win;
			if (win != null)
			{
				win.Close();
			}
		}

		internal static void Open()
		{
			if (IsOpen)
			{
				_win.BringToFront();
				return;
			}
			_layerBtn.Clear();
			_toolBtn.Clear();
			_groundBtn.Clear();
			_natureBtn.Clear();
			_hillBtn.Clear();
			_steppers.Clear();
			UiScope ui = Windows.Ui;
			_win = ((ui != null) ? ui.Custom.Window((Action<UiWindow>)delegate(UiWindow w)
			{
				//IL_026e: Unknown result type (might be due to invalid IL or missing references)
				//IL_02a2: Unknown result type (might be due to invalid IL or missing references)
				w.Title(Tx.T("editor.title")).Size((float)Options.WindowWidth.Value, (float)Options.WindowHeight.Value).Position(60f, 40f)
					.Draggable(true)
					.Closable(true)
					.Fullscreenable(true)
					.FullscreenButton(true);
				w.OnClose((Action)Closed);
				UiContainer titleBar = w.TitleBar;
				if (titleBar != null)
				{
					titleBar.Button(Tx.T("editor.help"), (Action)HelpWindow.Toggle);
				}
				UiContainer titleBar2 = w.TitleBar;
				if (titleBar2 != null)
				{
					titleBar2.Button("-", (Action)delegate
					{
						Resize(0.9f);
					});
				}
				UiContainer titleBar3 = w.TitleBar;
				if (titleBar3 != null)
				{
					titleBar3.Button("+", (Action)delegate
					{
						Resize(1.1f);
					});
				}
				UiContainer body = w.Body;
				body.Spacing(6f);
				UiContainer obj = body.Row((Action<UiContainer>)delegate(UiContainer r)
				{
					Btn(r, Tx.T("editor.loadMine"), delegate
					{
						LoadFrom(Islands.Local);
					});
					Btn(r, Tx.T("editor.applyMine"), delegate
					{
						ApplyTo(Islands.Local);
					});
					Btn(r, Tx.T("editor.newBlank"), NewBlank);
					Btn(r, Tx.T("editor.paste"), PasteCode);
					Btn(r, Tx.T("editor.copy"), CopyCode);
				});
				if (obj != null)
				{
					UiLayout.Height<UiContainer>(obj, 34f);
				}
				UiContainer obj2 = body.Row((Action<UiContainer>)delegate(UiContainer r)
				{
					UiText obj8 = r.Text("");
					_playerLbl = ((obj8 != null) ? UiLayout.WeightW<UiText>(obj8, 2f) : null);
					Btn(r, Tx.T("editor.players"), PlayersWindow.Toggle);
					Btn(r, Tx.T("editor.nextPlayer"), Islands.SelectNext);
					Btn(r, Tx.T("editor.loadSelected"), delegate
					{
						LoadFrom(Islands.Selected);
					});
					Btn(r, Tx.T("editor.applySelected"), delegate
					{
						ApplyTo(Islands.Selected);
					});
				});
				if (obj2 != null)
				{
					UiLayout.Height<UiContainer>(obj2, 34f);
				}
				UiContainer obj3 = body.Row((Action<UiContainer>)delegate(UiContainer main)
				{
					main.Spacing(10f);
					UiScroll obj8 = main.Scroll((Action<UiContainer>)BuildLeftPanel);
					_left = ((obj8 != null) ? UiLayout.FillHeight<UiScroll>(UiLayout.FixedW<UiScroll>(obj8, LeftWidth())) : null);
					UiContainer obj9 = main.Column((Action<UiContainer>)delegate(UiContainer col)
					{
						_noData = col.Paragraph(Tx.T("editor.noData"));
						UiImage obj10 = col.Image((Texture)null);
						_map = ((obj10 != null) ? UiLayout.FillHeight<UiImage>(UiLayout.FillWidth<UiImage>(obj10.KeepAspect(false))) : null);
						UiImage map = _map;
						if (map != null)
						{
							map.OnPointer((Action<UiPointerEvent>)OnPointer);
						}
						UiImage map2 = _map;
						if (map2 != null)
						{
							map2.OnScroll((Action<float>)delegate(float n)
							{
								Run(delegate
								{
									//IL_0006: Unknown result type (might be due to invalid IL or missing references)
									MapView.Zoom(n, _pointerAt);
									_texDirty = true;
								});
							});
						}
						UiImage map3 = _map;
						if (map3 != null)
						{
							map3.OnResize((Action<Vector2>)delegate
							{
								Run(delegate
								{
									_texDirty = true;
								});
							});
						}
					});
					if (obj9 != null)
					{
						UiLayout.FillHeight<UiContainer>(UiLayout.FillWidth<UiContainer>(obj9));
					}
				});
				if (obj3 != null)
				{
					UiLayout.FillHeight<UiContainer>(obj3);
				}
				UiContainer obj4 = body.Row((Action<UiContainer>)delegate(UiContainer r)
				{
					Btn(r, Tx.T("editor.undo"), delegate
					{
						if (M.CanUndo)
						{
							M.Undo();
							AfterEdit(redraw: true);
						}
					});
					Btn(r, Tx.T("editor.redo"), delegate
					{
						if (M.CanRedo)
						{
							M.Redo();
							AfterEdit(redraw: true);
						}
					});
					Btn(r, Tx.T("editor.check"), RunCheck);
					Btn(r, Tx.T("editor.clearNature"), delegate
					{
						M.ClearNatureUnderBuildings();
						SetStatus(Tx.T("editor.natureCleared"));
						AfterEdit(redraw: true);
					});
					Btn(r, Tx.T("editor.hpDefault"), delegate
					{
						M.SetAllHpToDefault();
						SetStatus(Tx.T("editor.hpDone"));
						AfterEdit(redraw: false);
					});
				});
				if (obj4 != null)
				{
					UiLayout.Height<UiContainer>(obj4, 34f);
				}
				UiContainer obj5 = body.Row((Action<UiContainer>)delegate(UiContainer r)
				{
					Btn(r, Tx.T("editor.coastOutline"), delegate
					{
						M.Morph("outline");
						AfterEdit(redraw: true);
					});
					Btn(r, Tx.T("editor.coastGrow"), delegate
					{
						M.Morph("grow");
						AfterEdit(redraw: true);
					});
					Btn(r, Tx.T("editor.coastShrink"), delegate
					{
						M.Morph("shrink");
						AfterEdit(redraw: true);
					});
					Btn(r, Tx.T("editor.fit"), delegate
					{
						MapView.Fit();
						_texDirty = true;
					});
					UiToggle obj8 = r.Toggle(Tx.T("editor.yUp"), _yUp, (Action<bool>)delegate(bool v)
					{
						Changed(delegate
						{
							_yUp = v;
							AfterEdit(redraw: true);
						});
					});
					_yUpTog = ((obj8 != null) ? UiLayout.WeightW<UiToggle>(obj8, 2f) : null);
				});
				if (obj5 != null)
				{
					UiLayout.Height<UiContainer>(obj5, 34f);
				}
				_status = body.Text(Tx.T("editor.start"));
				UiText obj6 = body.Text("");
				_hover = ((obj6 != null) ? obj6.Color(new Color(0.75f, 0.8f, 0.9f, 1f)) : null);
				UiText obj7 = body.Paragraph("");
				_checks = ((obj7 != null) ? obj7.Color(new Color(1f, 0.55f, 0.5f, 1f)) : null);
			}) : null);
			if (_win != null)
			{
				_uiDirty = (_texDirty = (_viewDirty = true));
				Flush();
				Windows.Refresh();
			}
		}

		private static void Closed()
		{
			_win = null;
			_map = null;
			_left = null;
			_noData = (_status = (_hover = (_checks = (_playerLbl = (_bName = (_bInfo = null))))));
			_painting = false;
			_hoverTile = null;
			_hoverKey = "";
			_titleShown = null;
			_dragButton = -1;
			MapView.Release();
			Windows.Refresh();
		}

		private static UiButton Btn(UiContainer row, string text, Action click)
		{
			UiButton obj = row.Button(text, (Action)delegate
			{
				Run(click);
			});
			if (obj == null)
			{
				return null;
			}
			return UiLayout.FillWidth<UiButton>(obj);
		}

		private static void Changed(Action change)
		{
			if (!_refreshing)
			{
				Run(change);
			}
		}

		private static void Run(Action action)
		{
			try
			{
				action();
			}
			catch (Exception ex)
			{
				Plugin.L.LogError((object)("[editor] " + ex));
			}
			Flush();
		}

		private static float LeftWidth()
		{
			return Mathf.Clamp((float)Options.WindowWidth.Value * 0.3f, 240f, 340f);
		}

		private static void Resize(float factor)
		{
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			if (IsOpen)
			{
				int num = Mathf.Clamp(Mathf.RoundToInt((float)Options.WindowWidth.Value * factor), 720, 2400);
				int num2 = Mathf.Clamp(Mathf.RoundToInt((float)Options.WindowHeight.Value * factor), 560, 1400);
				Options.WindowWidth.Value = num;
				Options.WindowHeight.Value = num2;
				Vector2 anchoredPosition = ((UiElement)_win).Root.anchoredPosition;
				_win.Size((float)num, (float)num2);
				_win.Position(anchoredPosition.x, 0f - anchoredPosition.y);
				UiScroll left = _left;
				if (left != null)
				{
					UiLayout.FixedW<UiScroll>(left, LeftWidth());
				}
				SetStatus(Tx.T("editor.windowSize", num, num2));
			}
		}

		private static void Stepper(UiContainer parent, string text, Func<int> get, Action<int> set, int min, int max, int step)
		{
			UiText value = null;
			UiContainer obj = parent.Row((Action<UiContainer>)delegate(UiContainer r)
			{
				r.Spacing(4f);
				UiText obj2 = r.Text(text);
				if (obj2 != null)
				{
					UiLayout.FillWidth<UiText>(obj2);
				}
				UiButton obj3 = r.Button("-", (Action)delegate
				{
					Run(delegate
					{
						set(Mathf.Max(min, get() - step));
						_uiDirty = true;
					});
				});
				if (obj3 != null)
				{
					UiLayout.FixedW<UiButton>(obj3, 38f);
				}
				UiText obj4 = r.Text("");
				value = ((obj4 != null) ? UiLayout.FixedW<UiText>(obj4.Align((TextAlignmentOptions)514), 48f) : null);
				UiButton obj5 = r.Button("+", (Action)delegate
				{
					Run(delegate
					{
						set(Mathf.Min(max, get() + step));
						_uiDirty = true;
					});
				});
				if (obj5 != null)
				{
					UiLayout.FixedW<UiButton>(obj5, 38f);
				}
			});
			if (obj != null)
			{
				UiLayout.Height<UiContainer>(obj, 32f);
			}
			_steppers.Add(delegate
			{
				if (value != null)
				{
					value.Value = get().ToString();
				}
			});
		}

		private static void BuildLeftPanel(UiContainer c)
		{
			c.Spacing(4f);
			UiContainer obj = c.Row((Action<UiContainer>)delegate(UiContainer r)
			{
				for (int i = 0; i < LayerNames.Length; i++)
				{
					int idx = i;
					_layerBtn.Add(Btn(r, LayerNames[i], delegate
					{
						M.Layer = (EditLayer)idx;
						_hoverKey = "";
						_uiDirty = true;
					}));
				}
			});
			if (obj != null)
			{
				UiLayout.Height<UiContainer>(obj, 32f);
			}
			_paintGroup = c.Column((Action<UiContainer>)delegate(UiContainer p)
			{
				p.Spacing(4f);
				Pairs(p, ToolNames, _toolBtn, delegate(int i)
				{
					M.Tool = (EditTool)i;
					_uiDirty = true;
				});
				p.Text(Tx.T("editor.brush"));
				_groundGroup = p.Column((Action<UiContainer>)delegate(UiContainer g)
				{
					g.Spacing(4f);
					Pairs(g, EditorModel.GroundNames, _groundBtn, delegate(int i)
					{
						M.GroundBrush = i;
						_uiDirty = true;
					});
				});
				_natureGroup = p.Column((Action<UiContainer>)delegate(UiContainer g)
				{
					g.Spacing(4f);
					List<string> list = new List<string> { Tx.T("editor.erase") };
					list.AddRange(EditorModel.NatureNames);
					Pairs(g, list.ToArray(), _natureBtn, delegate(int i)
					{
						M.NatureBrush = i - 1;
						_uiDirty = true;
					});
				});
				Stepper(p, Tx.T("editor.brushSize"), () => M.BrushSize, delegate(int v)
				{
					M.BrushSize = v;
				}, 1, 9, 1);
				_symX = p.Toggle(Tx.T("editor.symX"), M.SymX, (Action<bool>)delegate(bool v)
				{
					Changed(delegate
					{
						M.SymX = v;
					});
				});
				_symY = p.Toggle(Tx.T("editor.symY"), M.SymY, (Action<bool>)delegate(bool v)
				{
					Changed(delegate
					{
						M.SymY = v;
					});
				});
				_fill = p.Toggle(Tx.T("editor.filled"), M.FillShapes, (Action<bool>)delegate(bool v)
				{
					Changed(delegate
					{
						M.FillShapes = v;
					});
				});
				_sprayGroup = p.Column((Action<UiContainer>)delegate(UiContainer s)
				{
					s.Spacing(4f);
					Stepper(s, Tx.T("editor.sprayRadius"), () => M.SprayRadius, delegate(int v)
					{
						M.SprayRadius = v;
					}, 1, 15, 1);
					Stepper(s, Tx.T("editor.sprayDensity"), () => M.SprayDensity, delegate(int v)
					{
						M.SprayDensity = v;
					}, 5, 100, 5);
				});
			});
			_buildGroup = c.Column((Action<UiContainer>)delegate(UiContainer g)
			{
				g.Spacing(4f);
				g.Paragraph(Tx.T("editor.bldgHelp"));
				UiContainer obj2 = g.Row((Action<UiContainer>)delegate(UiContainer r)
				{
					UiButton obj4 = r.Button("<", (Action)delegate
					{
						Run(delegate
						{
							CycleBuilding(-1);
						});
					});
					if (obj4 != null)
					{
						UiLayout.FixedW<UiButton>(obj4, 44f);
					}
					UiText obj5 = r.Text("");
					_bName = ((obj5 != null) ? UiLayout.FillWidth<UiText>(obj5.Align((TextAlignmentOptions)514)) : null);
					UiButton obj6 = r.Button(">", (Action)delegate
					{
						Run(delegate
						{
							CycleBuilding(1);
						});
					});
					if (obj6 != null)
					{
						UiLayout.FixedW<UiButton>(obj6, 44f);
					}
				});
				if (obj2 != null)
				{
					UiLayout.Height<UiContainer>(obj2, 32f);
				}
				_bInfo = g.Text("");
				UiContainer obj3 = g.Row((Action<UiContainer>)delegate(UiContainer r)
				{
					_rotateBtn = Btn(r, Tx.T("editor.rotate"), delegate
					{
						M.BOrient = (M.BOrient + 1) % 4;
						_hoverKey = "";
						_uiDirty = true;
					});
					UiToggle obj4 = r.Toggle(Tx.T("editor.mirrored"), M.BMirror, (Action<bool>)delegate(bool v)
					{
						Changed(delegate
						{
							M.BMirror = v;
							_hoverKey = "";
							_uiDirty = true;
						});
					});
					_mirrorTog = ((obj4 != null) ? UiLayout.FillWidth<UiToggle>(obj4) : null);
				});
				if (obj3 != null)
				{
					UiLayout.Height<UiContainer>(obj3, 32f);
				}
				Stepper(g, Tx.T("editor.hp"), () => M.BHealth, delegate(int v)
				{
					M.BHealth = v;
				}, 0, 1000, 5);
				g.Paragraph(Tx.T("editor.bldgPreview"));
			});
			_hillGroup = c.Column((Action<UiContainer>)delegate(UiContainer g)
			{
				g.Spacing(4f);
				g.Paragraph(Tx.T("editor.hillHelp"));
				string[] array = new string[EditorModel.HillShapes.Length];
				for (int i = 0; i < array.Length; i++)
				{
					array[i] = EditorModel.HillShapes[i].Name;
				}
				Pairs(g, array, _hillBtn, delegate(int hillShape)
				{
					M.HillShape = hillShape;
					_hoverKey = "";
					_uiDirty = true;
				});
				UiContainer obj2 = g.Row((Action<UiContainer>)delegate(UiContainer r)
				{
					_hillRotateBtn = Btn(r, Tx.T("editor.rotate"), delegate
					{
						M.BOrient = (M.BOrient + 1) % 4;
						_hoverKey = "";
						_uiDirty = true;
					});
					UiToggle obj4 = r.Toggle(Tx.T("editor.mirrored"), M.BMirror, (Action<bool>)delegate(bool v)
					{
						Changed(delegate
						{
							M.BMirror = v;
							_hoverKey = "";
							_uiDirty = true;
						});
					});
					_hillMirrorTog = ((obj4 != null) ? UiLayout.FillWidth<UiToggle>(obj4) : null);
				});
				if (obj2 != null)
				{
					UiLayout.Height<UiContainer>(obj2, 32f);
				}
				UiContainer obj3 = g.Row((Action<UiContainer>)delegate(UiContainer r)
				{
					Btn(r, Tx.T("editor.hillsVisible"), MakeHillsVisible);
				});
				if (obj3 != null)
				{
					UiLayout.Height<UiContainer>(obj3, 32f);
				}
				g.Paragraph(Tx.T("editor.hillsInfo") ?? "");
			});
		}

		private static void MakeHillsVisible()
		{
			int num = M.MakeHillsVisible();
			SetStatus((num > 0) ? Tx.T("editor.hillsAdded", num) : Tx.T("editor.hillsNone"));
			AfterEdit(redraw: true);
		}

		private static void Pairs(UiContainer parent, string[] names, List<UiButton> store, Action<int> click)
		{
			for (int i = 0; i < names.Length; i += 2)
			{
				int a = i;
				int b = i + 1;
				UiContainer obj = parent.Row((Action<UiContainer>)delegate(UiContainer r)
				{
					r.Spacing(4f);
					store.Add(Btn(r, names[a], delegate
					{
						click(a);
					}));
					if (b < names.Length)
					{
						store.Add(Btn(r, names[b], delegate
						{
							click(b);
						}));
					}
					else
					{
						UiText obj2 = r.Text("");
						if (obj2 != null)
						{
							UiLayout.FillWidth<UiText>(obj2);
						}
					}
				});
				if (obj != null)
				{
					UiLayout.Height<UiContainer>(obj, 32f);
				}
			}
		}

		private static void Flush()
		{
			if (!IsOpen)
			{
				return;
			}
			try
			{
				if (_uiDirty)
				{
					RefreshUi();
				}
				if (_texDirty)
				{
					RenderTexture();
				}
				UpdatePreview();
				if (_viewDirty)
				{
					Upload();
				}
			}
			catch (Exception ex)
			{
				Plugin.L.LogError((object)("[editor] redraw: " + ex));
			}
		}

		private static void SetStatus(string s)
		{
			if (_status != null)
			{
				_status.Value = s;
			}
		}

		private static void AfterEdit(bool redraw)
		{
			_uiDirty = true;
			if (redraw)
			{
				_texDirty = true;
			}
			_checkLines.Clear();
		}

		private static void Show(UiElement e, bool on)
		{
			GameObject val = (((Object)(object)((e != null) ? e.Root : null) != (Object)null) ? ((Component)e.Root).gameObject : null);
			if ((Object)(object)val != (Object)null && val.activeSelf != on)
			{
				val.SetActive(on);
			}
		}

		private static void RefreshUi()
		{
			_uiDirty = false;
			_refreshing = true;
			try
			{
				BuildingTable table = Buildings.Table;
				if (M.Table != table)
				{
					M.Table = table;
					if (M.Table.Get(M.BType) == null)
					{
						using SortedDictionary<int, BuildingInfo>.KeyCollection.Enumerator enumerator = M.Table.ById.Keys.GetEnumerator();
						if (enumerator.MoveNext())
						{
							int current = enumerator.Current;
							M.BType = current;
						}
					}
				}
				string text = Tx.T("editor.title") + (M.Dirty ? " *" : "");
				if (text != _titleShown)
				{
					_titleShown = text;
					_win.Title(text);
				}
				if (_playerLbl != null)
				{
					UiText playerLbl = _playerLbl;
					object[] array = new object[1];
					MatchPlayer selected = Islands.Selected;
					array[0] = ((selected != null) ? selected.Name : null) ?? Tx.T("editor.pressNext");
					playerLbl.Value = Tx.T("editor.selected", array);
				}
				bool flag = M.Layer == EditLayer.Ground || M.Layer == EditLayer.Nature;
				Show((UiElement)(object)_paintGroup, flag);
				Show((UiElement)(object)_buildGroup, M.Layer == EditLayer.Buildings);
				Show((UiElement)(object)_hillGroup, M.Layer == EditLayer.Hills);
				for (int i = 0; i < _hillBtn.Count; i++)
				{
					UiButton obj = _hillBtn[i];
					if (obj != null)
					{
						obj.Selected(M.HillShape == i);
					}
				}
				Show((UiElement)(object)_groundGroup, M.Layer == EditLayer.Ground);
				Show((UiElement)(object)_natureGroup, M.Layer == EditLayer.Nature);
				Show((UiElement)(object)_sprayGroup, flag && M.Tool == EditTool.Spray);
				for (int j = 0; j < _layerBtn.Count; j++)
				{
					UiButton obj2 = _layerBtn[j];
					if (obj2 != null)
					{
						obj2.Selected(M.Layer == (EditLayer)j);
					}
				}
				for (int k = 0; k < _toolBtn.Count; k++)
				{
					UiButton obj3 = _toolBtn[k];
					if (obj3 != null)
					{
						obj3.Selected(M.Tool == (EditTool)k);
					}
				}
				for (int l = 0; l < _groundBtn.Count; l++)
				{
					UiButton obj4 = _groundBtn[l];
					if (obj4 != null)
					{
						obj4.Selected(M.GroundBrush == l);
					}
				}
				for (int m = 0; m < _natureBtn.Count; m++)
				{
					UiButton obj5 = _natureBtn[m];
					if (obj5 != null)
					{
						obj5.Selected(M.NatureBrush == m - 1);
					}
				}
				foreach (Action stepper in _steppers)
				{
					stepper();
				}
				UiToggle symX = _symX;
				if (symX != null)
				{
					symX.Set(M.SymX);
				}
				UiToggle symY = _symY;
				if (symY != null)
				{
					symY.Set(M.SymY);
				}
				UiToggle fill = _fill;
				if (fill != null)
				{
					fill.Set(M.FillShapes);
				}
				UiToggle yUpTog = _yUpTog;
				if (yUpTog != null)
				{
					yUpTog.Set(_yUp);
				}
				BuildingInfo buildingInfo = M.Table.Get(M.BType);
				if (_bName != null)
				{
					_bName.Value = M.BType + ": " + M.Table.NameOf(M.BType);
				}
				if (_bInfo != null)
				{
					_bInfo.Value = ((buildingInfo == null) ? Tx.T("editor.unknownType") : Tx.T("editor.bInfo", buildingInfo.Tier, buildingInfo.Hp, buildingInfo.Shape.Length));
				}
				UiButton rotateBtn = _rotateBtn;
				if (rotateBtn != null)
				{
					rotateBtn.Text(Tx.T("editor.rotateN", (M.BOrient % 4 + 4) % 4));
				}
				UiToggle mirrorTog = _mirrorTog;
				if (mirrorTog != null)
				{
					mirrorTog.Set(M.BMirror);
				}
				UiButton hillRotateBtn = _hillRotateBtn;
				if (hillRotateBtn != null)
				{
					hillRotateBtn.Text(Tx.T("editor.rotateN", (M.BOrient % 4 + 4) % 4));
				}
				UiToggle hillMirrorTog = _hillMirrorTog;
				if (hillMirrorTog != null)
				{
					hillMirrorTog.Set(M.BMirror);
				}
				if (_checks != null)
				{
					_checks.Value = string.Join("\n", _checkLines);
				}
				Show((UiElement)(object)_noData, !M.HasData);
				Show((UiElement)(object)_map, M.HasData);
				if (!_hoverTile.HasValue && _hover != null)
				{
					_hover.Value = (M.HasData ? M.Summary() : "");
				}
			}
			finally
			{
				_refreshing = false;
			}
		}

		private static void CycleBuilding(int dir)
		{
			List<int> list = new List<int>(M.Table.ById.Keys);
			if (list.Count != 0)
			{
				int num = Math.Max(0, list.IndexOf(M.BType));
				M.BType = list[(num + dir + list.Count) % list.Count];
				_hoverKey = "";
				_uiDirty = true;
			}
		}

		private static Color32 C(int rgb)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			return new Color32((byte)((rgb >> 16) & 0xFF), (byte)((rgb >> 8) & 0xFF), (byte)(rgb & 0xFF), byte.MaxValue);
		}

		internal static Color32 BuildingColor(int type)
		{
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			float num = (float)type * 47f % 360f / 60f;
			float num2 = 0.7f;
			float num3 = 0.4f;
			float num4 = (1f - Mathf.Abs(2f * num3 - 1f)) * num2;
			float num5 = num4 * (1f - Mathf.Abs(num % 2f - 1f));
			float num6 = 0f;
			float num7 = 0f;
			float num8 = 0f;
			if (num < 1f)
			{
				num6 = num4;
				num7 = num5;
			}
			else if (num < 2f)
			{
				num6 = num5;
				num7 = num4;
			}
			else if (num < 3f)
			{
				num7 = num4;
				num8 = num5;
			}
			else if (num < 4f)
			{
				num7 = num5;
				num8 = num4;
			}
			else if (num < 5f)
			{
				num6 = num5;
				num8 = num4;
			}
			else
			{
				num6 = num4;
				num8 = num5;
			}
			float num9 = num3 - num4 / 2f;
			return new Color32((byte)((num6 + num9) * 255f), (byte)((num7 + num9) * 255f), (byte)((num8 + num9) * 255f), byte.MaxValue);
		}

		private static void RenderTexture()
		{
			_texDirty = false;
			_viewDirty = true;
			_hoverKey = "";
			if (_map != null)
			{
				MapView.Measure(_map);
			}
			MapView.Render(M, _yUp);
		}

		private static void Upload()
		{
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			_viewDirty = false;
			if (!MapView.Ready)
			{
				return;
			}
			IEnumerable<(int, int)> hover = null;
			Color32 tint = default(Color32);
			((Color32)(ref tint))..ctor(byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue);
			float blend = 0.35f;
			if (M.HasData)
			{
				(int, int)? hoverTile = _hoverTile;
				if (hoverTile.HasValue)
				{
					var (num, num2) = hoverTile.GetValueOrDefault();
					if (M.Layer == EditLayer.Buildings)
					{
						(int, int, int, int) tuple2 = M.CurrentBuilding(num, num2);
						hover = M.Footprint(tuple2.Item1, num, num2, tuple2.Item2, tuple2.Item3);
						((Color32)(ref tint))..ctor(byte.MaxValue, byte.MaxValue, (byte)0, byte.MaxValue);
						blend = 0.5f;
					}
					else if (M.Layer == EditLayer.Hills)
					{
						int num3 = M.HitCliff(num, num2);
						hover = ((num3 >= 0) ? M.CliffFootprint(M.Data.Cliffs[num3]) : M.CliffFootprint(M.CurrentHill(num, num2)));
						tint = ((num3 >= 0) ? new Color32(byte.MaxValue, (byte)80, (byte)60, byte.MaxValue) : new Color32(byte.MaxValue, (byte)200, (byte)120, byte.MaxValue));
						blend = 0.5f;
					}
					else
					{
						hover = new(int, int)[1] { (num, num2) };
					}
				}
			}
			MapView.Upload(hover, tint, blend, M.HasData ? M.Side : 0, _yUp, _map);
		}

		private static (int X, int Y) TileAt(Vector2 at, bool clamp)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			MapView.TileAt(at, _yUp, clamp, out var x, out var y);
			return (X: x, Y: y);
		}

		private static void OnPointer(UiPointerEvent e)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected I4, but got Unknown
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			if (!M.HasData)
			{
				return;
			}
			_pointerAt = ((UiPointerEvent)(ref e)).Position;
			UiPointerKind kind = ((UiPointerEvent)(ref e)).Kind;
			switch ((int)kind)
			{
			default:
				return;
			case 0:
			{
				if (((UiPointerEvent)(ref e)).Button == 1 || ((UiPointerEvent)(ref e)).Button == 2)
				{
					_dragButton = ((UiPointerEvent)(ref e)).Button;
					_dragMoved = 0f;
					return;
				}
				if (((UiPointerEvent)(ref e)).Button != 0)
				{
					return;
				}
				(int, int) tuple = TileAt(((UiPointerEvent)(ref e)).Position, clamp: false);
				if (!M.InBounds(tuple.Item1, tuple.Item2))
				{
					return;
				}
				M.PointerDown(tuple.Item1, tuple.Item2);
				_painting = M.Layer != EditLayer.Hills;
				_checkLines.Clear();
				if (M.Layer == EditLayer.Hills && M.HillMessage != null)
				{
					SetStatus(M.HillMessage);
				}
				_texDirty = true;
				_uiDirty = true;
				break;
			}
			case 4:
				if (_dragButton >= 0 && ((UiPointerEvent)(ref e)).Button == _dragButton)
				{
					float dragMoved = _dragMoved;
					Vector2 delta = ((UiPointerEvent)(ref e)).Delta;
					_dragMoved = dragMoved + ((Vector2)(ref delta)).magnitude;
					if (_dragMoved < 4f)
					{
						return;
					}
					MapView.Pan(((UiPointerEvent)(ref e)).Delta);
					_texDirty = true;
				}
				else
				{
					if (_painting)
					{
						(int, int) tuple3 = TileAt(((UiPointerEvent)(ref e)).Position, clamp: true);
						M.PointerDrag(tuple3.Item1, tuple3.Item2);
						_texDirty = true;
					}
					SetHover(TileAt(((UiPointerEvent)(ref e)).Position, clamp: true));
				}
				break;
			case 1:
				if (_dragButton >= 0 && ((UiPointerEvent)(ref e)).Button == _dragButton)
				{
					bool num = _dragButton == 1 && _dragMoved < 4f;
					_dragButton = -1;
					if (!num)
					{
						return;
					}
					(int, int) tuple2 = TileAt(((UiPointerEvent)(ref e)).Position, clamp: false);
					if (!M.InBounds(tuple2.Item1, tuple2.Item2))
					{
						return;
					}
					M.RightClick(tuple2.Item1, tuple2.Item2);
					_texDirty = true;
					_uiDirty = true;
				}
				else if (_painting)
				{
					M.PointerUp();
					_painting = false;
					_uiDirty = true;
				}
				break;
			case 3:
			case 5:
				SetHover(TileAt(((UiPointerEvent)(ref e)).Position, clamp: false));
				break;
			case 6:
				if (!_painting)
				{
					SetHover(null);
				}
				break;
			case 2:
				return;
			}
			Flush();
		}

		private static void SetHover((int X, int Y)? tile)
		{
			if (tile.HasValue && !M.InBounds(tile.Value.X, tile.Value.Y))
			{
				tile = null;
			}
			_hoverTile = tile;
		}

		private static void UpdatePreview()
		{
			(int, int)? hoverTile = _hoverTile;
			string text = ((!hoverTile.HasValue) ? "" : $"{hoverTile.Value.Item1},{hoverTile.Value.Item2}|{M.Layer}|{M.BType}|{M.HillShape}|{M.BOrient}|{M.BMirror}|{_yUp}|{(M.HasData ? M.Data.Buildings.Count : 0)}");
			if (!(text == _hoverKey))
			{
				_hoverKey = text;
				_viewDirty = true;
				if (_hover != null)
				{
					_hover.Value = (hoverTile.HasValue ? DescribeTile(hoverTile.Value.Item1, hoverTile.Value.Item2) : (M.HasData ? M.Summary() : ""));
				}
			}
		}

		private static string DescribeTile(int x, int y)
		{
			if (!M.InBounds(x, y))
			{
				return "";
			}
			int num = M.Data.Ground[M.Cell(x, y)];
			int num2 = M.Data.Nature[M.Cell(x, y)];
			StringBuilder stringBuilder = new StringBuilder(Tx.T("tile.info", x, y, (num >= 0 && num < EditorModel.GroundNames.Length) ? EditorModel.GroundNames[num] : ("#" + num)));
			if (num2 != -1)
			{
				stringBuilder.Append(", ").Append((num2 >= 0 && num2 < EditorModel.NatureNames.Length) ? EditorModel.NatureNames[num2] : ("#" + num2));
			}
			if (num == 4)
			{
				int num3 = M.HitCliff(x, y);
				if (num3 < 0)
				{
					stringBuilder.Append(" (" + Tx.T("tile.invisible") + ")");
				}
				else
				{
					IslandCliff islandCliff = M.Data.Cliffs[num3];
					string text = Tx.T("tile.hillPiece");
					(int, int, int, string)[] hillShapes = EditorModel.HillShapes;
					for (int i = 0; i < hillShapes.Length; i++)
					{
						(int, int, int, string) tuple = hillShapes[i];
						if (tuple.Item1 == islandCliff.W && tuple.Item2 == islandCliff.H && tuple.Item3 == islandCliff.Kind)
						{
							text = tuple.Item4;
						}
					}
					stringBuilder.Append(Tx.T("tile.hill", text, islandCliff.X, islandCliff.Y, islandCliff.Orient, (islandCliff.Mirror != 0) ? Tx.T("tile.mirrored") : ""));
				}
			}
			int num4 = M.HitBuilding(x, y);
			if (num4 >= 0)
			{
				IslandBuilding islandBuilding = M.Data.Buildings[num4];
				StringBuilder stringBuilder2 = stringBuilder;
				StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(26, 4, stringBuilder2);
				handler.AppendLiteral(", ");
				handler.AppendFormatted(M.Table.NameOf(islandBuilding.Type));
				handler.AppendLiteral(" (HP ");
				handler.AppendFormatted(islandBuilding.Health);
				handler.AppendLiteral(", orient ");
				handler.AppendFormatted(islandBuilding.Orient);
				handler.AppendLiteral(", mirror ");
				handler.AppendFormatted(islandBuilding.Mirror);
				handler.AppendLiteral(")");
				stringBuilder2.Append(ref handler);
			}
			return stringBuilder.ToString();
		}

		private static void RunCheck()
		{
			List<string> list = M.Check();
			_checkLines.Clear();
			if (list.Count == 0)
			{
				_checkLines.Add(Tx.T("editor.checkOk"));
			}
			else
			{
				HashSet<string> hashSet = new HashSet<string>();
				foreach (string item in list)
				{
					if (hashSet.Add(item))
					{
						_checkLines.Add(item);
					}
				}
				if (_checkLines.Count > 3)
				{
					int num = _checkLines.Count - 3;
					_checkLines.RemoveRange(3, num);
					_checkLines.Add(Tx.T("check.more", num));
				}
			}
			SetStatus((list.Count == 0) ? Tx.T("editor.checkGood") : Tx.T("editor.checkBad", list.Count));
			_texDirty = true;
			_uiDirty = true;
		}

		private static void NewBlank()
		{
			int num = Islands.SideOf(Islands.Local);
			M.NewBlank((num > 0) ? num : (M.HasData ? M.Side : 49));
			_checkLines.Clear();
			SetStatus(Tx.T("editor.blank"));
			_texDirty = true;
			_uiDirty = true;
		}

		internal static void LoadFrom(MatchPlayer player)
		{
			if (player == null)
			{
				SetStatus(Tx.T("editor.noPlayer"));
				Flush();
				return;
			}
			byte[] array = Islands.Export(player);
			if (array == null || array.Length == 0)
			{
				SetStatus(Tx.T("editor.noIsland"));
				Flush();
			}
			else
			{
				Load(array, dirty: false, Tx.T("editor.loaded", player.Name));
				Flush();
			}
		}

		private static bool Load(byte[] code, bool dirty, string what)
		{
			try
			{
				IslandData islandData = IslandCodec.FromCodeBytes(code);
				if (!islandData.SideIsExact)
				{
					SetStatus(Tx.T("editor.badLayout"));
					return false;
				}
				M.Load(islandData);
				M.Dirty = dirty;
				if (islandData.Cliffs.Count > 0)
				{
					SortedDictionary<string, int> sortedDictionary = new SortedDictionary<string, int>();
					foreach (IslandCliff cliff in islandData.Cliffs)
					{
						string key = $"{((cliff.Kind == 0) ? "main" : "extension")} {cliff.W}x{cliff.H}";
						sortedDictionary[key] = ((!sortedDictionary.TryGetValue(key, out var value)) ? 1 : (value + 1));
					}
					Plugin.L.LogInfo((object)("[editor] hill pieces: " + string.Join(", ", sortedDictionary.Select((KeyValuePair<string, int> p) => $"{p.Key} x{p.Value}"))));
				}
				_checkLines.Clear();
				SetStatus(what + ": " + M.Summary() + ((islandData.TrailingBytes > 0) ? Tx.T("summary.unread", islandData.TrailingBytes) : "") + ".");
				_texDirty = true;
				_uiDirty = true;
				return true;
			}
			catch (Exception ex)
			{
				SetStatus(Tx.T("editor.badCode", ex.Message));
				return false;
			}
		}

		private static void ApplyTo(MatchPlayer player)
		{
			if (!M.HasData)
			{
				SetStatus(Tx.T("editor.nothingToApply"));
				return;
			}
			if (player == null)
			{
				SetStatus(Tx.T("editor.noPlayer"));
				return;
			}
			int count = M.Check().Count;
			string message;
			bool flag = Islands.Import(player, IslandCodec.ToCodeBytes(M.Data), out message);
			if (flag)
			{
				M.Dirty = false;
			}
			SetStatus(message + ((flag && count > 0) ? $" {count} placement problem(s) were present." : ""));
			_uiDirty = true;
		}

		private static void PasteCode()
		{
			string error;
			byte[] array = Clipboard.ReadIslandCode(out error);
			if (array == null)
			{
				SetStatus(error);
			}
			else
			{
				Load(array, dirty: true, Tx.T("editor.pasted"));
			}
		}

		private static void CopyCode()
		{
			if (!M.HasData)
			{
				SetStatus(Tx.T("editor.nothingToCopy"));
				return;
			}
			string text = Convert.ToBase64String(IslandCodec.ToCodeBytes(M.Data));
			SetStatus(Clipboard.SetText(text) ? Tx.T("editor.copied", text.Length) : Tx.T("clipboard.failed"));
		}
	}
	internal static class MapView
	{
		private const float ZoomStep = 1.25f;

		private const float MaxTile = 48f;

		private static readonly Color32 Outside = new Color32((byte)22, (byte)28, (byte)38, byte.MaxValue);

		private static readonly Color32 Anchor = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue);

		private static readonly Color32 Problem = new Color32(byte.MaxValue, (byte)40, (byte)40, byte.MaxValue);

		private static Texture2D _tex;

		private static Color32[] _px;

		private static Color32[] _view;

		private static int[] _owner;

		private static int[] _hill;

		private static int _w;

		private static int _h;

		private static int _side;

		private static float _zoom;

		private static float _cx;

		private static float _cy;

		private static float _ox;

		private static float _oy;

		private static float _pxPerUnit = 1f;

		private static bool _fit = true;

		private static bool _rawFailed;

		internal static bool Ready => _px != null;

		internal static float TilePixels => _zoom;

		internal static void Fit()
		{
			_fit = true;
		}

		internal static void Release()
		{
			if ((Object)(object)_tex != (Object)null)
			{
				Object.Destroy((Object)(object)_tex);
			}
			_tex = null;
			_px = (_view = null);
			_w = (_h = 0);
		}

		internal static bool Measure(UiImage map)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Expected O, but got Unknown
			if ((Object)(object)((map != null) ? ((UiElement)map).Root : null) == (Object)null)
			{
				return false;
			}
			Vector2 size = map.Size;
			Canvas componentInParent = ((Component)((UiElement)map).Root).GetComponentInParent<Canvas>();
			float num = (((Object)(object)componentInParent != (Object)null && (Object)(object)componentInParent.rootCanvas != (Object)null) ? componentInParent.rootCanvas.scaleFactor : 1f);
			int num2 = Mathf.RoundToInt(size.x * num);
			int num3 = Mathf.RoundToInt(size.y * num);
			if (num2 < 16 || num3 < 16)
			{
				return false;
			}
			_pxPerUnit = ((size.x > 0.01f) ? ((float)num2 / size.x) : 1f);
			if (num2 == _w && num3 == _h && (Object)(object)_tex != (Object)null)
			{
				return false;
			}
			_w = num2;
			_h = num3;
			if ((Object)(object)_tex != (Object)null)
			{
				Object.Destroy((Object)(object)_tex);
			}
			_tex = new Texture2D(num2, num3, (TextureFormat)4, false)
			{
				filterMode = (FilterMode)0,
				wrapMode = (TextureWrapMode)1
			};
			_px = (Color32[])(object)new Color32[num2 * num3];
			_view = (Color32[])(object)new Color32[num2 * num3];
			map.SetTexture((Texture)(object)_tex);
			return true;
		}

		private static void Place(int side)
		{
			if (side != _side)
			{
				_side = side;
				_fit = true;
			}
			float num = (float)Mathf.Min(_w, _h) / (float)side;
			if (_fit)
			{
				_zoom = num;
				_cx = (_cy = (float)side * 0.5f);
			}
			_zoom = Mathf.Clamp(_zoom, num, Mathf.Max(num, 48f));
			_cx = Keep(_cx, _w, side);
			_cy = Keep(_cy, _h, side);
			_ox = (float)_w * 0.5f - _cx * _zoom;
			_oy = (float)_h * 0.5f - _cy * _zoom;
		}

		private static float Keep(float c, int pixels, int side)
		{
			float num = (float)pixels * 0.5f / _zoom;
			if (!((float)side <= 2f * num))
			{
				return Mathf.Clamp(c, num, (float)side - num);
			}
			return (float)side * 0.5f;
		}

		internal static void Zoom(float notches, Vector2 at)
		{
			//IL_0011: 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)
			if (_side > 0 && notches != 0f)
			{
				float num = at.x * _pxPerUnit;
				float num2 = at.y * _pxPerUnit;
				float num3 = (num - _ox) / _zoom;
				float num4 = (num2 - _oy) / _zoom;
				float num5 = (float)Mathf.Min(_w, _h) / (float)_side;
				float num6 = Mathf.Clamp(_zoom * Mathf.Pow(1.25f, notches), num5, Mathf.Max(num5, 48f));
				if (!Mathf.Approximately(num6, _zoom))
				{
					_fit = false;
					_zoom = num6;
					_cx = ((float)_w * 0.5f - (num - num3 * num6)) / num6;
					_cy = ((float)_h * 0.5f - (num2 - num4 * num6)) / num6;
				}
			}
		}

		internal static void Pan(Vector2 delta)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			if (!(_zoom <= 0f))
			{
				_fit = false;
				_cx -= delta.x * _pxPerUnit / _zoom;
				_cy -= delta.y * _pxPerUnit / _zoom;
			}
		}

		internal static bool TileAt(Vector2 at, bool yUp, bool clamp, out int x, out int y)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			x = (y = -1);
			if (_side <= 0 || _zoom <= 0f)
			{
				return false;
			}
			x = Mathf.FloorToInt((at.x * _pxPerUnit - _ox) / _zoom);
			int num = Mathf.FloorToInt((at.y * _pxPerUnit - _oy) / _zoom);
			if (clamp)
			{
				x = Mathf.Clamp(x, 0, _side - 1);
				num = Mathf.Clamp(num, 0, _side - 1);
			}
			y = (yUp ? num : (_side - 1 - num));
			if (x >= 0 && x < _side && num >= 0)
			{
				return num < _side;
			}
			return false;
		}

		private static int X(int tile)
		{
			return Mathf.Clamp(Mathf.FloorToInt(_ox + (float)tile * _zoom), 0, _w);
		}

		private static int Y(int row)
		{
			return Mathf.Clamp(Mathf.FloorToInt(_oy + (float)row * _zoom), 0, _h);
		}

		internal static void Render(EditorModel m, bool yUp)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_028f: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_029d: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0319: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_038b: Unknown result type (might be due to invalid IL or missing references)
			//IL_039e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0399: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03be: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ba: Unknown result type (might be due to invalid IL or missing references)
			if (_px == null)
			{
				return;
			}
			Array.Fill(_px, Outside);
			if (!m.HasData)
			{
				return;
			}
			IslandData data = m.Data;
			int side = m.Side;
			Place(side);
			if (_owner == null || _owner.Length != side * side)
			{
				_owner = new int[side * side];
			}
			Array.Fill(_owner, -1);
			for (int i = 0; i < data.Buildings.Count; i++)
			{
				foreach (var (num, num2) in m.Footprint(data.Buildings[i]))
				{
					if (m.InBounds(num, num2))
					{
						_owner[num2 * side + num] = i;
					}
				}
			}
			if (_hill == null || _hill.Length != side * side)
			{
				_hill = new int[side * side];
			}
			Array.Fill(_hill, -1);
			for (int j = 0; j < data.Cliffs.Count; j++)
			{
				foreach (var (num3, num4) in m.CliffFootprint(data.Cliffs[j]))
				{
					if (m.InBounds(num3, num4))
					{
						_hill[num4 * side + num3] = j;
					}
				}
			}
			int num5 = Math.Max(0, Mathf.FloorToInt((0f - _ox) / _zoom));
			int num6 = Math.Min(side, Mathf.CeilToInt(((float)_w - _ox) / _zoom));
			int num7 = Math.Max(0, Mathf.FloorToInt((0f - _oy) / _zoom));
			int num8 = Math.Min(side, Mathf.CeilToInt(((float)_h - _oy) / _zoom));
			for (int k = num7; k < num8; k++)
			{
				int num9 = Y(k);
				int num10 = Y(k + 1);
				if (num10 <= num9)
				{
					continue;
				}
				int num11 = (yUp ? k : (side - 1 - k));
				for (int l = num5; l < num6; l++)
				{
					int num12 = X(l);
					int num13 = X(l + 1);
					if (num13 <= num12)
					{
						continue;
					}
					int num14 = Math.Min(num13 - num12, num10 - num9);
					int num15 = num11 * side + l;
					int num16 = data.Ground[num15];
					Color32 val = (Color32)((num16 >= 0 && num16 < EditorWindow.GroundColors.Length) ? EditorWindow.GroundColors[num16] : new Color32(byte.MaxValue, (byte)0, byte.MaxValue, byte.MaxValue));
					Fill(_px, num12, num9, num13, num10, val);
					if (num14 >= 6)
					{
						Color32 col = Shade(val, (num16 == 0) ? 0.93f : 0.84f);
						Fill(_px, num12, num9, num12 + 1, num10, col);
						Fill(_px, num12, num9, num13, num9 + 1, col);
					}
					if (num16 == 4)
					{
						DrawHillTile(num15, l, k, num12, num9, num13, num10, num14, side, yUp, val);
					}
					int num17 = _owner[num15];
					if (num17 >= 0)
					{
						DrawBuildingTile(data.Buildings[num17], num17, l, k, num12, num9, num13, num10, num14, side, yUp);
						continue;
					}
					int num18 = data.Nature[num15];
					if (num18 != -1)
					{
						Color32 val2 = (Color32)((num18 >= 0 && num18 < EditorWindow.NatureColors.Length) ? EditorWindow.NatureColors[num18] : new Color32(byte.MaxValue, (byte)0, byte.MaxValue, byte.MaxValue));
						if (num14 >= 5)
						{
							Disc(_px, num12, num9, num13, num10, val2, (num14 >= 10) ? Shade(val2, 0.7f) : val2);
						}
						else
						{
							Fill(_px, num12 + num14 / 4, num9 + num14 / 4, num13 - num14 / 4, num10 - num14 / 4, val2);
						}
					}
				}
			}
			foreach (var (num19, num20) in m.Problems)
			{
				if (m.InBounds(num19, num20))
				{
					int num21 = (yUp ? num20 : (side - 1 - num20));
					int num22 = X(num19);
					int num23 = X(num19 + 1);
					int num24 = Y(num21);
					int num25 = Y(num21 + 1);
					if (num23 > num22 && num25 > num24)
					{
						Frame(_px, num22, num24, num23, num25, Math.Max(1, (num23 - num22) / 8), Problem);
					}
				}
			}
		}

		private static void DrawBuildingTile(IslandBuilding bd, int index, int gx, int row, int x0, int y0, int x1, int y1, int t, int side, bool yUp)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: 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_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			Color32 val = EditorWindow.BuildingColor(bd.Type);
			Fill(_px, x0, y0, x1, y1, val);
			Color32 col = Shade(val, 0.55f);
			int num = Math.Max(1, t / 8);
			if (OwnerAt(gx - 1, row, side, yUp) != index)
			{
				Fill(_px, x0, y0, x0 + num, y1, col);
			}
			if (OwnerAt(gx + 1, row, side, yUp) != index)
			{
				Fill(_px, x1 - num, y0, x1, y1, col);
			}
			if (OwnerAt(gx, row - 1, side, yUp) != index)
			{
				Fill(_px, x0, y0, x1, y0 + num, col);
			}
			if (OwnerAt(gx, row + 1, side, yUp) != index)
			{
				Fill(_px, x0, y1 - num, x1, y1, col);
			}
			int num2 = (yUp ? row : (side - 1 - row));
			if (bd.X == gx && bd.Y == num2)
			{
				int num3 = Math.Max(2, t / 4);
				int num4 = (x0 + x1) / 2;
				int num5 = (y0 + y1) / 2;
				Fill(_px, num4 - num3 / 2, num5 - num3 / 2, num4 - num3 / 2 + num3, num5 - num3 / 2 + num3, Anchor);
			}
		}

		private static void DrawHillTile(int cell, int gx, int row, int x0, int y0, int x1, int y1, int t, int side, bool yUp, Color32 ground)
		{
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//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_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			int num = _hill[cell];
			if (num < 0)
			{
				if (t < 4)
				{
					return;
				}
				Color32 val = Shade(ground, 0.72f);
				for (int i = Math.Max(y0, 0); i < Math.Min(y1, _h); i++)
				{
					for (int j = Math.Max(x0, 0); j < Math.Min(x1, _w); j++)
					{
						if ((j + i) % 6 < 2)
						{
							_px[i * _w + j] = val;
						}
					}
				}
				return;
			}
			Fill(_px, x0, y0, x1, y1, Shade(ground, 1.12f));
			Color32 col = Shade(ground, 0.5f);
			int num2 = Math.Max(1, t / 8);
			if (HillAt(gx - 1, row, side, yUp) != num)
			{
				Fill(_px, x0, y0, x0 + num2, y1, col);
			}
			if (HillAt(gx + 1, row, side, yUp) != num)
			{
				Fill(_px, x1 - num2, y0, x1, y1, col);
			}
			if (HillAt(gx, row - 1, side, yUp) != num)
			{
				Fill(_px, x0, y0, x1, y0 + num2, col);
			}
			if (HillAt(gx, row + 1, side, yUp) != num)
			{
				Fill(_px, x0, y1 - num2, x1, y1, col);
			}
		}

		private static int HillAt(int gx, int row, int side, bool yUp)
		{
			if (gx < 0 || gx >= side || row < 0 || row >= side)
			{
				return -1;
			}
			int num = (yUp ? row : (side - 1 - row));
			return _hill[num * side + gx];
		}

		private static int OwnerAt(int gx, int row, int side, bool yUp)
		{
			if (gx < 0 || gx >= side || row < 0 || row >= side)
			{
				return -1;
			}
			int num = (yUp ? row : (side - 1 - row));
			return _owner[num * side + gx];
		}

		internal unsafe static void Upload(IEnumerable<(int X, int Y)> hover, Color32 tint, float blend, int side, bool yUp, UiImage map)
		{
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			if (_px == null || (Object)(object)_tex == (Object)null)
			{
				return;
			}
			Array.Copy(_px, _view, _px.Length);
			if (hover != null)
			{
				foreach (var (num, num2) in hover)
				{
					if (num >= 0 && num2 >= 0 && num < side && num2 < side)
					{
						int num3 = (yUp ? num2 : (side - 1 - num2));
						int x = X(num);
						int x2 = X(num + 1);
						int y = Y(num3);
						int y2 = Y(num3 + 1);
						Blend(_view, x, y, x2, y2, tint, blend);
					}
				}
			}
			if (!_rawFailed)
			{
				try
				{
					fixed (Color32* view = _view)
					{
						_tex.LoadRawTextureData((IntPtr)view, _view.Length * 4);
					}
					_tex.Apply(false);
					return;
				}
				catch (Exception ex)
				{
					_rawFailed = true;
					Plugin.L.LogWarning((object)("[editor] map: raw texture upload not available here (" + ex.Message + "), using SetPixels32"));
				}
			}
			_tex.SetPixels32(new Il2CppStructArray<Color32>(_view));
			_tex.Apply(false);
			if (map != null)
			{
				map.Refresh();
			}
		}

		private static Color32 Shade(Color32 c, float k)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: 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)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			return new Color32((byte)Math.Min(255f, (float)(int)c.r * k), (byte)Math.Min(255f, (float)(int)c.g * k), (byte)Math.Min(255f, (float)(int)c.b * k), byte.MaxValue);
		}

		private static void Fill(Color32[] target, int x0, int y0, int x1, int y1, Color32 col)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			x0 = Math.Max(x0, 0);
			y0 = Math.Max(y0, 0);
			x1 = Math.Min(x1, _w);
			y1 = Math.Min(y1, _h);
			for (int i = y0; i < y1; i++)
			{
				Array.Fill(target, col, i * _w + x0, Math.Max(0, x1 - x0));
			}
		}

		private static void Frame(Color32[] target, int x0, int y0, int x1, int y1, int bw, Color32 col)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			Fill(target, x0, y0, x1, y0 + bw, col);
			Fill(target, x0, y1 - bw, x1, y1, col);
			Fill(target, x0, y0, x0 + bw, y1, col);
			Fill(target, x1 - bw, y0, x1, y1, col);
		}

		private static void Blend(Color32[] target, int x0, int y0, int x1, int y1, Color32 col, float k)
		{
			//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_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: 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_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			x0 = Math.Max(x0, 0);
			y0 = Math.Max(y0, 0);
			x1 = Math.Min(x1, _w);
			y1 = Math.Min(y1, _h);
			for (int i = y0; i < y1; i++)
			{
				for (int j = x0; j < x1; j++)
				{
					int num = i * _w + j;
					Color32 val = target[num];
					target[num] = new Color32((byte)((float)(int)val.r + (float)(col.r - val.r) * k), (byte)((float)(int)val.g + (float)(col.g - val.g) * k), (byte)((float)(int)val.b + (float)(col.b - val.b) * k), byte.MaxValue);
				}
			}
		}

		private static void Disc(Color32[] target, int x0, int y0, int x1, int y1, Color32 col, Color32 rim)
		{
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			float num = (float)(x0 + x1) * 0.5f;
			float num2 = (float)(y0 + y1) * 0.5f;
			float num3 = (float)Math.Min(x1 - x0, y1 - y0) * 0.36f;
			float num4 = num3 * num3;
			float num5 = (num3 - 1.2f) * (num3 - 1.2f);
			int num6 = Math.Max(0, Mathf.FloorToInt(num2 - num3));
			int num7 = Math.Min(_h, Mathf.CeilToInt(num2 + num3));
			int num8 = Math.Max(0, Mathf.FloorToInt(num - num3));
			int num9 = Math.Min(_w, Mathf.CeilToInt(num + num3));
			for (int i = num6; i < num7; i++)
			{
				float num10 = (float)i + 0.5f - num2;
				for (int j = num8; j < num9; j++)
				{
					float num11 = (float)j + 0.5f - num;
					float num12 = num11 * num11 + num10 * num10;
					if (num12 <= num4)
					{
						target[i * _w + j] = ((num12 > num5) ? rim : col);
					}
				}
			}
		}
	}
	internal static class Buildings
	{
		private static BuildingTable _live;

		internal static BuildingTable Table
		{
			get
			{
				object obj = _live;
				if (obj == null)
				{
					obj = ReadLive() ?? BuildingTable.FromDumpOrDefault(null);
					_live = (BuildingTable)obj;
				}
				return (BuildingTable)obj;
			}
		}

		private static BuildingTable ReadLive()
		{
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Expected O, but got Unknown
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			Il2CppArrayBase<BuildingTypes> val = Resources.FindObjectsOfTypeAll<BuildingTypes>();
			Il2CppReferenceArray<BuildingType> val2 = ((val.Length > 0) ? val[0].Types : null);
			if (val2 == null || ((Il2CppArrayBase<BuildingType>)(object)val2).Length == 0)
			{
				return null;
			}
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < ((Il2CppArrayBase<BuildingType>)(object)val2).Length; i++)
			{
				BuildingType val3 = ((Il2CppArrayBase<BuildingType>)(object)val2)[i];
				if (val3 != null)
				{
					stringBuilder.Append(i).Append(": ").Append(val3.DisplayName)
						.Append(" | tier=")
						.Append(val3.tier)
						.Append(" hp=")
						.Append(val3.health)
						.Append(" | [");
					Il2CppStructArray<int2> localPositions = val3.localPositions;
					int num = 0;
					while (localPositions != null && num < ((Il2CppArrayBase<int2>)(object)localPositions).Length)
					{
						stringBuilder.Append((num > 0) ? ",[" : "[").Append(((Il2CppArrayBase<int2>)(object)localPositions)[num].x).Append(',')
							.Append(((Il2CppArrayBase<int2>)(object)localPositions)[num].y)
							.Append(']');
						num++;
					}
					stringBuilder.Append("]\n");
				}
			}
			BuildingTable buildingTable = BuildingTable.Parse(stringBuilder.ToString());
			if (buildingTable.ById.Count == 0)
			{
				return null;
			}
			ManualLogSource l = Plugin.L;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val4 = new BepInExInfoLogInterpolatedStringHandler(47, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val4).AppendLiteral("[buildings] ");
				((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<int>(buildingTable.ById.Count);
				((BepInExLogInterpolatedStringHandler)val4).AppendLiteral(" building types read from the game.");
			}
			l.LogInfo(val4);
			return buildingTable;
		}
	}
	internal sealed class BuildingInfo
	{
		public int Id;

		public string RawName;

		public int Tier;

		public int Hp;

		public int[][] Shape;

		public string Name => GameNames.Building(RawName);
	}
	internal sealed class BuildingTable
	{
		public readonly SortedDictionary<int, BuildingInfo> ById = new SortedDictionary<int, BuildingInfo>();

		private static readonly Regex Full = new Regex("^\\s*(\\d+)\\s*:\\s*(.+?)\\s*\\|\\s*tier\\s*=\\s*(-?\\d+)\\s+hp\\s*=\\s*(-?\\d+)\\s*\\|\\s*(\\[.*\\])\\s*$");

		private static readonly Regex Plain = new Regex("^\\s*(\\d+)\\s*:\\s*(.+?)\\s*(\\[\\s*\\[.*\\])\\s*$");

		private static readonly Regex Pair = new Regex("\\[\\s*(-?\\d+)\\s*,\\s*(-?\\d+)\\s*\\]");

		public const string DefaultDump = "0: Archery Range | tier=2 hp=60 | [[0,0],[-1,0],[0,-1],[-1,-1],[-1,-2]]\n1: Barracks | tier=1 hp=60 | [[-1,1],[0,1],[0,0],[0,-1],[1,0],[1,-1]]\n2: Castle | tier=1 hp=200 | [[-1,-1],[-1,0],[-1,1],[-1,2],[0,-1],[0,0],[0,1],[0,2],[1,-1],[1,0],[1,1],[1,2],[2,-1],[2,0],[2,1],[2,2]]\n3: Cathedral | tier=2 hp=40 | [[1,0],[0,0],[-1,0],[-2,0],[0,1],[0,-1]]\n4: Church | tier=1 hp=15 | [[0,0],[-1,0],[-2,0]]\n5: Cottage | tier=1 hp=10 | [[0,0],[0,1]]\n6: Dock | tier=1 hp=50 | [[0,0],[1,0],[2,0],[2,1],[3,0],[3,1],[4,-1],[4,0],[4,1],[5,-1],[5,0],[5,1]]\n7: Farm | tier=1 hp=15 | [[0,1],[0,0],[0,-1],[0,-2],[1,1],[1,0],[1,-1],[1,-2]]\n8: Guard Tower | tier=2 hp=40 | [[0,0],[-1,0],[0,-1],[-1,-1]]\n9: Guard Tower Up | tier=2 hp=40 | [[0,0],[-1,0],[0,-1],[-1,-1]]\n10: Hospital | tier=2 hp=40 | [[0,0],[-1,0],[1,0],[0,-1],[0,1]]\n11: House | tier=1 hp=15 | [[0,0],[-1,0],[0,-1]]\n12: Lumber Camp | tier=3 hp=20 | [[0,0],[-1,0],[-1,1],[-2,1]]\n13: Market | tier=3 hp=10 | [[0,0],[1,0],[1,1],[0,1]]\n14: Sorcerer Tower | tier=2 hp=20 | [[0,0],[1,0],[0,1]]\n15: Stone Quarry | tier=3 hp=20 | [[0,0],[0,1],[1,0]]\n16: Storage | tier=2 hp=20 | [[0,0],[1,0],[0,-1],[1,-1],[0,1],[1,1]]\n17: University | tier=1 hp=50 | [[0,1],[0,0],[0,-1],[1,1],[1,-1],[2,1],[2,-1]]\n18: Wall | tier=1 hp=50 | [[0,0]]\n19: Windmill | tier=2 hp=20 | [[0,0],[-1,0],[-1,1],[0,1]]\n20: Wonder | tier=3 hp=150 | [[3,-1],[3,0],[3,1],[2,-1],[2,0],[2,1],[1,-1],[1,0],[1,1],[0,-1],[0,0],[0,1],[-1,-1],[-1,0],[-1,1]]\n21: Fishing Ship | tier=2 hp=30 | [[0,0],[0,1]]\n22: Lighthouse | tier=3 hp=50 | [[0,0],[-1,0],[0,-1],[-1,-1]]\n23: Land Camp | tier=3 hp=20 | [[0,0],[1,1],[0,1],[-1,1]]";

		public BuildingInfo Get(int id)
		{
			if (!ById.TryGetValue(id, out var value))
			{
				return null;
			}
			return value;
		}

		public string NameOf(int id)
		{
			return Get(id)?.Name ?? ("type " + id);
		}

		public static BuildingTable Parse(string text)
		{
			BuildingTable buildingTable = new BuildingTable();
			if (string.IsNullOrEmpty(text))
			{
				return buildingTable;
			}
			string[] array = text.Split('\n');
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i].Trim();
				if (text2.Length == 0)
				{
					continue;
				}
				int tier = 0;
				int hp = 0;
				Match match = Full.Match(text2);
				int num;
				string rawName;
				string value;
				if (match.Success)
				{
					num = int.Parse(match.Groups[1].Value);
					rawName = match.Groups[2].Value;
					tier = int.Parse(match.Groups[3].Value);
					hp = int.Parse(match.Groups[4].Value);
					value = match.Groups[5].Value;
				}
				else
				{
					match = Plain.Match(text2);
					if (!match.Success)
					{
						continue;
					}
					num = int.Parse(match.Groups[1].Value);
					rawName = match.Groups[2].Value.TrimEnd(' ', '|');
					value = match.Groups[3].Value;
				}
				List<int[]> list = new List<int[]>();
				foreach (Match item in Pair.Matches(value))
				{
					list.Add(new int[2]
					{
						int.Parse(item.Groups[1].Value),
						int.Parse(item.Groups[2].Value)
					});
				}
				if (list.Count != 0)
				{
					buildingTable.ById[num] = new BuildingInfo
					{
						Id = num,
						RawName = rawName,
						Tier = tier,
						Hp = hp,
						Shape = list.ToArray()
					};
				}
			}
			return buildingTable;
		}

		public static BuildingTable FromDumpOrDefault(string dumpText)
		{
			BuildingTable buildingTable = Parse(dumpText);
			if (buildingTable.ById.Count <= 0)
			{
				return Parse("0: Archery Range | tier=2 hp=60 | [[0,0],[-1,0],[0,-1],[-1,-1],[-1,-2]]\n1: Barracks | tier=1 hp=60 | [[-1,1],[0,1],[0,0],[0,-1],[1,0],[1,-1]]\n2: Castle | tier=1 hp=200 | [[-1,-1],[-1,0],[-1,1],[-1,2],[0,-1],[0,0],[0,1],[0,2],[1,-1],[1,0],[1,1],[1,2],[2,-1],[2,0],[2,1],[2,2]]\n3: Cathedral | tier=2 hp=40 | [[1,0],[0,0],[-1,0],[-2,0],[0,1],[0,-1]]\n4: Church | tier=1 hp=15 | [[0,0],[-1,0],[-2,0]]\n5: Cottage | tier=1 hp=10 | [[0,0],[0,1]]\n6: Dock | tier=1 hp=50 | [[0,0],[1,0],[2,0],[2,1],[3,0],[3,1],[4,-1],[4,0],[4,1],[5,-1],[5,0],[5,1]]\n7: Farm | tier=1 hp=15 | [[0,1],[0,0],[0,-1],[0,-2],[1,1],[1,0],[1,-1],[1,-2]]\n8: Guard Tower | tier=2 hp=40 | [[0,0],[-1,0],[0,-1],[-1,-1]]\n9: Guard Tower Up | tier=2 hp=40 | [[0,0],[-1,0],[0,-1],[-1,-1]]\n10: Hospital | tier=2 hp=40 | [[0,0],[-1,0],[1,0],[0,-1],[0,1]]\n11: House | tier=1 hp=15 | [[0,0],[-1,0],[0,-1]]\n12: Lumber Camp | tier=3 hp=20 | [[0,0],[-1,0],[-1,1],[-2,1]]\n13: Market | tier=3 hp=10 | [[0,0],[1,0],[1,1],[0,1]]\n14: Sorcerer Tower | tier=2 hp=20 | [[0,0],[1,0],[0,1]]\n15: Stone Quarry | tier=3 hp=20 | [[0,0],[0,1],[1,0]]\n16: Storage | tier=2 hp=20 | [[0,0],[1,0],[0,-1],[1,-1],[0,1],[1,1]]\n17: University | tier=1 hp=50 | [[0,1],[0,0],[0,-1],[1,1],[1,-1],[2,1],[2,-1]]\n18: Wall | tier=1 hp=50 | [[0,0]]\n19: Windmill | tier=2 hp=20 | [[0,0],[-1,0],[-1,1],[0,1]]\n20: Wonder | tier=3 hp=150 | [[3,-1],[3,0],[3,1],[2,-1],[2,0],[2,1],[1,-1],[1,0],[1,1],[0,-1],[0,0],[0,1],[-1,-1],[-1,0],[-1,1]]\n21: Fishing Ship | tier=2 hp=30 | [[0,0],[0,1]]\n22: Lighthouse | tier=3 hp=50 | [[0,0],[-1,0],[0,-1],[-1,-1]]\n23: Land Camp | tier=3 hp=20 | [[0,0],[1,1],[0,1],[-1,1]]");
			}
			return buildingTable;
		}
	}
	internal static class Clipboard
	{
		public static bool SetText(string text)
		{
			try
			{
				GUIUtility.systemCopyBuffer = text ?? "";
				return true;
			}
			catch (Exception ex)
			{
				Plugin.L.LogWarning((object)("[clipboard] write: " + ex.Message));
				return false;
			}
		}

		public static bool TryGetText(out string text)
		{
			try
			{
				text = GUIUtility.systemCopyBuffer;
			}
			catch (Exception ex)
			{
				Plugin.L.LogWarning((object)("[clipboard] read: " + ex.Message));
				text = null;
			}
			return !string.IsNullOrEmpty(text);
		}

		public static bool TryDecodeBase64(string s, out byte[] data)
		{
			data = null;
			StringBuilder stringBuilder = new StringBuilder(s.Length);
			foreach (char c in s)
			{
				if (!char.IsWhiteSpace(c))
				{
					stringBuilder.Append(c);
				}
			}
			while (stringBuilder.Length % 4 != 0)
			{
				stringBuilder.Append('=');
			}
			try
			{
				data = Convert.FromBase64String(stringBuilder.ToString());
				return true;
			}
			catch (FormatException)
			{
				return false;
			}
		}

		public static byte[] ReadIslandCode(out string error)
		{
			error = null;
			if (!TryGetText(out var text))
			{
				error = Tx.T("clipboard.noText");
				return null;
			}
			if (!TryDecodeBase64(text, out var data))
			{
				error = Tx.T("clipboard.notCode");
				return null;
			}
			return data;
		}
	}
	internal static class GameNames
	{
		private static readonly Dictionary<string, string> Cache = new Dictionary<string, string>();

		private static string _language;

		internal static string Building(string english)
		{
			if (string.IsNullOrEmpty(english))
			{
				return english;
			}
			string language = Texts.Language;
			if (language != _language)
			{
				Cache.Clear();
				_language = language;
			}
			if (Cache.TryGetValue(english, out var value))
			{
				return value;
			}
			value = Texts.Game("building." + english.ToUpperInvariant().Replace(' ', '_') + ".name", english);
			Cache[english] = value;
			return value;
		}
	}
	internal static class ImportGuard
	{
		private static bool _active;

		private static int _checks;

		private static int _refused;

		private static int _allowed;

		private static long _started;

		private static PatchSwitch _patch;

		internal static void Install(Patcher patcher)
		{
			_patch = patcher.Switch(typeof(IslandGrid), "CanPlaceBuilding", typeof(ImportGuard), (string)null, "CanPlacePostfix");
		}

		internal static void Begin()
		{
			_checks = (_refused = (_allowed = 0));
			_started = Environment.TickCount64;
			_active = true;
			if (_patch != null)
			{
				_patch.On = true;
			}
		}

		internal static void End()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			_active = false;
			if (_patch != null)
			{
				_patch.On = false;
			}
			ManualLogSource l = Plugin.L;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(60, 4, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[import] ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(_checks);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" placement check(s), ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(_refused);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" refused, ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(_allowed);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" allowed anyway; ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<long>(Environment.TickCount64 - _started);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ms");
			}
			l.LogInfo(val);
		}

		internal static string Note()
		{
			if (_allowed <= 0)
			{
				return "";
			}
			return " (" + Tx.T("apply.allowed", _allowed) + ")";
		}

		internal static void CanPlacePostfix(Building __0, ref bool __result)
		{
			if (!_active)
			{
				return;
			}
			_checks++;
			if (!__result && !(__0 == (Building)null))
			{
				_refused++;
				IntPtr pointer = ((Il2CppObjectBase)__0).Pointer;
				DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(42, 4);
				defaultInterpolatedStringHandler.AppendLiteral("[import] placement refused: ");
				BuildingType type = __0.type;
				defaultInterpolatedStringHandler.AppendFormatted(((type != null) ? type.DisplayName : null) ?? "?");
				defaultInterpolatedStringHandler.AppendLiteral(" at x=");
				defaultInterpolatedStringHandler.AppendFormatted(Mem.ReadInt(pointer, 24));
				defaultInterpolatedStringHandler.AppendLiteral(" y=");
				defaultInterpolatedStringHandler.AppendFormatted(Mem.ReadInt(pointer, 28));
				defaultInterpolatedStringHandler.AppendLiteral(" rot=");
				defaultInterpolatedStringHandler.AppendFormatted(Mem.ReadInt(pointer, 32));
				string text = defaultInterpolatedStringHandler.ToStringAndClear();
				if (Options.BypassPlacement.Value)
				{
					__result = true;
					_allowed++;
					text += " -> allowed";
				}
				Plugin.L.LogWarning((object)text);
			}
		}
	}
	internal sealed class IslandBuilding
	{
		public int Type;

		public int X;

		public int Y;

		public int Orient;

		public int Mirror;

		public int Health;

		public ulong? Disaster;

		public int Turn;

		public IslandBuilding Clone()
		{
			return (IslandBuilding)MemberwiseClone();
		}
	}
	internal sealed class IslandCliff
	{
		public int Kind;

		public int W;

		public int H;

		public int X;

		public int Y;

		public int Orient;

		public int Mirror;

		public IslandCliff Clone()
		{
			return (IslandCliff)MemberwiseClone();
		}
	}
	internal sealed class IslandData
	{
		private sealed class Reader
		{
			private readonly byte[] _b;

			public int Pos;

			public int Left => _b.Length - Pos;

			public Reader(byte[] b)
			{
				_b = b;
			}

			private int Byte()
			{
				if (Pos >= _b.Length)
				{
					throw new FormatException("unexpected end of the island data");
				}
				return _b[Pos++];
			}

			public ulong U64()
			{
				int num = Byte();
				if (num <= 240)
				{
					return (ulong)num;
				}
				if (num < 249)
				{
					return (ulong)(num * 256 - 61456 + Byte());
				}
				if (num == 249)
				{
					int num2 = Byte();
					int num3 = Byte();
					return (ulong)(num2 * 256 + num3 + 2288);
				}
				int num4 = num - 247;
				ulong num5 = 0uL;
				for (int i = 0; i < num4; i++)
				{
					num5 |= (ulong)((long)Byte() << 8 * i);
				}
				return num5;
			}

			public int I32()
			{
				ulong num = U64();
				long num2 = (long)(((num & 1) == 0L) ? (num / 2) : (0L - (num + 1) / 2)