Decompiled source of Architet v0.19.3

Architect.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace Architect;

internal static class Anel
{
	private static GameObject go;

	private static CircleProjector cp;

	private static Material vermelho;

	private static float raioFeito = -1f;

	private static readonly MethodInfo mCriar = AccessTools.Method(typeof(CircleProjector), "CreateSegments", (Type[])null, (Type[])null);

	private static bool Criar()
	{
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Expected O, but got Unknown
		//IL_009e: 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)
		GameObject val = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab("guard_stone") : null);
		PrivateArea val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<PrivateArea>() : null);
		CircleProjector val3 = (((Object)(object)val2 != (Object)null) ? val2.m_areaMarker : null);
		if ((Object)(object)val3 == (Object)null || (Object)(object)val3.m_prefab == (Object)null)
		{
			return false;
		}
		go = new GameObject("Architect_Anel");
		go.SetActive(false);
		cp = go.AddComponent<CircleProjector>();
		cp.m_prefab = val3.m_prefab;
		cp.m_mask = val3.m_mask;
		cp.m_speed = val3.m_speed;
		cp.m_radius = 1f;
		cp.m_nrOfSegments = 8;
		go.SetActive(true);
		raioFeito = -1f;
		return true;
	}

	private static void Pintar()
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Expected O, but got Unknown
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Expected O, but got Unknown
		//IL_0088: 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_00be: Unknown result type (might be due to invalid IL or missing references)
		Color val3 = default(Color);
		foreach (Transform item in go.transform)
		{
			Transform val = item;
			Renderer[] componentsInChildren = ((Component)val).GetComponentsInChildren<Renderer>();
			foreach (Renderer val2 in componentsInChildren)
			{
				if ((Object)(object)vermelho == (Object)null)
				{
					vermelho = new Material(val2.sharedMaterial);
					((Color)(ref val3))..ctor(1f, 0.12f, 0.08f, 1f);
					if (vermelho.HasProperty("_Color"))
					{
						vermelho.color = val3;
					}
					if (vermelho.HasProperty("_EmissionColor"))
					{
						vermelho.EnableKeyword("_EMISSION");
						vermelho.SetColor("_EmissionColor", val3 * 1.5f);
					}
				}
				val2.sharedMaterial = vermelho;
			}
		}
	}

	internal static void Mostrar(Vector3 centro, float raio)
	{
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)go == (Object)null && !Criar())
		{
			return;
		}
		go.transform.position = centro;
		if (Mathf.Abs(raio - raioFeito) < 0.02f)
		{
			return;
		}
		raioFeito = raio;
		cp.m_radius = raio;
		cp.m_nrOfSegments = Mathf.Clamp(Mathf.RoundToInt((float)Math.PI * 2f * raio / 1.2f), 8, 220);
		if (mCriar != null)
		{
			try
			{
				mCriar.Invoke(cp, null);
			}
			catch
			{
			}
		}
		Pintar();
	}

	internal static void Esconder()
	{
		if ((Object)(object)go != (Object)null)
		{
			Object.Destroy((Object)(object)go);
		}
		go = null;
		cp = null;
		raioFeito = -1f;
	}
}
internal static class ArquivoCopia
{
	internal static string NomeSeguro(string nome)
	{
		string text = (nome ?? "").Trim();
		if (text.EndsWith(".blueprint", StringComparison.OrdinalIgnoreCase))
		{
			text = text.Substring(0, text.Length - 10);
		}
		StringBuilder stringBuilder = new StringBuilder();
		string text2 = text;
		foreach (char c in text2)
		{
			if (char.IsControl(c) || Array.IndexOf(Path.GetInvalidFileNameChars(), c) >= 0)
			{
				stringBuilder.Append('_');
			}
			else
			{
				stringBuilder.Append(c);
			}
		}
		text = stringBuilder.ToString().Trim(' ', '.');
		if (text.Length > 80)
		{
			text = text.Substring(0, 80).TrimEnd(' ', '.');
		}
		if (text.Length == 0)
		{
			throw new ArgumentException("Dê um nome para a blueprint.");
		}
		string text3 = text.Split('.')[0].ToUpperInvariant();
		switch (text3)
		{
		default:
			if (text3.Length != 4 || (!text3.StartsWith("COM") && !text3.StartsWith("LPT")) || text3[3] < '1' || text3[3] > '9')
			{
				break;
			}
			goto case "CON";
		case "CON":
		case "PRN":
		case "AUX":
		case "NUL":
			text = "Blueprint " + text;
			break;
		}
		return text;
	}

	internal static string Gravar(string pasta, string nome, IList<string> linhas)
	{
		string text = NomeSeguro(nome);
		Directory.CreateDirectory(pasta);
		string text2 = null;
		for (int i = 0; i < 1000; i++)
		{
			string text3 = text + ((i == 0) ? "" : (" (" + i.ToString(CultureInfo.InvariantCulture) + ")"));
			text2 = Path.Combine(pasta, text3 + ".blueprint");
			FileStream stream;
			try
			{
				stream = new FileStream(text2, FileMode.CreateNew, FileAccess.Write, FileShare.None);
			}
			catch (IOException)
			{
				if (File.Exists(text2))
				{
					continue;
				}
				throw;
			}
			try
			{
				using StreamWriter streamWriter = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
				streamWriter.WriteLine("#Name:" + text3);
				streamWriter.WriteLine("#Creator:Architect");
				streamWriter.WriteLine("#Description:Copia da construcao; sem inventarios ou estado de dano.");
				streamWriter.WriteLine("#Category:Architect");
				streamWriter.WriteLine("#Pieces");
				foreach (string linha in linhas)
				{
					streamWriter.WriteLine(linha);
				}
				return text2;
			}
			catch
			{
				try
				{
					File.Delete(text2);
				}
				catch
				{
				}
				throw;
			}
		}
		throw new IOException("Já existem muitas cópias com esse nome.");
	}
}
internal static class BauDaObra
{
	internal const string Chave = "architect_obra";

	internal const int Largura = 8;

	internal const int Altura = 7;

	internal const string Nome = "Caixote da obra";

	private const string Base = "piece_chest_wood";

	internal const string Prefab = "architect_bau";

	internal const string Comum = "architect_bau_comum";

	private const string Vanilla = "piece_chest_wood";

	private static GameObject modelo;

	private static GameObject suporte;

	private static readonly FieldInfo fNomeados = AccessTools.Field(typeof(ZNetScene), "m_namedPrefabs");

	private static readonly FieldInfo fW = AccessTools.Field(typeof(Inventory), "m_width");

	private static readonly FieldInfo fH = AccessTools.Field(typeof(Inventory), "m_height");

	private static readonly FieldInfo fNome = AccessTools.Field(typeof(Inventory), "m_name");

	private static float proximoAjuste;

