Decompiled source of LevelEasily v0.2.1

plugins/LevelEasily.dll

Decompiled 2 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("LevelEasily")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+da9f65d15c9de9c3c031f976db05b2398fe2ee70")]
[assembly: AssemblyProduct("LevelEasily")]
[assembly: AssemblyTitle("LevelEasily")]
[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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LevelEasily
{
	internal enum VertexState
	{
		Level,
		Cut,
		Fill,
		UnderPiece,
		NeedsPickaxe
	}
	internal sealed class VertexPlan
	{
		public Vector2Int Grid;

		public Vector3 Point;

		public float Goal;

		public bool Unreachable;

		public VertexState State;

		public float PickVolume;

		public float YieldVolume;

		public float StoneVolume;

		public bool Selected;

		public float Rise => Goal - Point.y;

		public bool Wanted
		{
			get
			{
				VertexState state = State;
				if ((uint)(state - 1) <= 1u)
				{
					return true;
				}
				return false;
			}
		}

		public bool FlatAfterWrite
		{
			get
			{
				if (!Unreachable)
				{
					if (State != VertexState.Level)
					{
						return Selected;
					}
					return true;
				}
				return false;
			}
		}
	}
	internal sealed class AreaPlan
	{
		public const float ChangeThreshold = 0.01f;

		private const float HoeReach = 1f;

		private const float PieceMargin = 0.45f;

		private const float PieceSlack = 0.5f;

		public const int VanillaLevelLimit = 8;

		private const float MaxDepthYield = 7.95f;

		private static readonly Collider[] Overlaps = (Collider[])(object)new Collider[32];

		private readonly Dictionary<Vector2Int, VertexPlan> byGrid = new Dictionary<Vector2Int, VertexPlan>();

		public RectInt Area { get; }

		public float Target { get; }

		public bool FreeFill { get; }

		public List<VertexPlan> Vertices { get; } = new List<VertexPlan>();

		public Vector3 Centre
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_001f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				//IL_002c: Unknown result type (might be due to invalid IL or missing references)
				RectInt area = Area;
				float x = ((RectInt)(ref area)).center.x;
				float target = Target;
				area = Area;
				return new Vector3(x, target, ((RectInt)(ref area)).center.y);
			}
		}

		public float HalfDiagonal
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_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_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_002c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0031: Unknown result type (might be due to invalid IL or missing references)
				RectInt area = Area;
				int width = ((RectInt)(ref area)).width;
				area = Area;
				int num = width * ((RectInt)(ref area)).width;
				area = Area;
				int height = ((RectInt)(ref area)).height;
				area = Area;
				return Mathf.Sqrt((float)(num + height * ((RectInt)(ref area)).height)) / 2f;
			}
		}

		private AreaPlan(RectInt area, float target, bool freeFill)
		{
			//IL_001d: 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)
			Area = area;
			Target = target;
			FreeFill = freeFill;
		}

		public bool TryGet(Vector2Int grid, out VertexPlan vertex)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return byGrid.TryGetValue(grid, out vertex);
		}

		public int Count(VertexState state)
		{
			int num = 0;
			foreach (VertexPlan vertex in Vertices)
			{
				if (vertex.State == state)
				{
					num++;
				}
			}
			return num;
		}

		public static AreaPlan Measure(RectInt area, float target, bool freeFill, bool hasPickaxe, GameObject ghost, int pieceMask)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: 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_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			AreaPlan areaPlan = new AreaPlan(area, target, freeFill);
			Dictionary<Heightmap, TerrainComp> dictionary = new Dictionary<Heightmap, TerrainComp>();
			Vector3 val = default(Vector3);
			foreach (Vector2Int item3 in VertexPositions(area))
			{
				Vector2Int current = item3;
				((Vector3)(ref val))..ctor((float)((Vector2Int)(ref current)).x, 0f, (float)((Vector2Int)(ref current)).y);
				Heightmap val2 = Heightmap.FindHeightmap(val);
				if (Object.op_Implicit((Object)(object)val2) && val2.GetWorldHeight(val, ref val.y))
				{
					if (!dictionary.TryGetValue(val2, out var value))
					{
						value = (dictionary[val2] = TerrainComp.FindTerrainCompiler(((Component)val2).transform.position));
					}
					(float baseHeight, float smoothDelta) tuple = BaseHeight(val2, value, val);
					float item = tuple.baseHeight;
					float item2 = tuple.smoothDelta;
					float num = Mathf.Clamp(target, item - 8f, item + 8f);
					VertexPlan vertexPlan = new VertexPlan
					{
						Grid = current,
						Point = val,
						Goal = num,
						Unreachable = (Mathf.Abs(num - target) > 0.01f)
					};
					Classify(vertexPlan, item2, freeFill, hasPickaxe, ghost, pieceMask);
					vertexPlan.YieldVolume = ((num > item - 7.95f) ? vertexPlan.PickVolume : 0f);
					areaPlan.Vertices.Add(vertexPlan);
					areaPlan.byGrid[current] = vertexPlan;
				}
			}
			return areaPlan;
		}

		public static (float baseHeight, float smoothDelta) BaseHeight(Heightmap heightmap, TerrainComp compiler, Vector3 point)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)compiler) || !compiler.m_initialized)
			{
				return (baseHeight: point.y, smoothDelta: 0f);
			}
			int num = default(int);
			int num2 = default(int);
			heightmap.WorldToVertex(point, ref num, ref num2);
			int num3 = compiler.m_width + 1;
			if (num < 0 || num2 < 0 || num >= num3 || num2 >= num3)
			{
				return (baseHeight: point.y, smoothDelta: 0f);
			}
			int num4 = num2 * num3 + num;
			float num5 = compiler.m_levelDelta[num4];
			float num6 = compiler.m_smoothDelta[num4];
			return (baseHeight: point.y - Mathf.Clamp(num5 + num6, -8f, 8f), smoothDelta: num6);
		}

		private static void Classify(VertexPlan v, float smoothDelta, bool freeFill, bool hasPickaxe, GameObject ghost, int pieceMask)
		{
			float rise = v.Rise;
			if (Mathf.Abs(rise) <= 0.01f)
			{
				v.State = VertexState.Level;
			}
			else if (UnderPiece(v, ghost, pieceMask))
			{
				v.State = VertexState.UnderPiece;
			}
			else if (rise < 0f)
			{
				v.PickVolume = Mathf.Max(0f, 0f - rise - (1f + smoothDelta));
				v.State = ((!(v.PickVolume > 0f) || hasPickaxe) ? VertexState.Cut : VertexState.NeedsPickaxe);
			}
			else
			{
				v.StoneVolume = (freeFill ? Mathf.Max(0f, rise - (1f - smoothDelta)) : rise);
				v.State = VertexState.Fill;
			}
		}

		private static bool UnderPiece(VertexPlan v, GameObject ghost, int pieceMask)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			float num = Mathf.Min(v.Point.y, v.Goal) - 0.5f;
			float num2 = Mathf.Max(v.Point.y, v.Goal) + 0.5f;
			Vector3 val = new Vector3(v.Point.x, (num + num2) / 2f, v.Point.z);
			Vector3 val2 = default(Vector3);
			((Vector3)(ref val2))..ctor(0.45f, (num2 - num) / 2f, 0.45f);
			int num3 = Physics.OverlapBoxNonAlloc(val, val2, Overlaps, Quaternion.identity, pieceMask, (QueryTriggerInteraction)1);
			for (int i = 0; i < num3; i++)
			{
				Piece componentInParent = ((Component)Overlaps[i]).GetComponentInParent<Piece>();
				if (Object.op_Implicit((Object)(object)componentInParent) && (!Object.op_Implicit((Object)(object)ghost) || (Object)(object)((Component)componentInParent).gameObject != (Object)(object)ghost))
				{
					return true;
				}
			}
			return false;
		}

		public static IEnumerable<Vector2Int> VertexPositions(RectInt area)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			for (int x = ((RectInt)(ref area)).xMin; x <= ((RectInt)(ref area)).xMax; x++)
			{
				for (int z = ((RectInt)(ref area)).yMin; z <= ((RectInt)(ref area)).yMax; z++)
				{
					yield return new Vector2Int(x, z);
				}
			}
		}

		public static IEnumerable<Vector2Int> Cells(RectInt area)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			for (int x = ((RectInt)(ref area)).xMin; x < ((RectInt)(ref area)).xMax; x++)
			{
				for (int z = ((RectInt)(ref area)).yMin; z < ((RectInt)(ref area)).yMax; z++)
				{
					yield return new Vector2Int(x, z);
				}
			}
		}
	}
	internal enum Shortage
	{
		None,
		Stamina,
		HoeWear,
		PickaxeWear,
		Stone
	}
	internal readonly struct Cost
	{
		public readonly int Vertices;

		public readonly int HoeSwings;

		public readonly int RaiseSwings;

		public readonly int PickHits;

		public readonly int Stone;

		public readonly int Returned;

		public readonly float Stamina;

		public readonly float HoeWear;

		public readonly float PickWear;

		public readonly float Seconds;

		public int AllSwings => HoeSwings + RaiseSwings;

		public Cost(int vertices, int hoeSwings, int raiseSwings, int pickHits, int stone, float stamina, float hoeWear, float pickWear, float seconds, int returned)
		{
			Returned = returned;
			Vertices = vertices;
			HoeSwings = hoeSwings;
			RaiseSwings = raiseSwings;
			PickHits = pickHits;
			Stone = stone;
			Stamina = stamina;
			HoeWear = hoeWear;
			PickWear = pickWear;
			Seconds = seconds;
		}
	}
	internal sealed class Budget
	{
		public ItemData Hoe;

		public ItemData Pickaxe;

		public float HoeStamina;

		public float HoeWear;

		public float PickStamina;

		public float PickWear;

		public float PickVolume;

		public float PlaceDelay;

		public float PickSeconds;

		public DigYield Yield;

		public float Stamina;

		public float HoeDurability;

		public float PickDurability;

		public int Stone;

		private static readonly List<VertexPlan> wanted = new List<VertexPlan>();

		public static Budget Of(Player player, VanillaRates rates, float pickSeconds, float staminaDiscount)
		{
			ItemData rightItem = ((Humanoid)player).GetRightItem();
			Budget budget = new Budget
			{
				Hoe = rightItem,
				HoeStamina = player.GetBuildStamina() * (1f - staminaDiscount),
				HoeWear = (rightItem.m_shared.m_useDurability ? (player.GetPlaceDurability(rightItem) * Game.m_durabilityRate) : 0f),
				HoeDurability = (rightItem.m_shared.m_useDurability ? rightItem.m_durability : float.PositiveInfinity),
				Stamina = player.GetStamina(),
				Stone = (player.m_noPlacementCost ? int.MaxValue : ((Humanoid)player).GetInventory().CountItems(rates.Stone.m_itemData.m_shared.m_name, -1, true)),
				PlaceDelay = player.m_placeDelay,
				PickSeconds = pickSeconds
			};
			budget.Pickaxe = (from i in ((Humanoid)player).GetInventory().GetAllItems()
				where (int)i.m_shared.m_skillType == 12 && rates.DigVolumePerHit(i) > 0f && (!i.m_shared.m_useDurability || i.m_durability > 0f)
				orderby HitsLeft(i) * rates.DigVolumePerHit(i) descending
				select i).FirstOrDefault();
			if (budget.Pickaxe != null)
			{
				ItemData pickaxe = budget.Pickaxe;
				budget.PickVolume = rates.DigVolumePerHit(pickaxe);
				budget.Yield = rates.YieldPerHit(pickaxe);
				budget.PickStamina = AttackStamina(player, pickaxe) * (1f - staminaDiscount);
				budget.PickWear = (pickaxe.m_shared.m_useDurability ? (pickaxe.m_shared.m_useDurabilityDrain * Game.m_durabilityRate) : 0f);
				budget.PickDurability = (pickaxe.m_shared.m_useDurability ? pickaxe.m_durability : float.PositiveInfinity);
			}
			return budget;
		}

		private static float HitsLeft(ItemData tool)
		{
			float num = tool.m_shared.m_useDurabilityDrain * Game.m_durabilityRate;
			if (!tool.m_shared.m_useDurability || !(num > 0f))
			{
				return float.PositiveInfinity;
			}
			return tool.m_durability / num;
		}

		private static float AttackStamina(Player player, ItemData tool)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			float attackStamina = tool.m_shared.m_attack.m_attackStamina;
			if (attackStamina <= 0f)
			{
				return 0f;
			}
			attackStamina *= 1f + ((Character)player).GetEquipmentAttackStaminaModifier();
			((Character)player).GetSEMan().ModifyAttackStaminaUsage(attackStamina, ref attackStamina, true);
			return attackStamina - attackStamina * 0.33f * ((Character)player).GetSkillFactor(tool.m_shared.m_skillType);
		}

		public Cost CostOf(int vertices, float stoneVolume, float pickVolume, float yieldVolume, VanillaRates rates)
		{
			int num = ((stoneVolume > 0.01f) ? Mathf.CeilToInt(stoneVolume / rates.RaiseVolumePerSwing) : 0);
			int num2 = ((vertices > 0) ? Mathf.CeilToInt((float)vertices / (float)rates.VerticesPerSwing) : 0);
			int num3 = ((pickVolume > 0.01f && PickVolume > 0f) ? Mathf.CeilToInt(pickVolume / PickVolume) : 0);
			int num4 = num2 + num;
			return new Cost(vertices, num2, num, num3, num * rates.StonePerRaiseSwing, (float)num4 * HoeStamina + (float)num3 * PickStamina, (float)num4 * HoeWear, (float)num3 * PickWear, (float)num4 * PlaceDelay + (float)num3 * PickSeconds, Returned(pickVolume, yieldVolume));
		}

		private int Returned(float pickVolume, float yieldVolume)
		{
			if (!Object.op_Implicit((Object)(object)Yield.Item) || PickVolume <= 0f)
			{
				return 0;
			}
			return Mathf.FloorToInt((Yield.AtMaxDepth ? pickVolume : yieldVolume) / PickVolume * Yield.PerHit);
		}

		private Shortage Check(Cost cost)
		{
			if (cost.Stamina > Stamina)
			{
				return Shortage.Stamina;
			}
			if (cost.HoeWear > HoeDurability)
			{
				return Shortage.HoeWear;
			}
			if (cost.PickWear > PickDurability)
			{
				return Shortage.PickaxeWear;
			}
			if (cost.Stone > Stone)
			{
				return Shortage.Stone;
			}
			return Shortage.None;
		}

		public (Cost cost, Shortage shortage) Select(AreaPlan plan, Vector3 player, VanillaRates rates, Func<VertexPlan, bool> allowed = null)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			wanted.Clear();
			foreach (VertexPlan vertex in plan.Vertices)
			{
				vertex.Selected = false;
				if (vertex.Wanted && (allowed == null || allowed(vertex)))
				{
					wanted.Add(vertex);
				}
			}
			wanted.Sort((VertexPlan a, VertexPlan b) => Flat(a.Point - player).CompareTo(Flat(b.Point - player)));
			Cost item = CostOf(0, 0f, 0f, 0f, rates);
			int num = 0;
			float num2 = 0f;
			float num3 = 0f;
			float num4 = 0f;
			foreach (VertexPlan item2 in wanted)
			{
				Cost cost = CostOf(num + 1, num2 + item2.StoneVolume, num3 + item2.PickVolume, num4 + item2.YieldVolume, rates);
				Shortage shortage = Check(cost);
				if (shortage != Shortage.None)
				{
					return (cost: item, shortage: shortage);
				}
				item2.Selected = true;
				num++;
				num2 += item2.StoneVolume;
				num3 += item2.PickVolume;
				num4 += item2.YieldVolume;
				item = cost;
			}
			return (cost: item, shortage: Shortage.None);
		}

		private static float Flat(Vector3 v)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			return v.x * v.x + v.z * v.z;
		}
	}
	internal sealed class GaugeMesh
	{
		private const float HalfSize = 0.15f;

		private const float Lift = 0.05f;

		private readonly GameObject root = new GameObject("LevelEasilyPreview");

		private readonly Mesh mesh = new Mesh();

		private readonly List<Vector3> vertices = new List<Vector3>();

		private readonly List<Color> colours = new List<Color>();

		private readonly List<int> indices = new List<int>();

		public GaugeMesh()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected O, but got Unknown
			Object.DontDestroyOnLoad((Object)(object)root);
			mesh.MarkDynamic();
			root.AddComponent<MeshFilter>().sharedMesh = mesh;
			Material val = new Material(Shader.Find("Hidden/Internal-Colored"));
			val.SetInt("_ZTest", 8);
			val.SetInt("_ZWrite", 0);
			val.SetInt("_Cull", 0);
			((Renderer)root.AddComponent<MeshRenderer>()).sharedMaterial = val;
			root.SetActive(false);
		}

		public void SetVisible(bool visible)
		{
			root.SetActive(visible);
		}

		public void Rebuild(IEnumerable<(Vector3 point, Color colour)> markers)
		{
			//IL_0034: 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)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: 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_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: 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_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: 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_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: 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)
			vertices.Clear();
			colours.Clear();
			indices.Clear();
			foreach (var marker in markers)
			{
				Vector3 item = marker.point;
				Color item2 = marker.colour;
				Vector3 val = item + Vector3.up * 0.05f;
				indices.Add(vertices.Count);
				vertices.Add(val + new Vector3(-0.15f, 0f, -0.15f));
				indices.Add(vertices.Count);
				vertices.Add(val + new Vector3(-0.15f, 0f, 0.15f));
				indices.Add(vertices.Count);
				vertices.Add(val + new Vector3(0.15f, 0f, 0.15f));
				indices.Add(vertices.Count);
				vertices.Add(val + new Vector3(0.15f, 0f, -0.15f));
				for (int i = 0; i < 4; i++)
				{
					colours.Add(item2);
				}
			}
			mesh.Clear();
			mesh.SetVertices(vertices);
			mesh.SetColors(colours);
			mesh.SetIndices(indices, (MeshTopology)2, 0, true, 0);
			mesh.RecalculateBounds();
		}
	}
	[BepInPlugin("PetyM.LevelEasily", "LevelEasily", "0.2.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(Player), "TryPlacePiece")]
		private static class TryPlacePiecePatch
		{
			private static bool Prefix(Player __instance, Piece piece, ref bool __result)
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				if (!IsAreaPiece(piece))
				{
					return true;
				}
				if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer)
				{
					__result = false;
					return false;
				}
				__instance.UpdatePlacementGhost(true);
				if ((int)__instance.m_placementStatus != 0)
				{
					return true;
				}
				instance.BeginLevel(__instance);
				__result = false;
				return false;
			}
		}

		private const string Guid = "PetyM.LevelEasily";

		private const string PieceName = "LevelEasily_LevelArea";

		private const float FullColourDeviation = 1f;

		private const float AimDistance = 50f;

		private const float MeasureInterval = 0.5f;

		private const float TargetTolerance = 0.02f;

		private const float ClaimWait = 0.5f;

		private const float PlayerClearance = 1.5f;

		private const float PlayerSafeRise = 0.5f;

		private const int MaxWorkSounds = 6;

		private const float MinWorkSoundSpacing = 0.3f;

		private const float MaxWorkSoundSpacing = 0.7f;

		private static readonly Color Level = new Color(0.2f, 0.95f, 0.3f, 0.9f);

		private static readonly Color TooHigh = new Color(1f, 0.1f, 0.1f, 0.9f);

		private static readonly Color TooLow = new Color(0.1f, 0.35f, 1f, 0.9f);

		private static readonly Color OutOfReach = new Color(0.75f, 0.2f, 1f, 0.9f);

		private static readonly Color UnderPiece = new Color(0.55f, 0.55f, 0.55f, 0.9f);

		private static readonly Color NoPickaxe = new Color(0.4f, 0f, 0f, 0.9f);

		private static readonly Color Unaffordable = new Color(0.15f, 0.15f, 0.15f, 0.9f);

		private static Plugin instance;

		private ConfigEntry<KeyboardShortcut> lockKey;

		private ConfigEntry<KeyboardShortcut> raiseKey;

		private ConfigEntry<KeyboardShortcut> lowerKey;

		private ConfigEntry<KeyboardShortcut> widerKey;

		private ConfigEntry<KeyboardShortcut> narrowerKey;

		private ConfigEntry<KeyboardShortcut> longerKey;

		private ConfigEntry<KeyboardShortcut> shorterKey;

		private ConfigEntry<float> step;

		private ConfigEntry<float> pickaxeSeconds;

		private ConfigEntry<float> staminaDiscount;

		private ConfigEntry<int> maxSize;

		private ConfigEntry<bool> preserveSoil;

		private int aimMask;

		private int pieceMask;

		private VanillaRates rates;

		private GaugeMesh preview;

		private AreaPlan plan;

		private Budget budget;

		private Cost cost;

		private Shortage shortage;

		private float lastMeasure;

		private bool working;

		private Vector2Int size = new Vector2Int(4, 4);

		private float? lockedHeight;

		private Vector2Int? gridAnchor;

		private string readout;

		private GUIStyle readoutStyle;

		private void Awake()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Expected O, but got Unknown
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Expected O, but got Unknown
			//IL_021b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Expected O, but got Unknown
			//IL_02aa: Unknown result type (might be due to invalid IL or missing references)
			instance = this;
			lockKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Keys", "Lock", new KeyboardShortcut((KeyCode)108, Array.Empty<KeyCode>()), "Locks the target height (top surface of the building piece under the cursor, otherwise the ground under the player) and the area grid. Press again to unlock.");
			raiseKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Keys", "Raise target", new KeyboardShortcut((KeyCode)280, Array.Empty<KeyCode>()), (ConfigDescription)null);
			lowerKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Keys", "Lower target", new KeyboardShortcut((KeyCode)281, Array.Empty<KeyCode>()), (ConfigDescription)null);
			widerKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Keys", "Wider", new KeyboardShortcut((KeyCode)275, Array.Empty<KeyCode>()), (ConfigDescription)null);
			narrowerKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Keys", "Narrower", new KeyboardShortcut((KeyCode)276, Array.Empty<KeyCode>()), (ConfigDescription)null);
			longerKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Keys", "Longer", new KeyboardShortcut((KeyCode)273, Array.Empty<KeyCode>()), (ConfigDescription)null);
			shorterKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Keys", "Shorter", new KeyboardShortcut((KeyCode)274, Array.Empty<KeyCode>()), (ConfigDescription)null);
			step = ((BaseUnityPlugin)this).Config.Bind<float>("Keys", "Height step", 0.1f, "How many metres one key press moves the target.");
			maxSize = ((BaseUnityPlugin)this).Config.Bind<int>("Area", "Largest side", 16, new ConfigDescription("Largest length of an area side in metres.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 32), Array.Empty<object>()));
			preserveSoil = ((BaseUnityPlugin)this).Config.Bind<bool>("Area", "Preserve cultivated and paved ground", true, "Levels cultivated and paved ground but does not paint it over with dirt.");
			pickaxeSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Cost", "Pickaxe hit time", 1f, new ConfigDescription("How many seconds one counted pickaxe hit blocks the hoe for.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>()));
			staminaDiscount = ((BaseUnityPlugin)this).Config.Bind<float>("Cost", "Stamina discount", 0.3f, new ConfigDescription("How much less stamina hoe swings and pickaxe hits cost compared with manual work (0.3 = 30 % less).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			aimMask = LayerMask.GetMask(new string[5] { "piece", "piece_nonsolid", "Default", "static_solid", "terrain" });
			pieceMask = LayerMask.GetMask(new string[4] { "piece", "piece_nonsolid", "Default", "static_solid" });
			PrefabManager.OnVanillaPrefabsAvailable += AddLevelAreaPiece;
			new Harmony("PetyM.LevelEasily").PatchAll();
		}

		private void AddLevelAreaPiece()
		{
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Expected O, but got Unknown
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Expected O, but got Unknown
			PrefabManager.OnVanillaPrefabsAvailable -= AddLevelAreaPiece;
			rates = VanillaRates.FromHoe(Cache.GetPrefab<ItemDrop>("Hoe").m_itemData.m_shared.m_buildPieces, ((BaseUnityPlugin)this).Logger);
			GameObject val = PrefabManager.Instance.CreateClonedPrefab("LevelEasily_LevelArea", ((Component)rates.LevelPiece).gameObject);
			CircleProjector[] componentsInChildren = val.GetComponentsInChildren<CircleProjector>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Object.DestroyImmediate((Object)(object)componentsInChildren[i]);
			}
			Renderer[] componentsInChildren2 = val.GetComponentsInChildren<Renderer>(true);
			for (int i = 0; i < componentsInChildren2.Length; i++)
			{
				componentsInChildren2[i].enabled = false;
			}
			PieceManager.Instance.AddPiece(new CustomPiece(val, false, new PieceConfig
			{
				Name = "Level area",
				Description = "Levels a rectangle snapped to the metre grid to the target height with one click. Costs as much as the manual work would: hoe swings, pickaxe hits from your inventory and stone for filling.\nArrows: size · L: lock height and grid · PageUp/PageDown: move target",
				PieceTable = "Hoe"
			}));
		}

		private static bool IsAreaPiece(Piece piece)
		{
			if (Object.op_Implicit((Object)(object)piece))
			{
				return ((Object)piece).name == "LevelEasily_LevelArea";
			}
			return false;
		}

		private void Update()
		{
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: 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_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			GameObject val = (Object.op_Implicit((Object)(object)localPlayer) ? localPlayer.m_placementGhost : null);
			if (!Object.op_Implicit((Object)(object)val) || !val.activeSelf || !IsAreaPiece(localPlayer.GetSelectedPiece()) || ((Humanoid)localPlayer).GetRightItem() == null)
			{
				plan = null;
				preview?.SetVisible(visible: false);
				return;
			}
			if (AcceptsInput())
			{
				HandleKeys(localPlayer);
			}
			budget = Budget.Of(localPlayer, rates, pickaxeSeconds.Value, staminaDiscount.Value);
			RectInt val2 = SnapArea(val.transform.position);
			float num = GroundUnder(localPlayer);
			float num2 = lockedHeight ?? num;
			bool flag = num2 <= num + 0.01f;
			bool hasPickaxe = budget.Pickaxe != null;
			if (plan == null || plan.Area != val2 || Mathf.Abs(plan.Target - num2) > 0.02f || plan.FreeFill != flag || Time.time - lastMeasure > 0.5f)
			{
				plan = AreaPlan.Measure(val2, num2, flag, hasPickaxe, val, pieceMask);
				lastMeasure = Time.time;
			}
			(Cost, Shortage) tuple = budget.Select(plan, ((Component)localPlayer).transform.position, rates);
			cost = tuple.Item1;
			shortage = tuple.Item2;
			readout = Readout();
			if (preview == null)
			{
				preview = new GaugeMesh();
			}
			preview.SetVisible(visible: true);
			preview.Rebuild(plan.Vertices.Select((VertexPlan v) => (Point: v.Point, ColourFor(v))));
		}

		private void OnGUI()
		{
			//IL_0063: 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_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			if (plan != null)
			{
				if (readoutStyle == null)
				{
					readoutStyle = new GUIStyle(GUI.skin.label)
					{
						alignment = (TextAnchor)1,
						fontSize = 18
					};
				}
				GUI.Label(new Rect((float)Screen.width / 2f - 450f, (float)Screen.height / 2f + 40f, 900f, 160f), readout, readoutStyle);
			}
		}

		private static bool AcceptsInput()
		{
			if (!Console.IsVisible() && (!Object.op_Implicit((Object)(object)Chat.instance) || !Chat.instance.HasFocus()) && !TextInput.IsVisible() && !Menu.IsVisible() && !InventoryGui.IsVisible())
			{
				return !Hud.IsPieceSelectionVisible();
			}
			return false;
		}

		private void HandleKeys(Player player)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: 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_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			Vector3 forward = ((Component)GameCamera.instance).transform.forward;
			int num = Steps(widerKey, narrowerKey);
			int num2 = Steps(longerKey, shorterKey);
			size += ((Mathf.Abs(forward.z) >= Mathf.Abs(forward.x)) ? new Vector2Int(num, num2) : new Vector2Int(num2, num));
			((Vector2Int)(ref size)).Clamp(Vector2Int.one, Vector2Int.one * maxSize.Value);
			KeyboardShortcut value = lockKey.Value;
			RectInt area;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				lockedHeight = (lockedHeight.HasValue ? ((float?)null) : new float?(AimedHeight(player)));
				Vector2Int? obj;
				if (!lockedHeight.HasValue)
				{
					obj = null;
				}
				else
				{
					AreaPlan areaPlan = plan;
					if (areaPlan == null)
					{
						obj = null;
					}
					else
					{
						area = areaPlan.Area;
						obj = ((RectInt)(ref area)).min;
					}
				}
				gridAnchor = obj;
			}
			int num3 = Steps(raiseKey, lowerKey);
			if (num3 == 0)
			{
				return;
			}
			lockedHeight = (lockedHeight ?? GroundUnder(player)) + (float)num3 * step.Value;
			Vector2Int? val = gridAnchor;
			if (!val.HasValue)
			{
				AreaPlan areaPlan2 = plan;
				Vector2Int? obj2;
				if (areaPlan2 == null)
				{
					obj2 = null;
				}
				else
				{
					area = areaPlan2.Area;
					obj2 = ((RectInt)(ref area)).min;
				}
				gridAnchor = obj2;
			}
		}

		private static int Steps(ConfigEntry<KeyboardShortcut> up, ConfigEntry<KeyboardShortcut> down)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			KeyboardShortcut value = up.Value;
			bool num = ((KeyboardShortcut)(ref value)).IsDown();
			value = down.Value;
			return (num ? 1 : 0) - (((KeyboardShortcut)(ref value)).IsDown() ? 1 : 0);
		}

		private static float GroundUnder(Player player)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			return ZoneSystem.instance.GetGroundHeight(((Component)player).transform.position);
		}

		private float AimedHeight(Player player)
		{
			//IL_000c: 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_004c: 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)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			Transform transform = ((Component)GameCamera.instance).transform;
			RaycastHit val = default(RaycastHit);
			if (!Physics.Raycast(transform.position, transform.forward, ref val, 50f, aimMask) || !Object.op_Implicit((Object)(object)((Component)((RaycastHit)(ref val)).collider).GetComponentInParent<Piece>()))
			{
				return GroundUnder(player);
			}
			Bounds bounds = ((RaycastHit)(ref val)).collider.bounds;
			Ray val2 = default(Ray);
			((Ray)(ref val2))..ctor(new Vector3(((RaycastHit)(ref val)).point.x, ((Bounds)(ref bounds)).max.y + 1f, ((RaycastHit)(ref val)).point.z), Vector3.down);
			RaycastHit val3 = default(RaycastHit);
			if (!((RaycastHit)(ref val)).collider.Raycast(val2, ref val3, ((Bounds)(ref bounds)).size.y + 2f))
			{
				return ((RaycastHit)(ref val)).point.y;
			}
			return ((RaycastHit)(ref val3)).point.y;
		}

		private RectInt SnapArea(Vector3 cursor)
		{
			//IL_0002: 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_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: 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_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			Vector2Int val = default(Vector2Int);
			((Vector2Int)(ref val))..ctor(Mathf.RoundToInt(cursor.x - (float)((Vector2Int)(ref size)).x / 2f), Mathf.RoundToInt(cursor.z - (float)((Vector2Int)(ref size)).y / 2f));
			Vector2Int? val2 = gridAnchor;
			if (val2.HasValue)
			{
				Vector2Int valueOrDefault = val2.GetValueOrDefault();
				val = valueOrDefault + Vector2Int.RoundToInt(new Vector2((float)(((Vector2Int)(ref val)).x - ((Vector2Int)(ref valueOrDefault)).x) / (float)((Vector2Int)(ref size)).x, (float)(((Vector2Int)(ref val)).y - ((Vector2Int)(ref valueOrDefault)).y) / (float)((Vector2Int)(ref size)).y)) * size;
			}
			return new RectInt(val, size);
		}

		private static Color ColourFor(VertexPlan v)
		{
			//IL_0023: 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_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: 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_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			switch (v.State)
			{
			case VertexState.UnderPiece:
				return UnderPiece;
			case VertexState.NeedsPickaxe:
				return NoPickaxe;
			case VertexState.Level:
				if (!v.Unreachable)
				{
					return Level;
				}
				return OutOfReach;
			default:
			{
				Color val = (v.Unreachable ? OutOfReach : Color.Lerp(Color.white, (v.Rise < 0f) ? TooHigh : TooLow, Mathf.Lerp(0.4f, 1f, (Mathf.Abs(v.Rise) - 0.01f) / 1f)));
				if (!v.Selected)
				{
					return Color.Lerp(val, Unaffordable, 0.7f);
				}
				return val;
			}
			}
		}

		private static string ShortageText(Shortage s)
		{
			return s switch
			{
				Shortage.Stamina => "not enough stamina", 
				Shortage.HoeWear => "the hoe would break", 
				Shortage.PickaxeWear => "the pickaxe would break", 
				Shortage.Stone => "not enough stone", 
				_ => "", 
			};
		}

		private string Readout()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append($"{((Vector2Int)(ref size)).x} × {((Vector2Int)(ref size)).y} m · target {plan.Target:0.00} m");
			if (lockedHeight.HasValue)
			{
				stringBuilder.Append(" · locked");
			}
			if (plan.Target < ZoneSystem.instance.m_waterLevel)
			{
				stringBuilder.Append(" · below sea level");
			}
			stringBuilder.AppendLine();
			int num = plan.Vertices.Count((VertexPlan v) => v.Wanted);
			if (working)
			{
				stringBuilder.AppendLine("levelling…");
			}
			else if (num == 0)
			{
				stringBuilder.AppendLine("nothing to level");
			}
			else
			{
				stringBuilder.Append($"hoe {cost.AllSwings}× · pickaxe {cost.PickHits}× · stone {cost.Stone} · stamina {cost.Stamina:0} · {cost.Seconds:0.#} s");
				if (cost.Returned > 0)
				{
					stringBuilder.Append($" · you dig up {cost.Returned}× {Localization.instance.Localize(budget.Yield.Item.m_itemData.m_shared.m_name)}");
				}
				stringBuilder.AppendLine();
				stringBuilder.Append($"wear: hoe {cost.HoeWear:0.#}");
				if (cost.PickHits > 0)
				{
					stringBuilder.Append($", {Localization.instance.Localize(budget.Pickaxe.m_shared.m_name)} {cost.PickWear:0.#}");
				}
				if (cost.Vertices < num)
				{
					stringBuilder.Append($" · levels {cost.Vertices} of {num} points ({ShortageText(shortage)})");
				}
				stringBuilder.AppendLine();
			}
			List<string> list = new List<string>();
			int num2 = plan.Count(VertexState.UnderPiece);
			int num3 = plan.Count(VertexState.NeedsPickaxe);
			int num4 = plan.Vertices.Count((VertexPlan v) => v.Unreachable);
			if (num2 > 0)
			{
				list.Add($"under building {num2}");
			}
			if (num3 > 0)
			{
				list.Add($"no pickaxe {num3}");
			}
			if (num4 > 0)
			{
				list.Add($"out of reach ±8 m {num4}");
			}
			if (list.Count > 0)
			{
				stringBuilder.AppendLine("skipped: " + string.Join(" · ", list));
			}
			stringBuilder.Append(Hint(narrowerKey) + "/" + Hint(widerKey) + " width · " + Hint(shorterKey) + "/" + Hint(longerKey) + " length · " + Hint(lockKey) + " lock · " + Hint(raiseKey) + "/" + Hint(lowerKey) + " height");
			return stringBuilder.ToString();
		}

		private static string Hint(ConfigEntry<KeyboardShortcut> key)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return ((object)key.Value/*cast due to .constrained prefix*/).ToString();
		}

		private void BeginLevel(Player player)
		{
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			if (working || plan == null || budget == null)
			{
				return;
			}
			if (cost.Vertices == 0)
			{
				if (shortage == Shortage.Stamina)
				{
					Hud.instance.StaminaBarEmptyFlash();
				}
				Refuse(player, (shortage != Shortage.None) ? Capitalise(ShortageText(shortage)) : ((plan.Count(VertexState.NeedsPickaxe) > 0) ? "You need a pickaxe in your inventory" : "The area is already level"));
			}
			else
			{
				string text = Blocker(player, plan);
				if (text != null)
				{
					Refuse(player, text);
				}
				else
				{
					((MonoBehaviour)this).StartCoroutine(LevelRoutine(player, plan.Area, plan.Target, plan.FreeFill));
				}
			}
		}

		private static string Blocker(Player player, AreaPlan area)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			foreach (VertexPlan item in TerrainWriter.Touched(area))
			{
				if (Location.IsInsideNoBuildLocation(item.Point))
				{
					return "$msg_nobuildzone";
				}
				if (!PrivateArea.CheckAccess(item.Point, 0f, false, false))
				{
					PrivateArea.CheckAccess(item.Point, 0f, true, false);
					return "$msg_privatezone";
				}
			}
			if (!OtherPlayerInTheWay(player, area))
			{
				return null;
			}
			return "Another player is standing in the area";
		}

		private static bool OtherPlayerInTheWay(Player self, AreaPlan area)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: 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_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if (!Object.op_Implicit((Object)(object)allPlayer) || (Object)(object)allPlayer == (Object)(object)self)
				{
					continue;
				}
				Vector3 position = ((Component)allPlayer).transform.position;
				foreach (VertexPlan vertex in area.Vertices)
				{
					if (vertex.Selected && !(vertex.Rise <= 0.5f))
					{
						Vector3 val = vertex.Point - position;
						if (val.x * val.x + val.z * val.z < 2.25f)
						{
							return true;
						}
					}
				}
			}
			return false;
		}

		private IEnumerator LevelRoutine(Player player, RectInt area, float target, bool freeFill)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			working = true;
			ItemData hoe = ((Humanoid)player).GetRightItem();
			player.m_lastToolUseTime = Time.time + 0.5f;
			try
			{
				Dictionary<Heightmap, TerrainComp> claimed = TerrainWriter.Claim(plan);
				if (claimed == null)
				{
					Refuse(player, "The terrain cannot be modified here right now");
					yield break;
				}
				yield return (object)new WaitForSeconds(0.5f);
				if (!Object.op_Implicit((Object)(object)player) || (Object)(object)player != (Object)(object)Player.m_localPlayer || ((Character)player).IsDead() || ((Humanoid)player).GetRightItem() != hoe)
				{
					yield break;
				}
				if (!TerrainWriter.Ready(claimed))
				{
					Refuse(player, "Another player is modifying the terrain here");
					yield break;
				}
				Budget budget = Budget.Of(player, rates, pickaxeSeconds.Value, staminaDiscount.Value);
				AreaPlan areaPlan = AreaPlan.Measure(area, target, freeFill, budget.Pickaxe != null, player.m_placementGhost, pieceMask);
				var (paid, shortage) = budget.Select(areaPlan, ((Component)player).transform.position, rates, (VertexPlan v) => TerrainWriter.Covers(claimed, v));
				if (paid.Vertices == 0)
				{
					Refuse(player, (shortage != Shortage.None) ? Capitalise(ShortageText(shortage)) : "The area is already level");
					yield break;
				}
				string text = Blocker(player, areaPlan);
				if (text != null)
				{
					Refuse(player, text);
					yield break;
				}
				try
				{
					TerrainWriter.Write(areaPlan, claimed, preserveSoil.Value);
				}
				finally
				{
					Charge(player, budget, paid);
				}
				((MonoBehaviour)this).StartCoroutine(PlayWork(player, hoe, budget, paid, areaPlan));
				player.m_lastToolUseTime = Time.time + Mathf.Max(0f, paid.Seconds - player.m_placeDelay);
				plan = null;
				((MonoBehaviour)this).StartCoroutine(ResetGrassLater(areaPlan));
			}
			finally
			{
				working = false;
			}
		}

		private IEnumerator PlayWork(Player player, ItemData hoe, Budget paidFrom, Cost paid, AreaPlan written)
		{
			List<(Vector3, Action<Vector3>)> list = new List<(Vector3, Action<Vector3>)>();
			List<VertexPlan> list2 = written.Vertices.Where((VertexPlan v) => v.Selected).ToList();
			List<VertexPlan> vertices = list2.Where((VertexPlan v) => v.PickVolume > 0f).ToList();
			List<VertexPlan> vertices2 = list2.Where((VertexPlan v) => v.StoneVolume > 0f).ToList();
			TerrainOp digOp = ((paidFrom.Pickaxe != null) ? rates.DigOp(paidFrom.Pickaxe) : null);
			int num = Mathf.Clamp(paid.HoeSwings, 1, 6);
			int num2 = ((paidFrom.Pickaxe != null) ? Mathf.Min(paid.PickHits, 6) : 0);
			int num3 = Mathf.Min(paid.RaiseSwings, 6);
			for (int num4 = 0; num4 < Mathf.Max(num, Mathf.Max(num2, num3)); num4++)
			{
				if (num4 < num2)
				{
					list.Add((RandomPoint(vertices), Pick));
				}
				if (num4 < num3)
				{
					list.Add((RandomPoint(vertices2), Raise));
				}
				if (num4 < num)
				{
					list.Add((RandomPoint(list2), Hoe));
				}
			}
			player.FaceLookDirection();
			float spacing = Mathf.Clamp(paid.Seconds / (float)list.Count, 0.3f, 0.7f);
			foreach (var (obj, action) in list)
			{
				if (Object.op_Implicit((Object)(object)player))
				{
					if (((Humanoid)player).GetRightItem() == hoe)
					{
						((Character)player).m_zanim.SetTrigger(hoe.m_shared.m_attack.m_attackAnimation);
					}
					action(obj);
					yield return (object)new WaitForSeconds(spacing);
					continue;
				}
				yield break;
			}
			void Hoe(Vector3 at)
			{
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: 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_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_0047: Unknown result type (might be due to invalid IL or missing references)
				//IL_0055: Unknown result type (might be due to invalid IL or missing references)
				//IL_005b: Unknown result type (might be due to invalid IL or missing references)
				//IL_007d: 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_0090: 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)
				rates.LevelPiece.m_placeEffect.Create(at, Quaternion.identity, (Transform)null, 1f, -1, default(ZDOID));
				rates.LevelOp.m_onPlacedEffect.Create(at, Quaternion.identity, (Transform)null, 1f, -1, default(ZDOID));
				hoe.m_shared.m_buildEffect.Create(((Component)player).transform.position, Quaternion.identity, (Transform)null, 1f, -1, default(ZDOID));
			}
			void Pick(Vector3 at)
			{
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: 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_004b: 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_005a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0060: Unknown result type (might be due to invalid IL or missing references)
				//IL_007f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0080: Unknown result type (might be due to invalid IL or missing references)
				//IL_008e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0094: Unknown result type (might be due to invalid IL or missing references)
				paidFrom.Pickaxe.m_shared.m_hitTerrainEffect.Create(at, Quaternion.identity, (Transform)null, 1f, -1, default(ZDOID));
				paidFrom.Pickaxe.m_shared.m_attack.m_hitTerrainEffect.Create(at, Quaternion.identity, (Transform)null, 1f, -1, default(ZDOID));
				if (Object.op_Implicit((Object)(object)digOp))
				{
					digOp.m_onPlacedEffect.Create(at, Quaternion.identity, (Transform)null, 1f, -1, default(ZDOID));
				}
			}
			void Raise(Vector3 at)
			{
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: 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_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_0047: Unknown result type (might be due to invalid IL or missing references)
				//IL_0055: Unknown result type (might be due to invalid IL or missing references)
				//IL_005b: Unknown result type (might be due to invalid IL or missing references)
				rates.RaisePiece.m_placeEffect.Create(at, Quaternion.identity, (Transform)null, 1f, -1, default(ZDOID));
				rates.RaiseOp.m_onPlacedEffect.Create(at, Quaternion.identity, (Transform)null, 1f, -1, default(ZDOID));
			}
		}

		private static Vector3 RandomPoint(List<VertexPlan> vertices)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			VertexPlan vertexPlan = vertices[Random.Range(0, vertices.Count)];
			return new Vector3(vertexPlan.Point.x, vertexPlan.Goal, vertexPlan.Point.z);
		}

		private void Charge(Player player, Budget paidFrom, Cost paid)
		{
			((Character)player).UseStamina(paid.Stamina);
			if (paidFrom.Hoe.m_shared.m_useDurability)
			{
				paidFrom.Hoe.m_durability = Mathf.Max(0f, paidFrom.Hoe.m_durability - paid.HoeWear);
			}
			if (paid.PickHits > 0 && paidFrom.Pickaxe.m_shared.m_useDurability)
			{
				paidFrom.Pickaxe.m_durability = Mathf.Max(0f, paidFrom.Pickaxe.m_durability - paid.PickWear);
			}
			if (paid.Stone > 0 && !player.m_noPlacementCost)
			{
				((Humanoid)player).GetInventory().RemoveItem(rates.Stone.m_itemData.m_shared.m_name, paid.Stone, -1, true);
			}
			if (paid.Returned > 0)
			{
				GiveDugItems(player, paidFrom.Yield.Item, paid.Returned);
			}
		}

		private static void GiveDugItems(Player player, ItemDrop item, int amount)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: 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)
			Inventory inventory = ((Humanoid)player).GetInventory();
			int i;
			for (i = 0; i < amount && inventory.CanAddItem(((Component)item).gameObject, i + 1); i++)
			{
			}
			if (i > 0)
			{
				inventory.AddItem(((Component)item).gameObject, i);
			}
			int num = Mathf.Max(1, item.m_itemData.m_shared.m_maxStackSize);
			for (int num2 = amount - i; num2 > 0; num2 -= num)
			{
				Object.Instantiate<GameObject>(((Component)item).gameObject, ((Component)player).transform.position + Vector3.up, Quaternion.identity).GetComponent<ItemDrop>().m_itemData.m_stack = Mathf.Min(num2, num);
			}
			((Character)player).Message((MessageType)1, $"+{amount} {Localization.instance.Localize(item.m_itemData.m_shared.m_name)}", 0, (Sprite)null, false);
		}

		private IEnumerator ResetGrassLater(AreaPlan levelled)
		{
			yield return null;
			yield return null;
			if (Object.op_Implicit((Object)(object)ClutterSystem.instance))
			{
				ClutterSystem.instance.ResetGrass(levelled.Centre, levelled.HalfDiagonal + 1f);
			}
		}

		private static string Capitalise(string text)
		{
			if (text.Length != 0)
			{
				return char.ToUpper(text[0]) + text.Substring(1);
			}
			return text;
		}

		private static void Refuse(Player player, string message)
		{
			((Character)player).Message((MessageType)2, message, 0, (Sprite)null, false);
		}
	}
	internal static class TerrainWriter
	{
		private static readonly List<Heightmap> Found = new List<Heightmap>();

		public static IEnumerable<VertexPlan> Touched(AreaPlan plan)
		{
			foreach (VertexPlan vertex in plan.Vertices)
			{
				if (vertex.Wanted || vertex.State == VertexState.Level)
				{
					yield return vertex;
				}
			}
		}

		public static Dictionary<Heightmap, TerrainComp> Claim(AreaPlan plan)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<Heightmap, TerrainComp> dictionary = new Dictionary<Heightmap, TerrainComp>();
			foreach (VertexPlan item in Touched(plan))
			{
				Found.Clear();
				Heightmap.FindHeightmap(item.Point, 0f, Found);
				foreach (Heightmap item2 in Found)
				{
					if (!dictionary.ContainsKey(item2))
					{
						TerrainComp andCreateTerrainCompiler = item2.GetAndCreateTerrainCompiler();
						if (!Object.op_Implicit((Object)(object)andCreateTerrainCompiler) || !andCreateTerrainCompiler.m_nview.IsValid())
						{
							return null;
						}
						andCreateTerrainCompiler.m_nview.ClaimOwnership();
						dictionary[item2] = andCreateTerrainCompiler;
					}
				}
			}
			if (dictionary.Count <= 0)
			{
				return null;
			}
			return dictionary;
		}

		public static bool Covers(Dictionary<Heightmap, TerrainComp> claimed, VertexPlan v)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			Found.Clear();
			Heightmap.FindHeightmap(v.Point, 0f, Found);
			if (Found.Count == 0)
			{
				return false;
			}
			foreach (Heightmap item in Found)
			{
				if (!claimed.ContainsKey(item))
				{
					return false;
				}
			}
			return true;
		}

		public static bool Ready(Dictionary<Heightmap, TerrainComp> claimed)
		{
			foreach (TerrainComp value in claimed.Values)
			{
				if (!Object.op_Implicit((Object)(object)value) || !value.m_nview.IsValid() || !value.m_nview.IsOwner() || !value.m_initialized)
				{
					return false;
				}
			}
			foreach (TerrainComp value2 in claimed.Values)
			{
				value2.CheckLoad();
				value2.m_hmap.Poke(0, false);
			}
			return true;
		}

		public static void Write(AreaPlan plan, Dictionary<Heightmap, TerrainComp> claimed, bool preserveSoil)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: 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_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			foreach (TerrainComp value in claimed.Values)
			{
				foreach (VertexPlan vertex in plan.Vertices)
				{
					if (vertex.Selected)
					{
						SetHeight(value, vertex);
					}
				}
				foreach (Vector2Int item in AreaPlan.Cells(plan.Area))
				{
					if (IsPaintedCell(plan, item))
					{
						PaintDirt(value, item, preserveSoil);
					}
				}
				value.m_operations++;
				value.m_lastOpPoint = plan.Centre;
				value.m_lastOpRadius = plan.HalfDiagonal + 1f;
				value.Save(false);
				value.m_hmap.Poke(0, false);
			}
		}

		private static void SetHeight(TerrainComp compiler, VertexPlan v)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			Heightmap hmap = compiler.m_hmap;
			int num = default(int);
			int num2 = default(int);
			hmap.WorldToVertex(v.Point, ref num, ref num2);
			int num3 = compiler.m_width + 1;
			float num4 = default(float);
			if (num >= 0 && num2 >= 0 && num < num3 && num2 < num3 && hmap.GetWorldHeight(v.Point, ref num4))
			{
				float item = AreaPlan.BaseHeight(hmap, compiler, new Vector3(v.Point.x, num4, v.Point.z)).baseHeight;
				int num5 = num2 * num3 + num;
				compiler.m_levelDelta[num5] = Mathf.Clamp(v.Goal - item, -8f, 8f);
				compiler.m_smoothDelta[num5] = 0f;
				compiler.m_modifiedHeight[num5] = true;
			}
		}

		private static bool IsPaintedCell(AreaPlan plan, Vector2Int cell)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			bool flag = false;
			for (int i = 0; i <= 1; i++)
			{
				for (int j = 0; j <= 1; j++)
				{
					if (!plan.TryGet(cell + new Vector2Int(i, j), out var vertex) || !vertex.FlatAfterWrite)
					{
						return false;
					}
					flag |= vertex.Selected;
				}
			}
			return flag;
		}

		private static void PaintDirt(TerrainComp compiler, Vector2Int cell, bool preserveSoil)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: 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_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: 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_007e: Unknown result type (might be due to invalid IL or missing references)
			Heightmap hmap = compiler.m_hmap;
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor((float)((Vector2Int)(ref cell)).x, 0f, (float)((Vector2Int)(ref cell)).y);
			int num = default(int);
			int num2 = default(int);
			hmap.WorldToVertexMask(val, ref num, ref num2);
			if (num >= 0 && num2 >= 0 && num <= compiler.m_width && num2 <= compiler.m_width)
			{
				int num3 = num2 * compiler.m_pitch + num;
				Color val2 = (compiler.m_modifiedPaint[num3] ? compiler.m_paintMask[num3] : hmap.GetPaintMask(num, num2));
				if (!preserveSoil || !IsWorkedSoil(hmap, val, val2))
				{
					compiler.m_paintMask[num3] = new Color(1f, 0f, 0f, val2.a);
					compiler.m_modifiedPaint[num3] = true;
				}
			}
		}

		private static bool IsWorkedSoil(Heightmap heightmap, Vector3 world, Color paint)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Invalid comparison between Unknown and I4
			if (!(paint.b > 0.5f))
			{
				if (paint.g > 0.5f)
				{
					return (int)heightmap.GetBiome(world + new Vector3(0.5f, 0f, 0.5f), 0.02f, false) != 64;
				}
				return false;
			}
			return true;
		}
	}
	internal sealed class VanillaRates
	{
		private const float MaxResidual = 0.05f;

		private readonly ManualLogSource log;

		private readonly Dictionary<SharedData, float> digVolumes = new Dictionary<SharedData, float>();

		private readonly Dictionary<SharedData, DigYield> digYields = new Dictionary<SharedData, DigYield>();

		public Piece LevelPiece { get; }

		public TerrainOp LevelOp { get; }

		public Piece RaisePiece { get; }

		public TerrainOp RaiseOp { get; }

		public int VerticesPerSwing { get; }

		public float RaiseVolumePerSwing { get; }

		public ItemDrop Stone { get; }

		public int StonePerRaiseSwing { get; }

		private VanillaRates(PieceTable hoe, ManualLogSource log)
		{
			this.log = log;
			LevelPiece = hoe.m_pieces.First((GameObject p) => Object.op_Implicit((Object)(object)p) && ((Object)p).name == "mud_road_v2").GetComponent<Piece>();
			Piece val = (RaisePiece = hoe.m_pieces.First((GameObject p) => Object.op_Implicit((Object)(object)p) && ((Object)p).name == "raise_v2").GetComponent<Piece>());
			RaiseOp = ((Component)val).GetComponentInChildren<TerrainOp>(true);
			LevelOp = ((Component)LevelPiece).GetComponentInChildren<TerrainOp>(true);
			Settings settings = LevelOp.m_settings;
			Settings raiseOp = ((Component)val).GetComponentInChildren<TerrainOp>(true).m_settings;
			VerticesPerSwing = SmoothVerticesPerSwing(settings.m_smoothRadius, settings.m_smoothPower);
			RaiseVolumePerSwing = Footprint(raiseOp.m_raiseRadius, raiseOp.m_square, (float d) => raiseOp.m_raiseDelta * Falloff(d, raiseOp.m_raiseRadius, raiseOp.m_raisePower, raiseOp.m_square));
			Stone = val.m_resources[0].m_resItem;
			StonePerRaiseSwing = val.m_resources[0].m_amount;
			log.LogInfo((object)($"Level ground: smooth r{settings.m_smoothRadius} power {settings.m_smoothPower} → {VerticesPerSwing} vertices per swing; " + $"piece groundPiece={LevelPiece.m_groundPiece} altGround={LevelPiece.m_allowAltGroundPlacement} " + $"dungeon={LevelPiece.m_allowedInDungeons} deepSnow={LevelPiece.m_allowedInDeepSnow}"));
			log.LogInfo((object)("Effects: Level ground place " + Describe(LevelPiece.m_placeEffect) + ", op " + Describe(LevelOp.m_onPlacedEffect) + "; Raise ground place " + Describe(val.m_placeEffect) + ", op " + Describe(RaiseOp.m_onPlacedEffect)));
			log.LogInfo((object)$"Raise ground: {RaiseVolumePerSwing:0.00} m³ and {StonePerRaiseSwing}× {((Object)Stone).name} per swing");
		}

		public TerrainOp DigOp(ItemData tool)
		{
			if (!Object.op_Implicit((Object)(object)tool.m_shared.m_spawnOnHitTerrain))
			{
				return null;
			}
			return tool.m_shared.m_spawnOnHitTerrain.GetComponentInChildren<TerrainOp>(true);
		}

		public static string Describe(EffectList effects)
		{
			if (effects?.m_effectPrefabs != null && effects.m_effectPrefabs.Length != 0)
			{
				return string.Join(", ", from e in effects.m_effectPrefabs
					where Object.op_Implicit((Object)(object)e.m_prefab)
					select ((Object)e.m_prefab).name);
			}
			return "none";
		}

		public static VanillaRates FromHoe(PieceTable hoe, ManualLogSource log)
		{
			return new VanillaRates(hoe, log);
		}

		public float DigVolumePerHit(ItemData tool)
		{
			SharedData shared = tool.m_shared;
			if (digVolumes.TryGetValue(shared, out var value))
			{
				return value;
			}
			value = 0f;
			TerrainOp val = (Object.op_Implicit((Object)(object)shared.m_spawnOnHitTerrain) ? shared.m_spawnOnHitTerrain.GetComponentInChildren<TerrainOp>(true) : null);
			if (Object.op_Implicit((Object)(object)val))
			{
				Settings s = val.m_settings;
				float levelDepth = (s.m_level ? Mathf.Max(0f, 0f - s.m_levelOffset) : 0f);
				float raiseDepth = (s.m_raise ? Mathf.Max(0f, 0f - s.m_raiseDelta) : 0f);
				value = Footprint(Mathf.Max(s.m_level ? s.m_levelRadius : 0f, s.m_raise ? s.m_raiseRadius : 0f), s.m_square, (float d) => Mathf.Max((d <= s.m_levelRadius || s.m_square) ? levelDepth : 0f, (d <= s.m_raiseRadius) ? (raiseDepth * Falloff(d, s.m_raiseRadius, s.m_raisePower, s.m_square)) : 0f));
				log.LogInfo((object)($"{shared.m_name}: {((Object)val).name} level={s.m_level} r{s.m_levelRadius} offset {s.m_levelOffset}, " + $"raise={s.m_raise} r{s.m_raiseRadius} delta {s.m_raiseDelta}, square={s.m_square} → {value:0.00} m³ per hit"));
			}
			digVolumes[shared] = value;
			return value;
		}

		public DigYield YieldPerHit(ItemData tool)
		{
			SharedData shared = tool.m_shared;
			if (digYields.TryGetValue(shared, out var value))
			{
				return value;
			}
			TerrainOp val = (Object.op_Implicit((Object)(object)shared.m_spawnOnHitTerrain) ? shared.m_spawnOnHitTerrain.GetComponentInChildren<TerrainOp>(true) : null);
			ItemDrop val2 = ((Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)val.m_spawnOnPlaced)) ? val.m_spawnOnPlaced.GetComponent<ItemDrop>() : null);
			value = (Object.op_Implicit((Object)(object)val2) ? new DigYield(val2, Mathf.Clamp01(val.m_chanceToSpawn) * (float)(1 + Mathf.Max(1, val.m_maxSpawned)) / 2f, val.m_spawnAtMaxLevelDepth) : new DigYield(null, 0f, atMaxDepth: false));
			log.LogInfo((object)(Object.op_Implicit((Object)(object)val2) ? ($"{shared.m_name}: a hit drops {((Object)val2).name} with chance {val.m_chanceToSpawn}, 1–{val.m_maxSpawned} pcs " + $"(average {value.PerHit:0.00}), also at max depth {val.m_spawnAtMaxLevelDepth}") : (shared.m_name + ": a terrain hit drops nothing")));
			digYields[shared] = value;
			return value;
		}

		private static int SmoothVerticesPerSwing(float radius, float power)
		{
			int num = Mathf.CeilToInt(radius);
			for (int num2 = 2 * num; num2 > 1; num2--)
			{
				float num3 = 0f;
				for (int i = 0; i < num2; i++)
				{
					for (int j = 0; j < num2; j++)
					{
						num3 = Mathf.Max(num3, Residual(i, j, num2, num, radius, power));
					}
				}
				if (num3 <= 0.05f)
				{
					return num2 * num2;
				}
			}
			return 1;
		}

		private static float Residual(int ox, int oz, int spacing, int reach, float radius, float power)
		{
			//IL_0028: 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)
			float num = 1f;
			for (int i = Mathf.FloorToInt((float)(ox - reach) / (float)spacing); i * spacing <= ox + reach; i++)
			{
				for (int j = Mathf.FloorToInt((float)(oz - reach) / (float)spacing); j * spacing <= oz + reach; j++)
				{
					float num2 = Vector2.Distance(new Vector2((float)ox, (float)oz), new Vector2((float)(i * spacing), (float)(j * spacing)));
					if (num2 < radius)
					{
						num *= Mathf.Pow(num2 / radius, power);
					}
				}
			}
			return num;
		}

		private static float Falloff(float distance, float radius, float power, bool square)
		{
			if (!square && !(power <= 0f))
			{
				return Mathf.Pow(Mathf.Max(0f, 1f - distance / radius), power);
			}
			return 1f;
		}

		private static float Footprint(float radius, bool square, Func<float, float> weight)
		{
			int num = Mathf.CeilToInt(radius);
			float num2 = 0f;
			for (int i = -num; i <= num; i++)
			{
				for (int j = -num; j <= num; j++)
				{
					float num3 = Mathf.Sqrt((float)(i * i + j * j));
					if (square || !(num3 > radius))
					{
						num2 += weight(num3);
					}
				}
			}
			return num2;
		}
	}
	internal readonly struct DigYield
	{
		public readonly ItemDrop Item;

		public readonly float PerHit;

		public readonly bool AtMaxDepth;

		public DigYield(ItemDrop item, float perHit, bool atMaxDepth)
		{
			Item = item;
			PerHit = perHit;
			AtMaxDepth = atMaxDepth;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}