Decompiled source of Valheim Cartographer Shared Map and Auto Discover v1.0.0

plugins/ValheimCartographer.dll

Decompiled 3 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using Splatform;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("assembly_guiutils")]
[assembly: IgnoresAccessChecksTo("assembly_utils")]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("ValheimCartographer")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ValheimCartographer")]
[assembly: AssemblyTitle("ValheimCartographer")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Cartografo
{
	internal static class Camas
	{
		internal const int ConfortoDaBase = 4;

		private static readonly HashSet<int> Vazio = new HashSet<int>();

		private static HashSet<int> hashes;

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

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

		internal static HashSet<int> Hashes
		{
			get
			{
				if (hashes == null && (Object)(object)ZNetScene.instance != (Object)null)
				{
					hashes = new HashSet<int>();
					foreach (GameObject prefab in ZNetScene.instance.m_prefabs)
					{
						if ((Object)(object)prefab != (Object)null && (Object)(object)prefab.GetComponent<Bed>() != (Object)null)
						{
							hashes.Add(StringExtensionMethods.GetStableHashCode(((Object)prefab).name));
						}
					}
				}
				return hashes ?? Vazio;
			}
		}

		internal static int Conforto(Vector3 posicao)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Expected I4, but got Unknown
			float num = default(float);
			bool flag = default(bool);
			Cover.GetCoverForPoint(posicao + Vector3.up, ref num, ref flag, 0.5f);
			if (num < 0.8f || !flag)
			{
				return 1;
			}
			Pecas.Clear();
			MelhorPorGrupo.Clear();
			Piece.GetAllComfortPiecesInRadius(posicao, 10f, Pecas);
			foreach (Piece peca in Pecas)
			{
				string key = (((int)peca.m_comfortGroup != 0) ? ("g" + (int)peca.m_comfortGroup) : ("n" + peca.m_name));
				if (!MelhorPorGrupo.TryGetValue(key, out var value) || peca.m_comfort > value)
				{
					MelhorPorGrupo[key] = peca.m_comfort;
				}
			}
			int num2 = 2;
			foreach (int value2 in MelhorPorGrupo.Values)
			{
				num2 += value2;
			}
			return num2;
		}
	}
	internal static class Captura
	{
		private const int Largura = 480;

		private const float Validade = 1f;

		private static RenderTexture alvo;

		private static CommandBuffer comando;

		private static Camera cameraAnexada;

		private static int quadroDoPedido = -1;

		private static bool lendo;

		private static Color32[] pixels;

		private static int largura;

		private static int altura;

		private static float quando = -10f;

		internal static bool Disponivel
		{
			get
			{
				if (pixels != null)
				{
					return Time.time - quando <= 1f;
				}
				return false;
			}
		}

		internal static void Pedir(Camera camera)
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected O, but got Unknown
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Expected O, but got Unknown
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			if (quadroDoPedido >= 0 || lendo || (Object)(object)camera == (Object)null || !SystemInfo.supportsAsyncGPUReadback)
			{
				return;
			}
			int num = Mathf.Max(1, Mathf.RoundToInt(480f * (float)camera.pixelHeight / (float)camera.pixelWidth));
			if ((Object)(object)alvo == (Object)null || ((Texture)alvo).height != num)
			{
				if ((Object)(object)alvo != (Object)null)
				{
					alvo.Release();
				}
				alvo = new RenderTexture(480, num, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)2);
				alvo.Create();
				comando = new CommandBuffer
				{
					name = "Valheim Cartographer capture"
				};
				comando.Blit(RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)1), RenderTargetIdentifier.op_Implicit((Texture)(object)alvo));
			}
			camera.AddCommandBuffer((CameraEvent)20, comando);
			cameraAnexada = camera;
			quadroDoPedido = Time.frameCount;
		}

		internal static void Atualizar()
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			if (quadroDoPedido >= 0 && Time.frameCount > quadroDoPedido)
			{
				if ((Object)(object)cameraAnexada != (Object)null)
				{
					cameraAnexada.RemoveCommandBuffer((CameraEvent)20, comando);
				}
				quadroDoPedido = -1;
				lendo = true;
				AsyncGPUReadback.Request((Texture)(object)alvo, 0, (TextureFormat)4, (Action<AsyncGPUReadbackRequest>)AoLer);
			}
		}

		private static void AoLer(AsyncGPUReadbackRequest pedido)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			lendo = false;
			if (!((AsyncGPUReadbackRequest)(ref pedido)).hasError)
			{
				pixels = ((AsyncGPUReadbackRequest)(ref pedido)).GetData<Color32>(0).ToArray();
				largura = ((AsyncGPUReadbackRequest)(ref pedido)).width;
				altura = ((AsyncGPUReadbackRequest)(ref pedido)).height;
				quando = Time.time;
			}
		}

		internal static bool Cor(Camera camera, Vector2 tela, out Vector3 lab)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			lab = Vector3.zero;
			if (!Disponivel)
			{
				return false;
			}
			int num = Mathf.RoundToInt(tela.x / (float)camera.pixelWidth * (float)largura);
			int num2 = Mathf.RoundToInt(tela.y / (float)camera.pixelHeight * (float)altura);
			if (Plugin.CapturaInvertida.Value)
			{
				num2 = altura - 1 - num2;
			}
			if (num < 1 || num2 < 1 || num >= largura - 1 || num2 >= altura - 1)
			{
				return false;
			}
			Vector3 val = Vector3.zero;
			for (int i = -1; i <= 1; i++)
			{
				for (int j = -1; j <= 1; j++)
				{
					Color32 val2 = pixels[(num2 + i) * largura + num + j];
					val += new Vector3((float)(int)val2.r, (float)(int)val2.g, (float)(int)val2.b);
				}
			}
			lab = Lab(val / 9f);
			return true;
		}

		private static Vector3 Lab(Vector3 rgb)
		{
			//IL_0000: 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_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			float num = Linear(rgb.x / 255f);
			float num2 = Linear(rgb.y / 255f);
			float num3 = Linear(rgb.z / 255f);
			float t = (0.4124f * num + 0.3576f * num2 + 0.1805f * num3) / 0.95047f;
			float t2 = 0.2126f * num + 0.7152f * num2 + 0.0722f * num3;
			float t3 = (0.0193f * num + 0.1192f * num2 + 0.9505f * num3) / 1.08883f;
			float num4 = F(t);
			float num5 = F(t2);
			float num6 = F(t3);
			return new Vector3(116f * num5 - 16f, 500f * (num4 - num5), 200f * (num5 - num6));
		}

		private static float Linear(float c)
		{
			if (!(c <= 0.04045f))
			{
				return Mathf.Pow((c + 0.055f) / 1.055f, 2.4f);
			}
			return c / 12.92f;
		}

		private static float F(float t)
		{
			if (!(t > 0.008856f))
			{
				return 7.787f * t + 0.13793103f;
			}
			return Mathf.Pow(t, 1f / 3f);
		}

		internal static string Gravar()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			if (pixels == null)
			{
				return null;
			}
			Texture2D val = new Texture2D(largura, altura, (TextureFormat)4, false);
			val.SetPixels32(pixels);
			val.Apply();
			string text = Path.Combine(Paths.ConfigPath, "ValheimCartographer");
			Directory.CreateDirectory(text);
			string text2 = Path.Combine(text, "capture.png");
			File.WriteAllBytes(text2, ImageConversion.EncodeToPNG(val));
			Object.Destroy((Object)(object)val);
			return text2;
		}
	}
	internal enum Gatilho
	{
		Mira,
		Visao
	}
	internal sealed class Tipo
	{
		internal readonly string Id;

		internal readonly string Rotulo;

		internal readonly string ItemDoIcone;

		internal readonly Gatilho Gatilho;

		internal readonly float Raio;

		internal readonly string[] Restos;

		internal readonly bool SoNaoColhidos;

		internal Tipo(string id, string rotulo, string itemDoIcone, Gatilho gatilho, float raio, string[] restos = null, bool soNaoColhidos = false)
		{
			Id = id;
			Rotulo = rotulo;
			ItemDoIcone = itemDoIcone;
			Gatilho = gatilho;
			Raio = raio;
			Restos = restos;
			SoNaoColhidos = soNaoColhidos;
		}
	}
	internal static class Catalogo
	{
		internal static readonly Dictionary<string, Tipo> PorId;

		internal static readonly Dictionary<int, Tipo> PorObjeto;

		internal static readonly Dictionary<string, Tipo> PorLocal;

		internal static Tipo Base;

		private static Tipo Novo(string id, string rotulo, string item, Gatilho gatilho, float raio, string[] restos = null, bool soNaoColhidos = false)
		{
			Tipo tipo = new Tipo(id, rotulo, item, gatilho, raio, restos, soNaoColhidos);
			PorId[id] = tipo;
			return tipo;
		}

		private static void Objetos(Tipo tipo, params string[] prefabs)
		{
			foreach (string text in prefabs)
			{
				PorObjeto[StringExtensionMethods.GetStableHashCode(text)] = tipo;
			}
		}

		private static void Locais(Tipo tipo, params string[] prefabs)
		{
			foreach (string key in prefabs)
			{
				PorLocal[key] = tipo;
			}
		}

		private static string[] Numerados(string prefixo, int de, int ate, string sufixo = "")
		{
			string[] array = new string[ate - de + 1];
			for (int i = de; i <= ate; i++)
			{
				array[i - de] = prefixo + i + sufixo;
			}
			return array;
		}

		private static void Minerio(string id, string rotulo, string item, float raio, params string[] prefabs)
		{
			Objetos(Novo(id, rotulo, item, Gatilho.Mira, raio, prefabs), prefabs);
		}

		private static Tipo Spawn(string id, string rotulo, string item, params string[] prefabs)
		{
			Tipo tipo = Novo(id, rotulo, item, Gatilho.Visao, 15f, prefabs);
			Objetos(tipo, prefabs);
			return tipo;
		}

		private static void Local(string id, string rotulo, string item, params string[] prefabs)
		{
			Locais(Novo(id, rotulo, item, Gatilho.Visao, 20f), prefabs);
		}

		static Catalogo()
		{
			PorId = new Dictionary<string, Tipo>();
			PorObjeto = new Dictionary<int, Tipo>();
			PorLocal = new Dictionary<string, Tipo>();
			Minerio("cobre", "$vc_copper", "CopperOre", 15f, "rock4_copper", "rock4_copper_frac");
			Minerio("estanho", "$vc_tin", "TinOre", 30f, "MineRock_Tin");
			Minerio("prata", "$vc_silver", "SilverOre", 15f, "silvervein", "silvervein_frac", "rock3_silver", "rock3_silver_frac");
			Minerio("obsidiana", "$vc_obsidian", "Obsidian", 30f, "MineRock_Obsidian");
			Minerio("ferro", "$vc_iron", "IronScrap", 15f, "mudpile_beacon", "mudpile", "mudpile_frac", "mudpile2", "mudpile2_frac", "mudpile_old");
			Minerio("marmore", "$vc_marble", "BlackMarble", 15f, "giant_ribs", "giant_ribs_frac", "giant_skull", "giant_skull_frac");
			Minerio("sucata", "$vc_scrap", "CopperScrap", 15f, "giant_helmet1", "giant_helmet1_destruction", "giant_helmet2", "giant_helmet2_destruction", "giant_sword1", "giant_sword1_destruction", "giant_sword2", "giant_sword2_destruction");
			Minerio("tecido", "$vc_tissue", "Softtissue", 15f, "giant_brain", "giant_brain_frac");
			Minerio("flametal", "$vc_flametal", "FlametalOreNew", 20f, "MineRock_Meteorite", "LeviathanLava");
			Minerio("gammeltroll", "$vc_gammeltroll", "GoldOre", 15f, "goldvein", "goldvein_frac", "TrollFrost_Frac", "TrollFrost_Frac_arm", "TrollFrost_Frac_legs");
			Local("cripta", "$vc_crypt", null, "Crypt2", "Crypt3", "Crypt4");
			Local("cripta_afundada", "$vc_crypt", null, "SunkenCrypt4");
			Local("caverna_troll", "$vc_cave", null, "TrollCave02");
			Local("caverna_urso", "$vc_cave", null, "BearCave");
			Local("caverna_gelo", "$vc_cave", null, "MountainCave01", "MountainCave02");
			Local("mina", "$vc_mine", null, "Mistlands_DvergrTownEntrance1", "Mistlands_DvergrTownEntrance2");
			Local("cidadela", "$vc_citadel", null, "Mistlands_DvergrBossEntrance1");
			Local("buraco", "$vc_hole", null, Numerados("MorgenHole", 1, 3));
			Local("morkhalla", "$vc_morkhalla", null, "MorkBorg");
			Local("tuneis", "$vc_tunnels", null, "TheHole01");
			Local("casa", "$vc_structure", null, "StoneHouse3", "StoneHouse4", "DN_hut01", "AbandonedLogCabin02", "AbandonedLogCabin03", "AbandonedLogCabin04");
			Locais(PorId["casa"], Numerados("WoodHouse", 1, 13));
			Locais(PorId["casa"], Numerados("SwampHut", 1, 5));
			Local("torre", "$vc_structure", null, "StoneTowerRuins03", "StoneTowerRuins04", "StoneTowerRuins05", "StoneTowerRuins07", "StoneTowerRuins08", "StoneTowerRuins09", "StoneTowerRuins10", "StoneTower1", "StoneTower3", "CharredTowerRuins1", "CharredTowerRuins1_dvergr", "CharredTowerRuins2", "CharredTowerRuins3", "Mistlands_GuardTower1_new", "Mistlands_GuardTower1_ruined_new", "Mistlands_GuardTower1_ruined_new2", "Mistlands_GuardTower2_new", "Mistlands_GuardTower3_new", "Mistlands_GuardTower3_ruined_new", "Mistlands_Lighthouse1_new");
			Local("ruina", "$vc_structure", null, "CombatRuin01", "Ruin1", "Ruin2", "Ruin3", "SwampRuin1", "SwampRuin2", "AshlandRuins", "CharredRuins1", "CharredRuins2", "CharredRuins3", "CharredRuins4", "FortressRuins", "Mistlands_Harbour1");
			Local("vila", "$vc_village", null, "WoodVillage1", "WoodFarm1", "NorthVillage", "LumberCamp");
			Local("fuling", "$enemy_goblin", "GoblinTotem", "GoblinCamp2");
			Local("acampamento", "$vc_camp", null, "Greydwarf_camp1");
			Local("pedras", "$vc_stones", null, "StoneCircle", "Dolmen01", "Dolmen02", "Dolmen03", "ShipSetting01", "ShipSetting02", "ShipSetting03", "NorthMemorialPlace");
			Locais(PorId["pedras"], Numerados("StoneHenge", 1, 6));
			Local("poco", "$vc_well", null, "SwampWell1", "MountainWell1");
			Local("escavacao", "$vc_dig", null, Numerados("Mistlands_Excavation", 1, 3));
			Local("fortaleza", "$vc_fortress", null, "CharredFortress");
			Local("naufragio", "$vc_wreck", null, "ShipWreck01", "ShipWreck02", "ShipWreck03", "ShipWreck04", "ShipWreck01_DN", "ShipWreck02_DN", "FrozenShip01_DN", "FrozenShip02_DN", "FrozenShip03_DN");
			Local("runa", "$vc_rune", null, "Runestone_Boars", "Runestone_Meadows", "Runestone_BlackForest", "Runestone_Greydwarfs", "Runestone_Draugr", "Runestone_Swamps", "Runestone_Mountains", "Runestone_Plains", "Runestone_Ashlands", "Runestone_DeepNorth", "Runestone_Mistlands", "DrakeLorestone");
			Local("misterio", "$vc_mystery", null, Numerados("PlaceofMystery", 1, 3));
			Local("ovos", "$vc_eggs", "DragonEgg", "DrakeNest01");
			Locais(Novo("ninho", "$vc_nest", "VoltureEgg", Gatilho.Visao, 15f, new string[1] { "Pickable_VoltureEgg" }, soNaoColhidos: true), "VoltureNest");
			Local("enxofre", "$vc_sulfur", "SulfurStone", "SulfurArch");
			Local("gosma", "$vc_guck", "Guck", "InfestedTree01");
			Local("piche", "$vc_tar", "Tar", "TarPit1", "TarPit2", "TarPit3", "TarPit1_1", "TarPit2_1", "TarPit3_1");
			Local("chefe_eikthyr", "$vc_boss $enemy_eikthyr", "TrophyEikthyr", "Eikthyrnir");
			Local("chefe_anciao", "$vc_boss $enemy_gdking", "TrophyTheElder", "GDKing");
			Local("chefe_massa", "$vc_boss $enemy_bonemass", "TrophyBonemass", "Bonemass");
			Local("chefe_moder", "$vc_boss $enemy_dragon", "TrophyDragonQueen", "Dragonqueen");
			Local("chefe_yagluth", "$vc_boss $enemy_goblinking", "TrophyGoblinKing", "GoblinKing");
			Local("chefe_fader", "$vc_boss $enemy_fader", "TrophyFader", "FaderLocation");
			Spawn("anao", "$vc_spawn_greydwarf", "TrophyGreydwarf", "Spawner_GreydwarfNest");
			Spawn("esqueleto", "$vc_spawn_skeleton", "TrophySkeleton", "BonePileSpawner", "BonePileSpawner_swamp");
			Locais(Spawn("draugr", "$vc_spawn_draugr", "TrophyDraugrElite", "Spawner_DraugrPile"), "Grave1");
			Local("surtling", "$vc_spawn_surtling", "TrophySurtling", "FireHole");
			Locais(Spawn("carbonizado", "$vc_spawn_charred", "TrophyCharredMelee", "Spawner_CharredStone", "Spawner_CharredStone_Elite", "Spawner_CharredStone_event"), "CharredStone_Spawner");
			Spawn("efigie", "$vc_spawn_charred", null, "Spawner_CharredCross");
			Spawn("elaking", "$vc_spawn_elaking", "TrophyElaking", "Spawner_Hole", "Spawner_Hole_double");
			Spawn("massa", "$vc_spawn_pulp", "TrophyBlob_Morkhalla", "BlobMorkBig");
			Spawn("krigen", "$vc_spawn_krigen", "TrophyJotunWarrior", "BlackIce_Core");
			Base = Novo("base", "$vc_base", null, Gatilho.Visao, 30f);
		}
	}
	internal static class Comandos
	{
		private sealed class Info : ConsoleCommand
		{
			public override string Name => "vc_info";

			public override string Help => "Valheim Cartographer: points received from the server and the last visibility check";

			public override void Run(string[] args)
			{
				Console.instance.Print($"Connected: {Rede.Pronto}. Points on the map: {Marcadores.Pontos.Count}.");
				Console.instance.Print("Last visibility check: " + ((Detector.Ultima.Length > 0) ? Detector.Ultima : "none yet"));
			}
		}

		private sealed class Capture : ConsoleCommand
		{
			public override string Name => "vc_capture";

			public override string Help => "Valheim Cartographer: saves the last screen capture used for the contrast check";

			public override void Run(string[] args)
			{
				string text = Captura.Gravar();
				Console.instance.Print((text != null) ? ("Saved to " + text + ". If it is upside down, turn on \"Flip screen capture\" in the config.") : "No capture yet: look at a place that is not on the map yet.");
			}
		}

		private sealed class Colors : ConsoleCommand
		{
			public override string Name => "vc_colors";

			public override string Help => "Valheim Cartographer: your map color, and saves the 10 player icons to a PNG";

			public override void Run(string[] args)
			{
				Console.instance.Print(Cores.Resumo());
				string text = Cores.GravarPeoes();
				Console.instance.Print((text != null) ? ("Player icons saved to " + text + ".") : "Could not paint the player icon: only names and your arrow get colors. See the BepInEx log.");
			}
		}

		internal static void Registrar()
		{
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new Info());
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new Capture());
			CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new Colors());
		}
	}
	internal static class Cores
	{
		[HarmonyPatch(typeof(Minimap), "UpdatePins")]
		private static class PintarJogadores
		{
			private static void Postfix(Minimap __instance)
			{
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
				//IL_0107: Unknown result type (might be due to invalid IL or missing references)
				List<PinData> playerPins = __instance.m_playerPins;
				List<PlayerInfo> tempPlayerInfo = __instance.m_tempPlayerInfo;
				if (playerPins.Count != tempPlayerInfo.Count || PorConta.Count == 0)
				{
					return;
				}
				for (int i = 0; i < playerPins.Count; i++)
				{
					int num = CorDe(tempPlayerInfo[i]);
					if (num >= 0)
					{
						PinData val = playerPins[i];
						Sprite val2 = Peao(num);
						if ((Object)(object)val2 != (Object)null && (Object)(object)val.m_icon != (Object)(object)val2)
						{
							val.m_icon = val2;
						}
						if ((Object)(object)val2 != (Object)null && (Object)(object)val.m_iconElement != (Object)null && (Object)(object)val.m_iconElement.sprite != (Object)(object)val2)
						{
							val.m_iconElement.sprite = val2;
						}
						Color val3 = Color32.op_Implicit(Paleta[num]);
						PinNameData namePinData = val.m_NamePinData;
						if ((Object)(object)((namePinData != null) ? namePinData.PinNameText : null) != (Object)null && ((Graphic)val.m_NamePinData.PinNameText).color != val3)
						{
							((Graphic)val.m_NamePinData.PinNameText).color = val3;
						}
					}
				}
			}
		}

		internal static readonly Color32[] Paleta = (Color32[])(object)new Color32[10]
		{
			new Color32((byte)229, (byte)57, (byte)53, byte.MaxValue),
			new Color32((byte)30, (byte)110, (byte)235, byte.MaxValue),
			new Color32((byte)253, (byte)216, (byte)53, byte.MaxValue),
			new Color32((byte)150, (byte)50, (byte)200, byte.MaxValue),
			new Color32((byte)251, (byte)140, (byte)0, byte.MaxValue),
			new Color32((byte)0, (byte)200, (byte)220, byte.MaxValue),
			new Color32((byte)240, (byte)80, (byte)160, byte.MaxValue),
			new Color32((byte)100, (byte)200, (byte)60, byte.MaxValue),
			new Color32((byte)245, (byte)245, (byte)245, byte.MaxValue),
			new Color32((byte)45, (byte)45, (byte)45, byte.MaxValue)
		};

		internal static readonly string[] Nomes = new string[10] { "red", "blue", "yellow", "purple", "orange", "cyan", "pink", "green", "white", "black" };

		private const float IntervaloDoServidor = 2f;

		private const float IntervaloDoJogador = 1f;

		private static readonly Dictionary<string, (int cor, string nome)> DoServidor = new Dictionary<string, (int, string)>();

		private static bool carregado;

		private static float proximoServidor;

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

		private static float proximoJogador;

		private static readonly Sprite[] Peoes = (Sprite[])(object)new Sprite[Paleta.Length];

		private static bool peaoFalhou;

		private static Color? amareloDaSeta;

		private static string Arquivo()
		{
			string text = Path.Combine(Paths.ConfigPath, "ValheimCartographer");
			Directory.CreateDirectory(text);
			return Path.Combine(text, "cores-dos-jogadores.txt");
		}

		private unsafe static string Conta(PlayerInfo jogador)
		{
			//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)
			string text = ((object)(*(PlatformUserID*)(&jogador.m_userInfo.m_id))/*cast due to .constrained prefix*/).ToString();
			if (!string.IsNullOrEmpty(text) && !(text == ((object)PlatformUserID.None/*cast due to .constrained prefix*/).ToString()))
			{
				return text;
			}
			return null;
		}

		internal static void Reiniciar()
		{
			PorConta.Clear();
		}

		private static void Carregar()
		{
			carregado = true;
			DoServidor.Clear();
			string text = Arquivo();
			if (!File.Exists(text))
			{
				return;
			}
			try
			{
				string[] array = File.ReadAllLines(text);
				foreach (string text2 in array)
				{
					string[] array2 = text2.Split('\t');
					if (array2.Length >= 2 && !text2.StartsWith("#") && int.TryParse(array2[1], out var result) && result >= 0 && result < Paleta.Length)
					{
						DoServidor[array2[0]] = (result, (array2.Length >= 3) ? array2[2] : "");
					}
				}
				Plugin.Log.LogInfo((object)$"Cores de {DoServidor.Count} jogadores carregadas");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Não consegui ler " + text + " (" + ex.Message + "); as cores serão dadas de novo"));
			}
		}

		private static void Salvar()
		{
			try
			{
				List<string> list = new List<string> { "# conta\tcor (0 = " + string.Join(", ", Nomes) + ")\tpersonagem" };
				foreach (KeyValuePair<string, (int, string)> item in DoServidor)
				{
					list.Add($"{item.Key}\t{item.Value.Item1}\t{item.Value.Item2}");
				}
				string text = Arquivo();
				string text2 = text + ".tmp";
				File.WriteAllLines(text2, list);
				if (File.Exists(text))
				{
					File.Replace(text2, text, text + ".bak");
				}
				else
				{
					File.Move(text2, text);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Não consegui gravar as cores dos jogadores: " + ex.Message));
			}
		}

		internal static void AtualizarServidor()
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			if (Time.time < proximoServidor)
			{
				return;
			}
			proximoServidor = Time.time + 2f;
			if (!carregado)
			{
				Carregar();
			}
			bool flag = false;
			foreach (PlayerInfo player in ZNet.instance.GetPlayerList())
			{
				string text = Conta(player);
				if (text != null)
				{
					if (!DoServidor.TryGetValue(text, out (int, string) value))
					{
						int num = CorLivre();
						DoServidor[text] = (num, player.m_name);
						Plugin.Log.LogInfo((object)(player.m_name + " ganhou a cor " + Nomes[num]));
						Salvar();
						flag = true;
					}
					else if (value.Item2 != player.m_name)
					{
						DoServidor[text] = (value.Item1, player.m_name);
						Salvar();
					}
				}
			}
			if (flag)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(0L, "VC_Colors", new object[1] { Tabela() });
			}
		}

		private static int CorLivre()
		{
			int[] array = new int[Paleta.Length];
			foreach (var value in DoServidor.Values)
			{
				int item = value.cor;
				array[item]++;
			}
			int num = 0;
			for (int i = 1; i < array.Length; i++)
			{
				if (array[i] < array[num])
				{
					num = i;
				}
			}
			return num;
		}

		private static ZPackage Tabela()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			val.Write(DoServidor.Count);
			foreach (KeyValuePair<string, (int, string)> item in DoServidor)
			{
				val.Write(item.Key);
				val.Write(item.Value.Item1);
			}
			return val;
		}

		internal static void Enviar(long destino)
		{
			if (!carregado)
			{
				Carregar();
			}
			ZRoutedRpc.instance.InvokeRoutedRPC(destino, "VC_Colors", new object[1] { Tabela() });
		}

		internal static void RPC_Cores(long remetente, ZPackage pacote)
		{
			if (ZNet.instance.IsDedicated())
			{
				return;
			}
			PorConta.Clear();
			int num = pacote.ReadInt();
			for (int i = 0; i < num; i++)
			{
				string key = pacote.ReadString();
				int num2 = pacote.ReadInt();
				if (num2 >= 0 && num2 < Paleta.Length)
				{
					PorConta[key] = num2;
				}
			}
			if ((Object)(object)Minimap.instance != (Object)null)
			{
				Minimap.instance.m_pinUpdateRequired = true;
			}
		}

		private static int CorDe(PlayerInfo jogador)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			string text = Conta(jogador);
			if (text == null || !PorConta.TryGetValue(text, out var value))
			{
				return -1;
			}
			return value;
		}

		internal static int Minha()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || (Object)(object)ZNet.instance == (Object)null)
			{
				return -1;
			}
			ZDOID zDOID = ((Character)localPlayer).GetZDOID();
			foreach (PlayerInfo player in ZNet.instance.GetPlayerList())
			{
				if (player.m_characterID == zDOID)
				{
					return CorDe(player);
				}
			}
			return -1;
		}

		internal static string Resumo()
		{
			int num = Minha();
			return string.Format("Your color: {0}. Colors received for {1} players.", (num >= 0) ? Nomes[num] : "none yet", PorConta.Count);
		}

		internal static string GravarPeoes()
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			Sprite[] array = (Sprite[])(object)new Sprite[Paleta.Length];
			for (int i = 0; i < Paleta.Length; i++)
			{
				array[i] = Peao(i);
				if ((Object)(object)array[i] == (Object)null)
				{
					return null;
				}
			}
			int width = ((Texture)array[0].texture).width;
			int height = ((Texture)array[0].texture).height;
			Texture2D val = new Texture2D(width * Paleta.Length, height, (TextureFormat)4, false);
			for (int j = 0; j < Paleta.Length; j++)
			{
				val.SetPixels32(j * width, 0, width, height, array[j].texture.GetPixels32());
			}
			val.Apply();
			string text = Path.Combine(Path.GetDirectoryName(Arquivo()), "player-icons.png");
			File.WriteAllBytes(text, ImageConversion.EncodeToPNG(val));
			Object.Destroy((Object)(object)val);
			return text;
		}

		internal static void AtualizarJogador()
		{
			if (Time.time < proximoJogador || (Object)(object)Minimap.instance == (Object)null || (Object)(object)ZNet.instance == (Object)null)
			{
				return;
			}
			proximoJogador = Time.time + 1f;
			Toggle publicPosition = Minimap.instance.m_publicPosition;
			if (Plugin.JogadoresVisiveis.Value)
			{
				if (!ZNet.instance.IsReferencePositionPublic())
				{
					ZNet.instance.SetPublicReferencePosition(true);
				}
				if ((Object)(object)publicPosition != (Object)null)
				{
					publicPosition.SetIsOnWithoutNotify(true);
					((Selectable)publicPosition).interactable = false;
				}
			}
			else if ((Object)(object)publicPosition != (Object)null && !((Selectable)publicPosition).interactable)
			{
				((Selectable)publicPosition).interactable = true;
			}
			int cor = Minha();
			PintarSeta(Minimap.instance.m_smallMarker, cor);
			PintarSeta(Minimap.instance.m_largeMarker, cor);
		}

		private static void PintarSeta(RectTransform seta, int cor)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			Image val = (((Object)(object)seta != (Object)null) ? ((Component)seta).GetComponent<Image>() : null);
			if (!((Object)(object)val == (Object)null))
			{
				if (!amareloDaSeta.HasValue)
				{
					amareloDaSeta = ((Graphic)val).color;
				}
				Color val2 = ((cor >= 0) ? Color32.op_Implicit(Paleta[cor]) : amareloDaSeta.Value);
				if (((Graphic)val).color != val2)
				{
					((Graphic)val).color = val2;
				}
			}
		}

		private static Sprite Peao(int cor)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: 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_0137: 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_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Expected O, but got Unknown
			//IL_007e: 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_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: 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_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)
			if ((Object)(object)Peoes[cor] != (Object)null)
			{
				return Peoes[cor];
			}
			Sprite val = ((peaoFalhou || (Object)(object)Minimap.instance == (Object)null) ? null : Minimap.instance.GetSprite((PinType)10));
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			try
			{
				int largura;
				int altura;
				Color32[] array = Icones.LerPixels(val, out largura, out altura);
				Color32 val2 = Paleta[cor];
				for (int i = 0; i < array.Length; i++)
				{
					Color32 val3 = array[i];
					if (val3.a > 0 && val3.r > val3.g + 35 && val3.r > val3.b + 35)
					{
						float num = (float)(int)val3.r / 255f * 1.05f;
						array[i] = new Color32((byte)Mathf.Min(255f, (float)(int)val2.r * num), (byte)Mathf.Min(255f, (float)(int)val2.g * num), (byte)Mathf.Min(255f, (float)(int)val2.b * num), val3.a);
					}
				}
				Texture2D val4 = new Texture2D(largura, altura, (TextureFormat)4, false)
				{
					wrapMode = (TextureWrapMode)1
				};
				val4.SetPixels32(array);
				val4.Apply();
				float x = val.pivot.x;
				Rect rect = val.rect;
				float num2 = x / ((Rect)(ref rect)).width;
				float y = val.pivot.y;
				rect = val.rect;
				Vector2 val5 = default(Vector2);
				((Vector2)(ref val5))..ctor(num2, y / ((Rect)(ref rect)).height);
				Sprite val6 = Sprite.Create(val4, new Rect(0f, 0f, (float)largura, (float)altura), val5, val.pixelsPerUnit);
				((Object)val6).name = "vc_player_" + Nomes[cor];
				Peoes[cor] = val6;
				return val6;
			}
			catch (Exception ex)
			{
				peaoFalhou = true;
				Plugin.Log.LogWarning((object)("Não consegui pintar o ícone dos jogadores (" + ex.Message + "); só os nomes e a seta ficam coloridos"));
				return null;
			}
		}
	}
	internal static class Detector
	{
		private const float Passo = 0.25f;

		private const float DistanciaDasCamas = 200f;

		private const float RaioDaCasa = 12f;

		private static float proximo;

		private static float proximaLista;

		private static float proximaLimpeza;

		private static float proximaConferencia;

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

		private static readonly HashSet<int> VistosAgora = new HashSet<int>();

		private static readonly List<int> Esquecer = new List<int>();

		private static readonly HashSet<int> Enviados = new HashSet<int>();

		private static readonly HashSet<int> BasesPerdidas = new HashSet<int>();

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

		private static readonly List<(ZNetView objeto, Tipo tipo)> Spawns = new List<(ZNetView, Tipo)>();

		private static readonly List<ZNetView> CamasCarregadas = new List<ZNetView>();

		private static readonly Dictionary<int, (Geometria forma, Transform raiz)> Formas = new Dictionary<int, (Geometria, Transform)>();

		private static readonly Dictionary<int, (float quando, int nivel)> Confortos = new Dictionary<int, (float, int)>();

		private static readonly List<Vector3> PontosVistos = new List<Vector3>();

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

		internal static string Ultima = "";

		internal static void Reiniciar()
		{
			Olhando.Clear();
			Enviados.Clear();
			BasesPerdidas.Clear();
			PertoDesde.Clear();
			Spawns.Clear();
			CamasCarregadas.Clear();
			Formas.Clear();
			Confortos.Clear();
		}

		internal static void Atualizar()
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: 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_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_032f: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || !Rede.Pronto || Time.time < proximo)
			{
				return;
			}
			proximo = Time.time + 0.25f;
			Mira(localPlayer);
			Camera mainCamera = Utils.GetMainCamera();
			if ((Object)(object)mainCamera == (Object)null || MenuAberto() || ((Character)localPlayer).IsDead() || ((Character)localPlayer).IsTeleporting() || ((Character)localPlayer).InCutscene() || Character.InInterior(((Component)localPlayer).transform.position))
			{
				Olhando.Clear();
				return;
			}
			if (Time.time >= proximaLista)
			{
				proximaLista = Time.time + 1f;
				ListarObjetos();
			}
			VistosAgora.Clear();
			Vector3 position = ((Component)localPlayer).transform.position;
			foreach (Location s_allLocation in Location.s_allLocations)
			{
				if ((Object)(object)s_allLocation != (Object)null && Catalogo.PorLocal.TryGetValue(Utils.GetPrefabName(((Component)s_allLocation).gameObject), out var value))
				{
					Location esteLocal = s_allLocation;
					Avaliar(((Object)s_allLocation).GetInstanceID(), value, ((Component)s_allLocation).transform.position, ((Component)s_allLocation).transform, s_allLocation.IsInside(position, 0f, false), mainCamera, () => Visao.DeLocal(esteLocal));
				}
			}
			foreach (var (val, tipo) in Spawns)
			{
				if ((Object)(object)val != (Object)null)
				{
					Vector3 position2 = ((Component)val).transform.position;
					Avaliar(((Object)val).GetInstanceID(), tipo, position2, ((Component)val).transform, Utils.DistanceXZ(position, position2) <= Plugin.DistanciaDeSpawn.Value, mainCamera);
				}
			}
			Bases(position, mainCamera);
			Esquecer.Clear();
			foreach (int key in Olhando.Keys)
			{
				if (!VistosAgora.Contains(key))
				{
					Esquecer.Add(key);
				}
			}
			Esquecer.ForEach(delegate(int chave)
			{
				Olhando.Remove(chave);
			});
			if (Time.time >= proximaLimpeza)
			{
				proximaLimpeza = Time.time + 30f;
				Esquecer.Clear();
				foreach (KeyValuePair<int, (Geometria, Transform)> forma in Formas)
				{
					if ((Object)(object)forma.Value.Item2 == (Object)null)
					{
						Esquecer.Add(forma.Key);
					}
				}
				Esquecer.ForEach(delegate(int chave)
				{
					Formas.Remove(chave);
				});
			}
			if (Time.time >= proximaConferencia)
			{
				proximaConferencia = Time.time + 5f;
				ConferirBases(position);
			}
		}

		private static bool MenuAberto()
		{
			if (!InventoryGui.IsVisible() && !Minimap.IsOpen() && !Menu.IsVisible() && !StoreGui.IsVisible() && !TextInput.IsVisible() && !Console.IsVisible() && !Hud.IsPieceSelectionVisible())
			{
				if ((Object)(object)Chat.instance != (Object)null)
				{
					return Chat.instance.HasFocus();
				}
				return false;
			}
			return true;
		}

		private static void Mira(Player jogador)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			GameObject hoverObject = ((Humanoid)jogador).GetHoverObject();
			ZNetView val = (((Object)(object)hoverObject != (Object)null) ? hoverObject.GetComponentInParent<ZNetView>() : null);
			if (!((Object)(object)val == (Object)null) && val.IsValid() && Catalogo.PorObjeto.TryGetValue(val.GetZDO().GetPrefab(), out var value) && value.Gatilho == Gatilho.Mira)
			{
				Vector3 position = ((Component)val).transform.position;
				int instanceID = ((Object)val).GetInstanceID();
				if (!Character.InInterior(position) && !Enviados.Contains(instanceID) && !Marcadores.Conhecido(value, position))
				{
					Reportar(value, position, instanceID, "crosshair");
				}
			}
		}

		private static void Reportar(Tipo tipo, Vector3 onde, int chave, string como)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			Enviados.Add(chave);
			Rede.Achei(tipo, onde);
			if (Plugin.LogDeDescobertas.Value && (Object)(object)Player.m_localPlayer != (Object)null)
			{
				float num = Vector3.Distance(((Component)Player.m_localPlayer).transform.position, onde);
				Plugin.Log.LogInfo((object)$"Descoberta {tipo.Id} a {num:0} m ({como})");
			}
		}

		private static void ListarObjetos()
		{
			Spawns.Clear();
			CamasCarregadas.Clear();
			if ((Object)(object)ZNetScene.instance == (Object)null)
			{
				return;
			}
			HashSet<int> hashes = Camas.Hashes;
			foreach (ZNetView value2 in ZNetScene.instance.m_instances.Values)
			{
				if (!((Object)(object)value2 == (Object)null) && value2.IsValid())
				{
					int prefab = value2.GetZDO().GetPrefab();
					if (Catalogo.PorObjeto.TryGetValue(prefab, out var value) && value.Gatilho == Gatilho.Visao)
					{
						Spawns.Add((value2, value));
					}
					else if (hashes.Contains(prefab))
					{
						CamasCarregadas.Add(value2);
					}
				}
			}
		}

		private static void Avaliar(int chave, Tipo tipo, Vector3 onde, Transform raiz, bool dentro, Camera camera, Func<Geometria> criarForma = null)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			if (Enviados.Contains(chave) || Character.InInterior(onde) || Marcadores.Conhecido(tipo, onde))
			{
				return;
			}
			if (dentro)
			{
				Reportar(tipo, onde, chave, "entered the area");
			}
			else
			{
				if (!Visao.Testar(Forma(chave, raiz, criarForma), camera, PontosVistos, out var tela, out var tamanho))
				{
					return;
				}
				Captura.Pedir(camera);
				float num = Visao.Contraste(camera, tela, PontosVistos);
				float num2 = Visao.Limite(num);
				Ultima = string.Format("{0}: size {1:0.0}% / needs {2:0.0}% (contrast {3}, ", tipo.Id, tamanho * 100f, num2 * 100f, (num < 0f) ? "n/a" : num.ToString("0")) + $"parts seen {Visao.UltimasVistas}/{Visao.UltimasAmostras})";
				if (!(tamanho < num2))
				{
					VistosAgora.Add(chave);
					float value;
					float num3 = (Olhando.TryGetValue(chave, out value) ? value : 0f) + 0.25f;
					if (num3 >= Plugin.TempoOlhando.Value)
					{
						Olhando.Remove(chave);
						Reportar(tipo, onde, chave, "seen: " + Ultima);
					}
					else
					{
						Olhando[chave] = num3;
					}
				}
			}
		}

		private static Geometria Forma(int chave, Transform raiz, Func<Geometria> criarForma)
		{
			if (Formas.TryGetValue(chave, out (Geometria, Transform) value) && (criarForma == null || Time.time - value.Item1.Criada < 10f))
			{
				return value.Item1;
			}
			Geometria geometria = ((criarForma != null) ? criarForma() : Visao.DeRaiz(raiz));
			Formas[chave] = (geometria, raiz);
			return geometria;
		}

		private static int Conforto(ZNetView cama)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			int instanceID = ((Object)cama).GetInstanceID();
			if (!Confortos.TryGetValue(instanceID, out (float, int) value) || Time.time - value.Item1 > 2f)
			{
				value = (Time.time, Camas.Conforto(((Component)cama).transform.position));
				Confortos[instanceID] = value;
			}
			return value.Item2;
		}

		private static void Bases(Vector3 aqui, Camera camera)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: 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)
			foreach (ZNetView camasCarregada in CamasCarregadas)
			{
				if ((Object)(object)camasCarregada == (Object)null)
				{
					continue;
				}
				Vector3 onde = ((Component)camasCarregada).transform.position;
				float num = Utils.DistanceXZ(onde, aqui);
				if (!(num > 200f) && !Enviados.Contains(((Object)camasCarregada).GetInstanceID()) && !Marcadores.Conhecido(Catalogo.Base, onde) && Conforto(camasCarregada) >= 4)
				{
					Avaliar(((Object)camasCarregada).GetInstanceID(), Catalogo.Base, onde, ((Component)camasCarregada).transform, num <= Plugin.DistanciaDeSpawn.Value, camera, delegate
					{
						//IL_000b: Unknown result type (might be due to invalid IL or missing references)
						Pecas.Clear();
						Piece.GetAllPiecesInRadius(onde, 12f, Pecas);
						return Visao.DePecas(Pecas);
					});
				}
			}
		}

		private static void ConferirBases(Vector3 aqui)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ZNetScene.instance == (Object)null)
			{
				return;
			}
			foreach (Marcadores.Ponto value2 in Marcadores.Pontos.Values)
			{
				if (value2.Tipo != Catalogo.Base || BasesPerdidas.Contains(value2.Id))
				{
					continue;
				}
				float value;
				if (Utils.DistanceXZ(value2.Pos, aqui) > 40f || !ZNetScene.instance.IsAreaReady(value2.Pos))
				{
					PertoDesde.Remove(value2.Id);
				}
				else if (!PertoDesde.TryGetValue(value2.Id, out value))
				{
					PertoDesde[value2.Id] = Time.time;
				}
				else
				{
					if (Time.time - value < 10f)
					{
						continue;
					}
					bool flag = false;
					foreach (ZNetView camasCarregada in CamasCarregadas)
					{
						if ((Object)(object)camasCarregada != (Object)null && Utils.DistanceXZ(((Component)camasCarregada).transform.position, value2.Pos) <= Catalogo.Base.Raio && Conforto(camasCarregada) >= 4)
						{
							flag = true;
							break;
						}
					}
					if (!flag)
					{
						BasesPerdidas.Add(value2.Id);
						Rede.Acabou(value2.Id);
					}
				}
			}
		}
	}
	internal static class Exploracao
	{
		[HarmonyPatch(typeof(Minimap), "Explore", new Type[]
		{
			typeof(int),
			typeof(int)
		})]
		private static class AnotarExploracao
		{
			private static void Postfix(Minimap __instance, int x, int y, bool __result)
			{
				if (__result && !aplicandoDoServidor && Plugin.MapaCompartilhado.Value && __instance.m_textureSize == 2048 && Pendentes.Count < 200000)
				{
					Pendentes.Add(y * 2048 + x);
				}
			}
		}

		internal const int Lado = 2048;

		internal const int Fatias = 16;

		internal const int BytesPorFatia = 32768;

		internal const int IndicesPorMensagem = 10000;

		private const float IntervaloDeEnvio = 5f;

		private const int MaximoPendentes = 200000;

		private const int LimiteParaRefazerTudo = 20000;

		private static readonly List<int> Pendentes = new List<int>();

		private static float proximoEnvio;

		private static bool aplicandoDoServidor;

		private static byte[] inicial;

		private static int fatiasIniciais;

		internal static void Reiniciar()
		{
			Pendentes.Clear();
			inicial = null;
			fatiasIniciais = 0;
		}

		internal static byte[] BitsLocais()
		{
			BitArray bitArray = Minimap.instance?.m_explored;
			if (bitArray == null || bitArray.Length != 4194304)
			{
				return null;
			}
			byte[] array = new byte[bitArray.Length / 8];
			bitArray.CopyTo(array, 0);
			return array;
		}

		internal static bool FatiaVazia(byte[] bytes, int fatia)
		{
			int i = fatia * 32768;
			for (int num = i + 32768; i < num; i++)
			{
				if (bytes[i] != 0)
				{
					return false;
				}
			}
			return true;
		}

		internal static byte[] Recortar(byte[] bytes, int fatia)
		{
			byte[] array = new byte[32768];
			Buffer.BlockCopy(bytes, fatia * 32768, array, 0, 32768);
			return array;
		}

		internal static void Atualizar()
		{
			if (Pendentes.Count != 0 && !(Time.time < proximoEnvio) && Rede.Pronto)
			{
				proximoEnvio = Time.time + 5f;
				Rede.Explorei(Pendentes);
				Pendentes.Clear();
			}
		}

		internal static void ReceberFatia(int fatia, bool doInicio, int total, byte[] dados)
		{
			Minimap instance = Minimap.instance;
			if ((Object)(object)instance == (Object)null || instance.m_textureSize != 2048 || dados.Length != 32768 || fatia < 0 || fatia >= 16)
			{
				return;
			}
			if (doInicio)
			{
				if (inicial == null)
				{
					inicial = new byte[524288];
					fatiasIniciais = 0;
				}
				Buffer.BlockCopy(dados, 0, inicial, fatia * 32768, 32768);
				if (++fatiasIniciais >= total)
				{
					AplicarBits(inicial);
					inicial = null;
				}
				return;
			}
			List<int> list = new List<int>();
			int num = fatia * 32768 * 8;
			for (int i = 0; i < dados.Length; i++)
			{
				if (dados[i] == 0)
				{
					continue;
				}
				for (int j = 0; j < 8; j++)
				{
					int num2 = num + i * 8 + j;
					if (((dados[i] >> j) & 1) != 0 && !instance.m_explored[num2])
					{
						list.Add(num2);
					}
				}
			}
			if (list.Count > 20000)
			{
				byte[] array = new byte[524288];
				Buffer.BlockCopy(dados, 0, array, fatia * 32768, 32768);
				AplicarBits(array);
			}
			else if (list.Count > 0)
			{
				AplicarIndices(list);
			}
		}

		private static void AplicarBits(byte[] bytes)
		{
			Minimap instance = Minimap.instance;
			if (!((Object)(object)instance == (Object)null) && bytes.Length * 8 == 4194304)
			{
				BitArray bitArray = new BitArray(instance.m_explored);
				bitArray.Or(new BitArray(bytes));
				aplicandoDoServidor = true;
				instance.ResetAndExplore(bitArray, new BitArray(instance.m_exploredOthers));
				instance.m_fogTexture.Apply();
				aplicandoDoServidor = false;
			}
		}

		internal static void AplicarIndices(List<int> indices)
		{
			Minimap instance = Minimap.instance;
			if ((Object)(object)instance == (Object)null || instance.m_textureSize != 2048)
			{
				return;
			}
			bool flag = false;
			aplicandoDoServidor = true;
			foreach (int index in indices)
			{
				if (index >= 0 && index < 4194304)
				{
					flag |= instance.Explore(index % 2048, index / 2048);
				}
			}
			aplicandoDoServidor = false;
			if (flag)
			{
				instance.m_fogTexture.Apply();
			}
		}
	}
	internal static class Icones
	{
		private const int Lado = 16;

		private const int Cores = 12;

		private static readonly Color32 Contorno = new Color32((byte)20, (byte)15, (byte)12, byte.MaxValue);

		private static readonly Dictionary<string, Sprite> Cache = new Dictionary<string, Sprite>();

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

		internal static Sprite Obter(Tipo tipo)
		{
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			if (Cache.TryGetValue(tipo.Id, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			if (Falharam.Contains(tipo.Id))
			{
				return null;
			}
			Texture2D val;
			try
			{
				val = ((tipo.ItemDoIcone != null) ? DoItem(tipo.ItemDoIcone) : DoRecurso(tipo.Id));
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Não consegui fazer o ícone de " + tipo.Id + ": " + ex.Message));
				val = null;
			}
			if ((Object)(object)val == (Object)null)
			{
				Falharam.Add(tipo.Id);
				return null;
			}
			((Texture)val).filterMode = (FilterMode)0;
			((Texture)val).wrapMode = (TextureWrapMode)1;
			Sprite val2 = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
			((Object)val2).name = "vc_" + tipo.Id;
			Cache[tipo.Id] = val2;
			return val2;
		}

		private static Texture2D DoRecurso(string nome)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			//IL_0065: Expected O, but got Unknown
			using Stream stream = typeof(Icones).Assembly.GetManifestResourceStream("Cartografo.Icones." + nome + ".png");
			if (stream == null)
			{
				Plugin.Log.LogWarning((object)("Ícone não encontrado na DLL: " + nome));
				return null;
			}
			using MemoryStream memoryStream = new MemoryStream();
			stream.CopyTo(memoryStream);
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
			ImageConversion.LoadImage(val, memoryStream.ToArray());
			return val;
		}

		private static Texture2D DoItem(string prefab)
		{
			ObjectDB instance = ObjectDB.instance;
			object obj;
			if (instance == null)
			{
				obj = null;
			}
			else
			{
				GameObject itemPrefab = instance.GetItemPrefab(prefab);
				if (itemPrefab == null)
				{
					obj = null;
				}
				else
				{
					ItemDrop component = itemPrefab.GetComponent<ItemDrop>();
					if (component == null)
					{
						obj = null;
					}
					else
					{
						ItemData itemData = component.m_itemData;
						obj = ((itemData != null) ? itemData.GetIcon() : null);
					}
				}
			}
			Sprite val = (Sprite)obj;
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogWarning((object)("Item do ícone não encontrado: " + prefab));
				return null;
			}
			int largura;
			int altura;
			return Contornar(Pixelizar(LerPixels(val, out largura, out altura), largura, altura));
		}

		internal static Color32[] LerPixels(Sprite sprite, out int largura, out int altura)
		{
			//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_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Expected O, but got Unknown
			Texture texture = (Texture)(object)sprite.texture;
			Rect textureRect = sprite.textureRect;
			RenderTexture temporary = RenderTexture.GetTemporary(texture.width, texture.height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)2);
			Graphics.Blit(texture, temporary);
			RenderTexture active = RenderTexture.active;
			RenderTexture.active = temporary;
			largura = Mathf.RoundToInt(((Rect)(ref textureRect)).width);
			altura = Mathf.RoundToInt(((Rect)(ref textureRect)).height);
			Texture2D val = new Texture2D(largura, altura, (TextureFormat)4, false);
			val.ReadPixels(new Rect(((Rect)(ref textureRect)).x, ((Rect)(ref textureRect)).y, (float)largura, (float)altura), 0, 0);
			val.Apply();
			RenderTexture.active = active;
			RenderTexture.ReleaseTemporary(temporary);
			Color32[] pixels = val.GetPixels32();
			Object.Destroy((Object)val);
			return pixels;
		}

		private static Color32[] Pixelizar(Color32[] px, int w, int h)
		{
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02de: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: 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_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			int num = w;
			int num2 = h;
			int num3 = -1;
			int num4 = -1;
			for (int i = 0; i < h; i++)
			{
				for (int j = 0; j < w; j++)
				{
					if (px[i * w + j].a > 40)
					{
						num = Mathf.Min(num, j);
						num2 = Mathf.Min(num2, i);
						num3 = Mathf.Max(num3, j);
						num4 = Mathf.Max(num4, i);
					}
				}
			}
			Color32[] array = (Color32[])(object)new Color32[256];
			if (num3 < 0)
			{
				return array;
			}
			int num5 = num3 - num + 1;
			int num6 = num4 - num2 + 1;
			float num7 = 16f / (float)Mathf.Max(num5, num6);
			int num8 = Mathf.Max(1, Mathf.RoundToInt((float)num5 * num7));
			int num9 = Mathf.Max(1, Mathf.RoundToInt((float)num6 * num7));
			Vector3[] cor = (Vector3[])(object)new Vector3[num8 * num9];
			float[] array2 = new float[num8 * num9];
			for (int k = 0; k < num9; k++)
			{
				int num10 = num2 + k * num6 / num9;
				int num11 = Mathf.Max(num10 + 1, num2 + (k + 1) * num6 / num9);
				for (int l = 0; l < num8; l++)
				{
					int num12 = num + l * num5 / num8;
					int num13 = Mathf.Max(num12 + 1, num + (l + 1) * num5 / num8);
					Vector3 val = Vector3.zero;
					float num14 = 0f;
					int num15 = 0;
					for (int m = num10; m < num11; m++)
					{
						for (int n = num12; n < num13; n++)
						{
							Color32 val2 = px[m * w + n];
							float num16 = (float)(int)val2.a / 255f;
							val += new Vector3((float)(int)val2.r, (float)(int)val2.g, (float)(int)val2.b) * num16;
							num14 += num16;
							num15++;
						}
					}
					cor[k * num8 + l] = val / (float)num15;
					array2[k * num8 + l] = num14 / (float)num15;
				}
			}
			Realcar(cor, 1.15f, 1.08f);
			List<int> list = new List<int>();
			for (int num17 = 0; num17 < array2.Length; num17++)
			{
				if (array2[num17] * 255f > 110f)
				{
					list.Add(num17);
				}
			}
			Vector3[] paleta = Paleta(list.Select((int num22) => cor[num22]).ToList(), 12);
			int num18 = (16 - num8) / 2;
			int num19 = (16 - num9) / 2;
			foreach (int item in list)
			{
				Vector3 val3 = MaisProxima(paleta, cor[item]);
				int num20 = item % num8;
				int num21 = item / num8;
				array[(num19 + num21) * 16 + num18 + num20] = new Color32((byte)val3.x, (byte)val3.y, (byte)val3.z, byte.MaxValue);
			}
			return array;
		}

		private static void Realcar(Vector3[] cor, float saturacao, float contraste)
		{
			//IL_000c: 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_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			float num = 0f;
			for (int i = 0; i < cor.Length; i++)
			{
				float num2 = Cinza(cor[i]);
				cor[i] = Limitar(new Vector3(num2, num2, num2) + (cor[i] - new Vector3(num2, num2, num2)) * saturacao);
				num += Cinza(cor[i]);
			}
			num /= (float)cor.Length;
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(num, num, num);
			for (int j = 0; j < cor.Length; j++)
			{
				cor[j] = Limitar(val + (cor[j] - val) * contraste);
			}
		}

		private static float Cinza(Vector3 c)
		{
			//IL_0005: 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_001e: Unknown result type (might be due to invalid IL or missing references)
			return 0.299f * c.x + 0.587f * c.y + 0.114f * c.z;
		}

		private static Vector3 Limitar(Vector3 c)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(Mathf.Clamp(c.x, 0f, 255f), Mathf.Clamp(c.y, 0f, 255f), Mathf.Clamp(c.z, 0f, 255f));
		}

		private static Vector3[] Paleta(List<Vector3> cores, int quantas)
		{
			if (cores.Count == 0)
			{
				return (Vector3[])(object)new Vector3[0];
			}
			List<List<Vector3>> list = new List<List<Vector3>> { cores };
			while (list.Count < quantas)
			{
				int num = -1;
				int canal = 0;
				float num2 = 0f;
				for (int i = 0; i < list.Count; i++)
				{
					if (list[i].Count < 2)
					{
						continue;
					}
					int k;
					for (k = 0; k < 3; k++)
					{
						float num3 = list[i].Max((Vector3 c) => ((Vector3)(ref c))[k]) - list[i].Min((Vector3 c) => ((Vector3)(ref c))[k]);
						if (num3 > num2)
						{
							num2 = num3;
							num = i;
							canal = k;
						}
					}
				}
				if (num < 0)
				{
					break;
				}
				List<Vector3> list2 = list[num].OrderBy((Vector3 c) => ((Vector3)(ref c))[canal]).ToList();
				int num4 = list2.Count / 2;
				list[num] = list2.GetRange(0, num4);
				list.Add(list2.GetRange(num4, list2.Count - num4));
			}
			return list.Select((List<Vector3> caixa) => caixa.Aggregate(Vector3.zero, (Vector3 a, Vector3 b) => a + b) / (float)caixa.Count).ToArray();
		}

		private static Vector3 MaisProxima(Vector3[] paleta, Vector3 cor)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: 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_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: 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_0034: Unknown result type (might be due to invalid IL or missing references)
			Vector3 result = cor;
			float num = float.MaxValue;
			foreach (Vector3 val in paleta)
			{
				Vector3 val2 = val - cor;
				float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude;
				if (sqrMagnitude < num)
				{
					num = sqrMagnitude;
					result = val;
				}
			}
			return result;
		}

		private static Texture2D Contornar(Color32[] icone16)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Expected O, but got Unknown
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			Color32[] array = (Color32[])(object)new Color32[324];
			for (int i = 0; i < 16; i++)
			{
				for (int j = 0; j < 16; j++)
				{
					array[(i + 1) * 18 + j + 1] = icone16[i * 16 + j];
				}
			}
			Color32[] array2 = (Color32[])array.Clone();
			for (int k = 0; k < 18; k++)
			{
				for (int l = 0; l < 18; l++)
				{
					if (array[k * 18 + l].a <= 0 && ((l > 0 && array[k * 18 + l - 1].a > 0) || (l < 17 && array[k * 18 + l + 1].a > 0) || (k > 0 && array[(k - 1) * 18 + l].a > 0) || (k < 17 && array[(k + 1) * 18 + l].a > 0)))
					{
						array2[k * 18 + l] = Contorno;
					}
				}
			}
			Texture2D val = new Texture2D(18, 18, (TextureFormat)4, false);
			val.SetPixels32(array2);
			val.Apply();
			return val;
		}
	}
	internal static class Marcadores
	{
		internal sealed class Ponto
		{
			internal int Id;

			internal Tipo Tipo;

			internal Vector3 Pos;

			internal PinData Pino;
		}

		[HarmonyPatch(typeof(Minimap), "UpdatePins")]
		private static class TamanhoENomes
		{
			private static void Postfix(Minimap __instance)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Invalid comparison between Unknown and I4
				//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)
				bool num = (int)__instance.m_mode == 2;
				bool flag = num || Plugin.NomesNoMinimapa.Value;
				float num2 = (num ? 36f : 18f);
				foreach (Ponto value in Pontos.Values)
				{
					PinData pino = value.Pino;
					if (!((Object)(object)pino?.m_uiElement == (Object)null))
					{
						Rect rect = pino.m_uiElement.rect;
						if (Mathf.Abs(((Rect)(ref rect)).width - num2) > 0.5f)
						{
							pino.m_uiElement.SetSizeWithCurrentAnchors((Axis)0, num2);
							pino.m_uiElement.SetSizeWithCurrentAnchors((Axis)1, num2);
						}
						PinNameData namePinData = pino.m_NamePinData;
						GameObject val = ((namePinData != null) ? namePinData.PinNameGameObject : null);
						if ((Object)(object)val != (Object)null && val.activeSelf != flag)
						{
							val.SetActive(flag);
						}
					}
				}
			}
		}

		private const float TamanhoNoMapa = 36f;

		private const float TamanhoNoMinimapa = 18f;

		internal static readonly Dictionary<int, Ponto> Pontos = new Dictionary<int, Ponto>();

		internal static void Limpar()
		{
			foreach (Ponto value in Pontos.Values)
			{
				if (value.Pino != null && (Object)(object)Minimap.instance != (Object)null)
				{
					Minimap.instance.RemovePin(value.Pino);
				}
			}
			Pontos.Clear();
		}

		internal static void Adicionar(int id, string tipoId, Vector3 posicao)
		{
			//IL_0031: 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_0057: 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_006b: Unknown result type (might be due to invalid IL or missing references)
			if (!Pontos.ContainsKey(id) && Catalogo.PorId.TryGetValue(tipoId, out var value))
			{
				Ponto ponto = new Ponto
				{
					Id = id,
					Tipo = value,
					Pos = posicao
				};
				Pontos[id] = ponto;
				if ((Object)(object)Minimap.instance != (Object)null)
				{
					ponto.Pino = Minimap.instance.AddPin(posicao, (PinType)8, value.Rotulo, false, false, 0L, default(PlatformUserID));
					ponto.Pino.m_icon = Icones.Obter(value) ?? Minimap.instance.GetSprite((PinType)3);
				}
			}
		}

		internal static void Remover(int id)
		{
			if (Pontos.TryGetValue(id, out var value))
			{
				Pontos.Remove(id);
				if (value.Pino != null && (Object)(object)Minimap.instance != (Object)null)
				{
					Minimap.instance.RemovePin(value.Pino);
				}
			}
		}

		internal static bool Conhecido(Tipo tipo, Vector3 posicao)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			foreach (Ponto value in Pontos.Values)
			{
				if (value.Tipo == tipo && Utils.DistanceXZ(value.Pos, posicao) < tipo.Raio)
				{
					return true;
				}
			}
			return false;
		}
	}
	internal static class Mesa
	{
		[HarmonyPatch(typeof(ObjectDB), "Awake")]
		private static class AoAbrir
		{
			private static void Postfix(ObjectDB __instance)
			{
				Aplicar(__instance);
			}
		}

		[HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")]
		private static class AoCopiar
		{
			private static void Postfix(ObjectDB __instance)
			{
				Aplicar(__instance);
			}
		}

		private const string Prefab = "piece_cartographytable";

		private static readonly List<(PieceTable tabela, GameObject peca)> Tiradas = new List<(PieceTable, GameObject)>();

		internal static void Ligar()
		{
			Plugin.RemoverMesa.SettingChanged += delegate
			{
				Aplicar(ObjectDB.instance);
			};
			SynchronizationManager.OnConfigurationSynchronized += delegate
			{
				Aplicar(ObjectDB.instance);
			};
		}

		internal static void Aplicar(ObjectDB banco)
		{
			if (Plugin.RemoverMesa.Value)
			{
				Tirar(banco);
			}
			else
			{
				Devolver();
			}
		}

		private static void Tirar(ObjectDB banco)
		{
			if ((Object)(object)banco == (Object)null)
			{
				return;
			}
			foreach (GameObject item in banco.m_items)
			{
				PieceTable val = ((!((Object)(object)item != (Object)null)) ? null : item.GetComponent<ItemDrop>()?.m_itemData?.m_shared?.m_buildPieces);
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				for (int num = val.m_pieces.Count - 1; num >= 0; num--)
				{
					GameObject val2 = val.m_pieces[num];
					if ((Object)(object)val2 != (Object)null && ((Object)val2).name == "piece_cartographytable")
					{
						val.m_pieces.RemoveAt(num);
						Tiradas.Add((val, val2));
						Plugin.Log.LogInfo((object)("Mesa de cartografia retirada do menu de " + ((Object)item).name));
					}
				}
			}
		}

		private static void Devolver()
		{
			foreach (var (val, val2) in Tiradas)
			{
				if ((Object)(object)val != (Object)null && (Object)(object)val2 != (Object)null && !val.m_pieces.Contains(val2))
				{
					val.m_pieces.Add(val2);
				}
			}
			Tiradas.Clear();
		}
	}
	[BepInPlugin("ernandevc.cartographer", "Valheim Cartographer: Shared Map & Auto Discover", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "ernandevc.cartographer";

		public const string Nome = "Valheim Cartographer: Shared Map & Auto Discover";

		public const string Versao = "1.0.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> MapaCompartilhado;

		internal static ConfigEntry<bool> RemoverMesa;

		internal static ConfigEntry<bool> JogadoresVisiveis;

		internal static ConfigEntry<float> TempoOlhando;

		internal static ConfigEntry<float> TamanhoContrasteAlto;

		internal static ConfigEntry<float> TamanhoContrasteNormal;

		internal static ConfigEntry<float> TamanhoContrasteBaixo;

		internal static ConfigEntry<float> CentroDaTela;

		internal static ConfigEntry<float> DistanciaDeSpawn;

		internal static ConfigEntry<bool> NomesNoMinimapa;

		internal static ConfigEntry<bool> AvisoAoDescobrir;

		internal static ConfigEntry<bool> CapturaInvertida;

		internal static ConfigEntry<bool> LogDeDescobertas;

		private readonly Harmony harmony = new Harmony("ernandevc.cartographer");

		private static ConfigDescription SoAdmin(string descricao, AcceptableValueBase faixa = null)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			return new ConfigDescription(descricao, faixa, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} });
		}

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			MapaCompartilhado = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - Shared map", "Shared explored map", true, SoAdmin("Everything any player explores shows up explored for everyone. The server keeps the combined map."));
			RemoverMesa = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - Shared map", "Remove cartography table", true, SoAdmin("Removes the Cartography Table from the build menu, since the map is already shared. Tables already built stay in the world."));
			JogadoresVisiveis = ((BaseUnityPlugin)this).Config.Bind<bool>("1 - Shared map", "Players always visible on map", true, SoAdmin("Turns on the map's \"Visible to other players\" option for every player and keeps it locked on, so everyone sees everyone. Each person always shows in their own color, given by the server."));
			TempoOlhando = ((BaseUnityPlugin)this).Config.Bind<float>("2 - Visibility", "Seconds looking", 1.5f, SoAdmin("How long a place must stay clearly visible, without interruption, before it is marked.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 10f)));
			TamanhoContrasteAlto = ((BaseUnityPlugin)this).Config.Bind<float>("2 - Visibility", "Minimum size, high contrast (%)", 1.5f, SoAdmin("Minimum on-screen size (percent of the screen height) for a place that stands out strongly from its surroundings, like a drake nest on snow or a tower against the sky.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 50f)));
			TamanhoContrasteNormal = ((BaseUnityPlugin)this).Config.Bind<float>("2 - Visibility", "Minimum size, normal contrast (%)", 5f, SoAdmin("Minimum on-screen size (percent of the screen height) for a place with normal contrast.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 50f)));
			TamanhoContrasteBaixo = ((BaseUnityPlugin)this).Config.Bind<float>("2 - Visibility", "Minimum size, low contrast (%)", 8f, SoAdmin("Minimum on-screen size (percent of the screen height) for a place that blends in: camouflaged, at night or in fog.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 50f)));
			CentroDaTela = ((BaseUnityPlugin)this).Config.Bind<float>("2 - Visibility", "Screen center area (%)", 50f, SoAdmin("Width and height of the central screen area, in percent of the screen, where a place must be to count as looked at.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 100f)));
			DistanciaDeSpawn = ((BaseUnityPlugin)this).Config.Bind<float>("2 - Visibility", "Spawner and bed distance (m)", 10f, SoAdmin("Getting this close to a monster spawner or to a base bed marks it even without looking.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 50f)));
			NomesNoMinimapa = ((BaseUnityPlugin)this).Config.Bind<bool>("3 - Display", "Names on minimap", false, "Also shows the marker names on the small minimap. They always show on the large map.");
			AvisoAoDescobrir = ((BaseUnityPlugin)this).Config.Bind<bool>("3 - Display", "Message on discovery", true, "Shows the game's \"Map location added\" message when you discover a new point.");
			CapturaInvertida = ((BaseUnityPlugin)this).Config.Bind<bool>("3 - Display", "Flip screen capture", false, "Only for troubleshooting the contrast check: turn on if the vc_capture console command saves an upside-down image.");
			LogDeDescobertas = ((BaseUnityPlugin)this).Config.Bind<bool>("4 - Troubleshooting", "Log discoveries", true, "Writes each discovery to the BepInEx log with how it was found: distance, on-screen size, required size, contrast and visible parts.");
			Traducoes.Registrar();
			Comandos.Registrar();
			Mesa.Ligar();
			harmony.PatchAll();
			Log.LogInfo((object)"Valheim Cartographer: Shared Map & Auto Discover 1.0.0 carregado");
		}

		private void Update()
		{
			if (!((Object)(object)ZNet.instance == (Object)null))
			{
				Servidor.Atualizar();
				if (!ZNet.instance.IsDedicated())
				{
					Rede.AtualizarCliente();
					Exploracao.Atualizar();
					Detector.Atualizar();
					Captura.Atualizar();
					Cores.AtualizarJogador();
				}
			}
		}

		private void OnApplicationQuit()
		{
			Servidor.Salvar();
		}
	}
	internal static class Rede
	{
		private const int Protocolo = 3;

		internal const int PontosPorMensagem = 1000;

		internal const string RpcOla = "VC_Hello";

		internal const string RpcParteDoMapa = "VC_MapPart";

		internal const string RpcAchei = "VC_Found";

		internal const string RpcAcabou = "VC_Gone";

		internal const string RpcExplorei = "VC_Explored";

		internal const string RpcTudo = "VC_All";

		internal const string RpcFatia = "VC_MapSlice";

		internal const string RpcNovo = "VC_New";

		internal const string RpcSumiu = "VC_Removed";

		internal const string RpcExplorado = "VC_ExploredAll";

		internal const string RpcCores = "VC_Colors";

		private static bool olaEnviado;

		internal static bool Pronto { get; private set; }

		internal static void Registrar()
		{
			ZRoutedRpc instance = ZRoutedRpc.instance;
			instance.Register<ZPackage>("VC_Hello", (Action<long, ZPackage>)Servidor.RPC_Ola);
			instance.Register<ZPackage>("VC_MapPart", (Action<long, ZPackage>)Servidor.RPC_ParteDoMapa);
			instance.Register<ZPackage>("VC_Found", (Action<long, ZPackage>)Servidor.RPC_Achei);
			instance.Register<ZPackage>("VC_Gone", (Action<long, ZPackage>)Servidor.RPC_Acabou);
			instance.Register<ZPackage>("VC_Explored", (Action<long, ZPackage>)Servidor.RPC_Explorei);
			instance.Register<ZPackage>("VC_All", (Action<long, ZPackage>)RPC_Tudo);
			instance.Register<ZPackage>("VC_MapSlice", (Action<long, ZPackage>)RPC_Fatia);
			instance.Register<ZPackage>("VC_New", (Action<long, ZPackage>)RPC_Novo);
			instance.Register<ZPackage>("VC_Removed", (Action<long, ZPackage>)RPC_Sumiu);
			instance.Register<ZPackage>("VC_ExploredAll", (Action<long, ZPackage>)RPC_Explorado);
			instance.Register<ZPackage>("VC_Colors", (Action<long, ZPackage>)Cores.RPC_Cores);
		}

		internal static void Reiniciar()
		{
			olaEnviado = false;
			Pronto = false;
			Marcadores.Limpar();
			Exploracao.Reiniciar();
			Detector.Reiniciar();
			Cores.Reiniciar();
		}

		internal static void AtualizarCliente()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			if (olaEnviado || ZRoutedRpc.instance == null || (Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)Minimap.instance == (Object)null || !Minimap.instance.m_hasGenerated)
			{
				return;
			}
			olaEnviado = true;
			ZPackage val = new ZPackage();
			val.Write(3);
			ZRoutedRpc.instance.InvokeRoutedRPC("VC_Hello", new object[1] { val });
			byte[] array = (Plugin.MapaCompartilhado.Value ? Exploracao.BitsLocais() : null);
			if (array == null)
			{
				return;
			}
			for (int i = 0; i < 16; i++)
			{
				if (!Exploracao.FatiaVazia(array, i))
				{
					ZRoutedRpc.instance.InvokeRoutedRPC("VC_MapPart", new object[1] { Fatia(i, inicial: false, 0, Exploracao.Recortar(array, i)) });
				}
			}
		}

		internal static void Achei(Tipo tipo, Vector3 posicao)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			ZPackage val = new ZPackage();
			val.Write(tipo.Id);
			val.Write(posicao);
			ZRoutedRpc.instance.InvokeRoutedRPC("VC_Found", new object[1] { val });
		}

		internal static void Acabou(int id)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			val.Write(id);
			ZRoutedRpc.instance.InvokeRoutedRPC("VC_Gone", new object[1] { val });
		}

		internal static void Explorei(List<int> indices)
		{
			for (int i = 0; i < indices.Count; i += 10000)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC("VC_Explored", new object[1] { Indices(indices, i) });
			}
		}

		internal static ZPackage Indices(List<int> indices, int inicio)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			int num = Mathf.Min(10000, indices.Count - inicio);
			ZPackage val = new ZPackage();
			val.Write(num);
			for (int i = inicio; i < inicio + num; i++)
			{
				val.Write(indices[i]);
			}
			ZPackage val2 = new ZPackage();
			val2.WriteCompressed(val);
			return val2;
		}

		internal static List<int> LerIndices(ZPackage pacote)
		{
			ZPackage val = pacote.ReadCompressedPackage();
			int num = val.ReadInt();
			List<int> list = new List<int>(num);
			for (int i = 0; i < num; i++)
			{
				list.Add(val.ReadInt());
			}
			return list;
		}

		internal static ZPackage Bytes(byte[] bytes)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			val.Write(bytes);
			return val;
		}

		internal static ZPackage Fatia(int fatia, bool inicial, int totalInicial, byte[] dados)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			val.Write(fatia);
			val.Write(inicial);
			val.Write(totalInicial);
			val.WriteCompressed(Bytes(dados));
			return val;
		}

		private static void RPC_Tudo(long remetente, ZPackage pacote)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			if (!ZNet.instance.IsDedicated())
			{
				bool num = pacote.ReadBool();
				bool flag = pacote.ReadBool();
				if (num)
				{
					Marcadores.Limpar();
				}
				int num2 = pacote.ReadInt();
				for (int i = 0; i < num2; i++)
				{
					int id = pacote.ReadInt();
					string tipoId = pacote.ReadString();
					Vector3 posicao = pacote.ReadVector3();
					Marcadores.Adicionar(id, tipoId, posicao);
				}
				if (flag)
				{
					Pronto = true;
					Plugin.Log.LogInfo((object)$"Servidor mandou {Marcadores.Pontos.Count} pontos");
				}
			}
		}

		private static void RPC_Fatia(long remetente, ZPackage pacote)
		{
			if (!ZNet.instance.IsDedicated() && Plugin.MapaCompartilhado.Value)
			{
				int fatia = pacote.ReadInt();
				bool doInicio = pacote.ReadBool();
				int total = pacote.ReadInt();
				Exploracao.ReceberFatia(fatia, doInicio, total, pacote.ReadCompressedPackage().ReadByteArray());
			}
		}

		private static void RPC_Novo(long remetente, ZPackage pacote)
		{
			//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_002a: Unknown result type (might be due to invalid IL or missing references)
			if (!ZNet.instance.IsDedicated())
			{
				int id = pacote.ReadInt();
				string text = pacote.ReadString();
				Vector3 posicao = pacote.ReadVector3();
				long num = pacote.ReadLong();
				Marcadores.Adicionar(id, text, posicao);
				if (num == ZRoutedRpc.instance.m_id && Plugin.AvisoAoDescobrir.Value && (Object)(object)Player.m_localPlayer != (Object)null && Catalogo.PorId.TryGetValue(text, out var value))
				{
					((Character)Player.m_localPlayer).Message((MessageType)1, "$msg_pin_added: " + value.Rotulo, 0, Icones.Obter(value), false);
				}
			}
		}

		private static void RPC_Sumiu(long remetente, ZPackage pacote)
		{
			if (!ZNet.instance.IsDedicated())
			{
				Marcadores.Remover(pacote.ReadInt());
			}
		}

		private static void RPC_Explorado(long remetente, ZPackage pacote)
		{
			if (!ZNet.instance.IsDedicated() && Plugin.MapaCompartilhado.Value)
			{
				Exploracao.AplicarIndices(LerIndices(pacote));
			}
		}
	}
	[HarmonyPatch(typeof(Game), "Start")]
	internal static class RegistrarRede
	{
		private static void Postfix()
		{
			Rede.Registrar();
			Rede.Reiniciar();
			if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer())
			{
				Servidor.Iniciar();
			}
		}
	}
	internal static class Servidor
	{
		private sealed class Ponto
		{
			internal int Id;

			internal string Tipo;

			internal Vector3 Pos;

			internal string Quem;

			internal long Quando;
		}

		private const int VersaoDoArquivo = 2;

		private const float EsperaParaConferir = 10f;

		private const float IntervaloDaVarredura = 600f;

		private const float IntervaloDoMapa = 5f;

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

		private static byte[] explorado = new byte[524288];

		private static int proximoId = 1;

		private static string mundo;

		private static long idDoMundo;

		private static bool sujo;

		private static bool ativo;

		private static readonly List<int> NovosExplorados = new List<int>();

		private static readonly HashSet<int> FatiasNovas = new HashSet<int>();

		private static float proximoMapa;

		private static readonly Queue<(float quando, Vector3 pos, int prefab)> AConferir = new Queue<(float, Vector3, int)>();

		private static float proximaVarredura;

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

		private static readonly HashSet<int> Vigiados = new HashSet<int>();

		private static readonly List<ZDO> Achados = new List<ZDO>();

		private static readonly HashSet<SectorIndex> Visitados = new HashSet<SectorIndex>();

		internal static void Iniciar()
		{
			ativo = true;
			AConferir.Clear();
			NovosExplorados.Clear();
			FatiasNovas.Clear();
			Vigiados.Clear();
			HashesPorTipo.Clear();
			Carregar();
			ZDOMan instance = ZDOMan.instance;
			instance.m_onZDODestroyed = (Action<ZDO>)Delegate.Combine(instance.m_onZDODestroyed, new Action<ZDO>(AoDestruirZdo));
			ZNet.WorldSaveStarted = (Action)Delegate.Remove(ZNet.WorldSaveStarted, new Action(Salvar));
			ZNet.WorldSaveStarted = (Action)Delegate.Combine(ZNet.WorldSaveStarted, new Action(Salvar));
			proximaVarredura = Time.time + 60f;
		}

		internal static void Encerrar()
		{
			Salvar();
			ativo = false;
		}

		private static string Arquivo(string nomeDoMundo)
		{
			string text = Path.Combine(Paths.ConfigPath, "ValheimCartographer");
			Directory.CreateDirectory(text);
			return Path.Combine(text, nomeDoMundo + ".vcmap");
		}

		private static void Carregar()
		{
			World world = ZNet.World;
			if (world == null || string.IsNullOrEmpty(world.m_name) || (world.m_name == mundo && world.m_uid == idDoMundo))
			{
				return;
			}
			mundo = world.m_name;
			idDoMundo = world.m_uid;
			Zerar();
			string text = Arquivo(mundo);
			if (!File.Exists(text))
			{
				Plugin.Log.LogInfo((object)("Mundo " + mundo + ": começando sem pontos"));
				return;
			}
			try
			{
				Ler(text);
			}
			catch (Exception ex)
			{
				Guardar(text, "corrompido");
				Plugin.Log.LogError((object)("Não consegui ler " + text + " (" + ex.Message + "); tentando o .bak"));
				Zerar();
				try
				{
					if (File.Exists(text + ".bak") && Ler(text + ".bak"))
					{
						sujo = true;
						return;
					}
				}
				catch (Exception ex2)
				{
					Plugin.Log.LogError((object)("O .bak também falhou (" + ex2.Message + "); começando sem pontos"));
				}
				Zerar();
			}
		}

		private static void Zerar()
		{
			Pontos.Clear();
			explorado = new byte[524288];
			proximoId = 1;
			sujo = false;
		}

		private static bool Ler(string caminho)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			//IL_0095: 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)
			ZPackage val = new ZPackage(File.ReadAllBytes(caminho));
			int num = val.ReadInt();
			long num2 = val.ReadLong();
			if (num != 2 || num2 != idDoMundo)
			{
				Guardar(caminho, $"outro-mundo-{num2}");
				Plugin.Log.LogWarning((object)$"{caminho} é de outro mundo com o mesmo nome (id {num2}, versão {num}); arquivo posto de lado, começando sem pontos");
				return false;
			}
			proximoId = val.ReadInt();
			int num3 = val.ReadInt();
			for (int i = 0; i < num3; i++)
			{
				Ponto ponto = new Ponto
				{
					Id = val.ReadInt(),
					Tipo = val.ReadString(),
					Pos = val.ReadVector3(),
					Quem = val.ReadString(),
					Quando = val.ReadLong()
				};
				Pontos[ponto.Id] = ponto;
			}
			byte[] array = val.ReadCompressedPackage().ReadByteArray();
			if (array.Length == explorado.Length)
			{
				explorado = array;
			}
			Plugin.Log.LogInfo((object)$"Mundo {mundo}: {Pontos.Count} pontos carregados");
			return true;
		}

		private static void Guardar(string caminho, string motivo)
		{
			try
			{
				File.Copy(caminho, $"{caminho}.{motivo}-{DateTime.Now:yyyyMMdd-HHmmss}", overwrite: true);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Não consegui copiar " + caminho + " (" + ex.Message + ")"));
			}
		}

		internal static void Salvar()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			if (!ativo || !sujo || string.IsNullOrEmpty(mundo))
			{
				return;
			}
			try
			{
				ZPackage val = new ZPackage();
				val.Write(2);
				val.Write(idDoMundo);
				val.Write(proximoId);
				val.Write(Pontos.Count);
				foreach (Ponto value in Pontos.Values)
				{
					val.Write(value.Id);
					val.Write(value.Tipo);
					val.Write(value.Pos);
					val.Write(value.Quem ?? "");
					val.Write(value.Quando);
				}
				val.WriteCompressed(Rede.Bytes(explorado));
				string text = Arquivo(mundo);
				string text2 = text + ".tmp";
				File.WriteAllBytes(text2, val.GetArray());
				if (File.Exists(text))
				{
					File.Replace(text2, text, text + ".bak");
				}
				else
				{
					File.Move(text2, text);
				}
				sujo = false;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Não consegui gravar os pontos do mundo " + mundo + ": " + ex.Message));
			}
		}

		internal static void Atualizar()
		{
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			if (!ativo)
			{
				return;
			}
			if (Time.time >= proximoMapa && (NovosExplorados.Count > 0 || FatiasNovas.Count > 0))
			{
				proximoMapa = Time.time + 5f;
				for (int i = 0; i < NovosExplorados.Count; i += 10000)
				{
					ZRoutedRpc.instance.InvokeRoutedRPC(0L, "VC_ExploredAll", new object[1] { Rede.Indices(NovosExplorados, i) });
				}
				NovosExplorados.Clear();
				foreach (int fatiasNova in FatiasNovas)
				{
					ZRoutedRpc.instance.InvokeRoutedRPC(0L, "VC_MapSlice", new object[1] { Rede.Fatia(fatiasNova, inicial: false, 0, Exploracao.Recortar(explorado, fatiasNova)) });
				}
				FatiasNovas.Clear();
			}
			while (AConferir.Count > 0 && Time.time - AConferir.Peek().quando >= 10f)
			{
				(float quando, Vector3 pos, int prefab) tuple = AConferir.Dequeue();
				Vector3 item = tuple.pos;
				int item2 = tuple.prefab;
				ConferirPerto(item, item2);
			}
			if (Time.time >= proximaVarredura)
			{
				proximaVarredura = Time.time + 600f;
				Varrer();
			}
			Cores.AtualizarServidor();
		}

		internal static void RPC_Ola(long remetente, ZPackage pacote)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			if (!ativo)
			{
				return;
			}
			Carregar();
			Cores.Enviar(remetente);
			List<Ponto> list = new List<Ponto>(Pontos.Values);
			int num = 0;
			do
			{
				int num2 = Mathf.Min(1000, list.Count - num);
				ZPackage val = new ZPackage();
				val.Write(num == 0);
				val.Write(num + num2 >= list.Count);
				val.Write(num2);
				for (int i = num; i < num + num2; i++)
				{
					val.Write(list[i].Id);
					val.Write(list[i].Tipo);
					val.Write(list[i].Pos);
				}
				ZRoutedRpc.instance.InvokeRoutedRPC(remetente, "VC_All", new object[1] { val });
				num += num2;
			}
			while (num < list.Count);
			if (!Plugin.MapaCompartilhado.Value)
			{
				return;
			}
			List<int> list2 = new List<int>();
			for (int j = 0; j < 16; j++)
			{
				if (!Exploracao.FatiaVazia(explorado, j))
				{
					list2.Add(j);
				}
			}
			foreach (int item in list2)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(remetente, "VC_MapSlice", new object[1] { Rede.Fatia(item, inicial: true, list2.Count, Exploracao.Recortar(explorado, item)) });
			}
		}

		internal static void RPC_ParteDoMapa(long remetente, ZPackage pacote)
		{
			if (!ativo || !Plugin.MapaCompartilhado.Value)
			{
				return;
			}
			int num = pacote.ReadInt();
			pacote.ReadBool();
			pacote.ReadInt();
			byte[] array = pacote.ReadCompressedPackage().ReadByteArray();
			if (num < 0 || num >= 16 || array.Length != 32768)
			{
				return;
			}
			int num2 = num * 32768;
			for (int i = 0; i < array.Length; i++)
			{
				byte b = (byte)(array[i] & ~explorado[num2 + i]);
				if (b != 0)
				{
					explorado[num2 + i] |= b;
					FatiasNovas.Add(num);
					sujo = true;
				}
			}
		}

		internal static void RPC_Achei(long remetente, ZPackage pacote)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be