	internal static Piece PecaComum()
	{
		GameObject val = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab("piece_chest_wood") : null);
		if (!((Object)(object)val != (Object)null))
		{
			return null;
		}
		return val.GetComponent<Piece>();
	}

	internal static bool Caixote(Container c)
	{
		ZNetView val = (((Object)(object)c != (Object)null) ? Rede(c) : null);
		if ((Object)(object)val == (Object)null || val.GetZDO() == null)
		{
			return false;
		}
		if (Utils.GetPrefabName(((Component)val).gameObject) == "architect_bau")
		{
			return true;
		}
		if (val.GetZDO().GetBool("architect_obra", false))
		{
			return !val.GetZDO().GetBool("architect_bau_comum", false);
		}
		return false;
	}

	internal static GameObject Modelo()
	{
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Expected O, but got Unknown
		if ((Object)(object)modelo == (Object)null)
		{
			GameObject val = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab("piece_chest_wood") : null);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			suporte = new GameObject("Architect_Modelos");
			suporte.SetActive(false);
			Object.DontDestroyOnLoad((Object)(object)suporte);
			modelo = Object.Instantiate<GameObject>(val, suporte.transform, false);
			((Object)modelo).name = "architect_bau";
			Container componentInChildren = modelo.GetComponentInChildren<Container>();
			if ((Object)(object)componentInChildren != (Object)null)
			{
				componentInChildren.m_width = 8;
				componentInChildren.m_height = 7;
				componentInChildren.m_name = "Caixote da obra";
			}
			Piece component = modelo.GetComponent<Piece>();
			if ((Object)(object)component != (Object)null)
			{
				component.m_name = "Caixote da obra";
				component.m_description = "Caixote do Architect: 56 espaços, respeitando as pilhas normais do jogo.";
			}
		}
		Registrar();
		return modelo;
	}

	internal static void Registrar()
	{
		ZNetScene instance = ZNetScene.instance;
		if ((Object)(object)instance == (Object)null || (Object)(object)modelo == (Object)null)
		{
			return;
		}
		IDictionary dictionary = ((fNomeados != null) ? (fNomeados.GetValue(instance) as IDictionary) : null);
		int stableHashCode = StringExtensionMethods.GetStableHashCode("architect_bau");
		if (dictionary == null || !dictionary.Contains(stableHashCode) || !((Object)/*isinst with value type is only supported in some contexts*/ == (Object)(object)modelo))
		{
			if (!instance.m_prefabs.Contains(modelo))
			{
				instance.m_prefabs.Add(modelo);
			}
			if (dictionary != null)
			{
				dictionary[stableHashCode] = modelo;
			}
		}
	}

	internal static void Esquecer()
	{
		modelo = null;
		suporte = null;
	}

	internal static ZNetView Rede(Container c)
	{
		if (!((Object)(object)c.m_rootObjectOverride != (Object)null))
		{
			return ((Component)c).GetComponent<ZNetView>();
		}
		return ((Component)c.m_rootObjectOverride).GetComponent<ZNetView>();
	}

	internal static bool Eh(Container c)
	{
		if ((Object)(object)c == (Object)null)
		{
			return false;
		}
		ZNetView val = Rede(c);
		if ((Object)(object)val == (Object)null || !val.IsValid())
		{
			return false;
		}
		if (!(Utils.GetPrefabName(((Component)val).gameObject) == "architect_bau"))
		{
			return val.GetZDO().GetBool("architect_obra", false);
		}
		return true;
	}

	internal static void Compactar(Container c)
	{
		ZNetView val = (((Object)(object)c != (Object)null) ? Rede(c) : null);
		Inventory val2 = (((Object)(object)c != (Object)null) ? c.GetInventory() : null);
		if ((Object)(object)val == (Object)null || !val.IsValid() || !val.IsOwner() || val2 == null || c.IsInUse())
		{
			return;
		}
		bool flag = false;
		foreach (ItemData item in new List<ItemData>(val2.GetAllItems()))
		{
			int num = Mathf.Max(1, item.m_shared.m_maxStackSize);
			while (item.m_stack > num && val2.GetEmptySlots() > 0)
			{
				ItemData val3 = item.Clone();
				int num2 = (val3.m_stack = Mathf.Min(num, item.m_stack - num));
				if (!val2.AddItem(val3))
				{
					break;
				}
				item.m_stack -= num2;
				flag = true;
			}
		}
		if (flag)
		{
			PilhaPegarTudo.Mudou(val2);
		}
		if (TemPilhaLegada(c) && (Object)(object)Player.m_localPlayer != (Object)null)
		{
			MigrarExcesso(c);
		}
	}

	private static void MigrarExcesso(Container origem)
	{
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_0174: Unknown result type (might be due to invalid IL or missing references)
		//IL_0179: Unknown result type (might be due to invalid IL or missing references)
		//IL_022c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0234: Unknown result type (might be due to invalid IL or missing references)
		//IL_0246: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
		Player localPlayer = Player.m_localPlayer;
		Piece componentInParent = ((Component)origem).GetComponentInParent<Piece>();
		if ((Object)(object)componentInParent == (Object)null || componentInParent.GetCreator() != localPlayer.GetPlayerID())
		{
			return;
		}
		List<Container> list = new List<Container>();
		List<Piece> list2 = new List<Piece>();
		Piece.GetAllPiecesInRadius(((Component)origem).transform.position, 12f, list2);
		foreach (Piece item in list2)
		{
			Container val = (((Object)(object)item != (Object)null) ? ((Component)item).GetComponentInChildren<Container>() : null);
			if ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)origem && Eh(val) && item.GetCreator() == localPlayer.GetPlayerID() && !val.IsInUse() && Rede(val).IsOwner())
			{
				list.Add(val);
			}
		}
		Inventory inventory = origem.GetInventory();
		int num = 0;
		foreach (ItemData item2 in new List<ItemData>(inventory.GetAllItems()))
		{
			int num2 = Mathf.Max(1, item2.m_shared.m_maxStackSize);
			while (item2.m_stack > num2)
			{
				Container val2 = null;
				foreach (Container item3 in list)
				{
					if (item3.GetInventory().GetEmptySlots() > 0)
					{
						val2 = item3;
						break;
					}
				}
				if ((Object)(object)val2 == (Object)null)
				{
					if (num >= 6)
					{
						return;
					}
					Vector3 val3 = Vector3.zero;
					bool flag = false;
					for (float num3 = 2f; num3 <= 12f; num3 += 1.5f)
					{
						if (flag)
						{
							break;
						}
						for (int i = 0; i < 24; i++)
						{
							if (flag)
							{
								break;
							}
							float num4 = (float)i * (float)Math.PI / 12f;
							Vector3 ponto = ((Component)origem).transform.position + new Vector3(Mathf.Cos(num4) * num3, 0f, Mathf.Sin(num4) * num3);
							if (PostoDaObra.Bom(PecaComum(), ponto, ((Component)origem).transform.rotation, null, out var nivel))
							{
								val3 = nivel;
								flag = true;
							}
						}
					}
					if (!flag)
					{
						return;
					}
					localPlayer.PlacePiece(PecaComum(), val3, ((Component)origem).transform.rotation, false, false);
					list2.Clear();
					Piece.GetAllPiecesInRadius(val3, 0.2f, list2);
					foreach (Piece item4 in list2)
					{
						if ((Object)(object)item4 != (Object)null && Utils.GetPrefabName(((Component)item4).gameObject) == "piece_chest_wood" && item4.GetCreator() == localPlayer.GetPlayerID() && ((Component)item4).GetComponentInChildren<Container>().GetInventory().NrOfItems() == 0)
						{
							val2 = ((Component)item4).GetComponentInChildren<Container>();
							break;
						}
					}
					if ((Object)(object)val2 == (Object)null)
					{
						return;
					}
					Marcar(val2);
					list.Add(val2);
					num++;
					Plugin.Log.LogInfo((object)"recipiente de migracao legado criado; sem alterar quantidade de recursos");
				}
				ItemData val4 = item2.Clone();
				int num5 = (val4.m_stack = Mathf.Min(num2, item2.m_stack - num2));
				if (!val2.GetInventory().AddItem(val4))
				{
					return;
				}
				item2.m_stack -= num5;
				PilhaPegarTudo.Mudou(inventory);
				PilhaPegarTudo.Mudou(val2.GetInventory());
			}
		}
	}

	internal static bool TemPilhaLegada(Container c)
	{
		if ((Object)(object)c == (Object)null || c.GetInventory() == null)
		{
			return false;
		}
		foreach (ItemData allItem in c.GetInventory().GetAllItems())
		{
			if (allItem.m_stack > Mathf.Max(1, allItem.m_shared.m_maxStackSize))
			{
				return true;
			}
		}
		return false;
	}

	internal static void Marcar(Container c)
	{
		ZNetView val = (((Object)(object)c != (Object)null) ? Rede(c) : null);
		if (!((Object)(object)val == (Object)null) && val.IsValid())
		{
			val.ClaimOwnership();
			bool flag = Utils.GetPrefabName(((Component)val).gameObject) != "architect_bau" && !val.GetZDO().GetBool("architect_obra", false);
			val.GetZDO().Set("architect_obra", true);
			if (flag)
			{
				val.GetZDO().Set("architect_bau_comum", true);
			}
			if (Caixote(c))
			{
				Ampliar(c);
			}
			PostoDaObra.Sincronizar(c);
		}
	}

	internal static void AjustarPerto(Vector3 p)
	{
		//IL_0023: 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_012f: Unknown result type (might be due to invalid IL or missing references)
		if (Time.time < proximoAjuste)
		{
			return;
		}
		proximoAjuste = Time.time + 2f;
		List<Piece> list = new List<Piece>();
		Piece.GetAllPiecesInRadius(p, 40f, list);
		List<Piece> list2 = new List<Piece>();
		foreach (Piece item in list)
		{
			if (PostoDaObra.MesaTemporaria(item))
			{
				list2.Add(item);
				PostoDaObra.Assentar(item);
			}
		}
		long num = (((Object)(object)Player.m_localPlayer != (Object)null) ? Player.m_localPlayer.GetPlayerID() : 0);
		if (list2.Count > 0 && num != 0)
		{
			foreach (Piece item2 in list)
			{
				if ((Object)(object)item2 == (Object)null || item2.GetCreator() != num || (Object)(object)((Component)item2).GetComponentInParent<Rigidbody>() != (Object)null)
				{
					continue;
				}
				Container componentInChildren = ((Component)item2).GetComponentInChildren<Container>();
				if ((Object)(object)componentInChildren == (Object)null || Eh(componentInChildren) || componentInChildren.IsInUse())
				{
					continue;
				}
				foreach (Piece item3 in list2)
				{
					if (Vector3.Distance(((Component)item3).transform.position, ((Component)item2).transform.position) <= 8f)
					{
						Marcar(componentInChildren);
						break;
					}
				}
			}
		}
		foreach (Piece item4 in list)
		{
			if ((Object)(object)item4 != (Object)null && Marcado(item4))
			{
				MobiliaDaObra.MesaEm(item4);
			}
			Container val = (((Object)(object)item4 != (Object)null) ? ((Component)item4).GetComponentInChildren<Container>() : null);
			if (!((Object)(object)val == (Object)null) && Eh(val) && !val.IsInUse())
			{
				PostoDaObra.Sincronizar(val);
				MobiliaDaObra.BauEm(val);
				MobiliaDaObra.BauNormal(val);
				Inventory inventory = val.GetInventory();
				if (Caixote(val) && inventory != null && (inventory.GetWidth() != 8 || inventory.GetHeight() != 7 || val.m_name != "Caixote da obra"))
				{
					Ampliar(val);
				}
				Compactar(val);
			}
		}
	}

	private static void Ampliar(Container c)
	{
		c.m_width = 8;
		c.m_height = 7;
		c.m_name = "Caixote da obra";
		Inventory inventory = c.GetInventory();
		if (inventory != null)
		{
			if (fW != null)
			{
				fW.SetValue(inventory, 8);
			}
			if (fH != null)
			{
				fH.SetValue(inventory, 7);
			}
			if (fNome != null)
			{
				fNome.SetValue(inventory, "Caixote da obra");
			}
			Arrumar(c);
		}
	}

	internal static void Arrumar(Container c)
	{
		//IL_0076: 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)
		Inventory val = (((Object)(object)c != (Object)null) ? c.GetInventory() : null);
		if (val == null)
		{
			return;
		}
		bool flag = false;
		foreach (ItemData allItem in val.GetAllItems())
		{
			if (allItem.m_gridPos.x < val.GetWidth() && allItem.m_gridPos.y < val.GetHeight())
			{
				continue;
			}
			bool flag2 = false;
			for (int i = 0; i < val.GetHeight(); i++)
			{
				if (flag2)
				{
					break;
				}
				for (int j = 0; j < val.GetWidth(); j++)
				{
					if (flag2)
					{
						break;
					}
					if (val.GetItemAt(j, i) == null)
					{
						allItem.m_gridPos = new Vector2i(j, i);
						flag2 = true;
					}
				}
			}
			if (flag2)
			{
				flag = true;
			}
		}
		ZNetView val2 = Rede(c);
		if (flag && (Object)(object)val2 != (Object)null && val2.IsValid() && val2.IsOwner())
		{
			PilhaPegarTudo.Mudou(val);
		}
	}

	internal static Container Perto(Vector3 p, float raio)
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: 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)
		if ((Object)(object)Player.m_localPlayer == (Object)null)
		{
			return null;
		}
		List<Piece> list = new List<Piece>();
		Piece.GetAllPiecesInRadius(p, raio, list);
		Container result = null;
		float num = float.MaxValue;
		foreach (Piece item in list)
		{
			Container val = (((Object)(object)item != (Object)null) ? ((Component)item).GetComponentInChildren<Container>() : null);
			if (Eh(val) && item.GetCreator() == Player.m_localPlayer.GetPlayerID() && PrivateArea.CheckAccess(((Component)item).transform.position, 0f, false, false))
			{
				Vector3 val2 = ((Component)item).transform.position - p;
				float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude;
				if (sqrMagnitude < num)
				{
					num = sqrMagnitude;
					result = val;
				}
			}
		}
		return result;
	}

	private static bool Marcado(Piece p)
	{
		ZNetView val = (((Object)(object)p != (Object)null) ? ((Component)p).GetComponent<ZNetView>() : null);
		if ((Object)(object)val != (Object)null && val.IsValid())
		{
			return val.GetZDO().GetBool("architect_obra", false);
		}
		return false;
	}

	internal static bool DaObra(CraftingStation st)
	{
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)st == (Object)null)
		{
			return false;
		}
		Piece componentInParent = ((Component)st).GetComponentInParent<Piece>();
		if (Marcado(componentInParent))
		{
			return true;
		}
		if ((Object)(object)componentInParent != (Object)null && st.m_name == "$piece_workbench" && (Object)(object)Player.m_localPlayer != (Object)null && componentInParent.GetCreator() == Player.m_localPlayer.GetPlayerID())
		{
			return (Object)(object)Perto(((Component)st).transform.position, 6f) != (Object)null;
		}
		return false;
	}

	private static bool PodePagar(Player pl, Piece pc, out string falta)
	{
		falta = null;
		Requirement[] resources = pc.m_resources;
		foreach (Requirement val in resources)
		{
			if ((Object)(object)val.m_resItem != (Object)null && val.m_amount > 0 && ((Humanoid)pl).GetInventory().CountItems(val.m_resItem.m_itemData.m_shared.m_name, -1, true) < val.m_amount)
			{
				falta = Obra.Nome(val.m_resItem.m_itemData.m_shared.m_name) + " " + val.m_amount;
				return false;
			}
		}
		return true;
	}

	private static void Pagar(Player pl, Piece pc)
	{
		Requirement[] resources = pc.m_resources;
		foreach (Requirement val in resources)
		{
			if ((Object)(object)val.m_resItem != (Object)null && val.m_amount > 0)
			{
				((Humanoid)pl).GetInventory().RemoveItem(val.m_resItem.m_itemData.m_shared.m_name, val.m_amount, -1, true);
			}
		}
	}

	internal static IEnumerator Colocar(Vector3 ancora, float giro, Bounds total, List<Piece> estacoes)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		return PostoDaObra.Colocar(ancora, giro, total, estacoes);
	}

	internal static void Explodir(Vector3 ancora, float raio)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		List<Piece> list = new List<Piece>();
		Piece.GetAllPiecesInRadius(ancora, raio, list);
		foreach (Piece item in list)
		{
			if (!((Object)(object)item == (Object)null) && Marcado(item))
			{
				WearNTear component = ((Component)item).GetComponent<WearNTear>();
				if ((Object)(object)component != (Object)null)
				{
					component.Remove(false);
				}
			}
		}
	}
}
[HarmonyPatch(typeof(Container), "Awake")]
internal static class BauDaObraAwake
{
	private static void Prefix(Container __instance)
	{
		if (BauDaObra.Caixote(__instance))
		{
			__instance.m_width = 8;
			__instance.m_height = 7;
			__instance.m_name = "Caixote da obra";
		}
	}

	private static void Postfix(Container __instance)
	{
		if (BauDaObra.Eh(__instance))
		{
			BauDaObra.Arrumar(__instance);
			PostoDaObra.Sincronizar(__instance);
		}
	}
}
[HarmonyPatch(typeof(Container), "Interact")]
internal static class BloquearPilhaLegada
{
	private static bool Prefix(Container __instance, ref bool __result)
	{
		if (!BauDaObra.Eh(__instance))
		{
			return true;
		}
		BauDaObra.Compactar(__instance);
		if (!BauDaObra.TemPilhaLegada(__instance))
		{
			return true;
		}
		Plugin.Avisar("bau legado: quantidade preservada; falta espaco para converter pilhas vanilla");
		__result = false;
		return false;
	}
}
[HarmonyPatch(typeof(Player), "PlacePiece")]
internal static class VincularBauNovo
{
	private static void Postfix(Player __instance, Piece piece, Vector3 pos)
	{
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_00aa: 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)
		if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer || (Object)(object)piece == (Object)null || ((Object)((Component)piece).gameObject).name != "piece_chest_wood")
		{
			return;
		}
		bool flag = false;
		List<Piece> list = new List<Piece>();
		Piece.GetAllPiecesInRadius(pos, 6f, list);
		foreach (Piece item in list)
		{
			if ((Object)(object)item != (Object)null && BauDaObra.DaObra(((Component)item).GetComponentInChildren<CraftingStation>()))
			{
				flag = true;
			}
		}
		if (!flag)
		{
			return;
		}
		foreach (Piece item2 in list)
		{
			if (!((Object)(object)item2 == (Object)null) && !(Vector3.Distance(((Component)item2).transform.position, pos) > 0.1f) && item2.GetCreator() == __instance.GetPlayerID())
			{
				Container componentInChildren = ((Component)item2).GetComponentInChildren<Container>();
				if ((Object)(object)componentInChildren != (Object)null && Utils.GetPrefabName(((Component)item2).gameObject) == "piece_chest_wood")
				{
					BauDaObra.Marcar(componentInChildren);
				}
			}
		}
	}
}
internal static class CatalogoBlueprints
{
	internal static string Pasta(string config, string jogo)
	{
		string path = Path.Combine(config, "marcopogo.PlanBuild.cfg");
		if (File.Exists(path))
		{
			bool flag = false;
			string[] array = File.ReadAllLines(path);
			foreach (string text in array)
			{
				string text2 = text.Trim();
				if (text2.StartsWith("#") || text2.StartsWith(";") || text2.Length == 0)
				{
					continue;
				}
				if (text2.StartsWith("["))
				{
					flag = text2.Equals("[Directories]", StringComparison.OrdinalIgnoreCase);
					continue;
				}
				int num = text2.IndexOf('=');
				if (flag && num >= 0 && text2.Substring(0, num).Trim().Equals("Save directory", StringComparison.OrdinalIgnoreCase))
				{
					string text3 = Environment.ExpandEnvironmentVariables(text2.Substring(num + 1).Trim().Trim('"'));
					if (text3.Length > 0)
					{
						return Path.GetFullPath(Path.IsPathRooted(text3) ? text3 : Path.Combine(jogo, text3));
					}
				}
			}
		}
		return Path.Combine(config, "PlanBuild", "blueprints");
	}

	internal static string Chave(string arquivo)
	{
		string text = Path.GetFileNameWithoutExtension(arquivo).Normalize(NormalizationForm.FormD);
		StringBuilder stringBuilder = new StringBuilder();
		string text2 = text;
		foreach (char c in text2)
		{
			if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
			{
				stringBuilder.Append(char.ToLowerInvariant(c));
			}
		}
		text = stringBuilder.ToString().Replace('_', ' ').Trim();
		return text switch
		{
			"11 prado" => "prado", 
			"12 floresta negra" => "floresta negra", 
			"13 pantano" => "pantano", 
			"14 planicies" => "planicies", 
			"15 montanha" => "montanha", 
			_ => text, 
		};
	}

	internal static List<string> Listar(IEnumerable<string> pastas, Action<string> aviso)
	{
		List<string> list = new List<string>();
		HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
		HashSet<string> locais = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
		foreach (string pasta in pastas)
		{
			if (!Directory.Exists(pasta))
			{
				continue;
			}
			List<string> list2 = new List<string>();
			Varrer(pasta, list2, locais, aviso);
			list2.Sort(StringComparer.OrdinalIgnoreCase);
			foreach (string item in list2)
			{
				if (hashSet.Add(Chave(item)))
				{
					list.Add(item);
				}
			}
		}
		list.Sort(StringComparer.OrdinalIgnoreCase);
		return list;
	}

	private static void Varrer(string pasta, List<string> arquivos, HashSet<string> locais, Action<string> aviso)
	{
		try
		{
			string fullPath = Path.GetFullPath(pasta);
			if (!locais.Add(fullPath))
			{
				return;
			}
			string[] files = Directory.GetFiles(fullPath);
			foreach (string text in files)
			{
				if (Path.GetExtension(text).Equals(".blueprint", StringComparison.OrdinalIgnoreCase))
				{
					arquivos.Add(text);
				}
			}
			string[] directories = Directory.GetDirectories(fullPath);
			foreach (string text2 in directories)
			{
				if ((File.GetAttributes(text2) & FileAttributes.ReparsePoint) == 0)
				{
					Varrer(text2, arquivos, locais, aviso);
				}
			}
		}
		catch (Exception ex)
		{
			aviso?.Invoke("pasta " + pasta + ": " + ex.Message);
		}
	}

	internal static int Localizar(List<string> arquivos, string anterior)
	{
		int num = arquivos.FindIndex((string f) => f.Equals(anterior, StringComparison.OrdinalIgnoreCase));
		if (num < 0)
		{
			return arquivos.FindIndex((string f) => Chave(f) == Chave(anterior));
		}
		return num;
	}
}
internal static class Compat
{
	internal const string RecipeGate = "raaotium.recipegate";
}
[HarmonyPatch(typeof(Player), "HaveRequirements", new Type[]
{
	typeof(Piece),
	typeof(RequirementMode)
})]
internal static class FerramentaConhecida
{
	[HarmonyPriority(0)]
	[HarmonyAfter(new string[] { "raaotium.recipegate" })]
	private static void Postfix(Piece piece, ref bool __result)
	{
		if ((Object)(object)piece != (Object)null && Ferramentas.EhFerramenta(piece.m_name))
		{
			__result = Ferramentas.Visivel(piece.m_name);
		}
	}
}
[HarmonyPatch(typeof(PieceTable), "IsPieceAvailable")]
internal static class FerramentaDisponivel
{
	[HarmonyPriority(0)]
	[HarmonyAfter(new string[] { "raaotium.recipegate" })]
	private static void Postfix(Piece piece, ref bool __result)
	{
		if ((Object)(object)piece != (Object)null && Ferramentas.EhFerramenta(piece.m_name))
		{
			__result = Ferramentas.Visivel(piece.m_name);
		}
	}
}
[HarmonyPatch(typeof(PieceTable), "UpdateAvailable")]
internal static class FerramentaNoMenu
{
	private static readonly FieldInfo fDisp = AccessTools.Field(typeof(PieceTable), "m_availablePieces");

	private static readonly FieldInfo fPorAba = AccessTools.Field(typeof(PieceTable), "m_availablePiecesByCategory");

	[HarmonyAfter(new string[] { "raaotium.recipegate" })]
	[HarmonyPriority(0)]
	private static void Postfix(PieceTable __instance)
	{
		List<Piece> list = Ferramentas.PecasNaTabela(__instance, visiveis: true);
		List<Piece> list2 = Ferramentas.PecasNaTabela(__instance, visiveis: false);
		HashSet<Piece> hashSet = ((fDisp != null) ? (fDisp.GetValue(__instance) as HashSet<Piece>) : null);
		List<List<Piece>> list3 = ((fPorAba != null) ? (fPorAba.GetValue(__instance) as List<List<Piece>>) : null);
		if (hashSet != null)
		{
			foreach (Piece item in list2)
			{
				hashSet.Remove(item);
			}
		}
		if (list3 != null)
		{
			foreach (List<Piece> item2 in list3)
			{
				if (item2 == null)
				{
					continue;
				}
				foreach (Piece item3 in list2)
				{
					item2.Remove(item3);
				}
			}
		}
		if (list.Count == 0)
		{
			return;
		}
		if (hashSet != null)
		{
			foreach (Piece item4 in list)
			{
				hashSet.Add(item4);
			}
		}
		if (list3 == null)
		{
			return;
		}
		foreach (List<Piece> item5 in list3)
		{
			if (item5 == null)
			{
				continue;
			}
			int num = -1;
			for (int i = 0; i < item5.Count; i++)
			{
				if ((Object)(object)item5[i] != (Object)null && item5[i].m_repairPiece)
				{
					num = i + 1;
					break;
				}
			}
			if (num < 0)
			{
				continue;
			}
			foreach (Piece item6 in list)
			{
				int num2 = item5.IndexOf(item6);
				if (num2 >= 0)
				{
					num = num2 + 1;
					continue;
				}
				item5.Insert(Mathf.Min(num, item5.Count), item6);
				num++;
			}
		}
	}
}
internal static class Contador
{
	private static GUIStyle texto;

	private static GUIStyle sombra;

	private static Font FonteDoJogo()
	{
		Font[] array = Resources.FindObjectsOfTypeAll<Font>();
		foreach (Font val in array)
		{
			if ((Object)(object)val != (Object)null && ((Object)val).name.StartsWith("AveriaSerifLibre-Bold"))
			{
				return val;
			}
		}
		Font[] array2 = Resources.FindObjectsOfTypeAll<Font>();
		foreach (Font val2 in array2)
		{
			if ((Object)(object)val2 != (Object)null && ((Object)val2).name.StartsWith("AveriaSerif"))
			{
				return val2;
			}
		}
		return null;
	}

	internal static void OnGUI()
	{
		//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_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Expected O, but got Unknown
		//IL_015b: Unknown result type (might be due to invalid IL or missing references)
		//IL_016c: Unknown result type (might be due to invalid IL or missing references)
		//IL_017a: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b5: Expected O, but got Unknown
		//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
		int num = Obra.Contagem_();
		bool flag = num >= 0;
		if (!flag)
		{
			num = Desmontar.Contagem_();
		}
		if (num < 0)
		{
			return;
		}
		Matrix4x4 matrix = GUI.matrix;
		Plugin.Ampliar();
		if (texto == null)
		{
			texto = new GUIStyle(GUI.skin.label);
			texto.fontSize = 56;
			texto.alignment = (TextAnchor)4;
			Font val = FonteDoJogo();
			if ((Object)(object)val != (Object)null)
			{
				texto.font = val;
			}
			else
			{
				texto.fontStyle = (FontStyle)1;
			}
			texto.normal.textColor = new Color(1f, 0.84f, 0.26f);
			sombra = new GUIStyle(texto);
			sombra.normal.textColor = new Color(0f, 0f, 0f, 0.75f);
		}
		string text = ((num > 0) ? ((flag ? "Montando em " : "Desmontando em ") + num) : "Saia da área");
		float num2 = Plugin.LarguraTela();
		float num3 = Plugin.AlturaTela();
		Rect val2 = default(Rect);
		((Rect)(ref val2))..ctor(0f, num3 * 0.5f - 40f, num2, 80f);
		GUI.Label(new Rect(((Rect)(ref val2)).x + 3f, ((Rect)(ref val2)).y + 3f, ((Rect)(ref val2)).width, ((Rect)(ref val2)).height), text, sombra);
		GUI.Label(val2, text, texto);
		GUI.matrix = matrix;
	}
}
internal static class CopiarBlueprint
{
	internal static bool Ativo;

	internal static bool Nomeando;

	private static Vector3 centro;

	private static float raio = 8f;

	private static float proxima;

	private static float abriu;

	private static string nome = "";

	private static string erro = "";

	private static List<Piece> pecas = new List<Piece>();

	internal static void Abrir()
	{
		//IL_006f: 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)
		if (Obra.Ocupada || Desmontar.Ativo)
		{
			Plugin.Avisar("termine a obra ou o desmonte antes de copiar");
			return;
		}
		if ((Object)(object)Player.m_localPlayer == (Object)null)
		{
			Plugin.Avisar("entre em um mundo para copiar uma construcao");
			return;
		}
		Seletor.Fechar();
		PainelObra.Fechar();
		Ativo = true;
		Nomeando = false;
		erro = "";
		pecas.Clear();
		abriu = Time.unscaledTime;
		centro = ((Component)Player.m_localPlayer).transform.position;
		Obra.OcultarParaCopiar();
		Plugin.Dizer("COPIAR: mire o centro, ajuste o raio com a roda e clique para conferir e salvar");
	}

	internal static void Fechar()
	{
		Ativo = (Nomeando = false);
		pecas.Clear();
		Anel.Esconder();
		ZCursor.Hide();
	}

	private static bool Pode(Piece p)
	{
		//IL_0084: 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_008e: 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)
		if ((Object)(object)p == (Object)null || !p.IsPlacedByPlayer() || p.GetCreator() != Player.m_localPlayer.GetPlayerID() || (Object)(object)((Component)p).GetComponentInParent<Rigidbody>() != (Object)null)
		{
			return false;
		}
		if ((Object)(object)((Component)p).GetComponent<Ship>() != (Object)null || (Object)(object)((Component)p).GetComponent<Vagon>() != (Object)null)
		{
			return false;
		}
		ZNetView component = ((Component)p).GetComponent<ZNetView>();
		if ((Object)(object)component == (Object)null || !component.IsValid() || component.GetZDO().GetBool("architect_obra", false))
		{
			return false;
		}
		Vector3 val = ((Component)p).transform.position - centro;
		val.y = 0f;
		return ((Vector3)(ref val)).magnitude <= raio;
	}

	private static void Levantar()
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		pecas.Clear();
		List<Piece> list = new List<Piece>();
		Piece.GetAllPiecesInRadius(centro, 500f, list);
		foreach (Piece item in list)
		{
			if (Pode(item))
			{
				pecas.Add(item);
			}
		}
	}

	internal static void Update()
	{
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: 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_00a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_0147: Unknown result type (might be due to invalid IL or missing references)
		if (!Ativo)
		{
			return;
		}
		if ((Object)(object)Player.m_localPlayer == (Object)null || !Ferramentas.CopiarNaMao())
		{
			Fechar();
		}
		else
		{
			if (Nomeando || !Plugin.UiLivre())
			{
				return;
			}
			if (Input.GetKeyDown(Plugin.TeclaVoltar.Value) || Input.GetKeyDown((KeyCode)27))
			{
				Fechar();
				return;
			}
			raio = Mathf.Clamp(raio + Plugin.Roda() * (Input.GetKey((KeyCode)304) ? 2f : 0.5f), 1f, 40f);
			if ((Object)(object)GameCamera.instance != (Object)null)
			{
				Transform transform = ((Component)GameCamera.instance).transform;
				RaycastHit val = default(RaycastHit);
				if (Physics.Raycast(transform.position, transform.forward, ref val, 120f, LayerMask.GetMask(new string[4] { "terrain", "piece", "Default", "static_solid" })))
				{
					centro = ((RaycastHit)(ref val)).point;
				}
			}
			Anel.Mostrar(centro, raio);
			if (Time.unscaledTime >= proxima)
			{
				Levantar();
				proxima = Time.unscaledTime + 0.25f;
			}
			if (Time.unscaledTime - abriu > 0.25f && (Input.GetMouseButtonDown(0) || Input.GetKeyDown(Plugin.TeclaConfirmar.Value)))
			{
				Levantar();
				if (pecas.Count == 0)
				{
					Plugin.Avisar("nenhuma peça sua dentro da área");
					return;
				}
				if (pecas.Count > 20000)
				{
					Plugin.Avisar("a área tem peças demais; reduza o raio");
					return;
				}
				Nomeando = true;
				nome = "Minha construcao " + DateTime.Now.ToString("yyyy-MM-dd HHmm");
				erro = "";
			}
		}
	}

	private static string F(float f)
	{
		return f.ToString("R", CultureInfo.InvariantCulture);
	}

	private static void Salvar()
	{
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d1: 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_00df: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e4: 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_00e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_010a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_0125: Unknown result type (might be due to invalid IL or missing references)
		//IL_012a: Unknown result type (might be due to invalid IL or missing references)
		//IL_012e: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0200: Unknown result type (might be due to invalid IL or missing references)
		//IL_0153: Unknown result type (might be due to invalid IL or missing references)
		//IL_0158: Unknown result type (might be due to invalid IL or missing references)
		//IL_0170: Unknown result type (might be due to invalid IL or missing references)
		//IL_024a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0253: Unknown result type (might be due to invalid IL or missing references)
		//IL_0258: Unknown result type (might be due to invalid IL or missing references)
		//IL_025a: Unknown result type (might be due to invalid IL or missing references)
		//IL_025f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0264: Unknown result type (might be due to invalid IL or missing references)
		//IL_0266: Unknown result type (might be due to invalid IL or missing references)
		//IL_026f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0274: Unknown result type (might be due to invalid IL or missing references)
		//IL_0279: Unknown result type (might be due to invalid IL or missing references)
		//IL_027b: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			if ((Object)(object)Player.m_localPlayer == (Object)null)
			{
				throw new InvalidOperationException("Architect indisponível.");
			}
			if (!PrivateArea.CheckAccess(centro, raio, false, false))
			{
				throw new InvalidOperationException("A área tem proteção de outro jogador.");
			}
			Levantar();
			if (pecas.Count == 0 || pecas.Count > 20000)
			{
				throw new InvalidOperationException("A seleção mudou; escolha a área novamente.");
			}
			float num = float.PositiveInfinity;
			float num2 = float.PositiveInfinity;
			foreach (Piece peca in pecas)
			{
				string prefabName = Utils.GetPrefabName(((Component)peca).gameObject);
				GameObject prefab = ZNetScene.instance.GetPrefab(prefabName);
				if ((Object)(object)prefab == (Object)null || (Object)(object)prefab.GetComponent<Piece>() == (Object)null)
				{
					throw new InvalidOperationException("Peça sem modelo: " + prefabName);
				}
				Vector3 lossyScale = ((Component)peca).transform.lossyScale;
				Vector3 lossyScale2 = prefab.transform.lossyScale;
				if (Vector3.Distance(lossyScale, lossyScale2) > 0.001f)
				{
					throw new InvalidOperationException("Há peça com escala alterada: " + prefabName);
				}
				float num3 = num;
				Bounds val = Planta.Transformar(Planta.CaixaLocal(prefab), ((Component)peca).transform.position, ((Component)peca).transform.rotation);
				num = Mathf.Min(num3, ((Bounds)(ref val)).min.y);
				if (prefabName.IndexOf("floor", StringComparison.OrdinalIgnoreCase) >= 0 && Vector3.Dot(((Component)peca).transform.up, Vector3.up) > 0.999f)
				{
					num2 = Mathf.Min(num2, ((Component)peca).transform.position.y);
				}
			}
			Vector3 val2 = default(Vector3);
			((Vector3)(ref val2))..ctor(centro.x, float.IsInfinity(num2) ? num : num2, centro.z);
			float num4 = Mathf.Round(((Component)Player.m_localPlayer).transform.eulerAngles.y / 22.5f) * 22.5f;
			Quaternion val3 = Quaternion.Inverse(Quaternion.Euler(0f, num4, 0f));
			List<string> list = new List<string>();
			pecas.Sort(delegate(Piece a, Piece b)
			{
				//IL_0006: 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)
				float y = ((Component)a).transform.position.y;
				return y.CompareTo(((Component)b).transform.position.y);
			});
			foreach (Piece peca2 in pecas)
			{
				Vector3 v = val3 * (((Component)peca2).transform.position - val2);
				Quaternion val4 = val3 * ((Component)peca2).transform.rotation;
				if (!Gate.Finita(v))
				{
					throw new InvalidOperationException("Posição inválida.");
				}
				list.Add(Utils.GetPrefabName(((Component)peca2).gameObject) + ";Building;" + F(v.x) + ";" + F(v.y) + ";" + F(v.z) + ";" + F(val4.x) + ";" + F(val4.y) + ";" + F(val4.z) + ";" + F(val4.w) + ";;1;1;1");
			}
			string text = ArquivoCopia.Gravar(Planta.Pasta, nome, list);
			int count = pecas.Count;
			Fechar();
			Obra.AtualizarLista();
			Plugin.Avisar("salva: " + Path.GetFileName(text) + " — " + count + " peças");
			Plugin.Log.LogInfo((object)("Blueprint copiada: " + text));
		}
		catch (Exception ex)
		{
			erro = ex.GetBaseException().Message;
			Plugin.Log.LogWarning((object)("copiar blueprint: " + erro));
		}
	}

	internal static void OnGUI()
	{
		//IL_0008: 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_00d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_010a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0158: Unknown result type (might be due to invalid IL or missing references)
		//IL_0194: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0204: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_024e: Unknown result type (might be due to invalid IL or missing references)
		//IL_027e: Unknown result type (might be due to invalid IL or missing references)
		if (!Ativo)
		{
			return;
		}
		Matrix4x4 matrix = GUI.matrix;
		Plugin.Ampliar();
		float num = Plugin.LarguraTela();
		float num2 = Plugin.AlturaTela();
		if (!Nomeando)
		{
			GUI.Box(new Rect(num * 0.5f - 230f, num2 - 112f, 460f, 76f), "Copiar construção — " + pecas.Count + " peças\nRoda: raio " + raio.ToString("0.0") + " m  |  Clique: conferir e salvar\nBackspace: cancelar");
		}
		else
		{
			float num3 = Mathf.Min(540f, num - 40f);
			Rect val = default(Rect);
			((Rect)(ref val))..ctor((num - num3) * 0.5f, (num2 - 260f) * 0.5f, num3, 260f);
			GUI.Box(val, "");
			GUI.Label(new Rect(((Rect)(ref val)).x + 18f, ((Rect)(ref val)).y + 12f, num3 - 36f, 30f), "Salvar blueprint — " + pecas.Count + " peças suas");
			nome = GUI.TextField(new Rect(((Rect)(ref val)).x + 18f, ((Rect)(ref val)).y + 52f, num3 - 36f, 34f), nome, 90);
			GUI.Label(new Rect(((Rect)(ref val)).x + 18f, ((Rect)(ref val)).y + 94f, num3 - 36f, 54f), "Sem conteúdo dos baús, vida ou combustível.\nUm nome existente gera uma cópia numerada.");
			GUI.Label(new Rect(((Rect)(ref val)).x + 18f, ((Rect)(ref val)).y + 148f, num3 - 36f, 40f), erro);
			if (GUI.Button(new Rect(((Rect)(ref val)).x + 18f, ((Rect)(ref val)).y + 206f, (num3 - 46f) / 2f, 36f), "Salvar blueprint"))
			{
				Salvar();
			}
			if (GUI.Button(new Rect(((Rect)(ref val)).x + num3 / 2f + 5f, ((Rect)(ref val)).y + 206f, (num3 - 46f) / 2f, 36f), "Voltar à seleção"))
			{
				Nomeando = false;
				erro = "";
				abriu = Time.unscaledTime;
				ZCursor.Hide();
			}
		}
		GUI.matrix = matrix;
	}
}
internal static class Desmontar
{
	private const float Folga = 10f;

	internal static bool Ativo;

	private static bool trabalhando;

	private static bool abortar;

	private static Vector3 centro;

	private static float raio = 8f;

	private static float proxima;

	private static bool travado;

	private static readonly List<Piece> pecas = new List<Piece>();

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

	private static string resumo = "";

	private static string avisoChao = "";

	private static List<Container> vazios = new List<Container>();

	private static string volta = "";

	private static int bausPrecisa;

	private static float raioAlvo = 8f;

	internal static bool Segurando;

	private static bool contando;

	private static int segundos;

	private static string PrefabBau => "piece_chest_wood";

	private static string ResumoVolta()
	{
		if (volta.Length <= 0)
		{
			return "Nada para recuperar.";
		}
		return "Volta: " + volta;
	}

	internal static IEnumerator Abrir()
	{
		if (Obra.Fase == Fase.Mirando)
		{
			Obra.Limpar();
		}
		Obra.Fase = Fase.Abrindo;
		Rede.Pedir();
		float ate = Time.time + 5f;
		while (!Rede.Respondeu && Time.time < ate)
		{
			yield return null;
		}
		Obra.Fase = Fase.Desligado;
		if (!Rede.Respondeu || !Rede.Ativo || !Rede.Desmontar)
		{
			Plugin.Avisar("Você não pode fazer isso");
			yield break;
		}
		Ativo = true;
		travado = false;
		Plugin.Dizer("DESMONTAR: mire o centro, roda muda o raio, clique marca a área");
	}

	internal static void DesligadoPeloServidor()
	{
		if (trabalhando)
		{
			abortar = true;
		}
		else if (Ativo)
		{
			Fechar();
		}
	}

	internal static void FecharSeParado()
	{
		if (!trabalhando && !contando && Ativo)
		{
			Fechar();
		}
	}

	internal static void Fechar()
	{
		Ativo = false;
		travado = false;
		Anel.Esconder();
		Obra.LimparMarcas();
		pecas.Clear();
	}

	internal static bool NoCirculo(Vector3 p)
	{
		float num = p.x - centro.x;
		float num2 = p.z - centro.z;
		return num * num + num2 * num2 <= (raio + 2f) * (raio + 2f);
	}

	internal static void Update()
	{
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_009a: 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)
		//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_0140: Unknown result type (might be due to invalid IL or missing references)
		//IL_0146: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_018e: 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)
		if (!Ativo || trabalhando)
		{
			return;
		}
		if ((Object)(object)Player.m_localPlayer == (Object)null)
		{
			Fechar();
			return;
		}
		raio = Mathf.MoveTowards(raio, raioAlvo, Time.deltaTime * Mathf.Max(20f, Mathf.Abs(raioAlvo - raio) * 12f));
		Anel.Mostrar(centro, raio);
		if (contando || !Plugin.UiLivre())
		{
			return;
		}
		bool flag = Input.GetKey((KeyCode)304) || Input.GetKey((KeyCode)303);
		if (Input.GetKeyDown(Plugin.TeclaVoltar.Value))
		{
			travado = false;
		}
		float num = Plugin.Roda();
		float num2 = (flag ? 2f : 0.5f);
		if (num > 0f || Input.GetKeyDown(Plugin.TeclaSubir.Value))
		{
			raioAlvo = Mathf.Min(40f, raioAlvo + num2);
		}
		if (num < 0f || Input.GetKeyDown(Plugin.TeclaDescer.Value))
		{
			raioAlvo = Mathf.Max(1f, raioAlvo - num2);
		}
		if (!travado && (Object)(object)GameCamera.instance != (Object)null)
		{
			Transform transform = ((Component)GameCamera.instance).transform;
			RaycastHit val = default(RaycastHit);
			if (Physics.Raycast(transform.position, transform.forward, ref val, 120f, LayerMask.GetMask(new string[4] { "terrain", "piece", "Default", "static_solid" })))
			{
				centro = ((RaycastHit)(ref val)).point;
			}
		}
		if (Time.time >= proxima)
		{
			proxima = Time.time + 0.25f;
			Analisar();
		}
		if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(Plugin.TeclaConfirmar.Value))
		{
			raio = raioAlvo;
			Analisar();
			if (problemas.Count > 0)
			{
				Plugin.Avisar("não dá: " + problemas[0]);
				return;
			}
			travado = true;
			Perguntar();
		}
	}

	private static void Perguntar()
	{
		//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ef: Expected O, but got Unknown
		//IL_0113: Unknown result type (might be due to invalid IL or missing references)
		//IL_011d: Expected O, but got Unknown
		//IL_0102: Unknown result type (might be due to invalid IL or missing references)
		//IL_010c: Expected O, but got Unknown
		string text = string.Format(CultureInfo.InvariantCulture, "Desmontar {0} peças num raio de {1:0.#} m?\n\n{2}\n\nO material vai para {3}{4}.", pecas.Count, raio, ResumoVolta(), (vazios.Count > 0) ? (vazios.Count + " baú(s) da obra aqui perto" + ((bausPrecisa > 0) ? (" e " + bausPrecisa + " baú(s) da obra novo(s)") : "")) : (bausPrecisa + " baú(s) da obra novo(s)"), (avisoChao.Length > 0) ? (" (" + avisoChao + ")") : "");
		UnifiedPopup.Push((PopupBase)new YesNoPopup("Architect — Desmontar", text, (PopupButtonCallback)delegate
		{
			UnifiedPopup.Pop();
			((MonoBehaviour)Plugin.Instancia).StartCoroutine(Contagem());
		}, (PopupButtonCallback)delegate
		{
			UnifiedPopup.Pop();
			travado = false;
		}, false, true));
	}

	private static bool Removivel(Piece p)
	{
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)p == (Object)null || !p.IsPlacedByPlayer() || !p.m_canBeRemoved)
		{
			return false;
		}
		if ((Object)(object)((Component)p).GetComponent<Ship>() != (Object)null || (Object)(object)((Component)p).GetComponent<Vagon>() != (Object)null)
		{
			return false;
		}
		if ((Object)(object)Player.m_localPlayer == (Object)null || p.GetCreator() != Player.m_localPlayer.GetPlayerID())
		{
			return false;
		}
		Vector3 val = ((Component)p).transform.position - centro;
		val.y = 0f;
		return ((Vector3)(ref val)).magnitude <= raio;
	}

	private static void Somar(List<Piece> l, Dictionary<string, int> mat, Dictionary<string, GameObject> prefabs, List<ItemData> itens)
	{
		foreach (Piece item in l)
		{
			Requirement[] resources = item.m_resources;
			foreach (Requirement val in resources)
			{
				if (!((Object)(object)val.m_resItem == (Object)null) && val.m_recover && val.m_amount > 0)
				{
					string name = val.m_resItem.m_itemData.m_shared.m_name;
					mat.TryGetValue(name, out var value);
					mat[name] = value + val.m_amount;
					prefabs[name] = ((Component)val.m_resItem).gameObject;
				}
			}
			Container componentInChildren = ((Component)item).GetComponentInChildren<Container>();
			if (!((Object)(object)componentInChildren != (Object)null) || componentInChildren.GetInventory() == null || itens == null)
			{
				continue;
			}
			foreach (ItemData allItem in componentInChildren.GetInventory().GetAllItems())
			{
				itens.Add(allItem);
			}
		}
	}

	private static int Pilhas(Dictionary<string, int> mat, Dictionary<string, GameObject> prefabs, int itens)
	{
		int num = itens;
		foreach (KeyValuePair<string, int> item in mat)
		{
			ItemDrop component = prefabs[item.Key].GetComponent<ItemDrop>();
			int num2 = (((Object)(object)component != (Object)null) ? Mathf.Max(1, component.m_itemData.m_shared.m_maxStackSize) : 50);
			num += (item.Value + num2 - 1) / num2;
		}
		return num;
	}

	private static Piece PecaBau()
	{
		Piece val = BauDaObra.PecaComum();
		GameObject val2 = (((Object)(object)val != (Object)null) ? ((Component)val).gameObject : null);
		if (!((Object)(object)val2 != (Object)null))
		{
			return null;
		}
		return val2.GetComponent<Piece>();
	}

	private static int MadeiraPorBau(Piece bau, out string nomeMadeira)
	{
		nomeMadeira = "$item_wood";
		Requirement[] resources = bau.m_resources;
		foreach (Requirement val in resources)
		{
			if ((Object)(object)val.m_resItem != (Object)null && val.m_amount > 0)
			{
				nomeMadeira = val.m_resItem.m_itemData.m_shared.m_name;
				return val.m_amount;
			}
		}
		return 0;
	}

	private static void Analisar()
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		problemas.Clear();
		pecas.Clear();
		Player localPlayer = Player.m_localPlayer;
		List<Piece> list = new List<Piece>();
		Piece.GetAllPiecesInRadius(centro, raio + 2f, list);
		foreach (Piece item in list)
		{
			if (Removivel(item))
			{
				pecas.Add(item);
			}
		}
		if (!Rede.Liberado() || !Rede.Desmontar)
		{
			problemas.Add("servidor não liberou");
			Rede.Pedir();
		}
		if (Vector3.Distance(((Component)localPlayer).transform.position, centro) > 60f)
		{
			problemas.Add("chegue mais perto (até 60 m)");
		}
		if (!PrivateArea.CheckAccess(centro, raio, false, false))
		{
			problemas.Add("a área tem proteção (ward) que não é sua");
		}
		if (pecas.Count == 0)
		{
			problemas.Add("nenhuma construção de jogador no círculo");
		}
		Piece val = PecaBau();
		if ((Object)(object)val == (Object)null)
		{
			problemas.Add("o jogo não tem " + PrefabBau);
			return;
		}
		Dictionary<string, int> dictionary = new Dictionary<string, int>();
		Dictionary<string, GameObject> prefabs = new Dictionary<string, GameObject>();
		List<ItemData> list2 = new List<ItemData>();
		Somar(pecas, dictionary, prefabs, list2);
		string nomeMadeira;
		int num = MadeiraPorBau(val, out nomeMadeira);
		int vagas = 10;
		dictionary.TryGetValue(nomeMadeira, out var value);
		vazios = VaziosPerto(localPlayer);
		bausPrecisa = Baus(dictionary, prefabs, list2.Count - Vagas(vazios), nomeMadeira, num, vagas);
		avisoChao = "";
		int num2 = (value + ((Humanoid)localPlayer).GetInventory().CountItems(nomeMadeira, -1, true)) / Mathf.Max(1, num);
		if (num2 < bausPrecisa)
		{
			avisoChao = ((num2 == 0) ? "sem madeira para baú: tudo fica no chão" : ("madeira só para " + num2 + " baú(s): o resto fica no chão"));
			bausPrecisa = num2;
		}
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.Append(string.Format(CultureInfo.InvariantCulture, "raio {0:0} m — {1} peças, {2} itens de baús → {3} baú(s) novos\n", raio, pecas.Count, list2.Count, bausPrecisa));
		List<string> list3 = new List<string>();
		foreach (KeyValuePair<string, int> item2 in dictionary)
		{
			list3.Add(Obra.Nome(item2.Key) + " " + item2.Value);
		}
		list3.Sort(StringComparer.CurrentCulture);
		volta = string.Join(", ", list3.ToArray());
		stringBuilder.Append("volta: " + volta);
		if (avisoChao.Length > 0)
		{
			stringBuilder.Append("\n<color=orange>" + avisoChao + "</color>");
		}
		resumo = stringBuilder.ToString();
	}

	private static List<Container> VaziosPerto(Player pl)
	{
		//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_00ff: 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_0075: 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_007f: Unknown result type (might be due to invalid IL or missing references)
		List<Container> list = new List<Container>();
		if ((Object)(object)pl == (Object)null)
		{
			return list;
		}
		List<Piece> list2 = new List<Piece>();
		Piece.GetAllPiecesInRadius(centro, raio + 12f, list2);
		long playerID = pl.GetPlayerID();
		foreach (Piece item in list2)
		{
			if ((Object)(object)item == (Object)null || !item.IsPlacedByPlayer() || item.GetCreator() != playerID)
			{
				continue;
			}
			Vector3 val = ((Component)item).transform.position - centro;
			val.y = 0f;
			if (!(((Vector3)(ref val)).magnitude <= raio + 0.5f))
			{
				Container componentInChildren = ((Component)item).GetComponentInChildren<Container>();
				if (!((Object)(object)componentInChildren == (Object)null) && componentInChildren.GetInventory() != null && !componentInChildren.IsInUse() && BauDaObra.Eh(componentInChildren))
				{
					list.Add(componentInChildren);
				}
			}
		}
		Vector3 eup = ((Component)pl).transform.position;
		list.Sort(delegate(Container a, Container b)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: 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_0027: 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_0032: 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)
			Vector3 val2 = ((Component)a).transform.position - eup;
			float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude;
			Vector3 val3 = ((Component)b).transform.position - eup;
			return sqrMagnitude.CompareTo(((Vector3)(ref val3)).sqrMagnitude);
		});
		return list;
	}

	private static int Vagas(List<Container> l)
	{
		int num = 0;
		foreach (Container item in l)
		{
			num += item.GetInventory().GetEmptySlots();
		}
		return num;
	}

	private static int Baus(Dictionary<string, int> mat, Dictionary<string, GameObject> prefabs, int itens, string nomeMadeira, int custo, int vagas)
	{
		mat.TryGetValue(nomeMadeira, out var value);
		for (int i = 0; i < 100; i++)
		{
			Dictionary<string, int> dictionary = new Dictionary<string, int>(mat);
			if (value > 0)
			{
				dictionary[nomeMadeira] = Mathf.Max(0, value - i * custo);
			}
			if (dictionary.ContainsKey(nomeMadeira) && dictionary[nomeMadeira] == 0)
			{
				dictionary.Remove(nomeMadeira);
			}
			if (i * vagas >= Pilhas(dictionary, prefabs, itens))
			{
				return i;
			}
		}
		return 100;
	}

	internal static bool BomLugar(Vector3 p, out float y)
	{
		//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)
		Piece modelo = PecaBau();
		Vector3 nivel;
		bool result = PostoDaObra.Bom(modelo, p, Quaternion.identity, null, out nivel);
		y = nivel.y;
		return result;
	}

	private static List<Vector3> Lugares(int n, Vector3 jogador)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//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)
		//IL_0032: 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_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0106: Unknown result type (might be due to invalid IL or missing references)
		//IL_010b: 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_0162: Unknown result type (might be due to invalid IL or missing references)
		//IL_0164: Unknown result type (might be due to invalid IL or missing references)
		//IL_0167: Unknown result type (might be due to invalid IL or missing references)
		List<Vector3> list = new List<Vector3>();
		if (n <= 0)
		{
			return list;
		}
		Vector3 val = jogador - centro;
		val.y = 0f;
		if (((Vector3)(ref val)).sqrMagnitude < 0.01f)
		{
			val = Vector3.forward;
		}
		float num = Mathf.Atan2(val.z, val.x);
		Vector3 val2 = default(Vector3);
		for (float num2 = 0f; num2 <= raio + 10f; num2 += 1.6f)
		{
			if (list.Count >= n)
			{
				break;
			}
			float num3 = ((num2 < 0.5f) ? ((float)Math.PI) : (2.2f / num2));
			int num4 = Mathf.CeilToInt((float)Math.PI / num3);
			for (int i = 0; i <= num4; i++)
			{
				if (list.Count >= n)
				{
					break;
				}
				for (int j = ((i == 0) ? 1 : (-1)); j <= 1; j += 2)
				{
					if (list.Count >= n)
					{
						break;
					}
					float num5 = num + (float)(j * i) * num3;
					((Vector3)(ref val2))..ctor(centro.x + Mathf.Cos(num5) * num2, 0f, centro.z + Mathf.Sin(num5) * num2);
					Quaternion giro = PostoDaObra.Olhar(centro, val2);
					if (!PostoDaObra.Bom(PecaBau(), val2, giro, null, out var nivel))
					{
						continue;
					}
					bool flag = false;
					foreach (Vector3 item in list)
					{
						Vector2 val3 = new Vector2(item.x - val2.x, item.z - val2.z);
						if (((Vector2)(ref val3)).magnitude < 2.2f)
						{
							flag = true;
							break;
						}
					}
					if (!flag)
					{
						val2 = nivel;
						list.Add(val2);
					}
				}
			}
		}
		return list;
	}

	private static IEnumerator Executar()
	{
		trabalhando = true;
		abortar = false;
		try
		{
			Player pl = Player.m_localPlayer;
			Rede.Pedir();
			float ate = Time.time + 5f;
			while (!Rede.Respondeu && Time.time < ate)
			{
				yield return null;
			}
			Analisar();
			if (problemas.Count > 0)
			{
				if (problemas[0].StartsWith("servidor"))
				{
					Plugin.Avisar("Você não pode fazer isso");
				}
				else
				{
					Plugin.Avisar("cancelado: " + problemas[0]);
				}
				yield break;
			}
			foreach (Piece peca in pecas)
			{
				Container componentInChildren = ((Component)peca).GetComponentInChildren<Container>();
				if ((Object)(object)componentInChildren != (Object)null && componentInChildren.IsInUse())
				{
					Plugin.Avisar("tem baú aberto dentro do círculo — feche e confirme de novo");
					yield break;
				}
			}
			if (abortar || !Rede.Liberado() || !Rede.Desmontar)
			{
				Plugin.Avisar("Você não pode fazer isso");
				yield break;
			}
			List<Piece> conferir = new List<Piece>(pecas);
			string pedido = Gate.PedirDesmonte(centro, raio, conferir);
			float limite = Time.time + 8f;
			while (!Gate.RespondeuDesmonte(pedido) && Time.time < limite)
			{
				yield return null;
			}
			if (!Gate.ConsumirDesmonte(pedido, centro, raio, conferir, out var motivoGate))
			{
				Plugin.Dizer("desmonte recusado: " + motivoGate);
				Plugin.Avisar("Você não pode fazer isso");
				yield break;
			}
			Piece bau = PecaBau();
			string nomeMadeira;
			int custo = MadeiraPorBau(bau, out nomeMadeira);
			List<Piece> alvo = new List<Piece>(pecas);
			Obra.LimparMarcas();
			List<ItemData> itens = new List<ItemData>();
			foreach (Piece item in alvo)
			{
				Container componentInChildren2 = ((Component)item).GetComponentInChildren<Container>();
				if (!((Object)(object)componentInChildren2 == (Object)null) && componentInChildren2.GetInventory() != null && componentInChildren2.GetInventory().NrOfItems() != 0)
				{
					ZNetView componentInParent = ((Component)componentInChildren2).GetComponentInParent<ZNetView>();
					if ((Object)(object)componentInParent != (Object)null)
					{
						componentInParent.ClaimOwnership();
					}
				}
			}
			yield return null;
			foreach (Piece item2 in alvo)
			{
				Container componentInChildren3 = ((Component)item2).GetComponentInChildren<Container>();
				if ((Object)(object)componentInChildren3 == (Object)null || componentInChildren3.GetInventory() == null || componentInChildren3.GetInventory().NrOfItems() == 0)
				{
					continue;
				}
				ZNetView componentInParent2 = ((Component)componentInChildren3).GetComponentInParent<ZNetView>();
				if ((Object)(object)componentInParent2 == (Object)null || !componentInParent2.IsOwner())
				{
					Plugin.Avisar("outro jogador está com um baú do círculo — tente de novo");
					yield break;
				}
				foreach (ItemData allItem in componentInChildren3.GetInventory().GetAllItems())
				{
					itens.Add(allItem.Clone());
				}
				componentInChildren3.GetInventory().RemoveAll();
			}
			Dictionary<string, int> mat = new Dictionary<string, int>();
			Dictionary<string, GameObject> prefabs = new Dictionary<string, GameObject>();
			Plugin.Dizer("desmontando " + alvo.Count + " peças...");
			alvo.Sort((Piece a, Piece b) => (((Object)(object)b != (Object)null) ? ((Component)b).transform.position.y : 0f).CompareTo(((Object)(object)a != (Object)null) ? ((Component)a).transform.position.y : 0f));
			Segurando = true;
			int n = 0;
			List<Piece> feitas = new List<Piece>();
			foreach (Piece p in alvo)
			{
				if (abortar)
				{
					break;
				}
				if ((Object)(object)p == (Object)null)
				{
					continue;
				}
				feitas.Add(p);
				Somar(new List<Piece> { p }, mat, prefabs, null);
				WearNTear w = ((Component)p).GetComponent<WearNTear>();
				if ((Object)(object)w != (Object)null)
				{
					w.Remove(true);
				}
				else
				{
					ZNetView component = ((Component)p).GetComponent<ZNetView>();
					if ((Object)(object)component != (Object)null && component.IsValid())
					{
						component.ClaimOwnership();
						ZNetScene.instance.Destroy(((Component)p).gameObject);
					}
				}
				int num;
				n = (num = n + 1);
				if (num % 20 == 0)
				{
					yield return null;
				}
			}
			yield return (object)new WaitForSeconds(1f);
			if (abortar)
			{
				bausPrecisa = 0;
				Plugin.Dizer("desmonte parado em " + feitas.Count + "/" + alvo.Count + " peças; o que já saiu ficou no chão");
				Plugin.Avisar("Você não pode fazer isso");
			}
			List<Inventory> destinos = new List<Inventory>();
			if (!abortar)
			{
				List<Container> meus = VaziosPerto(pl);
				foreach (Container item3 in meus)
				{
					ZNetView componentInParent3 = ((Component)item3).GetComponentInParent<ZNetView>();
					if ((Object)(object)componentInParent3 != (Object)null && componentInParent3.IsValid())
					{
						componentInParent3.ClaimOwnership();
					}
				}
				yield return null;
				foreach (Container item4 in meus)
				{
					ZNetView componentInParent4 = ((Component)item4).GetComponentInParent<ZNetView>();
					if ((Object)(object)componentInParent4 != (Object)null && componentInParent4.IsValid() && componentInParent4.IsOwner() && !item4.IsInUse() && BauDaObra.Eh(item4))
					{
						destinos.Add(item4.GetInventory());
					}
				}
				int livres = 0;
				foreach (Inventory item5 in destinos)
				{
					livres += item5.GetEmptySlots();
				}
				bausPrecisa = Baus(mat, prefabs, itens.Count - livres, nomeMadeira, custo, 10);
			}
			List<Vector3> lugares = Lugares(bausPrecisa, ((Component)pl).transform.position);
			if (lugares.Count < bausPrecisa)
			{
				Plugin.Avisar("só achei lugar seco para " + lugares.Count + " de " + bausPrecisa + " baú(s); o resto fica no chão");
				bausPrecisa = lugares.Count;
			}
			mat.TryGetValue(nomeMadeira, out var madeira);
			int pagar = bausPrecisa * custo;
			int doMonte = Mathf.Min(madeira, pagar);
			mat[nomeMadeira] = madeira - doMonte;
			if (mat[nomeMadeira] <= 0)
			{
				mat.Remove(nomeMadeira);
			}
			if (pagar > doMonte)
			{
				int num2 = ((Humanoid)pl).GetInventory().CountItems(nomeMadeira, -1, true);
				if (num2 < pagar - doMonte)
				{
					bausPrecisa = (doMonte + num2) / Mathf.Max(1, custo);
				}
				((Humanoid)pl).GetInventory().RemoveItem(nomeMadeira, Mathf.Max(0, Mathf.Min(num2, bausPrecisa * custo - doMonte)), -1, true);
				if (doMonte > bausPrecisa * custo)
				{
					mat[nomeMadeira] = (mat.ContainsKey(nomeMadeira) ? mat[nomeMadeira] : 0) + doMonte - bausPrecisa * custo;
				}
			}
			if (lugares.Count > bausPrecisa)
			{
				lugares.RemoveRange(bausPrecisa, lugares.Count - bausPrecisa);
			}
			foreach (Vector3 item6 in lugares)
			{
				Vector3 val = item6 - centro;
				val.y = 0f;
				Quaternion val2 = Quaternion.LookRotation(((Vector3)(ref val)).normalized);
				float num3 = Mathf.Round(((Quaternion)(ref val2)).eulerAngles.y / 22.5f) * 22.5f;
				pl.PlacePiece(bau, item6, Quaternion.Euler(0f, num3, 0f), false, false);
			}
			yield return (object)new WaitForSeconds(0.5f);
			List<Inventory> novos = new List<Inventory>(destinos);
			int jaExistiam = destinos.Count;
			long eu = pl.GetPlayerID();
			foreach (Vector3 item7 in lugares)
			{
				List<Piece> list = new List<Piece>();
				Piece.GetAllPiecesInRadius(item7, 0.6f, list);
				foreach (Piece item8 in list)
				{
					if (!((Object)(object)item8 == (Object)null) && !(Utils.GetPrefabName(((Component)item8).gameObject) != PrefabBau) && item8.GetCreator() == eu)
					{
						Container componentInChildren4 = ((Component)item8).GetComponentInChildren<Container>();
						if ((Object)(object)componentInChildren4 != (Object)null && componentInChildren4.GetInventory().NrOfItems() == 0 && !novos.Contains(componentInChildren4.GetInventory()))
						{
							BauDaObra.Marcar(componentInChildren4);
							novos.Add(componentInChildren4.GetInventory());
							break;
						}
					}
				}
			}
			List<string> nomes = new List<string>(mat.Keys);
			nomes.Sort((string a, string b) => string.Compare(Obra.Nome(a), Obra.Nome(b), StringComparison.CurrentCulture));
			itens.Sort((ItemData a, ItemData b) => string.Compare(Obra.Nome(a.m_shared.m_name), Obra.Nome(b.m_shared.m_name), StringComparison.CurrentCulture));
			int atual = 0;
			int noChao = 0;
			Vector3 sobra = ((lugares.Count > 0) ? lugares[0] : ((Component)pl).transform.position);
			int novosFeitos = novos.Count - jaExistiam;
			foreach (string item9 in nomes)
			{
				GameObject val3 = prefabs[item9];
				ItemDrop component2 = val3.GetComponent<ItemDrop>();
				int num4 = (((Object)(object)component2 != (Object)null) ? Mathf.Max(1, component2.m_itemData.m_shared.m_maxStackSize) : 50);
				int num5 = mat[item9];
				while (num5 > 0)
				{
					int num6;
					for (num6 = Mathf.Min(num5, num4); atual < novos.Count && !novos[atual].AddItem(val3, num6); atual++)
					{
					}
					if (atual >= novos.Count)
					{
						Obra.Devolver(null, sobra, val3, num6);
						noChao++;
					}
					num5 -= num6;
				}
			}
			foreach (ItemData item10 in itens)
			{
				for (; atual < novos.Count && !novos[atual].AddItem(item10); atual++)
				{
				}
				if (atual >= novos.Count)
				{
					ItemDrop.DropItem(item10, item10.m_stack, sobra + Vector3.up, Quaternion.identity);
					noChao++;
				}
			}
			PostoDaObra.Cancelar(centro);
			Rede.Registrar($"desmontado em ({centro.x:0.0}; {centro.z:0.0}) raio {raio:0}: {feitas.Count} peças, {novos.Count} baús");
			if (novos.Count == 0)
			{
				Plugin.Avisar($"desmontado: {feitas.Count} peças; sem baú, {noChao} pilhas ficaram no chão");
			}
			else
			{
				Plugin.Avisar(string.Format("desmontado: {0} peças, guardado em {1}{2}", feitas.Count, (jaExistiam > 0) ? (jaExistiam + " baú(s) seu(s)" + ((novosFeitos > 0) ? (" e " + novosFeitos + " novo(s)") : "")) : (novosFeitos + " baú(s) novo(s)"), (noChao > 0) ? (" — " + noChao + " pilhas não couberam e ficaram no chão ao lado") : ""));
			}
		}
		finally
		{
			Segurando = false;
			trabalhando = false;
			Fechar();
		}
	}

	private static bool DentroDoCirculo()
	{
		//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_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)
		Player localPlayer = Player.m_localPlayer;
		if ((Object)(object)localPlayer == (Object)null)
		{
			return false;
		}
		Vector3 val = ((Component)localPlayer).transform.position - centro;
		val.y = 0f;
		return ((Vector3)(ref val)).magnitude <= raio + 1f;
	}

	private static IEnumerator Contagem()
	{
		contando = true;
		for (segundos = 10; segundos >= 1; segundos--)
		{
			if (!Ativo)
			{
				contando = false;
				yield break;
			}
			yield return (object)new WaitForSeconds(1f);
		}
		segundos = 0;
		while (DentroDoCirculo())
		{
			if (!Ativo)
			{
				contando = false;
				yield break;
			}
			yield return null;
		}
		contando = false;
		if (Ativo)
		{
			((MonoBehaviour)Plugin.Instancia).StartCoroutine(Executar());
		}
	}

	internal static int Contagem_()
	{
		if (!contando)
		{
			return -1;
		}
		return segundos;
	}

	internal static string Linha()
	{
		if (trabalhando)
		{
			return "desmontando...";
		}
		if (contando)
		{
			return "";
		}
		if (problemas.Count > 0 && pecas.Count > 0)
		{
			return "<color=orange>" + problemas[0] + "</color>";
		}
		if (travado)
		{
			return "";
		}
		return string.Format(CultureInfo.InvariantCulture, "desmontar: raio {0:0.#} m · {1} peças", raio, pecas.Count);
	}

	internal static string Hud()
	{
		StringBuilder stringBuilder = new StringBuilder("<b>Architect — DESMONTAR</b>\n");
		if (trabalhando)
		{
			stringBuilder.Append("desmontando...");
			return stringBuilder.ToString();
		}
		stringBuilder.Append(resumo).Append('\n');
		foreach (string problema in problemas)
		{
			stringBuilder.Append("<color=red>• " + problema + "</color>\n");
		}
		stringBuilder.Append(travado ? "área marcada — confirme na janela\n" : "<color=lime>clique para marcar e confirmar</color>\n");
		stringBuilder.Append("roda: raio (Shift: mais rápido)");
		return stringBuilder.ToString();
	}
}
internal static class Ferramentas
{
	private const string NomeSelecionar = "Architect: Selecionar blueprint";

	private const string NomeBlueprint = "Architect: Montar";

	private const string NomeCopiar = "Architect: Copiar blueprint";

	private const string NomeDesmontar = "Architect: Desmontar";

	private const float Pergunta = 4f;

	private const float Validade = 12f;

	private static GameObject raiz;

	private static GameObject goBlueprint;

	private static GameObject goDesmontar;

	private static GameObject goSelecionar;

	private static GameObject goCopiar;

	private static PieceTable tabelaFeita;

	private static string selAnterior = "";

	private static readonly FieldInfo fKnown = AccessTools.Field(typeof(Player), "m_knownRecipes");

	private static readonly MethodInfo mAtualizar = AccessTools.Method(typeof(Player), "UpdateAvailablePiecesList", (Type[])null, (Type[])null);

	private static bool comFerramenta;

	private static Player jogadorSessao;

	private static float proximaPergunta;

	private static string mostrando = "";

	private static float proximaLimpeza;

	private static readonly string[] sobras = new string[5] { "Architect_Blueprint", "Architect_Montar", "Architect_Desmontar", "Architect_Selecionar_blueprint", "Architect_Copiar_blueprint" };

	private static Sprite Icone(string prefab)
	{
		GameObject val = (((Object)(object)ObjectDB.instance != (Object)null) ? ObjectDB.instance.GetItemPrefab(prefab) : null);
		ItemDrop val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<ItemDrop>() : null);
		if ((Object)(object)val2 != (Object)null && val2.m_itemData.m_shared.m_icons.Length > 0)
		{
			return val2.m_itemData.m_shared.m_icons[0];
		}
		GameObject val3 = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab(prefab) : null);
		Piece val4 = (((Object)(object)val3 != (Object)null) ? val3.GetComponent<Piece>() : null);
		if (!((Object)(object)val4 != (Object)null))
		{
			return null;
		}
		return val4.m_icon;
	}

	private static GameObject Criar(string nome, string descricao, Sprite icone)
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Expected O, but got Unknown
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = new GameObject(nome.Replace(": ", "_").Replace(' ', '_'));
		val.transform.SetParent(raiz.transform, false);
		val.AddComponent<ZNetView>();
		Piece val2 = val.AddComponent<Piece>();
		val2.m_name = nome;
		val2.m_description = descricao;
		val2.m_icon = icone;
		val2.m_category = (PieceCategory)100;
		val2.m_resources = (Requirement[])(object)new Requirement[0];
		val2.m_craftingStation = null;
		val2.m_enabled = true;
		return val;
	}

	private static void Garantir(Player pl)
	{
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Expected O, but got Unknown
		//IL_0368: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)ObjectDB.instance == (Object)null)
		{
			return;
		}
		GameObject itemPrefab = ObjectDB.instance.GetItemPrefab("Hammer");
		ItemDrop val = (((Object)(object)itemPrefab != (Object)null) ? itemPrefab.GetComponent<ItemDrop>() : null);
		PieceTable val2 = (((Object)(object)val != (Object)null) ? val.m_itemData.m_shared.m_buildPieces : null);
		if ((Object)(object)val2 == (Object)null)
		{
			return;
		}
		if ((Object)(object)raiz == (Object)null)
		{
			raiz = new GameObject("Architect_Ferramentas");
			raiz.SetActive(false);
			Object.DontDestroyOnLoad((Object)(object)raiz);
		}
		if ((Object)(object)goBlueprint == (Object)null)
		{
			goCopiar = Criar("Architect: Copiar blueprint", "Mire a area da construcao, selecione as pecas e salve uma blueprint com nome.", IconesFerramentas.Copiar());
			goBlueprint = Criar("Architect: Montar", "Escolhe uma blueprint e põe no lugar: mira, demarca o terreno e constrói com o material do baú.", IconesFerramentas.Montar());
			goSelecionar = Criar("Architect: Selecionar blueprint", "Abre a lista para selecionar ou trocar a blueprint. Depois, use Montar para posicionar.", IconesFerramentas.Selecionar());
			goDesmontar = Criar("Architect: Desmontar", "Desmonta tudo que é seu num círculo e guarda o material em baús feitos com a própria madeira.", IconesFerramentas.Desmontar());
		}
		bool flag = false;
		if (!val2.m_pieces.Contains(goBlueprint) || !val2.m_pieces.Contains(goDesmontar) || !val2.m_pieces.Contains(goSelecionar) || !val2.m_pieces.Contains(goCopiar))
		{
			val2.m_pieces.Remove(goBlueprint);
			val2.m_pieces.Remove(goDesmontar);
			val2.m_pieces.Remove(goSelecionar);
			val2.m_pieces.Remove(goCopiar);
			int index = 0;
			for (int i = 0; i < val2.m_pieces.Count; i++)
			{
				Piece val3 = (((Object)(object)val2.m_pieces[i] != (Object)null) ? val2.m_pieces[i].GetComponent<Piece>() : null);
				if ((Object)(object)val3 != (Object)null && val3.m_repairPiece)
				{
					index = i + 1;
					break;
				}
			}
			val2.m_pieces.Insert(index, goCopiar);
			val2.m_pieces.Insert(index, goDesmontar);
			val2.m_pieces.Insert(index, goBlueprint);
			val2.m_pieces.Insert(index, goSelecionar);
			flag = true;
		}
		HashSet<string> hashSet = ((fKnown != null) ? (fKnown.GetValue(pl) as HashSet<string>) : null);
		if (hashSet != null)
		{
			if (hashSet.Add("Architect: Copiar blueprint"))
			{
				flag = true;
			}
			if (hashSet.Add("Architect: Selecionar blueprint"))
			{
				flag = true;
			}
			if (hashSet.Add("Architect: Montar"))
			{
				flag = true;
			}
			if (hashSet.Add("Architect: Desmontar"))
			{
				flag = true;
			}
		}
		if (!flag && !((Object)(object)val2 != (Object)(object)tabelaFeita))
		{
			return;
		}
		StringBuilder stringBuilder = new StringBuilder("martelo: " + val2.m_pieces.Count + " peças; início da lista:");
		for (int j = 0; j < Mathf.Min(6, val2.m_pieces.Count); j++)
		{
			Piece val4 = (((Object)(object)val2.m_pieces[j] != (Object)null) ? val2.m_pieces[j].GetComponent<Piece>() : null);
			stringBuilder.Append(" [" + j + "] " + (((Object)(object)val4 != (Object)null) ? string.Concat(val4.m_name, "/", val4.m_category, val4.m_enabled ? "" : "(off)") : "null"));
		}
		stringBuilder.Append(" | conhece Montar: " + (hashSet?.Contains("Architect: Montar") ?? false) + ", Desmontar: " + (hashSet?.Contains("Architect: Desmontar") ?? false));
		Plugin.Log.LogInfo((object)stringBuilder.ToString());
		tabelaFeita = val2;
		if (!(mAtualizar != null))
		{
			return;
		}
		try
		{
			mAtualizar.Invoke(pl, null);
		}
		catch
		{
		}
	}

	private static void VoltarAoNormal()
	{
		//IL_002e: 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_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)tabelaFeita == (Object)null || tabelaFeita.m_selectedPiece == null)
		{
			return;
		}
		for (int i = 0; i < tabelaFeita.m_selectedPiece.Length; i++)
		{
			Vector2Int val = tabelaFeita.m_selectedPiece[i];
			if (((Vector2Int)(ref val)).y == 0 && ((Vector2Int)(ref val)).x >= 1 && ((Vector2Int)(ref val)).x <= 4)
			{
				ref Vector2Int reference = ref tabelaFeita.m_selectedPiece[i];
				reference = Vector2Int.zero;
			}
		}
	}

	internal static string Selecionada()
	{
		Player localPlayer = Player.m_localPlayer;
		if ((Object)(object)localPlayer == (Object)null || !((Character)localPlayer).InPlaceMode() || !Plugin.ComMartelo())
		{
			return "";
		}
		Piece selectedPiece = localPlayer.GetSelectedPiece();
		if ((Object)(object)selectedPiece == (Object)null)
		{
			return "";
		}
		if ((selectedPiece.m_name == "Architect: Montar" || selectedPiece.m_name == "Architect: Desmontar" || selectedPiece.m_name == "Architect: Selecionar blueprint" || selectedPiece.m_name == "Architect: Copiar blueprint") && Visivel(selectedPiece.m_name))
		{
			return selectedPiece.m_name;
		}
		return "";
	}

	internal static bool AlgumaSelecionada()
	{
		return Selecionada().Length > 0;
	}

	internal static bool CopiarNaMao()
	{
		return Selecionada() == "Architect: Copiar blueprint";
	}

	internal static bool MontarNaMao()
	{
		string text = Selecionada();
		if (!(text == "Architect: Montar"))
		{
			return text == "Architect: Selecionar blueprint";
		}
		return true;
	}

	internal static void UsarMontar()
	{
		Player localPlayer = Player.m_localPlayer;
		if ((Object)(object)localPlayer != (Object)null && (Object)(object)goBlueprint != (Object)null)
		{
			localPlayer.SetSelectedPiece(goBlueprint.GetComponent<Piece>());
		}
	}

	internal static void Remover()
	{
		if ((Object)(object)tabelaFeita != (Object)null)
		{
			tabelaFeita.m_pieces.Remove(goBlueprint);
			tabelaFeita.m_pieces.Remove(goDesmontar);
			tabelaFeita.m_pieces.Remove(goSelecionar);
			tabelaFeita.m_pieces.Remove(goCopiar);
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null && mAtualizar != null)
			{
				try
				{
					mAtualizar.Invoke(localPlayer, null);
				}
				catch
				{
				}
			}
		}
		if ((Object)(object)raiz != (Object)null)
		{
			Object.Destroy((Object)(object)raiz);
		}
		raiz = null;
		goBlueprint = null;
		goDesmontar = null;
		goSelecionar = null;
		goCopiar = null;
		tabelaFeita = null;
		selAnterior = "";
	}

	internal static bool EhFerramenta(string nome)
	{
		switch (nome)
		{
		default:
			return nome == "Architect: Copiar blueprint";
		case "Architect: Montar":
		case "Architect: Desmontar":
		case "Architect: Selecionar blueprint":
			return true;
		}
	}

	private static bool Mostrar(GameObject go)
	{
		if ((Object)(object)go == (Object)null || !Rede.Respondeu || !Rede.Ativo || Time.time - Rede.Quando > 12f)
		{
			return false;
		}
		if ((Object)(object)go == (Object)(object)goSelecionar || (Object)(object)go == (Object)(object)goBlueprint)
		{
			return Rede.Montar;
		}
		if ((Object)(object)go == (Object)(object)goDesmontar)
		{
			return Rede.Desmontar;
		}
		return (Object)(object)go == (Object)(object)goCopiar;
	}

	internal static bool Visivel(string nome)
	{
		return nome switch
		{
			"Architect: Selecionar blueprint" => Mostrar(goSelecionar), 
			"Architect: Montar" => Mostrar(goBlueprint), 
			"Architect: Desmontar" => Mostrar(goDesmontar), 
			"Architect: Copiar blueprint" => Mostrar(goCopiar), 
			_ => false, 
		};
	}

	internal static List<Piece> PecasNaTabela(PieceTable t, bool visiveis)
	{
		List<Piece> list = new List<Piece>();
		if ((Object)(object)t == (Object)null)
		{
			return list;
		}
		foreach (GameObject piece in t.m_pieces)
		{
			if (!((Object)(object)piece == (Object)null) && (!((Object)(object)piece != (Object)(object)goSelecionar) || !((Object)(object)piece != (Object)(object)goBlueprint) || !((Object)(object)piece != (Object)(object)goDesmontar) || !((Object)(object)piece != (Object)(object)goCopiar)) && Mostrar(piece) == visiveis)
			{
				Piece component = piece.GetComponent<Piece>();
				if ((Object)(object)component != (Object)null)
				{
					list.Add(component);
				}
			}
		}
		return list;
	}

	private static void SeguirServidor(Player pl)
	{
		if (Time.time >= proximaPergunta)
		{
			proximaPergunta = Time.time + 4f;
			Rede.Ping();
		}
		string text = (Mostrar(goSelecionar) ? "S" : "") + (Mostrar(goBlueprint) ? "M" : "") + (Mostrar(goDesmontar) ? "D" : "") + (Mostrar(goCopiar) ? "C" : "");
		if (!(text == mostrando))
		{
			mostrando = text;
			Piece selectedPiece = pl.GetSelectedPiece();
			if ((Object)(object)selectedPiece != (Object)null && EhFerramenta(selectedPiece.m_name) && !Visivel(selectedPiece.m_name))
			{
				VoltarAoNormal();
			}
			if (mAtualizar != null)
			{
				mAtualizar.Invoke(pl, null);
			}
		}
	}

	private static void Limpar()
	{
		//IL_0107: Unknown result type (might be due to invalid IL or missing references)
		if (Time.time < proximaLimpeza || ZDOMan.instance == null || (Object)(object)ZNetScene.instance == (Object)null)
		{
			return;
		}
		proximaLimpeza = Time.time + 15f;
		string[] array = sobras;
		foreach (string text in array)
		{
			List<ZDO> list = new List<ZDO>();
			int num = 0;
			for (int j = 0; j < 1000; j++)
			{
				if (ZDOMan.instance.GetAllZDOsWithPrefabIterative(text, list, ref num))
				{
					break;
				}
			}
			foreach (ZDO item in list)
			{
				if (item == null)
				{
					continue;
				}
				ZNetView val = ZNetScene.instance.FindInstance(item);
				if ((Object)(object)val != (Object)null)
				{
					if (val.IsValid())
					{
						val.ClaimOwnership();
					}
					ZNetScene.instance.Destroy(((Component)val).gameObject);
				}
				else
				{
					item.SetOwner(ZDOMan.GetSessionID());
					ZDOMan.instance.DestroyZDO(item);
				}
				Plugin.Log.LogInfo((object)("removida sobra " + text + " em " + item.GetPosition()));
			}
		}
	}

	internal static void Update()
	{
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		Player localPlayer = Player.m_localPlayer;
		if ((Object)(object)localPlayer == (Object)null)
		{
			selAnterior = "";
			jogadorSessao = null;
			return;
		}
		Garantir(localPlayer);
		SeguirServidor(localPlayer);
		if ((Object)(object)jogadorSessao != (Object)(object)localPlayer)
		{
			jogadorSessao = localPlayer;
			Obra.Limpar();
			((MonoBehaviour)Plugin.Instancia).StartCoroutine(Obra.Retomar());
			if (Selecionada().Length > 0)
			{
				VoltarAoNormal();
			}
			selAnterior = Selecionada();
			comFerramenta = false;
			return;
		}
		BauDaObra.Modelo();
		BauDaObra.AjustarPerto(((Component)localPlayer).transform.position);
		Limpar();
		string text = Selecionada();
		bool flag = text == "Architect: Montar" || text == "Architect: Selecionar blueprint";
		if (!flag && Seletor.Aberto)
		{
			Seletor.Fechar();
		}
		if (text.Length > 0)
		{
			comFerramenta = true;
		}
		else if (comFerramenta && !Plugin.ComMartelo())
		{
			comFerramenta = false;
			VoltarAoNormal();
		}
		if (text == "Architect: Selecionar blueprint" && Obra.Fase == Fase.Fixado)
		{
			selAnterior = text;
			Obra.Reescolher();
		}
		else if (text == "Architect: Copiar blueprint" && !CopiarBlueprint.Ativo && Plugin.UiLivre() && Input.GetMouseButtonDown(0))
		{
			CopiarBlueprint.Abrir();
		}
		else if (!(text == selAnterior))
		{
			selAnterior = text;
			if (!flag && text != "Architect: Copiar blueprint" && Obra.Fase == Fase.Mirando)
			{
				Obra.Limpar();
				((MonoBehaviour)Plugin.Instancia).StartCoroutine(Obra.Retomar());
			}
			if (text == "Architect: Selecionar blueprint" && (Obra.Fase == Fase.Fixado || Obra.Fase == Fase.Mirando))
			{
				Obra.Reescolher();
			}
			if (text != "Architect: Desmontar" && Desmontar.Ativo)
			{
				Desmontar.FecharSeParado();
			}
			if (text == "Architect: Copiar blueprint")
			{
				CopiarBlueprint.Abrir();
			}
			else if (flag && Obra.Fase == Fase.Desligado)
			{
				((MonoBehaviour)Plugin.Instancia).StartCoroutine(Obra.Abrir());
			}
			else if (text == "Architect: Desmontar" && !Desmontar.Ativo && Obra.Fase != Fase.Construindo)
			{
				((MonoBehaviour)Plugin.Instancia).StartCoroutine(Desmontar.Abrir());
			}
		}
	}
}
internal static class Gate
{
	private class Pedido
	{
		internal string id;

		internal string digest;

		internal string respostaDigest;

		internal string erro;

		internal bool recebeu;

		internal bool permitiu;

		internal float respondeuEm;
	}

	internal const int MaxPecas = 20000;

	private const string ReqObra = "Architect_ValidarObra_v2";

	private const string RespObra = "Architect_ObraValidada_v2";

	private const string ReqDesmonte = "Architect_ValidarDesmonte_v1";

	private const string RespDesmonte = "Architect_DesmonteValidado_v1";

	private static ZRoutedRpc rede;

	private static MethodInfo travarPeca;

	private static MethodInfo ligado;

	private static FieldInfo pronto;

	private static Assembly assembly;

	private static readonly Pedido obra = new Pedido();

	private static readonly Pedido desmonte = new Pedido();

	internal static bool Finita(Vector3 v)
	{
		if (!float.IsNaN(v.x) && !float.IsNaN(v.y) && !float.IsNaN(v.z) && !float.IsInfinity(v.x) && !float.IsInfinity(v.y))
		{
			return !float.IsInfinity(v.z);
		}
		return false;
	}

	private static bool Preparar(out string motivo)
	{
		motivo = "RecipeGate indisponivel ou ainda carregando";
		try
		{
			if (!Chainloader.PluginInfos.TryGetValue("raaotium.recipegate", out var value) || (Object)(object)value.Instance == (Object)null)
			{
				return false;
			}
			Assembly assembly = ((object)value.Instance).GetType().Assembly;
			if (Gate.assembly != assembly)
			{
				Gate.assembly = assembly;
				Type type = assembly.GetType("RecipeGate.Trava", throwOnError: true);
				Type type2 = assembly.GetType("RecipeGate.RecipeGatePlugin", throwOnError: true);
				Type type3 = assembly.GetType("RecipeGate.Mapa", throwOnError: true);
				travarPeca = AccessTools.Method(type, "TrancadaPeca", new Type[1] { typeof(Piece) }, (Type[])null);
				ligado = AccessTools.Method(type2, "Ligado", (Type[])null, (Type[])null);
				pronto = AccessTools.Field(type3, "Pronto");
			}
			if (travarPeca == null || ligado == null || pronto == null)
			{
				return false;
			}
			if (!(bool)ligado.Invoke(null, null))
			{
				motivo = "RecipeGate precisa estar ativo para autorizar a obra";
				return false;
			}
			if (!(bool)pronto.GetValue(null))
			{
				return false;
			}
			motivo = null;
			return true;
		}
		catch (Exception ex)
		{
			motivo = "falha ao consultar RecipeGate: " + ex.GetBaseException().Message;
			return false;
		}
	}

	internal static bool PermitirPeca(Piece p, out string motivo)
	{
		if (!Preparar(out motivo))
		{
			return false;
		}
		try
		{
			if ((Object)(object)p == (Object)null || !p.m_enabled)
			{
				motivo = "peca ausente ou desativada";
				return false;
			}
			if ((bool)travarPeca.Invoke(null, new object[1] { p }))
			{
				motivo = "RecipeGate bloqueia " + ((Object)((Component)p).gameObject).name;
				return false;
			}
			if (p.m_resources == null)
			{
				motivo = "receita de materiais ausente";
				return false;
			}
			Requirement[] resources = p.m_resources;
			foreach (Requirement val in resources)
			{
				if (val.m_amount < 0)
				{
					motivo = "custo de material invalido";
					return false;
				}
				if (val.m_amount > 0 && (Object)(object)val.m_resItem == (Object)null)
				{
					motivo = "material desconhecido";
					return false;
				}
			}
			motivo = null;
			return true;
		}
		catch (Exception ex)
		{
			motivo = "RecipeGate nao confirmou permissao: " + ex.GetBaseException().Message;
			return false;
		}
	}

	internal static void Registrar()
	{
		if (ZRoutedRpc.instance != null && rede != ZRoutedRpc.instance)
		{
			Desregistrar();
			rede = ZRoutedRpc.instance;
			rede.Register<ZPackage>("Architect_ObraValidada_v2", (Action<long, ZPackage>)delegate(long s, ZPackage p)
			{
				Resposta(obra, s, p);
			});
			rede.Register<ZPackage>("Architect_DesmonteValidado_v1", (Action<long, ZPackage>)delegate(long s, ZPackage p)
			{
				Resposta(desmonte, s, p);
			});
		}
	}

	internal static void Desregistrar()
	{
		if (rede != null)
		{
			FieldInfo fieldInfo = AccessTools.Field(typeof(ZRoutedRpc), "m_functions");
			IDictionary dictionary = ((fieldInfo != null) ? (fieldInfo.GetValue(rede) as IDictionary) : null);
			if (dictionary != null)
			{
				dictionary.Remove(StringExtensionMethods.GetStableHashCode("Architect_ObraValidada_v2"));
				dictionary.Remove(StringExtensionMethods.GetStableHashCode("Architect_DesmonteValidado_v1"));
			}
		}
		rede = null;
		obra.id = null;
		desmonte.id = null;
	}

	private static string Hash(ZPackage p)
	{
		return Plugin.Hash(Convert.ToBase64String(p.GetArray()));
	}

	private static string Uid(Piece pc)
	{
		ZNetView val = (((Object)(object)pc != (Object)null) ? ((Component)pc).GetComponent<ZNetView>() : null);
		if ((Object)(object)val == (Object)null || !val.IsValid())
		{
			throw new Exception("pecas mudaram");
		}
		return ((object)Unsafe.As<ZDOID, ZDOID>(ref val.GetZDO().m_uid)/*cast due to .constrained prefix*/).ToString();
	}

	private static ZPackage PacoteObra(string id, List<Peca> pecas, List<Piece> demolir)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Expected O, but got Unknown
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		ZPackage val = new ZPackage();
		val.Write(id);
		val.Write(pecas.Count);
		foreach (Peca peca in pecas)
		{
			val.Write(peca.Nome);
			val.Write(peca.Pos);
			val.Write(peca.Rot);
		}
		val.Write(demolir.Count);
		foreach (Piece item in demolir)
		{
			val.Write(Uid(item));
		}
		return val;
	}

	private static ZPackage PacoteDesmonte(string id, Vector3 centro, float raio, List<Piece> pecas)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Expected O, but got Unknown
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		ZPackage val = new ZPackage();
		val.Write(id);
		val.Write(centro);
		val.Write(raio);
		val.Write(pecas.Count);
		foreach (Piece peca in pecas)
		{
			val.Write(Uid(peca));
		}
		return val;
	}

	private static string Enviar(Pedido q, string req, Func<string, ZPackage> pacote)
	{
		Registrar();
		q.id = Guid.NewGuid().ToString("N");
		q.recebeu = false;
		q.permitiu = false;
		q.erro = "servidor nao respondeu";
		q.respostaDigest = null;
		try
		{
			ZPackage val = pacote(q.id);
			q.digest = Hash(val);
			if (rede != null)
			{
				rede.InvokeRoutedRPC(Rede.ServidorId(), req, new object[1] { val });
			}
		}
		catch (Exception ex)
		{
			q.recebeu = true;
			q.erro = ex.Message;
		}
		return q.id;
	}

	private static bool Fechar(Pedido q, string id, Func<string, ZPackage> pacote, out string motivo)
	{
		motivo = q.erro ?? "autorizacao ausente";
		bool flag = false;
		try
		{
			flag = id == q.id && q.recebeu && q.permitiu && Time.time - q.respondeuEm <= 5f && q.respostaDigest == q.digest && Hash(pacote(id)) == q.digest && Rede.Liberado();
		}
		catch (Exception ex)
		{
			motivo = ex.Message;
		}
		if (!flag && q.permitiu)
		{
			motivo = "pedido mudou ou autorizacao expirou";
		}
		q.id = null;
		q.recebeu = false;
		q.permitiu = false;
		return flag;
	}

	private static void Resposta(Pedido q, long sender, ZPackage p)
	{
		if (sender != Rede.ServidorId() || q.id == null)
		{
			return;
		}
		try
		{
			string text = p.ReadString();
			string text2 = p.ReadString();
			bool flag = p.ReadBool();
			if (!(text != q.id) && !(text2 != q.digest))
			{
				q.respostaDigest = text2;
				q.permitiu = flag;
				q.erro = (flag ? null : "servidor nao autorizou");
				q.recebeu = true;
				q.respondeuEm = Time.tim